aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWWWesten <4700006+WWWesten@users.noreply.github.com>2021-11-01 23:43:29 +0500
committerGitHub <noreply@github.com>2021-11-01 23:43:29 +0500
commit0a14279e2a21bcb9654a06a2d49e1e4f0cc5329c (patch)
treee1b1bd603b011ca98e5793e356326bf4a35a7050
parentf2817fef743eeb75a00782ceea363b2d3e7dc9f2 (diff)
parent76eeb8f655424d295e73ced8349c6fefee6ddb12 (diff)
Merge branch 'jellyfin:master' into master
-rw-r--r--.ci/azure-pipelines-abi.yml94
-rw-r--r--.ci/azure-pipelines-main.yml101
-rw-r--r--.ci/azure-pipelines-package.yml262
-rw-r--r--.ci/azure-pipelines-test.yml99
-rw-r--r--.ci/azure-pipelines.yml64
l---------[-rw-r--r--].copr/Makefile9
-rw-r--r--.drone.yml111
-rw-r--r--.editorconfig17
-rw-r--r--.gitattributes4
-rw-r--r--.github/CODEOWNERS4
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.md28
-rw-r--r--.github/ISSUE_TEMPLATE/enhancement-request.md20
-rw-r--r--.github/ISSUE_TEMPLATE/feature_request.md15
-rw-r--r--.github/ISSUE_TEMPLATE/media_playback.md34
-rw-r--r--.github/dependabot.yml15
-rw-r--r--.github/pull_request_template.md2
-rw-r--r--.github/stale.yml29
-rw-r--r--.github/workflows/automation.yml76
-rw-r--r--.github/workflows/codeql-analysis.yml38
-rw-r--r--.github/workflows/commands.yml119
-rw-r--r--.gitignore39
-rw-r--r--.gitmodules3
-rw-r--r--.npmrc3
-rw-r--r--.vscode/extensions.json14
-rw-r--r--.vscode/launch.json34
-rw-r--r--.vscode/tasks.json19
-rw-r--r--BDInfo/BDInfo.csproj16
-rw-r--r--BDInfo/BDInfoSettings.cs33
-rw-r--r--BDInfo/BDROM.cs456
-rw-r--r--BDInfo/LanguageCodes.cs493
-rw-r--r--BDInfo/Properties/AssemblyInfo.cs21
-rw-r--r--BDInfo/ReadMe.txt5
-rw-r--r--BDInfo/TSCodecAC3.cs309
-rw-r--r--BDInfo/TSCodecAVC.cs148
-rw-r--r--BDInfo/TSCodecDTS.cs159
-rw-r--r--BDInfo/TSCodecDTSHD.cs246
-rw-r--r--BDInfo/TSCodecLPCM.cs123
-rw-r--r--BDInfo/TSCodecMPEG2.cs208
-rw-r--r--BDInfo/TSCodecMVC.cs36
-rw-r--r--BDInfo/TSCodecTrueHD.cs186
-rw-r--r--BDInfo/TSCodecVC1.cs131
-rw-r--r--BDInfo/TSInterleavedFile.cs37
-rw-r--r--BDInfo/TSPlaylistFile.cs1282
-rw-r--r--BDInfo/TSStream.cs780
-rw-r--r--BDInfo/TSStreamBuffer.cs130
-rw-r--r--BDInfo/TSStreamClip.cs107
-rw-r--r--BDInfo/TSStreamClipFile.cs244
-rw-r--r--BDInfo/TSStreamFile.cs1555
-rw-r--r--CONTRIBUTORS.md162
-rw-r--r--Directory.Build.props14
-rw-r--r--Dockerfile106
-rw-r--r--Dockerfile.arm86
-rw-r--r--Dockerfile.arm6476
-rw-r--r--DvdLib/BigEndianBinaryReader.cs15
-rw-r--r--DvdLib/DvdLib.csproj14
-rw-r--r--DvdLib/Ifo/AudioAttributes.cs36
-rw-r--r--DvdLib/Ifo/Cell.cs3
-rw-r--r--DvdLib/Ifo/CellPlaybackInfo.cs2
-rw-r--r--DvdLib/Ifo/CellPositionInfo.cs2
-rw-r--r--DvdLib/Ifo/Chapter.cs4
-rw-r--r--DvdLib/Ifo/Dvd.cs49
-rw-r--r--DvdLib/Ifo/DvdTime.cs12
-rw-r--r--DvdLib/Ifo/PgcCommandTable.cs17
-rw-r--r--DvdLib/Ifo/Program.cs4
-rw-r--r--DvdLib/Ifo/ProgramChain.cs21
-rw-r--r--DvdLib/Ifo/Title.cs11
-rw-r--r--DvdLib/Ifo/UserOperation.cs2
-rw-r--r--DvdLib/Ifo/VideoAttributes.cs46
-rw-r--r--DvdLib/Properties/AssemblyInfo.cs4
-rw-r--r--Emby.Dlna/Api/DlnaServerService.cs306
-rw-r--r--Emby.Dlna/Api/DlnaService.cs83
-rw-r--r--Emby.Dlna/Common/Argument.cs19
-rw-r--r--Emby.Dlna/Common/DeviceIcon.cs28
-rw-r--r--Emby.Dlna/Common/DeviceService.cs35
-rw-r--r--Emby.Dlna/Common/ServiceAction.cs28
-rw-r--r--Emby.Dlna/Common/StateVariable.cs33
-rw-r--r--Emby.Dlna/Configuration/DlnaOptions.cs87
-rw-r--r--Emby.Dlna/ConfigurationExtension.cs18
-rw-r--r--Emby.Dlna/ConnectionManager/ConnectionManager.cs40
-rw-r--r--Emby.Dlna/ConnectionManager/ConnectionManagerService.cs53
-rw-r--r--Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs147
-rw-r--r--Emby.Dlna/ConnectionManager/ControlHandler.cs43
-rw-r--r--Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs39
-rw-r--r--Emby.Dlna/ContentDirectory/ContentDirectory.cs142
-rw-r--r--Emby.Dlna/ContentDirectory/ContentDirectoryService.cs176
-rw-r--r--Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs230
-rw-r--r--Emby.Dlna/ContentDirectory/ControlHandler.cs1263
-rw-r--r--Emby.Dlna/ContentDirectory/ServerItem.cs36
-rw-r--r--Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs49
-rw-r--r--Emby.Dlna/ContentDirectory/StubType.cs30
-rw-r--r--Emby.Dlna/ControlRequest.cs18
-rw-r--r--Emby.Dlna/ControlResponse.cs16
-rw-r--r--Emby.Dlna/Didl/DidlBuilder.cs635
-rw-r--r--Emby.Dlna/Didl/Filter.cs12
-rw-r--r--Emby.Dlna/Didl/StringWriterWithEncoding.cs8
-rw-r--r--Emby.Dlna/DlnaConfigurationFactory.cs23
-rw-r--r--Emby.Dlna/DlnaManager.cs294
-rw-r--r--Emby.Dlna/Emby.Dlna.csproj19
-rw-r--r--Emby.Dlna/EventSubscriptionResponse.cs17
-rw-r--r--Emby.Dlna/Eventing/DlnaEventManager.cs (renamed from Emby.Dlna/Eventing/EventManager.cs)117
-rw-r--r--Emby.Dlna/Eventing/EventSubscription.cs11
-rw-r--r--Emby.Dlna/IConnectionManager.cs3
-rw-r--r--Emby.Dlna/IContentDirectory.cs3
-rw-r--r--Emby.Dlna/IDlnaEventManager.cs (renamed from Emby.Dlna/IEventManager.cs)13
-rw-r--r--Emby.Dlna/IMediaReceiverRegistrar.cs3
-rw-r--r--Emby.Dlna/IUpnpService.cs9
-rw-r--r--Emby.Dlna/Images/logo120.pngbin7522 -> 6201 bytes
-rw-r--r--Emby.Dlna/Images/logo240.jpgbin11520 -> 11483 bytes
-rw-r--r--Emby.Dlna/Images/logo240.pngbin18287 -> 13339 bytes
-rw-r--r--Emby.Dlna/Images/logo48.pngbin2554 -> 2263 bytes
-rw-r--r--Emby.Dlna/Images/people48.pngbin286 -> 278 bytes
-rw-r--r--Emby.Dlna/Main/DlnaEntryPoint.cs222
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs58
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs35
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs46
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs118
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs45
-rw-r--r--Emby.Dlna/PlayTo/CurrentIdEventArgs.cs9
-rw-r--r--Emby.Dlna/PlayTo/Device.cs523
-rw-r--r--Emby.Dlna/PlayTo/DeviceInfo.cs9
-rw-r--r--Emby.Dlna/PlayTo/MediaChangedEventArgs.cs19
-rw-r--r--Emby.Dlna/PlayTo/PlayToController.cs643
-rw-r--r--Emby.Dlna/PlayTo/PlayToManager.cs163
-rw-r--r--Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs9
-rw-r--r--Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs9
-rw-r--r--Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs13
-rw-r--r--Emby.Dlna/PlayTo/PlaylistItem.cs4
-rw-r--r--Emby.Dlna/PlayTo/PlaylistItemFactory.cs11
-rw-r--r--Emby.Dlna/PlayTo/SsdpHttpClient.cs165
-rw-r--r--Emby.Dlna/PlayTo/TRANSPORTSTATE.cs11
-rw-r--r--Emby.Dlna/PlayTo/TransportCommands.cs109
-rw-r--r--Emby.Dlna/PlayTo/TransportState.cs13
-rw-r--r--Emby.Dlna/PlayTo/TransportStateEventArgs.cs9
-rw-r--r--Emby.Dlna/PlayTo/UpnpContainer.cs18
-rw-r--r--Emby.Dlna/PlayTo/uBaseObject.cs31
-rw-r--r--Emby.Dlna/PlayTo/uParser.cs47
-rw-r--r--Emby.Dlna/PlayTo/uParserObject.cs9
-rw-r--r--Emby.Dlna/PlayTo/uPnpNamespaces.cs92
-rw-r--r--Emby.Dlna/Profiles/DefaultProfile.cs13
-rw-r--r--Emby.Dlna/Profiles/DenonAvrProfile.cs4
-rw-r--r--Emby.Dlna/Profiles/DirectTvProfile.cs4
-rw-r--r--Emby.Dlna/Profiles/DishHopperJoeyProfile.cs16
-rw-r--r--Emby.Dlna/Profiles/Foobar2000Profile.cs4
-rw-r--r--Emby.Dlna/Profiles/LgTvProfile.cs6
-rw-r--r--Emby.Dlna/Profiles/LinksysDMA2100Profile.cs4
-rw-r--r--Emby.Dlna/Profiles/MarantzProfile.cs4
-rw-r--r--Emby.Dlna/Profiles/MediaMonkeyProfile.cs5
-rw-r--r--Emby.Dlna/Profiles/PanasonicVieraProfile.cs4
-rw-r--r--Emby.Dlna/Profiles/PopcornHourProfile.cs16
-rw-r--r--Emby.Dlna/Profiles/SamsungSmartTvProfile.cs4
-rw-r--r--Emby.Dlna/Profiles/SharpSmartTvProfile.cs2
-rw-r--r--Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs11
-rw-r--r--Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs11
-rw-r--r--Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs11
-rw-r--r--Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs11
-rw-r--r--Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs12
-rw-r--r--Emby.Dlna/Profiles/SonyBravia2010Profile.cs50
-rw-r--r--Emby.Dlna/Profiles/SonyBravia2011Profile.cs48
-rw-r--r--Emby.Dlna/Profiles/SonyBravia2012Profile.cs40
-rw-r--r--Emby.Dlna/Profiles/SonyBravia2013Profile.cs43
-rw-r--r--Emby.Dlna/Profiles/SonyBravia2014Profile.cs43
-rw-r--r--Emby.Dlna/Profiles/SonyPs3Profile.cs20
-rw-r--r--Emby.Dlna/Profiles/SonyPs4Profile.cs20
-rw-r--r--Emby.Dlna/Profiles/WdtvLiveProfile.cs10
-rw-r--r--Emby.Dlna/Profiles/XboxOneProfile.cs16
-rw-r--r--Emby.Dlna/Profiles/Xml/Default.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Denon AVR.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/LG Smart TV.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Marantz.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/MediaMonkey.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Panasonic Viera.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Popcorn Hour.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml4
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml6
-rw-r--r--Emby.Dlna/Profiles/Xml/WDTV Live.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/Xbox One.xml2
-rw-r--r--Emby.Dlna/Profiles/Xml/foobar2000.xml2
-rw-r--r--Emby.Dlna/Properties/AssemblyInfo.cs6
-rw-r--r--Emby.Dlna/Server/DescriptionXmlBuilder.cs193
-rw-r--r--Emby.Dlna/Service/BaseControlHandler.cs196
-rw-r--r--Emby.Dlna/Service/BaseService.cs28
-rw-r--r--Emby.Dlna/Service/ControlErrorHandler.cs22
-rw-r--r--Emby.Dlna/Service/ServiceXmlBuilder.cs39
-rw-r--r--Emby.Dlna/Ssdp/DeviceDiscovery.cs76
-rw-r--r--Emby.Dlna/Ssdp/Extensions.cs31
-rw-r--r--Emby.Dlna/Ssdp/SsdpExtensions.cs27
-rw-r--r--Emby.Drawing/Emby.Drawing.csproj15
-rw-r--r--Emby.Drawing/ImageProcessor.cs653
-rw-r--r--Emby.Drawing/NullImageEncoder.cs36
-rw-r--r--Emby.Drawing/Properties/AssemblyInfo.cs4
-rw-r--r--Emby.IsoMounting/.gitignore108
-rw-r--r--Emby.IsoMounting/IsoMounter.sln25
-rw-r--r--Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs8
-rw-r--r--Emby.IsoMounting/IsoMounter/IsoMounter.csproj17
-rw-r--r--Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs479
-rw-r--r--Emby.IsoMounting/IsoMounter/LinuxMount.cs83
-rw-r--r--Emby.IsoMounting/IsoMounter/Plugin.cs30
-rw-r--r--Emby.IsoMounting/LICENSE339
-rw-r--r--Emby.IsoMounting/README.md14
-rw-r--r--Emby.Naming/Audio/AlbumParser.cs55
-rw-r--r--Emby.Naming/Audio/AudioFileParser.cs26
-rw-r--r--Emby.Naming/Audio/MultiPartResult.cs21
-rw-r--r--Emby.Naming/AudioBook/AudioBookFileInfo.cs52
-rw-r--r--Emby.Naming/AudioBook/AudioBookFilePathParser.cs39
-rw-r--r--Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs13
-rw-r--r--Emby.Naming/AudioBook/AudioBookInfo.cs39
-rw-r--r--Emby.Naming/AudioBook/AudioBookListResolver.cs148
-rw-r--r--Emby.Naming/AudioBook/AudioBookNameParser.cs67
-rw-r--r--Emby.Naming/AudioBook/AudioBookNameParserResult.cs18
-rw-r--r--Emby.Naming/AudioBook/AudioBookResolver.cs49
-rw-r--r--Emby.Naming/Common/EpisodeExpression.cs70
-rw-r--r--Emby.Naming/Common/MediaType.cs11
-rw-r--r--Emby.Naming/Common/NamingOptions.cs762
-rw-r--r--Emby.Naming/Emby.Naming.csproj36
-rw-r--r--Emby.Naming/Extensions/StringExtensions.cs30
-rw-r--r--Emby.Naming/Properties/AssemblyInfo.cs4
-rw-r--r--Emby.Naming/StringExtensions.cs30
-rw-r--r--Emby.Naming/Subtitles/SubtitleInfo.cs21
-rw-r--r--Emby.Naming/Subtitles/SubtitleParser.cs41
-rw-r--r--Emby.Naming/TV/EpisodeInfo.cs54
-rw-r--r--Emby.Naming/TV/EpisodePathParser.cs115
-rw-r--r--Emby.Naming/TV/EpisodePathParserResult.cs42
-rw-r--r--Emby.Naming/TV/EpisodeResolver.cs59
-rw-r--r--Emby.Naming/TV/SeasonPathParser.cs129
-rw-r--r--Emby.Naming/TV/SeasonPathParserResult.cs11
-rw-r--r--Emby.Naming/Video/CleanDateTimeParser.cs87
-rw-r--r--Emby.Naming/Video/CleanDateTimeResult.cs30
-rw-r--r--Emby.Naming/Video/CleanStringParser.cs55
-rw-r--r--Emby.Naming/Video/CleanStringResult.cs16
-rw-r--r--Emby.Naming/Video/ExtraResolver.cs107
-rw-r--r--Emby.Naming/Video/ExtraResult.cs10
-rw-r--r--Emby.Naming/Video/ExtraRule.cs36
-rw-r--r--Emby.Naming/Video/ExtraRuleType.cs18
-rw-r--r--Emby.Naming/Video/FileStack.cs35
-rw-r--r--Emby.Naming/Video/FlagParser.cs35
-rw-r--r--Emby.Naming/Video/Format3DParser.cs90
-rw-r--r--Emby.Naming/Video/Format3DResult.cs35
-rw-r--r--Emby.Naming/Video/Format3DRule.cs21
-rw-r--r--Emby.Naming/Video/StackResolver.cs107
-rw-r--r--Emby.Naming/Video/StackResult.cs14
-rw-r--r--Emby.Naming/Video/StubResolver.cs43
-rw-r--r--Emby.Naming/Video/StubResult.cs16
-rw-r--r--Emby.Naming/Video/StubTypeRule.cs15
-rw-r--r--Emby.Naming/Video/VideoFileInfo.cs66
-rw-r--r--Emby.Naming/Video/VideoInfo.cs35
-rw-r--r--Emby.Naming/Video/VideoListResolver.cs278
-rw-r--r--Emby.Naming/Video/VideoResolver.cs145
-rw-r--r--Emby.Notifications/Api/NotificationsService.cs182
-rw-r--r--Emby.Notifications/CoreNotificationTypes.cs11
-rw-r--r--Emby.Notifications/Emby.Notifications.csproj15
-rw-r--r--Emby.Notifications/NotificationConfigurationFactory.cs4
-rw-r--r--Emby.Notifications/NotificationEntryPoint.cs (renamed from Emby.Notifications/Notifications.cs)183
-rw-r--r--Emby.Notifications/NotificationManager.cs54
-rw-r--r--Emby.Notifications/Properties/AssemblyInfo.cs4
-rw-r--r--Emby.Photos/Emby.Photos.csproj17
-rw-r--r--Emby.Photos/PhotoProvider.cs108
-rw-r--r--Emby.Photos/Properties/AssemblyInfo.cs4
-rw-r--r--Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs577
-rw-r--r--Emby.Server.Implementations/Activity/ActivityManager.cs61
-rw-r--r--Emby.Server.Implementations/Activity/ActivityRepository.cs310
-rw-r--r--Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs58
-rw-r--r--Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs202
-rw-r--r--Emby.Server.Implementations/AppBase/ConfigurationHelper.cs36
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs1750
-rw-r--r--Emby.Server.Implementations/Archiving/ZipClient.cs143
-rw-r--r--Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs4
-rw-r--r--Emby.Server.Implementations/Browser/BrowserLauncher.cs51
-rw-r--r--Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs19
-rw-r--r--Emby.Server.Implementations/Channels/ChannelImageProvider.cs16
-rw-r--r--Emby.Server.Implementations/Channels/ChannelManager.cs499
-rw-r--r--Emby.Server.Implementations/Channels/ChannelPostScanTask.cs83
-rw-r--r--Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs56
-rw-r--r--Emby.Server.Implementations/Collections/CollectionImageProvider.cs32
-rw-r--r--Emby.Server.Implementations/Collections/CollectionManager.cs266
-rw-r--r--Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs161
-rw-r--r--Emby.Server.Implementations/ConfigurationOptions.cs16
-rw-r--r--Emby.Server.Implementations/Cryptography/CryptographyProvider.cs88
-rw-r--r--Emby.Server.Implementations/Data/BaseSqliteRepository.cs411
-rw-r--r--Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs7
-rw-r--r--Emby.Server.Implementations/Data/ManagedConnection.cs55
-rw-r--r--Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs248
-rw-r--r--Emby.Server.Implementations/Data/SqliteExtensions.cs272
-rw-r--r--Emby.Server.Implementations/Data/SqliteItemRepository.cs4028
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserDataRepository.cs206
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserRepository.cs230
-rw-r--r--Emby.Server.Implementations/Data/SynchronouseMode.cs30
-rw-r--r--Emby.Server.Implementations/Data/TempStoreMode.cs23
-rw-r--r--Emby.Server.Implementations/Data/TypeMapper.cs36
-rw-r--r--Emby.Server.Implementations/Devices/DeviceId.cs31
-rw-r--r--Emby.Server.Implementations/Devices/DeviceManager.cs501
-rw-r--r--Emby.Server.Implementations/Diagnostics/CommonProcess.cs136
-rw-r--r--Emby.Server.Implementations/Diagnostics/ProcessFactory.cs12
-rw-r--r--Emby.Server.Implementations/Dto/DtoService.cs537
-rw-r--r--Emby.Server.Implementations/Emby.Server.Implementations.csproj47
-rw-r--r--Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs125
-rw-r--r--Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs325
-rw-r--r--Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs162
-rw-r--r--Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs61
-rw-r--r--Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs75
-rw-r--r--Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs209
-rw-r--r--Emby.Server.Implementations/EntryPoints/StartupWizard.cs67
-rw-r--r--Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs85
-rw-r--r--Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs59
-rw-r--r--Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs36
-rw-r--r--Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs24
-rw-r--r--Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs17
-rw-r--r--Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs132
-rw-r--r--Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs18
-rw-r--r--Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs800
-rw-r--r--Emby.Server.Implementations/HttpServer/FileWriter.cs210
-rw-r--r--Emby.Server.Implementations/HttpServer/HttpListenerHost.cs901
-rw-r--r--Emby.Server.Implementations/HttpServer/HttpResultFactory.cs722
-rw-r--r--Emby.Server.Implementations/HttpServer/IHttpListener.cs48
-rw-r--r--Emby.Server.Implementations/HttpServer/LoggerUtils.cs55
-rw-r--r--Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs221
-rw-r--r--Emby.Server.Implementations/HttpServer/ResponseFilter.cs88
-rw-r--r--Emby.Server.Implementations/HttpServer/Security/AuthService.cs234
-rw-r--r--Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs237
-rw-r--r--Emby.Server.Implementations/HttpServer/Security/SessionContext.cs39
-rw-r--r--Emby.Server.Implementations/HttpServer/StreamWriter.cs119
-rw-r--r--Emby.Server.Implementations/HttpServer/WebSocketConnection.cs327
-rw-r--r--Emby.Server.Implementations/HttpServer/WebSocketManager.cs90
-rw-r--r--Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs4
-rw-r--r--Emby.Server.Implementations/IO/FileRefresher.cs54
-rw-r--r--Emby.Server.Implementations/IO/IsoManager.cs75
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitor.cs265
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitorStartup.cs35
-rw-r--r--Emby.Server.Implementations/IO/ManagedFileSystem.cs417
-rw-r--r--Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs4
-rw-r--r--Emby.Server.Implementations/IO/StreamHelper.cs196
-rw-r--r--Emby.Server.Implementations/IO/ThrottledStream.cs355
-rw-r--r--Emby.Server.Implementations/IStartupOptions.cs30
-rw-r--r--Emby.Server.Implementations/Images/ArtistImageProvider.cs46
-rw-r--r--Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs128
-rw-r--r--Emby.Server.Implementations/Images/BaseFolderImageProvider.cs67
-rw-r--r--Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs (renamed from Emby.Server.Implementations/UserViews/CollectionFolderImageProvider.cs)30
-rw-r--r--Emby.Server.Implementations/Images/DynamicImageProvider.cs (renamed from Emby.Server.Implementations/UserViews/DynamicImageProvider.cs)30
-rw-r--r--Emby.Server.Implementations/Images/FolderImageProvider.cs37
-rw-r--r--Emby.Server.Implementations/Images/GenreImageProvider.cs55
-rw-r--r--Emby.Server.Implementations/Images/MusicAlbumImageProvider.cs19
-rw-r--r--Emby.Server.Implementations/Images/MusicGenreImageProvider.cs59
-rw-r--r--Emby.Server.Implementations/Images/PhotoAlbumImageProvider.cs19
-rw-r--r--Emby.Server.Implementations/Images/PlaylistImageProvider.cs66
-rw-r--r--Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs120
-rw-r--r--Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs104
-rw-r--r--Emby.Server.Implementations/Library/ExclusiveLiveStream.cs35
-rw-r--r--Emby.Server.Implementations/Library/IgnorePatterns.cs123
-rw-r--r--Emby.Server.Implementations/Library/LibraryManager.cs1414
-rw-r--r--Emby.Server.Implementations/Library/LiveStreamHelper.cs50
-rw-r--r--Emby.Server.Implementations/Library/MediaSourceManager.cs272
-rw-r--r--Emby.Server.Implementations/Library/MediaStreamSelector.cs51
-rw-r--r--Emby.Server.Implementations/Library/MusicManager.cs39
-rw-r--r--Emby.Server.Implementations/Library/PathExtensions.cs98
-rw-r--r--Emby.Server.Implementations/Library/ResolverHelper.cs64
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs39
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs139
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs45
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs97
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs35
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs26
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/GenericFolderResolver.cs27
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs (renamed from Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs)4
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs20
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs11
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs353
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs27
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs68
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs69
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs12
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs44
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs41
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs81
-rw-r--r--Emby.Server.Implementations/Library/SearchEngine.cs71
-rw-r--r--Emby.Server.Implementations/Library/UserDataManager.cs100
-rw-r--r--Emby.Server.Implementations/Library/UserManager.cs1220
-rw-r--r--Emby.Server.Implementations/Library/UserViewManager.cs101
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs13
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs30
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs15
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresValidator.cs19
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs14
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs19
-rw-r--r--Emby.Server.Implementations/Library/Validators/PeopleValidator.cs33
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs15
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosValidator.cs37
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs77
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs765
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs201
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs6
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs54
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs11
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs171
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs19
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs24
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs8
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs56
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs1014
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/BroadcasterDto.cs34
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CaptionDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CastDto.cs46
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ChannelDto.cs30
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ContentRatingDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CrewDto.cs40
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DayDto.cs30
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description1000Dto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description100Dto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DescriptionsProgramDto.cs24
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/EventDetailsDto.cs16
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/GracenoteDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/HeadendsDto.cs36
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ImageDataDto.cs70
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupDto.cs46
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupsDto.cs36
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LogoDto.cs34
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MapDto.cs58
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataDto.cs28
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataProgramsDto.cs16
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataScheduleDto.cs41
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MovieDto.cs30
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MultipartDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs156
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDto.cs90
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/QualityRatingDto.cs40
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RatingDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RecommendationDto.cs22
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RequestScheduleForChannelDto.cs24
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ShowImagesDto.cs24
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/StationDto.cs66
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TitleDto.cs16
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TokenDto.cs47
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs106
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs8
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs67
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvManager.cs563
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs58
-rw-r--r--Emby.Server.Implementations/LiveTv/RefreshGuideScheduledTask.cs (renamed from Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs)50
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs63
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs23
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs42
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunChannelCommands.cs35
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs473
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs582
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs328
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/IHdHomerunChannelCommands.cs11
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/LegacyHdHomerunChannelCommands.cs38
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs224
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs91
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs148
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs175
-rw-r--r--Emby.Server.Implementations/Localization/Core/af.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/ar.json105
-rw-r--r--Emby.Server.Implementations/Localization/Core/bg-BG.json87
-rw-r--r--Emby.Server.Implementations/Localization/Core/bn.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/ca.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/cs.json61
-rw-r--r--Emby.Server.Implementations/Localization/Core/cy.json14
-rw-r--r--Emby.Server.Implementations/Localization/Core/da.json61
-rw-r--r--Emby.Server.Implementations/Localization/Core/de.json49
-rw-r--r--Emby.Server.Implementations/Localization/Core/el.json53
-rw-r--r--Emby.Server.Implementations/Localization/Core/en-GB.json39
-rw-r--r--Emby.Server.Implementations/Localization/Core/en-US.json39
-rw-r--r--Emby.Server.Implementations/Localization/Core/eo.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/es-AR.json215
-rw-r--r--Emby.Server.Implementations/Localization/Core/es-MX.json93
-rw-r--r--Emby.Server.Implementations/Localization/Core/es.json49
-rw-r--r--Emby.Server.Implementations/Localization/Core/es_419.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/es_DO.json23
-rw-r--r--Emby.Server.Implementations/Localization/Core/et.json118
-rw-r--r--Emby.Server.Implementations/Localization/Core/fa.json117
-rw-r--r--Emby.Server.Implementations/Localization/Core/fi.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/fil.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/fr-CA.json201
-rw-r--r--Emby.Server.Implementations/Localization/Core/fr.json63
-rw-r--r--Emby.Server.Implementations/Localization/Core/gl.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/gsw.json203
-rw-r--r--Emby.Server.Implementations/Localization/Core/he.json185
-rw-r--r--Emby.Server.Implementations/Localization/Core/hi.json64
-rw-r--r--Emby.Server.Implementations/Localization/Core/hr.json135
-rw-r--r--Emby.Server.Implementations/Localization/Core/hu.json99
-rw-r--r--Emby.Server.Implementations/Localization/Core/id.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/is.json111
-rw-r--r--Emby.Server.Implementations/Localization/Core/it.json75
-rw-r--r--Emby.Server.Implementations/Localization/Core/ja.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/kk.json201
-rw-r--r--Emby.Server.Implementations/Localization/Core/ko.json211
-rw-r--r--Emby.Server.Implementations/Localization/Core/lt-LT.json193
-rw-r--r--Emby.Server.Implementations/Localization/Core/lv.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/mk.json101
-rw-r--r--Emby.Server.Implementations/Localization/Core/ml.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/mr.json62
-rw-r--r--Emby.Server.Implementations/Localization/Core/ms.json156
-rw-r--r--Emby.Server.Implementations/Localization/Core/nb.json139
-rw-r--r--Emby.Server.Implementations/Localization/Core/ne.json85
-rw-r--r--Emby.Server.Implementations/Localization/Core/nl.json53
-rw-r--r--Emby.Server.Implementations/Localization/Core/nn.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/pa.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/pl.json65
-rw-r--r--Emby.Server.Implementations/Localization/Core/pr.json5
-rw-r--r--Emby.Server.Implementations/Localization/Core/pt-BR.json85
-rw-r--r--Emby.Server.Implementations/Localization/Core/pt-PT.json207
-rw-r--r--Emby.Server.Implementations/Localization/Core/pt.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/ro.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/ru.json81
-rw-r--r--Emby.Server.Implementations/Localization/Core/sk.json113
-rw-r--r--Emby.Server.Implementations/Localization/Core/sl-SI.json213
-rw-r--r--Emby.Server.Implementations/Localization/Core/sq.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/sr.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/sv.json79
-rw-r--r--Emby.Server.Implementations/Localization/Core/ta.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/th.json121
-rw-r--r--Emby.Server.Implementations/Localization/Core/tr.json215
-rw-r--r--Emby.Server.Implementations/Localization/Core/uk.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/ur_PK.json117
-rw-r--r--Emby.Server.Implementations/Localization/Core/vi.json123
-rw-r--r--Emby.Server.Implementations/Localization/Core/zh-CN.json69
-rw-r--r--Emby.Server.Implementations/Localization/Core/zh-HK.json215
-rw-r--r--Emby.Server.Implementations/Localization/Core/zh-TW.json123
-rw-r--r--Emby.Server.Implementations/Localization/LocalizationManager.cs505
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/au.csv8
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/be.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/de.csv10
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ru.csv5
-rw-r--r--Emby.Server.Implementations/Localization/countries.json6
-rw-r--r--Emby.Server.Implementations/Localization/iso6392.txt2
-rw-r--r--Emby.Server.Implementations/MediaEncoder/EncodingManager.cs77
-rw-r--r--Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs66
-rw-r--r--Emby.Server.Implementations/Net/IWebSocket.cs53
-rw-r--r--Emby.Server.Implementations/Net/SocketFactory.cs210
-rw-r--r--Emby.Server.Implementations/Net/UdpSocket.cs137
-rw-r--r--Emby.Server.Implementations/Net/WebSocketConnectEventArgs.cs29
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/BigIntegerExt.cs167
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/IPAddressCollection.cs94
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs2008
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/IPNetworkCollection.cs129
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/LICENSE.txt24
-rw-r--r--Emby.Server.Implementations/Networking/NetworkManager.cs727
-rw-r--r--Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs126
-rw-r--r--Emby.Server.Implementations/Playlists/PlaylistManager.cs217
-rw-r--r--Emby.Server.Implementations/Playlists/PlaylistsFolder.cs (renamed from Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs)31
-rw-r--r--Emby.Server.Implementations/Plugins/PluginManager.cs757
-rw-r--r--Emby.Server.Implementations/Properties/AssemblyInfo.cs5
-rw-r--r--Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs246
-rw-r--r--Emby.Server.Implementations/Reflection/AssemblyInfo.cs25
-rw-r--r--Emby.Server.Implementations/ResourceFileManager.cs65
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs263
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/TaskManager.cs105
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs78
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs78
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs75
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs79
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs170
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs104
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs51
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs90
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs51
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs57
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs50
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs43
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs65
-rw-r--r--Emby.Server.Implementations/Security/AuthenticationRepository.cs427
-rw-r--r--Emby.Server.Implementations/Security/EncryptionManager.cs57
-rw-r--r--Emby.Server.Implementations/Serialization/JsonSerializer.cs289
-rw-r--r--Emby.Server.Implementations/Serialization/MyXmlSerializer.cs (renamed from Emby.Server.Implementations/Serialization/XmlSerializer.cs)55
-rw-r--r--Emby.Server.Implementations/ServerApplicationPaths.cs103
-rw-r--r--Emby.Server.Implementations/Services/HttpResult.cs61
-rw-r--r--Emby.Server.Implementations/Services/RequestHelper.cs52
-rw-r--r--Emby.Server.Implementations/Services/ResponseHelper.cs163
-rw-r--r--Emby.Server.Implementations/Services/ServiceController.cs184
-rw-r--r--Emby.Server.Implementations/Services/ServiceExec.cs219
-rw-r--r--Emby.Server.Implementations/Services/ServiceHandler.cs245
-rw-r--r--Emby.Server.Implementations/Services/ServiceMethod.cs17
-rw-r--r--Emby.Server.Implementations/Services/ServicePath.cs564
-rw-r--r--Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs128
-rw-r--r--Emby.Server.Implementations/Services/SwaggerService.cs247
-rw-r--r--Emby.Server.Implementations/Services/UrlExtensions.cs33
-rw-r--r--Emby.Server.Implementations/Session/HttpSessionController.cs191
-rw-r--r--Emby.Server.Implementations/Session/SessionManager.cs948
-rw-r--r--Emby.Server.Implementations/Session/SessionWebSocketListener.cs312
-rw-r--r--Emby.Server.Implementations/Session/WebSocketController.cs89
-rw-r--r--Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs42
-rw-r--r--Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/AlbumComparer.cs18
-rw-r--r--Emby.Server.Implementations/Sorting/AlphanumComparator.cs99
-rw-r--r--Emby.Server.Implementations/Sorting/ArtistComparer.cs28
-rw-r--r--Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/CriticRatingComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/DateCreatedComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/DatePlayedComparer.cs17
-rw-r--r--Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs40
-rw-r--r--Emby.Server.Implementations/Sorting/IsFolderComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/IsPlayedComparer.cs41
-rw-r--r--Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs41
-rw-r--r--Emby.Server.Implementations/Sorting/NameComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/PlayCountComparer.cs41
-rw-r--r--Emby.Server.Implementations/Sorting/PremiereDateComparer.cs24
-rw-r--r--Emby.Server.Implementations/Sorting/ProductionYearComparer.cs23
-rw-r--r--Emby.Server.Implementations/Sorting/RandomComparer.cs16
-rw-r--r--Emby.Server.Implementations/Sorting/RuntimeComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs18
-rw-r--r--Emby.Server.Implementations/Sorting/SortNameComparer.cs20
-rw-r--r--Emby.Server.Implementations/Sorting/StartDateComparer.cs21
-rw-r--r--Emby.Server.Implementations/Sorting/StudioComparer.cs24
-rw-r--r--Emby.Server.Implementations/SyncPlay/Group.cs688
-rw-r--r--Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs396
-rw-r--r--Emby.Server.Implementations/TV/TVSeriesManager.cs153
-rw-r--r--Emby.Server.Implementations/Udp/UdpServer.cs298
-rw-r--r--Emby.Server.Implementations/Updates/InstallationManager.cs840
-rw-r--r--Emby.Server.Implementations/UserViews/FolderImageProvider.cs106
-rw-r--r--Emby.Server.Implementations/Xml/XmlReaderSettingsFactory.cs20
-rw-r--r--Emby.XmlTv/.gitattributes63
-rw-r--r--Emby.XmlTv/.gitignore212
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Console/App.config6
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Console/Classes/EntityExtensions.cs58
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Console/Emby.XmlTv.Console.csproj22
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Console/Program.cs103
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Console/Properties/AssemblyInfo.cs36
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Test/Emby.XmlTv.Test.csproj124
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Test/Properties/AssemblyInfo.cs36
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderDateTimeTests.cs91
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderLanguageTests.cs181
-rw-r--r--Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderTests.cs219
-rw-r--r--Emby.XmlTv/Emby.XmlTv.sln44
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs1086
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Emby.XmlTv.csproj12
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvChannel.cs50
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCredit.cs13
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCreditType.cs17
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvEpisode.cs52
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvIcon.cs27
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvLanguage.cs15
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvPremiere.cs13
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvProgram.cs93
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Entities/XmlTvRating.cs40
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Properties/AssemblyInfo.cs21
-rw-r--r--Emby.XmlTv/Emby.XmlTv/XmlTvSchema.dtd575
-rw-r--r--Emby.XmlTv/License.txt21
-rw-r--r--Emby.XmlTv/Nuget/Emby.XmlTv.nuspec20
-rw-r--r--Emby.XmlTv/README.md1
-rw-r--r--Jellyfin.Api/Attributes/AcceptsFileAttribute.cs28
-rw-r--r--Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs18
-rw-r--r--Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs35
-rw-r--r--Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs35
-rw-r--r--Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs12
-rw-r--r--Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs18
-rw-r--r--Jellyfin.Api/Attributes/ProducesFileAttribute.cs28
-rw-r--r--Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs18
-rw-r--r--Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs18
-rw-r--r--Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs18
-rw-r--r--Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs47
-rw-r--r--Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/BaseAuthorizationHandler.cs112
-rw-r--r--Jellyfin.Api/Auth/CustomAuthenticationHandler.cs84
-rw-r--r--Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs44
-rw-r--r--Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs44
-rw-r--r--Jellyfin.Api/Auth/DownloadPolicy/DownloadRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs56
-rw-r--r--Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs56
-rw-r--r--Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs57
-rw-r--r--Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs44
-rw-r--r--Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs45
-rw-r--r--Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs44
-rw-r--r--Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs45
-rw-r--r--Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs11
-rw-r--r--Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs105
-rw-r--r--Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs25
-rw-r--r--Jellyfin.Api/BaseJellyfinApiController.cs19
-rw-r--r--Jellyfin.Api/Constants/AuthenticationSchemes.cs13
-rw-r--r--Jellyfin.Api/Constants/InternalClaimTypes.cs43
-rw-r--r--Jellyfin.Api/Constants/Policies.cs78
-rw-r--r--Jellyfin.Api/Constants/UserRoles.cs23
-rw-r--r--Jellyfin.Api/Controllers/ActivityLogController.cs57
-rw-r--r--Jellyfin.Api/Controllers/ApiKeyController.cs80
-rw-r--r--Jellyfin.Api/Controllers/ArtistsController.cs482
-rw-r--r--Jellyfin.Api/Controllers/AudioController.cs364
-rw-r--r--Jellyfin.Api/Controllers/BrandingController.cs57
-rw-r--r--Jellyfin.Api/Controllers/ChannelsController.cs251
-rw-r--r--Jellyfin.Api/Controllers/CollectionController.cs116
-rw-r--r--Jellyfin.Api/Controllers/ConfigurationController.cs135
-rw-r--r--Jellyfin.Api/Controllers/DashboardController.cs113
-rw-r--r--Jellyfin.Api/Controllers/DevicesController.cs141
-rw-r--r--Jellyfin.Api/Controllers/DisplayPreferencesController.cs212
-rw-r--r--Jellyfin.Api/Controllers/DlnaController.cs133
-rw-r--r--Jellyfin.Api/Controllers/DlnaServerController.cs386
-rw-r--r--Jellyfin.Api/Controllers/DynamicHlsController.cs1841
-rw-r--r--Jellyfin.Api/Controllers/EnvironmentController.cs197
-rw-r--r--Jellyfin.Api/Controllers/FilterController.cs217
-rw-r--r--Jellyfin.Api/Controllers/GenresController.cs212
-rw-r--r--Jellyfin.Api/Controllers/HlsSegmentController.cs192
-rw-r--r--Jellyfin.Api/Controllers/ImageByNameController.cs252
-rw-r--r--Jellyfin.Api/Controllers/ImageController.cs2032
-rw-r--r--Jellyfin.Api/Controllers/InstantMixController.cs361
-rw-r--r--Jellyfin.Api/Controllers/ItemLookupController.cs278
-rw-r--r--Jellyfin.Api/Controllers/ItemRefreshController.cs86
-rw-r--r--Jellyfin.Api/Controllers/ItemUpdateController.cs (renamed from MediaBrowser.Api/ItemUpdateService.cs)457
-rw-r--r--Jellyfin.Api/Controllers/ItemsController.cs833
-rw-r--r--Jellyfin.Api/Controllers/LibraryController.cs1003
-rw-r--r--Jellyfin.Api/Controllers/LibraryStructureController.cs327
-rw-r--r--Jellyfin.Api/Controllers/LiveTvController.cs1229
-rw-r--r--Jellyfin.Api/Controllers/LocalizationController.cs76
-rw-r--r--Jellyfin.Api/Controllers/MediaInfoController.cs328
-rw-r--r--Jellyfin.Api/Controllers/MoviesController.cs330
-rw-r--r--Jellyfin.Api/Controllers/MusicGenresController.cs196
-rw-r--r--Jellyfin.Api/Controllers/NotificationsController.cs138
-rw-r--r--Jellyfin.Api/Controllers/PackageController.cs167
-rw-r--r--Jellyfin.Api/Controllers/PersonsController.cs147
-rw-r--r--Jellyfin.Api/Controllers/PlaylistsController.cs220
-rw-r--r--Jellyfin.Api/Controllers/PlaystateController.cs371
-rw-r--r--Jellyfin.Api/Controllers/PluginsController.cs341
-rw-r--r--Jellyfin.Api/Controllers/QuickConnectController.cs123
-rw-r--r--Jellyfin.Api/Controllers/RemoteImageController.cs187
-rw-r--r--Jellyfin.Api/Controllers/ScheduledTasksController.cs161
-rw-r--r--Jellyfin.Api/Controllers/SearchController.cs268
-rw-r--r--Jellyfin.Api/Controllers/SessionController.cs508
-rw-r--r--Jellyfin.Api/Controllers/StartupController.cs150
-rw-r--r--Jellyfin.Api/Controllers/StudiosController.cs154
-rw-r--r--Jellyfin.Api/Controllers/SubtitleController.cs549
-rw-r--r--Jellyfin.Api/Controllers/SuggestionsController.cs91
-rw-r--r--Jellyfin.Api/Controllers/SyncPlayController.cs423
-rw-r--r--Jellyfin.Api/Controllers/SystemController.cs222
-rw-r--r--Jellyfin.Api/Controllers/TimeSyncController.cs34
-rw-r--r--Jellyfin.Api/Controllers/TrailersController.cs283
-rw-r--r--Jellyfin.Api/Controllers/TvShowsController.cs388
-rw-r--r--Jellyfin.Api/Controllers/UniversalAudioController.cs368
-rw-r--r--Jellyfin.Api/Controllers/UserController.cs590
-rw-r--r--Jellyfin.Api/Controllers/UserLibraryController.cs394
-rw-r--r--Jellyfin.Api/Controllers/UserViewsController.cs151
-rw-r--r--Jellyfin.Api/Controllers/VideoAttachmentsController.cs82
-rw-r--r--Jellyfin.Api/Controllers/VideoHlsController.cs586
-rw-r--r--Jellyfin.Api/Controllers/VideosController.cs687
-rw-r--r--Jellyfin.Api/Controllers/YearsController.cs229
-rw-r--r--Jellyfin.Api/Extensions/DtoExtensions.cs116
-rw-r--r--Jellyfin.Api/Helpers/AudioHelper.cs188
-rw-r--r--Jellyfin.Api/Helpers/ClaimHelpers.cs88
-rw-r--r--Jellyfin.Api/Helpers/ClassMigrationHelper.cs71
-rw-r--r--Jellyfin.Api/Helpers/DynamicHlsHelper.cs707
-rw-r--r--Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs140
-rw-r--r--Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs169
-rw-r--r--Jellyfin.Api/Helpers/HlsHelpers.cs138
-rw-r--r--Jellyfin.Api/Helpers/MediaInfoHelper.cs583
-rw-r--r--Jellyfin.Api/Helpers/ProgressiveFileStream.cs163
-rw-r--r--Jellyfin.Api/Helpers/RequestHelpers.cs157
-rw-r--r--Jellyfin.Api/Helpers/StreamingHelpers.cs774
-rw-r--r--Jellyfin.Api/Helpers/TranscodingJobHelper.cs892
-rw-r--r--Jellyfin.Api/Jellyfin.Api.csproj40
-rw-r--r--Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs90
-rw-r--r--Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs49
-rw-r--r--Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs48
-rw-r--r--Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs27
-rw-r--r--Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs90
-rw-r--r--Jellyfin.Api/Models/ConfigurationDtos/MediaEncoderPathDto.cs18
-rw-r--r--Jellyfin.Api/Models/ConfigurationPageInfo.cs67
-rw-r--r--Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs106
-rw-r--r--Jellyfin.Api/Models/EnvironmentDtos/DefaultDirectoryBrowserInfoDto.cs13
-rw-r--r--Jellyfin.Api/Models/EnvironmentDtos/ValidatePathDto.cs23
-rw-r--r--Jellyfin.Api/Models/LibraryDtos/LibraryOptionInfoDto.cs18
-rw-r--r--Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs31
-rw-r--r--Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs38
-rw-r--r--Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs16
-rw-r--r--Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs19
-rw-r--r--Jellyfin.Api/Models/LibraryStructureDto/AddVirtualFolderDto.cs15
-rw-r--r--Jellyfin.Api/Models/LibraryStructureDto/MediaPathDto.cs27
-rw-r--r--Jellyfin.Api/Models/LibraryStructureDto/UpdateLibraryOptionsDto.cs21
-rw-r--r--Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs23
-rw-r--r--Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs36
-rw-r--r--Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs179
-rw-r--r--Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs28
-rw-r--r--Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs78
-rw-r--r--Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs86
-rw-r--r--Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs30
-rw-r--r--Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs51
-rw-r--r--Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs21
-rw-r--r--Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs20
-rw-r--r--Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs284
-rw-r--r--Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs (renamed from MediaBrowser.Api/Playback/TranscodingThrottler.cs)130
-rw-r--r--Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs34
-rw-r--r--Jellyfin.Api/Models/PluginDtos/MBRegistrationRecord.cs40
-rw-r--r--Jellyfin.Api/Models/PluginDtos/PluginSecurityInfo.cs18
-rw-r--r--Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs88
-rw-r--r--Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs23
-rw-r--r--Jellyfin.Api/Models/StartupDtos/StartupRemoteAccessDto.cs22
-rw-r--r--Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs18
-rw-r--r--Jellyfin.Api/Models/StreamingDtos/HlsAudioRequestDto.cs13
-rw-r--r--Jellyfin.Api/Models/StreamingDtos/HlsVideoRequestDto.cs13
-rw-r--r--Jellyfin.Api/Models/StreamingDtos/StreamState.cs204
-rw-r--r--Jellyfin.Api/Models/StreamingDtos/StreamingRequestDto.cs45
-rw-r--r--Jellyfin.Api/Models/StreamingDtos/VideoRequestDto.cs19
-rw-r--r--Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs34
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs42
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs14
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs16
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs30
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs22
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs24
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs14
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs37
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs24
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs32
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs42
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs37
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs14
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs24
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs16
-rw-r--r--Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs16
-rw-r--r--Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs26
-rw-r--r--Jellyfin.Api/Models/UserDtos/CreateUserByName.cs18
-rw-r--r--Jellyfin.Api/Models/UserDtos/ForgotPasswordDto.cs16
-rw-r--r--Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs16
-rw-r--r--Jellyfin.Api/Models/UserDtos/QuickConnectDto.cs16
-rw-r--r--Jellyfin.Api/Models/UserDtos/UpdateUserEasyPassword.cs23
-rw-r--r--Jellyfin.Api/Models/UserDtos/UpdateUserPassword.cs28
-rw-r--r--Jellyfin.Api/Models/UserViewDtos/SpecialViewOptionDto.cs18
-rw-r--r--Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs64
-rw-r--r--Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs84
-rw-r--r--Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs104
-rw-r--r--Jellyfin.Data/DayOfWeekHelper.cs21
-rw-r--r--Jellyfin.Data/Dtos/DeviceOptionsDto.cs23
-rw-r--r--Jellyfin.Data/Entities/AccessSchedule.cs62
-rw-r--r--Jellyfin.Data/Entities/ActivityLog.cs130
-rw-r--r--Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs80
-rw-r--r--Jellyfin.Data/Entities/DisplayPreferences.cs150
-rw-r--r--Jellyfin.Data/Entities/Group.cs83
-rw-r--r--Jellyfin.Data/Entities/HomeSection.cs44
-rw-r--r--Jellyfin.Data/Entities/ImageInfo.cs54
-rw-r--r--Jellyfin.Data/Entities/ItemDisplayPreferences.cs113
-rw-r--r--Jellyfin.Data/Entities/Libraries/Artwork.cs67
-rw-r--r--Jellyfin.Data/Entities/Libraries/Book.cs29
-rw-r--r--Jellyfin.Data/Entities/Libraries/BookMetadata.cs34
-rw-r--r--Jellyfin.Data/Entities/Libraries/Chapter.cs83
-rw-r--r--Jellyfin.Data/Entities/Libraries/Collection.cs57
-rw-r--r--Jellyfin.Data/Entities/Libraries/CollectionItem.cs64
-rw-r--r--Jellyfin.Data/Entities/Libraries/Company.cs54
-rw-r--r--Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs59
-rw-r--r--Jellyfin.Data/Entities/Libraries/CustomItem.cs29
-rw-r--r--Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs17
-rw-r--r--Jellyfin.Data/Entities/Libraries/Episode.cs34
-rw-r--r--Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs49
-rw-r--r--Jellyfin.Data/Entities/Libraries/Genre.cs50
-rw-r--r--Jellyfin.Data/Entities/Libraries/ItemMetadata.cs148
-rw-r--r--Jellyfin.Data/Entities/Libraries/Library.cs60
-rw-r--r--Jellyfin.Data/Entities/Libraries/LibraryItem.cs55
-rw-r--r--Jellyfin.Data/Entities/Libraries/MediaFile.cs75
-rw-r--r--Jellyfin.Data/Entities/Libraries/MediaFileStream.cs50
-rw-r--r--Jellyfin.Data/Entities/Libraries/MetadataProvider.cs56
-rw-r--r--Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs66
-rw-r--r--Jellyfin.Data/Entities/Libraries/Movie.cs29
-rw-r--r--Jellyfin.Data/Entities/Libraries/MovieMetadata.cs70
-rw-r--r--Jellyfin.Data/Entities/Libraries/MusicAlbum.cs30
-rw-r--r--Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs56
-rw-r--r--Jellyfin.Data/Entities/Libraries/Person.cs92
-rw-r--r--Jellyfin.Data/Entities/Libraries/PersonRole.cs80
-rw-r--r--Jellyfin.Data/Entities/Libraries/Photo.cs29
-rw-r--r--Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs17
-rw-r--r--Jellyfin.Data/Entities/Libraries/Rating.cs59
-rw-r--r--Jellyfin.Data/Entities/Libraries/RatingSource.cs73
-rw-r--r--Jellyfin.Data/Entities/Libraries/Release.cs70
-rw-r--r--Jellyfin.Data/Entities/Libraries/Season.cs35
-rw-r--r--Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs29
-rw-r--r--Jellyfin.Data/Entities/Libraries/Series.cs46
-rw-r--r--Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs70
-rw-r--r--Jellyfin.Data/Entities/Libraries/Track.cs34
-rw-r--r--Jellyfin.Data/Entities/Libraries/TrackMetadata.cs17
-rw-r--r--Jellyfin.Data/Entities/Permission.cs68
-rw-r--r--Jellyfin.Data/Entities/Preference.cs68
-rw-r--r--Jellyfin.Data/Entities/Security/ApiKey.cs56
-rw-r--r--Jellyfin.Data/Entities/Security/Device.cs107
-rw-r--r--Jellyfin.Data/Entities/Security/DeviceOptions.cs35
-rw-r--r--Jellyfin.Data/Entities/User.cs521
-rw-r--r--Jellyfin.Data/Enums/ArtKind.cs33
-rw-r--r--Jellyfin.Data/Enums/BaseItemKind.cs205
-rw-r--r--Jellyfin.Data/Enums/ChromecastVersion.cs18
-rw-r--r--Jellyfin.Data/Enums/DynamicDayOfWeek.cs58
-rw-r--r--Jellyfin.Data/Enums/HomeSectionType.cs58
-rw-r--r--Jellyfin.Data/Enums/IndexingKind.cs23
-rw-r--r--Jellyfin.Data/Enums/MediaFileKind.cs33
-rw-r--r--Jellyfin.Data/Enums/PermissionKind.cs113
-rw-r--r--Jellyfin.Data/Enums/PersonRoleType.cs68
-rw-r--r--Jellyfin.Data/Enums/PreferenceKind.cs68
-rw-r--r--Jellyfin.Data/Enums/ScrollDirection.cs18
-rw-r--r--Jellyfin.Data/Enums/SortOrder.cs18
-rw-r--r--Jellyfin.Data/Enums/SubtitlePlaybackMode.cs33
-rw-r--r--Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs28
-rw-r--r--Jellyfin.Data/Enums/SyncPlayUserAccessType.cs23
-rw-r--r--Jellyfin.Data/Enums/UnratedItem.cs53
-rw-r--r--Jellyfin.Data/Enums/ViewType.cs113
-rw-r--r--Jellyfin.Data/Events/GenericEventArgs.cs (renamed from MediaBrowser.Model/Events/GenericEventArgs.cs)19
-rw-r--r--Jellyfin.Data/Events/System/PendingRestartEventArgs.cs11
-rw-r--r--Jellyfin.Data/Events/Users/UserCreatedEventArgs.cs18
-rw-r--r--Jellyfin.Data/Events/Users/UserDeletedEventArgs.cs18
-rw-r--r--Jellyfin.Data/Events/Users/UserLockedOutEventArgs.cs18
-rw-r--r--Jellyfin.Data/Events/Users/UserPasswordChangedEventArgs.cs18
-rw-r--r--Jellyfin.Data/Events/Users/UserUpdatedEventArgs.cs18
-rw-r--r--Jellyfin.Data/Interfaces/IHasArtwork.cs16
-rw-r--r--Jellyfin.Data/Interfaces/IHasCompanies.cs16
-rw-r--r--Jellyfin.Data/Interfaces/IHasConcurrencyToken.cs18
-rw-r--r--Jellyfin.Data/Interfaces/IHasPermissions.cs31
-rw-r--r--Jellyfin.Data/Interfaces/IHasReleases.cs16
-rw-r--r--Jellyfin.Data/Jellyfin.Data.csproj45
-rw-r--r--Jellyfin.Data/Queries/ActivityLogQuery.cs20
-rw-r--r--Jellyfin.Data/Queries/DeviceQuery.cs25
-rw-r--r--Jellyfin.Data/Queries/PaginatedQuery.cs18
-rw-r--r--Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj22
-rw-r--r--Jellyfin.Drawing.Skia/PercentPlayedDrawer.cs31
-rw-r--r--Jellyfin.Drawing.Skia/PlayedIndicatorDrawer.cs48
-rw-r--r--Jellyfin.Drawing.Skia/Properties/AssemblyInfo.cs4
-rw-r--r--Jellyfin.Drawing.Skia/SkiaCodecException.cs45
-rw-r--r--Jellyfin.Drawing.Skia/SkiaEncoder.cs726
-rw-r--r--Jellyfin.Drawing.Skia/SkiaException.cs39
-rw-r--r--Jellyfin.Drawing.Skia/SkiaHelper.cs23
-rw-r--r--Jellyfin.Drawing.Skia/StripCollageBuilder.cs262
-rw-r--r--Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs71
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfiguration.cs235
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs20
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs27
-rw-r--r--Jellyfin.Networking/Jellyfin.Networking.csproj23
-rw-r--r--Jellyfin.Networking/Manager/NetworkManager.cs1380
-rw-r--r--Jellyfin.Server.Implementations/Activity/ActivityManager.cs100
-rw-r--r--Jellyfin.Server.Implementations/Devices/DeviceManager.cs243
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Library/SubtitleDownloadFailureLogger.cs102
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationFailedLogger.cs52
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs49
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs104
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs112
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Session/SessionEndedLogger.cs54
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Session/SessionStartedLogger.cs54
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/System/PendingRestartNotifier.cs31
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs158
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedLogger.cs51
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledLogger.cs50
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs45
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs32
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUpdatedLogger.cs51
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserCreatedLogger.cs43
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedLogger.cs44
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs39
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserLockedOutLogger.cs47
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserPasswordChangedLogger.cs43
-rw-r--r--Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs42
-rw-r--r--Jellyfin.Server.Implementations/Events/EventManager.cs65
-rw-r--r--Jellyfin.Server.Implementations/Events/EventingServiceCollectionExtensions.cs72
-rw-r--r--Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj40
-rw-r--r--Jellyfin.Server.Implementations/JellyfinDb.cs162
-rw-r--r--Jellyfin.Server.Implementations/JellyfinDbProvider.cs51
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.Designer.cs72
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.cs46
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.Designer.cs312
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.cs197
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.Designer.cs459
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.cs132
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.Designer.cs461
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.cs51
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs464
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs28
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs522
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs108
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs535
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs240
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs520
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs35
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.Designer.cs653
-rw-r--r--Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.cs128
-rw-r--r--Jellyfin.Server.Implementations/Migrations/DesignTimeJellyfinDbFactory.cs20
-rw-r--r--Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs649
-rw-r--r--Jellyfin.Server.Implementations/ModelBuilderExtensions.cs48
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/ApiKeyConfiguration.cs20
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/CustomItemDisplayPreferencesConfiguration.cs20
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/DeviceConfiguration.cs28
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/DeviceOptionsConfiguration.cs20
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/DisplayPreferencesConfiguration.cs25
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/PermissionConfiguration.cs24
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/PreferenceConfiguration.cs21
-rw-r--r--Jellyfin.Server.Implementations/ModelConfiguration/UserConfiguration.cs56
-rw-r--r--Jellyfin.Server.Implementations/Properties/AssemblyInfo.cs (renamed from Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs)8
-rw-r--r--Jellyfin.Server.Implementations/Security/AuthenticationManager.cs73
-rw-r--r--Jellyfin.Server.Implementations/Security/AuthorizationContext.cs308
-rw-r--r--Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs118
-rw-r--r--Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs133
-rw-r--r--Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs64
-rw-r--r--Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs104
-rw-r--r--Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs36
-rw-r--r--Jellyfin.Server.Implementations/Users/UserManager.cs876
-rw-r--r--Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs21
-rw-r--r--Jellyfin.Server/Configuration/CorsPolicyProvider.cs49
-rw-r--r--Jellyfin.Server/CoreAppHost.cs117
-rw-r--r--Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs144
-rw-r--r--Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs421
-rw-r--r--Jellyfin.Server/Filters/AdditionalModelFilter.cs34
-rw-r--r--Jellyfin.Server/Filters/FileRequestFilter.cs43
-rw-r--r--Jellyfin.Server/Filters/FileResponseFilter.cs53
-rw-r--r--Jellyfin.Server/Filters/ParameterObsoleteFilter.cs36
-rw-r--r--Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs78
-rw-r--r--Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs21
-rw-r--r--Jellyfin.Server/Formatters/CssOutputFormatter.cs36
-rw-r--r--Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs24
-rw-r--r--Jellyfin.Server/Formatters/XmlOutputFormatter.cs33
-rw-r--r--Jellyfin.Server/Infrastructure/SymlinkFollowingPhysicalFileResultExecutor.cs144
-rw-r--r--Jellyfin.Server/Jellyfin.Server.csproj73
-rw-r--r--Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs84
-rw-r--r--Jellyfin.Server/Middleware/ExceptionMiddleware.cs151
-rw-r--r--Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs50
-rw-r--r--Jellyfin.Server/Middleware/LanFilteringMiddleware.cs45
-rw-r--r--Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs54
-rw-r--r--Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs39
-rw-r--r--Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs79
-rw-r--r--Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs47
-rw-r--r--Jellyfin.Server/Middleware/ServerStartupMessageMiddleware.cs51
-rw-r--r--Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs84
-rw-r--r--Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs40
-rw-r--r--Jellyfin.Server/Migrations/IMigrationRoutine.cs30
-rw-r--r--Jellyfin.Server/Migrations/MigrationOptions.cs27
-rw-r--r--Jellyfin.Server/Migrations/MigrationRunner.cs86
-rw-r--r--Jellyfin.Server/Migrations/MigrationsFactory.cs20
-rw-r--r--Jellyfin.Server/Migrations/MigrationsListStore.cs24
-rw-r--r--Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs45
-rw-r--r--Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs49
-rw-r--r--Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs82
-rw-r--r--Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs44
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs154
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs129
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs228
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs219
-rw-r--r--Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs49
-rw-r--r--Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs52
-rw-r--r--Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs82
-rw-r--r--Jellyfin.Server/Program.cs521
-rw-r--r--Jellyfin.Server/Properties/AssemblyInfo.cs7
-rw-r--r--Jellyfin.Server/Properties/launchSettings.json29
-rw-r--r--Jellyfin.Server/Resources/Configuration/logging.json18
-rw-r--r--Jellyfin.Server/SocketSharp/HttpFile.cs18
-rw-r--r--Jellyfin.Server/SocketSharp/HttpPostedFile.cs204
-rw-r--r--Jellyfin.Server/SocketSharp/RequestMono.cs680
-rw-r--r--Jellyfin.Server/SocketSharp/SharpWebSocket.cs149
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs263
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs534
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs181
-rw-r--r--Jellyfin.Server/Startup.cs197
-rw-r--r--Jellyfin.Server/StartupOptions.cs91
-rw-r--r--Jellyfin.Server/wwwroot/api-docs/banner-dark.svg34
-rw-r--r--Jellyfin.Server/wwwroot/api-docs/redoc/custom.css0
-rw-r--r--Jellyfin.Server/wwwroot/api-docs/swagger/custom.css15
-rw-r--r--Jellyfin.sln288
-rw-r--r--MediaBrowser.Api/ApiEntryPoint.cs868
-rw-r--r--MediaBrowser.Api/BaseApiService.cs373
-rw-r--r--MediaBrowser.Api/BrandingService.cs40
-rw-r--r--MediaBrowser.Api/ChannelService.cs341
-rw-r--r--MediaBrowser.Api/ConfigurationService.cs147
-rw-r--r--MediaBrowser.Api/Devices/DeviceService.cs161
-rw-r--r--MediaBrowser.Api/DisplayPreferencesService.cs93
-rw-r--r--MediaBrowser.Api/EnvironmentService.cs321
-rw-r--r--MediaBrowser.Api/FilterService.cs234
-rw-r--r--MediaBrowser.Api/IHasDtoOptions.cs12
-rw-r--r--MediaBrowser.Api/IHasItemFields.cs49
-rw-r--r--MediaBrowser.Api/Images/ImageByNameService.cs273
-rw-r--r--MediaBrowser.Api/Images/ImageRequest.cs100
-rw-r--r--MediaBrowser.Api/Images/ImageService.cs762
-rw-r--r--MediaBrowser.Api/Images/RemoteImageService.cs291
-rw-r--r--MediaBrowser.Api/ItemLookupService.cs319
-rw-r--r--MediaBrowser.Api/ItemRefreshService.cs77
-rw-r--r--MediaBrowser.Api/Library/LibraryService.cs1210
-rw-r--r--MediaBrowser.Api/Library/LibraryStructureService.cs416
-rw-r--r--MediaBrowser.Api/LiveTv/LiveTvService.cs1268
-rw-r--r--MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs105
-rw-r--r--MediaBrowser.Api/LocalizationService.cs105
-rw-r--r--MediaBrowser.Api/MediaBrowser.Api.csproj17
-rw-r--r--MediaBrowser.Api/Movies/CollectionService.cs96
-rw-r--r--MediaBrowser.Api/Movies/MoviesService.cs406
-rw-r--r--MediaBrowser.Api/Movies/TrailersService.cs71
-rw-r--r--MediaBrowser.Api/Music/AlbumsService.cs119
-rw-r--r--MediaBrowser.Api/Music/InstantMixService.cs185
-rw-r--r--MediaBrowser.Api/PackageService.cs218
-rw-r--r--MediaBrowser.Api/Playback/BaseStreamingService.cs1056
-rw-r--r--MediaBrowser.Api/Playback/Hls/BaseHlsService.cs344
-rw-r--r--MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs997
-rw-r--r--MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs162
-rw-r--r--MediaBrowser.Api/Playback/Hls/VideoHlsService.cs162
-rw-r--r--MediaBrowser.Api/Playback/MediaInfoService.cs632
-rw-r--r--MediaBrowser.Api/Playback/Progressive/AudioService.cs93
-rw-r--r--MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs452
-rw-r--r--MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs184
-rw-r--r--MediaBrowser.Api/Playback/Progressive/VideoService.cs129
-rw-r--r--MediaBrowser.Api/Playback/StaticRemoteStreamWriter.cs44
-rw-r--r--MediaBrowser.Api/Playback/StreamRequest.cs34
-rw-r--r--MediaBrowser.Api/Playback/StreamState.cs175
-rw-r--r--MediaBrowser.Api/Playback/UniversalAudioService.cs372
-rw-r--r--MediaBrowser.Api/PlaylistService.cs208
-rw-r--r--MediaBrowser.Api/PluginService.cs277
-rw-r--r--MediaBrowser.Api/Properties/AssemblyInfo.cs21
-rw-r--r--MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs241
-rw-r--r--MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs79
-rw-r--r--MediaBrowser.Api/SearchService.cs340
-rw-r--r--MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs102
-rw-r--r--MediaBrowser.Api/Session/SessionsService.cs519
-rw-r--r--MediaBrowser.Api/SimilarItemsHelper.cs223
-rw-r--r--MediaBrowser.Api/StartupWizardService.cs134
-rw-r--r--MediaBrowser.Api/Subtitles/SubtitleService.cs292
-rw-r--r--MediaBrowser.Api/SuggestionsService.cs92
-rw-r--r--MediaBrowser.Api/System/ActivityLogService.cs54
-rw-r--r--MediaBrowser.Api/System/ActivityLogWebSocketListener.cs56
-rw-r--r--MediaBrowser.Api/System/SystemService.cs222
-rw-r--r--MediaBrowser.Api/TvShowsService.cs503
-rw-r--r--MediaBrowser.Api/UserLibrary/ArtistsService.cs140
-rw-r--r--MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs386
-rw-r--r--MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs480
-rw-r--r--MediaBrowser.Api/UserLibrary/GenresService.cs122
-rw-r--r--MediaBrowser.Api/UserLibrary/ItemsService.cs516
-rw-r--r--MediaBrowser.Api/UserLibrary/MusicGenresService.cs106
-rw-r--r--MediaBrowser.Api/UserLibrary/PersonsService.cs123
-rw-r--r--MediaBrowser.Api/UserLibrary/PlaystateService.cs449
-rw-r--r--MediaBrowser.Api/UserLibrary/StudiosService.cs114
-rw-r--r--MediaBrowser.Api/UserLibrary/UserLibraryService.cs550
-rw-r--r--MediaBrowser.Api/UserLibrary/UserViewsService.cs134
-rw-r--r--MediaBrowser.Api/UserLibrary/YearsService.cs113
-rw-r--r--MediaBrowser.Api/UserService.cs578
-rw-r--r--MediaBrowser.Api/VideosService.cs200
-rw-r--r--MediaBrowser.Common/Configuration/ConfigurationStore.cs22
-rw-r--r--MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs4
-rw-r--r--MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs43
-rw-r--r--MediaBrowser.Common/Configuration/IApplicationPaths.cs37
-rw-r--r--MediaBrowser.Common/Configuration/IConfigurationFactory.cs21
-rw-r--r--MediaBrowser.Common/Configuration/IConfigurationManager.cs11
-rw-r--r--MediaBrowser.Common/Configuration/IValidatingConfiguration.cs15
-rw-r--r--MediaBrowser.Common/Crc32.cs89
-rw-r--r--MediaBrowser.Common/Cryptography/Constants.cs18
-rw-r--r--MediaBrowser.Common/Cryptography/CryptoExtensions.cs35
-rw-r--r--MediaBrowser.Common/Cryptography/PasswordHash.cs219
-rw-r--r--MediaBrowser.Common/Events/EventHelper.cs10
-rw-r--r--MediaBrowser.Common/Extensions/BaseExtensions.cs27
-rw-r--r--MediaBrowser.Common/Extensions/HttpContextExtensions.cs41
-rw-r--r--MediaBrowser.Common/Extensions/MethodNotAllowedException.cs26
-rw-r--r--MediaBrowser.Common/Extensions/ProcessExtensions.cs80
-rw-r--r--MediaBrowser.Common/Extensions/RateLimitExceededException.cs25
-rw-r--r--MediaBrowser.Common/Extensions/ResourceNotFoundException.cs39
-rw-r--r--MediaBrowser.Common/FfmpegException.cs39
-rw-r--r--MediaBrowser.Common/IApplicationHost.cs112
-rw-r--r--MediaBrowser.Common/MediaBrowser.Common.csproj38
-rw-r--r--MediaBrowser.Common/Net/CustomHeaderNames.cs13
-rw-r--r--MediaBrowser.Common/Net/HttpRequestOptions.cs147
-rw-r--r--MediaBrowser.Common/Net/HttpResponseInfo.cs75
-rw-r--r--MediaBrowser.Common/Net/IHttpClient.cs56
-rw-r--r--MediaBrowser.Common/Net/INetworkManager.cs234
-rw-r--r--MediaBrowser.Common/Net/IPHost.cs441
-rw-r--r--MediaBrowser.Common/Net/IPNetAddress.cs276
-rw-r--r--MediaBrowser.Common/Net/IPObject.cs395
-rw-r--r--MediaBrowser.Common/Net/NamedClient.cs18
-rw-r--r--MediaBrowser.Common/Net/NetworkExtensions.cs260
-rw-r--r--MediaBrowser.Common/Plugins/BasePlugin.cs215
-rw-r--r--MediaBrowser.Common/Plugins/BasePluginOfT.cs205
-rw-r--r--MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs27
-rw-r--r--MediaBrowser.Common/Plugins/IPlugin.cs52
-rw-r--r--MediaBrowser.Common/Plugins/IPluginAssembly.cs13
-rw-r--r--MediaBrowser.Common/Plugins/IPluginManager.cs96
-rw-r--r--MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs19
-rw-r--r--MediaBrowser.Common/Plugins/LocalPlugin.cs139
-rw-r--r--MediaBrowser.Common/Plugins/PluginManifest.cs108
-rw-r--r--MediaBrowser.Common/Progress/ActionableProgress.cs38
-rw-r--r--MediaBrowser.Common/Progress/SimpleProgress.cs17
-rw-r--r--MediaBrowser.Common/Properties/AssemblyInfo.cs4
-rw-r--r--MediaBrowser.Common/Providers/ProviderIdParsers.cs123
-rw-r--r--MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs21
-rw-r--r--MediaBrowser.Common/System/OperatingSystem.cs74
-rw-r--r--MediaBrowser.Common/Updates/IInstallationManager.cs122
-rw-r--r--MediaBrowser.Common/Updates/InstallationEventArgs.cs16
-rw-r--r--MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs3
-rw-r--r--MediaBrowser.Controller/Authentication/AuthenticationException.cs35
-rw-r--r--MediaBrowser.Controller/Authentication/AuthenticationResult.cs8
-rw-r--r--MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs13
-rw-r--r--MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs29
-rw-r--r--MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs137
-rw-r--r--MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs35
-rw-r--r--MediaBrowser.Controller/Channels/Channel.cs33
-rw-r--r--MediaBrowser.Controller/Channels/ChannelItemInfo.cs41
-rw-r--r--MediaBrowser.Controller/Channels/ChannelItemResult.cs13
-rw-r--r--MediaBrowser.Controller/Channels/ChannelItemType.cs2
-rw-r--r--MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs11
-rw-r--r--MediaBrowser.Controller/Channels/ChannelParentalRating.cs2
-rw-r--r--MediaBrowser.Controller/Channels/ChannelSearchInfo.cs9
-rw-r--r--MediaBrowser.Controller/Channels/IChannel.cs6
-rw-r--r--MediaBrowser.Controller/Channels/IChannelManager.cs35
-rw-r--r--MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs12
-rw-r--r--MediaBrowser.Controller/Channels/IHasCacheKey.cs4
-rw-r--r--MediaBrowser.Controller/Channels/IHasFolderAttributes.cs9
-rw-r--r--MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs6
-rw-r--r--MediaBrowser.Controller/Channels/ISearchableChannel.cs37
-rw-r--r--MediaBrowser.Controller/Channels/ISupportsDelete.cs15
-rw-r--r--MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs21
-rw-r--r--MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs9
-rw-r--r--MediaBrowser.Controller/Channels/InternalChannelFeatures.cs26
-rw-r--r--MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs5
-rw-r--r--MediaBrowser.Controller/Chapters/IChapterManager.cs7
-rw-r--r--MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs24
-rw-r--r--MediaBrowser.Controller/Collections/CollectionCreationOptions.cs21
-rw-r--r--MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs (renamed from MediaBrowser.Controller/Collections/CollectionEvents.cs)25
-rw-r--r--MediaBrowser.Controller/Collections/ICollectionManager.cs22
-rw-r--r--MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs4
-rw-r--r--MediaBrowser.Controller/Devices/CameraImageUploadInfo.cs10
-rw-r--r--MediaBrowser.Controller/Devices/IDeviceManager.cs67
-rw-r--r--MediaBrowser.Controller/Dlna/IDlnaManager.cs16
-rw-r--r--MediaBrowser.Controller/Drawing/IImageEncoder.cs52
-rw-r--r--MediaBrowser.Controller/Drawing/IImageProcessor.cs76
-rw-r--r--MediaBrowser.Controller/Drawing/ImageCollageOptions.cs11
-rw-r--r--MediaBrowser.Controller/Drawing/ImageHelper.cs70
-rw-r--r--MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs29
-rw-r--r--MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs4
-rw-r--r--MediaBrowser.Controller/Drawing/ImageStream.cs22
-rw-r--r--MediaBrowser.Controller/Dto/DtoOptions.cs56
-rw-r--r--MediaBrowser.Controller/Dto/IDtoService.cs40
-rw-r--r--MediaBrowser.Controller/Entities/AggregateFolder.cs67
-rw-r--r--MediaBrowser.Controller/Entities/Audio/Audio.cs103
-rw-r--r--MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs25
-rw-r--r--MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs4
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs104
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicArtist.cs118
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicGenre.cs62
-rw-r--r--MediaBrowser.Controller/Entities/AudioBook.cs22
-rw-r--r--MediaBrowser.Controller/Entities/BaseItem.cs1626
-rw-r--r--MediaBrowser.Controller/Entities/BaseItemExtensions.cs61
-rw-r--r--MediaBrowser.Controller/Entities/BasePluginFolder.cs28
-rw-r--r--MediaBrowser.Controller/Entities/Book.cs31
-rw-r--r--MediaBrowser.Controller/Entities/CollectionFolder.cs126
-rw-r--r--MediaBrowser.Controller/Entities/DayOfWeekHelper.cs71
-rw-r--r--MediaBrowser.Controller/Entities/Extensions.cs15
-rw-r--r--MediaBrowser.Controller/Entities/Folder.cs690
-rw-r--r--MediaBrowser.Controller/Entities/Genre.cs62
-rw-r--r--MediaBrowser.Controller/Entities/ICollectionFolder.cs9
-rw-r--r--MediaBrowser.Controller/Entities/IHasAspectRatio.cs4
-rw-r--r--MediaBrowser.Controller/Entities/IHasDisplayOrder.cs4
-rw-r--r--MediaBrowser.Controller/Entities/IHasMediaSources.cs16
-rw-r--r--MediaBrowser.Controller/Entities/IHasProgramAttributes.cs12
-rw-r--r--MediaBrowser.Controller/Entities/IHasScreenshots.cs2
-rw-r--r--MediaBrowser.Controller/Entities/IHasSeries.cs16
-rw-r--r--MediaBrowser.Controller/Entities/IHasShares.cs11
-rw-r--r--MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs7
-rw-r--r--MediaBrowser.Controller/Entities/IHasStartDate.cs2
-rw-r--r--MediaBrowser.Controller/Entities/IHasTrailers.cs77
-rw-r--r--MediaBrowser.Controller/Entities/IItemByName.cs4
-rw-r--r--MediaBrowser.Controller/Entities/IMetadataContainer.cs2
-rw-r--r--MediaBrowser.Controller/Entities/ISupportsPlaceHolders.cs2
-rw-r--r--MediaBrowser.Controller/Entities/InternalItemsQuery.cs321
-rw-r--r--MediaBrowser.Controller/Entities/InternalPeopleQuery.cs39
-rw-r--r--MediaBrowser.Controller/Entities/ItemImageInfo.cs30
-rw-r--r--MediaBrowser.Controller/Entities/LinkedChild.cs57
-rw-r--r--MediaBrowser.Controller/Entities/LinkedChildComparer.cs35
-rw-r--r--MediaBrowser.Controller/Entities/LinkedChildType.cs18
-rw-r--r--MediaBrowser.Controller/Entities/Movies/BoxSet.cs87
-rw-r--r--MediaBrowser.Controller/Entities/Movies/Movie.cs50
-rw-r--r--MediaBrowser.Controller/Entities/MusicVideo.cs21
-rw-r--r--MediaBrowser.Controller/Entities/PeopleHelper.cs19
-rw-r--r--MediaBrowser.Controller/Entities/Person.cs109
-rw-r--r--MediaBrowser.Controller/Entities/PersonInfo.cs66
-rw-r--r--MediaBrowser.Controller/Entities/Photo.cs65
-rw-r--r--MediaBrowser.Controller/Entities/PhotoAlbum.cs10
-rw-r--r--MediaBrowser.Controller/Entities/Share.cs10
-rw-r--r--MediaBrowser.Controller/Entities/SourceType.cs2
-rw-r--r--MediaBrowser.Controller/Entities/Studio.cs54
-rw-r--r--MediaBrowser.Controller/Entities/TV/Episode.cs195
-rw-r--r--MediaBrowser.Controller/Entities/TV/Season.cs142
-rw-r--r--MediaBrowser.Controller/Entities/TV/Series.cs129
-rw-r--r--MediaBrowser.Controller/Entities/TagExtensions.cs2
-rw-r--r--MediaBrowser.Controller/Entities/Trailer.cs25
-rw-r--r--MediaBrowser.Controller/Entities/User.cs297
-rw-r--r--MediaBrowser.Controller/Entities/UserItemData.cs30
-rw-r--r--MediaBrowser.Controller/Entities/UserRootFolder.cs75
-rw-r--r--MediaBrowser.Controller/Entities/UserView.cs126
-rw-r--r--MediaBrowser.Controller/Entities/UserViewBuilder.cs207
-rw-r--r--MediaBrowser.Controller/Entities/Video.cs342
-rw-r--r--MediaBrowser.Controller/Entities/Year.cs59
-rw-r--r--MediaBrowser.Controller/Events/IEventConsumer.cs20
-rw-r--r--MediaBrowser.Controller/Events/IEventManager.cs28
-rw-r--r--MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs19
-rw-r--r--MediaBrowser.Controller/Extensions/ConfigurationExtensions.cs101
-rw-r--r--MediaBrowser.Controller/Extensions/StringExtensions.cs55
-rw-r--r--MediaBrowser.Controller/IDisplayPreferencesManager.cs69
-rw-r--r--MediaBrowser.Controller/IO/FileData.cs25
-rw-r--r--MediaBrowser.Controller/IResourceFileManager.cs16
-rw-r--r--MediaBrowser.Controller/IServerApplicationHost.cs99
-rw-r--r--MediaBrowser.Controller/IServerApplicationPaths.cs50
-rw-r--r--MediaBrowser.Controller/Library/DeleteOptions.cs9
-rw-r--r--MediaBrowser.Controller/Library/IDirectStreamProvider.cs19
-rw-r--r--MediaBrowser.Controller/Library/IIntroProvider.cs18
-rw-r--r--MediaBrowser.Controller/Library/ILibraryManager.cs219
-rw-r--r--MediaBrowser.Controller/Library/ILibraryMonitor.cs2
-rw-r--r--MediaBrowser.Controller/Library/ILibraryPostScanTask.cs2
-rw-r--r--MediaBrowser.Controller/Library/ILiveStream.cs18
-rw-r--r--MediaBrowser.Controller/Library/IMediaSourceManager.cs61
-rw-r--r--MediaBrowser.Controller/Library/IMediaSourceProvider.cs6
-rw-r--r--MediaBrowser.Controller/Library/IMetadataFileSaver.cs2
-rw-r--r--MediaBrowser.Controller/Library/IMetadataSaver.cs5
-rw-r--r--MediaBrowser.Controller/Library/IMusicManager.cs17
-rw-r--r--MediaBrowser.Controller/Library/ISearchEngine.cs2
-rw-r--r--MediaBrowser.Controller/Library/IUserDataManager.cs40
-rw-r--r--MediaBrowser.Controller/Library/IUserManager.cs161
-rw-r--r--MediaBrowser.Controller/Library/IUserViewManager.cs24
-rw-r--r--MediaBrowser.Controller/Library/IntroInfo.cs4
-rw-r--r--MediaBrowser.Controller/Library/ItemChangeEventArgs.cs6
-rw-r--r--MediaBrowser.Controller/Library/ItemResolveArgs.cs105
-rw-r--r--MediaBrowser.Controller/Library/ItemUpdateType.cs2
-rw-r--r--MediaBrowser.Controller/Library/LibraryManagerExtensions.cs4
-rw-r--r--MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs17
-rw-r--r--MediaBrowser.Controller/Library/MetadataConfigurationStore.cs14
-rw-r--r--MediaBrowser.Controller/Library/NameExtensions.cs16
-rw-r--r--MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs26
-rw-r--r--MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs9
-rw-r--r--MediaBrowser.Controller/Library/PlaybackStopEventArgs.cs2
-rw-r--r--MediaBrowser.Controller/Library/Profiler.cs76
-rw-r--r--MediaBrowser.Controller/Library/SearchHintInfo.cs4
-rw-r--r--MediaBrowser.Controller/Library/TVUtils.cs9
-rw-r--r--MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs6
-rw-r--r--MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs19
-rw-r--r--MediaBrowser.Controller/LiveTv/ChannelInfo.cs22
-rw-r--r--MediaBrowser.Controller/LiveTv/IListingsProvider.cs9
-rw-r--r--MediaBrowser.Controller/LiveTv/ILiveTvManager.cs61
-rw-r--r--MediaBrowser.Controller/LiveTv/ILiveTvService.cs8
-rw-r--r--MediaBrowser.Controller/LiveTv/ITunerHost.cs21
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvChannel.cs146
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvConflictException.cs5
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvProgram.cs194
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs17
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs14
-rw-r--r--MediaBrowser.Controller/LiveTv/ProgramInfo.cs45
-rw-r--r--MediaBrowser.Controller/LiveTv/RecordingInfo.cs31
-rw-r--r--MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs4
-rw-r--r--MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs34
-rw-r--r--MediaBrowser.Controller/LiveTv/TimerEventInfo.cs12
-rw-r--r--MediaBrowser.Controller/LiveTv/TimerInfo.cs33
-rw-r--r--MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs7
-rw-r--r--MediaBrowser.Controller/MediaBrowser.Controller.csproj40
-rw-r--r--MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs204
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs3080
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs575
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs271
-rw-r--r--MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs23
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs21
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs13
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs111
-rw-r--r--MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs16
-rw-r--r--MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs4
-rw-r--r--MediaBrowser.Controller/MediaEncoding/JobLogger.cs63
-rw-r--r--MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs46
-rw-r--r--MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs15
-rw-r--r--MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs23
-rw-r--r--MediaBrowser.Controller/Net/AuthenticatedAttribute.cs66
-rw-r--r--MediaBrowser.Controller/Net/AuthorizationInfo.cs33
-rw-r--r--MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs213
-rw-r--r--MediaBrowser.Controller/Net/IAuthService.cs13
-rw-r--r--MediaBrowser.Controller/Net/IAuthorizationContext.cs14
-rw-r--r--MediaBrowser.Controller/Net/IHasResultFactory.cs17
-rw-r--r--MediaBrowser.Controller/Net/IHttpResultFactory.cs80
-rw-r--r--MediaBrowser.Controller/Net/IHttpServer.cs39
-rw-r--r--MediaBrowser.Controller/Net/ISessionContext.cs17
-rw-r--r--MediaBrowser.Controller/Net/IWebSocketConnection.cs51
-rw-r--r--MediaBrowser.Controller/Net/IWebSocketListener.cs11
-rw-r--r--MediaBrowser.Controller/Net/IWebSocketManager.cs18
-rw-r--r--MediaBrowser.Controller/Net/SecurityException.cs32
-rw-r--r--MediaBrowser.Controller/Net/StaticResultOptions.cs39
-rw-r--r--MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs39
-rw-r--r--MediaBrowser.Controller/Net/WebSocketListenerState.cs17
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessageInfo.cs4
-rw-r--r--MediaBrowser.Controller/Notifications/INotificationManager.cs4
-rw-r--r--MediaBrowser.Controller/Notifications/INotificationService.cs6
-rw-r--r--MediaBrowser.Controller/Notifications/INotificationTypeFactory.cs2
-rw-r--r--MediaBrowser.Controller/Notifications/UserNotification.cs6
-rw-r--r--MediaBrowser.Controller/Persistence/IDisplayPreferencesRepository.cs49
-rw-r--r--MediaBrowser.Controller/Persistence/IItemRepository.cs61
-rw-r--r--MediaBrowser.Controller/Persistence/IRepository.cs4
-rw-r--r--MediaBrowser.Controller/Persistence/IUserDataRepository.cs29
-rw-r--r--MediaBrowser.Controller/Persistence/IUserRepository.cs27
-rw-r--r--MediaBrowser.Controller/Persistence/MediaAttachmentQuery.cs21
-rw-r--r--MediaBrowser.Controller/Persistence/MediaStreamQuery.cs2
-rw-r--r--MediaBrowser.Controller/Playlists/IPlaylistManager.cs8
-rw-r--r--MediaBrowser.Controller/Playlists/Playlist.cs147
-rw-r--r--MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs20
-rw-r--r--MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs50
-rw-r--r--MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs9
-rw-r--r--MediaBrowser.Controller/Plugins/IServerEntryPoint.cs13
-rw-r--r--MediaBrowser.Controller/Properties/AssemblyInfo.cs4
-rw-r--r--MediaBrowser.Controller/Providers/AlbumInfo.cs19
-rw-r--r--MediaBrowser.Controller/Providers/ArtistInfo.cs6
-rw-r--r--MediaBrowser.Controller/Providers/BookInfo.cs4
-rw-r--r--MediaBrowser.Controller/Providers/BoxSetInfo.cs3
-rw-r--r--MediaBrowser.Controller/Providers/DirectoryService.cs72
-rw-r--r--MediaBrowser.Controller/Providers/DynamicImageInfo.cs10
-rw-r--r--MediaBrowser.Controller/Providers/DynamicImageResponse.cs8
-rw-r--r--MediaBrowser.Controller/Providers/EpisodeInfo.cs15
-rw-r--r--MediaBrowser.Controller/Providers/ExtraInfo.cs15
-rw-r--r--MediaBrowser.Controller/Providers/ExtraSource.cs9
-rw-r--r--MediaBrowser.Controller/Providers/ICustomMetadataProvider.cs4
-rw-r--r--MediaBrowser.Controller/Providers/IDirectoryService.cs11
-rw-r--r--MediaBrowser.Controller/Providers/IDynamicImageProvider.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IExternalId.cs34
-rw-r--r--MediaBrowser.Controller/Providers/IExtrasProvider.cs20
-rw-r--r--MediaBrowser.Controller/Providers/IForcedProvider.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IHasLookupInfo.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IHasOrder.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IImageEnhancer.cs61
-rw-r--r--MediaBrowser.Controller/Providers/IImageProvider.cs6
-rw-r--r--MediaBrowser.Controller/Providers/ILocalImageFileProvider.cs10
-rw-r--r--MediaBrowser.Controller/Providers/ILocalImageProvider.cs8
-rw-r--r--MediaBrowser.Controller/Providers/ILocalMetadataProvider.cs7
-rw-r--r--MediaBrowser.Controller/Providers/IMetadataProvider.cs4
-rw-r--r--MediaBrowser.Controller/Providers/IMetadataService.cs17
-rw-r--r--MediaBrowser.Controller/Providers/IPreRefreshProvider.cs3
-rw-r--r--MediaBrowser.Controller/Providers/IProviderManager.cs67
-rw-r--r--MediaBrowser.Controller/Providers/IRemoteImageProvider.cs6
-rw-r--r--MediaBrowser.Controller/Providers/IRemoteMetadataProvider.cs2
-rw-r--r--MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs6
-rw-r--r--MediaBrowser.Controller/Providers/ImageRefreshOptions.cs22
-rw-r--r--MediaBrowser.Controller/Providers/ItemInfo.cs12
-rw-r--r--MediaBrowser.Controller/Providers/ItemLookupInfo.cs36
-rw-r--r--MediaBrowser.Controller/Providers/LocalImageInfo.cs5
-rw-r--r--MediaBrowser.Controller/Providers/MetadataProviderPriority.cs39
-rw-r--r--MediaBrowser.Controller/Providers/MetadataRefreshMode.cs10
-rw-r--r--MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs38
-rw-r--r--MediaBrowser.Controller/Providers/MetadataResult.cs50
-rw-r--r--MediaBrowser.Controller/Providers/MovieInfo.cs3
-rw-r--r--MediaBrowser.Controller/Providers/MusicVideoInfo.cs8
-rw-r--r--MediaBrowser.Controller/Providers/PersonLookupInfo.cs3
-rw-r--r--MediaBrowser.Controller/Providers/RefreshPriority.cs23
-rw-r--r--MediaBrowser.Controller/Providers/RemoteSearchQuery.cs10
-rw-r--r--MediaBrowser.Controller/Providers/SeasonInfo.cs6
-rw-r--r--MediaBrowser.Controller/Providers/SeriesInfo.cs2
-rw-r--r--MediaBrowser.Controller/Providers/SongInfo.cs15
-rw-r--r--MediaBrowser.Controller/Providers/TrailerInfo.cs2
-rw-r--r--MediaBrowser.Controller/Providers/VideoContentType.cs6
-rw-r--r--MediaBrowser.Controller/QuickConnect/IQuickConnect.cs48
-rw-r--r--MediaBrowser.Controller/Resolvers/IItemResolver.cs25
-rw-r--r--MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs8
-rw-r--r--MediaBrowser.Controller/Resolvers/ItemResolver.cs (renamed from MediaBrowser.Controller/Resolvers/BaseItemResolver.cs)22
-rw-r--r--MediaBrowser.Controller/Resolvers/ResolverPriority.cs24
-rw-r--r--MediaBrowser.Controller/Security/AuthenticationInfo.cs5
-rw-r--r--MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs49
-rw-r--r--MediaBrowser.Controller/Security/IAuthenticationManager.cs33
-rw-r--r--MediaBrowser.Controller/Security/IAuthenticationRepository.cs34
-rw-r--r--MediaBrowser.Controller/Security/IEncryptionManager.cs19
-rw-r--r--MediaBrowser.Controller/Session/AuthenticationRequest.cs13
-rw-r--r--MediaBrowser.Controller/Session/ISessionController.cs14
-rw-r--r--MediaBrowser.Controller/Session/ISessionManager.cs124
-rw-r--r--MediaBrowser.Controller/Session/SessionEventArgs.cs4
-rw-r--r--MediaBrowser.Controller/Session/SessionInfo.cs119
-rw-r--r--MediaBrowser.Controller/Sorting/IBaseItemComparer.cs4
-rw-r--r--MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs7
-rw-r--r--MediaBrowser.Controller/Sorting/SortExtensions.cs127
-rw-r--r--MediaBrowser.Controller/Sorting/SortHelper.cs25
-rw-r--r--MediaBrowser.Controller/Subtitles/ISubtitleManager.cs43
-rw-r--r--MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs4
-rw-r--r--MediaBrowser.Controller/Subtitles/SubtitleDownloadEventArgs.cs27
-rw-r--r--MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs28
-rw-r--r--MediaBrowser.Controller/Subtitles/SubtitleResponse.cs7
-rw-r--r--MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs34
-rw-r--r--MediaBrowser.Controller/Sync/IHasDynamicAccess.cs18
-rw-r--r--MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs9
-rw-r--r--MediaBrowser.Controller/Sync/IServerSyncProvider.cs28
-rw-r--r--MediaBrowser.Controller/Sync/ISyncProvider.cs27
-rw-r--r--MediaBrowser.Controller/Sync/SyncedFileInfo.cs35
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupMember.cs60
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs233
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs128
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs167
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs170
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs682
-rw-r--r--MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs29
-rw-r--r--MediaBrowser.Controller/SyncPlay/IGroupState.cs219
-rw-r--r--MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs230
-rw-r--r--MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs64
-rw-r--r--MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs16
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs31
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs63
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs38
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs47
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs39
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs23
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs38
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs56
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs39
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs48
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs63
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs56
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs38
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs39
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs38
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs38
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs21
-rw-r--r--MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs21
-rw-r--r--MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs557
-rw-r--r--MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs29
-rw-r--r--MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs13
-rw-r--r--MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs13
-rw-r--r--MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs28
-rw-r--r--MediaBrowser.Controller/TV/ITVSeriesManager.cs12
-rw-r--r--MediaBrowser.LocalMetadata/BaseXmlProvider.cs65
-rw-r--r--MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs (renamed from MediaBrowser.LocalMetadata/Images/CollectionFolderImageProvider.cs)23
-rw-r--r--MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs51
-rw-r--r--MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs43
-rw-r--r--MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs184
-rw-r--r--MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj21
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs1129
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs62
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs72
-rw-r--r--MediaBrowser.LocalMetadata/Properties/AssemblyInfo.cs4
-rw-r--r--MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs19
-rw-r--r--MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs27
-rw-r--r--MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs162
-rw-r--r--MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs23
-rw-r--r--MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs39
-rw-r--r--MediaBrowser.LocalMetadata/XmlProviderUtils.cs13
-rw-r--r--MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs280
-rw-r--r--MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs83
-rw-r--r--MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs28
-rw-r--r--MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs41
-rw-r--r--MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs44
-rw-r--r--MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationStore.cs38
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs480
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs39
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs1047
-rw-r--r--MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj24
-rw-r--r--MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets6
-rw-r--r--MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs70
-rw-r--r--MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs327
-rw-r--r--MediaBrowser.MediaEncoding/Probing/MediaChapter.cs35
-rw-r--r--MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs83
-rw-r--r--MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs314
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs1089
-rw-r--r--MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs6
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/AssParser.cs121
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/ConfigurationExtension.cs29
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs40
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs346
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs7
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs93
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs21
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs395
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs61
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs502
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs17
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs19
-rw-r--r--MediaBrowser.MediaEncoding/packages.config3
-rw-r--r--MediaBrowser.Model/Activity/ActivityLogEntry.cs25
-rw-r--r--MediaBrowser.Model/Activity/IActivityManager.cs18
-rw-r--r--MediaBrowser.Model/Activity/IActivityRepository.cs12
-rw-r--r--MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs41
-rw-r--r--MediaBrowser.Model/Branding/BrandingOptions.cs7
-rw-r--r--MediaBrowser.Model/Channels/ChannelFeatures.cs25
-rw-r--r--MediaBrowser.Model/Channels/ChannelFolderType.cs2
-rw-r--r--MediaBrowser.Model/Channels/ChannelInfo.cs29
-rw-r--r--MediaBrowser.Model/Channels/ChannelItemSortField.cs2
-rw-r--r--MediaBrowser.Model/Channels/ChannelMediaContentType.cs2
-rw-r--r--MediaBrowser.Model/Channels/ChannelMediaType.cs2
-rw-r--r--MediaBrowser.Model/Channels/ChannelQuery.cs17
-rw-r--r--MediaBrowser.Model/Collections/CollectionCreationResult.cs2
-rw-r--r--MediaBrowser.Model/Configuration/AccessSchedule.cs21
-rw-r--r--MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs37
-rw-r--r--MediaBrowser.Model/Configuration/DynamicDayOfWeek.cs16
-rw-r--r--MediaBrowser.Model/Configuration/EncodingOptions.cs110
-rw-r--r--MediaBrowser.Model/Configuration/FanartOptions.cs11
-rw-r--r--MediaBrowser.Model/Configuration/ImageOption.cs13
-rw-r--r--MediaBrowser.Model/Configuration/ImageSavingConvention.cs2
-rw-r--r--MediaBrowser.Model/Configuration/LibraryOptions.cs427
-rw-r--r--MediaBrowser.Model/Configuration/MediaPathInfo.cs22
-rw-r--r--MediaBrowser.Model/Configuration/MetadataConfiguration.cs6
-rw-r--r--MediaBrowser.Model/Configuration/MetadataOptions.cs26
-rw-r--r--MediaBrowser.Model/Configuration/MetadataPlugin.cs3
-rw-r--r--MediaBrowser.Model/Configuration/MetadataPluginSummary.cs15
-rw-r--r--MediaBrowser.Model/Configuration/MetadataPluginType.cs4
-rw-r--r--MediaBrowser.Model/Configuration/PathSubstitution.cs18
-rw-r--r--MediaBrowser.Model/Configuration/ServerConfiguration.cs478
-rw-r--r--MediaBrowser.Model/Configuration/SubtitlePlaybackMode.cs11
-rw-r--r--MediaBrowser.Model/Configuration/TypeOptions.cs365
-rw-r--r--MediaBrowser.Model/Configuration/UnratedItem.cs15
-rw-r--r--MediaBrowser.Model/Configuration/UserConfiguration.cs49
-rw-r--r--MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs21
-rw-r--r--MediaBrowser.Model/Cryptography/ICryptoProvider.cs20
-rw-r--r--MediaBrowser.Model/Devices/ContentUploadHistory.cs13
-rw-r--r--MediaBrowser.Model/Devices/DeviceInfo.cs24
-rw-r--r--MediaBrowser.Model/Devices/DeviceQuery.cs18
-rw-r--r--MediaBrowser.Model/Devices/DevicesOptions.cs21
-rw-r--r--MediaBrowser.Model/Devices/LocalFileInfo.cs10
-rw-r--r--MediaBrowser.Model/Diagnostics/IProcess.cs21
-rw-r--r--MediaBrowser.Model/Diagnostics/IProcessFactory.cs22
-rw-r--r--MediaBrowser.Model/Dlna/AudioOptions.cs22
-rw-r--r--MediaBrowser.Model/Dlna/CodecProfile.cs20
-rw-r--r--MediaBrowser.Model/Dlna/CodecType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/ConditionProcessor.cs48
-rw-r--r--MediaBrowser.Model/Dlna/ContainerProfile.cs67
-rw-r--r--MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs160
-rw-r--r--MediaBrowser.Model/Dlna/DeviceIdentification.cs40
-rw-r--r--MediaBrowser.Model/Dlna/DeviceProfile.cs324
-rw-r--r--MediaBrowser.Model/Dlna/DeviceProfileInfo.cs3
-rw-r--r--MediaBrowser.Model/Dlna/DeviceProfileType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/DirectPlayProfile.cs12
-rw-r--r--MediaBrowser.Model/Dlna/DlnaFlags.cs2
-rw-r--r--MediaBrowser.Model/Dlna/DlnaMaps.cs12
-rw-r--r--MediaBrowser.Model/Dlna/DlnaProfileType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/EncodingContext.cs2
-rw-r--r--MediaBrowser.Model/Dlna/HeaderMatchType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/HttpHeaderInfo.cs3
-rw-r--r--MediaBrowser.Model/Dlna/IDeviceDiscovery.cs5
-rw-r--r--MediaBrowser.Model/Dlna/ITranscoderSupport.cs6
-rw-r--r--MediaBrowser.Model/Dlna/MediaFormatProfile.cs2
-rw-r--r--MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs335
-rw-r--r--MediaBrowser.Model/Dlna/PlaybackErrorCode.cs2
-rw-r--r--MediaBrowser.Model/Dlna/ProfileCondition.cs28
-rw-r--r--MediaBrowser.Model/Dlna/ProfileConditionType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/ProfileConditionValue.cs2
-rw-r--r--MediaBrowser.Model/Dlna/ResolutionConfiguration.cs9
-rw-r--r--MediaBrowser.Model/Dlna/ResolutionNormalizer.cs25
-rw-r--r--MediaBrowser.Model/Dlna/ResolutionOptions.cs3
-rw-r--r--MediaBrowser.Model/Dlna/ResponseProfile.cs14
-rw-r--r--MediaBrowser.Model/Dlna/SearchCriteria.cs70
-rw-r--r--MediaBrowser.Model/Dlna/SearchType.cs2
-rw-r--r--MediaBrowser.Model/Dlna/SortCriteria.cs9
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs270
-rw-r--r--MediaBrowser.Model/Dlna/StreamInfo.cs1049
-rw-r--r--MediaBrowser.Model/Dlna/SubtitleDeliveryMethod.cs16
-rw-r--r--MediaBrowser.Model/Dlna/SubtitleProfile.cs8
-rw-r--r--MediaBrowser.Model/Dlna/SubtitleStreamInfo.cs11
-rw-r--r--MediaBrowser.Model/Dlna/TranscodeSeekInfo.cs2
-rw-r--r--MediaBrowser.Model/Dlna/TranscodingProfile.cs22
-rw-r--r--MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs12
-rw-r--r--MediaBrowser.Model/Dlna/VideoOptions.cs3
-rw-r--r--MediaBrowser.Model/Dlna/XmlAttribute.cs12
-rw-r--r--MediaBrowser.Model/Drawing/DrawingUtils.cs67
-rw-r--r--MediaBrowser.Model/Drawing/ImageDimensions.cs35
-rw-r--r--MediaBrowser.Model/Drawing/ImageFormat.cs16
-rw-r--r--MediaBrowser.Model/Drawing/ImageOrientation.cs2
-rw-r--r--MediaBrowser.Model/Dto/BaseItemDto.cs72
-rw-r--r--MediaBrowser.Model/Dto/BaseItemPerson.cs15
-rw-r--r--MediaBrowser.Model/Dto/IHasServerId.cs3
-rw-r--r--MediaBrowser.Model/Dto/IItemDto.cs2
-rw-r--r--MediaBrowser.Model/Dto/ImageByNameInfo.cs6
-rw-r--r--MediaBrowser.Model/Dto/ImageInfo.cs13
-rw-r--r--MediaBrowser.Model/Dto/ImageOptions.cs21
-rw-r--r--MediaBrowser.Model/Dto/ItemCounts.cs25
-rw-r--r--MediaBrowser.Model/Dto/ItemIndex.cs20
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceInfo.cs99
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceType.cs2
-rw-r--r--MediaBrowser.Model/Dto/MetadataEditorInfo.cs23
-rw-r--r--MediaBrowser.Model/Dto/NameGuidPair.cs14
-rw-r--r--MediaBrowser.Model/Dto/NameIdPair.cs10
-rw-r--r--MediaBrowser.Model/Dto/NameValuePair.cs5
-rw-r--r--MediaBrowser.Model/Dto/RatingType.cs2
-rw-r--r--MediaBrowser.Model/Dto/RecommendationDto.cs6
-rw-r--r--MediaBrowser.Model/Dto/RecommendationType.cs2
-rw-r--r--MediaBrowser.Model/Dto/UserDto.cs25
-rw-r--r--MediaBrowser.Model/Dto/UserItemDataDto.cs3
-rw-r--r--MediaBrowser.Model/Entities/ChapterInfo.cs6
-rw-r--r--MediaBrowser.Model/Entities/CollectionType.cs34
-rw-r--r--MediaBrowser.Model/Entities/CollectionTypeOptions.cs16
-rw-r--r--MediaBrowser.Model/Entities/DisplayPreferencesDto.cs (renamed from MediaBrowser.Model/Entities/DisplayPreferences.cs)30
-rw-r--r--MediaBrowser.Model/Entities/EmptyRequestResult.cs6
-rw-r--r--MediaBrowser.Model/Entities/ExtraType.cs3
-rw-r--r--MediaBrowser.Model/Entities/IHasProviderIds.cs2
-rw-r--r--MediaBrowser.Model/Entities/ImageType.cs44
-rw-r--r--MediaBrowser.Model/Entities/IsoType.cs7
-rw-r--r--MediaBrowser.Model/Entities/LibraryUpdateInfo.cs31
-rw-r--r--MediaBrowser.Model/Entities/LocationType.cs13
-rw-r--r--MediaBrowser.Model/Entities/MediaAttachment.cs51
-rw-r--r--MediaBrowser.Model/Entities/MediaStream.cs477
-rw-r--r--MediaBrowser.Model/Entities/MediaStreamType.cs13
-rw-r--r--MediaBrowser.Model/Entities/MediaType.cs15
-rw-r--r--MediaBrowser.Model/Entities/MediaUrl.cs4
-rw-r--r--MediaBrowser.Model/Entities/MetadataFields.cs30
-rw-r--r--MediaBrowser.Model/Entities/MetadataProvider.cs (renamed from MediaBrowser.Model/Entities/MetadataProviders.cs)20
-rw-r--r--MediaBrowser.Model/Entities/PackageReviewInfo.cs38
-rw-r--r--MediaBrowser.Model/Entities/ParentalRating.cs26
-rw-r--r--MediaBrowser.Model/Entities/PersonType.cs47
-rw-r--r--MediaBrowser.Model/Entities/ProviderIdsExtensions.cs99
-rw-r--r--MediaBrowser.Model/Entities/ScrollDirection.cs17
-rw-r--r--MediaBrowser.Model/Entities/SeriesStatus.cs7
-rw-r--r--MediaBrowser.Model/Entities/SortOrder.cs17
-rw-r--r--MediaBrowser.Model/Entities/SpecialFolder.cs36
-rw-r--r--MediaBrowser.Model/Entities/TrailerType.cs2
-rw-r--r--MediaBrowser.Model/Entities/UserDataSaveReason.cs19
-rw-r--r--MediaBrowser.Model/Entities/Video3DFormat.cs2
-rw-r--r--MediaBrowser.Model/Entities/VideoType.cs13
-rw-r--r--MediaBrowser.Model/Entities/VirtualFolderInfo.cs27
-rw-r--r--MediaBrowser.Model/Extensions/EnumerableExtensions.cs54
-rw-r--r--MediaBrowser.Model/Extensions/ListHelper.cs24
-rw-r--r--MediaBrowser.Model/Extensions/StringHelper.cs64
-rw-r--r--MediaBrowser.Model/Globalization/CountryInfo.cs3
-rw-r--r--MediaBrowser.Model/Globalization/CultureDto.cs20
-rw-r--r--MediaBrowser.Model/Globalization/ILocalizationManager.cs36
-rw-r--r--MediaBrowser.Model/Globalization/LocalizationOption.cs4
-rw-r--r--MediaBrowser.Model/IO/AsyncFile.cs45
-rw-r--r--MediaBrowser.Model/IO/FileSystemEntryInfo.cs27
-rw-r--r--MediaBrowser.Model/IO/FileSystemEntryType.cs13
-rw-r--r--MediaBrowser.Model/IO/FileSystemMetadata.cs16
-rw-r--r--MediaBrowser.Model/IO/IFileSystem.cs172
-rw-r--r--MediaBrowser.Model/IO/IIsoManager.cs34
-rw-r--r--MediaBrowser.Model/IO/IIsoMount.cs22
-rw-r--r--MediaBrowser.Model/IO/IIsoMounter.cs33
-rw-r--r--MediaBrowser.Model/IO/IODefaults.cs25
-rw-r--r--MediaBrowser.Model/IO/IShortcutHandler.cs7
-rw-r--r--MediaBrowser.Model/IO/IStreamHelper.cs5
-rw-r--r--MediaBrowser.Model/IO/IZipClient.cs5
-rw-r--r--MediaBrowser.Model/IO/StreamDefaults.cs18
-rw-r--r--MediaBrowser.Model/Library/PlayAccess.cs2
-rw-r--r--MediaBrowser.Model/Library/UserViewQuery.cs14
-rw-r--r--MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs20
-rw-r--r--MediaBrowser.Model/LiveTv/ChannelType.cs6
-rw-r--r--MediaBrowser.Model/LiveTv/DayPattern.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/GuideInfo.cs3
-rw-r--r--MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs58
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs34
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvInfo.cs14
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvOptions.cs82
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs16
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvServiceStatus.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvTunerStatus.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/ProgramAudio.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/RecordingQuery.cs28
-rw-r--r--MediaBrowser.Model/LiveTv/RecordingStatus.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs21
-rw-r--r--MediaBrowser.Model/LiveTv/SeriesTimerQuery.cs8
-rw-r--r--MediaBrowser.Model/LiveTv/TimerInfoDto.cs4
-rw-r--r--MediaBrowser.Model/LiveTv/TimerQuery.cs3
-rw-r--r--MediaBrowser.Model/LiveTv/TunerHostInfo.cs35
-rw-r--r--MediaBrowser.Model/MediaBrowser.Model.csproj38
-rw-r--r--MediaBrowser.Model/MediaInfo/AudioCodec.cs8
-rw-r--r--MediaBrowser.Model/MediaInfo/BlurayDiscInfo.cs5
-rw-r--r--MediaBrowser.Model/MediaInfo/Container.cs8
-rw-r--r--MediaBrowser.Model/MediaInfo/IBlurayExaminer.cs2
-rw-r--r--MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs48
-rw-r--r--MediaBrowser.Model/MediaInfo/LiveStreamResponse.cs9
-rw-r--r--MediaBrowser.Model/MediaInfo/MediaInfo.cs42
-rw-r--r--MediaBrowser.Model/MediaInfo/MediaProtocol.cs2
-rw-r--r--MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs31
-rw-r--r--MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs22
-rw-r--r--MediaBrowser.Model/MediaInfo/SubtitleFormat.cs4
-rw-r--r--MediaBrowser.Model/MediaInfo/SubtitleTrackEvent.cs11
-rw-r--r--MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs11
-rw-r--r--MediaBrowser.Model/MediaInfo/TransportStreamTimestamp.cs2
-rw-r--r--MediaBrowser.Model/MediaInfo/VideoCodec.cs14
-rw-r--r--MediaBrowser.Model/Net/EndPointInfo.cs3
-rw-r--r--MediaBrowser.Model/Net/HttpException.cs43
-rw-r--r--MediaBrowser.Model/Net/HttpResponse.cs64
-rw-r--r--MediaBrowser.Model/Net/IAcceptSocket.cs15
-rw-r--r--MediaBrowser.Model/Net/ISocket.cs16
-rw-r--r--MediaBrowser.Model/Net/ISocketFactory.cs34
-rw-r--r--MediaBrowser.Model/Net/IpAddressInfo.cs37
-rw-r--r--MediaBrowser.Model/Net/IpEndPointInfo.cs29
-rw-r--r--MediaBrowser.Model/Net/MimeTypes.cs427
-rw-r--r--MediaBrowser.Model/Net/NetworkShare.cs30
-rw-r--r--MediaBrowser.Model/Net/NetworkShareType.cs16
-rw-r--r--MediaBrowser.Model/Net/SocketReceiveResult.cs18
-rw-r--r--MediaBrowser.Model/Net/WebSocketMessage.cs18
-rw-r--r--MediaBrowser.Model/Notifications/NotificationLevel.cs2
-rw-r--r--MediaBrowser.Model/Notifications/NotificationOption.cs31
-rw-r--r--MediaBrowser.Model/Notifications/NotificationOptions.cs63
-rw-r--r--MediaBrowser.Model/Notifications/NotificationRequest.cs17
-rw-r--r--MediaBrowser.Model/Notifications/NotificationType.cs3
-rw-r--r--MediaBrowser.Model/Notifications/NotificationTypeInfo.cs3
-rw-r--r--MediaBrowser.Model/Notifications/SendToUserType.cs2
-rw-r--r--MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs11
-rw-r--r--MediaBrowser.Model/Playlists/PlaylistCreationResult.cs9
-rw-r--r--MediaBrowser.Model/Playlists/PlaylistItemQuery.cs37
-rw-r--r--MediaBrowser.Model/Plugins/BasePluginConfiguration.cs2
-rw-r--r--MediaBrowser.Model/Plugins/IHasWebPages.cs2
-rw-r--r--MediaBrowser.Model/Plugins/PluginInfo.cs46
-rw-r--r--MediaBrowser.Model/Plugins/PluginPageInfo.cs31
-rw-r--r--MediaBrowser.Model/Plugins/PluginStatus.cs47
-rw-r--r--MediaBrowser.Model/Properties/AssemblyInfo.cs6
-rw-r--r--MediaBrowser.Model/Providers/ExternalIdInfo.cs40
-rw-r--r--MediaBrowser.Model/Providers/ExternalIdMediaType.cs71
-rw-r--r--MediaBrowser.Model/Providers/ExternalUrl.cs3
-rw-r--r--MediaBrowser.Model/Providers/ImageProviderInfo.cs25
-rw-r--r--MediaBrowser.Model/Providers/RemoteImageInfo.cs6
-rw-r--r--MediaBrowser.Model/Providers/RemoteImageQuery.cs9
-rw-r--r--MediaBrowser.Model/Providers/RemoteImageResult.cs1
-rw-r--r--MediaBrowser.Model/Providers/RemoteSearchResult.cs22
-rw-r--r--MediaBrowser.Model/Providers/RemoteSubtitleInfo.cs13
-rw-r--r--MediaBrowser.Model/Providers/SubtitleOptions.cs25
-rw-r--r--MediaBrowser.Model/Providers/SubtitleProviderInfo.cs4
-rw-r--r--MediaBrowser.Model/Querying/AllThemeMediaResult.cs15
-rw-r--r--MediaBrowser.Model/Querying/EpisodeQuery.cs61
-rw-r--r--MediaBrowser.Model/Querying/ItemCountsQuery.cs20
-rw-r--r--MediaBrowser.Model/Querying/ItemFields.cs79
-rw-r--r--MediaBrowser.Model/Querying/ItemFilter.cs28
-rw-r--r--MediaBrowser.Model/Querying/ItemSortBy.cs58
-rw-r--r--MediaBrowser.Model/Querying/LatestItemsQuery.cs25
-rw-r--r--MediaBrowser.Model/Querying/MovieRecommendationQuery.cs38
-rw-r--r--MediaBrowser.Model/Querying/NextUpQuery.cs36
-rw-r--r--MediaBrowser.Model/Querying/QueryFilters.cs25
-rw-r--r--MediaBrowser.Model/Querying/QueryFiltersLegacy.cs26
-rw-r--r--MediaBrowser.Model/Querying/QueryResult.cs30
-rw-r--r--MediaBrowser.Model/Querying/SessionQuery.cs13
-rw-r--r--MediaBrowser.Model/Querying/SimilarItemsQuery.cs29
-rw-r--r--MediaBrowser.Model/Querying/ThemeMediaResult.cs2
-rw-r--r--MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs57
-rw-r--r--MediaBrowser.Model/Querying/UserQuery.cs8
-rw-r--r--MediaBrowser.Model/QuickConnect/QuickConnectResult.cs78
-rw-r--r--MediaBrowser.Model/Reflection/IAssemblyInfo.cs14
-rw-r--r--MediaBrowser.Model/Search/SearchHint.cs10
-rw-r--r--MediaBrowser.Model/Search/SearchHintResult.cs3
-rw-r--r--MediaBrowser.Model/Search/SearchQuery.cs44
-rw-r--r--MediaBrowser.Model/Serialization/IJsonSerializer.cs99
-rw-r--r--MediaBrowser.Model/Serialization/IXmlSerializer.cs3
-rw-r--r--MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs12
-rw-r--r--MediaBrowser.Model/Services/ApiMemberAttribute.cs61
-rw-r--r--MediaBrowser.Model/Services/HttpUtility.cs691
-rw-r--r--MediaBrowser.Model/Services/IAsyncStreamWriter.cs11
-rw-r--r--MediaBrowser.Model/Services/IHasHeaders.cs9
-rw-r--r--MediaBrowser.Model/Services/IHasRequestFilter.cs20
-rw-r--r--MediaBrowser.Model/Services/IHttpRequest.cs40
-rw-r--r--MediaBrowser.Model/Services/IHttpResponse.cs20
-rw-r--r--MediaBrowser.Model/Services/IHttpResult.cs32
-rw-r--r--MediaBrowser.Model/Services/IRequest.cs159
-rw-r--r--MediaBrowser.Model/Services/IRequiresRequestStream.cs12
-rw-r--r--MediaBrowser.Model/Services/IService.cs11
-rw-r--r--MediaBrowser.Model/Services/IStreamWriter.cs9
-rw-r--r--MediaBrowser.Model/Services/QueryParamCollection.cs196
-rw-r--r--MediaBrowser.Model/Services/RouteAttribute.cs148
-rw-r--r--MediaBrowser.Model/Session/BrowseRequest.cs6
-rw-r--r--MediaBrowser.Model/Session/ClientCapabilities.cs26
-rw-r--r--MediaBrowser.Model/Session/GeneralCommand.cs14
-rw-r--r--MediaBrowser.Model/Session/GeneralCommandType.cs9
-rw-r--r--MediaBrowser.Model/Session/HardwareEncodingType.cs48
-rw-r--r--MediaBrowser.Model/Session/MessageCommand.cs6
-rw-r--r--MediaBrowser.Model/Session/PlayCommand.cs16
-rw-r--r--MediaBrowser.Model/Session/PlayMethod.cs2
-rw-r--r--MediaBrowser.Model/Session/PlayRequest.cs14
-rw-r--r--MediaBrowser.Model/Session/PlaybackProgressInfo.cs18
-rw-r--r--MediaBrowser.Model/Session/PlaybackStopInfo.cs11
-rw-r--r--MediaBrowser.Model/Session/PlayerStateInfo.cs3
-rw-r--r--MediaBrowser.Model/Session/PlaystateCommand.cs29
-rw-r--r--MediaBrowser.Model/Session/PlaystateRequest.cs4
-rw-r--r--MediaBrowser.Model/Session/QueueItem.cs14
-rw-r--r--MediaBrowser.Model/Session/RepeatMode.cs11
-rw-r--r--MediaBrowser.Model/Session/SessionMessageType.cs50
-rw-r--r--MediaBrowser.Model/Session/SessionUserInfo.cs2
-rw-r--r--MediaBrowser.Model/Session/TranscodeReason.cs31
-rw-r--r--MediaBrowser.Model/Session/TranscodingInfo.cs52
-rw-r--r--MediaBrowser.Model/Session/UserDataChangeInfo.cs3
-rw-r--r--MediaBrowser.Model/Subtitles/FontFile.cs34
-rw-r--r--MediaBrowser.Model/Sync/SyncCategory.cs18
-rw-r--r--MediaBrowser.Model/Sync/SyncJob.cs112
-rw-r--r--MediaBrowser.Model/Sync/SyncJobStatus.cs13
-rw-r--r--MediaBrowser.Model/Sync/SyncTarget.cs16
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupInfoDto.cs58
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupQueueMode.cs18
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs23
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs18
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupStateType.cs28
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs31
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupUpdate.cs42
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupUpdateType.cs63
-rw-r--r--MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs82
-rw-r--r--MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs58
-rw-r--r--MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs93
-rw-r--r--MediaBrowser.Model/SyncPlay/QueueItem.cs31
-rw-r--r--MediaBrowser.Model/SyncPlay/RequestType.cs33
-rw-r--r--MediaBrowser.Model/SyncPlay/SendCommand.cs65
-rw-r--r--MediaBrowser.Model/SyncPlay/SendCommandType.cs28
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs28
-rw-r--r--MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs33
-rw-r--r--MediaBrowser.Model/System/IEnvironmentInfo.cs21
-rw-r--r--MediaBrowser.Model/System/LogFile.cs3
-rw-r--r--MediaBrowser.Model/System/OperatingSystemId.cs12
-rw-r--r--MediaBrowser.Model/System/PublicSystemInfo.cs23
-rw-r--r--MediaBrowser.Model/System/SystemInfo.cs78
-rw-r--r--MediaBrowser.Model/System/WakeOnLanInfo.cs38
-rw-r--r--MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs3
-rw-r--r--MediaBrowser.Model/Tasks/IScheduledTask.cs13
-rw-r--r--MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs10
-rw-r--r--MediaBrowser.Model/Tasks/ITaskManager.cs26
-rw-r--r--MediaBrowser.Model/Tasks/ITaskTrigger.cs18
-rw-r--r--MediaBrowser.Model/Tasks/ScheduledTaskHelpers.cs6
-rw-r--r--MediaBrowser.Model/Tasks/TaskCompletionEventArgs.cs12
-rw-r--r--MediaBrowser.Model/Tasks/TaskCompletionStatus.cs10
-rw-r--r--MediaBrowser.Model/Tasks/TaskInfo.cs21
-rw-r--r--MediaBrowser.Model/Tasks/TaskOptions.cs2
-rw-r--r--MediaBrowser.Model/Tasks/TaskResult.cs3
-rw-r--r--MediaBrowser.Model/Tasks/TaskState.cs10
-rw-r--r--MediaBrowser.Model/Tasks/TaskTriggerInfo.cs17
-rw-r--r--MediaBrowser.Model/Updates/CheckForUpdateResult.cs29
-rw-r--r--MediaBrowser.Model/Updates/InstallationInfo.cs40
-rw-r--r--MediaBrowser.Model/Updates/PackageInfo.cs164
-rw-r--r--MediaBrowser.Model/Updates/PackageTargetSystem.cs21
-rw-r--r--MediaBrowser.Model/Updates/PackageVersionClass.cs21
-rw-r--r--MediaBrowser.Model/Updates/PackageVersionInfo.cs92
-rw-r--r--MediaBrowser.Model/Updates/RepositoryInfo.cs26
-rw-r--r--MediaBrowser.Model/Updates/VersionInfo.cs77
-rw-r--r--MediaBrowser.Model/Users/ForgotPasswordAction.cs2
-rw-r--r--MediaBrowser.Model/Users/ForgotPasswordResult.cs5
-rw-r--r--MediaBrowser.Model/Users/PinRedeemResult.cs7
-rw-r--r--MediaBrowser.Model/Users/UserAction.cs15
-rw-r--r--MediaBrowser.Model/Users/UserActionType.cs7
-rw-r--r--MediaBrowser.Model/Users/UserPolicy.cs135
-rw-r--r--MediaBrowser.Model/Xml/IXmlReaderSettingsFactory.cs9
-rw-r--r--MediaBrowser.Providers/Books/AudioBookMetadataService.cs26
-rw-r--r--MediaBrowser.Providers/Books/BookMetadataService.cs19
-rw-r--r--MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs49
-rw-r--r--MediaBrowser.Providers/BoxSets/MovieDbBoxSetImageProvider.cs158
-rw-r--r--MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs326
-rw-r--r--MediaBrowser.Providers/Channels/ChannelMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/Chapters/ChapterManager.cs22
-rw-r--r--MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs14
-rw-r--r--MediaBrowser.Providers/Folders/FolderMetadataService.cs20
-rw-r--r--MediaBrowser.Providers/Folders/UserViewMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/Genres/GenreMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs (renamed from MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs)15
-rw-r--r--MediaBrowser.Providers/Manager/ImageSaver.cs133
-rw-r--r--MediaBrowser.Providers/Manager/ItemImageProvider.cs292
-rw-r--r--MediaBrowser.Providers/Manager/MetadataService.cs279
-rw-r--r--MediaBrowser.Providers/Manager/ProviderManager.cs634
-rw-r--r--MediaBrowser.Providers/Manager/ProviderUtils.cs86
-rw-r--r--MediaBrowser.Providers/Manager/RefreshResult.cs15
-rw-r--r--MediaBrowser.Providers/MediaBrowser.Providers.csproj37
-rw-r--r--MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs39
-rw-r--r--MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs222
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs78
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs103
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs250
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs50
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs195
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs121
-rw-r--r--MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs119
-rw-r--r--MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs334
-rw-r--r--MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs315
-rw-r--r--MediaBrowser.Providers/Movies/ImdbExternalId.cs39
-rw-r--r--MediaBrowser.Providers/Movies/ImdbPersonExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbImageProvider.cs207
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbProvider.cs642
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbSearch.cs394
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbTrailerProvider.cs43
-rw-r--r--MediaBrowser.Providers/Movies/MovieExternalIds.cs124
-rw-r--r--MediaBrowser.Providers/Movies/MovieMetadataService.cs54
-rw-r--r--MediaBrowser.Providers/Movies/TmdbSettings.cs22
-rw-r--r--MediaBrowser.Providers/Movies/TrailerMetadataService.cs53
-rw-r--r--MediaBrowser.Providers/Music/AlbumInfoExtensions.cs (renamed from MediaBrowser.Providers/Music/Extensions.cs)34
-rw-r--r--MediaBrowser.Providers/Music/AlbumMetadataService.cs66
-rw-r--r--MediaBrowser.Providers/Music/ArtistMetadataService.cs33
-rw-r--r--MediaBrowser.Providers/Music/AudioDbExternalIds.cs63
-rw-r--r--MediaBrowser.Providers/Music/AudioMetadataService.cs21
-rw-r--r--MediaBrowser.Providers/Music/FanArtAlbumProvider.cs201
-rw-r--r--MediaBrowser.Providers/Music/FanArtArtistProvider.cs335
-rw-r--r--MediaBrowser.Providers/Music/ImvdbId.cs28
-rw-r--r--MediaBrowser.Providers/Music/MovieDbMusicVideoProvider.cs32
-rw-r--r--MediaBrowser.Providers/Music/MusicExternalIds.cs105
-rw-r--r--MediaBrowser.Providers/Music/MusicVideoMetadataService.cs26
-rw-r--r--MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/People/MovieDbPersonImageProvider.cs132
-rw-r--r--MediaBrowser.Providers/People/MovieDbPersonProvider.cs395
-rw-r--r--MediaBrowser.Providers/People/PersonMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/People/TvdbPersonImageProvider.cs118
-rw-r--r--MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/Photos/PhotoMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs22
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumImageProvider.cs (renamed from MediaBrowser.Providers/Music/AudioDbAlbumImageProvider.cs)54
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumProvider.cs (renamed from MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs)131
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistImageProvider.cs (renamed from MediaBrowser.Providers/Music/AudioDbArtistImageProvider.cs)53
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistProvider.cs (renamed from MediaBrowser.Providers/Music/AudioDbArtistProvider.cs)154
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherAlbumExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherArtistExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs11
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html53
-rw-r--r--MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs41
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs37
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html77
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumArtistExternalId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumExternalId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs (renamed from MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs)859
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistExternalId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistProvider.cs (renamed from MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs)187
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzOtherArtistExternalId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzReleaseGroupExternalId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzTrackId.cs28
-rw-r--r--MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs45
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/Configuration/PluginConfiguration.cs11
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/Configuration/config.html52
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableInt32Converter.cs44
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs41
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs (renamed from MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs)45
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs (renamed from MediaBrowser.Providers/Omdb/OmdbImageProvider.cs)42
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs (renamed from MediaBrowser.Providers/Omdb/OmdbItemProvider.cs)207
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs (renamed from MediaBrowser.Providers/Omdb/OmdbProvider.cs)368
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/Plugin.cs41
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetExternalId.cs32
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs113
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs132
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs15
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html52
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieExternalId.cs38
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs130
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs340
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonExternalId.cs31
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs87
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs139
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Plugin.cs60
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs109
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs216
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs99
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs121
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesExternalId.cs31
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs117
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs389
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs558
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs196
-rw-r--r--MediaBrowser.Providers/Properties/AssemblyInfo.cs6
-rw-r--r--MediaBrowser.Providers/Studios/StudioMetadataService.cs15
-rw-r--r--MediaBrowser.Providers/Studios/StudiosImageProvider.cs97
-rw-r--r--MediaBrowser.Providers/Subtitles/SubtitleManager.cs196
-rw-r--r--MediaBrowser.Providers/TV/DummySeasonProvider.cs209
-rw-r--r--MediaBrowser.Providers/TV/EpisodeMetadataService.cs36
-rw-r--r--MediaBrowser.Providers/TV/FanArt/FanArtSeasonProvider.cs205
-rw-r--r--MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs378
-rw-r--r--MediaBrowser.Providers/TV/MissingEpisodeProvider.cs391
-rw-r--r--MediaBrowser.Providers/TV/SeasonMetadataService.cs45
-rw-r--r--MediaBrowser.Providers/TV/SeriesMetadataService.cs168
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs129
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs216
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs245
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs308
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesImageProvider.cs185
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs683
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvDbClientManager.cs244
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeImageProvider.cs124
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs239
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbSeasonImageProvider.cs155
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs152
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs440
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbUtils.cs36
-rw-r--r--MediaBrowser.Providers/TV/TvExternalIds.cs63
-rw-r--r--MediaBrowser.Providers/TV/Zap2ItExternalId.cs27
-rw-r--r--MediaBrowser.Providers/Users/UserMetadataService.cs23
-rw-r--r--MediaBrowser.Providers/Videos/VideoMetadataService.cs20
-rw-r--r--MediaBrowser.Providers/Years/YearMetadataService.cs15
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/Resources/SampleTransformed.htm1277
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/Resources/StringCheck.xslt145
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/Resources/StringCheckSample.xml222
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/StringUsageReporter.cs259
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/TextIndexing/IndexBuilder.cs52
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordIndex.cs36
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrence.cs18
-rw-r--r--MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrences.cs13
-rw-r--r--MediaBrowser.Tests/M3uParserTest.cs92
-rw-r--r--MediaBrowser.Tests/MediaBrowser.Tests.csproj139
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/AssParserTests.cs86
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs114
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data.ass23
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data2.ass391
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/expected.vtt32
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/unit.srt44
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/VttWriterTest.cs105
-rw-r--r--MediaBrowser.Tests/Properties/AssemblyInfo.cs23
-rw-r--r--MediaBrowser.Tests/app.config11
-rw-r--r--MediaBrowser.WebDashboard/Api/ConfigurationPageInfo.cs58
-rw-r--r--MediaBrowser.WebDashboard/Api/DashboardService.cs448
-rw-r--r--MediaBrowser.WebDashboard/Api/PackageCreator.cs194
-rw-r--r--MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj23
-rw-r--r--MediaBrowser.WebDashboard/Properties/AssemblyInfo.cs21
-rw-r--r--MediaBrowser.WebDashboard/ServerEntryPoint.cs38
m---------MediaBrowser.WebDashboard/jellyfin-web0
-rw-r--r--MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationExtension.cs15
-rw-r--r--MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationFactory.cs24
-rw-r--r--MediaBrowser.XbmcMetadata/Configuration/NfoOptions.cs29
-rw-r--r--MediaBrowser.XbmcMetadata/EntryPoint.cs34
-rw-r--r--MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj15
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs794
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs164
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs129
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs33
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs56
-rw-r--r--MediaBrowser.XbmcMetadata/Properties/AssemblyInfo.cs6
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs44
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs44
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs32
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs35
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs45
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs40
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs37
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs45
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs46
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs37
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs68
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs66
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs556
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs99
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs93
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs60
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs80
-rw-r--r--MediaBrowser.sln192
-rw-r--r--MediaBrowser.sln.GhostDoc.xml35
-rw-r--r--Mono.Nat/AbstractNatDevice.cs55
-rw-r--r--Mono.Nat/Enums/ProtocolType.cs36
-rw-r--r--Mono.Nat/EventArgs/DeviceEventArgs.cs45
-rw-r--r--Mono.Nat/INatDevice.cs45
-rw-r--r--Mono.Nat/ISearcher.cs46
-rw-r--r--Mono.Nat/Mapping.cs121
-rw-r--r--Mono.Nat/Mono.Nat.csproj17
-rw-r--r--Mono.Nat/NatManager.cs86
-rw-r--r--Mono.Nat/NatProtocol.cs8
-rw-r--r--Mono.Nat/Pmp/PmpConstants.cs56
-rw-r--r--Mono.Nat/Pmp/PmpNatDevice.cs217
-rw-r--r--Mono.Nat/Pmp/PmpSearcher.cs235
-rw-r--r--Mono.Nat/Properties/AssemblyInfo.cs21
-rw-r--r--Mono.Nat/Upnp/Messages/GetServicesMessage.cs77
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs75
-rw-r--r--Mono.Nat/Upnp/Messages/UpnpMessage.cs99
-rw-r--r--Mono.Nat/Upnp/Searchers/UpnpSearcher.cs111
-rw-r--r--Mono.Nat/Upnp/UpnpNatDevice.cs269
-rw-r--r--OpenSubtitlesHandler/Console/OSHConsole.cs92
-rw-r--r--OpenSubtitlesHandler/Interfaces/IMethodResponse.cs71
-rw-r--r--OpenSubtitlesHandler/Interfaces/MethodResponseAttr.cs40
-rw-r--r--OpenSubtitlesHandler/Languages/DetectLanguageResult.cs31
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseAddComment.cs32
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseAddRequest.cs35
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseAutoUpdate.cs59
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash.cs37
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash2.cs37
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseCheckSubHash.cs38
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseDetectLanguage.cs37
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseError.cs36
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseGetAvailableTranslations.cs37
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseGetComments.cs39
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseGetSubLanguages.cs39
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseGetTranslation.cs36
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovie.cs36
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovieHash.cs38
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseLogIn.cs39
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseMovieDetails.cs73
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseMovieSearch.cs43
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseNoOperation.cs52
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongImdbMovie.cs33
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongMovieHash.cs33
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseSearchToMail.cs32
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseServerInfo.cs131
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleDownload.cs44
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleSearch.cs46
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitlesVote.cs43
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseTryUploadSubtitles.cs40
-rw-r--r--OpenSubtitlesHandler/MethodResponses/MethodResponseUploadSubtitles.cs38
-rw-r--r--OpenSubtitlesHandler/Methods Implemeted.txt39
-rw-r--r--OpenSubtitlesHandler/MovieHasher.cs48
-rw-r--r--OpenSubtitlesHandler/Movies/CheckMovieHash2Data.cs42
-rw-r--r--OpenSubtitlesHandler/Movies/CheckMovieHash2Result.cs37
-rw-r--r--OpenSubtitlesHandler/Movies/CheckMovieHashResult.cs41
-rw-r--r--OpenSubtitlesHandler/Movies/InsertMovieHashParameters.cs38
-rw-r--r--OpenSubtitlesHandler/Movies/MovieSearchResult.cs40
-rw-r--r--OpenSubtitlesHandler/Movies/SearchToMailMovieParameter.cs30
-rw-r--r--OpenSubtitlesHandler/OpenSubtitles.cs2744
-rw-r--r--OpenSubtitlesHandler/OpenSubtitlesHandler.csproj13
-rw-r--r--OpenSubtitlesHandler/OtherTypes/GetAvailableTranslationsResult.cs39
-rw-r--r--OpenSubtitlesHandler/OtherTypes/GetCommentsResult.cs36
-rw-r--r--OpenSubtitlesHandler/Properties/AssemblyInfo.cs24
-rw-r--r--OpenSubtitlesHandler/Readme.txt20
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/CheckSubHashResult.cs30
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/SubtitleDownloadResult.cs43
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/SubtitleLanguage.cs39
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchParameters.cs82
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchResult.cs136
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/TryUploadSubtitlesParameters.cs47
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleInfoParameter.cs46
-rw-r--r--OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleParameters.cs52
-rw-r--r--OpenSubtitlesHandler/Utilities.cs174
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Docs/XML-RPC.txt225
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Enums/XmlRpcValueType.cs25
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Types/XmlRpcMethodCall.cs63
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Values/IXmlRpcValue.cs36
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Values/XmlRpcStructMember.cs43
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueArray.cs121
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueBasic.cs99
-rw-r--r--OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueStruct.cs43
-rw-r--r--OpenSubtitlesHandler/XML-RPC/XmlRpcGenerator.cs350
-rw-r--r--README.md185
-rw-r--r--RSSDP/DeviceAvailableEventArgs.cs58
-rw-r--r--RSSDP/DeviceEventArgs.cs21
-rw-r--r--RSSDP/DeviceUnavailableEventArgs.cs22
-rw-r--r--RSSDP/DiscoveredSsdpDevice.cs24
-rw-r--r--RSSDP/DisposableManagedObjectBase.cs32
-rw-r--r--RSSDP/HttpParserBase.cs96
-rw-r--r--RSSDP/HttpRequestParser.cs46
-rw-r--r--RSSDP/HttpResponseParser.cs42
-rw-r--r--RSSDP/IEnumerableExtensions.cs12
-rw-r--r--RSSDP/ISsdpCommunicationsServer.cs24
-rw-r--r--RSSDP/ISsdpDeviceLocator.cs22
-rw-r--r--RSSDP/ISsdpDevicePublisher.cs1
-rw-r--r--RSSDP/Properties/AssemblyInfo.cs4
-rw-r--r--RSSDP/RSSDP.csproj12
-rw-r--r--RSSDP/RequestReceivedEventArgs.cs23
-rw-r--r--RSSDP/ResponseReceivedEventArgs.cs24
-rw-r--r--RSSDP/SsdpCommunicationsServer.cs162
-rw-r--r--RSSDP/SsdpConstants.cs6
-rw-r--r--RSSDP/SsdpDevice.cs82
-rw-r--r--RSSDP/SsdpDeviceLocator.cs199
-rw-r--r--RSSDP/SsdpDevicePublisher.cs234
-rw-r--r--RSSDP/SsdpEmbeddedDevice.cs17
-rw-r--r--RSSDP/SsdpRootDevice.cs30
-rw-r--r--SharedVersion.cs4
-rw-r--r--SocketHttpListener/ByteOrder.cs17
-rw-r--r--SocketHttpListener/CloseEventArgs.cs79
-rw-r--r--SocketHttpListener/CloseStatusCode.cs94
-rw-r--r--SocketHttpListener/CompressionMethod.cs23
-rw-r--r--SocketHttpListener/ErrorEventArgs.cs42
-rw-r--r--SocketHttpListener/Ext.cs947
-rw-r--r--SocketHttpListener/Fin.cs8
-rw-r--r--SocketHttpListener/HttpBase.cs70
-rw-r--r--SocketHttpListener/HttpResponse.cs123
-rw-r--r--SocketHttpListener/Mask.cs8
-rw-r--r--SocketHttpListener/MessageEventArgs.cs84
-rw-r--r--SocketHttpListener/Net/AuthenticationSchemeSelector.cs6
-rw-r--r--SocketHttpListener/Net/AuthenticationTypes.cs9
-rw-r--r--SocketHttpListener/Net/BoundaryType.cs11
-rw-r--r--SocketHttpListener/Net/ChunkStream.cs385
-rw-r--r--SocketHttpListener/Net/ChunkedInputStream.cs178
-rw-r--r--SocketHttpListener/Net/CookieHelper.cs141
-rw-r--r--SocketHttpListener/Net/EntitySendFormat.cs8
-rw-r--r--SocketHttpListener/Net/HttpConnection.cs528
-rw-r--r--SocketHttpListener/Net/HttpEndPointListener.cs526
-rw-r--r--SocketHttpListener/Net/HttpEndPointManager.cs192
-rw-r--r--SocketHttpListener/Net/HttpKnownHeaderNames.cs91
-rw-r--r--SocketHttpListener/Net/HttpListener.cs284
-rw-r--r--SocketHttpListener/Net/HttpListenerBasicIdentity.cs49
-rw-r--r--SocketHttpListener/Net/HttpListenerContext.Managed.cs99
-rw-r--r--SocketHttpListener/Net/HttpListenerContext.cs74
-rw-r--r--SocketHttpListener/Net/HttpListenerPrefixCollection.cs117
-rw-r--r--SocketHttpListener/Net/HttpListenerRequest.Managed.cs325
-rw-r--r--SocketHttpListener/Net/HttpListenerRequest.cs537
-rw-r--r--SocketHttpListener/Net/HttpListenerRequestUriBuilder.cs443
-rw-r--r--SocketHttpListener/Net/HttpListenerResponse.Managed.cs333
-rw-r--r--SocketHttpListener/Net/HttpListenerResponse.cs294
-rw-r--r--SocketHttpListener/Net/HttpRequestStream.Managed.cs210
-rw-r--r--SocketHttpListener/Net/HttpRequestStream.cs129
-rw-r--r--SocketHttpListener/Net/HttpResponseStream.Managed.cs329
-rw-r--r--SocketHttpListener/Net/HttpResponseStream.cs124
-rw-r--r--SocketHttpListener/Net/HttpStatusCode.cs321
-rw-r--r--SocketHttpListener/Net/HttpStatusDescription.cs69
-rw-r--r--SocketHttpListener/Net/HttpStreamAsyncResult.cs79
-rw-r--r--SocketHttpListener/Net/HttpVersion.cs16
-rw-r--r--SocketHttpListener/Net/ListenerPrefix.cs89
-rw-r--r--SocketHttpListener/Net/UriScheme.cs20
-rw-r--r--SocketHttpListener/Net/WebHeaderCollection.cs360
-rw-r--r--SocketHttpListener/Net/WebHeaderEncoding.cs84
-rw-r--r--SocketHttpListener/Net/WebSockets/HttpListenerWebSocketContext.cs92
-rw-r--r--SocketHttpListener/Net/WebSockets/HttpWebSocket.Managed.cs81
-rw-r--r--SocketHttpListener/Net/WebSockets/HttpWebSocket.cs159
-rw-r--r--SocketHttpListener/Net/WebSockets/WebSocketCloseStatus.cs27
-rw-r--r--SocketHttpListener/Net/WebSockets/WebSocketContext.cs24
-rw-r--r--SocketHttpListener/Net/WebSockets/WebSocketValidate.cs141
-rw-r--r--SocketHttpListener/Opcode.cs43
-rw-r--r--SocketHttpListener/PayloadData.cs130
-rw-r--r--SocketHttpListener/Properties/AssemblyInfo.cs21
-rw-r--r--SocketHttpListener/Rsv.cs8
-rw-r--r--SocketHttpListener/SocketHttpListener.csproj18
-rw-r--r--SocketHttpListener/SocketStream.cs74
-rw-r--r--SocketHttpListener/WebSocket.cs778
-rw-r--r--SocketHttpListener/WebSocketException.cs61
-rw-r--r--SocketHttpListener/WebSocketFrame.cs432
l---------[-rwxr-xr-x]build230
-rwxr-xr-xbuild.sh114
-rw-r--r--build.yaml17
-rwxr-xr-xbump_version201
-rwxr-xr-xdebian/bin/restart.sh56
-rw-r--r--debian/changelog83
-rw-r--r--debian/compat (renamed from deployment/debian-package-x64/pkg-src/compat)0
-rw-r--r--debian/conf/jellyfin51
-rw-r--r--debian/conf/jellyfin-sudoers (renamed from deployment/debian-package-x64/pkg-src/conf/jellyfin-sudoers)6
-rw-r--r--debian/conf/jellyfin.service.conf (renamed from deployment/debian-package-x64/pkg-src/conf/jellyfin.service.conf)0
-rw-r--r--debian/conf/logging.json (renamed from deployment/debian-package-x64/pkg-src/conf/logging.json)0
-rw-r--r--debian/control28
-rw-r--r--debian/copyright (renamed from deployment/debian-package-x64/pkg-src/copyright)0
-rw-r--r--debian/gbp.conf (renamed from deployment/debian-package-x64/pkg-src/gbp.conf)0
-rw-r--r--debian/install (renamed from deployment/debian-package-x64/pkg-src/install)0
-rw-r--r--debian/jellyfin.init61
-rw-r--r--debian/jellyfin.service14
-rw-r--r--debian/jellyfin.upstart (renamed from deployment/debian-package-x64/pkg-src/jellyfin.upstart)0
-rw-r--r--debian/metapackage/jellyfin13
-rw-r--r--debian/po/POTFILES.in (renamed from deployment/debian-package-x64/pkg-src/po/POTFILES.in)0
-rw-r--r--debian/po/templates.pot (renamed from deployment/debian-package-x64/pkg-src/po/templates.pot)0
-rw-r--r--debian/postinst (renamed from deployment/debian-package-x64/pkg-src/postinst)12
-rw-r--r--debian/postrm (renamed from deployment/debian-package-x64/pkg-src/postrm)4
-rw-r--r--debian/preinst (renamed from deployment/debian-package-x64/pkg-src/preinst)0
-rw-r--r--debian/prerm (renamed from deployment/debian-package-x64/pkg-src/prerm)0
-rwxr-xr-xdebian/rules51
-rw-r--r--debian/source.lintian-overrides (renamed from deployment/debian-package-x64/pkg-src/source.lintian-overrides)0
-rw-r--r--debian/source/format (renamed from deployment/debian-package-x64/pkg-src/source/format)0
-rw-r--r--debian/source/options (renamed from deployment/debian-package-x64/pkg-src/source/options)0
-rw-r--r--deployment/Dockerfile.centos.amd6432
-rw-r--r--deployment/Dockerfile.debian.amd6426
-rw-r--r--deployment/Dockerfile.debian.arm6439
-rw-r--r--deployment/Dockerfile.debian.armhf40
-rw-r--r--deployment/Dockerfile.docker.amd6413
-rw-r--r--deployment/Dockerfile.docker.arm6413
-rw-r--r--deployment/Dockerfile.docker.armhf13
-rw-r--r--deployment/Dockerfile.fedora.amd6432
-rw-r--r--deployment/Dockerfile.linux.amd6426
-rw-r--r--deployment/Dockerfile.linux.amd64-musl26
-rw-r--r--deployment/Dockerfile.linux.arm6426
-rw-r--r--deployment/Dockerfile.linux.armhf26
-rw-r--r--deployment/Dockerfile.macos26
-rw-r--r--deployment/Dockerfile.portable25
-rw-r--r--deployment/Dockerfile.ubuntu.amd6432
-rw-r--r--deployment/Dockerfile.ubuntu.arm6455
-rw-r--r--deployment/Dockerfile.ubuntu.armhf55
-rw-r--r--deployment/Dockerfile.windows.amd6425
-rw-r--r--deployment/README.md113
-rwxr-xr-xdeployment/build.centos.amd6459
-rwxr-xr-xdeployment/build.debian.amd6443
-rwxr-xr-xdeployment/build.debian.arm6444
-rwxr-xr-xdeployment/build.debian.armhf44
-rwxr-xr-xdeployment/build.fedora.amd6459
-rwxr-xr-xdeployment/build.linux.amd6431
-rwxr-xr-xdeployment/build.linux.amd64-musl31
-rwxr-xr-xdeployment/build.linux.arm6431
-rwxr-xr-xdeployment/build.linux.armhf31
-rwxr-xr-xdeployment/build.macos31
-rwxr-xr-xdeployment/build.portable31
-rwxr-xr-xdeployment/build.ubuntu.amd6443
-rwxr-xr-xdeployment/build.ubuntu.arm6444
-rwxr-xr-xdeployment/build.ubuntu.armhf44
-rwxr-xr-xdeployment/build.windows.amd6452
-rw-r--r--deployment/centos-package-x64/Dockerfile27
-rwxr-xr-xdeployment/centos-package-x64/clean.sh34
-rw-r--r--deployment/centos-package-x64/dependencies.txt1
-rwxr-xr-xdeployment/centos-package-x64/docker-build.sh20
-rwxr-xr-xdeployment/centos-package-x64/package.sh80
l---------deployment/centos-package-x64/pkg-src1
-rwxr-xr-xdeployment/common.build.sh111
-rw-r--r--deployment/debian-package-x64/Dockerfile21
-rwxr-xr-xdeployment/debian-package-x64/clean.sh29
-rw-r--r--deployment/debian-package-x64/dependencies.txt1
-rwxr-xr-xdeployment/debian-package-x64/docker-build.sh19
-rwxr-xr-xdeployment/debian-package-x64/package.sh31
-rw-r--r--deployment/debian-package-x64/pkg-src/bin/restart.sh20
-rw-r--r--deployment/debian-package-x64/pkg-src/changelog276
-rw-r--r--deployment/debian-package-x64/pkg-src/conf/jellyfin41
-rw-r--r--deployment/debian-package-x64/pkg-src/control28
-rw-r--r--deployment/debian-package-x64/pkg-src/jellyfin.init49
-rw-r--r--deployment/debian-package-x64/pkg-src/jellyfin.service14
-rw-r--r--deployment/debian-package-x64/pkg-src/rules23
-rwxr-xr-xdeployment/docker/build.sh12
-rw-r--r--deployment/docker/dependencies.txt1
-rwxr-xr-xdeployment/docker/package.sh12
-rw-r--r--deployment/fedora-package-x64/Dockerfile27
-rwxr-xr-xdeployment/fedora-package-x64/clean.sh34
-rwxr-xr-xdeployment/fedora-package-x64/create_tarball.sh55
-rw-r--r--deployment/fedora-package-x64/dependencies.txt1
-rwxr-xr-xdeployment/fedora-package-x64/docker-build.sh20
-rwxr-xr-xdeployment/fedora-package-x64/package.sh35
-rw-r--r--deployment/fedora-package-x64/pkg-src/jellyfin.service15
-rw-r--r--deployment/fedora-package-x64/pkg-src/jellyfin.spec339
-rw-r--r--deployment/fedora-package-x64/pkg-src/restart.sh6
-rwxr-xr-xdeployment/linux-x64/build.sh7
-rwxr-xr-xdeployment/linux-x64/clean.sh7
-rw-r--r--deployment/linux-x64/dependencies.txt1
-rwxr-xr-xdeployment/linux-x64/package.sh7
-rwxr-xr-xdeployment/macos/build.sh7
-rwxr-xr-xdeployment/macos/clean.sh7
-rw-r--r--deployment/macos/dependencies.txt1
-rwxr-xr-xdeployment/macos/package.sh7
-rwxr-xr-xdeployment/portable/build.sh8
-rwxr-xr-xdeployment/portable/clean.sh7
-rwxr-xr-xdeployment/portable/package.sh7
-rw-r--r--deployment/ubuntu-package-x64/Dockerfile21
-rwxr-xr-xdeployment/ubuntu-package-x64/clean.sh29
-rw-r--r--deployment/ubuntu-package-x64/dependencies.txt1
-rwxr-xr-xdeployment/ubuntu-package-x64/docker-build.sh19
-rwxr-xr-xdeployment/ubuntu-package-x64/package.sh31
l---------deployment/ubuntu-package-x64/pkg-src1
-rw-r--r--deployment/unraid/docker-templates/README.md2
-rw-r--r--deployment/unraid/docker-templates/jellyfin.xml18
-rwxr-xr-xdeployment/win-x64/build.sh7
-rwxr-xr-xdeployment/win-x64/clean.sh7
-rw-r--r--deployment/win-x64/dependencies.txt1
-rwxr-xr-xdeployment/win-x64/package.sh47
-rwxr-xr-xdeployment/win-x86/build.sh7
-rwxr-xr-xdeployment/win-x86/clean.sh7
-rw-r--r--deployment/win-x86/dependencies.txt1
-rwxr-xr-xdeployment/win-x86/package.sh45
-rw-r--r--deployment/windows/build-jellyfin.ps1110
-rw-r--r--deployment/windows/dependencies.txt1
-rw-r--r--deployment/windows/install-jellyfin.ps1460
-rw-r--r--deployment/windows/install.bat1
-rw-r--r--fedora/.gitignore (renamed from deployment/fedora-package-x64/pkg-src/.gitignore)0
-rw-r--r--fedora/Makefile26
-rw-r--r--fedora/README.md (renamed from deployment/fedora-package-x64/pkg-src/README.md)0
-rw-r--r--fedora/jellyfin-firewalld.xml (renamed from deployment/fedora-package-x64/pkg-src/jellyfin-firewalld.xml)0
-rw-r--r--fedora/jellyfin.env (renamed from deployment/fedora-package-x64/pkg-src/jellyfin.env)16
-rw-r--r--fedora/jellyfin.override.conf (renamed from deployment/fedora-package-x64/pkg-src/jellyfin.override.conf)0
-rw-r--r--fedora/jellyfin.service15
-rw-r--r--fedora/jellyfin.spec165
-rw-r--r--fedora/jellyfin.sudoers (renamed from deployment/fedora-package-x64/pkg-src/jellyfin.sudoers)7
-rwxr-xr-xfedora/restart.sh56
-rw-r--r--fuzz/.gitignore1
-rw-r--r--fuzz/Emby.Server.Implementations.Fuzz/Emby.Server.Implementations.Fuzz.csproj25
-rw-r--r--fuzz/Emby.Server.Implementations.Fuzz/Program.cs62
-rw-r--r--fuzz/Emby.Server.Implementations.Fuzz/Testcases/PathExtensions.TryReplaceSubPath/test1.txt1
-rw-r--r--fuzz/Emby.Server.Implementations.Fuzz/Testcases/SqliteItemRepository.ItemImageInfoFromValueString/test1.txt1
-rwxr-xr-xfuzz/Emby.Server.Implementations.Fuzz/fuzz.sh11
-rw-r--r--fuzz/Jellyfin.Server.Fuzz/Jellyfin.Server.Fuzz.csproj22
-rw-r--r--fuzz/Jellyfin.Server.Fuzz/Program.cs33
-rw-r--r--fuzz/Jellyfin.Server.Fuzz/Testcases/UrlDecodeQueryFeature/test1.txt1
-rwxr-xr-xfuzz/Jellyfin.Server.Fuzz/fuzz.sh11
-rw-r--r--hooks/pre_build6
-rw-r--r--jellyfin.ruleset79
-rw-r--r--new-file-header.txt22
-rw-r--r--nuget.config6
-rw-r--r--src/Jellyfin.Extensions/AlphanumericComparator.cs144
-rw-r--r--src/Jellyfin.Extensions/CopyToExtensions.cs26
-rw-r--r--src/Jellyfin.Extensions/DictionaryExtensions.cs64
-rw-r--r--src/Jellyfin.Extensions/EnumerableExtensions.cs51
-rw-r--r--src/Jellyfin.Extensions/Jellyfin.Extensions.csproj37
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonBoolNumberConverter.cs30
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverter.cs19
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs28
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonDateTimeConverter.cs34
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonDelimitedArrayConverter.cs81
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs26
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonLowerCaseConverter.cs25
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonNullableGuidConverter.cs33
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs45
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverterFactory.cs27
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverter.cs19
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs28
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonStringConverter.cs39
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonVersionConverter.cs23
-rw-r--r--src/Jellyfin.Extensions/Json/JsonDefaults.cs90
-rw-r--r--src/Jellyfin.Extensions/ReadOnlyListExtension.cs61
-rw-r--r--src/Jellyfin.Extensions/ShuffleExtensions.cs39
-rw-r--r--src/Jellyfin.Extensions/SplitStringExtensions.cs115
-rw-r--r--src/Jellyfin.Extensions/StreamExtensions.cs63
-rw-r--r--src/Jellyfin.Extensions/StringBuilderExtensions.cs35
-rw-r--r--src/Jellyfin.Extensions/StringExtensions.cs65
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs154
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandlerTests.cs110
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs71
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/IgnoreSchedulePolicy/IgnoreScheduleHandlerTests.cs62
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs59
-rw-r--r--tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs53
-rw-r--r--tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs45
-rw-r--r--tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs89
-rw-r--r--tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj39
-rw-r--r--tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs226
-rw-r--r--tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs226
-rw-r--r--tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs11
-rw-r--r--tests/Jellyfin.Api.Tests/TestHelpers.cs84
-rw-r--r--tests/Jellyfin.Common.Tests/Crc32Tests.cs33
-rw-r--r--tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs169
-rw-r--r--tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj34
-rw-r--r--tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs85
-rw-r--r--tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs200
-rw-r--r--tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj33
-rw-r--r--tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs131
-rw-r--r--tests/Jellyfin.Dlna.Tests/GetUuidTests.cs17
-rw-r--r--tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj28
-rw-r--r--tests/Jellyfin.Extensions.Tests/AlphanumericComparatorTests.cs29
-rw-r--r--tests/Jellyfin.Extensions.Tests/CopyToExtensionsTests.cs59
-rw-r--r--tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj35
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonBoolNumberTests.cs44
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedArrayTests.cs142
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedIReadOnlyListTests.cs92
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonGuidConverterTests.cs68
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonLowerCaseConverterTests.cs71
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonNullableGuidConverterTests.cs80
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonStringConverterTests.cs38
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonVersionConverterTests.cs36
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyArrayModel.cs20
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyIReadOnlyListModel.cs19
-rw-r--r--tests/Jellyfin.Extensions.Tests/ShuffleExtensionsTests.cs19
-rw-r--r--tests/Jellyfin.Extensions.Tests/StringExtensionsTests.cs41
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTests.cs52
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs126
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs25
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj42
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs196
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs29
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs57
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs90
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleEncoderTests.cs83
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_metadata.json144
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json111
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_year_only_metadata.json147
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json74
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_mp4_metadata.json260
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass22
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt8
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ssa20
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/example2.srt11
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json105
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs19
-rw-r--r--tests/Jellyfin.Model.Tests/Entities/MediaStreamTests.cs150
-rw-r--r--tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs196
-rw-r--r--tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs32
-rw-r--r--tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj28
-rw-r--r--tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs30
-rw-r--r--tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs272
-rw-r--r--tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs65
-rw-r--r--tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs36
-rw-r--r--tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj32
-rw-r--r--tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs50
-rw-r--r--tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs41
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs27
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs32
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs88
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs35
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs104
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs27
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs80
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs35
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs65
-rw-r--r--tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs61
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs67
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs52
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs106
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs74
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs448
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/StackTests.cs454
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/StubTests.cs53
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs462
-rw-r--r--tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs194
-rw-r--r--tests/Jellyfin.Networking.Tests/IPHostTests.cs53
-rw-r--r--tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs49
-rw-r--r--tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj39
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs63
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkParseTests.cs480
-rw-r--r--tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj34
-rw-r--r--tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs216
-rw-r--r--tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs98
-rw-r--r--tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs176
-rw-r--r--tests/Jellyfin.Providers.Tests/Omdb/JsonOmdbConverterTests.cs86
-rw-r--r--tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs27
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs290
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs69
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs76
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj45
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs72
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Library/IgnorePatternsTests.cs39
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs59
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs156
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs326
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs98
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/LiveTv/SchedulesDirect/SchedulesDirectDeserializeTests.cs240
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs179
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs45
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/QuickConnect/QuickConnectManagerTests.cs124
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Sorting/AiredEpisodeOrderComparerTests.cs164
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/headends_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineup_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineups_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/metadata_programs_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/programs_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_request.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_live_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_offline_response.json1
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/empty.zipbin0 -> 162 bytes
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json684
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/TypedBaseItem/BaseItemKindTests.cs63
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs113
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Users/UserManagerTests.cs28
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs59
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs30
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/BaseJellyfinTestController.cs14
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs54
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs86
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/DlnaControllerTests.cs141
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs53
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/MediaInfoControllerTests.cs61
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/MediaStructureControllerTests.cs122
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs119
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs170
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs49
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj44
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs116
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Middleware/RobotsRedirectionMiddlewareTests.cs32
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs40
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs54
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/TestPage.html9
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs43
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs27
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs32
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/xunit.runner.json4
-rw-r--r--tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj33
-rw-r--r--tests/Jellyfin.Server.Tests/ParseNetworkTests.cs126
-rw-r--r--tests/Jellyfin.Server.Tests/UrlDecodeQueryFeatureTests.cs28
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj35
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Location/MovieNfoLocationTests.cs65
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs144
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs257
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs86
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs86
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs80
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs92
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs116
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/American Gods.nfo187
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Dancing Queen.nfo50
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Fanart.nfo33
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Imdb.nfo1
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo248
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Radarr.nfo2
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo20
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo86
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo29
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo116
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tmdb.nfo1
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tvdb.nfo1
-rw-r--r--tests/Jellyfin.XbmcMetadata.Tests/Test Data/U2.nfo70
-rw-r--r--tests/coverletArgs.runsettings17
-rw-r--r--tests/jellyfin-tests.ruleset22
2639 files changed, 137656 insertions, 126312 deletions
diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml
new file mode 100644
index 000000000..31f861f63
--- /dev/null
+++ b/.ci/azure-pipelines-abi.yml
@@ -0,0 +1,94 @@
+parameters:
+- name: Packages
+ type: object
+ default: {}
+- name: LinuxImage
+ type: string
+ default: "ubuntu-latest"
+- name: DotNetSdkVersion
+ type: string
+ default: 6.0.x
+
+jobs:
+ - job: CompatibilityCheck
+ displayName: Compatibility Check
+ dependsOn: Build
+ condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber'])
+
+ pool:
+ vmImage: "${{ parameters.LinuxImage }}"
+
+ strategy:
+ matrix:
+ ${{ each Package in parameters.Packages }}:
+ ${{ Package.key }}:
+ NugetPackageName: ${{ Package.value.NugetPackageName }}
+ AssemblyFileName: ${{ Package.value.AssemblyFileName }}
+ maxParallel: 2
+
+ steps:
+ - checkout: none
+
+ - task: UseDotNet@2
+ displayName: "Update DotNet"
+ inputs:
+ packageType: sdk
+ version: ${{ parameters.DotNetSdkVersion }}
+ includePreviewVersions: true
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Install ABI CompatibilityChecker Tool'
+ inputs:
+ command: custom
+ custom: tool
+ arguments: 'update compatibilitychecker -g'
+
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download New Assembly Build Artifact'
+ inputs:
+ source: 'current'
+ artifact: "$(NugetPackageName)"
+ path: "$(System.ArtifactsDirectory)/new-artifacts"
+ runVersion: "latest"
+
+ - task: CopyFiles@2
+ displayName: 'Copy New Assembly Build Artifact'
+ inputs:
+ sourceFolder: $(System.ArtifactsDirectory)/new-artifacts
+ contents: '**/*.dll'
+ targetFolder: $(System.ArtifactsDirectory)/new-release
+ cleanTargetFolder: true
+ overWrite: true
+ flattenFolders: true
+
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download Reference Assembly Build Artifact'
+ enabled: false
+ inputs:
+ source: "specific"
+ artifact: "$(NugetPackageName)"
+ path: "$(System.ArtifactsDirectory)/current-artifacts"
+ project: "$(System.TeamProjectId)"
+ pipeline: "$(System.DefinitionId)"
+ runVersion: "latestFromBranch"
+ runBranch: "refs/heads/$(System.PullRequest.TargetBranch)"
+
+ - task: CopyFiles@2
+ displayName: 'Copy Reference Assembly Build Artifact'
+ enabled: false
+ inputs:
+ sourceFolder: $(System.ArtifactsDirectory)/current-artifacts
+ contents: '**/*.dll'
+ targetFolder: $(System.ArtifactsDirectory)/current-release
+ cleanTargetFolder: true
+ overWrite: true
+ flattenFolders: true
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Execute ABI Compatibility Check Tool'
+ enabled: false
+ inputs:
+ command: custom
+ custom: compat
+ arguments: 'current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only'
+ workingDirectory: $(System.ArtifactsDirectory)
diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml
new file mode 100644
index 000000000..1086d51d2
--- /dev/null
+++ b/.ci/azure-pipelines-main.yml
@@ -0,0 +1,101 @@
+parameters:
+ LinuxImage: 'ubuntu-latest'
+ RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj'
+ DotNetSdkVersion: 6.0.x
+
+jobs:
+ - job: Build
+ displayName: Build
+ strategy:
+ matrix:
+ Release:
+ BuildConfiguration: Release
+ Debug:
+ BuildConfiguration: Debug
+ pool:
+ vmImage: '${{ parameters.LinuxImage }}'
+ steps:
+ - checkout: self
+ clean: true
+ submodules: true
+ persistCredentials: true
+
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download Web Branch'
+ condition: in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')
+ inputs:
+ path: '$(Agent.TempDirectory)'
+ artifact: 'jellyfin-web-production'
+ source: 'specific'
+ project: 'jellyfin'
+ pipeline: 'Jellyfin Web'
+ runBranch: variables['Build.SourceBranch']
+
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download Web Target'
+ condition: eq(variables['Build.Reason'], 'PullRequest')
+ inputs:
+ path: '$(Agent.TempDirectory)'
+ artifact: 'jellyfin-web-production'
+ source: 'specific'
+ project: 'jellyfin'
+ pipeline: 'Jellyfin Web'
+ runBranch: variables['System.PullRequest.TargetBranch']
+
+ - task: ExtractFiles@1
+ displayName: 'Extract Web Client'
+ inputs:
+ archiveFilePatterns: '$(Agent.TempDirectory)/*.zip'
+ destinationFolder: '$(Build.SourcesDirectory)/MediaBrowser.WebDashboard'
+ cleanDestinationFolder: false
+
+ - task: UseDotNet@2
+ displayName: 'Update DotNet'
+ inputs:
+ packageType: sdk
+ version: ${{ parameters.DotNetSdkVersion }}
+ includePreviewVersions: true
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Publish Server'
+ inputs:
+ command: publish
+ publishWebProjects: false
+ projects: '${{ parameters.RestoreBuildProjects }}'
+ arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'
+ zipAfterPublish: false
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Artifact Naming'
+ condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
+ inputs:
+ targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/Emby.Naming.dll'
+ artifactName: 'Jellyfin.Naming'
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Artifact Controller'
+ condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
+ inputs:
+ targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Controller.dll'
+ artifactName: 'Jellyfin.Controller'
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Artifact Model'
+ condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
+ inputs:
+ targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Model.dll'
+ artifactName: 'Jellyfin.Model'
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Artifact Common'
+ condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
+ inputs:
+ targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Common.dll'
+ artifactName: 'Jellyfin.Common'
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Artifact Extensions'
+ condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
+ inputs:
+ targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/Jellyfin.Extensions.dll'
+ artifactName: 'Jellyfin.Extensions'
diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml
new file mode 100644
index 000000000..4abe52b43
--- /dev/null
+++ b/.ci/azure-pipelines-package.yml
@@ -0,0 +1,262 @@
+jobs:
+- job: BuildPackage
+ displayName: 'Build Packages'
+
+ strategy:
+ matrix:
+ CentOS.amd64:
+ BuildConfiguration: centos.amd64
+ Fedora.amd64:
+ BuildConfiguration: fedora.amd64
+ Debian.amd64:
+ BuildConfiguration: debian.amd64
+ Debian.arm64:
+ BuildConfiguration: debian.arm64
+ Debian.armhf:
+ BuildConfiguration: debian.armhf
+ Ubuntu.amd64:
+ BuildConfiguration: ubuntu.amd64
+ Ubuntu.arm64:
+ BuildConfiguration: ubuntu.arm64
+ Ubuntu.armhf:
+ BuildConfiguration: ubuntu.armhf
+ Linux.amd64:
+ BuildConfiguration: linux.amd64
+ Linux.amd64-musl:
+ BuildConfiguration: linux.amd64-musl
+ Linux.arm64:
+ BuildConfiguration: linux.arm64
+ Linux.armhf:
+ BuildConfiguration: linux.armhf
+ Windows.amd64:
+ BuildConfiguration: windows.amd64
+ MacOS:
+ BuildConfiguration: macos
+ Portable:
+ BuildConfiguration: portable
+
+ pool:
+ vmImage: 'ubuntu-latest'
+
+ steps:
+ - script: 'docker build -f deployment/Dockerfile.$(BuildConfiguration) -t jellyfin-server-$(BuildConfiguration) deployment'
+ displayName: 'Build Dockerfile'
+
+ - script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="yes" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
+ displayName: 'Run Dockerfile (unstable)'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+
+ - script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="no" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
+ displayName: 'Run Dockerfile (stable)'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish Release'
+ inputs:
+ targetPath: '$(Build.SourcesDirectory)/deployment/dist'
+ artifactName: 'jellyfin-server-$(BuildConfiguration)'
+
+ - task: SSH@0
+ displayName: 'Create target directory on repository server'
+ inputs:
+ sshEndpoint: repository
+ runOptions: 'inline'
+ inline: 'mkdir -p /srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)'
+
+ - task: CopyFilesOverSSH@0
+ displayName: 'Upload artifacts to repository server'
+ inputs:
+ sshEndpoint: repository
+ sourceFolder: '$(Build.SourcesDirectory)/deployment/dist'
+ contents: '**'
+ targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)'
+
+- job: OpenAPISpec
+ dependsOn: Test
+ condition: or(startsWith(variables['Build.SourceBranch'], 'refs/heads/master'),startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
+ displayName: 'Push OpenAPI Spec to repository'
+
+ pool:
+ vmImage: 'ubuntu-latest'
+
+ steps:
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download OpenAPI Spec'
+ inputs:
+ source: 'current'
+ artifact: "OpenAPI Spec"
+ path: "$(System.ArtifactsDirectory)/openapispec"
+ runVersion: "latest"
+
+ - task: SSH@0
+ displayName: 'Create target directory on repository server'
+ inputs:
+ sshEndpoint: repository
+ runOptions: 'inline'
+ inline: 'mkdir -p /srv/repository/incoming/azure/$(Build.BuildNumber)'
+
+ - task: CopyFilesOverSSH@0
+ displayName: 'Upload artifacts to repository server'
+ inputs:
+ sshEndpoint: repository
+ sourceFolder: '$(System.ArtifactsDirectory)/openapispec'
+ contents: 'openapi.json'
+ targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)'
+
+- job: BuildDocker
+ displayName: 'Build Docker'
+
+ strategy:
+ matrix:
+ amd64:
+ BuildConfiguration: amd64
+ arm64:
+ BuildConfiguration: arm64
+ armhf:
+ BuildConfiguration: armhf
+
+ pool:
+ vmImage: 'ubuntu-latest'
+
+ variables:
+ - name: JellyfinVersion
+ value: 0.0.0
+
+ steps:
+ - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )"
+ displayName: Set release version (stable)
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+
+ - task: Docker@2
+ displayName: 'Push Unstable Image'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+ inputs:
+ repository: 'jellyfin/jellyfin-server'
+ command: buildAndPush
+ buildContext: '.'
+ Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
+ containerRegistry: Docker Hub
+ tags: |
+ unstable-$(Build.BuildNumber)-$(BuildConfiguration)
+ unstable-$(BuildConfiguration)
+
+ - task: Docker@2
+ displayName: 'Push Stable Image'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+ inputs:
+ repository: 'jellyfin/jellyfin-server'
+ command: buildAndPush
+ buildContext: '.'
+ Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
+ containerRegistry: Docker Hub
+ tags: |
+ stable-$(Build.BuildNumber)-$(BuildConfiguration)
+ $(JellyfinVersion)-$(BuildConfiguration)
+
+- job: CollectArtifacts
+ timeoutInMinutes: 20
+ displayName: 'Collect Artifacts'
+ continueOnError: true
+ dependsOn:
+ - BuildPackage
+ - BuildDocker
+
+ pool:
+ vmImage: 'ubuntu-latest'
+
+ steps:
+ - task: SSH@0
+ displayName: 'Update Unstable Repository'
+ continueOnError: true
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+ inputs:
+ sshEndpoint: repository
+ runOptions: 'commands'
+ commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable &
+
+ - task: SSH@0
+ displayName: 'Update Stable Repository'
+ continueOnError: true
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+ inputs:
+ sshEndpoint: repository
+ runOptions: 'commands'
+ commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) &
+
+- job: PublishNuget
+ displayName: 'Publish NuGet packages'
+
+ pool:
+ vmImage: 'ubuntu-latest'
+
+ variables:
+ - name: JellyfinVersion
+ value: $[replace(variables['Build.SourceBranch'],'refs/tags/v','')]
+
+ steps:
+ - task: UseDotNet@2
+ displayName: 'Use .NET 6.0 sdk'
+ inputs:
+ packageType: 'sdk'
+ version: '6.0.x'
+ includePreviewVersions: true
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Build Stable Nuget packages'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+ inputs:
+ command: 'custom'
+ projects: |
+ Jellyfin.Data/Jellyfin.Data.csproj
+ MediaBrowser.Common/MediaBrowser.Common.csproj
+ MediaBrowser.Controller/MediaBrowser.Controller.csproj
+ MediaBrowser.Model/MediaBrowser.Model.csproj
+ Emby.Naming/Emby.Naming.csproj
+ src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
+ custom: 'pack'
+ arguments: -o $(Build.ArtifactStagingDirectory) -p:Version=$(JellyfinVersion)
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Build Unstable Nuget packages'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+ inputs:
+ command: 'custom'
+ projects: |
+ Jellyfin.Data/Jellyfin.Data.csproj
+ MediaBrowser.Common/MediaBrowser.Common.csproj
+ MediaBrowser.Controller/MediaBrowser.Controller.csproj
+ MediaBrowser.Model/MediaBrowser.Model.csproj
+ Emby.Naming/Emby.Naming.csproj
+ src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
+ custom: 'pack'
+ arguments: '--version-suffix $(Build.BuildNumber) -o $(Build.ArtifactStagingDirectory) -p:Stability=Unstable'
+
+ - task: PublishBuildArtifacts@1
+ displayName: 'Publish Nuget packages'
+ inputs:
+ pathToPublish: $(Build.ArtifactStagingDirectory)
+ artifactName: Jellyfin Nuget Packages
+
+ - task: NuGetCommand@2
+ displayName: 'Push Nuget packages to stable feed'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+ inputs:
+ command: 'push'
+ packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg'
+ nuGetFeedType: 'external'
+ publishFeedCredentials: 'NugetOrg'
+ allowPackageConflicts: true # This ignores an error if the version already exists
+
+ - task: NuGetAuthenticate@0
+ displayName: 'Authenticate to unstable Nuget feed'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+
+ - task: NuGetCommand@2
+ displayName: 'Push Nuget packages to unstable feed'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
+ inputs:
+ command: 'push'
+ packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg' # No symbols since Azure Artifact does not support it
+ nuGetFeedType: 'internal'
+ publishVstsFeed: '7cce6c46-d610-45e3-9fb7-65a6bfd1b671/a5746b79-f369-42db-93ff-59cd066f9327'
+ allowPackageConflicts: true # This ignores an error if the version already exists
diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml
new file mode 100644
index 000000000..80a5732ee
--- /dev/null
+++ b/.ci/azure-pipelines-test.yml
@@ -0,0 +1,99 @@
+parameters:
+- name: ImageNames
+ type: object
+ default:
+ Linux: "ubuntu-latest"
+ Windows: "windows-latest"
+ macOS: "macos-latest"
+- name: TestProjects
+ type: string
+ default: "tests/**/*Tests.csproj"
+- name: DotNetSdkVersion
+ type: string
+ default: 6.0.x
+
+jobs:
+ - job: Test
+ displayName: Test
+ strategy:
+ matrix:
+ ${{ each imageName in parameters.ImageNames }}:
+ ${{ imageName.key }}:
+ ImageName: ${{ imageName.value }}
+ pool:
+ vmImage: "$(ImageName)"
+ steps:
+ - checkout: self
+ clean: true
+ submodules: true
+ persistCredentials: false
+
+ # This is required for the SonarCloud analyzer
+ - task: UseDotNet@2
+ displayName: "Install .NET SDK 5.x"
+ condition: eq(variables['ImageName'], 'ubuntu-latest')
+ inputs:
+ packageType: sdk
+ version: '5.x'
+
+ - task: UseDotNet@2
+ displayName: "Update DotNet"
+ inputs:
+ packageType: sdk
+ version: ${{ parameters.DotNetSdkVersion }}
+ includePreviewVersions: true
+
+ - task: SonarCloudPrepare@1
+ displayName: 'Prepare analysis on SonarCloud'
+ condition: eq(variables['ImageName'], 'ubuntu-latest')
+ enabled: false
+ inputs:
+ SonarCloud: 'Sonarcloud for Jellyfin'
+ organization: 'jellyfin'
+ projectKey: 'jellyfin_jellyfin'
+
+ - task: DotNetCoreCLI@2
+ displayName: 'Run CLI Tests'
+ inputs:
+ command: "test"
+ projects: ${{ parameters.TestProjects }}
+ arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal'
+ publishTestResults: true
+ testRunTitle: $(Agent.JobName)
+ workingDirectory: "$(Build.SourcesDirectory)"
+
+ - task: SonarCloudAnalyze@1
+ displayName: 'Run Code Analysis'
+ condition: eq(variables['ImageName'], 'ubuntu-latest')
+ enabled: false
+
+ - task: SonarCloudPublish@1
+ displayName: 'Publish Quality Gate Result'
+ condition: eq(variables['ImageName'], 'ubuntu-latest')
+ enabled: false
+
+ - task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4
+ condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
+ displayName: 'Run ReportGenerator'
+ inputs:
+ reports: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
+ targetdir: "$(Agent.TempDirectory)/merged/"
+ reporttypes: "Cobertura"
+
+ ## V2 is already in the repository but it does not work "wrong number of segments" YAML error.
+ - task: PublishCodeCoverageResults@1
+ condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
+ displayName: 'Publish Code Coverage'
+ inputs:
+ codeCoverageTool: "cobertura"
+ #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2
+ summaryFileLocation: "$(Agent.TempDirectory)/merged/**.xml"
+ pathToSources: $(Build.SourcesDirectory)
+ failIfCoverageEmpty: true
+
+ - task: PublishPipelineArtifact@1
+ displayName: 'Publish OpenAPI Artifact'
+ condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux'))
+ inputs:
+ targetPath: "tests/Jellyfin.Server.Integration.Tests/bin/Release/net6.0/openapi.json"
+ artifactName: 'OpenAPI Spec'
diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml
new file mode 100644
index 000000000..19c9caacb
--- /dev/null
+++ b/.ci/azure-pipelines.yml
@@ -0,0 +1,64 @@
+name: $(Date:yyyyMMdd)$(Rev:.r)
+
+variables:
+- name: TestProjects
+ value: 'tests/**/*Tests.csproj'
+- name: RestoreBuildProjects
+ value: 'Jellyfin.Server/Jellyfin.Server.csproj'
+
+pr:
+ autoCancel: true
+
+trigger:
+ batch: true
+ branches:
+ include:
+ - '*'
+ tags:
+ include:
+ - 'v*'
+
+jobs:
+- ${{ if not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')) }}:
+ - template: azure-pipelines-main.yml
+ parameters:
+ LinuxImage: 'ubuntu-latest'
+ RestoreBuildProjects: $(RestoreBuildProjects)
+
+- ${{ if not(or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))) }}:
+ - template: azure-pipelines-test.yml
+ parameters:
+ ImageNames:
+ Linux: 'ubuntu-latest'
+ Windows: 'windows-latest'
+ macOS: 'macos-latest'
+
+- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
+ - template: azure-pipelines-test.yml
+ parameters:
+ ImageNames:
+ Linux: 'ubuntu-latest'
+
+- ${{ if not(or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))) }}:
+ - template: azure-pipelines-abi.yml
+ parameters:
+ Packages:
+ Naming:
+ NugetPackageName: Jellyfin.Naming
+ AssemblyFileName: Emby.Naming.dll
+ Controller:
+ NugetPackageName: Jellyfin.Controller
+ AssemblyFileName: MediaBrowser.Controller.dll
+ Model:
+ NugetPackageName: Jellyfin.Model
+ AssemblyFileName: MediaBrowser.Model.dll
+ Common:
+ NugetPackageName: Jellyfin.Common
+ AssemblyFileName: MediaBrowser.Common.dll
+ Extensions:
+ NugetPackageName: Jellyfin.Extensions
+ AssemblyFileName: Jellyfin.Extensions.dll
+ LinuxImage: 'ubuntu-latest'
+
+- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
+ - template: azure-pipelines-package.yml
diff --git a/.copr/Makefile b/.copr/Makefile
index 84b98a011..ec3c90dfd 100644..120000
--- a/.copr/Makefile
+++ b/.copr/Makefile
@@ -1,8 +1 @@
-srpm:
- dnf -y install git
- git submodule update --init --recursive
- cd deployment/fedora-package-x64; \
- ./create_tarball.sh; \
- rpmbuild -bs pkg-src/jellyfin.spec \
- --define "_sourcedir $$PWD/pkg-src/" \
- --define "_srcrpmdir $(outdir)"
+../fedora/Makefile \ No newline at end of file
diff --git a/.drone.yml b/.drone.yml
deleted file mode 100644
index 7705f4f93..000000000
--- a/.drone.yml
+++ /dev/null
@@ -1,111 +0,0 @@
----
-kind: pipeline
-name: build-debug
-
-steps:
-- name: submodules
- image: docker:git
- commands:
- - git submodule update --init --recursive
-
-- name: build
- image: microsoft/dotnet:2-sdk
- commands:
- - dotnet publish "Jellyfin.Server" --configuration Debug --output "../ci/ci-debug"
-
----
-kind: pipeline
-name: build-release
-
-steps:
-- name: submodules
- image: docker:git
- commands:
- - git submodule update --init --recursive
-
-- name: build
- image: microsoft/dotnet:2-sdk
- commands:
- - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release"
-
----
-
-kind: pipeline
-name: check-abi
-
-steps:
-- name: submodules
- image: docker:git
- commands:
- - git submodule update --init --recursive
-
-- name: build
- image: microsoft/dotnet:2-sdk
- commands:
- - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release"
-
-- name: clone-dotnet-compat
- image: docker:git
- commands:
- - git clone --depth 1 https://github.com/EraYaN/dotnet-compatibility ci/dotnet-compatibility
-
-- name: build-dotnet-compat
- image: microsoft/dotnet:2-sdk
- commands:
- - dotnet publish "ci/dotnet-compatibility/CompatibilityCheckerCoreCLI" --configuration Release --output "../../ci-tools"
-
-- name: download-last-nuget-release-common
- image: plugins/download
- settings:
- source: https://www.nuget.org/api/v2/package/Jellyfin.Common
- destination: ci/Jellyfin.Common.nupkg
-
-- name: download-last-nuget-release-model
- image: plugins/download
- settings:
- source: https://www.nuget.org/api/v2/package/Jellyfin.Model
- destination: ci/Jellyfin.Model.nupkg
-
-- name: download-last-nuget-release-controller
- image: plugins/download
- settings:
- source: https://www.nuget.org/api/v2/package/Jellyfin.Controller
- destination: ci/Jellyfin.Controller.nupkg
-
-- name: download-last-nuget-release-naming
- image: plugins/download
- settings:
- source: https://www.nuget.org/api/v2/package/Jellyfin.Naming
- destination: ci/Jellyfin.Naming.nupkg
-
-- name: extract-downloaded-nuget-packages
- image: garthk/unzip
- commands:
- - unzip -j ci/Jellyfin.Common.nupkg "*.dll" -d ci/nuget-packages
- - unzip -j ci/Jellyfin.Model.nupkg "*.dll" -d ci/nuget-packages
- - unzip -j ci/Jellyfin.Controller.nupkg "*.dll" -d ci/nuget-packages
- - unzip -j ci/Jellyfin.Naming.nupkg "*.dll" -d ci/nuget-packages
-
-- name: run-dotnet-compat-common
- image: microsoft/dotnet:2-runtime
- err_ignore: true
- commands:
- - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Common.dll ci/ci-release/MediaBrowser.Common.dll
-
-- name: run-dotnet-compat-model
- image: microsoft/dotnet:2-runtime
- err_ignore: true
- commands:
- - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Model.dll ci/ci-release/MediaBrowser.Model.dll
-
-- name: run-dotnet-compat-controller
- image: microsoft/dotnet:2-runtime
- err_ignore: true
- commands:
- - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Controller.dll ci/ci-release/MediaBrowser.Controller.dll
-
-- name: run-dotnet-compat-naming
- image: microsoft/dotnet:2-runtime
- err_ignore: true
- commands:
- - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/Emby.Naming.dll ci/ci-release/Emby.Naming.dll
diff --git a/.editorconfig b/.editorconfig
index dc9aaa3ed..b84e563ef 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -13,7 +13,7 @@ charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
-max_line_length = null
+max_line_length = off
# YAML indentation
[*.{yml,yaml}]
@@ -22,6 +22,7 @@ indent_size = 2
# XML indentation
[*.{csproj,xml}]
indent_size = 2
+
###############################
# .NET Coding Conventions #
###############################
@@ -51,11 +52,12 @@ dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
-dotnet_prefer_inferred_tuple_names = true:suggestion
-dotnet_prefer_inferred_anonymous_type_member_names = true:suggestion
+dotnet_style_prefer_inferred_tuple_names = true:suggestion
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
+
###############################
# Naming Conventions #
###############################
@@ -67,7 +69,7 @@ dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field
-dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected
+dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected
dotnet_naming_symbols.non_private_static_fields.required_modifiers = static
dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case
@@ -159,6 +161,7 @@ csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
+
###############################
# C# Formatting Rules #
###############################
@@ -189,9 +192,3 @@ csharp_space_between_method_call_empty_parameter_list_parentheses = false
# Wrapping preferences
csharp_preserve_single_line_statements = true
csharp_preserve_single_line_blocks = true
-###############################
-# VB Coding Conventions #
-###############################
-[*.vb]
-# Modifier preferences
-visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion
diff --git a/.gitattributes b/.gitattributes
index 0c0ab960a..8ae599725 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,5 @@
+* text=auto eol=lf
+*.png binary
+*.jpg binary
+
CONTRIBUTORS.md merge=union
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 000000000..e1900d583
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,4 @@
+# Joshua must review all changes to deployment and build.sh
+.ci/* @joshuaboniface
+deployment/* @joshuaboniface
+build.sh @joshuaboniface
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 137a689e8..c1d49778e 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -10,6 +10,21 @@ assignees: ''
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
+**System (please complete the following information):**
+ - OS: [e.g. Debian, Windows]
+ - Virtualization: [e.g. Docker, KVM, LXC]
+ - Clients: [Browser, Android, Fire Stick, etc.]
+ - Browser: [e.g. Firefox 91, Chrome 93, Safari 13]
+ - Jellyfin Version: [e.g. 10.7.6, unstable 20191231]
+ - FFmpeg Version: [e.g. 4.3.2-Jellyfin]
+ - Playback: [Direct Play, Remux, Direct Stream, Transcode]
+ - Hardware Acceleration: [e.g. none, VAAPI, NVENC, etc.]
+ - Installed Plugins: [e.g. none, Fanart, Anime, etc.]
+ - 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]
+
**To Reproduce**
<!-- Steps to reproduce the behavior: -->
1. Go to '...'
@@ -20,16 +35,17 @@ assignees: ''
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
-**Logs**
+**Server Logs**
+<!-- Please paste any log errors. -->
+
+**FFmpeg Logs**
+<!-- Please paste any log errors. -->
+
+**Browser Console Logs**
<!-- Please paste any log errors. -->
**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. -->
-**System (please complete the following information):**
- - OS: [e.g. Docker, Debian, Windows]
- - Browser: [e.g. Firefox, Chrome, Safari]
- - Jellyfin Version: [e.g. 10.0.1]
-
**Additional context**
<!-- Add any other context about the problem here. -->
diff --git a/.github/ISSUE_TEMPLATE/enhancement-request.md b/.github/ISSUE_TEMPLATE/enhancement-request.md
deleted file mode 100644
index a655b60f5..000000000
--- a/.github/ISSUE_TEMPLATE/enhancement-request.md
+++ /dev/null
@@ -1,20 +0,0 @@
----
-name: Enhancement request
-about: Suggest an modification to an existing feature
-title: ''
-labels: enhancement
-assignees: ''
-
----
-
-**Is your feature request related to a problem? Please describe.**
-<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
-
-**Describe the solution you'd like**
-<!-- A clear and concise description of what you want to happen. -->
-
-**Describe alternatives you've considered**
-<!-- A clear and concise description of any alternative solutions or features you've considered. -->
-
-**Additional context**
-<!-- Add any other context or screenshots about the feature request here. -->
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index 3cbc8cbb9..d886c6487 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -1,14 +1,13 @@
---
-name: Feature request
-about: Suggest a new feature
+name: Feature Request
+about: Request a new feature
title: ''
-labels: feature
+labels: feature-request
assignees: ''
-
---
-**Describe the feature you'd like**
-<!-- A clear and concise description of what you want to happen. -->
+**PLEASE DO NOT OPEN FEATURE REQUEST ISSUES ON GITHUB**
+
+**Feature requests should be opened on our dedicated [feature request](https://features.jellyfin.org/) hub so they can be appropriately discussed and prioritized.**
-**Additional context**
-<!-- Add any other context or screenshots about the feature request here. -->
+However, if you are willing to contribute to the project by adding a new feature yourself, then please ensure that you first review our [documentation](https://docs.jellyfin.org/general/contributing/development.html) on contributing code. Once you have reviewed the documentation, feel free to come back here and open an issue here outlining your proposed approach so that it can be documented, tracked, and discussed by other team members.
diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md
new file mode 100644
index 000000000..b51500f87
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/media_playback.md
@@ -0,0 +1,34 @@
+---
+name: Media playback issue
+about: Create a media playback issue report
+title: ''
+labels: mediaplayback
+assignees: ''
+
+---
+
+**Media Info of the file**
+<!-- Use the Media Info tool (set to text format, download here: https://mediaarea.net/en/MediaInfo) or copy the info from the web ui for the file with the playback issue. -->
+
+**Logs**
+<!-- Please paste any log messages from during the playback issue. -->
+
+**FFmpeg Logs**
+<!-- Please paste any FFmpeg logs if remuxing or transcoding appears to be part of the issue. -->
+
+**Stats for Nerds Screenshots**
+<!-- If available, add screenshots of the stats for nerds screen to help show the issue problem. -->
+
+**Server System (please complete the following information):**
+ - OS: [e.g. Docker on Linux, Docker on Windows, Debian, Windows]
+ - Jellyfin Version: [e.g. 10.0.1]
+ - Hardware settings & device: [e.g. NVENC on GTX1060, VAAPI on Intel i7 8700K]
+ - Reverse proxy: [e.g. no, nginx, apache, etc.]
+ - Other hardware notes: [e.g. Media mounted in CIFS/SMB share, Media mounted from Google Drive]
+
+**Client System (please complete the following information):**
+ - Device: [e.g. Apple iPhone XS, Xbox One S, LG OLED55C8, Samsung Galaxy Note9, Custom HTPC]
+ - OS: [e.g. iOS, Android, Windows, macOS]
+ - Client: [e.g. Web/Browser, webOS, Android, Android TV, Electron]
+ - Browser (if Web client): [e.g. Firefox, Chrome, Safari]
+ - Client and Browser Version: [e.g. 10.3.4 and 68.0]
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..70bcd4973
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,15 @@
+version: 2
+updates:
+- package-ecosystem: nuget
+ directory: "/"
+ schedule:
+ interval: weekly
+ time: '12:00'
+ open-pull-requests-limit: 10
+
+- package-ecosystem: github-actions
+ directory: '/'
+ schedule:
+ interval: weekly
+ time: '12:00'
+ open-pull-requests-limit: 10
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 967be0fb7..dc93d2c84 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,6 +1,6 @@
<!--
Ensure your title is short, descriptive, and in the imperative mood (Fix X, Change Y, instead of Fixed X, Changed Y).
-For a good inspiration of what to write in commit messages and PRs please review https://chris.beams.io/posts/git-commit/ and our https://jellyfin.readthedocs.io/en/latest/developer-docs/contributing/ page.
+For a good inspiration of what to write in commit messages and PRs please review https://chris.beams.io/posts/git-commit/ and our documentation.
-->
**Changes**
diff --git a/.github/stale.yml b/.github/stale.yml
new file mode 100644
index 000000000..cba9c33b2
--- /dev/null
+++ b/.github/stale.yml
@@ -0,0 +1,29 @@
+# Number of days of inactivity before an issue becomes stale
+daysUntilStale: 120
+# Number of days of inactivity before a stale issue is closed
+daysUntilClose: 21
+# Issues with these labels will never be considered stale
+exemptLabels:
+ - regression
+ - security
+ - dotnet-3.0-future
+ - roadmap
+ - future
+ - feature
+ - enhancement
+ - confirmed
+# Label to use when marking an issue as stale
+staleLabel: stale
+# Comment to post when marking an issue as stale. Set to `false` to disable
+markComment: >
+ This issue has gone 120 days without comment. To avoid abandoned issues, it will be closed in 21 days if there are no new comments.
+
+ If you're the original submitter of this issue, please comment confirming if this issue still affects you in the latest release or nightlies, or close the issue if it has been fixed. If you're another user also affected by this bug, please comment confirming so. Either action will remove the stale label.
+
+ This bot exists to prevent issues from becoming stale and forgotten. Jellyfin is always moving forward, and bugs are often fixed as side effects of other changes. We therefore ask that bug report authors remain vigilant about their issues to ensure they are closed if fixed, or re-confirmed - perhaps with fresh logs or reproduction examples - regularly. If you have any questions you can reach us on [Matrix or Social Media](https://docs.jellyfin.org/general/getting-help.html).
+# Comment to post when closing a stale issue. Set to `false` to disable
+closeComment: false
+
+# Disable automatic closing of pull requests
+pulls:
+ daysUntilClose: false
diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml
new file mode 100644
index 000000000..20294843d
--- /dev/null
+++ b/.github/workflows/automation.yml
@@ -0,0 +1,76 @@
+name: Automation
+
+on:
+ push:
+ branches:
+ - master
+ pull_request_target:
+ issue_comment:
+
+jobs:
+ label:
+ name: Labeling
+ runs-on: ubuntu-latest
+ if: ${{ github.repository == 'jellyfin/jellyfin' }}
+ steps:
+ - name: Apply label
+ uses: eps1lon/actions-label-merge-conflict@v2.0.1
+ if: ${{ github.event_name == 'push' || github.event_name == 'pull_request_target'}}
+ with:
+ dirtyLabel: 'merge conflict'
+ repoToken: ${{ secrets.JF_BOT_TOKEN }}
+
+ project:
+ name: Project board
+ runs-on: ubuntu-latest
+ if: ${{ github.repository == 'jellyfin/jellyfin' }}
+ steps:
+ - name: Remove from 'Current Release' project
+ uses: alex-page/github-project-automation-plus@v0.8.1
+ if: (github.event.pull_request || github.event.issue.pull_request) && !contains(github.event.*.labels.*.name, 'stable backport')
+ continue-on-error: true
+ with:
+ project: Current Release
+ action: delete
+ repo-token: ${{ secrets.JF_BOT_TOKEN }}
+
+ - name: Add to 'Release Next' project
+ uses: alex-page/github-project-automation-plus@v0.8.1
+ if: (github.event.pull_request || github.event.issue.pull_request) && github.event.action == 'opened'
+ continue-on-error: true
+ with:
+ project: Release Next
+ column: In progress
+ repo-token: ${{ secrets.JF_BOT_TOKEN }}
+
+ - name: Add to 'Current Release' project
+ uses: alex-page/github-project-automation-plus@v0.8.1
+ if: (github.event.pull_request || github.event.issue.pull_request) && !contains(github.event.*.labels.*.name, 'stable backport')
+ continue-on-error: true
+ with:
+ project: Current Release
+ column: In progress
+ repo-token: ${{ secrets.JF_BOT_TOKEN }}
+
+ - name: Check number of comments from the team member
+ if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER'
+ id: member_comments
+ run: echo "::set-output name=number::$(curl -s ${{ github.event.issue.comments_url }} | jq '.[] | select(.author_association == "MEMBER") | .author_association' | wc -l)"
+
+ - name: Move issue to needs triage
+ uses: alex-page/github-project-automation-plus@v0.8.1
+ if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' && steps.member_comments.outputs.number <= 1
+ continue-on-error: true
+ with:
+ project: Issue Triage for Main Repo
+ column: Needs triage
+ repo-token: ${{ secrets.JF_BOT_TOKEN }}
+
+ - name: Add issue to triage project
+ uses: alex-page/github-project-automation-plus@v0.8.1
+ if: github.event.issue.pull_request == '' && github.event.action == 'opened'
+ continue-on-error: true
+ with:
+ project: Issue Triage for Main Repo
+ column: Pending response
+ repo-token: ${{ secrets.JF_BOT_TOKEN }}
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 000000000..e07d913b5
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,38 @@
+name: "CodeQL"
+
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+ schedule:
+ - cron: '24 2 * * 4'
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+
+ strategy:
+ fail-fast: false
+ matrix:
+ language: [ 'csharp' ]
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v2
+ - name: Setup .NET Core
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: '6.0.x'
+ include-prerelease: true
+
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v1
+ with:
+ languages: ${{ matrix.language }}
+ queries: +security-extended
+ - name: Autobuild
+ uses: github/codeql-action/autobuild@v1
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v1
diff --git a/.github/workflows/commands.yml b/.github/workflows/commands.yml
new file mode 100644
index 000000000..af4d8beb9
--- /dev/null
+++ b/.github/workflows/commands.yml
@@ -0,0 +1,119 @@
+name: Commands
+on:
+ issue_comment:
+ types:
+ - created
+ - edited
+ pull_request_target:
+ types:
+ - labeled
+ - synchronize
+
+jobs:
+ rebase:
+ name: Rebase
+ if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '@jellyfin-bot rebase') && github.event.comment.author_association == 'MEMBER'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Notify as seen
+ uses: peter-evans/create-or-update-comment@v1.4.5
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ comment-id: ${{ github.event.comment.id }}
+ reactions: '+1'
+
+ - name: Checkout the latest code
+ uses: actions/checkout@v2
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ fetch-depth: 0
+
+ - name: Automatic Rebase
+ uses: cirrus-actions/rebase@1.5
+ env:
+ GITHUB_TOKEN: ${{ secrets.JF_BOT_TOKEN }}
+
+ check-backport:
+ name: Check Backport
+ if: ${{ ( github.event.issue.pull_request && contains(github.event.comment.body, '@jellyfin-bot check backport') ) || github.event.label.name == 'stable backport' || contains(github.event.pull_request.labels.*.name, 'stable backport' ) }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Notify as seen
+ uses: peter-evans/create-or-update-comment@v1.4.5
+ if: ${{ github.event.comment != null }}
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ comment-id: ${{ github.event.comment.id }}
+ reactions: eyes
+
+ - name: Checkout the latest code
+ uses: actions/checkout@v2
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ fetch-depth: 0
+
+ - name: Notify as running
+ id: comment_running
+ uses: peter-evans/create-or-update-comment@v1.4.5
+ if: ${{ github.event.comment != null }}
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ issue-number: ${{ github.event.issue.number }}
+ body: |
+ Running backport tests...
+
+ - name: Perform test backport
+ id: run_tests
+ run: |
+ set +o errexit
+ git config --global user.name "Jellyfin Bot"
+ git config --global user.email "team@jellyfin.org"
+ CURRENT_BRANCH="origin/${GITHUB_HEAD_REF}"
+ git checkout master
+ git merge --no-ff ${CURRENT_BRANCH}
+ MERGE_COMMIT_HASH=$( git log -q -1 | head -1 | awk '{ print $2 }' )
+ git fetch --all
+ CURRENT_STABLE=$( git branch -r | grep 'origin/release' | sort -rV | head -1 | awk -F '/' '{ print $NF }' )
+ stable_branch="Current stable release branch: ${CURRENT_STABLE}"
+ echo ${stable_branch}
+ echo ::set-output name=branch::${stable_branch}
+ git checkout -t origin/${CURRENT_STABLE} -b ${CURRENT_STABLE}
+ git cherry-pick -sx -m1 ${MERGE_COMMIT_HASH} &>output.txt
+ retcode=$?
+ cat output.txt | grep -v 'hint:'
+ output="$( grep -v 'hint:' output.txt )"
+ output="${output//'%'/'%25'}"
+ output="${output//$'\n'/'%0A'}"
+ output="${output//$'\r'/'%0D'}"
+ echo ::set-output name=output::$output
+ exit ${retcode}
+
+ - name: Notify with result success
+ uses: peter-evans/create-or-update-comment@v1.4.5
+ if: ${{ github.event.comment != null && success() }}
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ comment-id: ${{ steps.comment_running.outputs.comment-id }}
+ body: |
+ ${{ steps.run_tests.outputs.branch }}
+ Output from `git cherry-pick`:
+
+ ---
+
+ ${{ steps.run_tests.outputs.output }}
+ reactions: hooray
+
+ - name: Notify with result failure
+ uses: peter-evans/create-or-update-comment@v1.4.5
+ if: ${{ github.event.comment != null && failure() }}
+ with:
+ token: ${{ secrets.JF_BOT_TOKEN }}
+ comment-id: ${{ steps.comment_running.outputs.comment-id }}
+ body: |
+ ${{ steps.run_tests.outputs.branch }}
+ Output from `git cherry-pick`:
+
+ ---
+
+ ${{ steps.run_tests.outputs.output }}
+ reactions: confused
diff --git a/.gitignore b/.gitignore
index 65e47747e..c2ae76c1e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -239,24 +239,19 @@ pip-log.txt
##########
.idea/
-##########
-# Visual Studio Code
-##########
-.vscode/
-
#########################
# Build artifacts
#########################
# Artifacts for debian-x64
-deployment/debian-package-x64/pkg-src/.debhelper/
-deployment/debian-package-x64/pkg-src/*.debhelper
-deployment/debian-package-x64/pkg-src/debhelper-build-stamp
-deployment/debian-package-x64/pkg-src/files
-deployment/debian-package-x64/pkg-src/jellyfin.substvars
-deployment/debian-package-x64/pkg-src/jellyfin/
+debian/.debhelper/
+debian/*.debhelper
+debian/debhelper-build-stamp
+debian/files
+debian/jellyfin.substvars
+debian/jellyfin/
# Don't ignore the debian/bin folder
-!deployment/debian-package-x64/pkg-src/bin/
+!debian/bin/
deployment/**/dist/
deployment/**/pkg-dist/
@@ -266,3 +261,23 @@ deployment/collect-dist/
jellyfin_version.ini
ci/
+
+# Doxygen
+doc/
+
+# Deployment artifacts
+dist
+*.exe
+*.dll
+
+# BenchmarkDotNet artifacts
+BenchmarkDotNet.Artifacts
+
+# Ignore web artifacts from native builds
+web/
+web-src.*
+MediaBrowser.WebDashboard/jellyfin-web
+apiclient/generated
+
+# Omnisharp crash logs
+mono_crash.*.json
diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index c10f5905c..000000000
--- a/.gitmodules
+++ /dev/null
@@ -1,3 +0,0 @@
-[submodule "MediaBrowser.WebDashboard/jellyfin-web"]
- path = MediaBrowser.WebDashboard/jellyfin-web
- url = https://github.com/jellyfin/jellyfin-web.git
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 000000000..b7a317000
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1,3 @@
+registry=https://registry.npmjs.org/
+@jellyfin:registry=https://pkgs.dev.azure.com/jellyfin-project/jellyfin/_packaging/unstable/npm/registry/
+always-auth=true \ No newline at end of file
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 000000000..59d9452fe
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,14 @@
+{
+ // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
+ // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
+
+ // List of extensions which should be recommended for users of this workspace.
+ "recommendations": [
+ "ms-dotnettools.csharp",
+ "editorconfig.editorconfig"
+ ],
+ // List of extensions recommended by VS Code that should not be recommended for users of this workspace.
+ "unwantedRecommendations": [
+
+ ]
+}
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 21b8323ea..b82956a72 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -1,19 +1,30 @@
{
- // Use IntelliSense to find out which attributes exist for C# debugging
- // Use hover for the description of the existing attributes
- // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
- "version": "0.2.0",
- "configurations": [
+ "version": "0.2.0",
+ "configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
- // If you have changed target frameworks, make sure to update the program path.
- "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net6.0/jellyfin.dll",
"args": [],
"cwd": "${workspaceFolder}/Jellyfin.Server",
- // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
+ "console": "internalConsole",
+ "stopAtEntry": false,
+ "internalConsoleOptions": "openOnSessionStart",
+ "serverReadyAction": {
+ "action": "openExternally",
+ "pattern": "Overriding address\\(es\\) \\'(https?:\\S+)\\'",
+ }
+ },
+ {
+ "name": ".NET Core Launch (nowebclient)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net6.0/jellyfin.dll",
+ "args": ["--nowebclient"],
+ "cwd": "${workspaceFolder}/Jellyfin.Server",
"console": "internalConsole",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart"
@@ -24,5 +35,8 @@
"request": "attach",
"processId": "${command:pickProcess}"
}
- ,]
-} \ No newline at end of file
+ ],
+ "env": {
+ "DOTNET_CLI_TELEMETRY_OPTOUT": "1"
+ }
+}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index ac517e10c..09c523eb2 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -10,6 +10,21 @@
"${workspaceFolder}/Jellyfin.Server/Jellyfin.Server.csproj"
],
"problemMatcher": "$msCompile"
+ },
+ {
+ "label": "api tests",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "test",
+ "${workspaceFolder}/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj"
+ ],
+ "problemMatcher": "$msCompile"
+ }
+ ],
+ "options": {
+ "env": {
+ "DOTNET_CLI_TELEMETRY_OPTOUT": "1"
}
- ]
-} \ No newline at end of file
+ }
+}
diff --git a/BDInfo/BDInfo.csproj b/BDInfo/BDInfo.csproj
deleted file mode 100644
index b2c752d0c..000000000
--- a/BDInfo/BDInfo.csproj
+++ /dev/null
@@ -1,16 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/BDInfo/BDInfoSettings.cs b/BDInfo/BDInfoSettings.cs
deleted file mode 100644
index f4cb30016..000000000
--- a/BDInfo/BDInfoSettings.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-
-namespace BDInfo
-{
- class BDInfoSettings
- {
- public static bool GenerateStreamDiagnostics => true;
-
- public static bool EnableSSIF => true;
-
- public static bool AutosaveReport => false;
-
- public static bool GenerateFrameDataFile => false;
-
- public static bool FilterLoopingPlaylists => true;
-
- public static bool FilterShortPlaylists => false;
-
- public static int FilterShortPlaylistsValue => 0;
-
- public static bool UseImagePrefix => false;
-
- public static string UseImagePrefixValue => null;
-
- /// <summary>
- /// Setting this to false throws an IComparer error on some discs.
- /// </summary>
- public static bool KeepStreamOrder => true;
-
- public static bool GenerateTextSummary => false;
-
- public static string LastPath => string.Empty;
- }
-}
diff --git a/BDInfo/BDROM.cs b/BDInfo/BDROM.cs
deleted file mode 100644
index 6759ed55a..000000000
--- a/BDInfo/BDROM.cs
+++ /dev/null
@@ -1,456 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Model.IO;
-
-namespace BDInfo
-{
- public class BDROM
- {
- public FileSystemMetadata DirectoryRoot = null;
- public FileSystemMetadata DirectoryBDMV = null;
- public FileSystemMetadata DirectoryBDJO = null;
- public FileSystemMetadata DirectoryCLIPINF = null;
- public FileSystemMetadata DirectoryPLAYLIST = null;
- public FileSystemMetadata DirectorySNP = null;
- public FileSystemMetadata DirectorySSIF = null;
- public FileSystemMetadata DirectorySTREAM = null;
-
- public string VolumeLabel = null;
- public ulong Size = 0;
- public bool IsBDPlus = false;
- public bool IsBDJava = false;
- public bool IsDBOX = false;
- public bool IsPSP = false;
- public bool Is3D = false;
- public bool Is50Hz = false;
-
- private readonly IFileSystem _fileSystem;
-
- public Dictionary<string, TSPlaylistFile> PlaylistFiles =
- new Dictionary<string, TSPlaylistFile>();
- public Dictionary<string, TSStreamClipFile> StreamClipFiles =
- new Dictionary<string, TSStreamClipFile>();
- public Dictionary<string, TSStreamFile> StreamFiles =
- new Dictionary<string, TSStreamFile>();
- public Dictionary<string, TSInterleavedFile> InterleavedFiles =
- new Dictionary<string, TSInterleavedFile>();
-
- public delegate bool OnStreamClipFileScanError(
- TSStreamClipFile streamClipFile, Exception ex);
-
- public event OnStreamClipFileScanError StreamClipFileScanError;
-
- public delegate bool OnStreamFileScanError(
- TSStreamFile streamClipFile, Exception ex);
-
- public event OnStreamFileScanError StreamFileScanError;
-
- public delegate bool OnPlaylistFileScanError(
- TSPlaylistFile playlistFile, Exception ex);
-
- public event OnPlaylistFileScanError PlaylistFileScanError;
-
- public BDROM(string path, IFileSystem fileSystem)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- _fileSystem = fileSystem;
- //
- // Locate BDMV directories.
- //
-
- DirectoryBDMV =
- GetDirectoryBDMV(path);
-
- if (DirectoryBDMV == null)
- {
- throw new Exception("Unable to locate BD structure.");
- }
-
- DirectoryRoot =
- _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(DirectoryBDMV.FullName));
- DirectoryBDJO =
- GetDirectory("BDJO", DirectoryBDMV, 0);
- DirectoryCLIPINF =
- GetDirectory("CLIPINF", DirectoryBDMV, 0);
- DirectoryPLAYLIST =
- GetDirectory("PLAYLIST", DirectoryBDMV, 0);
- DirectorySNP =
- GetDirectory("SNP", DirectoryRoot, 0);
- DirectorySTREAM =
- GetDirectory("STREAM", DirectoryBDMV, 0);
- DirectorySSIF =
- GetDirectory("SSIF", DirectorySTREAM, 0);
-
- if (DirectoryCLIPINF == null
- || DirectoryPLAYLIST == null)
- {
- throw new Exception("Unable to locate BD structure.");
- }
-
- //
- // Initialize basic disc properties.
- //
-
- VolumeLabel = GetVolumeLabel(DirectoryRoot);
- Size = (ulong)GetDirectorySize(DirectoryRoot);
-
- if (null != GetDirectory("BDSVM", DirectoryRoot, 0))
- {
- IsBDPlus = true;
- }
- if (null != GetDirectory("SLYVM", DirectoryRoot, 0))
- {
- IsBDPlus = true;
- }
- if (null != GetDirectory("ANYVM", DirectoryRoot, 0))
- {
- IsBDPlus = true;
- }
-
- if (DirectoryBDJO != null &&
- _fileSystem.GetFilePaths(DirectoryBDJO.FullName).Any())
- {
- IsBDJava = true;
- }
-
- if (DirectorySNP != null &&
- GetFilePaths(DirectorySNP.FullName, ".mnv").Any())
- {
- IsPSP = true;
- }
-
- if (DirectorySSIF != null &&
- _fileSystem.GetFilePaths(DirectorySSIF.FullName).Any())
- {
- Is3D = true;
- }
-
- if (File.Exists(Path.Combine(DirectoryRoot.FullName, "FilmIndex.xml")))
- {
- IsDBOX = true;
- }
-
- //
- // Initialize file lists.
- //
-
- if (DirectoryPLAYLIST != null)
- {
- FileSystemMetadata[] files = GetFiles(DirectoryPLAYLIST.FullName, ".mpls").ToArray();
- foreach (var file in files)
- {
- PlaylistFiles.Add(
- file.Name.ToUpper(), new TSPlaylistFile(this, file));
- }
- }
-
- if (DirectorySTREAM != null)
- {
- FileSystemMetadata[] files = GetFiles(DirectorySTREAM.FullName, ".m2ts").ToArray();
- foreach (var file in files)
- {
- StreamFiles.Add(
- file.Name.ToUpper(), new TSStreamFile(file, _fileSystem));
- }
- }
-
- if (DirectoryCLIPINF != null)
- {
- FileSystemMetadata[] files = GetFiles(DirectoryCLIPINF.FullName, ".clpi").ToArray();
- foreach (var file in files)
- {
- StreamClipFiles.Add(
- file.Name.ToUpper(), new TSStreamClipFile(file));
- }
- }
-
- if (DirectorySSIF != null)
- {
- FileSystemMetadata[] files = GetFiles(DirectorySSIF.FullName, ".ssif").ToArray();
- foreach (var file in files)
- {
- InterleavedFiles.Add(
- file.Name.ToUpper(), new TSInterleavedFile(file));
- }
- }
- }
-
- private IEnumerable<FileSystemMetadata> GetFiles(string path, string extension)
- {
- return _fileSystem.GetFiles(path, new[] { extension }, false, false);
- }
-
- private IEnumerable<string> GetFilePaths(string path, string extension)
- {
- return _fileSystem.GetFilePaths(path, new[] { extension }, false, false);
- }
-
- public void Scan()
- {
- var errorStreamClipFiles = new List<TSStreamClipFile>();
- foreach (var streamClipFile in StreamClipFiles.Values)
- {
- try
- {
- streamClipFile.Scan();
- }
- catch (Exception ex)
- {
- errorStreamClipFiles.Add(streamClipFile);
- if (StreamClipFileScanError != null)
- {
- if (StreamClipFileScanError(streamClipFile, ex))
- {
- continue;
- }
- else
- {
- break;
- }
- }
- else throw;
- }
- }
-
- foreach (var streamFile in StreamFiles.Values)
- {
- string ssifName = Path.GetFileNameWithoutExtension(streamFile.Name) + ".SSIF";
- if (InterleavedFiles.ContainsKey(ssifName))
- {
- streamFile.InterleavedFile = InterleavedFiles[ssifName];
- }
- }
-
- TSStreamFile[] streamFiles = new TSStreamFile[StreamFiles.Count];
- StreamFiles.Values.CopyTo(streamFiles, 0);
- Array.Sort(streamFiles, CompareStreamFiles);
-
- var errorPlaylistFiles = new List<TSPlaylistFile>();
- foreach (var playlistFile in PlaylistFiles.Values)
- {
- try
- {
- playlistFile.Scan(StreamFiles, StreamClipFiles);
- }
- catch (Exception ex)
- {
- errorPlaylistFiles.Add(playlistFile);
- if (PlaylistFileScanError != null)
- {
- if (PlaylistFileScanError(playlistFile, ex))
- {
- continue;
- }
- else
- {
- break;
- }
- }
- else throw;
- }
- }
-
- var errorStreamFiles = new List<TSStreamFile>();
- foreach (var streamFile in streamFiles)
- {
- try
- {
- var playlists = new List<TSPlaylistFile>();
- foreach (var playlist in PlaylistFiles.Values)
- {
- foreach (var streamClip in playlist.StreamClips)
- {
- if (streamClip.Name == streamFile.Name)
- {
- playlists.Add(playlist);
- break;
- }
- }
- }
- streamFile.Scan(playlists, false);
- }
- catch (Exception ex)
- {
- errorStreamFiles.Add(streamFile);
- if (StreamFileScanError != null)
- {
- if (StreamFileScanError(streamFile, ex))
- {
- continue;
- }
- else
- {
- break;
- }
- }
- else throw;
- }
- }
-
- foreach (var playlistFile in PlaylistFiles.Values)
- {
- playlistFile.Initialize();
- if (!Is50Hz)
- {
- foreach (var videoStream in playlistFile.VideoStreams)
- {
- if (videoStream.FrameRate == TSFrameRate.FRAMERATE_25 ||
- videoStream.FrameRate == TSFrameRate.FRAMERATE_50)
- {
- Is50Hz = true;
- }
- }
- }
- }
- }
-
- private FileSystemMetadata GetDirectoryBDMV(
- string path)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- FileSystemMetadata dir = _fileSystem.GetDirectoryInfo(path);
-
- while (dir != null)
- {
- if (string.Equals(dir.Name, "BDMV", StringComparison.OrdinalIgnoreCase))
- {
- return dir;
- }
- var parentFolder = Path.GetDirectoryName(dir.FullName);
- if (string.IsNullOrEmpty(parentFolder))
- {
- dir = null;
- }
- else
- {
- dir = _fileSystem.GetDirectoryInfo(parentFolder);
- }
- }
-
- return GetDirectory("BDMV", _fileSystem.GetDirectoryInfo(path), 0);
- }
-
- private FileSystemMetadata GetDirectory(
- string name,
- FileSystemMetadata dir,
- int searchDepth)
- {
- if (dir != null)
- {
- FileSystemMetadata[] children = _fileSystem.GetDirectories(dir.FullName).ToArray();
- foreach (var child in children)
- {
- if (string.Equals(child.Name, name, StringComparison.OrdinalIgnoreCase))
- {
- return child;
- }
- }
- if (searchDepth > 0)
- {
- foreach (var child in children)
- {
- GetDirectory(
- name, child, searchDepth - 1);
- }
- }
- }
- return null;
- }
-
- private long GetDirectorySize(FileSystemMetadata directoryInfo)
- {
- long size = 0;
-
- //if (!ExcludeDirs.Contains(directoryInfo.Name.ToUpper())) // TODO: Keep?
- {
- FileSystemMetadata[] pathFiles = _fileSystem.GetFiles(directoryInfo.FullName).ToArray();
- foreach (var pathFile in pathFiles)
- {
- if (pathFile.Extension.ToUpper() == ".SSIF")
- {
- continue;
- }
- size += pathFile.Length;
- }
-
- FileSystemMetadata[] pathChildren = _fileSystem.GetDirectories(directoryInfo.FullName).ToArray();
- foreach (var pathChild in pathChildren)
- {
- size += GetDirectorySize(pathChild);
- }
- }
-
- return size;
- }
-
- private string GetVolumeLabel(FileSystemMetadata dir)
- {
- return dir.Name;
- }
-
- public int CompareStreamFiles(
- TSStreamFile x,
- TSStreamFile y)
- {
- // TODO: Use interleaved file sizes
-
- if ((x == null || x.FileInfo == null) && (y == null || y.FileInfo == null))
- {
- return 0;
- }
- else if ((x == null || x.FileInfo == null) && (y != null && y.FileInfo != null))
- {
- return 1;
- }
- else if ((x != null || x.FileInfo != null) && (y == null || y.FileInfo == null))
- {
- return -1;
- }
- else
- {
- if (x.FileInfo.Length > y.FileInfo.Length)
- {
- return 1;
- }
- else if (y.FileInfo.Length > x.FileInfo.Length)
- {
- return -1;
- }
- else
- {
- return 0;
- }
- }
- }
-
- }
-}
diff --git a/BDInfo/LanguageCodes.cs b/BDInfo/LanguageCodes.cs
deleted file mode 100644
index ab2693ffb..000000000
--- a/BDInfo/LanguageCodes.cs
+++ /dev/null
@@ -1,493 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class LanguageCodes
- {
- public static string GetName(string code)
- {
- switch (code)
- {
- case "abk": return "Abkhazian";
- case "ace": return "Achinese";
- case "ach": return "Acoli";
- case "ada": return "Adangme";
- case "aar": return "Afar";
- case "afh": return "Afrihili";
- case "afr": return "Afrikaans";
- case "afa": return "Afro-Asiatic (Other)";
- case "aka": return "Akan";
- case "akk": return "Akkadian";
- case "alb": return "Albanian";
- case "sqi": return "Albanian";
- case "ale": return "Aleut";
- case "alg": return "Algonquian languages";
- case "tut": return "Altaic (Other)";
- case "amh": return "Amharic";
- case "apa": return "Apache languages";
- case "ara": return "Arabic";
- case "arc": return "Aramaic";
- case "arp": return "Arapaho";
- case "arn": return "Araucanian";
- case "arw": return "Arawak";
- case "arm": return "Armenian";
- case "hye": return "Armenian";
- case "art": return "Artificial (Other)";
- case "asm": return "Assamese";
- case "ath": return "Athapascan languages";
- case "aus": return "Australian languages";
- case "map": return "Austronesian (Other)";
- case "ava": return "Avaric";
- case "ave": return "Avestan";
- case "awa": return "Awadhi";
- case "aym": return "Aymara";
- case "aze": return "Azerbaijani";
- case "ban": return "Balinese";
- case "bat": return "Baltic (Other)";
- case "bal": return "Baluchi";
- case "bam": return "Bambara";
- case "bai": return "Bamileke languages";
- case "bad": return "Banda";
- case "bnt": return "Bantu (Other)";
- case "bas": return "Basa";
- case "bak": return "Bashkir";
- case "baq": return "Basque";
- case "eus": return "Basque";
- case "btk": return "Batak (Indonesia)";
- case "bej": return "Beja";
- case "bel": return "Belarusian";
- case "bem": return "Bemba";
- case "ben": return "Bengali";
- case "ber": return "Berber (Other)";
- case "bho": return "Bhojpuri";
- case "bih": return "Bihari";
- case "bik": return "Bikol";
- case "bin": return "Bini";
- case "bis": return "Bislama";
- case "bos": return "Bosnian";
- case "bra": return "Braj";
- case "bre": return "Breton";
- case "bug": return "Buginese";
- case "bul": return "Bulgarian";
- case "bua": return "Buriat";
- case "bur": return "Burmese";
- case "mya": return "Burmese";
- case "cad": return "Caddo";
- case "car": return "Carib";
- case "cat": return "Catalan";
- case "cau": return "Caucasian (Other)";
- case "ceb": return "Cebuano";
- case "cel": return "Celtic (Other)";
- case "cai": return "Central American Indian (Other)";
- case "chg": return "Chagatai";
- case "cmc": return "Chamic languages";
- case "cha": return "Chamorro";
- case "che": return "Chechen";
- case "chr": return "Cherokee";
- case "chy": return "Cheyenne";
- case "chb": return "Chibcha";
- case "chi": return "Chinese";
- case "zho": return "Chinese";
- case "chn": return "Chinook jargon";
- case "chp": return "Chipewyan";
- case "cho": return "Choctaw";
- case "chu": return "Church Slavic";
- case "chk": return "Chuukese";
- case "chv": return "Chuvash";
- case "cop": return "Coptic";
- case "cor": return "Cornish";
- case "cos": return "Corsican";
- case "cre": return "Cree";
- case "mus": return "Creek";
- case "crp": return "Creoles and pidgins (Other)";
- case "cpe": return "Creoles and pidgins,";
- case "cpf": return "Creoles and pidgins,";
- case "cpp": return "Creoles and pidgins,";
- case "scr": return "Croatian";
- case "hrv": return "Croatian";
- case "cus": return "Cushitic (Other)";
- case "cze": return "Czech";
- case "ces": return "Czech";
- case "dak": return "Dakota";
- case "dan": return "Danish";
- case "day": return "Dayak";
- case "del": return "Delaware";
- case "din": return "Dinka";
- case "div": return "Divehi";
- case "doi": return "Dogri";
- case "dgr": return "Dogrib";
- case "dra": return "Dravidian (Other)";
- case "dua": return "Duala";
- case "dut": return "Dutch";
- case "nld": return "Dutch";
- case "dum": return "Dutch, Middle (ca. 1050-1350)";
- case "dyu": return "Dyula";
- case "dzo": return "Dzongkha";
- case "efi": return "Efik";
- case "egy": return "Egyptian (Ancient)";
- case "eka": return "Ekajuk";
- case "elx": return "Elamite";
- case "eng": return "English";
- case "enm": return "English, Middle (1100-1500)";
- case "ang": return "English, Old (ca.450-1100)";
- case "epo": return "Esperanto";
- case "est": return "Estonian";
- case "ewe": return "Ewe";
- case "ewo": return "Ewondo";
- case "fan": return "Fang";
- case "fat": return "Fanti";
- case "fao": return "Faroese";
- case "fij": return "Fijian";
- case "fin": return "Finnish";
- case "fiu": return "Finno-Ugrian (Other)";
- case "fon": return "Fon";
- case "fre": return "French";
- case "fra": return "French";
- case "frm": return "French, Middle (ca.1400-1600)";
- case "fro": return "French, Old (842-ca.1400)";
- case "fry": return "Frisian";
- case "fur": return "Friulian";
- case "ful": return "Fulah";
- case "gaa": return "Ga";
- case "glg": return "Gallegan";
- case "lug": return "Ganda";
- case "gay": return "Gayo";
- case "gba": return "Gbaya";
- case "gez": return "Geez";
- case "geo": return "Georgian";
- case "kat": return "Georgian";
- case "ger": return "German";
- case "deu": return "German";
- case "nds": return "Saxon";
- case "gmh": return "German, Middle High (ca.1050-1500)";
- case "goh": return "German, Old High (ca.750-1050)";
- case "gem": return "Germanic (Other)";
- case "gil": return "Gilbertese";
- case "gon": return "Gondi";
- case "gor": return "Gorontalo";
- case "got": return "Gothic";
- case "grb": return "Grebo";
- case "grc": return "Greek, Ancient (to 1453)";
- case "gre": return "Greek";
- case "ell": return "Greek";
- case "grn": return "Guarani";
- case "guj": return "Gujarati";
- case "gwi": return "Gwich´in";
- case "hai": return "Haida";
- case "hau": return "Hausa";
- case "haw": return "Hawaiian";
- case "heb": return "Hebrew";
- case "her": return "Herero";
- case "hil": return "Hiligaynon";
- case "him": return "Himachali";
- case "hin": return "Hindi";
- case "hmo": return "Hiri Motu";
- case "hit": return "Hittite";
- case "hmn": return "Hmong";
- case "hun": return "Hungarian";
- case "hup": return "Hupa";
- case "iba": return "Iban";
- case "ice": return "Icelandic";
- case "isl": return "Icelandic";
- case "ibo": return "Igbo";
- case "ijo": return "Ijo";
- case "ilo": return "Iloko";
- case "inc": return "Indic (Other)";
- case "ine": return "Indo-European (Other)";
- case "ind": return "Indonesian";
- case "ina": return "Interlingua (International";
- case "ile": return "Interlingue";
- case "iku": return "Inuktitut";
- case "ipk": return "Inupiaq";
- case "ira": return "Iranian (Other)";
- case "gle": return "Irish";
- case "mga": return "Irish, Middle (900-1200)";
- case "sga": return "Irish, Old (to 900)";
- case "iro": return "Iroquoian languages";
- case "ita": return "Italian";
- case "jpn": return "Japanese";
- case "jav": return "Javanese";
- case "jrb": return "Judeo-Arabic";
- case "jpr": return "Judeo-Persian";
- case "kab": return "Kabyle";
- case "kac": return "Kachin";
- case "kal": return "Kalaallisut";
- case "kam": return "Kamba";
- case "kan": return "Kannada";
- case "kau": return "Kanuri";
- case "kaa": return "Kara-Kalpak";
- case "kar": return "Karen";
- case "kas": return "Kashmiri";
- case "kaw": return "Kawi";
- case "kaz": return "Kazakh";
- case "kha": return "Khasi";
- case "khm": return "Khmer";
- case "khi": return "Khoisan (Other)";
- case "kho": return "Khotanese";
- case "kik": return "Kikuyu";
- case "kmb": return "Kimbundu";
- case "kin": return "Kinyarwanda";
- case "kir": return "Kirghiz";
- case "kom": return "Komi";
- case "kon": return "Kongo";
- case "kok": return "Konkani";
- case "kor": return "Korean";
- case "kos": return "Kosraean";
- case "kpe": return "Kpelle";
- case "kro": return "Kru";
- case "kua": return "Kuanyama";
- case "kum": return "Kumyk";
- case "kur": return "Kurdish";
- case "kru": return "Kurukh";
- case "kut": return "Kutenai";
- case "lad": return "Ladino";
- case "lah": return "Lahnda";
- case "lam": return "Lamba";
- case "lao": return "Lao";
- case "lat": return "Latin";
- case "lav": return "Latvian";
- case "ltz": return "Letzeburgesch";
- case "lez": return "Lezghian";
- case "lin": return "Lingala";
- case "lit": return "Lithuanian";
- case "loz": return "Lozi";
- case "lub": return "Luba-Katanga";
- case "lua": return "Luba-Lulua";
- case "lui": return "Luiseno";
- case "lun": return "Lunda";
- case "luo": return "Luo (Kenya and Tanzania)";
- case "lus": return "Lushai";
- case "mac": return "Macedonian";
- case "mkd": return "Macedonian";
- case "mad": return "Madurese";
- case "mag": return "Magahi";
- case "mai": return "Maithili";
- case "mak": return "Makasar";
- case "mlg": return "Malagasy";
- case "may": return "Malay";
- case "msa": return "Malay";
- case "mal": return "Malayalam";
- case "mlt": return "Maltese";
- case "mnc": return "Manchu";
- case "mdr": return "Mandar";
- case "man": return "Mandingo";
- case "mni": return "Manipuri";
- case "mno": return "Manobo languages";
- case "glv": return "Manx";
- case "mao": return "Maori";
- case "mri": return "Maori";
- case "mar": return "Marathi";
- case "chm": return "Mari";
- case "mah": return "Marshall";
- case "mwr": return "Marwari";
- case "mas": return "Masai";
- case "myn": return "Mayan languages";
- case "men": return "Mende";
- case "mic": return "Micmac";
- case "min": return "Minangkabau";
- case "mis": return "Miscellaneous languages";
- case "moh": return "Mohawk";
- case "mol": return "Moldavian";
- case "mkh": return "Mon-Khmer (Other)";
- case "lol": return "Mongo";
- case "mon": return "Mongolian";
- case "mos": return "Mossi";
- case "mul": return "Multiple languages";
- case "mun": return "Munda languages";
- case "nah": return "Nahuatl";
- case "nau": return "Nauru";
- case "nav": return "Navajo";
- case "nde": return "Ndebele, North";
- case "nbl": return "Ndebele, South";
- case "ndo": return "Ndonga";
- case "nep": return "Nepali";
- case "new": return "Newari";
- case "nia": return "Nias";
- case "nic": return "Niger-Kordofanian (Other)";
- case "ssa": return "Nilo-Saharan (Other)";
- case "niu": return "Niuean";
- case "non": return "Norse, Old";
- case "nai": return "North American Indian (Other)";
- case "sme": return "Northern Sami";
- case "nor": return "Norwegian";
- case "nob": return "Norwegian Bokmål";
- case "nno": return "Norwegian Nynorsk";
- case "nub": return "Nubian languages";
- case "nym": return "Nyamwezi";
- case "nya": return "Nyanja";
- case "nyn": return "Nyankole";
- case "nyo": return "Nyoro";
- case "nzi": return "Nzima";
- case "oci": return "Occitan";
- case "oji": return "Ojibwa";
- case "ori": return "Oriya";
- case "orm": return "Oromo";
- case "osa": return "Osage";
- case "oss": return "Ossetian";
- case "oto": return "Otomian languages";
- case "pal": return "Pahlavi";
- case "pau": return "Palauan";
- case "pli": return "Pali";
- case "pam": return "Pampanga";
- case "pag": return "Pangasinan";
- case "pan": return "Panjabi";
- case "pap": return "Papiamento";
- case "paa": return "Papuan (Other)";
- case "per": return "Persian";
- case "fas": return "Persian";
- case "peo": return "Persian, Old (ca.600-400 B.C.)";
- case "phi": return "Philippine (Other)";
- case "phn": return "Phoenician";
- case "pon": return "Pohnpeian";
- case "pol": return "Polish";
- case "por": return "Portuguese";
- case "pra": return "Prakrit languages";
- case "pro": return "Provençal";
- case "pus": return "Pushto";
- case "que": return "Quechua";
- case "roh": return "Raeto-Romance";
- case "raj": return "Rajasthani";
- case "rap": return "Rapanui";
- case "rar": return "Rarotongan";
- case "roa": return "Romance (Other)";
- case "rum": return "Romanian";
- case "ron": return "Romanian";
- case "rom": return "Romany";
- case "run": return "Rundi";
- case "rus": return "Russian";
- case "sal": return "Salishan languages";
- case "sam": return "Samaritan Aramaic";
- case "smi": return "Sami languages (Other)";
- case "smo": return "Samoan";
- case "sad": return "Sandawe";
- case "sag": return "Sango";
- case "san": return "Sanskrit";
- case "sat": return "Santali";
- case "srd": return "Sardinian";
- case "sas": return "Sasak";
- case "sco": return "Scots";
- case "gla": return "Gaelic";
- case "sel": return "Selkup";
- case "sem": return "Semitic (Other)";
- case "scc": return "Serbian";
- case "srp": return "Serbian";
- case "srr": return "Serer";
- case "shn": return "Shan";
- case "sna": return "Shona";
- case "sid": return "Sidamo";
- case "sgn": return "Sign languages";
- case "bla": return "Siksika";
- case "snd": return "Sindhi";
- case "sin": return "Sinhalese";
- case "sit": return "Sino-Tibetan (Other)";
- case "sio": return "Siouan languages";
- case "den": return "Slave (Athapascan)";
- case "sla": return "Slavic (Other)";
- case "slo": return "Slovak";
- case "slk": return "Slovak";
- case "slv": return "Slovenian";
- case "sog": return "Sogdian";
- case "som": return "Somali";
- case "son": return "Songhai";
- case "snk": return "Soninke";
- case "wen": return "Sorbian languages";
- case "nso": return "Sotho, Northern";
- case "sot": return "Sotho, Southern";
- case "sai": return "South American Indian (Other)";
- case "spa": return "Spanish";
- case "suk": return "Sukuma";
- case "sux": return "Sumerian";
- case "sun": return "Sundanese";
- case "sus": return "Susu";
- case "swa": return "Swahili";
- case "ssw": return "Swati";
- case "swe": return "Swedish";
- case "syr": return "Syriac";
- case "tgl": return "Tagalog";
- case "tah": return "Tahitian";
- case "tai": return "Tai (Other)";
- case "tgk": return "Tajik";
- case "tmh": return "Tamashek";
- case "tam": return "Tamil";
- case "tat": return "Tatar";
- case "tel": return "Telugu";
- case "ter": return "Tereno";
- case "tet": return "Tetum";
- case "tha": return "Thai";
- case "tib": return "Tibetan";
- case "bod": return "Tibetan";
- case "tig": return "Tigre";
- case "tir": return "Tigrinya";
- case "tem": return "Timne";
- case "tiv": return "Tiv";
- case "tli": return "Tlingit";
- case "tpi": return "Tok Pisin";
- case "tkl": return "Tokelau";
- case "tog": return "Tonga (Nyasa)";
- case "ton": return "Tonga (Tonga Islands)";
- case "tsi": return "Tsimshian";
- case "tso": return "Tsonga";
- case "tsn": return "Tswana";
- case "tum": return "Tumbuka";
- case "tur": return "Turkish";
- case "ota": return "Turkish, Ottoman (1500-1928)";
- case "tuk": return "Turkmen";
- case "tvl": return "Tuvalu";
- case "tyv": return "Tuvinian";
- case "twi": return "Twi";
- case "uga": return "Ugaritic";
- case "uig": return "Uighur";
- case "ukr": return "Ukrainian";
- case "umb": return "Umbundu";
- case "und": return "Undetermined";
- case "urd": return "Urdu";
- case "uzb": return "Uzbek";
- case "vai": return "Vai";
- case "ven": return "Venda";
- case "vie": return "Vietnamese";
- case "vol": return "Volapük";
- case "vot": return "Votic";
- case "wak": return "Wakashan languages";
- case "wal": return "Walamo";
- case "war": return "Waray";
- case "was": return "Washo";
- case "wel": return "Welsh";
- case "cym": return "Welsh";
- case "wol": return "Wolof";
- case "xho": return "Xhosa";
- case "sah": return "Yakut";
- case "yao": return "Yao";
- case "yap": return "Yapese";
- case "yid": return "Yiddish";
- case "yor": return "Yoruba";
- case "ypk": return "Yupik languages";
- case "znd": return "Zande";
- case "zap": return "Zapotec";
- case "zen": return "Zenaga";
- case "zha": return "Zhuang";
- case "zul": return "Zulu";
- case "zun": return "Zuni";
-
- default: return code;
- }
- }
- }
-}
diff --git a/BDInfo/Properties/AssemblyInfo.cs b/BDInfo/Properties/AssemblyInfo.cs
deleted file mode 100644
index 788cf7366..000000000
--- a/BDInfo/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("BDInfo")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2016 CinemaSquid. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/BDInfo/ReadMe.txt b/BDInfo/ReadMe.txt
deleted file mode 100644
index e70b0b66c..000000000
--- a/BDInfo/ReadMe.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-The source is taken from the BDRom folder of this project:
-
-http://www.cinemasquid.com/blu-ray/tools/bdinfo
-
-BDInfoSettings was taken from the FormSettings class, and changed so that the settings all return defaults.
diff --git a/BDInfo/TSCodecAC3.cs b/BDInfo/TSCodecAC3.cs
deleted file mode 100644
index 35d306a19..000000000
--- a/BDInfo/TSCodecAC3.cs
+++ /dev/null
@@ -1,309 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-#undef DEBUG
-using System.IO;
-
-namespace BDInfo
-{
- public abstract class TSCodecAC3
- {
- private static byte[] eac3_blocks = new byte[] { 1, 2, 3, 6 };
-
- public static void Scan(
- TSAudioStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- if (stream.IsInitialized) return;
-
- byte[] sync = buffer.ReadBytes(2);
- if (sync == null ||
- sync[0] != 0x0B ||
- sync[1] != 0x77)
- {
- return;
- }
-
- int sr_code = 0;
- int frame_size = 0;
- int frame_size_code = 0;
- int channel_mode = 0;
- int lfe_on = 0;
- int dial_norm = 0;
- int num_blocks = 0;
-
- byte[] hdr = buffer.ReadBytes(4);
- int bsid = (hdr[3] & 0xF8) >> 3;
- buffer.Seek(-4, SeekOrigin.Current);
- if (bsid <= 10)
- {
- byte[] crc = buffer.ReadBytes(2);
- sr_code = buffer.ReadBits(2);
- frame_size_code = buffer.ReadBits(6);
- bsid = buffer.ReadBits(5);
- int bsmod = buffer.ReadBits(3);
-
- channel_mode = buffer.ReadBits(3);
- int cmixlev = 0;
- if (((channel_mode & 0x1) > 0) && (channel_mode != 0x1))
- {
- cmixlev = buffer.ReadBits(2);
- }
- int surmixlev = 0;
- if ((channel_mode & 0x4) > 0)
- {
- surmixlev = buffer.ReadBits(2);
- }
- int dsurmod = 0;
- if (channel_mode == 0x2)
- {
- dsurmod = buffer.ReadBits(2);
- if (dsurmod == 0x2)
- {
- stream.AudioMode = TSAudioMode.Surround;
- }
- }
- lfe_on = buffer.ReadBits(1);
- dial_norm = buffer.ReadBits(5);
- int compr = 0;
- if (1 == buffer.ReadBits(1))
- {
- compr = buffer.ReadBits(8);
- }
- int langcod = 0;
- if (1 == buffer.ReadBits(1))
- {
- langcod = buffer.ReadBits(8);
- }
- int mixlevel = 0;
- int roomtyp = 0;
- if (1 == buffer.ReadBits(1))
- {
- mixlevel = buffer.ReadBits(5);
- roomtyp = buffer.ReadBits(2);
- }
- if (channel_mode == 0)
- {
- int dialnorm2 = buffer.ReadBits(5);
- int compr2 = 0;
- if (1 == buffer.ReadBits(1))
- {
- compr2 = buffer.ReadBits(8);
- }
- int langcod2 = 0;
- if (1 == buffer.ReadBits(1))
- {
- langcod2 = buffer.ReadBits(8);
- }
- int mixlevel2 = 0;
- int roomtyp2 = 0;
- if (1 == buffer.ReadBits(1))
- {
- mixlevel2 = buffer.ReadBits(5);
- roomtyp2 = buffer.ReadBits(2);
- }
- }
- int copyrightb = buffer.ReadBits(1);
- int origbs = buffer.ReadBits(1);
- if (bsid == 6)
- {
- if (1 == buffer.ReadBits(1))
- {
- int dmixmod = buffer.ReadBits(2);
- int ltrtcmixlev = buffer.ReadBits(3);
- int ltrtsurmixlev = buffer.ReadBits(3);
- int lorocmixlev = buffer.ReadBits(3);
- int lorosurmixlev = buffer.ReadBits(3);
- }
- if (1 == buffer.ReadBits(1))
- {
- int dsurexmod = buffer.ReadBits(2);
- int dheadphonmod = buffer.ReadBits(2);
- if (dheadphonmod == 0x2)
- {
- // TODO
- }
- int adconvtyp = buffer.ReadBits(1);
- int xbsi2 = buffer.ReadBits(8);
- int encinfo = buffer.ReadBits(1);
- if (dsurexmod == 2)
- {
- stream.AudioMode = TSAudioMode.Extended;
- }
- }
- }
- }
- else
- {
- int frame_type = buffer.ReadBits(2);
- int substreamid = buffer.ReadBits(3);
- frame_size = (buffer.ReadBits(11) + 1) << 1;
-
- sr_code = buffer.ReadBits(2);
- if (sr_code == 3)
- {
- sr_code = buffer.ReadBits(2);
- }
- else
- {
- num_blocks = buffer.ReadBits(2);
- }
- channel_mode = buffer.ReadBits(3);
- lfe_on = buffer.ReadBits(1);
- }
-
- switch (channel_mode)
- {
- case 0: // 1+1
- stream.ChannelCount = 2;
- if (stream.AudioMode == TSAudioMode.Unknown)
- {
- stream.AudioMode = TSAudioMode.DualMono;
- }
- break;
- case 1: // 1/0
- stream.ChannelCount = 1;
- break;
- case 2: // 2/0
- stream.ChannelCount = 2;
- if (stream.AudioMode == TSAudioMode.Unknown)
- {
- stream.AudioMode = TSAudioMode.Stereo;
- }
- break;
- case 3: // 3/0
- stream.ChannelCount = 3;
- break;
- case 4: // 2/1
- stream.ChannelCount = 3;
- break;
- case 5: // 3/1
- stream.ChannelCount = 4;
- break;
- case 6: // 2/2
- stream.ChannelCount = 4;
- break;
- case 7: // 3/2
- stream.ChannelCount = 5;
- break;
- default:
- stream.ChannelCount = 0;
- break;
- }
-
- switch (sr_code)
- {
- case 0:
- stream.SampleRate = 48000;
- break;
- case 1:
- stream.SampleRate = 44100;
- break;
- case 2:
- stream.SampleRate = 32000;
- break;
- default:
- stream.SampleRate = 0;
- break;
- }
-
- if (bsid <= 10)
- {
- switch (frame_size_code >> 1)
- {
- case 18:
- stream.BitRate = 640000;
- break;
- case 17:
- stream.BitRate = 576000;
- break;
- case 16:
- stream.BitRate = 512000;
- break;
- case 15:
- stream.BitRate = 448000;
- break;
- case 14:
- stream.BitRate = 384000;
- break;
- case 13:
- stream.BitRate = 320000;
- break;
- case 12:
- stream.BitRate = 256000;
- break;
- case 11:
- stream.BitRate = 224000;
- break;
- case 10:
- stream.BitRate = 192000;
- break;
- case 9:
- stream.BitRate = 160000;
- break;
- case 8:
- stream.BitRate = 128000;
- break;
- case 7:
- stream.BitRate = 112000;
- break;
- case 6:
- stream.BitRate = 96000;
- break;
- case 5:
- stream.BitRate = 80000;
- break;
- case 4:
- stream.BitRate = 64000;
- break;
- case 3:
- stream.BitRate = 56000;
- break;
- case 2:
- stream.BitRate = 48000;
- break;
- case 1:
- stream.BitRate = 40000;
- break;
- case 0:
- stream.BitRate = 32000;
- break;
- default:
- stream.BitRate = 0;
- break;
- }
- }
- else
- {
- stream.BitRate = (long)
- (4.0 * frame_size * stream.SampleRate / (num_blocks * 256));
- }
-
- stream.LFE = lfe_on;
- if (stream.StreamType != TSStreamType.AC3_PLUS_AUDIO &&
- stream.StreamType != TSStreamType.AC3_PLUS_SECONDARY_AUDIO)
- {
- stream.DialNorm = dial_norm - 31;
- }
- stream.IsVBR = false;
- stream.IsInitialized = true;
- }
- }
-}
diff --git a/BDInfo/TSCodecAVC.cs b/BDInfo/TSCodecAVC.cs
deleted file mode 100644
index 5833d169f..000000000
--- a/BDInfo/TSCodecAVC.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecAVC
- {
- public static void Scan(
- TSVideoStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- uint parse = 0;
- byte accessUnitDelimiterParse = 0;
- byte sequenceParameterSetParse = 0;
- string profile = null;
- string level = null;
- byte constraintSet0Flag = 0;
- byte constraintSet1Flag = 0;
- byte constraintSet2Flag = 0;
- byte constraintSet3Flag = 0;
-
- for (int i = 0; i < buffer.Length; i++)
- {
- parse = (parse << 8) + buffer.ReadByte();
-
- if (parse == 0x00000109)
- {
- accessUnitDelimiterParse = 1;
- }
- else if (accessUnitDelimiterParse > 0)
- {
- --accessUnitDelimiterParse;
- if (accessUnitDelimiterParse == 0)
- {
- switch ((parse & 0xFF) >> 5)
- {
- case 0: // I
- case 3: // SI
- case 5: // I, SI
- tag = "I";
- break;
-
- case 1: // I, P
- case 4: // SI, SP
- case 6: // I, SI, P, SP
- tag = "P";
- break;
-
- case 2: // I, P, B
- case 7: // I, SI, P, SP, B
- tag = "B";
- break;
- }
- if (stream.IsInitialized) return;
- }
- }
- else if (parse == 0x00000127 || parse == 0x00000167)
- {
- sequenceParameterSetParse = 3;
- }
- else if (sequenceParameterSetParse > 0)
- {
- --sequenceParameterSetParse;
- switch (sequenceParameterSetParse)
- {
- case 2:
- switch (parse & 0xFF)
- {
- case 66:
- profile = "Baseline Profile";
- break;
- case 77:
- profile = "Main Profile";
- break;
- case 88:
- profile = "Extended Profile";
- break;
- case 100:
- profile = "High Profile";
- break;
- case 110:
- profile = "High 10 Profile";
- break;
- case 122:
- profile = "High 4:2:2 Profile";
- break;
- case 144:
- profile = "High 4:4:4 Profile";
- break;
- default:
- profile = "Unknown Profile";
- break;
- }
- break;
-
- case 1:
- constraintSet0Flag = (byte)
- ((parse & 0x80) >> 7);
- constraintSet1Flag = (byte)
- ((parse & 0x40) >> 6);
- constraintSet2Flag = (byte)
- ((parse & 0x20) >> 5);
- constraintSet3Flag = (byte)
- ((parse & 0x10) >> 4);
- break;
-
- case 0:
- byte b = (byte)(parse & 0xFF);
- if (b == 11 && constraintSet3Flag == 1)
- {
- level = "1b";
- }
- else
- {
- level = string.Format(
- "{0:D}.{1:D}",
- b / 10, (b - ((b / 10) * 10)));
- }
- stream.EncodingProfile = string.Format(
- "{0} {1}", profile, level);
- stream.IsVBR = true;
- stream.IsInitialized = true;
- break;
- }
- }
- }
- return;
- }
- }
-}
diff --git a/BDInfo/TSCodecDTS.cs b/BDInfo/TSCodecDTS.cs
deleted file mode 100644
index ff94cb702..000000000
--- a/BDInfo/TSCodecDTS.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecDTS
- {
- private static int[] dca_sample_rates =
- {
- 0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0,
- 12000, 24000, 48000, 96000, 192000
- };
-
- private static int[] dca_bit_rates =
- {
- 32000, 56000, 64000, 96000, 112000, 128000,
- 192000, 224000, 256000, 320000, 384000,
- 448000, 512000, 576000, 640000, 768000,
- 896000, 1024000, 1152000, 1280000, 1344000,
- 1408000, 1411200, 1472000, 1509000, 1920000,
- 2048000, 3072000, 3840000, 1/*open*/, 2/*variable*/, 3/*lossless*/
- };
-
- private static int[] dca_channels =
- {
- 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8
- };
-
- private static int[] dca_bits_per_sample =
- {
- 16, 16, 20, 20, 0, 24, 24
- };
-
- public static void Scan(
- TSAudioStream stream,
- TSStreamBuffer buffer,
- long bitrate,
- ref string tag)
- {
- if (stream.IsInitialized) return;
-
- bool syncFound = false;
- uint sync = 0;
- for (int i = 0; i < buffer.Length; i++)
- {
- sync = (sync << 8) + buffer.ReadByte();
- if (sync == 0x7FFE8001)
- {
- syncFound = true;
- break;
- }
- }
- if (!syncFound) return;
-
- int frame_type = buffer.ReadBits(1);
- int samples_deficit = buffer.ReadBits(5);
- int crc_present = buffer.ReadBits(1);
- int sample_blocks = buffer.ReadBits(7);
- int frame_size = buffer.ReadBits(14);
- if (frame_size < 95)
- {
- return;
- }
- int amode = buffer.ReadBits(6);
- int sample_rate = buffer.ReadBits(4);
- if (sample_rate < 0 || sample_rate >= dca_sample_rates.Length)
- {
- return;
- }
- int bit_rate = buffer.ReadBits(5);
- if (bit_rate < 0 || bit_rate >= dca_bit_rates.Length)
- {
- return;
- }
- int downmix = buffer.ReadBits(1);
- int dynrange = buffer.ReadBits(1);
- int timestamp = buffer.ReadBits(1);
- int aux_data = buffer.ReadBits(1);
- int hdcd = buffer.ReadBits(1);
- int ext_descr = buffer.ReadBits(3);
- int ext_coding = buffer.ReadBits(1);
- int aspf = buffer.ReadBits(1);
- int lfe = buffer.ReadBits(2);
- int predictor_history = buffer.ReadBits(1);
- if (crc_present == 1)
- {
- int crc = buffer.ReadBits(16);
- }
- int multirate_inter = buffer.ReadBits(1);
- int version = buffer.ReadBits(4);
- int copy_history = buffer.ReadBits(2);
- int source_pcm_res = buffer.ReadBits(3);
- int front_sum = buffer.ReadBits(1);
- int surround_sum = buffer.ReadBits(1);
- int dialog_norm = buffer.ReadBits(4);
- if (source_pcm_res < 0 || source_pcm_res >= dca_bits_per_sample.Length)
- {
- return;
- }
- int subframes = buffer.ReadBits(4);
- int total_channels = buffer.ReadBits(3) + 1 + ext_coding;
-
- stream.SampleRate = dca_sample_rates[sample_rate];
- stream.ChannelCount = total_channels;
- stream.LFE = (lfe > 0 ? 1 : 0);
- stream.BitDepth = dca_bits_per_sample[source_pcm_res];
- stream.DialNorm = -dialog_norm;
- if ((source_pcm_res & 0x1) == 0x1)
- {
- stream.AudioMode = TSAudioMode.Extended;
- }
-
- stream.BitRate = (uint)dca_bit_rates[bit_rate];
- switch (stream.BitRate)
- {
- case 1:
- if (bitrate > 0)
- {
- stream.BitRate = bitrate;
- stream.IsVBR = false;
- stream.IsInitialized = true;
- }
- else
- {
- stream.BitRate = 0;
- }
- break;
-
- case 2:
- case 3:
- stream.IsVBR = true;
- stream.IsInitialized = true;
- break;
-
- default:
- stream.IsVBR = false;
- stream.IsInitialized = true;
- break;
- }
- }
- }
-}
diff --git a/BDInfo/TSCodecDTSHD.cs b/BDInfo/TSCodecDTSHD.cs
deleted file mode 100644
index 57a136d2d..000000000
--- a/BDInfo/TSCodecDTSHD.cs
+++ /dev/null
@@ -1,246 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecDTSHD
- {
- private static int[] SampleRates = new int[]
- { 0x1F40, 0x3E80, 0x7D00, 0x0FA00, 0x1F400, 0x5622, 0x0AC44, 0x15888, 0x2B110, 0x56220, 0x2EE0, 0x5DC0, 0x0BB80, 0x17700, 0x2EE00, 0x5DC00 };
-
- public static void Scan(
- TSAudioStream stream,
- TSStreamBuffer buffer,
- long bitrate,
- ref string tag)
- {
- if (stream.IsInitialized &&
- (stream.StreamType == TSStreamType.DTS_HD_SECONDARY_AUDIO ||
- (stream.CoreStream != null &&
- stream.CoreStream.IsInitialized))) return;
-
- bool syncFound = false;
- uint sync = 0;
- for (int i = 0; i < buffer.Length; i++)
- {
- sync = (sync << 8) + buffer.ReadByte();
- if (sync == 0x64582025)
- {
- syncFound = true;
- break;
- }
- }
-
- if (!syncFound)
- {
- tag = "CORE";
- if (stream.CoreStream == null)
- {
- stream.CoreStream = new TSAudioStream();
- stream.CoreStream.StreamType = TSStreamType.DTS_AUDIO;
- }
- if (!stream.CoreStream.IsInitialized)
- {
- buffer.BeginRead();
- TSCodecDTS.Scan(stream.CoreStream, buffer, bitrate, ref tag);
- }
- return;
- }
-
- tag = "HD";
- int temp1 = buffer.ReadBits(8);
- int nuSubStreamIndex = buffer.ReadBits(2);
- int nuExtSSHeaderSize = 0;
- int nuExtSSFSize = 0;
- int bBlownUpHeader = buffer.ReadBits(1);
- if (1 == bBlownUpHeader)
- {
- nuExtSSHeaderSize = buffer.ReadBits(12) + 1;
- nuExtSSFSize = buffer.ReadBits(20) + 1;
- }
- else
- {
- nuExtSSHeaderSize = buffer.ReadBits(8) + 1;
- nuExtSSFSize = buffer.ReadBits(16) + 1;
- }
- int nuNumAudioPresent = 1;
- int nuNumAssets = 1;
- int bStaticFieldsPresent = buffer.ReadBits(1);
- if (1 == bStaticFieldsPresent)
- {
- int nuRefClockCode = buffer.ReadBits(2);
- int nuExSSFrameDurationCode = buffer.ReadBits(3) + 1;
- long nuTimeStamp = 0;
- if (1 == buffer.ReadBits(1))
- {
- nuTimeStamp = (buffer.ReadBits(18) << 18) + buffer.ReadBits(18);
- }
- nuNumAudioPresent = buffer.ReadBits(3) + 1;
- nuNumAssets = buffer.ReadBits(3) + 1;
- int[] nuActiveExSSMask = new int[nuNumAudioPresent];
- for (int i = 0; i < nuNumAudioPresent; i++)
- {
- nuActiveExSSMask[i] = buffer.ReadBits(nuSubStreamIndex + 1); //?
- }
- for (int i = 0; i < nuNumAudioPresent; i++)
- {
- for (int j = 0; j < nuSubStreamIndex + 1; j++)
- {
- if (((j + 1) % 2) == 1)
- {
- int mask = buffer.ReadBits(8);
- }
- }
- }
- if (1 == buffer.ReadBits(1))
- {
- int nuMixMetadataAdjLevel = buffer.ReadBits(2);
- int nuBits4MixOutMask = buffer.ReadBits(2) * 4 + 4;
- int nuNumMixOutConfigs = buffer.ReadBits(2) + 1;
- int[] nuMixOutChMask = new int[nuNumMixOutConfigs];
- for (int i = 0; i < nuNumMixOutConfigs; i++)
- {
- nuMixOutChMask[i] = buffer.ReadBits(nuBits4MixOutMask);
- }
- }
- }
- int[] AssetSizes = new int[nuNumAssets];
- for (int i = 0; i < nuNumAssets; i++)
- {
- if (1 == bBlownUpHeader)
- {
- AssetSizes[i] = buffer.ReadBits(20) + 1;
- }
- else
- {
- AssetSizes[i] = buffer.ReadBits(16) + 1;
- }
- }
- for (int i = 0; i < nuNumAssets; i++)
- {
- long bufferPosition = buffer.Position;
- int nuAssetDescriptorFSIZE = buffer.ReadBits(9) + 1;
- int DescriptorDataForAssetIndex = buffer.ReadBits(3);
- if (1 == bStaticFieldsPresent)
- {
- int AssetTypeDescrPresent = buffer.ReadBits(1);
- if (1 == AssetTypeDescrPresent)
- {
- int AssetTypeDescriptor = buffer.ReadBits(4);
- }
- int LanguageDescrPresent = buffer.ReadBits(1);
- if (1 == LanguageDescrPresent)
- {
- int LanguageDescriptor = buffer.ReadBits(24);
- }
- int bInfoTextPresent = buffer.ReadBits(1);
- if (1 == bInfoTextPresent)
- {
- int nuInfoTextByteSize = buffer.ReadBits(10) + 1;
- int[] InfoText = new int[nuInfoTextByteSize];
- for (int j = 0; j < nuInfoTextByteSize; j++)
- {
- InfoText[j] = buffer.ReadBits(8);
- }
- }
- int nuBitResolution = buffer.ReadBits(5) + 1;
- int nuMaxSampleRate = buffer.ReadBits(4);
- int nuTotalNumChs = buffer.ReadBits(8) + 1;
- int bOne2OneMapChannels2Speakers = buffer.ReadBits(1);
- int nuSpkrActivityMask = 0;
- if (1 == bOne2OneMapChannels2Speakers)
- {
- int bEmbeddedStereoFlag = 0;
- if (nuTotalNumChs > 2)
- {
- bEmbeddedStereoFlag = buffer.ReadBits(1);
- }
- int bEmbeddedSixChFlag = 0;
- if (nuTotalNumChs > 6)
- {
- bEmbeddedSixChFlag = buffer.ReadBits(1);
- }
- int bSpkrMaskEnabled = buffer.ReadBits(1);
- int nuNumBits4SAMask = 0;
- if (1 == bSpkrMaskEnabled)
- {
- nuNumBits4SAMask = buffer.ReadBits(2);
- nuNumBits4SAMask = nuNumBits4SAMask * 4 + 4;
- nuSpkrActivityMask = buffer.ReadBits(nuNumBits4SAMask);
- }
- // TODO...
- }
- stream.SampleRate = SampleRates[nuMaxSampleRate];
- stream.BitDepth = nuBitResolution;
-
- stream.LFE = 0;
- if ((nuSpkrActivityMask & 0x8) == 0x8)
- {
- ++stream.LFE;
- }
- if ((nuSpkrActivityMask & 0x1000) == 0x1000)
- {
- ++stream.LFE;
- }
- stream.ChannelCount = nuTotalNumChs - stream.LFE;
- }
- if (nuNumAssets > 1)
- {
- // TODO...
- break;
- }
- }
-
- // TODO
- if (stream.CoreStream != null)
- {
- var coreStream = (TSAudioStream)stream.CoreStream;
- if (coreStream.AudioMode == TSAudioMode.Extended &&
- stream.ChannelCount == 5)
- {
- stream.AudioMode = TSAudioMode.Extended;
- }
- /*
- if (coreStream.DialNorm != 0)
- {
- stream.DialNorm = coreStream.DialNorm;
- }
- */
- }
-
- if (stream.StreamType == TSStreamType.DTS_HD_MASTER_AUDIO)
- {
- stream.IsVBR = true;
- stream.IsInitialized = true;
- }
- else if (bitrate > 0)
- {
- stream.IsVBR = false;
- stream.BitRate = bitrate;
- if (stream.CoreStream != null)
- {
- stream.BitRate += stream.CoreStream.BitRate;
- stream.IsInitialized = true;
- }
- stream.IsInitialized = (stream.BitRate > 0 ? true : false);
- }
- }
- }
-}
diff --git a/BDInfo/TSCodecLPCM.cs b/BDInfo/TSCodecLPCM.cs
deleted file mode 100644
index 5709d8689..000000000
--- a/BDInfo/TSCodecLPCM.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecLPCM
- {
- public static void Scan(
- TSAudioStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- if (stream.IsInitialized) return;
-
- byte[] header = buffer.ReadBytes(4);
- int flags = (header[2] << 8) + header[3];
-
- switch ((flags & 0xF000) >> 12)
- {
- case 1: // 1/0/0
- stream.ChannelCount = 1;
- stream.LFE = 0;
- break;
- case 3: // 2/0/0
- stream.ChannelCount = 2;
- stream.LFE = 0;
- break;
- case 4: // 3/0/0
- stream.ChannelCount = 3;
- stream.LFE = 0;
- break;
- case 5: // 2/1/0
- stream.ChannelCount = 3;
- stream.LFE = 0;
- break;
- case 6: // 3/1/0
- stream.ChannelCount = 4;
- stream.LFE = 0;
- break;
- case 7: // 2/2/0
- stream.ChannelCount = 4;
- stream.LFE = 0;
- break;
- case 8: // 3/2/0
- stream.ChannelCount = 5;
- stream.LFE = 0;
- break;
- case 9: // 3/2/1
- stream.ChannelCount = 5;
- stream.LFE = 1;
- break;
- case 10: // 3/4/0
- stream.ChannelCount = 7;
- stream.LFE = 0;
- break;
- case 11: // 3/4/1
- stream.ChannelCount = 7;
- stream.LFE = 1;
- break;
- default:
- stream.ChannelCount = 0;
- stream.LFE = 0;
- break;
- }
-
- switch ((flags & 0xC0) >> 6)
- {
- case 1:
- stream.BitDepth = 16;
- break;
- case 2:
- stream.BitDepth = 20;
- break;
- case 3:
- stream.BitDepth = 24;
- break;
- default:
- stream.BitDepth = 0;
- break;
- }
-
- switch ((flags & 0xF00) >> 8)
- {
- case 1:
- stream.SampleRate = 48000;
- break;
- case 4:
- stream.SampleRate = 96000;
- break;
- case 5:
- stream.SampleRate = 192000;
- break;
- default:
- stream.SampleRate = 0;
- break;
- }
-
- stream.BitRate = (uint)
- (stream.SampleRate * stream.BitDepth *
- (stream.ChannelCount + stream.LFE));
-
- stream.IsVBR = false;
- stream.IsInitialized = true;
- }
- }
-}
diff --git a/BDInfo/TSCodecMPEG2.cs b/BDInfo/TSCodecMPEG2.cs
deleted file mode 100644
index 8bcd07d02..000000000
--- a/BDInfo/TSCodecMPEG2.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-#undef DEBUG
-
-
-namespace BDInfo
-{
- public abstract class TSCodecMPEG2
- {
- public static void Scan(
- TSVideoStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- int parse = 0;
- int pictureParse = 0;
- int sequenceHeaderParse = 0;
- int extensionParse = 0;
- int sequenceExtensionParse = 0;
-
- for (int i = 0; i < buffer.Length; i++)
- {
- parse = (parse << 8) + buffer.ReadByte();
-
- if (parse == 0x00000100)
- {
- pictureParse = 2;
- }
- else if (parse == 0x000001B3)
- {
- sequenceHeaderParse = 7;
- }
- else if (sequenceHeaderParse > 0)
- {
- --sequenceHeaderParse;
- switch (sequenceHeaderParse)
- {
-#if DEBUG
- case 6:
- break;
-
- case 5:
- break;
-
- case 4:
- stream.Width =
- (int)((parse & 0xFFF000) >> 12);
- stream.Height =
- (int)(parse & 0xFFF);
- break;
-
- case 3:
- stream.AspectRatio =
- (TSAspectRatio)((parse & 0xF0) >> 4);
-
- switch ((parse & 0xF0) >> 4)
- {
- case 0: // Forbidden
- break;
- case 1: // Square
- break;
- case 2: // 4:3
- break;
- case 3: // 16:9
- break;
- case 4: // 2.21:1
- break;
- default: // Reserved
- break;
- }
-
- switch (parse & 0xF)
- {
- case 0: // Forbidden
- break;
- case 1: // 23.976
- stream.FrameRateEnumerator = 24000;
- stream.FrameRateDenominator = 1001;
- break;
- case 2: // 24
- stream.FrameRateEnumerator = 24000;
- stream.FrameRateDenominator = 1000;
- break;
- case 3: // 25
- stream.FrameRateEnumerator = 25000;
- stream.FrameRateDenominator = 1000;
- break;
- case 4: // 29.97
- stream.FrameRateEnumerator = 30000;
- stream.FrameRateDenominator = 1001;
- break;
- case 5: // 30
- stream.FrameRateEnumerator = 30000;
- stream.FrameRateDenominator = 1000;
- break;
- case 6: // 50
- stream.FrameRateEnumerator = 50000;
- stream.FrameRateDenominator = 1000;
- break;
- case 7: // 59.94
- stream.FrameRateEnumerator = 60000;
- stream.FrameRateDenominator = 1001;
- break;
- case 8: // 60
- stream.FrameRateEnumerator = 60000;
- stream.FrameRateDenominator = 1000;
- break;
- default: // Reserved
- stream.FrameRateEnumerator = 0;
- stream.FrameRateDenominator = 0;
- break;
- }
- break;
-
- case 2:
- break;
-
- case 1:
- break;
-#endif
-
- case 0:
-#if DEBUG
- stream.BitRate =
- (((parse & 0xFFFFC0) >> 6) * 200);
-#endif
- stream.IsVBR = true;
- stream.IsInitialized = true;
- break;
- }
- }
- else if (pictureParse > 0)
- {
- --pictureParse;
- if (pictureParse == 0)
- {
- switch ((parse & 0x38) >> 3)
- {
- case 1:
- tag = "I";
- break;
- case 2:
- tag = "P";
- break;
- case 3:
- tag = "B";
- break;
- default:
- break;
- }
- if (stream.IsInitialized) return;
- }
- }
- else if (parse == 0x000001B5)
- {
- extensionParse = 1;
- }
- else if (extensionParse > 0)
- {
- --extensionParse;
- if (extensionParse == 0)
- {
- if ((parse & 0xF0) == 0x10)
- {
- sequenceExtensionParse = 1;
- }
- }
- }
- else if (sequenceExtensionParse > 0)
- {
- --sequenceExtensionParse;
-#if DEBUG
- if (sequenceExtensionParse == 0)
- {
- uint sequenceExtension =
- ((parse & 0x8) >> 3);
- if (sequenceExtension == 0)
- {
- stream.IsInterlaced = true;
- }
- else
- {
- stream.IsInterlaced = false;
- }
- }
-#endif
- }
- }
- }
- }
-}
diff --git a/BDInfo/TSCodecMVC.cs b/BDInfo/TSCodecMVC.cs
deleted file mode 100644
index abff0c1b0..000000000
--- a/BDInfo/TSCodecMVC.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- // TODO: Do something more interesting here...
-
- public abstract class TSCodecMVC
- {
- public static void Scan(
- TSVideoStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- stream.IsVBR = true;
- stream.IsInitialized = true;
- }
- }
-}
diff --git a/BDInfo/TSCodecTrueHD.cs b/BDInfo/TSCodecTrueHD.cs
deleted file mode 100644
index 5e81e162c..000000000
--- a/BDInfo/TSCodecTrueHD.cs
+++ /dev/null
@@ -1,186 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecTrueHD
- {
- public static void Scan(
- TSAudioStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- if (stream.IsInitialized &&
- stream.CoreStream != null &&
- stream.CoreStream.IsInitialized) return;
-
- bool syncFound = false;
- uint sync = 0;
- for (int i = 0; i < buffer.Length; i++)
- {
- sync = (sync << 8) + buffer.ReadByte();
- if (sync == 0xF8726FBA)
- {
- syncFound = true;
- break;
- }
- }
-
- if (!syncFound)
- {
- tag = "CORE";
- if (stream.CoreStream == null)
- {
- stream.CoreStream = new TSAudioStream();
- stream.CoreStream.StreamType = TSStreamType.AC3_AUDIO;
- }
- if (!stream.CoreStream.IsInitialized)
- {
- buffer.BeginRead();
- TSCodecAC3.Scan(stream.CoreStream, buffer, ref tag);
- }
- return;
- }
-
- tag = "HD";
- int ratebits = buffer.ReadBits(4);
- if (ratebits != 0xF)
- {
- stream.SampleRate =
- (((ratebits & 8) > 0 ? 44100 : 48000) << (ratebits & 7));
- }
- int temp1 = buffer.ReadBits(8);
- int channels_thd_stream1 = buffer.ReadBits(5);
- int temp2 = buffer.ReadBits(2);
-
- stream.ChannelCount = 0;
- stream.LFE = 0;
- int c_LFE2 = buffer.ReadBits(1);
- if (c_LFE2 == 1)
- {
- stream.LFE += 1;
- }
- int c_Cvh = buffer.ReadBits(1);
- if (c_Cvh == 1)
- {
- stream.ChannelCount += 1;
- }
- int c_LRw = buffer.ReadBits(1);
- if (c_LRw == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_LRsd = buffer.ReadBits(1);
- if (c_LRsd == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_Ts = buffer.ReadBits(1);
- if (c_Ts == 1)
- {
- stream.ChannelCount += 1;
- }
- int c_Cs = buffer.ReadBits(1);
- if (c_Cs == 1)
- {
- stream.ChannelCount += 1;
- }
- int c_LRrs = buffer.ReadBits(1);
- if (c_LRrs == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_LRc = buffer.ReadBits(1);
- if (c_LRc == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_LRvh = buffer.ReadBits(1);
- if (c_LRvh == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_LRs = buffer.ReadBits(1);
- if (c_LRs == 1)
- {
- stream.ChannelCount += 2;
- }
- int c_LFE = buffer.ReadBits(1);
- if (c_LFE == 1)
- {
- stream.LFE += 1;
- }
- int c_C = buffer.ReadBits(1);
- if (c_C == 1)
- {
- stream.ChannelCount += 1;
- }
- int c_LR = buffer.ReadBits(1);
- if (c_LR == 1)
- {
- stream.ChannelCount += 2;
- }
-
- int access_unit_size = 40 << (ratebits & 7);
- int access_unit_size_pow2 = 64 << (ratebits & 7);
-
- int a1 = buffer.ReadBits(16);
- int a2 = buffer.ReadBits(16);
- int a3 = buffer.ReadBits(16);
-
- int is_vbr = buffer.ReadBits(1);
- int peak_bitrate = buffer.ReadBits(15);
- peak_bitrate = (peak_bitrate * stream.SampleRate) >> 4;
-
- double peak_bitdepth =
- (double)peak_bitrate /
- (stream.ChannelCount + stream.LFE) /
- stream.SampleRate;
- if (peak_bitdepth > 14)
- {
- stream.BitDepth = 24;
- }
- else
- {
- stream.BitDepth = 16;
- }
-
-#if DEBUG
- System.Diagnostics.Debug.WriteLine(string.Format(
- "{0}\t{1}\t{2:F2}",
- stream.PID, peak_bitrate, peak_bitdepth));
-#endif
- /*
- // TODO: Get THD dialnorm from metadata
- if (stream.CoreStream != null)
- {
- TSAudioStream coreStream = (TSAudioStream)stream.CoreStream;
- if (coreStream.DialNorm != 0)
- {
- stream.DialNorm = coreStream.DialNorm;
- }
- }
- */
-
- stream.IsVBR = true;
- stream.IsInitialized = true;
- }
- }
-}
diff --git a/BDInfo/TSCodecVC1.cs b/BDInfo/TSCodecVC1.cs
deleted file mode 100644
index e2fbbf692..000000000
--- a/BDInfo/TSCodecVC1.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-
-namespace BDInfo
-{
- public abstract class TSCodecVC1
- {
- public static void Scan(
- TSVideoStream stream,
- TSStreamBuffer buffer,
- ref string tag)
- {
- int parse = 0;
- byte frameHeaderParse = 0;
- byte sequenceHeaderParse = 0;
- bool isInterlaced = false;
-
- for (int i = 0; i < buffer.Length; i++)
- {
- parse = (parse << 8) + buffer.ReadByte();
-
- if (parse == 0x0000010D)
- {
- frameHeaderParse = 4;
- }
- else if (frameHeaderParse > 0)
- {
- --frameHeaderParse;
- if (frameHeaderParse == 0)
- {
- uint pictureType = 0;
- if (isInterlaced)
- {
- if ((parse & 0x80000000) == 0)
- {
- pictureType =
- (uint)((parse & 0x78000000) >> 13);
- }
- else
- {
- pictureType =
- (uint)((parse & 0x3c000000) >> 12);
- }
- }
- else
- {
- pictureType =
- (uint)((parse & 0xf0000000) >> 14);
- }
-
- if ((pictureType & 0x20000) == 0)
- {
- tag = "P";
- }
- else if ((pictureType & 0x10000) == 0)
- {
- tag = "B";
- }
- else if ((pictureType & 0x8000) == 0)
- {
- tag = "I";
- }
- else if ((pictureType & 0x4000) == 0)
- {
- tag = "BI";
- }
- else
- {
- tag = null;
- }
- if (stream.IsInitialized) return;
- }
- }
- else if (parse == 0x0000010F)
- {
- sequenceHeaderParse = 6;
- }
- else if (sequenceHeaderParse > 0)
- {
- --sequenceHeaderParse;
- switch (sequenceHeaderParse)
- {
- case 5:
- int profileLevel = ((parse & 0x38) >> 3);
- if (((parse & 0xC0) >> 6) == 3)
- {
- stream.EncodingProfile = string.Format(
- "Advanced Profile {0}", profileLevel);
- }
- else
- {
- stream.EncodingProfile = string.Format(
- "Main Profile {0}", profileLevel);
- }
- break;
-
- case 0:
- if (((parse & 0x40) >> 6) > 0)
- {
- isInterlaced = true;
- }
- else
- {
- isInterlaced = false;
- }
- break;
- }
- stream.IsVBR = true;
- stream.IsInitialized = true;
- }
- }
- }
- }
-}
diff --git a/BDInfo/TSInterleavedFile.cs b/BDInfo/TSInterleavedFile.cs
deleted file mode 100644
index 0f35cfb2a..000000000
--- a/BDInfo/TSInterleavedFile.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-using MediaBrowser.Model.IO;
-
-// TODO: Do more interesting things here...
-
-namespace BDInfo
-{
- public class TSInterleavedFile
- {
- public FileSystemMetadata FileInfo = null;
- public string Name = null;
-
- public TSInterleavedFile(FileSystemMetadata fileInfo)
- {
- FileInfo = fileInfo;
- Name = fileInfo.Name.ToUpper();
- }
- }
-}
diff --git a/BDInfo/TSPlaylistFile.cs b/BDInfo/TSPlaylistFile.cs
deleted file mode 100644
index 1cc629b1d..000000000
--- a/BDInfo/TSPlaylistFile.cs
+++ /dev/null
@@ -1,1282 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-#undef DEBUG
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using MediaBrowser.Model.IO;
-
-namespace BDInfo
-{
- public class TSPlaylistFile
- {
- private FileSystemMetadata FileInfo = null;
- public string FileType = null;
- public bool IsInitialized = false;
- public string Name = null;
- public BDROM BDROM = null;
- public bool HasHiddenTracks = false;
- public bool HasLoops = false;
- public bool IsCustom = false;
-
- public List<double> Chapters = new List<double>();
-
- public Dictionary<ushort, TSStream> Streams =
- new Dictionary<ushort, TSStream>();
- public Dictionary<ushort, TSStream> PlaylistStreams =
- new Dictionary<ushort, TSStream>();
- public List<TSStreamClip> StreamClips =
- new List<TSStreamClip>();
- public List<Dictionary<ushort, TSStream>> AngleStreams =
- new List<Dictionary<ushort, TSStream>>();
- public List<Dictionary<double, TSStreamClip>> AngleClips =
- new List<Dictionary<double, TSStreamClip>>();
- public int AngleCount = 0;
-
- public List<TSStream> SortedStreams =
- new List<TSStream>();
- public List<TSVideoStream> VideoStreams =
- new List<TSVideoStream>();
- public List<TSAudioStream> AudioStreams =
- new List<TSAudioStream>();
- public List<TSTextStream> TextStreams =
- new List<TSTextStream>();
- public List<TSGraphicsStream> GraphicsStreams =
- new List<TSGraphicsStream>();
-
- public TSPlaylistFile(BDROM bdrom,
- FileSystemMetadata fileInfo)
- {
- BDROM = bdrom;
- FileInfo = fileInfo;
- Name = fileInfo.Name.ToUpper();
- }
-
- public TSPlaylistFile(BDROM bdrom,
- string name,
- List<TSStreamClip> clips)
- {
- BDROM = bdrom;
- Name = name;
- IsCustom = true;
- foreach (var clip in clips)
- {
- var newClip = new TSStreamClip(
- clip.StreamFile, clip.StreamClipFile);
-
- newClip.Name = clip.Name;
- newClip.TimeIn = clip.TimeIn;
- newClip.TimeOut = clip.TimeOut;
- newClip.Length = newClip.TimeOut - newClip.TimeIn;
- newClip.RelativeTimeIn = TotalLength;
- newClip.RelativeTimeOut = newClip.RelativeTimeIn + newClip.Length;
- newClip.AngleIndex = clip.AngleIndex;
- newClip.Chapters.Add(clip.TimeIn);
- StreamClips.Add(newClip);
-
- if (newClip.AngleIndex > AngleCount)
- {
- AngleCount = newClip.AngleIndex;
- }
- if (newClip.AngleIndex == 0)
- {
- Chapters.Add(newClip.RelativeTimeIn);
- }
- }
- LoadStreamClips();
- IsInitialized = true;
- }
-
- public override string ToString()
- {
- return Name;
- }
-
- public ulong InterleavedFileSize
- {
- get
- {
- ulong size = 0;
- foreach (var clip in StreamClips)
- {
- size += clip.InterleavedFileSize;
- }
- return size;
- }
- }
- public ulong FileSize
- {
- get
- {
- ulong size = 0;
- foreach (var clip in StreamClips)
- {
- size += clip.FileSize;
- }
- return size;
- }
- }
- public double TotalLength
- {
- get
- {
- double length = 0;
- foreach (var clip in StreamClips)
- {
- if (clip.AngleIndex == 0)
- {
- length += clip.Length;
- }
- }
- return length;
- }
- }
-
- public double TotalAngleLength
- {
- get
- {
- double length = 0;
- foreach (var clip in StreamClips)
- {
- length += clip.Length;
- }
- return length;
- }
- }
-
- public ulong TotalSize
- {
- get
- {
- ulong size = 0;
- foreach (var clip in StreamClips)
- {
- if (clip.AngleIndex == 0)
- {
- size += clip.PacketSize;
- }
- }
- return size;
- }
- }
-
- public ulong TotalAngleSize
- {
- get
- {
- ulong size = 0;
- foreach (var clip in StreamClips)
- {
- size += clip.PacketSize;
- }
- return size;
- }
- }
-
- public ulong TotalBitRate
- {
- get
- {
- if (TotalLength > 0)
- {
- return (ulong)Math.Round(((TotalSize * 8.0) / TotalLength));
- }
- return 0;
- }
- }
-
- public ulong TotalAngleBitRate
- {
- get
- {
- if (TotalAngleLength > 0)
- {
- return (ulong)Math.Round(((TotalAngleSize * 8.0) / TotalAngleLength));
- }
- return 0;
- }
- }
-
- public void Scan(
- Dictionary<string, TSStreamFile> streamFiles,
- Dictionary<string, TSStreamClipFile> streamClipFiles)
- {
- Stream fileStream = null;
- BinaryReader fileReader = null;
-
- try
- {
- Streams.Clear();
- StreamClips.Clear();
-
- fileStream = File.OpenRead(FileInfo.FullName);
- fileReader = new BinaryReader(fileStream);
-
- byte[] data = new byte[fileStream.Length];
- int dataLength = fileReader.Read(data, 0, data.Length);
-
- int pos = 0;
-
- FileType = ReadString(data, 8, ref pos);
- if (FileType != "MPLS0100" && FileType != "MPLS0200")
- {
- throw new Exception(string.Format(
- "Playlist {0} has an unknown file type {1}.",
- FileInfo.Name, FileType));
- }
-
- int playlistOffset = ReadInt32(data, ref pos);
- int chaptersOffset = ReadInt32(data, ref pos);
- int extensionsOffset = ReadInt32(data, ref pos);
-
- pos = playlistOffset;
-
- int playlistLength = ReadInt32(data, ref pos);
- int playlistReserved = ReadInt16(data, ref pos);
- int itemCount = ReadInt16(data, ref pos);
- int subitemCount = ReadInt16(data, ref pos);
-
- var chapterClips = new List<TSStreamClip>();
- for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
- {
- int itemStart = pos;
- int itemLength = ReadInt16(data, ref pos);
- string itemName = ReadString(data, 5, ref pos);
- string itemType = ReadString(data, 4, ref pos);
-
- TSStreamFile streamFile = null;
- string streamFileName = string.Format(
- "{0}.M2TS", itemName);
- if (streamFiles.ContainsKey(streamFileName))
- {
- streamFile = streamFiles[streamFileName];
- }
- if (streamFile == null)
- {
- // Error condition
- }
-
- TSStreamClipFile streamClipFile = null;
- string streamClipFileName = string.Format(
- "{0}.CLPI", itemName);
- if (streamClipFiles.ContainsKey(streamClipFileName))
- {
- streamClipFile = streamClipFiles[streamClipFileName];
- }
- if (streamClipFile == null)
- {
- throw new Exception(string.Format(
- "Playlist {0} referenced missing file {1}.",
- FileInfo.Name, streamFileName));
- }
-
- pos += 1;
- int multiangle = (data[pos] >> 4) & 0x01;
- int condition = data[pos] & 0x0F;
- pos += 2;
-
- int inTime = ReadInt32(data, ref pos);
- if (inTime < 0) inTime &= 0x7FFFFFFF;
- double timeIn = (double)inTime / 45000;
-
- int outTime = ReadInt32(data, ref pos);
- if (outTime < 0) outTime &= 0x7FFFFFFF;
- double timeOut = (double)outTime / 45000;
-
- var streamClip = new TSStreamClip(
- streamFile, streamClipFile);
-
- streamClip.Name = streamFileName; //TODO
- streamClip.TimeIn = timeIn;
- streamClip.TimeOut = timeOut;
- streamClip.Length = streamClip.TimeOut - streamClip.TimeIn;
- streamClip.RelativeTimeIn = TotalLength;
- streamClip.RelativeTimeOut = streamClip.RelativeTimeIn + streamClip.Length;
- StreamClips.Add(streamClip);
- chapterClips.Add(streamClip);
-
- pos += 12;
- if (multiangle > 0)
- {
- int angles = data[pos];
- pos += 2;
- for (int angle = 0; angle < angles - 1; angle++)
- {
- string angleName = ReadString(data, 5, ref pos);
- string angleType = ReadString(data, 4, ref pos);
- pos += 1;
-
- TSStreamFile angleFile = null;
- string angleFileName = string.Format(
- "{0}.M2TS", angleName);
- if (streamFiles.ContainsKey(angleFileName))
- {
- angleFile = streamFiles[angleFileName];
- }
- if (angleFile == null)
- {
- throw new Exception(string.Format(
- "Playlist {0} referenced missing angle file {1}.",
- FileInfo.Name, angleFileName));
- }
-
- TSStreamClipFile angleClipFile = null;
- string angleClipFileName = string.Format(
- "{0}.CLPI", angleName);
- if (streamClipFiles.ContainsKey(angleClipFileName))
- {
- angleClipFile = streamClipFiles[angleClipFileName];
- }
- if (angleClipFile == null)
- {
- throw new Exception(string.Format(
- "Playlist {0} referenced missing angle file {1}.",
- FileInfo.Name, angleClipFileName));
- }
-
- var angleClip =
- new TSStreamClip(angleFile, angleClipFile);
- angleClip.AngleIndex = angle + 1;
- angleClip.TimeIn = streamClip.TimeIn;
- angleClip.TimeOut = streamClip.TimeOut;
- angleClip.RelativeTimeIn = streamClip.RelativeTimeIn;
- angleClip.RelativeTimeOut = streamClip.RelativeTimeOut;
- angleClip.Length = streamClip.Length;
- StreamClips.Add(angleClip);
- }
- if (angles - 1 > AngleCount) AngleCount = angles - 1;
- }
-
- int streamInfoLength = ReadInt16(data, ref pos);
- pos += 2;
- int streamCountVideo = data[pos++];
- int streamCountAudio = data[pos++];
- int streamCountPG = data[pos++];
- int streamCountIG = data[pos++];
- int streamCountSecondaryAudio = data[pos++];
- int streamCountSecondaryVideo = data[pos++];
- int streamCountPIP = data[pos++];
- pos += 5;
-
-#if DEBUG
- Debug.WriteLine(string.Format(
- "{0} : {1} -> V:{2} A:{3} PG:{4} IG:{5} 2A:{6} 2V:{7} PIP:{8}",
- Name, streamFileName, streamCountVideo, streamCountAudio, streamCountPG, streamCountIG,
- streamCountSecondaryAudio, streamCountSecondaryVideo, streamCountPIP));
-#endif
-
- for (int i = 0; i < streamCountVideo; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- }
- for (int i = 0; i < streamCountAudio; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- }
- for (int i = 0; i < streamCountPG; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- }
- for (int i = 0; i < streamCountIG; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- }
- for (int i = 0; i < streamCountSecondaryAudio; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- pos += 2;
- }
- for (int i = 0; i < streamCountSecondaryVideo; i++)
- {
- var stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- pos += 6;
- }
- /*
- * TODO
- *
- for (int i = 0; i < streamCountPIP; i++)
- {
- TSStream stream = CreatePlaylistStream(data, ref pos);
- if (stream != null) PlaylistStreams[stream.PID] = stream;
- }
- */
-
- pos += itemLength - (pos - itemStart) + 2;
- }
-
- pos = chaptersOffset + 4;
-
- int chapterCount = ReadInt16(data, ref pos);
-
- for (int chapterIndex = 0;
- chapterIndex < chapterCount;
- chapterIndex++)
- {
- int chapterType = data[pos + 1];
-
- if (chapterType == 1)
- {
- int streamFileIndex =
- ((int)data[pos + 2] << 8) + data[pos + 3];
-
- long chapterTime =
- ((long)data[pos + 4] << 24) +
- ((long)data[pos + 5] << 16) +
- ((long)data[pos + 6] << 8) +
- ((long)data[pos + 7]);
-
- var streamClip = chapterClips[streamFileIndex];
-
- double chapterSeconds = (double)chapterTime / 45000;
-
- double relativeSeconds =
- chapterSeconds -
- streamClip.TimeIn +
- streamClip.RelativeTimeIn;
-
- // TODO: Ignore short last chapter?
- if (TotalLength - relativeSeconds > 1.0)
- {
- streamClip.Chapters.Add(chapterSeconds);
- this.Chapters.Add(relativeSeconds);
- }
- }
- else
- {
- // TODO: Handle other chapter types?
- }
- pos += 14;
- }
- }
- finally
- {
- if (fileReader != null)
- {
- fileReader.Dispose();
- }
- if (fileStream != null)
- {
- fileStream.Dispose();
- }
- }
- }
-
- public void Initialize()
- {
- LoadStreamClips();
-
- var clipTimes = new Dictionary<string, List<double>>();
- foreach (var clip in StreamClips)
- {
- if (clip.AngleIndex == 0)
- {
- if (clipTimes.ContainsKey(clip.Name))
- {
- if (clipTimes[clip.Name].Contains(clip.TimeIn))
- {
- HasLoops = true;
- break;
- }
- else
- {
- clipTimes[clip.Name].Add(clip.TimeIn);
- }
- }
- else
- {
- clipTimes[clip.Name] = new List<double> { clip.TimeIn };
- }
- }
- }
- ClearBitrates();
- IsInitialized = true;
- }
-
- protected TSStream CreatePlaylistStream(byte[] data, ref int pos)
- {
- TSStream stream = null;
-
- int start = pos;
-
- int headerLength = data[pos++];
- int headerPos = pos;
- int headerType = data[pos++];
-
- int pid = 0;
- int subpathid = 0;
- int subclipid = 0;
-
- switch (headerType)
- {
- case 1:
- pid = ReadInt16(data, ref pos);
- break;
- case 2:
- subpathid = data[pos++];
- subclipid = data[pos++];
- pid = ReadInt16(data, ref pos);
- break;
- case 3:
- subpathid = data[pos++];
- pid = ReadInt16(data, ref pos);
- break;
- case 4:
- subpathid = data[pos++];
- subclipid = data[pos++];
- pid = ReadInt16(data, ref pos);
- break;
- default:
- break;
- }
-
- pos = headerPos + headerLength;
-
- int streamLength = data[pos++];
- int streamPos = pos;
-
- var streamType = (TSStreamType)data[pos++];
- switch (streamType)
- {
- case TSStreamType.MVC_VIDEO:
- // TODO
- break;
-
- case TSStreamType.AVC_VIDEO:
- case TSStreamType.MPEG1_VIDEO:
- case TSStreamType.MPEG2_VIDEO:
- case TSStreamType.VC1_VIDEO:
-
- var videoFormat = (TSVideoFormat)
- (data[pos] >> 4);
- var frameRate = (TSFrameRate)
- (data[pos] & 0xF);
- var aspectRatio = (TSAspectRatio)
- (data[pos + 1] >> 4);
-
- stream = new TSVideoStream();
- ((TSVideoStream)stream).VideoFormat = videoFormat;
- ((TSVideoStream)stream).AspectRatio = aspectRatio;
- ((TSVideoStream)stream).FrameRate = frameRate;
-
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2} {3} {4}",
- pid,
- streamType,
- videoFormat,
- frameRate,
- aspectRatio));
-#endif
-
- break;
-
- case TSStreamType.AC3_AUDIO:
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- case TSStreamType.DTS_AUDIO:
- case TSStreamType.DTS_HD_AUDIO:
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- case TSStreamType.LPCM_AUDIO:
- case TSStreamType.MPEG1_AUDIO:
- case TSStreamType.MPEG2_AUDIO:
-
- int audioFormat = ReadByte(data, ref pos);
-
- var channelLayout = (TSChannelLayout)
- (audioFormat >> 4);
- var sampleRate = (TSSampleRate)
- (audioFormat & 0xF);
-
- string audioLanguage = ReadString(data, 3, ref pos);
-
- stream = new TSAudioStream();
- ((TSAudioStream)stream).ChannelLayout = channelLayout;
- ((TSAudioStream)stream).SampleRate = TSAudioStream.ConvertSampleRate(sampleRate);
- ((TSAudioStream)stream).LanguageCode = audioLanguage;
-
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2} {3} {4}",
- pid,
- streamType,
- audioLanguage,
- channelLayout,
- sampleRate));
-#endif
-
- break;
-
- case TSStreamType.INTERACTIVE_GRAPHICS:
- case TSStreamType.PRESENTATION_GRAPHICS:
-
- string graphicsLanguage = ReadString(data, 3, ref pos);
-
- stream = new TSGraphicsStream();
- ((TSGraphicsStream)stream).LanguageCode = graphicsLanguage;
-
- if (data[pos] != 0)
- {
- }
-
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2}",
- pid,
- streamType,
- graphicsLanguage));
-#endif
-
- break;
-
- case TSStreamType.SUBTITLE:
-
- int code = ReadByte(data, ref pos); // TODO
- string textLanguage = ReadString(data, 3, ref pos);
-
- stream = new TSTextStream();
- ((TSTextStream)stream).LanguageCode = textLanguage;
-
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2}",
- pid,
- streamType,
- textLanguage));
-#endif
-
- break;
-
- default:
- break;
- }
-
- pos = streamPos + streamLength;
-
- if (stream != null)
- {
- stream.PID = (ushort)pid;
- stream.StreamType = streamType;
- }
-
- return stream;
- }
-
- private void LoadStreamClips()
- {
- AngleClips.Clear();
- if (AngleCount > 0)
- {
- for (int angleIndex = 0; angleIndex < AngleCount; angleIndex++)
- {
- AngleClips.Add(new Dictionary<double, TSStreamClip>());
- }
- }
-
- TSStreamClip referenceClip = null;
- if (StreamClips.Count > 0)
- {
- referenceClip = StreamClips[0];
- }
- foreach (var clip in StreamClips)
- {
- if (clip.StreamClipFile.Streams.Count > referenceClip.StreamClipFile.Streams.Count)
- {
- referenceClip = clip;
- }
- else if (clip.Length > referenceClip.Length)
- {
- referenceClip = clip;
- }
- if (AngleCount > 0)
- {
- if (clip.AngleIndex == 0)
- {
- for (int angleIndex = 0; angleIndex < AngleCount; angleIndex++)
- {
- AngleClips[angleIndex][clip.RelativeTimeIn] = clip;
- }
- }
- else
- {
- AngleClips[clip.AngleIndex - 1][clip.RelativeTimeIn] = clip;
- }
- }
- }
-
- foreach (var clipStream
- in referenceClip.StreamClipFile.Streams.Values)
- {
- if (!Streams.ContainsKey(clipStream.PID))
- {
- var stream = clipStream.Clone();
- Streams[clipStream.PID] = stream;
-
- if (!IsCustom && !PlaylistStreams.ContainsKey(stream.PID))
- {
- stream.IsHidden = true;
- HasHiddenTracks = true;
- }
-
- if (stream.IsVideoStream)
- {
- VideoStreams.Add((TSVideoStream)stream);
- }
- else if (stream.IsAudioStream)
- {
- AudioStreams.Add((TSAudioStream)stream);
- }
- else if (stream.IsGraphicsStream)
- {
- GraphicsStreams.Add((TSGraphicsStream)stream);
- }
- else if (stream.IsTextStream)
- {
- TextStreams.Add((TSTextStream)stream);
- }
- }
- }
-
- if (referenceClip.StreamFile != null)
- {
- // TODO: Better way to add this in?
- if (BDInfoSettings.EnableSSIF &&
- referenceClip.StreamFile.InterleavedFile != null &&
- referenceClip.StreamFile.Streams.ContainsKey(4114) &&
- !Streams.ContainsKey(4114))
- {
- var stream = referenceClip.StreamFile.Streams[4114].Clone();
- Streams[4114] = stream;
- if (stream.IsVideoStream)
- {
- VideoStreams.Add((TSVideoStream)stream);
- }
- }
-
- foreach (var clipStream
- in referenceClip.StreamFile.Streams.Values)
- {
- if (Streams.ContainsKey(clipStream.PID))
- {
- var stream = Streams[clipStream.PID];
-
- if (stream.StreamType != clipStream.StreamType) continue;
-
- if (clipStream.BitRate > stream.BitRate)
- {
- stream.BitRate = clipStream.BitRate;
- }
- stream.IsVBR = clipStream.IsVBR;
-
- if (stream.IsVideoStream &&
- clipStream.IsVideoStream)
- {
- ((TSVideoStream)stream).EncodingProfile =
- ((TSVideoStream)clipStream).EncodingProfile;
- }
- else if (stream.IsAudioStream &&
- clipStream.IsAudioStream)
- {
- var audioStream = (TSAudioStream)stream;
- var clipAudioStream = (TSAudioStream)clipStream;
-
- if (clipAudioStream.ChannelCount > audioStream.ChannelCount)
- {
- audioStream.ChannelCount = clipAudioStream.ChannelCount;
- }
- if (clipAudioStream.LFE > audioStream.LFE)
- {
- audioStream.LFE = clipAudioStream.LFE;
- }
- if (clipAudioStream.SampleRate > audioStream.SampleRate)
- {
- audioStream.SampleRate = clipAudioStream.SampleRate;
- }
- if (clipAudioStream.BitDepth > audioStream.BitDepth)
- {
- audioStream.BitDepth = clipAudioStream.BitDepth;
- }
- if (clipAudioStream.DialNorm < audioStream.DialNorm)
- {
- audioStream.DialNorm = clipAudioStream.DialNorm;
- }
- if (clipAudioStream.AudioMode != TSAudioMode.Unknown)
- {
- audioStream.AudioMode = clipAudioStream.AudioMode;
- }
- if (clipAudioStream.CoreStream != null &&
- audioStream.CoreStream == null)
- {
- audioStream.CoreStream = (TSAudioStream)
- clipAudioStream.CoreStream.Clone();
- }
- }
- }
- }
- }
-
- for (int i = 0; i < AngleCount; i++)
- {
- AngleStreams.Add(new Dictionary<ushort, TSStream>());
- }
-
- if (!BDInfoSettings.KeepStreamOrder)
- {
- VideoStreams.Sort(CompareVideoStreams);
- }
- foreach (TSStream stream in VideoStreams)
- {
- SortedStreams.Add(stream);
- for (int i = 0; i < AngleCount; i++)
- {
- var angleStream = stream.Clone();
- angleStream.AngleIndex = i + 1;
- AngleStreams[i][angleStream.PID] = angleStream;
- SortedStreams.Add(angleStream);
- }
- }
-
- if (!BDInfoSettings.KeepStreamOrder)
- {
- AudioStreams.Sort(CompareAudioStreams);
- }
- foreach (TSStream stream in AudioStreams)
- {
- SortedStreams.Add(stream);
- }
-
- if (!BDInfoSettings.KeepStreamOrder)
- {
- GraphicsStreams.Sort(CompareGraphicsStreams);
- }
- foreach (TSStream stream in GraphicsStreams)
- {
- SortedStreams.Add(stream);
- }
-
- if (!BDInfoSettings.KeepStreamOrder)
- {
- TextStreams.Sort(CompareTextStreams);
- }
- foreach (TSStream stream in TextStreams)
- {
- SortedStreams.Add(stream);
- }
- }
-
- public void ClearBitrates()
- {
- foreach (var clip in StreamClips)
- {
- clip.PayloadBytes = 0;
- clip.PacketCount = 0;
- clip.PacketSeconds = 0;
-
- if (clip.StreamFile != null)
- {
- foreach (var stream in clip.StreamFile.Streams.Values)
- {
- stream.PayloadBytes = 0;
- stream.PacketCount = 0;
- stream.PacketSeconds = 0;
- }
-
- if (clip.StreamFile != null &&
- clip.StreamFile.StreamDiagnostics != null)
- {
- clip.StreamFile.StreamDiagnostics.Clear();
- }
- }
- }
-
- foreach (var stream in SortedStreams)
- {
- stream.PayloadBytes = 0;
- stream.PacketCount = 0;
- stream.PacketSeconds = 0;
- }
- }
-
- public bool IsValid
- {
- get
- {
- if (!IsInitialized) return false;
-
- if (BDInfoSettings.FilterShortPlaylists &&
- TotalLength < BDInfoSettings.FilterShortPlaylistsValue)
- {
- return false;
- }
-
- if (HasLoops &&
- BDInfoSettings.FilterLoopingPlaylists)
- {
- return false;
- }
-
- return true;
- }
- }
-
- public int CompareVideoStreams(
- TSVideoStream x,
- TSVideoStream y)
- {
- if (x == null && y == null)
- {
- return 0;
- }
- else if (x == null && y != null)
- {
- return 1;
- }
- else if (x != null && y == null)
- {
- return -1;
- }
- else
- {
- if (x.Height > y.Height)
- {
- return -1;
- }
- else if (y.Height > x.Height)
- {
- return 1;
- }
- else if (x.PID > y.PID)
- {
- return 1;
- }
- else if (y.PID > x.PID)
- {
- return -1;
- }
- else
- {
- return 0;
- }
- }
- }
-
- public int CompareAudioStreams(
- TSAudioStream x,
- TSAudioStream y)
- {
- if (x == y)
- {
- return 0;
- }
- else if (x == null && y == null)
- {
- return 0;
- }
- else if (x == null && y != null)
- {
- return -1;
- }
- else if (x != null && y == null)
- {
- return 1;
- }
- else
- {
- if (x.ChannelCount > y.ChannelCount)
- {
- return -1;
- }
- else if (y.ChannelCount > x.ChannelCount)
- {
- return 1;
- }
- else
- {
- int sortX = GetStreamTypeSortIndex(x.StreamType);
- int sortY = GetStreamTypeSortIndex(y.StreamType);
-
- if (sortX > sortY)
- {
- return -1;
- }
- else if (sortY > sortX)
- {
- return 1;
- }
- else
- {
- if (x.LanguageCode == "eng")
- {
- return -1;
- }
- else if (y.LanguageCode == "eng")
- {
- return 1;
- }
- else if (x.LanguageCode != y.LanguageCode)
- {
- return string.Compare(
- x.LanguageName, y.LanguageName);
- }
- else if (x.PID < y.PID)
- {
- return -1;
- }
- else if (y.PID < x.PID)
- {
- return 1;
- }
- return 0;
- }
- }
- }
- }
-
- public int CompareTextStreams(
- TSTextStream x,
- TSTextStream y)
- {
- if (x == y)
- {
- return 0;
- }
- else if (x == null && y == null)
- {
- return 0;
- }
- else if (x == null && y != null)
- {
- return -1;
- }
- else if (x != null && y == null)
- {
- return 1;
- }
- else
- {
- if (x.LanguageCode == "eng")
- {
- return -1;
- }
- else if (y.LanguageCode == "eng")
- {
- return 1;
- }
- else
- {
- if (x.LanguageCode == y.LanguageCode)
- {
- if (x.PID > y.PID)
- {
- return 1;
- }
- else if (y.PID > x.PID)
- {
- return -1;
- }
- else
- {
- return 0;
- }
- }
- else
- {
- return string.Compare(
- x.LanguageName, y.LanguageName);
- }
- }
- }
- }
-
- private int CompareGraphicsStreams(
- TSGraphicsStream x,
- TSGraphicsStream y)
- {
- if (x == y)
- {
- return 0;
- }
- else if (x == null && y == null)
- {
- return 0;
- }
- else if (x == null && y != null)
- {
- return -1;
- }
- else if (x != null && y == null)
- {
- return 1;
- }
- else
- {
- int sortX = GetStreamTypeSortIndex(x.StreamType);
- int sortY = GetStreamTypeSortIndex(y.StreamType);
-
- if (sortX > sortY)
- {
- return -1;
- }
- else if (sortY > sortX)
- {
- return 1;
- }
- else if (x.LanguageCode == "eng")
- {
- return -1;
- }
- else if (y.LanguageCode == "eng")
- {
- return 1;
- }
- else
- {
- if (x.LanguageCode == y.LanguageCode)
- {
- if (x.PID > y.PID)
- {
- return 1;
- }
- else if (y.PID > x.PID)
- {
- return -1;
- }
- else
- {
- return 0;
- }
- }
- else
- {
- return string.Compare(x.LanguageName, y.LanguageName);
- }
- }
- }
- }
-
- private int GetStreamTypeSortIndex(TSStreamType streamType)
- {
- switch (streamType)
- {
- case TSStreamType.Unknown:
- return 0;
- case TSStreamType.MPEG1_VIDEO:
- return 1;
- case TSStreamType.MPEG2_VIDEO:
- return 2;
- case TSStreamType.AVC_VIDEO:
- return 3;
- case TSStreamType.VC1_VIDEO:
- return 4;
- case TSStreamType.MVC_VIDEO:
- return 5;
-
- case TSStreamType.MPEG1_AUDIO:
- return 1;
- case TSStreamType.MPEG2_AUDIO:
- return 2;
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- return 3;
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- return 4;
- case TSStreamType.AC3_AUDIO:
- return 5;
- case TSStreamType.DTS_AUDIO:
- return 6;
- case TSStreamType.AC3_PLUS_AUDIO:
- return 7;
- case TSStreamType.DTS_HD_AUDIO:
- return 8;
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- return 9;
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- return 10;
- case TSStreamType.LPCM_AUDIO:
- return 11;
-
- case TSStreamType.SUBTITLE:
- return 1;
- case TSStreamType.INTERACTIVE_GRAPHICS:
- return 2;
- case TSStreamType.PRESENTATION_GRAPHICS:
- return 3;
-
- default:
- return 0;
- }
- }
-
- protected string ReadString(
- byte[] data,
- int count,
- ref int pos)
- {
- string val = Encoding.ASCII.GetString(data, pos, count);
-
- pos += count;
-
- return val;
- }
-
- protected int ReadInt32(
- byte[] data,
- ref int pos)
- {
- int val =
- ((int)data[pos] << 24) +
- ((int)data[pos + 1] << 16) +
- ((int)data[pos + 2] << 8) +
- ((int)data[pos + 3]);
-
- pos += 4;
-
- return val;
- }
-
- protected int ReadInt16(
- byte[] data,
- ref int pos)
- {
- int val =
- ((int)data[pos] << 8) +
- ((int)data[pos + 1]);
-
- pos += 2;
-
- return val;
- }
-
- protected byte ReadByte(
- byte[] data,
- ref int pos)
- {
- return data[pos++];
- }
- }
-}
diff --git a/BDInfo/TSStream.cs b/BDInfo/TSStream.cs
deleted file mode 100644
index 3c30a8597..000000000
--- a/BDInfo/TSStream.cs
+++ /dev/null
@@ -1,780 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-using System;
-using System.Collections.Generic;
-
-namespace BDInfo
-{
- public enum TSStreamType : byte
- {
- Unknown = 0,
- MPEG1_VIDEO = 0x01,
- MPEG2_VIDEO = 0x02,
- AVC_VIDEO = 0x1b,
- MVC_VIDEO = 0x20,
- VC1_VIDEO = 0xea,
- MPEG1_AUDIO = 0x03,
- MPEG2_AUDIO = 0x04,
- LPCM_AUDIO = 0x80,
- AC3_AUDIO = 0x81,
- AC3_PLUS_AUDIO = 0x84,
- AC3_PLUS_SECONDARY_AUDIO = 0xA1,
- AC3_TRUE_HD_AUDIO = 0x83,
- DTS_AUDIO = 0x82,
- DTS_HD_AUDIO = 0x85,
- DTS_HD_SECONDARY_AUDIO = 0xA2,
- DTS_HD_MASTER_AUDIO = 0x86,
- PRESENTATION_GRAPHICS = 0x90,
- INTERACTIVE_GRAPHICS = 0x91,
- SUBTITLE = 0x92
- }
-
- public enum TSVideoFormat : byte
- {
- Unknown = 0,
- VIDEOFORMAT_480i = 1,
- VIDEOFORMAT_576i = 2,
- VIDEOFORMAT_480p = 3,
- VIDEOFORMAT_1080i = 4,
- VIDEOFORMAT_720p = 5,
- VIDEOFORMAT_1080p = 6,
- VIDEOFORMAT_576p = 7,
- }
-
- public enum TSFrameRate : byte
- {
- Unknown = 0,
- FRAMERATE_23_976 = 1,
- FRAMERATE_24 = 2,
- FRAMERATE_25 = 3,
- FRAMERATE_29_97 = 4,
- FRAMERATE_50 = 6,
- FRAMERATE_59_94 = 7
- }
-
- public enum TSChannelLayout : byte
- {
- Unknown = 0,
- CHANNELLAYOUT_MONO = 1,
- CHANNELLAYOUT_STEREO = 3,
- CHANNELLAYOUT_MULTI = 6,
- CHANNELLAYOUT_COMBO = 12
- }
-
- public enum TSSampleRate : byte
- {
- Unknown = 0,
- SAMPLERATE_48 = 1,
- SAMPLERATE_96 = 4,
- SAMPLERATE_192 = 5,
- SAMPLERATE_48_192 = 12,
- SAMPLERATE_48_96 = 14
- }
-
- public enum TSAspectRatio
- {
- Unknown = 0,
- ASPECT_4_3 = 2,
- ASPECT_16_9 = 3,
- ASPECT_2_21 = 4
- }
-
- public class TSDescriptor
- {
- public byte Name;
- public byte[] Value;
-
- public TSDescriptor(byte name, byte length)
- {
- Name = name;
- Value = new byte[length];
- }
-
- public TSDescriptor Clone()
- {
- var descriptor =
- new TSDescriptor(Name, (byte)Value.Length);
- Value.CopyTo(descriptor.Value, 0);
- return descriptor;
- }
- }
-
- public abstract class TSStream
- {
- public TSStream()
- {
- }
-
- public override string ToString()
- {
- return string.Format("{0} ({1})", CodecShortName, PID);
- }
-
- public ushort PID;
- public TSStreamType StreamType;
- public List<TSDescriptor> Descriptors = null;
- public long BitRate = 0;
- public long ActiveBitRate = 0;
- public bool IsVBR = false;
- public bool IsInitialized = false;
- public string LanguageName;
- public bool IsHidden = false;
-
- public ulong PayloadBytes = 0;
- public ulong PacketCount = 0;
- public double PacketSeconds = 0;
- public int AngleIndex = 0;
-
- public ulong PacketSize => PacketCount * 192;
-
- private string _LanguageCode;
- public string LanguageCode
- {
- get => _LanguageCode;
- set
- {
- _LanguageCode = value;
- LanguageName = LanguageCodes.GetName(value);
- }
- }
-
- public bool IsVideoStream
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.MPEG1_VIDEO:
- case TSStreamType.MPEG2_VIDEO:
- case TSStreamType.AVC_VIDEO:
- case TSStreamType.MVC_VIDEO:
- case TSStreamType.VC1_VIDEO:
- return true;
-
- default:
- return false;
- }
- }
- }
-
- public bool IsAudioStream
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.MPEG1_AUDIO:
- case TSStreamType.MPEG2_AUDIO:
- case TSStreamType.LPCM_AUDIO:
- case TSStreamType.AC3_AUDIO:
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- case TSStreamType.DTS_AUDIO:
- case TSStreamType.DTS_HD_AUDIO:
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- return true;
-
- default:
- return false;
- }
- }
- }
-
- public bool IsGraphicsStream
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.PRESENTATION_GRAPHICS:
- case TSStreamType.INTERACTIVE_GRAPHICS:
- return true;
-
- default:
- return false;
- }
- }
- }
-
- public bool IsTextStream
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.SUBTITLE:
- return true;
-
- default:
- return false;
- }
- }
- }
-
- public string CodecName
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.MPEG1_VIDEO:
- return "MPEG-1 Video";
- case TSStreamType.MPEG2_VIDEO:
- return "MPEG-2 Video";
- case TSStreamType.AVC_VIDEO:
- return "MPEG-4 AVC Video";
- case TSStreamType.MVC_VIDEO:
- return "MPEG-4 MVC Video";
- case TSStreamType.VC1_VIDEO:
- return "VC-1 Video";
- case TSStreamType.MPEG1_AUDIO:
- return "MP1 Audio";
- case TSStreamType.MPEG2_AUDIO:
- return "MP2 Audio";
- case TSStreamType.LPCM_AUDIO:
- return "LPCM Audio";
- case TSStreamType.AC3_AUDIO:
- if (((TSAudioStream)this).AudioMode == TSAudioMode.Extended)
- return "Dolby Digital EX Audio";
- else
- return "Dolby Digital Audio";
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- return "Dolby Digital Plus Audio";
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- return "Dolby TrueHD Audio";
- case TSStreamType.DTS_AUDIO:
- if (((TSAudioStream)this).AudioMode == TSAudioMode.Extended)
- return "DTS-ES Audio";
- else
- return "DTS Audio";
- case TSStreamType.DTS_HD_AUDIO:
- return "DTS-HD High-Res Audio";
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- return "DTS Express";
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- return "DTS-HD Master Audio";
- case TSStreamType.PRESENTATION_GRAPHICS:
- return "Presentation Graphics";
- case TSStreamType.INTERACTIVE_GRAPHICS:
- return "Interactive Graphics";
- case TSStreamType.SUBTITLE:
- return "Subtitle";
- default:
- return "UNKNOWN";
- }
- }
- }
-
- public string CodecAltName
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.MPEG1_VIDEO:
- return "MPEG-1";
- case TSStreamType.MPEG2_VIDEO:
- return "MPEG-2";
- case TSStreamType.AVC_VIDEO:
- return "AVC";
- case TSStreamType.MVC_VIDEO:
- return "MVC";
- case TSStreamType.VC1_VIDEO:
- return "VC-1";
- case TSStreamType.MPEG1_AUDIO:
- return "MP1";
- case TSStreamType.MPEG2_AUDIO:
- return "MP2";
- case TSStreamType.LPCM_AUDIO:
- return "LPCM";
- case TSStreamType.AC3_AUDIO:
- return "DD AC3";
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- return "DD AC3+";
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- return "Dolby TrueHD";
- case TSStreamType.DTS_AUDIO:
- return "DTS";
- case TSStreamType.DTS_HD_AUDIO:
- return "DTS-HD Hi-Res";
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- return "DTS Express";
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- return "DTS-HD Master";
- case TSStreamType.PRESENTATION_GRAPHICS:
- return "PGS";
- case TSStreamType.INTERACTIVE_GRAPHICS:
- return "IGS";
- case TSStreamType.SUBTITLE:
- return "SUB";
- default:
- return "UNKNOWN";
- }
- }
- }
-
- public string CodecShortName
- {
- get
- {
- switch (StreamType)
- {
- case TSStreamType.MPEG1_VIDEO:
- return "MPEG-1";
- case TSStreamType.MPEG2_VIDEO:
- return "MPEG-2";
- case TSStreamType.AVC_VIDEO:
- return "AVC";
- case TSStreamType.MVC_VIDEO:
- return "MVC";
- case TSStreamType.VC1_VIDEO:
- return "VC-1";
- case TSStreamType.MPEG1_AUDIO:
- return "MP1";
- case TSStreamType.MPEG2_AUDIO:
- return "MP2";
- case TSStreamType.LPCM_AUDIO:
- return "LPCM";
- case TSStreamType.AC3_AUDIO:
- if (((TSAudioStream)this).AudioMode == TSAudioMode.Extended)
- return "AC3-EX";
- else
- return "AC3";
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- return "AC3+";
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- return "TrueHD";
- case TSStreamType.DTS_AUDIO:
- if (((TSAudioStream)this).AudioMode == TSAudioMode.Extended)
- return "DTS-ES";
- else
- return "DTS";
- case TSStreamType.DTS_HD_AUDIO:
- return "DTS-HD HR";
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- return "DTS Express";
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- return "DTS-HD MA";
- case TSStreamType.PRESENTATION_GRAPHICS:
- return "PGS";
- case TSStreamType.INTERACTIVE_GRAPHICS:
- return "IGS";
- case TSStreamType.SUBTITLE:
- return "SUB";
- default:
- return "UNKNOWN";
- }
- }
- }
-
- public virtual string Description => "";
-
- public abstract TSStream Clone();
-
- protected void CopyTo(TSStream stream)
- {
- stream.PID = PID;
- stream.StreamType = StreamType;
- stream.IsVBR = IsVBR;
- stream.BitRate = BitRate;
- stream.IsInitialized = IsInitialized;
- stream.LanguageCode = _LanguageCode;
- if (Descriptors != null)
- {
- stream.Descriptors = new List<TSDescriptor>();
- foreach (var descriptor in Descriptors)
- {
- stream.Descriptors.Add(descriptor.Clone());
- }
- }
- }
- }
-
- public class TSVideoStream : TSStream
- {
- public TSVideoStream()
- {
- }
-
- public int Width;
- public int Height;
- public bool IsInterlaced;
- public int FrameRateEnumerator;
- public int FrameRateDenominator;
- public TSAspectRatio AspectRatio;
- public string EncodingProfile;
-
- private TSVideoFormat _VideoFormat;
- public TSVideoFormat VideoFormat
- {
- get => _VideoFormat;
- set
- {
- _VideoFormat = value;
- switch (value)
- {
- case TSVideoFormat.VIDEOFORMAT_480i:
- Height = 480;
- IsInterlaced = true;
- break;
- case TSVideoFormat.VIDEOFORMAT_480p:
- Height = 480;
- IsInterlaced = false;
- break;
- case TSVideoFormat.VIDEOFORMAT_576i:
- Height = 576;
- IsInterlaced = true;
- break;
- case TSVideoFormat.VIDEOFORMAT_576p:
- Height = 576;
- IsInterlaced = false;
- break;
- case TSVideoFormat.VIDEOFORMAT_720p:
- Height = 720;
- IsInterlaced = false;
- break;
- case TSVideoFormat.VIDEOFORMAT_1080i:
- Height = 1080;
- IsInterlaced = true;
- break;
- case TSVideoFormat.VIDEOFORMAT_1080p:
- Height = 1080;
- IsInterlaced = false;
- break;
- }
- }
- }
-
- private TSFrameRate _FrameRate;
- public TSFrameRate FrameRate
- {
- get => _FrameRate;
- set
- {
- _FrameRate = value;
- switch (value)
- {
- case TSFrameRate.FRAMERATE_23_976:
- FrameRateEnumerator = 24000;
- FrameRateDenominator = 1001;
- break;
- case TSFrameRate.FRAMERATE_24:
- FrameRateEnumerator = 24000;
- FrameRateDenominator = 1000;
- break;
- case TSFrameRate.FRAMERATE_25:
- FrameRateEnumerator = 25000;
- FrameRateDenominator = 1000;
- break;
- case TSFrameRate.FRAMERATE_29_97:
- FrameRateEnumerator = 30000;
- FrameRateDenominator = 1001;
- break;
- case TSFrameRate.FRAMERATE_50:
- FrameRateEnumerator = 50000;
- FrameRateDenominator = 1000;
- break;
- case TSFrameRate.FRAMERATE_59_94:
- FrameRateEnumerator = 60000;
- FrameRateDenominator = 1001;
- break;
- }
- }
- }
-
- public override string Description
- {
- get
- {
- string description = "";
-
- if (Height > 0)
- {
- description += string.Format("{0:D}{1} / ",
- Height,
- IsInterlaced ? "i" : "p");
- }
- if (FrameRateEnumerator > 0 &&
- FrameRateDenominator > 0)
- {
- if (FrameRateEnumerator % FrameRateDenominator == 0)
- {
- description += string.Format("{0:D} fps / ",
- FrameRateEnumerator / FrameRateDenominator);
- }
- else
- {
- description += string.Format("{0:F3} fps / ",
- (double)FrameRateEnumerator / FrameRateDenominator);
- }
-
- }
- if (AspectRatio == TSAspectRatio.ASPECT_4_3)
- {
- description += "4:3 / ";
- }
- else if (AspectRatio == TSAspectRatio.ASPECT_16_9)
- {
- description += "16:9 / ";
- }
- if (EncodingProfile != null)
- {
- description += EncodingProfile + " / ";
- }
- if (description.EndsWith(" / "))
- {
- description = description.Substring(0, description.Length - 3);
- }
- return description;
- }
- }
-
- public override TSStream Clone()
- {
- var stream = new TSVideoStream();
- CopyTo(stream);
-
- stream.VideoFormat = _VideoFormat;
- stream.FrameRate = _FrameRate;
- stream.Width = Width;
- stream.Height = Height;
- stream.IsInterlaced = IsInterlaced;
- stream.FrameRateEnumerator = FrameRateEnumerator;
- stream.FrameRateDenominator = FrameRateDenominator;
- stream.AspectRatio = AspectRatio;
- stream.EncodingProfile = EncodingProfile;
-
- return stream;
- }
- }
-
- public enum TSAudioMode
- {
- Unknown,
- DualMono,
- Stereo,
- Surround,
- Extended
- }
-
- public class TSAudioStream : TSStream
- {
- public TSAudioStream()
- {
- }
-
- public int SampleRate;
- public int ChannelCount;
- public int BitDepth;
- public int LFE;
- public int DialNorm;
- public TSAudioMode AudioMode;
- public TSAudioStream CoreStream;
- public TSChannelLayout ChannelLayout;
-
- public static int ConvertSampleRate(
- TSSampleRate sampleRate)
- {
- switch (sampleRate)
- {
- case TSSampleRate.SAMPLERATE_48:
- return 48000;
-
- case TSSampleRate.SAMPLERATE_96:
- case TSSampleRate.SAMPLERATE_48_96:
- return 96000;
-
- case TSSampleRate.SAMPLERATE_192:
- case TSSampleRate.SAMPLERATE_48_192:
- return 192000;
- }
- return 0;
- }
-
- public string ChannelDescription
- {
- get
- {
- if (ChannelLayout == TSChannelLayout.CHANNELLAYOUT_MONO &&
- ChannelCount == 2)
- {
- }
-
- string description = "";
- if (ChannelCount > 0)
- {
- description += string.Format(
- "{0:D}.{1:D}",
- ChannelCount, LFE);
- }
- else
- {
- switch (ChannelLayout)
- {
- case TSChannelLayout.CHANNELLAYOUT_MONO:
- description += "1.0";
- break;
- case TSChannelLayout.CHANNELLAYOUT_STEREO:
- description += "2.0";
- break;
- case TSChannelLayout.CHANNELLAYOUT_MULTI:
- description += "5.1";
- break;
- }
- }
- if (AudioMode == TSAudioMode.Extended)
- {
- if (StreamType == TSStreamType.AC3_AUDIO)
- {
- description += "-EX";
- }
- if (StreamType == TSStreamType.DTS_AUDIO ||
- StreamType == TSStreamType.DTS_HD_AUDIO ||
- StreamType == TSStreamType.DTS_HD_MASTER_AUDIO)
- {
- description += "-ES";
- }
- }
- return description;
- }
- }
-
- public override string Description
- {
- get
- {
- string description = ChannelDescription;
-
- if (SampleRate > 0)
- {
- description += string.Format(
- " / {0:D} kHz", SampleRate / 1000);
- }
- if (BitRate > 0)
- {
- description += string.Format(
- " / {0:D} kbps", (uint)Math.Round((double)BitRate / 1000));
- }
- if (BitDepth > 0)
- {
- description += string.Format(
- " / {0:D}-bit", BitDepth);
- }
- if (DialNorm != 0)
- {
- description += string.Format(
- " / DN {0}dB", DialNorm);
- }
- if (ChannelCount == 2)
- {
- switch (AudioMode)
- {
- case TSAudioMode.DualMono:
- description += " / Dual Mono";
- break;
-
- case TSAudioMode.Surround:
- description += " / Dolby Surround";
- break;
- }
- }
- if (description.EndsWith(" / "))
- {
- description = description.Substring(0, description.Length - 3);
- }
- if (CoreStream != null)
- {
- string codec = "";
- switch (CoreStream.StreamType)
- {
- case TSStreamType.AC3_AUDIO:
- codec = "AC3 Embedded";
- break;
- case TSStreamType.DTS_AUDIO:
- codec = "DTS Core";
- break;
- }
- description += string.Format(
- " ({0}: {1})",
- codec,
- CoreStream.Description);
- }
- return description;
- }
- }
-
- public override TSStream Clone()
- {
- var stream = new TSAudioStream();
- CopyTo(stream);
-
- stream.SampleRate = SampleRate;
- stream.ChannelLayout = ChannelLayout;
- stream.ChannelCount = ChannelCount;
- stream.BitDepth = BitDepth;
- stream.LFE = LFE;
- stream.DialNorm = DialNorm;
- stream.AudioMode = AudioMode;
- if (CoreStream != null)
- {
- stream.CoreStream = (TSAudioStream)CoreStream.Clone();
- }
-
- return stream;
- }
- }
-
- public class TSGraphicsStream : TSStream
- {
- public TSGraphicsStream()
- {
- IsVBR = true;
- IsInitialized = true;
- }
-
- public override TSStream Clone()
- {
- var stream = new TSGraphicsStream();
- CopyTo(stream);
- return stream;
- }
- }
-
- public class TSTextStream : TSStream
- {
- public TSTextStream()
- {
- IsVBR = true;
- IsInitialized = true;
- }
-
- public override TSStream Clone()
- {
- var stream = new TSTextStream();
- CopyTo(stream);
- return stream;
- }
- }
-}
diff --git a/BDInfo/TSStreamBuffer.cs b/BDInfo/TSStreamBuffer.cs
deleted file mode 100644
index 30bd1a3f4..000000000
--- a/BDInfo/TSStreamBuffer.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-using System;
-using System.Collections.Specialized;
-using System.IO;
-
-namespace BDInfo
-{
- public class TSStreamBuffer
- {
- private MemoryStream Stream = new MemoryStream();
- private int SkipBits = 0;
- private byte[] Buffer;
- private int BufferLength = 0;
- public int TransferLength = 0;
-
- public TSStreamBuffer()
- {
- Buffer = new byte[4096];
- Stream = new MemoryStream(Buffer);
- }
-
- public long Length => (long)BufferLength;
-
- public long Position => Stream.Position;
-
- public void Add(
- byte[] buffer,
- int offset,
- int length)
- {
- TransferLength += length;
-
- if (BufferLength + length >= Buffer.Length)
- {
- length = Buffer.Length - BufferLength;
- }
- if (length > 0)
- {
- Array.Copy(buffer, offset, Buffer, BufferLength, length);
- BufferLength += length;
- }
- }
-
- public void Seek(
- long offset,
- SeekOrigin loc)
- {
- Stream.Seek(offset, loc);
- }
-
- public void Reset()
- {
- BufferLength = 0;
- TransferLength = 0;
- }
-
- public void BeginRead()
- {
- SkipBits = 0;
- Stream.Seek(0, SeekOrigin.Begin);
- }
-
- public void EndRead()
- {
- }
-
- public byte[] ReadBytes(int bytes)
- {
- if (Stream.Position + bytes >= BufferLength)
- {
- return null;
- }
-
- byte[] value = new byte[bytes];
- Stream.Read(value, 0, bytes);
- return value;
- }
-
- public byte ReadByte()
- {
- return (byte)Stream.ReadByte();
- }
-
- public int ReadBits(int bits)
- {
- long pos = Stream.Position;
-
- int shift = 24;
- int data = 0;
- for (int i = 0; i < 4; i++)
- {
- if (pos + i >= BufferLength) break;
- data += (Stream.ReadByte() << shift);
- shift -= 8;
- }
- var vector = new BitVector32(data);
-
- int value = 0;
- for (int i = SkipBits; i < SkipBits + bits; i++)
- {
- value <<= 1;
- value += (vector[1 << (32 - i - 1)] ? 1 : 0);
- }
-
- SkipBits += bits;
- Stream.Seek(pos + (SkipBits >> 3), SeekOrigin.Begin);
- SkipBits = SkipBits % 8;
-
- return value;
- }
- }
-}
diff --git a/BDInfo/TSStreamClip.cs b/BDInfo/TSStreamClip.cs
deleted file mode 100644
index 295eeb6b1..000000000
--- a/BDInfo/TSStreamClip.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-using System;
-using System.Collections.Generic;
-
-namespace BDInfo
-{
- public class TSStreamClip
- {
- public int AngleIndex = 0;
- public string Name;
- public double TimeIn;
- public double TimeOut;
- public double RelativeTimeIn;
- public double RelativeTimeOut;
- public double Length;
-
- public ulong FileSize = 0;
- public ulong InterleavedFileSize = 0;
- public ulong PayloadBytes = 0;
- public ulong PacketCount = 0;
- public double PacketSeconds = 0;
-
- public List<double> Chapters = new List<double>();
-
- public TSStreamFile StreamFile = null;
- public TSStreamClipFile StreamClipFile = null;
-
- public TSStreamClip(
- TSStreamFile streamFile,
- TSStreamClipFile streamClipFile)
- {
- if (streamFile != null)
- {
- Name = streamFile.Name;
- StreamFile = streamFile;
- FileSize = (ulong)StreamFile.FileInfo.Length;
- if (StreamFile.InterleavedFile != null)
- {
- InterleavedFileSize = (ulong)StreamFile.InterleavedFile.FileInfo.Length;
- }
- }
- StreamClipFile = streamClipFile;
- }
-
- public string DisplayName
- {
- get
- {
- if (StreamFile != null &&
- StreamFile.InterleavedFile != null &&
- BDInfoSettings.EnableSSIF)
- {
- return StreamFile.InterleavedFile.Name;
- }
- return Name;
- }
- }
-
- public ulong PacketSize => PacketCount * 192;
-
- public ulong PacketBitRate
- {
- get
- {
- if (PacketSeconds > 0)
- {
- return (ulong)Math.Round(((PacketSize * 8.0) / PacketSeconds));
- }
- return 0;
- }
- }
-
- public bool IsCompatible(TSStreamClip clip)
- {
- foreach (var stream1 in StreamFile.Streams.Values)
- {
- if (clip.StreamFile.Streams.ContainsKey(stream1.PID))
- {
- var stream2 = clip.StreamFile.Streams[stream1.PID];
- if (stream1.StreamType != stream2.StreamType)
- {
- return false;
- }
- }
- }
- return true;
- }
- }
-}
diff --git a/BDInfo/TSStreamClipFile.cs b/BDInfo/TSStreamClipFile.cs
deleted file mode 100644
index e1097b23d..000000000
--- a/BDInfo/TSStreamClipFile.cs
+++ /dev/null
@@ -1,244 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-#undef DEBUG
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using MediaBrowser.Model.IO;
-
-namespace BDInfo
-{
- public class TSStreamClipFile
- {
- public FileSystemMetadata FileInfo = null;
- public string FileType = null;
- public bool IsValid = false;
- public string Name = null;
-
- public Dictionary<ushort, TSStream> Streams =
- new Dictionary<ushort, TSStream>();
-
- public TSStreamClipFile(FileSystemMetadata fileInfo)
- {
- FileInfo = fileInfo;
- Name = fileInfo.Name.ToUpper();
- }
-
- public void Scan()
- {
- Stream fileStream = null;
- BinaryReader fileReader = null;
-
- try
- {
-#if DEBUG
- Debug.WriteLine(string.Format(
- "Scanning {0}...", Name));
-#endif
- Streams.Clear();
-
- fileStream = File.OpenRead(FileInfo.FullName);
- fileReader = new BinaryReader(fileStream);
-
- byte[] data = new byte[fileStream.Length];
- fileReader.Read(data, 0, data.Length);
-
- byte[] fileType = new byte[8];
- Array.Copy(data, 0, fileType, 0, fileType.Length);
-
- FileType = Encoding.ASCII.GetString(fileType, 0, fileType.Length);
- if (FileType != "HDMV0100" &&
- FileType != "HDMV0200")
- {
- throw new Exception(string.Format(
- "Clip info file {0} has an unknown file type {1}.",
- FileInfo.Name, FileType));
- }
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\tFileType: {0}", FileType));
-#endif
- int clipIndex =
- ((int)data[12] << 24) +
- ((int)data[13] << 16) +
- ((int)data[14] << 8) +
- ((int)data[15]);
-
- int clipLength =
- ((int)data[clipIndex] << 24) +
- ((int)data[clipIndex + 1] << 16) +
- ((int)data[clipIndex + 2] << 8) +
- ((int)data[clipIndex + 3]);
-
- byte[] clipData = new byte[clipLength];
- Array.Copy(data, clipIndex + 4, clipData, 0, clipData.Length);
-
- int streamCount = clipData[8];
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\tStreamCount: {0}", streamCount));
-#endif
- int streamOffset = 10;
- for (int streamIndex = 0;
- streamIndex < streamCount;
- streamIndex++)
- {
- TSStream stream = null;
-
- ushort PID = (ushort)
- ((clipData[streamOffset] << 8) +
- clipData[streamOffset + 1]);
-
- streamOffset += 2;
-
- var streamType = (TSStreamType)
- clipData[streamOffset + 1];
- switch (streamType)
- {
- case TSStreamType.MVC_VIDEO:
- // TODO
- break;
-
- case TSStreamType.AVC_VIDEO:
- case TSStreamType.MPEG1_VIDEO:
- case TSStreamType.MPEG2_VIDEO:
- case TSStreamType.VC1_VIDEO:
- {
- var videoFormat = (TSVideoFormat)
- (clipData[streamOffset + 2] >> 4);
- var frameRate = (TSFrameRate)
- (clipData[streamOffset + 2] & 0xF);
- var aspectRatio = (TSAspectRatio)
- (clipData[streamOffset + 3] >> 4);
-
- stream = new TSVideoStream();
- ((TSVideoStream)stream).VideoFormat = videoFormat;
- ((TSVideoStream)stream).AspectRatio = aspectRatio;
- ((TSVideoStream)stream).FrameRate = frameRate;
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2} {3} {4}",
- PID,
- streamType,
- videoFormat,
- frameRate,
- aspectRatio));
-#endif
- }
- break;
-
- case TSStreamType.AC3_AUDIO:
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- case TSStreamType.DTS_AUDIO:
- case TSStreamType.DTS_HD_AUDIO:
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- case TSStreamType.LPCM_AUDIO:
- case TSStreamType.MPEG1_AUDIO:
- case TSStreamType.MPEG2_AUDIO:
- {
- byte[] languageBytes = new byte[3];
- Array.Copy(clipData, streamOffset + 3,
- languageBytes, 0, languageBytes.Length);
- string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length);
-
- var channelLayout = (TSChannelLayout)
- (clipData[streamOffset + 2] >> 4);
- var sampleRate = (TSSampleRate)
- (clipData[streamOffset + 2] & 0xF);
-
- stream = new TSAudioStream();
- ((TSAudioStream)stream).LanguageCode = languageCode;
- ((TSAudioStream)stream).ChannelLayout = channelLayout;
- ((TSAudioStream)stream).SampleRate = TSAudioStream.ConvertSampleRate(sampleRate);
- ((TSAudioStream)stream).LanguageCode = languageCode;
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2} {3} {4}",
- PID,
- streamType,
- languageCode,
- channelLayout,
- sampleRate));
-#endif
- }
- break;
-
- case TSStreamType.INTERACTIVE_GRAPHICS:
- case TSStreamType.PRESENTATION_GRAPHICS:
- {
- byte[] languageBytes = new byte[3];
- Array.Copy(clipData, streamOffset + 2,
- languageBytes, 0, languageBytes.Length);
- string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length);
-
- stream = new TSGraphicsStream();
- stream.LanguageCode = languageCode;
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2}",
- PID,
- streamType,
- languageCode));
-#endif
- }
- break;
-
- case TSStreamType.SUBTITLE:
- {
- byte[] languageBytes = new byte[3];
- Array.Copy(clipData, streamOffset + 3,
- languageBytes, 0, languageBytes.Length);
- string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length);
-#if DEBUG
- Debug.WriteLine(string.Format(
- "\t{0} {1} {2}",
- PID,
- streamType,
- languageCode));
-#endif
- stream = new TSTextStream();
- stream.LanguageCode = languageCode;
- }
- break;
- }
-
- if (stream != null)
- {
- stream.PID = PID;
- stream.StreamType = streamType;
- Streams.Add(PID, stream);
- }
-
- streamOffset += clipData[streamOffset] + 1;
- }
- IsValid = true;
- }
- finally
- {
- if (fileReader != null) fileReader.Dispose();
- if (fileStream != null) fileStream.Dispose();
- }
- }
- }
-}
diff --git a/BDInfo/TSStreamFile.cs b/BDInfo/TSStreamFile.cs
deleted file mode 100644
index ecf6609e2..000000000
--- a/BDInfo/TSStreamFile.cs
+++ /dev/null
@@ -1,1555 +0,0 @@
-//============================================================================
-// BDInfo - Blu-ray Video and Audio Analysis Tool
-// Copyright © 2010 Cinema Squid
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//=============================================================================
-
-#undef DEBUG
-using System;
-using System.Collections.Generic;
-using System.IO;
-using MediaBrowser.Model.IO;
-
-namespace BDInfo
-{
- public class TSStreamState
- {
- public ulong TransferCount = 0;
-
- public string StreamTag = null;
-
- public ulong TotalPackets = 0;
- public ulong WindowPackets = 0;
-
- public ulong TotalBytes = 0;
- public ulong WindowBytes = 0;
-
- public long PeakTransferLength = 0;
- public long PeakTransferRate = 0;
-
- public double TransferMarker = 0;
- public double TransferInterval = 0;
-
- public TSStreamBuffer StreamBuffer = new TSStreamBuffer();
-
- public uint Parse = 0;
- public bool TransferState = false;
- public int TransferLength = 0;
- public int PacketLength = 0;
- public byte PacketLengthParse = 0;
- public byte PacketParse = 0;
-
- public byte PTSParse = 0;
- public ulong PTS = 0;
- public ulong PTSTemp = 0;
- public ulong PTSLast = 0;
- public ulong PTSPrev = 0;
- public ulong PTSDiff = 0;
- public ulong PTSCount = 0;
- public ulong PTSTransfer = 0;
-
- public byte DTSParse = 0;
- public ulong DTSTemp = 0;
- public ulong DTSPrev = 0;
-
- public byte PESHeaderLength = 0;
- public byte PESHeaderFlags = 0;
-#if DEBUG
- public byte PESHeaderIndex = 0;
- public byte[] PESHeader = new byte[256 + 9];
-#endif
- }
-
- public class TSPacketParser
- {
- public bool SyncState = false;
- public byte TimeCodeParse = 4;
- public byte PacketLength = 0;
- public byte HeaderParse = 0;
-
- public uint TimeCode;
- public byte TransportErrorIndicator;
- public byte PayloadUnitStartIndicator;
- public byte TransportPriority;
- public ushort PID;
- public byte TransportScramblingControl;
- public byte AdaptionFieldControl;
-
- public bool AdaptionFieldState = false;
- public byte AdaptionFieldParse = 0;
- public byte AdaptionFieldLength = 0;
-
- public ushort PCRPID = 0xFFFF;
- public byte PCRParse = 0;
- public ulong PreviousPCR = 0;
- public ulong PCR = 0;
- public ulong PCRCount = 0;
- public ulong PTSFirst = ulong.MaxValue;
- public ulong PTSLast = ulong.MinValue;
- public ulong PTSDiff = 0;
-
- public byte[] PAT = new byte[1024];
- public bool PATSectionStart = false;
- public byte PATPointerField = 0;
- public uint PATOffset = 0;
- public byte PATSectionLengthParse = 0;
- public ushort PATSectionLength = 0;
- public uint PATSectionParse = 0;
- public bool PATTransferState = false;
- public byte PATSectionNumber = 0;
- public byte PATLastSectionNumber = 0;
-
- public ushort TransportStreamId = 0xFFFF;
-
- public List<TSDescriptor> PMTProgramDescriptors = new List<TSDescriptor>();
- public ushort PMTPID = 0xFFFF;
- public Dictionary<ushort, byte[]> PMT = new Dictionary<ushort, byte[]>();
- public bool PMTSectionStart = false;
- public ushort PMTProgramInfoLength = 0;
- public byte PMTProgramDescriptor = 0;
- public byte PMTProgramDescriptorLengthParse = 0;
- public byte PMTProgramDescriptorLength = 0;
- public ushort PMTStreamInfoLength = 0;
- public uint PMTStreamDescriptorLengthParse = 0;
- public uint PMTStreamDescriptorLength = 0;
- public byte PMTPointerField = 0;
- public uint PMTOffset = 0;
- public uint PMTSectionLengthParse = 0;
- public ushort PMTSectionLength = 0;
- public uint PMTSectionParse = 0;
- public bool PMTTransferState = false;
- public byte PMTSectionNumber = 0;
- public byte PMTLastSectionNumber = 0;
-
- public byte PMTTemp = 0;
-
- public TSStream Stream = null;
- public TSStreamState StreamState = null;
-
- public ulong TotalPackets = 0;
- }
-
- public class TSStreamDiagnostics
- {
- public ulong Bytes = 0;
- public ulong Packets = 0;
- public double Marker = 0;
- public double Interval = 0;
- public string Tag = null;
- }
-
- public class TSStreamFile
- {
- public FileSystemMetadata FileInfo = null;
- public string Name = null;
- public long Size = 0;
- public double Length = 0;
-
- public TSInterleavedFile InterleavedFile = null;
-
- private Dictionary<ushort, TSStreamState> StreamStates =
- new Dictionary<ushort, TSStreamState>();
-
- public Dictionary<ushort, TSStream> Streams =
- new Dictionary<ushort, TSStream>();
-
- public Dictionary<ushort, List<TSStreamDiagnostics>> StreamDiagnostics =
- new Dictionary<ushort, List<TSStreamDiagnostics>>();
-
- private List<TSPlaylistFile> Playlists = null;
-
- private readonly IFileSystem _fileSystem;
-
- public TSStreamFile(FileSystemMetadata fileInfo, IFileSystem fileSystem)
- {
- FileInfo = fileInfo;
- _fileSystem = fileSystem;
- Name = fileInfo.Name.ToUpper();
- }
-
- public string DisplayName
- {
- get
- {
- if (BDInfoSettings.EnableSSIF &&
- InterleavedFile != null)
- {
- return InterleavedFile.Name;
- }
- return Name;
- }
- }
-
- private bool ScanStream(
- TSStream stream,
- TSStreamState streamState,
- TSStreamBuffer buffer)
- {
- streamState.StreamTag = null;
-
- long bitrate = 0;
- if (stream.IsAudioStream &&
- streamState.PTSTransfer > 0)
- {
- bitrate = (long)Math.Round(
- (buffer.TransferLength * 8.0) /
- ((double)streamState.PTSTransfer / 90000));
-
- if (bitrate > streamState.PeakTransferRate)
- {
- streamState.PeakTransferRate = bitrate;
- }
- }
- if (buffer.TransferLength > streamState.PeakTransferLength)
- {
- streamState.PeakTransferLength = buffer.TransferLength;
- }
-
- buffer.BeginRead();
- switch (stream.StreamType)
- {
- case TSStreamType.MPEG2_VIDEO:
- TSCodecMPEG2.Scan(
- (TSVideoStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.AVC_VIDEO:
- TSCodecAVC.Scan(
- (TSVideoStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.MVC_VIDEO:
- TSCodecMVC.Scan(
- (TSVideoStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.VC1_VIDEO:
- TSCodecVC1.Scan(
- (TSVideoStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.AC3_AUDIO:
- TSCodecAC3.Scan(
- (TSAudioStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- TSCodecAC3.Scan(
- (TSAudioStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- TSCodecTrueHD.Scan(
- (TSAudioStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.LPCM_AUDIO:
- TSCodecLPCM.Scan(
- (TSAudioStream)stream, buffer, ref streamState.StreamTag);
- break;
-
- case TSStreamType.DTS_AUDIO:
- TSCodecDTS.Scan(
- (TSAudioStream)stream, buffer, bitrate, ref streamState.StreamTag);
- break;
-
- case TSStreamType.DTS_HD_AUDIO:
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- TSCodecDTSHD.Scan(
- (TSAudioStream)stream, buffer, bitrate, ref streamState.StreamTag);
- break;
-
- default:
- stream.IsInitialized = true;
- break;
- }
- buffer.EndRead();
- streamState.StreamBuffer.Reset();
-
- bool isAVC = false;
- bool isMVC = false;
- foreach (var finishedStream in Streams.Values)
- {
- if (!finishedStream.IsInitialized)
- {
- return false;
- }
- if (finishedStream.StreamType == TSStreamType.AVC_VIDEO)
- {
- isAVC = true;
- }
- if (finishedStream.StreamType == TSStreamType.MVC_VIDEO)
- {
- isMVC = true;
- }
- }
- if (isMVC && !isAVC)
- {
- return false;
- }
- return true;
- }
-
- private void UpdateStreamBitrates(
- ushort PTSPID,
- ulong PTS,
- ulong PTSDiff)
- {
- if (Playlists == null) return;
-
- foreach (ushort PID in StreamStates.Keys)
- {
- if (Streams.ContainsKey(PID) &&
- Streams[PID].IsVideoStream &&
- PID != PTSPID)
- {
- continue;
- }
- if (StreamStates[PID].WindowPackets == 0)
- {
- continue;
- }
- UpdateStreamBitrate(PID, PTSPID, PTS, PTSDiff);
- }
-
- foreach (var playlist in Playlists)
- {
- double packetSeconds = 0;
- foreach (var clip in playlist.StreamClips)
- {
- if (clip.AngleIndex == 0)
- {
- packetSeconds += clip.PacketSeconds;
- }
- }
- if (packetSeconds > 0)
- {
- foreach (var playlistStream in playlist.SortedStreams)
- {
- if (playlistStream.IsVBR)
- {
- playlistStream.BitRate = (long)Math.Round(
- ((playlistStream.PayloadBytes * 8.0) / packetSeconds));
-
- if (playlistStream.StreamType == TSStreamType.AC3_TRUE_HD_AUDIO &&
- ((TSAudioStream)playlistStream).CoreStream != null)
- {
- playlistStream.BitRate -=
- ((TSAudioStream)playlistStream).CoreStream.BitRate;
- }
- }
- }
- }
- }
- }
-
- private void UpdateStreamBitrate(
- ushort PID,
- ushort PTSPID,
- ulong PTS,
- ulong PTSDiff)
- {
- if (Playlists == null) return;
-
- var streamState = StreamStates[PID];
- double streamTime = (double)PTS / 90000;
- double streamInterval = (double)PTSDiff / 90000;
- double streamOffset = streamTime + streamInterval;
-
- foreach (var playlist in Playlists)
- {
- foreach (var clip in playlist.StreamClips)
- {
- if (clip.Name != this.Name) continue;
-
- if (streamTime == 0 ||
- (streamTime >= clip.TimeIn &&
- streamTime <= clip.TimeOut))
- {
- clip.PayloadBytes += streamState.WindowBytes;
- clip.PacketCount += streamState.WindowPackets;
-
- if (streamOffset > clip.TimeIn &&
- streamOffset - clip.TimeIn > clip.PacketSeconds)
- {
- clip.PacketSeconds = streamOffset - clip.TimeIn;
- }
-
- var playlistStreams = playlist.Streams;
- if (clip.AngleIndex > 0 &&
- clip.AngleIndex < playlist.AngleStreams.Count + 1)
- {
- playlistStreams = playlist.AngleStreams[clip.AngleIndex - 1];
- }
- if (playlistStreams.ContainsKey(PID))
- {
- var stream = playlistStreams[PID];
-
- stream.PayloadBytes += streamState.WindowBytes;
- stream.PacketCount += streamState.WindowPackets;
-
- if (stream.IsVideoStream)
- {
- stream.PacketSeconds += streamInterval;
-
- stream.ActiveBitRate = (long)Math.Round(
- ((stream.PayloadBytes * 8.0) /
- stream.PacketSeconds));
- }
-
- if (stream.StreamType == TSStreamType.AC3_TRUE_HD_AUDIO &&
- ((TSAudioStream)stream).CoreStream != null)
- {
- stream.ActiveBitRate -=
- ((TSAudioStream)stream).CoreStream.BitRate;
- }
- }
- }
- }
- }
-
- if (Streams.ContainsKey(PID))
- {
- var stream = Streams[PID];
- stream.PayloadBytes += streamState.WindowBytes;
- stream.PacketCount += streamState.WindowPackets;
-
- if (stream.IsVideoStream)
- {
- var diag = new TSStreamDiagnostics();
- diag.Marker = (double)PTS / 90000;
- diag.Interval = (double)PTSDiff / 90000;
- diag.Bytes = streamState.WindowBytes;
- diag.Packets = streamState.WindowPackets;
- diag.Tag = streamState.StreamTag;
- StreamDiagnostics[PID].Add(diag);
-
- stream.PacketSeconds += streamInterval;
- }
- }
- streamState.WindowPackets = 0;
- streamState.WindowBytes = 0;
- }
-
- public void Scan(List<TSPlaylistFile> playlists, bool isFullScan)
- {
- if (playlists == null || playlists.Count == 0)
- {
- return;
- }
-
- Playlists = playlists;
- int dataSize = 16384;
- Stream fileStream = null;
- try
- {
- string fileName;
- if (BDInfoSettings.EnableSSIF &&
- InterleavedFile != null)
- {
- fileName = InterleavedFile.FileInfo.FullName;
- }
- else
- {
- fileName = FileInfo.FullName;
- }
- fileStream = _fileSystem.GetFileStream(
- fileName,
- FileOpenMode.Open,
- FileAccessMode.Read,
- FileShareMode.Read,
- false);
-
- Size = 0;
- Length = 0;
-
- Streams.Clear();
- StreamStates.Clear();
- StreamDiagnostics.Clear();
-
- var parser =
- new TSPacketParser();
-
- long fileLength = (uint)fileStream.Length;
- byte[] buffer = new byte[dataSize];
- int bufferLength = 0;
- while ((bufferLength =
- fileStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- int offset = 0;
- for (int i = 0; i < bufferLength; i++)
- {
- if (parser.SyncState == false)
- {
- if (parser.TimeCodeParse > 0)
- {
- parser.TimeCodeParse--;
- switch (parser.TimeCodeParse)
- {
- case 3:
- parser.TimeCode = 0;
- parser.TimeCode |=
- ((uint)buffer[i] & 0x3F) << 24;
- break;
- case 2:
- parser.TimeCode |=
- ((uint)buffer[i] & 0xFF) << 16;
- break;
- case 1:
- parser.TimeCode |=
- ((uint)buffer[i] & 0xFF) << 8;
- break;
- case 0:
- parser.TimeCode |=
- ((uint)buffer[i] & 0xFF);
- break;
- }
- }
- else if (buffer[i] == 0x47)
- {
- parser.SyncState = true;
- parser.PacketLength = 187;
- parser.TimeCodeParse = 4;
- parser.HeaderParse = 3;
- }
- }
- else if (parser.HeaderParse > 0)
- {
- parser.PacketLength--;
- parser.HeaderParse--;
-
- switch (parser.HeaderParse)
- {
- case 2:
- {
- parser.TransportErrorIndicator =
- (byte)((buffer[i] >> 7) & 0x1);
- parser.PayloadUnitStartIndicator =
- (byte)((buffer[i] >> 6) & 0x1);
- parser.TransportPriority =
- (byte)((buffer[i] >> 5) & 0x1);
- parser.PID =
- (ushort)((buffer[i] & 0x1f) << 8);
- }
- break;
-
- case 1:
- {
- parser.PID |= (ushort)buffer[i];
- if (Streams.ContainsKey(parser.PID))
- {
- parser.Stream = Streams[parser.PID];
- }
- else
- {
- parser.Stream = null;
- }
- if (!StreamStates.ContainsKey(parser.PID))
- {
- StreamStates[parser.PID] = new TSStreamState();
- }
- parser.StreamState = StreamStates[parser.PID];
- parser.StreamState.TotalPackets++;
- parser.StreamState.WindowPackets++;
- parser.TotalPackets++;
- }
- break;
-
- case 0:
- {
- parser.TransportScramblingControl =
- (byte)((buffer[i] >> 6) & 0x3);
- parser.AdaptionFieldControl =
- (byte)((buffer[i] >> 4) & 0x3);
-
- if ((parser.AdaptionFieldControl & 0x2) == 0x2)
- {
- parser.AdaptionFieldState = true;
- }
- if (parser.PayloadUnitStartIndicator == 1)
- {
- if (parser.PID == 0)
- {
- parser.PATSectionStart = true;
- }
- else if (parser.PID == parser.PMTPID)
- {
- parser.PMTSectionStart = true;
- }
- else if (parser.StreamState != null &&
- parser.StreamState.TransferState)
- {
- parser.StreamState.TransferState = false;
- parser.StreamState.TransferCount++;
-
- bool isFinished = ScanStream(
- parser.Stream,
- parser.StreamState,
- parser.StreamState.StreamBuffer);
-
- if (!isFullScan && isFinished)
- {
- return;
- }
- }
- }
- }
- break;
- }
- }
- else if (parser.AdaptionFieldState)
- {
- parser.PacketLength--;
- parser.AdaptionFieldParse = buffer[i];
- parser.AdaptionFieldLength = buffer[i];
- parser.AdaptionFieldState = false;
- }
- else if (parser.AdaptionFieldParse > 0)
- {
- parser.PacketLength--;
- parser.AdaptionFieldParse--;
- if ((parser.AdaptionFieldLength - parser.AdaptionFieldParse) == 1)
- {
- if ((buffer[i] & 0x10) == 0x10)
- {
- parser.PCRParse = 6;
- parser.PCR = 0;
- }
- }
- else if (parser.PCRParse > 0)
- {
- parser.PCRParse--;
- parser.PCR = (parser.PCR << 8) + (ulong)buffer[i];
- if (parser.PCRParse == 0)
- {
- parser.PreviousPCR = parser.PCR;
- parser.PCR = (parser.PCR & 0x1FF) +
- ((parser.PCR >> 15) * 300);
- }
- parser.PCRCount++;
- }
- if (parser.PacketLength == 0)
- {
- parser.SyncState = false;
- }
- }
- else if (parser.PID == 0)
- {
- if (parser.PATTransferState)
- {
- if ((bufferLength - i) > parser.PATSectionLength)
- {
- offset = parser.PATSectionLength;
- }
- else
- {
- offset = (bufferLength - i);
- }
- if (parser.PacketLength <= offset)
- {
- offset = parser.PacketLength;
- }
-
- for (int k = 0; k < offset; k++)
- {
- parser.PAT[parser.PATOffset++] = buffer[i++];
- parser.PATSectionLength--;
- parser.PacketLength--;
- }
- --i;
-
- if (parser.PATSectionLength == 0)
- {
- parser.PATTransferState = false;
- if (parser.PATSectionNumber == parser.PATLastSectionNumber)
- {
- for (int k = 0; k < (parser.PATOffset - 4); k += 4)
- {
- uint programNumber = (uint)
- ((parser.PAT[k] << 8) +
- parser.PAT[k + 1]);
-
- ushort programPID = (ushort)
- (((parser.PAT[k + 2] & 0x1F) << 8) +
- parser.PAT[k + 3]);
-
- if (programNumber == 1)
- {
- parser.PMTPID = programPID;
- }
- }
- }
- }
- }
- else
- {
- --parser.PacketLength;
- if (parser.PATSectionStart)
- {
- parser.PATPointerField = buffer[i];
- if (parser.PATPointerField == 0)
- {
- parser.PATSectionLengthParse = 3;
- }
- parser.PATSectionStart = false;
- }
- else if (parser.PATPointerField > 0)
- {
- --parser.PATPointerField;
- if (parser.PATPointerField == 0)
- {
- parser.PATSectionLengthParse = 3;
- }
- }
- else if (parser.PATSectionLengthParse > 0)
- {
- --parser.PATSectionLengthParse;
- switch (parser.PATSectionLengthParse)
- {
- case 2:
- break;
- case 1:
- parser.PATSectionLength = (ushort)
- ((buffer[i] & 0xF) << 8);
- break;
- case 0:
- parser.PATSectionLength |= buffer[i];
- if (parser.PATSectionLength > 1021)
- {
- parser.PATSectionLength = 0;
- }
- else
- {
- parser.PATSectionParse = 5;
- }
- break;
- }
- }
- else if (parser.PATSectionParse > 0)
- {
- --parser.PATSectionLength;
- --parser.PATSectionParse;
-
- switch (parser.PATSectionParse)
- {
- case 4:
- parser.TransportStreamId = (ushort)
- (buffer[i] << 8);
- break;
- case 3:
- parser.TransportStreamId |= buffer[i];
- break;
- case 2:
- break;
- case 1:
- parser.PATSectionNumber = buffer[i];
- if (parser.PATSectionNumber == 0)
- {
- parser.PATOffset = 0;
- }
- break;
- case 0:
- parser.PATLastSectionNumber = buffer[i];
- parser.PATTransferState = true;
- break;
- }
- }
- }
- if (parser.PacketLength == 0)
- {
- parser.SyncState = false;
- }
- }
- else if (parser.PID == parser.PMTPID)
- {
- if (parser.PMTTransferState)
- {
- if ((bufferLength - i) >= parser.PMTSectionLength)
- {
- offset = parser.PMTSectionLength;
- }
- else
- {
- offset = (bufferLength - i);
- }
- if (parser.PacketLength <= offset)
- {
- offset = parser.PacketLength;
- }
- if (!parser.PMT.ContainsKey(parser.PID))
- {
- parser.PMT[parser.PID] = new byte[1024];
- }
-
- byte[] PMT = parser.PMT[parser.PID];
- for (int k = 0; k < offset; k++)
- {
- PMT[parser.PMTOffset++] = buffer[i++];
- --parser.PMTSectionLength;
- --parser.PacketLength;
- }
- --i;
-
- if (parser.PMTSectionLength == 0)
- {
- parser.PMTTransferState = false;
- if (parser.PMTSectionNumber == parser.PMTLastSectionNumber)
- {
- //Console.WriteLine("PMT Start: " + parser.PMTTemp);
- try
- {
- for (int k = 0; k < (parser.PMTOffset - 4); k += 5)
- {
- byte streamType = PMT[k];
-
- ushort streamPID = (ushort)
- (((PMT[k + 1] & 0x1F) << 8) +
- PMT[k + 2]);
-
- ushort streamInfoLength = (ushort)
- (((PMT[k + 3] & 0xF) << 8) +
- PMT[k + 4]);
-
- /*
- if (streamInfoLength == 2)
- {
- // TODO: Cleanup
- //streamInfoLength = 0;
- }
-
- Console.WriteLine(string.Format(
- "Type: {0} PID: {1} Length: {2}",
- streamType, streamPID, streamInfoLength));
- */
-
- if (!Streams.ContainsKey(streamPID))
- {
- var streamDescriptors =
- new List<TSDescriptor>();
-
- /*
- * TODO: Getting bad streamInfoLength
- if (streamInfoLength > 0)
- {
- for (int d = 0; d < streamInfoLength; d++)
- {
- byte name = PMT[k + d + 5];
- byte length = PMT[k + d + 6];
- TSDescriptor descriptor =
- new TSDescriptor(name, length);
- for (int v = 0; v < length; v++)
- {
- descriptor.Value[v] =
- PMT[k + d + v + 7];
- }
- streamDescriptors.Add(descriptor);
- d += (length + 1);
- }
- }
- */
- CreateStream(streamPID, streamType, streamDescriptors);
- }
- k += streamInfoLength;
- }
- }
- catch
- {
- // TODO
- //Console.WriteLine(ex.Message);
- }
- }
- }
- }
- else
- {
- --parser.PacketLength;
- if (parser.PMTSectionStart)
- {
- parser.PMTPointerField = buffer[i];
- if (parser.PMTPointerField == 0)
- {
- parser.PMTSectionLengthParse = 3;
- }
- parser.PMTSectionStart = false;
- }
- else if (parser.PMTPointerField > 0)
- {
- --parser.PMTPointerField;
- if (parser.PMTPointerField == 0)
- {
- parser.PMTSectionLengthParse = 3;
- }
- }
- else if (parser.PMTSectionLengthParse > 0)
- {
- --parser.PMTSectionLengthParse;
- switch (parser.PMTSectionLengthParse)
- {
- case 2:
- if (buffer[i] != 0x2)
- {
- parser.PMTSectionLengthParse = 0;
- }
- break;
- case 1:
- parser.PMTSectionLength = (ushort)
- ((buffer[i] & 0xF) << 8);
- break;
- case 0:
- parser.PMTSectionLength |= buffer[i];
- if (parser.PMTSectionLength > 1021)
- {
- parser.PMTSectionLength = 0;
- }
- else
- {
- parser.PMTSectionParse = 9;
- }
- break;
- }
- }
- else if (parser.PMTSectionParse > 0)
- {
- --parser.PMTSectionLength;
- --parser.PMTSectionParse;
-
- switch (parser.PMTSectionParse)
- {
- case 8:
- case 7:
- break;
- case 6:
- parser.PMTTemp = buffer[i];
- break;
- case 5:
- parser.PMTSectionNumber = buffer[i];
- if (parser.PMTSectionNumber == 0)
- {
- parser.PMTOffset = 0;
- }
- break;
- case 4:
- parser.PMTLastSectionNumber = buffer[i];
- break;
- case 3:
- parser.PCRPID = (ushort)
- ((buffer[i] & 0x1F) << 8);
- break;
- case 2:
- parser.PCRPID |= buffer[i];
- break;
- case 1:
- parser.PMTProgramInfoLength = (ushort)
- ((buffer[i] & 0xF) << 8);
- break;
- case 0:
- parser.PMTProgramInfoLength |= buffer[i];
- if (parser.PMTProgramInfoLength == 0)
- {
- parser.PMTTransferState = true;
- }
- else
- {
- parser.PMTProgramDescriptorLengthParse = 2;
- }
- break;
- }
- }
- else if (parser.PMTProgramInfoLength > 0)
- {
- --parser.PMTSectionLength;
- --parser.PMTProgramInfoLength;
-
- if (parser.PMTProgramDescriptorLengthParse > 0)
- {
- --parser.PMTProgramDescriptorLengthParse;
- switch (parser.PMTProgramDescriptorLengthParse)
- {
- case 1:
- parser.PMTProgramDescriptor = buffer[i];
- break;
- case 0:
- parser.PMTProgramDescriptorLength = buffer[i];
- parser.PMTProgramDescriptors.Add(
- new TSDescriptor(
- parser.PMTProgramDescriptor,
- parser.PMTProgramDescriptorLength));
- break;
- }
- }
- else if (parser.PMTProgramDescriptorLength > 0)
- {
- --parser.PMTProgramDescriptorLength;
-
- var descriptor = parser.PMTProgramDescriptors[
- parser.PMTProgramDescriptors.Count - 1];
-
- int valueIndex =
- descriptor.Value.Length -
- parser.PMTProgramDescriptorLength - 1;
-
- descriptor.Value[valueIndex] = buffer[i];
-
- if (parser.PMTProgramDescriptorLength == 0 &&
- parser.PMTProgramInfoLength > 0)
- {
- parser.PMTProgramDescriptorLengthParse = 2;
- }
- }
- if (parser.PMTProgramInfoLength == 0)
- {
- parser.PMTTransferState = true;
- }
- }
- }
- if (parser.PacketLength == 0)
- {
- parser.SyncState = false;
- }
- }
- else if (parser.Stream != null &&
- parser.StreamState != null &&
- parser.TransportScramblingControl == 0)
- {
- var stream = parser.Stream;
- var streamState = parser.StreamState;
-
- streamState.Parse =
- (streamState.Parse << 8) + buffer[i];
-
- if (streamState.TransferState)
- {
- if ((bufferLength - i) >= streamState.PacketLength &&
- streamState.PacketLength > 0)
- {
- offset = streamState.PacketLength;
- }
- else
- {
- offset = (bufferLength - i);
- }
- if (parser.PacketLength <= offset)
- {
- offset = parser.PacketLength;
- }
- streamState.TransferLength = offset;
-
- if (!stream.IsInitialized ||
- stream.IsVideoStream)
- {
- streamState.StreamBuffer.Add(
- buffer, i, offset);
- }
- else
- {
- streamState.StreamBuffer.TransferLength += offset;
- }
-
- i += (int)(streamState.TransferLength - 1);
- streamState.PacketLength -= streamState.TransferLength;
- parser.PacketLength -= (byte)streamState.TransferLength;
-
- streamState.TotalBytes += (ulong)streamState.TransferLength;
- streamState.WindowBytes += (ulong)streamState.TransferLength;
-
- if (streamState.PacketLength == 0)
- {
- streamState.TransferState = false;
- streamState.TransferCount++;
- bool isFinished = ScanStream(
- stream,
- streamState,
- streamState.StreamBuffer);
-
- if (!isFullScan && isFinished)
- {
- return;
- }
- }
- }
- else
- {
- --parser.PacketLength;
-
- bool headerFound = false;
- if (stream.IsVideoStream &&
- streamState.Parse == 0x000001FD)
- {
- headerFound = true;
- }
- if (stream.IsVideoStream &&
- streamState.Parse >= 0x000001E0 &&
- streamState.Parse <= 0x000001EF)
- {
- headerFound = true;
- }
- if (stream.IsAudioStream &&
- streamState.Parse == 0x000001BD)
- {
- headerFound = true;
- }
- if (stream.IsAudioStream &&
- (streamState.Parse == 0x000001FA ||
- streamState.Parse == 0x000001FD))
- {
- headerFound = true;
- }
-
- if (!stream.IsVideoStream &&
- !stream.IsAudioStream &&
- (streamState.Parse == 0x000001FA ||
- streamState.Parse == 0x000001FD ||
- streamState.Parse == 0x000001BD ||
- (streamState.Parse >= 0x000001E0 &&
- streamState.Parse <= 0x000001EF)))
- {
- headerFound = true;
- }
-
- if (headerFound)
- {
- streamState.PacketLengthParse = 2;
-#if DEBUG
- streamState.PESHeaderIndex = 0;
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)((streamState.Parse >> 24) & 0xFF);
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)((streamState.Parse >> 16) & 0xFF);
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)((streamState.Parse >> 8) & 0xFF);
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- }
- else if (streamState.PacketLengthParse > 0)
- {
- --streamState.PacketLengthParse;
- switch (streamState.PacketLengthParse)
- {
- case 1:
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 0:
- streamState.PacketLength =
- (int)(streamState.Parse & 0xFFFF);
- streamState.PacketParse = 3;
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
- }
- }
- else if (streamState.PacketParse > 0)
- {
- --streamState.PacketLength;
- --streamState.PacketParse;
-
- switch (streamState.PacketParse)
- {
- case 2:
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 1:
- streamState.PESHeaderFlags =
- (byte)(streamState.Parse & 0xFF);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 0:
- streamState.PESHeaderLength =
- (byte)(streamState.Parse & 0xFF);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- if ((streamState.PESHeaderFlags & 0xC0) == 0x80)
- {
- streamState.PTSParse = 5;
- }
- else if ((streamState.PESHeaderFlags & 0xC0) == 0xC0)
- {
- streamState.DTSParse = 10;
- }
- if (streamState.PESHeaderLength == 0)
- {
- streamState.TransferState = true;
- }
- break;
- }
- }
- else if (streamState.PTSParse > 0)
- {
- --streamState.PacketLength;
- --streamState.PESHeaderLength;
- --streamState.PTSParse;
-
- switch (streamState.PTSParse)
- {
- case 4:
- streamState.PTSTemp =
- ((streamState.Parse & 0xE) << 29);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- break;
-
- case 3:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFF) << 22);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 2:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFE) << 14);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 1:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFF) << 7);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 0:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFE) >> 1);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- streamState.PTS = streamState.PTSTemp;
-
- if (streamState.PTS > streamState.PTSLast)
- {
- if (streamState.PTSLast > 0)
- {
- streamState.PTSTransfer = (streamState.PTS - streamState.PTSLast);
- }
- streamState.PTSLast = streamState.PTS;
- }
-
- streamState.PTSDiff = streamState.PTS - streamState.DTSPrev;
-
- if (streamState.PTSCount > 0 &&
- stream.IsVideoStream)
- {
- UpdateStreamBitrates(stream.PID, streamState.PTS, streamState.PTSDiff);
- if (streamState.DTSTemp < parser.PTSFirst)
- {
- parser.PTSFirst = streamState.DTSTemp;
- }
- if (streamState.DTSTemp > parser.PTSLast)
- {
- parser.PTSLast = streamState.DTSTemp;
- }
- Length = (double)(parser.PTSLast - parser.PTSFirst) / 90000;
- }
-
- streamState.DTSPrev = streamState.PTS;
- streamState.PTSCount++;
- if (streamState.PESHeaderLength == 0)
- {
- streamState.TransferState = true;
- }
- break;
- }
- }
- else if (streamState.DTSParse > 0)
- {
- --streamState.PacketLength;
- --streamState.PESHeaderLength;
- --streamState.DTSParse;
-
- switch (streamState.DTSParse)
- {
- case 9:
- streamState.PTSTemp =
- ((streamState.Parse & 0xE) << 29);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 8:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFF) << 22);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 7:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFE) << 14);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- break;
-
- case 6:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFF) << 7);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 5:
- streamState.PTSTemp |=
- ((streamState.Parse & 0xFE) >> 1);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- streamState.PTS = streamState.PTSTemp;
- if (streamState.PTS > streamState.PTSLast)
- {
- streamState.PTSLast = streamState.PTS;
- }
- break;
-
- case 4:
- streamState.DTSTemp =
- ((streamState.Parse & 0xE) << 29);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- break;
-
- case 3:
- streamState.DTSTemp |=
- ((streamState.Parse & 0xFF) << 22);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- break;
-
- case 2:
- streamState.DTSTemp |=
- ((streamState.Parse & 0xFE) << 14);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- break;
-
- case 1:
- streamState.DTSTemp |=
- ((streamState.Parse & 0xFF) << 7);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- break;
-
- case 0:
- streamState.DTSTemp |=
- ((streamState.Parse & 0xFE) >> 1);
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xff);
-#endif
- streamState.PTSDiff = streamState.DTSTemp - streamState.DTSPrev;
-
- if (streamState.PTSCount > 0 &&
- stream.IsVideoStream)
- {
- UpdateStreamBitrates(stream.PID, streamState.DTSTemp, streamState.PTSDiff);
- if (streamState.DTSTemp < parser.PTSFirst)
- {
- parser.PTSFirst = streamState.DTSTemp;
- }
- if (streamState.DTSTemp > parser.PTSLast)
- {
- parser.PTSLast = streamState.DTSTemp;
- }
- Length = (double)(parser.PTSLast - parser.PTSFirst) / 90000;
- }
- streamState.DTSPrev = streamState.DTSTemp;
- streamState.PTSCount++;
- if (streamState.PESHeaderLength == 0)
- {
- streamState.TransferState = true;
- }
- break;
- }
- }
- else if (streamState.PESHeaderLength > 0)
- {
- --streamState.PacketLength;
- --streamState.PESHeaderLength;
-#if DEBUG
- streamState.PESHeader[streamState.PESHeaderIndex++] =
- (byte)(streamState.Parse & 0xFF);
-#endif
- if (streamState.PESHeaderLength == 0)
- {
- streamState.TransferState = true;
- }
- }
- }
- if (parser.PacketLength == 0)
- {
- parser.SyncState = false;
- }
- }
- else
- {
- parser.PacketLength--;
- if ((bufferLength - i) >= parser.PacketLength)
- {
- i = i + parser.PacketLength;
- parser.PacketLength = 0;
- }
- else
- {
- parser.PacketLength -= (byte)((bufferLength - i) + 1);
- i = bufferLength;
- }
- if (parser.PacketLength == 0)
- {
- parser.SyncState = false;
- }
- }
- }
- Size += bufferLength;
- }
-
- ulong PTSLast = 0;
- ulong PTSDiff = 0;
- foreach (var stream in Streams.Values)
- {
- if (!stream.IsVideoStream) continue;
-
- if (StreamStates.ContainsKey(stream.PID) &&
- StreamStates[stream.PID].PTSLast > PTSLast)
- {
- PTSLast = StreamStates[stream.PID].PTSLast;
- PTSDiff = PTSLast - StreamStates[stream.PID].DTSPrev;
- }
- UpdateStreamBitrates(stream.PID, PTSLast, PTSDiff);
- }
- }
- finally
- {
- if (fileStream != null)
- {
- fileStream.Dispose();
- }
- }
- }
-
- private TSStream CreateStream(
- ushort streamPID,
- byte streamType,
- List<TSDescriptor> streamDescriptors)
- {
- TSStream stream = null;
-
- switch ((TSStreamType)streamType)
- {
- case TSStreamType.MVC_VIDEO:
- case TSStreamType.AVC_VIDEO:
- case TSStreamType.MPEG1_VIDEO:
- case TSStreamType.MPEG2_VIDEO:
- case TSStreamType.VC1_VIDEO:
- {
- stream = new TSVideoStream();
- }
- break;
-
- case TSStreamType.AC3_AUDIO:
- case TSStreamType.AC3_PLUS_AUDIO:
- case TSStreamType.AC3_PLUS_SECONDARY_AUDIO:
- case TSStreamType.AC3_TRUE_HD_AUDIO:
- case TSStreamType.DTS_AUDIO:
- case TSStreamType.DTS_HD_AUDIO:
- case TSStreamType.DTS_HD_MASTER_AUDIO:
- case TSStreamType.DTS_HD_SECONDARY_AUDIO:
- case TSStreamType.LPCM_AUDIO:
- case TSStreamType.MPEG1_AUDIO:
- case TSStreamType.MPEG2_AUDIO:
- {
- stream = new TSAudioStream();
- }
- break;
-
- case TSStreamType.INTERACTIVE_GRAPHICS:
- case TSStreamType.PRESENTATION_GRAPHICS:
- {
- stream = new TSGraphicsStream();
- }
- break;
-
- case TSStreamType.SUBTITLE:
- {
- stream = new TSTextStream();
- }
- break;
-
- default:
- break;
- }
-
- if (stream != null &&
- !Streams.ContainsKey(streamPID))
- {
- stream.PID = streamPID;
- stream.StreamType = (TSStreamType)streamType;
- stream.Descriptors = streamDescriptors;
- Streams[stream.PID] = stream;
- }
- if (!StreamDiagnostics.ContainsKey(streamPID))
- {
- StreamDiagnostics[streamPID] =
- new List<TSStreamDiagnostics>();
- }
-
- return stream;
- }
- }
-}
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 758202af6..5c4a031bc 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -1,26 +1,155 @@
# Jellyfin Contributors
- - [JoshuaBoniface](https://github.com/joshuaboniface)
- - [nvllsvm](https://github.com/nvllsvm)
- - [JustAMan](https://github.com/JustAMan)
+ - [97carmine](https://github.com/97carmine)
+ - [Abbe98](https://github.com/Abbe98)
+ - [agrenott](https://github.com/agrenott)
+ - [AndreCarvalho](https://github.com/AndreCarvalho)
+ - [anthonylavado](https://github.com/anthonylavado)
+ - [Artiume](https://github.com/Artiume)
+ - [AThomsen](https://github.com/AThomsen)
+ - [barongreenback](https://github.com/BaronGreenback)
+ - [barronpm](https://github.com/barronpm)
+ - [bilde2910](https://github.com/bilde2910)
+ - [bfayers](https://github.com/bfayers)
+ - [BnMcG](https://github.com/BnMcG)
+ - [Bond-009](https://github.com/Bond-009)
+ - [brianjmurrell](https://github.com/brianjmurrell)
+ - [bugfixin](https://github.com/bugfixin)
+ - [chaosinnovator](https://github.com/chaosinnovator)
+ - [ckcr4lyf](https://github.com/ckcr4lyf)
+ - [cocool97](https://github.com/cocool97)
+ - [ConfusedPolarBear](https://github.com/ConfusedPolarBear)
+ - [crankdoofus](https://github.com/crankdoofus)
+ - [crobibero](https://github.com/crobibero)
+ - [cromefire](https://github.com/cromefire)
+ - [cryptobank](https://github.com/cryptobank)
+ - [cvium](https://github.com/cvium)
+ - [dannymichel](https://github.com/dannymichel)
+ - [DaveChild](https://github.com/DaveChild)
+ - [Delgan](https://github.com/Delgan)
- [dcrdev](https://github.com/dcrdev)
+ - [dhartung](https://github.com/dhartung)
+ - [dinki](https://github.com/dinki)
+ - [dkanada](https://github.com/dkanada)
+ - [dlahoti](https://github.com/dlahoti)
+ - [dmitrylyzo](https://github.com/dmitrylyzo)
+ - [DMouse10462](https://github.com/DMouse10462)
+ - [DrPandemic](https://github.com/DrPandemic)
- [EraYaN](https://github.com/EraYaN)
+ - [escabe](https://github.com/escabe)
+ - [excelite](https://github.com/excelite)
+ - [fasheng](https://github.com/fasheng)
+ - [ferferga](https://github.com/ferferga)
+ - [fhriley](https://github.com/fhriley)
- [flemse](https://github.com/flemse)
- - [bfayers](https://github.com/bfayers)
- - [Bond_009](https://github.com/Bond-009)
- - [AnthonyLavado](https://github.com/anthonylavado)
- - [sparky8251](https://github.com/sparky8251)
- - [LeoVerto](https://github.com/LeoVerto)
+ - [Froghut](https://github.com/Froghut)
+ - [fruhnow](https://github.com/fruhnow)
+ - [geilername](https://github.com/geilername)
+ - [gnattu](https://github.com/gnattu)
+ - [GodTamIt](https://github.com/GodTamIt)
- [grafixeyehero](https://github.com/grafixeyehero)
- - [cvium](https://github.com/cvium)
- - [wtayl0r](https://github.com/wtayl0r)
- - [TtheCreator](https://github.com/Tthecreator)
- - [dkanada](https://github.com/dkanada)
- - [LogicalPhallacy](https://github.com/LogicalPhallacy/)
+ - [h1nk](https://github.com/h1nk)
+ - [hawken93](https://github.com/hawken93)
+ - [HelloWorld017](https://github.com/HelloWorld017)
+ - [ikomhoog](https://github.com/ikomhoog)
+ - [jftuga](https://github.com/jftuga)
+ - [joern-h](https://github.com/joern-h)
+ - [joshuaboniface](https://github.com/joshuaboniface)
+ - [JustAMan](https://github.com/JustAMan)
+ - [justinfenn](https://github.com/justinfenn)
+ - [KerryRJ](https://github.com/KerryRJ)
+ - [Larvitar](https://github.com/Larvitar)
+ - [LeoVerto](https://github.com/LeoVerto)
+ - [Liggy](https://github.com/Liggy)
+ - [lmaonator](https://github.com/lmaonator)
+ - [LogicalPhallacy](https://github.com/LogicalPhallacy)
+ - [loli10K](https://github.com/loli10K)
+ - [lostmypillow](https://github.com/lostmypillow)
+ - [Lynxy](https://github.com/Lynxy)
+ - [ManfredRichthofen](https://github.com/ManfredRichthofen)
+ - [Marenz](https://github.com/Marenz)
+ - [marius-luca-87](https://github.com/marius-luca-87)
+ - [mark-monteiro](https://github.com/mark-monteiro)
+ - [Matt07211](https://github.com/Matt07211)
+ - [Maxr1998](https://github.com/Maxr1998)
+ - [mcarlton00](https://github.com/mcarlton00)
+ - [mitchfizz05](https://github.com/mitchfizz05)
+ - [MrTimscampi](https://github.com/MrTimscampi)
+ - [n8225](https://github.com/n8225)
+ - [Narfinger](https://github.com/Narfinger)
+ - [NathanPickard](https://github.com/NathanPickard)
+ - [neilsb](https://github.com/neilsb)
+ - [nevado](https://github.com/nevado)
+ - [Nickbert7](https://github.com/Nickbert7)
+ - [nvllsvm](https://github.com/nvllsvm)
+ - [nyanmisaka](https://github.com/nyanmisaka)
+ - [OancaAndrei](https://github.com/OancaAndrei)
+ - [obradovichv](https://github.com/obradovichv)
+ - [oddstr13](https://github.com/oddstr13)
+ - [orryverducci](https://github.com/orryverducci)
+ - [petermcneil](https://github.com/petermcneil)
+ - [Phlogi](https://github.com/Phlogi)
+ - [pjeanjean](https://github.com/pjeanjean)
+ - [ploughpuff](https://github.com/ploughpuff)
+ - [pR0Ps](https://github.com/pR0Ps)
+ - [PrplHaz4](https://github.com/PrplHaz4)
- [RazeLighter777](https://github.com/RazeLighter777)
+ - [redSpoutnik](https://github.com/redSpoutnik)
+ - [ringmatter](https://github.com/ringmatter)
+ - [ryan-hartzell](https://github.com/ryan-hartzell)
+ - [s0urcelab](https://github.com/s0urcelab)
+ - [sachk](https://github.com/sachk)
+ - [sammyrc34](https://github.com/sammyrc34)
+ - [samuel9554](https://github.com/samuel9554)
+ - [scheidleon](https://github.com/scheidleon)
+ - [sebPomme](https://github.com/sebPomme)
+ - [SegiH](https://github.com/SegiH)
+ - [SenorSmartyPants](https://github.com/SenorSmartyPants)
+ - [shemanaev](https://github.com/shemanaev)
+ - [skaro13](https://github.com/skaro13)
+ - [sl1288](https://github.com/sl1288)
+ - [Smith00101010](https://github.com/Smith00101010)
+ - [sorinyo2004](https://github.com/sorinyo2004)
+ - [sparky8251](https://github.com/sparky8251)
+ - [spookbits](https://github.com/spookbits)
+ - [ssenart](https://github.com/ssenart)
+ - [stanionascu](https://github.com/stanionascu)
+ - [stevehayles](https://github.com/stevehayles)
+ - [SuperSandro2000](https://github.com/SuperSandro2000)
+ - [tbraeutigam](https://github.com/tbraeutigam)
+ - [teacupx](https://github.com/teacupx)
+ - [Terror-Gene](https://github.com/Terror-Gene)
+ - [ThatNerdyPikachu](https://github.com/ThatNerdyPikachu)
+ - [ThibaultNocchi](https://github.com/ThibaultNocchi)
+ - [thornbill](https://github.com/thornbill)
+ - [ThreeFive-O](https://github.com/ThreeFive-O)
+ - [TrisMcC](https://github.com/TrisMcC)
+ - [trumblejoe](https://github.com/trumblejoe)
+ - [TtheCreator](https://github.com/TtheCreator)
+ - [twinkybot](https://github.com/twinkybot)
+ - [Ullmie02](https://github.com/Ullmie02)
+ - [Unhelpful](https://github.com/Unhelpful)
+ - [viaregio](https://github.com/viaregio)
+ - [vitorsemeano](https://github.com/vitorsemeano)
+ - [voodoos](https://github.com/voodoos)
+ - [whooo](https://github.com/whooo)
+ - [WiiPlayer2](https://github.com/WiiPlayer2)
- [WillWill56](https://github.com/WillWill56)
- - [Liggy](https://github.com/Liggy)
- - [fruhnow](https://github.com/fruhnow)
+ - [wtayl0r](https://github.com/wtayl0r)
+ - [Wuerfelbecher](https://github.com/Wuerfelbecher)
+ - [Wunax](https://github.com/Wunax)
+ - [WWWesten](https://github.com/WWWesten)
+ - [WX9yMOXWId](https://github.com/WX9yMOXWId)
+ - [xosdy](https://github.com/xosdy)
+ - [XVicarious](https://github.com/XVicarious)
+ - [YouKnowBlom](https://github.com/YouKnowBlom)
+ - [KristupasSavickas](https://github.com/KristupasSavickas)
+ - [Pusta](https://github.com/pusta)
+ - [nielsvanvelzen](https://github.com/nielsvanvelzen)
+ - [skyfrk](https://github.com/skyfrk)
+ - [ianjazz246](https://github.com/ianjazz246)
+ - [peterspenler](https://github.com/peterspenler)
+ - [MBR-0001](https://github.com/MBR-0001)
# Emby Contributors
@@ -84,3 +213,6 @@
- [tikuf](https://github.com/tikuf/)
- [Tim Hobbs](https://github.com/timhobbs)
- [SvenVandenbrande](https://github.com/SvenVandenbrande)
+ - [olsh](https://github.com/olsh)
+ - [lbenini](https://github.com/lbenini)
+ - [gnuyent](https://github.com/gnuyent)
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 000000000..b899999ef
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,14 @@
+<Project>
+ <!-- Sets defaults for all projects in the repo -->
+
+ <PropertyGroup>
+ <Nullable>enable</Nullable>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)/jellyfin.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <AnalysisMode>AllEnabledByDefault</AnalysisMode>
+ </PropertyGroup>
+
+</Project>
diff --git a/Dockerfile b/Dockerfile
index 978b0d540..e133c0819 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,27 +1,93 @@
-ARG DOTNET_VERSION=2
+# DESIGNED FOR BUILDING ON AMD64 ONLY
+#####################################
+# Requires binfm_misc registration
+# https://github.com/multiarch/qemu-user-static#binfmt_misc-register
+ARG DOTNET_VERSION=6.0
-FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder
-WORKDIR /repo
-COPY . .
-ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-RUN dotnet publish \
- --configuration release \
- --output /jellyfin \
- Jellyfin.Server
-
-FROM jellyfin/ffmpeg as ffmpeg
-FROM microsoft/dotnet:${DOTNET_VERSION}-runtime
-# libfontconfig1 is required for Skia
+FROM node:lts-alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && npm ci --no-audit --unsafe-perm \
+ && mv dist /dist
+
+FROM debian:stable-slim as app
+
+# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
+ARG DEBIAN_FRONTEND="noninteractive"
+# http://stackoverflow.com/questions/48162574/ddg#49462622
+ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
+# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
+ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
+
+# https://github.com/intel/compute-runtime/releases
+ARG GMMLIB_VERSION=21.2.1
+ARG IGC_VERSION=1.0.8517
+ARG NEO_VERSION=21.35.20826
+ARG LEVEL_ZERO_VERSION=1.2.20826
+
+# Install dependencies:
+# mesa-va-drivers: needed for AMD VAAPI. Mesa >= 20.1 is required for HEVC transcoding.
+# curl: healthcheck
RUN apt-get update \
+ && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg wget apt-transport-https curl \
+ && wget -O - https://repo.jellyfin.org/jellyfin_team.gpg.key | apt-key add - \
+ && echo "deb [arch=$( dpkg --print-architecture )] https://repo.jellyfin.org/$( awk -F'=' '/^ID=/{ print $NF }' /etc/os-release ) $( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release ) main" | tee /etc/apt/sources.list.d/jellyfin.list \
+ && apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y \
- libfontconfig1 \
- && apt-get clean autoclean \
- && apt-get autoremove \
- && rm -rf /var/lib/{apt,dpkg,cache,log} \
+ mesa-va-drivers \
+ jellyfin-ffmpeg \
+ openssl \
+ locales \
+# Intel VAAPI Tone mapping dependencies:
+# Prefer NEO to Beignet since the latter one doesn't support Comet Lake or newer for now.
+# Do not use the intel-opencl-icd package from repo since they will not build with RELEASE_WITH_REGKEYS enabled.
+ && mkdir intel-compute-runtime \
+ && cd intel-compute-runtime \
+ && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-gmmlib_${GMMLIB_VERSION}_amd64.deb \
+ && wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-${IGC_VERSION}/intel-igc-core_${IGC_VERSION}_amd64.deb \
+ && wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-${IGC_VERSION}/intel-igc-opencl_${IGC_VERSION}_amd64.deb \
+ && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-opencl_${NEO_VERSION}_amd64.deb \
+ && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-ocloc_${NEO_VERSION}_amd64.deb \
+ && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-level-zero-gpu_${LEVEL_ZERO_VERSION}_amd64.deb \
+ && dpkg -i *.deb \
+ && cd .. \
+ && rm -rf intel-compute-runtime \
+ && apt-get remove gnupg wget apt-transport-https -y \
+ && apt-get clean autoclean -y \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/* \
&& mkdir -p /cache /config /media \
- && chmod 777 /cache /config /media
-COPY --from=ffmpeg / /
+ && chmod 777 /cache /config /media \
+ && sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
+
+# ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
+ENV LC_ALL en_US.UTF-8
+ENV LANG en_US.UTF-8
+ENV LANGUAGE en_US:en
+
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder
+WORKDIR /repo
+COPY . .
+ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
+# because of changes in docker and systemd we need to not build in parallel at the moment
+# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
+RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:DebugSymbols=false;DebugType=none"
+
+FROM app
+
+ENV HEALTHCHECK_URL=http://localhost:8096/health
+
COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
+
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll --datadir /config --cachedir /cache
+ENTRYPOINT ["./jellyfin/jellyfin", \
+ "--datadir", "/config", \
+ "--cachedir", "/cache", \
+ "--ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"]
+
+HEALTHCHECK --interval=30s --timeout=30s --start-period=10s --retries=3 \
+ CMD curl -Lk "${HEALTHCHECK_URL}" || exit 1
diff --git a/Dockerfile.arm b/Dockerfile.arm
index 9d1c30619..a46fa331d 100644
--- a/Dockerfile.arm
+++ b/Dockerfile.arm
@@ -1,36 +1,84 @@
+# DESIGNED FOR BUILDING ON ARM ONLY
+#####################################
# Requires binfm_misc registration
# https://github.com/multiarch/qemu-user-static#binfmt_misc-register
-ARG DOTNET_VERSION=3.0
+ARG DOTNET_VERSION=6.0
+FROM node:lts-alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && npm ci --no-audit --unsafe-perm \
+ && mv dist /dist
+
FROM multiarch/qemu-user-static:x86_64-arm as qemu
-FROM alpine as qemu_extract
-COPY --from=qemu /usr/bin qemu-arm-static.tar.gz
-RUN tar -xzvf qemu-arm-static.tar.gz
+FROM arm32v7/debian:stable-slim as app
+
+# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
+ARG DEBIAN_FRONTEND="noninteractive"
+# http://stackoverflow.com/questions/48162574/ddg#49462622
+ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
+# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
+ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
+
+COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
+
+# curl: setup & healthcheck
+RUN apt-get update \
+ && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg curl && \
+ curl -ks https://repo.jellyfin.org/debian/jellyfin_team.gpg.key | apt-key add - && \
+ curl -ks https://keyserver.ubuntu.com/pks/lookup?op=get\&search=0x6587ffd6536b8826e88a62547876ae518cbcf2f2 | apt-key add - && \
+ echo 'deb [arch=armhf] https://repo.jellyfin.org/debian buster main' > /etc/apt/sources.list.d/jellyfin.list && \
+ echo "deb http://ppa.launchpad.net/ubuntu-raspi2/ppa/ubuntu bionic main">> /etc/apt/sources.list.d/raspbins.list && \
+ apt-get update && \
+ apt-get install --no-install-recommends --no-install-suggests -y \
+ jellyfin-ffmpeg \
+ libssl-dev \
+ libfontconfig1 \
+ libfreetype6 \
+ libomxil-bellagio0 \
+ libomxil-bellagio-bin \
+ libraspberrypi0 \
+ vainfo \
+ libva2 \
+ locales \
+ && apt-get remove gnupg -y \
+ && apt-get clean autoclean -y \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir -p /cache /config /media \
+ && chmod 777 /cache /config /media \
+ && sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
-FROM microsoft/dotnet:${DOTNET_VERSION}-sdk-stretch as builder
+# ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
+ENV LC_ALL en_US.UTF-8
+ENV LANG en_US.UTF-8
+ENV LANGUAGE en_US:en
+
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-# TODO Remove or update the sed line when we update dotnet version.
-RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \;
# Discard objs - may cause failures if exists
RUN find . -type d -name obj | xargs -r rm -r
# Build
-RUN dotnet publish \
- -r linux-arm \
- --configuration release \
- --output /jellyfin \
- Jellyfin.Server
+RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:DebugSymbols=false;DebugType=none"
+FROM app
+
+ENV HEALTHCHECK_URL=http://localhost:8096/health
-FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm32v7
-COPY --from=qemu_extract qemu-arm-static /usr/bin
-RUN apt-get update \
- && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
- && mkdir -p /cache /config /media \
- && chmod 777 /cache /config /media
COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
+
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll --datadir /config --cachedir /cache
+ENTRYPOINT ["./jellyfin/jellyfin", \
+ "--datadir", "/config", \
+ "--cachedir", "/cache", \
+ "--ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"]
+
+HEALTHCHECK --interval=30s --timeout=30s --start-period=10s --retries=3 \
+ CMD curl -Lk "${HEALTHCHECK_URL}" || exit 1
diff --git a/Dockerfile.arm64 b/Dockerfile.arm64
index e61aaa167..1279c47f8 100644
--- a/Dockerfile.arm64
+++ b/Dockerfile.arm64
@@ -1,37 +1,75 @@
+# DESIGNED FOR BUILDING ON ARM64 ONLY
+#####################################
# Requires binfm_misc registration
# https://github.com/multiarch/qemu-user-static#binfmt_misc-register
-ARG DOTNET_VERSION=3.0
+ARG DOTNET_VERSION=6.0
+FROM node:lts-alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && npm ci --no-audit --unsafe-perm \
+ && mv dist /dist
+
FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu
-FROM alpine as qemu_extract
-COPY --from=qemu /usr/bin qemu-aarch64-static.tar.gz
-RUN tar -xzvf qemu-aarch64-static.tar.gz
+FROM arm64v8/debian:stable-slim as app
+
+# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
+ARG DEBIAN_FRONTEND="noninteractive"
+# http://stackoverflow.com/questions/48162574/ddg#49462622
+ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
+# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
+ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
+
+COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin
+
+# curl: healcheck
+RUN apt-get update && apt-get install --no-install-recommends --no-install-suggests -y \
+ ffmpeg \
+ libssl-dev \
+ ca-certificates \
+ libfontconfig1 \
+ libfreetype6 \
+ libomxil-bellagio0 \
+ libomxil-bellagio-bin \
+ locales \
+ curl \
+ && apt-get clean autoclean -y \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir -p /cache /config /media \
+ && chmod 777 /cache /config /media \
+ && sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
+# ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
+ENV LC_ALL en_US.UTF-8
+ENV LANG en_US.UTF-8
+ENV LANGUAGE en_US:en
-FROM microsoft/dotnet:${DOTNET_VERSION}-sdk-stretch as builder
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-# TODO Remove or update the sed line when we update dotnet version.
-RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \;
# Discard objs - may cause failures if exists
RUN find . -type d -name obj | xargs -r rm -r
# Build
-RUN dotnet publish \
- -r linux-arm64 \
- --configuration release \
- --output /jellyfin \
- Jellyfin.Server
+RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:DebugSymbols=false;DebugType=none"
+FROM app
+
+ENV HEALTHCHECK_URL=http://localhost:8096/health
-FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm64v8
-COPY --from=qemu_extract qemu-aarch64-static /usr/bin
-RUN apt-get update \
- && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
- && mkdir -p /cache /config /media \
- && chmod 777 /cache /config /media
COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
+
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll --datadir /config --cachedir /cache
+ENTRYPOINT ["./jellyfin/jellyfin", \
+ "--datadir", "/config", \
+ "--cachedir", "/cache", \
+ "--ffmpeg", "/usr/bin/ffmpeg"]
+
+HEALTHCHECK --interval=30s --timeout=30s --start-period=10s --retries=3 \
+ CMD curl -Lk "${HEALTHCHECK_URL}" || exit 1
diff --git a/DvdLib/BigEndianBinaryReader.cs b/DvdLib/BigEndianBinaryReader.cs
index b3b2eabd5..b3aad85ce 100644
--- a/DvdLib/BigEndianBinaryReader.cs
+++ b/DvdLib/BigEndianBinaryReader.cs
@@ -1,4 +1,6 @@
-using System;
+#pragma warning disable CS1591
+
+using System.Buffers.Binary;
using System.IO;
namespace DvdLib
@@ -12,19 +14,12 @@ namespace DvdLib
public override ushort ReadUInt16()
{
- return BitConverter.ToUInt16(ReadAndReverseBytes(2), 0);
+ return BinaryPrimitives.ReadUInt16BigEndian(base.ReadBytes(2));
}
public override uint ReadUInt32()
{
- return BitConverter.ToUInt32(ReadAndReverseBytes(4), 0);
- }
-
- private byte[] ReadAndReverseBytes(int count)
- {
- byte[] val = base.ReadBytes(count);
- Array.Reverse(val, 0, count);
- return val;
+ return BinaryPrimitives.ReadUInt32BigEndian(base.ReadBytes(4));
}
}
}
diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj
index b2c752d0c..755d29160 100644
--- a/DvdLib/DvdLib.csproj
+++ b/DvdLib/DvdLib.csproj
@@ -1,16 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{713F42B5-878E-499D-A878-E4C652B1D5E8}</ProjectGuid>
+ </PropertyGroup>
<ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <AnalysisMode>AllDisabledByDefault</AnalysisMode>
+ <Nullable>disable</Nullable>
</PropertyGroup>
</Project>
diff --git a/DvdLib/Ifo/AudioAttributes.cs b/DvdLib/Ifo/AudioAttributes.cs
deleted file mode 100644
index b76f9fc05..000000000
--- a/DvdLib/Ifo/AudioAttributes.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-namespace DvdLib.Ifo
-{
- public enum AudioCodec
- {
- AC3 = 0,
- MPEG1 = 2,
- MPEG2ext = 3,
- LPCM = 4,
- DTS = 6,
- }
-
- public enum ApplicationMode
- {
- Unspecified = 0,
- Karaoke = 1,
- Surround = 2,
- }
-
- public class AudioAttributes
- {
- public readonly AudioCodec Codec;
- public readonly bool MultichannelExtensionPresent;
- public readonly ApplicationMode Mode;
- public readonly byte QuantDRC;
- public readonly byte SampleRate;
- public readonly byte Channels;
- public readonly ushort LanguageCode;
- public readonly byte LanguageExtension;
- public readonly byte CodeExtension;
- }
-
- public class MultiChannelExtension
- {
-
- }
-}
diff --git a/DvdLib/Ifo/Cell.cs b/DvdLib/Ifo/Cell.cs
index 268ab897e..ea0b50e43 100644
--- a/DvdLib/Ifo/Cell.cs
+++ b/DvdLib/Ifo/Cell.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.IO;
namespace DvdLib.Ifo
@@ -5,6 +7,7 @@ namespace DvdLib.Ifo
public class Cell
{
public CellPlaybackInfo PlaybackInfo { get; private set; }
+
public CellPositionInfo PositionInfo { get; private set; }
internal void ParsePlayback(BinaryReader br)
diff --git a/DvdLib/Ifo/CellPlaybackInfo.cs b/DvdLib/Ifo/CellPlaybackInfo.cs
index e588e51ac..6e33a0ec5 100644
--- a/DvdLib/Ifo/CellPlaybackInfo.cs
+++ b/DvdLib/Ifo/CellPlaybackInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.IO;
namespace DvdLib.Ifo
diff --git a/DvdLib/Ifo/CellPositionInfo.cs b/DvdLib/Ifo/CellPositionInfo.cs
index 2b973e083..216aa0f77 100644
--- a/DvdLib/Ifo/CellPositionInfo.cs
+++ b/DvdLib/Ifo/CellPositionInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.IO;
namespace DvdLib.Ifo
diff --git a/DvdLib/Ifo/Chapter.cs b/DvdLib/Ifo/Chapter.cs
index bd3bd9704..e786cb553 100644
--- a/DvdLib/Ifo/Chapter.cs
+++ b/DvdLib/Ifo/Chapter.cs
@@ -1,9 +1,13 @@
+#pragma warning disable CS1591
+
namespace DvdLib.Ifo
{
public class Chapter
{
public ushort ProgramChainNumber { get; private set; }
+
public ushort ProgramNumber { get; private set; }
+
public uint ChapterNumber { get; private set; }
public Chapter(ushort pgcNum, ushort programNum, uint chapterNum)
diff --git a/DvdLib/Ifo/Dvd.cs b/DvdLib/Ifo/Dvd.cs
index f784be83e..7f8ece47d 100644
--- a/DvdLib/Ifo/Dvd.cs
+++ b/DvdLib/Ifo/Dvd.cs
@@ -1,8 +1,10 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
-using MediaBrowser.Model.IO;
namespace DvdLib.Ifo
{
@@ -13,36 +15,33 @@ namespace DvdLib.Ifo
private ushort _titleCount;
public readonly Dictionary<ushort, string> VTSPaths = new Dictionary<ushort, string>();
- private readonly IFileSystem _fileSystem;
-
- public Dvd(string path, IFileSystem fileSystem)
+ public Dvd(string path)
{
- _fileSystem = fileSystem;
Titles = new List<Title>();
- var allFiles = _fileSystem.GetFiles(path, true).ToList();
+ var allFiles = new DirectoryInfo(path).GetFiles(path, SearchOption.AllDirectories);
var vmgPath = allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.IFO", StringComparison.OrdinalIgnoreCase)) ??
allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.BUP", StringComparison.OrdinalIgnoreCase));
if (vmgPath == null)
{
- var allIfos = allFiles.Where(i => string.Equals(i.Extension, ".ifo", StringComparison.OrdinalIgnoreCase));
-
- foreach (var ifo in allIfos)
+ foreach (var ifo in allFiles)
{
- var num = ifo.Name.Split('_').ElementAtOrDefault(1);
- var numbersRead = new List<ushort>();
+ if (!string.Equals(ifo.Extension, ".ifo", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
- if (!string.IsNullOrEmpty(num) && ushort.TryParse(num, out var ifoNumber) && !numbersRead.Contains(ifoNumber))
+ var nums = ifo.Name.Split('_', StringSplitOptions.RemoveEmptyEntries);
+ if (nums.Length >= 2 && ushort.TryParse(nums[1], out var ifoNumber))
{
ReadVTS(ifoNumber, ifo.FullName);
- numbersRead.Add(ifoNumber);
}
}
}
else
{
- using (var vmgFs = _fileSystem.GetFileStream(vmgPath.FullName, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
+ using (var vmgFs = new FileStream(vmgPath.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var vmgRead = new BigEndianBinaryReader(vmgFs))
{
@@ -76,9 +75,9 @@ namespace DvdLib.Ifo
}
}
- private void ReadVTS(ushort vtsNum, List<FileSystemMetadata> allFiles)
+ private void ReadVTS(ushort vtsNum, IReadOnlyList<FileInfo> allFiles)
{
- var filename = string.Format("VTS_{0:00}_0.IFO", vtsNum);
+ var filename = string.Format(CultureInfo.InvariantCulture, "VTS_{0:00}_0.IFO", vtsNum);
var vtsPath = allFiles.FirstOrDefault(i => string.Equals(i.Name, filename, StringComparison.OrdinalIgnoreCase)) ??
allFiles.FirstOrDefault(i => string.Equals(i.Name, Path.ChangeExtension(filename, ".bup"), StringComparison.OrdinalIgnoreCase));
@@ -95,7 +94,7 @@ namespace DvdLib.Ifo
{
VTSPaths[vtsNum] = vtsPath;
- using (var vtsFs = _fileSystem.GetFileStream(vtsPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
+ using (var vtsFs = new FileStream(vtsPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var vtsRead = new BigEndianBinaryReader(vtsFs))
{
@@ -119,12 +118,19 @@ namespace DvdLib.Ifo
uint chapNum = 1;
vtsFs.Seek(baseAddr + offsets[titleNum], SeekOrigin.Begin);
var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum + 1));
- if (t == null) continue;
+ if (t == null)
+ {
+ continue;
+ }
do
{
t.Chapters.Add(new Chapter(vtsRead.ReadUInt16(), vtsRead.ReadUInt16(), chapNum));
- if (titleNum + 1 < numTitles && vtsFs.Position == (baseAddr + offsets[titleNum + 1])) break;
+ if (titleNum + 1 < numTitles && vtsFs.Position == (baseAddr + offsets[titleNum + 1]))
+ {
+ break;
+ }
+
chapNum++;
}
while (vtsFs.Position < (baseAddr + endaddr));
@@ -149,7 +155,10 @@ namespace DvdLib.Ifo
uint vtsPgcOffset = vtsRead.ReadUInt32();
var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum));
- if (t != null) t.AddPgc(vtsRead, startByte + vtsPgcOffset, entryPgc, pgcNum);
+ if (t != null)
+ {
+ t.AddPgc(vtsRead, startByte + vtsPgcOffset, entryPgc, pgcNum);
+ }
}
}
}
diff --git a/DvdLib/Ifo/DvdTime.cs b/DvdLib/Ifo/DvdTime.cs
index 3688089ec..d23140610 100644
--- a/DvdLib/Ifo/DvdTime.cs
+++ b/DvdLib/Ifo/DvdTime.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace DvdLib.Ifo
@@ -13,8 +15,14 @@ namespace DvdLib.Ifo
Second = GetBCDValue(data[2]);
Frames = GetBCDValue((byte)(data[3] & 0x3F));
- if ((data[3] & 0x80) != 0) FrameRate = 30;
- else if ((data[3] & 0x40) != 0) FrameRate = 25;
+ if ((data[3] & 0x80) != 0)
+ {
+ FrameRate = 30;
+ }
+ else if ((data[3] & 0x40) != 0)
+ {
+ FrameRate = 25;
+ }
}
private static byte GetBCDValue(byte data)
diff --git a/DvdLib/Ifo/PgcCommandTable.cs b/DvdLib/Ifo/PgcCommandTable.cs
deleted file mode 100644
index d329fcba2..000000000
--- a/DvdLib/Ifo/PgcCommandTable.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System.Collections.Generic;
-
-namespace DvdLib.Ifo
-{
- public class ProgramChainCommandTable
- {
- public readonly ushort LastByteAddress;
- public readonly List<VirtualMachineCommand> PreCommands;
- public readonly List<VirtualMachineCommand> PostCommands;
- public readonly List<VirtualMachineCommand> CellCommands;
- }
-
- public class VirtualMachineCommand
- {
- public readonly byte[] Command;
- }
-}
diff --git a/DvdLib/Ifo/Program.cs b/DvdLib/Ifo/Program.cs
index af08afa35..3d94fa7dc 100644
--- a/DvdLib/Ifo/Program.cs
+++ b/DvdLib/Ifo/Program.cs
@@ -1,10 +1,12 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
namespace DvdLib.Ifo
{
public class Program
{
- public readonly List<Cell> Cells;
+ public IReadOnlyList<Cell> Cells { get; }
public Program(List<Cell> cells)
{
diff --git a/DvdLib/Ifo/ProgramChain.cs b/DvdLib/Ifo/ProgramChain.cs
index 80889738f..83c0051b9 100644
--- a/DvdLib/Ifo/ProgramChain.cs
+++ b/DvdLib/Ifo/ProgramChain.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -20,27 +22,27 @@ namespace DvdLib.Ifo
public readonly List<Cell> Cells;
public DvdTime PlaybackTime { get; private set; }
+
public UserOperation ProhibitedUserOperations { get; private set; }
+
public byte[] AudioStreamControl { get; private set; } // 8*2 entries
public byte[] SubpictureStreamControl { get; private set; } // 32*4 entries
private ushort _nextProgramNumber;
- public readonly ProgramChain Next;
private ushort _prevProgramNumber;
- public readonly ProgramChain Previous;
private ushort _goupProgramNumber;
- public readonly ProgramChain Goup; // ?? maybe Group
public ProgramPlaybackMode PlaybackMode { get; private set; }
+
public uint ProgramCount { get; private set; }
public byte StillTime { get; private set; }
+
public byte[] Palette { get; private set; } // 16*4 entries
private ushort _commandTableOffset;
- public readonly ProgramChainCommandTable CommandTable;
private ushort _programMapOffset;
private ushort _cellPlaybackOffset;
@@ -73,8 +75,15 @@ namespace DvdLib.Ifo
StillTime = br.ReadByte();
byte pbMode = br.ReadByte();
- if (pbMode == 0) PlaybackMode = ProgramPlaybackMode.Sequential;
- else PlaybackMode = ((pbMode & 0x80) == 0) ? ProgramPlaybackMode.Random : ProgramPlaybackMode.Shuffle;
+ if (pbMode == 0)
+ {
+ PlaybackMode = ProgramPlaybackMode.Sequential;
+ }
+ else
+ {
+ PlaybackMode = ((pbMode & 0x80) == 0) ? ProgramPlaybackMode.Random : ProgramPlaybackMode.Shuffle;
+ }
+
ProgramCount = (uint)(pbMode & 0x7F);
Palette = br.ReadBytes(64);
diff --git a/DvdLib/Ifo/Title.cs b/DvdLib/Ifo/Title.cs
index 335e92992..29a0b95c7 100644
--- a/DvdLib/Ifo/Title.cs
+++ b/DvdLib/Ifo/Title.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.IO;
@@ -6,8 +8,11 @@ namespace DvdLib.Ifo
public class Title
{
public uint TitleNumber { get; private set; }
+
public uint AngleCount { get; private set; }
+
public ushort ChapterCount { get; private set; }
+
public byte VideoTitleSetNumber { get; private set; }
private ushort _parentalManagementMask;
@@ -15,6 +20,7 @@ namespace DvdLib.Ifo
private uint _vtsStartSector; // relative to start of entire disk
public ProgramChain EntryProgramChain { get; private set; }
+
public readonly List<ProgramChain> ProgramChains;
public readonly List<Chapter> Chapters;
@@ -53,7 +59,10 @@ namespace DvdLib.Ifo
var pgc = new ProgramChain(pgcNum);
pgc.ParseHeader(br);
ProgramChains.Add(pgc);
- if (entryPgc) EntryProgramChain = pgc;
+ if (entryPgc)
+ {
+ EntryProgramChain = pgc;
+ }
br.BaseStream.Seek(curPos, SeekOrigin.Begin);
}
diff --git a/DvdLib/Ifo/UserOperation.cs b/DvdLib/Ifo/UserOperation.cs
index 757a5a05d..5d111ebc0 100644
--- a/DvdLib/Ifo/UserOperation.cs
+++ b/DvdLib/Ifo/UserOperation.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace DvdLib.Ifo
diff --git a/DvdLib/Ifo/VideoAttributes.cs b/DvdLib/Ifo/VideoAttributes.cs
deleted file mode 100644
index 8b3996715..000000000
--- a/DvdLib/Ifo/VideoAttributes.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-namespace DvdLib.Ifo
-{
- public enum VideoCodec
- {
- MPEG1 = 0,
- MPEG2 = 1,
- }
-
- public enum VideoFormat
- {
- NTSC = 0,
- PAL = 1,
- }
-
- public enum AspectRatio
- {
- ar4to3 = 0,
- ar16to9 = 3
- }
-
- public enum FilmMode
- {
- None = -1,
- Camera = 0,
- Film = 1,
- }
-
- public class VideoAttributes
- {
- public readonly VideoCodec Codec;
- public readonly VideoFormat Format;
- public readonly AspectRatio Aspect;
- public readonly bool AutomaticPanScan;
- public readonly bool AutomaticLetterBox;
- public readonly bool Line21CCField1;
- public readonly bool Line21CCField2;
- public readonly int Width;
- public readonly int Height;
- public readonly bool Letterboxed;
- public readonly FilmMode FilmMode;
-
- public VideoAttributes()
- {
- }
- }
-}
diff --git a/DvdLib/Properties/AssemblyInfo.cs b/DvdLib/Properties/AssemblyInfo.cs
index 5fc055d1f..6acd571d6 100644
--- a/DvdLib/Properties/AssemblyInfo.cs
+++ b/DvdLib/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs
deleted file mode 100644
index 68bf80163..000000000
--- a/Emby.Dlna/Api/DlnaServerService.cs
+++ /dev/null
@@ -1,306 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Emby.Dlna.Main;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Dlna.Api
-{
- [Route("/Dlna/{UuId}/description.xml", "GET", Summary = "Gets dlna server info")]
- [Route("/Dlna/{UuId}/description", "GET", Summary = "Gets dlna server info")]
- public class GetDescriptionXml
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/contentdirectory/contentdirectory.xml", "GET", Summary = "Gets dlna content directory xml")]
- [Route("/Dlna/{UuId}/contentdirectory/contentdirectory", "GET", Summary = "Gets dlna content directory xml")]
- public class GetContentDirectory
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/connectionmanager/connectionmanager.xml", "GET", Summary = "Gets dlna connection manager xml")]
- [Route("/Dlna/{UuId}/connectionmanager/connectionmanager", "GET", Summary = "Gets dlna connection manager xml")]
- public class GetConnnectionManager
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/mediareceiverregistrar/mediareceiverregistrar.xml", "GET", Summary = "Gets dlna mediareceiverregistrar xml")]
- [Route("/Dlna/{UuId}/mediareceiverregistrar/mediareceiverregistrar", "GET", Summary = "Gets dlna mediareceiverregistrar xml")]
- public class GetMediaReceiverRegistrar
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/contentdirectory/control", "POST", Summary = "Processes a control request")]
- public class ProcessContentDirectoryControlRequest : IRequiresRequestStream
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
-
- public Stream RequestStream { get; set; }
- }
-
- [Route("/Dlna/{UuId}/connectionmanager/control", "POST", Summary = "Processes a control request")]
- public class ProcessConnectionManagerControlRequest : IRequiresRequestStream
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
-
- public Stream RequestStream { get; set; }
- }
-
- [Route("/Dlna/{UuId}/mediareceiverregistrar/control", "POST", Summary = "Processes a control request")]
- public class ProcessMediaReceiverRegistrarControlRequest : IRequiresRequestStream
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UuId { get; set; }
-
- public Stream RequestStream { get; set; }
- }
-
- [Route("/Dlna/{UuId}/mediareceiverregistrar/events", "SUBSCRIBE", Summary = "Processes an event subscription request")]
- [Route("/Dlna/{UuId}/mediareceiverregistrar/events", "UNSUBSCRIBE", Summary = "Processes an event subscription request")]
- public class ProcessMediaReceiverRegistrarEventRequest
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "SUBSCRIBE,UNSUBSCRIBE")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/contentdirectory/events", "SUBSCRIBE", Summary = "Processes an event subscription request")]
- [Route("/Dlna/{UuId}/contentdirectory/events", "UNSUBSCRIBE", Summary = "Processes an event subscription request")]
- public class ProcessContentDirectoryEventRequest
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "SUBSCRIBE,UNSUBSCRIBE")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/connectionmanager/events", "SUBSCRIBE", Summary = "Processes an event subscription request")]
- [Route("/Dlna/{UuId}/connectionmanager/events", "UNSUBSCRIBE", Summary = "Processes an event subscription request")]
- public class ProcessConnectionManagerEventRequest
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "SUBSCRIBE,UNSUBSCRIBE")]
- public string UuId { get; set; }
- }
-
- [Route("/Dlna/{UuId}/icons/{Filename}", "GET", Summary = "Gets a server icon")]
- [Route("/Dlna/icons/{Filename}", "GET", Summary = "Gets a server icon")]
- public class GetIcon
- {
- [ApiMember(Name = "UuId", Description = "Server UuId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string UuId { get; set; }
-
- [ApiMember(Name = "Filename", Description = "The icon filename", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Filename { get; set; }
- }
-
- public class DlnaServerService : IService, IRequiresRequest
- {
- private readonly IDlnaManager _dlnaManager;
-
- private const string XMLContentType = "text/xml; charset=UTF-8";
-
- public IRequest Request { get; set; }
- private IHttpResultFactory _resultFactory;
-
- private IContentDirectory ContentDirectory => DlnaEntryPoint.Current.ContentDirectory;
-
- private IConnectionManager ConnectionManager => DlnaEntryPoint.Current.ConnectionManager;
-
- private IMediaReceiverRegistrar MediaReceiverRegistrar => DlnaEntryPoint.Current.MediaReceiverRegistrar;
-
- public DlnaServerService(IDlnaManager dlnaManager, IHttpResultFactory httpResultFactory)
- {
- _dlnaManager = dlnaManager;
- _resultFactory = httpResultFactory;
- }
-
- private string GetHeader(string name)
- {
- return Request.Headers[name];
- }
-
- public object Get(GetDescriptionXml request)
- {
- var url = Request.AbsoluteUri;
- var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase));
- var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers.ToDictionary(), request.UuId, serverAddress);
-
- var cacheLength = TimeSpan.FromDays(1);
- var cacheKey = Request.RawUrl.GetMD5();
- var bytes = Encoding.UTF8.GetBytes(xml);
-
- return _resultFactory.GetStaticResult(Request, cacheKey, null, cacheLength, XMLContentType, () => Task.FromResult<Stream>(new MemoryStream(bytes)));
- }
-
- public object Get(GetContentDirectory request)
- {
- var xml = ContentDirectory.GetServiceXml(Request.Headers.ToDictionary());
-
- return _resultFactory.GetResult(Request, xml, XMLContentType);
- }
-
- public object Get(GetMediaReceiverRegistrar request)
- {
- var xml = MediaReceiverRegistrar.GetServiceXml(Request.Headers.ToDictionary());
-
- return _resultFactory.GetResult(Request, xml, XMLContentType);
- }
-
- public object Get(GetConnnectionManager request)
- {
- var xml = ConnectionManager.GetServiceXml(Request.Headers.ToDictionary());
-
- return _resultFactory.GetResult(Request, xml, XMLContentType);
- }
-
- public object Post(ProcessMediaReceiverRegistrarControlRequest request)
- {
- var response = PostAsync(request.RequestStream, MediaReceiverRegistrar);
-
- return _resultFactory.GetResult(Request, response.Xml, XMLContentType);
- }
-
- public object Post(ProcessContentDirectoryControlRequest request)
- {
- var response = PostAsync(request.RequestStream, ContentDirectory);
-
- return _resultFactory.GetResult(Request, response.Xml, XMLContentType);
- }
-
- public object Post(ProcessConnectionManagerControlRequest request)
- {
- var response = PostAsync(request.RequestStream, ConnectionManager);
-
- return _resultFactory.GetResult(Request, response.Xml, XMLContentType);
- }
-
- private ControlResponse PostAsync(Stream requestStream, IUpnpService service)
- {
- var id = GetPathValue(2);
-
- return service.ProcessControlRequest(new ControlRequest
- {
- Headers = Request.Headers.ToDictionary(),
- InputXml = requestStream,
- TargetServerUuId = id,
- RequestedUrl = Request.AbsoluteUri
- });
- }
-
- protected string GetPathValue(int index)
- {
- var pathInfo = Parse(Request.PathInfo);
- var first = pathInfo[0];
-
- // backwards compatibility
- // TODO: Work out what this is doing.
- if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(first, "jellyfin", StringComparison.OrdinalIgnoreCase))
- {
- index++;
- }
-
- return pathInfo[index];
- }
-
- private List<string> Parse(string pathUri)
- {
- var actionParts = pathUri.Split(new[] { "://" }, StringSplitOptions.None);
-
- var pathInfo = actionParts[actionParts.Length - 1];
-
- var optionsPos = pathInfo.LastIndexOf('?');
- if (optionsPos != -1)
- {
- pathInfo = pathInfo.Substring(0, optionsPos);
- }
-
- var args = pathInfo.Split('/');
-
- return args.Skip(1).ToList();
- }
-
- public object Get(GetIcon request)
- {
- var contentType = "image/" + Path.GetExtension(request.Filename)
- .TrimStart('.')
- .ToLowerInvariant();
-
- var cacheLength = TimeSpan.FromDays(365);
- var cacheKey = Request.RawUrl.GetMD5();
-
- return _resultFactory.GetStaticResult(Request, cacheKey, null, cacheLength, contentType, () => Task.FromResult(_dlnaManager.GetIcon(request.Filename).Stream));
- }
-
- public object Subscribe(ProcessContentDirectoryEventRequest request)
- {
- return ProcessEventRequest(ContentDirectory);
- }
-
- public object Subscribe(ProcessConnectionManagerEventRequest request)
- {
- return ProcessEventRequest(ConnectionManager);
- }
-
- public object Subscribe(ProcessMediaReceiverRegistrarEventRequest request)
- {
- return ProcessEventRequest(MediaReceiverRegistrar);
- }
-
- public object Unsubscribe(ProcessContentDirectoryEventRequest request)
- {
- return ProcessEventRequest(ContentDirectory);
- }
-
- public object Unsubscribe(ProcessConnectionManagerEventRequest request)
- {
- return ProcessEventRequest(ConnectionManager);
- }
-
- public object Unsubscribe(ProcessMediaReceiverRegistrarEventRequest request)
- {
- return ProcessEventRequest(MediaReceiverRegistrar);
- }
-
- private object ProcessEventRequest(IEventManager eventManager)
- {
- var subscriptionId = GetHeader("SID");
-
- if (string.Equals(Request.Verb, "SUBSCRIBE", StringComparison.OrdinalIgnoreCase))
- {
- var notificationType = GetHeader("NT");
-
- var callback = GetHeader("CALLBACK");
- var timeoutString = GetHeader("TIMEOUT");
-
- if (string.IsNullOrEmpty(notificationType))
- {
- return GetSubscriptionResponse(eventManager.RenewEventSubscription(subscriptionId, notificationType, timeoutString, callback));
- }
-
- return GetSubscriptionResponse(eventManager.CreateEventSubscription(notificationType, timeoutString, callback));
- }
-
- return GetSubscriptionResponse(eventManager.CancelEventSubscription(subscriptionId));
- }
-
- private object GetSubscriptionResponse(EventSubscriptionResponse response)
- {
- return _resultFactory.GetResult(Request, response.Content, response.ContentType, response.Headers);
- }
- }
-}
diff --git a/Emby.Dlna/Api/DlnaService.cs b/Emby.Dlna/Api/DlnaService.cs
deleted file mode 100644
index 7f51f477a..000000000
--- a/Emby.Dlna/Api/DlnaService.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System.Linq;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Dlna.Api
-{
- [Route("/Dlna/ProfileInfos", "GET", Summary = "Gets a list of profiles")]
- public class GetProfileInfos : IReturn<DeviceProfileInfo[]>
- {
- }
-
- [Route("/Dlna/Profiles/{Id}", "DELETE", Summary = "Deletes a profile")]
- public class DeleteProfile : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Profile Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/Dlna/Profiles/Default", "GET", Summary = "Gets the default profile")]
- public class GetDefaultProfile : IReturn<DeviceProfile>
- {
- }
-
- [Route("/Dlna/Profiles/{Id}", "GET", Summary = "Gets a single profile")]
- public class GetProfile : IReturn<DeviceProfile>
- {
- [ApiMember(Name = "Id", Description = "Profile Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Dlna/Profiles/{Id}", "POST", Summary = "Updates a profile")]
- public class UpdateProfile : DeviceProfile, IReturnVoid
- {
- }
-
- [Route("/Dlna/Profiles", "POST", Summary = "Creates a profile")]
- public class CreateProfile : DeviceProfile, IReturnVoid
- {
- }
-
- [Authenticated(Roles = "Admin")]
- public class DlnaService : IService
- {
- private readonly IDlnaManager _dlnaManager;
-
- public DlnaService(IDlnaManager dlnaManager)
- {
- _dlnaManager = dlnaManager;
- }
-
- public object Get(GetProfileInfos request)
- {
- return _dlnaManager.GetProfileInfos().ToArray();
- }
-
- public object Get(GetProfile request)
- {
- return _dlnaManager.GetProfile(request.Id);
- }
-
- public object Get(GetDefaultProfile request)
- {
- return _dlnaManager.GetDefaultProfile();
- }
-
- public void Delete(DeleteProfile request)
- {
- _dlnaManager.DeleteProfile(request.Id);
- }
-
- public void Post(UpdateProfile request)
- {
- _dlnaManager.UpdateProfile(request);
- }
-
- public void Post(CreateProfile request)
- {
- _dlnaManager.CreateProfile(request);
- }
- }
-}
diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs
index 3e325c41c..e4e9c55e0 100644
--- a/Emby.Dlna/Common/Argument.cs
+++ b/Emby.Dlna/Common/Argument.cs
@@ -1,12 +1,23 @@
-
namespace Emby.Dlna.Common
{
+ /// <summary>
+ /// DLNA Query parameter type, used when querying DLNA devices via SOAP.
+ /// </summary>
public class Argument
{
- public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets name of the DLNA argument.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
- public string Direction { get; set; }
+ /// <summary>
+ /// Gets or sets the direction of the parameter.
+ /// </summary>
+ public string Direction { get; set; } = string.Empty;
- public string RelatedStateVariable { get; set; }
+ /// <summary>
+ /// Gets or sets the related DLNA state variable for this argument.
+ /// </summary>
+ public string RelatedStateVariable { get; set; } = string.Empty;
}
}
diff --git a/Emby.Dlna/Common/DeviceIcon.cs b/Emby.Dlna/Common/DeviceIcon.cs
index 3a91b952e..f9fd1dcec 100644
--- a/Emby.Dlna/Common/DeviceIcon.cs
+++ b/Emby.Dlna/Common/DeviceIcon.cs
@@ -1,21 +1,41 @@
+using System.Globalization;
namespace Emby.Dlna.Common
{
+ /// <summary>
+ /// Defines the <see cref="DeviceIcon" />.
+ /// </summary>
public class DeviceIcon
{
- public string Url { get; set; }
+ /// <summary>
+ /// Gets or sets the Url.
+ /// </summary>
+ public string Url { get; set; } = string.Empty;
- public string MimeType { get; set; }
+ /// <summary>
+ /// Gets or sets the MimeType.
+ /// </summary>
+ public string MimeType { get; set; } = string.Empty;
+ /// <summary>
+ /// Gets or sets the Width.
+ /// </summary>
public int Width { get; set; }
+ /// <summary>
+ /// Gets or sets the Height.
+ /// </summary>
public int Height { get; set; }
- public string Depth { get; set; }
+ /// <summary>
+ /// Gets or sets the Depth.
+ /// </summary>
+ public string Depth { get; set; } = string.Empty;
+ /// <inheritdoc />
public override string ToString()
{
- return string.Format("{0}x{1}", Height, Width);
+ return string.Format(CultureInfo.InvariantCulture, "{0}x{1}", Height, Width);
}
}
}
diff --git a/Emby.Dlna/Common/DeviceService.cs b/Emby.Dlna/Common/DeviceService.cs
index c60d65291..c1369558e 100644
--- a/Emby.Dlna/Common/DeviceService.cs
+++ b/Emby.Dlna/Common/DeviceService.cs
@@ -1,21 +1,36 @@
-
namespace Emby.Dlna.Common
{
+ /// <summary>
+ /// Defines the <see cref="DeviceService" />.
+ /// </summary>
public class DeviceService
{
- public string ServiceType { get; set; }
+ /// <summary>
+ /// Gets or sets the Service Type.
+ /// </summary>
+ public string ServiceType { get; set; } = string.Empty;
- public string ServiceId { get; set; }
+ /// <summary>
+ /// Gets or sets the Service Id.
+ /// </summary>
+ public string ServiceId { get; set; } = string.Empty;
- public string ScpdUrl { get; set; }
+ /// <summary>
+ /// Gets or sets the Scpd Url.
+ /// </summary>
+ public string ScpdUrl { get; set; } = string.Empty;
- public string ControlUrl { get; set; }
+ /// <summary>
+ /// Gets or sets the Control Url.
+ /// </summary>
+ public string ControlUrl { get; set; } = string.Empty;
- public string EventSubUrl { get; set; }
+ /// <summary>
+ /// Gets or sets the EventSubUrl.
+ /// </summary>
+ public string EventSubUrl { get; set; } = string.Empty;
- public override string ToString()
- {
- return string.Format("{0}", ServiceId);
- }
+ /// <inheritdoc />
+ public override string ToString() => ServiceId;
}
}
diff --git a/Emby.Dlna/Common/ServiceAction.cs b/Emby.Dlna/Common/ServiceAction.cs
index 5e030d396..02b81a0aa 100644
--- a/Emby.Dlna/Common/ServiceAction.cs
+++ b/Emby.Dlna/Common/ServiceAction.cs
@@ -2,20 +2,30 @@ using System.Collections.Generic;
namespace Emby.Dlna.Common
{
+ /// <summary>
+ /// Defines the <see cref="ServiceAction" />.
+ /// </summary>
public class ServiceAction
{
- public string Name { get; set; }
-
- public List<Argument> ArgumentList { get; set; }
-
- public override string ToString()
- {
- return Name;
- }
-
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ServiceAction"/> class.
+ /// </summary>
public ServiceAction()
{
ArgumentList = new List<Argument>();
}
+
+ /// <summary>
+ /// Gets or sets the name of the action.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets the ArgumentList.
+ /// </summary>
+ public List<Argument> ArgumentList { get; }
+
+ /// <inheritdoc />
+ public override string ToString() => Name;
}
}
diff --git a/Emby.Dlna/Common/StateVariable.cs b/Emby.Dlna/Common/StateVariable.cs
index 4ca84bf51..fd733e085 100644
--- a/Emby.Dlna/Common/StateVariable.cs
+++ b/Emby.Dlna/Common/StateVariable.cs
@@ -1,25 +1,34 @@
using System;
+using System.Collections.Generic;
namespace Emby.Dlna.Common
{
+ /// <summary>
+ /// Defines the <see cref="StateVariable" />.
+ /// </summary>
public class StateVariable
{
- public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets the name of the state variable.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
- public string DataType { get; set; }
+ /// <summary>
+ /// Gets or sets the data type of the state variable.
+ /// </summary>
+ public string DataType { get; set; } = string.Empty;
+ /// <summary>
+ /// Gets or sets a value indicating whether it sends events.
+ /// </summary>
public bool SendsEvents { get; set; }
- public string[] AllowedValues { get; set; }
+ /// <summary>
+ /// Gets or sets the allowed values range.
+ /// </summary>
+ public IReadOnlyList<string> AllowedValues { get; set; } = Array.Empty<string>();
- public override string ToString()
- {
- return Name;
- }
-
- public StateVariable()
- {
- AllowedValues = Array.Empty<string>();
- }
+ /// <inheritdoc />
+ public override string ToString() => Name;
}
}
diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs
index 0ebb490a1..91fac4bef 100644
--- a/Emby.Dlna/Configuration/DlnaOptions.cs
+++ b/Emby.Dlna/Configuration/DlnaOptions.cs
@@ -1,23 +1,92 @@
+#pragma warning disable CS1591
namespace Emby.Dlna.Configuration
{
+ /// <summary>
+ /// The DlnaOptions class contains the user definable parameters for the dlna subsystems.
+ /// </summary>
public class DlnaOptions
{
- public bool EnablePlayTo { get; set; }
- public bool EnableServer { get; set; }
- public bool EnableDebugLog { get; set; }
- public bool BlastAliveMessages { get; set; }
- public int ClientDiscoveryIntervalSeconds { get; set; }
- public int BlastAliveMessageIntervalSeconds { get; set; }
- public string DefaultUserId { get; set; }
-
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DlnaOptions"/> class.
+ /// </summary>
public DlnaOptions()
{
EnablePlayTo = true;
EnableServer = true;
BlastAliveMessages = true;
+ SendOnlyMatchedHost = true;
ClientDiscoveryIntervalSeconds = 60;
- BlastAliveMessageIntervalSeconds = 1800;
+ AliveMessageIntervalSeconds = 1800;
}
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets a value to indicate the status of the dlna playTo subsystem.
+ /// </summary>
+ public bool EnablePlayTo { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets a value to indicate the status of the dlna server subsystem.
+ /// </summary>
+ public bool EnableServer { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether detailed dlna server logs are sent to the console/log.
+ /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public bool EnableDebugLog { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether whether detailed playTo debug logs are sent to the console/log.
+ /// If the setting "Emby.Dlna.PlayTo": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public bool EnablePlayToTracing { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ssdp client discovery interval time (in seconds).
+ /// This is the time after which the server will send a ssdp search request.
+ /// </summary>
+ public int ClientDiscoveryIntervalSeconds { get; set; }
+
+ /// <summary>
+ /// Gets or sets the frequency at which ssdp alive notifications are transmitted.
+ /// </summary>
+ public int AliveMessageIntervalSeconds { get; set; }
+
+ /// <summary>
+ /// Gets or sets the frequency at which ssdp alive notifications are transmitted. MIGRATING - TO BE REMOVED ONCE WEB HAS BEEN ALTERED.
+ /// </summary>
+ public int BlastAliveMessageIntervalSeconds
+ {
+ get
+ {
+ return AliveMessageIntervalSeconds;
+ }
+
+ set
+ {
+ AliveMessageIntervalSeconds = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the default user account that the dlna server uses.
+ /// </summary>
+ public string? DefaultUserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether playTo device profiles should be created.
+ /// </summary>
+ public bool AutoCreatePlayToProfiles { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to blast alive messages.
+ /// </summary>
+ public bool BlastAliveMessages { get; set; } = true;
+
+ /// <summary>
+ /// gets or sets a value indicating whether to send only matched host.
+ /// </summary>
+ public bool SendOnlyMatchedHost { get; set; } = true;
}
}
diff --git a/Emby.Dlna/ConfigurationExtension.cs b/Emby.Dlna/ConfigurationExtension.cs
index 82d726e01..3ca43052a 100644
--- a/Emby.Dlna/ConfigurationExtension.cs
+++ b/Emby.Dlna/ConfigurationExtension.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+#pragma warning disable CS1591
+
using Emby.Dlna.Configuration;
using MediaBrowser.Common.Configuration;
@@ -11,19 +12,4 @@ namespace Emby.Dlna
return manager.GetConfiguration<DlnaOptions>("dlna");
}
}
-
- public class DlnaConfigurationFactory : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new ConfigurationStore[]
- {
- new ConfigurationStore
- {
- Key = "dlna",
- ConfigurationType = typeof (DlnaOptions)
- }
- };
- }
- }
}
diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs
deleted file mode 100644
index cc427f2a1..000000000
--- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using System.Collections.Generic;
-using Emby.Dlna.Service;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Model.Xml;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Dlna.ConnectionManager
-{
- public class ConnectionManager : BaseService, IConnectionManager
- {
- private readonly IDlnaManager _dlna;
- private readonly ILogger _logger;
- private readonly IServerConfigurationManager _config;
- protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
-
- public ConnectionManager(IDlnaManager dlna, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
- : base(logger, httpClient)
- {
- _dlna = dlna;
- _config = config;
- _logger = logger;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
- }
-
- public string GetServiceXml(IDictionary<string, string> headers)
- {
- return new ConnectionManagerXmlBuilder().GetXml();
- }
-
- public ControlResponse ProcessControlRequest(ControlRequest request)
- {
- var profile = _dlna.GetProfile(request.Headers) ??
- _dlna.GetDefaultProfile();
-
- return new ControlHandler(_config, _logger, XmlReaderSettingsFactory, profile).ProcessControlRequest(request);
- }
- }
-}
diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs
new file mode 100644
index 000000000..916044a0c
--- /dev/null
+++ b/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs
@@ -0,0 +1,53 @@
+#pragma warning disable CS1591
+
+using System.Net.Http;
+using System.Threading.Tasks;
+using Emby.Dlna.Service;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dlna;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Dlna.ConnectionManager
+{
+ /// <summary>
+ /// Defines the <see cref="ConnectionManagerService" />.
+ /// </summary>
+ public class ConnectionManagerService : BaseService, IConnectionManager
+ {
+ private readonly IDlnaManager _dlna;
+ private readonly IServerConfigurationManager _config;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConnectionManagerService"/> class.
+ /// </summary>
+ /// <param name="dlna">The <see cref="IDlnaManager"/> for use with the <see cref="ConnectionManagerService"/> instance.</param>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> for use with the <see cref="ConnectionManagerService"/> instance.</param>
+ /// <param name="logger">The <see cref="ILogger{ConnectionManagerService}"/> for use with the <see cref="ConnectionManagerService"/> instance..</param>
+ /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/> for use with the <see cref="ConnectionManagerService"/> instance..</param>
+ public ConnectionManagerService(
+ IDlnaManager dlna,
+ IServerConfigurationManager config,
+ ILogger<ConnectionManagerService> logger,
+ IHttpClientFactory httpClientFactory)
+ : base(logger, httpClientFactory)
+ {
+ _dlna = dlna;
+ _config = config;
+ }
+
+ /// <inheritdoc />
+ public string GetServiceXml()
+ {
+ return ConnectionManagerXmlBuilder.GetXml();
+ }
+
+ /// <inheritdoc />
+ public Task<ControlResponse> ProcessControlRequestAsync(ControlRequest request)
+ {
+ var profile = _dlna.GetProfile(request.Headers) ??
+ _dlna.GetDefaultProfile();
+
+ return new ControlHandler(_config, Logger, profile).ProcessControlRequestAsync(request);
+ }
+ }
+}
diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs
index f5873455a..c484dac54 100644
--- a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs
+++ b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs
@@ -1,48 +1,62 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using Emby.Dlna.Common;
using Emby.Dlna.Service;
namespace Emby.Dlna.ConnectionManager
{
- public class ConnectionManagerXmlBuilder
+ /// <summary>
+ /// Defines the <see cref="ConnectionManagerXmlBuilder" />.
+ /// </summary>
+ public static class ConnectionManagerXmlBuilder
{
- public string GetXml()
+ /// <summary>
+ /// Gets the ConnectionManager:1 service template.
+ /// See http://upnp.org/specs/av/UPnP-av-ConnectionManager-v1-Service.pdf.
+ /// </summary>
+ /// <returns>An XML description of this service.</returns>
+ public static string GetXml()
{
- return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(), GetStateVariables());
+ return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables());
}
+ /// <summary>
+ /// Get the list of state variables for this invocation.
+ /// </summary>
+ /// <returns>The <see cref="IEnumerable{StateVariable}"/>.</returns>
private static IEnumerable<StateVariable> GetStateVariables()
{
- var list = new List<StateVariable>();
-
- list.Add(new StateVariable
+ var list = new List<StateVariable>
{
- Name = "SourceProtocolInfo",
- DataType = "string",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "SourceProtocolInfo",
+ DataType = "string",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "SinkProtocolInfo",
- DataType = "string",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "SinkProtocolInfo",
+ DataType = "string",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "CurrentConnectionIDs",
- DataType = "string",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "CurrentConnectionIDs",
+ DataType = "string",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ConnectionStatus",
- DataType = "string",
- SendsEvents = false,
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ConnectionStatus",
+ DataType = "string",
+ SendsEvents = false,
- AllowedValues = new string[]
+ AllowedValues = new[]
{
"OK",
"ContentFormatMismatch",
@@ -50,55 +64,56 @@ namespace Emby.Dlna.ConnectionManager
"UnreliableChannel",
"Unknown"
}
- });
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ConnectionManager",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ConnectionManager",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Direction",
- DataType = "string",
- SendsEvents = false,
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Direction",
+ DataType = "string",
+ SendsEvents = false,
- AllowedValues = new string[]
+ AllowedValues = new[]
{
"Output",
"Input"
}
- });
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ProtocolInfo",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ProtocolInfo",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ConnectionID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ConnectionID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_AVTransportID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_AVTransportID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RcsID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RcsID",
+ DataType = "ui4",
+ SendsEvents = false
+ }
+ };
return list;
}
diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs
index 16211c61f..1a1790ee6 100644
--- a/Emby.Dlna/ConnectionManager/ControlHandler.cs
+++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs
@@ -1,40 +1,55 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Xml;
using Emby.Dlna.Service;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.ConnectionManager
{
+ /// <summary>
+ /// Defines the <see cref="ControlHandler" />.
+ /// </summary>
public class ControlHandler : BaseControlHandler
{
private readonly DeviceProfile _profile;
- protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ControlHandler"/> class.
+ /// </summary>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="logger">The <see cref="ILogger"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="profile">The <see cref="DeviceProfile"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile)
+ : base(config, logger)
+ {
+ _profile = profile;
+ }
+
+ /// <inheritdoc />
+ protected override void WriteResult(string methodName, IReadOnlyDictionary<string, string> methodParams, XmlWriter xmlWriter)
{
if (string.Equals(methodName, "GetProtocolInfo", StringComparison.OrdinalIgnoreCase))
{
- return HandleGetProtocolInfo();
+ HandleGetProtocolInfo(xmlWriter);
+ return;
}
throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
- private IEnumerable<KeyValuePair<string, string>> HandleGetProtocolInfo()
+ /// <summary>
+ /// Builds the response to the GetProtocolInfo request.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private void HandleGetProtocolInfo(XmlWriter xmlWriter)
{
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "Source", _profile.ProtocolInfo },
- { "Sink", "" }
- };
- }
-
- public ControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory, DeviceProfile profile) : base(config, logger, xmlReaderSettingsFactory)
- {
- _profile = profile;
+ xmlWriter.WriteElementString("Source", _profile.ProtocolInfo);
+ xmlWriter.WriteElementString("Sink", string.Empty);
}
}
}
diff --git a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs
index b7727b558..542c7bfb4 100644
--- a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs
+++ b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs
@@ -1,11 +1,20 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using Emby.Dlna.Common;
namespace Emby.Dlna.ConnectionManager
{
- public class ServiceActionListBuilder
+ /// <summary>
+ /// Defines the <see cref="ServiceActionListBuilder" />.
+ /// </summary>
+ public static class ServiceActionListBuilder
{
- public IEnumerable<ServiceAction> GetActions()
+ /// <summary>
+ /// Returns an enumerable of the ConnectionManagar:1 DLNA actions.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{ServiceAction}"/>.</returns>
+ public static IEnumerable<ServiceAction> GetActions()
{
var list = new List<ServiceAction>
{
@@ -19,6 +28,10 @@ namespace Emby.Dlna.ConnectionManager
return list;
}
+ /// <summary>
+ /// Returns the action details for "PrepareForConnection".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction PrepareForConnection()
{
var action = new ServiceAction
@@ -78,6 +91,10 @@ namespace Emby.Dlna.ConnectionManager
return action;
}
+ /// <summary>
+ /// Returns the action details for "GetCurrentConnectionInfo".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetCurrentConnectionInfo()
{
var action = new ServiceAction
@@ -144,7 +161,11 @@ namespace Emby.Dlna.ConnectionManager
return action;
}
- private ServiceAction GetProtocolInfo()
+ /// <summary>
+ /// Returns the action details for "GetProtocolInfo".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetProtocolInfo()
{
var action = new ServiceAction
{
@@ -168,7 +189,11 @@ namespace Emby.Dlna.ConnectionManager
return action;
}
- private ServiceAction GetCurrentConnectionIDs()
+ /// <summary>
+ /// Returns the action details for "GetCurrentConnectionIDs".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetCurrentConnectionIDs()
{
var action = new ServiceAction
{
@@ -185,7 +210,11 @@ namespace Emby.Dlna.ConnectionManager
return action;
}
- private ServiceAction ConnectionComplete()
+ /// <summary>
+ /// Returns the action details for "ConnectionComplete".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction ConnectionComplete()
{
var action = new ServiceAction
{
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs
deleted file mode 100644
index b0fec90e6..000000000
--- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs
+++ /dev/null
@@ -1,142 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Emby.Dlna.Service;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.TV;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Xml;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Dlna.ContentDirectory
-{
- public class ContentDirectory : BaseService, IContentDirectory
- {
- private readonly ILibraryManager _libraryManager;
- private readonly IImageProcessor _imageProcessor;
- private readonly IUserDataManager _userDataManager;
- private readonly IDlnaManager _dlna;
- private readonly IServerConfigurationManager _config;
- private readonly IUserManager _userManager;
- private readonly ILocalizationManager _localization;
- private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IUserViewManager _userViewManager;
- private readonly IMediaEncoder _mediaEncoder;
- protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
- private readonly ITVSeriesManager _tvSeriesManager;
-
- public ContentDirectory(IDlnaManager dlna,
- IUserDataManager userDataManager,
- IImageProcessor imageProcessor,
- ILibraryManager libraryManager,
- IServerConfigurationManager config,
- IUserManager userManager,
- ILogger logger,
- IHttpClient httpClient, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IUserViewManager userViewManager, IMediaEncoder mediaEncoder, IXmlReaderSettingsFactory xmlReaderSettingsFactory, ITVSeriesManager tvSeriesManager)
- : base(logger, httpClient)
- {
- _dlna = dlna;
- _userDataManager = userDataManager;
- _imageProcessor = imageProcessor;
- _libraryManager = libraryManager;
- _config = config;
- _userManager = userManager;
- _localization = localization;
- _mediaSourceManager = mediaSourceManager;
- _userViewManager = userViewManager;
- _mediaEncoder = mediaEncoder;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
- _tvSeriesManager = tvSeriesManager;
- }
-
- private int SystemUpdateId
- {
- get
- {
- var now = DateTime.UtcNow;
-
- return now.Year + now.DayOfYear + now.Hour;
- }
- }
-
- public string GetServiceXml(IDictionary<string, string> headers)
- {
- return new ContentDirectoryXmlBuilder().GetXml();
- }
-
- public ControlResponse ProcessControlRequest(ControlRequest request)
- {
- var profile = _dlna.GetProfile(request.Headers) ??
- _dlna.GetDefaultProfile();
-
- var serverAddress = request.RequestedUrl.Substring(0, request.RequestedUrl.IndexOf("/dlna", StringComparison.OrdinalIgnoreCase));
-
- var user = GetUser(profile);
-
- return new ControlHandler(
- Logger,
- _libraryManager,
- profile,
- serverAddress,
- null,
- _imageProcessor,
- _userDataManager,
- user,
- SystemUpdateId,
- _config,
- _localization,
- _mediaSourceManager,
- _userViewManager,
- _mediaEncoder,
- XmlReaderSettingsFactory,
- _tvSeriesManager)
- .ProcessControlRequest(request);
- }
-
- private User GetUser(DeviceProfile profile)
- {
- if (!string.IsNullOrEmpty(profile.UserId))
- {
- var user = _userManager.GetUserById(profile.UserId);
-
- if (user != null)
- {
- return user;
- }
- }
-
- var userId = _config.GetDlnaConfiguration().DefaultUserId;
-
- if (!string.IsNullOrEmpty(userId))
- {
- var user = _userManager.GetUserById(userId);
-
- if (user != null)
- {
- return user;
- }
- }
-
- foreach (var user in _userManager.Users)
- {
- if (user.Policy.IsAdministrator)
- {
- return user;
- }
- }
-
- foreach (var user in _userManager.Users)
- {
- return user;
- }
-
- return null;
- }
- }
-}
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs
new file mode 100644
index 000000000..9020dea99
--- /dev/null
+++ b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs
@@ -0,0 +1,176 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Linq;
+using System.Net.Http;
+using System.Threading.Tasks;
+using Emby.Dlna.Service;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.TV;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Globalization;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Dlna.ContentDirectory
+{
+ /// <summary>
+ /// Defines the <see cref="ContentDirectoryService" />.
+ /// </summary>
+ public class ContentDirectoryService : BaseService, IContentDirectory
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IImageProcessor _imageProcessor;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDlnaManager _dlna;
+ private readonly IServerConfigurationManager _config;
+ private readonly IUserManager _userManager;
+ private readonly ILocalizationManager _localization;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IUserViewManager _userViewManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly ITVSeriesManager _tvSeriesManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ContentDirectoryService"/> class.
+ /// </summary>
+ /// <param name="dlna">The <see cref="IDlnaManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="userDataManager">The <see cref="IUserDataManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="imageProcessor">The <see cref="IImageProcessor"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="libraryManager">The <see cref="ILibraryManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="userManager">The <see cref="IUserManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="logger">The <see cref="ILogger{ContentDirectoryService}"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="httpClient">The <see cref="IHttpClientFactory"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="localization">The <see cref="ILocalizationManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="userViewManager">The <see cref="IUserViewManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ /// <param name="tvSeriesManager">The <see cref="ITVSeriesManager"/> to use in the <see cref="ContentDirectoryService"/> instance.</param>
+ public ContentDirectoryService(
+ IDlnaManager dlna,
+ IUserDataManager userDataManager,
+ IImageProcessor imageProcessor,
+ ILibraryManager libraryManager,
+ IServerConfigurationManager config,
+ IUserManager userManager,
+ ILogger<ContentDirectoryService> logger,
+ IHttpClientFactory httpClient,
+ ILocalizationManager localization,
+ IMediaSourceManager mediaSourceManager,
+ IUserViewManager userViewManager,
+ IMediaEncoder mediaEncoder,
+ ITVSeriesManager tvSeriesManager)
+ : base(logger, httpClient)
+ {
+ _dlna = dlna;
+ _userDataManager = userDataManager;
+ _imageProcessor = imageProcessor;
+ _libraryManager = libraryManager;
+ _config = config;
+ _userManager = userManager;
+ _localization = localization;
+ _mediaSourceManager = mediaSourceManager;
+ _userViewManager = userViewManager;
+ _mediaEncoder = mediaEncoder;
+ _tvSeriesManager = tvSeriesManager;
+ }
+
+ /// <summary>
+ /// Gets the system id. (A unique id which changes on when our definition changes.)
+ /// </summary>
+ private static int SystemUpdateId
+ {
+ get
+ {
+ var now = DateTime.UtcNow;
+
+ return now.Year + now.DayOfYear + now.Hour;
+ }
+ }
+
+ /// <inheritdoc />
+ public string GetServiceXml()
+ {
+ return ContentDirectoryXmlBuilder.GetXml();
+ }
+
+ /// <inheritdoc />
+ public Task<ControlResponse> ProcessControlRequestAsync(ControlRequest request)
+ {
+ if (request == null)
+ {
+ throw new ArgumentNullException(nameof(request));
+ }
+
+ var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile();
+
+ var serverAddress = request.RequestedUrl.Substring(0, request.RequestedUrl.IndexOf("/dlna", StringComparison.OrdinalIgnoreCase));
+
+ var user = GetUser(profile);
+
+ return new ControlHandler(
+ Logger,
+ _libraryManager,
+ profile,
+ serverAddress,
+ null,
+ _imageProcessor,
+ _userDataManager,
+ user,
+ SystemUpdateId,
+ _config,
+ _localization,
+ _mediaSourceManager,
+ _userViewManager,
+ _mediaEncoder,
+ _tvSeriesManager)
+ .ProcessControlRequestAsync(request);
+ }
+
+ /// <summary>
+ /// Get the user stored in the device profile.
+ /// </summary>
+ /// <param name="profile">The <see cref="DeviceProfile"/>.</param>
+ /// <returns>The <see cref="User"/>.</returns>
+ private User? GetUser(DeviceProfile profile)
+ {
+ if (!string.IsNullOrEmpty(profile.UserId))
+ {
+ var user = _userManager.GetUserById(Guid.Parse(profile.UserId));
+
+ if (user != null)
+ {
+ return user;
+ }
+ }
+
+ var userId = _config.GetDlnaConfiguration().DefaultUserId;
+
+ if (!string.IsNullOrEmpty(userId))
+ {
+ var user = _userManager.GetUserById(Guid.Parse(userId));
+
+ if (user != null)
+ {
+ return user;
+ }
+ }
+
+ foreach (var user in _userManager.Users)
+ {
+ if (user.HasPermission(PermissionKind.IsAdministrator))
+ {
+ return user;
+ }
+ }
+
+ return _userManager.Users.FirstOrDefault();
+ }
+ }
+}
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
index 15fdb36c4..3edaabb70 100644
--- a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
+++ b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
@@ -1,145 +1,159 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using Emby.Dlna.Common;
using Emby.Dlna.Service;
namespace Emby.Dlna.ContentDirectory
{
- public class ContentDirectoryXmlBuilder
+ /// <summary>
+ /// Defines the <see cref="ContentDirectoryXmlBuilder" />.
+ /// </summary>
+ public static class ContentDirectoryXmlBuilder
{
- public string GetXml()
+ /// <summary>
+ /// Gets the ContentDirectory:1 service template.
+ /// See http://upnp.org/specs/av/UPnP-av-ContentDirectory-v1-Service.pdf.
+ /// </summary>
+ /// <returns>An XML description of this service.</returns>
+ public static string GetXml()
{
- return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(),
- GetStateVariables());
+ return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables());
}
+ /// <summary>
+ /// Get the list of state variables for this invocation.
+ /// </summary>
+ /// <returns>The <see cref="IEnumerable{StateVariable}"/>.</returns>
private static IEnumerable<StateVariable> GetStateVariables()
{
- var list = new List<StateVariable>();
-
- list.Add(new StateVariable
+ var list = new List<StateVariable>
{
- Name = "A_ARG_TYPE_Filter",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Filter",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_SortCriteria",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_SortCriteria",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Index",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Index",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Count",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Count",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_UpdateID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_UpdateID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SearchCapabilities",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "SearchCapabilities",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SortCapabilities",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "SortCapabilities",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SystemUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "SystemUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_SearchCriteria",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_SearchCriteria",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Result",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Result",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ObjectID",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ObjectID",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_BrowseFlag",
- DataType = "string",
- SendsEvents = false,
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_BrowseFlag",
+ DataType = "string",
+ SendsEvents = false,
- AllowedValues = new string[]
+ AllowedValues = new[]
{
"BrowseMetadata",
"BrowseDirectChildren"
}
- });
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_BrowseLetter",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_BrowseLetter",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_CategoryType",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_CategoryType",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_PosSec",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_PosSec",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Featurelist",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Featurelist",
+ DataType = "string",
+ SendsEvents = false
+ }
+ };
return list;
}
diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs
index 1150afdba..ac336e5dc 100644
--- a/Emby.Dlna/ContentDirectory/ControlHandler.cs
+++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -8,6 +10,8 @@ using System.Threading;
using System.Xml;
using Emby.Dlna.Didl;
using Emby.Dlna.Service;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
@@ -15,7 +19,6 @@ using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
@@ -25,13 +28,26 @@ using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
+using Book = MediaBrowser.Controller.Entities.Book;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Dlna.ContentDirectory
{
+ /// <summary>
+ /// Defines the <see cref="ControlHandler" />.
+ /// </summary>
public class ControlHandler : BaseControlHandler
{
+ private const string NsDc = "http://purl.org/dc/elements/1.1/";
+ private const string NsDidl = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
+ private const string NsDlna = "urn:schemas-dlna-org:metadata-1-0/";
+ private const string NsUpnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
+
private readonly ILibraryManager _libraryManager;
private readonly IUserDataManager _userDataManager;
private readonly IServerConfigurationManager _config;
@@ -39,20 +55,47 @@ namespace Emby.Dlna.ContentDirectory
private readonly IUserViewManager _userViewManager;
private readonly ITVSeriesManager _tvSeriesManager;
- private const string NS_DC = "http://purl.org/dc/elements/1.1/";
- private const string NS_DIDL = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
- private const string NS_DLNA = "urn:schemas-dlna-org:metadata-1-0/";
- private const string NS_UPNP = "urn:schemas-upnp-org:metadata-1-0/upnp/";
-
private readonly int _systemUpdateId;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly DidlBuilder _didlBuilder;
private readonly DeviceProfile _profile;
- public ControlHandler(ILogger logger, ILibraryManager libraryManager, DeviceProfile profile, string serverAddress, string accessToken, IImageProcessor imageProcessor, IUserDataManager userDataManager, User user, int systemUpdateId, IServerConfigurationManager config, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IUserViewManager userViewManager, IMediaEncoder mediaEncoder, IXmlReaderSettingsFactory xmlReaderSettingsFactory, ITVSeriesManager tvSeriesManager)
- : base(config, logger, xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ControlHandler"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="libraryManager">The <see cref="ILibraryManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="profile">The <see cref="DeviceProfile"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="serverAddress">The server address to use in this instance> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="accessToken">The <see cref="string"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="imageProcessor">The <see cref="IImageProcessor"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="userDataManager">The <see cref="IUserDataManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="user">The <see cref="User"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="systemUpdateId">The system id for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="localization">The <see cref="ILocalizationManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="userViewManager">The <see cref="IUserViewManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="tvSeriesManager">The <see cref="ITVSeriesManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ public ControlHandler(
+ ILogger logger,
+ ILibraryManager libraryManager,
+ DeviceProfile profile,
+ string serverAddress,
+ string accessToken,
+ IImageProcessor imageProcessor,
+ IUserDataManager userDataManager,
+ User user,
+ int systemUpdateId,
+ IServerConfigurationManager config,
+ ILocalizationManager localization,
+ IMediaSourceManager mediaSourceManager,
+ IUserViewManager userViewManager,
+ IMediaEncoder mediaEncoder,
+ ITVSeriesManager tvSeriesManager)
+ : base(config, logger)
{
_libraryManager = libraryManager;
_userDataManager = userDataManager;
@@ -63,149 +106,210 @@ namespace Emby.Dlna.ContentDirectory
_profile = profile;
_config = config;
- _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, mediaEncoder);
+ _didlBuilder = new DidlBuilder(
+ profile,
+ user,
+ imageProcessor,
+ serverAddress,
+ accessToken,
+ userDataManager,
+ localization,
+ mediaSourceManager,
+ Logger,
+ mediaEncoder,
+ libraryManager);
}
- protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams)
+ /// <inheritdoc />
+ protected override void WriteResult(string methodName, IReadOnlyDictionary<string, string> methodParams, XmlWriter xmlWriter)
{
- var deviceId = "test";
+ if (xmlWriter == null)
+ {
+ throw new ArgumentNullException(nameof(xmlWriter));
+ }
+
+ if (methodParams == null)
+ {
+ throw new ArgumentNullException(nameof(methodParams));
+ }
- var user = _user;
+ const string DeviceId = "test";
if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase))
- return HandleGetSearchCapabilities();
+ {
+ HandleGetSearchCapabilities(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "GetSortCapabilities", StringComparison.OrdinalIgnoreCase))
- return HandleGetSortCapabilities();
+ {
+ HandleGetSortCapabilities(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "GetSortExtensionCapabilities", StringComparison.OrdinalIgnoreCase))
- return HandleGetSortExtensionCapabilities();
+ {
+ HandleGetSortExtensionCapabilities(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "GetSystemUpdateID", StringComparison.OrdinalIgnoreCase))
- return HandleGetSystemUpdateID();
+ {
+ HandleGetSystemUpdateID(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "Browse", StringComparison.OrdinalIgnoreCase))
- return HandleBrowse(methodParams, user, deviceId);
+ {
+ HandleBrowse(xmlWriter, methodParams, DeviceId);
+ return;
+ }
if (string.Equals(methodName, "X_GetFeatureList", StringComparison.OrdinalIgnoreCase))
- return HandleXGetFeatureList();
+ {
+ HandleXGetFeatureList(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "GetFeatureList", StringComparison.OrdinalIgnoreCase))
- return HandleGetFeatureList();
+ {
+ HandleGetFeatureList(xmlWriter);
+ return;
+ }
if (string.Equals(methodName, "X_SetBookmark", StringComparison.OrdinalIgnoreCase))
- return HandleXSetBookmark(methodParams, user);
+ {
+ HandleXSetBookmark(methodParams);
+ return;
+ }
if (string.Equals(methodName, "Search", StringComparison.OrdinalIgnoreCase))
- return HandleSearch(methodParams, user, deviceId);
+ {
+ HandleSearch(xmlWriter, methodParams, DeviceId);
+ return;
+ }
if (string.Equals(methodName, "X_BrowseByLetter", StringComparison.OrdinalIgnoreCase))
- return HandleX_BrowseByLetter(methodParams, user, deviceId);
+ {
+ HandleXBrowseByLetter(xmlWriter, methodParams, DeviceId);
+ return;
+ }
throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
- private IEnumerable<KeyValuePair<string, string>> HandleXSetBookmark(IDictionary<string, string> sparams, User user)
+ /// <summary>
+ /// Adds a "XSetBookmark" element to the xml document.
+ /// </summary>
+ /// <param name="sparams">The method parameters.</param>
+ private void HandleXSetBookmark(IReadOnlyDictionary<string, string> sparams)
{
var id = sparams["ObjectID"];
- var serverItem = GetItemFromObjectId(id, user);
+ var serverItem = GetItemFromObjectId(id);
var item = serverItem.Item;
- var newbookmark = int.Parse(sparams["PosSecond"], _usCulture);
+ var newbookmark = int.Parse(sparams["PosSecond"], CultureInfo.InvariantCulture);
- var userdata = _userDataManager.GetUserData(user, item);
+ var userdata = _userDataManager.GetUserData(_user, item);
userdata.PlaybackPositionTicks = TimeSpan.FromSeconds(newbookmark).Ticks;
- _userDataManager.SaveUserData(user, item, userdata, UserDataSaveReason.TogglePlayed,
+ _userDataManager.SaveUserData(
+ _user,
+ item,
+ userdata,
+ UserDataSaveReason.TogglePlayed,
CancellationToken.None);
-
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
- private IEnumerable<KeyValuePair<string, string>> HandleGetSearchCapabilities()
+ /// <summary>
+ /// Adds the "SearchCaps" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleGetSearchCapabilities(XmlWriter xmlWriter)
{
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "SearchCaps", "res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords" }
- };
- }
-
- private IEnumerable<KeyValuePair<string, string>> HandleGetSortCapabilities()
- {
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "SortCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating" }
- };
+ xmlWriter.WriteElementString(
+ "SearchCaps",
+ "res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords");
}
- private IEnumerable<KeyValuePair<string, string>> HandleGetSortExtensionCapabilities()
+ /// <summary>
+ /// Adds the "SortCaps" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleGetSortCapabilities(XmlWriter xmlWriter)
{
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "SortExtensionCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating" }
- };
+ xmlWriter.WriteElementString(
+ "SortCaps",
+ "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
- private IEnumerable<KeyValuePair<string, string>> HandleGetSystemUpdateID()
+ /// <summary>
+ /// Adds the "SortExtensionCaps" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter)
{
- var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- headers.Add("Id", _systemUpdateId.ToString(_usCulture));
- return headers;
- }
-
- private IEnumerable<KeyValuePair<string, string>> HandleGetFeatureList()
- {
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "FeatureList", GetFeatureListXml() }
- };
+ xmlWriter.WriteElementString(
+ "SortExtensionCaps",
+ "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
- private IEnumerable<KeyValuePair<string, string>> HandleXGetFeatureList()
+ /// <summary>
+ /// Adds the "Id" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private void HandleGetSystemUpdateID(XmlWriter xmlWriter)
{
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
- {
- { "FeatureList", GetFeatureListXml() }
- };
+ xmlWriter.WriteElementString("Id", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
- private string GetFeatureListXml()
+ /// <summary>
+ /// Adds the "FeatureList" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleGetFeatureList(XmlWriter xmlWriter)
{
- var builder = new StringBuilder();
-
- builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
- builder.Append("<Features xmlns=\"urn:schemas-upnp-org:av:avs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd\">");
-
- builder.Append("<Feature name=\"samsung.com_BASICVIEW\" version=\"1\">");
- builder.Append("<container id=\"I\" type=\"object.item.imageItem\"/>");
- builder.Append("<container id=\"A\" type=\"object.item.audioItem\"/>");
- builder.Append("<container id=\"V\" type=\"object.item.videoItem\"/>");
- builder.Append("</Feature>");
-
- builder.Append("</Features>");
-
- return builder.ToString();
+ xmlWriter.WriteElementString("FeatureList", WriteFeatureListXml());
}
- public string GetValueOrDefault(IDictionary<string, string> sparams, string key, string defaultValue)
+ /// <summary>
+ /// Adds the "FeatureList" element to the xml document.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleXGetFeatureList(XmlWriter xmlWriter)
+ => HandleGetFeatureList(xmlWriter);
+
+ /// <summary>
+ /// Builds a static feature list.
+ /// </summary>
+ /// <returns>The xml feature list.</returns>
+ private static string WriteFeatureListXml()
{
- if (sparams.TryGetValue(key, out string val))
- {
- return val;
- }
-
- return defaultValue;
+ return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<Features xmlns=\"urn:schemas-upnp-org:av:avs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd\">"
+ + "<Feature name=\"samsung.com_BASICVIEW\" version=\"1\">"
+ + "<container id=\"I\" type=\"object.item.imageItem\"/>"
+ + "<container id=\"A\" type=\"object.item.audioItem\"/>"
+ + "<container id=\"V\" type=\"object.item.videoItem\"/>"
+ + "</Feature>"
+ + "</Features>";
}
- private IEnumerable<KeyValuePair<string, string>> HandleBrowse(IDictionary<string, string> sparams, User user, string deviceId)
+ /// <summary>
+ /// Builds the "Browse" xml response.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ /// <param name="sparams">The method parameters.</param>
+ /// <param name="deviceId">The device Id to use.</param>
+ private void HandleBrowse(XmlWriter xmlWriter, IReadOnlyDictionary<string, string> sparams, string deviceId)
{
var id = sparams["ObjectID"];
var flag = sparams["BrowseFlag"];
- var filter = new Filter(GetValueOrDefault(sparams, "Filter", "*"));
- var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", ""));
+ var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));
+ var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty));
var provided = 0;
@@ -224,104 +328,108 @@ namespace Emby.Dlna.ContentDirectory
start = startVal;
}
- var settings = new XmlWriterSettings
- {
- Encoding = Encoding.UTF8,
- CloseOutput = false,
- OmitXmlDeclaration = true,
- ConformanceLevel = ConformanceLevel.Fragment
- };
-
- StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8);
-
int totalCount;
- var dlnaOptions = _config.GetDlnaConfiguration();
-
- using (var writer = XmlWriter.Create(builder, settings))
+ using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
{
- //writer.WriteStartDocument();
-
- writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL);
-
- writer.WriteAttributeString("xmlns", "dc", null, NS_DC);
- writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA);
- writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP);
- //didl.SetAttribute("xmlns:sec", NS_SEC);
-
- DidlBuilder.WriteXmlRootAttributes(_profile, writer);
-
- var serverItem = GetItemFromObjectId(id, user);
- var item = serverItem.Item;
+ var settings = new XmlWriterSettings()
+ {
+ Encoding = Encoding.UTF8,
+ CloseOutput = false,
+ OmitXmlDeclaration = true,
+ ConformanceLevel = ConformanceLevel.Fragment
+ };
- if (string.Equals(flag, "BrowseMetadata"))
+ using (var writer = XmlWriter.Create(builder, settings))
{
- totalCount = 1;
+ writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
- if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue)
- {
- var childrenResult = (GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount));
+ writer.WriteAttributeString("xmlns", "dc", null, NsDc);
+ writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
+ writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
- _didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id);
- }
- else
- {
- _didlBuilder.WriteItemElement(dlnaOptions, writer, item, user, null, null, deviceId, filter);
- }
+ DidlBuilder.WriteXmlRootAttributes(_profile, writer);
- provided++;
- }
- else
- {
- var childrenResult = (GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount));
- totalCount = childrenResult.TotalRecordCount;
-
- provided = childrenResult.Items.Length;
+ var serverItem = GetItemFromObjectId(id);
+ var item = serverItem.Item;
- foreach (var i in childrenResult.Items)
+ if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal))
{
- var childItem = i.Item;
- var displayStubType = i.StubType;
+ totalCount = 1;
- if (childItem.IsDisplayedAsFolder || displayStubType.HasValue)
+ if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue)
{
- var childCount = (GetUserItems(childItem, displayStubType, user, sortCriteria, null, 0))
- .TotalRecordCount;
+ var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount);
- _didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter);
+ _didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id);
}
else
{
- _didlBuilder.WriteItemElement(dlnaOptions, writer, childItem, user, item, serverItem.StubType, deviceId, filter);
+ _didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter);
+ }
+
+ provided++;
+ }
+ else
+ {
+ var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount);
+ totalCount = childrenResult.TotalRecordCount;
+
+ provided = childrenResult.Items.Count;
+
+ foreach (var i in childrenResult.Items)
+ {
+ var childItem = i.Item;
+ var displayStubType = i.StubType;
+
+ if (childItem.IsDisplayedAsFolder || displayStubType.HasValue)
+ {
+ var childCount = GetUserItems(childItem, displayStubType, _user, sortCriteria, null, 0)
+ .TotalRecordCount;
+
+ _didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter);
+ }
+ else
+ {
+ _didlBuilder.WriteItemElement(writer, childItem, _user, item, serverItem.StubType, deviceId, filter);
+ }
}
}
+
+ writer.WriteFullEndElement();
}
- writer.WriteFullEndElement();
- //writer.WriteEndDocument();
- }
- var resXML = builder.ToString();
+ xmlWriter.WriteElementString("Result", builder.ToString());
+ }
- return new[]
- {
- new KeyValuePair<string,string>("Result", resXML),
- new KeyValuePair<string,string>("NumberReturned", provided.ToString(_usCulture)),
- new KeyValuePair<string,string>("TotalMatches", totalCount.ToString(_usCulture)),
- new KeyValuePair<string,string>("UpdateID", _systemUpdateId.ToString(_usCulture))
- };
+ xmlWriter.WriteElementString("NumberReturned", provided.ToString(CultureInfo.InvariantCulture));
+ xmlWriter.WriteElementString("TotalMatches", totalCount.ToString(CultureInfo.InvariantCulture));
+ xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
- private IEnumerable<KeyValuePair<string, string>> HandleX_BrowseByLetter(IDictionary<string, string> sparams, User user, string deviceId)
+ /// <summary>
+ /// Builds the response to the "X_BrowseByLetter request.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ /// <param name="sparams">The method parameters.</param>
+ /// <param name="deviceId">The device id.</param>
+ private void HandleXBrowseByLetter(XmlWriter xmlWriter, IReadOnlyDictionary<string, string> sparams, string deviceId)
{
// TODO: Implement this method
- return HandleSearch(sparams, user, deviceId);
+ HandleSearch(xmlWriter, sparams, deviceId);
}
- private IEnumerable<KeyValuePair<string, string>> HandleSearch(IDictionary<string, string> sparams, User user, string deviceId)
+ /// <summary>
+ /// Builds a response to the "Search" request.
+ /// </summary>
+ /// <param name="xmlWriter">The xmlWriter<see cref="XmlWriter"/>.</param>
+ /// <param name="sparams">The method parameters.</param>
+ /// <param name="deviceId">The deviceId<see cref="string"/>.</param>
+ private void HandleSearch(XmlWriter xmlWriter, IReadOnlyDictionary<string, string> sparams, string deviceId)
{
- var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", ""));
- var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", ""));
- var filter = new Filter(GetValueOrDefault(sparams, "Filter", "*"));
+ var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", string.Empty));
+ var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty));
+ var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));
// sort example: dc:title, dc:date
@@ -340,109 +448,106 @@ namespace Emby.Dlna.ContentDirectory
start = startVal;
}
- var settings = new XmlWriterSettings
- {
- Encoding = Encoding.UTF8,
- CloseOutput = false,
- OmitXmlDeclaration = true,
- ConformanceLevel = ConformanceLevel.Fragment
- };
+ QueryResult<BaseItem> childrenResult;
- StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8);
- int totalCount = 0;
- int provided = 0;
-
- using (var writer = XmlWriter.Create(builder, settings))
+ using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
{
- //writer.WriteStartDocument();
-
- writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL);
-
- writer.WriteAttributeString("xmlns", "dc", null, NS_DC);
- writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA);
- writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP);
- //didl.SetAttribute("xmlns:sec", NS_SEC);
+ var settings = new XmlWriterSettings()
+ {
+ Encoding = Encoding.UTF8,
+ CloseOutput = false,
+ OmitXmlDeclaration = true,
+ ConformanceLevel = ConformanceLevel.Fragment
+ };
- DidlBuilder.WriteXmlRootAttributes(_profile, writer);
+ using (var writer = XmlWriter.Create(builder, settings))
+ {
+ writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
- var serverItem = GetItemFromObjectId(sparams["ContainerID"], user);
+ writer.WriteAttributeString("xmlns", "dc", null, NsDc);
+ writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
+ writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
- var item = serverItem.Item;
+ DidlBuilder.WriteXmlRootAttributes(_profile, writer);
- var childrenResult = (GetChildrenSorted(item, user, searchCriteria, sortCriteria, start, requestedCount));
+ var serverItem = GetItemFromObjectId(sparams["ContainerID"]);
- totalCount = childrenResult.TotalRecordCount;
+ var item = serverItem.Item;
- provided = childrenResult.Items.Length;
+ childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount);
- var dlnaOptions = _config.GetDlnaConfiguration();
+ var dlnaOptions = _config.GetDlnaConfiguration();
- foreach (var i in childrenResult.Items)
- {
- if (i.IsDisplayedAsFolder)
+ foreach (var i in childrenResult.Items)
{
- var childCount = (GetChildrenSorted(i, user, searchCriteria, sortCriteria, null, 0))
- .TotalRecordCount;
+ if (i.IsDisplayedAsFolder)
+ {
+ var childCount = GetChildrenSorted(i, _user, searchCriteria, sortCriteria, null, 0)
+ .TotalRecordCount;
- _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter);
- }
- else
- {
- _didlBuilder.WriteItemElement(dlnaOptions, writer, i, user, item, serverItem.StubType, deviceId, filter);
+ _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter);
+ }
+ else
+ {
+ _didlBuilder.WriteItemElement(writer, i, _user, item, serverItem.StubType, deviceId, filter);
+ }
}
+
+ writer.WriteFullEndElement();
}
- writer.WriteFullEndElement();
- //writer.WriteEndDocument();
+ xmlWriter.WriteElementString("Result", builder.ToString());
}
- var resXML = builder.ToString();
-
- return new List<KeyValuePair<string, string>>
- {
- new KeyValuePair<string,string>("Result", resXML),
- new KeyValuePair<string,string>("NumberReturned", provided.ToString(_usCulture)),
- new KeyValuePair<string,string>("TotalMatches", totalCount.ToString(_usCulture)),
- new KeyValuePair<string,string>("UpdateID", _systemUpdateId.ToString(_usCulture))
- };
+ xmlWriter.WriteElementString("NumberReturned", childrenResult.Items.Count.ToString(CultureInfo.InvariantCulture));
+ xmlWriter.WriteElementString("TotalMatches", childrenResult.TotalRecordCount.ToString(CultureInfo.InvariantCulture));
+ xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
- private QueryResult<BaseItem> GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit)
+ /// <summary>
+ /// Returns the child items meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="search">The <see cref="SearchCriteria"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{BaseItem}"/>.</returns>
+ private static QueryResult<BaseItem> GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit)
{
var folder = (Folder)item;
- var sortOrders = new List<string>();
- if (!folder.IsPreSorted)
- {
- sortOrders.Add(ItemSortBy.SortName);
- }
+ var sortOrders = folder.IsPreSorted
+ ? Array.Empty<(string, SortOrder)>()
+ : new[] { (ItemSortBy.SortName, sort.SortOrder) };
- var mediaTypes = new List<string>();
+ string[] mediaTypes = Array.Empty<string>();
bool? isFolder = null;
if (search.SearchType == SearchType.Audio)
{
- mediaTypes.Add(MediaType.Audio);
+ mediaTypes = new[] { MediaType.Audio };
isFolder = false;
}
else if (search.SearchType == SearchType.Video)
{
- mediaTypes.Add(MediaType.Video);
+ mediaTypes = new[] { MediaType.Video };
isFolder = false;
}
else if (search.SearchType == SearchType.Image)
{
- mediaTypes.Add(MediaType.Photo);
+ mediaTypes = new[] { MediaType.Photo };
isFolder = false;
}
else if (search.SearchType == SearchType.Playlist)
{
- //items = items.OfType<Playlist>();
+ // items = items.OfType<Playlist>();
isFolder = true;
}
else if (search.SearchType == SearchType.MusicAlbum)
{
- //items = items.OfType<MusicAlbum>();
+ // items = items.OfType<MusicAlbum>();
isFolder = true;
}
@@ -450,22 +555,36 @@ namespace Emby.Dlna.ContentDirectory
{
Limit = limit,
StartIndex = startIndex,
- OrderBy = sortOrders.Select(i => new ValueTuple<string, SortOrder>(i, sort.SortOrder)).ToArray(),
+ OrderBy = sortOrders,
User = user,
Recursive = true,
IsMissing = false,
- ExcludeItemTypes = new[] { typeof(Book).Name },
+ ExcludeItemTypes = new[] { nameof(Book) },
IsFolder = isFolder,
- MediaTypes = mediaTypes.ToArray(),
+ MediaTypes = mediaTypes,
DtoOptions = GetDtoOptions()
});
}
- private DtoOptions GetDtoOptions()
+ /// <summary>
+ /// Returns a new DtoOptions object.
+ /// </summary>
+ /// <returns>The <see cref="DtoOptions"/>.</returns>
+ private static DtoOptions GetDtoOptions()
{
return new DtoOptions(true);
}
+ /// <summary>
+ /// Returns the User items meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="stubType">The <see cref="StubType"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit)
{
if (item is MusicGenre)
@@ -500,11 +619,11 @@ namespace Emby.Dlna.ContentDirectory
}
else if (string.Equals(CollectionType.Folders, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase))
{
- return GetFolders(item, user, stubType, sort, startIndex, limit);
+ return GetFolders(user, startIndex, limit);
}
else if (string.Equals(CollectionType.LiveTv, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase))
{
- return GetLiveTvChannels(item, user, stubType, sort, startIndex, limit);
+ return GetLiveTvChannels(user, sort, startIndex, limit);
}
}
@@ -523,7 +642,7 @@ namespace Emby.Dlna.ContentDirectory
Limit = limit,
StartIndex = startIndex,
IsVirtualItem = false,
- ExcludeItemTypes = new[] { typeof(Book).Name },
+ ExcludeItemTypes = new[] { nameof(Book) },
IsPlaceHolder = false,
DtoOptions = GetDtoOptions()
};
@@ -535,14 +654,22 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(queryResult);
}
- private QueryResult<ServerItem> GetLiveTvChannels(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
+ /// <summary>
+ /// Returns the Live Tv Channels meeting the criteria.
+ /// </summary>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private QueryResult<ServerItem> GetLiveTvChannels(User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
StartIndex = startIndex,
Limit = limit,
};
- query.IncludeItemTypes = new[] { typeof(LiveTvChannel).Name };
+ query.IncludeItemTypes = new[] { nameof(LiveTvChannel) };
SetSorting(query, sort, false);
@@ -551,6 +678,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the music folders meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="stubType">The <see cref="StubType"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -567,7 +704,7 @@ namespace Emby.Dlna.ContentDirectory
if (stubType.HasValue && stubType.Value == StubType.Playlists)
{
- return GetMusicPlaylists(item, user, query);
+ return GetMusicPlaylists(user, query);
}
if (stubType.HasValue && stubType.Value == StubType.Albums)
@@ -610,65 +747,76 @@ namespace Emby.Dlna.ContentDirectory
return GetMusicGenres(item, user, query);
}
- var list = new List<ServerItem>();
-
- list.Add(new ServerItem(item)
+ var list = new List<ServerItem>
{
- StubType = StubType.Latest
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Latest
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Playlists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Playlists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Albums
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Albums
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.AlbumArtists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.AlbumArtists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Artists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Artists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Songs
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Songs
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Genres
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Genres
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteArtists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteArtists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteAlbums
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteAlbums
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteSongs
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteSongs
+ }
+ };
return new QueryResult<ServerItem>
{
- Items = list.ToArray(),
+ Items = list,
TotalRecordCount = list.Count
};
}
+ /// <summary>
+ /// Returns the movie folders meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="stubType">The <see cref="StubType"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMovieFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -695,7 +843,7 @@ namespace Emby.Dlna.ContentDirectory
if (stubType.HasValue && stubType.Value == StubType.Collections)
{
- return GetMovieCollections(item, user, query);
+ return GetMovieCollections(user, query);
}
if (stubType.HasValue && stubType.Value == StubType.Favorites)
@@ -708,46 +856,49 @@ namespace Emby.Dlna.ContentDirectory
return GetGenres(item, user, query);
}
- var list = new List<ServerItem>();
-
- list.Add(new ServerItem(item)
- {
- StubType = StubType.ContinueWatching
- });
-
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Latest
- });
-
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Movies
- });
-
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Collections
- });
-
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Favorites
- });
-
- list.Add(new ServerItem(item)
+ var array = new[]
{
- StubType = StubType.Genres
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.ContinueWatching
+ },
+ new ServerItem(item)
+ {
+ StubType = StubType.Latest
+ },
+ new ServerItem(item)
+ {
+ StubType = StubType.Movies
+ },
+ new ServerItem(item)
+ {
+ StubType = StubType.Collections
+ },
+ new ServerItem(item)
+ {
+ StubType = StubType.Favorites
+ },
+ new ServerItem(item)
+ {
+ StubType = StubType.Genres
+ }
+ };
return new QueryResult<ServerItem>
{
- Items = list.ToArray(),
- TotalRecordCount = list.Count
+ Items = array,
+ TotalRecordCount = array.Length
};
}
- private QueryResult<ServerItem> GetFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
+ /// <summary>
+ /// Returns the folders meeting the criteria.
+ /// </summary>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private QueryResult<ServerItem> GetFolders(User user, int? startIndex, int? limit)
{
var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true)
.OrderBy(i => i.SortName)
@@ -757,13 +908,26 @@ namespace Emby.Dlna.ContentDirectory
})
.ToArray();
- return new QueryResult<ServerItem>
- {
- Items = folders,
- TotalRecordCount = folders.Length
- };
+ return ApplyPaging(
+ new QueryResult<ServerItem>
+ {
+ Items = folders,
+ TotalRecordCount = folders.Length
+ },
+ startIndex,
+ limit);
}
+ /// <summary>
+ /// Returns the TV folders meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="stubType">The <see cref="StubType"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -780,7 +944,7 @@ namespace Emby.Dlna.ContentDirectory
if (stubType.HasValue && stubType.Value == StubType.NextUp)
{
- return GetNextUp(item, user, query);
+ return GetNextUp(item, query);
}
if (stubType.HasValue && stubType.Value == StubType.Latest)
@@ -808,60 +972,68 @@ namespace Emby.Dlna.ContentDirectory
return GetGenres(item, user, query);
}
- var list = new List<ServerItem>();
-
- list.Add(new ServerItem(item)
+ var list = new List<ServerItem>
{
- StubType = StubType.ContinueWatching
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.ContinueWatching
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.NextUp
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.NextUp
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Latest
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Latest
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Series
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Series
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteSeries
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteSeries
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteEpisodes
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteEpisodes
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Genres
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Genres
+ }
+ };
return new QueryResult<ServerItem>
{
- Items = list.ToArray(),
+ Items = list,
TotalRecordCount = list.Count
};
}
+ /// <summary>
+ /// Returns the Movies that are part watched that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMovieContinueWatching(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.OrderBy = new ValueTuple<string, SortOrder>[]
+ query.OrderBy = new[]
{
- new ValueTuple<string, SortOrder> (ItemSortBy.DatePlayed, SortOrder.Descending),
- new ValueTuple<string, SortOrder> (ItemSortBy.SortName, SortOrder.Ascending)
+ (ItemSortBy.DatePlayed, SortOrder.Descending),
+ (ItemSortBy.SortName, SortOrder.Ascending)
};
query.IsResumable = true;
@@ -872,136 +1044,213 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the series meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetSeries(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the Movie folders meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMovieMovies(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
- private QueryResult<ServerItem> GetMovieCollections(BaseItem parent, User user, InternalItemsQuery query)
+ /// <summary>
+ /// Returns the Movie collections meeting the criteria.
+ /// </summary>
+ /// <param name="user">The see cref="User"/>.</param>
+ /// <param name="query">The see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private QueryResult<ServerItem> GetMovieCollections(User user, InternalItemsQuery query)
{
query.Recursive = true;
- //query.Parent = parent;
+ // query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(BoxSet).Name };
+ query.IncludeItemTypes = new[] { nameof(BoxSet) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the Music albums meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicAlbums(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicAlbum) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the Music songs meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicSongs(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Audio).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the songs tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetFavoriteSongs(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Audio).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the series tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetFavoriteSeries(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the episodes tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetFavoriteEpisodes(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the movies tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMovieFavorites(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// /// Returns the albums tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetFavoriteAlbums(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicAlbum) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the genres meeting the criteria.
+ /// The GetGenres.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetGenres(BaseItem parent, User user, InternalItemsQuery query)
{
var genresResult = _libraryManager.GetGenres(new InternalItemsQuery(user)
@@ -1020,6 +1269,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the music genres meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicGenres(BaseItem parent, User user, InternalItemsQuery query)
{
var genresResult = _libraryManager.GetMusicGenres(new InternalItemsQuery(user)
@@ -1038,6 +1294,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the music albums by artist that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicAlbumArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetAlbumArtists(new InternalItemsQuery(user)
@@ -1056,6 +1319,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the music artists meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetArtists(new InternalItemsQuery(user)
@@ -1074,6 +1344,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the artists tagged as favourite that meet the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetFavoriteArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetArtists(new InternalItemsQuery(user)
@@ -1093,10 +1370,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
- private QueryResult<ServerItem> GetMusicPlaylists(BaseItem parent, User user, InternalItemsQuery query)
+ /// <summary>
+ /// Returns the music playlists meeting the criteria.
+ /// </summary>
+ /// <param name="user">The user<see cref="User"/>.</param>
+ /// <param name="query">The query<see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private QueryResult<ServerItem> GetMusicPlaylists(User user, InternalItemsQuery query)
{
query.Parent = null;
- query.IncludeItemTypes = new[] { typeof(Playlist).Name };
+ query.IncludeItemTypes = new[] { nameof(Playlist) };
query.SetUser(user);
query.Recursive = true;
@@ -1105,72 +1388,114 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the latest music meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicLatest(BaseItem parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new ValueTuple<string, SortOrder>[] { };
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
- var items = _userViewManager.GetLatestItems(new LatestItemsQuery
- {
- UserId = user.Id,
- Limit = 50,
- IncludeItemTypes = new[] { typeof(Audio).Name },
- ParentId = parent == null ? Guid.Empty : parent.Id,
- GroupItems = true
-
- }, query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
+ var items = _userViewManager.GetLatestItems(
+ new LatestItemsQuery
+ {
+ UserId = user.Id,
+ Limit = 50,
+ IncludeItemTypes = new[] { nameof(Audio) },
+ ParentId = parent?.Id ?? Guid.Empty,
+ GroupItems = true
+ },
+ query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
return ToResult(items);
}
- private QueryResult<ServerItem> GetNextUp(BaseItem parent, User user, InternalItemsQuery query)
+ /// <summary>
+ /// Returns the next up item meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private QueryResult<ServerItem> GetNextUp(BaseItem parent, InternalItemsQuery query)
{
- query.OrderBy = new ValueTuple<string, SortOrder>[] { };
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
- var result = _tvSeriesManager.GetNextUp(new NextUpQuery
- {
- Limit = query.Limit,
- StartIndex = query.StartIndex,
- UserId = query.User.Id
-
- }, new[] { parent }, query.DtoOptions);
+ var result = _tvSeriesManager.GetNextUp(
+ new NextUpQuery
+ {
+ Limit = query.Limit,
+ StartIndex = query.StartIndex,
+ UserId = query.User.Id
+ },
+ new[] { parent },
+ query.DtoOptions);
return ToResult(result);
}
+ /// <summary>
+ /// Returns the latest tv meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetTvLatest(BaseItem parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new ValueTuple<string, SortOrder>[] { };
-
- var items = _userViewManager.GetLatestItems(new LatestItemsQuery
- {
- UserId = user.Id,
- Limit = 50,
- IncludeItemTypes = new[] { typeof(Episode).Name },
- ParentId = parent == null ? Guid.Empty : parent.Id,
- GroupItems = false
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
- }, query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
+ var items = _userViewManager.GetLatestItems(
+ new LatestItemsQuery
+ {
+ UserId = user.Id,
+ Limit = 50,
+ IncludeItemTypes = new[] { nameof(Episode) },
+ ParentId = parent == null ? Guid.Empty : parent.Id,
+ GroupItems = false
+ },
+ query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
return ToResult(items);
}
+ /// <summary>
+ /// Returns the latest movies meeting the criteria.
+ /// </summary>
+ /// <param name="parent">The <see cref="BaseItem"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMovieLatest(BaseItem parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new ValueTuple<string, SortOrder>[] { };
-
- var items = _userViewManager.GetLatestItems(new LatestItemsQuery
- {
- UserId = user.Id,
- Limit = 50,
- IncludeItemTypes = new[] { typeof(Movie).Name },
- ParentId = parent == null ? Guid.Empty : parent.Id,
- GroupItems = true
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
- }, query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
+ var items = _userViewManager.GetLatestItems(
+ new LatestItemsQuery
+ {
+ UserId = user.Id,
+ Limit = 50,
+ IncludeItemTypes = new[] { nameof(Movie) },
+ ParentId = parent?.Id ?? Guid.Empty,
+ GroupItems = true
+ },
+ query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
return ToResult(items);
}
+ /// <summary>
+ /// Returns music artist items that meet the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="parentId">The <see cref="Guid"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicArtistItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1178,7 +1503,7 @@ namespace Emby.Dlna.ContentDirectory
Recursive = true,
ParentId = parentId,
ArtistIds = new[] { item.Id },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions()
@@ -1191,6 +1516,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the genre items meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="parentId">The <see cref="Guid"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1198,7 +1533,11 @@ namespace Emby.Dlna.ContentDirectory
Recursive = true,
ParentId = parentId,
GenreIds = new[] { item.Id },
- IncludeItemTypes = new[] { typeof(Movie).Name, typeof(Series).Name },
+ IncludeItemTypes = new[]
+ {
+ nameof(Movie),
+ nameof(Series)
+ },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions()
@@ -1211,6 +1550,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ /// <summary>
+ /// Returns the music genre items meeting the criteria.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="parentId">The <see cref="Guid"/>.</param>
+ /// <param name="user">The <see cref="User"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
private QueryResult<ServerItem> GetMusicGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1218,7 +1567,7 @@ namespace Emby.Dlna.ContentDirectory
Recursive = true,
ParentId = parentId,
GenreIds = new[] { item.Id },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions()
@@ -1231,7 +1580,12 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
- private QueryResult<ServerItem> ToResult(BaseItem[] result)
+ /// <summary>
+ /// Converts a <see cref="BaseItem"/> array into a <see cref="QueryResult{ServerItem}"/>.
+ /// </summary>
+ /// <param name="result">An array of <see cref="BaseItem"/>.</param>
+ /// <returns>A <see cref="QueryResult{ServerItem}"/>.</returns>
+ private static QueryResult<ServerItem> ToResult(BaseItem[] result)
{
var serverItems = result
.Select(i => new ServerItem(i))
@@ -1244,7 +1598,12 @@ namespace Emby.Dlna.ContentDirectory
};
}
- private QueryResult<ServerItem> ToResult(QueryResult<BaseItem> result)
+ /// <summary>
+ /// Converts a <see cref="QueryResult{BaseItem}"/> to a <see cref="QueryResult{ServerItem}"/>.
+ /// </summary>
+ /// <param name="result">A <see cref="QueryResult{BaseItem}"/>.</param>
+ /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns>
+ private static QueryResult<ServerItem> ToResult(QueryResult<BaseItem> result)
{
var serverItems = result
.Items
@@ -1258,42 +1617,65 @@ namespace Emby.Dlna.ContentDirectory
};
}
- private void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted)
+ /// <summary>
+ /// Sets the sorting method on a query.
+ /// </summary>
+ /// <param name="query">The <see cref="InternalItemsQuery"/>.</param>
+ /// <param name="sort">The <see cref="SortCriteria"/>.</param>
+ /// <param name="isPreSorted">True if pre-sorted.</param>
+ private static void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted)
{
- var sortOrders = new List<string>();
- if (!isPreSorted)
+ if (isPreSorted)
{
- sortOrders.Add(ItemSortBy.SortName);
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
+ }
+ else
+ {
+ query.OrderBy = new[] { (ItemSortBy.SortName, sort.SortOrder) };
}
-
- query.OrderBy = sortOrders.Select(i => new ValueTuple<string, SortOrder>(i, sort.SortOrder)).ToArray();
}
- private QueryResult<ServerItem> ApplyPaging(QueryResult<ServerItem> result, int? startIndex, int? limit)
+ /// <summary>
+ /// Apply paging to a query.
+ /// </summary>
+ /// <param name="result">The <see cref="QueryResult{ServerItem}"/>.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The maximum number to return.</param>
+ /// <returns>A <see cref="QueryResult{ServerItem}"/>.</returns>
+ private static QueryResult<ServerItem> ApplyPaging(QueryResult<ServerItem> result, int? startIndex, int? limit)
{
result.Items = result.Items.Skip(startIndex ?? 0).Take(limit ?? int.MaxValue).ToArray();
return result;
}
- private ServerItem GetItemFromObjectId(string id, User user)
+ /// <summary>
+ /// Retrieves the ServerItem id.
+ /// </summary>
+ /// <param name="id">The id<see cref="string"/>.</param>
+ /// <returns>The <see cref="ServerItem"/>.</returns>
+ private ServerItem GetItemFromObjectId(string id)
{
return DidlBuilder.IsIdRoot(id)
-
? new ServerItem(_libraryManager.GetUserRootFolder())
- : ParseItemId(id, user);
+ : ParseItemId(id);
}
- private ServerItem ParseItemId(string id, User user)
+ /// <summary>
+ /// Parses the item id into a <see cref="ServerItem"/>.
+ /// </summary>
+ /// <param name="id">The <see cref="string"/>.</param>
+ /// <returns>The corresponding <see cref="ServerItem"/>.</returns>
+ private ServerItem ParseItemId(string id)
{
StubType? stubType = null;
// After using PlayTo, MediaMonkey sends a request to the server trying to get item info
- const string paramsSrch = "Params=";
- var paramsIndex = id.IndexOf(paramsSrch, StringComparison.OrdinalIgnoreCase);
+ const string ParamsSrch = "Params=";
+ var paramsIndex = id.IndexOf(ParamsSrch, StringComparison.OrdinalIgnoreCase);
if (paramsIndex != -1)
{
- id = id.Substring(paramsIndex + paramsSrch.Length);
+ id = id.Substring(paramsIndex + ParamsSrch.Length);
var parts = id.Split(';');
id = parts[23];
@@ -1304,8 +1686,8 @@ namespace Emby.Dlna.ContentDirectory
{
if (id.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))
{
- stubType = (StubType)Enum.Parse(typeof(StubType), name, true);
- id = id.Split(new[] { '_' }, 2)[1];
+ stubType = Enum.Parse<StubType>(name, true);
+ id = id.Split('_', 2)[1];
break;
}
@@ -1321,48 +1703,9 @@ namespace Emby.Dlna.ContentDirectory
};
}
- _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id);
+ Logger.LogError("Error parsing item Id: {Id}. Returning user root folder.", id);
return new ServerItem(_libraryManager.GetUserRootFolder());
}
}
-
- internal class ServerItem
- {
- public BaseItem Item { get; set; }
- public StubType? StubType { get; set; }
-
- public ServerItem(BaseItem item)
- {
- Item = item;
-
- if (item is IItemByName && !(item is Folder))
- {
- StubType = Dlna.ContentDirectory.StubType.Folder;
- }
- }
- }
-
- public enum StubType
- {
- Folder = 0,
- Latest = 2,
- Playlists = 3,
- Albums = 4,
- AlbumArtists = 5,
- Artists = 6,
- Songs = 7,
- Genres = 8,
- FavoriteSongs = 9,
- FavoriteArtists = 10,
- FavoriteAlbums = 11,
- ContinueWatching = 12,
- Movies = 13,
- Collections = 14,
- Favorites = 15,
- NextUp = 16,
- Series = 17,
- FavoriteSeries = 18,
- FavoriteEpisodes = 19
- }
}
diff --git a/Emby.Dlna/ContentDirectory/ServerItem.cs b/Emby.Dlna/ContentDirectory/ServerItem.cs
new file mode 100644
index 000000000..ff30e6e4a
--- /dev/null
+++ b/Emby.Dlna/ContentDirectory/ServerItem.cs
@@ -0,0 +1,36 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities;
+
+namespace Emby.Dlna.ContentDirectory
+{
+ /// <summary>
+ /// Defines the <see cref="ServerItem" />.
+ /// </summary>
+ internal class ServerItem
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ServerItem"/> class.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ public ServerItem(BaseItem item)
+ {
+ Item = item;
+
+ if (item is IItemByName && item is not Folder)
+ {
+ StubType = Dlna.ContentDirectory.StubType.Folder;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the underlying base item.
+ /// </summary>
+ public BaseItem Item { get; set; }
+
+ /// <summary>
+ /// Gets or sets the DLNA item type.
+ /// </summary>
+ public StubType? StubType { get; set; }
+ }
+}
diff --git a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
index e999314fa..7e3db4651 100644
--- a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
+++ b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
@@ -3,9 +3,16 @@ using Emby.Dlna.Common;
namespace Emby.Dlna.ContentDirectory
{
- public class ServiceActionListBuilder
+ /// <summary>
+ /// Defines the <see cref="ServiceActionListBuilder" />.
+ /// </summary>
+ public static class ServiceActionListBuilder
{
- public IEnumerable<ServiceAction> GetActions()
+ /// <summary>
+ /// Returns a list of services that this instance provides.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{ServiceAction}"/>.</returns>
+ public static IEnumerable<ServiceAction> GetActions()
{
return new[]
{
@@ -20,6 +27,10 @@ namespace Emby.Dlna.ContentDirectory
};
}
+ /// <summary>
+ /// Returns the action details for "GetSystemUpdateID".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetGetSystemUpdateIDAction()
{
var action = new ServiceAction
@@ -37,6 +48,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ /// <summary>
+ /// Returns the action details for "GetSearchCapabilities".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetSearchCapabilitiesAction()
{
var action = new ServiceAction
@@ -54,6 +69,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ /// <summary>
+ /// Returns the action details for "GetSortCapabilities".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetSortCapabilitiesAction()
{
var action = new ServiceAction
@@ -71,6 +90,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ /// <summary>
+ /// Returns the action details for "X_GetFeatureList".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetX_GetFeatureListAction()
{
var action = new ServiceAction
@@ -88,6 +111,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ /// <summary>
+ /// Returns the action details for "Search".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetSearchAction()
{
var action = new ServiceAction
@@ -168,7 +195,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetBrowseAction()
+ /// <summary>
+ /// Returns the action details for "Browse".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetBrowseAction()
{
var action = new ServiceAction
{
@@ -248,7 +279,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetBrowseByLetterAction()
+ /// <summary>
+ /// Returns the action details for "X_BrowseByLetter".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetBrowseByLetterAction()
{
var action = new ServiceAction
{
@@ -335,7 +370,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetXSetBookmarkAction()
+ /// <summary>
+ /// Returns the action details for "X_SetBookmark".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetXSetBookmarkAction()
{
var action = new ServiceAction
{
diff --git a/Emby.Dlna/ContentDirectory/StubType.cs b/Emby.Dlna/ContentDirectory/StubType.cs
new file mode 100644
index 000000000..187dc1d75
--- /dev/null
+++ b/Emby.Dlna/ContentDirectory/StubType.cs
@@ -0,0 +1,30 @@
+#pragma warning disable CS1591
+
+namespace Emby.Dlna.ContentDirectory
+{
+ /// <summary>
+ /// Defines the DLNA item types.
+ /// </summary>
+ public enum StubType
+ {
+ Folder = 0,
+ Latest = 2,
+ Playlists = 3,
+ Albums = 4,
+ AlbumArtists = 5,
+ Artists = 6,
+ Songs = 7,
+ Genres = 8,
+ FavoriteSongs = 9,
+ FavoriteArtists = 10,
+ FavoriteAlbums = 11,
+ ContinueWatching = 12,
+ Movies = 13,
+ Collections = 14,
+ Favorites = 15,
+ NextUp = 16,
+ Series = 17,
+ FavoriteSeries = 18,
+ FavoriteEpisodes = 19
+ }
+}
diff --git a/Emby.Dlna/ControlRequest.cs b/Emby.Dlna/ControlRequest.cs
index afd9a0b87..8ee6325e9 100644
--- a/Emby.Dlna/ControlRequest.cs
+++ b/Emby.Dlna/ControlRequest.cs
@@ -1,21 +1,25 @@
-using System.Collections.Generic;
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.IO;
+using Microsoft.AspNetCore.Http;
namespace Emby.Dlna
{
public class ControlRequest
{
- public IDictionary<string, string> Headers { get; set; }
+ public ControlRequest(IHeaderDictionary headers)
+ {
+ Headers = headers;
+ }
+
+ public IHeaderDictionary Headers { get; }
public Stream InputXml { get; set; }
public string TargetServerUuId { get; set; }
public string RequestedUrl { get; set; }
-
- public ControlRequest()
- {
- Headers = new Dictionary<string, string>();
- }
}
}
diff --git a/Emby.Dlna/ControlResponse.cs b/Emby.Dlna/ControlResponse.cs
index d2b79fc58..8b0958842 100644
--- a/Emby.Dlna/ControlResponse.cs
+++ b/Emby.Dlna/ControlResponse.cs
@@ -1,18 +1,28 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
namespace Emby.Dlna
{
public class ControlResponse
{
- public IDictionary<string, string> Headers { get; set; }
+ public ControlResponse(string xml, bool isSuccessful)
+ {
+ Headers = new Dictionary<string, string>();
+ Xml = xml;
+ IsSuccessful = isSuccessful;
+ }
+
+ public IDictionary<string, string> Headers { get; }
public string Xml { get; set; }
public bool IsSuccessful { get; set; }
- public ControlResponse()
+ /// <inheritdoc />
+ public override string ToString()
{
- Headers = new Dictionary<string, string>();
+ return Xml;
}
}
}
diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs
index 605f4f37b..0a84f30c4 100644
--- a/Emby.Dlna/Didl/DidlBuilder.cs
+++ b/Emby.Dlna/Didl/DidlBuilder.cs
@@ -1,38 +1,45 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
-using Emby.Dlna.Configuration;
using Emby.Dlna.ContentDirectory;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
+using XmlAttribute = MediaBrowser.Model.Dlna.XmlAttribute;
namespace Emby.Dlna.Didl
{
public class DidlBuilder
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- private const string NS_DIDL = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
- private const string NS_DC = "http://purl.org/dc/elements/1.1/";
- private const string NS_UPNP = "urn:schemas-upnp-org:metadata-1-0/upnp/";
- private const string NS_DLNA = "urn:schemas-dlna-org:metadata-1-0/";
+ private const string NsDidl = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
+ private const string NsDc = "http://purl.org/dc/elements/1.1/";
+ private const string NsUpnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
+ private const string NsDlna = "urn:schemas-dlna-org:metadata-1-0/";
private readonly DeviceProfile _profile;
private readonly IImageProcessor _imageProcessor;
@@ -44,6 +51,7 @@ namespace Emby.Dlna.Didl
private readonly IMediaSourceManager _mediaSourceManager;
private readonly ILogger _logger;
private readonly IMediaEncoder _mediaEncoder;
+ private readonly ILibraryManager _libraryManager;
public DidlBuilder(
DeviceProfile profile,
@@ -55,7 +63,8 @@ namespace Emby.Dlna.Didl
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
ILogger logger,
- IMediaEncoder mediaEncoder)
+ IMediaEncoder mediaEncoder,
+ ILibraryManager libraryManager)
{
_profile = profile;
_user = user;
@@ -67,6 +76,7 @@ namespace Emby.Dlna.Didl
_mediaSourceManager = mediaSourceManager;
_logger = logger;
_mediaEncoder = mediaEncoder;
+ _libraryManager = libraryManager;
}
public static string NormalizeDlnaMediaUrl(string url)
@@ -74,7 +84,7 @@ namespace Emby.Dlna.Didl
return url + "&dlnaheaders=true";
}
- public string GetItemDidl(DlnaOptions options, BaseItem item, User user, BaseItem context, string deviceId, Filter filter, StreamInfo streamInfo)
+ public string GetItemDidl(BaseItem item, User user, BaseItem context, string deviceId, Filter filter, StreamInfo streamInfo)
{
var settings = new XmlWriterSettings
{
@@ -86,23 +96,24 @@ namespace Emby.Dlna.Didl
using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
{
+ // If this using are changed to single lines, then write.Flush needs to be appended before the return.
using (var writer = XmlWriter.Create(builder, settings))
{
- //writer.WriteStartDocument();
+ // writer.WriteStartDocument();
- writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
- writer.WriteAttributeString("xmlns", "dc", null, NS_DC);
- writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA);
- writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP);
- //didl.SetAttribute("xmlns:sec", NS_SEC);
+ writer.WriteAttributeString("xmlns", "dc", null, NsDc);
+ writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
+ writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
+ // didl.SetAttribute("xmlns:sec", NS_SEC);
WriteXmlRootAttributes(_profile, writer);
- WriteItemElement(options, writer, item, user, context, null, deviceId, filter, streamInfo);
+ WriteItemElement(writer, item, user, context, null, deviceId, filter, streamInfo);
writer.WriteFullEndElement();
- //writer.WriteEndDocument();
+ // writer.WriteEndDocument();
}
return builder.ToString();
@@ -113,7 +124,7 @@ namespace Emby.Dlna.Didl
{
foreach (var att in profile.XmlRootAttributes)
{
- var parts = att.Name.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = att.Name.Split(':', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
writer.WriteAttributeString(parts[0], parts[1], null, att.Value);
@@ -126,7 +137,6 @@ namespace Emby.Dlna.Didl
}
public void WriteItemElement(
- DlnaOptions options,
XmlWriter writer,
BaseItem item,
User user,
@@ -138,7 +148,7 @@ namespace Emby.Dlna.Didl
{
var clientId = GetClientId(item, null);
- writer.WriteStartElement(string.Empty, "item", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "item", NsDidl);
writer.WriteAttributeString("restricted", "1");
writer.WriteAttributeString("id", clientId);
@@ -158,43 +168,28 @@ namespace Emby.Dlna.Didl
AddGeneralProperties(item, null, context, writer, filter);
- AddSamsungBookmarkInfo(item, user, writer);
+ AddSamsungBookmarkInfo(item, user, writer, streamInfo);
// refID?
// storeAttribute(itemNode, object, ClassProperties.REF_ID, false);
- var hasMediaSources = item as IHasMediaSources;
-
- if (hasMediaSources != null)
+ if (item is IHasMediaSources)
{
if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
{
- AddAudioResource(options, writer, item, deviceId, filter, streamInfo);
+ AddAudioResource(writer, item, deviceId, filter, streamInfo);
}
else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
{
- AddVideoResource(options, writer, item, deviceId, filter, streamInfo);
+ AddVideoResource(writer, item, deviceId, filter, streamInfo);
}
}
- AddCover(item, context, null, writer);
+ AddCover(item, null, writer);
writer.WriteFullEndElement();
}
- private string GetMimeType(string input)
- {
- var mime = MimeTypes.GetMimeType(input);
-
- // TODO: Instead of being hard-coded here, this should probably be moved into all of the existing profiles
- if (string.Equals(mime, "video/mp2t", StringComparison.OrdinalIgnoreCase))
- {
- mime = "video/mpeg";
- }
-
- return mime;
- }
-
- private void AddVideoResource(DlnaOptions options, XmlWriter writer, BaseItem video, string deviceId, Filter filter, StreamInfo streamInfo = null)
+ private void AddVideoResource(XmlWriter writer, BaseItem video, string deviceId, Filter filter, StreamInfo streamInfo = null)
{
if (streamInfo == null)
{
@@ -213,7 +208,9 @@ namespace Emby.Dlna.Didl
var targetWidth = streamInfo.TargetWidth;
var targetHeight = streamInfo.TargetHeight;
- var contentFeatureList = new ContentFeatureBuilder(_profile).BuildVideoHeader(streamInfo.Container,
+ var contentFeatureList = ContentFeatureBuilder.BuildVideoHeader(
+ _profile,
+ streamInfo.Container,
streamInfo.TargetVideoCodec.FirstOrDefault(),
streamInfo.TargetAudioCodec.FirstOrDefault(),
targetWidth,
@@ -238,7 +235,7 @@ namespace Emby.Dlna.Didl
foreach (var contentFeature in contentFeatureList)
{
- AddVideoResource(writer, video, deviceId, filter, contentFeature, streamInfo);
+ AddVideoResource(writer, filter, contentFeature, streamInfo);
}
var subtitleProfiles = streamInfo.GetSubtitleProfiles(_mediaEncoder, false, _serverAddress, _accessToken);
@@ -285,7 +282,7 @@ namespace Emby.Dlna.Didl
}
else if (string.Equals(subtitleMode, "smi", StringComparison.OrdinalIgnoreCase))
{
- writer.WriteStartElement(string.Empty, "res", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "res", NsDidl);
writer.WriteAttributeString("protocolInfo", "http-get:*:smi/caption:*");
@@ -294,8 +291,11 @@ namespace Emby.Dlna.Didl
}
else
{
- writer.WriteStartElement(string.Empty, "res", NS_DIDL);
- var protocolInfo = string.Format("http-get:*:text/{0}:*", info.Format.ToLowerInvariant());
+ writer.WriteStartElement(string.Empty, "res", NsDidl);
+ var protocolInfo = string.Format(
+ CultureInfo.InvariantCulture,
+ "http-get:*:text/{0}:*",
+ info.Format.ToLowerInvariant());
writer.WriteAttributeString("protocolInfo", protocolInfo);
writer.WriteString(info.Url);
@@ -305,9 +305,9 @@ namespace Emby.Dlna.Didl
return true;
}
- private void AddVideoResource(XmlWriter writer, BaseItem video, string deviceId, Filter filter, string contentFeatures, StreamInfo streamInfo)
+ private void AddVideoResource(XmlWriter writer, Filter filter, string contentFeatures, StreamInfo streamInfo)
{
- writer.WriteStartElement(string.Empty, "res", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "res", NsDidl);
var url = NormalizeDlnaMediaUrl(streamInfo.ToUrl(_serverAddress, _accessToken));
@@ -315,7 +315,7 @@ namespace Emby.Dlna.Didl
if (mediaSource.RunTimeTicks.HasValue)
{
- writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
+ writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", CultureInfo.InvariantCulture));
}
if (filter.Contains("res@size"))
@@ -326,7 +326,7 @@ namespace Emby.Dlna.Didl
if (size.HasValue)
{
- writer.WriteAttributeString("size", size.Value.ToString(_usCulture));
+ writer.WriteAttributeString("size", size.Value.ToString(CultureInfo.InvariantCulture));
}
}
}
@@ -340,28 +340,35 @@ namespace Emby.Dlna.Didl
if (targetChannels.HasValue)
{
- writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
+ writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(CultureInfo.InvariantCulture));
}
if (filter.Contains("res@resolution"))
{
if (targetWidth.HasValue && targetHeight.HasValue)
{
- writer.WriteAttributeString("resolution", string.Format("{0}x{1}", targetWidth.Value, targetHeight.Value));
+ writer.WriteAttributeString(
+ "resolution",
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}x{1}",
+ targetWidth.Value,
+ targetHeight.Value));
}
}
if (targetSampleRate.HasValue)
{
- writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
+ writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(CultureInfo.InvariantCulture));
}
if (totalBitrate.HasValue)
{
- writer.WriteAttributeString("bitrate", totalBitrate.Value.ToString(_usCulture));
+ writer.WriteAttributeString("bitrate", totalBitrate.Value.ToString(CultureInfo.InvariantCulture));
}
- var mediaProfile = _profile.GetVideoMediaProfile(streamInfo.Container,
+ var mediaProfile = _profile.GetVideoMediaProfile(
+ streamInfo.Container,
streamInfo.TargetAudioCodec.FirstOrDefault(),
streamInfo.TargetVideoCodec.FirstOrDefault(),
streamInfo.TargetAudioBitrate,
@@ -381,17 +388,19 @@ namespace Emby.Dlna.Didl
streamInfo.TargetVideoCodecTag,
streamInfo.IsTargetAVC);
- var filename = url.Substring(0, url.IndexOf('?'));
+ var filename = url.Substring(0, url.IndexOf('?', StringComparison.Ordinal));
var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
- ? GetMimeType(filename)
+ ? MimeTypes.GetMimeType(filename)
: mediaProfile.MimeType;
- writer.WriteAttributeString("protocolInfo", string.Format(
- "http-get:*:{0}:{1}",
- mimeType,
- contentFeatures
- ));
+ writer.WriteAttributeString(
+ "protocolInfo",
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "http-get:*:{0}:{1}",
+ mimeType,
+ contentFeatures));
writer.WriteString(url);
@@ -404,56 +413,123 @@ namespace Emby.Dlna.Didl
{
switch (itemStubType.Value)
{
- case StubType.Latest: return _localization.GetLocalizedString("Latest");
- case StubType.Playlists: return _localization.GetLocalizedString("Playlists");
- case StubType.AlbumArtists: return _localization.GetLocalizedString("HeaderAlbumArtists");
- case StubType.Albums: return _localization.GetLocalizedString("Albums");
- case StubType.Artists: return _localization.GetLocalizedString("Artists");
- case StubType.Songs: return _localization.GetLocalizedString("Songs");
- case StubType.Genres: return _localization.GetLocalizedString("Genres");
- case StubType.FavoriteAlbums: return _localization.GetLocalizedString("HeaderFavoriteAlbums");
- case StubType.FavoriteArtists: return _localization.GetLocalizedString("HeaderFavoriteArtists");
- case StubType.FavoriteSongs: return _localization.GetLocalizedString("HeaderFavoriteSongs");
+ case StubType.Latest: return _localization.GetLocalizedString("Latest");
+ case StubType.Playlists: return _localization.GetLocalizedString("Playlists");
+ case StubType.AlbumArtists: return _localization.GetLocalizedString("HeaderAlbumArtists");
+ case StubType.Albums: return _localization.GetLocalizedString("Albums");
+ case StubType.Artists: return _localization.GetLocalizedString("Artists");
+ case StubType.Songs: return _localization.GetLocalizedString("Songs");
+ case StubType.Genres: return _localization.GetLocalizedString("Genres");
+ case StubType.FavoriteAlbums: return _localization.GetLocalizedString("HeaderFavoriteAlbums");
+ case StubType.FavoriteArtists: return _localization.GetLocalizedString("HeaderFavoriteArtists");
+ case StubType.FavoriteSongs: return _localization.GetLocalizedString("HeaderFavoriteSongs");
case StubType.ContinueWatching: return _localization.GetLocalizedString("HeaderContinueWatching");
- case StubType.Movies: return _localization.GetLocalizedString("Movies");
- case StubType.Collections: return _localization.GetLocalizedString("Collections");
- case StubType.Favorites: return _localization.GetLocalizedString("Favorites");
- case StubType.NextUp: return _localization.GetLocalizedString("HeaderNextUp");
- case StubType.FavoriteSeries: return _localization.GetLocalizedString("HeaderFavoriteShows");
+ case StubType.Movies: return _localization.GetLocalizedString("Movies");
+ case StubType.Collections: return _localization.GetLocalizedString("Collections");
+ case StubType.Favorites: return _localization.GetLocalizedString("Favorites");
+ case StubType.NextUp: return _localization.GetLocalizedString("HeaderNextUp");
+ case StubType.FavoriteSeries: return _localization.GetLocalizedString("HeaderFavoriteShows");
case StubType.FavoriteEpisodes: return _localization.GetLocalizedString("HeaderFavoriteEpisodes");
- case StubType.Series: return _localization.GetLocalizedString("Shows");
- default: break;
+ case StubType.Series: return _localization.GetLocalizedString("Shows");
}
}
- if (item is Episode episode && context is Season season)
+ return item is Episode episode
+ ? GetEpisodeDisplayName(episode, context)
+ : item.Name;
+ }
+
+ /// <summary>
+ /// Gets episode display name appropriate for the given context.
+ /// </summary>
+ /// <remarks>
+ /// If context is a season, this will return a string containing just episode number and name.
+ /// Otherwise the result will include series nams and season number.
+ /// </remarks>
+ /// <param name="episode">The episode.</param>
+ /// <param name="context">Current context.</param>
+ /// <returns>Formatted name of the episode.</returns>
+ private string GetEpisodeDisplayName(Episode episode, BaseItem context)
+ {
+ string[] components;
+
+ if (context is Season season)
{
// This is a special embedded within a season
- if (item.ParentIndexNumber.HasValue && item.ParentIndexNumber.Value == 0
+ if (episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value == 0
&& season.IndexNumber.HasValue && season.IndexNumber.Value != 0)
{
- return string.Format(_localization.GetLocalizedString("ValueSpecialEpisodeName"), item.Name);
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("ValueSpecialEpisodeName"),
+ episode.Name);
}
- if (item.IndexNumber.HasValue)
- {
- var number = item.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
+ // inside a season use simple format (ex. '12 - Episode Name')
+ var epNumberName = GetEpisodeIndexFullName(episode);
+ components = new[] { epNumberName, episode.Name };
+ }
+ else
+ {
+ // outside a season include series and season details (ex. 'TV Show - S05E11 - Episode Name')
+ var epNumberName = GetEpisodeNumberDisplayName(episode);
+ components = new[] { episode.SeriesName, epNumberName, episode.Name };
+ }
- if (episode.IndexNumberEnd.HasValue)
- {
- number += "-" + episode.IndexNumberEnd.Value.ToString("00", CultureInfo.InvariantCulture);
- }
+ return string.Join(" - ", components.Where(NotNullOrWhiteSpace));
+ }
- return number + " - " + item.Name;
+ /// <summary>
+ /// Gets complete episode number.
+ /// </summary>
+ /// <param name="episode">The episode.</param>
+ /// <returns>For single episodes returns just the number. For double episodes - current and ending numbers.</returns>
+ private string GetEpisodeIndexFullName(Episode episode)
+ {
+ var name = string.Empty;
+ if (episode.IndexNumber.HasValue)
+ {
+ name += episode.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
+
+ if (episode.IndexNumberEnd.HasValue)
+ {
+ name += "-" + episode.IndexNumberEnd.Value.ToString("00", CultureInfo.InvariantCulture);
}
}
- return item.Name;
+ return name;
}
- private void AddAudioResource(DlnaOptions options, XmlWriter writer, BaseItem audio, string deviceId, Filter filter, StreamInfo streamInfo = null)
+ /// <summary>
+ /// Gets episode number formatted as 'S##E##'.
+ /// </summary>
+ /// <param name="episode">The episode.</param>
+ /// <returns>Formatted episode number.</returns>
+ private string GetEpisodeNumberDisplayName(Episode episode)
{
- writer.WriteStartElement(string.Empty, "res", NS_DIDL);
+ var name = string.Empty;
+ var seasonNumber = episode.Season?.IndexNumber;
+
+ if (seasonNumber.HasValue)
+ {
+ name = "S" + seasonNumber.Value.ToString("00", CultureInfo.InvariantCulture);
+ }
+
+ var indexName = GetEpisodeIndexFullName(episode);
+
+ if (!string.IsNullOrWhiteSpace(indexName))
+ {
+ name += "E" + indexName;
+ }
+
+ return name;
+ }
+
+ private bool NotNullOrWhiteSpace(string s) => !string.IsNullOrWhiteSpace(s);
+
+ private void AddAudioResource(XmlWriter writer, BaseItem audio, string deviceId, Filter filter, StreamInfo streamInfo = null)
+ {
+ writer.WriteStartElement(string.Empty, "res", NsDidl);
if (streamInfo == null)
{
@@ -474,7 +550,7 @@ namespace Emby.Dlna.Didl
if (mediaSource.RunTimeTicks.HasValue)
{
- writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
+ writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", CultureInfo.InvariantCulture));
}
if (filter.Contains("res@size"))
@@ -485,7 +561,7 @@ namespace Emby.Dlna.Didl
if (size.HasValue)
{
- writer.WriteAttributeString("size", size.Value.ToString(_usCulture));
+ writer.WriteAttributeString("size", size.Value.ToString(CultureInfo.InvariantCulture));
}
}
}
@@ -497,33 +573,36 @@ namespace Emby.Dlna.Didl
if (targetChannels.HasValue)
{
- writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
+ writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(CultureInfo.InvariantCulture));
}
if (targetSampleRate.HasValue)
{
- writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
+ writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(CultureInfo.InvariantCulture));
}
if (targetAudioBitrate.HasValue)
{
- writer.WriteAttributeString("bitrate", targetAudioBitrate.Value.ToString(_usCulture));
+ writer.WriteAttributeString("bitrate", targetAudioBitrate.Value.ToString(CultureInfo.InvariantCulture));
}
- var mediaProfile = _profile.GetAudioMediaProfile(streamInfo.Container,
+ var mediaProfile = _profile.GetAudioMediaProfile(
+ streamInfo.Container,
streamInfo.TargetAudioCodec.FirstOrDefault(),
targetChannels,
targetAudioBitrate,
targetSampleRate,
targetAudioBitDepth);
- var filename = url.Substring(0, url.IndexOf('?'));
+ var filename = url.Substring(0, url.IndexOf('?', StringComparison.Ordinal));
var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
- ? GetMimeType(filename)
+ ? MimeTypes.GetMimeType(filename)
: mediaProfile.MimeType;
- var contentFeatures = new ContentFeatureBuilder(_profile).BuildAudioHeader(streamInfo.Container,
+ var contentFeatures = ContentFeatureBuilder.BuildAudioHeader(
+ _profile,
+ streamInfo.Container,
streamInfo.TargetAudioCodec.FirstOrDefault(),
targetAudioBitrate,
targetSampleRate,
@@ -533,11 +612,13 @@ namespace Emby.Dlna.Didl
streamInfo.RunTimeTicks ?? 0,
streamInfo.TranscodeSeekInfo);
- writer.WriteAttributeString("protocolInfo", string.Format(
- "http-get:*:{0}:{1}",
- mimeType,
- contentFeatures
- ));
+ writer.WriteAttributeString(
+ "protocolInfo",
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "http-get:*:{0}:{1}",
+ mimeType,
+ contentFeatures));
writer.WriteString(url);
@@ -545,29 +626,22 @@ namespace Emby.Dlna.Didl
}
public static bool IsIdRoot(string id)
- {
- if (string.IsNullOrWhiteSpace(id)
+ => string.IsNullOrWhiteSpace(id)
|| string.Equals(id, "0", StringComparison.OrdinalIgnoreCase)
// Samsung sometimes uses 1 as root
- || string.Equals(id, "1", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- return false;
- }
+ || string.Equals(id, "1", StringComparison.OrdinalIgnoreCase);
public void WriteFolderElement(XmlWriter writer, BaseItem folder, StubType? stubType, BaseItem context, int childCount, Filter filter, string requestedId = null)
{
- writer.WriteStartElement(string.Empty, "container", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "container", NsDidl);
writer.WriteAttributeString("restricted", "1");
writer.WriteAttributeString("searchable", "1");
- writer.WriteAttributeString("childCount", childCount.ToString(_usCulture));
+ writer.WriteAttributeString("childCount", childCount.ToString(CultureInfo.InvariantCulture));
var clientId = GetClientId(folder, stubType);
- if (string.Equals(requestedId, "0"))
+ if (string.Equals(requestedId, "0", StringComparison.Ordinal))
{
writer.WriteAttributeString("id", "0");
writer.WriteAttributeString("parentID", "-1");
@@ -596,19 +670,19 @@ namespace Emby.Dlna.Didl
AddGeneralProperties(folder, stubType, context, writer, filter);
- AddCover(folder, context, stubType, writer);
+ AddCover(folder, stubType, writer);
writer.WriteFullEndElement();
}
- private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer)
+ private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer, StreamInfo streamInfo)
{
if (!item.SupportsPositionTicksResume || item is Folder)
{
return;
}
- MediaBrowser.Model.Dlna.XmlAttribute secAttribute = null;
+ XmlAttribute secAttribute = null;
foreach (var attribute in _profile.XmlRootAttributes)
{
if (string.Equals(attribute.Name, "xmlns:sec", StringComparison.OrdinalIgnoreCase))
@@ -625,24 +699,28 @@ namespace Emby.Dlna.Didl
}
var userdata = _userDataManager.GetUserData(user, item);
+ var playbackPositionTicks = (streamInfo != null && streamInfo.StartPositionTicks > 0) ? streamInfo.StartPositionTicks : userdata.PlaybackPositionTicks;
- if (userdata.PlaybackPositionTicks > 0)
+ if (playbackPositionTicks > 0)
{
- var elementValue = string.Format("BM={0}", Convert.ToInt32(TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds).ToString(_usCulture));
+ var elementValue = string.Format(
+ CultureInfo.InvariantCulture,
+ "BM={0}",
+ Convert.ToInt32(TimeSpan.FromTicks(playbackPositionTicks).TotalSeconds));
AddValue(writer, "sec", "dcmInfo", elementValue, secAttribute.Value);
}
}
/// <summary>
- /// Adds fields used by both items and folders
+ /// Adds fields used by both items and folders.
/// </summary>
private void AddCommonFields(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
{
// Don't filter on dc:title because not all devices will include it in the filter
// MediaMonkey for example won't display content without a title
- //if (filter.Contains("dc:title"))
+ // if (filter.Contains("dc:title"))
{
- AddValue(writer, "dc", "title", GetDisplayName(item, itemStubType, context), NS_DC);
+ AddValue(writer, "dc", "title", GetDisplayName(item, itemStubType, context), NsDc);
}
WriteObjectClass(writer, item, itemStubType);
@@ -651,7 +729,7 @@ namespace Emby.Dlna.Didl
{
if (item.PremiereDate.HasValue)
{
- AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("o"), NS_DC);
+ AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("o", CultureInfo.InvariantCulture), NsDc);
}
}
@@ -659,16 +737,16 @@ namespace Emby.Dlna.Didl
{
foreach (var genre in item.Genres)
{
- AddValue(writer, "upnp", "genre", genre, NS_UPNP);
+ AddValue(writer, "upnp", "genre", genre, NsUpnp);
}
}
foreach (var studio in item.Studios)
{
- AddValue(writer, "upnp", "publisher", studio, NS_UPNP);
+ AddValue(writer, "upnp", "publisher", studio, NsUpnp);
}
- if (!(item is Folder))
+ if (item is not Folder)
{
if (filter.Contains("dc:description"))
{
@@ -676,27 +754,29 @@ namespace Emby.Dlna.Didl
if (!string.IsNullOrWhiteSpace(desc))
{
- AddValue(writer, "dc", "description", desc, NS_DC);
+ AddValue(writer, "dc", "description", desc, NsDc);
}
}
- //if (filter.Contains("upnp:longDescription"))
- //{
+
+ // if (filter.Contains("upnp:longDescription"))
+ // {
// if (!string.IsNullOrWhiteSpace(item.Overview))
// {
- // AddValue(writer, "upnp", "longDescription", item.Overview, NS_UPNP);
+ // AddValue(writer, "upnp", "longDescription", item.Overview, NsUpnp);
// }
- //}
+ // }
}
if (!string.IsNullOrEmpty(item.OfficialRating))
{
if (filter.Contains("dc:rating"))
{
- AddValue(writer, "dc", "rating", item.OfficialRating, NS_DC);
+ AddValue(writer, "dc", "rating", item.OfficialRating, NsDc);
}
+
if (filter.Contains("upnp:rating"))
{
- AddValue(writer, "upnp", "rating", item.OfficialRating, NS_UPNP);
+ AddValue(writer, "upnp", "rating", item.OfficialRating, NsUpnp);
}
}
@@ -708,7 +788,7 @@ namespace Emby.Dlna.Didl
// More types here
// http://oss.linn.co.uk/repos/Public/LibUpnpCil/DidlLite/UpnpAv/Test/TestDidlLite.cs
- writer.WriteStartElement("upnp", "class", NS_UPNP);
+ writer.WriteStartElement("upnp", "class", NsUpnp);
if (item.IsDisplayedAsFolder || stubType.HasValue)
{
@@ -781,52 +861,50 @@ namespace Emby.Dlna.Didl
private void AddPeople(BaseItem item, XmlWriter writer)
{
- //var types = new[]
- //{
- // PersonType.Director,
- // PersonType.Writer,
- // PersonType.Producer,
- // PersonType.Composer,
- // "Creator"
- //};
-
- //var people = _libraryManager.GetPeople(item);
-
- //var index = 0;
-
- //// Seeing some LG models locking up due content with large lists of people
- //// The actual issue might just be due to processing a more metadata than it can handle
- //var limit = 6;
+ if (!item.SupportsPeople)
+ {
+ return;
+ }
- //foreach (var actor in people)
- //{
- // var type = types.FirstOrDefault(i => string.Equals(i, actor.Type, StringComparison.OrdinalIgnoreCase) || string.Equals(i, actor.Role, StringComparison.OrdinalIgnoreCase))
- // ?? PersonType.Actor;
+ var types = new[]
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer,
+ PersonType.Composer,
+ "creator"
+ };
- // AddValue(writer, "upnp", type.ToLowerInvariant(), actor.Name, NS_UPNP);
+ // Seeing some LG models locking up due content with large lists of people
+ // The actual issue might just be due to processing a more metadata than it can handle
+ var people = _libraryManager.GetPeople(
+ new InternalPeopleQuery
+ {
+ ItemId = item.Id,
+ Limit = 6
+ });
- // index++;
+ foreach (var actor in people)
+ {
+ var type = types.FirstOrDefault(i => string.Equals(i, actor.Type, StringComparison.OrdinalIgnoreCase) || string.Equals(i, actor.Role, StringComparison.OrdinalIgnoreCase))
+ ?? PersonType.Actor;
- // if (index >= limit)
- // {
- // break;
- // }
- //}
+ AddValue(writer, "upnp", type.ToLowerInvariant(), actor.Name, NsUpnp);
+ }
}
private void AddGeneralProperties(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
{
AddCommonFields(item, itemStubType, context, writer, filter);
- var hasArtists = item as IHasArtist;
var hasAlbumArtists = item as IHasAlbumArtist;
- if (hasArtists != null)
+ if (item is IHasArtist hasArtists)
{
foreach (var artist in hasArtists.Artists)
{
- AddValue(writer, "upnp", "artist", artist, NS_UPNP);
- AddValue(writer, "dc", "creator", artist, NS_DC);
+ AddValue(writer, "upnp", "artist", artist, NsUpnp);
+ AddValue(writer, "dc", "creator", artist, NsDc);
// If it doesn't support album artists (musicvideo), then tag as both
if (hasAlbumArtists == null)
@@ -846,16 +924,16 @@ namespace Emby.Dlna.Didl
if (!string.IsNullOrWhiteSpace(item.Album))
{
- AddValue(writer, "upnp", "album", item.Album, NS_UPNP);
+ AddValue(writer, "upnp", "album", item.Album, NsUpnp);
}
if (item.IndexNumber.HasValue)
{
- AddValue(writer, "upnp", "originalTrackNumber", item.IndexNumber.Value.ToString(_usCulture), NS_UPNP);
+ AddValue(writer, "upnp", "originalTrackNumber", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), NsUpnp);
if (item is Episode)
{
- AddValue(writer, "upnp", "episodeNumber", item.IndexNumber.Value.ToString(_usCulture), NS_UPNP);
+ AddValue(writer, "upnp", "episodeNumber", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), NsUpnp);
}
}
}
@@ -864,7 +942,7 @@ namespace Emby.Dlna.Didl
{
try
{
- writer.WriteStartElement("upnp", "artist", NS_UPNP);
+ writer.WriteStartElement("upnp", "artist", NsUpnp);
writer.WriteAttributeString("role", "AlbumArtist");
writer.WriteString(name);
@@ -873,7 +951,7 @@ namespace Emby.Dlna.Didl
}
catch (XmlException ex)
{
- _logger.LogError(ex, "Error adding xml value: {value}", name);
+ _logger.LogError(ex, "Error adding xml value: {Value}", name);
}
}
@@ -885,11 +963,11 @@ namespace Emby.Dlna.Didl
}
catch (XmlException ex)
{
- _logger.LogError(ex, "Error adding xml value: {value}", value);
+ _logger.LogError(ex, "Error adding xml value: {Value}", value);
}
}
- private void AddCover(BaseItem item, BaseItem context, StubType? stubType, XmlWriter writer)
+ private void AddCover(BaseItem item, StubType? stubType, XmlWriter writer)
{
ImageDownloadInfo imageInfo = GetImageInfo(item);
@@ -898,16 +976,29 @@ namespace Emby.Dlna.Didl
return;
}
- var albumartUrlInfo = GetImageUrl(imageInfo, _profile.MaxAlbumArtWidth, _profile.MaxAlbumArtHeight, "jpg");
+ // TODO: Remove these default values
+ var albumArtUrlInfo = GetImageUrl(
+ imageInfo,
+ _profile.MaxAlbumArtWidth ?? 10000,
+ _profile.MaxAlbumArtHeight ?? 10000,
+ "jpg");
+
+ writer.WriteStartElement("upnp", "albumArtURI", NsUpnp);
+ if (!string.IsNullOrEmpty(_profile.AlbumArtPn))
+ {
+ writer.WriteAttributeString("dlna", "profileID", NsDlna, _profile.AlbumArtPn);
+ }
- writer.WriteStartElement("upnp", "albumArtURI", NS_UPNP);
- writer.WriteAttributeString("dlna", "profileID", NS_DLNA, _profile.AlbumArtPn);
- writer.WriteString(albumartUrlInfo.Url);
+ writer.WriteString(albumArtUrlInfo.url);
writer.WriteFullEndElement();
- // TOOD: Remove these default values
- var iconUrlInfo = GetImageUrl(imageInfo, _profile.MaxIconWidth ?? 48, _profile.MaxIconHeight ?? 48, "jpg");
- writer.WriteElementString("upnp", "icon", NS_UPNP, iconUrlInfo.Url);
+ // TODO: Remove these default values
+ var iconUrlInfo = GetImageUrl(
+ imageInfo,
+ _profile.MaxIconWidth ?? 48,
+ _profile.MaxIconHeight ?? 48,
+ "jpg");
+ writer.WriteElementString("upnp", "icon", NsUpnp, iconUrlInfo.url);
if (!_profile.EnableAlbumArtInDidl)
{
@@ -921,8 +1012,6 @@ namespace Emby.Dlna.Didl
}
}
- AddImageResElement(item, writer, 160, 160, "jpg", "JPEG_TN");
-
if (!_profile.EnableSingleAlbumArtLimit || string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
{
AddImageResElement(item, writer, 4096, 4096, "jpg", "JPEG_LRG");
@@ -931,19 +1020,12 @@ namespace Emby.Dlna.Didl
AddImageResElement(item, writer, 4096, 4096, "png", "PNG_LRG");
AddImageResElement(item, writer, 160, 160, "png", "PNG_TN");
}
- }
- private void AddEmbeddedImageAsCover(string name, XmlWriter writer)
- {
- writer.WriteStartElement("upnp", "albumArtURI", NS_UPNP);
- writer.WriteAttributeString("dlna", "profileID", NS_DLNA, _profile.AlbumArtPn);
- writer.WriteString(_serverAddress + "/Dlna/icons/people480.jpg");
- writer.WriteFullEndElement();
-
- writer.WriteElementString("upnp", "icon", NS_UPNP, _serverAddress + "/Dlna/icons/people48.jpg");
+ AddImageResElement(item, writer, 160, 160, "jpg", "JPEG_TN");
}
- private void AddImageResElement(BaseItem item,
+ private void AddImageResElement(
+ BaseItem item,
XmlWriter writer,
int maxWidth,
int maxHeight,
@@ -959,25 +1041,28 @@ namespace Emby.Dlna.Didl
var albumartUrlInfo = GetImageUrl(imageInfo, maxWidth, maxHeight, format);
- writer.WriteStartElement(string.Empty, "res", NS_DIDL);
+ writer.WriteStartElement(string.Empty, "res", NsDidl);
// Images must have a reported size or many clients (Bubble upnp), will only use the first thumbnail
// rather than using a larger one when available
- var width = albumartUrlInfo.Width ?? maxWidth;
- var height = albumartUrlInfo.Height ?? maxHeight;
+ var width = albumartUrlInfo.width ?? maxWidth;
+ var height = albumartUrlInfo.height ?? maxHeight;
- var contentFeatures = new ContentFeatureBuilder(_profile)
- .BuildImageHeader(format, width, height, imageInfo.IsDirectStream, org_Pn);
+ var contentFeatures = ContentFeatureBuilder.BuildImageHeader(_profile, format, width, height, imageInfo.IsDirectStream, org_Pn);
- writer.WriteAttributeString("protocolInfo", string.Format(
- "http-get:*:{0}:{1}",
- GetMimeType("file." + format),
- contentFeatures
- ));
+ writer.WriteAttributeString(
+ "protocolInfo",
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "http-get:*:{0}:{1}",
+ MimeTypes.GetMimeType("file." + format),
+ contentFeatures));
- writer.WriteAttributeString("resolution", string.Format("{0}x{1}", width, height));
+ writer.WriteAttributeString(
+ "resolution",
+ string.Format(CultureInfo.InvariantCulture, "{0}x{1}", width, height));
- writer.WriteString(albumartUrlInfo.Url);
+ writer.WriteString(albumartUrlInfo.url);
writer.WriteFullEndElement();
}
@@ -988,10 +1073,12 @@ namespace Emby.Dlna.Didl
{
return GetImageInfo(item, ImageType.Primary);
}
+
if (item.HasImage(ImageType.Thumb))
{
return GetImageInfo(item, ImageType.Thumb);
}
+
if (item.HasImage(ImageType.Backdrop))
{
if (item is Channel)
@@ -1000,19 +1087,58 @@ namespace Emby.Dlna.Didl
}
}
- item = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Primary));
+ // For audio tracks without art use album art if available.
+ if (item is Audio audioItem)
+ {
+ var album = audioItem.AlbumEntity;
+ return album != null && album.HasImage(ImageType.Primary)
+ ? GetImageInfo(album, ImageType.Primary)
+ : null;
+ }
- if (item != null)
+ // Don't look beyond album/playlist level. Metadata service may assign an image from a different album/show to the parent folder.
+ if (item is MusicAlbum || item is Playlist)
{
- if (item.HasImage(ImageType.Primary))
- {
- return GetImageInfo(item, ImageType.Primary);
- }
+ return null;
+ }
+
+ // For other item types check parents, but be aware that image retrieved from a parent may be not suitable for this media item.
+ var parentWithImage = GetFirstParentWithImageBelowUserRoot(item);
+ if (parentWithImage != null)
+ {
+ return GetImageInfo(parentWithImage, ImageType.Primary);
}
return null;
}
+ private BaseItem GetFirstParentWithImageBelowUserRoot(BaseItem item)
+ {
+ if (item == null)
+ {
+ return null;
+ }
+
+ if (item.HasImage(ImageType.Primary))
+ {
+ return item;
+ }
+
+ var parent = item.GetParent();
+ if (parent is UserRootFolder)
+ {
+ return null;
+ }
+
+ // terminate in case we went past user root folder (unlikely?)
+ if (parent is Folder folder && folder.IsRoot)
+ {
+ return null;
+ }
+
+ return GetFirstParentWithImageBelowUserRoot(parent);
+ }
+
private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
{
var imageInfo = item.GetImageInfo(type, 0);
@@ -1032,29 +1158,15 @@ namespace Emby.Dlna.Didl
if (width == 0 || height == 0)
{
- //_imageProcessor.GetImageSize(item, imageInfo);
width = null;
height = null;
}
-
else if (width == -1 || height == -1)
{
width = null;
height = null;
}
- //try
- //{
- // var size = _imageProcessor.GetImageSize(imageInfo);
-
- // width = size.Width;
- // height = size.Height;
- //}
- //catch
- //{
-
- //}
-
var inputFormat = (Path.GetExtension(imageInfo.Path) ?? string.Empty)
.TrimStart('.')
.Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
@@ -1071,30 +1183,6 @@ namespace Emby.Dlna.Didl
};
}
- private class ImageDownloadInfo
- {
- internal Guid ItemId;
- internal string ImageTag;
- internal ImageType Type;
-
- internal int? Width;
- internal int? Height;
-
- internal bool IsDirectStream;
-
- internal string Format;
-
- internal ItemImageInfo ItemImageInfo;
- }
-
- private class ImageUrlInfo
- {
- internal string Url;
-
- internal int? Width;
- internal int? Height;
- }
-
public static string GetClientId(BaseItem item, StubType? stubType)
{
return GetClientId(item.Id, stubType);
@@ -1102,7 +1190,7 @@ namespace Emby.Dlna.Didl
public static string GetClientId(Guid idValue, StubType? stubType)
{
- var id = idValue.ToString("N");
+ var id = idValue.ToString("N", CultureInfo.InvariantCulture);
if (stubType.HasValue)
{
@@ -1112,11 +1200,13 @@ namespace Emby.Dlna.Didl
return id;
}
- private ImageUrlInfo GetImageUrl(ImageDownloadInfo info, int maxWidth, int maxHeight, string format)
+ private (string url, int? width, int? height) GetImageUrl(ImageDownloadInfo info, int maxWidth, int maxHeight, string format)
{
- var url = string.Format("{0}/Items/{1}/Images/{2}/0/{3}/{4}/{5}/{6}/0/0",
+ var url = string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}/Items/{1}/Images/{2}/0/{3}/{4}/{5}/{6}/0/0",
_serverAddress,
- info.ItemId.ToString("N"),
+ info.ItemId.ToString("N", CultureInfo.InvariantCulture),
info.Type,
info.ImageTag,
format,
@@ -1130,8 +1220,7 @@ namespace Emby.Dlna.Didl
if (width.HasValue && height.HasValue)
{
- var newSize = DrawingUtils.Resize(
- new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight);
+ var newSize = DrawingUtils.Resize(new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight);
width = newSize.Width;
height = newSize.Height;
@@ -1148,12 +1237,26 @@ namespace Emby.Dlna.Didl
// just lie
info.IsDirectStream = true;
- return new ImageUrlInfo
- {
- Url = url,
- Width = width,
- Height = height
- };
+ return (url, width, height);
+ }
+
+ private class ImageDownloadInfo
+ {
+ internal Guid ItemId { get; set; }
+
+ internal string ImageTag { get; set; }
+
+ internal ImageType Type { get; set; }
+
+ internal int? Width { get; set; }
+
+ internal int? Height { get; set; }
+
+ internal bool IsDirectStream { get; set; }
+
+ internal string Format { get; set; }
+
+ internal ItemImageInfo ItemImageInfo { get; set; }
}
}
}
diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs
index a0e67870e..d703f043e 100644
--- a/Emby.Dlna/Didl/Filter.cs
+++ b/Emby.Dlna/Didl/Filter.cs
@@ -1,5 +1,6 @@
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Extensions;
namespace Emby.Dlna.Didl
{
@@ -11,21 +12,18 @@ namespace Emby.Dlna.Didl
public Filter()
: this("*")
{
-
}
public Filter(string filter)
{
- _all = StringHelper.EqualsIgnoreCase(filter, "*");
+ _all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase);
- _fields = (filter ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+ _fields = (filter ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries);
}
public bool Contains(string field)
{
- // Don't bother with this. Some clients (media monkey) use the filter and then don't display very well when very little data comes back.
- return true;
- //return _all || ListHelper.ContainsIgnoreCase(_fields, field);
+ return _all || Array.Exists(_fields, x => x.Equals(field, StringComparison.OrdinalIgnoreCase));
}
}
}
diff --git a/Emby.Dlna/Didl/StringWriterWithEncoding.cs b/Emby.Dlna/Didl/StringWriterWithEncoding.cs
index c3c4bd393..b66f53ece 100644
--- a/Emby.Dlna/Didl/StringWriterWithEncoding.cs
+++ b/Emby.Dlna/Didl/StringWriterWithEncoding.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+#pragma warning disable CA1305
+
using System;
using System.IO;
using System.Text;
@@ -6,7 +9,7 @@ namespace Emby.Dlna.Didl
{
public class StringWriterWithEncoding : StringWriter
{
- private readonly Encoding _encoding;
+ private readonly Encoding? _encoding;
public StringWriterWithEncoding()
{
@@ -27,7 +30,6 @@ namespace Emby.Dlna.Didl
{
}
-
public StringWriterWithEncoding(Encoding encoding)
{
_encoding = encoding;
@@ -51,6 +53,6 @@ namespace Emby.Dlna.Didl
_encoding = encoding;
}
- public override Encoding Encoding => (null == _encoding) ? base.Encoding : _encoding;
+ public override Encoding Encoding => _encoding ?? base.Encoding;
}
}
diff --git a/Emby.Dlna/DlnaConfigurationFactory.cs b/Emby.Dlna/DlnaConfigurationFactory.cs
new file mode 100644
index 000000000..6cc6b73a0
--- /dev/null
+++ b/Emby.Dlna/DlnaConfigurationFactory.cs
@@ -0,0 +1,23 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using Emby.Dlna.Configuration;
+using MediaBrowser.Common.Configuration;
+
+namespace Emby.Dlna
+{
+ public class DlnaConfigurationFactory : IConfigurationFactory
+ {
+ public IEnumerable<ConfigurationStore> GetConfigurations()
+ {
+ return new[]
+ {
+ new ConfigurationStore
+ {
+ Key = "dlna",
+ ConfigurationType = typeof(DlnaOptions)
+ }
+ };
+ }
+ }
+}
diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs
index f53d27451..f37d2d7d7 100644
--- a/Emby.Dlna/DlnaManager.cs
+++ b/Emby.Dlna/DlnaManager.cs
@@ -1,12 +1,17 @@
+#pragma warning disable CS1591
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Reflection;
using System.Text;
+using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Emby.Dlna.Profiles;
using Emby.Dlna.Server;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller;
@@ -15,9 +20,10 @@ using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Reflection;
using MediaBrowser.Model.Serialization;
+using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Primitives;
namespace Emby.Dlna
{
@@ -26,10 +32,10 @@ namespace Emby.Dlna
private readonly IApplicationPaths _appPaths;
private readonly IXmlSerializer _xmlSerializer;
private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
- private readonly IJsonSerializer _jsonSerializer;
+ private readonly ILogger<DlnaManager> _logger;
private readonly IServerApplicationHost _appHost;
- private readonly IAssemblyInfo _assemblyInfo;
+ private static readonly Assembly _assembly = typeof(DlnaManager).Assembly;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private readonly Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>> _profiles = new Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>>(StringComparer.Ordinal);
@@ -38,24 +44,24 @@ namespace Emby.Dlna
IFileSystem fileSystem,
IApplicationPaths appPaths,
ILoggerFactory loggerFactory,
- IJsonSerializer jsonSerializer,
- IServerApplicationHost appHost,
- IAssemblyInfo assemblyInfo)
+ IServerApplicationHost appHost)
{
_xmlSerializer = xmlSerializer;
_fileSystem = fileSystem;
_appPaths = appPaths;
- _logger = loggerFactory.CreateLogger("Dlna");
- _jsonSerializer = jsonSerializer;
+ _logger = loggerFactory.CreateLogger<DlnaManager>();
_appHost = appHost;
- _assemblyInfo = assemblyInfo;
}
+ private string UserProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user");
+
+ private string SystemProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system");
+
public async Task InitProfilesAsync()
{
try
{
- await ExtractSystemProfilesAsync();
+ await ExtractSystemProfilesAsync().ConfigureAwait(false);
LoadProfiles();
}
catch (Exception ex)
@@ -85,15 +91,16 @@ namespace Emby.Dlna
.Select(i => i.Item2)
.ToList();
}
-
}
+ /// <inheritdoc />
public DeviceProfile GetDefaultProfile()
{
return new DefaultProfile();
}
- public DeviceProfile GetProfile(DeviceIdentification deviceInfo)
+ /// <inheritdoc />
+ public DeviceProfile? GetProfile(DeviceIdentification deviceInfo)
{
if (deviceInfo == null)
{
@@ -103,13 +110,13 @@ namespace Emby.Dlna
var profile = GetProfiles()
.FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification));
- if (profile != null)
+ if (profile == null)
{
- _logger.LogDebug("Found matching device profile: {0}", profile.Name);
+ LogUnmatchedProfile(deviceInfo);
}
else
{
- LogUnmatchedProfile(deviceInfo);
+ _logger.LogDebug("Found matching device profile: {ProfileName}", profile.Name);
}
return profile;
@@ -120,83 +127,57 @@ namespace Emby.Dlna
var builder = new StringBuilder();
builder.AppendLine("No matching device profile found. The default will need to be used.");
- builder.AppendLine(string.Format("DeviceDescription:{0}", profile.DeviceDescription ?? string.Empty));
- builder.AppendLine(string.Format("FriendlyName:{0}", profile.FriendlyName ?? string.Empty));
- builder.AppendLine(string.Format("Manufacturer:{0}", profile.Manufacturer ?? string.Empty));
- builder.AppendLine(string.Format("ManufacturerUrl:{0}", profile.ManufacturerUrl ?? string.Empty));
- builder.AppendLine(string.Format("ModelDescription:{0}", profile.ModelDescription ?? string.Empty));
- builder.AppendLine(string.Format("ModelName:{0}", profile.ModelName ?? string.Empty));
- builder.AppendLine(string.Format("ModelNumber:{0}", profile.ModelNumber ?? string.Empty));
- builder.AppendLine(string.Format("ModelUrl:{0}", profile.ModelUrl ?? string.Empty));
- builder.AppendLine(string.Format("SerialNumber:{0}", profile.SerialNumber ?? string.Empty));
+ builder.Append("FriendlyName: ").AppendLine(profile.FriendlyName);
+ builder.Append("Manufacturer: ").AppendLine(profile.Manufacturer);
+ builder.Append("ManufacturerUrl: ").AppendLine(profile.ManufacturerUrl);
+ builder.Append("ModelDescription: ").AppendLine(profile.ModelDescription);
+ builder.Append("ModelName: ").AppendLine(profile.ModelName);
+ builder.Append("ModelNumber: ").AppendLine(profile.ModelNumber);
+ builder.Append("ModelUrl: ").AppendLine(profile.ModelUrl);
+ builder.Append("SerialNumber: ").AppendLine(profile.SerialNumber);
_logger.LogInformation(builder.ToString());
}
- private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo)
+ /// <summary>
+ /// Attempts to match a device with a profile.
+ /// Rules:
+ /// - If the profile field has no value, the field matches irregardless of its contents.
+ /// - the profile field can be an exact match, or a reg exp.
+ /// </summary>
+ /// <param name="deviceInfo">The <see cref="DeviceIdentification"/> of the device.</param>
+ /// <param name="profileInfo">The <see cref="DeviceIdentification"/> of the profile.</param>
+ /// <returns><b>True</b> if they match.</returns>
+ public bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo)
{
- if (!string.IsNullOrEmpty(profileInfo.DeviceDescription))
- {
- if (deviceInfo.DeviceDescription == null || !IsRegexMatch(deviceInfo.DeviceDescription, profileInfo.DeviceDescription))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.FriendlyName))
- {
- if (deviceInfo.FriendlyName == null || !IsRegexMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.Manufacturer))
- {
- if (deviceInfo.Manufacturer == null || !IsRegexMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl))
- {
- if (deviceInfo.ManufacturerUrl == null || !IsRegexMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.ModelDescription))
- {
- if (deviceInfo.ModelDescription == null || !IsRegexMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.ModelName))
- {
- if (deviceInfo.ModelName == null || !IsRegexMatch(deviceInfo.ModelName, profileInfo.ModelName))
- return false;
- }
-
- if (!string.IsNullOrEmpty(profileInfo.ModelNumber))
- {
- if (deviceInfo.ModelNumber == null || !IsRegexMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber))
- return false;
- }
+ return IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)
+ && IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)
+ && IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)
+ && IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)
+ && IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)
+ && IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)
+ && IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)
+ && IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber);
+ }
- if (!string.IsNullOrEmpty(profileInfo.ModelUrl))
+ private bool IsRegexOrSubstringMatch(string input, string pattern)
+ {
+ if (string.IsNullOrEmpty(pattern))
{
- if (deviceInfo.ModelUrl == null || !IsRegexMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl))
- return false;
+ // In profile identification: An empty pattern matches anything.
+ return true;
}
- if (!string.IsNullOrEmpty(profileInfo.SerialNumber))
+ if (string.IsNullOrEmpty(input))
{
- if (deviceInfo.SerialNumber == null || !IsRegexMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber))
- return false;
+ // The profile contains a value, and the device doesn't.
+ return false;
}
- return true;
- }
-
- private bool IsRegexMatch(string input, string pattern)
- {
try
{
- return Regex.IsMatch(input, pattern);
+ return input.Equals(pattern, StringComparison.OrdinalIgnoreCase)
+ || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
catch (ArgumentException ex)
{
@@ -205,37 +186,33 @@ namespace Emby.Dlna
}
}
- public DeviceProfile GetProfile(IDictionary<string, string> headers)
+ /// <inheritdoc />
+ public DeviceProfile? GetProfile(IHeaderDictionary headers)
{
if (headers == null)
{
throw new ArgumentNullException(nameof(headers));
}
- // Convert to case insensitive
- headers = new Dictionary<string, string>(headers, StringComparer.OrdinalIgnoreCase);
-
var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
-
- if (profile != null)
+ if (profile == null)
{
- _logger.LogDebug("Found matching device profile: {0}", profile.Name);
+ _logger.LogDebug("No matching device profile found. {@Headers}", headers);
}
else
{
- var headerString = string.Join(", ", headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
- _logger.LogDebug("No matching device profile found. {0}", headerString);
+ _logger.LogDebug("Found matching device profile: {0}", profile.Name);
}
return profile;
}
- private bool IsMatch(IDictionary<string, string> headers, DeviceIdentification profileInfo)
+ private bool IsMatch(IHeaderDictionary headers, DeviceIdentification profileInfo)
{
return profileInfo.Headers.Any(i => IsMatch(headers, i));
}
- private bool IsMatch(IDictionary<string, string> headers, HttpHeaderInfo header)
+ private bool IsMatch(IHeaderDictionary headers, HttpHeaderInfo header)
{
// Handle invalid user setup
if (string.IsNullOrEmpty(header.Name))
@@ -243,15 +220,15 @@ namespace Emby.Dlna
return false;
}
- if (headers.TryGetValue(header.Name, out string value))
+ if (headers.TryGetValue(header.Name, out StringValues value))
{
switch (header.Match)
{
case HeaderMatchType.Equals:
return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
case HeaderMatchType.Substring:
- var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
- //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
+ var isMatch = value.ToString().IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
+ // _logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
return isMatch;
case HeaderMatchType.Regex:
return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase);
@@ -263,10 +240,6 @@ namespace Emby.Dlna
return false;
}
- private string UserProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user");
-
- private string SystemProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system");
-
private IEnumerable<DeviceProfile> GetProfiles(string path, DeviceProfileType type)
{
try
@@ -278,19 +251,19 @@ namespace Emby.Dlna
return xmlFies
.Select(i => ParseProfileFile(i, type))
.Where(i => i != null)
- .ToList();
+ .ToList()!; // We just filtered out all the nulls
}
catch (IOException)
{
- return new List<DeviceProfile>();
+ return Array.Empty<DeviceProfile>();
}
}
- private DeviceProfile ParseProfileFile(string path, DeviceProfileType type)
+ private DeviceProfile? ParseProfileFile(string path, DeviceProfileType type)
{
lock (_profiles)
{
- if (_profiles.TryGetValue(path, out Tuple<InternalProfileInfo, DeviceProfile> profileTuple))
+ if (_profiles.TryGetValue(path, out Tuple<InternalProfileInfo, DeviceProfile>? profileTuple))
{
return profileTuple.Item2;
}
@@ -303,7 +276,7 @@ namespace Emby.Dlna
profile = ReserializeProfile(tempProfile);
- profile.Id = path.ToLowerInvariant().GetMD5().ToString("N");
+ profile.Id = path.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
_profiles[path] = new Tuple<InternalProfileInfo, DeviceProfile>(GetInternalProfileInfo(_fileSystem.GetFileInfo(path), type), profile);
@@ -318,14 +291,20 @@ namespace Emby.Dlna
}
}
- public DeviceProfile GetProfile(string id)
+ /// <inheritdoc />
+ public DeviceProfile? GetProfile(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
- var info = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase));
+ var info = GetProfileInfosInternal().FirstOrDefault(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase));
+
+ if (info == null)
+ {
+ return null;
+ }
return ParseProfileFile(info.Path, info.Info.Type);
}
@@ -342,6 +321,7 @@ namespace Emby.Dlna
}
}
+ /// <inheritdoc />
public IEnumerable<DeviceProfileInfo> GetProfileInfos()
{
return GetProfileInfosInternal().Select(i => i.Info);
@@ -349,17 +329,14 @@ namespace Emby.Dlna
private InternalProfileInfo GetInternalProfileInfo(FileSystemMetadata file, DeviceProfileType type)
{
- return new InternalProfileInfo
- {
- Path = file.FullName,
-
- Info = new DeviceProfileInfo
+ return new InternalProfileInfo(
+ new DeviceProfileInfo
{
- Id = file.FullName.ToLowerInvariant().GetMD5().ToString("N"),
+ Id = file.FullName.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture),
Name = _fileSystem.GetFileNameWithoutExtension(file),
Type = type
- }
- };
+ },
+ file.FullName);
}
private async Task ExtractSystemProfilesAsync()
@@ -368,25 +345,33 @@ namespace Emby.Dlna
var systemProfilesPath = SystemProfilesPath;
- foreach (var name in _assemblyInfo.GetManifestResourceNames(GetType())
- .Where(i => i.StartsWith(namespaceName))
- .ToList())
+ foreach (var name in _assembly.GetManifestResourceNames())
{
- var filename = Path.GetFileName(name).Substring(namespaceName.Length);
+ if (!name.StartsWith(namespaceName, StringComparison.Ordinal))
+ {
+ continue;
+ }
- var path = Path.Combine(systemProfilesPath, filename);
+ var path = Path.Join(
+ systemProfilesPath,
+ Path.GetFileName(name.AsSpan()).Slice(namespaceName.Length));
- using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), name))
+ // The stream should exist as we just got its name from GetManifestResourceNames
+ using (var stream = _assembly.GetManifestResourceStream(name)!)
{
+ var length = stream.Length;
var fileInfo = _fileSystem.GetFileInfo(path);
- if (!fileInfo.Exists || fileInfo.Length != stream.Length)
+ if (!fileInfo.Exists || fileInfo.Length != length)
{
Directory.CreateDirectory(systemProfilesPath);
- using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ var fileOptions = AsyncFile.WriteOptions;
+ fileOptions.Mode = FileMode.CreateNew;
+ fileOptions.PreallocationSize = length;
+ using (var fileStream = new FileStream(path, fileOptions))
{
- await stream.CopyToAsync(fileStream);
+ await stream.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
}
@@ -396,6 +381,7 @@ namespace Emby.Dlna
Directory.CreateDirectory(UserProfilesPath);
}
+ /// <inheritdoc />
public void DeleteProfile(string id)
{
var info = GetProfileInfosInternal().First(i => string.Equals(id, i.Info.Id, StringComparison.OrdinalIgnoreCase));
@@ -413,6 +399,7 @@ namespace Emby.Dlna
}
}
+ /// <inheritdoc />
public void CreateProfile(DeviceProfile profile)
{
profile = ReserializeProfile(profile);
@@ -428,7 +415,8 @@ namespace Emby.Dlna
SaveProfile(profile, path, DeviceProfileType.User);
}
- public void UpdateProfile(DeviceProfile profile)
+ /// <inheritdoc />
+ public void UpdateProfile(string profileId, DeviceProfile profile)
{
profile = ReserializeProfile(profile);
@@ -436,12 +424,13 @@ namespace Emby.Dlna
{
throw new ArgumentException("Profile is missing Id");
}
+
if (string.IsNullOrEmpty(profile.Name))
{
throw new ArgumentException("Profile is missing Name");
}
- var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase));
+ var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profileId, StringComparison.OrdinalIgnoreCase));
var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
var path = Path.Combine(UserProfilesPath, newFilename);
@@ -461,6 +450,7 @@ namespace Emby.Dlna
{
_profiles[path] = new Tuple<InternalProfileInfo, DeviceProfile>(GetInternalProfileInfo(_fileSystem.GetFileInfo(path), type), profile);
}
+
SerializeToXml(profile, path);
}
@@ -471,10 +461,10 @@ namespace Emby.Dlna
/// <summary>
/// Recreates the object using serialization, to ensure it's not a subclass.
- /// If it's a subclass it may not serlialize properly to xml (different root element tag name)
+ /// If it's a subclass it may not serialize properly to xml (different root element tag name).
/// </summary>
- /// <param name="profile"></param>
- /// <returns></returns>
+ /// <param name="profile">The device profile.</param>
+ /// <returns>The re-serialized device profile.</returns>
private DeviceProfile ReserializeProfile(DeviceProfile profile)
{
if (profile.GetType() == typeof(DeviceProfile))
@@ -482,42 +472,56 @@ namespace Emby.Dlna
return profile;
}
- var json = _jsonSerializer.SerializeToString(profile);
+ var json = JsonSerializer.Serialize(profile, _jsonOptions);
- return _jsonSerializer.DeserializeFromString<DeviceProfile>(json);
+ // Output can't be null if the input isn't null
+ return JsonSerializer.Deserialize<DeviceProfile>(json, _jsonOptions)!;
}
- class InternalProfileInfo
+ /// <inheritdoc />
+ public string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress)
{
- internal DeviceProfileInfo Info { get; set; }
- internal string Path { get; set; }
- }
-
- public string GetServerDescriptionXml(IDictionary<string, string> headers, string serverUuId, string serverAddress)
- {
- var profile = GetProfile(headers) ??
- GetDefaultProfile();
+ var profile = GetDefaultProfile();
var serverId = _appHost.SystemId;
return new DescriptionXmlBuilder(profile, serverUuId, serverAddress, _appHost.FriendlyName, serverId).GetXml();
}
- public ImageStream GetIcon(string filename)
+ /// <inheritdoc />
+ public ImageStream? GetIcon(string filename)
{
var format = filename.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
? ImageFormat.Png
: ImageFormat.Jpg;
var resource = GetType().Namespace + ".Images." + filename.ToLowerInvariant();
+ var stream = _assembly.GetManifestResourceStream(resource);
+ if (stream == null)
+ {
+ return null;
+ }
- return new ImageStream
+ return new ImageStream(stream)
{
- Format = format,
- Stream = _assemblyInfo.GetManifestResourceStream(GetType(), resource)
+ Format = format
};
}
+
+ private class InternalProfileInfo
+ {
+ internal InternalProfileInfo(DeviceProfileInfo info, string path)
+ {
+ Info = info;
+ Path = path;
+ }
+
+ internal DeviceProfileInfo Info { get; }
+
+ internal string Path { get; }
+ }
}
+
/*
class DlnaProfileEntryPoint : IServerEntryPoint
{
@@ -539,7 +543,7 @@ namespace Emby.Dlna
private void DumpProfiles()
{
- DeviceProfile[] list = new []
+ DeviceProfile[] list = new[]
{
new SamsungSmartTvProfile(),
new XboxOneProfile(),
@@ -563,9 +567,9 @@ namespace Emby.Dlna
new Foobar2000Profile(),
new SharpSmartTvProfile(),
new MediaMonkeyProfile(),
- //new Windows81Profile(),
- //new WindowsMediaCenterProfile(),
- //new WindowsPhoneProfile(),
+ // new Windows81Profile(),
+ // new WindowsMediaCenterProfile(),
+ // new WindowsPhoneProfile(),
new DirectTvProfile(),
new DishHopperJoeyProfile(),
new DefaultProfile(),
diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj
index 71ded2337..c8332e44e 100644
--- a/Emby.Dlna/Emby.Dlna.csproj
+++ b/Emby.Dlna/Emby.Dlna.csproj
@@ -1,5 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{805844AB-E92F-45E6-9D99-4F6D48D129A5}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
@@ -12,10 +17,18 @@
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
<ItemGroup>
<EmbeddedResource Include="Images\logo120.jpg" />
<EmbeddedResource Include="Images\logo120.png" />
@@ -58,4 +71,8 @@
<EmbeddedResource Include="Profiles\Xml\Xbox One.xml" />
</ItemGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" />
+ </ItemGroup>
+
</Project>
diff --git a/Emby.Dlna/EventSubscriptionResponse.cs b/Emby.Dlna/EventSubscriptionResponse.cs
index 6dc1aacf4..635d2c47a 100644
--- a/Emby.Dlna/EventSubscriptionResponse.cs
+++ b/Emby.Dlna/EventSubscriptionResponse.cs
@@ -1,17 +1,22 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
namespace Emby.Dlna
{
public class EventSubscriptionResponse
{
- public string Content { get; set; }
- public string ContentType { get; set; }
-
- public Dictionary<string, string> Headers { get; set; }
-
- public EventSubscriptionResponse()
+ public EventSubscriptionResponse(string content, string contentType)
{
+ Content = content;
+ ContentType = contentType;
Headers = new Dictionary<string, string>();
}
+
+ public string Content { get; set; }
+
+ public string ContentType { get; set; }
+
+ public Dictionary<string, string> Headers { get; }
}
}
diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs
index b4ff3ec1d..d17e23871 100644
--- a/Emby.Dlna/Eventing/EventManager.cs
+++ b/Emby.Dlna/Eventing/DlnaEventManager.cs
@@ -1,75 +1,76 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Net.Http;
+using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.Eventing
{
- public class EventManager : IEventManager
+ public class DlnaEventManager : IDlnaEventManager
{
private readonly ConcurrentDictionary<string, EventSubscription> _subscriptions =
new ConcurrentDictionary<string, EventSubscription>(StringComparer.OrdinalIgnoreCase);
private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
- public EventManager(ILogger logger, IHttpClient httpClient)
+ public DlnaEventManager(ILogger logger, IHttpClientFactory httpClientFactory)
{
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_logger = logger;
}
public EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string notificationType, string requestedTimeoutString, string callbackUrl)
{
var subscription = GetSubscription(subscriptionId, false);
-
- int timeoutSeconds;
-
- // Remove logging for now because some devices are sending this very frequently
- // TODO re-enable with dlna debug logging setting
- //_logger.LogDebug("Renewing event subscription for {0} with timeout of {1} to {2}",
- // subscription.NotificationType,
- // timeout,
- // subscription.CallbackUrl);
-
if (subscription != null)
{
subscription.TimeoutSeconds = ParseTimeout(requestedTimeoutString) ?? 300;
- timeoutSeconds = subscription.TimeoutSeconds;
+ int timeoutSeconds = subscription.TimeoutSeconds;
subscription.SubscriptionTime = DateTime.UtcNow;
- }
- else
- {
- timeoutSeconds = 300;
+
+ _logger.LogDebug(
+ "Renewing event subscription for {0} with timeout of {1} to {2}",
+ subscription.NotificationType,
+ timeoutSeconds,
+ subscription.CallbackUrl);
+
+ return GetEventSubscriptionResponse(subscriptionId, requestedTimeoutString, timeoutSeconds);
}
- return GetEventSubscriptionResponse(subscriptionId, requestedTimeoutString, timeoutSeconds);
+ return new EventSubscriptionResponse(string.Empty, "text/plain");
}
public EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl)
{
var timeout = ParseTimeout(requestedTimeoutString) ?? 300;
- var id = "uuid:" + Guid.NewGuid().ToString("N");
+ var id = "uuid:" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
- // Remove logging for now because some devices are sending this very frequently
- // TODO re-enable with dlna debug logging setting
- //_logger.LogDebug("Creating event subscription for {0} with timeout of {1} to {2}",
- // notificationType,
- // timeout,
- // callbackUrl);
+ _logger.LogDebug(
+ "Creating event subscription for {0} with timeout of {1} to {2}",
+ notificationType,
+ timeout,
+ callbackUrl);
_subscriptions.TryAdd(id, new EventSubscription
{
Id = id,
CallbackUrl = callbackUrl,
SubscriptionTime = DateTime.UtcNow,
- TimeoutSeconds = timeout
+ TimeoutSeconds = timeout,
+ NotificationType = notificationType
});
return GetEventSubscriptionResponse(id, requestedTimeoutString, timeout);
@@ -80,9 +81,7 @@ namespace Emby.Dlna.Eventing
if (!string.IsNullOrEmpty(header))
{
// Starts with SECOND-
- header = header.Split('-').Last();
-
- if (int.TryParse(header, NumberStyles.Integer, _usCulture, out var val))
+ if (int.TryParse(header.AsSpan().RightPart('-'), NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
{
return val;
}
@@ -95,26 +94,17 @@ namespace Emby.Dlna.Eventing
{
_logger.LogDebug("Cancelling event subscription {0}", subscriptionId);
- _subscriptions.TryRemove(subscriptionId, out EventSubscription sub);
+ _subscriptions.TryRemove(subscriptionId, out _);
- return new EventSubscriptionResponse
- {
- Content = string.Empty,
- ContentType = "text/plain"
- };
+ return new EventSubscriptionResponse(string.Empty, "text/plain");
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private EventSubscriptionResponse GetEventSubscriptionResponse(string subscriptionId, string requestedTimeoutString, int timeoutSeconds)
{
- var response = new EventSubscriptionResponse
- {
- Content = string.Empty,
- ContentType = "text/plain"
- };
+ var response = new EventSubscriptionResponse(string.Empty, "text/plain");
response.Headers["SID"] = subscriptionId;
- response.Headers["TIMEOUT"] = string.IsNullOrEmpty(requestedTimeoutString) ? ("SECOND-" + timeoutSeconds.ToString(_usCulture)) : requestedTimeoutString;
+ response.Headers["TIMEOUT"] = string.IsNullOrEmpty(requestedTimeoutString) ? ("SECOND-" + timeoutSeconds.ToString(CultureInfo.InvariantCulture)) : requestedTimeoutString;
return response;
}
@@ -153,33 +143,30 @@ namespace Emby.Dlna.Eventing
builder.Append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
foreach (var key in stateVariables.Keys)
{
- builder.Append("<e:property>");
- builder.Append("<" + key + ">");
- builder.Append(stateVariables[key]);
- builder.Append("</" + key + ">");
- builder.Append("</e:property>");
+ builder.Append("<e:property>")
+ .Append('<')
+ .Append(key)
+ .Append('>')
+ .Append(stateVariables[key])
+ .Append("</")
+ .Append(key)
+ .Append('>')
+ .Append("</e:property>");
}
- builder.Append("</e:propertyset>");
- var options = new HttpRequestOptions
- {
- RequestContent = builder.ToString(),
- RequestContentType = "text/xml",
- Url = subscription.CallbackUrl,
- BufferContent = false
- };
+ builder.Append("</e:propertyset>");
- options.RequestHeaders.Add("NT", subscription.NotificationType);
- options.RequestHeaders.Add("NTS", "upnp:propchange");
- options.RequestHeaders.Add("SID", subscription.Id);
- options.RequestHeaders.Add("SEQ", subscription.TriggerCount.ToString(_usCulture));
+ using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl);
+ options.Content = new StringContent(builder.ToString(), Encoding.UTF8, MediaTypeNames.Text.Xml);
+ options.Headers.TryAddWithoutValidation("NT", subscription.NotificationType);
+ options.Headers.TryAddWithoutValidation("NTS", "upnp:propchange");
+ options.Headers.TryAddWithoutValidation("SID", subscription.Id);
+ options.Headers.TryAddWithoutValidation("SEQ", subscription.TriggerCount.ToString(CultureInfo.InvariantCulture));
try
{
- using (await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false))
- {
-
- }
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(options, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
diff --git a/Emby.Dlna/Eventing/EventSubscription.cs b/Emby.Dlna/Eventing/EventSubscription.cs
index eb8781e0c..4fd7f8169 100644
--- a/Emby.Dlna/Eventing/EventSubscription.cs
+++ b/Emby.Dlna/Eventing/EventSubscription.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace Emby.Dlna.Eventing
@@ -5,14 +9,19 @@ namespace Emby.Dlna.Eventing
public class EventSubscription
{
public string Id { get; set; }
+
public string CallbackUrl { get; set; }
+
public string NotificationType { get; set; }
public DateTime SubscriptionTime { get; set; }
+
public int TimeoutSeconds { get; set; }
public long TriggerCount { get; set; }
+ public bool IsExpired => SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow;
+
public void IncrementTriggerCount()
{
if (TriggerCount == long.MaxValue)
@@ -22,7 +31,5 @@ namespace Emby.Dlna.Eventing
TriggerCount++;
}
-
- public bool IsExpired => SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow;
}
}
diff --git a/Emby.Dlna/IConnectionManager.cs b/Emby.Dlna/IConnectionManager.cs
index 855c4454d..9f643a9e6 100644
--- a/Emby.Dlna/IConnectionManager.cs
+++ b/Emby.Dlna/IConnectionManager.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
namespace Emby.Dlna
{
- public interface IConnectionManager : IEventManager, IUpnpService
+ public interface IConnectionManager : IDlnaEventManager, IUpnpService
{
}
}
diff --git a/Emby.Dlna/IContentDirectory.cs b/Emby.Dlna/IContentDirectory.cs
index b54a17c00..10f4d6386 100644
--- a/Emby.Dlna/IContentDirectory.cs
+++ b/Emby.Dlna/IContentDirectory.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
namespace Emby.Dlna
{
- public interface IContentDirectory : IEventManager, IUpnpService
+ public interface IContentDirectory : IDlnaEventManager, IUpnpService
{
}
}
diff --git a/Emby.Dlna/IEventManager.cs b/Emby.Dlna/IDlnaEventManager.cs
index 4f67a1b9b..33cf0896b 100644
--- a/Emby.Dlna/IEventManager.cs
+++ b/Emby.Dlna/IDlnaEventManager.cs
@@ -1,22 +1,33 @@
+#pragma warning disable CS1591
namespace Emby.Dlna
{
- public interface IEventManager
+ public interface IDlnaEventManager
{
/// <summary>
/// Cancels the event subscription.
/// </summary>
/// <param name="subscriptionId">The subscription identifier.</param>
+ /// <returns>The response.</returns>
EventSubscriptionResponse CancelEventSubscription(string subscriptionId);
/// <summary>
/// Renews the event subscription.
/// </summary>
+ /// <param name="subscriptionId">The subscription identifier.</param>
+ /// <param name="notificationType">The notification type.</param>
+ /// <param name="requestedTimeoutString">The requested timeout as a sting.</param>
+ /// <param name="callbackUrl">The callback url.</param>
+ /// <returns>The response.</returns>
EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string notificationType, string requestedTimeoutString, string callbackUrl);
/// <summary>
/// Creates the event subscription.
/// </summary>
+ /// <param name="notificationType">The notification type.</param>
+ /// <param name="requestedTimeoutString">The requested timeout as a sting.</param>
+ /// <param name="callbackUrl">The callback url.</param>
+ /// <returns>The response.</returns>
EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl);
}
}
diff --git a/Emby.Dlna/IMediaReceiverRegistrar.cs b/Emby.Dlna/IMediaReceiverRegistrar.cs
index 5dde01f58..43e934b53 100644
--- a/Emby.Dlna/IMediaReceiverRegistrar.cs
+++ b/Emby.Dlna/IMediaReceiverRegistrar.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
namespace Emby.Dlna
{
- public interface IMediaReceiverRegistrar : IEventManager, IUpnpService
+ public interface IMediaReceiverRegistrar : IDlnaEventManager, IUpnpService
{
}
}
diff --git a/Emby.Dlna/IUpnpService.cs b/Emby.Dlna/IUpnpService.cs
index ab8aa4619..9e7859567 100644
--- a/Emby.Dlna/IUpnpService.cs
+++ b/Emby.Dlna/IUpnpService.cs
@@ -1,4 +1,6 @@
-using System.Collections.Generic;
+#pragma warning disable CS1591
+
+using System.Threading.Tasks;
namespace Emby.Dlna
{
@@ -7,15 +9,14 @@ namespace Emby.Dlna
/// <summary>
/// Gets the content directory XML.
/// </summary>
- /// <param name="headers">The headers.</param>
/// <returns>System.String.</returns>
- string GetServiceXml(IDictionary<string, string> headers);
+ string GetServiceXml();
/// <summary>
/// Processes the control request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>ControlResponse.</returns>
- ControlResponse ProcessControlRequest(ControlRequest request);
+ Task<ControlResponse> ProcessControlRequestAsync(ControlRequest request);
}
}
diff --git a/Emby.Dlna/Images/logo120.png b/Emby.Dlna/Images/logo120.png
index 321c47729..14f6c8d5f 100644
--- a/Emby.Dlna/Images/logo120.png
+++ b/Emby.Dlna/Images/logo120.png
Binary files differ
diff --git a/Emby.Dlna/Images/logo240.jpg b/Emby.Dlna/Images/logo240.jpg
index da1cb5e07..78a27f1b5 100644
--- a/Emby.Dlna/Images/logo240.jpg
+++ b/Emby.Dlna/Images/logo240.jpg
Binary files differ
diff --git a/Emby.Dlna/Images/logo240.png b/Emby.Dlna/Images/logo240.png
index 64c828129..ff50314d4 100644
--- a/Emby.Dlna/Images/logo240.png
+++ b/Emby.Dlna/Images/logo240.png
Binary files differ
diff --git a/Emby.Dlna/Images/logo48.png b/Emby.Dlna/Images/logo48.png
index b8fc14564..d6b5fd1df 100644
--- a/Emby.Dlna/Images/logo48.png
+++ b/Emby.Dlna/Images/logo48.png
Binary files differ
diff --git a/Emby.Dlna/Images/people48.png b/Emby.Dlna/Images/people48.png
index 7fb25e6b3..dae5f6057 100644
--- a/Emby.Dlna/Images/people48.png
+++ b/Emby.Dlna/Images/people48.png
Binary files differ
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index a20006578..5d252d8dc 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -1,9 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
using System.Linq;
-using System.Threading;
+using System.Net.Http;
+using System.Net.Sockets;
using System.Threading.Tasks;
using Emby.Dlna.PlayTo;
using Emby.Dlna.Ssdp;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
@@ -19,23 +27,19 @@ using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.System;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
using Rssdp;
using Rssdp.Infrastructure;
namespace Emby.Dlna.Main
{
- public class DlnaEntryPoint : IServerEntryPoint, IRunBeforeStartup
+ public sealed class DlnaEntryPoint : IServerEntryPoint, IRunBeforeStartup
{
private readonly IServerConfigurationManager _config;
- private readonly ILogger _logger;
+ private readonly ILogger<DlnaEntryPoint> _logger;
private readonly IServerApplicationHost _appHost;
-
- private PlayToManager _manager;
private readonly ISessionManager _sessionManager;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
private readonly IDlnaManager _dlnaManager;
@@ -44,28 +48,25 @@ namespace Emby.Dlna.Main
private readonly ILocalizationManager _localization;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder;
-
private readonly IDeviceDiscovery _deviceDiscovery;
-
- private SsdpDevicePublisher _Publisher;
-
private readonly ISocketFactory _socketFactory;
- private readonly IEnvironmentInfo _environmentInfo;
private readonly INetworkManager _networkManager;
+ private readonly object _syncLock = new object();
+ private readonly NetworkConfiguration _netConfig;
+ private readonly bool _disabled;
+ private PlayToManager _manager;
+ private SsdpDevicePublisher _publisher;
private ISsdpCommunicationsServer _communicationsServer;
- internal IContentDirectory ContentDirectory { get; private set; }
- internal IConnectionManager ConnectionManager { get; private set; }
- internal IMediaReceiverRegistrar MediaReceiverRegistrar { get; private set; }
+ private bool _disposed;
- public static DlnaEntryPoint Current;
-
- public DlnaEntryPoint(IServerConfigurationManager config,
+ public DlnaEntryPoint(
+ IServerConfigurationManager config,
ILoggerFactory loggerFactory,
IServerApplicationHost appHost,
ISessionManager sessionManager,
- IHttpClient httpClient,
+ IHttpClientFactory httpClientFactory,
ILibraryManager libraryManager,
IUserManager userManager,
IDlnaManager dlnaManager,
@@ -76,16 +77,14 @@ namespace Emby.Dlna.Main
IDeviceDiscovery deviceDiscovery,
IMediaEncoder mediaEncoder,
ISocketFactory socketFactory,
- IEnvironmentInfo environmentInfo,
INetworkManager networkManager,
IUserViewManager userViewManager,
- IXmlReaderSettingsFactory xmlReaderSettingsFactory,
ITVSeriesManager tvSeriesManager)
{
_config = config;
_appHost = appHost;
_sessionManager = sessionManager;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_libraryManager = libraryManager;
_userManager = userManager;
_dlnaManager = dlnaManager;
@@ -96,41 +95,74 @@ namespace Emby.Dlna.Main
_deviceDiscovery = deviceDiscovery;
_mediaEncoder = mediaEncoder;
_socketFactory = socketFactory;
- _environmentInfo = environmentInfo;
_networkManager = networkManager;
- _logger = loggerFactory.CreateLogger("Dlna");
+ _logger = loggerFactory.CreateLogger<DlnaEntryPoint>();
- ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager,
+ ContentDirectory = new ContentDirectory.ContentDirectoryService(
+ dlnaManager,
userDataManager,
imageProcessor,
libraryManager,
config,
userManager,
- _logger,
- httpClient,
+ loggerFactory.CreateLogger<ContentDirectory.ContentDirectoryService>(),
+ httpClientFactory,
localizationManager,
mediaSourceManager,
userViewManager,
mediaEncoder,
- xmlReaderSettingsFactory,
tvSeriesManager);
- ConnectionManager = new ConnectionManager.ConnectionManager(dlnaManager, config, _logger, httpClient, xmlReaderSettingsFactory);
+ ConnectionManager = new ConnectionManager.ConnectionManagerService(
+ dlnaManager,
+ config,
+ loggerFactory.CreateLogger<ConnectionManager.ConnectionManagerService>(),
+ httpClientFactory);
- MediaReceiverRegistrar = new MediaReceiverRegistrar.MediaReceiverRegistrar(_logger, httpClient, config, xmlReaderSettingsFactory);
+ MediaReceiverRegistrar = new MediaReceiverRegistrar.MediaReceiverRegistrarService(
+ loggerFactory.CreateLogger<MediaReceiverRegistrar.MediaReceiverRegistrarService>(),
+ httpClientFactory,
+ config);
Current = this;
+
+ _netConfig = config.GetConfiguration<NetworkConfiguration>("network");
+ _disabled = appHost.ListenWithHttps && _netConfig.RequireHttps;
+
+ if (_disabled && _config.GetDlnaConfiguration().EnableServer)
+ {
+ _logger.LogError("The DLNA specification does not support HTTPS.");
+ }
}
+ public static DlnaEntryPoint Current { get; private set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the dlna server is enabled.
+ /// </summary>
+ public static bool Enabled { get; private set; }
+
+ public IContentDirectory ContentDirectory { get; private set; }
+
+ public IConnectionManager ConnectionManager { get; private set; }
+
+ public IMediaReceiverRegistrar MediaReceiverRegistrar { get; private set; }
+
public async Task RunAsync()
{
await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false);
+ if (_disabled)
+ {
+ // No use starting as dlna won't work, as we're running purely on HTTPS.
+ return;
+ }
+
ReloadComponents();
- _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
+ _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
}
- void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
+ private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
{
@@ -138,15 +170,16 @@ namespace Emby.Dlna.Main
}
}
- private async void ReloadComponents()
+ private void ReloadComponents()
{
var options = _config.GetDlnaConfiguration();
+ Enabled = options.EnableServer;
StartSsdpHandler();
if (options.EnableServer)
{
- await StartDevicePublisher(options).ConfigureAwait(false);
+ StartDevicePublisher(options);
}
else
{
@@ -169,7 +202,8 @@ namespace Emby.Dlna.Main
{
if (_communicationsServer == null)
{
- var enableMultiSocketBinding = _environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
+ var enableMultiSocketBinding = OperatingSystem.IsWindows() ||
+ OperatingSystem.IsLinux();
_communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
{
@@ -194,7 +228,10 @@ namespace Emby.Dlna.Main
{
try
{
- ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer);
+ if (communicationsServer != null)
+ {
+ ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer);
+ }
}
catch (Exception ex)
{
@@ -215,27 +252,34 @@ namespace Emby.Dlna.Main
}
}
- public async Task StartDevicePublisher(Configuration.DlnaOptions options)
+ public void StartDevicePublisher(Configuration.DlnaOptions options)
{
if (!options.BlastAliveMessages)
{
return;
}
- if (_Publisher != null)
+ if (_publisher != null)
{
return;
}
try
{
- _Publisher = new SsdpDevicePublisher(_communicationsServer, _environmentInfo.OperatingSystemName, _environmentInfo.OperatingSystemVersion);
- _Publisher.LogFunction = LogMessage;
- _Publisher.SupportPnpRootDevice = false;
+ _publisher = new SsdpDevicePublisher(
+ _communicationsServer,
+ _networkManager,
+ MediaBrowser.Common.System.OperatingSystem.Name,
+ Environment.OSVersion.VersionString,
+ _config.GetDlnaConfiguration().SendOnlyMatchedHost)
+ {
+ LogFunction = LogMessage,
+ SupportPnpRootDevice = false
+ };
- await RegisterServerEndpoints().ConfigureAwait(false);
+ RegisterServerEndpoints();
- _Publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
+ _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
}
catch (Exception ex)
{
@@ -243,31 +287,53 @@ namespace Emby.Dlna.Main
}
}
- private async Task RegisterServerEndpoints()
+ private void RegisterServerEndpoints()
{
- var addresses = (await _appHost.GetLocalIpAddresses(CancellationToken.None).ConfigureAwait(false)).ToList();
-
var udn = CreateUuid(_appHost.SystemId);
+ var descriptorUri = "/dlna/" + udn + "/description.xml";
+
+ var bindAddresses = NetworkManager.CreateCollection(
+ _networkManager.GetInternalBindAddresses()
+ .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)));
- foreach (var address in addresses)
+ if (bindAddresses.Count == 0)
{
- // TODO: Remove this condition on platforms that support it
- //if (address.AddressFamily == IpAddressFamily.InterNetworkV6)
- //{
- // continue;
- //}
+ // No interfaces returned, so use loopback.
+ bindAddresses = _networkManager.GetLoopbacks();
+ }
+
+ foreach (IPNetAddress address in bindAddresses)
+ {
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ // Not supporting IPv6 right now
+ continue;
+ }
+
+ // Limit to LAN addresses only
+ if (!_networkManager.IsInLocalNetwork(address))
+ {
+ continue;
+ }
var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
_logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
- var descriptorUri = "/dlna/" + udn + "/description.xml";
- var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);
+ var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri);
+ if (!string.IsNullOrEmpty(_appHost.PublishedServerUrl))
+ {
+ // DLNA will only work over http, so we must reset to http:// : {port}.
+ uri.Scheme = "http";
+ uri.Port = _netConfig.HttpServerPortNumber;
+ }
var device = new SsdpRootDevice
{
- CacheLifetime = TimeSpan.FromSeconds(1800), //How long SSDP clients can cache this info.
- Location = uri, // Must point to the URL that serves your devices UPnP description document.
+ CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
+ Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document.
+ Address = address.Address,
+ PrefixLength = address.PrefixLength,
FriendlyName = "Jellyfin",
Manufacturer = "Jellyfin",
ModelName = "Jellyfin Server",
@@ -276,13 +342,13 @@ namespace Emby.Dlna.Main
};
SetProperies(device, fullService);
- _Publisher.AddDevice(device);
+ _publisher.AddDevice(device);
var embeddedDevices = new[]
{
"urn:schemas-upnp-org:service:ContentDirectory:1",
"urn:schemas-upnp-org:service:ConnectionManager:1",
- //"urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
+ // "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
};
foreach (var subDevice in embeddedDevices)
@@ -308,12 +374,13 @@ namespace Emby.Dlna.Main
{
guid = text.GetMD5();
}
- return guid.ToString("N");
+
+ return guid.ToString("N", CultureInfo.InvariantCulture);
}
private void SetProperies(SsdpDevice device, string fullDeviceType)
{
- var service = fullDeviceType.Replace("urn:", string.Empty).Replace(":1", string.Empty);
+ var service = fullDeviceType.Replace("urn:", string.Empty, StringComparison.OrdinalIgnoreCase).Replace(":1", string.Empty, StringComparison.OrdinalIgnoreCase);
var serviceParts = service.Split(':');
@@ -324,7 +391,6 @@ namespace Emby.Dlna.Main
device.DeviceType = serviceParts[2];
}
- private readonly object _syncLock = new object();
private void StartPlayToManager()
{
lock (_syncLock)
@@ -336,7 +402,8 @@ namespace Emby.Dlna.Main
try
{
- _manager = new PlayToManager(_logger,
+ _manager = new PlayToManager(
+ _logger,
_sessionManager,
_libraryManager,
_userManager,
@@ -344,7 +411,7 @@ namespace Emby.Dlna.Main
_appHost,
_imageProcessor,
_deviceDiscovery,
- _httpClient,
+ _httpClientFactory,
_config,
_userDataManager,
_localization,
@@ -375,13 +442,30 @@ namespace Emby.Dlna.Main
{
_logger.LogError(ex, "Error disposing PlayTo manager");
}
+
_manager = null;
}
}
}
+ public void DisposeDevicePublisher()
+ {
+ if (_publisher != null)
+ {
+ _logger.LogInformation("Disposing SsdpDevicePublisher");
+ _publisher.Dispose();
+ _publisher = null;
+ }
+ }
+
+ /// <inheritdoc />
public void Dispose()
{
+ if (_disposed)
+ {
+ return;
+ }
+
DisposeDevicePublisher();
DisposePlayToManager();
DisposeDeviceDiscovery();
@@ -397,16 +481,8 @@ namespace Emby.Dlna.Main
ConnectionManager = null;
MediaReceiverRegistrar = null;
Current = null;
- }
- public void DisposeDevicePublisher()
- {
- if (_Publisher != null)
- {
- _logger.LogInformation("Disposing SsdpDevicePublisher");
- _Publisher.Dispose();
- _Publisher = null;
- }
+ _disposed = true;
}
}
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
index ae8175f4a..d8fb12742 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
@@ -1,44 +1,58 @@
using System;
using System.Collections.Generic;
+using System.Xml;
using Emby.Dlna.Service;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.MediaReceiverRegistrar
{
+ /// <summary>
+ /// Defines the <see cref="ControlHandler" />.
+ /// </summary>
public class ControlHandler : BaseControlHandler
{
- protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ControlHandler"/> class.
+ /// </summary>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ /// <param name="logger">The <see cref="ILogger"/> for use with the <see cref="ControlHandler"/> instance.</param>
+ public ControlHandler(IServerConfigurationManager config, ILogger logger)
+ : base(config, logger)
{
- if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase))
- return HandleIsAuthorized();
- if (string.Equals(methodName, "IsValidated", StringComparison.OrdinalIgnoreCase))
- return HandleIsValidated();
-
- throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
- private static IEnumerable<KeyValuePair<string, string>> HandleIsAuthorized()
+ /// <inheritdoc />
+ protected override void WriteResult(string methodName, IReadOnlyDictionary<string, string> methodParams, XmlWriter xmlWriter)
{
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
+ if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase))
{
- { "Result", "1" }
- };
- }
+ HandleIsAuthorized(xmlWriter);
+ return;
+ }
- private static IEnumerable<KeyValuePair<string, string>> HandleIsValidated()
- {
- return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
+ if (string.Equals(methodName, "IsValidated", StringComparison.OrdinalIgnoreCase))
{
- { "Result", "1" }
- };
- }
+ HandleIsValidated(xmlWriter);
+ return;
+ }
- public ControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
- : base(config, logger, xmlReaderSettingsFactory)
- {
+ throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
+
+ /// <summary>
+ /// Records that the handle is authorized in the xml stream.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleIsAuthorized(XmlWriter xmlWriter)
+ => xmlWriter.WriteElementString("Result", "1");
+
+ /// <summary>
+ /// Records that the handle is validated in the xml stream.
+ /// </summary>
+ /// <param name="xmlWriter">The <see cref="XmlWriter"/>.</param>
+ private static void HandleIsValidated(XmlWriter xmlWriter)
+ => xmlWriter.WriteElementString("Result", "1");
}
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
deleted file mode 100644
index 2b84528ea..000000000
--- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.Collections.Generic;
-using Emby.Dlna.Service;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Xml;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Dlna.MediaReceiverRegistrar
-{
- public class MediaReceiverRegistrar : BaseService, IMediaReceiverRegistrar
- {
- private readonly IServerConfigurationManager _config;
- protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
-
- public MediaReceiverRegistrar(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
- : base(logger, httpClient)
- {
- _config = config;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
- }
-
- public string GetServiceXml(IDictionary<string, string> headers)
- {
- return new MediaReceiverRegistrarXmlBuilder().GetXml();
- }
-
- public ControlResponse ProcessControlRequest(ControlRequest request)
- {
- return new ControlHandler(
- _config,
- Logger, XmlReaderSettingsFactory)
- .ProcessControlRequest(request);
- }
- }
-}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs
new file mode 100644
index 000000000..a5aae515c
--- /dev/null
+++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs
@@ -0,0 +1,46 @@
+using System.Net.Http;
+using System.Threading.Tasks;
+using Emby.Dlna.Service;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Dlna.MediaReceiverRegistrar
+{
+ /// <summary>
+ /// Defines the <see cref="MediaReceiverRegistrarService" />.
+ /// </summary>
+ public class MediaReceiverRegistrarService : BaseService, IMediaReceiverRegistrar
+ {
+ private readonly IServerConfigurationManager _config;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MediaReceiverRegistrarService"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger{MediaReceiverRegistrarService}"/> for use with the <see cref="MediaReceiverRegistrarService"/> instance.</param>
+ /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/> for use with the <see cref="MediaReceiverRegistrarService"/> instance.</param>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/> for use with the <see cref="MediaReceiverRegistrarService"/> instance.</param>
+ public MediaReceiverRegistrarService(
+ ILogger<MediaReceiverRegistrarService> logger,
+ IHttpClientFactory httpClientFactory,
+ IServerConfigurationManager config)
+ : base(logger, httpClientFactory)
+ {
+ _config = config;
+ }
+
+ /// <inheritdoc />
+ public string GetServiceXml()
+ {
+ return MediaReceiverRegistrarXmlBuilder.GetXml();
+ }
+
+ /// <inheritdoc />
+ public Task<ControlResponse> ProcessControlRequestAsync(ControlRequest request)
+ {
+ return new ControlHandler(
+ _config,
+ Logger)
+ .ProcessControlRequestAsync(request);
+ }
+ }
+}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
index 641341185..f3789a791 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
@@ -4,73 +4,85 @@ using Emby.Dlna.Service;
namespace Emby.Dlna.MediaReceiverRegistrar
{
- public class MediaReceiverRegistrarXmlBuilder
+ /// <summary>
+ /// Defines the <see cref="MediaReceiverRegistrarXmlBuilder" />.
+ /// See https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-drmnd/5d37515e-7a63-4709-8258-8fd4e0ed4482.
+ /// </summary>
+ public static class MediaReceiverRegistrarXmlBuilder
{
- public string GetXml()
+ /// <summary>
+ /// Retrieves an XML description of the X_MS_MediaReceiverRegistrar.
+ /// </summary>
+ /// <returns>An XML representation of this service.</returns>
+ public static string GetXml()
{
- return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(),
- GetStateVariables());
+ return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables());
}
+ /// <summary>
+ /// The a list of all the state variables for this invocation.
+ /// </summary>
+ /// <returns>The <see cref="IEnumerable{StateVariable}"/>.</returns>
private static IEnumerable<StateVariable> GetStateVariables()
{
- var list = new List<StateVariable>();
-
- list.Add(new StateVariable
+ var list = new List<StateVariable>
{
- Name = "AuthorizationGrantedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "AuthorizationGrantedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_DeviceID",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_DeviceID",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "AuthorizationDeniedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "AuthorizationDeniedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "ValidationSucceededUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "ValidationSucceededUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RegistrationRespMsg",
- DataType = "bin.base64",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RegistrationRespMsg",
+ DataType = "bin.base64",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RegistrationReqMsg",
- DataType = "bin.base64",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RegistrationReqMsg",
+ DataType = "bin.base64",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "ValidationRevokedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "ValidationRevokedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Result",
- DataType = "int",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Result",
+ DataType = "int",
+ SendsEvents = false
+ }
+ };
return list;
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
index 86429f605..56788ae22 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
@@ -3,9 +3,16 @@ using Emby.Dlna.Common;
namespace Emby.Dlna.MediaReceiverRegistrar
{
- public class ServiceActionListBuilder
+ /// <summary>
+ /// Defines the <see cref="ServiceActionListBuilder" />.
+ /// </summary>
+ public static class ServiceActionListBuilder
{
- public IEnumerable<ServiceAction> GetActions()
+ /// <summary>
+ /// Returns a list of services that this instance provides.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{ServiceAction}"/>.</returns>
+ public static IEnumerable<ServiceAction> GetActions()
{
return new[]
{
@@ -19,6 +26,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
};
}
+ /// <summary>
+ /// Returns the action details for "IsValidated".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetIsValidated()
{
var action = new ServiceAction
@@ -41,6 +52,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ /// <summary>
+ /// Returns the action details for "IsAuthorized".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetIsAuthorized()
{
var action = new ServiceAction
@@ -63,6 +78,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ /// <summary>
+ /// Returns the action details for "RegisterDevice".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetRegisterDevice()
{
var action = new ServiceAction
@@ -85,6 +104,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ /// <summary>
+ /// Returns the action details for "GetValidationSucceededUpdateID".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
private static ServiceAction GetGetValidationSucceededUpdateID()
{
var action = new ServiceAction
@@ -101,7 +124,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetAuthorizationDeniedUpdateID()
+ /// <summary>
+ /// Returns the action details for "GetGetAuthorizationDeniedUpdateID".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetGetAuthorizationDeniedUpdateID()
{
var action = new ServiceAction
{
@@ -117,7 +144,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetValidationRevokedUpdateID()
+ /// <summary>
+ /// Returns the action details for "GetValidationRevokedUpdateID".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetGetValidationRevokedUpdateID()
{
var action = new ServiceAction
{
@@ -133,7 +164,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetAuthorizationGrantedUpdateID()
+ /// <summary>
+ /// Returns the action details for "GetAuthorizationGrantedUpdateID".
+ /// </summary>
+ /// <returns>The <see cref="ServiceAction"/>.</returns>
+ private static ServiceAction GetGetAuthorizationGrantedUpdateID()
{
var action = new ServiceAction
{
diff --git a/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs b/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs
deleted file mode 100644
index fdf435bcf..000000000
--- a/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System;
-
-namespace Emby.Dlna.PlayTo
-{
- public class CurrentIdEventArgs : EventArgs
- {
- public string Id { get; set; }
- }
-}
diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs
index b62c5e1d4..0b2288000 100644
--- a/Emby.Dlna/PlayTo/Device.cs
+++ b/Emby.Dlna/PlayTo/Device.cs
@@ -1,40 +1,65 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Net.Http;
+using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Emby.Dlna.Common;
-using Emby.Dlna.Server;
using Emby.Dlna.Ssdp;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.PlayTo
{
public class Device : IDisposable
{
- #region Fields & Properties
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILogger _logger;
+
+ private readonly object _timerLock = new object();
private Timer _timer;
+ private int _muteVol;
+ private int _volume;
+ private DateTime _lastVolumeRefresh;
+ private bool _volumeRefreshActive;
+ private int _connectFailureCount;
+ private bool _disposed;
+
+ public Device(DeviceInfo deviceProperties, IHttpClientFactory httpClientFactory, ILogger logger)
+ {
+ Properties = deviceProperties;
+ _httpClientFactory = httpClientFactory;
+ _logger = logger;
+ }
+
+ public event EventHandler<PlaybackStartEventArgs> PlaybackStart;
+
+ public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
+
+ public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped;
+
+ public event EventHandler<MediaChangedEventArgs> MediaChanged;
public DeviceInfo Properties { get; set; }
- private int _muteVol;
public bool IsMuted { get; set; }
- private int _volume;
-
public int Volume
{
get
{
- RefreshVolumeIfNeeded();
+ RefreshVolumeIfNeeded().GetAwaiter().GetResult();
return _volume;
}
+
set => _volume = value;
}
@@ -42,29 +67,21 @@ namespace Emby.Dlna.PlayTo
public TimeSpan Position { get; set; } = TimeSpan.FromSeconds(0);
- public TRANSPORTSTATE TransportState { get; private set; }
+ public TransportState TransportState { get; private set; }
- public bool IsPlaying => TransportState == TRANSPORTSTATE.PLAYING;
+ public bool IsPlaying => TransportState == TransportState.Playing;
- public bool IsPaused => TransportState == TRANSPORTSTATE.PAUSED || TransportState == TRANSPORTSTATE.PAUSED_PLAYBACK;
+ public bool IsPaused => TransportState == TransportState.Paused || TransportState == TransportState.PausedPlayback;
- public bool IsStopped => TransportState == TRANSPORTSTATE.STOPPED;
+ public bool IsStopped => TransportState == TransportState.Stopped;
- #endregion
+ public Action OnDeviceUnavailable { get; set; }
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly IServerConfigurationManager _config;
+ private TransportCommands AvCommands { get; set; }
- public Action OnDeviceUnavailable { get; set; }
+ private TransportCommands RendererCommands { get; set; }
- public Device(DeviceInfo deviceProperties, IHttpClient httpClient, ILogger logger, IServerConfigurationManager config)
- {
- Properties = deviceProperties;
- _httpClient = httpClient;
- _logger = logger;
- _config = config;
- }
+ public UBaseObject CurrentMediaInfo { get; private set; }
public void Start()
{
@@ -72,26 +89,24 @@ namespace Emby.Dlna.PlayTo
_timer = new Timer(TimerCallback, null, 1000, Timeout.Infinite);
}
- private DateTime _lastVolumeRefresh;
- private bool _volumeRefreshActive;
- private void RefreshVolumeIfNeeded()
+ private Task RefreshVolumeIfNeeded()
{
- if (!_volumeRefreshActive)
- {
- return;
- }
-
- if (DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
+ if (_volumeRefreshActive
+ && DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
{
_lastVolumeRefresh = DateTime.UtcNow;
- RefreshVolume(CancellationToken.None);
+ return RefreshVolume();
}
+
+ return Task.CompletedTask;
}
- private async void RefreshVolume(CancellationToken cancellationToken)
+ private async Task RefreshVolume(CancellationToken cancellationToken = default)
{
if (_disposed)
+ {
return;
+ }
try
{
@@ -104,7 +119,6 @@ namespace Emby.Dlna.PlayTo
}
}
- private readonly object _timerLock = new object();
private void RestartTimer(bool immediate = false)
{
lock (_timerLock)
@@ -139,8 +153,6 @@ namespace Emby.Dlna.PlayTo
}
}
- #region Commanding
-
public Task VolumeDown(CancellationToken cancellationToken)
{
var sendVolume = Math.Max(Volume - 5, 0);
@@ -207,9 +219,11 @@ namespace Emby.Dlna.PlayTo
{
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetMute");
+ var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetMute");
if (command == null)
+ {
return false;
+ }
var service = GetServiceRenderingControl();
@@ -221,7 +235,13 @@ namespace Emby.Dlna.PlayTo
_logger.LogDebug("Setting mute");
var value = mute ? 1 : 0;
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value))
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType, value),
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
IsMuted = mute;
@@ -230,15 +250,20 @@ namespace Emby.Dlna.PlayTo
}
/// <summary>
- /// Sets volume on a scale of 0-100
+ /// Sets volume on a scale of 0-100.
/// </summary>
+ /// <param name="value">The volume on a scale of 0-100.</param>
+ /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task SetVolume(int value, CancellationToken cancellationToken)
{
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume");
+ var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume");
if (command == null)
+ {
return;
+ }
var service = GetServiceRenderingControl();
@@ -251,7 +276,13 @@ namespace Emby.Dlna.PlayTo
// Remote control will perform better
Volume = value;
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value))
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType, value),
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
@@ -259,9 +290,11 @@ namespace Emby.Dlna.PlayTo
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Seek");
+ var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Seek");
if (command == null)
+ {
return;
+ }
var service = GetAvTransportService();
@@ -270,7 +303,13 @@ namespace Emby.Dlna.PlayTo
throw new InvalidOperationException("Unable to find service");
}
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, string.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME"))
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ avCommands.BuildPost(command, service.ServiceType, string.Format(CultureInfo.InvariantCulture, "{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME"),
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
RestartTimer(true);
@@ -280,18 +319,20 @@ namespace Emby.Dlna.PlayTo
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
- url = url.Replace("&", "&amp;");
+ url = url.Replace("&", "&amp;", StringComparison.Ordinal);
_logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header);
- var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
+ var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
if (command == null)
+ {
return;
+ }
var dictionary = new Dictionary<string, string>
{
- {"CurrentURI", url},
- {"CurrentURIMetaData", CreateDidlMeta(metaData)}
+ { "CurrentURI", url },
+ { "CurrentURIMetaData", CreateDidlMeta(metaData) }
};
var service = GetAvTransportService();
@@ -302,14 +343,21 @@ namespace Emby.Dlna.PlayTo
}
var post = avCommands.BuildPost(command, service.ServiceType, url, dictionary);
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header)
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ post,
+ header: header,
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
- await Task.Delay(50).ConfigureAwait(false);
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
try
{
- await SetPlay(avCommands, CancellationToken.None).ConfigureAwait(false);
+ await SetPlay(avCommands, cancellationToken).ConfigureAwait(false);
}
catch
{
@@ -320,14 +368,50 @@ namespace Emby.Dlna.PlayTo
RestartTimer(true);
}
- private string CreateDidlMeta(string value)
+ /*
+ * SetNextAvTransport is used to specify to the DLNA device what is the next track to play.
+ * Without that information, the next track command on the device does not work.
+ */
+ public async Task SetNextAvTransport(string url, string header, string metaData, CancellationToken cancellationToken = default)
+ {
+ var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
+
+ url = url.Replace("&", "&amp;", StringComparison.Ordinal);
+
+ _logger.LogDebug("{PropertyName} - SetNextAvTransport Uri: {Url} DlnaHeaders: {Header}", Properties.Name, url, header);
+
+ var command = avCommands.ServiceActions.FirstOrDefault(c => string.Equals(c.Name, "SetNextAVTransportURI", StringComparison.OrdinalIgnoreCase));
+ if (command == null)
+ {
+ return;
+ }
+
+ var dictionary = new Dictionary<string, string>
+ {
+ { "NextURI", url },
+ { "NextURIMetaData", CreateDidlMeta(metaData) }
+ };
+
+ var service = GetAvTransportService();
+
+ if (service == null)
+ {
+ throw new InvalidOperationException("Unable to find service");
+ }
+
+ var post = avCommands.BuildPost(command, service.ServiceType, url, dictionary);
+ await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ private static string CreateDidlMeta(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
- return DescriptionXmlBuilder.Escape(value);
+ return SecurityElement.Escape(value);
}
private Task SetPlay(TransportCommands avCommands, CancellationToken cancellationToken)
@@ -344,12 +428,21 @@ namespace Emby.Dlna.PlayTo
throw new InvalidOperationException("Unable to find service");
}
- return new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1));
+ return new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ avCommands.BuildPost(command, service.ServiceType, 1),
+ cancellationToken: cancellationToken);
}
public async Task SetPlay(CancellationToken cancellationToken)
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
+ if (avCommands == null)
+ {
+ return;
+ }
await SetPlay(avCommands, cancellationToken).ConfigureAwait(false);
@@ -360,7 +453,7 @@ namespace Emby.Dlna.PlayTo
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Stop");
+ var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Stop");
if (command == null)
{
return;
@@ -368,7 +461,13 @@ namespace Emby.Dlna.PlayTo
var service = GetAvTransportService();
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1))
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ avCommands.BuildPost(command, service.ServiceType, 1),
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
RestartTimer(true);
@@ -378,7 +477,7 @@ namespace Emby.Dlna.PlayTo
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Pause");
+ var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Pause");
if (command == null)
{
return;
@@ -386,19 +485,20 @@ namespace Emby.Dlna.PlayTo
var service = GetAvTransportService();
- await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1))
+ await new SsdpHttpClient(_httpClientFactory)
+ .SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ avCommands.BuildPost(command, service.ServiceType, 1),
+ cancellationToken: cancellationToken)
.ConfigureAwait(false);
- TransportState = TRANSPORTSTATE.PAUSED;
+ TransportState = TransportState.Paused;
RestartTimer(true);
}
- #endregion
-
- #region Get data
-
- private int _connectFailureCount;
private async void TimerCallback(object sender)
{
if (_disposed)
@@ -427,7 +527,7 @@ namespace Emby.Dlna.PlayTo
if (transportState.HasValue)
{
// If we're not playing anything no need to get additional data
- if (transportState.Value == TRANSPORTSTATE.STOPPED)
+ if (transportState.Value == TransportState.Stopped)
{
UpdateMediaInfo(null, transportState.Value);
}
@@ -451,10 +551,12 @@ namespace Emby.Dlna.PlayTo
_connectFailureCount = 0;
if (_disposed)
+ {
return;
+ }
- // If we're not playing anything make sure we don't get data more often than neccessry to keep the Session alive
- if (transportState.Value == TRANSPORTSTATE.STOPPED)
+ // If we're not playing anything make sure we don't get data more often than necessary to keep the Session alive
+ if (transportState.Value == TransportState.Stopped)
{
RestartTimerInactive();
}
@@ -471,7 +573,9 @@ namespace Emby.Dlna.PlayTo
catch (Exception ex)
{
if (_disposed)
+ {
return;
+ }
_logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name);
@@ -487,6 +591,7 @@ namespace Emby.Dlna.PlayTo
return;
}
}
+
RestartTimerInactive();
}
}
@@ -500,7 +605,7 @@ namespace Emby.Dlna.PlayTo
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
+ var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
if (command == null)
{
return;
@@ -513,15 +618,19 @@ namespace Emby.Dlna.PlayTo
return;
}
- var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true)
- .ConfigureAwait(false);
+ var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null)
{
return;
}
- var volume = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i != null);
+ var volume = result.Document.Descendants(UPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i != null);
var volumeValue = volume?.Value;
if (string.IsNullOrWhiteSpace(volumeValue))
@@ -529,7 +638,7 @@ namespace Emby.Dlna.PlayTo
return;
}
- Volume = int.Parse(volumeValue, UsCulture);
+ Volume = int.Parse(volumeValue, CultureInfo.InvariantCulture);
if (Volume > 0)
{
@@ -546,7 +655,7 @@ namespace Emby.Dlna.PlayTo
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
- var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
+ var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
if (command == null)
{
return;
@@ -559,20 +668,26 @@ namespace Emby.Dlna.PlayTo
return;
}
- var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true)
- .ConfigureAwait(false);
+ var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null)
+ {
return;
+ }
- var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse")
+ var valueNode = result.Document.Descendants(UPnpNamespaces.RenderingControl + "GetMuteResponse")
.Select(i => i.Element("CurrentMute"))
.FirstOrDefault(i => i != null);
IsMuted = string.Equals(valueNode?.Value, "1", StringComparison.OrdinalIgnoreCase);
}
- private async Task<TRANSPORTSTATE?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken)
+ private async Task<TransportState?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken)
{
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetTransportInfo");
if (command == null)
@@ -586,8 +701,12 @@ namespace Emby.Dlna.PlayTo
return null;
}
- var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false)
- .ConfigureAwait(false);
+ var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ avCommands.BuildPost(command, service.ServiceType),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null)
{
@@ -595,12 +714,12 @@ namespace Emby.Dlna.PlayTo
}
var transportState =
- result.Document.Descendants(uPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i != null);
+ result.Document.Descendants(UPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i != null);
- var transportStateValue = transportState == null ? null : transportState.Value;
+ var transportStateValue = transportState?.Value;
if (transportStateValue != null
- && Enum.TryParse(transportStateValue, true, out TRANSPORTSTATE state))
+ && Enum.TryParse(transportStateValue, true, out TransportState state))
{
return state;
}
@@ -608,7 +727,7 @@ namespace Emby.Dlna.PlayTo
return null;
}
- private async Task<uBaseObject> GetMediaInfo(TransportCommands avCommands, CancellationToken cancellationToken)
+ private async Task<UBaseObject> GetMediaInfo(TransportCommands avCommands, CancellationToken cancellationToken)
{
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMediaInfo");
if (command == null)
@@ -623,9 +742,17 @@ namespace Emby.Dlna.PlayTo
}
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
+ if (rendererCommands == null)
+ {
+ return null;
+ }
- var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false)
- .ConfigureAwait(false);
+ var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null)
{
@@ -639,7 +766,7 @@ namespace Emby.Dlna.PlayTo
return null;
}
- var e = track.Element(uPnpNamespaces.items) ?? track;
+ var e = track.Element(UPnpNamespaces.Items) ?? track;
var elementString = (string)e;
@@ -655,13 +782,13 @@ namespace Emby.Dlna.PlayTo
return null;
}
- e = track.Element(uPnpNamespaces.items) ?? track;
+ e = track.Element(UPnpNamespaces.Items) ?? track;
elementString = (string)e;
if (!string.IsNullOrWhiteSpace(elementString))
{
- return new uBaseObject
+ return new UBaseObject
{
Url = elementString
};
@@ -670,7 +797,7 @@ namespace Emby.Dlna.PlayTo
return null;
}
- private async Task<(bool, uBaseObject)> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken)
+ private async Task<(bool, UBaseObject)> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken)
{
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetPositionInfo");
if (command == null)
@@ -687,43 +814,52 @@ namespace Emby.Dlna.PlayTo
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
- var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false)
- .ConfigureAwait(false);
+ if (rendererCommands == null)
+ {
+ return (false, null);
+ }
+
+ var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(
+ Properties.BaseUrl,
+ service,
+ command.Name,
+ rendererCommands.BuildPost(command, service.ServiceType),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null)
{
return (false, null);
}
- var trackUriElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackURI")).FirstOrDefault(i => i != null);
- var trackUri = trackUriElem == null ? null : trackUriElem.Value;
+ var trackUriElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackURI")).FirstOrDefault(i => i != null);
+ var trackUri = trackUriElem?.Value;
- var durationElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i != null);
- var duration = durationElem == null ? null : durationElem.Value;
+ var durationElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i != null);
+ var duration = durationElem?.Value;
if (!string.IsNullOrWhiteSpace(duration)
&& !string.Equals(duration, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{
- Duration = TimeSpan.Parse(duration, UsCulture);
+ Duration = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
}
else
{
Duration = null;
}
- var positionElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("RelTime")).FirstOrDefault(i => i != null);
- var position = positionElem == null ? null : positionElem.Value;
+ var positionElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("RelTime")).FirstOrDefault(i => i != null);
+ var position = positionElem?.Value;
if (!string.IsNullOrWhiteSpace(position) && !string.Equals(position, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{
- Position = TimeSpan.Parse(position, UsCulture);
+ Position = TimeSpan.Parse(position, CultureInfo.InvariantCulture);
}
var track = result.Document.Descendants("TrackMetaData").FirstOrDefault();
if (track == null)
{
- //If track is null, some vendors do this, use GetMediaInfo instead
+ // If track is null, some vendors do this, use GetMediaInfo instead.
return (true, null);
}
@@ -751,7 +887,7 @@ namespace Emby.Dlna.PlayTo
return (true, null);
}
- var e = uPnpResponse.Element(uPnpNamespaces.items);
+ var e = uPnpResponse.Element(UPnpNamespaces.Items);
var uTrack = CreateUBaseObject(e, trackUri);
@@ -760,17 +896,16 @@ namespace Emby.Dlna.PlayTo
private XElement ParseResponse(string xml)
{
- // Handle different variations sent back by devices
+ // Handle different variations sent back by devices.
try
{
return XElement.Parse(xml);
}
catch (XmlException)
{
-
}
- // first try to add a root node with a dlna namesapce
+ // first try to add a root node with a dlna namespace.
try
{
return XElement.Parse("<data xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">" + xml + "</data>")
@@ -779,43 +914,41 @@ namespace Emby.Dlna.PlayTo
}
catch (XmlException)
{
-
}
// some devices send back invalid xml
try
{
- return XElement.Parse(xml.Replace("&", "&amp;"));
+ return XElement.Parse(xml.Replace("&", "&amp;", StringComparison.Ordinal));
}
catch (XmlException)
{
-
}
return null;
}
- private static uBaseObject CreateUBaseObject(XElement container, string trackUri)
+ private static UBaseObject CreateUBaseObject(XElement container, string trackUri)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
- var url = container.GetValue(uPnpNamespaces.Res);
+ var url = container.GetValue(UPnpNamespaces.Res);
if (string.IsNullOrWhiteSpace(url))
{
url = trackUri;
}
- return new uBaseObject
+ return new UBaseObject
{
- Id = container.GetAttributeValue(uPnpNamespaces.Id),
- ParentId = container.GetAttributeValue(uPnpNamespaces.ParentId),
- Title = container.GetValue(uPnpNamespaces.title),
- IconUrl = container.GetValue(uPnpNamespaces.Artwork),
- SecondText = "",
+ Id = container.GetAttributeValue(UPnpNamespaces.Id),
+ ParentId = container.GetAttributeValue(UPnpNamespaces.ParentId),
+ Title = container.GetValue(UPnpNamespaces.Title),
+ IconUrl = container.GetValue(UPnpNamespaces.Artwork),
+ SecondText = string.Empty,
Url = url,
ProtocolInfo = GetProtocolInfo(container),
MetaData = container.ToString()
@@ -829,11 +962,11 @@ namespace Emby.Dlna.PlayTo
throw new ArgumentNullException(nameof(container));
}
- var resElement = container.Element(uPnpNamespaces.Res);
+ var resElement = container.Element(UPnpNamespaces.Res);
if (resElement != null)
{
- var info = resElement.Attribute(uPnpNamespaces.ProtocolInfo);
+ var info = resElement.Attribute(UPnpNamespaces.ProtocolInfo);
if (info != null && !string.IsNullOrWhiteSpace(info.Value))
{
@@ -844,10 +977,6 @@ namespace Emby.Dlna.PlayTo
return new string[4];
}
- #endregion
-
- #region From XML
-
private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken)
{
if (AvCommands != null)
@@ -868,9 +997,13 @@ namespace Emby.Dlna.PlayTo
string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
- var httpClient = new SsdpHttpClient(_httpClient, _config);
+ var httpClient = new SsdpHttpClient(_httpClientFactory);
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
+ if (document == null)
+ {
+ return null;
+ }
AvCommands = TransportCommands.Create(document);
return AvCommands;
@@ -896,9 +1029,13 @@ namespace Emby.Dlna.PlayTo
string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
- var httpClient = new SsdpHttpClient(_httpClient, _config);
+ var httpClient = new SsdpHttpClient(_httpClientFactory);
_logger.LogDebug("Dlna Device.GetRenderingProtocolAsync");
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
+ if (document == null)
+ {
+ return null;
+ }
RendererCommands = TransportCommands.Create(document);
return RendererCommands;
@@ -912,12 +1049,12 @@ namespace Emby.Dlna.PlayTo
return url;
}
- if (!url.Contains("/"))
+ if (!url.Contains('/', StringComparison.Ordinal))
{
url = "/dmr/" + url;
}
- if (!url.StartsWith("/"))
+ if (!url.StartsWith('/'))
{
url = "/" + url;
}
@@ -925,25 +1062,25 @@ namespace Emby.Dlna.PlayTo
return baseUrl + url;
}
- private TransportCommands AvCommands { get; set; }
-
- private TransportCommands RendererCommands { get; set; }
-
- public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, CancellationToken cancellationToken)
+ public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClientFactory httpClientFactory, ILogger logger, CancellationToken cancellationToken)
{
- var ssdpHttpClient = new SsdpHttpClient(httpClient, config);
+ var ssdpHttpClient = new SsdpHttpClient(httpClientFactory);
var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false);
+ if (document == null)
+ {
+ return null;
+ }
var friendlyNames = new List<string>();
- var name = document.Descendants(uPnpNamespaces.ud.GetName("friendlyName")).FirstOrDefault();
+ var name = document.Descendants(UPnpNamespaces.Ud.GetName("friendlyName")).FirstOrDefault();
if (name != null && !string.IsNullOrWhiteSpace(name.Value))
{
friendlyNames.Add(name.Value);
}
- var room = document.Descendants(uPnpNamespaces.ud.GetName("roomName")).FirstOrDefault();
+ var room = document.Descendants(UPnpNamespaces.Ud.GetName("roomName")).FirstOrDefault();
if (room != null && !string.IsNullOrWhiteSpace(room.Value))
{
friendlyNames.Add(room.Value);
@@ -951,78 +1088,78 @@ namespace Emby.Dlna.PlayTo
var deviceProperties = new DeviceInfo()
{
- Name = string.Join(" ", friendlyNames),
- BaseUrl = string.Format("http://{0}:{1}", url.Host, url.Port)
+ Name = string.Join(' ', friendlyNames),
+ BaseUrl = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", url.Host, url.Port)
};
- var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault();
+ var model = document.Descendants(UPnpNamespaces.Ud.GetName("modelName")).FirstOrDefault();
if (model != null)
{
deviceProperties.ModelName = model.Value;
}
- var modelNumber = document.Descendants(uPnpNamespaces.ud.GetName("modelNumber")).FirstOrDefault();
+ var modelNumber = document.Descendants(UPnpNamespaces.Ud.GetName("modelNumber")).FirstOrDefault();
if (modelNumber != null)
{
deviceProperties.ModelNumber = modelNumber.Value;
}
- var uuid = document.Descendants(uPnpNamespaces.ud.GetName("UDN")).FirstOrDefault();
+ var uuid = document.Descendants(UPnpNamespaces.Ud.GetName("UDN")).FirstOrDefault();
if (uuid != null)
{
deviceProperties.UUID = uuid.Value;
}
- var manufacturer = document.Descendants(uPnpNamespaces.ud.GetName("manufacturer")).FirstOrDefault();
+ var manufacturer = document.Descendants(UPnpNamespaces.Ud.GetName("manufacturer")).FirstOrDefault();
if (manufacturer != null)
{
deviceProperties.Manufacturer = manufacturer.Value;
}
- var manufacturerUrl = document.Descendants(uPnpNamespaces.ud.GetName("manufacturerURL")).FirstOrDefault();
+ var manufacturerUrl = document.Descendants(UPnpNamespaces.Ud.GetName("manufacturerURL")).FirstOrDefault();
if (manufacturerUrl != null)
{
deviceProperties.ManufacturerUrl = manufacturerUrl.Value;
}
- var presentationUrl = document.Descendants(uPnpNamespaces.ud.GetName("presentationURL")).FirstOrDefault();
+ var presentationUrl = document.Descendants(UPnpNamespaces.Ud.GetName("presentationURL")).FirstOrDefault();
if (presentationUrl != null)
{
deviceProperties.PresentationUrl = presentationUrl.Value;
}
- var modelUrl = document.Descendants(uPnpNamespaces.ud.GetName("modelURL")).FirstOrDefault();
+ var modelUrl = document.Descendants(UPnpNamespaces.Ud.GetName("modelURL")).FirstOrDefault();
if (modelUrl != null)
{
deviceProperties.ModelUrl = modelUrl.Value;
}
- var serialNumber = document.Descendants(uPnpNamespaces.ud.GetName("serialNumber")).FirstOrDefault();
+ var serialNumber = document.Descendants(UPnpNamespaces.Ud.GetName("serialNumber")).FirstOrDefault();
if (serialNumber != null)
{
deviceProperties.SerialNumber = serialNumber.Value;
}
- var modelDescription = document.Descendants(uPnpNamespaces.ud.GetName("modelDescription")).FirstOrDefault();
+ var modelDescription = document.Descendants(UPnpNamespaces.Ud.GetName("modelDescription")).FirstOrDefault();
if (modelDescription != null)
{
deviceProperties.ModelDescription = modelDescription.Value;
}
- var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault();
+ var icon = document.Descendants(UPnpNamespaces.Ud.GetName("icon")).FirstOrDefault();
if (icon != null)
{
deviceProperties.Icon = CreateIcon(icon);
}
- foreach (var services in document.Descendants(uPnpNamespaces.ud.GetName("serviceList")))
+ foreach (var services in document.Descendants(UPnpNamespaces.Ud.GetName("serviceList")))
{
if (services == null)
{
continue;
}
- var servicesList = services.Descendants(uPnpNamespaces.ud.GetName("service"));
+ var servicesList = services.Descendants(UPnpNamespaces.Ud.GetName("service"));
if (servicesList == null)
{
continue;
@@ -1039,12 +1176,9 @@ namespace Emby.Dlna.PlayTo
}
}
- return new Device(deviceProperties, httpClient, logger, config);
+ return new Device(deviceProperties, httpClientFactory, logger);
}
- #endregion
-
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
private static DeviceIcon CreateIcon(XElement element)
{
if (element == null)
@@ -1052,14 +1186,14 @@ namespace Emby.Dlna.PlayTo
throw new ArgumentNullException(nameof(element));
}
- var mimeType = element.GetDescendantValue(uPnpNamespaces.ud.GetName("mimetype"));
- var width = element.GetDescendantValue(uPnpNamespaces.ud.GetName("width"));
- var height = element.GetDescendantValue(uPnpNamespaces.ud.GetName("height"));
- var depth = element.GetDescendantValue(uPnpNamespaces.ud.GetName("depth"));
- var url = element.GetDescendantValue(uPnpNamespaces.ud.GetName("url"));
+ var mimeType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("mimetype"));
+ var width = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("width"));
+ var height = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("height"));
+ var depth = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("depth"));
+ var url = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("url"));
- var widthValue = int.Parse(width, NumberStyles.Integer, UsCulture);
- var heightValue = int.Parse(height, NumberStyles.Integer, UsCulture);
+ var widthValue = int.Parse(width, NumberStyles.Integer, CultureInfo.InvariantCulture);
+ var heightValue = int.Parse(height, NumberStyles.Integer, CultureInfo.InvariantCulture);
return new DeviceIcon
{
@@ -1073,11 +1207,11 @@ namespace Emby.Dlna.PlayTo
private static DeviceService Create(XElement element)
{
- var type = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceType"));
- var id = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceId"));
- var scpdUrl = element.GetDescendantValue(uPnpNamespaces.ud.GetName("SCPDURL"));
- var controlURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("controlURL"));
- var eventSubURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("eventSubURL"));
+ var type = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceType"));
+ var id = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceId"));
+ var scpdUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("SCPDURL"));
+ var controlURL = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("controlURL"));
+ var eventSubURL = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("eventSubURL"));
return new DeviceService
{
@@ -1089,14 +1223,7 @@ namespace Emby.Dlna.PlayTo
};
}
- public event EventHandler<PlaybackStartEventArgs> PlaybackStart;
- public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
- public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped;
- public event EventHandler<MediaChangedEventArgs> MediaChanged;
-
- public uBaseObject CurrentMediaInfo { get; private set; }
-
- private void UpdateMediaInfo(uBaseObject mediaInfo, TRANSPORTSTATE state)
+ private void UpdateMediaInfo(UBaseObject mediaInfo, TransportState state)
{
TransportState = state;
@@ -1105,7 +1232,7 @@ namespace Emby.Dlna.PlayTo
if (previousMediaInfo == null && mediaInfo != null)
{
- if (state != TRANSPORTSTATE.STOPPED)
+ if (state != TransportState.Stopped)
{
OnPlaybackStart(mediaInfo);
}
@@ -1124,56 +1251,47 @@ namespace Emby.Dlna.PlayTo
}
}
- private void OnPlaybackStart(uBaseObject mediaInfo)
+ private void OnPlaybackStart(UBaseObject mediaInfo)
{
- PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
+ if (string.IsNullOrWhiteSpace(mediaInfo.Url))
{
- MediaInfo = mediaInfo
- });
+ return;
+ }
+
+ PlaybackStart?.Invoke(this, new PlaybackStartEventArgs(mediaInfo));
}
- private void OnPlaybackProgress(uBaseObject mediaInfo)
+ private void OnPlaybackProgress(UBaseObject mediaInfo)
{
- var mediaUrl = mediaInfo.Url;
- if (string.IsNullOrWhiteSpace(mediaUrl))
+ if (string.IsNullOrWhiteSpace(mediaInfo.Url))
{
return;
}
- PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
- {
- MediaInfo = mediaInfo
- });
+ PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs(mediaInfo));
}
- private void OnPlaybackStop(uBaseObject mediaInfo)
+ private void OnPlaybackStop(UBaseObject mediaInfo)
{
-
- PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
- {
- MediaInfo = mediaInfo
- });
+ PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs(mediaInfo));
}
- private void OnMediaChanged(uBaseObject old, uBaseObject newMedia)
+ private void OnMediaChanged(UBaseObject old, UBaseObject newMedia)
{
- MediaChanged?.Invoke(this, new MediaChangedEventArgs
- {
- OldMediaInfo = old,
- NewMediaInfo = newMedia
- });
+ MediaChanged?.Invoke(this, new MediaChangedEventArgs(old, newMedia));
}
- #region IDisposable
-
- bool _disposed;
-
+ /// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
@@ -1192,11 +1310,10 @@ namespace Emby.Dlna.PlayTo
_disposed = true;
}
- #endregion
-
+ /// <inheritdoc />
public override string ToString()
{
- return string.Format("{0} - {1}", Properties.Name, Properties.BaseUrl);
+ return string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Properties.Name, Properties.BaseUrl);
}
}
}
diff --git a/Emby.Dlna/PlayTo/DeviceInfo.cs b/Emby.Dlna/PlayTo/DeviceInfo.cs
index 9e7c04bdb..2acfff4eb 100644
--- a/Emby.Dlna/PlayTo/DeviceInfo.cs
+++ b/Emby.Dlna/PlayTo/DeviceInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using Emby.Dlna.Common;
using MediaBrowser.Model.Dlna;
@@ -6,6 +10,9 @@ namespace Emby.Dlna.PlayTo
{
public class DeviceInfo
{
+ private readonly List<DeviceService> _services = new List<DeviceService>();
+ private string _baseUrl = string.Empty;
+
public DeviceInfo()
{
Name = "Generic Device";
@@ -31,7 +38,6 @@ namespace Emby.Dlna.PlayTo
public string PresentationUrl { get; set; }
- private string _baseUrl = string.Empty;
public string BaseUrl
{
get => _baseUrl;
@@ -40,7 +46,6 @@ namespace Emby.Dlna.PlayTo
public DeviceIcon Icon { get; set; }
- private readonly List<DeviceService> _services = new List<DeviceService>();
public List<DeviceService> Services => _services;
public DeviceIdentification ToDeviceIdentification()
diff --git a/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs b/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs
new file mode 100644
index 000000000..0f7a524d6
--- /dev/null
+++ b/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs
@@ -0,0 +1,19 @@
+#pragma warning disable CS1591
+
+using System;
+
+namespace Emby.Dlna.PlayTo
+{
+ public class MediaChangedEventArgs : EventArgs
+ {
+ public MediaChangedEventArgs(UBaseObject oldMediaInfo, UBaseObject newMediaInfo)
+ {
+ OldMediaInfo = oldMediaInfo;
+ NewMediaInfo = newMediaInfo;
+ }
+
+ public UBaseObject OldMediaInfo { get; set; }
+
+ public UBaseObject NewMediaInfo { get; set; }
+ }
+}
diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs
index be86dde16..f25d8017e 100644
--- a/Emby.Dlna/PlayTo/PlayToController.cs
+++ b/Emby.Dlna/PlayTo/PlayToController.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -5,7 +9,8 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Emby.Dlna.Didl;
-using MediaBrowser.Common.Configuration;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
@@ -15,17 +20,16 @@ using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Services;
using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
+using Photo = MediaBrowser.Controller.Entities.Photo;
namespace Emby.Dlna.PlayTo
{
public class PlayToController : ISessionController, IDisposable
{
- private Device _device;
private readonly SessionInfo _session;
private readonly ISessionManager _sessionManager;
private readonly ILibraryManager _libraryManager;
@@ -36,16 +40,17 @@ namespace Emby.Dlna.PlayTo
private readonly IUserDataManager _userDataManager;
private readonly ILocalizationManager _localization;
private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IConfigurationManager _config;
private readonly IMediaEncoder _mediaEncoder;
private readonly IDeviceDiscovery _deviceDiscovery;
private readonly string _serverAddress;
private readonly string _accessToken;
- public bool IsSessionActive => !_disposed && _device != null;
+ private readonly List<PlaylistItem> _playlist = new List<PlaylistItem>();
+ private Device _device;
+ private int _currentPlaylistIndex;
- public bool SupportsMediaControl => IsSessionActive;
+ private bool _disposed;
public PlayToController(
SessionInfo session,
@@ -61,7 +66,6 @@ namespace Emby.Dlna.PlayTo
IUserDataManager userDataManager,
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
- IConfigurationManager config,
IMediaEncoder mediaEncoder)
{
_session = session;
@@ -77,22 +81,41 @@ namespace Emby.Dlna.PlayTo
_userDataManager = userDataManager;
_localization = localization;
_mediaSourceManager = mediaSourceManager;
- _config = config;
_mediaEncoder = mediaEncoder;
}
+ public bool IsSessionActive => !_disposed && _device != null;
+
+ public bool SupportsMediaControl => IsSessionActive;
+
public void Init(Device device)
{
_device = device;
_device.OnDeviceUnavailable = OnDeviceUnavailable;
- _device.PlaybackStart += _device_PlaybackStart;
- _device.PlaybackProgress += _device_PlaybackProgress;
- _device.PlaybackStopped += _device_PlaybackStopped;
- _device.MediaChanged += _device_MediaChanged;
+ _device.PlaybackStart += OnDevicePlaybackStart;
+ _device.PlaybackProgress += OnDevicePlaybackProgress;
+ _device.PlaybackStopped += OnDevicePlaybackStopped;
+ _device.MediaChanged += OnDeviceMediaChanged;
_device.Start();
- _deviceDiscovery.DeviceLeft += _deviceDiscovery_DeviceLeft;
+ _deviceDiscovery.DeviceLeft += OnDeviceDiscoveryDeviceLeft;
+ }
+
+ /*
+ * Send a message to the DLNA device to notify what is the next track in the playlist.
+ */
+ private async Task SendNextTrackMessage(int currentPlayListItemIndex, CancellationToken cancellationToken)
+ {
+ if (currentPlayListItemIndex >= 0 && currentPlayListItemIndex < _playlist.Count - 1)
+ {
+ // The current playing item is indeed in the play list and we are not yet at the end of the playlist.
+ var nextItemIndex = currentPlayListItemIndex + 1;
+ var nextItem = _playlist[nextItemIndex];
+
+ // Send the SetNextAvTransport message.
+ await _device.SetNextAvTransport(nextItem.StreamUrl, GetDlnaHeaders(nextItem), nextItem.Didl, cancellationToken).ConfigureAwait(false);
+ }
}
private void OnDeviceUnavailable()
@@ -101,36 +124,31 @@ namespace Emby.Dlna.PlayTo
{
_sessionManager.ReportSessionEnded(_session.Id);
}
- catch
+ catch (Exception ex)
{
// Could throw if the session is already gone
+ _logger.LogError(ex, "Error reporting the end of session {Id}", _session.Id);
}
}
- void _deviceDiscovery_DeviceLeft(object sender, GenericEventArgs<UpnpDeviceInfo> e)
+ private void OnDeviceDiscoveryDeviceLeft(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
var info = e.Argument;
- info.Headers.TryGetValue("NTS", out string nts);
-
- if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty;
-
- if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty;
-
- if (usn.IndexOf(_device.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1 &&
- !_disposed)
+ if (!_disposed
+ && info.Headers.TryGetValue("USN", out string usn)
+ && usn.IndexOf(_device.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1
+ && (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1
+ || (info.Headers.TryGetValue("NT", out string nt)
+ && nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1)))
{
- if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1 ||
- nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1)
- {
- OnDeviceUnavailable();
- }
+ OnDeviceUnavailable();
}
}
- async void _device_MediaChanged(object sender, MediaChangedEventArgs e)
+ private async void OnDeviceMediaChanged(object sender, MediaChangedEventArgs e)
{
- if (_disposed)
+ if (_disposed || string.IsNullOrEmpty(e.OldMediaInfo.Url))
{
return;
}
@@ -140,17 +158,29 @@ namespace Emby.Dlna.PlayTo
var streamInfo = StreamParams.ParseFromUrl(e.OldMediaInfo.Url, _libraryManager, _mediaSourceManager);
if (streamInfo.Item != null)
{
- var positionTicks = GetProgressPositionTicks(e.OldMediaInfo, streamInfo);
+ var positionTicks = GetProgressPositionTicks(streamInfo);
- ReportPlaybackStopped(e.OldMediaInfo, streamInfo, positionTicks);
+ await ReportPlaybackStopped(streamInfo, positionTicks).ConfigureAwait(false);
}
streamInfo = StreamParams.ParseFromUrl(e.NewMediaInfo.Url, _libraryManager, _mediaSourceManager);
- if (streamInfo.Item == null) return;
+ if (streamInfo.Item == null)
+ {
+ return;
+ }
- var newItemProgress = GetProgressInfo(e.NewMediaInfo, streamInfo);
+ var newItemProgress = GetProgressInfo(streamInfo);
await _sessionManager.OnPlaybackStart(newItemProgress).ConfigureAwait(false);
+
+ // Send a message to the DLNA device to notify what is the next track in the playlist.
+ var currentItemIndex = _playlist.FindIndex(item => item.StreamInfo.ItemId == streamInfo.ItemId);
+ if (currentItemIndex >= 0)
+ {
+ _currentPlaylistIndex = currentItemIndex;
+ }
+
+ await SendNextTrackMessage(currentItemIndex, CancellationToken.None);
}
catch (Exception ex)
{
@@ -158,7 +188,7 @@ namespace Emby.Dlna.PlayTo
}
}
- async void _device_PlaybackStopped(object sender, PlaybackStoppedEventArgs e)
+ private async void OnDevicePlaybackStopped(object sender, PlaybackStoppedEventArgs e)
{
if (_disposed)
{
@@ -169,11 +199,14 @@ namespace Emby.Dlna.PlayTo
{
var streamInfo = StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager);
- if (streamInfo.Item == null) return;
+ if (streamInfo.Item == null)
+ {
+ return;
+ }
- var positionTicks = GetProgressPositionTicks(e.MediaInfo, streamInfo);
+ var positionTicks = GetProgressPositionTicks(streamInfo);
- ReportPlaybackStopped(e.MediaInfo, streamInfo, positionTicks);
+ await ReportPlaybackStopped(streamInfo, positionTicks).ConfigureAwait(false);
var mediaSource = await streamInfo.GetMediaSource(CancellationToken.None).ConfigureAwait(false);
@@ -181,7 +214,7 @@ namespace Emby.Dlna.PlayTo
(_device.Duration == null ? (long?)null : _device.Duration.Value.Ticks) :
mediaSource.RunTimeTicks;
- var playedToCompletion = (positionTicks.HasValue && positionTicks.Value == 0);
+ var playedToCompletion = positionTicks.HasValue && positionTicks.Value == 0;
if (!playedToCompletion && duration.HasValue && positionTicks.HasValue)
{
@@ -197,7 +230,7 @@ namespace Emby.Dlna.PlayTo
}
else
{
- Playlist.Clear();
+ _playlist.Clear();
}
}
catch (Exception ex)
@@ -206,7 +239,7 @@ namespace Emby.Dlna.PlayTo
}
}
- private async void ReportPlaybackStopped(uBaseObject mediaInfo, StreamParams streamInfo, long? positionTicks)
+ private async Task ReportPlaybackStopped(StreamParams streamInfo, long? positionTicks)
{
try
{
@@ -216,7 +249,6 @@ namespace Emby.Dlna.PlayTo
SessionId = _session.Id,
PositionTicks = positionTicks,
MediaSourceId = streamInfo.MediaSourceId
-
}).ConfigureAwait(false);
}
catch (Exception ex)
@@ -225,7 +257,7 @@ namespace Emby.Dlna.PlayTo
}
}
- async void _device_PlaybackStart(object sender, PlaybackStartEventArgs e)
+ private async void OnDevicePlaybackStart(object sender, PlaybackStartEventArgs e)
{
if (_disposed)
{
@@ -238,7 +270,7 @@ namespace Emby.Dlna.PlayTo
if (info.Item != null)
{
- var progress = GetProgressInfo(e.MediaInfo, info);
+ var progress = GetProgressInfo(info);
await _sessionManager.OnPlaybackStart(progress).ConfigureAwait(false);
}
@@ -249,7 +281,7 @@ namespace Emby.Dlna.PlayTo
}
}
- async void _device_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
+ private async void OnDevicePlaybackProgress(object sender, PlaybackProgressEventArgs e)
{
if (_disposed)
{
@@ -269,7 +301,7 @@ namespace Emby.Dlna.PlayTo
if (info.Item != null)
{
- var progress = GetProgressInfo(e.MediaInfo, info);
+ var progress = GetProgressInfo(info);
await _sessionManager.OnPlaybackProgress(progress).ConfigureAwait(false);
}
@@ -280,7 +312,7 @@ namespace Emby.Dlna.PlayTo
}
}
- private long? GetProgressPositionTicks(uBaseObject mediaInfo, StreamParams info)
+ private long? GetProgressPositionTicks(StreamParams info)
{
var ticks = _device.Position.Ticks;
@@ -292,13 +324,13 @@ namespace Emby.Dlna.PlayTo
return ticks;
}
- private PlaybackStartInfo GetProgressInfo(uBaseObject mediaInfo, StreamParams info)
+ private PlaybackStartInfo GetProgressInfo(StreamParams info)
{
return new PlaybackStartInfo
{
ItemId = info.ItemId,
SessionId = _session.Id,
- PositionTicks = GetProgressPositionTicks(mediaInfo, info),
+ PositionTicks = GetProgressPositionTicks(info),
IsMuted = _device.IsMuted,
IsPaused = _device.IsPaused,
MediaSourceId = info.MediaSourceId,
@@ -313,11 +345,9 @@ namespace Emby.Dlna.PlayTo
};
}
- #region SendCommands
-
- public async Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
+ public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
{
- _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand);
+ _logger.LogDebug("{0} - Received PlayRequest: {1}", _session.DeviceName, command.PlayCommand);
var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId);
@@ -328,45 +358,52 @@ namespace Emby.Dlna.PlayTo
}
var startIndex = command.StartIndex ?? 0;
+ int len = items.Count - startIndex;
if (startIndex > 0)
{
- items = items.Skip(startIndex).ToList();
+ items = items.GetRange(startIndex, len);
}
- var playlist = new List<PlaylistItem>();
- var isFirst = true;
+ var playlist = new PlaylistItem[len];
+
+ // Not nullable enabled - so this is required.
+ playlist[0] = CreatePlaylistItem(
+ items[0],
+ user,
+ command.StartPositionTicks ?? 0,
+ command.MediaSourceId ?? string.Empty,
+ command.AudioStreamIndex,
+ command.SubtitleStreamIndex);
- foreach (var item in items)
+ for (int i = 1; i < len; i++)
{
- if (isFirst && command.StartPositionTicks.HasValue)
- {
- playlist.Add(CreatePlaylistItem(item, user, command.StartPositionTicks.Value, command.MediaSourceId, command.AudioStreamIndex, command.SubtitleStreamIndex));
- isFirst = false;
- }
- else
- {
- playlist.Add(CreatePlaylistItem(item, user, 0, null, null, null));
- }
+ playlist[i] = CreatePlaylistItem(items[i], user, 0, string.Empty, null, null);
}
_logger.LogDebug("{0} - Playlist created", _session.DeviceName);
if (command.PlayCommand == PlayCommand.PlayLast)
{
- Playlist.AddRange(playlist);
+ _playlist.AddRange(playlist);
}
+
if (command.PlayCommand == PlayCommand.PlayNext)
{
- Playlist.AddRange(playlist);
+ _playlist.AddRange(playlist);
}
if (!command.ControllingUserId.Equals(Guid.Empty))
{
- _sessionManager.LogSessionActivity(_session.Client, _session.ApplicationVersion, _session.DeviceId,
- _session.DeviceName, _session.RemoteEndPoint, user);
+ _sessionManager.LogSessionActivity(
+ _session.Client,
+ _session.ApplicationVersion,
+ _session.DeviceId,
+ _session.DeviceName,
+ _session.RemoteEndPoint,
+ user);
}
- await PlayItems(playlist).ConfigureAwait(false);
+ return PlayItems(playlist, cancellationToken);
}
private Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
@@ -374,7 +411,7 @@ namespace Emby.Dlna.PlayTo
switch (command.Command)
{
case PlaystateCommand.Stop:
- Playlist.Clear();
+ _playlist.Clear();
return _device.SetStop(CancellationToken.None);
case PlaystateCommand.Pause:
@@ -390,10 +427,10 @@ namespace Emby.Dlna.PlayTo
return Seek(command.SeekPositionTicks ?? 0);
case PlaystateCommand.NextTrack:
- return SetPlaylistIndex(_currentPlaylistIndex + 1);
+ return SetPlaylistIndex(_currentPlaylistIndex + 1, cancellationToken);
case PlaystateCommand.PreviousTrack:
- return SetPlaylistIndex(_currentPlaylistIndex - 1);
+ return SetPlaylistIndex(_currentPlaylistIndex - 1, cancellationToken);
}
return Task.CompletedTask;
@@ -413,8 +450,14 @@ namespace Emby.Dlna.PlayTo
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, info.SubtitleStreamIndex);
await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
+
+ // Send a message to the DLNA device to notify what is the next track in the play list.
+ var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl);
+ await SendNextTrackMessage(newItemIndex, CancellationToken.None);
+
return;
}
+
await SeekAfterTransportChange(newPosition, CancellationToken.None).ConfigureAwait(false);
}
}
@@ -429,14 +472,6 @@ namespace Emby.Dlna.PlayTo
return info.IsDirectStream;
}
- #endregion
-
- #region Playlist
-
- private int _currentPlaylistIndex;
- private readonly List<PlaylistItem> _playlist = new List<PlaylistItem>();
- private List<PlaylistItem> Playlist => _playlist;
-
private void AddItemFromId(Guid id, List<BaseItem> list)
{
var item = _libraryManager.GetItemById(id);
@@ -446,7 +481,13 @@ namespace Emby.Dlna.PlayTo
}
}
- private PlaylistItem CreatePlaylistItem(BaseItem item, User user, long startPostionTicks, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
+ private PlaylistItem CreatePlaylistItem(
+ BaseItem item,
+ User user,
+ long startPostionTicks,
+ string mediaSourceId,
+ int? audioStreamIndex,
+ int? subtitleStreamIndex)
{
var deviceInfo = _device.Properties;
@@ -454,16 +495,27 @@ namespace Emby.Dlna.PlayTo
_dlnaManager.GetDefaultProfile();
var mediaSources = item is IHasMediaSources
- ? (_mediaSourceManager.GetStaticMediaSources(item, true, user))
- : new List<MediaSourceInfo>();
+ ? _mediaSourceManager.GetStaticMediaSources(item, true, user).ToArray()
+ : Array.Empty<MediaSourceInfo>();
var playlistItem = GetPlaylistItem(item, mediaSources, profile, _session.DeviceId, mediaSourceId, audioStreamIndex, subtitleStreamIndex);
playlistItem.StreamInfo.StartPositionTicks = startPostionTicks;
playlistItem.StreamUrl = DidlBuilder.NormalizeDlnaMediaUrl(playlistItem.StreamInfo.ToUrl(_serverAddress, _accessToken));
- var itemXml = new DidlBuilder(profile, user, _imageProcessor, _serverAddress, _accessToken, _userDataManager, _localization, _mediaSourceManager, _logger, _mediaEncoder)
- .GetItemDidl(_config.GetDlnaConfiguration(), item, user, null, _session.DeviceId, new Filter(), playlistItem.StreamInfo);
+ var itemXml = new DidlBuilder(
+ profile,
+ user,
+ _imageProcessor,
+ _serverAddress,
+ _accessToken,
+ _userDataManager,
+ _localization,
+ _mediaSourceManager,
+ _logger,
+ _mediaEncoder,
+ _libraryManager)
+ .GetItemDidl(item, user, null, _session.DeviceId, new Filter(), playlistItem.StreamInfo);
playlistItem.Didl = itemXml;
@@ -477,43 +529,45 @@ namespace Emby.Dlna.PlayTo
if (streamInfo.MediaType == DlnaProfileType.Audio)
{
- return new ContentFeatureBuilder(profile)
- .BuildAudioHeader(streamInfo.Container,
- streamInfo.TargetAudioCodec.FirstOrDefault(),
- streamInfo.TargetAudioBitrate,
- streamInfo.TargetAudioSampleRate,
- streamInfo.TargetAudioChannels,
- streamInfo.TargetAudioBitDepth,
- streamInfo.IsDirectStream,
- streamInfo.RunTimeTicks ?? 0,
- streamInfo.TranscodeSeekInfo);
+ return ContentFeatureBuilder.BuildAudioHeader(
+ profile,
+ streamInfo.Container,
+ streamInfo.TargetAudioCodec.FirstOrDefault(),
+ streamInfo.TargetAudioBitrate,
+ streamInfo.TargetAudioSampleRate,
+ streamInfo.TargetAudioChannels,
+ streamInfo.TargetAudioBitDepth,
+ streamInfo.IsDirectStream,
+ streamInfo.RunTimeTicks ?? 0,
+ streamInfo.TranscodeSeekInfo);
}
if (streamInfo.MediaType == DlnaProfileType.Video)
{
- var list = new ContentFeatureBuilder(profile)
- .BuildVideoHeader(streamInfo.Container,
- streamInfo.TargetVideoCodec.FirstOrDefault(),
- streamInfo.TargetAudioCodec.FirstOrDefault(),
- streamInfo.TargetWidth,
- streamInfo.TargetHeight,
- streamInfo.TargetVideoBitDepth,
- streamInfo.TargetVideoBitrate,
- streamInfo.TargetTimestamp,
- streamInfo.IsDirectStream,
- streamInfo.RunTimeTicks ?? 0,
- streamInfo.TargetVideoProfile,
- streamInfo.TargetVideoLevel,
- streamInfo.TargetFramerate ?? 0,
- streamInfo.TargetPacketLength,
- streamInfo.TranscodeSeekInfo,
- streamInfo.IsTargetAnamorphic,
- streamInfo.IsTargetInterlaced,
- streamInfo.TargetRefFrames,
- streamInfo.TargetVideoStreamCount,
- streamInfo.TargetAudioStreamCount,
- streamInfo.TargetVideoCodecTag,
- streamInfo.IsTargetAVC);
+ var list = ContentFeatureBuilder.BuildVideoHeader(
+ profile,
+ streamInfo.Container,
+ streamInfo.TargetVideoCodec.FirstOrDefault(),
+ streamInfo.TargetAudioCodec.FirstOrDefault(),
+ streamInfo.TargetWidth,
+ streamInfo.TargetHeight,
+ streamInfo.TargetVideoBitDepth,
+ streamInfo.TargetVideoBitrate,
+ streamInfo.TargetTimestamp,
+ streamInfo.IsDirectStream,
+ streamInfo.RunTimeTicks ?? 0,
+ streamInfo.TargetVideoProfile,
+ streamInfo.TargetVideoLevel,
+ streamInfo.TargetFramerate ?? 0,
+ streamInfo.TargetPacketLength,
+ streamInfo.TranscodeSeekInfo,
+ streamInfo.IsTargetAnamorphic,
+ streamInfo.IsTargetInterlaced,
+ streamInfo.TargetRefFrames,
+ streamInfo.TargetVideoStreamCount,
+ streamInfo.TargetAudioStreamCount,
+ streamInfo.TargetVideoCodecTag,
+ streamInfo.IsTargetAVC);
return list.Count == 0 ? null : list[0];
}
@@ -521,7 +575,7 @@ namespace Emby.Dlna.PlayTo
return null;
}
- private PlaylistItem GetPlaylistItem(BaseItem item, List<MediaSourceInfo> mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
+ private PlaylistItem GetPlaylistItem(BaseItem item, MediaSourceInfo[] mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
{
if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
{
@@ -530,7 +584,7 @@ namespace Emby.Dlna.PlayTo
StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions
{
ItemId = item.Id,
- MediaSources = mediaSources.ToArray(),
+ MediaSources = mediaSources,
Profile = profile,
DeviceId = deviceId,
MaxBitrate = profile.MaxStreamingBitrate,
@@ -550,7 +604,7 @@ namespace Emby.Dlna.PlayTo
StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions
{
ItemId = item.Id,
- MediaSources = mediaSources.ToArray(),
+ MediaSources = mediaSources,
Profile = profile,
DeviceId = deviceId,
MaxBitrate = profile.MaxStreamingBitrate,
@@ -563,7 +617,7 @@ namespace Emby.Dlna.PlayTo
if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
{
- return new PlaylistItemFactory().Create((Photo)item, profile);
+ return PlaylistItemFactory.Create((Photo)item, profile);
}
throw new ArgumentException("Unrecognized item type.");
@@ -573,30 +627,34 @@ namespace Emby.Dlna.PlayTo
/// Plays the items.
/// </summary>
/// <param name="items">The items.</param>
- /// <returns></returns>
- private async Task<bool> PlayItems(IEnumerable<PlaylistItem> items)
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns><c>true</c> on success.</returns>
+ private async Task<bool> PlayItems(IEnumerable<PlaylistItem> items, CancellationToken cancellationToken = default)
{
- Playlist.Clear();
- Playlist.AddRange(items);
- _logger.LogDebug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count);
+ _playlist.Clear();
+ _playlist.AddRange(items);
+ _logger.LogDebug("{0} - Playing {1} items", _session.DeviceName, _playlist.Count);
- await SetPlaylistIndex(0).ConfigureAwait(false);
+ await SetPlaylistIndex(0, cancellationToken).ConfigureAwait(false);
return true;
}
- private async Task SetPlaylistIndex(int index)
+ private async Task SetPlaylistIndex(int index, CancellationToken cancellationToken = default)
{
- if (index < 0 || index >= Playlist.Count)
+ if (index < 0 || index >= _playlist.Count)
{
- Playlist.Clear();
- await _device.SetStop(CancellationToken.None);
+ _playlist.Clear();
+ await _device.SetStop(cancellationToken).ConfigureAwait(false);
return;
}
_currentPlaylistIndex = index;
- var currentitem = Playlist[index];
+ var currentitem = _playlist[index];
+
+ await _device.SetAvTransport(currentitem.StreamUrl, GetDlnaHeaders(currentitem), currentitem.Didl, cancellationToken).ConfigureAwait(false);
- await _device.SetAvTransport(currentitem.StreamUrl, GetDlnaHeaders(currentitem), currentitem.Didl, CancellationToken.None);
+ // Send a message to the DLNA device to notify what is the next track in the play list.
+ await SendNextTrackMessage(index, cancellationToken);
var streamInfo = currentitem.StreamInfo;
if (streamInfo.StartPositionTicks > 0 && EnableClientSideSeek(streamInfo))
@@ -605,93 +663,93 @@ namespace Emby.Dlna.PlayTo
}
}
- #endregion
-
- private bool _disposed;
-
+ /// <inheritdoc />
public void Dispose()
{
- if (!_disposed)
- {
- _disposed = true;
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- _device.PlaybackStart -= _device_PlaybackStart;
- _device.PlaybackProgress -= _device_PlaybackProgress;
- _device.PlaybackStopped -= _device_PlaybackStopped;
- _device.MediaChanged -= _device_MediaChanged;
- //_deviceDiscovery.DeviceLeft -= _deviceDiscovery_DeviceLeft;
- _device.OnDeviceUnavailable = null;
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+ if (disposing)
+ {
_device.Dispose();
}
- }
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+ _device.PlaybackStart -= OnDevicePlaybackStart;
+ _device.PlaybackProgress -= OnDevicePlaybackProgress;
+ _device.PlaybackStopped -= OnDevicePlaybackStopped;
+ _device.MediaChanged -= OnDeviceMediaChanged;
+ _deviceDiscovery.DeviceLeft -= OnDeviceDiscoveryDeviceLeft;
+ _device.OnDeviceUnavailable = null;
+ _device = null;
+
+ _disposed = true;
+ }
private Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
{
- if (Enum.TryParse(command.Name, true, out GeneralCommandType commandType))
- {
- switch (commandType)
- {
- case GeneralCommandType.VolumeDown:
- return _device.VolumeDown(cancellationToken);
- case GeneralCommandType.VolumeUp:
- return _device.VolumeUp(cancellationToken);
- case GeneralCommandType.Mute:
- return _device.Mute(cancellationToken);
- case GeneralCommandType.Unmute:
- return _device.Unmute(cancellationToken);
- case GeneralCommandType.ToggleMute:
- return _device.ToggleMute(cancellationToken);
- case GeneralCommandType.SetAudioStreamIndex:
+ switch (command.Name)
+ {
+ case GeneralCommandType.VolumeDown:
+ return _device.VolumeDown(cancellationToken);
+ case GeneralCommandType.VolumeUp:
+ return _device.VolumeUp(cancellationToken);
+ case GeneralCommandType.Mute:
+ return _device.Mute(cancellationToken);
+ case GeneralCommandType.Unmute:
+ return _device.Unmute(cancellationToken);
+ case GeneralCommandType.ToggleMute:
+ return _device.ToggleMute(cancellationToken);
+ case GeneralCommandType.SetAudioStreamIndex:
+ if (command.Arguments.TryGetValue("Index", out string index))
+ {
+ if (int.TryParse(index, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
{
- if (command.Arguments.TryGetValue("Index", out string arg))
- {
- if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var val))
- {
- return SetAudioStreamIndex(val);
- }
+ return SetAudioStreamIndex(val);
+ }
- throw new ArgumentException("Unsupported SetAudioStreamIndex value supplied.");
- }
+ throw new ArgumentException("Unsupported SetAudioStreamIndex value supplied.");
+ }
- throw new ArgumentException("SetAudioStreamIndex argument cannot be null");
- }
- case GeneralCommandType.SetSubtitleStreamIndex:
+ throw new ArgumentException("SetAudioStreamIndex argument cannot be null");
+ case GeneralCommandType.SetSubtitleStreamIndex:
+ if (command.Arguments.TryGetValue("Index", out index))
+ {
+ if (int.TryParse(index, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
{
- if (command.Arguments.TryGetValue("Index", out string arg))
- {
- if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var val))
- {
- return SetSubtitleStreamIndex(val);
- }
+ return SetSubtitleStreamIndex(val);
+ }
- throw new ArgumentException("Unsupported SetSubtitleStreamIndex value supplied.");
- }
+ throw new ArgumentException("Unsupported SetSubtitleStreamIndex value supplied.");
+ }
- throw new ArgumentException("SetSubtitleStreamIndex argument cannot be null");
- }
- case GeneralCommandType.SetVolume:
+ throw new ArgumentException("SetSubtitleStreamIndex argument cannot be null");
+ case GeneralCommandType.SetVolume:
+ if (command.Arguments.TryGetValue("Volume", out string vol))
+ {
+ if (int.TryParse(vol, NumberStyles.Integer, CultureInfo.InvariantCulture, out var volume))
{
- if (command.Arguments.TryGetValue("Volume", out string arg))
- {
- if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var volume))
- {
- return _device.SetVolume(volume, cancellationToken);
- }
+ return _device.SetVolume(volume, cancellationToken);
+ }
- throw new ArgumentException("Unsupported volume value supplied.");
- }
+ throw new ArgumentException("Unsupported volume value supplied.");
+ }
- throw new ArgumentException("Volume argument cannot be null");
- }
- default:
- return Task.CompletedTask;
- }
+ throw new ArgumentException("Volume argument cannot be null");
+ default:
+ return Task.CompletedTask;
}
-
- return Task.CompletedTask;
}
private async Task SetAudioStreamIndex(int? newIndex)
@@ -704,13 +762,17 @@ namespace Emby.Dlna.PlayTo
if (info.Item != null)
{
- var newPosition = GetProgressPositionTicks(media, info) ?? 0;
+ var newPosition = GetProgressPositionTicks(info) ?? 0;
var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null;
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, newIndex, info.SubtitleStreamIndex);
await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
+ // Send a message to the DLNA device to notify what is the next track in the play list.
+ var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl);
+ await SendNextTrackMessage(newItemIndex, CancellationToken.None);
+
if (EnableClientSideSeek(newItem.StreamInfo))
{
await SeekAfterTransportChange(newPosition, CancellationToken.None).ConfigureAwait(false);
@@ -729,13 +791,17 @@ namespace Emby.Dlna.PlayTo
if (info.Item != null)
{
- var newPosition = GetProgressPositionTicks(media, info) ?? 0;
+ var newPosition = GetProgressPositionTicks(info) ?? 0;
var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null;
var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, newIndex);
await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false);
+ // Send a message to the DLNA device to notify what is the next track in the play list.
+ var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl);
+ await SendNextTrackMessage(newItemIndex, CancellationToken.None);
+
if (EnableClientSideSeek(newItem.StreamInfo) && newPosition > 0)
{
await SeekAfterTransportChange(newPosition, CancellationToken.None).ConfigureAwait(false);
@@ -746,20 +812,80 @@ namespace Emby.Dlna.PlayTo
private async Task SeekAfterTransportChange(long positionTicks, CancellationToken cancellationToken)
{
- const int maxWait = 15000000;
- const int interval = 500;
+ const int MaxWait = 15000000;
+ const int Interval = 500;
+
var currentWait = 0;
- while (_device.TransportState != TRANSPORTSTATE.PLAYING && currentWait < maxWait)
+ while (_device.TransportState != TransportState.Playing && currentWait < MaxWait)
{
- await Task.Delay(interval).ConfigureAwait(false);
- currentWait += interval;
+ await Task.Delay(Interval, cancellationToken).ConfigureAwait(false);
+ currentWait += Interval;
}
await _device.Seek(TimeSpan.FromTicks(positionTicks), cancellationToken).ConfigureAwait(false);
}
+ private static int? GetIntValue(IReadOnlyDictionary<string, string> values, string name)
+ {
+ var value = values.GetValueOrDefault(name);
+
+ if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return null;
+ }
+
+ private static long GetLongValue(IReadOnlyDictionary<string, string> values, string name)
+ {
+ var value = values.GetValueOrDefault(name);
+
+ if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return 0;
+ }
+
+ /// <inheritdoc />
+ public Task SendMessage<T>(SessionMessageType name, Guid messageId, T data, CancellationToken cancellationToken)
+ {
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
+ if (_device == null)
+ {
+ return Task.CompletedTask;
+ }
+
+ if (name == SessionMessageType.Play)
+ {
+ return SendPlayCommand(data as PlayRequest, cancellationToken);
+ }
+
+ if (name == SessionMessageType.Playstate)
+ {
+ return SendPlaystateCommand(data as PlaystateRequest, cancellationToken);
+ }
+
+ if (name == SessionMessageType.GeneralCommand)
+ {
+ return SendGeneralCommand(data as GeneralCommand, cancellationToken);
+ }
+
+ // Not supported or needed right now
+ return Task.CompletedTask;
+ }
+
private class StreamParams
{
+ private MediaSourceInfo mediaSource;
+ private IMediaSourceManager _mediaSourceManager;
+
public Guid ItemId { get; set; }
public bool IsDirectStream { get; set; }
@@ -771,21 +897,20 @@ namespace Emby.Dlna.PlayTo
public int? SubtitleStreamIndex { get; set; }
public string DeviceProfileId { get; set; }
+
public string DeviceId { get; set; }
public string MediaSourceId { get; set; }
+
public string LiveStreamId { get; set; }
public BaseItem Item { get; set; }
- private MediaSourceInfo MediaSource;
-
- private IMediaSourceManager _mediaSourceManager;
public async Task<MediaSourceInfo> GetMediaSource(CancellationToken cancellationToken)
{
- if (MediaSource != null)
+ if (mediaSource != null)
{
- return MediaSource;
+ return mediaSource;
}
var hasMediaSources = Item as IHasMediaSources;
@@ -795,9 +920,12 @@ namespace Emby.Dlna.PlayTo
return null;
}
- MediaSource = await _mediaSourceManager.GetMediaSource(Item, MediaSourceId, LiveStreamId, false, cancellationToken).ConfigureAwait(false);
+ if (_mediaSourceManager != null)
+ {
+ mediaSource = await _mediaSourceManager.GetMediaSource(Item, MediaSourceId, LiveStreamId, false, cancellationToken).ConfigureAwait(false);
+ }
- return MediaSource;
+ return mediaSource;
}
private static Guid GetItemId(string url)
@@ -809,16 +937,16 @@ namespace Emby.Dlna.PlayTo
var parts = url.Split('/');
- for (var i = 0; i < parts.Length; i++)
+ for (var i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (string.Equals(part, "audio", StringComparison.OrdinalIgnoreCase) ||
string.Equals(part, "videos", StringComparison.OrdinalIgnoreCase))
{
- if (parts.Length > i + 1)
+ if (Guid.TryParse(parts[i + 1], out var result))
{
- return Guid.Parse(parts[i + 1]);
+ return result;
}
}
}
@@ -843,18 +971,20 @@ namespace Emby.Dlna.PlayTo
return request;
}
- var index = url.IndexOf('?');
- if (index == -1) return request;
+ var index = url.IndexOf('?', StringComparison.Ordinal);
+ if (index == -1)
+ {
+ return request;
+ }
var query = url.Substring(index + 1);
- QueryParamCollection values = MyHttpUtility.ParseQueryString(query);
-
- request.DeviceProfileId = values.Get("DeviceProfileId");
- request.DeviceId = values.Get("DeviceId");
- request.MediaSourceId = values.Get("MediaSourceId");
- request.LiveStreamId = values.Get("LiveStreamId");
- request.IsDirectStream = string.Equals("true", values.Get("Static"), StringComparison.OrdinalIgnoreCase);
+ Dictionary<string, string> values = QueryHelpers.ParseQuery(query).ToDictionary(kv => kv.Key, kv => kv.Value.ToString());
+ request.DeviceProfileId = values.GetValueOrDefault("DeviceProfileId");
+ request.DeviceId = values.GetValueOrDefault("DeviceId");
+ request.MediaSourceId = values.GetValueOrDefault("MediaSourceId");
+ request.LiveStreamId = values.GetValueOrDefault("LiveStreamId");
+ request.IsDirectStream = string.Equals("true", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase);
request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex");
request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex");
request.StartPositionTicks = GetLongValue(values, "StartPositionTicks");
@@ -866,58 +996,5 @@ namespace Emby.Dlna.PlayTo
return request;
}
}
-
- private static int? GetIntValue(QueryParamCollection values, string name)
- {
- var value = values.Get(name);
-
- if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return null;
- }
-
- private static long GetLongValue(QueryParamCollection values, string name)
- {
- var value = values.Get(name);
-
- if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return 0;
- }
-
- public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
- {
- if (_disposed)
- {
- throw new ObjectDisposedException(GetType().Name);
- }
-
- if (_device == null)
- {
- return Task.CompletedTask;
- }
-
- if (string.Equals(name, "Play", StringComparison.OrdinalIgnoreCase))
- {
- return SendPlayCommand(data as PlayRequest, cancellationToken);
- }
- if (string.Equals(name, "PlayState", StringComparison.OrdinalIgnoreCase))
- {
- return SendPlaystateCommand(data as PlaystateRequest, cancellationToken);
- }
- if (string.Equals(name, "GeneralCommand", StringComparison.OrdinalIgnoreCase))
- {
- return SendGeneralCommand(data as GeneralCommand, cancellationToken);
- }
-
- // Not supported or needed right now
- return Task.CompletedTask;
- }
}
}
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index 28e70d046..7927f5f8f 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -1,9 +1,15 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
using System.Linq;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
@@ -12,15 +18,13 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.PlayTo
{
- class PlayToManager : IDisposable
+ public sealed class PlayToManager : IDisposable
{
private readonly ILogger _logger;
private readonly ISessionManager _sessionManager;
@@ -30,7 +34,7 @@ namespace Emby.Dlna.PlayTo
private readonly IDlnaManager _dlnaManager;
private readonly IServerApplicationHost _appHost;
private readonly IImageProcessor _imageProcessor;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerConfigurationManager _config;
private readonly IUserDataManager _userDataManager;
private readonly ILocalizationManager _localization;
@@ -43,7 +47,7 @@ namespace Emby.Dlna.PlayTo
private SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
- public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, IServerConfigurationManager config, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder)
+ public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClientFactory httpClientFactory, IServerConfigurationManager config, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder)
{
_logger = logger;
_sessionManager = sessionManager;
@@ -53,7 +57,7 @@ namespace Emby.Dlna.PlayTo
_appHost = appHost;
_imageProcessor = imageProcessor;
_deviceDiscovery = deviceDiscovery;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_config = config;
_userDataManager = userDataManager;
_localization = localization;
@@ -63,10 +67,10 @@ namespace Emby.Dlna.PlayTo
public void Start()
{
- _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
+ _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered;
}
- async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
+ private async void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
if (_disposed)
{
@@ -75,17 +79,20 @@ namespace Emby.Dlna.PlayTo
var info = e.Argument;
- if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty;
-
- if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty;
+ if (!info.Headers.TryGetValue("USN", out string usn))
+ {
+ usn = string.Empty;
+ }
- string location = info.Location.ToString();
+ if (!info.Headers.TryGetValue("NT", out string nt))
+ {
+ nt = string.Empty;
+ }
// It has to report that it's a media renderer
- if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 &&
- nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1)
+ if (!usn.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase)
+ && !nt.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase))
{
- //_logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location);
return;
}
@@ -105,11 +112,10 @@ namespace Emby.Dlna.PlayTo
return;
}
- await AddDevice(info, location, cancellationToken).ConfigureAwait(false);
+ await AddDevice(info, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
-
}
catch (Exception ex)
{
@@ -121,81 +127,88 @@ namespace Emby.Dlna.PlayTo
}
}
- private string GetUuid(string usn)
+ internal static string GetUuid(string usn)
{
- var found = false;
- var index = usn.IndexOf("uuid:", StringComparison.OrdinalIgnoreCase);
- if (index != -1)
+ const string UuidStr = "uuid:";
+ const string UuidColonStr = "::";
+
+ var index = usn.IndexOf(UuidStr, StringComparison.OrdinalIgnoreCase);
+ if (index == -1)
{
- usn = usn.Substring(index);
- found = true;
+ return usn.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
- index = usn.IndexOf("::", StringComparison.OrdinalIgnoreCase);
+
+ ReadOnlySpan<char> tmp = usn.AsSpan()[(index + UuidStr.Length)..];
+
+ index = tmp.IndexOf(UuidColonStr, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
- usn = usn.Substring(0, index);
+ tmp = tmp[..index];
}
- if (found)
+ index = tmp.IndexOf('{');
+ if (index != -1)
{
- return usn;
+ int endIndex = tmp.IndexOf('}');
+ if (endIndex != -1)
+ {
+ tmp = tmp[(index + 1)..endIndex];
+ }
}
- return usn.GetMD5().ToString("N");
+ return tmp.ToString();
}
- private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken)
+ private async Task AddDevice(UpnpDeviceInfo info, CancellationToken cancellationToken)
{
var uri = info.Location;
- _logger.LogDebug("Attempting to create PlayToController from location {0}", location);
+ _logger.LogDebug("Attempting to create PlayToController from location {0}", uri);
- _logger.LogDebug("Logging session activity from location {0}", location);
if (info.Headers.TryGetValue("USN", out string uuid))
{
uuid = GetUuid(uuid);
}
else
{
- uuid = location.GetMD5().ToString("N");
+ uuid = uri.ToString().GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
- var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersion, uuid, null, uri.OriginalString, null);
+ var sessionInfo = await _sessionManager
+ .LogSessionActivity("DLNA", _appHost.ApplicationVersionString, uuid, null, uri.OriginalString, null)
+ .ConfigureAwait(false);
var controller = sessionInfo.SessionControllers.OfType<PlayToController>().FirstOrDefault();
if (controller == null)
{
- var device = await Device.CreateuPnpDeviceAsync(uri, _httpClient, _config, _logger, cancellationToken).ConfigureAwait(false);
+ var device = await Device.CreateuPnpDeviceAsync(uri, _httpClientFactory, _logger, cancellationToken).ConfigureAwait(false);
+ if (device == null)
+ {
+ _logger.LogError("Ignoring device as xml response is invalid.");
+ return;
+ }
string deviceName = device.Properties.Name;
_sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName);
- string serverAddress;
- if (info.LocalIpAddress == null || info.LocalIpAddress.Equals(IpAddressInfo.Any) || info.LocalIpAddress.Equals(IpAddressInfo.IPv6Any))
- {
- serverAddress = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- }
- else
- {
- serverAddress = _appHost.GetLocalApiUrl(info.LocalIpAddress);
- }
-
- controller = new PlayToController(sessionInfo,
- _sessionManager,
- _libraryManager,
- _logger,
- _dlnaManager,
- _userManager,
- _imageProcessor,
- serverAddress,
- null,
- _deviceDiscovery,
- _userDataManager,
- _localization,
- _mediaSourceManager,
- _config,
- _mediaEncoder);
+ string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress);
+
+ controller = new PlayToController(
+ sessionInfo,
+ _sessionManager,
+ _libraryManager,
+ _logger,
+ _dlnaManager,
+ _userManager,
+ _imageProcessor,
+ serverAddress,
+ null,
+ _deviceDiscovery,
+ _userDataManager,
+ _localization,
+ _mediaSourceManager,
+ _mediaEncoder);
sessionInfo.AddController(controller);
@@ -208,17 +221,17 @@ namespace Emby.Dlna.PlayTo
{
PlayableMediaTypes = profile.GetSupportedMediaTypes(),
- SupportedCommands = new string[]
+ SupportedCommands = new[]
{
- GeneralCommandType.VolumeDown.ToString(),
- GeneralCommandType.VolumeUp.ToString(),
- GeneralCommandType.Mute.ToString(),
- GeneralCommandType.Unmute.ToString(),
- GeneralCommandType.ToggleMute.ToString(),
- GeneralCommandType.SetVolume.ToString(),
- GeneralCommandType.SetAudioStreamIndex.ToString(),
- GeneralCommandType.SetSubtitleStreamIndex.ToString(),
- GeneralCommandType.PlayMediaSource.ToString()
+ GeneralCommandType.VolumeDown,
+ GeneralCommandType.VolumeUp,
+ GeneralCommandType.Mute,
+ GeneralCommandType.Unmute,
+ GeneralCommandType.ToggleMute,
+ GeneralCommandType.SetVolume,
+ GeneralCommandType.SetAudioStreamIndex,
+ GeneralCommandType.SetSubtitleStreamIndex,
+ GeneralCommandType.PlayMediaSource
},
SupportsMediaControl = true
@@ -228,19 +241,23 @@ namespace Emby.Dlna.PlayTo
}
}
+ /// <inheritdoc />
public void Dispose()
{
- _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
+ _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered;
try
{
_disposeCancellationTokenSource.Cancel();
}
- catch
+ catch (Exception ex)
{
-
+ _logger.LogDebug(ex, "Error while disposing PlayToManager");
}
+ _sessionLock.Dispose();
+ _disposeCancellationTokenSource.Dispose();
+
_disposed = true;
}
}
diff --git a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs
index ffa56419b..c95d8b1e8 100644
--- a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs
+++ b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs
@@ -1,9 +1,16 @@
+#pragma warning disable CS1591
+
using System;
namespace Emby.Dlna.PlayTo
{
public class PlaybackProgressEventArgs : EventArgs
{
- public uBaseObject MediaInfo { get; set; }
+ public PlaybackProgressEventArgs(UBaseObject mediaInfo)
+ {
+ MediaInfo = mediaInfo;
+ }
+
+ public UBaseObject MediaInfo { get; set; }
}
}
diff --git a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs
index 8cd8b47ac..619c861ed 100644
--- a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs
+++ b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs
@@ -1,9 +1,16 @@
+#pragma warning disable CS1591
+
using System;
namespace Emby.Dlna.PlayTo
{
public class PlaybackStartEventArgs : EventArgs
{
- public uBaseObject MediaInfo { get; set; }
+ public PlaybackStartEventArgs(UBaseObject mediaInfo)
+ {
+ MediaInfo = mediaInfo;
+ }
+
+ public UBaseObject MediaInfo { get; set; }
}
}
diff --git a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs
index 2afdc324d..d0ec25059 100644
--- a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs
+++ b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs
@@ -1,15 +1,16 @@
+#pragma warning disable CS1591
+
using System;
namespace Emby.Dlna.PlayTo
{
public class PlaybackStoppedEventArgs : EventArgs
{
- public uBaseObject MediaInfo { get; set; }
- }
+ public PlaybackStoppedEventArgs(UBaseObject mediaInfo)
+ {
+ MediaInfo = mediaInfo;
+ }
- public class MediaChangedEventArgs : EventArgs
- {
- public uBaseObject OldMediaInfo { get; set; }
- public uBaseObject NewMediaInfo { get; set; }
+ public UBaseObject MediaInfo { get; set; }
}
}
diff --git a/Emby.Dlna/PlayTo/PlaylistItem.cs b/Emby.Dlna/PlayTo/PlaylistItem.cs
index 1e62b61e9..5056e69ae 100644
--- a/Emby.Dlna/PlayTo/PlaylistItem.cs
+++ b/Emby.Dlna/PlayTo/PlaylistItem.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.PlayTo
diff --git a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs
index aceb634e3..657491303 100644
--- a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs
+++ b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs
@@ -1,4 +1,7 @@
-using System.Globalization;
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.IO;
using System.Linq;
using MediaBrowser.Controller.Entities;
@@ -7,11 +10,9 @@ using MediaBrowser.Model.Session;
namespace Emby.Dlna.PlayTo
{
- public class PlaylistItemFactory
+ public static class PlaylistItemFactory
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public PlaylistItem Create(Photo item, DeviceProfile profile)
+ public static PlaylistItem Create(Photo item, DeviceProfile profile)
{
var playlistItem = new PlaylistItem
{
diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
index 1ad99fac5..cade7b4c2 100644
--- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs
+++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
@@ -1,13 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Globalization;
-using System.IO;
+using System.Net.Http;
+using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Emby.Dlna.Common;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
namespace Emby.Dlna.PlayTo
{
@@ -16,35 +20,36 @@ namespace Emby.Dlna.PlayTo
private const string USERAGENT = "Microsoft-Windows/6.2 UPnP/1.0 Microsoft-DLNA DLNADOC/1.50";
private const string FriendlyName = "Jellyfin";
- private readonly IHttpClient _httpClient;
- private readonly IServerConfigurationManager _config;
+ private readonly IHttpClientFactory _httpClientFactory;
- public SsdpHttpClient(IHttpClient httpClient, IServerConfigurationManager config)
+ public SsdpHttpClient(IHttpClientFactory httpClientFactory)
{
- _httpClient = httpClient;
- _config = config;
+ _httpClientFactory = httpClientFactory;
}
- public async Task<XDocument> SendCommandAsync(string baseUrl,
+ public async Task<XDocument> SendCommandAsync(
+ string baseUrl,
DeviceService service,
string command,
string postData,
- bool logRequest = true,
- string header = null)
+ string header = null,
+ CancellationToken cancellationToken = default)
{
- var cancellationToken = CancellationToken.None;
-
- using (var response = await PostSoapDataAsync(NormalizeServiceUrl(baseUrl, service.ControlUrl), "\"" + service.ServiceType + "#" + command + "\"", postData, header, logRequest, cancellationToken)
- .ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- using (var reader = new StreamReader(stream, Encoding.UTF8))
- {
- return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace);
- }
- }
- }
+ var url = NormalizeServiceUrl(baseUrl, service.ControlUrl);
+ using var response = await PostSoapDataAsync(
+ url,
+ $"\"{service.ServiceType}#{command}\"",
+ postData,
+ header,
+ cancellationToken)
+ .ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ return await XDocument.LoadAsync(
+ stream,
+ LoadOptions.None,
+ cancellationToken).ConfigureAwait(false);
}
private static string NormalizeServiceUrl(string baseUrl, string serviceUrl)
@@ -55,110 +60,82 @@ namespace Emby.Dlna.PlayTo
return serviceUrl;
}
- if (!serviceUrl.StartsWith("/"))
+ if (!serviceUrl.StartsWith('/'))
+ {
serviceUrl = "/" + serviceUrl;
+ }
return baseUrl + serviceUrl;
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public async Task SubscribeAsync(string url,
+ public async Task SubscribeAsync(
+ string url,
string ip,
int port,
string localIp,
int eventport,
int timeOut = 3600)
{
- var options = new HttpRequestOptions
- {
- Url = url,
- UserAgent = USERAGENT,
- LogErrorResponseBody = true,
- BufferContent = false,
-
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true
- };
-
- options.RequestHeaders["HOST"] = ip + ":" + port.ToString(_usCulture);
- options.RequestHeaders["CALLBACK"] = "<" + localIp + ":" + eventport.ToString(_usCulture) + ">";
- options.RequestHeaders["NT"] = "upnp:event";
- options.RequestHeaders["TIMEOUT"] = "Second-" + timeOut.ToString(_usCulture);
-
- using (await _httpClient.SendAsync(options, "SUBSCRIBE").ConfigureAwait(false))
- {
-
- }
+ using var options = new HttpRequestMessage(new HttpMethod("SUBSCRIBE"), url);
+ options.Headers.UserAgent.ParseAdd(USERAGENT);
+ options.Headers.TryAddWithoutValidation("HOST", ip + ":" + port.ToString(CultureInfo.InvariantCulture));
+ options.Headers.TryAddWithoutValidation("CALLBACK", "<" + localIp + ":" + eventport.ToString(CultureInfo.InvariantCulture) + ">");
+ options.Headers.TryAddWithoutValidation("NT", "upnp:event");
+ options.Headers.TryAddWithoutValidation("TIMEOUT", "Second-" + timeOut.ToString(CultureInfo.InvariantCulture));
+
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(options, HttpCompletionOption.ResponseHeadersRead)
+ .ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
}
public async Task<XDocument> GetDataAsync(string url, CancellationToken cancellationToken)
{
- var options = new HttpRequestOptions
+ using var options = new HttpRequestMessage(HttpMethod.Get, url);
+ options.Headers.UserAgent.ParseAdd(USERAGENT);
+ options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName);
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ try
{
- Url = url,
- UserAgent = USERAGENT,
- LogErrorResponseBody = true,
- BufferContent = false,
-
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true,
-
- CancellationToken = cancellationToken
- };
-
- options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName;
-
- using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
+ return await XDocument.LoadAsync(
+ stream,
+ LoadOptions.None,
+ cancellationToken).ConfigureAwait(false);
+ }
+ catch
{
- using (var stream = response.Content)
- {
- using (var reader = new StreamReader(stream, Encoding.UTF8))
- {
- return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace);
- }
- }
+ return null;
}
}
- private Task<HttpResponseInfo> PostSoapDataAsync(string url,
+ private async Task<HttpResponseMessage> PostSoapDataAsync(
+ string url,
string soapAction,
string postData,
string header,
- bool logRequest,
CancellationToken cancellationToken)
{
- if (!soapAction.StartsWith("\""))
- soapAction = "\"" + soapAction + "\"";
-
- var options = new HttpRequestOptions
+ if (soapAction[0] != '\"')
{
- Url = url,
- UserAgent = USERAGENT,
- LogRequest = logRequest || _config.GetDlnaConfiguration().EnableDebugLog,
- LogErrorResponseBody = true,
- BufferContent = false,
-
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true,
-
- CancellationToken = cancellationToken
- };
+ soapAction = $"\"{soapAction}\"";
+ }
- options.RequestHeaders["SOAPAction"] = soapAction;
- options.RequestHeaders["Pragma"] = "no-cache";
- options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName;
+ using var options = new HttpRequestMessage(HttpMethod.Post, url);
+ options.Headers.UserAgent.ParseAdd(USERAGENT);
+ options.Headers.TryAddWithoutValidation("SOAPACTION", soapAction);
+ options.Headers.TryAddWithoutValidation("Pragma", "no-cache");
+ options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName);
if (!string.IsNullOrEmpty(header))
{
- options.RequestHeaders["contentFeatures.dlna.org"] = header;
+ options.Headers.TryAddWithoutValidation("contentFeatures.dlna.org", header);
}
- options.RequestContentType = "text/xml";
- options.AppendCharsetToMimeType = true;
- options.RequestContent = postData;
+ options.Content = new StringContent(postData, Encoding.UTF8, MediaTypeNames.Text.Xml);
- return _httpClient.Post(options);
+ return await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
}
}
diff --git a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs b/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs
deleted file mode 100644
index 9f1690b04..000000000
--- a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace Emby.Dlna.PlayTo
-{
- public enum TRANSPORTSTATE
- {
- STOPPED,
- PLAYING,
- TRANSITIONING,
- PAUSED_PLAYBACK,
- PAUSED
- }
-}
diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs
index b96fa43e5..b58669355 100644
--- a/Emby.Dlna/PlayTo/TransportCommands.cs
+++ b/Emby.Dlna/PlayTo/TransportCommands.cs
@@ -1,5 +1,8 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Emby.Dlna.Common;
@@ -9,36 +12,28 @@ namespace Emby.Dlna.PlayTo
{
public class TransportCommands
{
- private List<StateVariable> _stateVariables = new List<StateVariable>();
- public List<StateVariable> StateVariables
- {
- get => _stateVariables;
- set => _stateVariables = value;
- }
+ private const string CommandBase = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<SOAP-ENV:Body>" + "<m:{0} xmlns:m=\"{1}\">" + "{2}" + "</m:{0}>" + "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
- private List<ServiceAction> _serviceActions = new List<ServiceAction>();
- public List<ServiceAction> ServiceActions
- {
- get => _serviceActions;
- set => _serviceActions = value;
- }
+ public List<StateVariable> StateVariables { get; } = new List<StateVariable>();
+
+ public List<ServiceAction> ServiceActions { get; } = new List<ServiceAction>();
public static TransportCommands Create(XDocument document)
{
var command = new TransportCommands();
- var actionList = document.Descendants(uPnpNamespaces.svc + "actionList");
+ var actionList = document.Descendants(UPnpNamespaces.Svc + "actionList");
- foreach (var container in actionList.Descendants(uPnpNamespaces.svc + "action"))
+ foreach (var container in actionList.Descendants(UPnpNamespaces.Svc + "action"))
{
command.ServiceActions.Add(ServiceActionFromXml(container));
}
- var stateValues = document.Descendants(uPnpNamespaces.ServiceStateTable).FirstOrDefault();
+ var stateValues = document.Descendants(UPnpNamespaces.ServiceStateTable).FirstOrDefault();
if (stateValues != null)
{
- foreach (var container in stateValues.Elements(uPnpNamespaces.svc + "stateVariable"))
+ foreach (var container in stateValues.Elements(UPnpNamespaces.Svc + "stateVariable"))
{
command.StateVariables.Add(FromXml(container));
}
@@ -49,19 +44,19 @@ namespace Emby.Dlna.PlayTo
private static ServiceAction ServiceActionFromXml(XElement container)
{
- var argumentList = new List<Argument>();
+ var serviceAction = new ServiceAction
+ {
+ Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty,
+ };
- foreach (var arg in container.Descendants(uPnpNamespaces.svc + "argument"))
+ var argumentList = serviceAction.ArgumentList;
+
+ foreach (var arg in container.Descendants(UPnpNamespaces.Svc + "argument"))
{
argumentList.Add(ArgumentFromXml(arg));
}
- return new ServiceAction
- {
- Name = container.GetValue(uPnpNamespaces.svc + "name"),
-
- ArgumentList = argumentList
- };
+ return serviceAction;
}
private static Argument ArgumentFromXml(XElement container)
@@ -73,30 +68,30 @@ namespace Emby.Dlna.PlayTo
return new Argument
{
- Name = container.GetValue(uPnpNamespaces.svc + "name"),
- Direction = container.GetValue(uPnpNamespaces.svc + "direction"),
- RelatedStateVariable = container.GetValue(uPnpNamespaces.svc + "relatedStateVariable")
+ Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty,
+ Direction = container.GetValue(UPnpNamespaces.Svc + "direction") ?? string.Empty,
+ RelatedStateVariable = container.GetValue(UPnpNamespaces.Svc + "relatedStateVariable") ?? string.Empty
};
}
private static StateVariable FromXml(XElement container)
{
- var allowedValues = new List<string>();
- var element = container.Descendants(uPnpNamespaces.svc + "allowedValueList")
+ var allowedValues = Array.Empty<string>();
+ var element = container.Descendants(UPnpNamespaces.Svc + "allowedValueList")
.FirstOrDefault();
if (element != null)
{
- var values = element.Descendants(uPnpNamespaces.svc + "allowedValue");
+ var values = element.Descendants(UPnpNamespaces.Svc + "allowedValue");
- allowedValues.AddRange(values.Select(child => child.Value));
+ allowedValues = values.Select(child => child.Value).ToArray();
}
return new StateVariable
{
- Name = container.GetValue(uPnpNamespaces.svc + "name"),
- DataType = container.GetValue(uPnpNamespaces.svc + "dataType"),
- AllowedValues = allowedValues.ToArray()
+ Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty,
+ DataType = container.GetValue(UPnpNamespaces.Svc + "dataType") ?? string.Empty,
+ AllowedValues = allowedValues
};
}
@@ -106,16 +101,22 @@ namespace Emby.Dlna.PlayTo
foreach (var arg in action.ArgumentList)
{
- if (arg.Direction == "out")
+ if (string.Equals(arg.Direction, "out", StringComparison.Ordinal))
+ {
continue;
+ }
- if (arg.Name == "InstanceID")
+ if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal))
+ {
stateString += BuildArgumentXml(arg, "0");
+ }
else
+ {
stateString += BuildArgumentXml(arg, null);
+ }
}
- return string.Format(CommandBase, action.Name, xmlNamespace, stateString);
+ return string.Format(CultureInfo.InvariantCulture, CommandBase, action.Name, xmlNamespace, stateString);
}
public string BuildPost(ServiceAction action, string xmlNamesapce, object value, string commandParameter = "")
@@ -124,15 +125,22 @@ namespace Emby.Dlna.PlayTo
foreach (var arg in action.ArgumentList)
{
- if (arg.Direction == "out")
+ if (string.Equals(arg.Direction, "out", StringComparison.Ordinal))
+ {
continue;
- if (arg.Name == "InstanceID")
+ }
+
+ if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal))
+ {
stateString += BuildArgumentXml(arg, "0");
+ }
else
+ {
stateString += BuildArgumentXml(arg, value.ToString(), commandParameter);
+ }
}
- return string.Format(CommandBase, action.Name, xmlNamesapce, stateString);
+ return string.Format(CultureInfo.InvariantCulture, CommandBase, action.Name, xmlNamesapce, stateString);
}
public string BuildPost(ServiceAction action, string xmlNamesapce, object value, Dictionary<string, string> dictionary)
@@ -141,33 +149,36 @@ namespace Emby.Dlna.PlayTo
foreach (var arg in action.ArgumentList)
{
- if (arg.Name == "InstanceID")
+ if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal))
+ {
stateString += BuildArgumentXml(arg, "0");
+ }
else if (dictionary.ContainsKey(arg.Name))
+ {
stateString += BuildArgumentXml(arg, dictionary[arg.Name]);
+ }
else
+ {
stateString += BuildArgumentXml(arg, value.ToString());
+ }
}
- return string.Format(CommandBase, action.Name, xmlNamesapce, stateString);
+ return string.Format(CultureInfo.InvariantCulture, CommandBase, action.Name, xmlNamesapce, stateString);
}
- private string BuildArgumentXml(Argument argument, string value, string commandParameter = "")
+ private string BuildArgumentXml(Argument argument, string? value, string commandParameter = "")
{
var state = StateVariables.FirstOrDefault(a => string.Equals(a.Name, argument.RelatedStateVariable, StringComparison.OrdinalIgnoreCase));
if (state != null)
{
var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ??
- state.AllowedValues.FirstOrDefault() ??
- value;
+ (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : value);
- return string.Format("<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}</{0}>", argument.Name, state.DataType ?? "string", sendValue);
+ return string.Format(CultureInfo.InvariantCulture, "<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}</{0}>", argument.Name, state.DataType ?? "string", sendValue);
}
- return string.Format("<{0}>{1}</{0}>", argument.Name, value);
+ return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", argument.Name, value);
}
-
- private const string CommandBase = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<SOAP-ENV:Body>" + "<m:{0} xmlns:m=\"{1}\">" + "{2}" + "</m:{0}>" + "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
}
}
diff --git a/Emby.Dlna/PlayTo/TransportState.cs b/Emby.Dlna/PlayTo/TransportState.cs
new file mode 100644
index 000000000..2058e9dc7
--- /dev/null
+++ b/Emby.Dlna/PlayTo/TransportState.cs
@@ -0,0 +1,13 @@
+#pragma warning disable CS1591
+
+namespace Emby.Dlna.PlayTo
+{
+ public enum TransportState
+ {
+ Stopped,
+ Playing,
+ Transitioning,
+ PausedPlayback,
+ Paused
+ }
+}
diff --git a/Emby.Dlna/PlayTo/TransportStateEventArgs.cs b/Emby.Dlna/PlayTo/TransportStateEventArgs.cs
deleted file mode 100644
index 7dcd39e10..000000000
--- a/Emby.Dlna/PlayTo/TransportStateEventArgs.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System;
-
-namespace Emby.Dlna.PlayTo
-{
- public class TransportStateEventArgs : EventArgs
- {
- public TRANSPORTSTATE State { get; set; }
- }
-}
diff --git a/Emby.Dlna/PlayTo/UpnpContainer.cs b/Emby.Dlna/PlayTo/UpnpContainer.cs
index 943e0347b..05f27603f 100644
--- a/Emby.Dlna/PlayTo/UpnpContainer.cs
+++ b/Emby.Dlna/PlayTo/UpnpContainer.cs
@@ -1,25 +1,27 @@
+#pragma warning disable CS1591
+
using System;
using System.Xml.Linq;
using Emby.Dlna.Ssdp;
namespace Emby.Dlna.PlayTo
{
- public class UpnpContainer : uBaseObject
+ public class UpnpContainer : UBaseObject
{
- public static uBaseObject Create(XElement container)
+ public static UBaseObject Create(XElement container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
- return new uBaseObject
+ return new UBaseObject
{
- Id = container.GetAttributeValue(uPnpNamespaces.Id),
- ParentId = container.GetAttributeValue(uPnpNamespaces.ParentId),
- Title = container.GetValue(uPnpNamespaces.title),
- IconUrl = container.GetValue(uPnpNamespaces.Artwork),
- UpnpClass = container.GetValue(uPnpNamespaces.uClass)
+ Id = container.GetAttributeValue(UPnpNamespaces.Id),
+ ParentId = container.GetAttributeValue(UPnpNamespaces.ParentId),
+ Title = container.GetValue(UPnpNamespaces.Title),
+ IconUrl = container.GetValue(UPnpNamespaces.Artwork),
+ UpnpClass = container.GetValue(UPnpNamespaces.Class)
};
}
}
diff --git a/Emby.Dlna/PlayTo/uBaseObject.cs b/Emby.Dlna/PlayTo/uBaseObject.cs
index f29a126df..02d2da58d 100644
--- a/Emby.Dlna/PlayTo/uBaseObject.cs
+++ b/Emby.Dlna/PlayTo/uBaseObject.cs
@@ -1,8 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace Emby.Dlna.PlayTo
{
- public class uBaseObject
+ public class UBaseObject
{
public string Id { get; set; }
@@ -18,20 +23,10 @@ namespace Emby.Dlna.PlayTo
public string Url { get; set; }
- public string[] ProtocolInfo { get; set; }
+ public IReadOnlyList<string> ProtocolInfo { get; set; }
public string UpnpClass { get; set; }
- public bool Equals(uBaseObject obj)
- {
- if (obj == null)
- {
- throw new ArgumentNullException(nameof(obj));
- }
-
- return string.Equals(Id, obj.Id);
- }
-
public string MediaType
{
get
@@ -42,10 +37,12 @@ namespace Emby.Dlna.PlayTo
{
return MediaBrowser.Model.Entities.MediaType.Audio;
}
+
if (classType.IndexOf(MediaBrowser.Model.Entities.MediaType.Video, StringComparison.Ordinal) != -1)
{
return MediaBrowser.Model.Entities.MediaType.Video;
}
+
if (classType.IndexOf("image", StringComparison.Ordinal) != -1)
{
return MediaBrowser.Model.Entities.MediaType.Photo;
@@ -54,5 +51,15 @@ namespace Emby.Dlna.PlayTo
return null;
}
}
+
+ public bool Equals(UBaseObject obj)
+ {
+ if (obj == null)
+ {
+ throw new ArgumentNullException(nameof(obj));
+ }
+
+ return string.Equals(Id, obj.Id, StringComparison.Ordinal);
+ }
}
}
diff --git a/Emby.Dlna/PlayTo/uParser.cs b/Emby.Dlna/PlayTo/uParser.cs
deleted file mode 100644
index 3a0ffffd4..000000000
--- a/Emby.Dlna/PlayTo/uParser.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Xml.Linq;
-
-namespace Emby.Dlna.PlayTo
-{
- public class uParser
- {
- public static IList<uBaseObject> ParseBrowseXml(XDocument doc)
- {
- if (doc == null)
- {
- throw new ArgumentException("doc");
- }
-
- var list = new List<uBaseObject>();
-
- var document = doc.Document;
-
- if (document == null)
- return list;
-
- var item = (from result in document.Descendants("Result") select result).FirstOrDefault();
-
- if (item == null)
- return list;
-
- var uPnpResponse = XElement.Parse((string)item);
-
- var uObjects = from container in uPnpResponse.Elements(uPnpNamespaces.containers)
- select new uParserObject { Element = container };
-
- var uObjects2 = from container in uPnpResponse.Elements(uPnpNamespaces.items)
- select new uParserObject { Element = container };
-
- list.AddRange(uObjects.Concat(uObjects2).Select(CreateObjectFromXML).Where(uObject => uObject != null));
-
- return list;
- }
-
- public static uBaseObject CreateObjectFromXML(uParserObject uItem)
- {
- return UpnpContainer.Create(uItem.Element);
- }
- }
-}
diff --git a/Emby.Dlna/PlayTo/uParserObject.cs b/Emby.Dlna/PlayTo/uParserObject.cs
deleted file mode 100644
index 87a7f69c6..000000000
--- a/Emby.Dlna/PlayTo/uParserObject.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.Xml.Linq;
-
-namespace Emby.Dlna.PlayTo
-{
- public class uParserObject
- {
- public XElement Element { get; set; }
- }
-}
diff --git a/Emby.Dlna/PlayTo/uPnpNamespaces.cs b/Emby.Dlna/PlayTo/uPnpNamespaces.cs
index 7132ecd15..5042d4493 100644
--- a/Emby.Dlna/PlayTo/uPnpNamespaces.cs
+++ b/Emby.Dlna/PlayTo/uPnpNamespaces.cs
@@ -1,39 +1,67 @@
+#pragma warning disable CS1591
+
using System.Xml.Linq;
namespace Emby.Dlna.PlayTo
{
- public class uPnpNamespaces
+ public static class UPnpNamespaces
{
- public static XNamespace dc = "http://purl.org/dc/elements/1.1/";
- public static XNamespace ns = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
- public static XNamespace svc = "urn:schemas-upnp-org:service-1-0";
- public static XNamespace ud = "urn:schemas-upnp-org:device-1-0";
- public static XNamespace upnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
- public static XNamespace RenderingControl = "urn:schemas-upnp-org:service:RenderingControl:1";
- public static XNamespace AvTransport = "urn:schemas-upnp-org:service:AVTransport:1";
- public static XNamespace ContentDirectory = "urn:schemas-upnp-org:service:ContentDirectory:1";
-
- public static XName containers = ns + "container";
- public static XName items = ns + "item";
- public static XName title = dc + "title";
- public static XName creator = dc + "creator";
- public static XName artist = upnp + "artist";
- public static XName Id = "id";
- public static XName ParentId = "parentID";
- public static XName uClass = upnp + "class";
- public static XName Artwork = upnp + "albumArtURI";
- public static XName Description = dc + "description";
- public static XName LongDescription = upnp + "longDescription";
- public static XName Album = upnp + "album";
- public static XName Author = upnp + "author";
- public static XName Director = upnp + "director";
- public static XName PlayCount = upnp + "playbackCount";
- public static XName Tracknumber = upnp + "originalTrackNumber";
- public static XName Res = ns + "res";
- public static XName Duration = "duration";
- public static XName ProtocolInfo = "protocolInfo";
-
- public static XName ServiceStateTable = svc + "serviceStateTable";
- public static XName StateVariable = svc + "stateVariable";
+ public static XNamespace Dc { get; } = "http://purl.org/dc/elements/1.1/";
+
+ public static XNamespace Ns { get; } = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
+
+ public static XNamespace Svc { get; } = "urn:schemas-upnp-org:service-1-0";
+
+ public static XNamespace Ud { get; } = "urn:schemas-upnp-org:device-1-0";
+
+ public static XNamespace UPnp { get; } = "urn:schemas-upnp-org:metadata-1-0/upnp/";
+
+ public static XNamespace RenderingControl { get; } = "urn:schemas-upnp-org:service:RenderingControl:1";
+
+ public static XNamespace AvTransport { get; } = "urn:schemas-upnp-org:service:AVTransport:1";
+
+ public static XNamespace ContentDirectory { get; } = "urn:schemas-upnp-org:service:ContentDirectory:1";
+
+ public static XName Containers { get; } = Ns + "container";
+
+ public static XName Items { get; } = Ns + "item";
+
+ public static XName Title { get; } = Dc + "title";
+
+ public static XName Creator { get; } = Dc + "creator";
+
+ public static XName Artist { get; } = UPnp + "artist";
+
+ public static XName Id { get; } = "id";
+
+ public static XName ParentId { get; } = "parentID";
+
+ public static XName Class { get; } = UPnp + "class";
+
+ public static XName Artwork { get; } = UPnp + "albumArtURI";
+
+ public static XName Description { get; } = Dc + "description";
+
+ public static XName LongDescription { get; } = UPnp + "longDescription";
+
+ public static XName Album { get; } = UPnp + "album";
+
+ public static XName Author { get; } = UPnp + "author";
+
+ public static XName Director { get; } = UPnp + "director";
+
+ public static XName PlayCount { get; } = UPnp + "playbackCount";
+
+ public static XName Tracknumber { get; } = UPnp + "originalTrackNumber";
+
+ public static XName Res { get; } = Ns + "res";
+
+ public static XName Duration { get; } = "duration";
+
+ public static XName ProtocolInfo { get; } = "protocolInfo";
+
+ public static XName ServiceStateTable { get; } = Svc + "serviceStateTable";
+
+ public static XName StateVariable { get; } = Svc + "stateVariable";
}
}
diff --git a/Emby.Dlna/Profiles/DefaultProfile.cs b/Emby.Dlna/Profiles/DefaultProfile.cs
index ea50bd4a7..8eaf12ba9 100644
--- a/Emby.Dlna/Profiles/DefaultProfile.cs
+++ b/Emby.Dlna/Profiles/DefaultProfile.cs
@@ -1,3 +1,7 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Globalization;
using System.Linq;
using MediaBrowser.Model.Dlna;
@@ -8,9 +12,10 @@ namespace Emby.Dlna.Profiles
{
public DefaultProfile()
{
+ Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
Name = "Generic Device";
- ProtocolInfo = "http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*";
+ ProtocolInfo = "http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*";
Manufacturer = "Jellyfin";
ModelDescription = "UPnP/AV 1.0 Compliant Media Server";
@@ -62,14 +67,14 @@ namespace Emby.Dlna.Profiles
new DirectPlayProfile
{
// play all
- Container = "",
+ Container = string.Empty,
Type = DlnaProfileType.Video
},
new DirectPlayProfile
{
// play all
- Container = "",
+ Container = string.Empty,
Type = DlnaProfileType.Audio
}
};
@@ -162,7 +167,7 @@ namespace Emby.Dlna.Profiles
public void AddXmlRootAttribute(string name, string value)
{
- var atts = XmlRootAttributes ?? new XmlAttribute[] { };
+ var atts = XmlRootAttributes ?? System.Array.Empty<XmlAttribute>();
var list = atts.ToList();
list.Add(new XmlAttribute
diff --git a/Emby.Dlna/Profiles/DenonAvrProfile.cs b/Emby.Dlna/Profiles/DenonAvrProfile.cs
index a73885191..a5ba0f36c 100644
--- a/Emby.Dlna/Profiles/DenonAvrProfile.cs
+++ b/Emby.Dlna/Profiles/DenonAvrProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -26,7 +28,7 @@ namespace Emby.Dlna.Profiles
},
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = System.Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/DirectTvProfile.cs b/Emby.Dlna/Profiles/DirectTvProfile.cs
index 317c0976a..f6f98b07d 100644
--- a/Emby.Dlna/Profiles/DirectTvProfile.cs
+++ b/Emby.Dlna/Profiles/DirectTvProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -121,7 +123,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = System.Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs
index d501cce0d..2a7524a6a 100644
--- a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs
+++ b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -9,7 +11,7 @@ namespace Emby.Dlna.Profiles
{
Name = "Dish Hopper-Joey";
- ProtocolInfo = "http-get:*:video/mp2t:*,http-get:*:video/MP1S:*,http-get:*:video/mpeg2:*,http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:audio/mpeg:*,http-get:*:audio/mpeg3:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/mp4a-latm:*,http-get:*:image/jpeg:*";
+ ProtocolInfo = "http-get:*:video/mp2t:*,http-get:*:video/mpeg:*,http-get:*:video/MP1S:*,http-get:*:video/mpeg2:*,http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:audio/mpeg:*,http-get:*:audio/mpeg3:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/mp4a-latm:*,http-get:*:image/jpeg:*";
Identification = new DeviceIdentification
{
@@ -22,7 +24,7 @@ namespace Emby.Dlna.Profiles
{
Match = HeaderMatchType.Substring,
Name = "User-Agent",
- Value ="Zip_"
+ Value = "Zip_"
}
}
};
@@ -79,7 +81,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -122,7 +124,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -159,7 +161,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3,he-aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -175,7 +177,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -190,7 +192,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.VideoAudio,
- Conditions = new []
+ Conditions = new[]
{
// The device does not have any audio switching capabilities
new ProfileCondition
diff --git a/Emby.Dlna/Profiles/Foobar2000Profile.cs b/Emby.Dlna/Profiles/Foobar2000Profile.cs
index 947194bce..68e959770 100644
--- a/Emby.Dlna/Profiles/Foobar2000Profile.cs
+++ b/Emby.Dlna/Profiles/Foobar2000Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -70,7 +72,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = System.Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/LgTvProfile.cs b/Emby.Dlna/Profiles/LgTvProfile.cs
index 145685ab1..fbb368d3e 100644
--- a/Emby.Dlna/Profiles/LgTvProfile.cs
+++ b/Emby.Dlna/Profiles/LgTvProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -82,7 +84,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -189,7 +191,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[]
+ ResponseProfiles = new[]
{
new ResponseProfile
{
diff --git a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs
index 3f0bb4263..1a510dfec 100644
--- a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs
+++ b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -30,7 +32,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[]
+ ResponseProfiles = new[]
{
new ResponseProfile
{
diff --git a/Emby.Dlna/Profiles/MarantzProfile.cs b/Emby.Dlna/Profiles/MarantzProfile.cs
index 162e284be..24078ab29 100644
--- a/Emby.Dlna/Profiles/MarantzProfile.cs
+++ b/Emby.Dlna/Profiles/MarantzProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -35,7 +37,7 @@ namespace Emby.Dlna.Profiles
},
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = System.Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs
index 53cae4e2f..28d639b6d 100644
--- a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs
+++ b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -35,7 +38,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs
index 5f31ec484..0d536acf3 100644
--- a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs
+++ b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -136,7 +138,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/PopcornHourProfile.cs b/Emby.Dlna/Profiles/PopcornHourProfile.cs
index aefe8c44f..7fbf8c164 100644
--- a/Emby.Dlna/Profiles/PopcornHourProfile.cs
+++ b/Emby.Dlna/Profiles/PopcornHourProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -91,8 +93,8 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Codec="h264",
- Conditions = new []
+ Codec = "h264",
+ Conditions = new[]
{
new ProfileCondition(ProfileConditionType.EqualsAny, ProfileConditionValue.VideoProfile, "baseline|constrained baseline"),
new ProfileCondition
@@ -120,7 +122,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -148,7 +150,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -164,7 +166,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Audio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -180,7 +182,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Audio,
Codec = "mp3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -200,7 +202,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[]
+ ResponseProfiles = new[]
{
new ResponseProfile
{
diff --git a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs
index 51a1c8173..ddbebba2a 100644
--- a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs
+++ b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -137,7 +139,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs
index f840cfb34..aa8d434e3 100644
--- a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs
+++ b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs
index 2af1d3b50..765c12504 100644
--- a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs
+++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -147,7 +150,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -175,7 +178,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -194,7 +197,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -221,7 +224,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs
index 3de0b5192..390c8a3e4 100644
--- a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs
+++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -147,7 +150,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -175,7 +178,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -194,7 +197,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -221,7 +224,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs
index 889484bea..25adc4d02 100644
--- a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs
+++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -135,7 +138,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -163,7 +166,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -182,7 +185,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -209,7 +212,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs
index acb90bd01..0a39a5f40 100644
--- a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs
+++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -135,7 +138,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -163,7 +166,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -182,7 +185,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -209,7 +212,7 @@ namespace Emby.Dlna.Profiles
}
};
- ResponseProfiles = new ResponseProfile[] { };
+ ResponseProfiles = Array.Empty<ResponseProfile>();
}
}
}
diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs
index e1808b205..05c8ab1c1 100644
--- a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs
+++ b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -112,7 +114,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -154,7 +156,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -170,7 +172,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -189,7 +191,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -215,7 +217,7 @@ namespace Emby.Dlna.Profiles
VideoCodec = "h264,mpeg4,vc1",
AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
diff --git a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs
index f8e8faa76..9f0d82b8f 100644
--- a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs
+++ b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -11,7 +13,7 @@ namespace Emby.Dlna.Profiles
Identification = new DeviceIdentification
{
- FriendlyName = @"KDL-\d{2}[EHLNPB]X\d[01]\d.*",
+ FriendlyName = @"KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*",
Manufacturer = "Sony",
Headers = new[]
@@ -19,7 +21,7 @@ namespace Emby.Dlna.Profiles
new HttpHeaderInfo
{
Name = "X-AV-Client-Info",
- Value = @".*KDL-\d{2}[EHLNPB]X\d[01]\d.*",
+ Value = @".*KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*",
Match = HeaderMatchType.Regex
}
}
@@ -100,13 +102,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
+ OrgPn = "AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -126,13 +128,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/mpeg",
- OrgPn="AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
+ OrgPn = "AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -146,28 +148,28 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
+ OrgPn = "AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="mpeg2video",
+ VideoCodec = "mpeg2video",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "mpeg",
- VideoCodec="mpeg1video,mpeg2video",
+ VideoCodec = "mpeg1video,mpeg2video",
MimeType = "video/mpeg",
- OrgPn="MPEG_PS_NTSC,MPEG_PS_PAL",
+ OrgPn = "MPEG_PS_NTSC,MPEG_PS_PAL",
Type = DlnaProfileType.Video
}
};
@@ -178,7 +180,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -202,7 +204,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -241,7 +243,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "mpeg2video",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -273,7 +275,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -301,7 +303,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -317,7 +319,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -339,7 +341,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "mp3,mp2",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs
index 111f36e9b..dfb91817a 100644
--- a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs
+++ b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -11,7 +13,7 @@ namespace Emby.Dlna.Profiles
Identification = new DeviceIdentification
{
- FriendlyName = @"KDL-\d{2}([A-Z]X\d2\d|CX400).*",
+ FriendlyName = @"KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*",
Manufacturer = "Sony",
Headers = new[]
@@ -19,7 +21,7 @@ namespace Emby.Dlna.Profiles
new HttpHeaderInfo
{
Name = "X-AV-Client-Info",
- Value = @".*KDL-\d{2}([A-Z]X\d2\d|CX400).*",
+ Value = @".*KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*",
Match = HeaderMatchType.Regex
}
}
@@ -118,7 +120,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -141,13 +143,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
+ OrgPn = "AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -167,13 +169,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/mpeg",
- OrgPn="AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
+ OrgPn = "AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -187,28 +189,28 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
+ OrgPn = "AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="mpeg2video",
+ VideoCodec = "mpeg2video",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "mpeg",
- VideoCodec="mpeg1video,mpeg2video",
+ VideoCodec = "mpeg1video,mpeg2video",
MimeType = "video/mpeg",
- OrgPn="MPEG_PS_NTSC,MPEG_PS_PAL",
+ OrgPn = "MPEG_PS_NTSC,MPEG_PS_PAL",
Type = DlnaProfileType.Video
},
new ResponseProfile
@@ -225,7 +227,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -264,7 +266,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "mpeg2video",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -296,7 +298,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -324,7 +326,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -362,7 +364,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "mp3,mp2",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs
index d5efe4270..d59ee38d7 100644
--- a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs
+++ b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -11,7 +13,7 @@ namespace Emby.Dlna.Profiles
Identification = new DeviceIdentification
{
- FriendlyName = @"KDL-\d{2}[A-Z]X\d5(\d|G).*",
+ FriendlyName = @"KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*",
Manufacturer = "Sony",
Headers = new[]
@@ -19,7 +21,7 @@ namespace Emby.Dlna.Profiles
new HttpHeaderInfo
{
Name = "X-AV-Client-Info",
- Value = @".*KDL-\d{2}[A-Z]X\d5(\d|G).*",
+ Value = @".*KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*",
Match = HeaderMatchType.Regex
}
}
@@ -129,13 +131,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
+ OrgPn = "AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -155,13 +157,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/mpeg",
- OrgPn="AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
+ OrgPn = "AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -175,28 +177,28 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
+ OrgPn = "AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="mpeg2video",
+ VideoCodec = "mpeg2video",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "mpeg",
- VideoCodec="mpeg1video,mpeg2video",
+ VideoCodec = "mpeg1video,mpeg2video",
MimeType = "video/mpeg",
- OrgPn="MPEG_PS_NTSC,MPEG_PS_PAL",
+ OrgPn = "MPEG_PS_NTSC,MPEG_PS_PAL",
Type = DlnaProfileType.Video
},
new ResponseProfile
@@ -213,7 +215,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -280,7 +282,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "mp3,mp2",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs
index 3b0228694..73b0fd67e 100644
--- a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs
+++ b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -11,7 +13,7 @@ namespace Emby.Dlna.Profiles
Identification = new DeviceIdentification
{
- FriendlyName = @"KDL-\d{2}[WR][5689]\d{2}A.*",
+ FriendlyName = @"KDL-[0-9]{2}[WR][5689][0-9]{2}A.*",
Manufacturer = "Sony",
Headers = new[]
@@ -19,7 +21,7 @@ namespace Emby.Dlna.Profiles
new HttpHeaderInfo
{
Name = "X-AV-Client-Info",
- Value = @".*KDL-\d{2}[WR][5689]\d{2}A.*",
+ Value = @".*KDL-[0-9]{2}[WR][5689][0-9]{2}A.*",
Match = HeaderMatchType.Regex
}
}
@@ -162,7 +164,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -185,13 +187,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
+ OrgPn = "AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -211,13 +213,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/mpeg",
- OrgPn="AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
+ OrgPn = "AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -231,28 +233,28 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
+ OrgPn = "AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="mpeg2video",
+ VideoCodec = "mpeg2video",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "mpeg",
- VideoCodec="mpeg1video,mpeg2video",
+ VideoCodec = "mpeg1video,mpeg2video",
MimeType = "video/mpeg",
- OrgPn="MPEG_PS_NTSC,MPEG_PS_PAL",
+ OrgPn = "MPEG_PS_NTSC,MPEG_PS_PAL",
Type = DlnaProfileType.Video
},
new ResponseProfile
@@ -263,14 +265,13 @@ namespace Emby.Dlna.Profiles
}
};
-
CodecProfiles = new[]
{
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -298,7 +299,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "mp3,mp2",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs
index e860eae34..db8ee5750 100644
--- a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs
+++ b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -11,7 +13,7 @@ namespace Emby.Dlna.Profiles
Identification = new DeviceIdentification
{
- FriendlyName = @"(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*",
+ FriendlyName = @"(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*",
Manufacturer = "Sony",
Headers = new[]
@@ -19,7 +21,7 @@ namespace Emby.Dlna.Profiles
new HttpHeaderInfo
{
Name = "X-AV-Client-Info",
- Value = @".*(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*",
+ Value = @".*(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*",
Match = HeaderMatchType.Regex
}
}
@@ -162,7 +164,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -185,13 +187,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
+ OrgPn = "AVC_TS_HD_24_AC3_T,AVC_TS_HD_50_AC3_T,AVC_TS_HD_60_AC3_T,AVC_TS_HD_EU_T",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -211,13 +213,13 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/mpeg",
- OrgPn="AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
+ OrgPn = "AVC_TS_HD_24_AC3_ISO,AVC_TS_HD_50_AC3_ISO,AVC_TS_HD_60_AC3_ISO,AVC_TS_HD_EU_ISO",
Type = DlnaProfileType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -231,28 +233,28 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="h264",
- AudioCodec="ac3,aac,mp3",
+ VideoCodec = "h264",
+ AudioCodec = "ac3,aac,mp3",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
+ OrgPn = "AVC_TS_HD_24_AC3,AVC_TS_HD_50_AC3,AVC_TS_HD_60_AC3,AVC_TS_HD_EU",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "ts,mpegts",
- VideoCodec="mpeg2video",
+ VideoCodec = "mpeg2video",
MimeType = "video/vnd.dlna.mpeg-tts",
- OrgPn="MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
+ OrgPn = "MPEG_TS_SD_EU,MPEG_TS_SD_NA,MPEG_TS_SD_KO",
Type = DlnaProfileType.Video
},
new ResponseProfile
{
Container = "mpeg",
- VideoCodec="mpeg1video,mpeg2video",
+ VideoCodec = "mpeg1video,mpeg2video",
MimeType = "video/mpeg",
- OrgPn="MPEG_PS_NTSC,MPEG_PS_PAL",
+ OrgPn = "MPEG_PS_NTSC,MPEG_PS_PAL",
Type = DlnaProfileType.Video
},
new ResponseProfile
@@ -263,14 +265,13 @@ namespace Emby.Dlna.Profiles
}
};
-
CodecProfiles = new[]
{
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -298,7 +299,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "mp3,mp2",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/SonyPs3Profile.cs b/Emby.Dlna/Profiles/SonyPs3Profile.cs
index 88d064695..e4a7a3a59 100644
--- a/Emby.Dlna/Profiles/SonyPs3Profile.cs
+++ b/Emby.Dlna/Profiles/SonyPs3Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -50,7 +52,7 @@ namespace Emby.Dlna.Profiles
Container = "ts,mpegts",
Type = DlnaProfileType.Video,
VideoCodec = "mpeg1video,mpeg2video,h264",
- AudioCodec = "ac3,mp2,mp3,aac"
+ AudioCodec = "aac,ac3,mp2"
},
new DirectPlayProfile
{
@@ -90,7 +92,7 @@ namespace Emby.Dlna.Profiles
{
Container = "ts",
VideoCodec = "h264",
- AudioCodec = "ac3,aac,mp3",
+ AudioCodec = "aac,ac3,mp2",
Type = DlnaProfileType.Video
},
new TranscodingProfile
@@ -106,7 +108,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -131,7 +133,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -174,7 +176,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -199,7 +201,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "wmapro",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -215,7 +217,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -233,7 +235,7 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "mp4,mov",
- AudioCodec="aac",
+ AudioCodec = "aac",
MimeType = "video/mp4",
Type = DlnaProfileType.Video
},
@@ -242,7 +244,7 @@ namespace Emby.Dlna.Profiles
{
Container = "avi",
MimeType = "video/divx",
- OrgPn="AVI",
+ OrgPn = "AVI",
Type = DlnaProfileType.Video
},
diff --git a/Emby.Dlna/Profiles/SonyPs4Profile.cs b/Emby.Dlna/Profiles/SonyPs4Profile.cs
index 499cf8803..985df0c9a 100644
--- a/Emby.Dlna/Profiles/SonyPs4Profile.cs
+++ b/Emby.Dlna/Profiles/SonyPs4Profile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -50,7 +52,7 @@ namespace Emby.Dlna.Profiles
Container = "ts,mpegts",
Type = DlnaProfileType.Video,
VideoCodec = "mpeg1video,mpeg2video,h264",
- AudioCodec = "ac3,mp2,mp3,aac"
+ AudioCodec = "aac,ac3,mp2"
},
new DirectPlayProfile
{
@@ -92,7 +94,7 @@ namespace Emby.Dlna.Profiles
{
Container = "ts",
VideoCodec = "h264",
- AudioCodec = "mp3",
+ AudioCodec = "aac,ac3,mp2",
Type = DlnaProfileType.Video
},
new TranscodingProfile
@@ -108,7 +110,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -133,7 +135,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -176,7 +178,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "ac3",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -201,7 +203,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "wmapro",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -217,7 +219,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -235,7 +237,7 @@ namespace Emby.Dlna.Profiles
new ResponseProfile
{
Container = "mp4,mov",
- AudioCodec="aac",
+ AudioCodec = "aac",
MimeType = "video/mp4",
Type = DlnaProfileType.Video
},
@@ -244,7 +246,7 @@ namespace Emby.Dlna.Profiles
{
Container = "avi",
MimeType = "video/divx",
- OrgPn="AVI",
+ OrgPn = "AVI",
Type = DlnaProfileType.Video
},
diff --git a/Emby.Dlna/Profiles/WdtvLiveProfile.cs b/Emby.Dlna/Profiles/WdtvLiveProfile.cs
index bf7b1ab47..937ca0f42 100644
--- a/Emby.Dlna/Profiles/WdtvLiveProfile.cs
+++ b/Emby.Dlna/Profiles/WdtvLiveProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -18,7 +20,7 @@ namespace Emby.Dlna.Profiles
Headers = new[]
{
- new HttpHeaderInfo {Name = "User-Agent", Value = "alphanetworks", Match = HeaderMatchType.Substring},
+ new HttpHeaderInfo { Name = "User-Agent", Value = "alphanetworks", Match = HeaderMatchType.Substring },
new HttpHeaderInfo
{
Name = "User-Agent",
@@ -166,7 +168,7 @@ namespace Emby.Dlna.Profiles
{
Type = DlnaProfileType.Photo,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -191,7 +193,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -219,7 +221,7 @@ namespace Emby.Dlna.Profiles
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/XboxOneProfile.cs b/Emby.Dlna/Profiles/XboxOneProfile.cs
index 710b891e3..84d8184a2 100644
--- a/Emby.Dlna/Profiles/XboxOneProfile.cs
+++ b/Emby.Dlna/Profiles/XboxOneProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.Profiles
@@ -117,7 +119,7 @@ namespace Emby.Dlna.Profiles
Type = DlnaProfileType.Video,
Container = "mp4,mov",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -136,7 +138,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "mpeg4",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -185,7 +187,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "h264",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -234,7 +236,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.Video,
Codec = "wmv2,wmv3,vc1",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -282,7 +284,7 @@ namespace Emby.Dlna.Profiles
new CodecProfile
{
Type = CodecType.Video,
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -305,7 +307,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "ac3,wmav2,wmapro",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
@@ -321,7 +323,7 @@ namespace Emby.Dlna.Profiles
{
Type = CodecType.VideoAudio,
Codec = "aac",
- Conditions = new []
+ Conditions = new[]
{
new ProfileCondition
{
diff --git a/Emby.Dlna/Profiles/Xml/Default.xml b/Emby.Dlna/Profiles/Xml/Default.xml
index daac4135a..9460f9d5a 100644
--- a/Emby.Dlna/Profiles/Xml/Default.xml
+++ b/Emby.Dlna/Profiles/Xml/Default.xml
@@ -21,7 +21,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Denon AVR.xml b/Emby.Dlna/Profiles/Xml/Denon AVR.xml
index c76cd9a89..571786906 100644
--- a/Emby.Dlna/Profiles/Xml/Denon AVR.xml
+++ b/Emby.Dlna/Profiles/Xml/Denon AVR.xml
@@ -26,7 +26,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml b/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml
index f2ce68ab5..eea0febfd 100644
--- a/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml
+++ b/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>10</TimelineOffsetSeconds>
<RequiresPlainVideoItems>true</RequiresPlainVideoItems>
<RequiresPlainFolders>true</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml b/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml
index 5ff497560..5b299577e 100644
--- a/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml
+++ b/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml
@@ -28,7 +28,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mp2t:*,http-get:*:video/MP1S:*,http-get:*:video/mpeg2:*,http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:audio/mpeg:*,http-get:*:audio/mpeg3:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/mp4a-latm:*,http-get:*:image/jpeg:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mp2t:http-get:*:video/mpeg:*,http-get:*:video/MP1S:*,http-get:*:video/mpeg2:*,http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:audio/mpeg:*,http-get:*:audio/mpeg3:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/mp4a-latm:*,http-get:*:image/jpeg:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/LG Smart TV.xml b/Emby.Dlna/Profiles/Xml/LG Smart TV.xml
index a0f0e0ee8..20f5ba79b 100644
--- a/Emby.Dlna/Profiles/Xml/LG Smart TV.xml
+++ b/Emby.Dlna/Profiles/Xml/LG Smart TV.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>10</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml b/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml
index 55910c77f..d01e3a145 100644
--- a/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml
+++ b/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml
@@ -25,7 +25,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Marantz.xml b/Emby.Dlna/Profiles/Xml/Marantz.xml
index a6345ab3f..0cc9c86e8 100644
--- a/Emby.Dlna/Profiles/Xml/Marantz.xml
+++ b/Emby.Dlna/Profiles/Xml/Marantz.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/MediaMonkey.xml b/Emby.Dlna/Profiles/Xml/MediaMonkey.xml
index 2c2c3a1de..9d5ddc3d1 100644
--- a/Emby.Dlna/Profiles/Xml/MediaMonkey.xml
+++ b/Emby.Dlna/Profiles/Xml/MediaMonkey.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml b/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml
index 934f0550d..8f766853b 100644
--- a/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml
+++ b/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml
@@ -28,7 +28,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>10</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml b/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml
index eab220fae..aa881d014 100644
--- a/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml
+++ b/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml
@@ -21,7 +21,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml b/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml
index 3e6f56e5b..7160a9c2e 100644
--- a/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml
+++ b/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml b/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml
index 74240b843..c9b907e58 100644
--- a/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml
+++ b/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>true</RequiresPlainVideoItems>
<RequiresPlainFolders>true</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml
index f20e9fcb6..1461db311 100644
--- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml
+++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml
@@ -3,10 +3,10 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Sony Bravia (2010)</Name>
<Identification>
- <FriendlyName>KDL-\d{2}[EHLNPB]X\d[01]\d.*</FriendlyName>
+ <FriendlyName>KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*</FriendlyName>
<Manufacturer>Sony</Manufacturer>
<Headers>
- <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-\d{2}[EHLNPB]X\d[01]\d.*" match="Regex" />
+ <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*" match="Regex" />
</Headers>
</Identification>
<Manufacturer>Microsoft Corporation</Manufacturer>
diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml
index 49819ccfd..7c5f2b181 100644
--- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml
+++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml
@@ -3,10 +3,10 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Sony Bravia (2011)</Name>
<Identification>
- <FriendlyName>KDL-\d{2}([A-Z]X\d2\d|CX400).*</FriendlyName>
+ <FriendlyName>KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*</FriendlyName>
<Manufacturer>Sony</Manufacturer>
<Headers>
- <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-\d{2}([A-Z]X\d2\d|CX400).*" match="Regex" />
+ <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*" match="Regex" />
</Headers>
</Identification>
<Manufacturer>Microsoft Corporation</Manufacturer>
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml
index aaad7b342..842a8fba3 100644
--- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml
+++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml
@@ -3,10 +3,10 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Sony Bravia (2012)</Name>
<Identification>
- <FriendlyName>KDL-\d{2}[A-Z]X\d5(\d|G).*</FriendlyName>
+ <FriendlyName>KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*</FriendlyName>
<Manufacturer>Sony</Manufacturer>
<Headers>
- <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-\d{2}[A-Z]X\d5(\d|G).*" match="Regex" />
+ <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*" match="Regex" />
</Headers>
</Identification>
<Manufacturer>Microsoft Corporation</Manufacturer>
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml
index 8e2e8dbaa..f1135c3fe 100644
--- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml
+++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml
@@ -3,10 +3,10 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Sony Bravia (2013)</Name>
<Identification>
- <FriendlyName>KDL-\d{2}[WR][5689]\d{2}A.*</FriendlyName>
+ <FriendlyName>KDL-[0-9]{2}[WR][5689][0-9]{2}A.*</FriendlyName>
<Manufacturer>Sony</Manufacturer>
<Headers>
- <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-\d{2}[WR][5689]\d{2}A.*" match="Regex" />
+ <HttpHeaderInfo name="X-AV-Client-Info" value=".*KDL-[0-9]{2}[WR][5689][0-9]{2}A.*" match="Regex" />
</Headers>
</Identification>
<Manufacturer>Microsoft Corporation</Manufacturer>
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml
index 17a6135e1..85c7868c6 100644
--- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml
+++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml
@@ -3,10 +3,10 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Sony Bravia (2014)</Name>
<Identification>
- <FriendlyName>(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*</FriendlyName>
+ <FriendlyName>(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*</FriendlyName>
<Manufacturer>Sony</Manufacturer>
<Headers>
- <HttpHeaderInfo name="X-AV-Client-Info" value=".*(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*" match="Regex" />
+ <HttpHeaderInfo name="X-AV-Client-Info" value=".*(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*" match="Regex" />
</Headers>
</Identification>
<Manufacturer>Microsoft Corporation</Manufacturer>
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml
index df385135c..129b188e2 100644
--- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml
+++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
@@ -38,7 +38,7 @@
<XmlRootAttributes />
<DirectPlayProfiles>
<DirectPlayProfile container="avi" audioCodec="mp2,mp3" videoCodec="mpeg4" type="Video" />
- <DirectPlayProfile container="ts,mpegts" audioCodec="ac3,mp2,mp3,aac" videoCodec="mpeg1video,mpeg2video,h264" type="Video" />
+ <DirectPlayProfile container="ts,mpegts" audioCodec="aac,ac3,mp2" videoCodec="mpeg1video,mpeg2video,h264" type="Video" />
<DirectPlayProfile container="mpeg" audioCodec="mp2" videoCodec="mpeg1video,mpeg2video" type="Video" />
<DirectPlayProfile container="mp4" audioCodec="aac,ac3" videoCodec="h264,mpeg4" type="Video" />
<DirectPlayProfile container="aac,mp3,wav" type="Audio" />
@@ -46,7 +46,7 @@
</DirectPlayProfiles>
<TranscodingProfiles>
<TranscodingProfile container="mp3" type="Audio" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
- <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="ac3,aac,mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
+ <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="aac,ac3,mp2" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
<TranscodingProfile container="jpeg" type="Photo" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
</TranscodingProfiles>
<ContainerProfiles>
diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml
index 20f50f6b6..592119305 100644
--- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml
+++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml
@@ -29,7 +29,7 @@
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
<SonyAggregationFlags>10</SonyAggregationFlags>
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
@@ -38,7 +38,7 @@
<XmlRootAttributes />
<DirectPlayProfiles>
<DirectPlayProfile container="avi" audioCodec="mp2,mp3" videoCodec="mpeg4" type="Video" />
- <DirectPlayProfile container="ts,mpegts" audioCodec="ac3,mp2,mp3,aac" videoCodec="mpeg1video,mpeg2video,h264" type="Video" />
+ <DirectPlayProfile container="ts,mpegts" audioCodec="aac,ac3,mp2" videoCodec="mpeg1video,mpeg2video,h264" type="Video" />
<DirectPlayProfile container="mpeg" audioCodec="mp2" videoCodec="mpeg1video,mpeg2video" type="Video" />
<DirectPlayProfile container="mp4,mkv,m4v" audioCodec="aac,ac3" videoCodec="h264,mpeg4" type="Video" />
<DirectPlayProfile container="aac,mp3,wav" type="Audio" />
@@ -46,7 +46,7 @@
</DirectPlayProfiles>
<TranscodingProfiles>
<TranscodingProfile container="mp3" type="Audio" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Bytes" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
- <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
+ <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="aac,ac3,mp2" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
<TranscodingProfile container="jpeg" type="Photo" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" />
</TranscodingProfiles>
<ContainerProfiles>
diff --git a/Emby.Dlna/Profiles/Xml/WDTV Live.xml b/Emby.Dlna/Profiles/Xml/WDTV Live.xml
index 05380e33a..ccb74ee64 100644
--- a/Emby.Dlna/Profiles/Xml/WDTV Live.xml
+++ b/Emby.Dlna/Profiles/Xml/WDTV Live.xml
@@ -28,7 +28,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>5</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/Xbox One.xml b/Emby.Dlna/Profiles/Xml/Xbox One.xml
index 5f5cf1af3..26a65bbd4 100644
--- a/Emby.Dlna/Profiles/Xml/Xbox One.xml
+++ b/Emby.Dlna/Profiles/Xml/Xbox One.xml
@@ -28,7 +28,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>40</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Profiles/Xml/foobar2000.xml b/Emby.Dlna/Profiles/Xml/foobar2000.xml
index f3eedb35c..5ce75ace5 100644
--- a/Emby.Dlna/Profiles/Xml/foobar2000.xml
+++ b/Emby.Dlna/Profiles/Xml/foobar2000.xml
@@ -27,7 +27,7 @@
<MaxStaticBitrate>140000000</MaxStaticBitrate>
<MusicStreamingTranscodingBitrate>192000</MusicStreamingTranscodingBitrate>
<MaxStaticMusicBitrate xsi:nil="true" />
- <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*image/jpeg:*,http-get:*image/png:*,http-get:*image/gif:*,http-get:*image/tiff:*</ProtocolInfo>
+ <ProtocolInfo>http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*</ProtocolInfo>
<TimelineOffsetSeconds>0</TimelineOffsetSeconds>
<RequiresPlainVideoItems>false</RequiresPlainVideoItems>
<RequiresPlainFolders>false</RequiresPlainFolders>
diff --git a/Emby.Dlna/Properties/AssemblyInfo.cs b/Emby.Dlna/Properties/AssemblyInfo.cs
index 9d3a22c97..606ffcf4f 100644
--- a/Emby.Dlna/Properties/AssemblyInfo.cs
+++ b/Emby.Dlna/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
@@ -8,11 +9,12 @@ using System.Resources;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.Dlna.Tests")]
// Version information for an assembly consists of the following four values:
//
diff --git a/Emby.Dlna/Server/DescriptionXmlBuilder.cs b/Emby.Dlna/Server/DescriptionXmlBuilder.cs
index 03d8f80ab..80a45f2b2 100644
--- a/Emby.Dlna/Server/DescriptionXmlBuilder.cs
+++ b/Emby.Dlna/Server/DescriptionXmlBuilder.cs
@@ -1,11 +1,13 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Security;
using System.Text;
using Emby.Dlna.Common;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Extensions;
namespace Emby.Dlna.Server
{
@@ -13,7 +15,6 @@ namespace Emby.Dlna.Server
{
private readonly DeviceProfile _profile;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly string _serverUdn;
private readonly string _serverAddress;
private readonly string _serverName;
@@ -38,8 +39,6 @@ namespace Emby.Dlna.Server
_serverId = serverId;
}
- private static bool EnableAbsoluteUrls => false;
-
public string GetXml()
{
var builder = new StringBuilder();
@@ -63,21 +62,16 @@ namespace Emby.Dlna.Server
foreach (var att in attributes)
{
- builder.AppendFormat(" {0}=\"{1}\"", att.Name, att.Value);
+ builder.AppendFormat(CultureInfo.InvariantCulture, " {0}=\"{1}\"", att.Name, att.Value);
}
- builder.Append(">");
+ builder.Append('>');
builder.Append("<specVersion>");
builder.Append("<major>1</major>");
builder.Append("<minor>0</minor>");
builder.Append("</specVersion>");
- if (!EnableAbsoluteUrls)
- {
- builder.Append("<URLBase>" + Escape(_serverAddress) + "</URLBase>");
- }
-
AppendDeviceInfo(builder);
builder.Append("</root>");
@@ -92,86 +86,14 @@ namespace Emby.Dlna.Server
AppendIconList(builder);
- builder.Append("<presentationURL>" + Escape(_serverAddress) + "/web/index.html</presentationURL>");
+ builder.Append("<presentationURL>")
+ .Append(SecurityElement.Escape(_serverAddress))
+ .Append("/web/index.html</presentationURL>");
AppendServiceList(builder);
builder.Append("</device>");
}
- private static readonly char[] s_escapeChars = new char[]
- {
- '<',
- '>',
- '"',
- '\'',
- '&'
- };
-
- private static readonly string[] s_escapeStringPairs = new[]
- {
- "<",
- "&lt;",
- ">",
- "&gt;",
- "\"",
- "&quot;",
- "'",
- "&apos;",
- "&",
- "&amp;"
- };
-
- private static string GetEscapeSequence(char c)
- {
- int num = s_escapeStringPairs.Length;
- for (int i = 0; i < num; i += 2)
- {
- string text = s_escapeStringPairs[i];
- string result = s_escapeStringPairs[i + 1];
- if (text[0] == c)
- {
- return result;
- }
- }
- return c.ToString(CultureInfo.InvariantCulture);
- }
-
- /// <summary>Replaces invalid XML characters in a string with their valid XML equivalent.</summary>
- /// <returns>The input string with invalid characters replaced.</returns>
- /// <param name="str">The string within which to escape invalid characters. </param>
- public static string Escape(string str)
- {
- if (str == null)
- {
- return null;
- }
-
- StringBuilder stringBuilder = null;
- int length = str.Length;
- int num = 0;
- while (true)
- {
- int num2 = str.IndexOfAny(s_escapeChars, num);
- if (num2 == -1)
- {
- break;
- }
- if (stringBuilder == null)
- {
- stringBuilder = new StringBuilder();
- }
- stringBuilder.Append(str, num, num2 - num);
- stringBuilder.Append(GetEscapeSequence(str[num2]));
- num = num2 + 1;
- }
- if (stringBuilder == null)
- {
- return str;
- }
- stringBuilder.Append(str, num, length - num);
- return stringBuilder.ToString();
- }
-
private void AppendDeviceProperties(StringBuilder builder)
{
builder.Append("<dlna:X_DLNACAP/>");
@@ -181,32 +103,54 @@ namespace Emby.Dlna.Server
builder.Append("<deviceType>urn:schemas-upnp-org:device:MediaServer:1</deviceType>");
- builder.Append("<friendlyName>" + Escape(GetFriendlyName()) + "</friendlyName>");
- builder.Append("<manufacturer>" + Escape(_profile.Manufacturer ?? string.Empty) + "</manufacturer>");
- builder.Append("<manufacturerURL>" + Escape(_profile.ManufacturerUrl ?? string.Empty) + "</manufacturerURL>");
-
- builder.Append("<modelDescription>" + Escape(_profile.ModelDescription ?? string.Empty) + "</modelDescription>");
- builder.Append("<modelName>" + Escape(_profile.ModelName ?? string.Empty) + "</modelName>");
-
- builder.Append("<modelNumber>" + Escape(_profile.ModelNumber ?? string.Empty) + "</modelNumber>");
- builder.Append("<modelURL>" + Escape(_profile.ModelUrl ?? string.Empty) + "</modelURL>");
+ builder.Append("<friendlyName>")
+ .Append(SecurityElement.Escape(GetFriendlyName()))
+ .Append("</friendlyName>");
+ builder.Append("<manufacturer>")
+ .Append(SecurityElement.Escape(_profile.Manufacturer ?? string.Empty))
+ .Append("</manufacturer>");
+ builder.Append("<manufacturerURL>")
+ .Append(SecurityElement.Escape(_profile.ManufacturerUrl ?? string.Empty))
+ .Append("</manufacturerURL>");
+
+ builder.Append("<modelDescription>")
+ .Append(SecurityElement.Escape(_profile.ModelDescription ?? string.Empty))
+ .Append("</modelDescription>");
+ builder.Append("<modelName>")
+ .Append(SecurityElement.Escape(_profile.ModelName ?? string.Empty))
+ .Append("</modelName>");
+
+ builder.Append("<modelNumber>")
+ .Append(SecurityElement.Escape(_profile.ModelNumber ?? string.Empty))
+ .Append("</modelNumber>");
+ builder.Append("<modelURL>")
+ .Append(SecurityElement.Escape(_profile.ModelUrl ?? string.Empty))
+ .Append("</modelURL>");
if (string.IsNullOrEmpty(_profile.SerialNumber))
{
- builder.Append("<serialNumber>" + Escape(_serverId) + "</serialNumber>");
+ builder.Append("<serialNumber>")
+ .Append(SecurityElement.Escape(_serverId))
+ .Append("</serialNumber>");
}
else
{
- builder.Append("<serialNumber>" + Escape(_profile.SerialNumber) + "</serialNumber>");
+ builder.Append("<serialNumber>")
+ .Append(SecurityElement.Escape(_profile.SerialNumber))
+ .Append("</serialNumber>");
}
builder.Append("<UPC/>");
- builder.Append("<UDN>uuid:" + Escape(_serverUdn) + "</UDN>");
+ builder.Append("<UDN>uuid:")
+ .Append(SecurityElement.Escape(_serverUdn))
+ .Append("</UDN>");
if (!string.IsNullOrEmpty(_profile.SonyAggregationFlags))
{
- builder.Append("<av:aggregationFlags xmlns:av=\"urn:schemas-sony-com:av\">" + Escape(_profile.SonyAggregationFlags) + "</av:aggregationFlags>");
+ builder.Append("<av:aggregationFlags xmlns:av=\"urn:schemas-sony-com:av\">")
+ .Append(SecurityElement.Escape(_profile.SonyAggregationFlags))
+ .Append("</av:aggregationFlags>");
}
}
@@ -244,11 +188,21 @@ namespace Emby.Dlna.Server
{
builder.Append("<icon>");
- builder.Append("<mimetype>" + Escape(icon.MimeType ?? string.Empty) + "</mimetype>");
- builder.Append("<width>" + Escape(icon.Width.ToString(_usCulture)) + "</width>");
- builder.Append("<height>" + Escape(icon.Height.ToString(_usCulture)) + "</height>");
- builder.Append("<depth>" + Escape(icon.Depth ?? string.Empty) + "</depth>");
- builder.Append("<url>" + BuildUrl(icon.Url) + "</url>");
+ builder.Append("<mimetype>")
+ .Append(SecurityElement.Escape(icon.MimeType ?? string.Empty))
+ .Append("</mimetype>");
+ builder.Append("<width>")
+ .Append(SecurityElement.Escape(icon.Width.ToString(CultureInfo.InvariantCulture)))
+ .Append("</width>");
+ builder.Append("<height>")
+ .Append(SecurityElement.Escape(icon.Height.ToString(CultureInfo.InvariantCulture)))
+ .Append("</height>");
+ builder.Append("<depth>")
+ .Append(SecurityElement.Escape(icon.Depth ?? string.Empty))
+ .Append("</depth>");
+ builder.Append("<url>")
+ .Append(BuildUrl(icon.Url))
+ .Append("</url>");
builder.Append("</icon>");
}
@@ -264,11 +218,21 @@ namespace Emby.Dlna.Server
{
builder.Append("<service>");
- builder.Append("<serviceType>" + Escape(service.ServiceType ?? string.Empty) + "</serviceType>");
- builder.Append("<serviceId>" + Escape(service.ServiceId ?? string.Empty) + "</serviceId>");
- builder.Append("<SCPDURL>" + BuildUrl(service.ScpdUrl) + "</SCPDURL>");
- builder.Append("<controlURL>" + BuildUrl(service.ControlUrl) + "</controlURL>");
- builder.Append("<eventSubURL>" + BuildUrl(service.EventSubUrl) + "</eventSubURL>");
+ builder.Append("<serviceType>")
+ .Append(SecurityElement.Escape(service.ServiceType ?? string.Empty))
+ .Append("</serviceType>");
+ builder.Append("<serviceId>")
+ .Append(SecurityElement.Escape(service.ServiceId ?? string.Empty))
+ .Append("</serviceId>");
+ builder.Append("<SCPDURL>")
+ .Append(BuildUrl(service.ScpdUrl))
+ .Append("</SCPDURL>");
+ builder.Append("<controlURL>")
+ .Append(BuildUrl(service.ControlUrl))
+ .Append("</controlURL>");
+ builder.Append("<eventSubURL>")
+ .Append(BuildUrl(service.EventSubUrl))
+ .Append("</eventSubURL>");
builder.Append("</service>");
}
@@ -283,16 +247,9 @@ namespace Emby.Dlna.Server
return string.Empty;
}
- url = url.TrimStart('/');
-
- url = "/dlna/" + _serverUdn + "/" + url;
-
- if (EnableAbsoluteUrls)
- {
- url = _serverAddress.TrimEnd('/') + url;
- }
+ url = _serverAddress.TrimEnd('/') + "/dlna/" + _serverUdn + "/" + url.TrimStart('/');
- return Escape(url);
+ return SecurityElement.Escape(url);
}
private IEnumerable<DeviceIcon> GetIcons()
diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs
index 5f78674b8..581e4a286 100644
--- a/Emby.Dlna/Service/BaseControlHandler.cs
+++ b/Emby.Dlna/Service/BaseControlHandler.cs
@@ -1,81 +1,70 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using System.Text;
+using System.Threading.Tasks;
using System.Xml;
+using Diacritics.Extensions;
using Emby.Dlna.Didl;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.Service
{
public abstract class BaseControlHandler
{
- private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/";
-
- protected readonly IServerConfigurationManager Config;
- protected readonly ILogger _logger;
- protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
+ private const string NsSoapEnv = "http://schemas.xmlsoap.org/soap/envelope/";
- protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ protected BaseControlHandler(IServerConfigurationManager config, ILogger logger)
{
Config = config;
- _logger = logger;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ Logger = logger;
}
- public ControlResponse ProcessControlRequest(ControlRequest request)
+ protected IServerConfigurationManager Config { get; }
+
+ protected ILogger Logger { get; }
+
+ public async Task<ControlResponse> ProcessControlRequestAsync(ControlRequest request)
{
try
{
- var enableDebugLogging = Config.GetDlnaConfiguration().EnableDebugLog;
-
- if (enableDebugLogging)
- {
- LogRequest(request);
- }
-
- var response = ProcessControlRequestInternal(request);
-
- if (enableDebugLogging)
- {
- LogResponse(response);
- }
+ LogRequest(request);
+ var response = await ProcessControlRequestInternalAsync(request).ConfigureAwait(false);
+ LogResponse(response);
return response;
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error processing control request");
+ Logger.LogError(ex, "Error processing control request");
- return new ControlErrorHandler().GetResponse(ex);
+ return ControlErrorHandler.GetResponse(ex);
}
}
- private ControlResponse ProcessControlRequestInternal(ControlRequest request)
+ private async Task<ControlResponse> ProcessControlRequestInternalAsync(ControlRequest request)
{
- ControlRequestInfo requestInfo = null;
+ ControlRequestInfo? requestInfo = null;
- using (var streamReader = new StreamReader(request.InputXml))
+ using (var streamReader = new StreamReader(request.InputXml, Encoding.UTF8))
{
- var readerSettings = XmlReaderSettingsFactory.Create(false);
-
- readerSettings.CheckCharacters = false;
- readerSettings.IgnoreProcessingInstructions = true;
- readerSettings.IgnoreComments = true;
-
- using (var reader = XmlReader.Create(streamReader, readerSettings))
+ var readerSettings = new XmlReaderSettings()
{
- requestInfo = ParseRequest(reader);
- }
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true,
+ Async = true
+ };
+
+ using var reader = XmlReader.Create(streamReader, readerSettings);
+ requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false);
}
- _logger.LogDebug("Received control request {0}", requestInfo.LocalName);
-
- var result = GetResult(requestInfo.LocalName, requestInfo.Headers);
+ Logger.LogDebug("Received control request {0}", requestInfo.LocalName);
var settings = new XmlWriterSettings
{
@@ -89,17 +78,14 @@ namespace Emby.Dlna.Service
{
writer.WriteStartDocument(true);
- writer.WriteStartElement("SOAP-ENV", "Envelope", NS_SOAPENV);
- writer.WriteAttributeString(string.Empty, "encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/");
+ writer.WriteStartElement("SOAP-ENV", "Envelope", NsSoapEnv);
+ writer.WriteAttributeString(string.Empty, "encodingStyle", NsSoapEnv, "http://schemas.xmlsoap.org/soap/encoding/");
- writer.WriteStartElement("SOAP-ENV", "Body", NS_SOAPENV);
+ writer.WriteStartElement("SOAP-ENV", "Body", NsSoapEnv);
writer.WriteStartElement("u", requestInfo.LocalName + "Response", requestInfo.NamespaceURI);
- foreach (var i in result)
- {
- writer.WriteStartElement(i.Key);
- writer.WriteString(i.Value);
- writer.WriteFullEndElement();
- }
+
+ WriteResult(requestInfo.LocalName, requestInfo.Headers, writer);
+
writer.WriteFullEndElement();
writer.WriteFullEndElement();
@@ -107,25 +93,19 @@ namespace Emby.Dlna.Service
writer.WriteEndDocument();
}
- var xml = builder.ToString().Replace("xmlns:m=", "xmlns:u=");
-
- var controlResponse = new ControlResponse
- {
- Xml = xml,
- IsSuccessful = true
- };
+ var xml = builder.ToString().Replace("xmlns:m=", "xmlns:u=", StringComparison.Ordinal);
- //logger.LogDebug(xml);
+ var controlResponse = new ControlResponse(xml, true);
controlResponse.Headers.Add("EXT", string.Empty);
return controlResponse;
}
- private ControlRequestInfo ParseRequest(XmlReader reader)
+ private async Task<ControlRequestInfo> ParseRequestAsync(XmlReader reader)
{
- reader.MoveToContent();
- reader.Read();
+ await reader.MoveToContentAsync().ConfigureAwait(false);
+ await reader.ReadAsync().ConfigureAwait(false);
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
@@ -138,74 +118,78 @@ namespace Emby.Dlna.Service
{
if (!reader.IsEmptyElement)
{
- using (var subReader = reader.ReadSubtree())
- {
- return ParseBodyTag(subReader);
- }
+ using var subReader = reader.ReadSubtree();
+ return await ParseBodyTagAsync(subReader).ConfigureAwait(false);
}
else
{
- reader.Read();
+ await reader.ReadAsync().ConfigureAwait(false);
}
+
break;
}
+
default:
{
- reader.Skip();
+ await reader.SkipAsync().ConfigureAwait(false);
break;
}
}
}
else
{
- reader.Read();
+ await reader.ReadAsync().ConfigureAwait(false);
}
}
- return new ControlRequestInfo();
+ throw new EndOfStreamException("Stream ended but no body tag found.");
}
- private ControlRequestInfo ParseBodyTag(XmlReader reader)
+ private async Task<ControlRequestInfo> ParseBodyTagAsync(XmlReader reader)
{
- var result = new ControlRequestInfo();
+ string? namespaceURI = null, localName = null;
- reader.MoveToContent();
- reader.Read();
+ await reader.MoveToContentAsync().ConfigureAwait(false);
+ await reader.ReadAsync().ConfigureAwait(false);
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
- result.LocalName = reader.LocalName;
- result.NamespaceURI = reader.NamespaceURI;
+ localName = reader.LocalName;
+ namespaceURI = reader.NamespaceURI;
if (!reader.IsEmptyElement)
{
- using (var subReader = reader.ReadSubtree())
- {
- ParseFirstBodyChild(subReader, result.Headers);
- return result;
- }
+ var result = new ControlRequestInfo(localName, namespaceURI);
+ using var subReader = reader.ReadSubtree();
+ await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false);
+ return result;
}
else
{
- reader.Read();
+ await reader.ReadAsync().ConfigureAwait(false);
}
}
else
{
- reader.Read();
+ await reader.ReadAsync().ConfigureAwait(false);
}
}
- return result;
+ if (localName != null && namespaceURI != null)
+ {
+ return new ControlRequestInfo(localName, namespaceURI);
+ }
+
+ throw new EndOfStreamException("Stream ended but no control found.");
}
- private void ParseFirstBodyChild(XmlReader reader, IDictionary<string, string> headers)
+ private async Task ParseFirstBodyChildAsync(XmlReader reader, IDictionary<string, string> headers)
{
- reader.MoveToContent();
- reader.Read();
+ await reader.MoveToContentAsync().ConfigureAwait(false);
+ await reader.ReadAsync().ConfigureAwait(false);
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
@@ -213,23 +197,16 @@ namespace Emby.Dlna.Service
if (reader.NodeType == XmlNodeType.Element)
{
// TODO: Should we be doing this here, or should it be handled earlier when decoding the request?
- headers[reader.LocalName.RemoveDiacritics()] = reader.ReadElementContentAsString();
+ headers[reader.LocalName.RemoveDiacritics()] = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);
}
else
{
- reader.Read();
+ await reader.ReadAsync().ConfigureAwait(false);
}
}
}
- private class ControlRequestInfo
- {
- public string LocalName;
- public string NamespaceURI;
- public IDictionary<string, string> Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- protected abstract IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams);
+ protected abstract void WriteResult(string methodName, IReadOnlyDictionary<string, string> methodParams, XmlWriter xmlWriter);
private void LogRequest(ControlRequest request)
{
@@ -238,10 +215,7 @@ namespace Emby.Dlna.Service
return;
}
- var originalHeaders = request.Headers;
- var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
-
- _logger.LogDebug("Control request. Headers: {0}", headers);
+ Logger.LogDebug("Control request. Headers: {@Headers}", request.Headers);
}
private void LogResponse(ControlResponse response)
@@ -251,11 +225,23 @@ namespace Emby.Dlna.Service
return;
}
- var originalHeaders = response.Headers;
- var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
- //builder.Append(response.Xml);
+ Logger.LogDebug("Control response. Headers: {@Headers}\n{Xml}", response.Headers, response.Xml);
+ }
+
+ private class ControlRequestInfo
+ {
+ public ControlRequestInfo(string localName, string namespaceUri)
+ {
+ LocalName = localName;
+ NamespaceURI = namespaceUri;
+ Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
+ public string LocalName { get; set; }
+
+ public string NamespaceURI { get; set; }
- _logger.LogDebug("Control response. Headers: {0}", headers);
+ public Dictionary<string, string> Headers { get; }
}
}
}
diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs
index 5359e94c4..68fd98758 100644
--- a/Emby.Dlna/Service/BaseService.cs
+++ b/Emby.Dlna/Service/BaseService.cs
@@ -1,36 +1,36 @@
+#pragma warning disable CS1591
+
+using System.Net.Http;
using Emby.Dlna.Eventing;
-using MediaBrowser.Common.Net;
using Microsoft.Extensions.Logging;
namespace Emby.Dlna.Service
{
- public class BaseService : IEventManager
+ public class BaseService : IDlnaEventManager
{
- protected IEventManager EventManager;
- protected IHttpClient HttpClient;
- protected ILogger Logger;
-
- protected BaseService(ILogger logger, IHttpClient httpClient)
+ protected BaseService(ILogger<BaseService> logger, IHttpClientFactory httpClientFactory)
{
Logger = logger;
- HttpClient = httpClient;
-
- EventManager = new EventManager(Logger, HttpClient);
+ EventManager = new DlnaEventManager(logger, httpClientFactory);
}
+ protected IDlnaEventManager EventManager { get; }
+
+ protected ILogger Logger { get; }
+
public EventSubscriptionResponse CancelEventSubscription(string subscriptionId)
{
return EventManager.CancelEventSubscription(subscriptionId);
}
- public EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string notificationType, string timeoutString, string callbackUrl)
+ public EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string notificationType, string requestedTimeoutString, string callbackUrl)
{
- return EventManager.RenewEventSubscription(subscriptionId, notificationType, timeoutString, callbackUrl);
+ return EventManager.RenewEventSubscription(subscriptionId, notificationType, requestedTimeoutString, callbackUrl);
}
- public EventSubscriptionResponse CreateEventSubscription(string notificationType, string timeoutString, string callbackUrl)
+ public EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl)
{
- return EventManager.CreateEventSubscription(notificationType, timeoutString, callbackUrl);
+ return EventManager.CreateEventSubscription(notificationType, requestedTimeoutString, callbackUrl);
}
}
}
diff --git a/Emby.Dlna/Service/ControlErrorHandler.cs b/Emby.Dlna/Service/ControlErrorHandler.cs
index d5eb4a887..3e2cd6d2e 100644
--- a/Emby.Dlna/Service/ControlErrorHandler.cs
+++ b/Emby.Dlna/Service/ControlErrorHandler.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Text;
@@ -6,11 +8,11 @@ using Emby.Dlna.Didl;
namespace Emby.Dlna.Service
{
- public class ControlErrorHandler
+ public static class ControlErrorHandler
{
- private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/";
+ private const string NsSoapEnv = "http://schemas.xmlsoap.org/soap/envelope/";
- public ControlResponse GetResponse(Exception ex)
+ public static ControlResponse GetResponse(Exception ex)
{
var settings = new XmlWriterSettings
{
@@ -24,11 +26,11 @@ namespace Emby.Dlna.Service
{
writer.WriteStartDocument(true);
- writer.WriteStartElement("SOAP-ENV", "Envelope", NS_SOAPENV);
- writer.WriteAttributeString(string.Empty, "encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/");
+ writer.WriteStartElement("SOAP-ENV", "Envelope", NsSoapEnv);
+ writer.WriteAttributeString(string.Empty, "encodingStyle", NsSoapEnv, "http://schemas.xmlsoap.org/soap/encoding/");
- writer.WriteStartElement("SOAP-ENV", "Body", NS_SOAPENV);
- writer.WriteStartElement("SOAP-ENV", "Fault", NS_SOAPENV);
+ writer.WriteStartElement("SOAP-ENV", "Body", NsSoapEnv);
+ writer.WriteStartElement("SOAP-ENV", "Fault", NsSoapEnv);
writer.WriteElementString("faultcode", "500");
writer.WriteElementString("faultstring", ex.Message);
@@ -44,11 +46,7 @@ namespace Emby.Dlna.Service
writer.WriteEndDocument();
}
- return new ControlResponse
- {
- Xml = builder.ToString(),
- IsSuccessful = false
- };
+ return new ControlResponse(builder.ToString(), false);
}
}
}
diff --git a/Emby.Dlna/Service/ServiceXmlBuilder.cs b/Emby.Dlna/Service/ServiceXmlBuilder.cs
index bd1f0bf05..1e56d09b2 100644
--- a/Emby.Dlna/Service/ServiceXmlBuilder.cs
+++ b/Emby.Dlna/Service/ServiceXmlBuilder.cs
@@ -1,7 +1,9 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
+using System.Security;
using System.Text;
using Emby.Dlna.Common;
-using Emby.Dlna.Server;
namespace Emby.Dlna.Service
{
@@ -35,7 +37,9 @@ namespace Emby.Dlna.Service
{
builder.Append("<action>");
- builder.Append("<name>" + DescriptionXmlBuilder.Escape(item.Name ?? string.Empty) + "</name>");
+ builder.Append("<name>")
+ .Append(SecurityElement.Escape(item.Name ?? string.Empty))
+ .Append("</name>");
builder.Append("<argumentList>");
@@ -43,9 +47,15 @@ namespace Emby.Dlna.Service
{
builder.Append("<argument>");
- builder.Append("<name>" + DescriptionXmlBuilder.Escape(argument.Name ?? string.Empty) + "</name>");
- builder.Append("<direction>" + DescriptionXmlBuilder.Escape(argument.Direction ?? string.Empty) + "</direction>");
- builder.Append("<relatedStateVariable>" + DescriptionXmlBuilder.Escape(argument.RelatedStateVariable ?? string.Empty) + "</relatedStateVariable>");
+ builder.Append("<name>")
+ .Append(SecurityElement.Escape(argument.Name ?? string.Empty))
+ .Append("</name>");
+ builder.Append("<direction>")
+ .Append(SecurityElement.Escape(argument.Direction ?? string.Empty))
+ .Append("</direction>");
+ builder.Append("<relatedStateVariable>")
+ .Append(SecurityElement.Escape(argument.RelatedStateVariable ?? string.Empty))
+ .Append("</relatedStateVariable>");
builder.Append("</argument>");
}
@@ -66,18 +76,27 @@ namespace Emby.Dlna.Service
{
var sendEvents = item.SendsEvents ? "yes" : "no";
- builder.Append("<stateVariable sendEvents=\"" + sendEvents + "\">");
+ builder.Append("<stateVariable sendEvents=\"")
+ .Append(sendEvents)
+ .Append("\">");
- builder.Append("<name>" + DescriptionXmlBuilder.Escape(item.Name ?? string.Empty) + "</name>");
- builder.Append("<dataType>" + DescriptionXmlBuilder.Escape(item.DataType ?? string.Empty) + "</dataType>");
+ builder.Append("<name>")
+ .Append(SecurityElement.Escape(item.Name ?? string.Empty))
+ .Append("</name>");
+ builder.Append("<dataType>")
+ .Append(SecurityElement.Escape(item.DataType ?? string.Empty))
+ .Append("</dataType>");
- if (item.AllowedValues.Length > 0)
+ if (item.AllowedValues.Count > 0)
{
builder.Append("<allowedValueList>");
foreach (var allowedValue in item.AllowedValues)
{
- builder.Append("<allowedValue>" + DescriptionXmlBuilder.Escape(allowedValue) + "</allowedValue>");
+ builder.Append("<allowedValue>")
+ .Append(SecurityElement.Escape(allowedValue))
+ .Append("</allowedValue>");
}
+
builder.Append("</allowedValueList>");
}
diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
index 298f68a28..391dda147 100644
--- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs
+++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
@@ -1,27 +1,38 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
using Rssdp;
using Rssdp.Infrastructure;
namespace Emby.Dlna.Ssdp
{
- public class DeviceDiscovery : IDeviceDiscovery
+ public sealed class DeviceDiscovery : IDeviceDiscovery, IDisposable
{
- private bool _disposed;
+ private readonly object _syncLock = new object();
- private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
- private event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscoveredInternal;
+ private SsdpDeviceLocator _deviceLocator;
+ private ISsdpCommunicationsServer _commsServer;
private int _listenerCount;
- private object _syncLock = new object();
+ private bool _disposed;
+
+ public DeviceDiscovery(IServerConfigurationManager config)
+ {
+ _config = config;
+ }
+
+ private event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscoveredInternal;
+
+ /// <inheritdoc />
public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscovered
{
add
@@ -31,8 +42,10 @@ namespace Emby.Dlna.Ssdp
_listenerCount++;
DeviceDiscoveredInternal += value;
}
+
StartInternal();
}
+
remove
{
lock (_syncLock)
@@ -43,23 +56,9 @@ namespace Emby.Dlna.Ssdp
}
}
+ /// <inheritdoc />
public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceLeft;
- private SsdpDeviceLocator _deviceLocator;
-
- private readonly ISocketFactory _socketFactory;
- private ISsdpCommunicationsServer _commsServer;
-
- public DeviceDiscovery(
- ILoggerFactory loggerFactory,
- IServerConfigurationManager config,
- ISocketFactory socketFactory)
- {
- _logger = loggerFactory.CreateLogger(nameof(DeviceDiscovery));
- _config = config;
- _socketFactory = socketFactory;
- }
-
// Call this method from somewhere in your code to start the search.
public void Start(ISsdpCommunicationsServer communicationsServer)
{
@@ -72,18 +71,18 @@ namespace Emby.Dlna.Ssdp
{
lock (_syncLock)
{
- if (_listenerCount > 0 && _deviceLocator == null)
+ if (_listenerCount > 0 && _deviceLocator == null && _commsServer != null)
{
_deviceLocator = new SsdpDeviceLocator(_commsServer);
// (Optional) Set the filter so we only see notifications for devices we care about
// (can be any search target value i.e device type, uuid value etc - any value that appears in the
// DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
- //_DeviceLocator.NotificationFilter = "upnp:rootdevice";
+ // _DeviceLocator.NotificationFilter = "upnp:rootdevice";
// Connect our event handler so we process devices as they are found
- _deviceLocator.DeviceAvailable += deviceLocator_DeviceAvailable;
- _deviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable;
+ _deviceLocator.DeviceAvailable += OnDeviceLocatorDeviceAvailable;
+ _deviceLocator.DeviceUnavailable += OnDeviceLocatorDeviceUnavailable;
var dueTime = TimeSpan.FromSeconds(5);
var interval = TimeSpan.FromSeconds(_config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds);
@@ -94,7 +93,7 @@ namespace Emby.Dlna.Ssdp
}
// Process each found device in the event handler
- void deviceLocator_DeviceAvailable(object sender, DeviceAvailableEventArgs e)
+ private void OnDeviceLocatorDeviceAvailable(object sender, DeviceAvailableEventArgs e)
{
var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
@@ -102,20 +101,18 @@ namespace Emby.Dlna.Ssdp
var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
- var args = new GenericEventArgs<UpnpDeviceInfo>
- {
- Argument = new UpnpDeviceInfo
+ var args = new GenericEventArgs<UpnpDeviceInfo>(
+ new UpnpDeviceInfo
{
Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers,
- LocalIpAddress = e.LocalIpAddress
- }
- };
+ RemoteIpAddress = e.RemoteIpAddress
+ });
DeviceDiscoveredInternal?.Invoke(this, args);
}
- private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
+ private void OnDeviceLocatorDeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
{
var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
@@ -123,18 +120,17 @@ namespace Emby.Dlna.Ssdp
var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
- var args = new GenericEventArgs<UpnpDeviceInfo>
- {
- Argument = new UpnpDeviceInfo
+ var args = new GenericEventArgs<UpnpDeviceInfo>(
+ new UpnpDeviceInfo
{
Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers
- }
- };
+ });
DeviceLeft?.Invoke(this, args);
}
+ /// <inheritdoc />
public void Dispose()
{
if (!_disposed)
diff --git a/Emby.Dlna/Ssdp/Extensions.cs b/Emby.Dlna/Ssdp/Extensions.cs
deleted file mode 100644
index c680c123e..000000000
--- a/Emby.Dlna/Ssdp/Extensions.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using System.Xml.Linq;
-
-namespace Emby.Dlna.Ssdp
-{
- public static class Extensions
- {
- public static string GetValue(this XElement container, XName name)
- {
- var node = container.Element(name);
-
- return node == null ? null : node.Value;
- }
-
- public static string GetAttributeValue(this XElement container, XName name)
- {
- var node = container.Attribute(name);
-
- return node == null ? null : node.Value;
- }
-
- public static string GetDescendantValue(this XElement container, XName name)
- {
- foreach (var node in container.Descendants(name))
- {
- return node.Value;
- }
-
- return null;
- }
- }
-}
diff --git a/Emby.Dlna/Ssdp/SsdpExtensions.cs b/Emby.Dlna/Ssdp/SsdpExtensions.cs
new file mode 100644
index 000000000..d00eb02b4
--- /dev/null
+++ b/Emby.Dlna/Ssdp/SsdpExtensions.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using System.Linq;
+using System.Xml.Linq;
+
+namespace Emby.Dlna.Ssdp
+{
+ public static class SsdpExtensions
+ {
+ public static string? GetValue(this XElement container, XName name)
+ {
+ var node = container.Element(name);
+
+ return node?.Value;
+ }
+
+ public static string? GetAttributeValue(this XElement container, XName name)
+ {
+ var node = container.Attribute(name);
+
+ return node?.Value;
+ }
+
+ public static string? GetDescendantValue(this XElement container, XName name)
+ => container.Descendants(name).FirstOrDefault()?.Value;
+ }
+}
diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj
index 9f97baf77..149e4b5d9 100644
--- a/Emby.Drawing/Emby.Drawing.csproj
+++ b/Emby.Drawing/Emby.Drawing.csproj
@@ -1,8 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <ProjectGuid>{08FFF49B-F175-4807-A2B5-73B0EBD9F716}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -15,4 +21,11 @@
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
+ <!-- Code analysers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs
index faaeb5af8..ac73cfa42 100644
--- a/Emby.Drawing/ImageProcessor.cs
+++ b/Emby.Drawing/ImageProcessor.cs
@@ -3,86 +3,67 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Threading;
+using System.Text;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
+using Photo = MediaBrowser.Controller.Entities.Photo;
namespace Emby.Drawing
{
/// <summary>
- /// Class ImageProcessor
+ /// Class ImageProcessor.
/// </summary>
- public class ImageProcessor : IImageProcessor, IDisposable
+ public sealed class ImageProcessor : IImageProcessor, IDisposable
{
- /// <summary>
- /// The us culture
- /// </summary>
- protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Gets the list of currently registered image processors
- /// Image processors are specialized metadata providers that run after the normal ones
- /// </summary>
- /// <value>The image enhancers.</value>
- public IImageEnhancer[] ImageEnhancers { get; private set; }
+ // Increment this when there's a change requiring caches to be invalidated
+ private const string Version = "3";
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
+ private static readonly HashSet<string> _transparentImageTypes
+ = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
+ private readonly ILogger<ImageProcessor> _logger;
private readonly IFileSystem _fileSystem;
private readonly IServerApplicationPaths _appPaths;
- private IImageEncoder _imageEncoder;
- private readonly Func<ILibraryManager> _libraryManager;
- private readonly Func<IMediaEncoder> _mediaEncoder;
+ private readonly IImageEncoder _imageEncoder;
+ private readonly IMediaEncoder _mediaEncoder;
+
+ private bool _disposed;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ImageProcessor"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="appPaths">The server application paths.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="imageEncoder">The image encoder.</param>
+ /// <param name="mediaEncoder">The media encoder.</param>
public ImageProcessor(
- ILoggerFactory loggerFactory,
+ ILogger<ImageProcessor> logger,
IServerApplicationPaths appPaths,
IFileSystem fileSystem,
IImageEncoder imageEncoder,
- Func<ILibraryManager> libraryManager,
- Func<IMediaEncoder> mediaEncoder)
+ IMediaEncoder mediaEncoder)
{
- _logger = loggerFactory.CreateLogger(nameof(ImageProcessor));
+ _logger = logger;
_fileSystem = fileSystem;
_imageEncoder = imageEncoder;
- _libraryManager = libraryManager;
_mediaEncoder = mediaEncoder;
_appPaths = appPaths;
-
- ImageEnhancers = Array.Empty<IImageEnhancer>();
-
- ImageHelper.ImageProcessor = this;
}
- public IImageEncoder ImageEncoder
- {
- get => _imageEncoder;
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- _imageEncoder = value;
- }
- }
+ private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
+ /// <inheritdoc />
public IReadOnlyCollection<string> SupportedInputFormats =>
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
@@ -94,9 +75,7 @@ namespace Emby.Drawing
"aiff",
"cr2",
"crw",
-
- // Remove until supported
- //"nef",
+ "nef",
"orf",
"pef",
"arw",
@@ -115,56 +94,34 @@ namespace Emby.Drawing
"wbmp"
};
-
+ /// <inheritdoc />
public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation;
- private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
-
- private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
-
- public void AddParts(IEnumerable<IImageEnhancer> enhancers)
- {
- ImageEnhancers = enhancers.ToArray();
- }
-
+ /// <inheritdoc />
public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
{
var file = await ProcessImage(options).ConfigureAwait(false);
- using (var fileStream = _fileSystem.GetFileStream(file.Item1, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
+ using (var fileStream = AsyncFile.OpenRead(file.Item1))
{
await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
}
}
+ /// <inheritdoc />
public IReadOnlyCollection<ImageFormat> GetSupportedImageOutputFormats()
=> _imageEncoder.SupportedOutputFormats;
- private static readonly HashSet<string> TransparentImageTypes
- = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
-
+ /// <inheritdoc />
public bool SupportsTransparency(string path)
- => TransparentImageTypes.Contains(Path.GetExtension(path));
+ => _transparentImageTypes.Contains(Path.GetExtension(path));
- public async Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
+ /// <inheritdoc />
+ public async Task<(string path, string? mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
{
- if (options == null)
- {
- throw new ArgumentNullException(nameof(options));
- }
-
ItemImageInfo originalImage = options.Image;
BaseItem item = options.Item;
- if (!originalImage.IsLocalFile)
- {
- if (item == null)
- {
- item = _libraryManager().GetItemById(options.ItemId);
- }
- originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false);
- }
-
string originalImagePath = originalImage.Path;
DateTime dateModified = originalImage.DateModified;
ImageDimensions? originalImageSize = null;
@@ -180,30 +137,15 @@ namespace Emby.Drawing
var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
originalImagePath = supportedImageInfo.path;
- dateModified = supportedImageInfo.dateModified;
- bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
- if (options.Enhancers.Length > 0)
+ if (!File.Exists(originalImagePath))
{
- if (item == null)
- {
- item = _libraryManager().GetItemById(options.ItemId);
- }
-
- var tuple = await GetEnhancedImage(new ItemImageInfo
- {
- DateModified = dateModified,
- Type = originalImage.Type,
- Path = originalImagePath
- }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false);
-
- originalImagePath = tuple.path;
- dateModified = tuple.dateModified;
- requiresTransparency = tuple.transparent;
- // TODO: Get this info
- originalImageSize = null;
+ return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
+ dateModified = supportedImageInfo.dateModified;
+ bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath));
+
bool autoOrient = false;
ImageOrientation? orientation = null;
if (item is Photo photo)
@@ -230,27 +172,31 @@ namespace Emby.Drawing
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
- ImageDimensions newSize = ImageHelper.GetNewImageSize(options, null);
int quality = options.Quality;
ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
- string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);
-
- CheckDisposed();
-
- LockInfo lockInfo = GetLock(cacheFilePath);
-
- await lockInfo.Lock.WaitAsync().ConfigureAwait(false);
+ string cacheFilePath = GetCacheFilePath(
+ originalImagePath,
+ options.Width,
+ options.Height,
+ options.MaxWidth,
+ options.MaxHeight,
+ options.FillWidth,
+ options.FillHeight,
+ quality,
+ dateModified,
+ outputFormat,
+ options.AddPlayedIndicator,
+ options.PercentPlayed,
+ options.UnplayedCount,
+ options.Blur,
+ options.BackgroundColor,
+ options.ForegroundLayer);
try
{
if (!File.Exists(cacheFilePath))
{
- if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
- {
- options.CropWhiteSpace = false;
- }
-
string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);
if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
@@ -265,17 +211,11 @@ namespace Emby.Drawing
{
// If it fails for whatever reason, return the original image
_logger.LogError(ex, "Error encoding image");
-
- // Just spit out the original file if all the options are default
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
}
- finally
- {
- ReleaseLock(cacheFilePath, lockInfo);
- }
}
- private ImageFormat GetOutputFormat(ImageFormat[] clientSupportedFormats, bool requiresTransparency)
+ private ImageFormat GetOutputFormat(IReadOnlyCollection<ImageFormat> clientSupportedFormats, bool requiresTransparency)
{
var serverFormats = GetSupportedImageOutputFormats();
@@ -303,75 +243,129 @@ namespace Emby.Drawing
return ImageFormat.Jpg;
}
- private string GetMimeType(ImageFormat format, string path)
- {
- switch(format)
+ private string? GetMimeType(ImageFormat format, string path)
+ => format switch
{
- case ImageFormat.Bmp: return MimeTypes.GetMimeType("i.bmp");
- case ImageFormat.Gif: return MimeTypes.GetMimeType("i.gif");
- case ImageFormat.Jpg: return MimeTypes.GetMimeType("i.jpg");
- case ImageFormat.Png: return MimeTypes.GetMimeType("i.png");
- case ImageFormat.Webp: return MimeTypes.GetMimeType("i.webp");
- default: return MimeTypes.GetMimeType(path);
- }
- }
-
- /// <summary>
- /// Increment this when there's a change requiring caches to be invalidated
- /// </summary>
- private const string Version = "3";
+ ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"),
+ ImageFormat.Gif => MimeTypes.GetMimeType("i.gif"),
+ ImageFormat.Jpg => MimeTypes.GetMimeType("i.jpg"),
+ ImageFormat.Png => MimeTypes.GetMimeType("i.png"),
+ ImageFormat.Webp => MimeTypes.GetMimeType("i.webp"),
+ _ => MimeTypes.GetMimeType(path)
+ };
/// <summary>
- /// Gets the cache file path based on a set of parameters
+ /// Gets the cache file path based on a set of parameters.
/// </summary>
- private string GetCacheFilePath(string originalPath, ImageDimensions outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer)
+ private string GetCacheFilePath(
+ string originalPath,
+ int? width,
+ int? height,
+ int? maxWidth,
+ int? maxHeight,
+ int? fillWidth,
+ int? fillHeight,
+ int quality,
+ DateTime dateModified,
+ ImageFormat format,
+ bool addPlayedIndicator,
+ double percentPlayed,
+ int? unwatchedCount,
+ int? blur,
+ string backgroundColor,
+ string foregroundLayer)
{
- var filename = originalPath
- + "width=" + outputSize.Width
- + "height=" + outputSize.Height
- + "quality=" + quality
- + "datemodified=" + dateModified.Ticks
- + "f=" + format;
+ var filename = new StringBuilder(256);
+ filename.Append(originalPath);
+
+ filename.Append(",quality=");
+ filename.Append(quality);
+
+ filename.Append(",datemodified=");
+ filename.Append(dateModified.Ticks);
+
+ filename.Append(",f=");
+ filename.Append(format);
+
+ if (width.HasValue)
+ {
+ filename.Append(",width=");
+ filename.Append(width.Value);
+ }
+
+ if (height.HasValue)
+ {
+ filename.Append(",height=");
+ filename.Append(height.Value);
+ }
+
+ if (maxWidth.HasValue)
+ {
+ filename.Append(",maxwidth=");
+ filename.Append(maxWidth.Value);
+ }
+
+ if (maxHeight.HasValue)
+ {
+ filename.Append(",maxheight=");
+ filename.Append(maxHeight.Value);
+ }
+
+ if (fillWidth.HasValue)
+ {
+ filename.Append(",fillwidth=");
+ filename.Append(fillWidth.Value);
+ }
+
+ if (fillHeight.HasValue)
+ {
+ filename.Append(",fillheight=");
+ filename.Append(fillHeight.Value);
+ }
if (addPlayedIndicator)
{
- filename += "pl=true";
+ filename.Append(",pl=true");
}
if (percentPlayed > 0)
{
- filename += "p=" + percentPlayed;
+ filename.Append(",p=");
+ filename.Append(percentPlayed);
}
if (unwatchedCount.HasValue)
{
- filename += "p=" + unwatchedCount.Value;
+ filename.Append(",p=");
+ filename.Append(unwatchedCount.Value);
}
if (blur.HasValue)
{
- filename += "blur=" + blur.Value;
+ filename.Append(",blur=");
+ filename.Append(blur.Value);
}
if (!string.IsNullOrEmpty(backgroundColor))
{
- filename += "b=" + backgroundColor;
+ filename.Append(",b=");
+ filename.Append(backgroundColor);
}
if (!string.IsNullOrEmpty(foregroundLayer))
{
- filename += "fl=" + foregroundLayer;
+ filename.Append(",fl=");
+ filename.Append(foregroundLayer);
}
- filename += "v=" + Version;
+ filename.Append(",v=");
+ filename.Append(Version);
- return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLowerInvariant());
+ return GetCachePath(ResizedImageCachePath, filename.ToString(), "." + format.ToString().ToLowerInvariant());
}
+ /// <inheritdoc />
public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info)
- => GetImageDimensions(item, info, true);
-
- public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem)
{
int width = info.Width;
int height = info.Height;
@@ -382,82 +376,65 @@ namespace Emby.Drawing
}
string path = info.Path;
- _logger.LogInformation("Getting image size for item {ItemType} {Path}", item.GetType().Name, path);
+ _logger.LogDebug("Getting image size for item {ItemType} {Path}", item.GetType().Name, path);
ImageDimensions size = GetImageDimensions(path);
info.Width = size.Width;
info.Height = size.Height;
- if (updateItem)
- {
- _libraryManager().UpdateImages(item);
- }
-
return size;
}
- /// <summary>
- /// Gets the size of the image.
- /// </summary>
+ /// <inheritdoc />
public ImageDimensions GetImageDimensions(string path)
=> _imageEncoder.GetImageSize(path);
- /// <summary>
- /// Gets the image cache tag.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="image">The image.</param>
- /// <returns>Guid.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
+ /// <inheritdoc />
+ public string GetImageBlurHash(string path)
{
- var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
+ var size = GetImageDimensions(path);
+ if (size.Width <= 0 || size.Height <= 0)
+ {
+ return string.Empty;
+ }
+
+ // We want tiles to be as close to square as possible, and to *mostly* keep under 16 tiles for performance.
+ // One tile is (width / xComp) x (height / yComp) pixels, which means that ideally yComp = xComp * height / width.
+ // See more at https://github.com/woltapp/blurhash/#how-do-i-pick-the-number-of-x-and-y-components
+ float xCompF = MathF.Sqrt(16.0f * size.Width / size.Height);
+ float yCompF = xCompF * size.Height / size.Width;
- return GetImageCacheTag(item, image, supportedEnhancers);
+ int xComp = Math.Min((int)xCompF + 1, 9);
+ int yComp = Math.Min((int)yCompF + 1, 9);
+
+ return _imageEncoder.GetImageBlurHash(xComp, yComp, path);
}
+ /// <inheritdoc />
+ public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
+ => (item.Path + image.DateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture);
+
+ /// <inheritdoc />
public string GetImageCacheTag(BaseItem item, ChapterInfo chapter)
{
- try
- {
- return GetImageCacheTag(item, new ItemImageInfo
- {
- Path = chapter.ImagePath,
- Type = ImageType.Chapter,
- DateModified = chapter.ImageDateModified
- });
- }
- catch
+ return GetImageCacheTag(item, new ItemImageInfo
{
- return null;
- }
+ Path = chapter.ImagePath,
+ Type = ImageType.Chapter,
+ DateModified = chapter.ImageDateModified
+ });
}
- /// <summary>
- /// Gets the image cache tag.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="image">The image.</param>
- /// <param name="imageEnhancers">The image enhancers.</param>
- /// <returns>Guid.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers)
+ /// <inheritdoc />
+ public string? GetImageCacheTag(User user)
{
- string originalImagePath = image.Path;
- DateTime dateModified = image.DateModified;
- ImageType imageType = image.Type;
-
- // Optimization
- if (imageEnhancers.Length == 0)
+ if (user.ProfileImage == null)
{
- return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
+ return null;
}
- // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
- var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
- cacheKeys.Add(originalImagePath + dateModified.Ticks);
-
- return string.Join("|", cacheKeys).GetMD5().ToString("N");
+ return (user.ProfileImage.Path + user.ProfileImage.LastModified.Ticks).GetMD5()
+ .ToString("N", CultureInfo.InvariantCulture);
}
private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified)
@@ -476,15 +453,15 @@ namespace Emby.Drawing
{
try
{
- string filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N");
+ string filename = (originalImagePath + dateModified.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("N", CultureInfo.InvariantCulture);
- string cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png";
+ string cacheExtension = _mediaEncoder.SupportsEncoder("libwebp") ? ".webp" : ".png";
var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension);
var file = _fileSystem.GetFileInfo(outputPath);
if (!file.Exists)
{
- await _mediaEncoder().ConvertImage(originalImagePath, outputPath).ConfigureAwait(false);
+ await _mediaEncoder.ConvertImage(originalImagePath, outputPath).ConfigureAwait(false);
dateModified = _fileSystem.GetLastWriteTimeUtc(outputPath);
}
else
@@ -504,159 +481,6 @@ namespace Emby.Drawing
}
/// <summary>
- /// Gets the enhanced image.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <returns>Task{System.String}.</returns>
- public async Task<string> GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex)
- {
- var enhancers = GetSupportedEnhancers(item, imageType);
-
- ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex);
-
- bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path);
-
- var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None);
-
- return result.path;
- }
-
- private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage(
- ItemImageInfo image,
- bool inputImageSupportsTransparency,
- BaseItem item,
- int imageIndex,
- IImageEnhancer[] enhancers,
- CancellationToken cancellationToken)
- {
- var originalImagePath = image.Path;
- var dateModified = image.DateModified;
- var imageType = image.Type;
-
- try
- {
- var cacheGuid = GetImageCacheTag(item, image, enhancers);
-
- // Enhance if we have enhancers
- var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
-
- string enhancedImagePath = enhancedImageInfo.path;
-
- // If the path changed update dateModified
- if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
- {
- var treatmentRequiresTransparency = enhancedImageInfo.transparent;
-
- return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency);
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error enhancing image");
- }
-
- return (originalImagePath, dateModified, inputImageSupportsTransparency);
- }
-
- /// <summary>
- /// Gets the enhanced image internal.
- /// </summary>
- /// <param name="originalImagePath">The original image path.</param>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <param name="supportedEnhancers">The supported enhancers.</param>
- /// <param name="cacheGuid">The cache unique identifier.</param>
- /// <returns>Task&lt;System.String&gt;.</returns>
- /// <exception cref="ArgumentNullException">
- /// originalImagePath
- /// or
- /// item
- /// </exception>
- private async Task<(string path, bool transparent)> GetEnhancedImageInternal(
- string originalImagePath,
- BaseItem item,
- ImageType imageType,
- int imageIndex,
- IImageEnhancer[] supportedEnhancers,
- string cacheGuid,
- CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(originalImagePath))
- {
- throw new ArgumentNullException(nameof(originalImagePath));
- }
-
- if (item == null)
- {
- throw new ArgumentNullException(nameof(item));
- }
-
- var treatmentRequiresTransparency = false;
- foreach (var enhancer in supportedEnhancers)
- {
- if (!treatmentRequiresTransparency)
- {
- treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency;
- }
- }
-
- // All enhanced images are saved as png to allow transparency
- string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ?
- ".webp" :
- (treatmentRequiresTransparency ? ".png" : ".jpg");
-
- string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension);
-
- LockInfo lockInfo = GetLock(enhancedImagePath);
-
- await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
- {
- // Check again in case of contention
- if (File.Exists(enhancedImagePath))
- {
- return (enhancedImagePath, treatmentRequiresTransparency);
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
-
- await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
-
- return (enhancedImagePath, treatmentRequiresTransparency);
- }
- finally
- {
- ReleaseLock(enhancedImagePath, lockInfo);
- }
- }
-
- /// <summary>
- /// Executes the image enhancers.
- /// </summary>
- /// <param name="imageEnhancers">The image enhancers.</param>
- /// <param name="inputPath">The input path.</param>
- /// <param name="outputPath">The output path.</param>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <returns>Task{EnhancedImage}.</returns>
- private static async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex)
- {
- // Run the enhancers sequentially in order of priority
- foreach (var enhancer in imageEnhancers)
- {
- await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
-
- // Feed the output into the next enhancer as input
- inputPath = outputPath;
- }
- }
-
- /// <summary>
/// Gets the cache path.
/// </summary>
/// <param name="path">The path.</param>
@@ -668,7 +492,7 @@ namespace Emby.Drawing
/// or
/// uniqueName
/// or
- /// fileExtension
+ /// fileExtension.
/// </exception>
public string GetCachePath(string path, string uniqueName, string fileExtension)
{
@@ -676,6 +500,7 @@ namespace Emby.Drawing
{
throw new ArgumentNullException(nameof(path));
}
+
if (string.IsNullOrEmpty(uniqueName))
{
throw new ArgumentNullException(nameof(uniqueName));
@@ -700,115 +525,49 @@ namespace Emby.Drawing
/// <exception cref="ArgumentNullException">
/// path
/// or
- /// filename
+ /// filename.
/// </exception>
- public string GetCachePath(string path, string filename)
+ public string GetCachePath(ReadOnlySpan<char> path, ReadOnlySpan<char> filename)
{
- if (string.IsNullOrEmpty(path))
+ if (path.IsEmpty)
{
- throw new ArgumentNullException(nameof(path));
+ throw new ArgumentException("Path can't be empty.", nameof(path));
}
- if (string.IsNullOrEmpty(filename))
+
+ if (filename.IsEmpty)
{
- throw new ArgumentNullException(nameof(filename));
+ throw new ArgumentException("Filename can't be empty.", nameof(filename));
}
- var prefix = filename.Substring(0, 1);
+ var prefix = filename.Slice(0, 1);
- return Path.Combine(path, prefix, filename);
+ return Path.Join(path, prefix, filename);
}
- public void CreateImageCollage(ImageCollageOptions options)
+ /// <inheritdoc />
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
_logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
- _imageEncoder.CreateImageCollage(options);
+ _imageEncoder.CreateImageCollage(options, libraryName);
_logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
}
- public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType)
- {
- List<IImageEnhancer> list = null;
-
- foreach (var i in ImageEnhancers)
- {
- try
- {
- if (i.Supports(item, imageType))
- {
- if (list == null)
- {
- list = new List<IImageEnhancer>();
- }
- list.Add(i);
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name);
- }
- }
-
- return list == null ? Array.Empty<IImageEnhancer>() : list.ToArray();
- }
-
- private Dictionary<string, LockInfo> _locks = new Dictionary<string, LockInfo>();
- private class LockInfo
- {
- public SemaphoreSlim Lock = new SemaphoreSlim(1, 1);
- public int Count = 1;
- }
- private LockInfo GetLock(string key)
- {
- lock (_locks)
- {
- if (_locks.TryGetValue(key, out LockInfo info))
- {
- info.Count++;
- }
- else
- {
- info = new LockInfo();
- _locks[key] = info;
- }
- return info;
- }
- }
-
- private void ReleaseLock(string key, LockInfo info)
+ /// <inheritdoc />
+ public void Dispose()
{
- info.Lock.Release();
-
- lock (_locks)
+ if (_disposed)
{
- info.Count--;
- if (info.Count <= 0)
- {
- _locks.Remove(key);
- info.Lock.Dispose();
- }
+ return;
}
- }
-
- private bool _disposed;
- public void Dispose()
- {
- _disposed = true;
- var disposable = _imageEncoder as IDisposable;
- if (disposable != null)
+ if (_imageEncoder is IDisposable disposable)
{
disposable.Dispose();
}
- }
- private void CheckDisposed()
- {
- if (_disposed)
- {
- throw new ObjectDisposedException(GetType().Name);
- }
+ _disposed = true;
}
}
}
diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs
index fc4a5af9f..1c05aa916 100644
--- a/Emby.Drawing/NullImageEncoder.cs
+++ b/Emby.Drawing/NullImageEncoder.cs
@@ -5,36 +5,46 @@ using MediaBrowser.Model.Drawing;
namespace Emby.Drawing
{
+ /// <summary>
+ /// A fallback implementation of <see cref="IImageEncoder" />.
+ /// </summary>
public class NullImageEncoder : IImageEncoder
{
+ /// <inheritdoc />
public IReadOnlyCollection<string> SupportedInputFormats
=> new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "png", "jpeg", "jpg" };
+ /// <inheritdoc />
public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
=> new HashSet<ImageFormat>() { ImageFormat.Jpg, ImageFormat.Png };
- public void CropWhiteSpace(string inputPath, string outputPath)
- {
- throw new NotImplementedException();
- }
+ /// <inheritdoc />
+ public string Name => "Null Image Encoder";
- public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
+ /// <inheritdoc />
+ public bool SupportsImageCollageCreation => false;
+
+ /// <inheritdoc />
+ public bool SupportsImageEncoding => false;
+
+ /// <inheritdoc />
+ public ImageDimensions GetImageSize(string path)
+ => throw new NotImplementedException();
+
+ /// <inheritdoc />
+ public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat)
{
throw new NotImplementedException();
}
- public void CreateImageCollage(ImageCollageOptions options)
+ /// <inheritdoc />
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
throw new NotImplementedException();
}
- public string Name => "Null Image Encoder";
-
- public bool SupportsImageCollageCreation => false;
-
- public bool SupportsImageEncoding => false;
-
- public ImageDimensions GetImageSize(string path)
+ /// <inheritdoc />
+ public string GetImageBlurHash(int xComp, int yComp, string path)
{
throw new NotImplementedException();
}
diff --git a/Emby.Drawing/Properties/AssemblyInfo.cs b/Emby.Drawing/Properties/AssemblyInfo.cs
index 8dfefe0af..281008e37 100644
--- a/Emby.Drawing/Properties/AssemblyInfo.cs
+++ b/Emby.Drawing/Properties/AssemblyInfo.cs
@@ -8,8 +8,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
diff --git a/Emby.IsoMounting/.gitignore b/Emby.IsoMounting/.gitignore
deleted file mode 100644
index bdc3535f7..000000000
--- a/Emby.IsoMounting/.gitignore
+++ /dev/null
@@ -1,108 +0,0 @@
-# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)
-[Bb]in/
-[Oo]bj/
-
-# mstest test results
-TestResults
-
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-
-# User-specific files
-*.suo
-*.user
-*.sln.docstates
-
-# Build results
-[Dd]ebug/
-[Rr]elease/
-x64/
-*_i.c
-*_p.c
-*.ilk
-*.meta
-*.obj
-*.pch
-*.pdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.log
-*.vspscc
-*.vssscc
-.builds
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opensdf
-*.sdf
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*
-
-# NCrunch
-*.ncrunch*
-.*crunch*.local.xml
-
-# Installshield output folder
-[Ee]xpress
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish
-
-# Publish Web Output
-*.Publish.xml
-
-# NuGet Packages Directory
-packages
-
-# Windows Azure Build Output
-csx
-*.build.csdef
-
-# Windows Store app package directory
-AppPackages/
-
-# Others
-[Bb]in
-[Oo]bj
-sql
-TestResults
-[Tt]est[Rr]esult*
-*.Cache
-ClientBin
-[Ss]tyle[Cc]op.*
-~$*
-*.dbmdl
-Generated_Code #added for RIA/Silverlight projects
-
-# Backup & report files from converting an old project file to a newer
-# Visual Studio version. Backup files are not needed, because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
diff --git a/Emby.IsoMounting/IsoMounter.sln b/Emby.IsoMounting/IsoMounter.sln
deleted file mode 100644
index 55db1b1ae..000000000
--- a/Emby.IsoMounting/IsoMounter.sln
+++ /dev/null
@@ -1,25 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.27004.2009
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IsoMounter", "IsoMounter\IsoMounter.csproj", "{B94C929C-6552-4620-9BE5-422DD9A151BA}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {C0E8EAD1-E4D7-44CD-B801-03BD12F30B1B}
- EndGlobalSection
-EndGlobal
diff --git a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs b/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs
deleted file mode 100644
index 4755e4e82..000000000
--- a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-using MediaBrowser.Model.Plugins;
-
-namespace IsoMounter.Configuration
-{
- public class PluginConfiguration : BasePluginConfiguration
- {
- }
-}
diff --git a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj b/Emby.IsoMounting/IsoMounter/IsoMounter.csproj
deleted file mode 100644
index dafa51cd5..000000000
--- a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <Compile Include="..\..\SharedVersion.cs" />
- </ItemGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
deleted file mode 100644
index 943caa3e6..000000000
--- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
+++ /dev/null
@@ -1,479 +0,0 @@
-using System;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Diagnostics;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace IsoMounter
-{
- public class LinuxIsoManager : IIsoMounter
- {
- [DllImport("libc", SetLastError = true)]
- static extern uint getuid();
-
- #region Private Fields
-
- private readonly IEnvironmentInfo EnvironmentInfo;
- private readonly bool ExecutablesAvailable;
- private readonly ILogger _logger;
- private readonly string MountCommand;
- private readonly string MountPointRoot;
- private readonly IProcessFactory ProcessFactory;
- private readonly string SudoCommand;
- private readonly string UmountCommand;
-
- #endregion
-
- #region Constructor(s)
-
- public LinuxIsoManager(ILogger logger, IEnvironmentInfo environment, IProcessFactory processFactory)
- {
-
- EnvironmentInfo = environment;
- _logger = logger;
- ProcessFactory = processFactory;
-
- MountPointRoot = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar + "Emby";
-
- _logger.LogDebug(
- "[{0}] System PATH is currently set to [{1}].",
- Name,
- Environment.GetEnvironmentVariable("PATH") ?? ""
- );
-
- _logger.LogDebug(
- "[{0}] System path separator is [{1}].",
- Name,
- Path.PathSeparator
- );
-
- _logger.LogDebug(
- "[{0}] Mount point root is [{1}].",
- Name,
- MountPointRoot
- );
-
- //
- // Get the location of the executables we need to support mounting/unmounting ISO images.
- //
-
- SudoCommand = GetFullPathForExecutable("sudo");
-
- _logger.LogInformation(
- "[{0}] Using version of [sudo] located at [{1}].",
- Name,
- SudoCommand
- );
-
- MountCommand = GetFullPathForExecutable("mount");
-
- _logger.LogInformation(
- "[{0}] Using version of [mount] located at [{1}].",
- Name,
- MountCommand
- );
-
- UmountCommand = GetFullPathForExecutable("umount");
-
- _logger.LogInformation(
- "[{0}] Using version of [umount] located at [{1}].",
- Name,
- UmountCommand
- );
-
- if (!string.IsNullOrEmpty(SudoCommand) && !string.IsNullOrEmpty(MountCommand) && !string.IsNullOrEmpty(UmountCommand))
- {
- ExecutablesAvailable = true;
- }
- else
- {
- ExecutablesAvailable = false;
- }
-
- }
-
- #endregion
-
- #region Interface Implementation for IIsoMounter
-
- public bool IsInstalled => true;
-
- public string Name => "LinuxMount";
-
- public bool RequiresInstallation => false;
-
- public bool CanMount(string path)
- {
-
- if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Linux)
- {
- return false;
- }
- _logger.LogInformation(
- "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].",
- Name,
- path,
- Path.GetExtension(path),
- EnvironmentInfo.OperatingSystem,
- ExecutablesAvailable
- );
-
- if (ExecutablesAvailable)
- {
- return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- return false;
- }
- }
-
- public Task Install(CancellationToken cancellationToken)
- {
- return Task.FromResult(false);
- }
-
- public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken)
- {
- if (MountISO(isoPath, out LinuxMount mountedISO))
- {
- return Task.FromResult<IIsoMount>(mountedISO);
- }
- else
- {
- throw new IOException(string.Format(
- "An error occurred trying to mount image [$0].",
- isoPath
- ));
- }
- }
-
- #endregion
-
- #region Interface Implementation for IDisposable
-
- // Flag: Has Dispose already been called?
- private bool disposed = false;
-
- public void Dispose()
- {
-
- // Dispose of unmanaged resources.
- Dispose(true);
-
- // Suppress finalization.
- GC.SuppressFinalize(this);
-
- }
-
- protected virtual void Dispose(bool disposing)
- {
-
- if (disposed)
- {
- return;
- }
-
- _logger.LogInformation(
- "[{0}] Disposing [{1}].",
- Name,
- disposing
- );
-
- if (disposing)
- {
-
- //
- // Free managed objects here.
- //
-
- }
-
- //
- // Free any unmanaged objects here.
- //
-
- disposed = true;
-
- }
-
- #endregion
-
- #region Private Methods
-
- private string GetFullPathForExecutable(string name)
- {
-
- foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
- {
- string path = test.Trim();
-
- if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, name)))
- {
- return Path.GetFullPath(path);
- }
- }
-
- return string.Empty;
- }
-
- private uint GetUID()
- {
-
- var uid = getuid();
-
- _logger.LogDebug(
- "[{0}] GetUserId() returned [{2}].",
- Name,
- uid
- );
-
- return uid;
-
- }
-
- private bool ExecuteCommand(string cmdFilename, string cmdArguments)
- {
-
- bool processFailed = false;
-
- var process = ProcessFactory.Create(
- new ProcessOptions
- {
- CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- FileName = cmdFilename,
- Arguments = cmdArguments,
- IsHidden = true,
- ErrorDialog = false,
- EnableRaisingEvents = true
- }
- );
-
- try
- {
- process.Start();
-
- //StreamReader outputReader = process.StandardOutput.;
- //StreamReader errorReader = process.StandardError;
-
- _logger.LogDebug(
- "[{Name}] Standard output from process is [{Error}].",
- Name,
- process.StandardOutput.ReadToEnd()
- );
-
- _logger.LogDebug(
- "[{Name}] Standard error from process is [{Error}].",
- Name,
- process.StandardError.ReadToEnd()
- );
- }
- catch (Exception ex)
- {
- processFailed = true;
- _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
- }
-
- if (!processFailed && process.ExitCode == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
-
- }
-
- private bool MountISO(string isoPath, out LinuxMount mountedISO)
- {
-
- string cmdArguments;
- string cmdFilename;
- string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString());
-
- if (!string.IsNullOrEmpty(isoPath))
- {
-
- _logger.LogInformation(
- "[{Name}] Attempting to mount [{Path}].",
- Name,
- isoPath
- );
-
- _logger.LogDebug(
- "[{Name}] ISO will be mounted at [{Path}].",
- Name,
- mountPoint
- );
-
- }
- else
- {
-
- throw new ArgumentNullException(nameof(isoPath));
-
- }
-
- try
- {
- Directory.CreateDirectory(mountPoint);
- }
- catch (UnauthorizedAccessException)
- {
- throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
- }
- catch (Exception)
- {
- throw new IOException("Unable to create mount point for " + isoPath);
- }
-
- if (GetUID() == 0)
- {
- cmdFilename = MountCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint);
- }
- else
- {
- cmdFilename = SudoCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
- }
-
- _logger.LogDebug(
- "[{0}] Mount command [{1}], mount arguments [{2}].",
- Name,
- cmdFilename,
- cmdArguments
- );
-
- if (ExecuteCommand(cmdFilename, cmdArguments))
- {
-
- _logger.LogInformation(
- "[{0}] ISO mount completed successfully.",
- Name
- );
-
- mountedISO = new LinuxMount(this, isoPath, mountPoint);
-
- }
- else
- {
-
- _logger.LogInformation(
- "[{0}] ISO mount completed with errors.",
- Name
- );
-
- try
- {
- Directory.Delete(mountPoint, false);
- }
- catch (Exception ex)
- {
- _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
- }
-
- mountedISO = null;
-
- }
-
- return mountedISO != null;
-
- }
-
- private void UnmountISO(LinuxMount mount)
- {
-
- string cmdArguments;
- string cmdFilename;
-
- if (mount != null)
- {
-
- _logger.LogInformation(
- "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
- Name,
- mount.IsoPath,
- mount.MountedPath
- );
-
- }
- else
- {
-
- throw new ArgumentNullException(nameof(mount));
-
- }
-
- if (GetUID() == 0)
- {
- cmdFilename = UmountCommand;
- cmdArguments = string.Format("\"{0}\"", mount.MountedPath);
- }
- else
- {
- cmdFilename = SudoCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
- }
-
- _logger.LogDebug(
- "[{0}] Umount command [{1}], umount arguments [{2}].",
- Name,
- cmdFilename,
- cmdArguments
- );
-
- if (ExecuteCommand(cmdFilename, cmdArguments))
- {
-
- _logger.LogInformation(
- "[{0}] ISO unmount completed successfully.",
- Name
- );
-
- }
- else
- {
-
- _logger.LogInformation(
- "[{0}] ISO unmount completed with errors.",
- Name
- );
-
- }
-
- try
- {
- Directory.Delete(mount.MountedPath, false);
- }
- catch (Exception ex)
- {
- _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
- }
- }
-
- #endregion
-
- #region Internal Methods
-
- internal void OnUnmount(LinuxMount mount)
- {
-
- UnmountISO(mount);
-
- }
-
- #endregion
-
- }
-
-}
-
diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs
deleted file mode 100644
index b8636822b..000000000
--- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System;
-using MediaBrowser.Model.IO;
-
-namespace IsoMounter
-{
- internal class LinuxMount : IIsoMount
- {
-
- #region Private Fields
-
- private readonly LinuxIsoManager linuxIsoManager;
-
- #endregion
-
- #region Constructor(s)
-
- internal LinuxMount(LinuxIsoManager isoManager, string isoPath, string mountFolder)
- {
-
- linuxIsoManager = isoManager;
-
- IsoPath = isoPath;
- MountedPath = mountFolder;
-
- }
-
- #endregion
-
- #region Interface Implementation for IDisposable
-
- // Flag: Has Dispose already been called?
- private bool disposed = false;
-
- public void Dispose()
- {
-
- // Dispose of unmanaged resources.
- Dispose(true);
-
- // Suppress finalization.
- GC.SuppressFinalize(this);
-
- }
-
- protected virtual void Dispose(bool disposing)
- {
-
- if (disposed)
- {
- return;
- }
-
- if (disposing)
- {
-
- //
- // Free managed objects here.
- //
-
- linuxIsoManager.OnUnmount(this);
-
- }
-
- //
- // Free any unmanaged objects here.
- //
-
- disposed = true;
-
- }
-
- #endregion
-
- #region Interface Implementation for IIsoMount
-
- public string IsoPath { get; private set; }
- public string MountedPath { get; private set; }
-
- #endregion
-
- }
-
-}
diff --git a/Emby.IsoMounting/IsoMounter/Plugin.cs b/Emby.IsoMounting/IsoMounter/Plugin.cs
deleted file mode 100644
index f45b39d3e..000000000
--- a/Emby.IsoMounting/IsoMounter/Plugin.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using IsoMounter.Configuration;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Model.Serialization;
-
-namespace IsoMounter
-{
- public class Plugin : BasePlugin<PluginConfiguration>
- {
- public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer)
- {
- }
-
- private Guid _id = new Guid("4682DD4C-A675-4F1B-8E7C-79ADF137A8F8");
- public override Guid Id => _id;
-
- /// <summary>
- /// Gets the name of the plugin
- /// </summary>
- /// <value>The name.</value>
- public override string Name => "Iso Mounter";
-
- /// <summary>
- /// Gets the description.
- /// </summary>
- /// <value>The description.</value>
- public override string Description => "Mount and stream ISO contents";
- }
-}
diff --git a/Emby.IsoMounting/LICENSE b/Emby.IsoMounting/LICENSE
deleted file mode 100644
index d7f105139..000000000
--- a/Emby.IsoMounting/LICENSE
+++ /dev/null
@@ -1,339 +0,0 @@
-GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- {description}
- Copyright (C) {year} {fullname}
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- {signature of Ty Coon}, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
diff --git a/Emby.IsoMounting/README.md b/Emby.IsoMounting/README.md
deleted file mode 100644
index 78bab9936..000000000
--- a/Emby.IsoMounting/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# MediaBrowser.IsoMounting.Linux
-This implements two core interfaces, IIsoManager, and IIsoMount.
-### IIsoManager
-The manager class can be used to create a mount, and also determine if the mounter is capable of mounting a given file.
-### IIsoMount
-IIsoMount then represents a mount instance, which will be unmounted on disposal.
-***
-This Linux version use sudo, mount and umount.
-
-You need to add this to your sudo file via visudo(change the username):
-
- Defaults:jsmith !requiretty
- jsmith ALL=(root) NOPASSWD: /bin/mount
- jsmith ALL=(root) NOPASSWD: /bin/umount
diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs
index 7d029a9f4..bbfdccc90 100644
--- a/Emby.Naming/Audio/AlbumParser.cs
+++ b/Emby.Naming/Audio/AlbumParser.cs
@@ -1,30 +1,38 @@
using System;
using System.Globalization;
using System.IO;
-using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Common;
namespace Emby.Naming.Audio
{
+ /// <summary>
+ /// Helper class to determine if Album is multipart.
+ /// </summary>
public class AlbumParser
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AlbumParser"/> class.
+ /// </summary>
+ /// <param name="options">Naming options containing AlbumStackingPrefixes.</param>
public AlbumParser(NamingOptions options)
{
_options = options;
}
- public MultiPartResult ParseMultiPart(string path)
+ /// <summary>
+ /// Function that determines if album is multipart.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <returns>True if album is multipart.</returns>
+ public bool IsMultiPart(string path)
{
- var result = new MultiPartResult();
-
var filename = Path.GetFileName(path);
-
- if (string.IsNullOrEmpty(filename))
+ if (filename.Length == 0)
{
- return result;
+ return false;
}
// TODO: Move this logic into options object
@@ -33,31 +41,36 @@ namespace Emby.Naming.Audio
// Normalize
// Remove whitespace
- filename = filename.Replace("-", " ");
- filename = filename.Replace(".", " ");
- filename = filename.Replace("(", " ");
- filename = filename.Replace(")", " ");
+ filename = filename.Replace('-', ' ');
+ filename = filename.Replace('.', ' ');
+ filename = filename.Replace('(', ' ');
+ filename = filename.Replace(')', ' ');
filename = Regex.Replace(filename, @"\s+", " ");
- filename = filename.TrimStart();
+ ReadOnlySpan<char> trimmedFilename = filename.TrimStart();
foreach (var prefix in _options.AlbumStackingPrefixes)
{
- if (filename.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) == 0)
+ if (!trimmedFilename.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
- var tmp = filename.Substring(prefix.Length);
+ continue;
+ }
- tmp = tmp.Trim().Split(' ').FirstOrDefault() ?? string.Empty;
+ var tmp = trimmedFilename.Slice(prefix.Length).Trim();
- if (int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
- {
- result.IsMultiPart = true;
- break;
- }
+ int index = tmp.IndexOf(' ');
+ if (index != -1)
+ {
+ tmp = tmp.Slice(0, index);
+ }
+
+ if (int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out _))
+ {
+ return true;
}
}
- return result;
+ return false;
}
}
}
diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs
index 609eb779a..2b610ec79 100644
--- a/Emby.Naming/Audio/AudioFileParser.cs
+++ b/Emby.Naming/Audio/AudioFileParser.cs
@@ -1,23 +1,25 @@
using System;
using System.IO;
-using System.Linq;
using Emby.Naming.Common;
+using Jellyfin.Extensions;
namespace Emby.Naming.Audio
{
- public class AudioFileParser
+ /// <summary>
+ /// Static helper class to determine if file at path is audio file.
+ /// </summary>
+ public static class AudioFileParser
{
- private readonly NamingOptions _options;
-
- public AudioFileParser(NamingOptions options)
- {
- _options = options;
- }
-
- public bool IsAudioFile(string path)
+ /// <summary>
+ /// Static helper method to determine if file at path is audio file.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions.</param>
+ /// <returns>True if file at path is audio file.</returns>
+ public static bool IsAudioFile(string path, NamingOptions options)
{
- var extension = Path.GetExtension(path) ?? string.Empty;
- return _options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
+ var extension = Path.GetExtension(path.AsSpan());
+ return options.AudioFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
}
}
}
diff --git a/Emby.Naming/Audio/MultiPartResult.cs b/Emby.Naming/Audio/MultiPartResult.cs
deleted file mode 100644
index b1fa6e563..000000000
--- a/Emby.Naming/Audio/MultiPartResult.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace Emby.Naming.Audio
-{
- public class MultiPartResult
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets the part.
- /// </summary>
- /// <value>The part.</value>
- public string Part { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is multi part.
- /// </summary>
- /// <value><c>true</c> if this instance is multi part; otherwise, <c>false</c>.</value>
- public bool IsMultiPart { get; set; }
- }
-}
diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs
index de66a5402..862e39667 100644
--- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs
+++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs
@@ -3,44 +3,74 @@ using System;
namespace Emby.Naming.AudioBook
{
/// <summary>
- /// Represents a single video file
+ /// Represents a single video file.
/// </summary>
public class AudioBookFileInfo : IComparable<AudioBookFileInfo>
{
/// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookFileInfo"/> class.
+ /// </summary>
+ /// <param name="path">Path to audiobook file.</param>
+ /// <param name="container">File type.</param>
+ /// <param name="partNumber">Number of part this file represents.</param>
+ /// <param name="chapterNumber">Number of chapter this file represents.</param>
+ public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default)
+ {
+ Path = path;
+ Container = container;
+ PartNumber = partNumber;
+ ChapterNumber = chapterNumber;
+ }
+
+ /// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; set; }
+
/// <summary>
/// Gets or sets the container.
/// </summary>
/// <value>The container.</value>
public string Container { get; set; }
+
/// <summary>
/// Gets or sets the part number.
/// </summary>
/// <value>The part number.</value>
public int? PartNumber { get; set; }
+
/// <summary>
/// Gets or sets the chapter number.
/// </summary>
/// <value>The chapter number.</value>
public int? ChapterNumber { get; set; }
- /// <summary>
- /// Gets or sets the type.
- /// </summary>
- /// <value>The type.</value>
- public bool IsDirectory { get; set; }
- public int CompareTo(AudioBookFileInfo other)
+ /// <inheritdoc />
+ public int CompareTo(AudioBookFileInfo? other)
{
- if (ReferenceEquals(this, other)) return 0;
- if (ReferenceEquals(null, other)) return 1;
+ if (ReferenceEquals(this, other))
+ {
+ return 0;
+ }
+
+ if (ReferenceEquals(null, other))
+ {
+ return 1;
+ }
+
var chapterNumberComparison = Nullable.Compare(ChapterNumber, other.ChapterNumber);
- if (chapterNumberComparison != 0) return chapterNumberComparison;
+ if (chapterNumberComparison != 0)
+ {
+ return chapterNumberComparison;
+ }
+
var partNumberComparison = Nullable.Compare(PartNumber, other.PartNumber);
- if (partNumberComparison != 0) return partNumberComparison;
+ if (partNumberComparison != 0)
+ {
+ return partNumberComparison;
+ }
+
return string.Compare(Path, other.Path, StringComparison.Ordinal);
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
index 590979794..7b4429ab1 100644
--- a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
+++ b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
@@ -5,24 +5,30 @@ using Emby.Naming.Common;
namespace Emby.Naming.AudioBook
{
+ /// <summary>
+ /// Parser class to extract part and/or chapter number from audiobook filename.
+ /// </summary>
public class AudioBookFilePathParser
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookFilePathParser"/> class.
+ /// </summary>
+ /// <param name="options">Naming options containing AudioBookPartsExpressions.</param>
public AudioBookFilePathParser(NamingOptions options)
{
_options = options;
}
- public AudioBookFilePathParserResult Parse(string path, bool IsDirectory)
+ /// <summary>
+ /// Based on regex determines if filename includes part/chapter number.
+ /// </summary>
+ /// <param name="path">Path to audiobook file.</param>
+ /// <returns>Returns <see cref="AudioBookFilePathParser"/> object.</returns>
+ public AudioBookFilePathParserResult Parse(string path)
{
- var result = Parse(path);
- return !result.Success ? new AudioBookFilePathParserResult() : result;
- }
-
- private AudioBookFilePathParserResult Parse(string path)
- {
- var result = new AudioBookFilePathParserResult();
+ AudioBookFilePathParserResult result = default;
var fileName = Path.GetFileNameWithoutExtension(path);
foreach (var expression in _options.AudioBookPartsExpressions)
{
@@ -40,6 +46,7 @@ namespace Emby.Naming.AudioBook
}
}
}
+
if (!result.PartNumber.HasValue)
{
var value = match.Groups["part"];
@@ -47,27 +54,13 @@ namespace Emby.Naming.AudioBook
{
if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
{
- result.ChapterNumber = intValue;
+ result.PartNumber = intValue;
}
}
}
}
}
- /*var matches = _iRegexProvider.GetRegex("\\d+", RegexOptions.IgnoreCase).Matches(fileName);
- if (matches.Count > 0)
- {
- if (!result.ChapterNumber.HasValue)
- {
- result.ChapterNumber = int.Parse(matches[0].Groups[0].Value);
- }
- if (matches.Count > 1)
- {
- result.PartNumber = int.Parse(matches[matches.Count - 1].Groups[0].Value);
- }
- }*/
- result.Success = result.PartNumber.HasValue || result.ChapterNumber.HasValue;
-
return result;
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
index 3a8e3c31f..48ab8b57d 100644
--- a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
+++ b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
@@ -1,9 +1,18 @@
namespace Emby.Naming.AudioBook
{
- public class AudioBookFilePathParserResult
+ /// <summary>
+ /// Data object for passing result of audiobook part/chapter extraction.
+ /// </summary>
+ public struct AudioBookFilePathParserResult
{
+ /// <summary>
+ /// Gets or sets optional number of path extracted from audiobook filename.
+ /// </summary>
public int? PartNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional number of chapter extracted from audiobook filename.
+ /// </summary>
public int? ChapterNumber { get; set; }
- public bool Success { get; set; }
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs
index f6e1d5be4..acd8905af 100644
--- a/Emby.Naming/AudioBook/AudioBookInfo.cs
+++ b/Emby.Naming/AudioBook/AudioBookInfo.cs
@@ -3,37 +3,54 @@ using System.Collections.Generic;
namespace Emby.Naming.AudioBook
{
/// <summary>
- /// Represents a complete video, including all parts and subtitles
+ /// Represents a complete video, including all parts and subtitles.
/// </summary>
public class AudioBookInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookInfo" /> class.
+ /// </summary>
+ /// <param name="name">Name of audiobook.</param>
+ /// <param name="year">Year of audiobook release.</param>
+ /// <param name="files">List of files composing the actual audiobook.</param>
+ /// <param name="extras">List of extra files.</param>
+ /// <param name="alternateVersions">Alternative version of files.</param>
+ public AudioBookInfo(string name, int? year, IReadOnlyList<AudioBookFileInfo> files, IReadOnlyList<AudioBookFileInfo> extras, IReadOnlyList<AudioBookFileInfo> alternateVersions)
+ {
+ Name = name;
+ Year = year;
+ Files = files;
+ Extras = extras;
+ AlternateVersions = alternateVersions;
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the year.
+ /// </summary>
public int? Year { get; set; }
+
/// <summary>
/// Gets or sets the files.
/// </summary>
/// <value>The files.</value>
- public List<AudioBookFileInfo> Files { get; set; }
+ public IReadOnlyList<AudioBookFileInfo> Files { get; set; }
+
/// <summary>
/// Gets or sets the extras.
/// </summary>
/// <value>The extras.</value>
- public List<AudioBookFileInfo> Extras { get; set; }
+ public IReadOnlyList<AudioBookFileInfo> Extras { get; set; }
+
/// <summary>
/// Gets or sets the alternate versions.
/// </summary>
/// <value>The alternate versions.</value>
- public List<AudioBookFileInfo> AlternateVersions { get; set; }
-
- public AudioBookInfo()
- {
- Files = new List<AudioBookFileInfo>();
- Extras = new List<AudioBookFileInfo>();
- AlternateVersions = new List<AudioBookFileInfo>();
- }
+ public IReadOnlyList<AudioBookFileInfo> AlternateVersions { get; set; }
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs
index 4e3ad7cac..1e4a8d2ed 100644
--- a/Emby.Naming/AudioBook/AudioBookListResolver.cs
+++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs
@@ -1,4 +1,6 @@
+using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using Emby.Naming.Common;
using Emby.Naming.Video;
@@ -6,61 +8,145 @@ using MediaBrowser.Model.IO;
namespace Emby.Naming.AudioBook
{
+ /// <summary>
+ /// Class used to resolve Name, Year, alternative files and extras from stack of files.
+ /// </summary>
public class AudioBookListResolver
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookListResolver"/> class.
+ /// </summary>
+ /// <param name="options">Naming options passed along to <see cref="AudioBookResolver"/> and <see cref="AudioBookNameParser"/>.</param>
public AudioBookListResolver(NamingOptions options)
{
_options = options;
}
- public IEnumerable<AudioBookInfo> Resolve(List<FileSystemMetadata> files)
+ /// <summary>
+ /// Resolves Name, Year and differentiate alternative files and extras from regular audiobook files.
+ /// </summary>
+ /// <param name="files">List of files related to audiobook.</param>
+ /// <returns>Returns IEnumerable of <see cref="AudioBookInfo"/>.</returns>
+ public IEnumerable<AudioBookInfo> Resolve(IEnumerable<FileSystemMetadata> files)
{
var audioBookResolver = new AudioBookResolver(_options);
+ // File with empty fullname will be sorted out here.
var audiobookFileInfos = files
- .Select(i => audioBookResolver.Resolve(i.FullName, i.IsDirectory))
- .Where(i => i != null)
+ .Select(i => audioBookResolver.Resolve(i.FullName))
+ .OfType<AudioBookFileInfo>()
.ToList();
- // Filter out all extras, otherwise they could cause stacks to not be resolved
- // See the unit test TestStackedWithTrailer
- var metadata = audiobookFileInfos
- .Select(i => new FileSystemMetadata
- {
- FullName = i.Path,
- IsDirectory = i.IsDirectory
- });
-
var stackResult = new StackResolver(_options)
- .ResolveAudioBooks(metadata);
-
- var list = new List<AudioBookInfo>();
+ .ResolveAudioBooks(audiobookFileInfos);
- foreach (var stack in stackResult.Stacks)
+ foreach (var stack in stackResult)
{
- var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).ToList();
+ var stackFiles = stack.Files
+ .Select(i => audioBookResolver.Resolve(i))
+ .OfType<AudioBookFileInfo>()
+ .ToList();
+
stackFiles.Sort();
- var info = new AudioBookInfo
- {
- Files = stackFiles,
- Name = stack.Name
- };
- list.Add(info);
+
+ var nameParserResult = new AudioBookNameParser(_options).Parse(stack.Name);
+
+ FindExtraAndAlternativeFiles(ref stackFiles, out var extras, out var alternativeVersions, nameParserResult);
+
+ var info = new AudioBookInfo(
+ nameParserResult.Name,
+ nameParserResult.Year,
+ stackFiles,
+ extras,
+ alternativeVersions);
+
+ yield return info;
}
+ }
+
+ private void FindExtraAndAlternativeFiles(ref List<AudioBookFileInfo> stackFiles, out List<AudioBookFileInfo> extras, out List<AudioBookFileInfo> alternativeVersions, AudioBookNameParserResult nameParserResult)
+ {
+ extras = new List<AudioBookFileInfo>();
+ alternativeVersions = new List<AudioBookFileInfo>();
- // Whatever files are left, just add them
- /*list.AddRange(remainingFiles.Select(i => new AudioBookInfo
+ var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber != null || x.PartNumber != null);
+ var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber });
+ var nameWithReplacedDots = nameParserResult.Name.Replace(' ', '.');
+
+ foreach (var group in groupedBy)
{
- Files = new List<AudioBookFileInfo> { i },
- Name = i.,
- Year = i.Year
- }));*/
+ if (group.Key.ChapterNumber == null && group.Key.PartNumber == null)
+ {
+ if (group.Count() > 1 || haveChaptersOrPages)
+ {
+ var ex = new List<AudioBookFileInfo>();
+ var alt = new List<AudioBookFileInfo>();
+
+ foreach (var audioFile in group)
+ {
+ var name = Path.GetFileNameWithoutExtension(audioFile.Path);
+ if (name.Equals("audiobook", StringComparison.OrdinalIgnoreCase) ||
+ name.Contains(nameParserResult.Name, StringComparison.OrdinalIgnoreCase) ||
+ name.Contains(nameWithReplacedDots, StringComparison.OrdinalIgnoreCase))
+ {
+ alt.Add(audioFile);
+ }
+ else
+ {
+ ex.Add(audioFile);
+ }
+ }
+
+ if (ex.Count > 0)
+ {
+ var extra = ex
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .ToList();
+
+ stackFiles = stackFiles.Except(extra).ToList();
+ extras.AddRange(extra);
+ }
+
+ if (alt.Count > 0)
+ {
+ var alternatives = alt
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .ToList();
- var orderedList = list.OrderBy(i => i.Name);
+ var main = FindMainAudioBookFile(alternatives, nameParserResult.Name);
+ alternatives.Remove(main);
+ stackFiles = stackFiles.Except(alternatives).ToList();
+ alternativeVersions.AddRange(alternatives);
+ }
+ }
+ }
+ else if (group.Count() > 1)
+ {
+ var alternatives = group
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .Skip(1)
+ .ToList();
+
+ stackFiles = stackFiles.Except(alternatives).ToList();
+ alternativeVersions.AddRange(alternatives);
+ }
+ }
+ }
+
+ private AudioBookFileInfo FindMainAudioBookFile(List<AudioBookFileInfo> files, string name)
+ {
+ var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name, StringComparison.OrdinalIgnoreCase));
+ main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook", StringComparison.OrdinalIgnoreCase));
+ main ??= files.OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .First();
- return orderedList;
+ return main;
}
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookNameParser.cs b/Emby.Naming/AudioBook/AudioBookNameParser.cs
new file mode 100644
index 000000000..120482bc2
--- /dev/null
+++ b/Emby.Naming/AudioBook/AudioBookNameParser.cs
@@ -0,0 +1,67 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Emby.Naming.Common;
+
+namespace Emby.Naming.AudioBook
+{
+ /// <summary>
+ /// Helper class to retrieve name and year from audiobook previously retrieved name.
+ /// </summary>
+ public class AudioBookNameParser
+ {
+ private readonly NamingOptions _options;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookNameParser"/> class.
+ /// </summary>
+ /// <param name="options">Naming options containing AudioBookNamesExpressions.</param>
+ public AudioBookNameParser(NamingOptions options)
+ {
+ _options = options;
+ }
+
+ /// <summary>
+ /// Parse name and year from previously determined name of audiobook.
+ /// </summary>
+ /// <param name="name">Name of the audiobook.</param>
+ /// <returns>Returns <see cref="AudioBookNameParserResult"/> object.</returns>
+ public AudioBookNameParserResult Parse(string name)
+ {
+ AudioBookNameParserResult result = default;
+ foreach (var expression in _options.AudioBookNamesExpressions)
+ {
+ var match = new Regex(expression, RegexOptions.IgnoreCase).Match(name);
+ if (match.Success)
+ {
+ if (result.Name == null)
+ {
+ var value = match.Groups["name"];
+ if (value.Success)
+ {
+ result.Name = value.Value;
+ }
+ }
+
+ if (!result.Year.HasValue)
+ {
+ var value = match.Groups["year"];
+ if (value.Success)
+ {
+ if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
+ {
+ result.Year = intValue;
+ }
+ }
+ }
+ }
+ }
+
+ if (string.IsNullOrEmpty(result.Name))
+ {
+ result.Name = name;
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/Emby.Naming/AudioBook/AudioBookNameParserResult.cs b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs
new file mode 100644
index 000000000..3f2d7b2b0
--- /dev/null
+++ b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs
@@ -0,0 +1,18 @@
+namespace Emby.Naming.AudioBook
+{
+ /// <summary>
+ /// Data object used to pass result of name and year parsing.
+ /// </summary>
+ public struct AudioBookNameParserResult
+ {
+ /// <summary>
+ /// Gets or sets name of audiobook.
+ /// </summary>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional year of release.
+ /// </summary>
+ public int? Year { get; set; }
+ }
+}
diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs
index 67ab62e80..f6ad3601d 100644
--- a/Emby.Naming/AudioBook/AudioBookResolver.cs
+++ b/Emby.Naming/AudioBook/AudioBookResolver.cs
@@ -5,38 +5,37 @@ using Emby.Naming.Common;
namespace Emby.Naming.AudioBook
{
+ /// <summary>
+ /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
+ /// </summary>
public class AudioBookResolver
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookResolver"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions and also used to pass to AudioBookFilePathParser.</param>
public AudioBookResolver(NamingOptions options)
{
_options = options;
}
- public AudioBookFileInfo ParseFile(string path)
+ /// <summary>
+ /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
+ /// </summary>
+ /// <param name="path">Path to audiobook file.</param>
+ /// <returns>Returns <see cref="AudioBookResolver"/> object.</returns>
+ public AudioBookFileInfo? Resolve(string path)
{
- return Resolve(path, false);
- }
-
- public AudioBookFileInfo ParseDirectory(string path)
- {
- return Resolve(path, true);
- }
-
- public AudioBookFileInfo Resolve(string path, bool IsDirectory = false)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- if (IsDirectory) // TODO
+ if (path.Length == 0 || Path.GetFileNameWithoutExtension(path).Length == 0)
{
+ // Return null to indicate this path will not be used, instead of stopping whole process with exception
return null;
}
var extension = Path.GetExtension(path);
+
// Check supported extensions
if (!_options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
@@ -45,17 +44,13 @@ namespace Emby.Naming.AudioBook
var container = extension.TrimStart('.');
- var parsingResult = new AudioBookFilePathParser(_options)
- .Parse(path, IsDirectory);
+ var parsingResult = new AudioBookFilePathParser(_options).Parse(path);
- return new AudioBookFileInfo
- {
- Path = path,
- Container = container,
- PartNumber = parsingResult.PartNumber,
- ChapterNumber = parsingResult.ChapterNumber,
- IsDirectory = IsDirectory
- };
+ return new AudioBookFileInfo(
+ path,
+ container,
+ chapterNumber: parsingResult.ChapterNumber,
+ partNumber: parsingResult.PartNumber);
}
}
}
diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs
index fd85bf76a..19d3c7aab 100644
--- a/Emby.Naming/Common/EpisodeExpression.cs
+++ b/Emby.Naming/Common/EpisodeExpression.cs
@@ -3,38 +3,68 @@ using System.Text.RegularExpressions;
namespace Emby.Naming.Common
{
+ /// <summary>
+ /// Regular expressions for parsing TV Episodes.
+ /// </summary>
public class EpisodeExpression
{
private string _expression;
- public string Expression { get => _expression;
- set { _expression = value; _regex = null; } }
+ private Regex? _regex;
- public bool IsByDate { get; set; }
- public bool IsOptimistic { get; set; }
- public bool IsNamed { get; set; }
- public bool SupportsAbsoluteEpisodeNumbers { get; set; }
-
- public string[] DateTimeFormats { get; set; }
-
- private Regex _regex;
- public Regex Regex => _regex ?? (_regex = new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled));
-
- public EpisodeExpression(string expression, bool byDate)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeExpression"/> class.
+ /// </summary>
+ /// <param name="expression">Regular expressions.</param>
+ /// <param name="byDate">True if date is expected.</param>
+ public EpisodeExpression(string expression, bool byDate = false)
{
- Expression = expression;
+ _expression = expression;
IsByDate = byDate;
DateTimeFormats = Array.Empty<string>();
SupportsAbsoluteEpisodeNumbers = true;
}
- public EpisodeExpression(string expression)
- : this(expression, false)
+ /// <summary>
+ /// Gets or sets raw expressions string.
+ /// </summary>
+ public string Expression
{
+ get => _expression;
+ set
+ {
+ _expression = value;
+ _regex = null;
+ }
}
- public EpisodeExpression()
- : this(null)
- {
- }
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets property indicating if date can be find in expression.
+ /// </summary>
+ public bool IsByDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression is optimistic.
+ /// </summary>
+ public bool IsOptimistic { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression is named.
+ /// </summary>
+ public bool IsNamed { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression supports episodes with absolute numbers.
+ /// </summary>
+ public bool SupportsAbsoluteEpisodeNumbers { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional list of date formats used for date parsing.
+ /// </summary>
+ public string[] DateTimeFormats { get; set; }
+
+ /// <summary>
+ /// Gets a <see cref="Regex"/> expressions objects (creates it if null).
+ /// </summary>
+ public Regex Regex => _regex ??= new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
diff --git a/Emby.Naming/Common/MediaType.cs b/Emby.Naming/Common/MediaType.cs
index 49cc9ee39..dc9784c6d 100644
--- a/Emby.Naming/Common/MediaType.cs
+++ b/Emby.Naming/Common/MediaType.cs
@@ -1,17 +1,22 @@
namespace Emby.Naming.Common
{
+ /// <summary>
+ /// Type of audiovisual media.
+ /// </summary>
public enum MediaType
{
/// <summary>
- /// The audio
+ /// The audio.
/// </summary>
Audio = 0,
+
/// <summary>
- /// The photo
+ /// The photo.
/// </summary>
Photo = 1,
+
/// <summary>
- /// The video
+ /// The video.
/// </summary>
Video = 2
}
diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs
index 2ef0208ba..6355f8b1b 100644
--- a/Emby.Naming/Common/NamingOptions.cs
+++ b/Emby.Naming/Common/NamingOptions.cs
@@ -2,46 +2,23 @@ using System;
using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Video;
+using MediaBrowser.Model.Entities;
+
+// ReSharper disable StringLiteralTypo
namespace Emby.Naming.Common
{
+ /// <summary>
+ /// Big ugly class containing lot of different naming options that should be split and injected instead of passes everywhere.
+ /// </summary>
public class NamingOptions
{
- public string[] AudioFileExtensions { get; set; }
- public string[] AlbumStackingPrefixes { get; set; }
-
- public string[] SubtitleFileExtensions { get; set; }
- public char[] SubtitleFlagDelimiters { get; set; }
-
- public string[] SubtitleForcedFlags { get; set; }
- public string[] SubtitleDefaultFlags { get; set; }
-
- public EpisodeExpression[] EpisodeExpressions { get; set; }
- public string[] EpisodeWithoutSeasonExpressions { get; set; }
- public string[] EpisodeMultiPartExpressions { get; set; }
-
- public string[] VideoFileExtensions { get; set; }
- public string[] StubFileExtensions { get; set; }
-
- public string[] AudioBookPartsExpressions { get; set; }
-
- public StubTypeRule[] StubTypes { get; set; }
-
- public char[] VideoFlagDelimiters { get; set; }
- public Format3DRule[] Format3DRules { get; set; }
-
- public string[] VideoFileStackingExpressions { get; set; }
- public string[] CleanDateTimes { get; set; }
- public string[] CleanStrings { get; set; }
-
-
- public EpisodeExpression[] MultipleEpisodeExpressions { get; set; }
-
- public ExtraRule[] VideoExtraRules { get; set; }
-
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NamingOptions"/> class.
+ /// </summary>
public NamingOptions()
{
- VideoFileExtensions = new string[]
+ VideoFileExtensions = new[]
{
".m4v",
".3gp",
@@ -104,75 +81,67 @@ namespace Emby.Naming.Common
StubTypes = new[]
{
- new StubTypeRule
- {
- StubType = "dvd",
- Token = "dvd"
- },
- new StubTypeRule
- {
- StubType = "hddvd",
- Token = "hddvd"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bluray"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "brrip"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bd25"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bd50"
- },
- new StubTypeRule
- {
- StubType = "vhs",
- Token = "vhs"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "HDTV"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "PDTV"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "DSR"
- }
+ new StubTypeRule(
+ stubType: "dvd",
+ token: "dvd"),
+
+ new StubTypeRule(
+ stubType: "hddvd",
+ token: "hddvd"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bluray"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "brrip"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bd25"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bd50"),
+
+ new StubTypeRule(
+ stubType: "vhs",
+ token: "vhs"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "HDTV"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "PDTV"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "DSR")
};
VideoFileStackingExpressions = new[]
{
- "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(.*?)(\\.[^.]+)$",
- "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(.*?)(\\.[^.]+)$",
- "(.*?)([ ._-]*[a-d])(.*?)(\\.[^.]+)$"
+ "(?<title>.*?)(?<volume>[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(?<ignore>.*?)(?<extension>\\.[^.]+)$",
+ "(?<title>.*?)(?<volume>[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(?<ignore>.*?)(?<extension>\\.[^.]+)$",
+ "(?<title>.*?)(?<volume>[ ._-]*[a-d])(?<ignore>.*?)(?<extension>\\.[^.]+)$"
};
CleanDateTimes = new[]
{
- @"(.+[^ _\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9][0-9]|20[0-1][0-9])([ _\,\.\(\)\[\]\-][^0-9]|$)"
+ @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*",
+ @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*"
};
CleanStrings = new[]
{
- @"[ _\,\.\(\)\[\]\-](ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
- @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
- @"(\[.*\])"
+ @"^\s*(?<cleaned>.+?)[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|blu-ray|x264|x265|h264|h265|xvid|xvidvd|xxx|www.www|AAC|DTS|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
+ @"^(?<cleaned>.+?)(\[.*\])",
+ @"^\s*(?<cleaned>.+?)\WE[0-9]+(-|~)E?[0-9]+(\W|$)",
+ @"^\s*\[[^\]]+\](?!\.\w+$)\s*(?<cleaned>.+)",
+ @"^\s*(?<cleaned>.+?)\s+-\s+[0-9]+\s*$"
};
SubtitleFileExtensions = new[]
@@ -284,18 +253,18 @@ namespace Emby.Naming.Common
},
// <!-- foo.ep01, foo.EP_01 -->
new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"),
- new EpisodeExpression("([0-9]{4})[\\.-]([0-9]{2})[\\.-]([0-9]{2})", true)
+ new EpisodeExpression("(?<year>[0-9]{4})[\\.-](?<month>[0-9]{2})[\\.-](?<day>[0-9]{2})", true)
{
- DateTimeFormats = new []
+ DateTimeFormats = new[]
{
"yyyy.MM.dd",
"yyyy-MM-dd",
"yyyy_MM_dd"
}
},
- new EpisodeExpression("([0-9]{2})[\\.-]([0-9]{2})[\\.-]([0-9]{4})", true)
+ new EpisodeExpression(@"(?<day>[0-9]{2})[.-](?<month>[0-9]{2})[.-](?<year>[0-9]{4})", true)
{
- DateTimeFormats = new []
+ DateTimeFormats = new[]
{
"dd.MM.yyyy",
"dd-MM-yyyy",
@@ -303,11 +272,30 @@ namespace Emby.Naming.Common
}
},
- new EpisodeExpression("[\\\\/\\._ \\[\\(-]([0-9]+)x([0-9]+(?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([^\\\\/]*)$")
+ // This isn't a Kodi naming rule, but the expression below causes false positives,
+ // so we make sure this one gets tested first.
+ // "Foo Bar 889"
+ new EpisodeExpression(@".*[\\\/](?![Ee]pisode)(?<seriesname>[\w\s]+?)\s(?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*[^\\\/x]*$")
+ {
+ IsNamed = true
+ },
+
+ new EpisodeExpression(@"[\\\/\._ \[\(-]([0-9]+)x([0-9]+(?:(?:[a-i]|\.[1-9])(?![0-9]))?)([^\\\/]*)$")
{
SupportsAbsoluteEpisodeNumbers = true
},
- new EpisodeExpression(@"[\\\\/\\._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/])*)[\\\\/\\._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([\\._ -][^\\\\/]*)$")
+
+ // Not a Kodi rule as well, but below rule also causes false positives for triple-digit episode names
+ // [bar] Foo - 1 [baz] special case of below expression to prevent false positives with digits in the series name
+ new EpisodeExpression(@".*[\\\/]?.*?(\[.*?\])+.*?(?<seriesname>[-\w\s]+?)[\s_]*-[\s_]*(?<epnumber>[0-9]+).*$")
+ {
+ IsNamed = true
+ },
+
+ // /server/anything_102.mp4
+ // /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv
+ // /server/anything_1996.11.14.mp4
+ new EpisodeExpression(@"[\\/._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/_])*)[\\\/._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\.[1-9])(?![0-9]))?)([._ -][^\\\/]*)$")
{
IsOptimistic = true,
IsNamed = true,
@@ -320,71 +308,69 @@ namespace Emby.Naming.Common
// *** End Kodi Standard Naming
- new EpisodeExpression(@".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})[^\\\/]*$")
+ // "Episode 16", "Episode 16 - Title"
+ new EpisodeExpression(@"[Ee]pisode (?<epnumber>[0-9]+)(-(?<endingepnumber>[0-9]+))?[^\\\/]*$")
{
IsNamed = true
},
- new EpisodeExpression(@".*(\\|\/)[sS](?<seasonnumber>\d{1,4})[x,X]?[eE](?<epnumber>\d{1,3})[^\\\/]*$")
+ new EpisodeExpression(@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]+)[xX](?<epnumber>[0-9]+)[^\\\/]*$")
{
IsNamed = true
},
- new EpisodeExpression(@".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))[^\\\/]*$")
+ new EpisodeExpression(@".*(\\|\/)[sS](?<seasonnumber>[0-9]+)[x,X]?[eE](?<epnumber>[0-9]+)[^\\\/]*$")
{
IsNamed = true
},
- new EpisodeExpression(@".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})[^\\\/]*$")
+ new EpisodeExpression(@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]+))[^\\\/]*$")
+ {
+ IsNamed = true
+ },
+
+ new EpisodeExpression(@".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]+)[^\\\/]*$")
{
IsNamed = true
},
// "01.avi"
- new EpisodeExpression(@".*[\\\/](?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.\w+$")
+ new EpisodeExpression(@".*[\\\/](?<epnumber>[0-9]+)(-(?<endingepnumber>[0-9]+))*\.\w+$")
{
IsOptimistic = true,
IsNamed = true
},
// "1-12 episode title"
- new EpisodeExpression(@"([0-9]+)-([0-9]+)")
- {
- },
+ new EpisodeExpression(@"([0-9]+)-([0-9]+)"),
// "01 - blah.avi", "01-blah.avi"
- new EpisodeExpression(@".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\s?-\s?[^\\\/]*$")
+ new EpisodeExpression(@".*(\\|\/)(?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*\s?-\s?[^\\\/]*$")
{
IsOptimistic = true,
IsNamed = true
},
// "01.blah.avi"
- new EpisodeExpression(@".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.[^\\\/]+$")
+ new EpisodeExpression(@".*(\\|\/)(?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*\.[^\\\/]+$")
{
IsOptimistic = true,
IsNamed = true
},
// "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah"
- new EpisodeExpression(@".*[\\\/][^\\\/]* - (?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*[^\\\/]*$")
+ new EpisodeExpression(@".*[\\\/][^\\\/]* - (?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*[^\\\/]*$")
{
IsOptimistic = true,
IsNamed = true
},
// "01 episode title.avi"
- new EpisodeExpression(@"[Ss]eason[\._ ](?<seasonnumber>[0-9]+)[\\\/](?<epnumber>\d{1,3})([^\\\/]*)$")
+ new EpisodeExpression(@"[Ss]eason[\._ ](?<seasonnumber>[0-9]+)[\\\/](?<epnumber>[0-9]{1,3})([^\\\/]*)$")
{
IsOptimistic = true,
IsNamed = true
},
- // "Episode 16", "Episode 16 - Title"
- new EpisodeExpression(@".*[\\\/][^\\\/]* (?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*[^\\\/]*$")
- {
- IsOptimistic = true,
- IsNamed = true
- }
};
EpisodeWithoutSeasonExpressions = new[]
@@ -399,206 +385,220 @@ namespace Emby.Naming.Common
VideoExtraRules = new[]
{
- new ExtraRule
- {
- ExtraType = "trailer",
- RuleType = ExtraRuleType.Filename,
- Token = "trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "trailer",
- RuleType = ExtraRuleType.Suffix,
- Token = "-trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "trailer",
- RuleType = ExtraRuleType.Suffix,
- Token = ".trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "trailer",
- RuleType = ExtraRuleType.Suffix,
- Token = "_trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "trailer",
- RuleType = ExtraRuleType.Suffix,
- Token = " trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "sample",
- RuleType = ExtraRuleType.Filename,
- Token = "sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "sample",
- RuleType = ExtraRuleType.Suffix,
- Token = "-sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "sample",
- RuleType = ExtraRuleType.Suffix,
- Token = ".sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "sample",
- RuleType = ExtraRuleType.Suffix,
- Token = "_sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "sample",
- RuleType = ExtraRuleType.Suffix,
- Token = " sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "themesong",
- RuleType = ExtraRuleType.Filename,
- Token = "theme",
- MediaType = MediaType.Audio
- },
-
- new ExtraRule
- {
- ExtraType = "scene",
- RuleType = ExtraRuleType.Suffix,
- Token = "-scene",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "clip",
- RuleType = ExtraRuleType.Suffix,
- Token = "-clip",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "interview",
- RuleType = ExtraRuleType.Suffix,
- Token = "-interview",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "behindthescenes",
- RuleType = ExtraRuleType.Suffix,
- Token = "-behindthescenes",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "deletedscene",
- RuleType = ExtraRuleType.Suffix,
- Token = "-deleted",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "featurette",
- RuleType = ExtraRuleType.Suffix,
- Token = "-featurette",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = "short",
- RuleType = ExtraRuleType.Suffix,
- Token = "-short",
- MediaType = MediaType.Video
- }
-
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Filename,
+ "trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ "-trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ ".trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ "_trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ " trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Filename,
+ "sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ "-sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ ".sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ "_sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ " sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.ThemeSong,
+ ExtraRuleType.Filename,
+ "theme",
+ MediaType.Audio),
+
+ new ExtraRule(
+ ExtraType.Scene,
+ ExtraRuleType.Suffix,
+ "-scene",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-clip",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Interview,
+ ExtraRuleType.Suffix,
+ "-interview",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.BehindTheScenes,
+ ExtraRuleType.Suffix,
+ "-behindthescenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.DeletedScene,
+ ExtraRuleType.Suffix,
+ "-deleted",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.DeletedScene,
+ ExtraRuleType.Suffix,
+ "-deletedscene",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-featurette",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-short",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.BehindTheScenes,
+ ExtraRuleType.DirectoryName,
+ "behind the scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.DeletedScene,
+ ExtraRuleType.DirectoryName,
+ "deleted scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Interview,
+ ExtraRuleType.DirectoryName,
+ "interviews",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Scene,
+ ExtraRuleType.DirectoryName,
+ "scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.DirectoryName,
+ "samples",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.DirectoryName,
+ "shorts",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.DirectoryName,
+ "featurettes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Unknown,
+ ExtraRuleType.DirectoryName,
+ "extras",
+ MediaType.Video),
};
+
Format3DRules = new[]
{
// Kodi rules:
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "hsbs"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "sbs"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "htab"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "tab"
- },
- // Media Browser rules:
- new Format3DRule
- {
- Token = "fsbs"
- },
- new Format3DRule
- {
- Token = "hsbs"
- },
- new Format3DRule
- {
- Token = "sbs"
- },
- new Format3DRule
- {
- Token = "ftab"
- },
- new Format3DRule
- {
- Token = "htab"
- },
- new Format3DRule
- {
- Token = "tab"
- },
- new Format3DRule
- {
- Token = "sbs3d"
- },
- new Format3DRule
- {
- Token = "mvc"
- }
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "hsbs"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "sbs"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "htab"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "tab"),
+
+ // Media Browser rules:
+ new Format3DRule("fsbs"),
+ new Format3DRule("hsbs"),
+ new Format3DRule("sbs"),
+ new Format3DRule("ftab"),
+ new Format3DRule("htab"),
+ new Format3DRule("tab"),
+ new Format3DRule("sbs3d"),
+ new Format3DRule("mvc")
};
+
AudioBookPartsExpressions = new[]
{
// Detect specified chapters, like CH 01
- @"ch(?:apter)?[\s_-]?(?<chapter>\d+)",
+ @"ch(?:apter)?[\s_-]?(?<chapter>[0-9]+)",
// Detect specified parts, like Part 02
- @"p(?:ar)?t[\s_-]?(?<part>\d+)",
+ @"p(?:ar)?t[\s_-]?(?<part>[0-9]+)",
// Chapter is often beginning of filename
- @"^(?<chapter>\d+)",
+ "^(?<chapter>[0-9]+)",
// Part if often ending of filename
- @"(?<part>\d+)$",
+ @"(?<!ch(?:apter) )(?<part>[0-9]+)$",
// Sometimes named as 0001_005 (chapter_part)
- @"(?<chapter>\d+)_(?<part>\d+)",
+ "(?<chapter>[0-9]+)_(?<part>[0-9]+)",
// Some audiobooks are ripped from cd's, and will be named by disk number.
- @"dis(?:c|k)[\s_-]?(?<chapter>\d+)"
+ @"dis(?:c|k)[\s_-]?(?<chapter>[0-9]+)"
+ };
+
+ AudioBookNamesExpressions = new[]
+ {
+ // Detect year usually in brackets after name Batman (2020)
+ @"^(?<name>.+?)\s*\(\s*(?<year>[0-9]{4})\s*\)\s*$",
+ @"^\s*(?<name>[^ ].*?)\s*$"
};
var extensions = VideoFileExtensions.ToList();
@@ -636,23 +636,21 @@ namespace Emby.Naming.Common
".mxf"
});
- MultipleEpisodeExpressions = new string[]
+ MultipleEpisodeExpressions = new[]
{
- @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[eExX](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})(-[xE]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
- @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$"
-
+ @".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )[0-9]{1,4}[eExX](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )[0-9]{1,4}[xX][eE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})(-[xE]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )[0-9]{1,4}[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )[0-9]{1,4}[xX][eE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))(-[xX]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]{1,3})((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
+ @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]{1,3})(-[xX]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$"
}.Select(i => new EpisodeExpression(i)
{
IsNamed = true
-
}).ToArray();
VideoFileExtensions = extensions
@@ -662,13 +660,139 @@ namespace Emby.Naming.Common
Compile();
}
- public Regex[] VideoFileStackingRegexes { get; private set; }
- public Regex[] CleanDateTimeRegexes { get; private set; }
- public Regex[] CleanStringRegexes { get; private set; }
+ /// <summary>
+ /// Gets or sets list of audio file extensions.
+ /// </summary>
+ public string[] AudioFileExtensions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of album stacking prefixes.
+ /// </summary>
+ public string[] AlbumStackingPrefixes { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of subtitle file extensions.
+ /// </summary>
+ public string[] SubtitleFileExtensions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of subtitles flag delimiters.
+ /// </summary>
+ public char[] SubtitleFlagDelimiters { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of subtitle forced flags.
+ /// </summary>
+ public string[] SubtitleForcedFlags { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of subtitle default flags.
+ /// </summary>
+ public string[] SubtitleDefaultFlags { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of episode regular expressions.
+ /// </summary>
+ public EpisodeExpression[] EpisodeExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw episode without season regular expressions strings.
+ /// </summary>
+ public string[] EpisodeWithoutSeasonExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw multi-part episodes regular expressions strings.
+ /// </summary>
+ public string[] EpisodeMultiPartExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of video file extensions.
+ /// </summary>
+ public string[] VideoFileExtensions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of video stub file extensions.
+ /// </summary>
+ public string[] StubFileExtensions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw audiobook parts regular expressions strings.
+ /// </summary>
+ public string[] AudioBookPartsExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw audiobook names regular expressions strings.
+ /// </summary>
+ public string[] AudioBookNamesExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of stub type rules.
+ /// </summary>
+ public StubTypeRule[] StubTypes { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of video flag delimiters.
+ /// </summary>
+ public char[] VideoFlagDelimiters { get; set; }
- public Regex[] EpisodeWithoutSeasonRegexes { get; private set; }
- public Regex[] EpisodeMultiPartRegexes { get; private set; }
+ /// <summary>
+ /// Gets or sets list of 3D Format rules.
+ /// </summary>
+ public Format3DRule[] Format3DRules { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw video file-stacking expressions strings.
+ /// </summary>
+ public string[] VideoFileStackingExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw clean DateTimes regular expressions strings.
+ /// </summary>
+ public string[] CleanDateTimes { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of raw clean strings regular expressions strings.
+ /// </summary>
+ public string[] CleanStrings { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of multi-episode regular expressions.
+ /// </summary>
+ public EpisodeExpression[] MultipleEpisodeExpressions { get; set; }
+
+ /// <summary>
+ /// Gets or sets list of extra rules for videos.
+ /// </summary>
+ public ExtraRule[] VideoExtraRules { get; set; }
+ /// <summary>
+ /// Gets list of video file-stack regular expressions.
+ /// </summary>
+ public Regex[] VideoFileStackingRegexes { get; private set; } = Array.Empty<Regex>();
+
+ /// <summary>
+ /// Gets list of clean datetime regular expressions.
+ /// </summary>
+ public Regex[] CleanDateTimeRegexes { get; private set; } = Array.Empty<Regex>();
+
+ /// <summary>
+ /// Gets list of clean string regular expressions.
+ /// </summary>
+ public Regex[] CleanStringRegexes { get; private set; } = Array.Empty<Regex>();
+
+ /// <summary>
+ /// Gets list of episode without season regular expressions.
+ /// </summary>
+ public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } = Array.Empty<Regex>();
+
+ /// <summary>
+ /// Gets list of multi-part episode regular expressions.
+ /// </summary>
+ public Regex[] EpisodeMultiPartRegexes { get; private set; } = Array.Empty<Regex>();
+
+ /// <summary>
+ /// Compiles raw regex strings into regexes.
+ /// </summary>
public void Compile()
{
VideoFileStackingRegexes = VideoFileStackingExpressions.Select(Compile).ToArray();
diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj
index e344e7811..e9e9edda6 100644
--- a/Emby.Naming/Emby.Naming.csproj
+++ b/Emby.Naming/Emby.Naming.csproj
@@ -1,23 +1,51 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <ProjectGuid>{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </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>
- <Compile Include="..\SharedVersion.cs" />
+ <Compile Include="../SharedVersion.cs" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
+ <ProjectReference Include="../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ <ProjectReference Include="../MediaBrowser.Model/MediaBrowser.Model.csproj" />
</ItemGroup>
<PropertyGroup>
<Authors>Jellyfin Contributors</Authors>
<PackageId>Jellyfin.Naming</PackageId>
- <PackageLicenseUrl>https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt</PackageLicenseUrl>
+ <VersionPrefix>10.8.0</VersionPrefix>
<RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
</PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/Emby.Naming/Extensions/StringExtensions.cs b/Emby.Naming/Extensions/StringExtensions.cs
deleted file mode 100644
index 26c09aeb4..000000000
--- a/Emby.Naming/Extensions/StringExtensions.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using System.Text;
-
-namespace Emby.Naming.Extensions
-{
- public static class StringExtensions
- {
- public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
- {
- var sb = new StringBuilder();
-
- var previousIndex = 0;
- var index = str.IndexOf(oldValue, comparison);
-
- while (index != -1)
- {
- sb.Append(str.Substring(previousIndex, index - previousIndex));
- sb.Append(newValue);
- index += oldValue.Length;
-
- previousIndex = index;
- index = str.IndexOf(oldValue, index, comparison);
- }
-
- sb.Append(str.Substring(previousIndex));
-
- return sb.ToString();
- }
- }
-}
diff --git a/Emby.Naming/Properties/AssemblyInfo.cs b/Emby.Naming/Properties/AssemblyInfo.cs
index 15311570b..f26e0ba79 100644
--- a/Emby.Naming/Properties/AssemblyInfo.cs
+++ b/Emby.Naming/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/Emby.Naming/StringExtensions.cs b/Emby.Naming/StringExtensions.cs
deleted file mode 100644
index 7c61922af..000000000
--- a/Emby.Naming/StringExtensions.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using System.Text;
-
-namespace Emby.Naming
-{
- internal static class StringExtensions
- {
- public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
- {
- var sb = new StringBuilder();
-
- var previousIndex = 0;
- var index = str.IndexOf(oldValue, comparison);
-
- while (index != -1)
- {
- sb.Append(str.Substring(previousIndex, index - previousIndex));
- sb.Append(newValue);
- index += oldValue.Length;
-
- previousIndex = index;
- index = str.IndexOf(oldValue, index, comparison);
- }
-
- sb.Append(str.Substring(previousIndex));
-
- return sb.ToString();
- }
- }
-}
diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs
index e4709dfbb..1fb2e0dc8 100644
--- a/Emby.Naming/Subtitles/SubtitleInfo.cs
+++ b/Emby.Naming/Subtitles/SubtitleInfo.cs
@@ -1,22 +1,41 @@
namespace Emby.Naming.Subtitles
{
+ /// <summary>
+ /// Class holding information about subtitle.
+ /// </summary>
public class SubtitleInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="SubtitleInfo"/> class.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="isDefault">Is subtitle default.</param>
+ /// <param name="isForced">Is subtitle forced.</param>
+ public SubtitleInfo(string path, bool isDefault, bool isForced)
+ {
+ Path = path;
+ IsDefault = isDefault;
+ IsForced = isForced;
+ }
+
+ /// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; set; }
+
/// <summary>
/// Gets or sets the language.
/// </summary>
/// <value>The language.</value>
- public string Language { get; set; }
+ public string? Language { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is default.
/// </summary>
/// <value><c>true</c> if this instance is default; otherwise, <c>false</c>.</value>
public bool IsDefault { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is forced.
/// </summary>
diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs
index ac9432d57..a19340ef6 100644
--- a/Emby.Naming/Subtitles/SubtitleParser.cs
+++ b/Emby.Naming/Subtitles/SubtitleParser.cs
@@ -5,20 +5,32 @@ using Emby.Naming.Common;
namespace Emby.Naming.Subtitles
{
+ /// <summary>
+ /// Subtitle Parser class.
+ /// </summary>
public class SubtitleParser
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubtitleParser"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> object containing SubtitleFileExtensions, SubtitleDefaultFlags, SubtitleForcedFlags and SubtitleFlagDelimiters.</param>
public SubtitleParser(NamingOptions options)
{
_options = options;
}
- public SubtitleInfo ParseFile(string path)
+ /// <summary>
+ /// Parse file to determine if is subtitle and <see cref="SubtitleInfo"/>.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <returns>Returns null or <see cref="SubtitleInfo"/> object if parsing is successful.</returns>
+ public SubtitleInfo? ParseFile(string path)
{
- if (string.IsNullOrEmpty(path))
+ if (path.Length == 0)
{
- throw new ArgumentNullException(nameof(path));
+ return null;
}
var extension = Path.GetExtension(path);
@@ -28,21 +40,19 @@ namespace Emby.Naming.Subtitles
}
var flags = GetFlags(path);
+ var info = new SubtitleInfo(
+ path,
+ _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)),
+ _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)));
- var info = new SubtitleInfo
- {
- Path = path,
- IsDefault = _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)),
- IsForced = _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase))
- };
-
- var parts = flags.Where(i => !_options.SubtitleDefaultFlags.Contains(i, StringComparer.OrdinalIgnoreCase) && !_options.SubtitleForcedFlags.Contains(i, StringComparer.OrdinalIgnoreCase))
+ var parts = flags.Where(i => !_options.SubtitleDefaultFlags.Contains(i, StringComparer.OrdinalIgnoreCase)
+ && !_options.SubtitleForcedFlags.Contains(i, StringComparer.OrdinalIgnoreCase))
.ToList();
// Should have a name, language and file extension
if (parts.Count >= 3)
{
- info.Language = parts[parts.Count - 2];
+ info.Language = parts[^2];
}
return info;
@@ -50,12 +60,7 @@ namespace Emby.Naming.Subtitles
private string[] GetFlags(string path)
{
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _.
+ // Note: the tags need be surrounded be either a space ( ), hyphen -, dot . or underscore _.
var file = Path.GetFileName(path);
diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs
index c8aca7a6f..a8920b36a 100644
--- a/Emby.Naming/TV/EpisodeInfo.cs
+++ b/Emby.Naming/TV/EpisodeInfo.cs
@@ -1,50 +1,94 @@
namespace Emby.Naming.TV
{
+ /// <summary>
+ /// Holder object for Episode information.
+ /// </summary>
public class EpisodeInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeInfo"/> class.
+ /// </summary>
+ /// <param name="path">Path to the file.</param>
+ public EpisodeInfo(string path)
+ {
+ Path = path;
+ }
+
+ /// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; set; }
+
/// <summary>
/// Gets or sets the container.
/// </summary>
/// <value>The container.</value>
- public string Container { get; set; }
+ public string? Container { get; set; }
+
/// <summary>
/// Gets or sets the name of the series.
/// </summary>
/// <value>The name of the series.</value>
- public string SeriesName { get; set; }
+ public string? SeriesName { get; set; }
+
/// <summary>
/// Gets or sets the format3 d.
/// </summary>
/// <value>The format3 d.</value>
- public string Format3D { get; set; }
+ public string? Format3D { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [is3 d].
/// </summary>
/// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
public bool Is3D { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is stub.
/// </summary>
/// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
public bool IsStub { get; set; }
+
/// <summary>
/// Gets or sets the type of the stub.
/// </summary>
/// <value>The type of the stub.</value>
- public string StubType { get; set; }
+ public string? StubType { get; set; }
+ /// <summary>
+ /// Gets or sets optional season number.
+ /// </summary>
public int? SeasonNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional episode number.
+ /// </summary>
public int? EpisodeNumber { get; set; }
- public int? EndingEpsiodeNumber { get; set; }
+ /// <summary>
+ /// Gets or sets optional ending episode number. For multi-episode files 1-13.
+ /// </summary>
+ public int? EndingEpisodeNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional year of release.
+ /// </summary>
public int? Year { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional year of release.
+ /// </summary>
public int? Month { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional day of release.
+ /// </summary>
public int? Day { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether by date expression was used.
+ /// </summary>
public bool IsByDate { get; set; }
}
}
diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs
index 9485d697b..6d0597356 100644
--- a/Emby.Naming/TV/EpisodePathParser.cs
+++ b/Emby.Naming/TV/EpisodePathParser.cs
@@ -2,52 +2,70 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using System.Text.RegularExpressions;
using Emby.Naming.Common;
namespace Emby.Naming.TV
{
+ /// <summary>
+ /// Used to parse information about episode from path.
+ /// </summary>
public class EpisodePathParser
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodePathParser"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> object containing EpisodeExpressions and MultipleEpisodeExpressions.</param>
public EpisodePathParser(NamingOptions options)
{
_options = options;
}
- public EpisodePathParserResult Parse(string path, bool IsDirectory, bool? isNamed = null, bool? isOptimistic = null, bool? supportsAbsoluteNumbers = null, bool fillExtendedInfo = true)
+ /// <summary>
+ /// Parses information about episode from path.
+ /// </summary>
+ /// <param name="path">Path.</param>
+ /// <param name="isDirectory">Is path for a directory or file.</param>
+ /// <param name="isNamed">Do we want to use IsNamed expressions.</param>
+ /// <param name="isOptimistic">Do we want to use Optimistic expressions.</param>
+ /// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param>
+ /// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param>
+ /// <returns>Returns <see cref="EpisodePathParserResult"/> object.</returns>
+ public EpisodePathParserResult Parse(
+ string path,
+ bool isDirectory,
+ bool? isNamed = null,
+ bool? isOptimistic = null,
+ bool? supportsAbsoluteNumbers = null,
+ bool fillExtendedInfo = true)
{
// Added to be able to use regex patterns which require a file extension.
// There were no failed tests without this block, but to be safe, we can keep it until
// the regex which require file extensions are modified so that they don't need them.
- if (IsDirectory)
+ if (isDirectory)
+ {
path += ".mp4";
+ }
- EpisodePathParserResult result = null;
+ EpisodePathParserResult? result = null;
foreach (var expression in _options.EpisodeExpressions)
{
- if (supportsAbsoluteNumbers.HasValue)
+ if (supportsAbsoluteNumbers.HasValue
+ && expression.SupportsAbsoluteEpisodeNumbers != supportsAbsoluteNumbers.Value)
{
- if (expression.SupportsAbsoluteEpisodeNumbers != supportsAbsoluteNumbers.Value)
- {
- continue;
- }
+ continue;
}
- if (isNamed.HasValue)
+
+ if (isNamed.HasValue && expression.IsNamed != isNamed.Value)
{
- if (expression.IsNamed != isNamed.Value)
- {
- continue;
- }
+ continue;
}
- if (isOptimistic.HasValue)
+
+ if (isOptimistic.HasValue && expression.IsOptimistic != isOptimistic.Value)
{
- if (expression.IsOptimistic != isOptimistic.Value)
- {
- continue;
- }
+ continue;
}
var currentResult = Parse(path, expression);
@@ -66,7 +84,7 @@ namespace Emby.Naming.TV
{
result.SeriesName = result.SeriesName
.Trim()
- .Trim(new[] { '_', '.', '-' })
+ .Trim('_', '.', '-')
.Trim();
}
}
@@ -94,7 +112,8 @@ namespace Emby.Naming.TV
DateTime date;
if (expression.DateTimeFormats.Length > 0)
{
- if (DateTime.TryParseExact(match.Groups[0].Value,
+ if (DateTime.TryParseExact(
+ match.Groups[0].Value,
expression.DateTimeFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
@@ -106,15 +125,12 @@ namespace Emby.Naming.TV
result.Success = true;
}
}
- else
+ else if (DateTime.TryParse(match.Groups[0].Value, out date))
{
- if (DateTime.TryParse(match.Groups[0].Value, out date))
- {
- result.Year = date.Year;
- result.Month = date.Month;
- result.Day = date.Day;
- result.Success = true;
- }
+ result.Year = date.Year;
+ result.Month = date.Month;
+ result.Day = date.Day;
+ result.Success = true;
}
// TODO: Only consider success if date successfully parsed?
@@ -135,15 +151,16 @@ namespace Emby.Naming.TV
var endingNumberGroup = match.Groups["endingepnumber"];
if (endingNumberGroup.Success)
{
- // Will only set EndingEpsiodeNumber if the captured number is not followed by additional numbers
+ // Will only set EndingEpisodeNumber if the captured number is not followed by additional numbers
// or a 'p' or 'i' as what you would get with a pixel resolution specification.
// It avoids erroneous parsing of something like "series-s09e14-1080p.mkv" as a multi-episode from E14 to E108
int nextIndex = endingNumberGroup.Index + endingNumberGroup.Length;
- if (nextIndex >= name.Length || "0123456789iIpP".IndexOf(name[nextIndex]) == -1)
+ if (nextIndex >= name.Length
+ || !"0123456789iIpP".Contains(name[nextIndex], StringComparison.Ordinal))
{
if (int.TryParse(endingNumberGroup.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
{
- result.EndingEpsiodeNumber = num;
+ result.EndingEpisodeNumber = num;
}
}
}
@@ -157,6 +174,7 @@ namespace Emby.Naming.TV
{
result.SeasonNumber = num;
}
+
if (int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
{
result.EpisodeNumber = num;
@@ -168,8 +186,11 @@ namespace Emby.Naming.TV
// Invalidate match when the season is 200 through 1927 or above 2500
// because it is an error unless the TV show is intentionally using false season numbers.
// It avoids erroneous parsing of something like "Series Special (1920x1080).mkv" as being season 1920 episode 1080.
- if (result.SeasonNumber >= 200 && result.SeasonNumber < 1928 || result.SeasonNumber > 2500)
+ if ((result.SeasonNumber >= 200 && result.SeasonNumber < 1928)
+ || result.SeasonNumber > 2500)
+ {
result.Success = false;
+ }
result.IsByDate = expression.IsByDate;
}
@@ -179,7 +200,7 @@ namespace Emby.Naming.TV
private void FillAdditional(string path, EpisodePathParserResult info)
{
- var expressions = _options.MultipleEpisodeExpressions.ToList();
+ var expressions = _options.MultipleEpisodeExpressions.Where(i => i.IsNamed).ToList();
if (string.IsNullOrEmpty(info.SeriesName))
{
@@ -191,29 +212,29 @@ namespace Emby.Naming.TV
private void FillAdditional(string path, EpisodePathParserResult info, IEnumerable<EpisodeExpression> expressions)
{
- var results = expressions
- .Where(i => i.IsNamed)
- .Select(i => Parse(path, i))
- .Where(i => i.Success);
-
- foreach (var result in results)
+ foreach (var i in expressions)
{
+ var result = Parse(path, i);
+
+ if (!result.Success)
+ {
+ continue;
+ }
+
if (string.IsNullOrEmpty(info.SeriesName))
{
info.SeriesName = result.SeriesName;
}
- if (!info.EndingEpsiodeNumber.HasValue && info.EpisodeNumber.HasValue)
+ if (!info.EndingEpisodeNumber.HasValue && info.EpisodeNumber.HasValue)
{
- info.EndingEpsiodeNumber = result.EndingEpsiodeNumber;
+ info.EndingEpisodeNumber = result.EndingEpisodeNumber;
}
- if (!string.IsNullOrEmpty(info.SeriesName))
+ if (!string.IsNullOrEmpty(info.SeriesName)
+ && (!info.EpisodeNumber.HasValue || info.EndingEpisodeNumber.HasValue))
{
- if (!info.EpisodeNumber.HasValue || info.EndingEpsiodeNumber.HasValue)
- {
- break;
- }
+ break;
}
}
}
diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs
index e1a48bfbc..233d5a4f6 100644
--- a/Emby.Naming/TV/EpisodePathParserResult.cs
+++ b/Emby.Naming/TV/EpisodePathParserResult.cs
@@ -1,16 +1,54 @@
namespace Emby.Naming.TV
{
+ /// <summary>
+ /// Holder object for <see cref="EpisodePathParser"/> result.
+ /// </summary>
public class EpisodePathParserResult
{
+ /// <summary>
+ /// Gets or sets optional season number.
+ /// </summary>
public int? SeasonNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional episode number.
+ /// </summary>
public int? EpisodeNumber { get; set; }
- public int? EndingEpsiodeNumber { get; set; }
- public string SeriesName { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional ending episode number. For multi-episode files 1-13.
+ /// </summary>
+ public int? EndingEpisodeNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name of the series.
+ /// </summary>
+ /// <value>The name of the series.</value>
+ public string? SeriesName { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether parsing was successful.
+ /// </summary>
public bool Success { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether by date expression was used.
+ /// </summary>
public bool IsByDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional year of release.
+ /// </summary>
public int? Year { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional year of release.
+ /// </summary>
public int? Month { get; set; }
+
+ /// <summary>
+ /// Gets or sets optional day of release.
+ /// </summary>
public int? Day { get; set; }
}
}
diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs
index fccf9bdec..5e952e47b 100644
--- a/Emby.Naming/TV/EpisodeResolver.cs
+++ b/Emby.Naming/TV/EpisodeResolver.cs
@@ -6,60 +6,77 @@ using Emby.Naming.Video;
namespace Emby.Naming.TV
{
+ /// <summary>
+ /// Used to resolve information about episode from path.
+ /// </summary>
public class EpisodeResolver
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeResolver"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> object containing VideoFileExtensions and passed to <see cref="StubResolver"/>, <see cref="Format3DParser"/> and <see cref="EpisodePathParser"/>.</param>
public EpisodeResolver(NamingOptions options)
{
_options = options;
}
- public EpisodeInfo Resolve(string path, bool IsDirectory, bool? isNamed = null, bool? isOptimistic = null, bool? supportsAbsoluteNumbers = null, bool fillExtendedInfo = true)
+ /// <summary>
+ /// Resolve information about episode from path.
+ /// </summary>
+ /// <param name="path">Path.</param>
+ /// <param name="isDirectory">Is path for a directory or file.</param>
+ /// <param name="isNamed">Do we want to use IsNamed expressions.</param>
+ /// <param name="isOptimistic">Do we want to use Optimistic expressions.</param>
+ /// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param>
+ /// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param>
+ /// <returns>Returns null or <see cref="EpisodeInfo"/> object if successful.</returns>
+ public EpisodeInfo? Resolve(
+ string path,
+ bool isDirectory,
+ bool? isNamed = null,
+ bool? isOptimistic = null,
+ bool? supportsAbsoluteNumbers = null,
+ bool fillExtendedInfo = true)
{
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
bool isStub = false;
- string container = null;
- string stubType = null;
+ string? container = null;
+ string? stubType = null;
- if (!IsDirectory)
+ if (!isDirectory)
{
var extension = Path.GetExtension(path);
// Check supported extensions
if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
- var stubResult = StubResolver.ResolveFile(path, _options);
-
- isStub = stubResult.IsStub;
-
// It's not supported. Check stub extensions
- if (!isStub)
+ if (!StubResolver.TryResolveFile(path, _options, out stubType))
{
return null;
}
- stubType = stubResult.StubType;
+ isStub = true;
}
container = extension.TrimStart('.');
}
- var flags = new FlagParser(_options).GetFlags(path);
- var format3DResult = new Format3DParser(_options).Parse(flags);
+ var format3DResult = Format3DParser.Parse(path, _options);
var parsingResult = new EpisodePathParser(_options)
- .Parse(path, IsDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo);
+ .Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo);
+
+ if (!parsingResult.Success && !isStub)
+ {
+ return null;
+ }
- return new EpisodeInfo
+ return new EpisodeInfo(path)
{
- Path = path,
Container = container,
IsStub = isStub,
- EndingEpsiodeNumber = parsingResult.EndingEpsiodeNumber,
+ EndingEpisodeNumber = parsingResult.EndingEpisodeNumber,
EpisodeNumber = parsingResult.EpisodeNumber,
SeasonNumber = parsingResult.SeasonNumber,
SeriesName = parsingResult.SeriesName,
diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs
index f1dcc50b8..6236f86c4 100644
--- a/Emby.Naming/TV/SeasonPathParser.cs
+++ b/Emby.Naming/TV/SeasonPathParser.cs
@@ -1,72 +1,77 @@
using System;
using System.Globalization;
using System.IO;
-using System.Linq;
-using Emby.Naming.Common;
namespace Emby.Naming.TV
{
- public class SeasonPathParser
+ /// <summary>
+ /// Class to parse season paths.
+ /// </summary>
+ public static class SeasonPathParser
{
- private readonly NamingOptions _options;
-
- public SeasonPathParser(NamingOptions options)
+ /// <summary>
+ /// A season folder must contain one of these somewhere in the name.
+ /// </summary>
+ private static readonly string[] _seasonFolderNames =
{
- _options = options;
- }
+ "season",
+ "sæson",
+ "temporada",
+ "saison",
+ "staffel",
+ "series",
+ "сезон",
+ "stagione"
+ };
- public SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders)
+ /// <summary>
+ /// Attempts to parse season number from path.
+ /// </summary>
+ /// <param name="path">Path to season.</param>
+ /// <param name="supportSpecialAliases">Support special aliases when parsing.</param>
+ /// <param name="supportNumericSeasonFolders">Support numeric season folders when parsing.</param>
+ /// <returns>Returns <see cref="SeasonPathParserResult"/> object.</returns>
+ public static SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders)
{
var result = new SeasonPathParserResult();
- var seasonNumberInfo = GetSeasonNumberFromPath(path, supportSpecialAliases, supportNumericSeasonFolders);
+ var (seasonNumber, isSeasonFolder) = GetSeasonNumberFromPath(path, supportSpecialAliases, supportNumericSeasonFolders);
- result.SeasonNumber = seasonNumberInfo.Item1;
+ result.SeasonNumber = seasonNumber;
if (result.SeasonNumber.HasValue)
{
result.Success = true;
- result.IsSeasonFolder = seasonNumberInfo.Item2;
+ result.IsSeasonFolder = isSeasonFolder;
}
return result;
}
/// <summary>
- /// A season folder must contain one of these somewhere in the name
- /// </summary>
- private static readonly string[] SeasonFolderNames =
- {
- "season",
- "sæson",
- "temporada",
- "saison",
- "staffel",
- "series",
- "сезон",
- "stagione"
- };
-
- /// <summary>
/// Gets the season number from path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="supportSpecialAliases">if set to <c>true</c> [support special aliases].</param>
/// <param name="supportNumericSeasonFolders">if set to <c>true</c> [support numeric season folders].</param>
/// <returns>System.Nullable{System.Int32}.</returns>
- private Tuple<int?, bool> GetSeasonNumberFromPath(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders)
+ private static (int? seasonNumber, bool isSeasonFolder) GetSeasonNumberFromPath(
+ string path,
+ bool supportSpecialAliases,
+ bool supportNumericSeasonFolders)
{
- var filename = Path.GetFileName(path);
+ string filename = Path.GetFileName(path);
if (supportSpecialAliases)
{
if (string.Equals(filename, "specials", StringComparison.OrdinalIgnoreCase))
{
- return new Tuple<int?, bool>(0, true);
+ return (0, true);
}
+
if (string.Equals(filename, "extras", StringComparison.OrdinalIgnoreCase))
{
- return new Tuple<int?, bool>(0, true);
+ return (0, true);
}
}
@@ -74,29 +79,27 @@ namespace Emby.Naming.TV
{
if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
{
- return new Tuple<int?, bool>(val, true);
+ return (val, true);
}
}
if (filename.StartsWith("s", StringComparison.OrdinalIgnoreCase))
{
- var testFilename = filename.Substring(1);
+ var testFilename = filename.AsSpan().Slice(1);
if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
{
- return new Tuple<int?, bool>(val, true);
+ return (val, true);
}
}
// Look for one of the season folder names
- foreach (var name in SeasonFolderNames)
+ foreach (var name in _seasonFolderNames)
{
- var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase);
-
- if (index != -1)
+ if (filename.Contains(name, StringComparison.OrdinalIgnoreCase))
{
var result = GetSeasonNumberFromPathSubstring(filename.Replace(name, " ", StringComparison.OrdinalIgnoreCase));
- if (result.Item1.HasValue)
+ if (result.seasonNumber.HasValue)
{
return result;
}
@@ -106,51 +109,59 @@ namespace Emby.Naming.TV
}
var parts = filename.Split(new[] { '.', '_', ' ', '-' }, StringSplitOptions.RemoveEmptyEntries);
- var resultNumber = parts.Select(GetSeasonNumberFromPart).FirstOrDefault(i => i.HasValue);
- return new Tuple<int?, bool>(resultNumber, true);
+ foreach (var part in parts)
+ {
+ if (TryGetSeasonNumberFromPart(part, out int seasonNumber))
+ {
+ return (seasonNumber, true);
+ }
+ }
+
+ return (null, true);
}
- private int? GetSeasonNumberFromPart(string part)
+ private static bool TryGetSeasonNumberFromPart(ReadOnlySpan<char> part, out int seasonNumber)
{
+ seasonNumber = 0;
if (part.Length < 2 || !part.StartsWith("s", StringComparison.OrdinalIgnoreCase))
{
- return null;
+ return false;
}
- part = part.Substring(1);
-
- if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
+ if (int.TryParse(part.Slice(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
- return value;
+ seasonNumber = value;
+ return true;
}
- return null;
+ return false;
}
/// <summary>
- /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel")
+ /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel").
/// </summary>
/// <param name="path">The path.</param>
/// <returns>System.Nullable{System.Int32}.</returns>
- private Tuple<int?, bool> GetSeasonNumberFromPathSubstring(string path)
+ private static (int? seasonNumber, bool isSeasonFolder) GetSeasonNumberFromPathSubstring(ReadOnlySpan<char> path)
{
var numericStart = -1;
var length = 0;
- var hasOpenParenth = false;
+ var hasOpenParenthesis = false;
var isSeasonFolder = true;
// Find out where the numbers start, and then keep going until they end
for (var i = 0; i < path.Length; i++)
{
- if (char.IsNumber(path, i))
+ if (char.IsNumber(path[i]))
{
- if (!hasOpenParenth)
+ if (!hasOpenParenthesis)
{
if (numericStart == -1)
{
numericStart = i;
}
+
length++;
}
}
@@ -162,22 +173,22 @@ namespace Emby.Naming.TV
}
var currentChar = path[i];
- if (currentChar.Equals('('))
+ if (currentChar == '(')
{
- hasOpenParenth = true;
+ hasOpenParenthesis = true;
}
- else if (currentChar.Equals(')'))
+ else if (currentChar == ')')
{
- hasOpenParenth = false;
+ hasOpenParenthesis = false;
}
}
if (numericStart == -1)
{
- return new Tuple<int?, bool>(null, isSeasonFolder);
+ return (null, isSeasonFolder);
}
- return new Tuple<int?, bool>(int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture), isSeasonFolder);
+ return (int.Parse(path.Slice(numericStart, length), provider: CultureInfo.InvariantCulture), isSeasonFolder);
}
}
}
diff --git a/Emby.Naming/TV/SeasonPathParserResult.cs b/Emby.Naming/TV/SeasonPathParserResult.cs
index eab27a4a5..b4b6f236a 100644
--- a/Emby.Naming/TV/SeasonPathParserResult.cs
+++ b/Emby.Naming/TV/SeasonPathParserResult.cs
@@ -1,5 +1,8 @@
namespace Emby.Naming.TV
{
+ /// <summary>
+ /// Data object to pass result of <see cref="SeasonPathParser"/>.
+ /// </summary>
public class SeasonPathParserResult
{
/// <summary>
@@ -7,11 +10,17 @@ namespace Emby.Naming.TV
/// </summary>
/// <value>The season number.</value>
public int? SeasonNumber { get; set; }
+
/// <summary>
- /// Gets or sets a value indicating whether this <see cref="SeasonPathParserResult"/> is success.
+ /// Gets or sets a value indicating whether this <see cref="SeasonPathParserResult" /> is success.
/// </summary>
/// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
public bool Success { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether "Is season folder".
+ /// Seems redundant and barely used.
+ /// </summary>
public bool IsSeasonFolder { get; set; }
}
}
diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs
index 74807ef53..0ee633dcc 100644
--- a/Emby.Naming/Video/CleanDateTimeParser.cs
+++ b/Emby.Naming/Video/CleanDateTimeParser.cs
@@ -1,86 +1,55 @@
-using System;
+using System.Collections.Generic;
using System.Globalization;
-using System.IO;
-using System.Linq;
using System.Text.RegularExpressions;
-using Emby.Naming.Common;
namespace Emby.Naming.Video
{
/// <summary>
- /// http://kodi.wiki/view/Advancedsettings.xml#video
+ /// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
/// </summary>
- public class CleanDateTimeParser
+ public static class CleanDateTimeParser
{
- private readonly NamingOptions _options;
-
- public CleanDateTimeParser(NamingOptions options)
- {
- _options = options;
- }
-
- public CleanDateTimeResult Clean(string name)
+ /// <summary>
+ /// Attempts to clean the name.
+ /// </summary>
+ /// <param name="name">Name of video.</param>
+ /// <param name="cleanDateTimeRegexes">Optional list of regexes to clean the name.</param>
+ /// <returns>Returns <see cref="CleanDateTimeResult"/> object.</returns>
+ public static CleanDateTimeResult Clean(string name, IReadOnlyList<Regex> cleanDateTimeRegexes)
{
- var originalName = name;
-
- try
- {
- var extension = Path.GetExtension(name) ?? string.Empty;
- // Check supported extensions
- if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) &&
- !_options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
- {
- // Dummy up a file extension because the expressions will fail without one
- // This is tricky because we can't just check Path.GetExtension for empty
- // If the input is "St. Vincent (2014)", it will produce ". Vincent (2014)" as the extension
- name += ".mkv";
- }
- }
- catch (ArgumentException)
- {
-
- }
-
- var result = _options.CleanDateTimeRegexes.Select(i => Clean(name, i))
- .FirstOrDefault(i => i.HasChanged) ??
- new CleanDateTimeResult { Name = originalName };
-
- if (result.HasChanged)
+ CleanDateTimeResult result = new CleanDateTimeResult(name);
+ if (string.IsNullOrEmpty(name))
{
return result;
}
- // Make a second pass, running clean string first
- var cleanStringResult = new CleanStringParser().Clean(name, _options.CleanStringRegexes);
-
- if (!cleanStringResult.HasChanged)
+ var len = cleanDateTimeRegexes.Count;
+ for (int i = 0; i < len; i++)
{
- return result;
+ if (TryClean(name, cleanDateTimeRegexes[i], ref result))
+ {
+ return result;
+ }
}
- return _options.CleanDateTimeRegexes.Select(i => Clean(cleanStringResult.Name, i))
- .FirstOrDefault(i => i.HasChanged) ??
- result;
+ return result;
}
- private static CleanDateTimeResult Clean(string name, Regex expression)
+ private static bool TryClean(string name, Regex expression, ref CleanDateTimeResult result)
{
- var result = new CleanDateTimeResult();
-
var match = expression.Match(name);
- if (match.Success && match.Groups.Count == 4)
+ if (match.Success
+ && match.Groups.Count == 5
+ && match.Groups[1].Success
+ && match.Groups[2].Success
+ && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year))
{
- if (match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year))
- {
- name = match.Groups[1].Value;
- result.Year = year;
- result.HasChanged = true;
- }
+ result = new CleanDateTimeResult(match.Groups[1].Value.TrimEnd(), year);
+ return true;
}
- result.Name = name;
- return result;
+ return false;
}
}
}
diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs
index 6bf24e4d8..c675a19d0 100644
--- a/Emby.Naming/Video/CleanDateTimeResult.cs
+++ b/Emby.Naming/Video/CleanDateTimeResult.cs
@@ -1,21 +1,31 @@
namespace Emby.Naming.Video
{
- public class CleanDateTimeResult
+ /// <summary>
+ /// Holder structure for name and year.
+ /// </summary>
+ public readonly struct CleanDateTimeResult
{
/// <summary>
- /// Gets or sets the name.
+ /// Initializes a new instance of the <see cref="CleanDateTimeResult"/> struct.
/// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
+ /// <param name="name">Name of video.</param>
+ /// <param name="year">Year of release.</param>
+ public CleanDateTimeResult(string name, int? year = null)
+ {
+ Name = name;
+ Year = year;
+ }
+
/// <summary>
- /// Gets or sets the year.
+ /// Gets the name.
/// </summary>
- /// <value>The year.</value>
- public int? Year { get; set; }
+ /// <value>The name.</value>
+ public string Name { get; }
+
/// <summary>
- /// Gets or sets a value indicating whether this instance has changed.
+ /// Gets the year.
/// </summary>
- /// <value><c>true</c> if this instance has changed; otherwise, <c>false</c>.</value>
- public bool HasChanged { get; set; }
+ /// <value>The year.</value>
+ public int? Year { get; }
}
}
diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs
index 02b90310d..b81333500 100644
--- a/Emby.Naming/Video/CleanStringParser.cs
+++ b/Emby.Naming/Video/CleanStringParser.cs
@@ -1,49 +1,56 @@
+using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
namespace Emby.Naming.Video
{
/// <summary>
- /// http://kodi.wiki/view/Advancedsettings.xml#video
+ /// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
/// </summary>
- public class CleanStringParser
+ public static class CleanStringParser
{
- public CleanStringResult Clean(string name, IEnumerable<Regex> expressions)
+ /// <summary>
+ /// Attempts to extract clean name with regular expressions.
+ /// </summary>
+ /// <param name="name">Name of file.</param>
+ /// <param name="expressions">List of regex to parse name and year from.</param>
+ /// <param name="newName">Parsing result string.</param>
+ /// <returns>True if parsing was successful.</returns>
+ public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList<Regex> expressions, out string newName)
{
- var hasChanged = false;
-
- foreach (var exp in expressions)
+ if (string.IsNullOrEmpty(name))
{
- var result = Clean(name, exp);
+ newName = string.Empty;
+ return false;
+ }
- if (!string.IsNullOrEmpty(result.Name))
+ // Iteratively apply the regexps to clean the string.
+ bool cleaned = false;
+ for (int i = 0; i < expressions.Count; i++)
+ {
+ if (TryClean(name, expressions[i], out newName))
{
- name = result.Name;
- hasChanged = hasChanged || result.HasChanged;
+ cleaned = true;
+ name = newName;
}
}
- return new CleanStringResult
- {
- Name = name,
- HasChanged = hasChanged
- };
+ newName = cleaned ? name : string.Empty;
+ return cleaned;
}
- private static CleanStringResult Clean(string name, Regex expression)
+ private static bool TryClean(string name, Regex expression, out string newName)
{
- var result = new CleanStringResult();
-
var match = expression.Match(name);
-
- if (match.Success)
+ if (match.Success && match.Groups.TryGetValue("cleaned", out var cleaned))
{
- result.HasChanged = true;
- name = name.Substring(0, match.Index);
+ newName = cleaned.Value;
+ return true;
}
- result.Name = name;
- return result;
+ newName = string.Empty;
+ return false;
}
}
}
diff --git a/Emby.Naming/Video/CleanStringResult.cs b/Emby.Naming/Video/CleanStringResult.cs
deleted file mode 100644
index b3bc59712..000000000
--- a/Emby.Naming/Video/CleanStringResult.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace Emby.Naming.Video
-{
- public class CleanStringResult
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance has changed.
- /// </summary>
- /// <value><c>true</c> if this instance has changed; otherwise, <c>false</c>.</value>
- public bool HasChanged { get; set; }
- }
-}
diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs
index 3459b689a..7bc226614 100644
--- a/Emby.Naming/Video/ExtraResolver.cs
+++ b/Emby.Naming/Video/ExtraResolver.cs
@@ -1,83 +1,102 @@
using System;
using System.IO;
-using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Audio;
using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Resolve if file is extra for video.
+ /// </summary>
public class ExtraResolver
{
+ private static readonly char[] _digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExtraResolver"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> object containing VideoExtraRules and passed to <see cref="AudioFileParser"/> and <see cref="VideoResolver"/>.</param>
public ExtraResolver(NamingOptions options)
{
_options = options;
}
+ /// <summary>
+ /// Attempts to resolve if file is extra.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <returns>Returns <see cref="ExtraResult"/> object.</returns>
public ExtraResult GetExtraInfo(string path)
{
- return _options.VideoExtraRules
- .Select(i => GetExtraInfo(path, i))
- .FirstOrDefault(i => !string.IsNullOrEmpty(i.ExtraType)) ?? new ExtraResult();
- }
-
- private ExtraResult GetExtraInfo(string path, ExtraRule rule)
- {
var result = new ExtraResult();
- if (rule.MediaType == MediaType.Audio)
+ for (var i = 0; i < _options.VideoExtraRules.Length; i++)
{
- if (!new AudioFileParser(_options).IsAudioFile(path))
+ var rule = _options.VideoExtraRules[i];
+ if (rule.MediaType == MediaType.Audio)
{
- return result;
+ if (!AudioFileParser.IsAudioFile(path, _options))
+ {
+ continue;
+ }
}
- }
- else if (rule.MediaType == MediaType.Video)
- {
- if (!new VideoResolver(_options).IsVideoFile(path))
+ else if (rule.MediaType == MediaType.Video)
{
- return result;
+ if (!VideoResolver.IsVideoFile(path, _options))
+ {
+ continue;
+ }
}
- }
- else
- {
- return result;
- }
- if (rule.RuleType == ExtraRuleType.Filename)
- {
- var filename = Path.GetFileNameWithoutExtension(path);
+ var pathSpan = path.AsSpan();
+ if (rule.RuleType == ExtraRuleType.Filename)
+ {
+ var filename = Path.GetFileNameWithoutExtension(pathSpan);
- if (string.Equals(filename, rule.Token, StringComparison.OrdinalIgnoreCase))
+ if (filename.Equals(rule.Token, StringComparison.OrdinalIgnoreCase))
+ {
+ result.ExtraType = rule.ExtraType;
+ result.Rule = rule;
+ }
+ }
+ else if (rule.RuleType == ExtraRuleType.Suffix)
{
- result.ExtraType = rule.ExtraType;
- result.Rule = rule;
+ // Trim the digits from the end of the filename so we can recognize things like -trailer2
+ var filename = Path.GetFileNameWithoutExtension(pathSpan).TrimEnd(_digits);
+
+ if (filename.EndsWith(rule.Token, StringComparison.OrdinalIgnoreCase))
+ {
+ result.ExtraType = rule.ExtraType;
+ result.Rule = rule;
+ }
}
- }
+ else if (rule.RuleType == ExtraRuleType.Regex)
+ {
+ var filename = Path.GetFileName(path);
- else if (rule.RuleType == ExtraRuleType.Suffix)
- {
- var filename = Path.GetFileNameWithoutExtension(path);
+ var regex = new Regex(rule.Token, RegexOptions.IgnoreCase);
- if (filename.IndexOf(rule.Token, StringComparison.OrdinalIgnoreCase) > 0)
+ if (regex.IsMatch(filename))
+ {
+ result.ExtraType = rule.ExtraType;
+ result.Rule = rule;
+ }
+ }
+ else if (rule.RuleType == ExtraRuleType.DirectoryName)
{
- result.ExtraType = rule.ExtraType;
- result.Rule = rule;
+ var directoryName = Path.GetFileName(Path.GetDirectoryName(pathSpan));
+ if (directoryName.Equals(rule.Token, StringComparison.OrdinalIgnoreCase))
+ {
+ result.ExtraType = rule.ExtraType;
+ result.Rule = rule;
+ }
}
- }
-
- else if (rule.RuleType == ExtraRuleType.Regex)
- {
- var filename = Path.GetFileName(path);
- var regex = new Regex(rule.Token, RegexOptions.IgnoreCase);
-
- if (regex.IsMatch(filename))
+ if (result.ExtraType != null)
{
- result.ExtraType = rule.ExtraType;
- result.Rule = rule;
+ return result;
}
}
diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs
index ff6f20c47..243fc2b41 100644
--- a/Emby.Naming/Video/ExtraResult.cs
+++ b/Emby.Naming/Video/ExtraResult.cs
@@ -1,16 +1,22 @@
+using MediaBrowser.Model.Entities;
+
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Holder object for passing results from ExtraResolver.
+ /// </summary>
public class ExtraResult
{
/// <summary>
/// Gets or sets the type of the extra.
/// </summary>
/// <value>The type of the extra.</value>
- public string ExtraType { get; set; }
+ public ExtraType? ExtraType { get; set; }
+
/// <summary>
/// Gets or sets the rule.
/// </summary>
/// <value>The rule.</value>
- public ExtraRule Rule { get; set; }
+ public ExtraRule? Rule { get; set; }
}
}
diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs
index b8eb8427e..e267ac55f 100644
--- a/Emby.Naming/Video/ExtraRule.cs
+++ b/Emby.Naming/Video/ExtraRule.cs
@@ -1,28 +1,46 @@
-using Emby.Naming.Common;
+using MediaBrowser.Model.Entities;
+using MediaType = Emby.Naming.Common.MediaType;
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// A rule used to match a file path with an <see cref="MediaBrowser.Model.Entities.ExtraType"/>.
+ /// </summary>
public class ExtraRule
{
/// <summary>
- /// Gets or sets the token.
+ /// Initializes a new instance of the <see cref="ExtraRule"/> class.
+ /// </summary>
+ /// <param name="extraType">Type of extra.</param>
+ /// <param name="ruleType">Type of rule.</param>
+ /// <param name="token">Token.</param>
+ /// <param name="mediaType">Media type.</param>
+ public ExtraRule(ExtraType extraType, ExtraRuleType ruleType, string token, MediaType mediaType)
+ {
+ Token = token;
+ ExtraType = extraType;
+ RuleType = ruleType;
+ MediaType = mediaType;
+ }
+
+ /// <summary>
+ /// Gets or sets the token to use for matching against the file path.
/// </summary>
- /// <value>The token.</value>
public string Token { get; set; }
+
/// <summary>
- /// Gets or sets the type of the extra.
+ /// Gets or sets the type of the extra to return when matched.
/// </summary>
- /// <value>The type of the extra.</value>
- public string ExtraType { get; set; }
+ public ExtraType ExtraType { get; set; }
+
/// <summary>
/// Gets or sets the type of the rule.
/// </summary>
- /// <value>The type of the rule.</value>
public ExtraRuleType RuleType { get; set; }
+
/// <summary>
- /// Gets or sets the type of the media.
+ /// Gets or sets the type of the media to return when matched.
/// </summary>
- /// <value>The type of the media.</value>
public MediaType MediaType { get; set; }
}
}
diff --git a/Emby.Naming/Video/ExtraRuleType.cs b/Emby.Naming/Video/ExtraRuleType.cs
index 565239ff9..324319505 100644
--- a/Emby.Naming/Video/ExtraRuleType.cs
+++ b/Emby.Naming/Video/ExtraRuleType.cs
@@ -1,18 +1,28 @@
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Extra rules type to determine against what <see cref="ExtraRule.Token"/> should be matched.
+ /// </summary>
public enum ExtraRuleType
{
/// <summary>
- /// The suffix
+ /// Match <see cref="ExtraRule.Token"/> against a suffix in the file name.
/// </summary>
Suffix = 0,
+
/// <summary>
- /// The filename
+ /// Match <see cref="ExtraRule.Token"/> against the file name, excluding the file extension.
/// </summary>
Filename = 1,
+
/// <summary>
- /// The regex
+ /// Match <see cref="ExtraRule.Token"/> against the file name, including the file extension.
/// </summary>
- Regex = 2
+ Regex = 2,
+
+ /// <summary>
+ /// Match <see cref="ExtraRule.Token"/> against the name of the directory containing the file.
+ /// </summary>
+ DirectoryName = 3
}
}
diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs
index 2df1e9aed..6519db57c 100644
--- a/Emby.Naming/Video/FileStack.cs
+++ b/Emby.Naming/Video/FileStack.cs
@@ -4,20 +4,43 @@ using System.Linq;
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Object holding list of files paths with additional information.
+ /// </summary>
public class FileStack
{
- public string Name { get; set; }
- public List<string> Files { get; set; }
- public bool IsDirectoryStack { get; set; }
-
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FileStack"/> class.
+ /// </summary>
public FileStack()
{
Files = new List<string>();
}
- public bool ContainsFile(string file, bool IsDirectory)
+ /// <summary>
+ /// Gets or sets name of file stack.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets list of paths in stack.
+ /// </summary>
+ public List<string> Files { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether stack is directory stack.
+ /// </summary>
+ public bool IsDirectoryStack { get; set; }
+
+ /// <summary>
+ /// Helper function to determine if path is in the stack.
+ /// </summary>
+ /// <param name="file">Path of desired file.</param>
+ /// <param name="isDirectory">Requested type of stack.</param>
+ /// <returns>True if file is in the stack.</returns>
+ public bool ContainsFile(string file, bool isDirectory)
{
- if (IsDirectoryStack == IsDirectory)
+ if (IsDirectoryStack == isDirectory)
{
return Files.Contains(file, StringComparer.OrdinalIgnoreCase);
}
diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs
deleted file mode 100644
index bb129499b..000000000
--- a/Emby.Naming/Video/FlagParser.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System;
-using System.IO;
-using Emby.Naming.Common;
-
-namespace Emby.Naming.Video
-{
- public class FlagParser
- {
- private readonly NamingOptions _options;
-
- public FlagParser(NamingOptions options)
- {
- _options = options;
- }
-
- public string[] GetFlags(string path)
- {
- return GetFlags(path, _options.VideoFlagDelimiters);
- }
-
- public string[] GetFlags(string path, char[] delimeters)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _.
-
- var file = Path.GetFileName(path);
-
- return file.Split(delimeters, StringSplitOptions.RemoveEmptyEntries);
- }
- }
-}
diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs
index e6f830c58..089089989 100644
--- a/Emby.Naming/Video/Format3DParser.cs
+++ b/Emby.Naming/Video/Format3DParser.cs
@@ -1,31 +1,37 @@
using System;
-using System.Linq;
using Emby.Naming.Common;
namespace Emby.Naming.Video
{
- public class Format3DParser
+ /// <summary>
+ /// Parse 3D format related flags.
+ /// </summary>
+ public static class Format3DParser
{
- private readonly NamingOptions _options;
+ // Static default result to save on allocation costs.
+ private static readonly Format3DResult _defaultResult = new (false, null);
- public Format3DParser(NamingOptions options)
+ /// <summary>
+ /// Parse 3D format related flags.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <returns>Returns <see cref="Format3DResult"/> object.</returns>
+ public static Format3DResult Parse(ReadOnlySpan<char> path, NamingOptions namingOptions)
{
- _options = options;
- }
-
- public Format3DResult Parse(string path)
- {
- var delimeters = _options.VideoFlagDelimiters.ToList();
- delimeters.Add(' ');
+ int oldLen = namingOptions.VideoFlagDelimiters.Length;
+ Span<char> delimiters = stackalloc char[oldLen + 1];
+ namingOptions.VideoFlagDelimiters.AsSpan().CopyTo(delimiters);
+ delimiters[oldLen] = ' ';
- return Parse(new FlagParser(_options).GetFlags(path, delimeters.ToArray()));
+ return Parse(path, delimiters, namingOptions);
}
- internal Format3DResult Parse(string[] videoFlags)
+ private static Format3DResult Parse(ReadOnlySpan<char> path, ReadOnlySpan<char> delimiters, NamingOptions namingOptions)
{
- foreach (var rule in _options.Format3DRules)
+ foreach (var rule in namingOptions.Format3DRules)
{
- var result = Parse(videoFlags, rule);
+ var result = Parse(path, rule, delimiters);
if (result.Is3D)
{
@@ -33,49 +39,43 @@ namespace Emby.Naming.Video
}
}
- return new Format3DResult();
+ return _defaultResult;
}
- private static Format3DResult Parse(string[] videoFlags, Format3DRule rule)
+ private static Format3DResult Parse(ReadOnlySpan<char> path, Format3DRule rule, ReadOnlySpan<char> delimiters)
{
- var result = new Format3DResult();
+ bool is3D = false;
+ string? format3D = null;
- if (string.IsNullOrEmpty(rule.PreceedingToken))
+ // If there's no preceding token we just consider it found
+ var foundPrefix = string.IsNullOrEmpty(rule.PrecedingToken);
+ while (path.Length > 0)
{
- result.Format3D = new[] { rule.Token }.FirstOrDefault(i => videoFlags.Contains(i, StringComparer.OrdinalIgnoreCase));
- result.Is3D = !string.IsNullOrEmpty(result.Format3D);
-
- if (result.Is3D)
+ var index = path.IndexOfAny(delimiters);
+ if (index == -1)
{
- result.Tokens.Add(rule.Token);
+ index = path.Length - 1;
}
- }
- else
- {
- var foundPrefix = false;
- string format = null;
- foreach (var flag in videoFlags)
- {
- if (foundPrefix)
- {
- result.Tokens.Add(rule.PreceedingToken);
+ var currentSlice = path[..index];
+ path = path[(index + 1)..];
- if (string.Equals(rule.Token, flag, StringComparison.OrdinalIgnoreCase))
- {
- format = flag;
- result.Tokens.Add(rule.Token);
- }
- break;
- }
- foundPrefix = string.Equals(flag, rule.PreceedingToken, StringComparison.OrdinalIgnoreCase);
+ if (!foundPrefix)
+ {
+ foundPrefix = currentSlice.Equals(rule.PrecedingToken, StringComparison.OrdinalIgnoreCase);
+ continue;
}
- result.Is3D = foundPrefix && !string.IsNullOrEmpty(format);
- result.Format3D = format;
+ is3D = foundPrefix && currentSlice.Equals(rule.Token, StringComparison.OrdinalIgnoreCase);
+
+ if (is3D)
+ {
+ format3D = rule.Token;
+ break;
+ }
}
- return result;
+ return is3D ? new Format3DResult(true, format3D) : _defaultResult;
}
}
}
diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs
index e12494079..aac959c13 100644
--- a/Emby.Naming/Video/Format3DResult.cs
+++ b/Emby.Naming/Video/Format3DResult.cs
@@ -1,28 +1,31 @@
-using System.Collections.Generic;
-
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Helper object to return data from <see cref="Format3DParser"/>.
+ /// </summary>
public class Format3DResult
{
/// <summary>
- /// Gets or sets a value indicating whether [is3 d].
+ /// Initializes a new instance of the <see cref="Format3DResult"/> class.
/// </summary>
- /// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
- public bool Is3D { get; set; }
+ /// <param name="is3D">A value indicating whether the parsed string contains 3D tokens.</param>
+ /// <param name="format3D">The 3D format. Value might be null if [is3D] is <c>false</c>.</param>
+ public Format3DResult(bool is3D, string? format3D)
+ {
+ Is3D = is3D;
+ Format3D = format3D;
+ }
+
/// <summary>
- /// Gets or sets the format3 d.
+ /// Gets a value indicating whether [is3 d].
/// </summary>
- /// <value>The format3 d.</value>
- public string Format3D { get; set; }
+ /// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
+ public bool Is3D { get; }
+
/// <summary>
- /// Gets or sets the tokens.
+ /// Gets the format3 d.
/// </summary>
- /// <value>The tokens.</value>
- public List<string> Tokens { get; set; }
-
- public Format3DResult()
- {
- Tokens = new List<string>();
- }
+ /// <value>The format3 d.</value>
+ public string? Format3D { get; }
}
}
diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs
index dc260175a..e562691df 100644
--- a/Emby.Naming/Video/Format3DRule.cs
+++ b/Emby.Naming/Video/Format3DRule.cs
@@ -1,16 +1,31 @@
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Data holder class for 3D format rule.
+ /// </summary>
public class Format3DRule
{
/// <summary>
+ /// Initializes a new instance of the <see cref="Format3DRule"/> class.
+ /// </summary>
+ /// <param name="token">Token.</param>
+ /// <param name="precedingToken">Token present before current token.</param>
+ public Format3DRule(string token, string? precedingToken = null)
+ {
+ Token = token;
+ PrecedingToken = precedingToken;
+ }
+
+ /// <summary>
/// Gets or sets the token.
/// </summary>
/// <value>The token.</value>
public string Token { get; set; }
+
/// <summary>
- /// Gets or sets the preceeding token.
+ /// Gets or sets the preceding token.
/// </summary>
- /// <value>The preceeding token.</value>
- public string PreceedingToken { get; set; }
+ /// <value>The preceding token.</value>
+ public string? PrecedingToken { get; set; }
}
}
diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs
index 4893002c1..36f65a562 100644
--- a/Emby.Naming/Video/StackResolver.cs
+++ b/Emby.Naming/Video/StackResolver.cs
@@ -3,65 +3,90 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
+using Emby.Naming.AudioBook;
using Emby.Naming.Common;
using MediaBrowser.Model.IO;
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Resolve <see cref="FileStack"/> from list of paths.
+ /// </summary>
public class StackResolver
{
private readonly NamingOptions _options;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StackResolver"/> class.
+ /// </summary>
+ /// <param name="options"><see cref="NamingOptions"/> object containing VideoFileStackingRegexes and passes options to <see cref="VideoResolver"/>.</param>
public StackResolver(NamingOptions options)
{
_options = options;
}
- public StackResult ResolveDirectories(IEnumerable<string> files)
+ /// <summary>
+ /// Resolves only directories from paths.
+ /// </summary>
+ /// <param name="files">List of paths.</param>
+ /// <returns>Enumerable <see cref="FileStack"/> of directories.</returns>
+ public IEnumerable<FileStack> ResolveDirectories(IEnumerable<string> files)
{
- return Resolve(files.Select(i => new FileSystemMetadata
- {
- FullName = i,
- IsDirectory = true
- }));
+ return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = true }));
}
- public StackResult ResolveFiles(IEnumerable<string> files)
+ /// <summary>
+ /// Resolves only files from paths.
+ /// </summary>
+ /// <param name="files">List of paths.</param>
+ /// <returns>Enumerable <see cref="FileStack"/> of files.</returns>
+ public IEnumerable<FileStack> ResolveFiles(IEnumerable<string> files)
{
- return Resolve(files.Select(i => new FileSystemMetadata
- {
- FullName = i,
- IsDirectory = false
- }));
+ return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = false }));
}
- public StackResult ResolveAudioBooks(IEnumerable<FileSystemMetadata> files)
+ /// <summary>
+ /// Resolves audiobooks from paths.
+ /// </summary>
+ /// <param name="files">List of paths.</param>
+ /// <returns>Enumerable <see cref="FileStack"/> of directories.</returns>
+ public IEnumerable<FileStack> ResolveAudioBooks(IEnumerable<AudioBookFileInfo> files)
{
- var result = new StackResult();
- foreach (var directory in files.GroupBy(file => file.IsDirectory ? file.FullName : Path.GetDirectoryName(file.FullName)))
+ var groupedDirectoryFiles = files.GroupBy(file => Path.GetDirectoryName(file.Path));
+
+ foreach (var directory in groupedDirectoryFiles)
{
- var stack = new FileStack();
- stack.Name = Path.GetFileName(directory.Key);
- stack.IsDirectoryStack = false;
- foreach (var file in directory)
+ if (string.IsNullOrEmpty(directory.Key))
+ {
+ foreach (var file in directory)
+ {
+ var stack = new FileStack { Name = Path.GetFileNameWithoutExtension(file.Path), IsDirectoryStack = false };
+ stack.Files.Add(file.Path);
+ yield return stack;
+ }
+ }
+ else
{
- if (file.IsDirectory)
- continue;
- stack.Files.Add(file.FullName);
+ var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false };
+ foreach (var file in directory)
+ {
+ stack.Files.Add(file.Path);
+ }
+
+ yield return stack;
}
- result.Stacks.Add(stack);
}
- return result;
}
- public StackResult Resolve(IEnumerable<FileSystemMetadata> files)
+ /// <summary>
+ /// Resolves videos from paths.
+ /// </summary>
+ /// <param name="files">List of paths.</param>
+ /// <returns>Enumerable <see cref="FileStack"/> of videos.</returns>
+ public IEnumerable<FileStack> Resolve(IEnumerable<FileSystemMetadata> files)
{
- var result = new StackResult();
-
- var resolver = new VideoResolver(_options);
-
var list = files
- .Where(i => i.IsDirectory || (resolver.IsVideoFile(i.FullName) || resolver.IsStubFile(i.FullName)))
+ .Where(i => i.IsDirectory || VideoResolver.IsVideoFile(i.FullName, _options) || VideoResolver.IsStubFile(i.FullName, _options))
.OrderBy(i => i.FullName)
.ToList();
@@ -84,10 +109,10 @@ namespace Emby.Naming.Video
if (match1.Success)
{
- var title1 = match1.Groups[1].Value;
- var volume1 = match1.Groups[2].Value;
- var ignore1 = match1.Groups[3].Value;
- var extension1 = match1.Groups[4].Value;
+ var title1 = match1.Groups["title"].Value;
+ var volume1 = match1.Groups["volume"].Value;
+ var ignore1 = match1.Groups["ignore"].Value;
+ var extension1 = match1.Groups["extension"].Value;
var j = i + 1;
while (j < list.Count)
@@ -114,16 +139,16 @@ namespace Emby.Naming.Video
{
if (!string.Equals(volume1, volume2, StringComparison.OrdinalIgnoreCase))
{
- if (string.Equals(ignore1, ignore2, StringComparison.OrdinalIgnoreCase) &&
- string.Equals(extension1, extension2, StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(ignore1, ignore2, StringComparison.OrdinalIgnoreCase)
+ && string.Equals(extension1, extension2, StringComparison.OrdinalIgnoreCase))
{
if (stack.Files.Count == 0)
{
stack.Name = title1 + ignore1;
stack.IsDirectoryStack = file1.IsDirectory;
- //stack.Name = title1 + ignore1 + extension1;
stack.Files.Add(file1.FullName);
}
+
stack.Files.Add(file2.FullName);
}
else
@@ -181,17 +206,15 @@ namespace Emby.Naming.Video
if (stack.Files.Count > 1)
{
- result.Stacks.Add(stack);
+ yield return stack;
i += stack.Files.Count - 1;
break;
}
}
}
-
- return result;
}
- private string GetRegexInput(FileSystemMetadata file)
+ private static string GetRegexInput(FileSystemMetadata file)
{
// For directories, dummy up an extension otherwise the expressions will fail
var input = !file.IsDirectory
@@ -201,7 +224,7 @@ namespace Emby.Naming.Video
return Path.GetFileName(input);
}
- private Match FindMatch(FileSystemMetadata input, Regex regex, int offset)
+ private static Match FindMatch(FileSystemMetadata input, Regex regex, int offset)
{
var regexInput = GetRegexInput(input);
diff --git a/Emby.Naming/Video/StackResult.cs b/Emby.Naming/Video/StackResult.cs
deleted file mode 100644
index de35d2825..000000000
--- a/Emby.Naming/Video/StackResult.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System.Collections.Generic;
-
-namespace Emby.Naming.Video
-{
- public class StackResult
- {
- public List<FileStack> Stacks { get; set; }
-
- public StackResult()
- {
- Stacks = new List<FileStack>();
- }
- }
-}
diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs
index f86bcbdf0..079987fe8 100644
--- a/Emby.Naming/Video/StubResolver.cs
+++ b/Emby.Naming/Video/StubResolver.cs
@@ -5,32 +5,47 @@ using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Resolve if file is stub (.disc).
+ /// </summary>
public static class StubResolver
{
- public static StubResult ResolveFile(string path, NamingOptions options)
+ /// <summary>
+ /// Tries to resolve if file is stub (.disc).
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="options">NamingOptions containing StubFileExtensions and StubTypes.</param>
+ /// <param name="stubType">Stub type.</param>
+ /// <returns>True if file is a stub.</returns>
+ public static bool TryResolveFile(string path, NamingOptions options, out string? stubType)
{
- var result = new StubResult();
- var extension = Path.GetExtension(path) ?? string.Empty;
+ stubType = default;
- if (options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
+ if (string.IsNullOrEmpty(path))
{
- result.IsStub = true;
+ return false;
+ }
- path = Path.GetFileNameWithoutExtension(path);
+ var extension = Path.GetExtension(path);
- var token = (Path.GetExtension(path) ?? string.Empty).TrimStart('.');
+ if (!options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
+ {
+ return false;
+ }
- foreach (var rule in options.StubTypes)
+ path = Path.GetFileNameWithoutExtension(path);
+ var token = Path.GetExtension(path).TrimStart('.');
+
+ foreach (var rule in options.StubTypes)
+ {
+ if (string.Equals(rule.Token, token, StringComparison.OrdinalIgnoreCase))
{
- if (string.Equals(rule.Token, token, StringComparison.OrdinalIgnoreCase))
- {
- result.StubType = rule.StubType;
- break;
- }
+ stubType = rule.StubType;
+ return true;
}
}
- return result;
+ return true;
}
}
}
diff --git a/Emby.Naming/Video/StubResult.cs b/Emby.Naming/Video/StubResult.cs
deleted file mode 100644
index 7f9509ca5..000000000
--- a/Emby.Naming/Video/StubResult.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace Emby.Naming.Video
-{
- public struct StubResult
- {
- /// <summary>
- /// Gets or sets a value indicating whether this instance is stub.
- /// </summary>
- /// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
- public bool IsStub { get; set; }
- /// <summary>
- /// Gets or sets the type of the stub.
- /// </summary>
- /// <value>The type of the stub.</value>
- public string StubType { get; set; }
- }
-}
diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs
index b46050085..dfb3ac013 100644
--- a/Emby.Naming/Video/StubTypeRule.cs
+++ b/Emby.Naming/Video/StubTypeRule.cs
@@ -1,12 +1,27 @@
namespace Emby.Naming.Video
{
+ /// <summary>
+ /// Data class holding information about Stub type rule.
+ /// </summary>
public class StubTypeRule
{
/// <summary>
+ /// Initializes a new instance of the <see cref="StubTypeRule"/> class.
+ /// </summary>
+ /// <param name="token">Token.</param>
+ /// <param name="stubType">Stub type.</param>
+ public StubTypeRule(string token, string stubType)
+ {
+ Token = token;
+ StubType = stubType;
+ }
+
+ /// <summary>
/// Gets or sets the token.
/// </summary>
/// <value>The token.</value>
public string Token { get; set; }
+
/// <summary>
/// Gets or sets the type of the stub.
/// </summary>
diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs
index 6a29ada7e..481773ff6 100644
--- a/Emby.Naming/Video/VideoFileInfo.cs
+++ b/Emby.Naming/Video/VideoFileInfo.cs
@@ -1,76 +1,120 @@
+using System;
+using MediaBrowser.Model.Entities;
namespace Emby.Naming.Video
{
/// <summary>
- /// Represents a single video file
+ /// Represents a single video file.
/// </summary>
public class VideoFileInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="VideoFileInfo"/> class.
+ /// </summary>
+ /// <param name="name">Name of file.</param>
+ /// <param name="path">Path to the file.</param>
+ /// <param name="container">Container type.</param>
+ /// <param name="year">Year of release.</param>
+ /// <param name="extraType">Extra type.</param>
+ /// <param name="extraRule">Extra rule.</param>
+ /// <param name="format3D">Format 3D.</param>
+ /// <param name="is3D">Is 3D.</param>
+ /// <param name="isStub">Is Stub.</param>
+ /// <param name="stubType">Stub type.</param>
+ /// <param name="isDirectory">Is directory.</param>
+ public VideoFileInfo(string name, string path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default)
+ {
+ Path = path;
+ Container = container;
+ Name = name;
+ Year = year;
+ ExtraType = extraType;
+ ExtraRule = extraRule;
+ Format3D = format3D;
+ Is3D = is3D;
+ IsStub = isStub;
+ StubType = stubType;
+ IsDirectory = isDirectory;
+ }
+
+ /// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; set; }
+
/// <summary>
/// Gets or sets the container.
/// </summary>
/// <value>The container.</value>
- public string Container { get; set; }
+ public string? Container { get; set; }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the year.
/// </summary>
/// <value>The year.</value>
public int? Year { get; set; }
+
/// <summary>
- /// Gets or sets the type of the extra, e.g. trailer, theme song, behing the scenes, etc.
+ /// Gets or sets the type of the extra, e.g. trailer, theme song, behind the scenes, etc.
/// </summary>
/// <value>The type of the extra.</value>
- public string ExtraType { get; set; }
+ public ExtraType? ExtraType { get; set; }
+
/// <summary>
/// Gets or sets the extra rule.
/// </summary>
/// <value>The extra rule.</value>
- public ExtraRule ExtraRule { get; set; }
+ public ExtraRule? ExtraRule { get; set; }
+
/// <summary>
/// Gets or sets the format3 d.
/// </summary>
/// <value>The format3 d.</value>
- public string Format3D { get; set; }
+ public string? Format3D { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [is3 d].
/// </summary>
/// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
public bool Is3D { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is stub.
/// </summary>
/// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
public bool IsStub { get; set; }
+
/// <summary>
/// Gets or sets the type of the stub.
/// </summary>
/// <value>The type of the stub.</value>
- public string StubType { get; set; }
+ public string? StubType { get; set; }
+
/// <summary>
- /// Gets or sets the type.
+ /// Gets or sets a value indicating whether this instance is a directory.
/// </summary>
/// <value>The type.</value>
public bool IsDirectory { get; set; }
+
/// <summary>
/// Gets the file name without extension.
/// </summary>
/// <value>The file name without extension.</value>
- public string FileNameWithoutExtension => !IsDirectory ? System.IO.Path.GetFileNameWithoutExtension(Path) : System.IO.Path.GetFileName(Path);
+ public ReadOnlySpan<char> FileNameWithoutExtension => !IsDirectory
+ ? System.IO.Path.GetFileNameWithoutExtension(Path.AsSpan())
+ : System.IO.Path.GetFileName(Path.AsSpan());
+ /// <inheritdoc />
public override string ToString()
{
- // Makes debugging easier
- return Name ?? base.ToString();
+ return "VideoFileInfo(Name: '" + Name + "')";
}
}
}
diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs
index d96d0e757..930fdb33f 100644
--- a/Emby.Naming/Video/VideoInfo.cs
+++ b/Emby.Naming/Video/VideoInfo.cs
@@ -1,43 +1,54 @@
+using System;
using System.Collections.Generic;
namespace Emby.Naming.Video
{
/// <summary>
- /// Represents a complete video, including all parts and subtitles
+ /// Represents a complete video, including all parts and subtitles.
/// </summary>
public class VideoInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="VideoInfo" /> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ public VideoInfo(string? name)
+ {
+ Name = name;
+
+ Files = Array.Empty<VideoFileInfo>();
+ Extras = Array.Empty<VideoFileInfo>();
+ AlternateVersions = Array.Empty<VideoFileInfo>();
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
- public string Name { get; set; }
+ public string? Name { get; set; }
+
/// <summary>
/// Gets or sets the year.
/// </summary>
/// <value>The year.</value>
public int? Year { get; set; }
+
/// <summary>
/// Gets or sets the files.
/// </summary>
/// <value>The files.</value>
- public List<VideoFileInfo> Files { get; set; }
+ public IReadOnlyList<VideoFileInfo> Files { get; set; }
+
/// <summary>
/// Gets or sets the extras.
/// </summary>
/// <value>The extras.</value>
- public List<VideoFileInfo> Extras { get; set; }
+ public IReadOnlyList<VideoFileInfo> Extras { get; set; }
+
/// <summary>
/// Gets or sets the alternate versions.
/// </summary>
/// <value>The alternate versions.</value>
- public List<VideoFileInfo> AlternateVersions { get; set; }
-
- public VideoInfo()
- {
- Files = new List<VideoFileInfo>();
- Extras = new List<VideoFileInfo>();
- AlternateVersions = new List<VideoFileInfo>();
- }
+ public IReadOnlyList<VideoFileInfo> AlternateVersions { get; set; }
}
}
diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs
index afedc30ef..ed7d511a3 100644
--- a/Emby.Naming/Video/VideoListResolver.cs
+++ b/Emby.Naming/Video/VideoListResolver.cs
@@ -4,71 +4,60 @@ using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Common;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
namespace Emby.Naming.Video
{
- public class VideoListResolver
+ /// <summary>
+ /// Resolves alternative versions and extras from list of video files.
+ /// </summary>
+ public static class VideoListResolver
{
- private readonly NamingOptions _options;
-
- public VideoListResolver(NamingOptions options)
- {
- _options = options;
- }
-
- public IEnumerable<VideoInfo> Resolve(List<FileSystemMetadata> files, bool supportMultiVersion = true)
+ /// <summary>
+ /// Resolves alternative versions and extras from list of video files.
+ /// </summary>
+ /// <param name="files">List of related video files.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param>
+ /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns>
+ public static IEnumerable<VideoInfo> Resolve(IEnumerable<FileSystemMetadata> files, NamingOptions namingOptions, bool supportMultiVersion = true)
{
- var videoResolver = new VideoResolver(_options);
-
var videoInfos = files
- .Select(i => videoResolver.Resolve(i.FullName, i.IsDirectory))
- .Where(i => i != null)
+ .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, namingOptions))
+ .OfType<VideoFileInfo>()
.ToList();
// Filter out all extras, otherwise they could cause stacks to not be resolved
// See the unit test TestStackedWithTrailer
var nonExtras = videoInfos
- .Where(i => string.IsNullOrEmpty(i.ExtraType))
- .Select(i => new FileSystemMetadata
- {
- FullName = i.Path,
- IsDirectory = i.IsDirectory
- });
+ .Where(i => i.ExtraType == null)
+ .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });
- var stackResult = new StackResolver(_options)
- .Resolve(nonExtras);
+ var stackResult = new StackResolver(namingOptions)
+ .Resolve(nonExtras).ToList();
var remainingFiles = videoInfos
- .Where(i => !stackResult.Stacks.Any(s => s.ContainsFile(i.Path, i.IsDirectory)))
+ .Where(i => !stackResult.Any(s => i.Path != null && s.ContainsFile(i.Path, i.IsDirectory)))
.ToList();
var list = new List<VideoInfo>();
- foreach (var stack in stackResult.Stacks)
+ foreach (var stack in stackResult)
{
- var info = new VideoInfo
+ var info = new VideoInfo(stack.Name)
{
- Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)).ToList(),
- Name = stack.Name
+ Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions))
+ .OfType<VideoFileInfo>()
+ .ToList()
};
- info.Year = info.Files.First().Year;
-
- var extraBaseNames = new List<string>
- {
- stack.Name,
- Path.GetFileNameWithoutExtension(stack.Files[0])
- };
+ info.Year = info.Files[0].Year;
- var extras = GetExtras(remainingFiles, extraBaseNames);
+ var extras = ExtractExtras(remainingFiles, stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0].AsSpan()), namingOptions.VideoFlagDelimiters);
if (extras.Count > 0)
{
- remainingFiles = remainingFiles
- .Except(extras)
- .ToList();
-
info.Extras = extras;
}
@@ -76,24 +65,17 @@ namespace Emby.Naming.Video
}
var standaloneMedia = remainingFiles
- .Where(i => string.IsNullOrEmpty(i.ExtraType))
+ .Where(i => i.ExtraType == null)
.ToList();
foreach (var media in standaloneMedia)
{
- var info = new VideoInfo
- {
- Files = new List<VideoFileInfo> { media },
- Name = media.Name
- };
+ var info = new VideoInfo(media.Name) { Files = new[] { media } };
- info.Year = info.Files.First().Year;
+ info.Year = info.Files[0].Year;
- var extras = GetExtras(remainingFiles, new List<string> { media.FileNameWithoutExtension });
-
- remainingFiles = remainingFiles
- .Except(extras.Concat(new[] { media }))
- .ToList();
+ remainingFiles.Remove(media);
+ var extras = ExtractExtras(remainingFiles, media.FileNameWithoutExtension, namingOptions.VideoFlagDelimiters);
info.Extras = extras;
@@ -102,8 +84,7 @@ namespace Emby.Naming.Video
if (supportMultiVersion)
{
- list = GetVideosGroupedByVersion(list)
- .ToList();
+ list = GetVideosGroupedByVersion(list, namingOptions);
}
// If there's only one resolved video, use the folder name as well to find extras
@@ -111,20 +92,16 @@ namespace Emby.Naming.Video
{
var info = list[0];
var videoPath = list[0].Files[0].Path;
- var parentPath = Path.GetDirectoryName(videoPath);
+ var parentPath = Path.GetDirectoryName(videoPath.AsSpan());
- if (!string.IsNullOrEmpty(parentPath))
+ if (!parentPath.IsEmpty)
{
- var folderName = Path.GetFileName(Path.GetDirectoryName(videoPath));
- if (!string.IsNullOrEmpty(folderName))
+ var folderName = Path.GetFileName(parentPath);
+ if (!folderName.IsEmpty)
{
- var extras = GetExtras(remainingFiles, new List<string> { folderName });
-
- remainingFiles = remainingFiles
- .Except(extras)
- .ToList();
-
- info.Extras.AddRange(extras);
+ var extras = ExtractExtras(remainingFiles, folderName, namingOptions.VideoFlagDelimiters);
+ extras.AddRange(info.Extras);
+ info.Extras = extras;
}
}
@@ -137,18 +114,20 @@ namespace Emby.Naming.Video
.Except(extrasByFileName)
.ToList();
- info.Extras.AddRange(extrasByFileName);
+ extrasByFileName.AddRange(info.Extras);
+ info.Extras = extrasByFileName;
}
// If there's only one video, accept all trailers
- // Be lenient because people use all kinds of mish mash conventions with trailers
+ // Be lenient because people use all kinds of mishmash conventions with trailers.
if (list.Count == 1)
{
var trailers = remainingFiles
- .Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase))
+ .Where(i => i.ExtraType == ExtraType.Trailer)
.ToList();
- list[0].Extras.AddRange(trailers);
+ trailers.AddRange(list[0].Extras);
+ list[0].Extras = trailers;
remainingFiles = remainingFiles
.Except(trailers)
@@ -156,83 +135,170 @@ namespace Emby.Naming.Video
}
// Whatever files are left, just add them
- list.AddRange(remainingFiles.Select(i => new VideoInfo
+ list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name)
{
- Files = new List<VideoFileInfo> { i },
- Name = i.Name,
+ Files = new[] { i },
Year = i.Year
}));
- var orderedList = list.OrderBy(i => i.Name);
-
- return orderedList;
+ return list;
}
- private IEnumerable<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos)
+ private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, NamingOptions namingOptions)
{
if (videos.Count == 0)
{
return videos;
}
- var list = new List<VideoInfo>();
+ var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan()));
- var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path));
+ if (folderName.Length <= 1 || !HaveSameYear(videos))
+ {
+ return videos;
+ }
- if (!string.IsNullOrEmpty(folderName) && folderName.Length > 1)
+ // Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if]
+ for (var i = 0; i < videos.Count; i++)
{
- if (videos.All(i => i.Files.Count == 1 && IsEligibleForMultiVersion(folderName, i.Files[0].Path)))
+ var video = videos[i];
+ if (!IsEligibleForMultiVersion(folderName, video.Files[0].Path, namingOptions))
{
- if (HaveSameYear(videos))
- {
- var ordered = videos.OrderBy(i => i.Name).ToList();
+ return videos;
+ }
+ }
- list.Add(ordered[0]);
+ // The list is created and overwritten in the caller, so we are allowed to do in-place sorting
+ videos.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
- list[0].AlternateVersions = ordered.Skip(1).Select(i => i.Files[0]).ToList();
- list[0].Name = folderName;
- list[0].Extras.AddRange(ordered.Skip(1).SelectMany(i => i.Extras));
+ var list = new List<VideoInfo>
+ {
+ videos[0]
+ };
- return list;
- }
+ var alternateVersionsLen = videos.Count - 1;
+ var alternateVersions = new VideoFileInfo[alternateVersionsLen];
+ var extras = new List<VideoFileInfo>(list[0].Extras);
+ for (int i = 0; i < alternateVersionsLen; i++)
+ {
+ var video = videos[i + 1];
+ alternateVersions[i] = video.Files[0];
+ extras.AddRange(video.Extras);
+ }
+
+ list[0].AlternateVersions = alternateVersions;
+ list[0].Name = folderName.ToString();
+ list[0].Extras = extras;
+
+ return list;
+ }
+
+ private static bool HaveSameYear(IReadOnlyList<VideoInfo> videos)
+ {
+ if (videos.Count == 1)
+ {
+ return true;
+ }
+
+ var firstYear = videos[0].Year ?? -1;
+ for (var i = 1; i < videos.Count; i++)
+ {
+ if ((videos[i].Year ?? -1) != firstYear)
+ {
+ return false;
}
}
- return videos;
+ return true;
}
- private bool HaveSameYear(List<VideoInfo> videos)
+ private static bool IsEligibleForMultiVersion(ReadOnlySpan<char> folderName, string testFilePath, NamingOptions namingOptions)
{
- return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2;
+ var testFilename = Path.GetFileNameWithoutExtension(testFilePath.AsSpan());
+ if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+
+ // Remove the folder name before cleaning as we don't care about cleaning that part
+ if (folderName.Length <= testFilename.Length)
+ {
+ testFilename = testFilename[folderName.Length..].Trim();
+ }
+
+ // There are no span overloads for regex unfortunately
+ var tmpTestFilename = testFilename.ToString();
+ if (CleanStringParser.TryClean(tmpTestFilename, namingOptions.CleanStringRegexes, out var cleanName))
+ {
+ tmpTestFilename = cleanName.Trim().ToString();
+ }
+
+ // The CleanStringParser should have removed common keywords etc.
+ return string.IsNullOrEmpty(tmpTestFilename)
+ || testFilename[0] == '-'
+ || Regex.IsMatch(tmpTestFilename, @"^\[([^]]*)\]", RegexOptions.Compiled);
}
- private bool IsEligibleForMultiVersion(string folderName, string testFilename)
+ private static ReadOnlySpan<char> TrimFilenameDelimiters(ReadOnlySpan<char> name, ReadOnlySpan<char> videoFlagDelimiters)
{
- testFilename = Path.GetFileNameWithoutExtension(testFilename) ?? string.Empty;
+ return name.IsEmpty ? name : name.TrimEnd().TrimEnd(videoFlagDelimiters).TrimEnd();
+ }
- if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
+ private static bool StartsWith(ReadOnlySpan<char> fileName, ReadOnlySpan<char> baseName, ReadOnlySpan<char> trimmedBaseName)
+ {
+ if (baseName.IsEmpty)
{
- testFilename = testFilename.Substring(folderName.Length).Trim();
- return string.IsNullOrEmpty(testFilename) ||
- testFilename.StartsWith("-") ||
- string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)) ;
+ return false;
}
- return false;
+ return fileName.StartsWith(baseName, StringComparison.OrdinalIgnoreCase)
+ || (!trimmedBaseName.IsEmpty && fileName.StartsWith(trimmedBaseName, StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// <summary>
+ /// Finds similar filenames to that of [baseName] and removes any matches from [remainingFiles].
+ /// </summary>
+ /// <param name="remainingFiles">The list of remaining filenames.</param>
+ /// <param name="baseName">The base name to use for the comparison.</param>
+ /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
+ /// <returns>A list of video extras for [baseName].</returns>
+ private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> baseName, ReadOnlySpan<char> videoFlagDelimiters)
+ {
+ return ExtractExtras(remainingFiles, baseName, ReadOnlySpan<char>.Empty, videoFlagDelimiters);
}
- private List<VideoFileInfo> GetExtras(IEnumerable<VideoFileInfo> remainingFiles, List<string> baseNames)
+ /// <summary>
+ /// Finds similar filenames to that of [firstBaseName] and [secondBaseName] and removes any matches from [remainingFiles].
+ /// </summary>
+ /// <param name="remainingFiles">The list of remaining filenames.</param>
+ /// <param name="firstBaseName">The first base name to use for the comparison.</param>
+ /// <param name="secondBaseName">The second base name to use for the comparison.</param>
+ /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
+ /// <returns>A list of video extras for [firstBaseName] and [secondBaseName].</returns>
+ private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> firstBaseName, ReadOnlySpan<char> secondBaseName, ReadOnlySpan<char> videoFlagDelimiters)
{
- foreach (var name in baseNames.ToList())
+ var trimmedFirstBaseName = TrimFilenameDelimiters(firstBaseName, videoFlagDelimiters);
+ var trimmedSecondBaseName = TrimFilenameDelimiters(secondBaseName, videoFlagDelimiters);
+
+ var result = new List<VideoFileInfo>();
+ for (var pos = remainingFiles.Count - 1; pos >= 0; pos--)
{
- var trimmedName = name.TrimEnd().TrimEnd(_options.VideoFlagDelimiters).TrimEnd();
- baseNames.Add(trimmedName);
+ var file = remainingFiles[pos];
+ if (file.ExtraType == null)
+ {
+ continue;
+ }
+
+ var filename = file.FileNameWithoutExtension;
+ if (StartsWith(filename, firstBaseName, trimmedFirstBaseName)
+ || StartsWith(filename, secondBaseName, trimmedSecondBaseName))
+ {
+ result.Add(file);
+ remainingFiles.RemoveAt(pos);
+ }
}
- return remainingFiles
- .Where(i => !string.IsNullOrEmpty(i.ExtraType))
- .Where(i => baseNames.Any(b => i.FileNameWithoutExtension.StartsWith(b, StringComparison.OrdinalIgnoreCase)))
- .ToList();
+ return result;
}
}
}
diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs
index a67315651..4c9df27f5 100644
--- a/Emby.Naming/Video/VideoResolver.cs
+++ b/Emby.Naming/Video/VideoResolver.cs
@@ -1,138 +1,157 @@
using System;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
-using System.Linq;
using Emby.Naming.Common;
+using Jellyfin.Extensions;
namespace Emby.Naming.Video
{
- public class VideoResolver
+ /// <summary>
+ /// Resolves <see cref="VideoFileInfo"/> from file path.
+ /// </summary>
+ public static class VideoResolver
{
- private readonly NamingOptions _options;
-
- public VideoResolver(NamingOptions options)
- {
- _options = options;
- }
-
/// <summary>
/// Resolves the directory.
/// </summary>
/// <param name="path">The path.</param>
+ /// <param name="namingOptions">The naming options.</param>
/// <returns>VideoFileInfo.</returns>
- public VideoFileInfo ResolveDirectory(string path)
+ public static VideoFileInfo? ResolveDirectory(string? path, NamingOptions namingOptions)
{
- return Resolve(path, true);
+ return Resolve(path, true, namingOptions);
}
/// <summary>
/// Resolves the file.
/// </summary>
/// <param name="path">The path.</param>
+ /// <param name="namingOptions">The naming options.</param>
/// <returns>VideoFileInfo.</returns>
- public VideoFileInfo ResolveFile(string path)
+ public static VideoFileInfo? ResolveFile(string? path, NamingOptions namingOptions)
{
- return Resolve(path, false);
+ return Resolve(path, false, namingOptions);
}
/// <summary>
/// Resolves the specified path.
/// </summary>
/// <param name="path">The path.</param>
- /// <param name="IsDirectory">if set to <c>true</c> [is folder].</param>
+ /// <param name="isDirectory">if set to <c>true</c> [is folder].</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <param name="parseName">Whether or not the name should be parsed for info.</param>
/// <returns>VideoFileInfo.</returns>
- /// <exception cref="ArgumentNullException">path</exception>
- public VideoFileInfo Resolve(string path, bool IsDirectory, bool parseName = true)
+ /// <exception cref="ArgumentNullException"><c>path</c> is <c>null</c>.</exception>
+ public static VideoFileInfo? Resolve(string? path, bool isDirectory, NamingOptions namingOptions, bool parseName = true)
{
if (string.IsNullOrEmpty(path))
{
- throw new ArgumentNullException(nameof(path));
+ return null;
}
bool isStub = false;
- string container = null;
- string stubType = null;
+ ReadOnlySpan<char> container = ReadOnlySpan<char>.Empty;
+ string? stubType = null;
- if (!IsDirectory)
+ if (!isDirectory)
{
- var extension = Path.GetExtension(path);
+ var extension = Path.GetExtension(path.AsSpan());
+
// Check supported extensions
- if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
+ if (!namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
{
- var stubResult = StubResolver.ResolveFile(path, _options);
-
- isStub = stubResult.IsStub;
-
// It's not supported. Check stub extensions
- if (!isStub)
+ if (!StubResolver.TryResolveFile(path, namingOptions, out stubType))
{
return null;
}
- stubType = stubResult.StubType;
+ isStub = true;
}
container = extension.TrimStart('.');
}
- var flags = new FlagParser(_options).GetFlags(path);
- var format3DResult = new Format3DParser(_options).Parse(flags);
+ var format3DResult = Format3DParser.Parse(path, namingOptions);
- var extraResult = new ExtraResolver(_options).GetExtraInfo(path);
+ var extraResult = new ExtraResolver(namingOptions).GetExtraInfo(path);
- var name = IsDirectory
- ? Path.GetFileName(path)
- : Path.GetFileNameWithoutExtension(path);
+ var name = Path.GetFileNameWithoutExtension(path);
int? year = null;
if (parseName)
{
- var cleanDateTimeResult = CleanDateTime(name);
+ var cleanDateTimeResult = CleanDateTime(name, namingOptions);
+ name = cleanDateTimeResult.Name;
+ year = cleanDateTimeResult.Year;
- if (string.IsNullOrEmpty(extraResult.ExtraType))
+ if (extraResult.ExtraType == null
+ && TryCleanString(name, namingOptions, out var newName))
{
- name = CleanString(cleanDateTimeResult.Name).Name;
+ name = newName;
}
-
- year = cleanDateTimeResult.Year;
}
- return new VideoFileInfo
- {
- Path = path,
- Container = container,
- IsStub = isStub,
- Name = name,
- Year = year,
- StubType = stubType,
- Is3D = format3DResult.Is3D,
- Format3D = format3DResult.Format3D,
- ExtraType = extraResult.ExtraType,
- IsDirectory = IsDirectory,
- ExtraRule = extraResult.Rule
- };
+ return new VideoFileInfo(
+ path: path,
+ container: container.IsEmpty ? null : container.ToString(),
+ isStub: isStub,
+ name: name,
+ year: year,
+ stubType: stubType,
+ is3D: format3DResult.Is3D,
+ format3D: format3DResult.Format3D,
+ extraType: extraResult.ExtraType,
+ isDirectory: isDirectory,
+ extraRule: extraResult.Rule);
}
- public bool IsVideoFile(string path)
+ /// <summary>
+ /// Determines if path is video file based on extension.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <returns>True if is video file.</returns>
+ public static bool IsVideoFile(string path, NamingOptions namingOptions)
{
- var extension = Path.GetExtension(path) ?? string.Empty;
- return _options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
+ var extension = Path.GetExtension(path.AsSpan());
+ return namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
}
- public bool IsStubFile(string path)
+ /// <summary>
+ /// Determines if path is video file stub based on extension.
+ /// </summary>
+ /// <param name="path">Path to file.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <returns>True if is video file stub.</returns>
+ public static bool IsStubFile(string path, NamingOptions namingOptions)
{
- var extension = Path.GetExtension(path) ?? string.Empty;
- return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
+ var extension = Path.GetExtension(path.AsSpan());
+ return namingOptions.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
}
- public CleanStringResult CleanString(string name)
+ /// <summary>
+ /// Tries to clean name of clutter.
+ /// </summary>
+ /// <param name="name">Raw name.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <param name="newName">Clean name.</param>
+ /// <returns>True if cleaning of name was successful.</returns>
+ public static bool TryCleanString([NotNullWhen(true)] string? name, NamingOptions namingOptions, out string newName)
{
- return new CleanStringParser().Clean(name, _options.CleanStringRegexes);
+ return CleanStringParser.TryClean(name, namingOptions.CleanStringRegexes, out newName);
}
- public CleanDateTimeResult CleanDateTime(string name)
+ /// <summary>
+ /// Tries to get name and year from raw name.
+ /// </summary>
+ /// <param name="name">Raw name.</param>
+ /// <param name="namingOptions">The naming options.</param>
+ /// <returns>Returns <see cref="CleanDateTimeResult"/> with name and optional year.</returns>
+ public static CleanDateTimeResult CleanDateTime(string name, NamingOptions namingOptions)
{
- return new CleanDateTimeParser(_options).Clean(name);
+ return CleanDateTimeParser.Clean(name, namingOptions.CleanDateTimeRegexes);
}
}
}
diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs
deleted file mode 100644
index 83845558a..000000000
--- a/Emby.Notifications/Api/NotificationsService.cs
+++ /dev/null
@@ -1,182 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Notifications;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Notifications.Api
-{
- [Route("/Notifications/{UserId}", "GET", Summary = "Gets notifications")]
- public class GetNotifications : IReturn<NotificationResult>
- {
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsRead { get; set; }
-
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
- }
-
- public class Notification
- {
- public string Id { get; set; }
-
- public string UserId { get; set; }
-
- public DateTime Date { get; set; }
-
- public bool IsRead { get; set; }
-
- public string Name { get; set; }
-
- public string Description { get; set; }
-
- public string Url { get; set; }
-
- public NotificationLevel Level { get; set; }
- }
-
- public class NotificationResult
- {
- public Notification[] Notifications { get; set; }
- public int TotalRecordCount { get; set; }
- }
-
- public class NotificationsSummary
- {
- public int UnreadCount { get; set; }
- public NotificationLevel MaxUnreadNotificationLevel { get; set; }
- }
-
- [Route("/Notifications/{UserId}/Summary", "GET", Summary = "Gets a notification summary for a user")]
- public class GetNotificationsSummary : IReturn<NotificationsSummary>
- {
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string UserId { get; set; }
- }
-
- [Route("/Notifications/Types", "GET", Summary = "Gets notification types")]
- public class GetNotificationTypes : IReturn<List<NotificationTypeInfo>>
- {
- }
-
- [Route("/Notifications/Services", "GET", Summary = "Gets notification types")]
- public class GetNotificationServices : IReturn<List<NameIdPair>>
- {
- }
-
- [Route("/Notifications/Admin", "POST", Summary = "Sends a notification to all admin users")]
- public class AddAdminNotification : IReturnVoid
- {
- [ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Name { get; set; }
-
- [ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Description { get; set; }
-
- [ApiMember(Name = "ImageUrl", Description = "The notification's image url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ImageUrl { get; set; }
-
- [ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Url { get; set; }
-
- [ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public NotificationLevel Level { get; set; }
- }
-
- [Route("/Notifications/{UserId}/Read", "POST", Summary = "Marks notifications as read")]
- public class MarkRead : IReturnVoid
- {
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
- public string Ids { get; set; }
- }
-
- [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")]
- public class MarkUnread : IReturnVoid
- {
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
- public string Ids { get; set; }
- }
-
- [Authenticated]
- public class NotificationsService : IService
- {
- private readonly INotificationManager _notificationManager;
- private readonly IUserManager _userManager;
-
- public NotificationsService(INotificationManager notificationManager, IUserManager userManager)
- {
- _notificationManager = notificationManager;
- _userManager = userManager;
- }
-
- public object Get(GetNotificationTypes request)
- {
- return _notificationManager.GetNotificationTypes();
- }
-
- public object Get(GetNotificationServices request)
- {
- return _notificationManager.GetNotificationServices().ToList();
- }
-
- public object Get(GetNotificationsSummary request)
- {
- return new NotificationsSummary
- {
-
- };
- }
-
- public Task Post(AddAdminNotification request)
- {
- // This endpoint really just exists as post of a real with sickbeard
- return AddNotification(request);
- }
-
- private Task AddNotification(AddAdminNotification request)
- {
- var notification = new NotificationRequest
- {
- Date = DateTime.UtcNow,
- Description = request.Description,
- Level = request.Level,
- Name = request.Name,
- Url = request.Url,
- UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray()
- };
-
- return _notificationManager.SendNotification(notification, CancellationToken.None);
- }
-
- public void Post(MarkRead request)
- {
- }
-
- public void Post(MarkUnread request)
- {
- }
-
- public object Get(GetNotifications request)
- {
- return new NotificationResult();
- }
- }
-}
diff --git a/Emby.Notifications/CoreNotificationTypes.cs b/Emby.Notifications/CoreNotificationTypes.cs
index 0f9fc08d9..ec3490e23 100644
--- a/Emby.Notifications/CoreNotificationTypes.cs
+++ b/Emby.Notifications/CoreNotificationTypes.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Notifications;
@@ -75,10 +76,6 @@ namespace Emby.Notifications
},
new NotificationTypeInfo
{
- Type = NotificationType.CameraImageUploaded.ToString()
- },
- new NotificationTypeInfo
- {
Type = NotificationType.UserLockedOut.ToString()
},
new NotificationTypeInfo
@@ -113,10 +110,6 @@ namespace Emby.Notifications
{
note.Category = _localization.GetLocalizedString("Plugin");
}
- else if (note.Type.IndexOf("CameraImageUploaded", StringComparison.OrdinalIgnoreCase) != -1)
- {
- note.Category = _localization.GetLocalizedString("Sync");
- }
else if (note.Type.IndexOf("UserLockedOut", StringComparison.OrdinalIgnoreCase) != -1)
{
note.Category = _localization.GetLocalizedString("User");
diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj
index 5c68e48c8..d200682e6 100644
--- a/Emby.Notifications/Emby.Notifications.csproj
+++ b/Emby.Notifications/Emby.Notifications.csproj
@@ -1,8 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <ProjectGuid>{2E030C33-6923-4530-9E54-FA29FA6AD1A9}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -15,4 +21,11 @@
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
+ <!-- Code analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/Emby.Notifications/NotificationConfigurationFactory.cs b/Emby.Notifications/NotificationConfigurationFactory.cs
index d08475f7d..3fb3553d0 100644
--- a/Emby.Notifications/NotificationConfigurationFactory.cs
+++ b/Emby.Notifications/NotificationConfigurationFactory.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Notifications;
@@ -13,7 +15,7 @@ namespace Emby.Notifications
new ConfigurationStore
{
Key = "notifications",
- ConfigurationType = typeof (NotificationOptions)
+ ConfigurationType = typeof(NotificationOptions)
}
};
}
diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/NotificationEntryPoint.cs
index ec08fd193..e8ae14ff2 100644
--- a/Emby.Notifications/Notifications.cs
+++ b/Emby.Notifications/NotificationEntryPoint.cs
@@ -4,6 +4,7 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
@@ -13,7 +14,6 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Notifications;
using Microsoft.Extensions.Logging;
@@ -21,70 +21,84 @@ using Microsoft.Extensions.Logging;
namespace Emby.Notifications
{
/// <summary>
- /// Creates notifications for various system events
+ /// Creates notifications for various system events.
/// </summary>
- public class Notifications : IServerEntryPoint
+ public class NotificationEntryPoint : IServerEntryPoint
{
- private readonly ILogger _logger;
-
+ private readonly ILogger<NotificationEntryPoint> _logger;
+ private readonly IActivityManager _activityManager;
+ private readonly ILocalizationManager _localization;
private readonly INotificationManager _notificationManager;
-
private readonly ILibraryManager _libraryManager;
private readonly IServerApplicationHost _appHost;
+ private readonly IConfigurationManager _config;
- private Timer LibraryUpdateTimer { get; set; }
private readonly object _libraryChangedSyncLock = new object();
+ private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
- private readonly IConfigurationManager _config;
- private readonly ILocalizationManager _localization;
- private readonly IActivityManager _activityManager;
+ private Timer? _libraryUpdateTimer;
private string[] _coreNotificationTypes;
- public Notifications(
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NotificationEntryPoint" /> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ /// <param name="localization">The localization manager.</param>
+ /// <param name="notificationManager">The notification manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="config">The configuration manager.</param>
+ public NotificationEntryPoint(
+ ILogger<NotificationEntryPoint> logger,
IActivityManager activityManager,
ILocalizationManager localization,
- ILogger logger,
INotificationManager notificationManager,
ILibraryManager libraryManager,
IServerApplicationHost appHost,
IConfigurationManager config)
{
_logger = logger;
+ _activityManager = activityManager;
+ _localization = localization;
_notificationManager = notificationManager;
_libraryManager = libraryManager;
_appHost = appHost;
_config = config;
- _localization = localization;
- _activityManager = activityManager;
_coreNotificationTypes = new CoreNotificationTypes(localization).GetNotificationTypes().Select(i => i.Type).ToArray();
}
+ /// <inheritdoc />
public Task RunAsync()
{
- _libraryManager.ItemAdded += _libraryManager_ItemAdded;
- _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
- _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged;
- _activityManager.EntryCreated += _activityManager_EntryCreated;
+ _libraryManager.ItemAdded += OnLibraryManagerItemAdded;
+ _appHost.HasPendingRestartChanged += OnAppHostHasPendingRestartChanged;
+ _activityManager.EntryCreated += OnActivityManagerEntryCreated;
return Task.CompletedTask;
}
- private async void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
+ private async void OnAppHostHasPendingRestartChanged(object? sender, EventArgs e)
{
var type = NotificationType.ServerRestartRequired.ToString();
var notification = new NotificationRequest
{
NotificationType = type,
- Name = string.Format(_localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), _appHost.Name)
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("ServerNameNeedsToBeRestarted"),
+ _appHost.Name)
};
await SendNotification(notification, null).ConfigureAwait(false);
}
- private async void _activityManager_EntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e)
+ private async void OnActivityManagerEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e)
{
var entry = e.Argument;
@@ -117,27 +131,7 @@ namespace Emby.Notifications
return _config.GetConfiguration<NotificationOptions>("notifications");
}
- private async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e)
- {
- if (!_appHost.HasUpdateAvailable)
- {
- return;
- }
-
- var type = NotificationType.ApplicationUpdateAvailable.ToString();
-
- var notification = new NotificationRequest
- {
- Description = "Please see jellyfin.media for details.",
- NotificationType = type,
- Name = _localization.GetLocalizedString("NewVersionIsAvailable")
- };
-
- await SendNotification(notification, null).ConfigureAwait(false);
- }
-
- private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
- private void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
+ private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
@@ -146,14 +140,17 @@ namespace Emby.Notifications
lock (_libraryChangedSyncLock)
{
- if (LibraryUpdateTimer == null)
+ if (_libraryUpdateTimer == null)
{
- LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000,
- Timeout.Infinite);
+ _libraryUpdateTimer = new Timer(
+ LibraryUpdateTimerCallback,
+ null,
+ 5000,
+ Timeout.Infinite);
}
else
{
- LibraryUpdateTimer.Change(5000, Timeout.Infinite);
+ _libraryUpdateTimer.Change(5000, Timeout.Infinite);
}
_itemsAdded.Add(e.Item);
@@ -180,7 +177,7 @@ namespace Emby.Notifications
return item.SourceType == SourceType.Library;
}
- private async void LibraryUpdateTimerCallback(object state)
+ private async void LibraryUpdateTimerCallback(object? state)
{
List<BaseItem> items;
@@ -188,17 +185,24 @@ namespace Emby.Notifications
{
items = _itemsAdded.ToList();
_itemsAdded.Clear();
- DisposeLibraryUpdateTimer();
+ _libraryUpdateTimer!.Dispose(); // Shouldn't be null as it just set off this callback
+ _libraryUpdateTimer = null;
}
- items = items.Take(10).ToList();
+ if (items.Count > 10)
+ {
+ items = items.GetRange(0, 10);
+ }
foreach (var item in items)
{
var notification = new NotificationRequest
{
NotificationType = NotificationType.NewLibraryContent.ToString(),
- Name = string.Format(_localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"),
+ GetItemName(item)),
Description = item.Overview
};
@@ -206,57 +210,63 @@ namespace Emby.Notifications
}
}
+ /// <summary>
+ /// Creates a human readable name for the item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <returns>A human readable name for the item.</returns>
public static string GetItemName(BaseItem item)
{
var name = item.Name;
- var episode = item as Episode;
- if (episode != null)
+ if (item is Episode episode)
{
if (episode.IndexNumber.HasValue)
{
- name = string.Format("Ep{0} - {1}", episode.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "Ep{0} - {1}",
+ episode.IndexNumber.Value,
+ name);
}
+
if (episode.ParentIndexNumber.HasValue)
{
- name = string.Format("S{0}, {1}", episode.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "S{0}, {1}",
+ episode.ParentIndexNumber.Value,
+ name);
}
}
- var hasSeries = item as IHasSeries;
-
- if (hasSeries != null)
+ if (item is IHasSeries hasSeries)
{
name = hasSeries.SeriesName + " - " + name;
}
- var hasAlbumArtist = item as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (item is IHasAlbumArtist hasAlbumArtist)
{
var artists = hasAlbumArtist.AlbumArtists;
- if (artists.Length > 0)
+ if (artists.Count > 0)
{
name = artists[0] + " - " + name;
}
}
- else
+ else if (item is IHasArtist hasArtist)
{
- var hasArtist = item as IHasArtist;
- if (hasArtist != null)
- {
- var artists = hasArtist.Artists;
+ var artists = hasArtist.Artists;
- if (artists.Length > 0)
- {
- name = artists[0] + " - " + name;
- }
+ if (artists.Count > 0)
+ {
+ name = artists[0] + " - " + name;
}
}
return name;
}
- private async Task SendNotification(NotificationRequest notification, BaseItem relatedItem)
+ private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem)
{
try
{
@@ -268,23 +278,36 @@ namespace Emby.Notifications
}
}
+ /// <inheritdoc />
public void Dispose()
{
- DisposeLibraryUpdateTimer();
-
- _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
- _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
- _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
- _activityManager.EntryCreated -= _activityManager_EntryCreated;
+ Dispose(true);
+ GC.SuppressFinalize(this);
}
- private void DisposeLibraryUpdateTimer()
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
{
- if (LibraryUpdateTimer != null)
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
{
- LibraryUpdateTimer.Dispose();
- LibraryUpdateTimer = null;
+ _libraryUpdateTimer?.Dispose();
}
+
+ _libraryUpdateTimer = null;
+
+ _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
+ _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged;
+ _activityManager.EntryCreated -= OnActivityManagerEntryCreated;
+
+ _disposed = true;
}
}
}
diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs
index 3d1d4722d..8b281e487 100644
--- a/Emby.Notifications/NotificationManager.cs
+++ b/Emby.Notifications/NotificationManager.cs
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
@@ -15,20 +18,32 @@ using Microsoft.Extensions.Logging;
namespace Emby.Notifications
{
+ /// <summary>
+ /// NotificationManager class.
+ /// </summary>
public class NotificationManager : INotificationManager
{
- private readonly ILogger _logger;
+ private readonly ILogger<NotificationManager> _logger;
private readonly IUserManager _userManager;
private readonly IServerConfigurationManager _config;
- private INotificationService[] _services;
- private INotificationTypeFactory[] _typeFactories;
-
- public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config)
+ private INotificationService[] _services = Array.Empty<INotificationService>();
+ private INotificationTypeFactory[] _typeFactories = Array.Empty<INotificationTypeFactory>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NotificationManager" /> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="config">The server configuration manager.</param>
+ public NotificationManager(
+ ILogger<NotificationManager> logger,
+ IUserManager userManager,
+ IServerConfigurationManager config)
{
+ _logger = logger;
_userManager = userManager;
_config = config;
- _logger = loggerFactory.CreateLogger(GetType().Name);
}
private NotificationOptions GetConfiguration()
@@ -36,12 +51,14 @@ namespace Emby.Notifications
return _config.GetConfiguration<NotificationOptions>("notifications");
}
+ /// <inheritdoc />
public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken)
{
return SendNotification(request, null, cancellationToken);
}
- public Task SendNotification(NotificationRequest request, BaseItem relatedItem, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken)
{
var notificationType = request.NotificationType;
@@ -63,7 +80,8 @@ namespace Emby.Notifications
return Task.WhenAll(tasks);
}
- private Task SendNotification(NotificationRequest request,
+ private Task SendNotification(
+ NotificationRequest request,
INotificationService service,
IEnumerable<User> users,
string title,
@@ -78,17 +96,17 @@ namespace Emby.Notifications
return Task.WhenAll(tasks);
}
- private IEnumerable<Guid> GetUserIds(NotificationRequest request, NotificationOption options)
+ private IEnumerable<Guid> GetUserIds(NotificationRequest request, NotificationOption? options)
{
if (request.SendToUserMode.HasValue)
{
switch (request.SendToUserMode.Value)
{
case SendToUserType.Admins:
- return _userManager.Users.Where(i => i.Policy.IsAdministrator)
+ return _userManager.Users.Where(i => i.HasPermission(PermissionKind.IsAdministrator))
.Select(i => i.Id);
case SendToUserType.All:
- return _userManager.Users.Select(i => i.Id);
+ return _userManager.UsersIds;
case SendToUserType.Custom:
return request.UserIds;
default:
@@ -101,14 +119,15 @@ namespace Emby.Notifications
var config = GetConfiguration();
return _userManager.Users
- .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N"), i.Policy))
+ .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N", CultureInfo.InvariantCulture), i))
.Select(i => i.Id);
}
return request.UserIds;
}
- private async Task SendNotification(NotificationRequest request,
+ private async Task SendNotification(
+ NotificationRequest request,
INotificationService service,
string title,
string description,
@@ -125,7 +144,7 @@ namespace Emby.Notifications
User = user
};
- _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Name);
+ _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Username);
try
{
@@ -160,12 +179,14 @@ namespace Emby.Notifications
return GetConfiguration().IsServiceEnabled(service.Name, notificationType);
}
+ /// <inheritdoc />
public void AddParts(IEnumerable<INotificationService> services, IEnumerable<INotificationTypeFactory> notificationTypeFactories)
{
_services = services.ToArray();
_typeFactories = notificationTypeFactories.ToArray();
}
+ /// <inheritdoc />
public List<NotificationTypeInfo> GetNotificationTypes()
{
var list = _typeFactories.Select(i =>
@@ -179,7 +200,6 @@ namespace Emby.Notifications
_logger.LogError(ex, "Error in GetNotificationTypes");
return new List<NotificationTypeInfo>();
}
-
}).SelectMany(i => i).ToList();
var config = GetConfiguration();
@@ -192,13 +212,13 @@ namespace Emby.Notifications
return list;
}
+ /// <inheritdoc />
public IEnumerable<NameIdPair> GetNotificationServices()
{
return _services.Select(i => new NameIdPair
{
Name = i.Name,
- Id = i.Name.GetMD5().ToString("N")
-
+ Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture)
}).OrderBy(i => i.Name);
}
}
diff --git a/Emby.Notifications/Properties/AssemblyInfo.cs b/Emby.Notifications/Properties/AssemblyInfo.cs
index fd7037551..5c82c90c4 100644
--- a/Emby.Notifications/Properties/AssemblyInfo.cs
+++ b/Emby.Notifications/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj
index c9830abc5..bf6252c19 100644
--- a/Emby.Photos/Emby.Photos.csproj
+++ b/Emby.Photos/Emby.Photos.csproj
@@ -1,5 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{89AB4548-770D-41FD-A891-8DAFF44F452C}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
@@ -10,12 +15,20 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TagLibSharp" Version="2.2.0-beta" />
+ <PackageReference Include="TagLibSharp" Version="2.2.0" />
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs
index a4179e660..4071e4e54 100644
--- a/Emby.Photos/PhotoProvider.cs
+++ b/Emby.Photos/PhotoProvider.cs
@@ -17,86 +17,80 @@ using TagLib.IFD.Tags;
namespace Emby.Photos
{
+ /// <summary>
+ /// Metadata provider for photos.
+ /// </summary>
public class PhotoProvider : ICustomMetadataProvider<Photo>, IForcedProvider, IHasItemChangeMonitor
{
- private readonly ILogger _logger;
- private IImageProcessor _imageProcessor;
+ private readonly ILogger<PhotoProvider> _logger;
+ private readonly IImageProcessor _imageProcessor;
- public PhotoProvider(ILogger logger, IImageProcessor imageProcessor)
+ // These are causing taglib to hang
+ private readonly string[] _includeExtensions = new string[] { ".jpg", ".jpeg", ".png", ".tiff", ".cr2" };
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PhotoProvider" /> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="imageProcessor">The image processor.</param>
+ public PhotoProvider(ILogger<PhotoProvider> logger, IImageProcessor imageProcessor)
{
_logger = logger;
_imageProcessor = imageProcessor;
}
+ /// <inheritdoc />
+ public string Name => "Embedded Information";
+
+ /// <inheritdoc />
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
if (item.IsFileProtocol)
{
var file = directoryService.GetFile(item.Path);
- if (file != null && file.LastWriteTimeUtc != item.DateModified)
- {
- return true;
- }
+ return file != null && file.LastWriteTimeUtc != item.DateModified;
}
return false;
}
- // These are causing taglib to hang
- private string[] _includextensions = new string[] { ".jpg", ".jpeg", ".png", ".tiff", ".cr2" };
-
+ /// <inheritdoc />
public Task<ItemUpdateType> FetchAsync(Photo item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
item.SetImagePath(ImageType.Primary, item.Path);
// Examples: https://github.com/mono/taglib-sharp/blob/a5f6949a53d09ce63ee7495580d6802921a21f14/tests/fixtures/TagLib.Tests.Images/NullOrientationTest.cs
- if (_includextensions.Contains(Path.GetExtension(item.Path) ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ if (_includeExtensions.Contains(Path.GetExtension(item.Path), StringComparer.OrdinalIgnoreCase))
{
try
{
using (var file = TagLib.File.Create(item.Path))
{
- var image = file as TagLib.Image.File;
-
- var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;
-
- if (tag != null)
+ if (file.GetTag(TagTypes.TiffIFD) is IFDTag tag)
{
var structure = tag.Structure;
-
- if (structure != null)
+ if (structure != null
+ && structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) is SubIFDEntry exif)
{
- var exif = structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) as SubIFDEntry;
-
- if (exif != null)
+ var exifStructure = exif.Structure;
+ if (exifStructure != null)
{
- var exifStructure = exif.Structure;
+ var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;
+ if (entry != null)
+ {
+ item.Aperture = (double)entry.Value.Numerator / entry.Value.Denominator;
+ }
- if (exifStructure != null)
+ entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;
+ if (entry != null)
{
- var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;
-
- if (entry != null)
- {
- double val = entry.Value.Numerator;
- val /= entry.Value.Denominator;
- item.Aperture = val;
- }
-
- entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;
-
- if (entry != null)
- {
- double val = entry.Value.Numerator;
- val /= entry.Value.Denominator;
- item.ShutterSpeed = val;
- }
+ item.ShutterSpeed = (double)entry.Value.Numerator / entry.Value.Denominator;
}
}
}
}
- if (image != null)
+ if (file is TagLib.Image.File image)
{
item.CameraMake = image.ImageTag.Make;
item.CameraModel = image.ImageTag.Model;
@@ -105,23 +99,14 @@ namespace Emby.Photos
item.Height = image.Properties.PhotoHeight;
var rating = image.ImageTag.Rating;
- if (rating.HasValue)
- {
- item.CommunityRating = rating;
- }
- else
- {
- item.CommunityRating = null;
- }
+ item.CommunityRating = rating.HasValue ? rating : null;
item.Overview = image.ImageTag.Comment;
- if (!string.IsNullOrWhiteSpace(image.ImageTag.Title))
+ if (!string.IsNullOrWhiteSpace(image.ImageTag.Title)
+ && !item.LockedFields.Contains(MetadataField.Name))
{
- if (!item.LockedFields.Contains(MetadataFields.Name))
- {
- item.Name = image.ImageTag.Title;
- }
+ item.Name = image.ImageTag.Title;
}
var dateTaken = image.ImageTag.DateTime;
@@ -140,12 +125,9 @@ namespace Emby.Photos
{
item.Orientation = null;
}
- else
+ else if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out ImageOrientation orientation))
{
- if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out ImageOrientation orientation))
- {
- item.Orientation = orientation;
- }
+ item.Orientation = orientation;
}
item.ExposureTime = image.ImageTag.ExposureTime;
@@ -178,7 +160,7 @@ namespace Emby.Photos
try
{
- var size = _imageProcessor.GetImageDimensions(item, img, false);
+ var size = _imageProcessor.GetImageDimensions(item, img);
if (size.Width > 0 && size.Height > 0)
{
@@ -192,10 +174,8 @@ namespace Emby.Photos
}
}
- const ItemUpdateType result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
- return Task.FromResult(result);
+ const ItemUpdateType Result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
+ return Task.FromResult(Result);
}
-
- public string Name => "Embedded Information";
}
}
diff --git a/Emby.Photos/Properties/AssemblyInfo.cs b/Emby.Photos/Properties/AssemblyInfo.cs
index 262125d38..a3bb4362a 100644
--- a/Emby.Photos/Properties/AssemblyInfo.cs
+++ b/Emby.Photos/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
deleted file mode 100644
index 739f68767..000000000
--- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
+++ /dev/null
@@ -1,577 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Notifications;
-using MediaBrowser.Model.Tasks;
-using MediaBrowser.Model.Updates;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityLogEntryPoint : IServerEntryPoint
- {
- private readonly IInstallationManager _installationManager;
-
- //private readonly ILogger _logger;
- private readonly ISessionManager _sessionManager;
- private readonly ITaskManager _taskManager;
- private readonly IActivityManager _activityManager;
- private readonly ILocalizationManager _localization;
-
- private readonly ILibraryManager _libraryManager;
- private readonly ISubtitleManager _subManager;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
- private readonly IServerApplicationHost _appHost;
- private readonly IDeviceManager _deviceManager;
-
- public ActivityLogEntryPoint(ISessionManager sessionManager, IDeviceManager deviceManager, ITaskManager taskManager, IActivityManager activityManager, ILocalizationManager localization, IInstallationManager installationManager, ILibraryManager libraryManager, ISubtitleManager subManager, IUserManager userManager, IServerConfigurationManager config, IServerApplicationHost appHost)
- {
- _sessionManager = sessionManager;
- _taskManager = taskManager;
- _activityManager = activityManager;
- _localization = localization;
- _installationManager = installationManager;
- _libraryManager = libraryManager;
- _subManager = subManager;
- _userManager = userManager;
- _config = config;
- _appHost = appHost;
- _deviceManager = deviceManager;
- }
-
- public Task RunAsync()
- {
- _taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
- _installationManager.PluginInstalled += _installationManager_PluginInstalled;
- _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
- _installationManager.PluginUpdated += _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
-
- _sessionManager.SessionStarted += _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded += _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
-
- //_subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
- _subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated += _userManager_UserCreated;
- _userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
- _userManager.UserDeleted += _userManager_UserDeleted;
- _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
- _userManager.UserLockedOut += _userManager_UserLockedOut;
-
- //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
- //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
-
- _deviceManager.CameraImageUploaded += _deviceManager_CameraImageUploaded;
-
- _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
-
- return Task.CompletedTask;
- }
-
- void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("CameraImageUploadedFrom"), e.Argument.Device.Name),
- Type = NotificationType.CameraImageUploaded.ToString()
- });
- }
-
- void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name),
- Type = NotificationType.UserLockedOut.ToString(),
- UserId = e.Argument.Id
- });
- }
-
- void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitleDownloadFailure",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = e.Exception.Message
- });
- }
-
- void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.LogWarning("PlaybackStopped reported with null media info.");
- return;
- }
-
- if (e.Item != null && e.Item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
- Type = GetPlaybackStoppedNotificationType(item.MediaType),
- UserId = user.Id
- });
- }
-
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- var item = e.MediaInfo;
-
- if (item == null)
- {
- //_logger.LogWarning("PlaybackStart reported with null media info.");
- return;
- }
-
- if (e.Item != null && e.Item.IsThemeMedia)
- {
- // Don't report theme song or local trailer playback
- return;
- }
-
- if (e.Users.Count == 0)
- {
- return;
- }
-
- var user = e.Users.First();
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
- Type = GetPlaybackNotificationType(item.MediaType),
- UserId = user.Id
- });
- }
-
- private static string GetItemName(BaseItemDto item)
- {
- var name = item.Name;
-
- if (!string.IsNullOrEmpty(item.SeriesName))
- {
- name = item.SeriesName + " - " + name;
- }
-
- if (item.Artists != null && item.Artists.Length > 0)
- {
- name = item.Artists[0] + " - " + name;
- }
-
- return name;
- }
-
- private static string GetPlaybackNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlayback.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlayback.ToString();
- }
-
- return null;
- }
-
- private static string GetPlaybackStoppedNotificationType(string mediaType)
- {
- if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.AudioPlaybackStopped.ToString();
- }
- if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
- {
- return NotificationType.VideoPlaybackStopped.ToString();
- }
-
- return null;
- }
-
- void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrEmpty(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionEnded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId
- });
- }
-
- void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
- {
- var user = e.Argument.User;
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), user.Name),
- Type = "AuthenticationSucceeded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.SessionInfo.RemoteEndPoint),
- UserId = user.Id
- });
- }
-
- void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
- Type = "AuthenticationFailed",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
- Severity = LogLevel.Error
- });
- }
-
- void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("MessageApplicationUpdatedTo"), e.Argument.versionStr),
- Type = NotificationType.ApplicationUpdateInstalled.ToString(),
- Overview = e.Argument.description
- });
- }
-
- void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
- Type = "NamedConfigurationUpdated"
- });
- }
-
- void _config_ConfigurationUpdated(object sender, EventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
- Type = "ServerConfigurationUpdated"
- });
- }
-
- void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserPolicyUpdatedWithName"), e.Argument.Name),
- Type = "UserPolicyUpdated",
- UserId = e.Argument.Id
- });
- }
-
- void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
- Type = "UserDeleted"
- });
- }
-
- void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
- Type = "UserPasswordChanged",
- UserId = e.Argument.Id
- });
- }
-
- void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
- Type = "UserCreated",
- UserId = e.Argument.Id
- });
- }
-
- void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
- Type = "SubtitlesDownloaded",
- ItemId = e.Item.Id.ToString("N"),
- ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
- });
- }
-
- void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
- {
- string name;
- var session = e.SessionInfo;
-
- if (string.IsNullOrEmpty(session.UserName))
- {
- name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
-
- // Causing too much spam for now
- return;
- }
- else
- {
- name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = name,
- Type = "SessionStarted",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
- UserId = session.UserId
- });
- }
-
- void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
- Type = NotificationType.PluginUpdateInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
- Overview = e.Argument.Item2.description
- });
- }
-
- void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
- Type = NotificationType.PluginUninstalled.ToString()
- });
- }
-
- void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
- {
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
- Type = NotificationType.PluginInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
- });
- }
-
- void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
- {
- var installationInfo = e.InstallationInfo;
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("NameInstallFailed"), installationInfo.Name),
- Type = NotificationType.InstallationFailed.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), installationInfo.Version),
- Overview = e.Exception.Message
- });
- }
-
- void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- var result = e.Result;
- var task = e.Task;
-
- var activityTask = task.ScheduledTask as IConfigurableScheduledTask;
- if (activityTask != null && !activityTask.IsLogged)
- {
- return;
- }
-
- var time = result.EndTimeUtc - result.StartTimeUtc;
- var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
-
- if (result.Status == TaskCompletionStatus.Failed)
- {
- var vals = new List<string>();
-
- if (!string.IsNullOrEmpty(e.Result.ErrorMessage))
- {
- vals.Add(e.Result.ErrorMessage);
- }
- if (!string.IsNullOrEmpty(e.Result.LongErrorMessage))
- {
- vals.Add(e.Result.LongErrorMessage);
- }
-
- CreateLogEntry(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
- Type = NotificationType.TaskFailed.ToString(),
- Overview = string.Join(Environment.NewLine, vals.ToArray()),
- ShortOverview = runningTime,
- Severity = LogLevel.Error
- });
- }
- }
-
- private void CreateLogEntry(ActivityLogEntry entry)
- {
- try
- {
- _activityManager.Create(entry);
- }
- catch
- {
- // Logged at lower levels
- }
- }
-
- public void Dispose()
- {
- _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
-
- _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
- _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
- _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
- _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
-
- _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
- _sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
- _sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
- _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
-
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
-
- _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
-
- _userManager.UserCreated -= _userManager_UserCreated;
- _userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
- _userManager.UserDeleted -= _userManager_UserDeleted;
- _userManager.UserPolicyUpdated -= _userManager_UserPolicyUpdated;
- _userManager.UserLockedOut -= _userManager_UserLockedOut;
-
- _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
- _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
-
- _deviceManager.CameraImageUploaded -= _deviceManager_CameraImageUploaded;
-
- _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
- }
-
- /// <summary>
- /// Constructs a user-friendly string for this TimeSpan instance.
- /// </summary>
- public static string ToUserFriendlyString(TimeSpan span)
- {
- const int DaysInYear = 365;
- const int DaysInMonth = 30;
-
- // Get each non-zero value from TimeSpan component
- var values = new List<string>();
-
- // Number of years
- int days = span.Days;
- if (days >= DaysInYear)
- {
- int years = days / DaysInYear;
- values.Add(CreateValueString(years, "year"));
- days = days % DaysInYear;
- }
- // Number of months
- if (days >= DaysInMonth)
- {
- int months = days / DaysInMonth;
- values.Add(CreateValueString(months, "month"));
- days = days % DaysInMonth;
- }
- // Number of days
- if (days >= 1)
- values.Add(CreateValueString(days, "day"));
- // Number of hours
- if (span.Hours >= 1)
- values.Add(CreateValueString(span.Hours, "hour"));
- // Number of minutes
- if (span.Minutes >= 1)
- values.Add(CreateValueString(span.Minutes, "minute"));
- // Number of seconds (include when 0 if no other components included)
- if (span.Seconds >= 1 || values.Count == 0)
- values.Add(CreateValueString(span.Seconds, "second"));
-
- // Combine values into string
- var builder = new StringBuilder();
- for (int i = 0; i < values.Count; i++)
- {
- if (builder.Length > 0)
- builder.Append(i == values.Count - 1 ? " and " : ", ");
- builder.Append(values[i]);
- }
- // Return result
- return builder.ToString();
- }
-
- /// <summary>
- /// Constructs a string description of a time-span value.
- /// </summary>
- /// <param name="value">The value of this item</param>
- /// <param name="description">The name of this item (singular form)</param>
- private static string CreateValueString(int value, string description)
- {
- return string.Format("{0:#,##0} {1}",
- value, value == 1 ? description : string.Format("{0}s", description));
- }
- }
-}
diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs
deleted file mode 100644
index 6febcc2f7..000000000
--- a/Emby.Server.Implementations/Activity/ActivityManager.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityManager : IActivityManager
- {
- public event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated;
-
- private readonly IActivityRepository _repo;
- private readonly ILogger _logger;
- private readonly IUserManager _userManager;
-
- public ActivityManager(
- ILoggerFactory loggerFactory,
- IActivityRepository repo,
- IUserManager userManager)
- {
- _logger = loggerFactory.CreateLogger(nameof(ActivityManager));
- _repo = repo;
- _userManager = userManager;
- }
-
- public void Create(ActivityLogEntry entry)
- {
- entry.Date = DateTime.UtcNow;
-
- _repo.Create(entry);
-
- EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(entry));
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
- {
- var result = _repo.GetActivityLogEntries(minDate, hasUserId, startIndex, limit);
-
- foreach (var item in result.Items.Where(i => !i.UserId.Equals(Guid.Empty)))
- {
- var user = _userManager.GetUserById(item.UserId);
-
- if (user != null)
- {
- var dto = _userManager.GetUserDto(user);
- item.UserPrimaryImageTag = dto.PrimaryImageTag;
- }
- }
-
- return result;
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit)
- {
- return GetActivityLogEntries(minDate, null, startIndex, limit);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs
deleted file mode 100644
index aeed8b6f1..000000000
--- a/Emby.Server.Implementations/Activity/ActivityRepository.cs
+++ /dev/null
@@ -1,310 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Emby.Server.Implementations.Data;
-using MediaBrowser.Controller;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-using SQLitePCL.pretty;
-
-namespace Emby.Server.Implementations.Activity
-{
- public class ActivityRepository : BaseSqliteRepository, IActivityRepository
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- protected IFileSystem FileSystem { get; private set; }
-
- public ActivityRepository(ILoggerFactory loggerFactory, IServerApplicationPaths appPaths, IFileSystem fileSystem)
- : base(loggerFactory.CreateLogger(nameof(ActivityRepository)))
- {
- DbFilePath = Path.Combine(appPaths.DataPath, "activitylog.db");
- FileSystem = fileSystem;
- }
-
- public void Initialize()
- {
- try
- {
- InitializeInternal();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error loading database file. Will reset and retry.");
-
- FileSystem.DeleteFile(DbFilePath);
-
- InitializeInternal();
- }
- }
-
- private void InitializeInternal()
- {
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- connection.RunQueries(new[]
- {
- "create table if not exists ActivityLog (Id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Overview TEXT, ShortOverview TEXT, Type TEXT NOT NULL, ItemId TEXT, UserId TEXT, DateCreated DATETIME NOT NULL, LogSeverity TEXT NOT NULL)",
- "drop index if exists idx_ActivityLogEntries"
- });
-
- TryMigrate(connection);
- }
- }
-
- private void TryMigrate(ManagedConnection connection)
- {
- try
- {
- if (TableExists(connection, "ActivityLogEntries"))
- {
- connection.RunQueries(new[]
- {
- "INSERT INTO ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) SELECT Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity FROM ActivityLogEntries",
- "drop table if exists ActivityLogEntries"
- });
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error migrating activity log database");
- }
- }
-
- private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLog";
-
- public void Create(ActivityLogEntry entry)
- {
- if (entry == null)
- {
- throw new ArgumentNullException(nameof(entry));
- }
-
- using (WriteLock.Write())
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"))
- {
- statement.TryBind("@Name", entry.Name);
-
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
-
- public void Update(ActivityLogEntry entry)
- {
- if (entry == null)
- {
- throw new ArgumentNullException(nameof(entry));
- }
-
- using (WriteLock.Write())
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id"))
- {
- statement.TryBind("@Id", entry.Id);
-
- statement.TryBind("@Name", entry.Name);
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
-
- public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
- {
- using (WriteLock.Read())
- using (var connection = CreateConnection(true))
- {
- var commandText = BaseActivitySelectText;
- var whereClauses = new List<string>();
-
- if (minDate.HasValue)
- {
- whereClauses.Add("DateCreated>=@DateCreated");
- }
- if (hasUserId.HasValue)
- {
- if (hasUserId.Value)
- {
- whereClauses.Add("UserId not null");
- }
- else
- {
- whereClauses.Add("UserId is null");
- }
- }
-
- var whereTextWithoutPaging = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- if (startIndex.HasValue && startIndex.Value > 0)
- {
- var pagingWhereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
- pagingWhereText,
- startIndex.Value.ToString(_usCulture)));
- }
-
- var whereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- commandText += whereText;
-
- commandText += " ORDER BY DateCreated DESC";
-
- if (limit.HasValue)
- {
- commandText += " LIMIT " + limit.Value.ToString(_usCulture);
- }
-
- var statementTexts = new List<string>();
- statementTexts.Add(commandText);
- statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
-
- return connection.RunInTransaction(db =>
- {
- var list = new List<ActivityLogEntry>();
- var result = new QueryResult<ActivityLogEntry>();
-
- var statements = PrepareAllSafe(db, statementTexts).ToList();
-
- using (var statement = statements[0])
- {
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetEntry(row));
- }
- }
-
- using (var statement = statements[1])
- {
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
-
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
-
- result.Items = list.ToArray();
- return result;
-
- }, ReadTransactionMode);
- }
- }
-
- private static ActivityLogEntry GetEntry(IReadOnlyList<IResultSetValue> reader)
- {
- var index = 0;
-
- var info = new ActivityLogEntry
- {
- Id = reader[index].ToInt64()
- };
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Name = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Overview = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.ShortOverview = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Type = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.ItemId = reader[index].ToString();
- }
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.UserId = new Guid(reader[index].ToString());
- }
-
- index++;
- info.Date = reader[index].ReadDateTime();
-
- index++;
- if (reader[index].SQLiteType != SQLiteType.Null)
- {
- info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true);
- }
-
- return info;
- }
- }
-}
diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
index 65cdccfa5..6edfad575 100644
--- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
+++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
@@ -5,54 +5,60 @@ using MediaBrowser.Common.Configuration;
namespace Emby.Server.Implementations.AppBase
{
/// <summary>
- /// Provides a base class to hold common application paths used by both the Ui and Server.
+ /// Provides a base class to hold common application paths used by both the UI and Server.
/// This can be subclassed to add application-specific paths.
/// </summary>
public abstract class BaseApplicationPaths : IApplicationPaths
{
+ private string _dataPath;
+
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationPaths"/> class.
/// </summary>
+ /// <param name="programDataPath">The program data path.</param>
+ /// <param name="logDirectoryPath">The log directory path.</param>
+ /// <param name="configurationDirectoryPath">The configuration directory path.</param>
+ /// <param name="cacheDirectoryPath">The cache directory path.</param>
+ /// <param name="webDirectoryPath">The web directory path.</param>
protected BaseApplicationPaths(
string programDataPath,
string logDirectoryPath,
string configurationDirectoryPath,
- string cacheDirectoryPath)
+ string cacheDirectoryPath,
+ string webDirectoryPath)
{
ProgramDataPath = programDataPath;
LogDirectoryPath = logDirectoryPath;
ConfigurationDirectoryPath = configurationDirectoryPath;
CachePath = cacheDirectoryPath;
+ WebPath = webDirectoryPath;
- DataPath = Path.Combine(ProgramDataPath, "data");
+ _dataPath = Directory.CreateDirectory(Path.Combine(ProgramDataPath, "data")).FullName;
}
/// <summary>
- /// Gets the path to the program data folder
+ /// Gets the path to the program data folder.
/// </summary>
/// <value>The program data path.</value>
- public string ProgramDataPath { get; private set; }
+ public string ProgramDataPath { get; }
+
+ /// <inheritdoc/>
+ public string WebPath { get; }
/// <summary>
- /// Gets the path to the system folder
+ /// Gets the path to the system folder.
/// </summary>
+ /// <value>The path to the system folder.</value>
public string ProgramSystemPath { get; } = AppContext.BaseDirectory;
/// <summary>
- /// Gets the folder path to the data directory
+ /// Gets the folder path to the data directory.
/// </summary>
/// <value>The data directory.</value>
- private string _dataPath;
- public string DataPath
- {
- get => _dataPath;
- private set => _dataPath = Directory.CreateDirectory(value).FullName;
- }
+ public string DataPath => _dataPath;
- /// <summary>
- /// Gets the magic strings used for virtual path manipulation.
- /// </summary>
- public string VirtualDataPath { get; } = "%AppDataPath%";
+ /// <inheritdoc />
+ public string VirtualDataPath => "%AppDataPath%";
/// <summary>
/// Gets the image cache path.
@@ -61,43 +67,43 @@ namespace Emby.Server.Implementations.AppBase
public string ImageCachePath => Path.Combine(CachePath, "images");
/// <summary>
- /// Gets the path to the plugin directory
+ /// Gets the path to the plugin directory.
/// </summary>
/// <value>The plugins path.</value>
public string PluginsPath => Path.Combine(ProgramDataPath, "plugins");
/// <summary>
- /// Gets the path to the plugin configurations directory
+ /// Gets the path to the plugin configurations directory.
/// </summary>
/// <value>The plugin configurations path.</value>
public string PluginConfigurationsPath => Path.Combine(PluginsPath, "configurations");
/// <summary>
- /// Gets the path to the log directory
+ /// Gets the path to the log directory.
/// </summary>
/// <value>The log directory path.</value>
- public string LogDirectoryPath { get; private set; }
+ public string LogDirectoryPath { get; }
/// <summary>
- /// Gets the path to the application configuration root directory
+ /// Gets the path to the application configuration root directory.
/// </summary>
/// <value>The configuration directory path.</value>
- public string ConfigurationDirectoryPath { get; private set; }
+ public string ConfigurationDirectoryPath { get; }
/// <summary>
- /// Gets the path to the system configuration file
+ /// Gets the path to the system configuration file.
/// </summary>
/// <value>The system configuration file path.</value>
public string SystemConfigurationFilePath => Path.Combine(ConfigurationDirectoryPath, "system.xml");
/// <summary>
- /// Gets the folder path to the cache directory
+ /// Gets or sets the folder path to the cache directory.
/// </summary>
/// <value>The cache directory.</value>
public string CachePath { get; set; }
/// <summary>
- /// Gets the folder path to the temp directory within the cache folder
+ /// Gets the folder path to the temp directory within the cache folder.
/// </summary>
/// <value>The temp directory.</value>
public string TempDirectory => Path.Combine(CachePath, "temp");
diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
index af60a8dce..d38535634 100644
--- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
+++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
@@ -1,9 +1,11 @@
+#nullable disable
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
-using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
@@ -15,15 +17,48 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.AppBase
{
/// <summary>
- /// Class BaseConfigurationManager
+ /// Class BaseConfigurationManager.
/// </summary>
public abstract class BaseConfigurationManager : IConfigurationManager
{
+ private readonly IFileSystem _fileSystem;
+
+ private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
+
/// <summary>
- /// Gets the type of the configuration.
+ /// The _configuration sync lock.
/// </summary>
- /// <value>The type of the configuration.</value>
- protected abstract Type ConfigurationType { get; }
+ private readonly object _configurationSyncLock = new object();
+
+ private ConfigurationStore[] _configurationStores = Array.Empty<ConfigurationStore>();
+ private IConfigurationFactory[] _configurationFactories = Array.Empty<IConfigurationFactory>();
+
+ /// <summary>
+ /// The _configuration loaded.
+ /// </summary>
+ private bool _configurationLoaded;
+
+ /// <summary>
+ /// The _configuration.
+ /// </summary>
+ private BaseApplicationConfiguration _configuration;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
+ /// </summary>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="xmlSerializer">The XML serializer.</param>
+ /// <param name="fileSystem">The file system.</param>
+ protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
+ {
+ CommonApplicationPaths = applicationPaths;
+ XmlSerializer = xmlSerializer;
+ _fileSystem = fileSystem;
+ Logger = loggerFactory.CreateLogger<BaseConfigurationManager>();
+
+ UpdateCachePath();
+ }
/// <summary>
/// Occurs when [configuration updated].
@@ -41,10 +76,17 @@ namespace Emby.Server.Implementations.AppBase
public event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdated;
/// <summary>
+ /// Gets the type of the configuration.
+ /// </summary>
+ /// <value>The type of the configuration.</value>
+ protected abstract Type ConfigurationType { get; }
+
+ /// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
- protected ILogger Logger { get; private set; }
+ protected ILogger<BaseConfigurationManager> Logger { get; private set; }
+
/// <summary>
/// Gets the XML serializer.
/// </summary>
@@ -52,36 +94,39 @@ namespace Emby.Server.Implementations.AppBase
protected IXmlSerializer XmlSerializer { get; private set; }
/// <summary>
- /// Gets or sets the application paths.
+ /// Gets the application paths.
/// </summary>
/// <value>The application paths.</value>
public IApplicationPaths CommonApplicationPaths { get; private set; }
- public readonly IFileSystem FileSystem;
/// <summary>
- /// The _configuration loaded
- /// </summary>
- private bool _configurationLoaded;
- /// <summary>
- /// The _configuration sync lock
- /// </summary>
- private object _configurationSyncLock = new object();
- /// <summary>
- /// The _configuration
- /// </summary>
- private BaseApplicationConfiguration _configuration;
- /// <summary>
- /// Gets the system configuration
+ /// Gets or sets the system configuration.
/// </summary>
/// <value>The configuration.</value>
public BaseApplicationConfiguration CommonConfiguration
{
get
{
- // Lazy load
- LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer));
- return _configuration;
+ if (_configurationLoaded)
+ {
+ return _configuration;
+ }
+
+ lock (_configurationSyncLock)
+ {
+ if (_configurationLoaded)
+ {
+ return _configuration;
+ }
+
+ _configuration = (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer);
+
+ _configurationLoaded = true;
+
+ return _configuration;
+ }
}
+
protected set
{
_configuration = value;
@@ -90,26 +135,37 @@ namespace Emby.Server.Implementations.AppBase
}
}
- private ConfigurationStore[] _configurationStores = { };
- private IConfigurationFactory[] _configurationFactories = { };
-
/// <summary>
- /// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
+ /// Manually pre-loads a factory so that it is available pre system initialisation.
/// </summary>
- /// <param name="applicationPaths">The application paths.</param>
- /// <param name="loggerFactory">The logger factory.</param>
- /// <param name="xmlSerializer">The XML serializer.</param>
- /// <param name="fileSystem">The file system</param>
- protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
+ /// <typeparam name="T">Class to register.</typeparam>
+ public virtual void RegisterConfiguration<T>()
+ where T : IConfigurationFactory
{
- CommonApplicationPaths = applicationPaths;
- XmlSerializer = xmlSerializer;
- FileSystem = fileSystem;
- Logger = loggerFactory.CreateLogger(GetType().Name);
+ IConfigurationFactory factory = Activator.CreateInstance<T>();
- UpdateCachePath();
+ if (_configurationFactories == null)
+ {
+ _configurationFactories = new[] { factory };
+ }
+ else
+ {
+ var oldLen = _configurationFactories.Length;
+ var arr = new IConfigurationFactory[oldLen + 1];
+ _configurationFactories.CopyTo(arr, 0);
+ arr[oldLen] = factory;
+ _configurationFactories = arr;
+ }
+
+ _configurationStores = _configurationFactories
+ .SelectMany(i => i.GetConfigurations())
+ .ToArray();
}
+ /// <summary>
+ /// Adds parts.
+ /// </summary>
+ /// <param name="factories">The configuration factories.</param>
public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
{
_configurationFactories = factories.ToArray();
@@ -151,7 +207,7 @@ namespace Emby.Server.Implementations.AppBase
/// Replaces the configuration.
/// </summary>
/// <param name="newConfiguration">The new configuration.</param>
- /// <exception cref="ArgumentNullException">newConfiguration</exception>
+ /// <exception cref="ArgumentNullException"><c>newConfiguration</c> is <c>null</c>.</exception>
public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
{
if (newConfiguration == null)
@@ -171,6 +227,7 @@ namespace Emby.Server.Implementations.AppBase
private void UpdateCachePath()
{
string cachePath;
+
// If the configuration file has no entry (i.e. not set in UI)
if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
{
@@ -193,7 +250,7 @@ namespace Emby.Server.Implementations.AppBase
cachePath = CommonConfiguration.CachePath;
}
- Logger.LogInformation("Setting cache path to " + cachePath);
+ Logger.LogInformation("Setting cache path: {Path}", cachePath);
((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
}
@@ -201,59 +258,70 @@ namespace Emby.Server.Implementations.AppBase
/// Replaces the cache path.
/// </summary>
/// <param name="newConfig">The new configuration.</param>
- /// <exception cref="DirectoryNotFoundException"></exception>
+ /// <exception cref="DirectoryNotFoundException">The new cache path doesn't exist.</exception>
private void ValidateCachePath(BaseApplicationConfiguration newConfig)
{
var newPath = newConfig.CachePath;
if (!string.IsNullOrWhiteSpace(newPath)
- && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
+ && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath, StringComparison.Ordinal))
{
// Validate
if (!Directory.Exists(newPath))
{
- throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
+ throw new DirectoryNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} does not exist.",
+ newPath));
}
EnsureWriteAccess(newPath);
}
}
+ /// <summary>
+ /// Ensures that we have write access to the path.
+ /// </summary>
+ /// <param name="path">The path.</param>
protected void EnsureWriteAccess(string path)
{
var file = Path.Combine(path, Guid.NewGuid().ToString());
File.WriteAllText(file, string.Empty);
- FileSystem.DeleteFile(file);
+ _fileSystem.DeleteFile(file);
}
- private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
-
private string GetConfigurationFile(string key)
{
return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
}
+ /// <inheritdoc />
public object GetConfiguration(string key)
{
- return _configurations.GetOrAdd(key, k =>
- {
- var file = GetConfigurationFile(key);
+ return _configurations.GetOrAdd(
+ key,
+ (k, configurationManager) =>
+ {
+ var file = configurationManager.GetConfigurationFile(k);
- var configurationInfo = _configurationStores
- .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
+ var configurationInfo = Array.Find(
+ configurationManager._configurationStores,
+ i => string.Equals(i.Key, k, StringComparison.OrdinalIgnoreCase));
- if (configurationInfo == null)
- {
- throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
- }
+ if (configurationInfo == null)
+ {
+ throw new ResourceNotFoundException("Configuration with key " + k + " not found.");
+ }
- var configurationType = configurationInfo.ConfigurationType;
+ var configurationType = configurationInfo.ConfigurationType;
- lock (_configurationSyncLock)
- {
- return LoadConfiguration(file, configurationType);
- }
- });
+ lock (configurationManager._configurationSyncLock)
+ {
+ return configurationManager.LoadConfiguration(file, configurationType);
+ }
+ },
+ this);
}
private object LoadConfiguration(string path, Type configurationType)
@@ -273,12 +341,13 @@ namespace Emby.Server.Implementations.AppBase
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error loading configuration file: {path}", path);
+ Logger.LogError(ex, "Error loading configuration file: {Path}", path);
return Activator.CreateInstance(configurationType);
}
}
+ /// <inheritdoc />
public void SaveConfiguration(string key, object configuration)
{
var configurationStore = GetConfigurationStore(key);
@@ -289,8 +358,7 @@ namespace Emby.Server.Implementations.AppBase
throw new ArgumentException("Expected configuration type is " + configurationType.Name);
}
- var validatingStore = configurationStore as IValidatingConfiguration;
- if (validatingStore != null)
+ if (configurationStore is IValidatingConfiguration validatingStore)
{
var currentConfiguration = GetConfiguration(key);
@@ -316,6 +384,11 @@ namespace Emby.Server.Implementations.AppBase
OnNamedConfigurationUpdated(key, configuration);
}
+ /// <summary>
+ /// Event handler for when a named configuration has been updated.
+ /// </summary>
+ /// <param name="key">The key of the configuration.</param>
+ /// <param name="configuration">The old configuration.</param>
protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
{
NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
@@ -325,6 +398,7 @@ namespace Emby.Server.Implementations.AppBase
});
}
+ /// <inheritdoc />
public Type GetConfigurationType(string key)
{
return GetConfigurationStore(key)
diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
index 90b97061f..3a916e5c0 100644
--- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
+++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
@@ -6,13 +6,13 @@ using MediaBrowser.Model.Serialization;
namespace Emby.Server.Implementations.AppBase
{
/// <summary>
- /// Class ConfigurationHelper
+ /// Class ConfigurationHelper.
/// </summary>
public static class ConfigurationHelper
{
/// <summary>
/// Reads an xml configuration file from the file system
- /// It will immediately re-serialize and save if new serialization data is available due to property changes
+ /// It will immediately re-serialize and save if new serialization data is available due to property changes.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="path">The path.</param>
@@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.AppBase
{
object configuration;
- byte[] buffer = null;
+ byte[]? buffer = null;
// Use try/catch to avoid the extra file system lookup using File.Exists
try
@@ -33,27 +33,31 @@ namespace Emby.Server.Implementations.AppBase
}
catch (Exception)
{
- configuration = Activator.CreateInstance(type);
+ // Note: CreateInstance returns null for Nullable<T>, e.g. CreateInstance(typeof(int?)) returns null.
+ configuration = Activator.CreateInstance(type)!;
}
- using (var stream = new MemoryStream())
+ using var stream = new MemoryStream(buffer?.Length ?? 0);
+ xmlSerializer.SerializeToStream(configuration, stream);
+
+ // Take the object we just got and serialize it back to bytes
+ Span<byte> newBytes = stream.GetBuffer().AsSpan(0, (int)stream.Length);
+
+ // If the file didn't exist before, or if something has changed, re-save
+ if (buffer == null || !newBytes.SequenceEqual(buffer))
{
- xmlSerializer.SerializeToStream(configuration, stream);
+ var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
- // Take the object we just got and serialize it back to bytes
- var newBytes = stream.ToArray();
+ Directory.CreateDirectory(directory);
- // If the file didn't exist before, or if something has changed, re-save
- if (buffer == null || !buffer.SequenceEqual(newBytes))
+ // Save it after load in case we got new items
+ using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- // Save it after load in case we got new items
- File.WriteAllBytes(path, newBytes);
+ fs.Write(newBytes);
}
-
- return configuration;
}
+
+ return configuration;
}
}
}
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index 042b04b3b..6fd152a42 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -1,5 +1,8 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -9,7 +12,6 @@ using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
-using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Emby.Dlna;
@@ -18,7 +20,6 @@ using Emby.Dlna.Ssdp;
using Emby.Drawing;
using Emby.Notifications;
using Emby.Photos;
-using Emby.Server.Implementations.Activity;
using Emby.Server.Implementations.Archiving;
using Emby.Server.Implementations.Channels;
using Emby.Server.Implementations.Collections;
@@ -26,10 +27,7 @@ using Emby.Server.Implementations.Configuration;
using Emby.Server.Implementations.Cryptography;
using Emby.Server.Implementations.Data;
using Emby.Server.Implementations.Devices;
-using Emby.Server.Implementations.Diagnostics;
using Emby.Server.Implementations.Dto;
-using Emby.Server.Implementations.FFMpeg;
-using Emby.Server.Implementations.HttpServer;
using Emby.Server.Implementations.HttpServer.Security;
using Emby.Server.Implementations.IO;
using Emby.Server.Implementations.Library;
@@ -37,29 +35,29 @@ using Emby.Server.Implementations.LiveTv;
using Emby.Server.Implementations.Localization;
using Emby.Server.Implementations.Net;
using Emby.Server.Implementations.Playlists;
-using Emby.Server.Implementations.Reflection;
+using Emby.Server.Implementations.Plugins;
+using Emby.Server.Implementations.QuickConnect;
using Emby.Server.Implementations.ScheduledTasks;
-using Emby.Server.Implementations.Security;
using Emby.Server.Implementations.Serialization;
using Emby.Server.Implementations.Session;
+using Emby.Server.Implementations.SyncPlay;
using Emby.Server.Implementations.TV;
+using Emby.Server.Implementations.Udp;
using Emby.Server.Implementations.Updates;
-using Emby.Server.Implementations.Xml;
-using MediaBrowser.Api;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller;
-using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
@@ -73,56 +71,127 @@ using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
+using MediaBrowser.Controller.QuickConnect;
using MediaBrowser.Controller.Resolvers;
-using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Controller.Subtitles;
+using MediaBrowser.Controller.SyncPlay;
using MediaBrowser.Controller.TV;
using MediaBrowser.LocalMetadata.Savers;
using MediaBrowser.MediaEncoding.BdInfo;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Reflection;
using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
-using MediaBrowser.Model.Updates;
-using MediaBrowser.Model.Xml;
using MediaBrowser.Providers.Chapters;
using MediaBrowser.Providers.Manager;
+using MediaBrowser.Providers.Plugins.Tmdb;
using MediaBrowser.Providers.Subtitles;
-using MediaBrowser.Providers.TV.TheTVDB;
-using MediaBrowser.WebDashboard.Api;
using MediaBrowser.XbmcMetadata.Providers;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
-using ServiceStack;
-using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
+using Microsoft.Extensions.Logging;
+using Prometheus.DotNetRuntime;
+using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
namespace Emby.Server.Implementations
{
/// <summary>
- /// Class CompositionRoot
+ /// Class CompositionRoot.
/// </summary>
public abstract class ApplicationHost : IServerApplicationHost, IDisposable
{
/// <summary>
+ /// The environment variable prefixes to log at server startup.
+ /// </summary>
+ private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
+
+ /// <summary>
+ /// The disposable parts.
+ /// </summary>
+ private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
+
+ private readonly IFileSystem _fileSystemManager;
+ private readonly IConfiguration _startupConfig;
+ private readonly IXmlSerializer _xmlSerializer;
+ private readonly IStartupOptions _startupOptions;
+ private readonly IPluginManager _pluginManager;
+
+ private List<Type> _creatingInstances;
+ private IMediaEncoder _mediaEncoder;
+ private ISessionManager _sessionManager;
+ private string[] _urlPrefixes;
+
+ /// <summary>
+ /// Gets or sets all concrete types.
+ /// </summary>
+ /// <value>All concrete types.</value>
+ private Type[] _allConcreteTypes;
+
+ private DeviceId _deviceId;
+
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
+ /// </summary>
+ /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
+ /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
+ public ApplicationHost(
+ IServerApplicationPaths applicationPaths,
+ ILoggerFactory loggerFactory,
+ IStartupOptions options,
+ IConfiguration startupConfig,
+ IFileSystem fileSystem,
+ IServiceCollection serviceCollection)
+ {
+ ApplicationPaths = applicationPaths;
+ LoggerFactory = loggerFactory;
+ _startupOptions = options;
+ _startupConfig = startupConfig;
+ _fileSystemManager = fileSystem;
+ ServiceCollection = serviceCollection;
+
+ Logger = LoggerFactory.CreateLogger<ApplicationHost>();
+ fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
+
+ ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
+ ApplicationVersionString = ApplicationVersion.ToString(3);
+ ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
+
+ _xmlSerializer = new MyXmlSerializer();
+ ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
+ _pluginManager = new PluginManager(
+ LoggerFactory.CreateLogger<PluginManager>(),
+ this,
+ ConfigurationManager.Configuration,
+ ApplicationPaths.PluginsPath,
+ ApplicationVersion);
+ }
+
+ /// <summary>
+ /// Occurs when [has pending restart changed].
+ /// </summary>
+ public event EventHandler HasPendingRestartChanged;
+
+ /// <summary>
/// Gets a value indicating whether this instance can self restart.
/// </summary>
- /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
- public abstract bool CanSelfRestart { get; }
+ public bool CanSelfRestart => _startupOptions.RestartPath != null;
+
+ public bool CoreStartupHasCompleted { get; private set; }
public virtual bool CanLaunchWebBrowser
{
@@ -133,255 +202,136 @@ namespace Emby.Server.Implementations
return false;
}
- if (StartupOptions.IsService)
+ if (_startupOptions.IsService)
{
return false;
}
- if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
- {
- return true;
- }
-
- if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
- {
- return true;
- }
-
- return false;
+ return OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
}
}
/// <summary>
- /// Occurs when [has pending restart changed].
- /// </summary>
- public event EventHandler HasPendingRestartChanged;
-
- /// <summary>
- /// Occurs when [application updated].
+ /// Gets the <see cref="INetworkManager"/> singleton instance.
/// </summary>
- public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
+ public INetworkManager NetManager { get; internal set; }
/// <summary>
- /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
+ /// Gets a value indicating whether this instance has changes that require the entire application to restart.
/// </summary>
/// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
public bool HasPendingRestart { get; private set; }
+ /// <inheritdoc />
public bool IsShuttingDown { get; private set; }
/// <summary>
- /// Gets or sets the logger.
+ /// Gets the logger.
/// </summary>
- /// <value>The logger.</value>
- protected ILogger Logger { get; set; }
+ protected ILogger<ApplicationHost> Logger { get; }
- /// <summary>
- /// Gets or sets the plugins.
- /// </summary>
- /// <value>The plugins.</value>
- public IPlugin[] Plugins { get; protected set; }
+ protected IServiceCollection ServiceCollection { get; }
/// <summary>
- /// Gets or sets the logger factory.
+ /// Gets the logger factory.
/// </summary>
- /// <value>The logger factory.</value>
- public ILoggerFactory LoggerFactory { get; protected set; }
+ protected ILoggerFactory LoggerFactory { get; }
/// <summary>
- /// Gets the application paths.
+ /// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
- protected ServerApplicationPaths ApplicationPaths { get; set; }
-
- /// <summary>
- /// Gets all concrete types.
- /// </summary>
- /// <value>All concrete types.</value>
- public Type[] AllConcreteTypes { get; protected set; }
-
- /// <summary>
- /// The disposable parts
- /// </summary>
- protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
+ protected IServerApplicationPaths ApplicationPaths { get; set; }
/// <summary>
- /// Gets the configuration manager.
+ /// Gets or sets the configuration manager.
/// </summary>
/// <value>The configuration manager.</value>
- protected IConfigurationManager ConfigurationManager { get; set; }
-
- public IFileSystem FileSystemManager { get; set; }
-
- protected IEnvironmentInfo EnvironmentInfo { get; set; }
-
- public PackageVersionClass SystemUpdateLevel
- {
- get
- {
-#if BETA
- return PackageVersionClass.Beta;
-#endif
- return PackageVersionClass.Release;
- }
- }
-
- protected IServiceProvider _serviceProvider;
+ public ServerConfigurationManager ConfigurationManager { get; set; }
/// <summary>
- /// Gets the server configuration manager.
+ /// Gets or sets the service provider.
/// </summary>
- /// <value>The server configuration manager.</value>
- public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
+ public IServiceProvider ServiceProvider { get; set; }
/// <summary>
- /// Gets the configuration manager.
+ /// Gets the http port for the webhost.
/// </summary>
- /// <returns>IConfigurationManager.</returns>
- protected IConfigurationManager GetConfigurationManager()
- {
- return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
- }
-
- protected virtual IResourceFileManager CreateResourceFileManager()
- {
- return new ResourceFileManager(HttpResultFactory, LoggerFactory, FileSystemManager);
- }
+ public int HttpPort { get; private set; }
/// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- public IUserManager UserManager { get; set; }
- /// <summary>
- /// Gets or sets the library manager.
+ /// Gets the https port for the webhost.
/// </summary>
- /// <value>The library manager.</value>
- internal ILibraryManager LibraryManager { get; set; }
- /// <summary>
- /// Gets or sets the directory watchers.
- /// </summary>
- /// <value>The directory watchers.</value>
- private ILibraryMonitor LibraryMonitor { get; set; }
- /// <summary>
- /// Gets or sets the provider manager.
- /// </summary>
- /// <value>The provider manager.</value>
- private IProviderManager ProviderManager { get; set; }
- /// <summary>
- /// Gets or sets the HTTP server.
- /// </summary>
- /// <value>The HTTP server.</value>
- private IHttpServer HttpServer { get; set; }
- private IDtoService DtoService { get; set; }
- public IImageProcessor ImageProcessor { get; set; }
+ public int HttpsPort { get; private set; }
/// <summary>
- /// Gets or sets the media encoder.
+ /// Gets the value of the PublishedServerUrl setting.
/// </summary>
- /// <value>The media encoder.</value>
- private IMediaEncoder MediaEncoder { get; set; }
- private ISubtitleEncoder SubtitleEncoder { get; set; }
-
- private ISessionManager SessionManager { get; set; }
+ public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey];
- private ILiveTvManager LiveTvManager { get; set; }
+ /// <inheritdoc />
+ public Version ApplicationVersion { get; }
- public LocalizationManager LocalizationManager { get; set; }
-
- private IEncodingManager EncodingManager { get; set; }
- private IChannelManager ChannelManager { get; set; }
+ /// <inheritdoc />
+ public string ApplicationVersionString { get; }
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets the current application user agent.
/// </summary>
- /// <value>The user data repository.</value>
- private IUserDataManager UserDataManager { get; set; }
- private IUserRepository UserRepository { get; set; }
- internal SqliteItemRepository ItemRepository { get; set; }
-
- private INotificationManager NotificationManager { get; set; }
- private ISubtitleManager SubtitleManager { get; set; }
- private IChapterManager ChapterManager { get; set; }
- private IDeviceManager DeviceManager { get; set; }
-
- internal IUserViewManager UserViewManager { get; set; }
-
- private IAuthenticationRepository AuthenticationRepository { get; set; }
- private ITVSeriesManager TVSeriesManager { get; set; }
- private ICollectionManager CollectionManager { get; set; }
- private IMediaSourceManager MediaSourceManager { get; set; }
- private IPlaylistManager PlaylistManager { get; set; }
-
- private readonly IConfiguration _configuration;
+ /// <value>The application user agent.</value>
+ public string ApplicationUserAgent { get; }
/// <summary>
- /// Gets or sets the installation manager.
+ /// Gets the email address for use within a comment section of a user agent field.
+ /// Presently used to provide contact information to MusicBrainz service.
/// </summary>
- /// <value>The installation manager.</value>
- protected IInstallationManager InstallationManager { get; private set; }
+ public string ApplicationUserAgentAddress => "team@jellyfin.org";
/// <summary>
- /// Gets or sets the zip client.
+ /// Gets the current application name.
/// </summary>
- /// <value>The zip client.</value>
- protected IZipClient ZipClient { get; private set; }
- protected IHttpResultFactory HttpResultFactory { get; private set; }
- protected IAuthService AuthService { get; private set; }
-
- public IStartupOptions StartupOptions { get; private set; }
-
- internal IImageEncoder ImageEncoder { get; private set; }
-
- protected IProcessFactory ProcessFactory { get; private set; }
- protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
- protected readonly IXmlSerializer XmlSerializer;
-
- protected ISocketFactory SocketFactory { get; private set; }
- protected ITaskManager TaskManager { get; private set; }
- public IHttpClient HttpClient { get; private set; }
- protected INetworkManager NetworkManager { get; set; }
- public IJsonSerializer JsonSerializer { get; private set; }
- protected IIsoManager IsoManager { get; private set; }
+ /// <value>The application name.</value>
+ public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
- /// <summary>
- /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
- /// </summary>
- public ApplicationHost(ServerApplicationPaths applicationPaths,
- ILoggerFactory loggerFactory,
- IStartupOptions options,
- IFileSystem fileSystem,
- IEnvironmentInfo environmentInfo,
- IImageEncoder imageEncoder,
- INetworkManager networkManager,
- IConfiguration configuration)
+ public string SystemId
{
- _configuration = configuration;
-
- // hack alert, until common can target .net core
- BaseExtensions.CryptographyProvider = CryptographyProvider;
-
- XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
-
- NetworkManager = networkManager;
- networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
- EnvironmentInfo = environmentInfo;
+ get
+ {
+ _deviceId ??= new DeviceId(ApplicationPaths, LoggerFactory);
- ApplicationPaths = applicationPaths;
- LoggerFactory = loggerFactory;
- FileSystemManager = fileSystem;
+ return _deviceId.Value;
+ }
+ }
- ConfigurationManager = GetConfigurationManager();
+ /// <inheritdoc/>
+ public string Name => ApplicationProductName;
- Logger = LoggerFactory.CreateLogger("App");
+ private string CertificatePath { get; set; }
- StartupOptions = options;
+ public X509Certificate2 Certificate { get; private set; }
- ImageEncoder = imageEncoder;
+ /// <inheritdoc/>
+ public bool ListenWithHttps => Certificate != null && ConfigurationManager.GetNetworkConfiguration().EnableHttps;
- fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
+ public string FriendlyName =>
+ string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
+ ? Environment.MachineName
+ : ConfigurationManager.Configuration.ServerName;
- NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
+ /// <summary>
+ /// Temporary function to migration network settings out of system.xml and into network.xml.
+ /// TODO: remove at the point when a fixed migration path has been decided upon.
+ /// </summary>
+ private void MigrateNetworkConfiguration()
+ {
+ string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
+ if (!File.Exists(path))
+ {
+ var networkSettings = new NetworkConfiguration();
+ ClassMigrationHelper.CopyProperties(ConfigurationManager.Configuration, networkSettings);
+ _xmlSerializer.SerializeToFile(networkSettings, path);
+ Logger.LogDebug("Successfully migrated network settings.");
+ }
}
public string ExpandVirtualPath(string path)
@@ -400,124 +350,114 @@ namespace Emby.Server.Implementations
.Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
}
- private string[] GetConfiguredLocalSubnets()
- {
- return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
- }
-
- private void NetworkManager_NetworkChanged(object sender, EventArgs e)
- {
- _validAddressResults.Clear();
- }
-
- public string ApplicationVersion => typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
-
- /// <summary>
- /// Gets the current application user agent
- /// </summary>
- /// <value>The application user agent.</value>
- public string ApplicationUserAgent => Name.Replace(' ','-') + "/" + ApplicationVersion;
-
- private string _productName;
- /// <summary>
- /// Gets the current application name
- /// </summary>
- /// <value>The application name.</value>
- public string ApplicationProductName => _productName ?? (_productName = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName);
-
- private DeviceId _deviceId;
- public string SystemId
- {
- get
- {
- if (_deviceId == null)
- {
- _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
- }
-
- return _deviceId.Value;
- }
- }
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ApplicationProductName;
-
/// <summary>
- /// Creates an instance of type and resolves all constructor dependencies
+ /// Creates an instance of type and resolves all constructor dependencies.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.Object.</returns>
public object CreateInstance(Type type)
- => ActivatorUtilities.CreateInstance(_serviceProvider, type);
+ => ActivatorUtilities.CreateInstance(ServiceProvider, type);
/// <summary>
- /// Creates an instance of type and resolves all constructor dependencies
+ /// Creates an instance of type and resolves all constructor dependencies.
/// </summary>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
+ /// <typeparam name="T">The type.</typeparam>
+ /// <returns>T.</returns>
public T CreateInstance<T>()
- => ActivatorUtilities.CreateInstance<T>(_serviceProvider);
+ => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
/// <summary>
/// Creates the instance safe.
/// </summary>
- /// <param name="typeInfo">The type information.</param>
+ /// <param name="type">The type.</param>
/// <returns>System.Object.</returns>
protected object CreateInstanceSafe(Type type)
{
+ _creatingInstances ??= new List<Type>();
+
+ if (_creatingInstances.IndexOf(type) != -1)
+ {
+ Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
+ foreach (var entry in _creatingInstances)
+ {
+ Logger.LogError("Called from: {TypeName}", entry.FullName);
+ }
+
+ _pluginManager.FailPlugin(type.Assembly);
+
+ throw new ExternalException("DI Loop detected.");
+ }
+
try
{
+ _creatingInstances.Add(type);
Logger.LogDebug("Creating instance of {Type}", type);
- return ActivatorUtilities.CreateInstance(_serviceProvider, type);
+ return ActivatorUtilities.CreateInstance(ServiceProvider, type);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error creating {Type}", type);
+ // If this is a plugin fail it.
+ _pluginManager.FailPlugin(type.Assembly);
return null;
}
+ finally
+ {
+ _creatingInstances.Remove(type);
+ }
}
/// <summary>
/// Resolves this instance.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type.</typeparam>
/// <returns>``0.</returns>
- public T Resolve<T>() => _serviceProvider.GetService<T>();
+ public T Resolve<T>() => ServiceProvider.GetService<T>();
- /// <summary>
- /// Gets the export types.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns>IEnumerable{Type}.</returns>
+ /// <inheritdoc/>
public IEnumerable<Type> GetExportTypes<T>()
{
var currentType = typeof(T);
- return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
+ return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
}
- /// <summary>
- /// Gets the exports.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
- /// <returns>IEnumerable{``0}.</returns>
- public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
+ /// <inheritdoc />
+ public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
{
+ // Convert to list so this isn't executed for each iteration
var parts = GetExportTypes<T>()
- .Select(x => CreateInstanceSafe(x))
+ .Select(CreateInstanceSafe)
.Where(i => i != null)
.Cast<T>()
- .ToList(); // Convert to list so this isn't executed for each iteration
+ .ToList();
if (manageLifetime)
{
- lock (DisposableParts)
+ lock (_disposableParts)
{
- DisposableParts.AddRange(parts.OfType<IDisposable>());
+ _disposableParts.AddRange(parts.OfType<IDisposable>());
+ }
+ }
+
+ return parts;
+ }
+
+ /// <inheritdoc />
+ public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
+ {
+ // Convert to list so this isn't executed for each iteration
+ var parts = GetExportTypes<T>()
+ .Select(i => defaultFunc(i))
+ .Where(i => i != null)
+ .Cast<T>()
+ .ToList();
+
+ if (manageLifetime)
+ {
+ lock (_disposableParts)
+ {
+ _disposableParts.AddRange(parts.OfType<IDisposable>());
}
}
@@ -527,39 +467,42 @@ namespace Emby.Server.Implementations
/// <summary>
/// Runs the startup tasks.
/// </summary>
- public async Task RunStartupTasks()
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns><see cref="Task" />.</returns>
+ public async Task RunStartupTasksAsync(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
Logger.LogInformation("Running startup tasks");
Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
+ ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
- MediaEncoder.Init();
-
- //if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
- //{
- // if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
- // {
- // ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
- // ServerConfigurationManager.SaveConfiguration();
- // }
- //}
+ _mediaEncoder.SetFFmpegPath();
- Logger.LogInformation("ServerId: {0}", SystemId);
+ Logger.LogInformation("ServerId: {ServerId}", SystemId);
var entryPoints = GetExports<IServerEntryPoint>();
- var now = DateTime.UtcNow;
- await Task.WhenAll(StartEntryPoints(entryPoints, true));
- Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:fff} ms", DateTime.Now - now);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var stopWatch = new Stopwatch();
+ stopWatch.Start();
+
+ await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
+ Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
Logger.LogInformation("Core startup complete");
- HttpServer.GlobalResponse = null;
+ CoreStartupHasCompleted = true;
+
+ cancellationToken.ThrowIfCancellationRequested();
- now = DateTime.UtcNow;
- await Task.WhenAll(StartEntryPoints(entryPoints, false));
- Logger.LogInformation("Executed all post-startup entry points in {Elapsed:fff} ms", DateTime.Now - now);
+ stopWatch.Restart();
+
+ await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
+ Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
+ stopWatch.Stop();
}
private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
@@ -577,318 +520,232 @@ namespace Emby.Server.Implementations
}
}
- public async Task Init(IServiceCollection serviceCollection)
+ /// <inheritdoc/>
+ public void Init()
{
- HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
- HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
+ DiscoverTypes();
- // Safeguard against invalid configuration
- if (HttpPort == HttpsPort)
- {
- HttpPort = ServerConfiguration.DefaultHttpPort;
- HttpsPort = ServerConfiguration.DefaultHttpsPort;
- }
+ ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
- JsonSerializer = new JsonSerializer(FileSystemManager);
+ // Have to migrate settings here as migration subsystem not yet initialised.
+ MigrateNetworkConfiguration();
+ NetManager = new NetworkManager(ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
- if (Plugins != null)
+ // Initialize runtime stat collection
+ if (ConfigurationManager.Configuration.EnableMetrics)
{
- var pluginBuilder = new StringBuilder();
-
- foreach (var plugin in Plugins)
- {
- pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
- }
-
- Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
+ DotNetRuntimeStatsBuilder.Default().StartCollecting();
}
- DiscoverTypes();
+ var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
+ HttpPort = networkConfiguration.HttpServerPortNumber;
+ HttpsPort = networkConfiguration.HttpsPortNumber;
- SetHttpLimit();
+ // Safeguard against invalid configuration
+ if (HttpPort == HttpsPort)
+ {
+ HttpPort = NetworkConfiguration.DefaultHttpPort;
+ HttpsPort = NetworkConfiguration.DefaultHttpsPort;
+ }
- await RegisterResources(serviceCollection);
+ CertificatePath = networkConfiguration.CertificatePath;
+ Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
- FindParts();
- }
+ RegisterServices();
- protected virtual IHttpClient CreateHttpClient()
- {
- return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory, FileSystemManager, () => ApplicationUserAgent);
+ _pluginManager.RegisterServices(ServiceCollection);
}
- public static IStreamHelper StreamHelper { get; set; }
-
/// <summary>
- /// Registers resources that classes will depend on
+ /// Registers services/resources with the service collection that will be available via DI.
/// </summary>
- protected async Task RegisterResources(IServiceCollection serviceCollection)
+ protected virtual void RegisterServices()
{
- serviceCollection.AddMemoryCache();
-
- serviceCollection.AddSingleton(ConfigurationManager);
- serviceCollection.AddSingleton<IApplicationHost>(this);
-
- serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
-
- serviceCollection.AddSingleton(JsonSerializer);
-
- serviceCollection.AddSingleton(LoggerFactory);
- serviceCollection.AddLogging();
- serviceCollection.AddSingleton(Logger);
-
- serviceCollection.AddSingleton(EnvironmentInfo);
-
- serviceCollection.AddSingleton(FileSystemManager);
- serviceCollection.AddSingleton<TvDbClientManager>();
-
- HttpClient = CreateHttpClient();
- serviceCollection.AddSingleton(HttpClient);
-
- serviceCollection.AddSingleton(NetworkManager);
-
- IsoManager = new IsoManager();
- serviceCollection.AddSingleton(IsoManager);
-
- TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
- serviceCollection.AddSingleton(TaskManager);
-
- serviceCollection.AddSingleton(XmlSerializer);
+ ServiceCollection.AddSingleton(_startupOptions);
- ProcessFactory = new ProcessFactory();
- serviceCollection.AddSingleton(ProcessFactory);
+ ServiceCollection.AddMemoryCache();
- ApplicationHost.StreamHelper = new StreamHelper();
- serviceCollection.AddSingleton(StreamHelper);
+ ServiceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
+ ServiceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
+ ServiceCollection.AddSingleton<IApplicationHost>(this);
+ ServiceCollection.AddSingleton<IPluginManager>(_pluginManager);
+ ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
- serviceCollection.AddSingleton(CryptographyProvider);
+ ServiceCollection.AddSingleton(_fileSystemManager);
+ ServiceCollection.AddSingleton<TmdbClientManager>();
- SocketFactory = new SocketFactory();
- serviceCollection.AddSingleton(SocketFactory);
+ ServiceCollection.AddSingleton(NetManager);
- InstallationManager = new InstallationManager(LoggerFactory, this, ApplicationPaths, HttpClient, JsonSerializer, ServerConfigurationManager, FileSystemManager, CryptographyProvider, ZipClient, PackageRuntime);
- serviceCollection.AddSingleton(InstallationManager);
+ ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
- ZipClient = new ZipClient();
- serviceCollection.AddSingleton(ZipClient);
+ ServiceCollection.AddSingleton(_xmlSerializer);
- HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
- serviceCollection.AddSingleton(HttpResultFactory);
+ ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
- serviceCollection.AddSingleton<IServerApplicationHost>(this);
- serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
+ ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
- serviceCollection.AddSingleton(ServerConfigurationManager);
+ ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
- var assemblyInfo = new AssemblyInfo();
- serviceCollection.AddSingleton<IAssemblyInfo>(assemblyInfo);
+ ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
- LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory);
- await LocalizationManager.LoadAll();
- serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
+ ServiceCollection.AddSingleton<IZipClient, ZipClient>();
- serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
+ ServiceCollection.AddSingleton<IServerApplicationHost>(this);
+ ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
- serviceCollection.AddSingleton<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
+ ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
- UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
- serviceCollection.AddSingleton(UserDataManager);
+ ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
- UserRepository = GetUserRepository();
- // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
- serviceCollection.AddSingleton(UserRepository);
+ ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
+ ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
- var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
- serviceCollection.AddSingleton<IDisplayPreferencesRepository>(displayPreferencesRepo);
+ ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
- ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, assemblyInfo);
- serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
+ ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
+ ServiceCollection.AddSingleton<EncodingHelper>();
- AuthenticationRepository = GetAuthenticationRepository();
- serviceCollection.AddSingleton(AuthenticationRepository);
+ // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
+ ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
+ ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
+ ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
+ ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
- UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
- serviceCollection.AddSingleton(UserManager);
+ ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
- LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
- serviceCollection.AddSingleton(LibraryManager);
+ ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
- // TODO wtaylor: investigate use of second music manager
- var musicManager = new MusicManager(LibraryManager);
- serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
+ ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
- LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager, EnvironmentInfo);
- serviceCollection.AddSingleton(LibraryMonitor);
+ ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
- serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
+ ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
- CertificateInfo = GetCertificateInfo(true);
- Certificate = GetCertificate(CertificateInfo);
+ ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
- HttpServer = new HttpListenerHost(this,
- LoggerFactory,
- ServerConfigurationManager,
- _configuration,
- NetworkManager,
- JsonSerializer,
- XmlSerializer);
+ ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
- HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
- serviceCollection.AddSingleton(HttpServer);
+ ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
- ImageProcessor = GetImageProcessor();
- serviceCollection.AddSingleton(ImageProcessor);
+ ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
- TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
- serviceCollection.AddSingleton(TVSeriesManager);
+ // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
+ ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
+ ServiceCollection.AddSingleton<IDtoService, DtoService>();
- var encryptionManager = new EncryptionManager();
- serviceCollection.AddSingleton<IEncryptionManager>(encryptionManager);
+ ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
- DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
- serviceCollection.AddSingleton(DeviceManager);
+ ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
- MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
- serviceCollection.AddSingleton(MediaSourceManager);
+ ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
- SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
- serviceCollection.AddSingleton(SubtitleManager);
+ ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
- ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
- serviceCollection.AddSingleton(ProviderManager);
+ ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
- DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
- serviceCollection.AddSingleton(DtoService);
+ ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
- ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
- serviceCollection.AddSingleton(ChannelManager);
+ ServiceCollection.AddSingleton<LiveTvDtoService>();
+ ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
- SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager);
- serviceCollection.AddSingleton(SessionManager);
+ ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
- serviceCollection.AddSingleton<IDlnaManager>(
- new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this, assemblyInfo));
+ ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
- CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
- serviceCollection.AddSingleton(CollectionManager);
+ ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
- PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
- serviceCollection.AddSingleton(PlaylistManager);
+ ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
- LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
- serviceCollection.AddSingleton(LiveTvManager);
+ ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
- UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
- serviceCollection.AddSingleton(UserViewManager);
+ ServiceCollection.AddScoped<ISessionContext, SessionContext>();
- NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
- serviceCollection.AddSingleton(NotificationManager);
+ ServiceCollection.AddSingleton<IAuthService, AuthService>();
+ ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
- serviceCollection.AddSingleton<IDeviceDiscovery>(
- new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
+ ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
- ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
- serviceCollection.AddSingleton(ChapterManager);
+ ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
- RegisterMediaEncoder(serviceCollection);
+ ServiceCollection.AddSingleton<TranscodingJobHelper>();
+ ServiceCollection.AddScoped<MediaInfoHelper>();
+ ServiceCollection.AddScoped<AudioHelper>();
+ ServiceCollection.AddScoped<DynamicHlsHelper>();
- EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
- serviceCollection.AddSingleton(EncodingManager);
-
- var activityLogRepo = GetActivityLogRepository();
- serviceCollection.AddSingleton(activityLogRepo);
- serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
-
- var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
- serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
- serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
-
- AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
- serviceCollection.AddSingleton(AuthService);
-
- SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
- serviceCollection.AddSingleton(SubtitleEncoder);
-
- serviceCollection.AddSingleton(CreateResourceFileManager());
+ ServiceCollection.AddSingleton<IDirectoryService, DirectoryService>();
+ }
- displayPreferencesRepo.Initialize();
+ /// <summary>
+ /// Create services registered with the service container that need to be initialized at application startup.
+ /// </summary>
+ /// <returns>A task representing the service initialization operation.</returns>
+ public async Task InitializeServices()
+ {
+ var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
+ await localizationManager.LoadAll().ConfigureAwait(false);
- var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
+ _mediaEncoder = Resolve<IMediaEncoder>();
+ _sessionManager = Resolve<ISessionManager>();
SetStaticProperties();
- ((UserManager)UserManager).Initialize();
+ var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
+ ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
- ((UserDataManager)UserDataManager).Repository = userDataRepo;
- ItemRepository.Initialize(userDataRepo, UserManager);
- ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
-
- _serviceProvider = serviceCollection.BuildServiceProvider();
- }
-
- protected virtual IBrotliCompressor CreateBrotliCompressor()
- {
- return null;
+ FindParts();
}
- public virtual string PackageRuntime => "netcore";
-
- public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
+ public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
{
// Distinct these to prevent users from reporting problems that aren't actually problems
var commandLineArgs = Environment
.GetCommandLineArgs()
.Distinct();
+ // Get all relevant environment variables
+ var allEnvVars = Environment.GetEnvironmentVariables();
+ var relevantEnvVars = new Dictionary<object, object>();
+ foreach (var key in allEnvVars.Keys)
+ {
+ if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
+ {
+ relevantEnvVars.Add(key, allEnvVars[key]);
+ }
+ }
+
+ logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
logger.LogInformation("Arguments: {Args}", commandLineArgs);
- logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
- logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
+ logger.LogInformation("Operating system: {OS}", MediaBrowser.Common.System.OperatingSystem.Name);
+ logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
+ logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
}
- private void SetHttpLimit()
+ private X509Certificate2 GetCertificate(string path, string password)
{
- try
- {
- // Increase the max http request limit
- ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error setting http limit");
- }
- }
-
- protected virtual bool SupportsDualModeSockets => true;
-
- private X509Certificate GetCertificate(CertificateInfo info)
- {
- var certificateLocation = info == null ? null : info.Path;
-
- if (string.IsNullOrWhiteSpace(certificateLocation))
+ if (string.IsNullOrWhiteSpace(path))
{
return null;
}
try
{
- if (!File.Exists(certificateLocation))
+ if (!File.Exists(path))
{
return null;
}
// Don't use an empty string password
- var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
+ password = string.IsNullOrWhiteSpace(password) ? null : password;
- var localCert = new X509Certificate2(certificateLocation, password);
- //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
+ var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
if (!localCert.HasPrivateKey)
{
- Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
+ Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
return null;
}
@@ -896,269 +753,117 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
+ Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
return null;
}
}
- private IImageProcessor GetImageProcessor()
- {
- return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
- }
-
- protected virtual FFMpegInstallInfo GetFfmpegInstallInfo()
- {
- var info = new FFMpegInstallInfo();
-
- // Windows builds: http://ffmpeg.zeranoe.com/builds/
- // Linux builds: http://johnvansickle.com/ffmpeg/
- // OS X builds: http://ffmpegmac.net/
- // OS X x64: http://www.evermeet.cx/ffmpeg/
-
- if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux)
- {
- info.FFMpegFilename = "ffmpeg";
- info.FFProbeFilename = "ffprobe";
- info.ArchiveType = "7z";
- info.Version = "20170308";
- }
- else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
- {
- info.FFMpegFilename = "ffmpeg.exe";
- info.FFProbeFilename = "ffprobe.exe";
- info.Version = "20170308";
- info.ArchiveType = "7z";
- }
- else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
- {
- info.FFMpegFilename = "ffmpeg";
- info.FFProbeFilename = "ffprobe";
- info.ArchiveType = "7z";
- info.Version = "20170308";
- }
-
- return info;
- }
-
- protected virtual FFMpegInfo GetFFMpegInfo()
- {
- return new FFMpegLoader(ApplicationPaths, FileSystemManager, GetFfmpegInstallInfo())
- .GetFFMpegInfo(StartupOptions);
- }
-
/// <summary>
- /// Registers the media encoder.
- /// </summary>
- /// <returns>Task.</returns>
- private void RegisterMediaEncoder(IServiceCollection serviceCollection)
- {
- string encoderPath = null;
- string probePath = null;
-
- var info = GetFFMpegInfo();
-
- encoderPath = info.EncoderPath;
- probePath = info.ProbePath;
- var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
-
- var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
- LoggerFactory,
- JsonSerializer,
- encoderPath,
- probePath,
- hasExternalEncoder,
- ServerConfigurationManager,
- FileSystemManager,
- LiveTvManager,
- IsoManager,
- LibraryManager,
- ChannelManager,
- SessionManager,
- () => SubtitleEncoder,
- () => MediaSourceManager,
- HttpClient,
- ZipClient,
- ProcessFactory,
- 5000);
-
- MediaEncoder = mediaEncoder;
- serviceCollection.AddSingleton(MediaEncoder);
- }
-
- /// <summary>
- /// Gets the user repository.
- /// </summary>
- /// <returns>Task{IUserRepository}.</returns>
- private IUserRepository GetUserRepository()
- {
- var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
-
- repo.Initialize();
-
- return repo;
- }
-
- private IAuthenticationRepository GetAuthenticationRepository()
- {
- var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
-
- repo.Initialize();
-
- return repo;
- }
-
- private IActivityRepository GetActivityLogRepository()
- {
- var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
-
- repo.Initialize();
-
- return repo;
- }
-
- /// <summary>
- /// Dirty hacks
+ /// Dirty hacks.
/// </summary>
private void SetStaticProperties()
{
- ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor;
-
// For now there's no real way to inject these properly
- BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
- BaseItem.ConfigurationManager = ServerConfigurationManager;
- BaseItem.LibraryManager = LibraryManager;
- BaseItem.ProviderManager = ProviderManager;
- BaseItem.LocalizationManager = LocalizationManager;
- BaseItem.ItemRepository = ItemRepository;
- User.UserManager = UserManager;
- BaseItem.FileSystem = FileSystemManager;
- BaseItem.UserDataManager = UserDataManager;
- BaseItem.ChannelManager = ChannelManager;
- Video.LiveTvManager = LiveTvManager;
- Folder.UserViewManager = UserViewManager;
- UserView.TVSeriesManager = TVSeriesManager;
- UserView.PlaylistManager = PlaylistManager;
- UserView.CollectionManager = CollectionManager;
- BaseItem.MediaSourceManager = MediaSourceManager;
- CollectionFolder.XmlSerializer = XmlSerializer;
- CollectionFolder.JsonSerializer = JsonSerializer;
+ BaseItem.Logger = Resolve<ILogger<BaseItem>>();
+ BaseItem.ConfigurationManager = ConfigurationManager;
+ BaseItem.LibraryManager = Resolve<ILibraryManager>();
+ BaseItem.ProviderManager = Resolve<IProviderManager>();
+ BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
+ BaseItem.ItemRepository = Resolve<IItemRepository>();
+ BaseItem.FileSystem = _fileSystemManager;
+ BaseItem.UserDataManager = Resolve<IUserDataManager>();
+ BaseItem.ChannelManager = Resolve<IChannelManager>();
+ Video.LiveTvManager = Resolve<ILiveTvManager>();
+ Folder.UserViewManager = Resolve<IUserViewManager>();
+ UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
+ UserView.CollectionManager = Resolve<ICollectionManager>();
+ BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
+ CollectionFolder.XmlSerializer = _xmlSerializer;
CollectionFolder.ApplicationHost = this;
- AuthenticatedAttribute.AuthService = AuthService;
}
/// <summary>
- /// Finds the parts.
+ /// Finds plugin components and register them with the appropriate services.
/// </summary>
- protected void FindParts()
+ private void FindParts()
{
- if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
+ if (!ConfigurationManager.Configuration.IsPortAuthorized)
{
- ServerConfigurationManager.Configuration.IsPortAuthorized = true;
+ ConfigurationManager.Configuration.IsPortAuthorized = true;
ConfigurationManager.SaveConfiguration();
}
- ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
- Plugins = GetExports<IPlugin>()
- .Select(LoadPlugin)
- .Where(i => i != null)
- .ToArray();
-
- HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>());
+ _pluginManager.CreatePlugins();
- StartServer();
+ _urlPrefixes = GetUrlPrefixes().ToArray();
- LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
+ Resolve<ILibraryManager>().AddParts(
+ GetExports<IResolverIgnoreRule>(),
GetExports<IItemResolver>(),
GetExports<IIntroProvider>(),
GetExports<IBaseItemComparer>(),
GetExports<ILibraryPostScanTask>());
- ProviderManager.AddParts(GetExports<IImageProvider>(),
+ Resolve<IProviderManager>().AddParts(
+ GetExports<IImageProvider>(),
GetExports<IMetadataService>(),
GetExports<IMetadataProvider>(),
GetExports<IMetadataSaver>(),
GetExports<IExternalId>());
- ImageProcessor.AddParts(GetExports<IImageEnhancer>());
+ Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
- LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
+ Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
- SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
+ Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
- ChannelManager.AddParts(GetExports<IChannel>());
+ Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
- MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
+ Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
+ }
- NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
- UserManager.AddParts(GetExports<IAuthenticationProvider>());
+ /// <summary>
+ /// Discovers the types.
+ /// </summary>
+ protected void DiscoverTypes()
+ {
+ Logger.LogInformation("Loading assemblies");
- IsoManager.AddParts(GetExports<IIsoMounter>());
+ _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
}
- private IPlugin LoadPlugin(IPlugin plugin)
+ private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
{
- try
+ foreach (var ass in assemblies)
{
- if (plugin is IPluginAssembly assemblyPlugin)
+ Type[] exportedTypes;
+ try
{
- var assembly = plugin.GetType().Assembly;
- var assemblyName = assembly.GetName();
- var assemblyFilePath = assembly.Location;
-
- var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
-
- assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
-
- try
- {
- var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
- if (idAttributes.Length > 0)
- {
- var attribute = (GuidAttribute)idAttributes[0];
- var assemblyId = new Guid(attribute.Value);
-
- assemblyPlugin.SetId(assemblyId);
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
- }
+ exportedTypes = ass.GetExportedTypes();
}
-
- if (plugin is IHasPluginConfiguration hasPluginConfiguration)
+ catch (FileNotFoundException ex)
{
- hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
+ Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
+ _pluginManager.FailPlugin(ass);
+ continue;
+ }
+ catch (TypeLoadException ex)
+ {
+ Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
+ _pluginManager.FailPlugin(ass);
+ continue;
}
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
- return null;
- }
-
- return plugin;
- }
-
- /// <summary>
- /// Discovers the types.
- /// </summary>
- protected void DiscoverTypes()
- {
- Logger.LogInformation("Loading assemblies");
- AllConcreteTypes = GetComposablePartAssemblies()
- .SelectMany(x => x.ExportedTypes)
- .Where(type =>
+ foreach (Type type in exportedTypes)
{
- return type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType;
- })
- .ToArray();
+ if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
+ {
+ yield return type;
+ }
+ }
+ }
}
- private CertificateInfo CertificateInfo { get; set; }
- protected X509Certificate Certificate { get; private set; }
-
private IEnumerable<string> GetUrlPrefixes()
{
var hosts = new[] { "+" };
@@ -1167,10 +872,10 @@ namespace Emby.Server.Implementations
{
var prefixes = new List<string>
{
- "http://"+i+":" + HttpPort + "/"
+ "http://" + i + ":" + HttpPort + "/"
};
- if (CertificateInfo != null)
+ if (Certificate != null)
{
prefixes.Add("https://" + i + ":" + HttpsPort + "/");
}
@@ -1179,88 +884,6 @@ namespace Emby.Server.Implementations
});
}
- protected abstract IHttpListener CreateHttpListener();
-
- /// <summary>
- /// Starts the server.
- /// </summary>
- private void StartServer()
- {
- try
- {
- ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
- return;
- }
- catch (Exception ex)
- {
- var msg = string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase)
- ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system."
- : "Error starting Http Server";
-
- Logger.LogError(ex, msg);
-
- if (HttpPort == ServerConfiguration.DefaultHttpPort)
- {
- throw;
- }
- }
-
- HttpPort = ServerConfiguration.DefaultHttpPort;
-
- try
- {
- ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error starting http server");
-
- throw;
- }
- }
-
- private CertificateInfo GetCertificateInfo(bool generateCertificate)
- {
- if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
- {
- // Custom cert
- return new CertificateInfo
- {
- Path = ServerConfigurationManager.Configuration.CertificatePath,
- Password = ServerConfigurationManager.Configuration.CertificatePassword
- };
- }
-
- // Generate self-signed cert
- var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
- var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
- var password = "embycert";
-
- //if (generateCertificate)
- //{
- // if (!File.Exists(certPath))
- // {
- // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
-
- // try
- // {
- // CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, password, Logger);
- // }
- // catch (Exception ex)
- // {
- // Logger.LogError(ex, "Error creating ssl cert");
- // return null;
- // }
- // }
- //}
-
- return new CertificateInfo
- {
- Path = certPath,
- Password = password
- };
- }
-
/// <summary>
/// Called when [configuration updated].
/// </summary>
@@ -1269,34 +892,31 @@ namespace Emby.Server.Implementations
protected void OnConfigurationUpdated(object sender, EventArgs e)
{
var requiresRestart = false;
+ var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
// Don't do anything if these haven't been set yet
if (HttpPort != 0 && HttpsPort != 0)
{
// Need to restart if ports have changed
- if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
- ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
+ if (networkConfiguration.HttpServerPortNumber != HttpPort ||
+ networkConfiguration.HttpsPortNumber != HttpsPort)
{
- if (ServerConfigurationManager.Configuration.IsPortAuthorized)
+ if (ConfigurationManager.Configuration.IsPortAuthorized)
{
- ServerConfigurationManager.Configuration.IsPortAuthorized = false;
- ServerConfigurationManager.SaveConfiguration();
+ ConfigurationManager.Configuration.IsPortAuthorized = false;
+ ConfigurationManager.SaveConfiguration();
requiresRestart = true;
}
}
}
- if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
+ if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
{
requiresRestart = true;
}
- var currentCertPath = CertificateInfo == null ? null : CertificateInfo.Path;
- var newCertInfo = GetCertificateInfo(false);
- var newCertPath = newCertInfo == null ? null : newCertInfo.Path;
-
- if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
+ if (ValidateSslCertificate(networkConfiguration))
{
requiresRestart = true;
}
@@ -1310,7 +930,34 @@ namespace Emby.Server.Implementations
}
/// <summary>
- /// Notifies that the kernel that a change has been made that requires a restart
+ /// Validates the SSL certificate.
+ /// </summary>
+ /// <param name="networkConfig">The new configuration.</param>
+ /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
+ private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
+ {
+ var newPath = networkConfig.CertificatePath;
+
+ if (!string.IsNullOrWhiteSpace(newPath)
+ && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
+ {
+ if (File.Exists(newPath))
+ {
+ return true;
+ }
+
+ throw new FileNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Certificate file '{0}' does not exist.",
+ newPath));
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Notifies that the kernel that a change has been made that requires a restart.
/// </summary>
public void NotifyPendingRestart()
{
@@ -1347,7 +994,7 @@ namespace Emby.Server.Implementations
{
try
{
- await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -1368,21 +1015,11 @@ namespace Emby.Server.Implementations
/// <returns>IEnumerable{Assembly}.</returns>
protected IEnumerable<Assembly> GetComposablePartAssemblies()
{
- if (Directory.Exists(ApplicationPaths.PluginsPath))
+ foreach (var p in _pluginManager.LoadAssemblies())
{
- foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly))
- {
- Logger.LogInformation("Loading assembly {Path}", file);
- yield return Assembly.LoadFrom(file);
- }
+ yield return p;
}
- // Include composable parts in the Api assembly
- yield return typeof(ApiEntryPoint).Assembly;
-
- // Include composable parts in the Dashboard assembly
- yield return typeof(DashboardService).Assembly;
-
// Include composable parts in the Model assembly
yield return typeof(SystemInfo).Assembly;
@@ -1416,6 +1053,9 @@ namespace Emby.Server.Implementations
// Xbmc
yield return typeof(ArtistNfoProvider).Assembly;
+ // Network
+ yield return typeof(NetworkManager).Assembly;
+
foreach (var i in GetAssembliesWithPartsInternal())
{
yield return i;
@@ -1427,277 +1067,155 @@ namespace Emby.Server.Implementations
/// <summary>
/// Gets the system status.
/// </summary>
+ /// <param name="request">Where this request originated.</param>
/// <returns>SystemInfo.</returns>
- public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
+ public SystemInfo GetSystemInfo(HttpRequest request)
{
- var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
-
return new SystemInfo
{
HasPendingRestart = HasPendingRestart,
IsShuttingDown = IsShuttingDown,
- Version = ApplicationVersion,
- ProductName = ApplicationProductName,
+ Version = ApplicationVersionString,
WebSocketPortNumber = HttpPort,
- CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
+ CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
Id = SystemId,
ProgramDataPath = ApplicationPaths.ProgramDataPath,
+ WebPath = ApplicationPaths.WebPath,
LogPath = ApplicationPaths.LogDirectoryPath,
ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
CachePath = ApplicationPaths.CachePath,
- HttpServerPortNumber = HttpPort,
- SupportsHttps = SupportsHttps,
- HttpsPortNumber = HttpsPort,
- OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
- OperatingSystemDisplayName = EnvironmentInfo.OperatingSystemName,
+ OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
+ OperatingSystemDisplayName = MediaBrowser.Common.System.OperatingSystem.Name,
CanSelfRestart = CanSelfRestart,
CanLaunchWebBrowser = CanLaunchWebBrowser,
- WanAddress = wanAddress,
- HasUpdateAvailable = HasUpdateAvailable,
- TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
+ TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
ServerName = FriendlyName,
- LocalAddress = localAddress,
+ LocalAddress = GetSmartApiUrl(request),
SupportsLibraryMonitor = true,
- EncoderLocationType = MediaEncoder.EncoderLocationType,
- SystemArchitecture = EnvironmentInfo.SystemArchitecture,
- SystemUpdateLevel = SystemUpdateLevel,
- PackageName = StartupOptions.PackageName
+ SystemArchitecture = RuntimeInformation.OSArchitecture,
+ PackageName = _startupOptions.PackageName
};
}
- public WakeOnLanInfo[] GetWakeOnLanInfo()
- {
- return NetworkManager.GetMacAddresses()
- .Select(i => new WakeOnLanInfo
- {
- MacAddress = i
- })
- .ToArray();
- }
+ public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
+ => NetManager.GetMacAddresses()
+ .Select(i => new WakeOnLanInfo(i))
+ .ToList();
- public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
+ public PublicSystemInfo GetPublicSystemInfo(HttpRequest request)
{
- var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
return new PublicSystemInfo
{
- Version = ApplicationVersion,
+ Version = ApplicationVersionString,
+ ProductName = ApplicationProductName,
Id = SystemId,
- OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
- WanAddress = wanAddress,
+ OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
ServerName = FriendlyName,
- LocalAddress = localAddress
+ LocalAddress = GetSmartApiUrl(request),
+ StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
};
}
- public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
-
- public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
-
- public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public string GetSmartApiUrl(IPAddress remoteAddr, int? port = null)
{
- try
+ // Published server ends with a /
+ if (!string.IsNullOrEmpty(PublishedServerUrl))
{
- // Return the first matched address, if found, or the first known local address
- var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
-
- foreach (var address in addresses)
- {
- return GetLocalApiUrl(address);
- }
-
- return null;
+ // Published server ends with a '/', so we need to remove it.
+ return PublishedServerUrl.Trim('/');
}
- catch (Exception ex)
+
+ string smart = NetManager.GetBindInterface(remoteAddr, out port);
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- Logger.LogError(ex, "Error getting local Ip address information");
+ return smart.Trim('/');
}
- return null;
+ return GetLocalApiUrl(smart.Trim('/'), null, port);
}
- public async Task<string> GetWanApiUrl(CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public string GetSmartApiUrl(HttpRequest request, int? port = null)
{
- const string url = "http://ipv4.icanhazip.com";
- try
+ // Return the host in the HTTP request as the API url
+ if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
{
- using (var response = await HttpClient.Get(new HttpRequestOptions
- {
- Url = url,
- LogErrorResponseBody = false,
- LogErrors = false,
- LogRequest = false,
- TimeoutMs = 10000,
- BufferContent = false,
- CancellationToken = cancellationToken
- }))
+ int? requestPort = request.Host.Port;
+ if ((requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
{
- return GetLocalApiUrl(response.ReadToEnd().Trim());
+ requestPort = -1;
}
+
+ return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
}
- catch (Exception ex)
+
+ // Published server ends with a /
+ if (!string.IsNullOrEmpty(PublishedServerUrl))
{
- Logger.LogError(ex, "Error getting WAN Ip address information");
+ // Published server ends with a '/', so we need to remove it.
+ return PublishedServerUrl.Trim('/');
}
- return null;
- }
- public string GetLocalApiUrl(IpAddressInfo ipAddress)
- {
- if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
+ string smart = NetManager.GetBindInterface(request, out port);
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- return GetLocalApiUrl("[" + ipAddress.Address + "]");
+ return smart.Trim('/');
}
- return GetLocalApiUrl(ipAddress.Address);
- }
-
- public string GetLocalApiUrl(string host)
- {
- return string.Format("http://{0}:{1}",
- host,
- HttpPort.ToString(CultureInfo.InvariantCulture));
- }
-
- public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
- {
- return GetLocalIpAddressesInternal(true, 0, cancellationToken);
+ return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
}
- private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public string GetSmartApiUrl(string hostname, int? port = null)
{
- var addresses = ServerConfigurationManager
- .Configuration
- .LocalNetworkAddresses
- .Select(NormalizeConfiguredLocalAddress)
- .Where(i => i != null)
- .ToList();
-
- if (addresses.Count == 0)
+ // Published server ends with a /
+ if (!string.IsNullOrEmpty(PublishedServerUrl))
{
- addresses.AddRange(NetworkManager.GetLocalIpAddresses());
+ // Published server ends with a '/', so we need to remove it.
+ return PublishedServerUrl.Trim('/');
}
- var resultList = new List<IpAddressInfo>();
+ string smart = NetManager.GetBindInterface(hostname, out port);
- foreach (var address in addresses)
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- if (!allowLoopback)
- {
- if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
- {
- continue;
- }
- }
-
- var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
- if (valid)
- {
- resultList.Add(address);
-
- if (limit > 0 && resultList.Count >= limit)
- {
- return resultList;
- }
- }
+ return smart.Trim('/');
}
- return resultList;
+ return GetLocalApiUrl(smart.Trim('/'), null, port);
}
- private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
+ /// <inheritdoc/>
+ public string GetLoopbackHttpApiUrl()
{
- var index = address.Trim('/').IndexOf('/');
-
- if (index != -1)
+ if (NetManager.IsIP6Enabled)
{
- address = address.Substring(index + 1);
+ return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
}
- if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result))
- {
- return result;
- }
- return null;
+ return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
}
- private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
- private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
{
- if (address.Equals(IpAddressInfo.Loopback) ||
- address.Equals(IpAddressInfo.IPv6Loopback))
- {
- return true;
- }
-
- var apiUrl = GetLocalApiUrl(address);
- apiUrl += "/system/ping";
-
- if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
- {
- return cachedResult;
- }
-
- var logPing = false;
-
-#if DEBUG
- logPing = true;
-#endif
-
- try
- {
- using (var response = await HttpClient.SendAsync(new HttpRequestOptions
- {
- Url = apiUrl,
- LogErrorResponseBody = false,
- LogErrors = logPing,
- LogRequest = logPing,
- TimeoutMs = 30000,
- BufferContent = false,
-
- CancellationToken = cancellationToken
-
- }, "POST").ConfigureAwait(false))
- {
- using (var reader = new StreamReader(response.Content))
- {
- var result = reader.ReadToEnd();
- var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
-
- _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
- Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
- return valid;
- }
- }
- }
- catch (OperationCanceledException)
- {
- Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
- throw;
- }
- catch (Exception ex)
- {
- Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
-
- _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
- return false;
- }
+ // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
+ // not. For consistency, always trim the trailing slash.
+ return new UriBuilder
+ {
+ Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
+ Host = hostname,
+ Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
+ Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
+ }.ToString().TrimEnd('/');
}
- public string FriendlyName =>
- string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
- ? Environment.MachineName
- : ServerConfigurationManager.Configuration.ServerName;
-
- public int HttpPort { get; private set; }
-
- public int HttpsPort { get; private set; }
-
- /// <summary>
- /// Shuts down.
- /// </summary>
+ /// <inheritdoc />
public async Task Shutdown()
{
if (IsShuttingDown)
@@ -1709,7 +1227,7 @@ namespace Emby.Server.Implementations
try
{
- await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -1721,124 +1239,25 @@ namespace Emby.Server.Implementations
protected abstract void ShutdownInternal();
- public event EventHandler HasUpdateAvailableChanged;
-
- private bool _hasUpdateAvailable;
- public bool HasUpdateAvailable
- {
- get => _hasUpdateAvailable;
- set
- {
- var fireEvent = value && !_hasUpdateAvailable;
-
- _hasUpdateAvailable = value;
-
- if (fireEvent)
- {
- HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
- }
- }
- }
-
- /// <summary>
- /// Removes the plugin.
- /// </summary>
- /// <param name="plugin">The plugin.</param>
- public void RemovePlugin(IPlugin plugin)
- {
- var list = Plugins.ToList();
- list.Remove(plugin);
- Plugins = list.ToArray();
- }
-
- /// <summary>
- /// This returns localhost in the case of no external dns, and the hostname if the
- /// dns is prefixed with a valid Uri prefix.
- /// </summary>
- /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
- /// <returns>The hostname in <paramref name="externalDns"/></returns>
- private static string GetHostnameFromExternalDns(string externalDns)
+ public IEnumerable<Assembly> GetApiPluginAssemblies()
{
- if (string.IsNullOrEmpty(externalDns))
- {
- return "localhost";
- }
-
- try
- {
- return new Uri(externalDns).Host;
- }
- catch
- {
- return externalDns;
- }
- }
-
- public virtual void LaunchUrl(string url)
- {
- if (!CanLaunchWebBrowser)
- {
- throw new NotSupportedException();
- }
-
- var process = ProcessFactory.Create(new ProcessOptions
- {
- FileName = url,
- //EnableRaisingEvents = true,
- UseShellExecute = true,
- ErrorDialog = false
- });
-
- process.Exited += ProcessExited;
+ var assemblies = _allConcreteTypes
+ .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
+ .Select(i => i.Assembly)
+ .Distinct();
- try
- {
- process.Start();
- }
- catch (Exception ex)
+ foreach (var assembly in assemblies)
{
- Logger.LogError(ex, "Error launching url: {url}", url);
- throw;
+ Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
+ yield return assembly;
}
}
- private static void ProcessExited(object sender, EventArgs e)
- {
- ((IProcess)sender).Dispose();
- }
-
- public virtual void EnableLoopback(string appName)
- {
- }
-
- /// <summary>
- /// Called when [application updated].
- /// </summary>
- /// <param name="package">The package.</param>
- protected void OnApplicationUpdated(PackageVersionInfo package)
- {
- Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
-
- ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
- {
- Argument = package
- });
-
- NotifyPendingRestart();
- }
-
- private bool _disposed;
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
+ /// <inheritdoc />
public void Dispose()
{
- if (!_disposed)
- {
- _disposed = true;
-
- Dispose(true);
- }
+ Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
@@ -1847,14 +1266,19 @@ namespace Emby.Server.Implementations
/// <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 (_disposed)
+ {
+ return;
+ }
+
if (dispose)
{
var type = GetType();
Logger.LogInformation("Disposing {Type}", type.Name);
- var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
- DisposableParts.Clear();
+ var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
+ _disposableParts.Clear();
foreach (var part in parts)
{
@@ -1870,12 +1294,8 @@ namespace Emby.Server.Implementations
}
}
}
- }
- }
- internal class CertificateInfo
- {
- public string Path { get; set; }
- public string Password { get; set; }
+ _disposed = true;
+ }
}
}
diff --git a/Emby.Server.Implementations/Archiving/ZipClient.cs b/Emby.Server.Implementations/Archiving/ZipClient.cs
index 6b0fd2dc6..9e1d550eb 100644
--- a/Emby.Server.Implementations/Archiving/ZipClient.cs
+++ b/Emby.Server.Implementations/Archiving/ZipClient.cs
@@ -10,15 +10,10 @@ using SharpCompress.Readers.Zip;
namespace Emby.Server.Implementations.Archiving
{
/// <summary>
- /// Class DotNetZipClient
+ /// Class DotNetZipClient.
/// </summary>
public class ZipClient : IZipClient
{
- public ZipClient()
- {
-
- }
-
/// <summary>
/// Extracts all.
/// </summary>
@@ -27,10 +22,8 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles)
{
- using (var fileStream = File.OpenRead(sourceFile))
- {
- ExtractAll(fileStream, targetPath, overwriteExistingFiles);
- }
+ using var fileStream = File.OpenRead(sourceFile);
+ ExtractAll(fileStream, targetPath, overwriteExistingFiles);
}
/// <summary>
@@ -41,67 +34,64 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAll(Stream source, string targetPath, bool overwriteExistingFiles)
{
- using (var reader = ReaderFactory.Open(source))
+ using var reader = ReaderFactory.Open(source);
+ var options = new ExtractionOptions
{
- var options = new ExtractionOptions();
- options.ExtractFullPath = true;
-
- if (overwriteExistingFiles)
- {
- options.Overwrite = true;
- }
+ ExtractFullPath = true
+ };
- reader.WriteAllToDirectory(targetPath, options);
+ if (overwriteExistingFiles)
+ {
+ options.Overwrite = true;
}
+
+ Directory.CreateDirectory(targetPath);
+ reader.WriteAllToDirectory(targetPath, options);
}
+ /// <inheritdoc />
public void ExtractAllFromZip(Stream source, string targetPath, bool overwriteExistingFiles)
{
- using (var reader = ZipReader.Open(source))
+ using var reader = ZipReader.Open(source);
+ var options = new ExtractionOptions
{
- var options = new ExtractionOptions();
- options.ExtractFullPath = true;
-
- if (overwriteExistingFiles)
- {
- options.Overwrite = true;
- }
+ ExtractFullPath = true,
+ Overwrite = overwriteExistingFiles
+ };
- reader.WriteAllToDirectory(targetPath, options);
- }
+ Directory.CreateDirectory(targetPath);
+ reader.WriteAllToDirectory(targetPath, options);
}
+ /// <inheritdoc />
public void ExtractAllFromGz(Stream source, string targetPath, bool overwriteExistingFiles)
{
- using (var reader = GZipReader.Open(source))
+ using var reader = GZipReader.Open(source);
+ var options = new ExtractionOptions
{
- var options = new ExtractionOptions();
- options.ExtractFullPath = true;
-
- if (overwriteExistingFiles)
- {
- options.Overwrite = true;
- }
+ ExtractFullPath = true,
+ Overwrite = overwriteExistingFiles
+ };
- reader.WriteAllToDirectory(targetPath, options);
- }
+ Directory.CreateDirectory(targetPath);
+ reader.WriteAllToDirectory(targetPath, options);
}
+ /// <inheritdoc />
public void ExtractFirstFileFromGz(Stream source, string targetPath, string defaultFileName)
{
- using (var reader = GZipReader.Open(source))
+ using var reader = GZipReader.Open(source);
+ if (reader.MoveToNextEntry())
{
- if (reader.MoveToNextEntry())
+ var entry = reader.Entry;
+
+ var filename = entry.Key;
+ if (string.IsNullOrWhiteSpace(filename))
{
- var entry = reader.Entry;
-
- var filename = entry.Key;
- if (string.IsNullOrWhiteSpace(filename))
- {
- filename = defaultFileName;
- }
- reader.WriteEntryToFile(Path.Combine(targetPath, filename));
+ filename = defaultFileName;
}
+
+ reader.WriteEntryToFile(Path.Combine(targetPath, filename));
}
}
@@ -113,10 +103,8 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles)
{
- using (var fileStream = File.OpenRead(sourceFile))
- {
- ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles);
- }
+ using var fileStream = File.OpenRead(sourceFile);
+ ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles);
}
/// <summary>
@@ -127,24 +115,18 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFrom7z(Stream source, string targetPath, bool overwriteExistingFiles)
{
- using (var archive = SevenZipArchive.Open(source))
+ using var archive = SevenZipArchive.Open(source);
+ using var reader = archive.ExtractAllEntries();
+ var options = new ExtractionOptions
{
- using (var reader = archive.ExtractAllEntries())
- {
- var options = new ExtractionOptions();
- options.ExtractFullPath = true;
+ ExtractFullPath = true,
+ Overwrite = overwriteExistingFiles
+ };
- if (overwriteExistingFiles)
- {
- options.Overwrite = true;
- }
-
- reader.WriteAllToDirectory(targetPath, options);
- }
- }
+ Directory.CreateDirectory(targetPath);
+ reader.WriteAllToDirectory(targetPath, options);
}
-
/// <summary>
/// Extracts all from tar.
/// </summary>
@@ -153,10 +135,8 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles)
{
- using (var fileStream = File.OpenRead(sourceFile))
- {
- ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles);
- }
+ using var fileStream = File.OpenRead(sourceFile);
+ ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles);
}
/// <summary>
@@ -167,21 +147,16 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFromTar(Stream source, string targetPath, bool overwriteExistingFiles)
{
- using (var archive = TarArchive.Open(source))
+ using var archive = TarArchive.Open(source);
+ using var reader = archive.ExtractAllEntries();
+ var options = new ExtractionOptions
{
- using (var reader = archive.ExtractAllEntries())
- {
- var options = new ExtractionOptions();
- options.ExtractFullPath = true;
-
- if (overwriteExistingFiles)
- {
- options.Overwrite = true;
- }
+ ExtractFullPath = true,
+ Overwrite = overwriteExistingFiles
+ };
- reader.WriteAllToDirectory(targetPath, options);
- }
- }
+ Directory.CreateDirectory(targetPath);
+ reader.WriteAllToDirectory(targetPath, options);
}
}
}
diff --git a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs
index b27f84848..7ae26bd8b 100644
--- a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs
+++ b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs
@@ -4,8 +4,12 @@ using MediaBrowser.Model.Branding;
namespace Emby.Server.Implementations.Branding
{
+ /// <summary>
+ /// A configuration factory for <see cref="BrandingOptions"/>.
+ /// </summary>
public class BrandingConfigurationFactory : IConfigurationFactory
{
+ /// <inheritdoc />
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new[]
diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs
deleted file mode 100644
index 718129ef0..000000000
--- a/Emby.Server.Implementations/Browser/BrowserLauncher.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using System;
-using MediaBrowser.Controller;
-
-namespace Emby.Server.Implementations.Browser
-{
- /// <summary>
- /// Class BrowserLauncher
- /// </summary>
- public static class BrowserLauncher
- {
- /// <summary>
- /// Opens the dashboard page.
- /// </summary>
- /// <param name="page">The page.</param>
- /// <param name="appHost">The app host.</param>
- private static void OpenDashboardPage(string page, IServerApplicationHost appHost)
- {
- var url = appHost.GetLocalApiUrl("localhost") + "/web/" + page;
-
- OpenUrl(appHost, url);
- }
-
- /// <summary>
- /// Opens the web client.
- /// </summary>
- /// <param name="appHost">The app host.</param>
- public static void OpenWebApp(IServerApplicationHost appHost)
- {
- OpenDashboardPage("index.html", appHost);
- }
-
- /// <summary>
- /// Opens the URL.
- /// </summary>
- /// <param name="url">The URL.</param>
- private static void OpenUrl(IServerApplicationHost appHost, string url)
- {
- try
- {
- appHost.LaunchUrl(url);
- }
- catch (NotSupportedException)
- {
-
- }
- catch (Exception)
- {
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
index c10f00f9b..3e149cc82 100644
--- a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
+++ b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Channels;
@@ -9,25 +10,31 @@ using MediaBrowser.Model.Dto;
namespace Emby.Server.Implementations.Channels
{
+ /// <summary>
+ /// A media source provider for channels.
+ /// </summary>
public class ChannelDynamicMediaSourceProvider : IMediaSourceProvider
{
private readonly ChannelManager _channelManager;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelDynamicMediaSourceProvider"/> class.
+ /// </summary>
+ /// <param name="channelManager">The channel manager.</param>
public ChannelDynamicMediaSourceProvider(IChannelManager channelManager)
{
_channelManager = (ChannelManager)channelManager;
}
+ /// <inheritdoc />
public Task<IEnumerable<MediaSourceInfo>> GetMediaSources(BaseItem item, CancellationToken cancellationToken)
{
- if (item.SourceType == SourceType.Channel)
- {
- return _channelManager.GetDynamicMediaSources(item, cancellationToken);
- }
-
- return Task.FromResult<IEnumerable<MediaSourceInfo>>(new List<MediaSourceInfo>());
+ return item.SourceType == SourceType.Channel
+ ? _channelManager.GetDynamicMediaSources(item, cancellationToken)
+ : Task.FromResult(Enumerable.Empty<MediaSourceInfo>());
}
+ /// <inheritdoc />
public Task<ILiveStream> OpenMediaSource(string openToken, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
throw new NotImplementedException();
diff --git a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs
index bafa68818..25cbfcf14 100644
--- a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs
+++ b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs
@@ -9,20 +9,32 @@ using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Channels
{
+ /// <summary>
+ /// An image provider for channels.
+ /// </summary>
public class ChannelImageProvider : IDynamicImageProvider, IHasItemChangeMonitor
{
private readonly IChannelManager _channelManager;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelImageProvider"/> class.
+ /// </summary>
+ /// <param name="channelManager">The channel manager.</param>
public ChannelImageProvider(IChannelManager channelManager)
{
_channelManager = channelManager;
}
+ /// <inheritdoc />
+ public string Name => "Channel Image Provider";
+
+ /// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return GetChannel(item).GetSupportedChannelImages();
}
+ /// <inheritdoc />
public Task<DynamicImageResponse> GetImage(BaseItem item, ImageType type, CancellationToken cancellationToken)
{
var channel = GetChannel(item);
@@ -30,8 +42,7 @@ namespace Emby.Server.Implementations.Channels
return channel.GetChannelImage(type, cancellationToken);
}
- public string Name => "Channel Image Provider";
-
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
return item is Channel;
@@ -44,6 +55,7 @@ namespace Emby.Server.Implementations.Channels
return ((ChannelManager)_channelManager).GetChannelProvider(channel);
}
+ /// <inheritdoc />
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
return GetSupportedImages(item).Any(i => !item.HasImage(i));
diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs
index 949b89226..09aee602a 100644
--- a/Emby.Server.Implementations/Channels/ChannelManager.cs
+++ b/Emby.Server.Implementations/Channels/ChannelManager.cs
@@ -1,100 +1,120 @@
+#nullable disable
+
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Server.Implementations.Channels
{
+ /// <summary>
+ /// The LiveTV channel manager.
+ /// </summary>
public class ChannelManager : IChannelManager
{
- internal IChannel[] Channels { get; private set; }
-
private readonly IUserManager _userManager;
private readonly IUserDataManager _userDataManager;
private readonly IDtoService _dtoService;
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<ChannelManager> _logger;
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
private readonly IProviderManager _providerManager;
-
- private readonly ILocalizationManager _localization;
-
+ private readonly IMemoryCache _memoryCache;
+ private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelManager"/> class.
+ /// </summary>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="dtoService">The dto service.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="config">The server configuration manager.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="providerManager">The provider manager.</param>
+ /// <param name="memoryCache">The memory cache.</param>
public ChannelManager(
IUserManager userManager,
IDtoService dtoService,
ILibraryManager libraryManager,
- ILoggerFactory loggerFactory,
+ ILogger<ChannelManager> logger,
IServerConfigurationManager config,
IFileSystem fileSystem,
IUserDataManager userDataManager,
- IJsonSerializer jsonSerializer,
- ILocalizationManager localization,
- IHttpClient httpClient,
- IProviderManager providerManager)
+ IProviderManager providerManager,
+ IMemoryCache memoryCache)
{
_userManager = userManager;
_dtoService = dtoService;
_libraryManager = libraryManager;
- _logger = loggerFactory.CreateLogger(nameof(ChannelManager));
+ _logger = logger;
_config = config;
_fileSystem = fileSystem;
_userDataManager = userDataManager;
- _jsonSerializer = jsonSerializer;
- _localization = localization;
- _httpClient = httpClient;
_providerManager = providerManager;
+ _memoryCache = memoryCache;
}
+ internal IChannel[] Channels { get; private set; }
+
private static TimeSpan CacheLength => TimeSpan.FromHours(3);
+ /// <inheritdoc />
public void AddParts(IEnumerable<IChannel> channels)
{
Channels = channels.ToArray();
}
+ /// <inheritdoc />
public bool EnableMediaSourceDisplay(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
- return !(channel is IDisableMediaSourceDisplay);
+ return channel is not IDisableMediaSourceDisplay;
}
+ /// <inheritdoc />
public bool CanDelete(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
- var supportsDelete = channel as ISupportsDelete;
- return supportsDelete != null && supportsDelete.CanDelete(item);
+ return channel is ISupportsDelete supportsDelete && supportsDelete.CanDelete(item);
}
+ /// <inheritdoc />
public bool EnableMediaProbe(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
@@ -103,6 +123,7 @@ namespace Emby.Server.Implementations.Channels
return channel is ISupportsMediaProbe;
}
+ /// <inheritdoc />
public Task DeleteItem(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
@@ -129,11 +150,16 @@ namespace Emby.Server.Implementations.Channels
.OrderBy(i => i.Name);
}
+ /// <summary>
+ /// Get the installed channel IDs.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{T}"/> containing installed channel IDs.</returns>
public IEnumerable<Guid> GetInstalledChannelIds()
{
return GetAllChannels().Select(i => GetInternalChannelId(i.Name));
}
+ /// <inheritdoc />
public QueryResult<Channel> GetChannelsInternal(ChannelQuery query)
{
var user = query.UserId.Equals(Guid.Empty)
@@ -152,15 +178,13 @@ namespace Emby.Server.Implementations.Channels
{
try
{
- var hasAttributes = GetChannelProvider(i) as IHasFolderAttributes;
-
- return (hasAttributes != null && hasAttributes.Attributes.Contains("Recordings", StringComparer.OrdinalIgnoreCase)) == val;
+ return (GetChannelProvider(i) is IHasFolderAttributes hasAttributes
+ && hasAttributes.Attributes.Contains("Recordings", StringComparer.OrdinalIgnoreCase)) == val;
}
catch
{
return false;
}
-
}).ToList();
}
@@ -177,7 +201,6 @@ namespace Emby.Server.Implementations.Channels
{
return false;
}
-
}).ToList();
}
@@ -194,9 +217,9 @@ namespace Emby.Server.Implementations.Channels
{
return false;
}
-
}).ToList();
}
+
if (query.IsFavorite.HasValue)
{
var val = query.IsFavorite.Value;
@@ -215,46 +238,41 @@ namespace Emby.Server.Implementations.Channels
try
{
- return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N"));
+ return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N", CultureInfo.InvariantCulture));
}
catch
{
return false;
}
-
}).ToList();
}
var all = channels;
var totalCount = all.Count;
- if (query.StartIndex.HasValue)
- {
- all = all.Skip(query.StartIndex.Value).ToList();
- }
- if (query.Limit.HasValue)
+ if (query.StartIndex.HasValue || query.Limit.HasValue)
{
- all = all.Take(query.Limit.Value).ToList();
+ int startIndex = query.StartIndex ?? 0;
+ int count = query.Limit == null ? totalCount - startIndex : Math.Min(query.Limit.Value, totalCount - startIndex);
+ all = all.GetRange(startIndex, count);
}
- var returnItems = all.ToArray();
-
if (query.RefreshLatestChannelItems)
{
- foreach (var item in returnItems)
+ foreach (var item in all)
{
- var task = RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None);
- Task.WaitAll(task);
+ RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).GetAwaiter().GetResult();
}
}
return new QueryResult<Channel>
{
- Items = returnItems,
+ Items = all,
TotalRecordCount = totalCount
};
}
+ /// <inheritdoc />
public QueryResult<BaseItemDto> GetChannels(ChannelQuery query)
{
var user = query.UserId.Equals(Guid.Empty)
@@ -263,11 +281,9 @@ namespace Emby.Server.Implementations.Channels
var internalResult = GetChannelsInternal(query);
- var dtoOptions = new DtoOptions()
- {
- };
+ var dtoOptions = new DtoOptions();
- //TODO Fix The co-variant conversion (internalResult.Items) between Folder[] and BaseItem[], this can generate runtime issues.
+ // TODO Fix The co-variant conversion (internalResult.Items) between Folder[] and BaseItem[], this can generate runtime issues.
var returnItems = _dtoService.GetBaseItemDtos(internalResult.Items, dtoOptions, user);
var result = new QueryResult<BaseItemDto>
@@ -279,6 +295,12 @@ namespace Emby.Server.Implementations.Channels
return result;
}
+ /// <summary>
+ /// Refreshes the associated channels.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
+ /// <returns>The completed task.</returns>
public async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
{
var allChannelsList = GetAllChannels().ToList();
@@ -303,9 +325,7 @@ namespace Emby.Server.Implementations.Channels
}
numComplete++;
- double percent = numComplete;
- percent /= allChannelsList.Count;
-
+ double percent = (double)numComplete / allChannelsList.Count;
progress.Report(100 * percent);
}
@@ -314,31 +334,26 @@ namespace Emby.Server.Implementations.Channels
private Channel GetChannelEntity(IChannel channel)
{
- var item = GetChannel(GetInternalChannelId(channel.Name));
-
- if (item == null)
- {
- item = GetChannel(channel, CancellationToken.None).Result;
- }
-
- return item;
+ return GetChannel(GetInternalChannelId(channel.Name)) ?? GetChannel(channel, CancellationToken.None).Result;
}
- private List<MediaSourceInfo> GetSavedMediaSources(BaseItem item)
+ private MediaSourceInfo[] GetSavedMediaSources(BaseItem item)
{
var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json");
try
{
- return _jsonSerializer.DeserializeFromFile<List<MediaSourceInfo>>(path) ?? new List<MediaSourceInfo>();
+ var bytes = File.ReadAllBytes(path);
+ return JsonSerializer.Deserialize<MediaSourceInfo[]>(bytes, _jsonOptions)
+ ?? Array.Empty<MediaSourceInfo>();
}
catch
{
- return new List<MediaSourceInfo>();
+ return Array.Empty<MediaSourceInfo>();
}
}
- private void SaveMediaSources(BaseItem item, List<MediaSourceInfo> mediaSources)
+ private async Task SaveMediaSources(BaseItem item, List<MediaSourceInfo> mediaSources)
{
var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json");
@@ -350,16 +365,18 @@ namespace Emby.Server.Implementations.Channels
}
catch
{
-
}
+
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path));
- _jsonSerializer.SerializeToFile(mediaSources, path);
+ await using FileStream createStream = File.Create(path);
+ await JsonSerializer.SerializeAsync(createStream, mediaSources, _jsonOptions).ConfigureAwait(false);
}
+ /// <inheritdoc />
public IEnumerable<MediaSourceInfo> GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken)
{
IEnumerable<MediaSourceInfo> results = GetSavedMediaSources(item);
@@ -369,16 +386,20 @@ namespace Emby.Server.Implementations.Channels
.ToList();
}
+ /// <summary>
+ /// Gets the dynamic media sources based on the provided item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
+ /// <returns>The task representing the operation to get the media sources.</returns>
public async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, CancellationToken cancellationToken)
{
var channel = GetChannel(item.ChannelId);
var channelPlugin = GetChannelProvider(channel);
- var requiresCallback = channelPlugin as IRequiresMediaInfoCallback;
-
IEnumerable<MediaSourceInfo> results;
- if (requiresCallback != null)
+ if (channelPlugin is IRequiresMediaInfoCallback requiresCallback)
{
results = await GetChannelItemMediaSourcesInternal(requiresCallback, item.ExternalId, cancellationToken)
.ConfigureAwait(false);
@@ -393,32 +414,24 @@ namespace Emby.Server.Implementations.Channels
.ToList();
}
- private readonly ConcurrentDictionary<string, Tuple<DateTime, List<MediaSourceInfo>>> _channelItemMediaInfo =
- new ConcurrentDictionary<string, Tuple<DateTime, List<MediaSourceInfo>>>();
-
private async Task<IEnumerable<MediaSourceInfo>> GetChannelItemMediaSourcesInternal(IRequiresMediaInfoCallback channel, string id, CancellationToken cancellationToken)
{
- if (_channelItemMediaInfo.TryGetValue(id, out Tuple<DateTime, List<MediaSourceInfo>> cachedInfo))
+ if (_memoryCache.TryGetValue(id, out List<MediaSourceInfo> cachedInfo))
{
- if ((DateTime.UtcNow - cachedInfo.Item1).TotalMinutes < 5)
- {
- return cachedInfo.Item2;
- }
+ return cachedInfo;
}
var mediaInfo = await channel.GetChannelItemMediaInfo(id, cancellationToken)
.ConfigureAwait(false);
var list = mediaInfo.ToList();
-
- var item2 = new Tuple<DateTime, List<MediaSourceInfo>>(DateTime.UtcNow, list);
- _channelItemMediaInfo.AddOrUpdate(id, item2, (key, oldValue) => item2);
+ _memoryCache.Set(id, list, DateTimeOffset.UtcNow.AddMinutes(5));
return list;
}
private static MediaSourceInfo NormalizeMediaSource(BaseItem item, MediaSourceInfo info)
{
- info.RunTimeTicks = info.RunTimeTicks ?? item.RunTimeTicks;
+ info.RunTimeTicks ??= item.RunTimeTicks;
return info;
}
@@ -453,18 +466,21 @@ namespace Emby.Server.Implementations.Channels
{
isNew = true;
}
+
item.Path = path;
if (!item.ChannelId.Equals(id))
{
forceUpdate = true;
}
+
item.ChannelId = id;
if (item.ParentId != parentFolderId)
{
forceUpdate = true;
}
+
item.ParentId = parentFolderId;
item.OfficialRating = GetOfficialRating(channelInfo.ParentalRating);
@@ -481,79 +497,96 @@ namespace Emby.Server.Implementations.Channels
_libraryManager.CreateItem(item, null);
}
- await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- ForceSave = !isNew && forceUpdate
- }, cancellationToken);
+ await item.RefreshMetadata(
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = !isNew && forceUpdate
+ },
+ cancellationToken).ConfigureAwait(false);
return item;
}
private static string GetOfficialRating(ChannelParentalRating rating)
{
- switch (rating)
- {
- case ChannelParentalRating.Adult:
- return "XXX";
- case ChannelParentalRating.UsR:
- return "R";
- case ChannelParentalRating.UsPG13:
- return "PG-13";
- case ChannelParentalRating.UsPG:
- return "PG";
- default:
- return null;
- }
+ return rating switch
+ {
+ ChannelParentalRating.Adult => "XXX",
+ ChannelParentalRating.UsR => "R",
+ ChannelParentalRating.UsPG13 => "PG-13",
+ ChannelParentalRating.UsPG => "PG",
+ _ => null
+ };
}
+ /// <summary>
+ /// Gets a channel with the provided Guid.
+ /// </summary>
+ /// <param name="id">The Guid.</param>
+ /// <returns>The corresponding channel.</returns>
public Channel GetChannel(Guid id)
{
return _libraryManager.GetItemById(id) as Channel;
}
+ /// <inheritdoc />
public Channel GetChannel(string id)
{
return _libraryManager.GetItemById(id) as Channel;
}
+ /// <inheritdoc />
public ChannelFeatures[] GetAllChannelFeatures()
{
- return _libraryManager.GetItemIds(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(Channel).Name },
- OrderBy = new ValueTuple<string, SortOrder>[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) }
-
- }).Select(i => GetChannelFeatures(i.ToString("N"))).ToArray();
+ return _libraryManager.GetItemIds(
+ new InternalItemsQuery
+ {
+ IncludeItemTypes = new[] { nameof(Channel) },
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
+ }).Select(i => GetChannelFeatures(i)).ToArray();
}
- public ChannelFeatures GetChannelFeatures(string id)
+ /// <inheritdoc />
+ public ChannelFeatures GetChannelFeatures(Guid? id)
{
- if (string.IsNullOrEmpty(id))
+ if (!id.HasValue)
{
throw new ArgumentNullException(nameof(id));
}
- var channel = GetChannel(id);
+ var channel = GetChannel(id.Value);
var channelProvider = GetChannelProvider(channel);
return GetChannelFeaturesDto(channel, channelProvider, channelProvider.GetChannelFeatures());
}
+ /// <summary>
+ /// Checks whether the provided Guid supports external transfer.
+ /// </summary>
+ /// <param name="channelId">The Guid.</param>
+ /// <returns>Whether or not the provided Guid supports external transfer.</returns>
public bool SupportsExternalTransfer(Guid channelId)
{
- //var channel = GetChannel(channelId);
var channelProvider = GetChannelProvider(channelId);
return channelProvider.GetChannelFeatures().SupportsContentDownloading;
}
- public ChannelFeatures GetChannelFeaturesDto(Channel channel,
+ /// <summary>
+ /// Gets the provided channel's supported features.
+ /// </summary>
+ /// <param name="channel">The channel.</param>
+ /// <param name="provider">The provider.</param>
+ /// <param name="features">The features.</param>
+ /// <returns>The supported features.</returns>
+ public ChannelFeatures GetChannelFeaturesDto(
+ Channel channel,
IChannel provider,
InternalChannelFeatures features)
{
var supportsLatest = provider is ISupportsLatestMedia;
- return new ChannelFeatures
+ return new ChannelFeatures(channel.Name, channel.Id)
{
CanFilter = !features.MaxPageSize.HasValue,
CanSearch = provider is ISearchableChannel,
@@ -563,8 +596,6 @@ namespace Emby.Server.Implementations.Channels
MediaTypes = features.MediaTypes.ToArray(),
SupportsSortOrderToggle = features.SupportsSortOrderToggle,
SupportsLatestMedia = supportsLatest,
- Name = channel.Name,
- Id = channel.Id.ToString("N"),
SupportsContentDownloading = features.SupportsContentDownloading,
AutoRefreshLevels = features.AutoRefreshLevels
};
@@ -576,9 +607,11 @@ namespace Emby.Server.Implementations.Channels
{
throw new ArgumentNullException(nameof(name));
}
+
return _libraryManager.GetNewItemId("Channel " + name, typeof(Channel));
}
+ /// <inheritdoc />
public async Task<QueryResult<BaseItemDto>> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken)
{
var internalResult = await GetLatestChannelItemsInternal(query, cancellationToken).ConfigureAwait(false);
@@ -597,11 +630,12 @@ namespace Emby.Server.Implementations.Channels
return result;
}
+ /// <inheritdoc />
public async Task<QueryResult<BaseItem>> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken)
{
var channels = GetAllChannels().Where(i => i is ISupportsLatestMedia).ToArray();
- if (query.ChannelIds.Length > 0)
+ if (query.ChannelIds.Count > 0)
{
// Avoid implicitly captured closure
var ids = query.ChannelIds;
@@ -623,22 +657,22 @@ namespace Emby.Server.Implementations.Channels
query.IsFolder = false;
// hack for trailers, figure out a better way later
- var sortByPremiereDate = channels.Length == 1 && channels[0].GetType().Name.IndexOf("Trailer") != -1;
+ var sortByPremiereDate = channels.Length == 1 && channels[0].GetType().Name.Contains("Trailer", StringComparison.Ordinal);
if (sortByPremiereDate)
{
query.OrderBy = new[]
{
- new ValueTuple<string, SortOrder>(ItemSortBy.PremiereDate, SortOrder.Descending),
- new ValueTuple<string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending),
- new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending)
+ (ItemSortBy.PremiereDate, SortOrder.Descending),
+ (ItemSortBy.ProductionYear, SortOrder.Descending),
+ (ItemSortBy.DateCreated, SortOrder.Descending)
};
}
else
{
query.OrderBy = new[]
{
- new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending)
+ (ItemSortBy.DateCreated, SortOrder.Descending)
};
}
@@ -647,32 +681,35 @@ namespace Emby.Server.Implementations.Channels
private async Task RefreshLatestChannelItems(IChannel channel, CancellationToken cancellationToken)
{
- var internalChannel = await GetChannel(channel, cancellationToken);
+ var internalChannel = await GetChannel(channel, cancellationToken).ConfigureAwait(false);
- var query = new InternalItemsQuery();
- query.Parent = internalChannel;
- query.EnableTotalRecordCount = false;
- query.ChannelIds = new Guid[] { internalChannel.Id };
+ var query = new InternalItemsQuery
+ {
+ Parent = internalChannel,
+ EnableTotalRecordCount = false,
+ ChannelIds = new Guid[] { internalChannel.Id }
+ };
var result = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
foreach (var item in result.Items)
{
- var folder = item as Folder;
-
- if (folder != null)
+ if (item is Folder folder)
{
- await GetChannelItemsInternal(new InternalItemsQuery
- {
- Parent = folder,
- EnableTotalRecordCount = false,
- ChannelIds = new Guid[] { internalChannel.Id }
-
- }, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
+ await GetChannelItemsInternal(
+ new InternalItemsQuery
+ {
+ Parent = folder,
+ EnableTotalRecordCount = false,
+ ChannelIds = new Guid[] { internalChannel.Id }
+ },
+ new SimpleProgress<double>(),
+ cancellationToken).ConfigureAwait(false);
}
}
}
+ /// <inheritdoc />
public async Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQuery query, IProgress<double> progress, CancellationToken cancellationToken)
{
// Get the internal channel entity
@@ -683,7 +720,8 @@ namespace Emby.Server.Implementations.Channels
var parentItem = query.ParentId == Guid.Empty ? channel : _libraryManager.GetItemById(query.ParentId);
- var itemsResult = await GetChannelItems(channelProvider,
+ var itemsResult = await GetChannelItems(
+ channelProvider,
query.User,
parentItem is Channel ? null : parentItem.ExternalId,
null,
@@ -695,22 +733,30 @@ namespace Emby.Server.Implementations.Channels
{
query.Parent = channel;
}
+
query.ChannelIds = Array.Empty<Guid>();
// Not yet sure why this is causing a problem
query.GroupByPresentationUniqueKey = false;
- //_logger.LogDebug("GetChannelItemsInternal");
-
// null if came from cache
if (itemsResult != null)
{
- var internalItems = itemsResult.Items
- .Select(i => GetChannelItemEntity(i, channelProvider, channel.Id, parentItem, cancellationToken))
- .ToArray();
+ var items = itemsResult.Items;
+ var itemsLen = items.Count;
+ var internalItems = new Guid[itemsLen];
+ for (int i = 0; i < itemsLen; i++)
+ {
+ internalItems[i] = (await GetChannelItemEntityAsync(
+ items[i],
+ channelProvider,
+ channel.Id,
+ parentItem,
+ cancellationToken).ConfigureAwait(false)).Id;
+ }
var existingIds = _libraryManager.GetItemIds(query);
- var deadIds = existingIds.Except(internalItems.Select(i => i.Id))
+ var deadIds = existingIds.Except(internalItems)
.ToArray();
foreach (var deadId in deadIds)
@@ -718,12 +764,15 @@ namespace Emby.Server.Implementations.Channels
var deadItem = _libraryManager.GetItemById(deadId);
if (deadItem != null)
{
- _libraryManager.DeleteItem(deadItem, new DeleteOptions
- {
- DeleteFileLocation = false,
- DeleteFromExternalProvider = false
-
- }, parentItem, false);
+ _libraryManager.DeleteItem(
+ deadItem,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false,
+ DeleteFromExternalProvider = false
+ },
+ parentItem,
+ false);
}
}
}
@@ -731,6 +780,7 @@ namespace Emby.Server.Implementations.Channels
return _libraryManager.GetItemsResult(query);
}
+ /// <inheritdoc />
public async Task<QueryResult<BaseItemDto>> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken)
{
var internalResult = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
@@ -746,15 +796,15 @@ namespace Emby.Server.Implementations.Channels
return result;
}
- private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
- private async Task<ChannelItemResult> GetChannelItems(IChannel channel,
+ private async Task<ChannelItemResult> GetChannelItems(
+ IChannel channel,
User user,
string externalFolderId,
ChannelItemSortField? sortField,
bool sortDescending,
CancellationToken cancellationToken)
{
- var userId = user == null ? null : user.Id.ToString("N");
+ var userId = user?.Id.ToString("N", CultureInfo.InvariantCulture);
var cacheLength = CacheLength;
var cachePath = GetChannelDataCachePath(channel, userId, externalFolderId, sortField, sortDescending);
@@ -763,7 +813,8 @@ namespace Emby.Server.Implementations.Channels
{
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
{
- var cachedResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
+ await using FileStream jsonStream = AsyncFile.OpenRead(cachePath);
+ var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (cachedResult != null)
{
return null;
@@ -772,11 +823,9 @@ namespace Emby.Server.Implementations.Channels
}
catch (FileNotFoundException)
{
-
}
catch (IOException)
{
-
}
await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -787,7 +836,8 @@ namespace Emby.Server.Implementations.Channels
{
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
{
- var cachedResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
+ await using FileStream jsonStream = AsyncFile.OpenRead(cachePath);
+ var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (cachedResult != null)
{
return null;
@@ -796,16 +846,14 @@ namespace Emby.Server.Implementations.Channels
}
catch (FileNotFoundException)
{
-
}
catch (IOException)
{
-
}
var query = new InternalChannelItemQuery
{
- UserId = user == null ? Guid.Empty : user.Id,
+ UserId = user?.Id ?? Guid.Empty,
SortBy = sortField,
SortDescending = sortDescending,
FolderId = externalFolderId
@@ -820,7 +868,7 @@ namespace Emby.Server.Implementations.Channels
throw new InvalidOperationException("Channel returned a null result from GetChannelItems");
}
- CacheResponse(result, cachePath);
+ await CacheResponse(result, cachePath);
return result;
}
@@ -830,53 +878,56 @@ namespace Emby.Server.Implementations.Channels
}
}
- private void CacheResponse(object result, string path)
+ private async Task CacheResponse(ChannelItemResult result, string path)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
- _jsonSerializer.SerializeToFile(result, path);
+ await using FileStream createStream = File.Create(path);
+ await JsonSerializer.SerializeAsync(createStream, result, _jsonOptions).ConfigureAwait(false);
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error writing to channel cache file: {path}", path);
+ _logger.LogError(ex, "Error writing to channel cache file: {Path}", path);
}
}
- private string GetChannelDataCachePath(IChannel channel,
+ private string GetChannelDataCachePath(
+ IChannel channel,
string userId,
string externalFolderId,
ChannelItemSortField? sortField,
bool sortDescending)
{
- var channelId = GetInternalChannelId(channel.Name).ToString("N");
+ var channelId = GetInternalChannelId(channel.Name).ToString("N", CultureInfo.InvariantCulture);
var userCacheKey = string.Empty;
- var hasCacheKey = channel as IHasCacheKey;
- if (hasCacheKey != null)
+ if (channel is IHasCacheKey hasCacheKey)
{
userCacheKey = hasCacheKey.GetCacheKey(userId) ?? string.Empty;
}
- var filename = string.IsNullOrEmpty(externalFolderId) ? "root" : externalFolderId.GetMD5().ToString("N");
+ var filename = string.IsNullOrEmpty(externalFolderId) ? "root" : externalFolderId.GetMD5().ToString("N", CultureInfo.InvariantCulture);
filename += userCacheKey;
- var version = ((channel.DataVersion ?? string.Empty) + "2").GetMD5().ToString("N");
+ var version = ((channel.DataVersion ?? string.Empty) + "2").GetMD5().ToString("N", CultureInfo.InvariantCulture);
if (sortField.HasValue)
{
filename += "-sortField-" + sortField.Value;
}
+
if (sortDescending)
{
filename += "-sortDescending";
}
- filename = filename.GetMD5().ToString("N");
+ filename = filename.GetMD5().ToString("N", CultureInfo.InvariantCulture);
- return Path.Combine(_config.ApplicationPaths.CachePath,
+ return Path.Combine(
+ _config.ApplicationPaths.CachePath,
"channels",
channelId,
version,
@@ -920,7 +971,7 @@ namespace Emby.Server.Implementations.Channels
return item;
}
- private BaseItem GetChannelItemEntity(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, BaseItem parentFolder, CancellationToken cancellationToken)
+ private async Task<BaseItem> GetChannelItemEntityAsync(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, BaseItem parentFolder, CancellationToken cancellationToken)
{
var parentFolderId = parentFolder.Id;
@@ -930,60 +981,32 @@ namespace Emby.Server.Implementations.Channels
if (info.Type == ChannelItemType.Folder)
{
- if (info.FolderType == ChannelFolderType.MusicAlbum)
- {
- item = GetItemById<MusicAlbum>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.FolderType == ChannelFolderType.MusicArtist)
- {
- item = GetItemById<MusicArtist>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.FolderType == ChannelFolderType.PhotoAlbum)
- {
- item = GetItemById<PhotoAlbum>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.FolderType == ChannelFolderType.Series)
+ item = info.FolderType switch
{
- item = GetItemById<Series>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.FolderType == ChannelFolderType.Season)
- {
- item = GetItemById<Season>(info.Id, channelProvider.Name, out isNew);
- }
- else
- {
- item = GetItemById<Folder>(info.Id, channelProvider.Name, out isNew);
- }
+ ChannelFolderType.MusicAlbum => GetItemById<MusicAlbum>(info.Id, channelProvider.Name, out isNew),
+ ChannelFolderType.MusicArtist => GetItemById<MusicArtist>(info.Id, channelProvider.Name, out isNew),
+ ChannelFolderType.PhotoAlbum => GetItemById<PhotoAlbum>(info.Id, channelProvider.Name, out isNew),
+ ChannelFolderType.Series => GetItemById<Series>(info.Id, channelProvider.Name, out isNew),
+ ChannelFolderType.Season => GetItemById<Season>(info.Id, channelProvider.Name, out isNew),
+ _ => GetItemById<Folder>(info.Id, channelProvider.Name, out isNew)
+ };
}
else if (info.MediaType == ChannelMediaType.Audio)
{
- if (info.ContentType == ChannelMediaContentType.Podcast)
- {
- item = GetItemById<AudioBook>(info.Id, channelProvider.Name, out isNew);
- }
- else
- {
- item = GetItemById<Audio>(info.Id, channelProvider.Name, out isNew);
- }
+ item = info.ContentType == ChannelMediaContentType.Podcast
+ ? GetItemById<AudioBook>(info.Id, channelProvider.Name, out isNew)
+ : GetItemById<Audio>(info.Id, channelProvider.Name, out isNew);
}
else
{
- if (info.ContentType == ChannelMediaContentType.Episode)
- {
- item = GetItemById<Episode>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.ContentType == ChannelMediaContentType.Movie)
- {
- item = GetItemById<Movie>(info.Id, channelProvider.Name, out isNew);
- }
- else if (info.ContentType == ChannelMediaContentType.Trailer || info.ExtraType == ExtraType.Trailer)
- {
- item = GetItemById<Trailer>(info.Id, channelProvider.Name, out isNew);
- }
- else
+ item = info.ContentType switch
{
- item = GetItemById<Video>(info.Id, channelProvider.Name, out isNew);
- }
+ ChannelMediaContentType.Episode => GetItemById<Episode>(info.Id, channelProvider.Name, out isNew),
+ ChannelMediaContentType.Movie => GetItemById<Movie>(info.Id, channelProvider.Name, out isNew),
+ var x when x == ChannelMediaContentType.Trailer || info.ExtraType == ExtraType.Trailer
+ => GetItemById<Trailer>(info.Id, channelProvider.Name, out isNew),
+ _ => GetItemById<Video>(info.Id, channelProvider.Name, out isNew)
+ };
}
var enableMediaProbe = channelProvider is ISupportsMediaProbe;
@@ -992,7 +1015,6 @@ namespace Emby.Server.Implementations.Channels
{
item.RunTimeTicks = null;
}
-
else if (isNew || !enableMediaProbe)
{
item.RunTimeTicks = info.RunTimeTicks;
@@ -1025,26 +1047,24 @@ namespace Emby.Server.Implementations.Channels
}
}
- var hasArtists = item as IHasArtist;
- if (hasArtists != null)
+ if (item is IHasArtist hasArtists)
{
hasArtists.Artists = info.Artists.ToArray();
}
- var hasAlbumArtists = item as IHasAlbumArtist;
- if (hasAlbumArtists != null)
+ if (item is IHasAlbumArtist hasAlbumArtists)
{
hasAlbumArtists.AlbumArtists = info.AlbumArtists.ToArray();
}
- var trailer = item as Trailer;
- if (trailer != null)
+ if (item is Trailer trailer)
{
if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes))
{
_logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name);
forceUpdate = true;
}
+
trailer.TrailerTypes = info.TrailerTypes.ToArray();
}
@@ -1056,18 +1076,19 @@ namespace Emby.Server.Implementations.Channels
}
// was used for status
- //if (!string.Equals(item.ExternalEtag ?? string.Empty, info.Etag ?? string.Empty, StringComparison.Ordinal))
- //{
+ // if (!string.Equals(item.ExternalEtag ?? string.Empty, info.Etag ?? string.Empty, StringComparison.Ordinal))
+ // {
// item.ExternalEtag = info.Etag;
// forceUpdate = true;
// _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name);
- //}
+ // }
if (!internalChannelId.Equals(item.ChannelId))
{
forceUpdate = true;
_logger.LogDebug("Forcing update due to ChannelId {0}", item.Name);
}
+
item.ChannelId = internalChannelId;
if (!item.ParentId.Equals(parentFolderId))
@@ -1075,16 +1096,17 @@ namespace Emby.Server.Implementations.Channels
forceUpdate = true;
_logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name);
}
+
item.ParentId = parentFolderId;
- var hasSeries = item as IHasSeries;
- if (hasSeries != null)
+ if (item is IHasSeries hasSeries)
{
if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase))
{
forceUpdate = true;
_logger.LogDebug("Forcing update due to SeriesName {0}", item.Name);
}
+
hasSeries.SeriesName = info.SeriesName;
}
@@ -1093,24 +1115,23 @@ namespace Emby.Server.Implementations.Channels
forceUpdate = true;
_logger.LogDebug("Forcing update due to ExternalId {0}", item.Name);
}
+
item.ExternalId = info.Id;
- var channelAudioItem = item as Audio;
- if (channelAudioItem != null)
+ if (item is Audio channelAudioItem)
{
channelAudioItem.ExtraType = info.ExtraType;
var mediaSource = info.MediaSources.FirstOrDefault();
- item.Path = mediaSource == null ? null : mediaSource.Path;
+ item.Path = mediaSource?.Path;
}
- var channelVideoItem = item as Video;
- if (channelVideoItem != null)
+ if (item is Video channelVideoItem)
{
channelVideoItem.ExtraType = info.ExtraType;
var mediaSource = info.MediaSources.FirstOrDefault();
- item.Path = mediaSource == null ? null : mediaSource.Path;
+ item.Path = mediaSource?.Path;
}
if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary))
@@ -1152,24 +1173,24 @@ namespace Emby.Server.Implementations.Channels
}
else if (forceUpdate)
{
- item.UpdateToRepository(ItemUpdateType.None, cancellationToken);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
}
if ((isNew || forceUpdate) && info.Type == ChannelItemType.Media)
{
if (enableMediaProbe && !info.IsLiveStream && item.HasPathProtocol)
{
- SaveMediaSources(item, new List<MediaSourceInfo>());
+ await SaveMediaSources(item, new List<MediaSourceInfo>()).ConfigureAwait(false);
}
else
{
- SaveMediaSources(item, info.MediaSources);
+ await SaveMediaSources(item, info.MediaSources).ConfigureAwait(false);
}
}
- if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime))
+ if (isNew || forceUpdate || item.DateLastRefreshed == default)
{
- _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal);
+ _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
}
return item;
diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
index ad6c537ef..2391eed42 100644
--- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
+++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
@@ -9,21 +9,34 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Channels
{
+ /// <summary>
+ /// A task to remove all non-installed channels from the database.
+ /// </summary>
public class ChannelPostScanTask
{
private readonly IChannelManager _channelManager;
- private readonly IUserManager _userManager;
private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
- public ChannelPostScanTask(IChannelManager channelManager, IUserManager userManager, ILogger logger, ILibraryManager libraryManager)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelPostScanTask"/> class.
+ /// </summary>
+ /// <param name="channelManager">The channel manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ public ChannelPostScanTask(IChannelManager channelManager, ILogger logger, ILibraryManager libraryManager)
{
_channelManager = channelManager;
- _userManager = userManager;
_logger = logger;
_libraryManager = libraryManager;
}
+ /// <summary>
+ /// Runs this task.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The completed task.</returns>
public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
CleanDatabase(cancellationToken);
@@ -32,71 +45,55 @@ namespace Emby.Server.Implementations.Channels
return Task.CompletedTask;
}
- public static string GetUserDistinctValue(User user)
- {
- var channels = user.Policy.EnabledChannels
- .OrderBy(i => i)
- .ToList();
-
- return string.Join("|", channels.ToArray());
- }
-
private void CleanDatabase(CancellationToken cancellationToken)
{
var installedChannelIds = ((ChannelManager)_channelManager).GetInstalledChannelIds();
- var databaseIds = _libraryManager.GetItemIds(new InternalItemsQuery
+ var uninstalledChannels = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Channel).Name }
+ IncludeItemTypes = new[] { nameof(Channel) },
+ ExcludeItemIds = installedChannelIds.ToArray()
});
- var invalidIds = databaseIds
- .Except(installedChannelIds)
- .ToList();
-
- foreach (var id in invalidIds)
+ foreach (var channel in uninstalledChannels)
{
cancellationToken.ThrowIfCancellationRequested();
- CleanChannel(id, cancellationToken);
+ CleanChannel((Channel)channel, cancellationToken);
}
}
- private void CleanChannel(Guid id, CancellationToken cancellationToken)
+ private void CleanChannel(Channel channel, CancellationToken cancellationToken)
{
- _logger.LogInformation("Cleaning channel {0} from database", id);
+ _logger.LogInformation("Cleaning channel {0} from database", channel.Id);
// Delete all channel items
- var allIds = _libraryManager.GetItemIds(new InternalItemsQuery
+ var items = _libraryManager.GetItemList(new InternalItemsQuery
{
- ChannelIds = new[] { id }
+ ChannelIds = new[] { channel.Id }
});
- foreach (var deleteId in allIds)
+ foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
- DeleteItem(deleteId);
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
// Finally, delete the channel itself
- DeleteItem(id);
- }
-
- private void DeleteItem(Guid id)
- {
- var item = _libraryManager.GetItemById(id);
-
- if (item == null)
- {
- return;
- }
-
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = false
-
- }, false);
+ _libraryManager.DeleteItem(
+ channel,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
}
}
diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
index 303a8ac7b..e5dde48d8 100644
--- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
+++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
@@ -5,60 +5,84 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Channels
{
+ /// <summary>
+ /// The "Refresh Channels" scheduled task.
+ /// </summary>
public class RefreshChannelsScheduledTask : IScheduledTask, IConfigurableScheduledTask
{
private readonly IChannelManager _channelManager;
- private readonly IUserManager _userManager;
- private readonly ILogger _logger;
+ private readonly ILogger<RefreshChannelsScheduledTask> _logger;
private readonly ILibraryManager _libraryManager;
+ private readonly ILocalizationManager _localization;
- public RefreshChannelsScheduledTask(IChannelManager channelManager, IUserManager userManager, ILogger logger, ILibraryManager libraryManager)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshChannelsScheduledTask"/> class.
+ /// </summary>
+ /// <param name="channelManager">The channel manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="localization">The localization manager.</param>
+ public RefreshChannelsScheduledTask(
+ IChannelManager channelManager,
+ ILogger<RefreshChannelsScheduledTask> logger,
+ ILibraryManager libraryManager,
+ ILocalizationManager localization)
{
_channelManager = channelManager;
- _userManager = userManager;
_logger = logger;
_libraryManager = libraryManager;
+ _localization = localization;
}
- public string Name => "Refresh Channels";
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TasksRefreshChannels");
- public string Description => "Refreshes internet channel information.";
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TasksRefreshChannelsDescription");
- public string Category => "Internet Channels";
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksChannelsCategory");
+ /// <inheritdoc />
public bool IsHidden => ((ChannelManager)_channelManager).Channels.Length == 0;
+ /// <inheritdoc />
public bool IsEnabled => true;
+ /// <inheritdoc />
public bool IsLogged => true;
+ /// <inheritdoc />
+ public string Key => "RefreshInternetChannels";
+
+ /// <inheritdoc />
public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
var manager = (ChannelManager)_channelManager;
await manager.RefreshChannels(new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
- await new ChannelPostScanTask(_channelManager, _userManager, _logger, _libraryManager).Run(progress, cancellationToken)
+ await new ChannelPostScanTask(_channelManager, _logger, _libraryManager).Run(progress, cancellationToken)
.ConfigureAwait(false);
}
- /// <summary>
- /// Creates the triggers that define when the task will run
- /// </summary>
+ /// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
+ return new[]
+ {
// Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks
+ }
};
}
-
- public string Key => "RefreshInternetChannels";
}
}
diff --git a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs
index cdfb5cadf..ca8409402 100644
--- a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs
+++ b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs
@@ -1,4 +1,3 @@
-using System;
using System.Collections.Generic;
using System.Linq;
using Emby.Server.Implementations.Images;
@@ -14,8 +13,18 @@ using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Collections
{
+ /// <summary>
+ /// A collection image provider.
+ /// </summary>
public class CollectionImageProvider : BaseDynamicImageProvider<BoxSet>
{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionImageProvider"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="providerManager">The provider manager.</param>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="imageProcessor">The image processor.</param>
public CollectionImageProvider(
IFileSystem fileSystem,
IProviderManager providerManager,
@@ -25,6 +34,7 @@ namespace Emby.Server.Implementations.Collections
{
}
+ /// <inheritdoc />
protected override bool Supports(BaseItem item)
{
// Right now this is the only way to prevent this image from getting created ahead of internet image providers
@@ -36,7 +46,8 @@ namespace Emby.Server.Implementations.Collections
return base.Supports(item);
}
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var playlist = (BoxSet)item;
@@ -47,13 +58,10 @@ namespace Emby.Server.Implementations.Collections
var episode = subItem as Episode;
- if (episode != null)
+ var series = episode?.Series;
+ if (series != null && series.HasImage(ImageType.Primary))
{
- var series = episode.Series;
- if (series != null && series.HasImage(ImageType.Primary))
- {
- return series;
- }
+ return series;
}
if (subItem.HasImage(ImageType.Primary))
@@ -74,13 +82,13 @@ namespace Emby.Server.Implementations.Collections
return null;
})
.Where(i => i != null)
- .GroupBy(x => x.Id)
+ .GroupBy(x => x!.Id) // We removed the null values
.Select(x => x.First())
- .OrderBy(i => Guid.NewGuid())
- .ToList();
+ .ToList()!; // Again... the list doesn't contain any null values
}
- protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+ /// <inheritdoc />
+ protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
}
diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs
index 2b99e0ddf..79ef70fff 100644
--- a/Emby.Server.Implementations/Collections/CollectionManager.cs
+++ b/Emby.Server.Implementations/Collections/CollectionManager.cs
@@ -4,13 +4,12 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Collections;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
@@ -20,20 +19,29 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Collections
{
+ /// <summary>
+ /// The collection manager.
+ /// </summary>
public class CollectionManager : ICollectionManager
{
private readonly ILibraryManager _libraryManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _iLibraryMonitor;
- private readonly ILogger _logger;
+ private readonly ILogger<CollectionManager> _logger;
private readonly IProviderManager _providerManager;
private readonly ILocalizationManager _localizationManager;
- private IApplicationPaths _appPaths;
-
- public event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
- public event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
- public event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
-
+ private readonly IApplicationPaths _appPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionManager"/> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="appPaths">The application paths.</param>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="iLibraryMonitor">The library monitor.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="providerManager">The provider manager.</param>
public CollectionManager(
ILibraryManager libraryManager,
IApplicationPaths appPaths,
@@ -46,12 +54,21 @@ namespace Emby.Server.Implementations.Collections
_libraryManager = libraryManager;
_fileSystem = fileSystem;
_iLibraryMonitor = iLibraryMonitor;
- _logger = loggerFactory.CreateLogger(nameof(CollectionManager));
+ _logger = loggerFactory.CreateLogger<CollectionManager>();
_providerManager = providerManager;
_localizationManager = localizationManager;
_appPaths = appPaths;
}
+ /// <inheritdoc />
+ public event EventHandler<CollectionCreatedEventArgs>? CollectionCreated;
+
+ /// <inheritdoc />
+ public event EventHandler<CollectionModifiedEventArgs>? ItemsAddedToCollection;
+
+ /// <inheritdoc />
+ public event EventHandler<CollectionModifiedEventArgs>? ItemsRemovedFromCollection;
+
private IEnumerable<Folder> FindFolders(string path)
{
return _libraryManager
@@ -61,14 +78,12 @@ namespace Emby.Server.Implementations.Collections
.Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path));
}
- internal async Task<Folder> EnsureLibraryFolder(string path, bool createIfNeeded)
+ internal async Task<Folder?> EnsureLibraryFolder(string path, bool createIfNeeded)
{
- var existingFolders = FindFolders(path)
- .ToList();
-
- if (existingFolders.Count > 0)
+ var existingFolder = FindFolders(path).FirstOrDefault();
+ if (existingFolder != null)
{
- return existingFolders[0];
+ return existingFolder;
}
if (!createIfNeeded)
@@ -80,14 +95,14 @@ namespace Emby.Server.Implementations.Collections
var libraryOptions = new LibraryOptions
{
- PathInfos = new[] { new MediaPathInfo { Path = path } },
+ PathInfos = new[] { new MediaPathInfo(path) },
EnableRealtimeMonitor = false,
SaveLocalMetadata = true
};
var name = _localizationManager.GetLocalizedString("Collections");
- await _libraryManager.AddVirtualFolder(name, CollectionType.BoxSets, libraryOptions, true).ConfigureAwait(false);
+ await _libraryManager.AddVirtualFolder(name, CollectionTypeOptions.BoxSets, libraryOptions, true).ConfigureAwait(false);
return FindFolders(path).First();
}
@@ -97,21 +112,22 @@ namespace Emby.Server.Implementations.Collections
return Path.Combine(_appPaths.DataPath, "collections");
}
- private Task<Folder> GetCollectionsFolder(bool createIfNeeded)
+ private Task<Folder?> GetCollectionsFolder(bool createIfNeeded)
{
return EnsureLibraryFolder(GetCollectionsFolderPath(), createIfNeeded);
}
private IEnumerable<BoxSet> GetCollections(User user)
{
- var folder = GetCollectionsFolder(false).Result;
+ var folder = GetCollectionsFolder(false).GetAwaiter().GetResult();
- return folder == null ?
- new List<BoxSet>() :
- folder.GetChildren(user, true).OfType<BoxSet>();
+ return folder == null
+ ? Enumerable.Empty<BoxSet>()
+ : folder.GetChildren(user, true).OfType<BoxSet>();
}
- public BoxSet CreateCollection(CollectionCreationOptions options)
+ /// <inheritdoc />
+ public async Task<BoxSet> CreateCollectionAsync(CollectionCreationOptions options)
{
var name = options.Name;
@@ -120,7 +136,7 @@ namespace Emby.Server.Implementations.Collections
// This could cause it to get re-resolved as a plain folder
var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
- var parentFolder = GetCollectionsFolder(true).Result;
+ var parentFolder = await GetCollectionsFolder(true).ConfigureAwait(false);
if (parentFolder == null)
{
@@ -144,20 +160,24 @@ namespace Emby.Server.Implementations.Collections
DateCreated = DateTime.UtcNow
};
- parentFolder.AddChild(collection, CancellationToken.None);
+ parentFolder.AddChild(collection);
- if (options.ItemIdList.Length > 0)
+ if (options.ItemIdList.Count > 0)
{
- AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- // The initial adding of items is going to create a local metadata file
- // This will cause internet metadata to be skipped as a result
- MetadataRefreshMode = MetadataRefreshMode.FullRefresh
- });
+ await AddToCollectionAsync(
+ collection.Id,
+ options.ItemIdList.Select(x => new Guid(x)),
+ false,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ // The initial adding of items is going to create a local metadata file
+ // This will cause internet metadata to be skipped as a result
+ MetadataRefreshMode = MetadataRefreshMode.FullRefresh
+ }).ConfigureAwait(false);
}
else
{
- _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High);
+ _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
}
CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
@@ -175,21 +195,13 @@ namespace Emby.Server.Implementations.Collections
}
}
- public void AddToCollection(Guid collectionId, IEnumerable<string> ids)
- {
- AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
- }
-
- public void AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
- {
- AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
- }
+ /// <inheritdoc />
+ public Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds)
+ => AddToCollectionAsync(collectionId, itemIds, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
- private void AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
+ private async Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
{
- var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
-
- if (collection == null)
+ if (_libraryManager.GetItemById(collectionId) is not BoxSet collection)
{
throw new ArgumentException("No collection exists with the supplied Id");
}
@@ -202,15 +214,14 @@ namespace Emby.Server.Implementations.Collections
foreach (var id in ids)
{
- var guidId = new Guid(id);
- var item = _libraryManager.GetItemById(guidId);
+ var item = _libraryManager.GetItemById(id);
if (item == null)
{
throw new ArgumentException("No item exists with the supplied Id");
}
- if (!currentLinkedChildrenIds.Contains(guidId))
+ if (!currentLinkedChildrenIds.Contains(id))
{
itemList.Add(item);
@@ -227,32 +238,22 @@ namespace Emby.Server.Implementations.Collections
collection.UpdateRatingToItems(linkedChildrenList);
- collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
+ await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
refreshOptions.ForceSave = true;
_providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
if (fireEvent)
{
- ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
- {
- Collection = collection,
- ItemsChanged = itemList
- });
+ ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList));
}
}
}
- public void RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds)
+ /// <inheritdoc />
+ public async Task RemoveFromCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds)
{
- RemoveFromCollection(collectionId, itemIds.Select(i => new Guid(i)));
- }
-
- public void RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
- {
- var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
-
- if (collection == null)
+ if (_libraryManager.GetItemById(collectionId) is not BoxSet collection)
{
throw new ArgumentException("No collection exists with the supplied Id");
}
@@ -285,128 +286,77 @@ namespace Emby.Server.Implementations.Collections
collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
}
- collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- ForceSave = true
- }, RefreshPriority.High);
+ await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ _providerManager.QueueRefresh(
+ collection.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = true
+ },
+ RefreshPriority.High);
- ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
- {
- Collection = collection,
- ItemsChanged = itemList
- });
+ ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList));
}
+ /// <inheritdoc />
public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
{
var results = new Dictionary<Guid, BaseItem>();
- var allBoxsets = GetCollections(user).ToList();
+ var allBoxSets = GetCollections(user).ToList();
foreach (var item in items)
{
- var grouping = item as ISupportsBoxSetGrouping;
-
- if (grouping == null)
- {
- results[item.Id] = item;
- }
- else
+ if (item is ISupportsBoxSetGrouping)
{
var itemId = item.Id;
- var currentBoxSets = allBoxsets
- .Where(i => i.ContainsLinkedChildByItemId(itemId))
- .ToList();
-
- if (currentBoxSets.Count > 0)
+ var itemIsInBoxSet = false;
+ foreach (var boxSet in allBoxSets)
{
- foreach (var boxset in currentBoxSets)
+ if (!boxSet.ContainsLinkedChildByItemId(itemId))
{
- results[boxset.Id] = boxset;
+ continue;
}
- }
- else
- {
- results[item.Id] = item;
- }
- }
- }
- return results.Values;
- }
- }
+ itemIsInBoxSet = true;
- public class CollectionManagerEntryPoint : IServerEntryPoint
- {
- private readonly CollectionManager _collectionManager;
- private readonly IServerConfigurationManager _config;
- private ILogger _logger;
+ results.TryAdd(boxSet.Id, boxSet);
+ }
- public CollectionManagerEntryPoint(ICollectionManager collectionManager, IServerConfigurationManager config, ILogger logger)
- {
- _collectionManager = (CollectionManager)collectionManager;
- _config = config;
- _logger = logger;
- }
+ // skip any item that is in a box set
+ if (itemIsInBoxSet)
+ {
+ continue;
+ }
- public async Task RunAsync()
- {
- if (!_config.Configuration.CollectionsUpgraded && _config.Configuration.IsStartupWizardCompleted)
- {
- var path = _collectionManager.GetCollectionsFolderPath();
+ var alreadyInResults = false;
- if (Directory.Exists(path))
- {
- try
+ // this is kind of a performance hack because only Video has alternate versions that should be in a box set?
+ if (item is Video video)
{
- await _collectionManager.EnsureLibraryFolder(path, true).ConfigureAwait(false);
+ foreach (var childId in video.GetLocalAlternateVersionIds())
+ {
+ if (!results.ContainsKey(childId))
+ {
+ continue;
+ }
+
+ alreadyInResults = true;
+ break;
+ }
}
- catch (Exception ex)
+
+ if (alreadyInResults)
{
- _logger.LogError(ex, "Error creating camera uploads library");
+ continue;
}
-
- _config.Configuration.CollectionsUpgraded = true;
- _config.SaveConfiguration();
}
- }
- }
- #region IDisposable Support
- private bool disposedValue = false; // To detect redundant calls
-
- protected virtual void Dispose(bool disposing)
- {
- if (!disposedValue)
- {
- if (disposing)
- {
- // TODO: dispose managed state (managed objects).
- }
-
- // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
- // TODO: set large fields to null.
-
- disposedValue = true;
+ results[item.Id] = item;
}
- }
- // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
- // ~CollectionManagerEntryPoint() {
- // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- // Dispose(false);
- // }
-
- // This code added to correctly implement the disposable pattern.
- public void Dispose()
- {
- // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- Dispose(true);
- // TODO: uncomment the following line if the finalizer is overridden above.
- // GC.SuppressFinalize(this);
+ return results.Values;
}
- #endregion
}
}
diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
index 18e279c2f..ff5602f24 100644
--- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
+++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
@@ -1,12 +1,14 @@
+#nullable disable
+
using System;
-using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using Emby.Server.Implementations.AppBase;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
@@ -14,11 +16,10 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Configuration
{
/// <summary>
- /// Class ServerConfigurationManager
+ /// Class ServerConfigurationManager.
/// </summary>
public class ServerConfigurationManager : BaseConfigurationManager, IServerConfigurationManager
{
-
/// <summary>
/// Initializes a new instance of the <see cref="ServerConfigurationManager" /> class.
/// </summary>
@@ -32,6 +33,9 @@ namespace Emby.Server.Implementations.Configuration
UpdateMetadataPath();
}
+ /// <summary>
+ /// Configuration updating event.
+ /// </summary>
public event EventHandler<GenericEventArgs<ServerConfiguration>> ConfigurationUpdating;
/// <summary>
@@ -62,176 +66,59 @@ namespace Emby.Server.Implementations.Configuration
base.OnConfigurationUpdated();
}
- public override void AddParts(IEnumerable<IConfigurationFactory> factories)
- {
- base.AddParts(factories);
-
- UpdateTranscodingTempPath();
- }
-
/// <summary>
/// Updates the metadata path.
/// </summary>
+ /// <exception cref="UnauthorizedAccessException">If the directory does not exist, and the caller does not have the required permission to create it.</exception>
+ /// <exception cref="NotSupportedException">If there is a custom path transcoding path specified, but it is invalid.</exception>
+ /// <exception cref="IOException">If the directory does not exist, and it also could not be created.</exception>
private void UpdateMetadataPath()
{
- string metadataPath;
-
- if (string.IsNullOrWhiteSpace(Configuration.MetadataPath))
- {
- metadataPath = GetInternalMetadataPath();
- }
- else
- {
- metadataPath = Path.Combine(Configuration.MetadataPath, "metadata");
- }
-
- ((ServerApplicationPaths)ApplicationPaths).InternalMetadataPath = metadataPath;
- }
-
- private string GetInternalMetadataPath()
- {
- return Path.Combine(ApplicationPaths.ProgramDataPath, "metadata");
- }
-
- /// <summary>
- /// Updates the transcoding temporary path.
- /// </summary>
- private void UpdateTranscodingTempPath()
- {
- var encodingConfig = this.GetConfiguration<EncodingOptions>("encoding");
-
- ((ServerApplicationPaths)ApplicationPaths).TranscodingTempPath = string.IsNullOrEmpty(encodingConfig.TranscodingTempPath) ?
- null :
- Path.Combine(encodingConfig.TranscodingTempPath, "transcoding-temp");
- }
-
- protected override void OnNamedConfigurationUpdated(string key, object configuration)
- {
- base.OnNamedConfigurationUpdated(key, configuration);
-
- if (string.Equals(key, "encoding", StringComparison.OrdinalIgnoreCase))
- {
- UpdateTranscodingTempPath();
- }
+ ((ServerApplicationPaths)ApplicationPaths).InternalMetadataPath = string.IsNullOrWhiteSpace(Configuration.MetadataPath)
+ ? ApplicationPaths.DefaultInternalMetadataPath
+ : Configuration.MetadataPath;
+ Directory.CreateDirectory(ApplicationPaths.InternalMetadataPath);
}
/// <summary>
/// Replaces the configuration.
/// </summary>
/// <param name="newConfiguration">The new configuration.</param>
- /// <exception cref="DirectoryNotFoundException"></exception>
+ /// <exception cref="DirectoryNotFoundException">If the configuration path doesn't exist.</exception>
public override void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
{
var newConfig = (ServerConfiguration)newConfiguration;
ValidateMetadataPath(newConfig);
- ValidateSslCertificate(newConfig);
- ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig });
+ ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration>(newConfig));
base.ReplaceConfiguration(newConfiguration);
}
-
- /// <summary>
- /// Validates the SSL certificate.
- /// </summary>
- /// <param name="newConfig">The new configuration.</param>
- /// <exception cref="DirectoryNotFoundException"></exception>
- private void ValidateSslCertificate(BaseApplicationConfiguration newConfig)
- {
- var serverConfig = (ServerConfiguration)newConfig;
-
- var newPath = serverConfig.CertificatePath;
-
- if (!string.IsNullOrWhiteSpace(newPath)
- && !string.Equals(Configuration.CertificatePath ?? string.Empty, newPath))
- {
- // Validate
- if (!File.Exists(newPath))
- {
- throw new FileNotFoundException(string.Format("Certificate file '{0}' does not exist.", newPath));
- }
- }
- }
-
/// <summary>
/// Validates the metadata path.
/// </summary>
/// <param name="newConfig">The new configuration.</param>
- /// <exception cref="DirectoryNotFoundException"></exception>
+ /// <exception cref="DirectoryNotFoundException">The new config path doesn't exist.</exception>
private void ValidateMetadataPath(ServerConfiguration newConfig)
{
var newPath = newConfig.MetadataPath;
if (!string.IsNullOrWhiteSpace(newPath)
- && !string.Equals(Configuration.MetadataPath ?? string.Empty, newPath))
+ && !string.Equals(Configuration.MetadataPath, newPath, StringComparison.Ordinal))
{
- // Validate
if (!Directory.Exists(newPath))
{
- throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
+ throw new DirectoryNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} does not exist.",
+ newPath));
}
EnsureWriteAccess(newPath);
}
}
-
- public bool SetOptimalValues()
- {
- var config = Configuration;
-
- var changed = false;
-
- if (!config.EnableCaseSensitiveItemIds)
- {
- config.EnableCaseSensitiveItemIds = true;
- changed = true;
- }
-
- if (!config.SkipDeserializationForBasicTypes)
- {
- config.SkipDeserializationForBasicTypes = true;
- changed = true;
- }
-
- if (!config.EnableSimpleArtistDetection)
- {
- config.EnableSimpleArtistDetection = true;
- changed = true;
- }
-
- if (!config.EnableNormalizedItemByNameIds)
- {
- config.EnableNormalizedItemByNameIds = true;
- changed = true;
- }
-
- if (!config.DisableLiveTvChannelUserDataName)
- {
- config.DisableLiveTvChannelUserDataName = true;
- changed = true;
- }
-
- if (!config.EnableNewOmdbSupport)
- {
- config.EnableNewOmdbSupport = true;
- changed = true;
- }
-
- if (!config.CameraUploadUpgraded)
- {
- config.CameraUploadUpgraded = true;
- changed = true;
- }
-
- if (!config.CollectionsUpgraded)
- {
- config.CollectionsUpgraded = true;
- changed = true;
- }
-
- return changed;
- }
}
}
diff --git a/Emby.Server.Implementations/ConfigurationOptions.cs b/Emby.Server.Implementations/ConfigurationOptions.cs
index 30bfd8749..01dc728c1 100644
--- a/Emby.Server.Implementations/ConfigurationOptions.cs
+++ b/Emby.Server.Implementations/ConfigurationOptions.cs
@@ -1,12 +1,24 @@
using System.Collections.Generic;
+using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
namespace Emby.Server.Implementations
{
+ /// <summary>
+ /// Static class containing the default configuration options for the web server.
+ /// </summary>
public static class ConfigurationOptions
{
- public static readonly Dictionary<string, string> Configuration = new Dictionary<string, string>
+ /// <summary>
+ /// Gets a new copy of the default configuration options.
+ /// </summary>
+ public static Dictionary<string, string> DefaultConfiguration => new Dictionary<string, string>
{
- {"HttpListenerHost:DefaultRedirectPath", "web/index.html"}
+ { HostWebClientKey, bool.TrueString },
+ { DefaultRedirectKey, "web/index.html" },
+ { FfmpegProbeSizeKey, "1G" },
+ { FfmpegAnalyzeDurationKey, "200M" },
+ { PlaylistsAllowDuplicatesKey, bool.FalseString },
+ { BindToUnixSocketKey, bool.FalseString }
};
}
}
diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
index 09fdbc856..673810c49 100644
--- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
+++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
@@ -1,40 +1,94 @@
using System;
-using System.IO;
+using System.Collections.Generic;
using System.Security.Cryptography;
-using System.Text;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Cryptography;
+using static MediaBrowser.Common.Cryptography.Constants;
namespace Emby.Server.Implementations.Cryptography
{
+ /// <summary>
+ /// Class providing abstractions over cryptographic functions.
+ /// </summary>
public class CryptographyProvider : ICryptoProvider
{
- public Guid GetMD5(string str)
- {
- return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
- }
+ // FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto
+ // Currently supported hash methods from https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptoconfig?view=netcore-2.1
+ // there might be a better way to autogenerate this list as dotnet updates, but I couldn't find one
+ // Please note the default method of PBKDF2 is not included, it cannot be used to generate hashes cleanly as it is actually a pbkdf with sha1
+ private static readonly HashSet<string> _supportedHashMethods = new HashSet<string>()
+ {
+ "MD5",
+ "System.Security.Cryptography.MD5",
+ "SHA",
+ "SHA1",
+ "System.Security.Cryptography.SHA1",
+ "SHA256",
+ "SHA-256",
+ "System.Security.Cryptography.SHA256",
+ "SHA384",
+ "SHA-384",
+ "System.Security.Cryptography.SHA384",
+ "SHA512",
+ "SHA-512",
+ "System.Security.Cryptography.SHA512"
+ };
+
+ /// <inheritdoc />
+ public string DefaultHashMethod => "PBKDF2";
- public byte[] ComputeSHA1(byte[] bytes)
+ /// <inheritdoc />
+ public IEnumerable<string> GetSupportedHashMethods()
+ => _supportedHashMethods;
+
+ private byte[] PBKDF2(string method, byte[] bytes, byte[] salt, int iterations)
{
- using (var provider = SHA1.Create())
+ // downgrading for now as we need this library to be dotnetstandard compliant
+ // with this downgrade we'll add a check to make sure we're on the downgrade method at the moment
+ if (method != DefaultHashMethod)
{
- return provider.ComputeHash(bytes);
+ throw new CryptographicException($"Cannot currently use PBKDF2 with requested hash method: {method}");
}
+
+ using var r = new Rfc2898DeriveBytes(bytes, salt, iterations);
+ return r.GetBytes(32);
}
- public byte[] ComputeMD5(Stream str)
+ /// <inheritdoc />
+ public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt)
{
- using (var provider = MD5.Create())
+ if (hashMethod == DefaultHashMethod)
{
- return provider.ComputeHash(str);
+ return PBKDF2(hashMethod, bytes, salt, DefaultIterations);
}
- }
- public byte[] ComputeMD5(byte[] bytes)
- {
- using (var provider = MD5.Create())
+ if (!_supportedHashMethods.Contains(hashMethod))
{
- return provider.ComputeHash(bytes);
+ throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
}
+
+ using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException($"Unknown hash method: {hashMethod}.");
+ if (salt.Length == 0)
+ {
+ return h.ComputeHash(bytes);
+ }
+
+ byte[] salted = new byte[bytes.Length + salt.Length];
+ Array.Copy(bytes, salted, bytes.Length);
+ Array.Copy(salt, 0, salted, bytes.Length, salt.Length);
+ return h.ComputeHash(salted);
}
+
+ /// <inheritdoc />
+ public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt)
+ => PBKDF2(DefaultHashMethod, bytes, salt, DefaultIterations);
+
+ /// <inheritdoc />
+ public byte[] GenerateSalt()
+ => GenerateSalt(DefaultSaltLength);
+
+ /// <inheritdoc />
+ public byte[] GenerateSalt(int length)
+ => RandomNumberGenerator.GetBytes(length);
}
}
diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
index fba81306b..73c31f49d 100644
--- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
+++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
@@ -1,187 +1,166 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
-using SQLitePCL;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
public abstract class BaseSqliteRepository : IDisposable
{
- protected string DbFilePath { get; set; }
- protected ReaderWriterLockSlim WriteLock;
+ private bool _disposed = false;
- protected ILogger Logger { get; private set; }
-
- protected BaseSqliteRepository(ILogger logger)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseSqliteRepository"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ protected BaseSqliteRepository(ILogger<BaseSqliteRepository> logger)
{
Logger = logger;
-
- WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
- protected TransactionMode TransactionMode => TransactionMode.Deferred;
+ /// <summary>
+ /// Gets or sets the path to the DB file.
+ /// </summary>
+ /// <value>Path to the DB file.</value>
+ protected string DbFilePath { get; set; }
- protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
+ /// <summary>
+ /// Gets the logger.
+ /// </summary>
+ /// <value>The logger.</value>
+ protected ILogger<BaseSqliteRepository> Logger { get; }
- internal static int ThreadSafeMode { get; set; }
+ /// <summary>
+ /// Gets the default connection flags.
+ /// </summary>
+ /// <value>The default connection flags.</value>
+ protected virtual ConnectionFlags DefaultConnectionFlags => ConnectionFlags.NoMutex;
- static BaseSqliteRepository()
- {
- SQLite3.EnableSharedCache = false;
+ /// <summary>
+ /// Gets the transaction mode.
+ /// </summary>
+ /// <value>The transaction mode.</value>>
+ protected TransactionMode TransactionMode => TransactionMode.Deferred;
- int rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MEMSTATUS, 0);
- //CheckOk(rc);
+ /// <summary>
+ /// Gets the transaction mode for read-only operations.
+ /// </summary>
+ /// <value>The transaction mode.</value>
+ protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
- rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MULTITHREAD, 1);
- //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SINGLETHREAD, 1);
- //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SERIALIZED, 1);
- //CheckOk(rc);
+ /// <summary>
+ /// Gets the cache size.
+ /// </summary>
+ /// <value>The cache size or null.</value>
+ protected virtual int? CacheSize => null;
- rc = raw.sqlite3_enable_shared_cache(1);
+ /// <summary>
+ /// Gets the journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
+ /// </summary>
+ /// <value>The journal mode.</value>
+ protected virtual string JournalMode => "TRUNCATE";
- ThreadSafeMode = raw.sqlite3_threadsafe();
- }
+ /// <summary>
+ /// Gets the page size.
+ /// </summary>
+ /// <value>The page size or null.</value>
+ protected virtual int? PageSize => null;
+
+ /// <summary>
+ /// Gets the temp store mode.
+ /// </summary>
+ /// <value>The temp store mode.</value>
+ /// <see cref="TempStoreMode"/>
+ protected virtual TempStoreMode TempStore => TempStoreMode.Default;
- private static bool _versionLogged;
+ /// <summary>
+ /// Gets the synchronous mode.
+ /// </summary>
+ /// <value>The synchronous mode or null.</value>
+ /// <see cref="SynchronousMode"/>
+ protected virtual SynchronousMode? Synchronous => null;
- private string _defaultWal;
- protected ManagedConnection _connection;
+ /// <summary>
+ /// Gets or sets the write lock.
+ /// </summary>
+ /// <value>The write lock.</value>
+ protected SemaphoreSlim WriteLock { get; set; } = new SemaphoreSlim(1, 1);
- protected virtual bool EnableSingleConnection => true;
+ /// <summary>
+ /// Gets or sets the write connection.
+ /// </summary>
+ /// <value>The write connection.</value>
+ protected SQLiteDatabaseConnection WriteConnection { get; set; }
- protected ManagedConnection CreateConnection(bool isReadOnly = false)
+ protected ManagedConnection GetConnection(bool readOnly = false)
{
- if (_connection != null)
+ WriteLock.Wait();
+ if (WriteConnection != null)
{
- return _connection;
+ return new ManagedConnection(WriteConnection, WriteLock);
}
- lock (WriteLock)
- {
- if (!_versionLogged)
- {
- _versionLogged = true;
- Logger.LogInformation("Sqlite version: " + SQLite3.Version);
- Logger.LogInformation("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray()));
- }
-
- ConnectionFlags connectionFlags;
-
- if (isReadOnly)
- {
- //Logger.LogInformation("Opening read connection");
- //connectionFlags = ConnectionFlags.ReadOnly;
- connectionFlags = ConnectionFlags.Create;
- connectionFlags |= ConnectionFlags.ReadWrite;
- }
- else
- {
- //Logger.LogInformation("Opening write connection");
- connectionFlags = ConnectionFlags.Create;
- connectionFlags |= ConnectionFlags.ReadWrite;
- }
-
- if (EnableSingleConnection)
- {
- connectionFlags |= ConnectionFlags.PrivateCache;
- }
- else
- {
- connectionFlags |= ConnectionFlags.SharedCached;
- }
+ WriteConnection = SQLite3.Open(
+ DbFilePath,
+ DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
+ null);
- connectionFlags |= ConnectionFlags.NoMutex;
-
- var db = SQLite3.Open(DbFilePath, connectionFlags, null);
-
- try
- {
- if (string.IsNullOrWhiteSpace(_defaultWal))
- {
- _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
-
- Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
- }
-
- var queries = new List<string>
- {
- //"PRAGMA cache size=-10000"
- //"PRAGMA read_uncommitted = true",
- "PRAGMA synchronous=Normal"
- };
-
- if (CacheSize.HasValue)
- {
- queries.Add("PRAGMA cache_size=" + CacheSize.Value.ToString(CultureInfo.InvariantCulture));
- }
+ if (CacheSize.HasValue)
+ {
+ WriteConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
+ }
- if (EnableTempStoreMemory)
- {
- queries.Add("PRAGMA temp_store = memory");
- }
- else
- {
- queries.Add("PRAGMA temp_store = file");
- }
+ if (!string.IsNullOrWhiteSpace(JournalMode))
+ {
+ WriteConnection.Execute("PRAGMA journal_mode=" + JournalMode);
+ }
- foreach (var query in queries)
- {
- db.Execute(query);
- }
- }
- catch
- {
- using (db)
- {
+ if (Synchronous.HasValue)
+ {
+ WriteConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
+ }
- }
+ if (PageSize.HasValue)
+ {
+ WriteConnection.Execute("PRAGMA page_size=" + PageSize.Value);
+ }
- throw;
- }
+ WriteConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
- _connection = new ManagedConnection(db, false);
+ // Configuration and pragmas can affect VACUUM so it needs to be last.
+ WriteConnection.Execute("VACUUM");
- return _connection;
- }
+ return new ManagedConnection(WriteConnection, WriteLock);
}
public IStatement PrepareStatement(ManagedConnection connection, string sql)
- {
- return connection.PrepareStatement(sql);
- }
-
- public IStatement PrepareStatementSafe(ManagedConnection connection, string sql)
- {
- return connection.PrepareStatement(sql);
- }
+ => connection.PrepareStatement(sql);
public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
- {
- return connection.PrepareStatement(sql);
- }
-
- public IStatement PrepareStatementSafe(IDatabaseConnection connection, string sql)
- {
- return connection.PrepareStatement(sql);
- }
+ => connection.PrepareStatement(sql);
- public List<IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable<string> sql)
+ public IStatement[] PrepareAll(IDatabaseConnection connection, IReadOnlyList<string> sql)
{
- return PrepareAllSafe(connection, sql);
- }
+ int len = sql.Count;
+ IStatement[] statements = new IStatement[len];
+ for (int i = 0; i < len; i++)
+ {
+ statements[i] = connection.PrepareStatement(sql[i]);
+ }
- public List<IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable<string> sql)
- {
- return sql.Select(connection.PrepareStatement).ToList();
+ return statements;
}
protected bool TableExists(ManagedConnection connection, string name)
{
- return connection.RunInTransaction(db =>
+ return connection.RunInTransaction(
+ db =>
{
using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
{
@@ -195,44 +174,34 @@ namespace Emby.Server.Implementations.Data
}
return false;
-
}, ReadTransactionMode);
}
- protected void RunDefaultInitialization(ManagedConnection db)
+ protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
{
- var queries = new List<string>
- {
- "PRAGMA journal_mode=WAL",
- "PRAGMA page_size=4096",
- "PRAGMA synchronous=Normal"
- };
+ var columnNames = new List<string>();
- if (EnableTempStoreMemory)
- {
- queries.AddRange(new List<string>
- {
- "pragma default_temp_store = memory",
- "pragma temp_store = memory"
- });
- }
- else
+ foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
{
- queries.AddRange(new List<string>
+ if (row.TryGetString(1, out var columnName))
{
- "pragma temp_store = file"
- });
+ columnNames.Add(columnName);
+ }
}
- db.ExecuteAll(string.Join(";", queries));
- Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
+ return columnNames;
}
- protected virtual bool EnableTempStoreMemory => false;
+ protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
+ {
+ if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
+ {
+ return;
+ }
- protected virtual int? CacheSize => null;
+ connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
+ }
- private bool _disposed;
protected void CheckDisposed()
{
if (_disposed)
@@ -241,139 +210,43 @@ namespace Emby.Server.Implementations.Data
}
}
+ /// <inheritdoc />
public void Dispose()
{
- _disposed = true;
Dispose(true);
+ GC.SuppressFinalize(this);
}
- private readonly object _disposeLock = new object();
-
/// <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)
- {
- DisposeConnection();
- }
- }
-
- private void DisposeConnection()
- {
- try
- {
- lock (_disposeLock)
- {
- using (WriteLock.Write())
- {
- if (_connection != null)
- {
- using (_connection)
- {
- _connection.Close();
- }
- _connection = null;
- }
-
- CloseConnection();
- }
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error disposing database");
- }
- }
-
- protected virtual void CloseConnection()
- {
-
- }
-
- protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
- {
- var list = new List<string>();
-
- foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
- {
- if (row[1].SQLiteType != SQLiteType.Null)
- {
- var name = row[1].ToString();
-
- list.Add(name);
- }
- }
-
- return list;
- }
-
- protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
- {
- if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
+ if (_disposed)
{
return;
}
- connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
- }
- }
-
- public static class ReaderWriterLockSlimExtensions
- {
- private sealed class ReadLockToken : IDisposable
- {
- private ReaderWriterLockSlim _sync;
- public ReadLockToken(ReaderWriterLockSlim sync)
- {
- _sync = sync;
- sync.EnterReadLock();
- }
- public void Dispose()
+ if (dispose)
{
- if (_sync != null)
+ WriteLock.Wait();
+ try
{
- _sync.ExitReadLock();
- _sync = null;
+ WriteConnection?.Dispose();
}
- }
- }
- private sealed class WriteLockToken : IDisposable
- {
- private ReaderWriterLockSlim _sync;
- public WriteLockToken(ReaderWriterLockSlim sync)
- {
- _sync = sync;
- sync.EnterWriteLock();
- }
- public void Dispose()
- {
- if (_sync != null)
+ finally
{
- _sync.ExitWriteLock();
- _sync = null;
+ WriteLock.Release();
}
+
+ WriteLock.Dispose();
}
- }
- public static IDisposable Read(this ReaderWriterLockSlim obj)
- {
- //if (BaseSqliteRepository.ThreadSafeMode > 0)
- //{
- // return new DummyToken();
- //}
- return new WriteLockToken(obj);
- }
+ WriteConnection = null;
+ WriteLock = null;
- public static IDisposable Write(this ReaderWriterLockSlim obj)
- {
- //if (BaseSqliteRepository.ThreadSafeMode > 0)
- //{
- // return new DummyToken();
- //}
- return new WriteLockToken(obj);
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
index f7743a3c2..3de9d6371 100644
--- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
+++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -10,9 +12,9 @@ namespace Emby.Server.Implementations.Data
public class CleanDatabaseScheduledTask : ILibraryPostScanTask
{
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<CleanDatabaseScheduledTask> _logger;
- public CleanDatabaseScheduledTask(ILibraryManager libraryManager, ILogger logger)
+ public CleanDatabaseScheduledTask(ILibraryManager libraryManager, ILogger<CleanDatabaseScheduledTask> logger)
{
_libraryManager = libraryManager;
_logger = logger;
@@ -49,7 +51,6 @@ namespace Emby.Server.Implementations.Data
_libraryManager.DeleteItem(item, new DeleteOptions
{
DeleteFileLocation = false
-
});
}
diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs
index b8f1e581a..44dad5b17 100644
--- a/Emby.Server.Implementations/Data/ManagedConnection.cs
+++ b/Emby.Server.Implementations/Data/ManagedConnection.cs
@@ -1,79 +1,82 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Threading;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
public class ManagedConnection : IDisposable
{
- private SQLiteDatabaseConnection db;
- private readonly bool _closeOnDispose;
+ private readonly SemaphoreSlim _writeLock;
+
+ private SQLiteDatabaseConnection? _db;
+
+ private bool _disposed = false;
- public ManagedConnection(SQLiteDatabaseConnection db, bool closeOnDispose)
+ public ManagedConnection(SQLiteDatabaseConnection db, SemaphoreSlim writeLock)
{
- this.db = db;
- _closeOnDispose = closeOnDispose;
+ _db = db;
+ _writeLock = writeLock;
}
public IStatement PrepareStatement(string sql)
{
- return db.PrepareStatement(sql);
+ return _db.PrepareStatement(sql);
}
public IEnumerable<IStatement> PrepareAll(string sql)
{
- return db.PrepareAll(sql);
+ return _db.PrepareAll(sql);
}
public void ExecuteAll(string sql)
{
- db.ExecuteAll(sql);
+ _db.ExecuteAll(sql);
}
public void Execute(string sql, params object[] values)
{
- db.Execute(sql, values);
+ _db.Execute(sql, values);
}
public void RunQueries(string[] sql)
{
- db.RunQueries(sql);
+ _db.RunQueries(sql);
}
public void RunInTransaction(Action<IDatabaseConnection> action, TransactionMode mode)
{
- db.RunInTransaction(action, mode);
+ _db.RunInTransaction(action, mode);
}
public T RunInTransaction<T>(Func<IDatabaseConnection, T> action, TransactionMode mode)
{
- return db.RunInTransaction(action, mode);
+ return _db.RunInTransaction(action, mode);
}
- public IEnumerable<IReadOnlyList<IResultSetValue>> Query(string sql)
+ public IEnumerable<IReadOnlyList<ResultSetValue>> Query(string sql)
{
- return db.Query(sql);
+ return _db.Query(sql);
}
- public IEnumerable<IReadOnlyList<IResultSetValue>> Query(string sql, params object[] values)
+ public IEnumerable<IReadOnlyList<ResultSetValue>> Query(string sql, params object[] values)
{
- return db.Query(sql, values);
- }
-
- public void Close()
- {
- using (db)
- {
-
- }
+ return _db.Query(sql, values);
}
public void Dispose()
{
- if (_closeOnDispose)
+ if (_disposed)
{
- Close();
+ return;
}
+
+ _writeLock.Release();
+
+ _db = null; // Don't dispose it
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
deleted file mode 100644
index 3d60925da..000000000
--- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
+++ /dev/null
@@ -1,248 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-using SQLitePCL.pretty;
-
-namespace Emby.Server.Implementations.Data
-{
- /// <summary>
- /// Class SQLiteDisplayPreferencesRepository
- /// </summary>
- public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository
- {
- protected IFileSystem FileSystem { get; private set; }
-
- public SqliteDisplayPreferencesRepository(ILoggerFactory loggerFactory, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IFileSystem fileSystem)
- : base(loggerFactory.CreateLogger(nameof(SqliteDisplayPreferencesRepository)))
- {
- _jsonSerializer = jsonSerializer;
- FileSystem = fileSystem;
- DbFilePath = Path.Combine(appPaths.DataPath, "displaypreferences.db");
- }
-
- /// <summary>
- /// Gets the name of the repository
- /// </summary>
- /// <value>The name.</value>
- public string Name => "SQLite";
-
- /// <summary>
- /// The _json serializer
- /// </summary>
- private readonly IJsonSerializer _jsonSerializer;
-
- public void Initialize()
- {
- try
- {
- InitializeInternal();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error loading database file. Will reset and retry.");
-
- FileSystem.DeleteFile(DbFilePath);
-
- InitializeInternal();
- }
- }
-
- /// <summary>
- /// Opens the connection to the database
- /// </summary>
- /// <returns>Task.</returns>
- private void InitializeInternal()
- {
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- string[] queries = {
-
- "create table if not exists userdisplaypreferences (id GUID NOT NULL, userId GUID NOT NULL, client text NOT NULL, data BLOB NOT NULL)",
- "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)"
- };
-
- connection.RunQueries(queries);
- }
- }
-
- /// <summary>
- /// Save the display preferences associated with an item in the repo
- /// </summary>
- /// <param name="displayPreferences">The display preferences.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="client">The client.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
- {
- if (displayPreferences == null)
- {
- throw new ArgumentNullException(nameof(displayPreferences));
- }
- if (string.IsNullOrEmpty(displayPreferences.Id))
- {
- throw new ArgumentNullException(nameof(displayPreferences.Id));
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- SaveDisplayPreferences(displayPreferences, userId, client, db);
- }, TransactionMode);
- }
- }
- }
-
- private void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, IDatabaseConnection connection)
- {
- var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
-
- using (var statement = connection.PrepareStatement("replace into userdisplaypreferences (id, userid, client, data) values (@id, @userId, @client, @data)"))
- {
- statement.TryBind("@id", displayPreferences.Id.ToGuidBlob());
- statement.TryBind("@userId", userId.ToGuidBlob());
- statement.TryBind("@client", client);
- statement.TryBind("@data", serialized);
-
- statement.MoveNext();
- }
- }
-
- /// <summary>
- /// Save all display preferences associated with a user in the repo
- /// </summary>
- /// <param name="displayPreferences">The display preferences.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public void SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId, CancellationToken cancellationToken)
- {
- if (displayPreferences == null)
- {
- throw new ArgumentNullException(nameof(displayPreferences));
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- foreach (var displayPreference in displayPreferences)
- {
- SaveDisplayPreferences(displayPreference, userId, displayPreference.Client, db);
- }
- }, TransactionMode);
- }
- }
- }
-
- /// <summary>
- /// Gets the display preferences.
- /// </summary>
- /// <param name="displayPreferencesId">The display preferences id.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="client">The client.</param>
- /// <returns>Task{DisplayPreferences}.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, Guid userId, string client)
- {
- if (string.IsNullOrEmpty(displayPreferencesId))
- {
- throw new ArgumentNullException(nameof(displayPreferencesId));
- }
-
- var guidId = displayPreferencesId.GetMD5();
-
- using (WriteLock.Read())
- {
- using (var connection = CreateConnection(true))
- {
- using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where id = @id and userId=@userId and client=@client"))
- {
- statement.TryBind("@id", guidId.ToGuidBlob());
- statement.TryBind("@userId", userId.ToGuidBlob());
- statement.TryBind("@client", client);
-
- foreach (var row in statement.ExecuteQuery())
- {
- return Get(row);
- }
- }
-
- return new DisplayPreferences
- {
- Id = guidId.ToString("N")
- };
- }
- }
- }
-
- /// <summary>
- /// Gets all display preferences for the given user.
- /// </summary>
- /// <param name="userId">The user id.</param>
- /// <returns>Task{DisplayPreferences}.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId)
- {
- var list = new List<DisplayPreferences>();
-
- using (WriteLock.Read())
- {
- using (var connection = CreateConnection(true))
- {
- using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId"))
- {
- statement.TryBind("@userId", userId.ToGuidBlob());
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(Get(row));
- }
- }
- }
- }
-
- return list;
- }
-
- private DisplayPreferences Get(IReadOnlyList<IResultSetValue> row)
- {
- using (var stream = new MemoryStream(row[0].ToBlob()))
- {
- stream.Position = 0;
- return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
- }
- }
-
- public void SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken)
- {
- SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken);
- }
-
- public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client)
- {
- return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs
index a486cb1a0..381eb92a8 100644
--- a/Emby.Server.Implementations/Data/SqliteExtensions.cs
+++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs
@@ -1,14 +1,57 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
-using System.IO;
-using MediaBrowser.Model.Serialization;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
public static class SqliteExtensions
{
+ private const string DatetimeFormatUtc = "yyyy-MM-dd HH:mm:ss.FFFFFFFK";
+ private const string DatetimeFormatLocal = "yyyy-MM-dd HH:mm:ss.FFFFFFF";
+
+ /// <summary>
+ /// An array of ISO-8601 DateTime formats that we support parsing.
+ /// </summary>
+ private static readonly string[] _datetimeFormats = new string[]
+ {
+ "THHmmssK",
+ "THHmmK",
+ "HH:mm:ss.FFFFFFFK",
+ "HH:mm:ssK",
+ "HH:mmK",
+ DatetimeFormatUtc,
+ "yyyy-MM-dd HH:mm:ssK",
+ "yyyy-MM-dd HH:mmK",
+ "yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
+ "yyyy-MM-ddTHH:mmK",
+ "yyyy-MM-ddTHH:mm:ssK",
+ "yyyyMMddHHmmssK",
+ "yyyyMMddHHmmK",
+ "yyyyMMddTHHmmssFFFFFFFK",
+ "THHmmss",
+ "THHmm",
+ "HH:mm:ss.FFFFFFF",
+ "HH:mm:ss",
+ "HH:mm",
+ DatetimeFormatLocal,
+ "yyyy-MM-dd HH:mm:ss",
+ "yyyy-MM-dd HH:mm",
+ "yyyy-MM-ddTHH:mm:ss.FFFFFFF",
+ "yyyy-MM-ddTHH:mm",
+ "yyyy-MM-ddTHH:mm:ss",
+ "yyyyMMddHHmmss",
+ "yyyyMMddHHmm",
+ "yyyyMMddTHHmmssFFFFFFF",
+ "yyyy-MM-dd",
+ "yyyyMMdd",
+ "yy-MM-dd"
+ };
+
public static void RunQueries(this SQLiteDatabaseConnection connection, string[] queries)
{
if (queries == null)
@@ -18,25 +61,11 @@ namespace Emby.Server.Implementations.Data
connection.RunInTransaction(conn =>
{
- //foreach (var query in queries)
- //{
- // conn.Execute(query);
- //}
- conn.ExecuteAll(string.Join(";", queries));
+ conn.ExecuteAll(string.Join(';', queries));
});
}
- public static byte[] ToGuidBlob(this string str)
- {
- return ToGuidBlob(new Guid(str));
- }
-
- public static byte[] ToGuidBlob(this Guid guid)
- {
- return guid.ToByteArray();
- }
-
- public static Guid ReadGuidFromBlob(this IResultSetValue result)
+ public static Guid ReadGuidFromBlob(this ResultSetValue result)
{
return new Guid(result.ToBlob());
}
@@ -54,147 +83,161 @@ namespace Emby.Server.Implementations.Data
CultureInfo.InvariantCulture);
}
- private static string GetDateTimeKindFormat(
- DateTimeKind kind)
- {
- return (kind == DateTimeKind.Utc) ? _datetimeFormatUtc : _datetimeFormatLocal;
- }
+ private static string GetDateTimeKindFormat(DateTimeKind kind)
+ => (kind == DateTimeKind.Utc) ? DatetimeFormatUtc : DatetimeFormatLocal;
- /// <summary>
- /// An array of ISO-8601 DateTime formats that we support parsing.
- /// </summary>
- private static string[] _datetimeFormats = new string[] {
- "THHmmssK",
- "THHmmK",
- "HH:mm:ss.FFFFFFFK",
- "HH:mm:ssK",
- "HH:mmK",
- "yyyy-MM-dd HH:mm:ss.FFFFFFFK", /* NOTE: UTC default (5). */
- "yyyy-MM-dd HH:mm:ssK",
- "yyyy-MM-dd HH:mmK",
- "yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
- "yyyy-MM-ddTHH:mmK",
- "yyyy-MM-ddTHH:mm:ssK",
- "yyyyMMddHHmmssK",
- "yyyyMMddHHmmK",
- "yyyyMMddTHHmmssFFFFFFFK",
- "THHmmss",
- "THHmm",
- "HH:mm:ss.FFFFFFF",
- "HH:mm:ss",
- "HH:mm",
- "yyyy-MM-dd HH:mm:ss.FFFFFFF", /* NOTE: Non-UTC default (19). */
- "yyyy-MM-dd HH:mm:ss",
- "yyyy-MM-dd HH:mm",
- "yyyy-MM-ddTHH:mm:ss.FFFFFFF",
- "yyyy-MM-ddTHH:mm",
- "yyyy-MM-ddTHH:mm:ss",
- "yyyyMMddHHmmss",
- "yyyyMMddHHmm",
- "yyyyMMddTHHmmssFFFFFFF",
- "yyyy-MM-dd",
- "yyyyMMdd",
- "yy-MM-dd"
- };
-
- private static string _datetimeFormatUtc = _datetimeFormats[5];
- private static string _datetimeFormatLocal = _datetimeFormats[19];
-
- public static DateTime ReadDateTime(this IResultSetValue result)
+ public static DateTime ReadDateTime(this ResultSetValue result)
{
var dateText = result.ToString();
return DateTime.ParseExact(
- dateText, _datetimeFormats,
+ dateText,
+ _datetimeFormats,
DateTimeFormatInfo.InvariantInfo,
- DateTimeStyles.None).ToUniversalTime();
+ DateTimeStyles.AdjustToUniversal);
}
- public static DateTime? TryReadDateTime(this IResultSetValue result)
+ public static bool TryReadDateTime(this IReadOnlyList<ResultSetValue> reader, int index, out DateTime result)
{
- var dateText = result.ToString();
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ var dateText = item.ToString();
- if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var dateTimeResult))
+ if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out var dateTimeResult))
{
- return dateTimeResult.ToUniversalTime();
+ result = dateTimeResult;
+ return true;
}
- return null;
+ result = default;
+ return false;
}
- /// <summary>
- /// Serializes to bytes.
- /// </summary>
- /// <returns>System.Byte[][].</returns>
- /// <exception cref="ArgumentNullException">obj</exception>
- public static byte[] SerializeToBytes(this IJsonSerializer json, object obj)
+ public static bool TryGetGuid(this IReadOnlyList<ResultSetValue> reader, int index, out Guid result)
{
- if (obj == null)
+ var item = reader[index];
+ if (item.IsDbNull())
{
- throw new ArgumentNullException(nameof(obj));
+ result = default;
+ return false;
}
- using (var stream = new MemoryStream())
- {
- json.SerializeToStream(obj, stream);
- return stream.ToArray();
- }
+ result = item.ReadGuidFromBlob();
+ return true;
}
- public static void Attach(ManagedConnection db, string path, string alias)
+ public static bool IsDbNull(this ResultSetValue result)
{
- var commandText = string.Format("attach @path as {0};", alias);
+ return result.SQLiteType == SQLiteType.Null;
+ }
- using (var statement = db.PrepareStatement(commandText))
+ public static string GetString(this IReadOnlyList<ResultSetValue> result, int index)
+ {
+ return result[index].ToString();
+ }
+
+ public static bool TryGetString(this IReadOnlyList<ResultSetValue> reader, int index, out string result)
+ {
+ result = null;
+ var item = reader[index];
+ if (item.IsDbNull())
{
- statement.TryBind("@path", path);
- statement.MoveNext();
+ return false;
}
+
+ result = item.ToString();
+ return true;
}
- public static bool IsDBNull(this IReadOnlyList<IResultSetValue> result, int index)
+ public static bool GetBoolean(this IReadOnlyList<ResultSetValue> result, int index)
{
- return result[index].SQLiteType == SQLiteType.Null;
+ return result[index].ToBool();
}
- public static string GetString(this IReadOnlyList<IResultSetValue> result, int index)
+ public static bool TryGetBoolean(this IReadOnlyList<ResultSetValue> reader, int index, out bool result)
{
- return result[index].ToString();
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ result = item.ToBool();
+ return true;
}
- public static bool GetBoolean(this IReadOnlyList<IResultSetValue> result, int index)
+ public static bool TryGetInt32(this IReadOnlyList<ResultSetValue> reader, int index, out int result)
{
- return result[index].ToBool();
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ result = item.ToInt();
+ return true;
}
- public static int GetInt32(this IReadOnlyList<IResultSetValue> result, int index)
+ public static long GetInt64(this IReadOnlyList<ResultSetValue> result, int index)
{
- return result[index].ToInt();
+ return result[index].ToInt64();
}
- public static long GetInt64(this IReadOnlyList<IResultSetValue> result, int index)
+ public static bool TryGetInt64(this IReadOnlyList<ResultSetValue> reader, int index, out long result)
{
- return result[index].ToInt64();
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ result = item.ToInt64();
+ return true;
+ }
+
+ public static bool TryGetSingle(this IReadOnlyList<ResultSetValue> reader, int index, out float result)
+ {
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ result = item.ToFloat();
+ return true;
}
- public static float GetFloat(this IReadOnlyList<IResultSetValue> result, int index)
+ public static bool TryGetDouble(this IReadOnlyList<ResultSetValue> reader, int index, out double result)
{
- return result[index].ToFloat();
+ var item = reader[index];
+ if (item.IsDbNull())
+ {
+ result = default;
+ return false;
+ }
+
+ result = item.ToDouble();
+ return true;
}
- public static Guid GetGuid(this IReadOnlyList<IResultSetValue> result, int index)
+ public static Guid GetGuid(this IReadOnlyList<ResultSetValue> result, int index)
{
return result[index].ReadGuidFromBlob();
}
+ [Conditional("DEBUG")]
private static void CheckName(string name)
{
-#if DEBUG
- //if (!name.IndexOf("@", StringComparison.OrdinalIgnoreCase) != 0)
- {
- throw new Exception("Invalid param name: " + name);
- }
-#endif
+ throw new ArgumentException("Invalid param name: " + name, nameof(name));
}
public static void TryBind(this IStatement statement, string name, double value)
@@ -268,7 +311,9 @@ namespace Emby.Server.Implementations.Data
{
if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam))
{
- bindParam.Bind(value.ToGuidBlob());
+ Span<byte> byteValue = stackalloc byte[16];
+ value.TryWriteBytes(byteValue);
+ bindParam.Bind(byteValue);
}
else
{
@@ -300,7 +345,7 @@ namespace Emby.Server.Implementations.Data
}
}
- public static void TryBind(this IStatement statement, string name, byte[] value)
+ public static void TryBind(this IStatement statement, string name, ReadOnlySpan<byte> value)
{
if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam))
{
@@ -396,12 +441,11 @@ namespace Emby.Server.Implementations.Data
}
}
- public static IEnumerable<IReadOnlyList<IResultSetValue>> ExecuteQuery(
- this IStatement This)
+ public static IEnumerable<IReadOnlyList<ResultSetValue>> ExecuteQuery(this IStatement statement)
{
- while (This.MoveNext())
+ while (statement.MoveNext())
{
- yield return This.Current;
+ yield return statement.Current;
}
}
}
diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
index 6502e4aed..13f1df7c8 100644
--- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
@@ -1,12 +1,21 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Buffers.Text;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Runtime.Serialization;
using System.Text;
+using System.Text.Json;
using System.Threading;
+using Diacritics.Extensions;
using Emby.Server.Implementations.Playlists;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
@@ -15,123 +24,445 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Reflection;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
/// <summary>
- /// Class SQLiteItemRepository
+ /// Class SQLiteItemRepository.
/// </summary>
public class SqliteItemRepository : BaseSqliteRepository, IItemRepository
{
+ private const string FromText = " from TypedBaseItems A";
+ private const string ChaptersTableName = "Chapters2";
+
+ private const string SaveItemCommandText =
+ @"replace into TypedBaseItems
+ (guid,type,data,Path,StartDate,EndDate,ChannelId,IsMovie,IsSeries,EpisodeTitle,IsRepeat,CommunityRating,CustomRating,IndexNumber,IsLocked,Name,OfficialRating,MediaType,Overview,ParentIndexNumber,PremiereDate,ProductionYear,ParentId,Genres,InheritedParentalRatingValue,SortName,ForcedSortName,RunTimeTicks,Size,DateCreated,DateModified,PreferredMetadataLanguage,PreferredMetadataCountryCode,Width,Height,DateLastRefreshed,DateLastSaved,IsInMixedFolder,LockedFields,Studios,Audio,ExternalServiceId,Tags,IsFolder,UnratedType,TopParentId,TrailerTypes,CriticRating,CleanName,PresentationUniqueKey,OriginalTitle,PrimaryVersionId,DateLastMediaAdded,Album,IsVirtualItem,SeriesName,UserDataKey,SeasonName,SeasonId,SeriesId,ExternalSeriesId,Tagline,ProviderIds,Images,ProductionLocations,ExtraIds,TotalBitrate,ExtraType,Artists,AlbumArtists,ExternalId,SeriesPresentationUniqueKey,ShowId,OwnerId)
+ values (@guid,@type,@data,@Path,@StartDate,@EndDate,@ChannelId,@IsMovie,@IsSeries,@EpisodeTitle,@IsRepeat,@CommunityRating,@CustomRating,@IndexNumber,@IsLocked,@Name,@OfficialRating,@MediaType,@Overview,@ParentIndexNumber,@PremiereDate,@ProductionYear,@ParentId,@Genres,@InheritedParentalRatingValue,@SortName,@ForcedSortName,@RunTimeTicks,@Size,@DateCreated,@DateModified,@PreferredMetadataLanguage,@PreferredMetadataCountryCode,@Width,@Height,@DateLastRefreshed,@DateLastSaved,@IsInMixedFolder,@LockedFields,@Studios,@Audio,@ExternalServiceId,@Tags,@IsFolder,@UnratedType,@TopParentId,@TrailerTypes,@CriticRating,@CleanName,@PresentationUniqueKey,@OriginalTitle,@PrimaryVersionId,@DateLastMediaAdded,@Album,@IsVirtualItem,@SeriesName,@UserDataKey,@SeasonName,@SeasonId,@SeriesId,@ExternalSeriesId,@Tagline,@ProviderIds,@Images,@ProductionLocations,@ExtraIds,@TotalBitrate,@ExtraType,@Artists,@AlbumArtists,@ExternalId,@SeriesPresentationUniqueKey,@ShowId,@OwnerId)";
+
+ private readonly IServerConfigurationManager _config;
+ private readonly IServerApplicationHost _appHost;
+ private readonly ILocalizationManager _localization;
+ // TODO: Remove this dependency. GetImageCacheTag() is the only method used and it can be converted to a static helper method
+ private readonly IImageProcessor _imageProcessor;
+
private readonly TypeMapper _typeMapper;
+ private readonly JsonSerializerOptions _jsonOptions;
- /// <summary>
- /// Gets the name of the repository
- /// </summary>
- /// <value>The name.</value>
- public string Name => "SQLite";
+ private readonly ItemFields[] _allItemFields = Enum.GetValues<ItemFields>();
- /// <summary>
- /// Gets the json serializer.
- /// </summary>
- /// <value>The json serializer.</value>
- private readonly IJsonSerializer _jsonSerializer;
+ private static readonly string[] _retriveItemColumns =
+ {
+ "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",
+ "guid",
+ "Genres",
+ "ParentId",
+ "Audio",
+ "ExternalServiceId",
+ "IsInMixedFolder",
+ "DateLastSaved",
+ "LockedFields",
+ "Studios",
+ "Tags",
+ "TrailerTypes",
+ "OriginalTitle",
+ "PrimaryVersionId",
+ "DateLastMediaAdded",
+ "Album",
+ "CriticRating",
+ "IsVirtualItem",
+ "SeriesName",
+ "SeasonName",
+ "SeasonId",
+ "SeriesId",
+ "PresentationUniqueKey",
+ "InheritedParentalRatingValue",
+ "ExternalSeriesId",
+ "Tagline",
+ "ProviderIds",
+ "Images",
+ "ProductionLocations",
+ "ExtraIds",
+ "TotalBitrate",
+ "ExtraType",
+ "Artists",
+ "AlbumArtists",
+ "ExternalId",
+ "SeriesPresentationUniqueKey",
+ "ShowId",
+ "OwnerId"
+ };
- /// <summary>
- /// The _app paths
- /// </summary>
- private readonly IServerConfigurationManager _config;
- private IServerApplicationHost _appHost;
+ private static readonly string _retriveItemColumnsSelectQuery = $"select {string.Join(',', _retriveItemColumns)} from TypedBaseItems where guid = @guid";
+
+ private static readonly string[] _mediaStreamSaveColumns =
+ {
+ "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"
+ };
+
+ private static readonly string _mediaStreamSaveColumnsInsertQuery =
+ $"insert into mediastreams ({string.Join(',', _mediaStreamSaveColumns)}) values ";
+
+ private static readonly string _mediaStreamSaveColumnsSelectQuery =
+ $"select {string.Join(',', _mediaStreamSaveColumns)} from mediastreams where ItemId=@ItemId";
+
+ private static readonly string[] _mediaAttachmentSaveColumns =
+ {
+ "ItemId",
+ "AttachmentIndex",
+ "Codec",
+ "CodecTag",
+ "Comment",
+ "Filename",
+ "MIMEType"
+ };
+
+ private static readonly string _mediaAttachmentSaveColumnsSelectQuery =
+ $"select {string.Join(',', _mediaAttachmentSaveColumns)} from mediaattachments where ItemId=@ItemId";
+
+ private static readonly string _mediaAttachmentInsertPrefix;
+
+ private static readonly HashSet<string> _programTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Program",
+ "TvChannel",
+ "LiveTvProgram",
+ "LiveTvTvChannel"
+ };
+
+ private static readonly HashSet<string> _programExcludeParentTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Series",
+ "Season",
+ "MusicAlbum",
+ "MusicArtist",
+ "PhotoAlbum"
+ };
+
+ private static readonly HashSet<string> _serviceTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "TvChannel",
+ "LiveTvTvChannel"
+ };
+
+ private static readonly HashSet<string> _startDateTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Program",
+ "LiveTvProgram"
+ };
+
+ private static readonly HashSet<string> _seriesTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Book",
+ "AudioBook",
+ "Episode",
+ "Season"
+ };
+
+ private static readonly HashSet<string> _artistExcludeParentTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Series",
+ "Season",
+ "PhotoAlbum"
+ };
+
+ private static readonly HashSet<string> _artistsTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "Audio",
+ "MusicAlbum",
+ "MusicVideo",
+ "AudioBook",
+ "AudioPodcast"
+ };
- public IImageProcessor ImageProcessor { get; set; }
+ private static readonly Type[] _knownTypes =
+ {
+ typeof(LiveTvProgram),
+ typeof(LiveTvChannel),
+ typeof(Series),
+ typeof(Audio),
+ typeof(MusicAlbum),
+ typeof(MusicArtist),
+ typeof(MusicGenre),
+ typeof(MusicVideo),
+ typeof(Movie),
+ typeof(Playlist),
+ typeof(AudioBook),
+ typeof(Trailer),
+ typeof(BoxSet),
+ typeof(Episode),
+ typeof(Season),
+ typeof(Series),
+ typeof(Book),
+ typeof(CollectionFolder),
+ typeof(Folder),
+ typeof(Genre),
+ typeof(Person),
+ typeof(Photo),
+ typeof(PhotoAlbum),
+ typeof(Studio),
+ typeof(UserRootFolder),
+ typeof(UserView),
+ typeof(Video),
+ typeof(Year),
+ typeof(Channel),
+ typeof(AggregateFolder)
+ };
+
+ private readonly Dictionary<string, string> _types = GetTypeMapDictionary();
+
+ static SqliteItemRepository()
+ {
+ var queryPrefixText = new StringBuilder();
+ queryPrefixText.Append("insert into mediaattachments (");
+ foreach (var column in _mediaAttachmentSaveColumns)
+ {
+ queryPrefixText.Append(column)
+ .Append(',');
+ }
+
+ queryPrefixText.Length -= 1;
+ queryPrefixText.Append(") values ");
+ _mediaAttachmentInsertPrefix = queryPrefixText.ToString();
+ }
/// <summary>
/// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
/// </summary>
+ /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="appHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{SqliteItemRepository}"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="imageProcessor">Instance of the <see cref="IImageProcessor"/> interface.</param>
+ /// <exception cref="ArgumentNullException">config is null.</exception>
public SqliteItemRepository(
IServerConfigurationManager config,
IServerApplicationHost appHost,
- IJsonSerializer jsonSerializer,
- ILoggerFactory loggerFactory,
- IAssemblyInfo assemblyInfo)
- : base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
+ ILogger<SqliteItemRepository> logger,
+ ILocalizationManager localization,
+ IImageProcessor imageProcessor)
+ : base(logger)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
- if (jsonSerializer == null)
- {
- throw new ArgumentNullException(nameof(jsonSerializer));
- }
-
- _appHost = appHost;
_config = config;
- _jsonSerializer = jsonSerializer;
- _typeMapper = new TypeMapper(assemblyInfo);
+ _appHost = appHost;
+ _localization = localization;
+ _imageProcessor = imageProcessor;
+
+ _typeMapper = new TypeMapper();
+ _jsonOptions = JsonDefaults.Options;
DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
}
- private const string ChaptersTableName = "Chapters2";
+ /// <inheritdoc />
+ public string Name => "SQLite";
+ /// <inheritdoc />
protected override int? CacheSize => 20000;
- protected override bool EnableTempStoreMemory => true;
+ /// <inheritdoc />
+ protected override TempStoreMode TempStore => TempStoreMode.Memory;
/// <summary>
- /// Opens the connection to the database
+ /// Opens the connection to the database.
/// </summary>
+ /// <param name="userDataRepo">The user data repository.</param>
+ /// <param name="userManager">The user manager.</param>
public void Initialize(SqliteUserDataRepository userDataRepo, IUserManager userManager)
{
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- const string createMediaStreamsTableCommand
+ const string CreateMediaStreamsTableCommand
= "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, CodecTag TEXT NULL, Comment TEXT NULL, NalLengthSize TEXT NULL, IsAvc BIT NULL, Title TEXT NULL, TimeBase TEXT NULL, CodecTimeBase TEXT NULL, ColorPrimaries TEXT NULL, ColorSpace TEXT NULL, ColorTransfer TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))";
+ const string CreateMediaAttachmentsTableCommand
+ = "create table if not exists mediaattachments (ItemId GUID, AttachmentIndex INT, Codec TEXT, CodecTag TEXT NULL, Comment TEXT NULL, Filename TEXT NULL, MIMEType TEXT NULL, PRIMARY KEY (ItemId, AttachmentIndex))";
- string[] queries = {
- "PRAGMA locking_mode=EXCLUSIVE",
+ string[] queries =
+ {
+ "PRAGMA locking_mode=EXCLUSIVE",
- "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
+ "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
- "create table if not exists AncestorIds (ItemId GUID NOT NULL, AncestorId GUID NOT NULL, AncestorIdText TEXT NOT NULL, PRIMARY KEY (ItemId, AncestorId))",
- "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)",
- "create index if not exists idx_AncestorIds5 on AncestorIds(AncestorIdText,ItemId)",
+ "create table if not exists AncestorIds (ItemId GUID NOT NULL, AncestorId GUID NOT NULL, AncestorIdText TEXT NOT NULL, PRIMARY KEY (ItemId, AncestorId))",
+ "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)",
+ "create index if not exists idx_AncestorIds5 on AncestorIds(AncestorIdText,ItemId)",
- "create table if not exists ItemValues (ItemId GUID NOT NULL, Type INT NOT NULL, Value TEXT NOT NULL, CleanValue TEXT NOT NULL)",
+ "create table if not exists ItemValues (ItemId GUID NOT NULL, Type INT NOT NULL, Value TEXT NOT NULL, CleanValue TEXT NOT NULL)",
- "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
+ "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
- "drop index if exists idxPeopleItemId",
- "create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)",
- "create index if not exists idxPeopleName on People(Name)",
+ "drop index if exists idxPeopleItemId",
+ "create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)",
+ "create index if not exists idxPeopleName on People(Name)",
- "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
+ "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
- createMediaStreamsTableCommand,
+ CreateMediaStreamsTableCommand,
+ CreateMediaAttachmentsTableCommand,
- "pragma shrink_memory"
- };
+ "pragma shrink_memory"
+ };
+ string[] postQueries =
+ {
+ // obsolete
+ "drop index if exists idx_TypedBaseItems",
+ "drop index if exists idx_mediastreams",
+ "drop index if exists idx_mediastreams1",
+ "drop index if exists idx_" + ChaptersTableName,
+ "drop index if exists idx_UserDataKeys1",
+ "drop index if exists idx_UserDataKeys2",
+ "drop index if exists idx_TypeTopParentId3",
+ "drop index if exists idx_TypeTopParentId2",
+ "drop index if exists idx_TypeTopParentId4",
+ "drop index if exists idx_Type",
+ "drop index if exists idx_TypeTopParentId",
+ "drop index if exists idx_GuidType",
+ "drop index if exists idx_TopParentId",
+ "drop index if exists idx_TypeTopParentId6",
+ "drop index if exists idx_ItemValues2",
+ "drop index if exists Idx_ProviderIds",
+ "drop index if exists idx_ItemValues3",
+ "drop index if exists idx_ItemValues4",
+ "drop index if exists idx_ItemValues5",
+ "drop index if exists idx_UserDataKeys3",
+ "drop table if exists UserDataKeys",
+ "drop table if exists ProviderIds",
+ "drop index if exists Idx_ProviderIds1",
+ "drop table if exists Images",
+ "drop index if exists idx_Images",
+ "drop index if exists idx_TypeSeriesPresentationUniqueKey",
+ "drop index if exists idx_SeriesPresentationUniqueKey",
+ "drop index if exists idx_TypeSeriesPresentationUniqueKey2",
+ "drop index if exists idx_AncestorIds3",
+ "drop index if exists idx_AncestorIds4",
+ "drop index if exists idx_AncestorIds2",
+
+ "create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
+ "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
+
+ "create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
+ "create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
+ "create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
+
+ // covering index
+ "create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
+
+ // series
+ "create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
+
+ // series counts
+ // seriesdateplayed sort order
+ "create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
+
+ // live tv programs
+ "create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
+
+ // covering index for getitemvalues
+ "create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
+
+ // used by movie suggestions
+ "create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
+ "create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
+
+ // latest items
+ "create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
+ "create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
+
+ // resume
+ "create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
+
+ // items by name
+ "create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
+ "create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
+
+ // Used to update inherited tags
+ "create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
+ };
+
+ using (var connection = GetConnection())
+ {
connection.RunQueries(queries);
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var existingColumnNames = GetColumnNames(db, "AncestorIds");
AddColumn(db, "AncestorIds", "AncestorIdText", "Text", existingColumnNames);
@@ -233,302 +564,20 @@ namespace Emby.Server.Implementations.Data
AddColumn(db, "MediaStreams", "ColorPrimaries", "TEXT", existingColumnNames);
AddColumn(db, "MediaStreams", "ColorSpace", "TEXT", existingColumnNames);
AddColumn(db, "MediaStreams", "ColorTransfer", "TEXT", existingColumnNames);
-
}, TransactionMode);
- string[] postQueries =
- {
- // obsolete
- "drop index if exists idx_TypedBaseItems",
- "drop index if exists idx_mediastreams",
- "drop index if exists idx_mediastreams1",
- "drop index if exists idx_"+ChaptersTableName,
- "drop index if exists idx_UserDataKeys1",
- "drop index if exists idx_UserDataKeys2",
- "drop index if exists idx_TypeTopParentId3",
- "drop index if exists idx_TypeTopParentId2",
- "drop index if exists idx_TypeTopParentId4",
- "drop index if exists idx_Type",
- "drop index if exists idx_TypeTopParentId",
- "drop index if exists idx_GuidType",
- "drop index if exists idx_TopParentId",
- "drop index if exists idx_TypeTopParentId6",
- "drop index if exists idx_ItemValues2",
- "drop index if exists Idx_ProviderIds",
- "drop index if exists idx_ItemValues3",
- "drop index if exists idx_ItemValues4",
- "drop index if exists idx_ItemValues5",
- "drop index if exists idx_UserDataKeys3",
- "drop table if exists UserDataKeys",
- "drop table if exists ProviderIds",
- "drop index if exists Idx_ProviderIds1",
- "drop table if exists Images",
- "drop index if exists idx_Images",
- "drop index if exists idx_TypeSeriesPresentationUniqueKey",
- "drop index if exists idx_SeriesPresentationUniqueKey",
- "drop index if exists idx_TypeSeriesPresentationUniqueKey2",
- "drop index if exists idx_AncestorIds3",
- "drop index if exists idx_AncestorIds4",
- "drop index if exists idx_AncestorIds2",
-
- "create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
- "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
-
- "create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
- "create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
- "create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
-
- // covering index
- "create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
-
- // series
- "create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
-
- // series counts
- // seriesdateplayed sort order
- "create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
-
- // live tv programs
- "create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
-
- // covering index for getitemvalues
- "create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
-
- // used by movie suggestions
- "create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
- "create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
-
- // latest items
- "create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
- "create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
-
- // resume
- "create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
-
- // items by name
- "create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
- "create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
-
- // Used to update inherited tags
- "create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
- };
-
connection.RunQueries(postQueries);
}
- userDataRepo.Initialize(WriteLock, _connection, userManager);
- }
-
- private static readonly string[] _retriveItemColumns =
- {
- "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",
- "guid",
- "Genres",
- "ParentId",
- "Audio",
- "ExternalServiceId",
- "IsInMixedFolder",
- "DateLastSaved",
- "LockedFields",
- "Studios",
- "Tags",
- "TrailerTypes",
- "OriginalTitle",
- "PrimaryVersionId",
- "DateLastMediaAdded",
- "Album",
- "CriticRating",
- "IsVirtualItem",
- "SeriesName",
- "SeasonName",
- "SeasonId",
- "SeriesId",
- "PresentationUniqueKey",
- "InheritedParentalRatingValue",
- "ExternalSeriesId",
- "Tagline",
- "ProviderIds",
- "Images",
- "ProductionLocations",
- "ExtraIds",
- "TotalBitrate",
- "ExtraType",
- "Artists",
- "AlbumArtists",
- "ExternalId",
- "SeriesPresentationUniqueKey",
- "ShowId",
- "OwnerId"
- };
-
- private static readonly string[] _mediaStreamSaveColumns =
- {
- "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"
- };
-
- private static string GetSaveItemCommandText()
- {
- var saveColumns = new []
- {
- "guid",
- "type",
- "data",
- "Path",
- "StartDate",
- "EndDate",
- "ChannelId",
- "IsMovie",
- "IsSeries",
- "EpisodeTitle",
- "IsRepeat",
- "CommunityRating",
- "CustomRating",
- "IndexNumber",
- "IsLocked",
- "Name",
- "OfficialRating",
- "MediaType",
- "Overview",
- "ParentIndexNumber",
- "PremiereDate",
- "ProductionYear",
- "ParentId",
- "Genres",
- "InheritedParentalRatingValue",
- "SortName",
- "ForcedSortName",
- "RunTimeTicks",
- "Size",
- "DateCreated",
- "DateModified",
- "PreferredMetadataLanguage",
- "PreferredMetadataCountryCode",
- "Width",
- "Height",
- "DateLastRefreshed",
- "DateLastSaved",
- "IsInMixedFolder",
- "LockedFields",
- "Studios",
- "Audio",
- "ExternalServiceId",
- "Tags",
- "IsFolder",
- "UnratedType",
- "TopParentId",
- "TrailerTypes",
- "CriticRating",
- "CleanName",
- "PresentationUniqueKey",
- "OriginalTitle",
- "PrimaryVersionId",
- "DateLastMediaAdded",
- "Album",
- "IsVirtualItem",
- "SeriesName",
- "UserDataKey",
- "SeasonName",
- "SeasonId",
- "SeriesId",
- "ExternalSeriesId",
- "Tagline",
- "ProviderIds",
- "Images",
- "ProductionLocations",
- "ExtraIds",
- "TotalBitrate",
- "ExtraType",
- "Artists",
- "AlbumArtists",
- "ExternalId",
- "SeriesPresentationUniqueKey",
- "ShowId",
- "OwnerId"
- };
-
- var saveItemCommandCommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns) + ") values (";
-
- for (var i = 0; i < saveColumns.Length; i++)
- {
- if (i != 0)
- {
- saveItemCommandCommandText += ",";
- }
- saveItemCommandCommandText += "@" + saveColumns[i];
- }
- saveItemCommandCommandText += ")";
- return saveItemCommandCommandText;
+ userDataRepo.Initialize(userManager, WriteLock, WriteConnection);
}
/// <summary>
- /// Save a standard item in the repo
+ /// Save a standard item in the repo.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <exception cref="ArgumentNullException">item</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public void SaveItem(BaseItem item, CancellationToken cancellationToken)
{
if (item == null)
@@ -536,7 +585,7 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(item));
}
- SaveItems(new [] { item }, cancellationToken);
+ SaveItems(new[] { item }, cancellationToken);
}
public void SaveImages(BaseItem item)
@@ -548,21 +597,19 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
+ using (var saveImagesStatement = PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id"))
{
- using (var saveImagesStatement = PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id"))
- {
- saveImagesStatement.TryBind("@Id", item.Id.ToGuidBlob());
- saveImagesStatement.TryBind("@Images", SerializeImages(item));
+ saveImagesStatement.TryBind("@Id", item.Id.ToByteArray());
+ saveImagesStatement.TryBind("@Images", SerializeImages(item.ImageInfos));
- saveImagesStatement.MoveNext();
- }
- }, TransactionMode);
- }
+ saveImagesStatement.MoveNext();
+ }
+ }, TransactionMode);
}
}
@@ -572,9 +619,7 @@ namespace Emby.Server.Implementations.Data
/// <param name="items">The items.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="ArgumentNullException">
- /// items
- /// or
- /// cancellationToken
+ /// <paramref name="items"/> or <paramref name="cancellationToken"/> is <c>null</c>.
/// </exception>
public void SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
{
@@ -602,24 +647,21 @@ namespace Emby.Server.Implementations.Data
tuples.Add((item, ancestorIds, topParent, userdataKey, inheritedTags));
}
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- SaveItemsInTranscation(db, tuples);
-
- }, TransactionMode);
- }
+ SaveItemsInTranscation(db, tuples);
+ }, TransactionMode);
}
}
private void SaveItemsInTranscation(IDatabaseConnection db, IEnumerable<(BaseItem, List<Guid>, BaseItem, string, List<string>)> tuples)
{
- var statements = PrepareAllSafe(db, new string[]
+ var statements = PrepareAll(db, new string[]
{
- GetSaveItemCommandText(),
+ SaveItemCommandText,
"delete from AncestorIds where ItemId=@ItemId"
});
@@ -671,12 +713,14 @@ namespace Emby.Server.Implementations.Data
private void SaveItem(BaseItem item, BaseItem topParent, string userDataKey, IStatement saveItemStatement)
{
+ Type type = item.GetType();
+
saveItemStatement.TryBind("@guid", item.Id);
- saveItemStatement.TryBind("@type", item.GetType().FullName);
+ saveItemStatement.TryBind("@type", type.FullName);
- if (TypeRequiresDeserialization(item.GetType()))
+ if (TypeRequiresDeserialization(type))
{
- saveItemStatement.TryBind("@data", _jsonSerializer.SerializeToBytes(item));
+ saveItemStatement.TryBind("@data", JsonSerializer.SerializeToUtf8Bytes(item, type, _jsonOptions));
}
else
{
@@ -703,7 +747,7 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.TryBindNull("@EndDate");
}
- saveItemStatement.TryBind("@ChannelId", item.ChannelId.Equals(Guid.Empty) ? null : item.ChannelId.ToString("N"));
+ saveItemStatement.TryBind("@ChannelId", item.ChannelId.Equals(Guid.Empty) ? null : item.ChannelId.ToString("N", CultureInfo.InvariantCulture));
if (item is IHasProgramAttributes hasProgramAttributes)
{
@@ -744,7 +788,7 @@ namespace Emby.Server.Implementations.Data
if (item.Genres.Length > 0)
{
- saveItemStatement.TryBind("@Genres", string.Join("|", item.Genres));
+ saveItemStatement.TryBind("@Genres", string.Join('|', item.Genres));
}
else
{
@@ -774,6 +818,7 @@ namespace Emby.Server.Implementations.Data
{
saveItemStatement.TryBindNull("@Width");
}
+
if (item.Height > 0)
{
saveItemStatement.TryBind("@Height", item.Height);
@@ -805,7 +850,7 @@ namespace Emby.Server.Implementations.Data
if (item.LockedFields.Length > 0)
{
- saveItemStatement.TryBind("@LockedFields", string.Join("|", item.LockedFields));
+ saveItemStatement.TryBind("@LockedFields", string.Join('|', item.LockedFields));
}
else
{
@@ -814,7 +859,7 @@ namespace Emby.Server.Implementations.Data
if (item.Studios.Length > 0)
{
- saveItemStatement.TryBind("@Studios", string.Join("|", item.Studios));
+ saveItemStatement.TryBind("@Studios", string.Join('|', item.Studios));
}
else
{
@@ -841,7 +886,7 @@ namespace Emby.Server.Implementations.Data
if (item.Tags.Length > 0)
{
- saveItemStatement.TryBind("@Tags", string.Join("|", item.Tags));
+ saveItemStatement.TryBind("@Tags", string.Join('|', item.Tags));
}
else
{
@@ -858,12 +903,12 @@ namespace Emby.Server.Implementations.Data
}
else
{
- saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N"));
+ saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N", CultureInfo.InvariantCulture));
}
if (item is Trailer trailer && trailer.TrailerTypes.Length > 0)
{
- saveItemStatement.TryBind("@TrailerTypes", string.Join("|", trailer.TrailerTypes));
+ saveItemStatement.TryBind("@TrailerTypes", string.Join('|', trailer.TrailerTypes));
}
else
{
@@ -913,6 +958,7 @@ namespace Emby.Server.Implementations.Data
{
saveItemStatement.TryBindNull("@SeriesName");
}
+
if (string.IsNullOrWhiteSpace(userDataKey))
{
saveItemStatement.TryBindNull("@UserDataKey");
@@ -952,12 +998,12 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.TryBind("@ExternalSeriesId", item.ExternalSeriesId);
saveItemStatement.TryBind("@Tagline", item.Tagline);
- saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item));
- saveItemStatement.TryBind("@Images", SerializeImages(item));
+ saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item.ProviderIds));
+ saveItemStatement.TryBind("@Images", SerializeImages(item.ImageInfos));
if (item.ProductionLocations.Length > 0)
{
- saveItemStatement.TryBind("@ProductionLocations", string.Join("|", item.ProductionLocations));
+ saveItemStatement.TryBind("@ProductionLocations", string.Join('|', item.ProductionLocations));
}
else
{
@@ -966,7 +1012,7 @@ namespace Emby.Server.Implementations.Data
if (item.ExtraIds.Length > 0)
{
- saveItemStatement.TryBind("@ExtraIds", string.Join("|", item.ExtraIds));
+ saveItemStatement.TryBind("@ExtraIds", string.Join('|', item.ExtraIds));
}
else
{
@@ -984,18 +1030,20 @@ namespace Emby.Server.Implementations.Data
}
string artists = null;
- if (item is IHasArtist hasArtists && hasArtists.Artists.Length > 0)
+ if (item is IHasArtist hasArtists && hasArtists.Artists.Count > 0)
{
- artists = string.Join("|", hasArtists.Artists);
+ artists = string.Join('|', hasArtists.Artists);
}
+
saveItemStatement.TryBind("@Artists", artists);
string albumArtists = null;
if (item is IHasAlbumArtist hasAlbumArtists
- && hasAlbumArtists.AlbumArtists.Length > 0)
+ && hasAlbumArtists.AlbumArtists.Count > 0)
{
- albumArtists = string.Join("|", hasAlbumArtists.AlbumArtists);
+ albumArtists = string.Join('|', hasAlbumArtists.AlbumArtists);
}
+
saveItemStatement.TryBind("@AlbumArtists", albumArtists);
saveItemStatement.TryBind("@ExternalId", item.ExternalId);
@@ -1021,10 +1069,10 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.MoveNext();
}
- private static string SerializeProviderIds(BaseItem item)
+ internal static string SerializeProviderIds(Dictionary<string, string> providerIds)
{
StringBuilder str = new StringBuilder();
- foreach (var i in item.ProviderIds)
+ foreach (var i in providerIds)
{
// Ideally we shouldn't need this IsNullOrWhiteSpace check,
// but we're seeing some cases of bad data slip through
@@ -1032,50 +1080,46 @@ namespace Emby.Server.Implementations.Data
{
continue;
}
- str.Append($"{i.Key}={i.Value}|");
+
+ str.Append(i.Key)
+ .Append('=')
+ .Append(i.Value)
+ .Append('|');
}
if (str.Length == 0)
{
return null;
}
+
str.Length -= 1; // Remove last |
return str.ToString();
}
- private static void DeserializeProviderIds(string value, BaseItem item)
+ internal static void DeserializeProviderIds(string value, IHasProviderIds item)
{
if (string.IsNullOrWhiteSpace(value))
{
return;
}
- if (item.ProviderIds.Count > 0)
- {
- return;
- }
-
- var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
-
- foreach (var part in parts)
+ foreach (var part in value.SpanSplit('|'))
{
- var idParts = part.Split('=');
-
- if (idParts.Length == 2)
+ var providerDelimiterIndex = part.IndexOf('=');
+ if (providerDelimiterIndex != -1 && providerDelimiterIndex == part.LastIndexOf('='))
{
- item.SetProviderId(idParts[0], idParts[1]);
+ item.SetProviderId(part.Slice(0, providerDelimiterIndex).ToString(), part.Slice(providerDelimiterIndex + 1).ToString());
}
}
}
- private string SerializeImages(BaseItem item)
+ internal string SerializeImages(ItemImageInfo[] images)
{
- var images = item.ImageInfos;
-
if (images.Length == 0)
{
return null;
}
+
StringBuilder str = new StringBuilder();
foreach (var i in images)
{
@@ -1083,130 +1127,211 @@ namespace Emby.Server.Implementations.Data
{
continue;
}
- str.Append(ToValueString(i) + "|");
+
+ AppendItemImageInfo(str, i);
+ str.Append('|');
}
+
str.Length -= 1; // Remove last |
return str.ToString();
}
- private void DeserializeImages(string value, BaseItem item)
+ internal ItemImageInfo[] DeserializeImages(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
- return;
+ return Array.Empty<ItemImageInfo>();
}
- if (item.ImageInfos.Length > 0)
- {
- return;
- }
+ // TODO The following is an ugly performance optimization, but it's extremely unlikely that the data in the database would be malformed
+ var valueSpan = value.AsSpan();
+ var count = valueSpan.Count('|') + 1;
- var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- var list = new List<ItemImageInfo>();
- foreach (var part in parts)
+ var position = 0;
+ var result = new ItemImageInfo[count];
+ foreach (var part in valueSpan.Split('|'))
{
var image = ItemImageInfoFromValueString(part);
if (image != null)
{
- list.Add(image);
+ result[position++] = image;
}
}
- item.ImageInfos = list.ToArray();
+ if (position == count)
+ {
+ return result;
+ }
+
+ if (position == 0)
+ {
+ return Array.Empty<ItemImageInfo>();
+ }
+
+ // Extremely unlikely, but somehow one or more of the image strings were malformed. Cut the array.
+ return result[..position];
}
- public string ToValueString(ItemImageInfo image)
+ private void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image)
{
- var delimeter = "*";
+ const char Delimiter = '*';
- var path = image.Path;
+ var path = image.Path ?? string.Empty;
- if (path == null)
+ bldr.Append(GetPathToSave(path))
+ .Append(Delimiter)
+ .Append(image.DateModified.Ticks)
+ .Append(Delimiter)
+ .Append(image.Type)
+ .Append(Delimiter)
+ .Append(image.Width)
+ .Append(Delimiter)
+ .Append(image.Height);
+
+ var hash = image.BlurHash;
+ if (!string.IsNullOrEmpty(hash))
{
- path = string.Empty;
+ bldr.Append(Delimiter)
+ // Replace delimiters with other characters.
+ // This can be removed when we migrate to a proper DB.
+ .Append(hash.Replace('*', '/').Replace('|', '\\'));
}
-
- return GetPathToSave(path) +
- delimeter +
- image.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) +
- delimeter +
- image.Type +
- delimeter +
- image.Width.ToString(CultureInfo.InvariantCulture) +
- delimeter +
- image.Height.ToString(CultureInfo.InvariantCulture);
}
- public ItemImageInfo ItemImageInfoFromValueString(string value)
+ internal ItemImageInfo ItemImageInfoFromValueString(ReadOnlySpan<char> value)
{
- var parts = value.Split(new[] { '*' }, StringSplitOptions.None);
+ var nextSegment = value.IndexOf('*');
+ if (nextSegment == -1)
+ {
+ return null;
+ }
- if (parts.Length < 3)
+ ReadOnlySpan<char> path = value[..nextSegment];
+ value = value[(nextSegment + 1)..];
+ nextSegment = value.IndexOf('*');
+ if (nextSegment == -1)
{
return null;
}
- var image = new ItemImageInfo();
+ ReadOnlySpan<char> dateModified = value[..nextSegment];
+ value = value[(nextSegment + 1)..];
+ nextSegment = value.IndexOf('*');
+ if (nextSegment == -1)
+ {
+ nextSegment = value.Length;
+ }
+
+ ReadOnlySpan<char> imageType = value[..nextSegment];
- image.Path = RestorePath(parts[0]);
+ var image = new ItemImageInfo
+ {
+ Path = RestorePath(path.ToString())
+ };
- if (long.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks))
+ if (long.TryParse(dateModified, NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks)
+ && ticks >= DateTime.MinValue.Ticks
+ && ticks <= DateTime.MaxValue.Ticks)
{
image.DateModified = new DateTime(ticks, DateTimeKind.Utc);
}
+ else
+ {
+ return null;
+ }
- if (Enum.TryParse(parts[2], true, out ImageType type))
+ if (Enum.TryParse(imageType, true, out ImageType type))
{
image.Type = type;
}
+ else
+ {
+ return null;
+ }
- if (parts.Length >= 5)
+ // Optional parameters: width*height*blurhash
+ if (nextSegment + 1 < value.Length - 1)
{
- if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var width)
- && int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out var height))
+ value = value[(nextSegment + 1)..];
+ nextSegment = value.IndexOf('*');
+ if (nextSegment == -1 || nextSegment == value.Length)
+ {
+ return image;
+ }
+
+ ReadOnlySpan<char> widthSpan = value[..nextSegment];
+
+ value = value[(nextSegment + 1)..];
+ nextSegment = value.IndexOf('*');
+ if (nextSegment == -1)
+ {
+ nextSegment = value.Length;
+ }
+
+ ReadOnlySpan<char> heightSpan = value[..nextSegment];
+
+ if (int.TryParse(widthSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var width)
+ && int.TryParse(heightSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var height))
{
image.Width = width;
image.Height = height;
}
+
+ if (nextSegment < value.Length - 1)
+ {
+ value = value[(nextSegment + 1)..];
+ var length = value.Length;
+
+ Span<char> blurHashSpan = stackalloc char[length];
+ for (int i = 0; i < length; i++)
+ {
+ var c = value[i];
+ blurHashSpan[i] = c switch
+ {
+ '/' => '*',
+ '\\' => '|',
+ _ => c
+ };
+ }
+
+ image.BlurHash = new string(blurHashSpan);
+ }
}
return image;
}
/// <summary>
- /// Internal retrieve from items or users table
+ /// Internal retrieve from items or users table.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>BaseItem.</returns>
- /// <exception cref="ArgumentNullException">id</exception>
- /// <exception cref="ArgumentException"></exception>
+ /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
+ /// <exception cref="ArgumentException"><paramr name="id"/> is <seealso cref="Guid.Empty"/>.</exception>
public BaseItem RetrieveItem(Guid id)
{
if (id == Guid.Empty)
{
- throw new ArgumentException(nameof(id), "Guid can't be empty");
+ throw new ArgumentException("Guid can't be empty", nameof(id));
}
CheckDisposed();
- using (WriteLock.Read())
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, _retriveItemColumnsSelectQuery))
{
- using (var statement = PrepareStatementSafe(connection, "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid = @guid"))
- {
- statement.TryBind("@guid", id);
+ statement.TryBind("@guid", id);
- foreach (var row in statement.ExecuteQuery())
- {
- return GetItem(row, new InternalItemsQuery());
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ return GetItem(row, new InternalItemsQuery());
}
-
- return null;
}
}
+
+ return null;
}
private bool TypeRequiresDeserialization(Type type)
@@ -1283,12 +1408,12 @@ namespace Emby.Server.Implementations.Data
return true;
}
- private BaseItem GetItem(IReadOnlyList<IResultSetValue> reader, InternalItemsQuery query)
+ private BaseItem GetItem(IReadOnlyList<ResultSetValue> reader, InternalItemsQuery query)
{
return GetItem(reader, query, HasProgramAttributes(query), HasEpisodeAttributes(query), HasServiceName(query), HasStartDate(query), HasTrailerTypes(query), HasArtistFields(query), HasSeriesFields(query));
}
- private BaseItem GetItem(IReadOnlyList<IResultSetValue> reader, InternalItemsQuery query, bool enableProgramAttributes, bool hasEpisodeAttributes, bool hasServiceName, bool queryHasStartDate, bool hasTrailerTypes, bool hasArtistFields, bool hasSeriesFields)
+ private BaseItem GetItem(IReadOnlyList<ResultSetValue> reader, InternalItemsQuery query, bool enableProgramAttributes, bool hasEpisodeAttributes, bool hasServiceName, bool queryHasStartDate, bool hasTrailerTypes, bool hasArtistFields, bool hasSeriesFields)
{
var typeString = reader.GetString(0);
@@ -1303,18 +1428,13 @@ namespace Emby.Server.Implementations.Data
if (TypeRequiresDeserialization(type))
{
- using (var stream = new MemoryStream(reader[1].ToBlob()))
+ try
{
- stream.Position = 0;
-
- try
- {
- item = _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
- }
- catch (SerializationException ex)
- {
- Logger.LogError(ex, "Error deserializing item");
- }
+ item = JsonSerializer.Deserialize(reader[1].ToBlob(), type, _jsonOptions) as BaseItem;
+ }
+ catch (JsonException ex)
+ {
+ Logger.LogError(ex, "Error deserializing item with JSON: {Data}", reader.GetString(1));
}
}
@@ -1338,55 +1458,57 @@ namespace Emby.Server.Implementations.Data
if (queryHasStartDate)
{
- if (!reader.IsDBNull(index))
+ if (item is IHasStartDate hasStartDate && reader.TryReadDateTime(index, out var startDate))
{
- if (item is IHasStartDate hasStartDate)
- {
- hasStartDate.StartDate = reader[index].ReadDateTime();
- }
+ hasStartDate.StartDate = startDate;
}
+
index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var endDate))
{
- item.EndDate = reader[index].TryReadDateTime();
+ item.EndDate = endDate;
}
- index++;
- if (!reader.IsDBNull(index))
+ var channelId = reader[index];
+ if (!channelId.IsDbNull())
{
- item.ChannelId = new Guid(reader.GetString(index));
+ if (!Utf8Parser.TryParse(channelId.ToBlob(), out Guid value, out _, standardFormat: 'N'))
+ {
+ var str = reader.GetString(index);
+ Logger.LogWarning("{ChannelId} isn't in the expected format", str);
+ value = new Guid(str);
+ }
+
+ item.ChannelId = value;
}
+
index++;
if (enableProgramAttributes)
{
if (item is IHasProgramAttributes hasProgramAttributes)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isMovie))
{
- hasProgramAttributes.IsMovie = reader.GetBoolean(index);
+ hasProgramAttributes.IsMovie = isMovie;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isSeries))
{
- hasProgramAttributes.IsSeries = reader.GetBoolean(index);
+ hasProgramAttributes.IsSeries = isSeries;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var episodeTitle))
{
- hasProgramAttributes.EpisodeTitle = reader.GetString(index);
+ hasProgramAttributes.EpisodeTitle = episodeTitle;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isRepeat))
{
- hasProgramAttributes.IsRepeat = reader.GetBoolean(index);
+ hasProgramAttributes.IsRepeat = isRepeat;
}
- index++;
}
else
{
@@ -1394,182 +1516,157 @@ namespace Emby.Server.Implementations.Data
}
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetSingle(index++, out var communityRating))
{
- item.CommunityRating = reader.GetFloat(index);
+ item.CommunityRating = communityRating;
}
- index++;
if (HasField(query, ItemFields.CustomRating))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var customRating))
{
- item.CustomRating = reader.GetString(index);
+ item.CustomRating = customRating;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var indexNumber))
{
- item.IndexNumber = reader.GetInt32(index);
+ item.IndexNumber = indexNumber;
}
- index++;
if (HasField(query, ItemFields.Settings))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isLocked))
{
- item.IsLocked = reader.GetBoolean(index);
+ item.IsLocked = isLocked;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var preferredMetadataLanguage))
{
- item.PreferredMetadataLanguage = reader.GetString(index);
+ item.PreferredMetadataLanguage = preferredMetadataLanguage;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var preferredMetadataCountryCode))
{
- item.PreferredMetadataCountryCode = reader.GetString(index);
+ item.PreferredMetadataCountryCode = preferredMetadataCountryCode;
}
- index++;
}
if (HasField(query, ItemFields.Width))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var width))
{
- item.Width = reader.GetInt32(index);
+ item.Width = width;
}
- index++;
}
if (HasField(query, ItemFields.Height))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var height))
{
- item.Height = reader.GetInt32(index);
+ item.Height = height;
}
- index++;
}
if (HasField(query, ItemFields.DateLastRefreshed))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var dateLastRefreshed))
{
- item.DateLastRefreshed = reader[index].ReadDateTime();
+ item.DateLastRefreshed = dateLastRefreshed;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var name))
{
- item.Name = reader.GetString(index);
+ item.Name = name;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var restorePath))
{
- item.Path = RestorePath(reader.GetString(index));
+ item.Path = RestorePath(restorePath);
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var premiereDate))
{
- item.PremiereDate = reader[index].TryReadDateTime();
+ item.PremiereDate = premiereDate;
}
- index++;
if (HasField(query, ItemFields.Overview))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var overview))
{
- item.Overview = reader.GetString(index);
+ item.Overview = overview;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var parentIndexNumber))
{
- item.ParentIndexNumber = reader.GetInt32(index);
+ item.ParentIndexNumber = parentIndexNumber;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var productionYear))
{
- item.ProductionYear = reader.GetInt32(index);
+ item.ProductionYear = productionYear;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var officialRating))
{
- item.OfficialRating = reader.GetString(index);
+ item.OfficialRating = officialRating;
}
- index++;
if (HasField(query, ItemFields.SortName))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var forcedSortName))
{
- item.ForcedSortName = reader.GetString(index);
+ item.ForcedSortName = forcedSortName;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt64(index++, out var runTimeTicks))
{
- item.RunTimeTicks = reader.GetInt64(index);
+ item.RunTimeTicks = runTimeTicks;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt64(index++, out var size))
{
- item.Size = reader.GetInt64(index);
+ item.Size = size;
}
- index++;
if (HasField(query, ItemFields.DateCreated))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var dateCreated))
{
- item.DateCreated = reader[index].ReadDateTime();
+ item.DateCreated = dateCreated;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var dateModified))
{
- item.DateModified = reader[index].ReadDateTime();
+ item.DateModified = dateModified;
}
- index++;
- item.Id = reader.GetGuid(index);
- index++;
+ item.Id = reader.GetGuid(index++);
if (HasField(query, ItemFields.Genres))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var genres))
{
- item.Genres = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Genres = genres.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetGuid(index++, out var parentId))
{
- item.ParentId = reader.GetGuid(index);
+ item.ParentId = parentId;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var audioString))
{
- if (Enum.TryParse(reader.GetString(index), true, out ProgramAudio audio))
+ if (Enum.TryParse(audioString, true, out ProgramAudio audio))
{
item.Audio = audio;
}
}
- index++;
// TODO: Even if not needed by apps, the server needs it internally
// But get this excluded from contexts where it is not needed
@@ -1577,160 +1674,156 @@ namespace Emby.Server.Implementations.Data
{
if (item is LiveTvChannel liveTvChannel)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var serviceName))
{
- liveTvChannel.ServiceName = reader.GetString(index);
+ liveTvChannel.ServiceName = serviceName;
}
}
+
index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isInMixedFolder))
{
- item.IsInMixedFolder = reader.GetBoolean(index);
+ item.IsInMixedFolder = isInMixedFolder;
}
- index++;
if (HasField(query, ItemFields.DateLastSaved))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryReadDateTime(index++, out var dateLastSaved))
{
- item.DateLastSaved = reader[index].ReadDateTime();
+ item.DateLastSaved = dateLastSaved;
}
- index++;
}
if (HasField(query, ItemFields.Settings))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var lockedFields))
{
- IEnumerable<MetadataFields> GetLockedFields(string s)
+ List<MetadataField> fields = null;
+ foreach (var i in lockedFields.AsSpan().Split('|'))
{
- foreach (var i in s.Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries))
+ if (Enum.TryParse(i, true, out MetadataField parsedValue))
{
- if (Enum.TryParse(i, true, out MetadataFields parsedValue))
- {
- yield return parsedValue;
- }
+ (fields ??= new List<MetadataField>()).Add(parsedValue);
}
}
- item.LockedFields = GetLockedFields(reader.GetString(index)).ToArray();
+
+ item.LockedFields = fields?.ToArray() ?? Array.Empty<MetadataField>();
}
- index++;
}
if (HasField(query, ItemFields.Studios))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var studios))
{
- item.Studios = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Studios = studios.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
- index++;
}
if (HasField(query, ItemFields.Tags))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var tags))
{
- item.Tags = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Tags = tags.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
- index++;
}
if (hasTrailerTypes)
{
if (item is Trailer trailer)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var trailerTypes))
{
- IEnumerable<TrailerType> GetTrailerTypes(string s)
+ List<TrailerType> types = null;
+ foreach (var i in trailerTypes.AsSpan().Split('|'))
{
- foreach (var i in s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
+ if (Enum.TryParse(i, true, out TrailerType parsedValue))
{
- if (Enum.TryParse(i, true, out TrailerType parsedValue))
- {
- yield return parsedValue;
- }
+ (types ??= new List<TrailerType>()).Add(parsedValue);
}
}
- trailer.TrailerTypes = GetTrailerTypes(reader.GetString(index)).ToArray();
+
+ trailer.TrailerTypes = types?.ToArray() ?? Array.Empty<TrailerType>();
}
}
+
index++;
}
if (HasField(query, ItemFields.OriginalTitle))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var originalTitle))
{
- item.OriginalTitle = reader.GetString(index);
+ item.OriginalTitle = originalTitle;
}
- index++;
}
if (item is Video video)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var primaryVersionId))
{
- video.PrimaryVersionId = reader.GetString(index);
+ video.PrimaryVersionId = primaryVersionId;
}
}
+
index++;
if (HasField(query, ItemFields.DateLastMediaAdded))
{
- if (item is Folder folder && !reader.IsDBNull(index))
+ if (item is Folder folder && reader.TryReadDateTime(index, out var dateLastMediaAdded))
{
- folder.DateLastMediaAdded = reader[index].TryReadDateTime();
+ folder.DateLastMediaAdded = dateLastMediaAdded;
}
+
index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var album))
{
- item.Album = reader.GetString(index);
+ item.Album = album;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetSingle(index++, out var criticRating))
{
- item.CriticRating = reader.GetFloat(index);
+ item.CriticRating = criticRating;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetBoolean(index++, out var isVirtualItem))
{
- item.IsVirtualItem = reader.GetBoolean(index);
+ item.IsVirtualItem = isVirtualItem;
}
- index++;
if (item is IHasSeries hasSeriesName)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var seriesName))
{
- hasSeriesName.SeriesName = reader.GetString(index);
+ hasSeriesName.SeriesName = seriesName;
}
}
+
index++;
if (hasEpisodeAttributes)
{
if (item is Episode episode)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var seasonName))
{
- episode.SeasonName = reader.GetString(index);
+ episode.SeasonName = seasonName;
}
+
index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetGuid(index, out var seasonId))
{
- episode.SeasonId = reader.GetGuid(index);
+ episode.SeasonId = seasonId;
}
}
else
{
index++;
}
+
index++;
}
@@ -1739,145 +1832,142 @@ namespace Emby.Server.Implementations.Data
{
if (hasSeries != null)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetGuid(index, out var seriesId))
{
- hasSeries.SeriesId = reader.GetGuid(index);
+ hasSeries.SeriesId = seriesId;
}
}
+
index++;
}
if (HasField(query, ItemFields.PresentationUniqueKey))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var presentationUniqueKey))
{
- item.PresentationUniqueKey = reader.GetString(index);
+ item.PresentationUniqueKey = presentationUniqueKey;
}
- index++;
}
if (HasField(query, ItemFields.InheritedParentalRatingValue))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var parentalRating))
{
- item.InheritedParentalRatingValue = reader.GetInt32(index);
+ item.InheritedParentalRatingValue = parentalRating;
}
- index++;
}
if (HasField(query, ItemFields.ExternalSeriesId))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var externalSeriesId))
{
- item.ExternalSeriesId = reader.GetString(index);
+ item.ExternalSeriesId = externalSeriesId;
}
- index++;
}
if (HasField(query, ItemFields.Taglines))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var tagLine))
{
- item.Tagline = reader.GetString(index);
+ item.Tagline = tagLine;
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (item.ProviderIds.Count == 0 && reader.TryGetString(index, out var providerIds))
{
- DeserializeProviderIds(reader.GetString(index), item);
+ DeserializeProviderIds(providerIds, item);
}
+
index++;
if (query.DtoOptions.EnableImages)
{
- if (!reader.IsDBNull(index))
+ if (item.ImageInfos.Length == 0 && reader.TryGetString(index, out var imageInfos))
{
- DeserializeImages(reader.GetString(index), item);
+ item.ImageInfos = DeserializeImages(imageInfos);
}
+
index++;
}
if (HasField(query, ItemFields.ProductionLocations))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var productionLocations))
{
- item.ProductionLocations = reader.GetString(index).Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
+ item.ProductionLocations = productionLocations.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
- index++;
}
if (HasField(query, ItemFields.ExtraIds))
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var extraIds))
{
- item.ExtraIds = SplitToGuids(reader.GetString(index));
+ item.ExtraIds = SplitToGuids(extraIds);
}
- index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetInt32(index++, out var totalBitrate))
{
- item.TotalBitrate = reader.GetInt32(index);
+ item.TotalBitrate = totalBitrate;
}
- index++;
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var extraTypeString))
{
- if (Enum.TryParse(reader.GetString(index), true, out ExtraType extraType))
+ if (Enum.TryParse(extraTypeString, true, out ExtraType extraType))
{
item.ExtraType = extraType;
}
}
- index++;
if (hasArtistFields)
{
- if (item is IHasArtist hasArtists && !reader.IsDBNull(index))
+ if (item is IHasArtist hasArtists && reader.TryGetString(index, out var artists))
{
- hasArtists.Artists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ hasArtists.Artists = artists.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
+
index++;
- if (item is IHasAlbumArtist hasAlbumArtists && !reader.IsDBNull(index))
+ if (item is IHasAlbumArtist hasAlbumArtists && reader.TryGetString(index, out var albumArtists))
{
- hasAlbumArtists.AlbumArtists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ hasAlbumArtists.AlbumArtists = albumArtists.Split('|', StringSplitOptions.RemoveEmptyEntries);
}
+
index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index++, out var externalId))
{
- item.ExternalId = reader.GetString(index);
+ item.ExternalId = externalId;
}
- index++;
if (HasField(query, ItemFields.SeriesPresentationUniqueKey))
{
if (hasSeries != null)
{
- if (!reader.IsDBNull(index))
+ if (reader.TryGetString(index, out var seriesPresentationUniqueKey))
{
- hasSeries.SeriesPresentationUniqueKey = reader.GetString(index);
+ hasSeries.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
}
}
+
index++;
}
if (enableProgramAttributes)
{
- if (item is LiveTvProgram program && !reader.IsDBNull(index))
+ if (item is LiveTvProgram program && reader.TryGetString(index, out var showId))
{
- program.ShowId = reader.GetString(index);
+ program.ShowId = showId;
}
+
index++;
}
- if (!reader.IsDBNull(index))
+ if (reader.TryGetGuid(index, out var ownerId))
{
- item.OwnerId = reader.GetGuid(index);
+ item.OwnerId = ownerId;
}
- index++;
return item;
}
@@ -1896,64 +1986,48 @@ namespace Emby.Server.Implementations.Data
return result;
}
- /// <summary>
- /// Gets chapters for an item
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>IEnumerable{ChapterInfo}.</returns>
- /// <exception cref="ArgumentNullException">id</exception>
+ /// <inheritdoc />
public List<ChapterInfo> GetChapters(BaseItem item)
{
CheckDisposed();
- using (WriteLock.Read())
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ var chapters = new List<ChapterInfo>();
+
+ using (var statement = PrepareStatement(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc"))
{
- var list = new List<ChapterInfo>();
+ statement.TryBind("@ItemId", item.Id);
- using (var statement = PrepareStatementSafe(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc"))
+ foreach (var row in statement.ExecuteQuery())
{
- statement.TryBind("@ItemId", item.Id);
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetChapter(row, item));
- }
+ chapters.Add(GetChapter(row, item));
}
-
- return list;
}
+
+ return chapters;
}
}
- /// <summary>
- /// Gets a single chapter for an item
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="index">The index.</param>
- /// <returns>ChapterInfo.</returns>
- /// <exception cref="ArgumentNullException">id</exception>
+ /// <inheritdoc />
public ChapterInfo GetChapter(BaseItem item, int index)
{
CheckDisposed();
- using (WriteLock.Read())
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex"))
{
- using (var statement = PrepareStatementSafe(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex"))
- {
- statement.TryBind("@ItemId", item.Id);
- statement.TryBind("@ChapterIndex", index);
+ statement.TryBind("@ItemId", item.Id);
+ statement.TryBind("@ChapterIndex", index);
- foreach (var row in statement.ExecuteQuery())
- {
- return GetChapter(row, item);
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ return GetChapter(row, item);
}
}
}
+
return null;
}
@@ -1961,32 +2035,40 @@ namespace Emby.Server.Implementations.Data
/// Gets the chapter.
/// </summary>
/// <param name="reader">The reader.</param>
+ /// <param name="item">The item.</param>
/// <returns>ChapterInfo.</returns>
- private ChapterInfo GetChapter(IReadOnlyList<IResultSetValue> reader, BaseItem item)
+ private ChapterInfo GetChapter(IReadOnlyList<ResultSetValue> reader, BaseItem item)
{
var chapter = new ChapterInfo
{
StartPositionTicks = reader.GetInt64(0)
};
- if (!reader.IsDBNull(1))
+ if (reader.TryGetString(1, out var chapterName))
{
- chapter.Name = reader.GetString(1);
+ chapter.Name = chapterName;
}
- if (!reader.IsDBNull(2))
+ if (reader.TryGetString(2, out var imagePath))
{
- chapter.ImagePath = reader.GetString(2);
+ chapter.ImagePath = imagePath;
if (!string.IsNullOrEmpty(chapter.ImagePath))
{
- chapter.ImageTag = ImageProcessor.GetImageCacheTag(item, chapter);
+ try
+ {
+ chapter.ImageTag = _imageProcessor.GetImageCacheTag(item, chapter);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Failed to create image cache tag.");
+ }
}
}
- if (!reader.IsDBNull(3))
+ if (reader.TryReadDateTime(3, out var imageDateModified))
{
- chapter.ImageDateModified = reader[3].ReadDateTime();
+ chapter.ImageDateModified = imageDateModified;
}
return chapter;
@@ -1995,7 +2077,9 @@ namespace Emby.Server.Implementations.Data
/// <summary>
/// Saves the chapters.
/// </summary>
- public void SaveChapters(Guid id, List<ChapterInfo> chapters)
+ /// <param name="id">The item id.</param>
+ /// <param name="chapters">The chapters.</param>
+ public void SaveChapters(Guid id, IReadOnlyList<ChapterInfo> chapters)
{
CheckDisposed();
@@ -2009,43 +2093,42 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(chapters));
}
- using (WriteLock.Write())
+ var idBlob = id.ToByteArray();
+
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- var idBlob = id.ToGuidBlob();
-
- // First delete chapters
- db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
+ // First delete chapters
+ db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
- InsertChapters(idBlob, chapters, db);
-
- }, TransactionMode);
- }
+ InsertChapters(idBlob, chapters, db);
+ }, TransactionMode);
}
}
- private void InsertChapters(byte[] idBlob, List<ChapterInfo> chapters, IDatabaseConnection db)
+ private void InsertChapters(byte[] idBlob, IReadOnlyList<ChapterInfo> chapters, IDatabaseConnection db)
{
var startIndex = 0;
var limit = 100;
var chapterIndex = 0;
+ const string StartInsertText = "insert into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath, ImageDateModified) values ";
+ var insertText = new StringBuilder(StartInsertText, 256);
+
while (startIndex < chapters.Count)
{
- var insertText = new StringBuilder("insert into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath, ImageDateModified) values ");
-
var endIndex = Math.Min(chapters.Count, startIndex + limit);
for (var i = startIndex; i < endIndex; i++)
{
- insertText.AppendFormat("(@ItemId, @ChapterIndex{0}, @StartPositionTicks{0}, @Name{0}, @ImagePath{0}, @ImageDateModified{0}),", i.ToString(CultureInfo.InvariantCulture));
+ insertText.AppendFormat(CultureInfo.InvariantCulture, "(@ItemId, @ChapterIndex{0}, @StartPositionTicks{0}, @Name{0}, @ImagePath{0}, @ImageDateModified{0}),", i.ToString(CultureInfo.InvariantCulture));
}
+
insertText.Length -= 1; // Remove last ,
- using (var statement = PrepareStatementSafe(db, insertText.ToString()))
+ using (var statement = PrepareStatement(db, insertText.ToString()))
{
statement.TryBind("@ItemId", idBlob);
@@ -2069,6 +2152,7 @@ namespace Emby.Server.Implementations.Data
}
startIndex += limit;
+ insertText.Length = StartInsertText.Length;
}
}
@@ -2094,31 +2178,6 @@ namespace Emby.Server.Implementations.Data
|| query.IsLiked.HasValue;
}
- private readonly ItemFields[] _allFields = Enum.GetNames(typeof(ItemFields))
- .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
- .ToArray();
-
- private string[] GetColumnNamesFromField(ItemFields field)
- {
- switch (field)
- {
- case ItemFields.Settings:
- return new[] { "IsLocked", "PreferredMetadataCountryCode", "PreferredMetadataLanguage", "LockedFields" };
- case ItemFields.ServiceName:
- return new[] { "ExternalServiceId" };
- case ItemFields.SortName:
- return new[] { "ForcedSortName" };
- case ItemFields.Taglines:
- return new[] { "Tagline" };
- case ItemFields.Tags:
- return new[] { "Tags" };
- case ItemFields.IsHD:
- return Array.Empty<string>();
- default:
- return new[] { field.ToString() };
- }
- }
-
private bool HasField(InternalItemsQuery query, ItemFields name)
{
switch (name)
@@ -2151,23 +2210,6 @@ namespace Emby.Server.Implementations.Data
}
}
- private static readonly HashSet<string> _programExcludeParentTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Series",
- "Season",
- "MusicAlbum",
- "MusicArtist",
- "PhotoAlbum"
- };
-
- private static readonly HashSet<string> _programTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Program",
- "TvChannel",
- "LiveTvProgram",
- "LiveTvTvChannel"
- };
-
private bool HasProgramAttributes(InternalItemsQuery query)
{
if (_programExcludeParentTypes.Contains(query.ParentType))
@@ -2183,12 +2225,6 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Any(x => _programTypes.Contains(x));
}
- private static readonly HashSet<string> _serviceTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "TvChannel",
- "LiveTvTvChannel"
- };
-
private bool HasServiceName(InternalItemsQuery query)
{
if (_programExcludeParentTypes.Contains(query.ParentType))
@@ -2204,12 +2240,6 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Any(x => _serviceTypes.Contains(x));
}
- private static readonly HashSet<string> _startDateTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Program",
- "LiveTvProgram"
- };
-
private bool HasStartDate(InternalItemsQuery query)
{
if (_programExcludeParentTypes.Contains(query.ParentType))
@@ -2245,23 +2275,6 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Contains("Trailer", StringComparer.OrdinalIgnoreCase);
}
-
- private static readonly HashSet<string> _artistExcludeParentTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Series",
- "Season",
- "PhotoAlbum"
- };
-
- private static readonly HashSet<string> _artistsTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Audio",
- "MusicAlbum",
- "MusicVideo",
- "AudioBook",
- "AudioPodcast"
- };
-
private bool HasArtistFields(InternalItemsQuery query)
{
if (_artistExcludeParentTypes.Contains(query.ParentType))
@@ -2277,15 +2290,6 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Any(x => _artistsTypes.Contains(x));
}
- private static readonly HashSet<string> _seriesTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "Audio",
- "MusicAlbum",
- "MusicVideo",
- "AudioBook",
- "AudioPodcast"
- };
-
private bool HasSeriesFields(InternalItemsQuery query)
{
if (string.Equals(query.ParentType, "PhotoAlbum", StringComparison.OrdinalIgnoreCase))
@@ -2301,77 +2305,98 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Any(x => _seriesTypes.Contains(x));
}
- private List<string> GetFinalColumnsToSelect(InternalItemsQuery query, IEnumerable<string> startColumns)
+ private void SetFinalColumnsToSelect(InternalItemsQuery query, List<string> columns)
{
- var list = startColumns.ToList();
-
- foreach (var field in _allFields)
+ foreach (var field in _allItemFields)
{
if (!HasField(query, field))
{
- foreach (var fieldToRemove in GetColumnNamesFromField(field))
+ switch (field)
{
- list.Remove(fieldToRemove);
+ case ItemFields.Settings:
+ columns.Remove("IsLocked");
+ columns.Remove("PreferredMetadataCountryCode");
+ columns.Remove("PreferredMetadataLanguage");
+ columns.Remove("LockedFields");
+ break;
+ case ItemFields.ServiceName:
+ columns.Remove("ExternalServiceId");
+ break;
+ case ItemFields.SortName:
+ columns.Remove("ForcedSortName");
+ break;
+ case ItemFields.Taglines:
+ columns.Remove("Tagline");
+ break;
+ case ItemFields.Tags:
+ columns.Remove("Tags");
+ break;
+ case ItemFields.IsHD:
+ // do nothing
+ break;
+ default:
+ columns.Remove(field.ToString());
+ break;
}
}
}
if (!HasProgramAttributes(query))
{
- list.Remove("IsMovie");
- list.Remove("IsSeries");
- list.Remove("EpisodeTitle");
- list.Remove("IsRepeat");
- list.Remove("ShowId");
+ columns.Remove("IsMovie");
+ columns.Remove("IsSeries");
+ columns.Remove("EpisodeTitle");
+ columns.Remove("IsRepeat");
+ columns.Remove("ShowId");
}
if (!HasEpisodeAttributes(query))
{
- list.Remove("SeasonName");
- list.Remove("SeasonId");
+ columns.Remove("SeasonName");
+ columns.Remove("SeasonId");
}
if (!HasStartDate(query))
{
- list.Remove("StartDate");
+ columns.Remove("StartDate");
}
if (!HasTrailerTypes(query))
{
- list.Remove("TrailerTypes");
+ columns.Remove("TrailerTypes");
}
if (!HasArtistFields(query))
{
- list.Remove("AlbumArtists");
- list.Remove("Artists");
+ columns.Remove("AlbumArtists");
+ columns.Remove("Artists");
}
if (!HasSeriesFields(query))
{
- list.Remove("SeriesId");
+ columns.Remove("SeriesId");
}
if (!HasEpisodeAttributes(query))
{
- list.Remove("SeasonName");
- list.Remove("SeasonId");
+ columns.Remove("SeasonName");
+ columns.Remove("SeasonId");
}
if (!query.DtoOptions.EnableImages)
{
- list.Remove("Images");
+ columns.Remove("Images");
}
if (EnableJoinUserData(query))
{
- list.Add("UserDatas.UserId");
- list.Add("UserDatas.lastPlayedDate");
- list.Add("UserDatas.playbackPositionTicks");
- list.Add("UserDatas.playcount");
- list.Add("UserDatas.isFavorite");
- list.Add("UserDatas.played");
- list.Add("UserDatas.rating");
+ columns.Add("UserDatas.UserId");
+ columns.Add("UserDatas.lastPlayedDate");
+ columns.Add("UserDatas.playbackPositionTicks");
+ columns.Add("UserDatas.playcount");
+ columns.Add("UserDatas.isFavorite");
+ columns.Add("UserDatas.played");
+ columns.Add("UserDatas.rating");
}
if (query.SimilarTo != null)
@@ -2379,15 +2404,15 @@ namespace Emby.Server.Implementations.Data
var item = query.SimilarTo;
var builder = new StringBuilder();
- builder.Append("(");
+ builder.Append('(');
if (string.IsNullOrEmpty(item.OfficialRating))
{
- builder.Append("((OfficialRating is null) * 10)");
+ builder.Append("(OfficialRating is null * 10)");
}
else
{
- builder.Append("((OfficialRating=@ItemOfficialRating) * 10)");
+ builder.Append("(OfficialRating=@ItemOfficialRating * 10)");
}
if (item.ProductionYear.HasValue)
@@ -2396,12 +2421,30 @@ namespace Emby.Server.Implementations.Data
builder.Append("+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 5 Then 5 Else 0 End )");
}
- //// genres, tags
- builder.Append("+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId)) * 10)");
+ // genres, tags, studios, person, year?
+ builder.Append("+ (Select count(1) * 10 from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId))");
+
+ if (item is MusicArtist)
+ {
+ // Match albums where the artist is AlbumArtist against other albums.
+ // It is assumed that similar albums => similar artists.
+ builder.Append(
+ @"+ (WITH artistValues AS (
+ SELECT DISTINCT albumValues.CleanValue
+ FROM ItemValues albumValues
+ INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
+ INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = @SimilarItemId
+ ), similarArtist AS (
+ SELECT albumValues.ItemId
+ FROM ItemValues albumValues
+ INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
+ INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = A.Guid
+ ) SELECT COUNT(DISTINCT(CleanValue)) * 10 FROM ItemValues WHERE ItemId IN (SELECT ItemId FROM similarArtist) AND CleanValue IN (SELECT CleanValue FROM artistValues))");
+ }
builder.Append(") as SimilarityScore");
- list.Add(builder.ToString());
+ columns.Add(builder.ToString());
var oldLen = query.ExcludeItemIds.Length;
var newLen = oldLen + item.ExtraIds.Length + 1;
@@ -2417,7 +2460,7 @@ namespace Emby.Server.Implementations.Data
if (!string.IsNullOrEmpty(query.SearchTerm))
{
var builder = new StringBuilder();
- builder.Append("(");
+ builder.Append('(');
builder.Append("((CleanName like @SearchTermStartsWith or (OriginalTitle not null and OriginalTitle like @SearchTermStartsWith)) * 10)");
@@ -2428,10 +2471,8 @@ namespace Emby.Server.Implementations.Data
builder.Append(") as SearchScore");
- list.Add(builder.ToString());
+ columns.Add(builder.ToString());
}
-
- return list;
}
private void BindSearchParams(InternalItemsQuery query, IStatement statement)
@@ -2451,6 +2492,7 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@SearchTermStartsWith", searchTerm + "%");
}
+
if (commandText.IndexOf("@SearchTermContains", StringComparison.OrdinalIgnoreCase) != -1)
{
statement.TryBind("@SearchTermContains", "%" + searchTerm + "%");
@@ -2496,31 +2538,25 @@ namespace Emby.Server.Implementations.Data
private string GetGroupBy(InternalItemsQuery query)
{
- var groups = new List<string>();
-
- if (EnableGroupByPresentationUniqueKey(query))
+ var enableGroupByPresentationUniqueKey = EnableGroupByPresentationUniqueKey(query);
+ if (enableGroupByPresentationUniqueKey && query.GroupBySeriesPresentationUniqueKey)
{
- groups.Add("PresentationUniqueKey");
+ return " Group by PresentationUniqueKey, SeriesPresentationUniqueKey";
}
- if (query.GroupBySeriesPresentationUniqueKey)
+ if (enableGroupByPresentationUniqueKey)
{
- groups.Add("SeriesPresentationUniqueKey");
+ return " Group by PresentationUniqueKey";
}
- if (groups.Count > 0)
+ if (query.GroupBySeriesPresentationUniqueKey)
{
- return " Group by " + string.Join(",", groups);
+ return " Group by SeriesPresentationUniqueKey";
}
return string.Empty;
}
- private string GetFromText(string alias = "A")
- {
- return " from TypedBaseItems " + alias;
- }
-
public int GetCount(InternalItemsQuery query)
{
if (query == null)
@@ -2538,41 +2574,43 @@ namespace Emby.Server.Implementations.Data
query.Limit = query.Limit.Value + 4;
}
- var commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" }))
- + GetFromText()
- + GetJoinUserDataText(query);
+ var columns = new List<string> { "count(distinct PresentationUniqueKey)" };
+ SetFinalColumnsToSelect(query, columns);
+ var commandTextBuilder = new StringBuilder("select ", 256)
+ .AppendJoin(',', columns)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query));
var whereClauses = GetWhereClauses(query, null);
if (whereClauses.Count != 0)
{
- commandText += " where " + string.Join(" AND ", whereClauses);
+ commandTextBuilder.Append(" where ")
+ .AppendJoin(" AND ", whereClauses);
}
- using (WriteLock.Read())
+ var commandText = commandTextBuilder.ToString();
+ int count;
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, commandText))
{
- using (var statement = PrepareStatementSafe(connection, commandText))
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- var count = statement.ExecuteQuery().SelectScalarInt().First();
- LogQueryTime("GetCount", commandText, now);
- return count;
- }
+ count = statement.ExecuteQuery().SelectScalarInt().First();
}
-
}
+
+ LogQueryTime("GetCount", commandText, now);
+ return count;
}
public List<BaseItem> GetItemList(InternalItemsQuery query)
@@ -2592,20 +2630,23 @@ namespace Emby.Server.Implementations.Data
query.Limit = query.Limit.Value + 4;
}
- var commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, _retriveItemColumns))
- + GetFromText()
- + GetJoinUserDataText(query);
+ var columns = _retriveItemColumns.ToList();
+ SetFinalColumnsToSelect(query, columns);
+ var commandTextBuilder = new StringBuilder("select ", 1024)
+ .AppendJoin(',', columns)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query));
var whereClauses = GetWhereClauses(query, null);
if (whereClauses.Count != 0)
{
- commandText += " where " + string.Join(" AND ", whereClauses);
+ commandTextBuilder.Append(" where ")
+ .AppendJoin(" AND ", whereClauses);
}
- commandText += GetGroupBy(query)
- + GetOrderByText(query);
+ commandTextBuilder.Append(GetGroupBy(query))
+ .Append(GetOrderByText(query));
if (query.Limit.HasValue || query.StartIndex.HasValue)
{
@@ -2613,99 +2654,96 @@ namespace Emby.Server.Implementations.Data
if (query.Limit.HasValue || offset > 0)
{
- commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" LIMIT ")
+ .Append(query.Limit ?? int.MaxValue);
}
if (offset > 0)
{
- commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" OFFSET ")
+ .Append(offset);
}
}
- using (WriteLock.Read())
+ var commandText = commandTextBuilder.ToString();
+ var items = new List<BaseItem>();
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, commandText))
{
- var list = new List<BaseItem>();
-
- using (var statement = PrepareStatementSafe(connection, commandText))
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- var hasEpisodeAttributes = HasEpisodeAttributes(query);
- var hasServiceName = HasServiceName(query);
- var hasProgramAttributes = HasProgramAttributes(query);
- var hasStartDate = HasStartDate(query);
- var hasTrailerTypes = HasTrailerTypes(query);
- var hasArtistFields = HasArtistFields(query);
- var hasSeriesFields = HasSeriesFields(query);
+ var hasEpisodeAttributes = HasEpisodeAttributes(query);
+ var hasServiceName = HasServiceName(query);
+ var hasProgramAttributes = HasProgramAttributes(query);
+ var hasStartDate = HasStartDate(query);
+ var hasTrailerTypes = HasTrailerTypes(query);
+ var hasArtistFields = HasArtistFields(query);
+ var hasSeriesFields = HasSeriesFields(query);
- foreach (var row in statement.ExecuteQuery())
+ foreach (var row in statement.ExecuteQuery())
+ {
+ var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
+ if (item != null)
{
- var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
- if (item != null)
- {
- list.Add(item);
- }
+ items.Add(item);
}
}
+ }
+
+ // Hack for right now since we currently don't support filtering out these duplicates within a query
+ if (query.EnableGroupByMetadataKey)
+ {
+ var limit = query.Limit ?? int.MaxValue;
+ limit -= 4;
+ var newList = new List<BaseItem>();
- // Hack for right now since we currently don't support filtering out these duplicates within a query
- if (query.EnableGroupByMetadataKey)
+ foreach (var item in items)
{
- var limit = query.Limit ?? int.MaxValue;
- limit -= 4;
- var newList = new List<BaseItem>();
+ AddItem(newList, item);
- foreach (var item in list)
+ if (newList.Count >= limit)
{
- AddItem(newList, item);
-
- if (newList.Count >= limit)
- {
- break;
- }
+ break;
}
-
- list = newList;
}
- LogQueryTime("GetItemList", commandText, now);
-
- return list;
+ items = newList;
}
}
+
+ LogQueryTime("GetItemList", commandText, now);
+
+ return items;
}
private string FixUnicodeChars(string buffer)
{
- if (buffer.IndexOf('\u2013') > -1) buffer = buffer.Replace('\u2013', '-'); // en dash
- if (buffer.IndexOf('\u2014') > -1) buffer = buffer.Replace('\u2014', '-'); // em dash
- if (buffer.IndexOf('\u2015') > -1) buffer = buffer.Replace('\u2015', '-'); // horizontal bar
- if (buffer.IndexOf('\u2017') > -1) buffer = buffer.Replace('\u2017', '_'); // double low line
- if (buffer.IndexOf('\u2018') > -1) buffer = buffer.Replace('\u2018', '\''); // left single quotation mark
- if (buffer.IndexOf('\u2019') > -1) buffer = buffer.Replace('\u2019', '\''); // right single quotation mark
- if (buffer.IndexOf('\u201a') > -1) buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark
- if (buffer.IndexOf('\u201b') > -1) buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark
- if (buffer.IndexOf('\u201c') > -1) buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark
- if (buffer.IndexOf('\u201d') > -1) buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark
- if (buffer.IndexOf('\u201e') > -1) buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark
- if (buffer.IndexOf('\u2026') > -1) buffer = buffer.Replace("\u2026", "..."); // horizontal ellipsis
- if (buffer.IndexOf('\u2032') > -1) buffer = buffer.Replace('\u2032', '\''); // prime
- if (buffer.IndexOf('\u2033') > -1) buffer = buffer.Replace('\u2033', '\"'); // double prime
- if (buffer.IndexOf('\u0060') > -1) buffer = buffer.Replace('\u0060', '\''); // grave accent
- if (buffer.IndexOf('\u00B4') > -1) buffer = buffer.Replace('\u00B4', '\''); // acute accent
-
- return buffer;
+ buffer = buffer.Replace('\u2013', '-'); // en dash
+ buffer = buffer.Replace('\u2014', '-'); // em dash
+ buffer = buffer.Replace('\u2015', '-'); // horizontal bar
+ buffer = buffer.Replace('\u2017', '_'); // double low line
+ buffer = buffer.Replace('\u2018', '\''); // left single quotation mark
+ buffer = buffer.Replace('\u2019', '\''); // right single quotation mark
+ buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark
+ buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark
+ buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark
+ buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark
+ buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark
+ buffer = buffer.Replace("\u2026", "...", StringComparison.Ordinal); // horizontal ellipsis
+ buffer = buffer.Replace('\u2032', '\''); // prime
+ buffer = buffer.Replace('\u2033', '\"'); // double prime
+ buffer = buffer.Replace('\u0060', '\''); // grave accent
+ return buffer.Replace('\u00B4', '\''); // acute accent
}
private void AddItem(List<BaseItem> items, BaseItem newItem)
@@ -2716,7 +2754,7 @@ namespace Emby.Server.Implementations.Data
foreach (var providerId in newItem.ProviderIds)
{
- if (providerId.Key == MetadataProviders.TmdbCollection.ToString())
+ if (providerId.Key == MetadataProvider.TmdbCollection.ToString())
{
continue;
}
@@ -2727,6 +2765,7 @@ namespace Emby.Server.Implementations.Data
{
items[i] = newItem;
}
+
return;
}
}
@@ -2739,15 +2778,16 @@ namespace Emby.Server.Implementations.Data
{
var elapsed = (DateTime.UtcNow - startDate).TotalMilliseconds;
- int slowThreshold = 100;
-
#if DEBUG
- slowThreshold = 10;
+ const int SlowThreshold = 100;
+#else
+ const int SlowThreshold = 10;
#endif
- if (elapsed >= slowThreshold)
+ if (elapsed >= SlowThreshold)
{
- Logger.LogWarning("{0} query time (slow): {1}ms. Query: {2}",
+ Logger.LogDebug(
+ "{Method} query time (slow): {ElapsedMs}ms. Query: {Query}",
methodName,
elapsed,
commandText);
@@ -2768,35 +2808,40 @@ namespace Emby.Server.Implementations.Data
var returnList = GetItemList(query);
return new QueryResult<BaseItem>
{
- Items = returnList.ToArray(),
+ Items = returnList,
TotalRecordCount = returnList.Count
};
}
var now = DateTime.UtcNow;
- var list = new List<BaseItem>();
-
// Hack for right now since we currently don't support filtering out these duplicates within a query
if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
{
query.Limit = query.Limit.Value + 4;
}
- var commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, _retriveItemColumns))
- + GetFromText()
- + GetJoinUserDataText(query);
+ var columns = _retriveItemColumns.ToList();
+ SetFinalColumnsToSelect(query, columns);
+ var commandTextBuilder = new StringBuilder("select ", 512)
+ .AppendJoin(',', columns)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query));
var whereClauses = GetWhereClauses(query, null);
var whereText = whereClauses.Count == 0 ?
string.Empty :
- " where " + string.Join(" AND ", whereClauses);
+ string.Join(" AND ", whereClauses);
- commandText += whereText
- + GetGroupBy(query)
- + GetOrderByText(query);
+ if (!string.IsNullOrEmpty(whereText))
+ {
+ commandTextBuilder.Append(" where ")
+ .Append(whereText);
+ }
+
+ commandTextBuilder.Append(GetGroupBy(query))
+ .Append(GetOrderByText(query));
if (query.Limit.HasValue || query.StartIndex.HasValue)
{
@@ -2804,158 +2849,170 @@ namespace Emby.Server.Implementations.Data
if (query.Limit.HasValue || offset > 0)
{
- commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" LIMIT ")
+ .Append(query.Limit ?? int.MaxValue);
}
if (offset > 0)
{
- commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" OFFSET ")
+ .Append(offset);
}
}
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
- var statementTexts = new List<string>();
+ var itemQuery = string.Empty;
+ var totalRecordCountQuery = string.Empty;
if (!isReturningZeroItems)
{
- statementTexts.Add(commandText);
+ itemQuery = commandTextBuilder.ToString();
}
+
if (query.EnableTotalRecordCount)
{
- commandText = string.Empty;
+ commandTextBuilder.Clear();
+
+ commandTextBuilder.Append(" select ");
+ List<string> columnsToSelect;
if (EnableGroupByPresentationUniqueKey(query))
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (distinct PresentationUniqueKey)" };
}
else if (query.GroupBySeriesPresentationUniqueKey)
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (distinct SeriesPresentationUniqueKey)" };
}
else
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (guid)" };
}
- commandText += GetJoinUserDataText(query)
- + whereText;
- statementTexts.Add(commandText);
+ SetFinalColumnsToSelect(query, columnsToSelect);
+
+ commandTextBuilder.AppendJoin(',', columnsToSelect)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query));
+ if (!string.IsNullOrEmpty(whereText))
+ {
+ commandTextBuilder.Append(" where ")
+ .Append(whereText);
+ }
+
+ totalRecordCountQuery = commandTextBuilder.ToString();
}
- using (WriteLock.Read())
+ var list = new List<BaseItem>();
+ var result = new QueryResult<BaseItem>();
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ connection.RunInTransaction(
+ db =>
{
- return connection.RunInTransaction(db =>
- {
- var result = new QueryResult<BaseItem>();
- var statements = PrepareAllSafe(db, statementTexts);
+ var itemQueryStatement = PrepareStatement(db, itemQuery);
+ var totalRecordCountQueryStatement = PrepareStatement(db, totalRecordCountQuery);
- if (!isReturningZeroItems)
+ if (!isReturningZeroItems)
+ {
+ using (var statement = itemQueryStatement)
{
- using (var statement = statements[0])
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- var hasEpisodeAttributes = HasEpisodeAttributes(query);
- var hasServiceName = HasServiceName(query);
- var hasProgramAttributes = HasProgramAttributes(query);
- var hasStartDate = HasStartDate(query);
- var hasTrailerTypes = HasTrailerTypes(query);
- var hasArtistFields = HasArtistFields(query);
- var hasSeriesFields = HasSeriesFields(query);
+ var hasEpisodeAttributes = HasEpisodeAttributes(query);
+ var hasServiceName = HasServiceName(query);
+ var hasProgramAttributes = HasProgramAttributes(query);
+ var hasStartDate = HasStartDate(query);
+ var hasTrailerTypes = HasTrailerTypes(query);
+ var hasArtistFields = HasArtistFields(query);
+ var hasSeriesFields = HasSeriesFields(query);
- foreach (var row in statement.ExecuteQuery())
+ foreach (var row in statement.ExecuteQuery())
+ {
+ var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
+ if (item != null)
{
- var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
- if (item != null)
- {
- list.Add(item);
- }
+ list.Add(item);
}
}
}
- if (query.EnableTotalRecordCount)
+ LogQueryTime("GetItems.ItemQuery", itemQuery, now);
+ }
+
+ now = DateTime.UtcNow;
+ if (query.EnableTotalRecordCount)
+ {
+ using (var statement = totalRecordCountQueryStatement)
{
- using (var statement = statements[statements.Count - 1])
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
+ result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
}
- LogQueryTime("GetItems", commandText, now);
-
- result.Items = list.ToArray();
- return result;
-
- }, ReadTransactionMode);
- }
+ LogQueryTime("GetItems.TotalRecordCount", totalRecordCountQuery, now);
+ }
+ }, ReadTransactionMode);
}
+
+ result.Items = list;
+ return result;
}
private string GetOrderByText(InternalItemsQuery query)
{
- if (string.IsNullOrEmpty(query.SearchTerm))
- {
- int oldLen = query.OrderBy.Length;
+ var orderBy = query.OrderBy;
+ bool hasSimilar = query.SimilarTo != null;
+ bool hasSearch = !string.IsNullOrEmpty(query.SearchTerm);
- if (query.SimilarTo != null && oldLen == 0)
- {
- var arr = new (string, SortOrder)[oldLen + 2];
- query.OrderBy.CopyTo(arr, 0);
- arr[oldLen] = ("SimilarityScore", SortOrder.Descending);
- arr[oldLen + 1] = (ItemSortBy.Random, SortOrder.Ascending);
- query.OrderBy = arr;
- }
- }
- else
+ if (hasSimilar || hasSearch)
{
- query.OrderBy = new []
+ List<(string, SortOrder)> prepend = new List<(string, SortOrder)>(4);
+ if (hasSearch)
{
- ("SearchScore", SortOrder.Descending),
- (ItemSortBy.SortName, SortOrder.Ascending)
- };
- }
+ prepend.Add(("SearchScore", SortOrder.Descending));
+ prepend.Add((ItemSortBy.SortName, SortOrder.Ascending));
+ }
- var orderBy = query.OrderBy;
+ if (hasSimilar)
+ {
+ prepend.Add(("SimilarityScore", SortOrder.Descending));
+ prepend.Add((ItemSortBy.Random, SortOrder.Ascending));
+ }
- if (orderBy.Length == 0)
+ var arr = new (string, SortOrder)[prepend.Count + orderBy.Count];
+ prepend.CopyTo(arr, 0);
+ orderBy.CopyTo(arr, prepend.Count);
+ orderBy = query.OrderBy = arr;
+ }
+ else if (orderBy.Count == 0)
{
return string.Empty;
}
- return " ORDER BY " + string.Join(",", orderBy.Select(i =>
+ return " ORDER BY " + string.Join(',', orderBy.Select(i =>
{
var columnMap = MapOrderByField(i.Item1, query);
- var columnAscending = i.Item2 == SortOrder.Ascending;
- const bool enableOrderInversion = false;
- if (columnMap.Item2 && enableOrderInversion)
- {
- columnAscending = !columnAscending;
- }
- var sortOrder = columnAscending ? "ASC" : "DESC";
+ var sortOrder = i.Item2 == SortOrder.Ascending ? "ASC" : "DESC";
return columnMap.Item1 + " " + sortOrder;
}));
@@ -3048,19 +3105,22 @@ namespace Emby.Server.Implementations.Data
var now = DateTime.UtcNow;
- var commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid" }))
- + GetFromText()
- + GetJoinUserDataText(query);
+ var columns = new List<string> { "guid" };
+ SetFinalColumnsToSelect(query, columns);
+ var commandTextBuilder = new StringBuilder("select ", 256)
+ .AppendJoin(',', columns)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query));
var whereClauses = GetWhereClauses(query, null);
if (whereClauses.Count != 0)
{
- commandText += " where " + string.Join(" AND ", whereClauses);
+ commandTextBuilder.Append(" where ")
+ .AppendJoin(" AND ", whereClauses);
}
- commandText += GetGroupBy(query)
- + GetOrderByText(query);
+ commandTextBuilder.Append(GetGroupBy(query))
+ .Append(GetOrderByText(query));
if (query.Limit.HasValue || query.StartIndex.HasValue)
{
@@ -3068,45 +3128,43 @@ namespace Emby.Server.Implementations.Data
if (query.Limit.HasValue || offset > 0)
{
- commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" LIMIT ")
+ .Append(query.Limit ?? int.MaxValue);
}
if (offset > 0)
{
- commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture);
+ commandTextBuilder.Append(" OFFSET ")
+ .Append(offset);
}
}
- using (WriteLock.Read())
+ var commandText = commandTextBuilder.ToString();
+ var list = new List<Guid>();
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, commandText))
{
- var list = new List<Guid>();
-
- using (var statement = PrepareStatementSafe(connection, commandText))
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(row[0].ReadGuidFromBlob());
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(row[0].ReadGuidFromBlob());
}
-
- LogQueryTime("GetItemList", commandText, now);
-
- return list;
}
}
+
+ LogQueryTime("GetItemList", commandText, now);
+ return list;
}
public List<Tuple<Guid, string>> GetItemIdsWithPath(InternalItemsQuery query)
@@ -3120,7 +3178,9 @@ namespace Emby.Server.Implementations.Data
var now = DateTime.UtcNow;
- var commandText = "select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid", "path" })) + GetFromText();
+ var columns = new List<string> { "guid", "path" };
+ SetFinalColumnsToSelect(query, columns);
+ var commandText = "select " + string.Join(',', columns) + FromText;
var whereClauses = GetWhereClauses(query, null);
if (whereClauses.Count != 0)
@@ -3146,39 +3206,33 @@ namespace Emby.Server.Implementations.Data
}
}
- using (WriteLock.Read())
+ var list = new List<Tuple<Guid, string>>();
+ using (var connection = GetConnection(true))
{
- var list = new List<Tuple<Guid, string>>();
- using (var connection = CreateConnection(true))
+ using (var statement = PrepareStatement(connection, commandText))
{
- using (var statement = PrepareStatementSafe(connection, commandText))
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- var id = row.GetGuid(0);
- string path = null;
+ foreach (var row in statement.ExecuteQuery())
+ {
+ var id = row.GetGuid(0);
- if (!row.IsDBNull(1))
- {
- path = row.GetString(1);
- }
- list.Add(new Tuple<Guid, string>(id, path));
- }
+ row.TryGetString(1, out var path);
+
+ list.Add(new Tuple<Guid, string>(id, path));
}
}
+ }
- LogQueryTime("GetItemIdsWithPath", commandText, now);
+ LogQueryTime("GetItemIdsWithPath", commandText, now);
- return list;
- }
+ return list;
}
public QueryResult<Guid> GetItemIds(InternalItemsQuery query)
@@ -3195,16 +3249,18 @@ namespace Emby.Server.Implementations.Data
var returnList = GetItemIdsList(query);
return new QueryResult<Guid>
{
- Items = returnList.ToArray(),
+ Items = returnList,
TotalRecordCount = returnList.Count
};
}
var now = DateTime.UtcNow;
+ var columns = new List<string> { "guid" };
+ SetFinalColumnsToSelect(query, columns);
var commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid" }))
- + GetFromText()
+ + string.Join(',', columns)
+ + FromText
+ GetJoinUserDataText(query);
var whereClauses = GetWhereClauses(query, null);
@@ -3232,7 +3288,6 @@ namespace Emby.Server.Implementations.Data
}
}
- var list = new List<Guid>();
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
var statementTexts = new List<string>();
@@ -3240,87 +3295,89 @@ namespace Emby.Server.Implementations.Data
{
statementTexts.Add(commandText);
}
+
if (query.EnableTotalRecordCount)
{
commandText = string.Empty;
+ List<string> columnsToSelect;
if (EnableGroupByPresentationUniqueKey(query))
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (distinct PresentationUniqueKey)" };
}
else if (query.GroupBySeriesPresentationUniqueKey)
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (distinct SeriesPresentationUniqueKey)" };
}
else
{
- commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText();
+ columnsToSelect = new List<string> { "count (guid)" };
}
+ SetFinalColumnsToSelect(query, columnsToSelect);
+ commandText += " select " + string.Join(',', columnsToSelect) + FromText;
+
commandText += GetJoinUserDataText(query)
+ whereText;
statementTexts.Add(commandText);
}
- using (WriteLock.Read())
+ var list = new List<Guid>();
+ var result = new QueryResult<Guid>();
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ connection.RunInTransaction(
+ db =>
{
- return connection.RunInTransaction(db =>
- {
- var result = new QueryResult<Guid>();
-
- var statements = PrepareAllSafe(db, statementTexts);
+ var statements = PrepareAll(db, statementTexts);
- if (!isReturningZeroItems)
+ if (!isReturningZeroItems)
+ {
+ using (var statement = statements[0])
{
- using (var statement = statements[0])
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(row[0].ReadGuidFromBlob());
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(row[0].ReadGuidFromBlob());
}
}
+ }
- if (query.EnableTotalRecordCount)
+ if (query.EnableTotalRecordCount)
+ {
+ using (var statement = statements[statements.Length - 1])
{
- using (var statement = statements[statements.Count - 1])
+ if (EnableJoinUserData(query))
{
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
- // Running this again will bind the params
- GetWhereClauses(query, statement);
+ // Running this again will bind the params
+ GetWhereClauses(query, statement);
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
+ result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
}
+ }
+ }, ReadTransactionMode);
+ }
- LogQueryTime("GetItemIds", commandText, now);
-
- result.Items = list.ToArray();
- return result;
+ LogQueryTime("GetItemIds", commandText, now);
- }, ReadTransactionMode);
- }
- }
+ result.Items = list;
+ return result;
}
private bool IsAlphaNumeric(string str)
@@ -3332,7 +3389,7 @@ namespace Emby.Server.Implementations.Data
for (int i = 0; i < str.Length; i++)
{
- if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
+ if (!char.IsLetter(str[i]) && !char.IsNumber(str[i]))
{
return false;
}
@@ -3356,7 +3413,7 @@ namespace Emby.Server.Implementations.Data
return IsAlphaNumeric(value);
}
- private List<string> GetWhereClauses(InternalItemsQuery query, IStatement statement, string paramSuffix = "")
+ private List<string> GetWhereClauses(InternalItemsQuery query, IStatement statement)
{
if (query.IsResumable ?? false)
{
@@ -3368,27 +3425,27 @@ namespace Emby.Server.Implementations.Data
if (query.IsHD.HasValue)
{
- var threshold = 1200;
+ const int Threshold = 1200;
if (query.IsHD.Value)
{
- minWidth = threshold;
+ minWidth = Threshold;
}
else
{
- maxWidth = threshold - 1;
+ maxWidth = Threshold - 1;
}
}
if (query.Is4K.HasValue)
{
- var threshold = 3800;
+ const int Threshold = 3800;
if (query.Is4K.Value)
{
- minWidth = threshold;
+ minWidth = Threshold;
}
else
{
- maxWidth = threshold - 1;
+ maxWidth = Threshold - 1;
}
}
@@ -3397,93 +3454,61 @@ namespace Emby.Server.Implementations.Data
if (minWidth.HasValue)
{
whereClauses.Add("Width>=@MinWidth");
- if (statement != null)
- {
- statement.TryBind("@MinWidth", minWidth);
- }
+ statement?.TryBind("@MinWidth", minWidth);
}
+
if (query.MinHeight.HasValue)
{
whereClauses.Add("Height>=@MinHeight");
- if (statement != null)
- {
- statement.TryBind("@MinHeight", query.MinHeight);
- }
+ statement?.TryBind("@MinHeight", query.MinHeight);
}
+
if (maxWidth.HasValue)
{
whereClauses.Add("Width<=@MaxWidth");
- if (statement != null)
- {
- statement.TryBind("@MaxWidth", maxWidth);
- }
+ statement?.TryBind("@MaxWidth", maxWidth);
}
+
if (query.MaxHeight.HasValue)
{
whereClauses.Add("Height<=@MaxHeight");
- if (statement != null)
- {
- statement.TryBind("@MaxHeight", query.MaxHeight);
- }
+ statement?.TryBind("@MaxHeight", query.MaxHeight);
}
if (query.IsLocked.HasValue)
{
whereClauses.Add("IsLocked=@IsLocked");
- if (statement != null)
- {
- statement.TryBind("@IsLocked", query.IsLocked);
- }
+ statement?.TryBind("@IsLocked", query.IsLocked);
}
var tags = query.Tags.ToList();
var excludeTags = query.ExcludeTags.ToList();
- if (query.IsMovie ?? false)
+ if (query.IsMovie == true)
{
- var alternateTypes = new List<string>();
- if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Movie).Name))
- {
- alternateTypes.Add(typeof(Movie).FullName);
- }
- if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Trailer).Name))
- {
- alternateTypes.Add(typeof(Trailer).FullName);
- }
-
- var programAttribtues = new List<string>();
- if (alternateTypes.Count == 0)
+ if (query.IncludeItemTypes.Length == 0
+ || query.IncludeItemTypes.Contains(nameof(Movie))
+ || query.IncludeItemTypes.Contains(nameof(Trailer)))
{
- programAttribtues.Add("IsMovie=@IsMovie");
+ whereClauses.Add("(IsMovie is null OR IsMovie=@IsMovie)");
}
else
{
- programAttribtues.Add("(IsMovie is null OR IsMovie=@IsMovie)");
+ whereClauses.Add("IsMovie=@IsMovie");
}
- if (statement != null)
- {
- statement.TryBind("@IsMovie", true);
- }
-
- whereClauses.Add("(" + string.Join(" OR ", programAttribtues) + ")");
+ statement?.TryBind("@IsMovie", true);
}
else if (query.IsMovie.HasValue)
{
whereClauses.Add("IsMovie=@IsMovie");
- if (statement != null)
- {
- statement.TryBind("@IsMovie", query.IsMovie);
- }
+ statement?.TryBind("@IsMovie", query.IsMovie);
}
if (query.IsSeries.HasValue)
{
whereClauses.Add("IsSeries=@IsSeries");
- if (statement != null)
- {
- statement.TryBind("@IsSeries", query.IsSeries);
- }
+ statement?.TryBind("@IsSeries", query.IsSeries);
}
if (query.IsSports.HasValue)
@@ -3535,155 +3560,111 @@ namespace Emby.Server.Implementations.Data
if (query.IsFolder.HasValue)
{
whereClauses.Add("IsFolder=@IsFolder");
- if (statement != null)
- {
- statement.TryBind("@IsFolder", query.IsFolder);
- }
- }
-
- var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray();
- if (includeTypes.Length == 1)
- {
- whereClauses.Add("type=@type");
- if (statement != null)
- {
- statement.TryBind("@type", includeTypes[0]);
- }
- }
- else if (includeTypes.Length > 1)
- {
- var inClause = string.Join(",", includeTypes.Select(i => "'" + i + "'"));
- whereClauses.Add($"type in ({inClause})");
+ statement?.TryBind("@IsFolder", query.IsFolder);
}
+ var includeTypes = query.IncludeItemTypes.Select(MapIncludeItemTypes).Where(x => x != null).ToArray();
// Only specify excluded types if no included types are specified
if (includeTypes.Length == 0)
{
- var excludeTypes = query.ExcludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray();
+ var excludeTypes = query.ExcludeItemTypes.Select(MapIncludeItemTypes).Where(x => x != null).ToArray();
if (excludeTypes.Length == 1)
{
whereClauses.Add("type<>@type");
- if (statement != null)
- {
- statement.TryBind("@type", excludeTypes[0]);
- }
+ statement?.TryBind("@type", excludeTypes[0]);
}
else if (excludeTypes.Length > 1)
{
- var inClause = string.Join(",", excludeTypes.Select(i => "'" + i + "'"));
+ var inClause = string.Join(',', excludeTypes.Select(i => "'" + i + "'"));
whereClauses.Add($"type not in ({inClause})");
}
}
+ else if (includeTypes.Length == 1)
+ {
+ whereClauses.Add("type=@type");
+ statement?.TryBind("@type", includeTypes[0]);
+ }
+ else if (includeTypes.Length > 1)
+ {
+ var inClause = string.Join(',', includeTypes.Select(i => "'" + i + "'"));
+ whereClauses.Add($"type in ({inClause})");
+ }
- if (query.ChannelIds.Length == 1)
+ if (query.ChannelIds.Count == 1)
{
whereClauses.Add("ChannelId=@ChannelId");
- if (statement != null)
- {
- statement.TryBind("@ChannelId", query.ChannelIds[0].ToString("N"));
- }
+ statement?.TryBind("@ChannelId", query.ChannelIds[0].ToString("N", CultureInfo.InvariantCulture));
}
- else if (query.ChannelIds.Length > 1)
+ else if (query.ChannelIds.Count > 1)
{
- var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i.ToString("N") + "'"));
+ var inClause = string.Join(',', query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
whereClauses.Add($"ChannelId in ({inClause})");
}
if (!query.ParentId.Equals(Guid.Empty))
{
whereClauses.Add("ParentId=@ParentId");
- if (statement != null)
- {
- statement.TryBind("@ParentId", query.ParentId);
- }
+ statement?.TryBind("@ParentId", query.ParentId);
}
if (!string.IsNullOrWhiteSpace(query.Path))
{
whereClauses.Add("Path=@Path");
- if (statement != null)
- {
- statement.TryBind("@Path", GetPathToSave(query.Path));
- }
+ statement?.TryBind("@Path", GetPathToSave(query.Path));
}
if (!string.IsNullOrWhiteSpace(query.PresentationUniqueKey))
{
whereClauses.Add("PresentationUniqueKey=@PresentationUniqueKey");
- if (statement != null)
- {
- statement.TryBind("@PresentationUniqueKey", query.PresentationUniqueKey);
- }
+ statement?.TryBind("@PresentationUniqueKey", query.PresentationUniqueKey);
}
if (query.MinCommunityRating.HasValue)
{
whereClauses.Add("CommunityRating>=@MinCommunityRating");
- if (statement != null)
- {
- statement.TryBind("@MinCommunityRating", query.MinCommunityRating.Value);
- }
+ statement?.TryBind("@MinCommunityRating", query.MinCommunityRating.Value);
}
if (query.MinIndexNumber.HasValue)
{
whereClauses.Add("IndexNumber>=@MinIndexNumber");
- if (statement != null)
- {
- statement.TryBind("@MinIndexNumber", query.MinIndexNumber.Value);
- }
+ statement?.TryBind("@MinIndexNumber", query.MinIndexNumber.Value);
}
if (query.MinDateCreated.HasValue)
{
whereClauses.Add("DateCreated>=@MinDateCreated");
- if (statement != null)
- {
- statement.TryBind("@MinDateCreated", query.MinDateCreated.Value);
- }
+ statement?.TryBind("@MinDateCreated", query.MinDateCreated.Value);
}
if (query.MinDateLastSaved.HasValue)
{
whereClauses.Add("(DateLastSaved not null and DateLastSaved>=@MinDateLastSavedForUser)");
- if (statement != null)
- {
- statement.TryBind("@MinDateLastSaved", query.MinDateLastSaved.Value);
- }
+ statement?.TryBind("@MinDateLastSaved", query.MinDateLastSaved.Value);
}
if (query.MinDateLastSavedForUser.HasValue)
{
whereClauses.Add("(DateLastSaved not null and DateLastSaved>=@MinDateLastSavedForUser)");
- if (statement != null)
- {
- statement.TryBind("@MinDateLastSavedForUser", query.MinDateLastSavedForUser.Value);
- }
+ statement?.TryBind("@MinDateLastSavedForUser", query.MinDateLastSavedForUser.Value);
}
if (query.IndexNumber.HasValue)
{
whereClauses.Add("IndexNumber=@IndexNumber");
- if (statement != null)
- {
- statement.TryBind("@IndexNumber", query.IndexNumber.Value);
- }
+ statement?.TryBind("@IndexNumber", query.IndexNumber.Value);
}
+
if (query.ParentIndexNumber.HasValue)
{
whereClauses.Add("ParentIndexNumber=@ParentIndexNumber");
- if (statement != null)
- {
- statement.TryBind("@ParentIndexNumber", query.ParentIndexNumber.Value);
- }
+ statement?.TryBind("@ParentIndexNumber", query.ParentIndexNumber.Value);
}
+
if (query.ParentIndexNumberNotEquals.HasValue)
{
whereClauses.Add("(ParentIndexNumber<>@ParentIndexNumberNotEquals or ParentIndexNumber is null)");
- if (statement != null)
- {
- statement.TryBind("@ParentIndexNumberNotEquals", query.ParentIndexNumberNotEquals.Value);
- }
+ statement?.TryBind("@ParentIndexNumberNotEquals", query.ParentIndexNumberNotEquals.Value);
}
var minEndDate = query.MinEndDate;
@@ -3704,73 +3685,64 @@ namespace Emby.Server.Implementations.Data
if (minEndDate.HasValue)
{
whereClauses.Add("EndDate>=@MinEndDate");
- if (statement != null)
- {
- statement.TryBind("@MinEndDate", minEndDate.Value);
- }
+ statement?.TryBind("@MinEndDate", minEndDate.Value);
}
if (maxEndDate.HasValue)
{
whereClauses.Add("EndDate<=@MaxEndDate");
- if (statement != null)
- {
- statement.TryBind("@MaxEndDate", maxEndDate.Value);
- }
+ statement?.TryBind("@MaxEndDate", maxEndDate.Value);
}
if (query.MinStartDate.HasValue)
{
whereClauses.Add("StartDate>=@MinStartDate");
- if (statement != null)
- {
- statement.TryBind("@MinStartDate", query.MinStartDate.Value);
- }
+ statement?.TryBind("@MinStartDate", query.MinStartDate.Value);
}
if (query.MaxStartDate.HasValue)
{
whereClauses.Add("StartDate<=@MaxStartDate");
- if (statement != null)
- {
- statement.TryBind("@MaxStartDate", query.MaxStartDate.Value);
- }
+ statement?.TryBind("@MaxStartDate", query.MaxStartDate.Value);
}
if (query.MinPremiereDate.HasValue)
{
whereClauses.Add("PremiereDate>=@MinPremiereDate");
- if (statement != null)
- {
- statement.TryBind("@MinPremiereDate", query.MinPremiereDate.Value);
- }
+ statement?.TryBind("@MinPremiereDate", query.MinPremiereDate.Value);
}
+
if (query.MaxPremiereDate.HasValue)
{
whereClauses.Add("PremiereDate<=@MaxPremiereDate");
- if (statement != null)
- {
- statement.TryBind("@MaxPremiereDate", query.MaxPremiereDate.Value);
- }
+ statement?.TryBind("@MaxPremiereDate", query.MaxPremiereDate.Value);
}
- if (query.TrailerTypes.Length > 0)
+ StringBuilder clauseBuilder = new StringBuilder();
+ const string Or = " OR ";
+
+ var trailerTypes = query.TrailerTypes;
+ int trailerTypesLen = trailerTypes.Length;
+ if (trailerTypesLen > 0)
{
- var clauses = new List<string>();
- var index = 0;
- foreach (var type in query.TrailerTypes)
- {
- var paramName = "@TrailerTypes" + index;
+ clauseBuilder.Append('(');
- clauses.Add("TrailerTypes like " + paramName);
- if (statement != null)
- {
- statement.TryBind(paramName, "%" + type + "%");
- }
- index++;
+ for (int i = 0; i < trailerTypesLen; i++)
+ {
+ var paramName = "@TrailerTypes" + i;
+ clauseBuilder.Append("TrailerTypes like ")
+ .Append(paramName)
+ .Append(Or);
+ statement?.TryBind(paramName, "%" + trailerTypes[i] + "%");
}
- var clause = "(" + string.Join(" OR ", clauses) + ")";
- whereClauses.Add(clause);
+
+ // Remove last " OR "
+ clauseBuilder.Length -= Or.Length;
+ clauseBuilder.Append(')');
+
+ whereClauses.Add(clauseBuilder.ToString());
+
+ clauseBuilder.Length = 0;
}
if (query.IsAiring.HasValue)
@@ -3778,93 +3750,77 @@ namespace Emby.Server.Implementations.Data
if (query.IsAiring.Value)
{
whereClauses.Add("StartDate<=@MaxStartDate");
- if (statement != null)
- {
- statement.TryBind("@MaxStartDate", DateTime.UtcNow);
- }
+ statement?.TryBind("@MaxStartDate", DateTime.UtcNow);
whereClauses.Add("EndDate>=@MinEndDate");
- if (statement != null)
- {
- statement.TryBind("@MinEndDate", DateTime.UtcNow);
- }
+ statement?.TryBind("@MinEndDate", DateTime.UtcNow);
}
else
{
whereClauses.Add("(StartDate>@IsAiringDate OR EndDate < @IsAiringDate)");
- if (statement != null)
- {
- statement.TryBind("@IsAiringDate", DateTime.UtcNow);
- }
+ statement?.TryBind("@IsAiringDate", DateTime.UtcNow);
}
}
- if (query.PersonIds.Length > 0)
+ int personIdsLen = query.PersonIds.Length;
+ if (personIdsLen > 0)
{
// TODO: Should this query with CleanName ?
- var clauses = new List<string>();
- var index = 0;
- foreach (var personId in query.PersonIds)
- {
- var paramName = "@PersonId" + index;
+ clauseBuilder.Append('(');
- clauses.Add("(guid in (select itemid from People where Name = (select Name from TypedBaseItems where guid=" + paramName + ")))");
+ Span<byte> idBytes = stackalloc byte[16];
+ for (int i = 0; i < personIdsLen; i++)
+ {
+ string paramName = "@PersonId" + i;
+ clauseBuilder.Append("(guid in (select itemid from People where Name = (select Name from TypedBaseItems where guid=")
+ .Append(paramName)
+ .Append("))) OR ");
if (statement != null)
{
- statement.TryBind(paramName, personId.ToGuidBlob());
+ query.PersonIds[i].TryWriteBytes(idBytes);
+ statement.TryBind(paramName, idBytes);
}
- index++;
}
- var clause = "(" + string.Join(" OR ", clauses) + ")";
- whereClauses.Add(clause);
+
+ // Remove last " OR "
+ clauseBuilder.Length -= Or.Length;
+ clauseBuilder.Append(')');
+
+ whereClauses.Add(clauseBuilder.ToString());
+
+ clauseBuilder.Length = 0;
}
if (!string.IsNullOrWhiteSpace(query.Person))
{
whereClauses.Add("Guid in (select ItemId from People where Name=@PersonName)");
- if (statement != null)
- {
- statement.TryBind("@PersonName", query.Person);
- }
+ statement?.TryBind("@PersonName", query.Person);
}
if (!string.IsNullOrWhiteSpace(query.MinSortName))
{
whereClauses.Add("SortName>=@MinSortName");
- if (statement != null)
- {
- statement.TryBind("@MinSortName", query.MinSortName);
- }
+ statement?.TryBind("@MinSortName", query.MinSortName);
}
if (!string.IsNullOrWhiteSpace(query.ExternalSeriesId))
{
whereClauses.Add("ExternalSeriesId=@ExternalSeriesId");
- if (statement != null)
- {
- statement.TryBind("@ExternalSeriesId", query.ExternalSeriesId);
- }
+ statement?.TryBind("@ExternalSeriesId", query.ExternalSeriesId);
}
if (!string.IsNullOrWhiteSpace(query.ExternalId))
{
whereClauses.Add("ExternalId=@ExternalId");
- if (statement != null)
- {
- statement.TryBind("@ExternalId", query.ExternalId);
- }
+ statement?.TryBind("@ExternalId", query.ExternalId);
}
if (!string.IsNullOrWhiteSpace(query.Name))
{
whereClauses.Add("CleanName=@Name");
-
- if (statement != null)
- {
- statement.TryBind("@Name", GetCleanValue(query.Name));
- }
+ statement?.TryBind("@Name", GetCleanValue(query.Name));
}
// These are the same, for now
@@ -3883,28 +3839,21 @@ namespace Emby.Server.Implementations.Data
if (!string.IsNullOrWhiteSpace(query.NameStartsWith))
{
whereClauses.Add("SortName like @NameStartsWith");
- if (statement != null)
- {
- statement.TryBind("@NameStartsWith", query.NameStartsWith + "%");
- }
+ statement?.TryBind("@NameStartsWith", query.NameStartsWith + "%");
}
+
if (!string.IsNullOrWhiteSpace(query.NameStartsWithOrGreater))
{
whereClauses.Add("SortName >= @NameStartsWithOrGreater");
// lowercase this because SortName is stored as lowercase
- if (statement != null)
- {
- statement.TryBind("@NameStartsWithOrGreater", query.NameStartsWithOrGreater.ToLowerInvariant());
- }
+ statement?.TryBind("@NameStartsWithOrGreater", query.NameStartsWithOrGreater.ToLowerInvariant());
}
+
if (!string.IsNullOrWhiteSpace(query.NameLessThan))
{
whereClauses.Add("SortName < @NameLessThan");
// lowercase this because SortName is stored as lowercase
- if (statement != null)
- {
- statement.TryBind("@NameLessThan", query.NameLessThan.ToLowerInvariant());
- }
+ statement?.TryBind("@NameLessThan", query.NameLessThan.ToLowerInvariant());
}
if (query.ImageTypes.Length > 0)
@@ -3920,18 +3869,12 @@ namespace Emby.Server.Implementations.Data
if (query.IsLiked.Value)
{
whereClauses.Add("rating>=@UserRating");
- if (statement != null)
- {
- statement.TryBind("@UserRating", UserItemData.MinLikeValue);
- }
+ statement?.TryBind("@UserRating", UserItemData.MinLikeValue);
}
else
{
whereClauses.Add("(rating is null or rating<@UserRating)");
- if (statement != null)
- {
- statement.TryBind("@UserRating", UserItemData.MinLikeValue);
- }
+ statement?.TryBind("@UserRating", UserItemData.MinLikeValue);
}
}
@@ -3945,10 +3888,8 @@ namespace Emby.Server.Implementations.Data
{
whereClauses.Add("(IsFavorite is null or IsFavorite=@IsFavoriteOrLiked)");
}
- if (statement != null)
- {
- statement.TryBind("@IsFavoriteOrLiked", query.IsFavoriteOrLiked.Value);
- }
+
+ statement?.TryBind("@IsFavoriteOrLiked", query.IsFavoriteOrLiked.Value);
}
if (query.IsFavorite.HasValue)
@@ -3961,10 +3902,8 @@ namespace Emby.Server.Implementations.Data
{
whereClauses.Add("(IsFavorite is null or IsFavorite=@IsFavorite)");
}
- if (statement != null)
- {
- statement.TryBind("@IsFavorite", query.IsFavorite.Value);
- }
+
+ statement?.TryBind("@IsFavorite", query.IsFavorite.Value);
}
if (EnableJoinUserData(query))
@@ -3972,7 +3911,7 @@ namespace Emby.Server.Implementations.Data
if (query.IsPlayed.HasValue)
{
// We should probably figure this out for all folders, but for right now, this is the only place where we need it
- if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(Series).Name, StringComparison.OrdinalIgnoreCase))
+ if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], nameof(Series), StringComparison.OrdinalIgnoreCase))
{
if (query.IsPlayed.Value)
{
@@ -3993,10 +3932,8 @@ namespace Emby.Server.Implementations.Data
{
whereClauses.Add("(played is null or played=@IsPlayed)");
}
- if (statement != null)
- {
- statement.TryBind("@IsPlayed", query.IsPlayed.Value);
- }
+
+ statement?.TryBind("@IsPlayed", query.IsPlayed.Value);
}
}
}
@@ -4024,10 +3961,12 @@ namespace Emby.Server.Implementations.Data
clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))");
if (statement != null)
{
- statement.TryBind(paramName, artistId.ToGuidBlob());
+ statement.TryBind(paramName, artistId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4043,10 +3982,12 @@ namespace Emby.Server.Implementations.Data
clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=1))");
if (statement != null)
{
- statement.TryBind(paramName, artistId.ToGuidBlob());
+ statement.TryBind(paramName, artistId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4062,10 +4003,12 @@ namespace Emby.Server.Implementations.Data
clauses.Add("((select CleanName from TypedBaseItems where guid=" + paramName + ") in (select CleanValue from itemvalues where ItemId=Guid and Type=0) AND (select CleanName from TypedBaseItems where guid=" + paramName + ") not in (select CleanValue from itemvalues where ItemId=Guid and Type=1))");
if (statement != null)
{
- statement.TryBind(paramName, artistId.ToGuidBlob());
+ statement.TryBind(paramName, artistId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4081,10 +4024,12 @@ namespace Emby.Server.Implementations.Data
clauses.Add("Album in (select Name from typedbaseitems where guid=" + paramName + ")");
if (statement != null)
{
- statement.TryBind(paramName, albumId.ToGuidBlob());
+ statement.TryBind(paramName, albumId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4100,15 +4045,17 @@ namespace Emby.Server.Implementations.Data
clauses.Add("(guid not in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))");
if (statement != null)
{
- statement.TryBind(paramName, artistId.ToGuidBlob());
+ statement.TryBind(paramName, artistId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
- if (query.GenreIds.Length > 0)
+ if (query.GenreIds.Count > 0)
{
var clauses = new List<string>();
var index = 0;
@@ -4119,15 +4066,17 @@ namespace Emby.Server.Implementations.Data
clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=2))");
if (statement != null)
{
- statement.TryBind(paramName, genreId.ToGuidBlob());
+ statement.TryBind(paramName, genreId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
- if (query.Genres.Length > 0)
+ if (query.Genres.Count > 0)
{
var clauses = new List<string>();
var index = 0;
@@ -4138,8 +4087,10 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@Genre" + index, GetCleanValue(item));
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4155,8 +4106,10 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@Tag" + index, GetCleanValue(item));
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4172,8 +4125,10 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@ExcludeTag" + index, GetCleanValue(item));
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4190,10 +4145,12 @@ namespace Emby.Server.Implementations.Data
if (statement != null)
{
- statement.TryBind(paramName, studioId.ToGuidBlob());
+ statement.TryBind(paramName, studioId.ToByteArray());
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4209,8 +4166,10 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@OfficialRating" + index, item);
}
+
index++;
}
+
var clause = "(" + string.Join(" OR ", clauses) + ")";
whereClauses.Add(clause);
}
@@ -4366,12 +4325,12 @@ namespace Emby.Server.Implementations.Data
whereClauses.Add("ProductionYear=@Years");
if (statement != null)
{
- statement.TryBind("@Years", query.Years[0].ToString());
+ statement.TryBind("@Years", query.Years[0].ToString(CultureInfo.InvariantCulture));
}
}
else if (query.Years.Length > 1)
{
- var val = string.Join(",", query.Years);
+ var val = string.Join(',', query.Years);
whereClauses.Add("ProductionYear in (" + val + ")");
}
@@ -4385,6 +4344,7 @@ namespace Emby.Server.Implementations.Data
statement.TryBind("@IsVirtualItem", isVirtualItem.Value);
}
}
+
if (query.IsSpecialSeason.HasValue)
{
if (query.IsSpecialSeason.Value)
@@ -4396,6 +4356,7 @@ namespace Emby.Server.Implementations.Data
whereClauses.Add("IndexNumber <> 0");
}
}
+
if (query.IsUnaired.HasValue)
{
if (query.IsUnaired.Value)
@@ -4407,6 +4368,7 @@ namespace Emby.Server.Implementations.Data
whereClauses.Add("PremiereDate < DATETIME('now')");
}
}
+
var queryMediaTypes = query.MediaTypes.Where(IsValidMediaType).ToArray();
if (queryMediaTypes.Length == 1)
{
@@ -4418,10 +4380,11 @@ namespace Emby.Server.Implementations.Data
}
else if (queryMediaTypes.Length > 1)
{
- var val = string.Join(",", queryMediaTypes.Select(i => "'" + i + "'"));
+ var val = string.Join(',', queryMediaTypes.Select(i => "'" + i + "'"));
whereClauses.Add("MediaType in (" + val + ")");
}
+
if (query.ItemIds.Length > 0)
{
var includeIds = new List<string>();
@@ -4434,11 +4397,13 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@IncludeId" + index, id);
}
+
index++;
}
whereClauses.Add("(" + string.Join(" OR ", includeIds) + ")");
}
+
if (query.ExcludeItemIds.Length > 0)
{
var excludeIds = new List<string>();
@@ -4451,20 +4416,21 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind("@ExcludeId" + index, id);
}
+
index++;
}
whereClauses.Add(string.Join(" AND ", excludeIds));
}
- if (query.ExcludeProviderIds.Count > 0)
+ if (query.ExcludeProviderIds != null && query.ExcludeProviderIds.Count > 0)
{
var excludeIds = new List<string>();
var index = 0;
foreach (var pair in query.ExcludeProviderIds)
{
- if (string.Equals(pair.Key, MetadataProviders.TmdbCollection.ToString(), StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(pair.Key, MetadataProvider.TmdbCollection.ToString(), StringComparison.OrdinalIgnoreCase))
{
continue;
}
@@ -4475,6 +4441,7 @@ namespace Emby.Server.Implementations.Data
{
statement.TryBind(paramName, "%" + pair.Key + "=" + pair.Value + "%");
}
+
index++;
break;
@@ -4486,21 +4453,21 @@ namespace Emby.Server.Implementations.Data
}
}
- if (query.HasAnyProviderId.Count > 0)
+ if (query.HasAnyProviderId != null && query.HasAnyProviderId.Count > 0)
{
var hasProviderIds = new List<string>();
var index = 0;
foreach (var pair in query.HasAnyProviderId)
{
- if (string.Equals(pair.Key, MetadataProviders.TmdbCollection.ToString(), StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(pair.Key, MetadataProvider.TmdbCollection.ToString(), StringComparison.OrdinalIgnoreCase))
{
continue;
}
// TODO this seems to be an idea for a better schema where ProviderIds are their own table
// buut this is not implemented
- //hasProviderIds.Add("(COALESCE((select value from ProviderIds where ItemId=Guid and Name = '" + pair.Key + "'), '') <> " + paramName + ")");
+ // hasProviderIds.Add("(COALESCE((select value from ProviderIds where ItemId=Guid and Name = '" + pair.Key + "'), '') <> " + paramName + ")");
// TODO this is a really BAD way to do it since the pair:
// Tmdb, 1234 matches Tmdb=1234 but also Tmdb=1234567
@@ -4510,13 +4477,14 @@ namespace Emby.Server.Implementations.Data
var paramName = "@HasAnyProviderId" + index;
// this is a search for the placeholder
- hasProviderIds.Add("ProviderIds like " + paramName + "");
+ hasProviderIds.Add("ProviderIds like " + paramName);
// this replaces the placeholder with a value, here: %key=val%
if (statement != null)
{
statement.TryBind(paramName, "%" + pair.Key + "=" + pair.Value + "%");
}
+
index++;
break;
@@ -4530,68 +4498,63 @@ namespace Emby.Server.Implementations.Data
if (query.HasImdbId.HasValue)
{
- whereClauses.Add("ProviderIds like '%imdb=%'");
+ whereClauses.Add(GetProviderIdClause(query.HasImdbId.Value, "imdb"));
}
if (query.HasTmdbId.HasValue)
{
- whereClauses.Add("ProviderIds like '%tmdb=%'");
+ whereClauses.Add(GetProviderIdClause(query.HasTmdbId.Value, "tmdb"));
}
if (query.HasTvdbId.HasValue)
{
- whereClauses.Add("ProviderIds like '%tvdb=%'");
+ whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb"));
}
- var includedItemByNameTypes = GetItemByNameTypesInQuery(query).SelectMany(MapIncludeItemTypes).ToList();
- var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0;
-
var queryTopParentIds = query.TopParentIds;
- if (queryTopParentIds.Length == 1)
+ if (queryTopParentIds.Length > 0)
{
- if (enableItemsByName && includedItemByNameTypes.Count == 1)
+ var includedItemByNameTypes = GetItemByNameTypesInQuery(query);
+ var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0;
+
+ if (queryTopParentIds.Length == 1)
{
- whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)");
- if (statement != null)
+ if (enableItemsByName && includedItemByNameTypes.Count == 1)
{
- statement.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
+ whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)");
+ statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
}
+ else if (enableItemsByName && includedItemByNameTypes.Count > 1)
+ {
+ var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
+ whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))");
+ }
+ else
+ {
+ whereClauses.Add("(TopParentId=@TopParentId)");
+ }
+
+ statement?.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture));
}
- else if (enableItemsByName && includedItemByNameTypes.Count > 1)
- {
- var itemByNameTypeVal = string.Join(",", includedItemByNameTypes.Select(i => "'" + i + "'"));
- whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))");
- }
- else
- {
- whereClauses.Add("(TopParentId=@TopParentId)");
- }
- if (statement != null)
+ else if (queryTopParentIds.Length > 1)
{
- statement.TryBind("@TopParentId", queryTopParentIds[0].ToString("N"));
- }
- }
- else if (queryTopParentIds.Length > 1)
- {
- var val = string.Join(",", queryTopParentIds.Select(i => "'" + i.ToString("N") + "'"));
+ var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
- if (enableItemsByName && includedItemByNameTypes.Count == 1)
- {
- whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))");
- if (statement != null)
+ if (enableItemsByName && includedItemByNameTypes.Count == 1)
{
- statement.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
+ whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))");
+ statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
+ }
+ else if (enableItemsByName && includedItemByNameTypes.Count > 1)
+ {
+ var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
+ whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))");
+ }
+ else
+ {
+ whereClauses.Add("TopParentId in (" + val + ")");
}
- }
- else if (enableItemsByName && includedItemByNameTypes.Count > 1)
- {
- var itemByNameTypeVal = string.Join(",", includedItemByNameTypes.Select(i => "'" + i + "'"));
- whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))");
- }
- else
- {
- whereClauses.Add("TopParentId in (" + val + ")");
}
}
@@ -4604,15 +4567,17 @@ namespace Emby.Server.Implementations.Data
statement.TryBind("@AncestorId", query.AncestorIds[0]);
}
}
+
if (query.AncestorIds.Length > 1)
{
- var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + i.ToString("N") + "'"));
- whereClauses.Add(string.Format("Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause));
+ var inClause = string.Join(',', query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
+ whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause));
}
+
if (!string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey))
{
var inClause = "select guid from TypedBaseItems where PresentationUniqueKey=@AncestorWithPresentationUniqueKey";
- whereClauses.Add(string.Format("Guid in (select itemId from AncestorIds where AncestorId in ({0}))", inClause));
+ whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorId in ({0}))", inClause));
if (statement != null)
{
statement.TryBind("@AncestorWithPresentationUniqueKey", query.AncestorWithPresentationUniqueKey);
@@ -4637,18 +4602,33 @@ namespace Emby.Server.Implementations.Data
statement.TryBind("@UnratedType", query.BlockUnratedItems[0].ToString());
}
}
+
if (query.BlockUnratedItems.Length > 1)
{
- var inClause = string.Join(",", query.BlockUnratedItems.Select(i => "'" + i.ToString() + "'"));
- whereClauses.Add(string.Format("(InheritedParentalRatingValue > 0 or UnratedType not in ({0}))", inClause));
+ var inClause = string.Join(',', query.BlockUnratedItems.Select(i => "'" + i.ToString() + "'"));
+ whereClauses.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "(InheritedParentalRatingValue > 0 or UnratedType not in ({0}))",
+ inClause));
}
if (query.ExcludeInheritedTags.Length > 0)
{
- var tagValues = query.ExcludeInheritedTags.Select(i => "'" + GetCleanValue(i) + "'");
- var tagValuesList = string.Join(",", tagValues);
-
- whereClauses.Add("((select CleanValue from itemvalues where ItemId=Guid and Type=6 and cleanvalue in (" + tagValuesList + ")) is null)");
+ var paramName = "@ExcludeInheritedTags";
+ if (statement == null)
+ {
+ int index = 0;
+ string excludedTags = string.Join(',', query.ExcludeInheritedTags.Select(t => paramName + index++));
+ whereClauses.Add("((select CleanValue from itemvalues where ItemId=Guid and Type=6 and cleanvalue in (" + excludedTags + ")) is null)");
+ }
+ else
+ {
+ for (int index = 0; index < query.ExcludeInheritedTags.Length; index++)
+ {
+ statement.TryBind(paramName + index, GetCleanValue(query.ExcludeInheritedTags[index]));
+ }
+ }
}
if (query.SeriesStatuses.Length > 0)
@@ -4669,7 +4649,7 @@ namespace Emby.Server.Implementations.Data
foreach (var folderId in query.BoxSetLibraryFolders)
{
- folderIdQueries.Add("data like '%" + folderId.ToString("N") + "%'");
+ folderIdQueries.Add("data like '%" + folderId.ToString("N", CultureInfo.InvariantCulture) + "%'");
}
whereClauses.Add("(" + string.Join(" OR ", folderIdQueries) + ")");
@@ -4762,29 +4742,48 @@ namespace Emby.Server.Implementations.Data
return whereClauses;
}
+ /// <summary>
+ /// Formats a where clause for the specified provider.
+ /// </summary>
+ /// <param name="includeResults">Whether or not to include items with this provider's ids.</param>
+ /// <param name="provider">Provider name.</param>
+ /// <returns>Formatted SQL clause.</returns>
+ private string GetProviderIdClause(bool includeResults, string provider)
+ {
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "ProviderIds {0} like '%{1}=%'",
+ includeResults ? string.Empty : "not",
+ provider);
+ }
+
private List<string> GetItemByNameTypesInQuery(InternalItemsQuery query)
{
var list = new List<string>();
- if (IsTypeInQuery(typeof(Person).Name, query))
+ if (IsTypeInQuery(nameof(Person), query))
{
- list.Add(typeof(Person).Name);
+ list.Add(typeof(Person).FullName);
}
- if (IsTypeInQuery(typeof(Genre).Name, query))
+
+ if (IsTypeInQuery(nameof(Genre), query))
{
- list.Add(typeof(Genre).Name);
+ list.Add(typeof(Genre).FullName);
}
- if (IsTypeInQuery(typeof(MusicGenre).Name, query))
+
+ if (IsTypeInQuery(nameof(MusicGenre), query))
{
- list.Add(typeof(MusicGenre).Name);
+ list.Add(typeof(MusicGenre).FullName);
}
- if (IsTypeInQuery(typeof(MusicArtist).Name, query))
+
+ if (IsTypeInQuery(nameof(MusicArtist), query))
{
- list.Add(typeof(MusicArtist).Name);
+ list.Add(typeof(MusicArtist).FullName);
}
- if (IsTypeInQuery(typeof(Studio).Name, query))
+
+ if (IsTypeInQuery(nameof(Studio), query))
{
- list.Add(typeof(Studio).Name);
+ list.Add(typeof(Studio).FullName);
}
return list;
@@ -4837,17 +4836,12 @@ namespace Emby.Server.Implementations.Data
return true;
}
- var types = new[]
- {
- typeof(Episode).Name,
- typeof(Video).Name,
- typeof(Movie).Name,
- typeof(MusicVideo).Name,
- typeof(Series).Name,
- typeof(Season).Name
- };
-
- if (types.Any(i => query.IncludeItemTypes.Contains(i, StringComparer.OrdinalIgnoreCase)))
+ if (query.IncludeItemTypes.Contains(nameof(Episode), StringComparer.OrdinalIgnoreCase)
+ || query.IncludeItemTypes.Contains(nameof(Video), StringComparer.OrdinalIgnoreCase)
+ || query.IncludeItemTypes.Contains(nameof(Movie), StringComparer.OrdinalIgnoreCase)
+ || query.IncludeItemTypes.Contains(nameof(MusicVideo), StringComparer.OrdinalIgnoreCase)
+ || query.IncludeItemTypes.Contains(nameof(Series), StringComparer.OrdinalIgnoreCase)
+ || query.IncludeItemTypes.Contains(nameof(Season), StringComparer.OrdinalIgnoreCase))
{
return true;
}
@@ -4855,105 +4849,64 @@ namespace Emby.Server.Implementations.Data
return false;
}
- private static readonly Type[] KnownTypes =
+ public void UpdateInheritedValues()
{
- typeof(LiveTvProgram),
- typeof(LiveTvChannel),
- typeof(Series),
- typeof(Audio),
- typeof(MusicAlbum),
- typeof(MusicArtist),
- typeof(MusicGenre),
- typeof(MusicVideo),
- typeof(Movie),
- typeof(Playlist),
- typeof(AudioBook),
- typeof(Trailer),
- typeof(BoxSet),
- typeof(Episode),
- typeof(Season),
- typeof(Series),
- typeof(Book),
- typeof(CollectionFolder),
- typeof(Folder),
- typeof(Genre),
- typeof(Person),
- typeof(Photo),
- typeof(PhotoAlbum),
- typeof(Studio),
- typeof(UserRootFolder),
- typeof(UserView),
- typeof(Video),
- typeof(Year),
- typeof(Channel),
- typeof(AggregateFolder)
- };
-
- public void UpdateInheritedValues(CancellationToken cancellationToken)
- {
- UpdateInheritedTags(cancellationToken);
- }
-
- private void UpdateInheritedTags(CancellationToken cancellationToken)
- {
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
+ string sql = string.Join(
+ ';',
+ new string[]
{
- connection.RunInTransaction(db =>
- {
- connection.ExecuteAll(string.Join(";", new string[]
- {
- "delete from itemvalues where type = 6",
+ "delete from itemvalues where type = 6",
- "insert into itemvalues (ItemId, Type, Value, CleanValue) select ItemId, 6, Value, CleanValue from ItemValues where Type=4",
+ "insert into itemvalues (ItemId, Type, Value, CleanValue) select ItemId, 6, Value, CleanValue from ItemValues where Type=4",
- @"insert into itemvalues (ItemId, Type, Value, CleanValue) select AncestorIds.itemid, 6, ItemValues.Value, ItemValues.CleanValue
+ @"insert into itemvalues (ItemId, Type, Value, CleanValue) select AncestorIds.itemid, 6, ItemValues.Value, ItemValues.CleanValue
FROM AncestorIds
LEFT JOIN ItemValues ON (AncestorIds.AncestorId = ItemValues.ItemId)
where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type = 4 "
+ });
- }));
-
- }, TransactionMode);
- }
+ using (var connection = GetConnection())
+ {
+ connection.RunInTransaction(
+ db =>
+ {
+ connection.ExecuteAll(sql);
+ }, TransactionMode);
}
}
- private static Dictionary<string, string[]> GetTypeMapDictionary()
+ private static Dictionary<string, string> GetTypeMapDictionary()
{
- var dict = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
+ var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- foreach (var t in KnownTypes)
+ foreach (var t in _knownTypes)
{
- dict[t.Name] = new[] { t.FullName };
+ dict[t.Name] = t.FullName;
}
- dict["Program"] = new[] { typeof(LiveTvProgram).FullName };
- dict["TvChannel"] = new[] { typeof(LiveTvChannel).FullName };
+ dict["Program"] = typeof(LiveTvProgram).FullName;
+ dict["TvChannel"] = typeof(LiveTvChannel).FullName;
return dict;
}
- // Not crazy about having this all the way down here, but at least it's in one place
- readonly Dictionary<string, string[]> _types = GetTypeMapDictionary();
-
- private IEnumerable<string> MapIncludeItemTypes(string value)
+ private string MapIncludeItemTypes(string value)
{
- if (_types.TryGetValue(value, out string[] result))
+ if (_types.TryGetValue(value, out string result))
{
return result;
}
if (IsValidType(value))
{
- return new[] { value };
+ return value;
}
- return Array.Empty<string>();
+ Logger.LogWarning("Unknown item type: {ItemType}", value);
+ return null;
}
- public void DeleteItem(Guid id, CancellationToken cancellationToken)
+ public void DeleteItem(Guid id)
{
if (id == Guid.Empty)
{
@@ -4962,37 +4915,35 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- var idBlob = id.ToGuidBlob();
+ var idBlob = id.ToByteArray();
- // Delete people
- ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob);
+ // Delete people
+ ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob);
- // Delete chapters
- ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", idBlob);
+ // Delete chapters
+ ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", idBlob);
- // Delete media streams
- ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", idBlob);
+ // Delete media streams
+ ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", idBlob);
- // Delete ancestors
- ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", idBlob);
+ // Delete ancestors
+ ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", idBlob);
- // Delete item values
- ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", idBlob);
+ // Delete item values
+ ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", idBlob);
- // Delete the item
- ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", idBlob);
- }, TransactionMode);
- }
+ // Delete the item
+ ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", idBlob);
+ }, TransactionMode);
}
}
- private void ExecuteWithSingleParam(IDatabaseConnection db, string query, byte[] value)
+ private void ExecuteWithSingleParam(IDatabaseConnection db, string query, ReadOnlySpan<byte> value)
{
using (var statement = PrepareStatement(db, query))
{
@@ -5011,34 +4962,37 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var commandText = "select Distinct Name from People";
+ var commandText = new StringBuilder("select Distinct p.Name from People p");
var whereClauses = GetPeopleWhereClauses(query, null);
if (whereClauses.Count != 0)
{
- commandText += " where " + string.Join(" AND ", whereClauses);
+ commandText.Append(" where ").Append(string.Join(" AND ", whereClauses));
}
- commandText += " order by ListOrder";
+ commandText.Append(" order by ListOrder");
- using (WriteLock.Read())
+ if (query.Limit > 0)
{
- using (var connection = CreateConnection(true))
+ commandText.Append(" LIMIT ").Append(query.Limit);
+ }
+
+ using (var connection = GetConnection(true))
+ {
+ var list = new List<string>();
+ using (var statement = PrepareStatement(connection, commandText.ToString()))
{
- var list = new List<string>();
- using (var statement = PrepareStatementSafe(connection, commandText))
- {
- // Run this again to bind the params
- GetPeopleWhereClauses(query, statement);
+ // Run this again to bind the params
+ GetPeopleWhereClauses(query, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(row.GetString(0));
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(row.GetString(0));
}
- return list;
}
+
+ return list;
}
}
@@ -5051,7 +5005,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People";
+ var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People p";
var whereClauses = GetPeopleWhereClauses(query, null);
@@ -5062,25 +5016,27 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
commandText += " order by ListOrder";
- using (WriteLock.Read())
+ if (query.Limit > 0)
+ {
+ commandText += " LIMIT " + query.Limit;
+ }
+
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ var list = new List<PersonInfo>();
+
+ using (var statement = PrepareStatement(connection, commandText))
{
- var list = new List<PersonInfo>();
+ // Run this again to bind the params
+ GetPeopleWhereClauses(query, statement);
- using (var statement = PrepareStatementSafe(connection, commandText))
+ foreach (var row in statement.ExecuteQuery())
{
- // Run this again to bind the params
- GetPeopleWhereClauses(query, statement);
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetPerson(row));
- }
+ list.Add(GetPerson(row));
}
-
- return list;
}
+
+ return list;
}
}
@@ -5088,69 +5044,71 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
var whereClauses = new List<string>();
+ if (query.User != null && query.IsFavorite.HasValue)
+ {
+ whereClauses.Add(@"p.Name IN (
+SELECT Name FROM TypedBaseItems WHERE UserDataKey IN (
+SELECT key FROM UserDatas WHERE isFavorite=@IsFavorite AND userId=@UserId)
+AND Type = @InternalPersonType)");
+ statement?.TryBind("@IsFavorite", query.IsFavorite.Value);
+ statement?.TryBind("@InternalPersonType", typeof(Person).FullName);
+ }
+
if (!query.ItemId.Equals(Guid.Empty))
{
whereClauses.Add("ItemId=@ItemId");
- if (statement != null)
- {
- statement.TryBind("@ItemId", query.ItemId.ToGuidBlob());
- }
+ statement?.TryBind("@ItemId", query.ItemId.ToByteArray());
}
+
if (!query.AppearsInItemId.Equals(Guid.Empty))
{
- whereClauses.Add("Name in (Select Name from People where ItemId=@AppearsInItemId)");
- if (statement != null)
- {
- statement.TryBind("@AppearsInItemId", query.AppearsInItemId.ToGuidBlob());
- }
+ whereClauses.Add("p.Name in (Select Name from People where ItemId=@AppearsInItemId)");
+ statement?.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray());
}
+
var queryPersonTypes = query.PersonTypes.Where(IsValidPersonType).ToList();
if (queryPersonTypes.Count == 1)
{
whereClauses.Add("PersonType=@PersonType");
- if (statement != null)
- {
- statement.TryBind("@PersonType", queryPersonTypes[0]);
- }
+ statement?.TryBind("@PersonType", queryPersonTypes[0]);
}
else if (queryPersonTypes.Count > 1)
{
- var val = string.Join(",", queryPersonTypes.Select(i => "'" + i + "'"));
+ var val = string.Join(',', queryPersonTypes.Select(i => "'" + i + "'"));
whereClauses.Add("PersonType in (" + val + ")");
}
+
var queryExcludePersonTypes = query.ExcludePersonTypes.Where(IsValidPersonType).ToList();
if (queryExcludePersonTypes.Count == 1)
{
whereClauses.Add("PersonType<>@PersonType");
- if (statement != null)
- {
- statement.TryBind("@PersonType", queryExcludePersonTypes[0]);
- }
+ statement?.TryBind("@PersonType", queryExcludePersonTypes[0]);
}
else if (queryExcludePersonTypes.Count > 1)
{
- var val = string.Join(",", queryExcludePersonTypes.Select(i => "'" + i + "'"));
+ var val = string.Join(',', queryExcludePersonTypes.Select(i => "'" + i + "'"));
whereClauses.Add("PersonType not in (" + val + ")");
}
+
if (query.MaxListOrder.HasValue)
{
whereClauses.Add("ListOrder<=@MaxListOrder");
- if (statement != null)
- {
- statement.TryBind("@MaxListOrder", query.MaxListOrder.Value);
- }
+ statement?.TryBind("@MaxListOrder", query.MaxListOrder.Value);
}
+
if (!string.IsNullOrWhiteSpace(query.NameContains))
{
- whereClauses.Add("Name like @NameContains");
- if (statement != null)
- {
- statement.TryBind("@NameContains", "%" + query.NameContains + "%");
- }
+ whereClauses.Add("p.Name like @NameContains");
+ statement?.TryBind("@NameContains", "%" + query.NameContains + "%");
+ }
+
+ if (query.User != null)
+ {
+ statement?.TryBind("@UserId", query.User.InternalId);
}
return whereClauses;
@@ -5170,7 +5128,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var itemIdBlob = itemId.ToGuidBlob();
+ Span<byte> itemIdBlob = stackalloc byte[16];
+ itemId.TryWriteBytes(itemIdBlob);
// First delete
deleteAncestorsStatement.Reset();
@@ -5186,15 +5145,16 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
for (var i = 0; i < ancestorIds.Count; i++)
{
- if (i > 0)
- {
- insertText.Append(",");
- }
-
- insertText.AppendFormat("(@ItemId, @AncestorId{0}, @AncestorIdText{0})", i.ToString(CultureInfo.InvariantCulture));
+ insertText.AppendFormat(
+ CultureInfo.InvariantCulture,
+ "(@ItemId, @AncestorId{0}, @AncestorIdText{0}),",
+ i.ToString(CultureInfo.InvariantCulture));
}
- using (var statement = PrepareStatementSafe(db, insertText.ToString()))
+ // Remove last ,
+ insertText.Length--;
+
+ using (var statement = PrepareStatement(db, insertText.ToString()))
{
statement.TryBind("@ItemId", itemIdBlob);
@@ -5203,9 +5163,10 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
var index = i.ToString(CultureInfo.InvariantCulture);
var ancestorId = ancestorIds[i];
+ ancestorId.TryWriteBytes(itemIdBlob);
- statement.TryBind("@AncestorId" + index, ancestorId.ToGuidBlob());
- statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N"));
+ statement.TryBind("@AncestorId" + index, itemIdBlob);
+ statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N", CultureInfo.InvariantCulture));
}
statement.Reset();
@@ -5245,74 +5206,93 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
public List<string> GetStudioNames()
{
- return GetItemValueNames(new[] { 3 }, new List<string>(), new List<string>());
+ return GetItemValueNames(new[] { 3 }, Array.Empty<string>(), Array.Empty<string>());
}
public List<string> GetAllArtistNames()
{
- return GetItemValueNames(new[] { 0, 1 }, new List<string>(), new List<string>());
+ return GetItemValueNames(new[] { 0, 1 }, Array.Empty<string>(), Array.Empty<string>());
}
public List<string> GetMusicGenreNames()
{
- return GetItemValueNames(new[] { 2 }, new List<string> { "Audio", "MusicVideo", "MusicAlbum", "MusicArtist" }, new List<string>());
+ return GetItemValueNames(
+ new[] { 2 },
+ new string[]
+ {
+ typeof(Audio).FullName,
+ typeof(MusicVideo).FullName,
+ typeof(MusicAlbum).FullName,
+ typeof(MusicArtist).FullName
+ },
+ Array.Empty<string>());
}
public List<string> GetGenreNames()
{
- return GetItemValueNames(new[] { 2 }, new List<string>(), new List<string> { "Audio", "MusicVideo", "MusicAlbum", "MusicArtist" });
+ return GetItemValueNames(
+ new[] { 2 },
+ Array.Empty<string>(),
+ new string[]
+ {
+ typeof(Audio).FullName,
+ typeof(MusicVideo).FullName,
+ typeof(MusicAlbum).FullName,
+ typeof(MusicArtist).FullName
+ });
}
- private List<string> GetItemValueNames(int[] itemValueTypes, List<string> withItemTypes, List<string> excludeItemTypes)
+ private List<string> GetItemValueNames(int[] itemValueTypes, IReadOnlyList<string> withItemTypes, IReadOnlyList<string> excludeItemTypes)
{
CheckDisposed();
- withItemTypes = withItemTypes.SelectMany(MapIncludeItemTypes).ToList();
- excludeItemTypes = excludeItemTypes.SelectMany(MapIncludeItemTypes).ToList();
-
var now = DateTime.UtcNow;
- var typeClause = itemValueTypes.Length == 1 ?
- ("Type=" + itemValueTypes[0].ToString(CultureInfo.InvariantCulture)) :
- ("Type in (" + string.Join(",", itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")");
-
- var commandText = "Select Value From ItemValues where " + typeClause;
+ var stringBuilder = new StringBuilder("Select Value From ItemValues where Type", 128);
+ if (itemValueTypes.Length == 1)
+ {
+ stringBuilder.Append('=')
+ .Append(itemValueTypes[0]);
+ }
+ else
+ {
+ stringBuilder.Append(" in (")
+ .AppendJoin(',', itemValueTypes)
+ .Append(')');
+ }
if (withItemTypes.Count > 0)
{
- var typeString = string.Join(",", withItemTypes.Select(i => "'" + i + "'"));
- commandText += " AND ItemId In (select guid from typedbaseitems where type in (" + typeString + "))";
+ stringBuilder.Append(" AND ItemId In (select guid from typedbaseitems where type in (")
+ .AppendJoinInSingleQuotes(',', withItemTypes)
+ .Append("))");
}
+
if (excludeItemTypes.Count > 0)
{
- var typeString = string.Join(",", excludeItemTypes.Select(i => "'" + i + "'"));
- commandText += " AND ItemId not In (select guid from typedbaseitems where type in (" + typeString + "))";
+ stringBuilder.Append(" AND ItemId not In (select guid from typedbaseitems where type in (")
+ .AppendJoinInSingleQuotes(',', excludeItemTypes)
+ .Append("))");
}
- commandText += " Group By CleanValue";
+ stringBuilder.Append(" Group By CleanValue");
+ var commandText = stringBuilder.ToString();
- using (WriteLock.Read())
+ var list = new List<string>();
+ using (var connection = GetConnection(true))
+ using (var statement = PrepareStatement(connection, commandText))
{
- using (var connection = CreateConnection(true))
+ foreach (var row in statement.ExecuteQuery())
{
- var list = new List<string>();
-
- using (var statement = PrepareStatementSafe(connection, commandText))
+ if (row.TryGetString(0, out var result))
{
- foreach (var row in statement.ExecuteQuery())
- {
- if (!row.IsDBNull(0))
- {
- list.Add(row.GetString(0));
- }
- }
+ list.Add(result);
}
-
- LogQueryTime("GetItemValueNames", commandText, now);
-
- return list;
}
}
+
+ LogQueryTime("GetItemValueNames", commandText, now);
+ return list;
}
private QueryResult<(BaseItem, ItemCounts)> GetItemValues(InternalItemsQuery query, int[] itemValueTypes, string returnType)
@@ -5332,18 +5312,19 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
var now = DateTime.UtcNow;
var typeClause = itemValueTypes.Length == 1 ?
- ("Type=" + itemValueTypes[0].ToString(CultureInfo.InvariantCulture)) :
- ("Type in (" + string.Join(",", itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")");
+ ("Type=" + itemValueTypes[0]) :
+ ("Type in (" + string.Join(',', itemValueTypes) + ")");
InternalItemsQuery typeSubQuery = null;
- Dictionary<string, string> itemCountColumns = null;
+ string itemCountColumns = null;
+ var stringBuilder = new StringBuilder(1024);
var typesToCount = query.IncludeItemTypes;
if (typesToCount.Length > 0)
{
- var itemCountColumnQuery = "select group_concat(type, '|')" + GetFromText("B");
+ stringBuilder.Append("(select group_concat(type, '|') from TypedBaseItems B");
typeSubQuery = new InternalItemsQuery(query.User)
{
@@ -5359,20 +5340,22 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
};
var whereClauses = GetWhereClauses(typeSubQuery, null);
- whereClauses.Add("guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND " + typeClause + ")");
-
- itemCountColumnQuery += " where " + string.Join(" AND ", whereClauses);
+ stringBuilder.Append(" where ")
+ .AppendJoin(" AND ", whereClauses)
+ .Append(" AND ")
+ .Append("guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND ")
+ .Append(typeClause)
+ .Append(")) as itemTypes");
- itemCountColumns = new Dictionary<string, string>()
- {
- { "itemTypes", "(" + itemCountColumnQuery + ") as itemTypes"}
- };
+ itemCountColumns = stringBuilder.ToString();
+ stringBuilder.Clear();
}
List<string> columns = _retriveItemColumns.ToList();
- if (itemCountColumns != null)
+ // Unfortunately we need to add it to columns to ensure the order of the columns in the select
+ if (!string.IsNullOrEmpty(itemCountColumns))
{
- columns.AddRange(itemCountColumns.Values);
+ columns.Add(itemCountColumns);
}
// do this first before calling GetFinalColumnsToSelect, otherwise ExcludeItemIds will be set by SimilarTo
@@ -5385,7 +5368,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
ItemIds = query.ItemIds,
TopParentIds = query.TopParentIds,
ParentId = query.ParentId,
- IsPlayed = query.IsPlayed,
IsAiring = query.IsAiring,
IsMovie = query.IsMovie,
IsSports = query.IsSports,
@@ -5394,23 +5376,24 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
IsSeries = query.IsSeries
};
- columns = GetFinalColumnsToSelect(query, columns);
-
- var commandText = "select "
- + string.Join(",", columns)
- + GetFromText()
- + GetJoinUserDataText(query);
+ SetFinalColumnsToSelect(query, columns);
var innerWhereClauses = GetWhereClauses(innerQuery, null);
- var innerWhereText = innerWhereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", innerWhereClauses);
+ stringBuilder.Append(" where Type=@SelectType And CleanName In (Select CleanValue from ItemValues where ")
+ .Append(typeClause)
+ .Append(" AND ItemId in (select guid from TypedBaseItems");
+ if (innerWhereClauses.Count > 0)
+ {
+ stringBuilder.Append(" where ")
+ .AppendJoin(" AND ", innerWhereClauses);
+ }
- var whereText = " where Type=@SelectType And CleanName In (Select CleanValue from ItemValues where " + typeClause + " AND ItemId in (select guid from TypedBaseItems" + innerWhereText + "))";
+ stringBuilder.Append("))");
var outerQuery = new InternalItemsQuery(query.User)
{
+ IsPlayed = query.IsPlayed,
IsFavorite = query.IsFavorite,
IsFavoriteOrLiked = query.IsFavoriteOrLiked,
IsLiked = query.IsLiked,
@@ -5420,6 +5403,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
NameStartsWithOrGreater = query.NameStartsWithOrGreater,
Tags = query.Tags,
OfficialRatings = query.OfficialRatings,
+ StudioIds = query.StudioIds,
GenreIds = query.GenreIds,
Genres = query.Genres,
Years = query.Years,
@@ -5430,21 +5414,31 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
};
var outerWhereClauses = GetWhereClauses(outerQuery, null);
-
if (outerWhereClauses.Count != 0)
{
- whereText += " AND " + string.Join(" AND ", outerWhereClauses);
+ stringBuilder.Append(" AND ")
+ .AppendJoin(" AND ", outerWhereClauses);
}
- commandText += whereText + " group by PresentationUniqueKey";
+ var whereText = stringBuilder.ToString();
+ stringBuilder.Clear();
+
+ stringBuilder.Append("select ")
+ .AppendJoin(',', columns)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query))
+ .Append(whereText)
+ .Append(" group by PresentationUniqueKey");
- if (query.SimilarTo != null || !string.IsNullOrEmpty(query.SearchTerm))
+ if (query.OrderBy.Count != 0
+ || query.SimilarTo != null
+ || !string.IsNullOrEmpty(query.SearchTerm))
{
- commandText += GetOrderByText(query);
+ stringBuilder.Append(GetOrderByText(query));
}
else
{
- commandText += " order by SortName";
+ stringBuilder.Append(" order by SortName");
}
if (query.Limit.HasValue || query.StartIndex.HasValue)
@@ -5453,47 +5447,51 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
if (query.Limit.HasValue || offset > 0)
{
- commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture);
+ stringBuilder.Append(" LIMIT ")
+ .Append(query.Limit ?? int.MaxValue);
}
if (offset > 0)
{
- commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture);
+ stringBuilder.Append(" OFFSET ")
+ .Append(offset);
}
}
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
- var statementTexts = new List<string>();
+ string commandText = string.Empty;
+
if (!isReturningZeroItems)
{
- statementTexts.Add(commandText);
+ commandText = stringBuilder.ToString();
}
+
+ string countText = string.Empty;
if (query.EnableTotalRecordCount)
{
- var countText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" }))
- + GetFromText()
- + GetJoinUserDataText(query)
- + whereText;
+ stringBuilder.Clear();
+ var columnsToSelect = new List<string> { "count (distinct PresentationUniqueKey)" };
+ SetFinalColumnsToSelect(query, columnsToSelect);
+ stringBuilder.Append("select ")
+ .AppendJoin(',', columnsToSelect)
+ .Append(FromText)
+ .Append(GetJoinUserDataText(query))
+ .Append(whereText);
- statementTexts.Add(countText);
+ countText = stringBuilder.ToString();
}
- using (WriteLock.Read())
+ var list = new List<(BaseItem, ItemCounts)>();
+ var result = new QueryResult<(BaseItem, ItemCounts)>();
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
- {
- return connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
- var list = new List<(BaseItem, ItemCounts)>();
- var result = new QueryResult<(BaseItem, ItemCounts)>();
-
- var statements = PrepareAllSafe(db, statementTexts);
-
if (!isReturningZeroItems)
{
- using (var statement = statements[0])
+ using (var statement = PrepareStatement(db, commandText))
{
statement.TryBind("@SelectType", returnType);
if (EnableJoinUserData(query))
@@ -5505,6 +5503,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
GetWhereClauses(typeSubQuery, null);
}
+
BindSimilarParams(query, statement);
BindSearchParams(query, statement);
GetWhereClauses(innerQuery, statement);
@@ -5528,20 +5527,12 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
list.Add((item, GetItemCounts(row, countStartColumn, typesToCount)));
}
}
-
- LogQueryTime("GetItemValues", commandText, now);
}
}
if (query.EnableTotalRecordCount)
{
- commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" }))
- + GetFromText()
- + GetJoinUserDataText(query)
- + whereText;
-
- using (var statement = statements[statements.Count - 1])
+ using (var statement = PrepareStatement(db, countText))
{
statement.TryBind("@SelectType", returnType);
if (EnableJoinUserData(query))
@@ -5553,31 +5544,32 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
GetWhereClauses(typeSubQuery, null);
}
+
BindSimilarParams(query, statement);
BindSearchParams(query, statement);
GetWhereClauses(innerQuery, statement);
GetWhereClauses(outerQuery, statement);
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
-
- LogQueryTime("GetItemValues", commandText, now);
}
}
+ },
+ ReadTransactionMode);
+ }
- if (result.TotalRecordCount == 0)
- {
- result.TotalRecordCount = list.Count;
- }
- result.Items = list.ToArray();
-
- return result;
+ LogQueryTime("GetItemValues", commandText, now);
- }, ReadTransactionMode);
- }
+ if (result.TotalRecordCount == 0)
+ {
+ result.TotalRecordCount = list.Count;
}
+
+ result.Items = list;
+
+ return result;
}
- private ItemCounts GetItemCounts(IReadOnlyList<IResultSetValue> reader, int countStartColumn, string[] typesToCount)
+ private static ItemCounts GetItemCounts(IReadOnlyList<ResultSetValue> reader, int countStartColumn, string[] typesToCount)
{
var counts = new ItemCounts();
@@ -5586,81 +5578,74 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
return counts;
}
- var typeString = reader.IsDBNull(countStartColumn) ? null : reader.GetString(countStartColumn);
-
- if (string.IsNullOrWhiteSpace(typeString))
+ if (!reader.TryGetString(countStartColumn, out var typeString))
{
return counts;
}
- var allTypes = typeString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
- .ToLookup(i => i);
-
- foreach (var type in allTypes)
+ foreach (var typeName in typeString.AsSpan().Split('|'))
{
- var value = type.Count();
- var typeName = type.Key;
-
- if (string.Equals(typeName, typeof(Series).FullName, StringComparison.OrdinalIgnoreCase))
+ if (typeName.Equals(typeof(Series).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.SeriesCount = value;
+ counts.SeriesCount++;
}
- else if (string.Equals(typeName, typeof(Episode).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(Episode).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.EpisodeCount = value;
+ counts.EpisodeCount++;
}
- else if (string.Equals(typeName, typeof(Movie).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(Movie).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.MovieCount = value;
+ counts.MovieCount++;
}
- else if (string.Equals(typeName, typeof(MusicAlbum).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(MusicAlbum).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.AlbumCount = value;
+ counts.AlbumCount++;
}
- else if (string.Equals(typeName, typeof(MusicArtist).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(MusicArtist).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.ArtistCount = value;
+ counts.ArtistCount++;
}
- else if (string.Equals(typeName, typeof(Audio).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(Audio).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.SongCount = value;
+ counts.SongCount++;
}
- else if (string.Equals(typeName, typeof(Trailer).FullName, StringComparison.OrdinalIgnoreCase))
+ else if (typeName.Equals(typeof(Trailer).FullName, StringComparison.OrdinalIgnoreCase))
{
- counts.TrailerCount = value;
+ counts.TrailerCount++;
}
- counts.ItemCount += value;
+
+ counts.ItemCount++;
}
return counts;
}
- private List<Tuple<int, string>> GetItemValuesToSave(BaseItem item, List<string> inheritedTags)
+ private List<(int, string)> GetItemValuesToSave(BaseItem item, List<string> inheritedTags)
{
- var list = new List<Tuple<int, string>>();
+ var list = new List<(int, string)>();
if (item is IHasArtist hasArtist)
{
- list.AddRange(hasArtist.Artists.Select(i => new Tuple<int, string>(0, i)));
+ list.AddRange(hasArtist.Artists.Select(i => (0, i)));
}
if (item is IHasAlbumArtist hasAlbumArtist)
{
- list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => new Tuple<int, string>(1, i)));
+ list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i)));
}
- list.AddRange(item.Genres.Select(i => new Tuple<int, string>(2, i)));
- list.AddRange(item.Studios.Select(i => new Tuple<int, string>(3, i)));
- list.AddRange(item.Tags.Select(i => new Tuple<int, string>(4, 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)));
// keywords was 5
- list.AddRange(inheritedTags.Select(i => new Tuple<int, string>(6, i)));
+ list.AddRange(inheritedTags.Select(i => (6, i)));
return list;
}
- private void UpdateItemValues(Guid itemId, List<Tuple<int, string>> values, IDatabaseConnection db)
+ private void UpdateItemValues(Guid itemId, List<(int, string)> values, IDatabaseConnection db)
{
if (itemId.Equals(Guid.Empty))
{
@@ -5674,7 +5659,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var guidBlob = itemId.ToGuidBlob();
+ var guidBlob = itemId.ToByteArray();
// First delete
db.Execute("delete from ItemValues where ItemId=@Id", guidBlob);
@@ -5682,30 +5667,29 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
InsertItemValues(guidBlob, values, db);
}
- private void InsertItemValues(byte[] idBlob, List<Tuple<int, string>> values, IDatabaseConnection db)
+ private void InsertItemValues(byte[] idBlob, List<(int, string)> values, IDatabaseConnection db)
{
+ const int Limit = 100;
var startIndex = 0;
- var limit = 100;
+ const string StartInsertText = "insert into ItemValues (ItemId, Type, Value, CleanValue) values ";
+ var insertText = new StringBuilder(StartInsertText);
while (startIndex < values.Count)
{
- var insertText = new StringBuilder("insert into ItemValues (ItemId, Type, Value, CleanValue) values ");
-
- var endIndex = Math.Min(values.Count, startIndex + limit);
- var isSubsequentRow = false;
+ var endIndex = Math.Min(values.Count, startIndex + Limit);
for (var i = startIndex; i < endIndex; i++)
{
- if (isSubsequentRow)
- {
- insertText.Append(",");
- }
-
- insertText.AppendFormat("(@ItemId, @Type{0}, @Value{0}, @CleanValue{0})", i.ToString(CultureInfo.InvariantCulture));
- isSubsequentRow = true;
+ insertText.AppendFormat(
+ CultureInfo.InvariantCulture,
+ "(@ItemId, @Type{0}, @Value{0}, @CleanValue{0}),",
+ i);
}
- using (var statement = PrepareStatementSafe(db, insertText.ToString()))
+ // Remove last comma
+ insertText.Length--;
+
+ using (var statement = PrepareStatement(db, insertText.ToString()))
{
statement.TryBind("@ItemId", idBlob);
@@ -5732,7 +5716,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
statement.MoveNext();
}
- startIndex += limit;
+ startIndex += Limit;
+ insertText.Length = StartInsertText.Length;
}
}
@@ -5750,50 +5735,44 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- var itemIdBlob = itemId.ToGuidBlob();
-
- // First delete chapters
- db.Execute("delete from People where ItemId=@ItemId", itemIdBlob);
+ var itemIdBlob = itemId.ToByteArray();
- InsertPeople(itemIdBlob, people, db);
+ // First delete chapters
+ db.Execute("delete from People where ItemId=@ItemId", itemIdBlob);
- }, TransactionMode);
-
- }
+ InsertPeople(itemIdBlob, people, db);
+ }, TransactionMode);
}
}
private void InsertPeople(byte[] idBlob, List<PersonInfo> people, IDatabaseConnection db)
{
+ const int Limit = 100;
var startIndex = 0;
- var limit = 100;
var listIndex = 0;
+ const string StartInsertText = "insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values ";
+ var insertText = new StringBuilder(StartInsertText);
while (startIndex < people.Count)
{
- var insertText = new StringBuilder("insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values ");
-
- var endIndex = Math.Min(people.Count, startIndex + limit);
- var isSubsequentRow = false;
-
+ var endIndex = Math.Min(people.Count, startIndex + Limit);
for (var i = startIndex; i < endIndex; i++)
{
- if (isSubsequentRow)
- {
- insertText.Append(",");
- }
-
- insertText.AppendFormat("(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0})", i.ToString(CultureInfo.InvariantCulture));
- isSubsequentRow = true;
+ insertText.AppendFormat(
+ CultureInfo.InvariantCulture,
+ "(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0}),",
+ i.ToString(CultureInfo.InvariantCulture));
}
- using (var statement = PrepareStatementSafe(db, insertText.ToString()))
+ // Remove last comma
+ insertText.Length--;
+
+ using (var statement = PrepareStatement(db, insertText.ToString()))
{
statement.TryBind("@ItemId", idBlob);
@@ -5816,30 +5795,32 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
statement.MoveNext();
}
- startIndex += limit;
+ startIndex += Limit;
+ insertText.Length = StartInsertText.Length;
}
}
- private PersonInfo GetPerson(IReadOnlyList<IResultSetValue> reader)
+ private PersonInfo GetPerson(IReadOnlyList<ResultSetValue> reader)
{
- var item = new PersonInfo();
-
- item.ItemId = reader.GetGuid(0);
- item.Name = reader.GetString(1);
+ var item = new PersonInfo
+ {
+ ItemId = reader.GetGuid(0),
+ Name = reader.GetString(1)
+ };
- if (!reader.IsDBNull(2))
+ if (reader.TryGetString(2, out var role))
{
- item.Role = reader.GetString(2);
+ item.Role = role;
}
- if (!reader.IsDBNull(3))
+ if (reader.TryGetString(3, out var type))
{
- item.Type = reader.GetString(3);
+ item.Type = type;
}
- if (!reader.IsDBNull(4))
+ if (reader.TryGetInt32(4, out var sortOrder))
{
- item.SortOrder = reader.GetInt32(4);
+ item.SortOrder = sortOrder;
}
return item;
@@ -5854,10 +5835,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
throw new ArgumentNullException(nameof(query));
}
- var cmdText = "select "
- + string.Join(",", _mediaStreamSaveColumns)
- + " from mediastreams where"
- + " ItemId=@ItemId";
+ var cmdText = _mediaStreamSaveColumnsSelectQuery;
if (query.Type.HasValue)
{
@@ -5871,34 +5849,31 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
cmdText += " order by StreamIndex ASC";
- using (WriteLock.Read())
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ var list = new List<MediaStream>();
+
+ using (var statement = PrepareStatement(connection, cmdText))
{
- var list = new List<MediaStream>();
+ statement.TryBind("@ItemId", query.ItemId.ToByteArray());
- using (var statement = PrepareStatementSafe(connection, cmdText))
+ if (query.Type.HasValue)
{
- statement.TryBind("@ItemId", query.ItemId.ToGuidBlob());
-
- if (query.Type.HasValue)
- {
- statement.TryBind("@StreamType", query.Type.Value.ToString());
- }
-
- if (query.Index.HasValue)
- {
- statement.TryBind("@StreamIndex", query.Index.Value);
- }
+ statement.TryBind("@StreamType", query.Type.Value.ToString());
+ }
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetMediaStream(row));
- }
+ if (query.Index.HasValue)
+ {
+ statement.TryBind("@StreamIndex", query.Index.Value);
}
- return list;
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(GetMediaStream(row));
+ }
}
+
+ return list;
}
}
@@ -5918,40 +5893,36 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
cancellationToken.ThrowIfCancellationRequested();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- var itemIdBlob = id.ToGuidBlob();
+ var itemIdBlob = id.ToByteArray();
- // First delete chapters
- db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob);
+ // First delete chapters
+ db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob);
- InsertMediaStreams(itemIdBlob, streams, db);
-
- }, TransactionMode);
- }
+ InsertMediaStreams(itemIdBlob, streams, db);
+ }, TransactionMode);
}
}
private void InsertMediaStreams(byte[] idBlob, List<MediaStream> streams, IDatabaseConnection db)
{
+ const int Limit = 10;
var startIndex = 0;
- var limit = 10;
+ var insertText = new StringBuilder(_mediaStreamSaveColumnsInsertQuery);
while (startIndex < streams.Count)
{
- var insertText = new StringBuilder(string.Format("insert into mediastreams ({0}) values ", string.Join(",", _mediaStreamSaveColumns)));
-
- var endIndex = Math.Min(streams.Count, startIndex + limit);
+ var endIndex = Math.Min(streams.Count, startIndex + Limit);
for (var i = startIndex; i < endIndex; i++)
{
if (i != startIndex)
{
- insertText.Append(",");
+ insertText.Append(',');
}
var index = i.ToString(CultureInfo.InvariantCulture);
@@ -5959,14 +5930,15 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
foreach (var column in _mediaStreamSaveColumns.Skip(1))
{
- insertText.Append("@" + column + index + ",");
+ insertText.Append('@').Append(column).Append(index).Append(',');
}
+
insertText.Length -= 1; // Remove the last comma
- insertText.Append(")");
+ insertText.Append(')');
}
- using (var statement = PrepareStatementSafe(db, insertText.ToString()))
+ using (var statement = PrepareStatement(db, insertText.ToString()))
{
statement.TryBind("@ItemId", idBlob);
@@ -6025,169 +5997,347 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
statement.MoveNext();
}
- startIndex += limit;
+ startIndex += Limit;
+ insertText.Length = _mediaStreamSaveColumnsInsertQuery.Length;
}
}
-
/// <summary>
/// Gets the chapter.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>ChapterInfo.</returns>
- private MediaStream GetMediaStream(IReadOnlyList<IResultSetValue> reader)
+ private MediaStream GetMediaStream(IReadOnlyList<ResultSetValue> reader)
{
var item = new MediaStream
{
Index = reader[1].ToInt()
};
- item.Type = (MediaStreamType)Enum.Parse(typeof(MediaStreamType), reader[2].ToString(), true);
+ item.Type = Enum.Parse<MediaStreamType>(reader[2].ToString(), true);
- if (reader[3].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(3, out var codec))
{
- item.Codec = reader[3].ToString();
+ item.Codec = codec;
}
- if (reader[4].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(4, out var language))
{
- item.Language = reader[4].ToString();
+ item.Language = language;
}
- if (reader[5].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(5, out var channelLayout))
{
- item.ChannelLayout = reader[5].ToString();
+ item.ChannelLayout = channelLayout;
}
- if (reader[6].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(6, out var profile))
{
- item.Profile = reader[6].ToString();
+ item.Profile = profile;
}
- if (reader[7].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(7, out var aspectRatio))
{
- item.AspectRatio = reader[7].ToString();
+ item.AspectRatio = aspectRatio;
}
- if (reader[8].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(8, out var path))
{
- item.Path = RestorePath(reader[8].ToString());
+ item.Path = RestorePath(path);
}
item.IsInterlaced = reader.GetBoolean(9);
- if (reader[10].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(10, out var bitrate))
{
- item.BitRate = reader.GetInt32(10);
+ item.BitRate = bitrate;
}
- if (reader[11].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(11, out var channels))
{
- item.Channels = reader.GetInt32(11);
+ item.Channels = channels;
}
- if (reader[12].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(12, out var sampleRate))
{
- item.SampleRate = reader.GetInt32(12);
+ item.SampleRate = sampleRate;
}
item.IsDefault = reader.GetBoolean(13);
item.IsForced = reader.GetBoolean(14);
item.IsExternal = reader.GetBoolean(15);
- if (reader[16].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(16, out var width))
+ {
+ item.Width = width;
+ }
+
+ if (reader.TryGetInt32(17, out var height))
+ {
+ item.Height = height;
+ }
+
+ if (reader.TryGetSingle(18, out var averageFrameRate))
+ {
+ item.AverageFrameRate = averageFrameRate;
+ }
+
+ if (reader.TryGetSingle(19, out var realFrameRate))
{
- item.Width = reader.GetInt32(16);
+ item.RealFrameRate = realFrameRate;
}
- if (reader[17].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetSingle(20, out var level))
{
- item.Height = reader.GetInt32(17);
+ item.Level = level;
}
- if (reader[18].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(21, out var pixelFormat))
{
- item.AverageFrameRate = reader.GetFloat(18);
+ item.PixelFormat = pixelFormat;
}
- if (reader[19].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(22, out var bitDepth))
{
- item.RealFrameRate = reader.GetFloat(19);
+ item.BitDepth = bitDepth;
}
- if (reader[20].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetBoolean(23, out var isAnamorphic))
{
- item.Level = reader.GetFloat(20);
+ item.IsAnamorphic = isAnamorphic;
}
- if (reader[21].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(24, out var refFrames))
{
- item.PixelFormat = reader[21].ToString();
+ item.RefFrames = refFrames;
}
- if (reader[22].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(25, out var codecTag))
{
- item.BitDepth = reader.GetInt32(22);
+ item.CodecTag = codecTag;
}
- if (reader[23].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(26, out var comment))
{
- item.IsAnamorphic = reader.GetBoolean(23);
+ item.Comment = comment;
}
- if (reader[24].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(27, out var nalLengthSize))
{
- item.RefFrames = reader.GetInt32(24);
+ item.NalLengthSize = nalLengthSize;
}
- if (reader[25].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetBoolean(28, out var isAVC))
{
- item.CodecTag = reader.GetString(25);
+ item.IsAVC = isAVC;
}
- if (reader[26].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(29, out var title))
{
- item.Comment = reader.GetString(26);
+ item.Title = title;
}
- if (reader[27].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(30, out var timeBase))
{
- item.NalLengthSize = reader.GetString(27);
+ item.TimeBase = timeBase;
}
- if (reader[28].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(31, out var codecTimeBase))
{
- item.IsAVC = reader[28].ToBool();
+ item.CodecTimeBase = codecTimeBase;
}
- if (reader[29].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(32, out var colorPrimaries))
{
- item.Title = reader[29].ToString();
+ item.ColorPrimaries = colorPrimaries;
}
- if (reader[30].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(33, out var colorSpace))
+ {
+ item.ColorSpace = colorSpace;
+ }
+
+ if (reader.TryGetString(34, out var colorTransfer))
+ {
+ item.ColorTransfer = colorTransfer;
+ }
+
+ if (item.Type == MediaStreamType.Subtitle)
+ {
+ item.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
+ item.LocalizedDefault = _localization.GetLocalizedString("Default");
+ item.LocalizedForced = _localization.GetLocalizedString("Forced");
+ }
+
+ return item;
+ }
+
+ public List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
+ {
+ CheckDisposed();
+
+ if (query == null)
+ {
+ throw new ArgumentNullException(nameof(query));
+ }
+
+ var cmdText = _mediaAttachmentSaveColumnsSelectQuery;
+
+ if (query.Index.HasValue)
+ {
+ cmdText += " AND AttachmentIndex=@AttachmentIndex";
+ }
+
+ cmdText += " order by AttachmentIndex ASC";
+
+ var list = new List<MediaAttachment>();
+ using (var connection = GetConnection(true))
+ using (var statement = PrepareStatement(connection, cmdText))
+ {
+ statement.TryBind("@ItemId", query.ItemId.ToByteArray());
+
+ if (query.Index.HasValue)
+ {
+ statement.TryBind("@AttachmentIndex", query.Index.Value);
+ }
+
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(GetMediaAttachment(row));
+ }
+ }
+
+ return list;
+ }
+
+ public void SaveMediaAttachments(
+ Guid id,
+ IReadOnlyList<MediaAttachment> attachments,
+ CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+ if (id == Guid.Empty)
+ {
+ throw new ArgumentException("Guid can't be empty.", nameof(id));
+ }
+
+ if (attachments == null)
+ {
+ throw new ArgumentNullException(nameof(attachments));
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ using (var connection = GetConnection())
+ {
+ connection.RunInTransaction(
+ db =>
+ {
+ var itemIdBlob = id.ToByteArray();
+
+ db.Execute("delete from mediaattachments where ItemId=@ItemId", itemIdBlob);
+
+ InsertMediaAttachments(itemIdBlob, attachments, db, cancellationToken);
+ }, TransactionMode);
+ }
+ }
+
+ private void InsertMediaAttachments(
+ byte[] idBlob,
+ IReadOnlyList<MediaAttachment> attachments,
+ IDatabaseConnection db,
+ CancellationToken cancellationToken)
+ {
+ const int InsertAtOnce = 10;
+
+ var insertText = new StringBuilder(_mediaAttachmentInsertPrefix);
+ for (var startIndex = 0; startIndex < attachments.Count; startIndex += InsertAtOnce)
+ {
+ var endIndex = Math.Min(attachments.Count, startIndex + InsertAtOnce);
+
+ for (var i = startIndex; i < endIndex; i++)
+ {
+ var index = i.ToString(CultureInfo.InvariantCulture);
+ insertText.Append("(@ItemId, ");
+
+ foreach (var column in _mediaAttachmentSaveColumns.Skip(1))
+ {
+ insertText.Append('@')
+ .Append(column)
+ .Append(index)
+ .Append(',');
+ }
+
+ insertText.Length -= 1;
+
+ insertText.Append("),");
+ }
+
+ insertText.Length--;
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ using (var statement = PrepareStatement(db, insertText.ToString()))
+ {
+ statement.TryBind("@ItemId", idBlob);
+
+ for (var i = startIndex; i < endIndex; i++)
+ {
+ var index = i.ToString(CultureInfo.InvariantCulture);
+
+ var attachment = attachments[i];
+
+ statement.TryBind("@AttachmentIndex" + index, attachment.Index);
+ statement.TryBind("@Codec" + index, attachment.Codec);
+ statement.TryBind("@CodecTag" + index, attachment.CodecTag);
+ statement.TryBind("@Comment" + index, attachment.Comment);
+ statement.TryBind("@Filename" + index, attachment.FileName);
+ statement.TryBind("@MIMEType" + index, attachment.MimeType);
+ }
+
+ statement.Reset();
+ statement.MoveNext();
+ }
+
+ insertText.Length = _mediaAttachmentInsertPrefix.Length;
+ }
+ }
+
+ /// <summary>
+ /// Gets the attachment.
+ /// </summary>
+ /// <param name="reader">The reader.</param>
+ /// <returns>MediaAttachment.</returns>
+ private MediaAttachment GetMediaAttachment(IReadOnlyList<ResultSetValue> reader)
+ {
+ var item = new MediaAttachment
+ {
+ Index = reader[1].ToInt()
+ };
+
+ if (reader.TryGetString(2, out var codec))
{
- item.TimeBase = reader[30].ToString();
+ item.Codec = codec;
}
- if (reader[31].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(3, out var codecTag))
{
- item.CodecTimeBase = reader[31].ToString();
+ item.CodecTag = codecTag;
}
- if (reader[32].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(4, out var comment))
{
- item.ColorPrimaries = reader[32].ToString();
+ item.Comment = comment;
}
- if (reader[33].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(5, out var fileName))
{
- item.ColorSpace = reader[33].ToString();
+ item.FileName = fileName;
}
- if (reader[34].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetString(6, out var mimeType))
{
- item.ColorTransfer = reader[34].ToString();
+ item.MimeType = mimeType;
}
return item;
diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
index 7a9b72244..107096b5f 100644
--- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
@@ -1,13 +1,16 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using System.Threading;
+using Jellyfin.Data.Entities;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
@@ -16,41 +19,41 @@ namespace Emby.Server.Implementations.Data
public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository
{
public SqliteUserDataRepository(
- ILoggerFactory loggerFactory,
+ ILogger<SqliteUserDataRepository> logger,
IApplicationPaths appPaths)
- : base(loggerFactory.CreateLogger(nameof(SqliteUserDataRepository)))
+ : base(logger)
{
DbFilePath = Path.Combine(appPaths.DataPath, "library.db");
}
- /// <summary>
- /// Gets the name of the repository
- /// </summary>
- /// <value>The name.</value>
+ /// <inheritdoc />
public string Name => "SQLite";
/// <summary>
- /// Opens the connection to the database
+ /// Opens the connection to the database.
/// </summary>
- /// <returns>Task.</returns>
- public void Initialize(ReaderWriterLockSlim writeLock, ManagedConnection managedConnection, IUserManager userManager)
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="dbLock">The lock to use for database IO.</param>
+ /// <param name="dbConnection">The connection to use for database IO.</param>
+ public void Initialize(IUserManager userManager, SemaphoreSlim dbLock, SQLiteDatabaseConnection dbConnection)
{
- _connection = managedConnection;
-
WriteLock.Dispose();
- WriteLock = writeLock;
+ WriteLock = dbLock;
+ WriteConnection?.Dispose();
+ WriteConnection = dbConnection;
- using (var connection = CreateConnection())
+ using (var connection = GetConnection())
{
var userDatasTableExists = TableExists(connection, "UserDatas");
var userDataTableExists = TableExists(connection, "userdata");
- var users = userDatasTableExists ? null : userManager.Users.ToArray();
+ var users = userDatasTableExists ? null : userManager.Users;
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
- db.ExecuteAll(string.Join(";", new[] {
-
+ db.ExecuteAll(string.Join(';', new[]
+ {
"create table if not exists UserDatas (key nvarchar not null, userId INT not null, rating float null, played bit not null, playCount int not null, isFavorite bit not null, playbackPositionTicks bigint not null, lastPlayedDate datetime null, AudioStreamIndex INT, SubtitleStreamIndex INT)",
"drop index if exists idx_userdata",
@@ -85,7 +88,7 @@ namespace Emby.Server.Implementations.Data
}
}
- private void ImportUserIds(IDatabaseConnection db, User[] users)
+ private void ImportUserIds(IDatabaseConnection db, IEnumerable<User> users)
{
var userIdsWithUserData = GetAllUserIdsWithUserData(db);
@@ -98,7 +101,7 @@ namespace Emby.Server.Implementations.Data
continue;
}
- statement.TryBind("@UserId", user.Id.ToGuidBlob());
+ statement.TryBind("@UserId", user.Id.ToByteArray());
statement.TryBind("@InternalUserId", user.InternalId);
statement.MoveNext();
@@ -119,9 +122,9 @@ namespace Emby.Server.Implementations.Data
{
list.Add(row[0].ReadGuidFromBlob());
}
- catch
+ catch (Exception ex)
{
-
+ Logger.LogError(ex, "Error while getting user");
}
}
}
@@ -129,41 +132,41 @@ namespace Emby.Server.Implementations.Data
return list;
}
- protected override bool EnableTempStoreMemory => true;
-
- /// <summary>
- /// Saves the user data.
- /// </summary>
- public void SaveUserData(long internalUserId, string key, UserItemData userData, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public void SaveUserData(long userId, string key, UserItemData userData, CancellationToken cancellationToken)
{
if (userData == null)
{
throw new ArgumentNullException(nameof(userData));
}
- if (internalUserId <= 0)
+
+ if (userId <= 0)
{
- throw new ArgumentNullException(nameof(internalUserId));
+ throw new ArgumentNullException(nameof(userId));
}
+
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
- PersistUserData(internalUserId, key, userData, cancellationToken);
+ PersistUserData(userId, key, userData, cancellationToken);
}
- public void SaveAllUserData(long internalUserId, UserItemData[] userData, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public void SaveAllUserData(long userId, UserItemData[] userData, CancellationToken cancellationToken)
{
if (userData == null)
{
throw new ArgumentNullException(nameof(userData));
}
- if (internalUserId <= 0)
+
+ if (userId <= 0)
{
- throw new ArgumentNullException(nameof(internalUserId));
+ throw new ArgumentNullException(nameof(userId));
}
- PersistAllUserData(internalUserId, userData, cancellationToken);
+ PersistAllUserData(userId, userData, cancellationToken);
}
/// <summary>
@@ -173,20 +176,17 @@ namespace Emby.Server.Implementations.Data
/// <param name="key">The key.</param>
/// <param name="userData">The user data.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
public void PersistUserData(long internalUserId, string key, UserItemData userData, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
- {
- SaveUserData(db, internalUserId, key, userData);
- }, TransactionMode);
- }
+ SaveUserData(db, internalUserId, key, userData);
+ }, TransactionMode);
}
}
@@ -243,70 +243,66 @@ namespace Emby.Server.Implementations.Data
}
/// <summary>
- /// Persist all user data for the specified user
+ /// Persist all user data for the specified user.
/// </summary>
private void PersistAllUserData(long internalUserId, UserItemData[] userDataList, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
- using (WriteLock.Write())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(
+ db =>
{
- connection.RunInTransaction(db =>
+ foreach (var userItemData in userDataList)
{
- foreach (var userItemData in userDataList)
- {
- SaveUserData(db, internalUserId, userItemData.Key, userItemData);
- }
- }, TransactionMode);
- }
+ SaveUserData(db, internalUserId, userItemData.Key, userItemData);
+ }
+ }, TransactionMode);
}
}
/// <summary>
/// Gets the user data.
/// </summary>
- /// <param name="internalUserId">The user id.</param>
+ /// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <returns>Task{UserItemData}.</returns>
/// <exception cref="ArgumentNullException">
/// userId
/// or
- /// key
+ /// key.
/// </exception>
- public UserItemData GetUserData(long internalUserId, string key)
+ public UserItemData GetUserData(long userId, string key)
{
- if (internalUserId <= 0)
+ if (userId <= 0)
{
- throw new ArgumentNullException(nameof(internalUserId));
+ throw new ArgumentNullException(nameof(userId));
}
+
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
- using (WriteLock.Read())
+ using (var connection = GetConnection(true))
{
- using (var connection = CreateConnection(true))
+ using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where key =@Key and userId=@UserId"))
{
- using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where key =@Key and userId=@UserId"))
- {
- statement.TryBind("@UserId", internalUserId);
- statement.TryBind("@Key", key);
+ statement.TryBind("@UserId", userId);
+ statement.TryBind("@Key", key);
- foreach (var row in statement.ExecuteQuery())
- {
- return ReadRow(row);
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ return ReadRow(row);
}
-
- return null;
}
+
+ return null;
}
}
- public UserItemData GetUserData(long internalUserId, List<string> keys)
+ public UserItemData GetUserData(long userId, List<string> keys)
{
if (keys == null)
{
@@ -318,35 +314,32 @@ namespace Emby.Server.Implementations.Data
return null;
}
- return GetUserData(internalUserId, keys[0]);
+ return GetUserData(userId, keys[0]);
}
/// <summary>
- /// Return all user-data associated with the given user
+ /// Return all user-data associated with the given user.
/// </summary>
- /// <param name="internalUserId"></param>
- /// <returns></returns>
- public List<UserItemData> GetAllUserData(long internalUserId)
+ /// <param name="userId">The internal user id.</param>
+ /// <returns>The list of user item data.</returns>
+ public List<UserItemData> GetAllUserData(long userId)
{
- if (internalUserId <= 0)
+ if (userId <= 0)
{
- throw new ArgumentNullException(nameof(internalUserId));
+ throw new ArgumentNullException(nameof(userId));
}
var list = new List<UserItemData>();
- using (WriteLock.Read())
+ using (var connection = GetConnection())
{
- using (var connection = CreateConnection())
+ using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where userId=@UserId"))
{
- using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where userId=@UserId"))
- {
- statement.TryBind("@UserId", internalUserId);
+ statement.TryBind("@UserId", userId);
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(ReadRow(row));
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(ReadRow(row));
}
}
}
@@ -355,19 +348,20 @@ namespace Emby.Server.Implementations.Data
}
/// <summary>
- /// Read a row from the specified reader into the provided userData object
+ /// Read a row from the specified reader into the provided userData object.
/// </summary>
- /// <param name="reader"></param>
- private UserItemData ReadRow(IReadOnlyList<IResultSetValue> reader)
+ /// <param name="reader">The list of result set values.</param>
+ /// <returns>The user item data.</returns>
+ private UserItemData ReadRow(IReadOnlyList<ResultSetValue> reader)
{
var userData = new UserItemData();
userData.Key = reader[0].ToString();
- //userData.UserId = reader[1].ReadGuidFromBlob();
+ // userData.UserId = reader[1].ReadGuidFromBlob();
- if (reader[2].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetDouble(2, out var rating))
{
- userData.Rating = reader[2].ToDouble();
+ userData.Rating = rating;
}
userData.Played = reader[3].ToBool();
@@ -375,32 +369,32 @@ namespace Emby.Server.Implementations.Data
userData.IsFavorite = reader[5].ToBool();
userData.PlaybackPositionTicks = reader[6].ToInt64();
- if (reader[7].SQLiteType != SQLiteType.Null)
+ if (reader.TryReadDateTime(7, out var lastPlayedDate))
{
- userData.LastPlayedDate = reader[7].TryReadDateTime();
+ userData.LastPlayedDate = lastPlayedDate;
}
- if (reader[8].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(8, out var audioStreamIndex))
{
- userData.AudioStreamIndex = reader[8].ToInt();
+ userData.AudioStreamIndex = audioStreamIndex;
}
- if (reader[9].SQLiteType != SQLiteType.Null)
+ if (reader.TryGetInt32(9, out var subtitleStreamIndex))
{
- userData.SubtitleStreamIndex = reader[9].ToInt();
+ userData.SubtitleStreamIndex = subtitleStreamIndex;
}
return userData;
}
+ /// <inheritdoc/>
+ /// <remarks>
+ /// There is nothing to dispose here since <see cref="BaseSqliteRepository.WriteLock"/> and
+ /// <see cref="BaseSqliteRepository.WriteConnection"/> are managed by <see cref="SqliteItemRepository"/>.
+ /// See <see cref="Initialize(IUserManager, SemaphoreSlim, SQLiteDatabaseConnection)"/>.
+ /// </remarks>
protected override void Dispose(bool dispose)
{
- // handled by library database
- }
-
- protected override void CloseConnection()
- {
- // handled by library database
}
}
}
diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
deleted file mode 100644
index db359d7dd..000000000
--- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs
+++ /dev/null
@@ -1,230 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-using SQLitePCL.pretty;
-
-namespace Emby.Server.Implementations.Data
-{
- /// <summary>
- /// Class SQLiteUserRepository
- /// </summary>
- public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
- {
- private readonly IJsonSerializer _jsonSerializer;
-
- public SqliteUserRepository(
- ILoggerFactory loggerFactory,
- IServerApplicationPaths appPaths,
- IJsonSerializer jsonSerializer)
- : base(loggerFactory.CreateLogger(nameof(SqliteUserRepository)))
- {
- _jsonSerializer = jsonSerializer;
-
- DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
- }
-
- /// <summary>
- /// Gets the name of the repository
- /// </summary>
- /// <value>The name.</value>
- public string Name => "SQLite";
-
- /// <summary>
- /// Opens the connection to the database
- /// </summary>
- /// <returns>Task.</returns>
- public void Initialize()
- {
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- var localUsersTableExists = TableExists(connection, "LocalUsersv2");
-
- connection.RunQueries(new[] {
- "create table if not exists LocalUsersv2 (Id INTEGER PRIMARY KEY, guid GUID NOT NULL, data BLOB NOT NULL)",
- "drop index if exists idx_users"
- });
-
- if (!localUsersTableExists && TableExists(connection, "Users"))
- {
- TryMigrateToLocalUsersTable(connection);
- }
- }
- }
-
- private void TryMigrateToLocalUsersTable(ManagedConnection connection)
- {
- try
- {
- connection.RunQueries(new[]
- {
- "INSERT INTO LocalUsersv2 (guid, data) SELECT guid,data from users"
- });
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error migrating users database");
- }
- }
-
- /// <summary>
- /// Save a user in the repo
- /// </summary>
- public void CreateUser(User user)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- var serialized = _jsonSerializer.SerializeToBytes(user);
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
- {
- statement.TryBind("@guid", user.Id.ToGuidBlob());
- statement.TryBind("@data", serialized);
-
- statement.MoveNext();
- }
-
- var createdUser = GetUser(user.Id, false);
-
- if (createdUser == null)
- {
- throw new ApplicationException("created user should never be null");
- }
-
- user.InternalId = createdUser.InternalId;
-
- }, TransactionMode);
- }
- }
- }
-
- public void UpdateUser(User user)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- var serialized = _jsonSerializer.SerializeToBytes(user);
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
- {
- statement.TryBind("@InternalId", user.InternalId);
- statement.TryBind("@data", serialized);
- statement.MoveNext();
- }
-
- }, TransactionMode);
- }
- }
- }
-
- private User GetUser(Guid guid, bool openLock)
- {
- using (openLock ? WriteLock.Read() : null)
- {
- using (var connection = CreateConnection(true))
- {
- using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
- {
- statement.TryBind("@guid", guid);
-
- foreach (var row in statement.ExecuteQuery())
- {
- return GetUser(row);
- }
- }
- }
- }
-
- return null;
- }
-
- private User GetUser(IReadOnlyList<IResultSetValue> row)
- {
- var id = row[0].ToInt64();
- var guid = row[1].ReadGuidFromBlob();
-
- using (var stream = new MemoryStream(row[2].ToBlob()))
- {
- stream.Position = 0;
- var user = _jsonSerializer.DeserializeFromStream<User>(stream);
- user.InternalId = id;
- user.Id = guid;
- return user;
- }
- }
-
- /// <summary>
- /// Retrieve all users from the database
- /// </summary>
- /// <returns>IEnumerable{User}.</returns>
- public List<User> RetrieveAllUsers()
- {
- var list = new List<User>();
-
- using (WriteLock.Read())
- {
- using (var connection = CreateConnection(true))
- {
- foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
- {
- list.Add(GetUser(row));
- }
- }
- }
-
- return list;
- }
-
- /// <summary>
- /// Deletes the user.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- public void DeleteUser(User user)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
- {
- statement.TryBind("@id", user.InternalId);
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Data/SynchronouseMode.cs b/Emby.Server.Implementations/Data/SynchronouseMode.cs
new file mode 100644
index 000000000..cde524e2e
--- /dev/null
+++ b/Emby.Server.Implementations/Data/SynchronouseMode.cs
@@ -0,0 +1,30 @@
+namespace Emby.Server.Implementations.Data;
+
+/// <summary>
+/// The disk synchronization mode, controls how aggressively SQLite will write data
+/// all the way out to physical storage.
+/// </summary>
+public enum SynchronousMode
+{
+ /// <summary>
+ /// SQLite continues without syncing as soon as it has handed data off to the operating system.
+ /// </summary>
+ Off = 0,
+
+ /// <summary>
+ /// SQLite database engine will still sync at the most critical moments.
+ /// </summary>
+ Normal = 1,
+
+ /// <summary>
+ /// SQLite database engine will use the xSync method of the VFS
+ /// to ensure that all content is safely written to the disk surface prior to continuing.
+ /// </summary>
+ Full = 2,
+
+ /// <summary>
+ /// EXTRA synchronous is like FULL with the addition that the directory containing a rollback journal
+ /// is synced after that journal is unlinked to commit a transaction in DELETE mode.
+ /// </summary>
+ Extra = 3
+}
diff --git a/Emby.Server.Implementations/Data/TempStoreMode.cs b/Emby.Server.Implementations/Data/TempStoreMode.cs
new file mode 100644
index 000000000..d2427ce47
--- /dev/null
+++ b/Emby.Server.Implementations/Data/TempStoreMode.cs
@@ -0,0 +1,23 @@
+namespace Emby.Server.Implementations.Data;
+
+/// <summary>
+/// Storage mode used by temporary database files.
+/// </summary>
+public enum TempStoreMode
+{
+ /// <summary>
+ /// The compile-time C preprocessor macro SQLITE_TEMP_STORE
+ /// is used to determine where temporary tables and indices are stored.
+ /// </summary>
+ Default = 0,
+
+ /// <summary>
+ /// Temporary tables and indices are stored in a file.
+ /// </summary>
+ File = 1,
+
+ /// <summary>
+ /// Temporary tables and indices are kept in as if they were pure in-memory databases memory.
+ /// </summary>
+ Memory = 2
+}
diff --git a/Emby.Server.Implementations/Data/TypeMapper.cs b/Emby.Server.Implementations/Data/TypeMapper.cs
index 37c952e88..064664e1f 100644
--- a/Emby.Server.Implementations/Data/TypeMapper.cs
+++ b/Emby.Server.Implementations/Data/TypeMapper.cs
@@ -1,54 +1,36 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
-using MediaBrowser.Model.Reflection;
namespace Emby.Server.Implementations.Data
{
/// <summary>
- /// Class TypeMapper
+ /// Class TypeMapper.
/// </summary>
public class TypeMapper
{
- private readonly IAssemblyInfo _assemblyInfo;
-
/// <summary>
- /// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
+ /// This holds all the types in the running assemblies
+ /// so that we can de-serialize properly when we don't have strong types.
/// </summary>
- private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
-
- public TypeMapper(IAssemblyInfo assemblyInfo)
- {
- _assemblyInfo = assemblyInfo;
- }
+ private readonly ConcurrentDictionary<string, Type?> _typeMap = new ConcurrentDictionary<string, Type?>();
/// <summary>
/// Gets the type.
/// </summary>
/// <param name="typeName">Name of the type.</param>
/// <returns>Type.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- public Type GetType(string typeName)
+ /// <exception cref="ArgumentNullException"><c>typeName</c> is null.</exception>
+ public Type? GetType(string typeName)
{
if (string.IsNullOrEmpty(typeName))
{
throw new ArgumentNullException(nameof(typeName));
}
- return _typeMap.GetOrAdd(typeName, LookupType);
- }
-
- /// <summary>
- /// Lookups the type.
- /// </summary>
- /// <param name="typeName">Name of the type.</param>
- /// <returns>Type.</returns>
- private Type LookupType(string typeName)
- {
- return _assemblyInfo
- .GetCurrentAssemblies()
- .Select(a => a.GetType(typeName))
- .FirstOrDefault(t => t != null);
+ return _typeMap.GetOrAdd(typeName, k => AppDomain.CurrentDomain.GetAssemblies()
+ .Select(a => a.GetType(k))
+ .FirstOrDefault(t => t != null));
}
}
}
diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs
index 495c3436a..0cfced8be 100644
--- a/Emby.Server.Implementations/Devices/DeviceId.cs
+++ b/Emby.Server.Implementations/Devices/DeviceId.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Devices
@@ -10,10 +14,19 @@ namespace Emby.Server.Implementations.Devices
public class DeviceId
{
private readonly IApplicationPaths _appPaths;
- private readonly ILogger _logger;
-
+ private readonly ILogger<DeviceId> _logger;
private readonly object _syncLock = new object();
+ private string _id;
+
+ public DeviceId(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
+ {
+ _appPaths = appPaths;
+ _logger = loggerFactory.CreateLogger<DeviceId>();
+ }
+
+ public string Value => _id ?? (_id = GetDeviceId());
+
private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt");
private string GetCachedId()
@@ -67,7 +80,7 @@ namespace Emby.Server.Implementations.Devices
private static string GetNewId()
{
- return Guid.NewGuid().ToString("N");
+ return Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
}
private string GetDeviceId()
@@ -82,15 +95,5 @@ namespace Emby.Server.Implementations.Devices
return id;
}
-
- private string _id;
-
- public DeviceId(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
- {
- _appPaths = appPaths;
- _logger = loggerFactory.CreateLogger("SystemId");
- }
-
- public string Value => _id ?? (_id = GetDeviceId());
}
}
diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs
deleted file mode 100644
index 7d6529a67..000000000
--- a/Emby.Server.Implementations/Devices/DeviceManager.cs
+++ /dev/null
@@ -1,501 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Devices;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.Users;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Devices
-{
- public class DeviceManager : IDeviceManager
- {
- private readonly IJsonSerializer _json;
- private readonly IUserManager _userManager;
- private readonly IFileSystem _fileSystem;
- private readonly ILibraryMonitor _libraryMonitor;
- private readonly IServerConfigurationManager _config;
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localizationManager;
-
- private readonly IAuthenticationRepository _authRepo;
-
- public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
- public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
-
- private readonly object _cameraUploadSyncLock = new object();
- private readonly object _capabilitiesSyncLock = new object();
-
- public DeviceManager(
- IAuthenticationRepository authRepo,
- IJsonSerializer json,
- ILibraryManager libraryManager,
- ILocalizationManager localizationManager,
- IUserManager userManager,
- IFileSystem fileSystem,
- ILibraryMonitor libraryMonitor,
- IServerConfigurationManager config)
- {
- _json = json;
- _userManager = userManager;
- _fileSystem = fileSystem;
- _libraryMonitor = libraryMonitor;
- _config = config;
- _libraryManager = libraryManager;
- _localizationManager = localizationManager;
- _authRepo = authRepo;
- }
-
-
- private Dictionary<string, ClientCapabilities> _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
- public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
- {
- var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- lock (_capabilitiesSyncLock)
- {
- _capabilitiesCache[deviceId] = capabilities;
-
- _json.SerializeToFile(capabilities, path);
- }
- }
-
- public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
- {
- _authRepo.UpdateDeviceOptions(deviceId, options);
-
- if (DeviceOptionsUpdated != null)
- {
- DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
- {
- Argument = new Tuple<string, DeviceOptions>(deviceId, options)
- });
- }
- }
-
- public DeviceOptions GetDeviceOptions(string deviceId)
- {
- return _authRepo.GetDeviceOptions(deviceId);
- }
-
- public ClientCapabilities GetCapabilities(string id)
- {
- lock (_capabilitiesSyncLock)
- {
- if (_capabilitiesCache.TryGetValue(id, out var result))
- {
- return result;
- }
-
- var path = Path.Combine(GetDevicePath(id), "capabilities.json");
- try
- {
- return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
- }
- catch
- {
- }
- }
-
- return new ClientCapabilities();
- }
-
- public DeviceInfo GetDevice(string id)
- {
- return GetDevice(id, true);
- }
-
- private DeviceInfo GetDevice(string id, bool includeCapabilities)
- {
- var session = _authRepo.Get(new AuthenticationInfoQuery
- {
- DeviceId = id
-
- }).Items.FirstOrDefault();
-
- var device = session == null ? null : ToDeviceInfo(session);
-
- return device;
- }
-
- public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
- {
- var sessions = _authRepo.Get(new AuthenticationInfoQuery
- {
- //UserId = query.UserId
- HasUser = true
-
- }).Items;
-
- // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
- if (query.SupportsSync.HasValue)
- {
- var val = query.SupportsSync.Value;
-
- sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val).ToArray();
- }
-
- if (!query.UserId.Equals(Guid.Empty))
- {
- var user = _userManager.GetUserById(query.UserId);
-
- sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)).ToArray();
- }
-
- var array = sessions.Select(ToDeviceInfo).ToArray();
-
- return new QueryResult<DeviceInfo>
- {
- Items = array,
- TotalRecordCount = array.Length
- };
- }
-
- private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
- {
- var caps = GetCapabilities(authInfo.DeviceId);
-
- return new DeviceInfo
- {
- AppName = authInfo.AppName,
- AppVersion = authInfo.AppVersion,
- Id = authInfo.DeviceId,
- LastUserId = authInfo.UserId,
- LastUserName = authInfo.UserName,
- Name = authInfo.DeviceName,
- DateLastActivity = authInfo.DateLastActivity,
- IconUrl = caps == null ? null : caps.IconUrl
- };
- }
-
- private string GetDevicesPath()
- {
- return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
- }
-
- private string GetDevicePath(string id)
- {
- return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N"));
- }
-
- public ContentUploadHistory GetCameraUploadHistory(string deviceId)
- {
- var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
-
- lock (_cameraUploadSyncLock)
- {
- try
- {
- return _json.DeserializeFromFile<ContentUploadHistory>(path);
- }
- catch (IOException)
- {
- return new ContentUploadHistory
- {
- DeviceId = deviceId
- };
- }
- }
- }
-
- public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
- {
- var device = GetDevice(deviceId, false);
- var uploadPathInfo = GetUploadPath(device);
-
- var path = uploadPathInfo.Item1;
-
- if (!string.IsNullOrWhiteSpace(file.Album))
- {
- path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
- }
-
- path = Path.Combine(path, file.Name);
- path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
-
- _libraryMonitor.ReportFileSystemChangeBeginning(path);
-
- try
- {
- using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
- {
- await stream.CopyToAsync(fs).ConfigureAwait(false);
- }
-
- AddCameraUpload(deviceId, file);
- }
- finally
- {
- _libraryMonitor.ReportFileSystemChangeComplete(path, true);
- }
-
- if (CameraImageUploaded != null)
- {
- CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
- {
- Argument = new CameraImageUploadInfo
- {
- Device = device,
- FileInfo = file
- }
- });
- }
- }
-
- private void AddCameraUpload(string deviceId, LocalFileInfo file)
- {
- var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- lock (_cameraUploadSyncLock)
- {
- ContentUploadHistory history;
-
- try
- {
- history = _json.DeserializeFromFile<ContentUploadHistory>(path);
- }
- catch (IOException)
- {
- history = new ContentUploadHistory
- {
- DeviceId = deviceId
- };
- }
-
- history.DeviceId = deviceId;
-
- var list = history.FilesUploaded.ToList();
- list.Add(file);
- history.FilesUploaded = list.ToArray();
-
- _json.SerializeToFile(history, path);
- }
- }
-
- internal Task EnsureLibraryFolder(string path, string name)
- {
- var existingFolders = _libraryManager
- .RootFolder
- .Children
- .OfType<Folder>()
- .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
- .ToList();
-
- if (existingFolders.Count > 0)
- {
- return Task.CompletedTask;
- }
-
- Directory.CreateDirectory(path);
-
- var libraryOptions = new LibraryOptions
- {
- PathInfos = new[] { new MediaPathInfo { Path = path } },
- EnablePhotos = true,
- EnableRealtimeMonitor = false,
- SaveLocalMetadata = true
- };
-
- if (string.IsNullOrWhiteSpace(name))
- {
- name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
- }
-
- return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
- }
-
- private Tuple<string, string, string> GetUploadPath(DeviceInfo device)
- {
- var config = _config.GetUploadOptions();
- var path = config.CameraUploadPath;
-
- if (string.IsNullOrWhiteSpace(path))
- {
- path = DefaultCameraUploadsPath;
- }
-
- var topLibraryPath = path;
-
- if (config.EnableCameraUploadSubfolders)
- {
- path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
- }
-
- return new Tuple<string, string, string>(path, topLibraryPath, null);
- }
-
- internal string GetUploadsPath()
- {
- var config = _config.GetUploadOptions();
- var path = config.CameraUploadPath;
-
- if (string.IsNullOrWhiteSpace(path))
- {
- path = DefaultCameraUploadsPath;
- }
-
- return path;
- }
-
- private string DefaultCameraUploadsPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
-
- public bool CanAccessDevice(User user, string deviceId)
- {
- if (user == null)
- {
- throw new ArgumentException("user not found");
- }
- if (string.IsNullOrEmpty(deviceId))
- {
- throw new ArgumentNullException(nameof(deviceId));
- }
-
- if (!CanAccessDevice(user.Policy, deviceId))
- {
- var capabilities = GetCapabilities(deviceId);
-
- if (capabilities != null && capabilities.SupportsPersistentIdentifier)
- {
- return false;
- }
- }
-
- return true;
- }
-
- private static bool CanAccessDevice(UserPolicy policy, string id)
- {
- if (policy.EnableAllDevices)
- {
- return true;
- }
-
- if (policy.IsAdministrator)
- {
- return true;
- }
-
- return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
- }
- }
-
- public class DeviceManagerEntryPoint : IServerEntryPoint
- {
- private readonly DeviceManager _deviceManager;
- private readonly IServerConfigurationManager _config;
- private ILogger _logger;
-
- public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, ILogger logger)
- {
- _deviceManager = (DeviceManager)deviceManager;
- _config = config;
- _logger = logger;
- }
-
- public async Task RunAsync()
- {
- if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
- {
- var path = _deviceManager.GetUploadsPath();
-
- if (Directory.Exists(path))
- {
- try
- {
- await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error creating camera uploads library");
- }
-
- _config.Configuration.CameraUploadUpgraded = true;
- _config.SaveConfiguration();
- }
- }
- }
-
- #region IDisposable Support
- private bool disposedValue = false; // To detect redundant calls
-
- protected virtual void Dispose(bool disposing)
- {
- if (!disposedValue)
- {
- if (disposing)
- {
- // TODO: dispose managed state (managed objects).
- }
-
- // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
- // TODO: set large fields to null.
-
- disposedValue = true;
- }
- }
-
- // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
- // ~DeviceManagerEntryPoint() {
- // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- // Dispose(false);
- // }
-
- // This code added to correctly implement the disposable pattern.
- public void Dispose()
- {
- // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- Dispose(true);
- // TODO: uncomment the following line if the finalizer is overridden above.
- // GC.SuppressFinalize(this);
- }
- #endregion
- }
-
- public class DevicesConfigStore : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new ConfigurationStore[]
- {
- new ConfigurationStore
- {
- Key = "devices",
- ConfigurationType = typeof(DevicesOptions)
- }
- };
- }
- }
-
- public static class UploadConfigExtension
- {
- public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
- {
- return config.GetConfiguration<DevicesOptions>("devices");
- }
- }
-}
diff --git a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs
deleted file mode 100644
index 78b22bda3..000000000
--- a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Diagnostics;
-
-namespace Emby.Server.Implementations.Diagnostics
-{
- public class CommonProcess : IProcess
- {
- public event EventHandler Exited;
-
- private readonly ProcessOptions _options;
- private readonly Process _process;
-
- public CommonProcess(ProcessOptions options)
- {
- _options = options;
-
- var startInfo = new ProcessStartInfo
- {
- Arguments = options.Arguments,
- FileName = options.FileName,
- WorkingDirectory = options.WorkingDirectory,
- UseShellExecute = options.UseShellExecute,
- CreateNoWindow = options.CreateNoWindow,
- RedirectStandardError = options.RedirectStandardError,
- RedirectStandardInput = options.RedirectStandardInput,
- RedirectStandardOutput = options.RedirectStandardOutput
- };
-
- startInfo.ErrorDialog = options.ErrorDialog;
-
- if (options.IsHidden)
- {
- startInfo.WindowStyle = ProcessWindowStyle.Hidden;
- }
-
- _process = new Process
- {
- StartInfo = startInfo
- };
-
- if (options.EnableRaisingEvents)
- {
- _process.EnableRaisingEvents = true;
- _process.Exited += _process_Exited;
- }
- }
-
- private bool _hasExited;
- private bool HasExited
- {
- get
- {
- if (_hasExited)
- {
- return true;
- }
-
- try
- {
- _hasExited = _process.HasExited;
- }
- catch (InvalidOperationException)
- {
- _hasExited = true;
- }
-
- return _hasExited;
- }
- }
-
- private void _process_Exited(object sender, EventArgs e)
- {
- _hasExited = true;
- if (Exited != null)
- {
- Exited(this, e);
- }
- }
-
- public ProcessOptions StartInfo => _options;
-
- public StreamWriter StandardInput => _process.StandardInput;
-
- public StreamReader StandardError => _process.StandardError;
-
- public StreamReader StandardOutput => _process.StandardOutput;
-
- public int ExitCode => _process.ExitCode;
-
- public void Start()
- {
- _process.Start();
- }
-
- public void Kill()
- {
- _process.Kill();
- }
-
- public bool WaitForExit(int timeMs)
- {
- return _process.WaitForExit(timeMs);
- }
-
- public Task<bool> WaitForExitAsync(int timeMs)
- {
- //Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true.
-
- if (HasExited)
- {
- return Task.FromResult(true);
- }
-
- timeMs = Math.Max(0, timeMs);
-
- var tcs = new TaskCompletionSource<bool>();
-
- var cancellationToken = new CancellationTokenSource(timeMs).Token;
-
- _process.Exited += (sender, args) => tcs.TrySetResult(true);
-
- cancellationToken.Register(() => tcs.TrySetResult(HasExited));
-
- return tcs.Task;
- }
-
- public void Dispose()
- {
- _process.Dispose();
- }
- }
-}
diff --git a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs
deleted file mode 100644
index 14aadaaae..000000000
--- a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using MediaBrowser.Model.Diagnostics;
-
-namespace Emby.Server.Implementations.Diagnostics
-{
- public class ProcessFactory : IProcessFactory
- {
- public IProcess Create(ProcessOptions options)
- {
- return new CommonProcess(options);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs
index 2233d3d40..ad76f3d6d 100644
--- a/Emby.Server.Implementations/Dto/DtoService.cs
+++ b/Emby.Server.Implementations/Dto/DtoService.cs
@@ -1,18 +1,21 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common;
using MediaBrowser.Controller.Channels;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Persistence;
@@ -21,16 +24,22 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
+using Book = MediaBrowser.Controller.Entities.Book;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Person = MediaBrowser.Controller.Entities.Person;
+using Photo = MediaBrowser.Controller.Entities.Photo;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Server.Implementations.Dto
{
public class DtoService : IDtoService
{
- private readonly ILogger _logger;
+ private readonly ILogger<DtoService> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IUserDataManager _userDataRepository;
private readonly IItemRepository _itemRepo;
@@ -39,21 +48,21 @@ namespace Emby.Server.Implementations.Dto
private readonly IProviderManager _providerManager;
private readonly IApplicationHost _appHost;
- private readonly Func<IMediaSourceManager> _mediaSourceManager;
- private readonly Func<ILiveTvManager> _livetvManager;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly Lazy<ILiveTvManager> _livetvManagerFactory;
public DtoService(
- ILoggerFactory loggerFactory,
+ ILogger<DtoService> logger,
ILibraryManager libraryManager,
IUserDataManager userDataRepository,
IItemRepository itemRepo,
IImageProcessor imageProcessor,
IProviderManager providerManager,
IApplicationHost appHost,
- Func<IMediaSourceManager> mediaSourceManager,
- Func<ILiveTvManager> livetvManager)
+ IMediaSourceManager mediaSourceManager,
+ Lazy<ILiveTvManager> livetvManagerFactory)
{
- _logger = loggerFactory.CreateLogger(nameof(DtoService));
+ _logger = logger;
_libraryManager = libraryManager;
_userDataRepository = userDataRepository;
_itemRepo = itemRepo;
@@ -61,64 +70,33 @@ namespace Emby.Server.Implementations.Dto
_providerManager = providerManager;
_appHost = appHost;
_mediaSourceManager = mediaSourceManager;
- _livetvManager = livetvManager;
- }
-
- /// <summary>
- /// Converts a BaseItem to a DTOBaseItem
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="fields">The fields.</param>
- /// <param name="user">The user.</param>
- /// <param name="owner">The owner.</param>
- /// <returns>Task{DtoBaseItem}.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public BaseItemDto GetBaseItemDto(BaseItem item, ItemFields[] fields, User user = null, BaseItem owner = null)
- {
- var options = new DtoOptions
- {
- Fields = fields
- };
-
- return GetBaseItemDto(item, options, user, owner);
- }
-
- public BaseItemDto[] GetBaseItemDtos(List<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
- {
- return GetBaseItemDtos(items, items.Count, options, user, owner);
+ _livetvManagerFactory = livetvManagerFactory;
}
- public BaseItemDto[] GetBaseItemDtos(BaseItem[] items, DtoOptions options, User user = null, BaseItem owner = null)
- {
- return GetBaseItemDtos(items, items.Length, options, user, owner);
- }
+ private ILiveTvManager LivetvManager => _livetvManagerFactory.Value;
- public BaseItemDto[] GetBaseItemDtos(IEnumerable<BaseItem> items, int itemCount, DtoOptions options, User user = null, BaseItem owner = null)
+ /// <inheritdoc />
+ public IReadOnlyList<BaseItemDto> GetBaseItemDtos(IReadOnlyList<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
{
- var returnItems = new BaseItemDto[itemCount];
- var programTuples = new List<Tuple<BaseItem, BaseItemDto>>();
- var channelTuples = new List<Tuple<BaseItemDto, LiveTvChannel>>();
-
- var index = 0;
- var allCollectionFolders = _libraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
+ var returnItems = new BaseItemDto[items.Count];
+ var programTuples = new List<(BaseItem, BaseItemDto)>();
+ var channelTuples = new List<(BaseItemDto, LiveTvChannel)>();
- foreach (var item in items)
+ for (int index = 0; index < items.Count; index++)
{
- var dto = GetBaseItemDtoInternal(item, options, allCollectionFolders, user, owner);
+ var item = items[index];
+ var dto = GetBaseItemDtoInternal(item, options, user, owner);
- var tvChannel = item as LiveTvChannel;
- if (tvChannel != null)
+ if (item is LiveTvChannel tvChannel)
{
- channelTuples.Add(new Tuple<BaseItemDto, LiveTvChannel>(dto, tvChannel));
+ channelTuples.Add((dto, tvChannel));
}
else if (item is LiveTvProgram)
{
- programTuples.Add(new Tuple<BaseItem, BaseItemDto>(item, dto));
+ programTuples.Add((item, dto));
}
- var byName = item as IItemByName;
-
- if (byName != null)
+ if (item is IItemByName byName)
{
if (options.ContainsField(ItemFields.ItemCounts))
{
@@ -136,18 +114,16 @@ namespace Emby.Server.Implementations.Dto
}
returnItems[index] = dto;
- index++;
}
if (programTuples.Count > 0)
{
- var task = _livetvManager().AddInfoToProgramDto(programTuples, options.Fields, user);
- Task.WaitAll(task);
+ LivetvManager.AddInfoToProgramDto(programTuples, options.Fields, user).GetAwaiter().GetResult();
}
if (channelTuples.Count > 0)
{
- _livetvManager().AddChannelInfo(channelTuples, options, user);
+ LivetvManager.AddChannelInfo(channelTuples, options, user);
}
return returnItems;
@@ -155,35 +131,33 @@ namespace Emby.Server.Implementations.Dto
public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
{
- var allCollectionFolders = _libraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
- var dto = GetBaseItemDtoInternal(item, options, allCollectionFolders, user, owner);
- var tvChannel = item as LiveTvChannel;
- if (tvChannel != null)
+ var dto = GetBaseItemDtoInternal(item, options, user, owner);
+ if (item is LiveTvChannel tvChannel)
{
- var list = new List<Tuple<BaseItemDto, LiveTvChannel>> { new Tuple<BaseItemDto, LiveTvChannel>(dto, tvChannel) };
- _livetvManager().AddChannelInfo(list, options, user);
+ var list = new List<(BaseItemDto, LiveTvChannel)>(1) { (dto, tvChannel) };
+ LivetvManager.AddChannelInfo(list, options, user);
}
else if (item is LiveTvProgram)
{
- var list = new List<Tuple<BaseItem, BaseItemDto>> { new Tuple<BaseItem, BaseItemDto>(item, dto) };
- var task = _livetvManager().AddInfoToProgramDto(list, options.Fields, user);
+ var list = new List<(BaseItem, BaseItemDto)>(1) { (item, dto) };
+ var task = LivetvManager.AddInfoToProgramDto(list, options.Fields, user);
Task.WaitAll(task);
}
- var byName = item as IItemByName;
-
- if (byName != null)
+ if (item is IItemByName itemByName
+ && options.ContainsField(ItemFields.ItemCounts))
{
- if (options.ContainsField(ItemFields.ItemCounts))
- {
- SetItemByNameInfo(item, dto, GetTaggedItems(byName, user, new DtoOptions(false)
- {
- EnableImages = false
-
- }), user);
- }
-
- return dto;
+ SetItemByNameInfo(
+ item,
+ dto,
+ GetTaggedItems(
+ itemByName,
+ user,
+ new DtoOptions(false)
+ {
+ EnableImages = false
+ }),
+ user);
}
return dto;
@@ -191,15 +165,15 @@ namespace Emby.Server.Implementations.Dto
private static IList<BaseItem> GetTaggedItems(IItemByName byName, User user, DtoOptions options)
{
- return byName.GetTaggedItems(new InternalItemsQuery(user)
- {
- Recursive = true,
- DtoOptions = options
-
- });
+ return byName.GetTaggedItems(
+ new InternalItemsQuery(user)
+ {
+ Recursive = true,
+ DtoOptions = options
+ });
}
- private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, List<Folder> allCollectionFolders, User user = null, BaseItem owner = null)
+ private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
{
var dto = new BaseItemDto
{
@@ -225,13 +199,13 @@ namespace Emby.Server.Implementations.Dto
catch (Exception ex)
{
// Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
- _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {itemName}", item.Name);
+ _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {ItemName}", item.Name);
}
}
if (options.ContainsField(ItemFields.DisplayPreferencesId))
{
- dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
+ dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N", CultureInfo.InvariantCulture);
}
if (user != null)
@@ -239,15 +213,12 @@ namespace Emby.Server.Implementations.Dto
AttachUserSpecificInfo(dto, item, user, options);
}
- var hasMediaSources = item as IHasMediaSources;
- if (hasMediaSources != null)
+ if (item is IHasMediaSources
+ && options.ContainsField(ItemFields.MediaSources))
{
- if (options.ContainsField(ItemFields.MediaSources))
- {
- dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(item, true, user).ToArray();
+ dto.MediaSources = _mediaSourceManager.GetStaticMediaSources(item, true, user).ToArray();
- NormalizeMediaSourceContainers(dto);
- }
+ NormalizeMediaSourceContainers(dto);
}
if (options.ContainsField(ItemFields.Studios))
@@ -276,11 +247,11 @@ namespace Emby.Server.Implementations.Dto
dto.Etag = item.GetEtag(user);
}
- var liveTvManager = _livetvManager();
+ var liveTvManager = LivetvManager;
var activeRecording = liveTvManager.GetActiveRecordingInfo(item.Path);
if (activeRecording != null)
{
- dto.Type = "Recording";
+ dto.Type = BaseItemKind.Recording;
dto.CanDownload = false;
dto.RunTimeTicks = null;
@@ -289,6 +260,7 @@ namespace Emby.Server.Implementations.Dto
dto.EpisodeTitle = dto.Name;
dto.Name = dto.SeriesName;
}
+
liveTvManager.AddInfoToRecordingDto(item, dto, activeRecording, user);
}
@@ -304,7 +276,8 @@ namespace Emby.Server.Implementations.Dto
{
continue;
}
- var containers = container.Split(new[] { ',' });
+
+ var containers = container.Split(',');
if (containers.Length < 2)
{
continue;
@@ -323,6 +296,7 @@ namespace Emby.Server.Implementations.Dto
{
path = path.TrimStart('.');
}
+
if (!string.IsNullOrEmpty(path) && containers.Contains(path, StringComparer.OrdinalIgnoreCase))
{
fileExtensionContainer = path;
@@ -336,8 +310,7 @@ namespace Emby.Server.Implementations.Dto
public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null)
{
- var allCollectionFolders = _libraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
- var dto = GetBaseItemDtoInternal(item, options, allCollectionFolders, user);
+ var dto = GetBaseItemDtoInternal(item, options, user);
if (taggedItems != null && options.ContainsField(ItemFields.ItemCounts))
{
@@ -404,7 +377,7 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.ChildCount))
{
- dto.ChildCount = dto.ChildCount ?? GetChildCount(folder, user);
+ dto.ChildCount ??= GetChildCount(folder, user);
}
}
@@ -418,7 +391,6 @@ namespace Emby.Server.Implementations.Dto
dto.DateLastMediaAdded = folder.DateLastMediaAdded;
}
}
-
else
{
if (options.EnableUserData)
@@ -434,7 +406,7 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.BasicSyncInfo))
{
- var userCanSync = user != null && user.Policy.EnableContentDownloading;
+ var userCanSync = user != null && user.HasPermission(PermissionKind.EnableContentDownloading);
if (userCanSync && item.SupportsExternalTransfer)
{
dto.SupportsSync = true;
@@ -448,27 +420,17 @@ namespace Emby.Server.Implementations.Dto
// Just return something so that apps that are expecting a value won't think the folders are empty
if (folder is ICollectionFolder || folder is UserView)
{
- return new Random().Next(1, 10);
+ return Random.Shared.Next(1, 10);
}
return folder.GetChildCount(user);
}
- /// <summary>
- /// Gets client-side Id of a server-side BaseItem
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">item</exception>
- public string GetDtoId(BaseItem item)
- {
- return item.Id.ToString("N");
- }
-
private static void SetBookProperties(BaseItemDto dto, Book item)
{
dto.SeriesName = item.SeriesName;
}
+
private static void SetPhotoProperties(BaseItemDto dto, Photo item)
{
dto.CameraMake = item.CameraMake;
@@ -494,16 +456,20 @@ namespace Emby.Server.Implementations.Dto
}
}
+ private string GetDtoId(BaseItem item)
+ {
+ return item.Id.ToString("N", CultureInfo.InvariantCulture);
+ }
+
private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
{
if (!string.IsNullOrEmpty(item.Album))
{
var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Name = item.Album,
Limit = 1
-
});
if (parentAlbumIds.Count > 0)
@@ -523,19 +489,6 @@ namespace Emby.Server.Implementations.Dto
.ToArray();
}
- private string GetImageCacheTag(BaseItem item, ImageType type)
- {
- try
- {
- return _imageProcessor.GetImageCacheTag(item, type);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting {type} image info", type);
- return null;
- }
- }
-
private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
{
try
@@ -550,11 +503,10 @@ namespace Emby.Server.Implementations.Dto
}
/// <summary>
- /// Attaches People DTO's to a DTOBaseItem
+ /// Attaches People DTO's to a DTOBaseItem.
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
- /// <returns>Task.</returns>
private void AttachPeople(BaseItemDto dto, BaseItem item)
{
// Ordering by person type to ensure actors and artists are at the front.
@@ -567,22 +519,27 @@ namespace Emby.Server.Implementations.Dto
{
return 0;
}
+
if (i.IsType(PersonType.GuestStar))
{
return 1;
}
+
if (i.IsType(PersonType.Director))
{
return 2;
}
+
if (i.IsType(PersonType.Writer))
{
return 3;
}
+
if (i.IsType(PersonType.Producer))
{
return 4;
}
+
if (i.IsType(PersonType.Composer))
{
return 4;
@@ -606,7 +563,6 @@ namespace Emby.Server.Implementations.Dto
_logger.LogError(ex, "Error getting person {Name}", c);
return null;
}
-
}).Where(i => i != null)
.GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
.Select(x => x.First())
@@ -625,8 +581,28 @@ namespace Emby.Server.Implementations.Dto
if (dictionary.TryGetValue(person.Name, out Person entity))
{
- baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
- baseItemPerson.Id = entity.Id.ToString("N");
+ baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary);
+ baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture);
+ if (dto.ImageBlurHashes != null)
+ {
+ // Only add BlurHash for the person's image.
+ baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
+ foreach (var (imageType, blurHash) in dto.ImageBlurHashes)
+ {
+ if (blurHash != null)
+ {
+ baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>();
+ foreach (var (imageId, blurHashValue) in blurHash)
+ {
+ if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase))
+ {
+ baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue;
+ }
+ }
+ }
+ }
+ }
+
list.Add(baseItemPerson);
}
}
@@ -639,7 +615,6 @@ namespace Emby.Server.Implementations.Dto
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
- /// <returns>Task.</returns>
private void AttachStudios(BaseItemDto dto, BaseItem item)
{
dto.Studios = item.Studios
@@ -674,8 +649,66 @@ namespace Emby.Server.Implementations.Dto
return _libraryManager.GetGenreId(name);
}
+ private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ImageType imageType, int imageIndex = 0)
+ {
+ var image = item.GetImageInfo(imageType, imageIndex);
+ if (image != null)
+ {
+ return GetTagAndFillBlurhash(dto, item, image);
+ }
+
+ return null;
+ }
+
+ private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ItemImageInfo image)
+ {
+ var tag = GetImageCacheTag(item, image);
+ if (!string.IsNullOrEmpty(image.BlurHash))
+ {
+ dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
+
+ if (!dto.ImageBlurHashes.ContainsKey(image.Type))
+ {
+ dto.ImageBlurHashes[image.Type] = new Dictionary<string, string>();
+ }
+
+ dto.ImageBlurHashes[image.Type][tag] = image.BlurHash;
+ }
+
+ return tag;
+ }
+
+ private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, int limit)
+ {
+ return GetTagsAndFillBlurhashes(dto, item, imageType, item.GetImages(imageType).Take(limit).ToList());
+ }
+
+ private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, List<ItemImageInfo> images)
+ {
+ var tags = GetImageTags(item, images);
+ var hashes = new Dictionary<string, string>();
+ for (int i = 0; i < images.Count; i++)
+ {
+ var img = images[i];
+ if (!string.IsNullOrEmpty(img.BlurHash))
+ {
+ var tag = tags[i];
+ hashes[tag] = img.BlurHash;
+ }
+ }
+
+ if (hashes.Count > 0)
+ {
+ dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
+
+ dto.ImageBlurHashes[imageType] = hashes;
+ }
+
+ return tags;
+ }
+
/// <summary>
- /// Sets simple property values on a DTOBaseItem
+ /// Sets simple property values on a DTOBaseItem.
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
@@ -694,8 +727,8 @@ namespace Emby.Server.Implementations.Dto
dto.LockData = item.IsLocked;
dto.ForcedSortName = item.ForcedSortName;
}
- dto.Container = item.Container;
+ dto.Container = item.Container;
dto.EndDate = item.EndDate;
if (options.ContainsField(ItemFields.ExternalUrls))
@@ -714,10 +747,12 @@ namespace Emby.Server.Implementations.Dto
dto.AspectRatio = hasAspectRatio.AspectRatio;
}
+ dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
+
var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
if (backdropLimit > 0)
{
- dto.BackdropImageTags = GetImageTags(item, item.GetImages(ImageType.Backdrop).Take(backdropLimit).ToList());
+ dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
}
if (options.ContainsField(ItemFields.ScreenshotImageTags))
@@ -725,7 +760,7 @@ namespace Emby.Server.Implementations.Dto
var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
if (screenshotLimit > 0)
{
- dto.ScreenshotImageTags = GetImageTags(item, item.GetImages(ImageType.Screenshot).Take(screenshotLimit).ToList());
+ dto.ScreenshotImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Screenshot, screenshotLimit);
}
}
@@ -741,12 +776,11 @@ namespace Emby.Server.Implementations.Dto
// Prevent implicitly captured closure
var currentItem = item;
- foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
- .ToList())
+ foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
{
if (options.GetImageLimit(image.Type) > 0)
{
- var tag = GetImageCacheTag(item, image);
+ var tag = GetTagAndFillBlurhash(dto, item, image);
if (tag != null)
{
@@ -771,7 +805,7 @@ namespace Emby.Server.Implementations.Dto
dto.MediaType = item.MediaType;
- if (!(item is LiveTvProgram))
+ if (item is not LiveTvProgram)
{
dto.LocationType = item.LocationType;
}
@@ -786,14 +820,12 @@ namespace Emby.Server.Implementations.Dto
dto.CriticRating = item.CriticRating;
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null)
+ if (item is IHasDisplayOrder hasDisplayOrder)
{
dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
}
- var hasCollectionType = item as IHasCollectionType;
- if (hasCollectionType != null)
+ if (item is IHasCollectionType hasCollectionType)
{
dto.CollectionType = hasCollectionType.CollectionType;
}
@@ -860,13 +892,10 @@ namespace Emby.Server.Implementations.Dto
dto.Taglines = new string[] { item.Tagline };
}
- if (dto.Taglines == null)
- {
- dto.Taglines = Array.Empty<string>();
- }
+ dto.Taglines ??= Array.Empty<string>();
}
- dto.Type = item.GetClientTypeName();
+ dto.Type = item.GetBaseItemKind();
if ((item.CommunityRating ?? 0) > 0)
{
dto.CommunityRating = item.CommunityRating;
@@ -893,43 +922,41 @@ namespace Emby.Server.Implementations.Dto
if (albumParent != null)
{
dto.AlbumId = albumParent.Id;
-
- dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
+ dto.AlbumPrimaryImageTag = GetTagAndFillBlurhash(dto, albumParent, ImageType.Primary);
}
- //if (options.ContainsField(ItemFields.MediaSourceCount))
- //{
+ // if (options.ContainsField(ItemFields.MediaSourceCount))
+ // {
// Songs always have one
- //}
+ // }
}
- var hasArtist = item as IHasArtist;
- if (hasArtist != null)
+ if (item is IHasArtist hasArtist)
{
dto.Artists = hasArtist.Artists;
- //var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
- //{
+ // var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
+ // {
// EnableTotalRecordCount = false,
- // ItemIds = new[] { item.Id.ToString("N") }
- //});
+ // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
+ // });
- //dto.ArtistItems = artistItems.Items
+ // dto.ArtistItems = artistItems.Items
// .Select(i =>
// {
// var artist = i.Item1;
// return new NameIdPair
// {
// Name = artist.Name,
- // Id = artist.Id.ToString("N")
+ // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
// };
// })
// .ToList();
// Include artists that are not in the database yet, e.g., just added via metadata editor
- //var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
+ // var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
dto.ArtistItems = hasArtist.Artists
- //.Except(foundArtists, new DistinctNameComparer())
+ // .Except(foundArtists, new DistinctNameComparer())
.Select(i =>
{
// This should not be necessary but we're seeing some cases of it
@@ -952,7 +979,6 @@ namespace Emby.Server.Implementations.Dto
}
return null;
-
}).Where(i => i != null).ToArray();
}
@@ -961,26 +987,26 @@ namespace Emby.Server.Implementations.Dto
{
dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
- //var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
- //{
+ // var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
+ // {
// EnableTotalRecordCount = false,
- // ItemIds = new[] { item.Id.ToString("N") }
- //});
+ // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
+ // });
- //dto.AlbumArtists = artistItems.Items
+ // dto.AlbumArtists = artistItems.Items
// .Select(i =>
// {
// var artist = i.Item1;
// return new NameIdPair
// {
// Name = artist.Name,
- // Id = artist.Id.ToString("N")
+ // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
// };
// })
// .ToList();
dto.AlbumArtists = hasAlbumArtist.AlbumArtists
- //.Except(foundArtists, new DistinctNameComparer())
+ // .Except(foundArtists, new DistinctNameComparer())
.Select(i =>
{
// This should not be necessary but we're seeing some cases of it
@@ -1003,13 +1029,11 @@ namespace Emby.Server.Implementations.Dto
}
return null;
-
}).Where(i => i != null).ToArray();
}
// Add video info
- var video = item as Video;
- if (video != null)
+ if (item is Video video)
{
dto.VideoType = video.VideoType;
dto.Video3DFormat = video.Video3DFormat;
@@ -1048,9 +1072,7 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.MediaStreams))
{
// Add VideoInfo
- var iHasMediaSources = item as IHasMediaSources;
-
- if (iHasMediaSources != null)
+ if (item is IHasMediaSources)
{
MediaStream[] mediaStreams;
@@ -1062,14 +1084,15 @@ namespace Emby.Server.Implementations.Dto
}
else
{
- mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, item.Id.ToString("N"), StringComparison.OrdinalIgnoreCase))
+ string id = item.Id.ToString("N", CultureInfo.InvariantCulture);
+ mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase))
.SelectMany(i => i.MediaStreams)
.ToArray();
}
}
else
{
- mediaStreams = _mediaSourceManager().GetStaticMediaSources(item, true).First().MediaStreams.ToArray();
+ mediaStreams = _mediaSourceManager.GetStaticMediaSources(item, true)[0].MediaStreams.ToArray();
}
dto.MediaStreams = mediaStreams;
@@ -1080,27 +1103,23 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.SpecialFeatureCount))
{
- if (allExtras == null)
- {
- allExtras = item.GetExtras().ToArray();
- }
-
+ allExtras = item.GetExtras().ToArray();
dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
}
if (options.ContainsField(ItemFields.LocalTrailerCount))
{
- if (allExtras == null)
+ allExtras ??= item.GetExtras().ToArray();
+ dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType == ExtraType.Trailer);
+
+ if (item is IHasTrailers hasTrailers)
{
- allExtras = item.GetExtras().ToArray();
+ dto.LocalTrailerCount += hasTrailers.GetTrailerCount();
}
-
- dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
}
// Add EpisodeInfo
- var episode = item as Episode;
- if (episode != null)
+ if (item is Episode episode)
{
dto.IndexNumberEnd = episode.IndexNumberEnd;
dto.SeriesName = episode.SeriesName;
@@ -1118,18 +1137,24 @@ namespace Emby.Server.Implementations.Dto
Series episodeSeries = null;
- //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
+ // this block will add the series poster for episodes without a poster
+ // TODO maybe remove the if statement entirely
+ // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
{
- episodeSeries = episodeSeries ?? episode.Series;
+ episodeSeries ??= episode.Series;
if (episodeSeries != null)
{
- dto.SeriesPrimaryImageTag = GetImageCacheTag(episodeSeries, ImageType.Primary);
+ dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary);
+ if (dto.ImageTags == null || !dto.ImageTags.ContainsKey(ImageType.Primary))
+ {
+ AttachPrimaryImageAspectRatio(dto, episodeSeries);
+ }
}
}
if (options.ContainsField(ItemFields.SeriesStudio))
{
- episodeSeries = episodeSeries ?? episode.Series;
+ episodeSeries ??= episode.Series;
if (episodeSeries != null)
{
dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
@@ -1138,17 +1163,15 @@ namespace Emby.Server.Implementations.Dto
}
// Add SeriesInfo
- var series = item as Series;
- if (series != null)
+ if (item is Series series)
{
dto.AirDays = series.AirDays;
dto.AirTime = series.AirTime;
- dto.Status = series.Status.HasValue ? series.Status.Value.ToString() : null;
+ dto.Status = series.Status?.ToString();
}
// Add SeasonInfo
- var season = item as Season;
- if (season != null)
+ if (item is Season season)
{
dto.SeriesName = season.SeriesName;
dto.SeriesId = season.SeriesId;
@@ -1157,31 +1180,35 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.SeriesStudio))
{
- series = series ?? season.Series;
+ series ??= season.Series;
if (series != null)
{
dto.SeriesStudio = series.Studios.FirstOrDefault();
}
}
- //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
+ // this block will add the series poster for seasons without a poster
+ // TODO maybe remove the if statement entirely
+ // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
{
- series = series ?? season.Series;
+ series ??= season.Series;
if (series != null)
{
- dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
+ dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
+ if (dto.ImageTags == null || !dto.ImageTags.ContainsKey(ImageType.Primary))
+ {
+ AttachPrimaryImageAspectRatio(dto, series);
+ }
}
}
}
- var musicVideo = item as MusicVideo;
- if (musicVideo != null)
+ if (item is MusicVideo musicVideo)
{
SetMusicVideoProperties(dto, musicVideo);
}
- var book = item as Book;
- if (book != null)
+ if (item is Book book)
{
SetBookProperties(dto, book);
}
@@ -1221,8 +1248,7 @@ namespace Emby.Server.Implementations.Dto
}
}
- var photo = item as Photo;
- if (photo != null)
+ if (item is Photo photo)
{
SetPhotoProperties(dto, photo);
}
@@ -1241,8 +1267,7 @@ namespace Emby.Server.Implementations.Dto
private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
{
- var musicAlbum = currentItem as MusicAlbum;
- if (musicAlbum != null)
+ if (currentItem is MusicAlbum musicAlbum)
{
var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
if (artist != null)
@@ -1253,7 +1278,7 @@ namespace Emby.Server.Implementations.Dto
var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
- if (parent == null && !(originalItem is UserRootFolder) && !(originalItem is UserView) && !(originalItem is AggregateFolder) && !(originalItem is ICollectionFolder) && !(originalItem is Channel))
+ if (parent == null && originalItem is not UserRootFolder && originalItem is not UserView && originalItem is not AggregateFolder && originalItem is not ICollectionFolder && originalItem is not Channel)
{
parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
}
@@ -1286,9 +1311,12 @@ namespace Emby.Server.Implementations.Dto
var imageTags = dto.ImageTags;
- while (((!(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && logoLimit > 0) || (!(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && artLimit > 0) || (!(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && thumbLimit > 0) || parent is Series) &&
- (parent = parent ?? (isFirst ? GetImageDisplayParent(item, item) ?? owner : parent)) != null)
+ while ((!(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && logoLimit > 0)
+ || (!(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && artLimit > 0)
+ || (!(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && thumbLimit > 0)
+ || parent is Series)
{
+ parent ??= isFirst ? GetImageDisplayParent(item, item) ?? owner : parent;
if (parent == null)
{
break;
@@ -1303,9 +1331,10 @@ namespace Emby.Server.Implementations.Dto
if (image != null)
{
dto.ParentLogoItemId = GetDtoId(parent);
- dto.ParentLogoImageTag = GetImageCacheTag(parent, image);
+ dto.ParentLogoImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
+
if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
{
var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
@@ -1313,19 +1342,21 @@ namespace Emby.Server.Implementations.Dto
if (image != null)
{
dto.ParentArtItemId = GetDtoId(parent);
- dto.ParentArtImageTag = GetImageCacheTag(parent, image);
+ dto.ParentArtImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
- if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
+
+ if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && parent is not ICollectionFolder && parent is not UserView)
{
var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
if (image != null)
{
dto.ParentThumbItemId = GetDtoId(parent);
- dto.ParentThumbImageTag = GetImageCacheTag(parent, image);
+ dto.ParentThumbImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
+
if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
{
var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
@@ -1333,7 +1364,7 @@ namespace Emby.Server.Implementations.Dto
if (images.Count > 0)
{
dto.ParentBackdropItemId = GetDtoId(parent);
- dto.ParentBackdropImageTags = GetImageTags(parent, images);
+ dto.ParentBackdropImageTags = GetTagsAndFillBlurhashes(dto, parent, ImageType.Backdrop, images);
}
}
@@ -1365,7 +1396,6 @@ namespace Emby.Server.Implementations.Dto
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
- /// <returns>Task.</returns>
public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
{
dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
@@ -1380,56 +1410,33 @@ namespace Emby.Server.Implementations.Dto
return null;
}
- var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary);
-
ImageDimensions size;
var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
if (defaultAspectRatio > 0)
{
- if (supportedEnhancers.Length == 0)
- {
- return defaultAspectRatio;
- }
-
- int dummyWidth = 200;
- int dummyHeight = Convert.ToInt32(dummyWidth / defaultAspectRatio);
- size = new ImageDimensions(dummyWidth, dummyHeight);
+ return defaultAspectRatio;
}
- else
+
+ if (!imageInfo.IsLocalFile)
{
- if (!imageInfo.IsLocalFile)
- {
- return null;
- }
+ return null;
+ }
- try
- {
- size = _imageProcessor.GetImageDimensions(item, imageInfo);
+ try
+ {
+ size = _imageProcessor.GetImageDimensions(item, imageInfo);
- if (size.Width <= 0 || size.Height <= 0)
- {
- return null;
- }
- }
- catch (Exception ex)
+ if (size.Width <= 0 || size.Height <= 0)
{
- _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
return null;
}
}
-
- foreach (var enhancer in supportedEnhancers)
+ catch (Exception ex)
{
- try
- {
- size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name);
- }
+ _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
+ return null;
}
var width = size.Width;
@@ -1440,7 +1447,7 @@ namespace Emby.Server.Implementations.Dto
return null;
}
- return width / height;
+ return (double)width / height;
}
}
}
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index bbf165d62..c1ce4b557 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -1,34 +1,40 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{E383961B-9356-4D5D-8233-9A1079D03055}</ProjectGuid>
+ </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Emby.Naming\Emby.Naming.csproj" />
<ProjectReference Include="..\Emby.Notifications\Emby.Notifications.csproj" />
+ <ProjectReference Include="..\Jellyfin.Api\Jellyfin.Api.csproj" />
+ <ProjectReference Include="..\Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
- <ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
<ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
- <ProjectReference Include="..\SocketHttpListener\SocketHttpListener.csproj" />
<ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
- <ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
- <ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
<ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
- <ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
<ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
<ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
- <ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj" />
<ProjectReference Include="..\MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
- <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
- <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.2.0" />
- <PackageReference Include="ServiceStack.Text.Core" Version="5.4.0" />
- <PackageReference Include="sharpcompress" Version="0.22.0" />
- <PackageReference Include="SQLitePCL.pretty.netstandard" Version="1.0.0" />
- <PackageReference Include="UTF.Unknown" Version="1.0.0-beta1" />
+ <PackageReference Include="DiscUtils.Udf" Version="0.16.13" />
+ <PackageReference Include="Jellyfin.XmlTv" Version="10.6.2" />
+ <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Mono.Nat" Version="3.0.1" />
+ <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.2.2" />
+ <PackageReference Include="sharpcompress" Version="0.30.0" />
+ <PackageReference Include="SQLitePCL.pretty.netstandard" Version="3.1.0" />
+ <PackageReference Include="DotNet.Glob" Version="3.1.3" />
</ItemGroup>
<ItemGroup>
@@ -36,15 +42,24 @@
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <!-- https://github.com/microsoft/ApplicationInsights-dotnet/issues/2047 -->
+ <NoWarn>AD0001</NoWarn>
</PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
<ItemGroup>
<EmbeddedResource Include="Localization\iso6392.txt" />
<EmbeddedResource Include="Localization\countries.json" />
<EmbeddedResource Include="Localization\Core\*.json" />
<EmbeddedResource Include="Localization\Ratings\*.csv" />
</ItemGroup>
-
</Project>
diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs
deleted file mode 100644
index 19ea09359..000000000
--- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Tasks;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- public class AutomaticRestartEntryPoint : IServerEntryPoint
- {
- private readonly IServerApplicationHost _appHost;
- private readonly ILogger _logger;
- private readonly ITaskManager _iTaskManager;
- private readonly ISessionManager _sessionManager;
- private readonly IServerConfigurationManager _config;
- private readonly ILiveTvManager _liveTvManager;
-
- private Timer _timer;
-
- public AutomaticRestartEntryPoint(IServerApplicationHost appHost, ILogger logger, ITaskManager iTaskManager, ISessionManager sessionManager, IServerConfigurationManager config, ILiveTvManager liveTvManager)
- {
- _appHost = appHost;
- _logger = logger;
- _iTaskManager = iTaskManager;
- _sessionManager = sessionManager;
- _config = config;
- _liveTvManager = liveTvManager;
- }
-
- public Task RunAsync()
- {
- if (_appHost.CanSelfRestart)
- {
- _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
- }
-
- return Task.CompletedTask;
- }
-
- void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
- {
- DisposeTimer();
-
- if (_appHost.HasPendingRestart)
- {
- _timer = new Timer(TimerCallback, null, TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(15));
- }
- }
-
- private async void TimerCallback(object state)
- {
- if (_config.Configuration.EnableAutomaticRestart)
- {
- var isIdle = await IsIdle().ConfigureAwait(false);
-
- if (isIdle)
- {
- DisposeTimer();
-
- _logger.LogInformation("Automatically restarting the system because it is idle and a restart is required.");
-
- try
- {
- _appHost.Restart();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error restarting server");
- }
- }
- }
- }
-
- private async Task<bool> IsIdle()
- {
- if (_iTaskManager.ScheduledTasks.Any(i => i.State != TaskState.Idle))
- {
- return false;
- }
-
- if (_liveTvManager.Services.Count == 1)
- {
- try
- {
- var timers = await _liveTvManager.GetTimers(new TimerQuery(), CancellationToken.None).ConfigureAwait(false);
- if (timers.Items.Any(i => i.Status == RecordingStatus.InProgress))
- {
- return false;
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting timers");
- }
- }
-
- var now = DateTime.UtcNow;
-
- return !_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 30);
- }
-
- public void Dispose()
- {
- _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
-
- DisposeTimer();
- }
-
- private void DisposeTimer()
- {
- if (_timer != null)
- {
- _timer.Dispose();
- _timer = null;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index f26a70586..640754af4 100644
--- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -1,224 +1,137 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
-using System.Globalization;
using System.Net;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
+using Jellyfin.Networking.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Events;
using Microsoft.Extensions.Logging;
using Mono.Nat;
namespace Emby.Server.Implementations.EntryPoints
{
+ /// <summary>
+ /// Server entrypoint handling external port forwarding.
+ /// </summary>
public class ExternalPortForwarding : IServerEntryPoint
{
private readonly IServerApplicationHost _appHost;
- private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
+ private readonly ILogger<ExternalPortForwarding> _logger;
private readonly IServerConfigurationManager _config;
private readonly IDeviceDiscovery _deviceDiscovery;
+ private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>();
+
private Timer _timer;
+ private string _configIdentifier;
- private NatManager _natManager;
+ private bool _disposed = false;
- public ExternalPortForwarding(ILoggerFactory loggerFactory, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExternalPortForwarding"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="config">The configuration manager.</param>
+ /// <param name="deviceDiscovery">The device discovery.</param>
+ public ExternalPortForwarding(
+ ILogger<ExternalPortForwarding> logger,
+ IServerApplicationHost appHost,
+ IServerConfigurationManager config,
+ IDeviceDiscovery deviceDiscovery)
{
- _logger = loggerFactory.CreateLogger("PortMapper");
+ _logger = logger;
_appHost = appHost;
_config = config;
_deviceDiscovery = deviceDiscovery;
- _httpClient = httpClient;
- _config.ConfigurationUpdated += _config_ConfigurationUpdated1;
- }
-
- private void _config_ConfigurationUpdated1(object sender, EventArgs e)
- {
- _config_ConfigurationUpdated(sender, e);
}
- private string _lastConfigIdentifier;
private string GetConfigIdentifier()
{
- var values = new List<string>();
- var config = _config.Configuration;
-
- values.Add(config.EnableUPnP.ToString());
- values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture));
- values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture));
- values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture));
- values.Add(_appHost.EnableHttps.ToString());
- values.Add((config.EnableRemoteAccess).ToString());
-
- return string.Join("|", values.ToArray());
+ const char Separator = '|';
+ var config = _config.GetNetworkConfiguration();
+
+ return new StringBuilder(32)
+ .Append(config.EnableUPnP).Append(Separator)
+ .Append(config.PublicPort).Append(Separator)
+ .Append(config.PublicHttpsPort).Append(Separator)
+ .Append(_appHost.HttpPort).Append(Separator)
+ .Append(_appHost.HttpsPort).Append(Separator)
+ .Append(_appHost.ListenWithHttps).Append(Separator)
+ .Append(config.EnableRemoteAccess).Append(Separator)
+ .ToString();
}
- private async void _config_ConfigurationUpdated(object sender, EventArgs e)
+ private void OnConfigurationUpdated(object sender, EventArgs e)
{
- if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
- {
- DisposeNat();
+ var oldConfigIdentifier = _configIdentifier;
+ _configIdentifier = GetConfigIdentifier();
- await RunAsync();
+ if (!string.Equals(_configIdentifier, oldConfigIdentifier, StringComparison.OrdinalIgnoreCase))
+ {
+ Stop();
+ Start();
}
}
+ /// <inheritdoc />
public Task RunAsync()
{
- if (_config.Configuration.EnableUPnP && _config.Configuration.EnableRemoteAccess)
- {
- Start();
- }
+ Start();
- _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
- _config.ConfigurationUpdated += _config_ConfigurationUpdated;
+ _config.ConfigurationUpdated += OnConfigurationUpdated;
return Task.CompletedTask;
}
private void Start()
{
- _logger.LogDebug("Starting NAT discovery");
- if (_natManager == null)
+ var config = _config.GetNetworkConfiguration();
+ if (!config.EnableUPnP || !config.EnableRemoteAccess)
{
- _natManager = new NatManager(_logger, _httpClient);
- _natManager.DeviceFound += NatUtility_DeviceFound;
- _natManager.StartDiscovery();
+ return;
}
- _timer = new Timer(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
+ _logger.LogInformation("Starting NAT discovery");
- _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
+ NatUtility.DeviceFound += OnNatUtilityDeviceFound;
+ NatUtility.StartDiscovery();
- _lastConfigIdentifier = GetConfigIdentifier();
+ _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
}
- private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
+ private void Stop()
{
- if (_disposed)
- {
- return;
- }
+ _logger.LogInformation("Stopping NAT discovery");
- var info = e.Argument;
+ NatUtility.StopDiscovery();
+ NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
- if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty;
-
- if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty;
-
- // Filter device type
- if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
- nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
- usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
- nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
- {
- return;
- }
-
- var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
-
- if (info.Location == null)
- {
- return;
- }
-
- lock (_usnsHandled)
- {
- if (_usnsHandled.Contains(identifier))
- {
- return;
- }
- _usnsHandled.Add(identifier);
- }
-
- _logger.LogDebug("Found NAT device: " + identifier);
-
- if (IPAddress.TryParse(info.Location.Host, out var address))
- {
- // The Handle method doesn't need the port
- var endpoint = new IPEndPoint(address, info.Location.Port);
-
- IPAddress localAddress = null;
-
- try
- {
- var localAddressString = await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false);
-
- if (Uri.TryCreate(localAddressString, UriKind.Absolute, out var uri))
- {
- localAddressString = uri.Host;
-
- if (!IPAddress.TryParse(localAddressString, out localAddress))
- {
- return;
- }
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error");
- return;
- }
-
- if (_disposed)
- {
- return;
- }
-
- // This should never happen, but the Handle method will throw ArgumentNullException if it does
- if (localAddress == null)
- {
- return;
- }
-
- var natManager = _natManager;
- if (natManager != null)
- {
- await natManager.Handle(localAddress, info, endpoint, NatProtocol.Upnp).ConfigureAwait(false);
- }
- }
+ _timer?.Dispose();
}
- private void ClearCreatedRules(object state)
+ private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
{
- lock (_createdRules)
- {
- _createdRules.Clear();
- }
- lock (_usnsHandled)
- {
- _usnsHandled.Clear();
- }
- }
-
- void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
- {
- if (_disposed)
- {
- return;
- }
-
try
{
- var device = e.Device;
-
- CreateRules(device);
+ await CreateRules(e.Device).ConfigureAwait(false);
}
- catch
+ catch (Exception ex)
{
- // Commenting out because users are reporting problems out of our control
- //_logger.LogError(ex, "Error creating port forwarding rules");
+ _logger.LogError(ex, "Error creating port forwarding rules");
}
}
- private List<string> _createdRules = new List<string>();
- private List<string> _usnsHandled = new List<string>();
- private async void CreateRules(INatDevice device)
+ private Task CreateRules(INatDevice device)
{
if (_disposed)
{
@@ -227,90 +140,74 @@ namespace Emby.Server.Implementations.EntryPoints
// On some systems the device discovered event seems to fire repeatedly
// This check will help ensure we're not trying to port map the same device over and over
- var address = device.LocalAddress;
-
- var addressString = address.ToString();
-
- lock (_createdRules)
+ if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
{
- if (!_createdRules.Contains(addressString))
- {
- _createdRules.Add(addressString);
- }
- else
- {
- return;
- }
+ return Task.CompletedTask;
}
- try
- {
- await CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort).ConfigureAwait(false);
- }
- catch (Exception ex)
+ return Task.WhenAll(CreatePortMaps(device));
+ }
+
+ private IEnumerable<Task> CreatePortMaps(INatDevice device)
+ {
+ var config = _config.GetNetworkConfiguration();
+ yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort);
+
+ if (_appHost.ListenWithHttps)
{
- _logger.LogError(ex, "Error creating http port map");
- return;
+ yield return CreatePortMap(device, _appHost.HttpsPort, config.PublicHttpsPort);
}
+ }
+
+ private async Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
+ {
+ _logger.LogDebug(
+ "Creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}",
+ privatePort,
+ publicPort,
+ device.DeviceEndpoint);
try
{
- await CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort).ConfigureAwait(false);
+ var mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name);
+ await device.CreatePortMapAsync(mapping).ConfigureAwait(false);
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error creating https port map");
+ _logger.LogError(
+ ex,
+ "Error creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}.",
+ privatePort,
+ publicPort,
+ device.DeviceEndpoint);
}
}
- private Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
- {
- _logger.LogDebug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString());
-
- return device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
- {
- Description = _appHost.Name
- });
- }
-
- private bool _disposed = false;
+ /// <inheritdoc />
public void Dispose()
{
- _disposed = true;
- DisposeNat();
+ Dispose(true);
+ GC.SuppressFinalize(this);
}
- private void DisposeNat()
+ /// <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)
{
- _logger.LogDebug("Stopping NAT discovery");
-
- if (_timer != null)
+ if (_disposed)
{
- _timer.Dispose();
- _timer = null;
+ return;
}
- _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
+ _config.ConfigurationUpdated -= OnConfigurationUpdated;
- var natManager = _natManager;
+ Stop();
- if (natManager != null)
- {
- _natManager = null;
-
- using (natManager)
- {
- try
- {
- natManager.StopDiscovery();
- natManager.DeviceFound -= NatUtility_DeviceFound;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error stopping NAT Discovery");
- }
- }
- }
+ _timer = null;
+
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
index 038965647..331de45c1 100644
--- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
@@ -1,9 +1,16 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
@@ -12,8 +19,7 @@ using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Extensions;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
@@ -21,40 +27,34 @@ namespace Emby.Server.Implementations.EntryPoints
public class LibraryChangedNotifier : IServerEntryPoint
{
/// <summary>
- /// The _library manager
+ /// The library update duration.
/// </summary>
- private readonly ILibraryManager _libraryManager;
+ private const int LibraryUpdateDuration = 30000;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IProviderManager _providerManager;
private readonly ISessionManager _sessionManager;
private readonly IUserManager _userManager;
- private readonly ILogger _logger;
+ private readonly ILogger<LibraryChangedNotifier> _logger;
/// <summary>
- /// The _library changed sync lock
+ /// The library changed sync lock.
/// </summary>
private readonly object _libraryChangedSyncLock = new object();
private readonly List<Folder> _foldersAddedTo = new List<Folder>();
private readonly List<Folder> _foldersRemovedFrom = new List<Folder>();
-
private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
private readonly List<BaseItem> _itemsRemoved = new List<BaseItem>();
private readonly List<BaseItem> _itemsUpdated = new List<BaseItem>();
-
- /// <summary>
- /// Gets or sets the library update timer.
- /// </summary>
- /// <value>The library update timer.</value>
- private Timer LibraryUpdateTimer { get; set; }
-
- /// <summary>
- /// The library update duration
- /// </summary>
- private const int LibraryUpdateDuration = 30000;
-
- private readonly IProviderManager _providerManager;
-
- public LibraryChangedNotifier(ILibraryManager libraryManager, ISessionManager sessionManager, IUserManager userManager, ILogger logger, IProviderManager providerManager)
+ private readonly ConcurrentDictionary<Guid, DateTime> _lastProgressMessageTimes = new ConcurrentDictionary<Guid, DateTime>();
+
+ public LibraryChangedNotifier(
+ ILibraryManager libraryManager,
+ ISessionManager sessionManager,
+ IUserManager userManager,
+ ILogger<LibraryChangedNotifier> logger,
+ IProviderManager providerManager)
{
_libraryManager = libraryManager;
_sessionManager = sessionManager;
@@ -63,22 +63,26 @@ namespace Emby.Server.Implementations.EntryPoints
_providerManager = providerManager;
}
+ /// <summary>
+ /// Gets or sets the library update timer.
+ /// </summary>
+ /// <value>The library update timer.</value>
+ private Timer LibraryUpdateTimer { get; set; }
+
public Task RunAsync()
{
- _libraryManager.ItemAdded += libraryManager_ItemAdded;
- _libraryManager.ItemUpdated += libraryManager_ItemUpdated;
- _libraryManager.ItemRemoved += libraryManager_ItemRemoved;
+ _libraryManager.ItemAdded += OnLibraryItemAdded;
+ _libraryManager.ItemUpdated += OnLibraryItemUpdated;
+ _libraryManager.ItemRemoved += OnLibraryItemRemoved;
- _providerManager.RefreshCompleted += _providerManager_RefreshCompleted;
- _providerManager.RefreshStarted += _providerManager_RefreshStarted;
- _providerManager.RefreshProgress += _providerManager_RefreshProgress;
+ _providerManager.RefreshCompleted += OnProviderRefreshCompleted;
+ _providerManager.RefreshStarted += OnProviderRefreshStarted;
+ _providerManager.RefreshProgress += OnProviderRefreshProgress;
return Task.CompletedTask;
}
- private Dictionary<Guid, DateTime> _lastProgressMessageTimes = new Dictionary<Guid, DateTime>();
-
- private void _providerManager_RefreshProgress(object sender, GenericEventArgs<Tuple<BaseItem, double>> e)
+ private void OnProviderRefreshProgress(object sender, GenericEventArgs<Tuple<BaseItem, double>> e)
{
var item = e.Argument.Item1;
@@ -97,15 +101,15 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
- _lastProgressMessageTimes[item.Id] = DateTime.UtcNow;
+ _lastProgressMessageTimes.AddOrUpdate(item.Id, key => DateTime.UtcNow, (key, existing) => DateTime.UtcNow);
var dict = new Dictionary<string, string>();
- dict["ItemId"] = item.Id.ToString("N");
+ dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture);
dict["Progress"] = progress.ToString(CultureInfo.InvariantCulture);
try
{
- _sessionManager.SendMessageToAdminSessions("RefreshProgress", dict, CancellationToken.None);
+ _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, dict, CancellationToken.None);
}
catch
{
@@ -115,36 +119,37 @@ namespace Emby.Server.Implementations.EntryPoints
foreach (var collectionFolder in collectionFolders)
{
- var collectionFolderDict = new Dictionary<string, string>();
- collectionFolderDict["ItemId"] = collectionFolder.Id.ToString("N");
- collectionFolderDict["Progress"] = (collectionFolder.GetRefreshProgress() ?? 0).ToString(CultureInfo.InvariantCulture);
+ var collectionFolderDict = new Dictionary<string, string>
+ {
+ ["ItemId"] = collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture),
+ ["Progress"] = (collectionFolder.GetRefreshProgress() ?? 0).ToString(CultureInfo.InvariantCulture)
+ };
try
{
- _sessionManager.SendMessageToAdminSessions("RefreshProgress", collectionFolderDict, CancellationToken.None);
+ _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, collectionFolderDict, CancellationToken.None);
}
catch
{
-
}
}
}
- private void _providerManager_RefreshStarted(object sender, GenericEventArgs<BaseItem> e)
+ private void OnProviderRefreshStarted(object sender, GenericEventArgs<BaseItem> e)
{
- _providerManager_RefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 0)));
+ OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 0)));
}
- private void _providerManager_RefreshCompleted(object sender, GenericEventArgs<BaseItem> e)
+ private void OnProviderRefreshCompleted(object sender, GenericEventArgs<BaseItem> e)
{
- _providerManager_RefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 100)));
+ OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 100)));
+
+ _lastProgressMessageTimes.TryRemove(e.Argument.Id, out DateTime removed);
}
private static bool EnableRefreshMessage(BaseItem item)
{
- var folder = item as Folder;
-
- if (folder == null)
+ if (item is not Folder folder)
{
return false;
}
@@ -177,7 +182,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
- void libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
+ private void OnLibraryItemAdded(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
@@ -188,16 +193,18 @@ namespace Emby.Server.Implementations.EntryPoints
{
if (LibraryUpdateTimer == null)
{
- LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration,
- Timeout.Infinite);
+ LibraryUpdateTimer = new Timer(
+ LibraryUpdateTimerCallback,
+ null,
+ LibraryUpdateDuration,
+ Timeout.Infinite);
}
else
{
LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite);
}
- var parent = e.Item.GetParent() as Folder;
- if (parent != null)
+ if (e.Item.GetParent() is Folder parent)
{
_foldersAddedTo.Add(parent);
}
@@ -211,7 +218,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
- void libraryManager_ItemUpdated(object sender, ItemChangeEventArgs e)
+ private void OnLibraryItemUpdated(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
@@ -222,8 +229,7 @@ namespace Emby.Server.Implementations.EntryPoints
{
if (LibraryUpdateTimer == null)
{
- LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration,
- Timeout.Infinite);
+ LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration, Timeout.Infinite);
}
else
{
@@ -239,7 +245,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
- void libraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
+ private void OnLibraryItemRemoved(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
@@ -250,16 +256,14 @@ namespace Emby.Server.Implementations.EntryPoints
{
if (LibraryUpdateTimer == null)
{
- LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration,
- Timeout.Infinite);
+ LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration, Timeout.Infinite);
}
else
{
LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite);
}
- var parent = e.Parent as Folder;
- if (parent != null)
+ if (e.Parent is Folder parent)
{
_foldersRemovedFrom.Add(parent);
}
@@ -293,7 +297,7 @@ namespace Emby.Server.Implementations.EntryPoints
.Select(x => x.First())
.ToList();
- SendChangeNotifications(_itemsAdded.ToList(), itemsUpdated, _itemsRemoved.ToList(), foldersAddedTo, foldersRemovedFrom, CancellationToken.None);
+ SendChangeNotifications(_itemsAdded.ToList(), itemsUpdated, _itemsRemoved.ToList(), foldersAddedTo, foldersRemovedFrom, CancellationToken.None).GetAwaiter().GetResult();
if (LibraryUpdateTimer != null)
{
@@ -318,7 +322,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// <param name="foldersAddedTo">The folders added to.</param>
/// <param name="foldersRemovedFrom">The folders removed from.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- private async void SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, CancellationToken cancellationToken)
+ private async Task SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, CancellationToken cancellationToken)
{
var userIds = _sessionManager.Sessions
.Select(i => i.UserId)
@@ -347,7 +351,7 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- await _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, "LibraryChanged", info, cancellationToken).ConfigureAwait(false);
+ await _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, SessionMessageType.LibraryChanged, info, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -378,17 +382,17 @@ namespace Emby.Server.Implementations.EntryPoints
return new LibraryUpdateInfo
{
- ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- CollectionFolders = GetTopParentIds(newAndRemoved, user, allUserRootChildren).ToArray()
+ CollectionFolders = GetTopParentIds(newAndRemoved, allUserRootChildren).ToArray()
};
}
@@ -399,7 +403,7 @@ namespace Emby.Server.Implementations.EntryPoints
return false;
}
- if (item is IItemByName && !(item is MusicArtist))
+ if (item is IItemByName && item is not MusicArtist)
{
return false;
}
@@ -407,7 +411,7 @@ namespace Emby.Server.Implementations.EntryPoints
return item.SourceType == SourceType.Library;
}
- private IEnumerable<string> GetTopParentIds(List<BaseItem> items, User user, List<Folder> allUserRootChildren)
+ private IEnumerable<string> GetTopParentIds(List<BaseItem> items, List<Folder> allUserRootChildren)
{
var list = new List<string>();
@@ -422,7 +426,7 @@ namespace Emby.Server.Implementations.EntryPoints
var collectionFolders = _libraryManager.GetCollectionFolders(item, allUserRootChildren);
foreach (var folder in allUserRootChildren)
{
- list.Add(folder.Id.ToString("N"));
+ list.Add(folder.Id.ToString("N", CultureInfo.InvariantCulture));
}
}
@@ -432,7 +436,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// <summary>
/// Translates the physical item to user library.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of item.</typeparam>
/// <param name="item">The item.</param>
/// <param name="user">The user.</param>
/// <param name="includeIfNotFound">if set to <c>true</c> [include if not found].</param>
@@ -452,7 +456,7 @@ namespace Emby.Server.Implementations.EntryPoints
return new[] { item };
}
- return new T[] { };
+ return Array.Empty<T>();
}
/// <summary>
@@ -477,13 +481,13 @@ namespace Emby.Server.Implementations.EntryPoints
LibraryUpdateTimer = null;
}
- _libraryManager.ItemAdded -= libraryManager_ItemAdded;
- _libraryManager.ItemUpdated -= libraryManager_ItemUpdated;
- _libraryManager.ItemRemoved -= libraryManager_ItemRemoved;
+ _libraryManager.ItemAdded -= OnLibraryItemAdded;
+ _libraryManager.ItemUpdated -= OnLibraryItemUpdated;
+ _libraryManager.ItemRemoved -= OnLibraryItemRemoved;
- _providerManager.RefreshCompleted -= _providerManager_RefreshCompleted;
- _providerManager.RefreshStarted -= _providerManager_RefreshStarted;
- _providerManager.RefreshProgress -= _providerManager_RefreshProgress;
+ _providerManager.RefreshCompleted -= OnProviderRefreshCompleted;
+ _providerManager.RefreshStarted -= OnProviderRefreshStarted;
+ _providerManager.RefreshProgress -= OnProviderRefreshProgress;
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
index 0186da9e1..e0ca02d98 100644
--- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
@@ -1,23 +1,34 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
- public class RecordingNotifier : IServerEntryPoint
+ public sealed class RecordingNotifier : IServerEntryPoint
{
private readonly ILiveTvManager _liveTvManager;
private readonly ISessionManager _sessionManager;
private readonly IUserManager _userManager;
- private readonly ILogger _logger;
+ private readonly ILogger<RecordingNotifier> _logger;
- public RecordingNotifier(ISessionManager sessionManager, IUserManager userManager, ILogger logger, ILiveTvManager liveTvManager)
+ public RecordingNotifier(
+ ISessionManager sessionManager,
+ IUserManager userManager,
+ ILogger<RecordingNotifier> logger,
+ ILiveTvManager liveTvManager)
{
_sessionManager = sessionManager;
_userManager = userManager;
@@ -25,47 +36,44 @@ namespace Emby.Server.Implementations.EntryPoints
_liveTvManager = liveTvManager;
}
+ /// <inheritdoc />
public Task RunAsync()
{
- _liveTvManager.TimerCancelled += _liveTvManager_TimerCancelled;
- _liveTvManager.SeriesTimerCancelled += _liveTvManager_SeriesTimerCancelled;
- _liveTvManager.TimerCreated += _liveTvManager_TimerCreated;
- _liveTvManager.SeriesTimerCreated += _liveTvManager_SeriesTimerCreated;
+ _liveTvManager.TimerCancelled += OnLiveTvManagerTimerCancelled;
+ _liveTvManager.SeriesTimerCancelled += OnLiveTvManagerSeriesTimerCancelled;
+ _liveTvManager.TimerCreated += OnLiveTvManagerTimerCreated;
+ _liveTvManager.SeriesTimerCreated += OnLiveTvManagerSeriesTimerCreated;
return Task.CompletedTask;
}
- private void _liveTvManager_SeriesTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
+ private async void OnLiveTvManagerSeriesTimerCreated(object sender, GenericEventArgs<TimerEventInfo> e)
{
- SendMessage("SeriesTimerCreated", e.Argument);
+ await SendMessage(SessionMessageType.SeriesTimerCreated, e.Argument).ConfigureAwait(false);
}
- private void _liveTvManager_TimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
+ private async void OnLiveTvManagerTimerCreated(object sender, GenericEventArgs<TimerEventInfo> e)
{
- SendMessage("TimerCreated", e.Argument);
+ await SendMessage(SessionMessageType.TimerCreated, e.Argument).ConfigureAwait(false);
}
- private void _liveTvManager_SeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
+ private async void OnLiveTvManagerSeriesTimerCancelled(object sender, GenericEventArgs<TimerEventInfo> e)
{
- SendMessage("SeriesTimerCancelled", e.Argument);
+ await SendMessage(SessionMessageType.SeriesTimerCancelled, e.Argument).ConfigureAwait(false);
}
- private void _liveTvManager_TimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
+ private async void OnLiveTvManagerTimerCancelled(object sender, GenericEventArgs<TimerEventInfo> e)
{
- SendMessage("TimerCancelled", e.Argument);
+ await SendMessage(SessionMessageType.TimerCancelled, e.Argument).ConfigureAwait(false);
}
- private async void SendMessage(string name, TimerEventInfo info)
+ private async Task SendMessage(SessionMessageType name, TimerEventInfo info)
{
- var users = _userManager.Users.Where(i => i.Policy.EnableLiveTvAccess).Select(i => i.Id).ToList();
+ var users = _userManager.Users.Where(i => i.HasPermission(PermissionKind.EnableLiveTvAccess)).Select(i => i.Id).ToList();
try
{
- await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None);
- }
- catch (ObjectDisposedException)
- {
- // TODO Log exception or Investigate and properly fix.
+ await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -73,12 +81,13 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
+ /// <inheritdoc />
public void Dispose()
{
- _liveTvManager.TimerCancelled -= _liveTvManager_TimerCancelled;
- _liveTvManager.SeriesTimerCancelled -= _liveTvManager_SeriesTimerCancelled;
- _liveTvManager.TimerCreated -= _liveTvManager_TimerCreated;
- _liveTvManager.SeriesTimerCreated -= _liveTvManager_SeriesTimerCreated;
+ _liveTvManager.TimerCancelled -= OnLiveTvManagerTimerCancelled;
+ _liveTvManager.SeriesTimerCancelled -= OnLiveTvManagerSeriesTimerCancelled;
+ _liveTvManager.TimerCreated -= OnLiveTvManagerTimerCreated;
+ _liveTvManager.SeriesTimerCreated -= OnLiveTvManagerSeriesTimerCreated;
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
deleted file mode 100644
index b7565adec..000000000
--- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Tasks;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- /// <summary>
- /// Class RefreshUsersMetadata
- /// </summary>
- public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask
- {
- private readonly ILogger _logger;
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- private IFileSystem _fileSystem;
-
- public string Name => "Refresh Users";
-
- public string Key => "RefreshUsers";
-
- public string Description => "Refresh user infos";
-
- public string Category => "Library";
-
- public bool IsHidden => true;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="RefreshUsersMetadata" /> class.
- /// </summary>
- public RefreshUsersMetadata(ILogger logger, IUserManager userManager, IFileSystem fileSystem)
- {
- _logger = logger;
- _userManager = userManager;
- _fileSystem = fileSystem;
- }
-
- public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
- {
- var users = _userManager.Users.ToList();
-
- foreach (var user in users)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
- }
- }
-
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
- {
- return new List<TaskTriggerInfo>
- {
- new TaskTriggerInfo
- {
- IntervalTicks = TimeSpan.FromDays(1).Ticks,
- Type = TaskTriggerInfo.TriggerInterval
- }
- };
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
deleted file mode 100644
index 091dd6a45..000000000
--- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
+++ /dev/null
@@ -1,209 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Tasks;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- /// <summary>
- /// Class WebSocketEvents
- /// </summary>
- public class ServerEventNotifier : IServerEntryPoint
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- /// <summary>
- /// The _installation manager
- /// </summary>
- private readonly IInstallationManager _installationManager;
-
- /// <summary>
- /// The _kernel
- /// </summary>
- private readonly IServerApplicationHost _appHost;
-
- /// <summary>
- /// The _task manager
- /// </summary>
- private readonly ITaskManager _taskManager;
-
- private readonly ISessionManager _sessionManager;
-
- public ServerEventNotifier(IServerApplicationHost appHost, IUserManager userManager, IInstallationManager installationManager, ITaskManager taskManager, ISessionManager sessionManager)
- {
- _userManager = userManager;
- _installationManager = installationManager;
- _appHost = appHost;
- _taskManager = taskManager;
- _sessionManager = sessionManager;
- }
-
- public Task RunAsync()
- {
- _userManager.UserDeleted += userManager_UserDeleted;
- _userManager.UserUpdated += userManager_UserUpdated;
- _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
- _userManager.UserConfigurationUpdated += _userManager_UserConfigurationUpdated;
-
- _appHost.HasPendingRestartChanged += kernel_HasPendingRestartChanged;
-
- _installationManager.PluginUninstalled += InstallationManager_PluginUninstalled;
- _installationManager.PackageInstalling += _installationManager_PackageInstalling;
- _installationManager.PackageInstallationCancelled += _installationManager_PackageInstallationCancelled;
- _installationManager.PackageInstallationCompleted += _installationManager_PackageInstallationCompleted;
- _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
-
- _taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
- return Task.CompletedTask;
- }
-
- void _installationManager_PackageInstalling(object sender, InstallationEventArgs e)
- {
- SendMessageToAdminSessions("PackageInstalling", e.InstallationInfo);
- }
-
- void _installationManager_PackageInstallationCancelled(object sender, InstallationEventArgs e)
- {
- SendMessageToAdminSessions("PackageInstallationCancelled", e.InstallationInfo);
- }
-
- void _installationManager_PackageInstallationCompleted(object sender, InstallationEventArgs e)
- {
- SendMessageToAdminSessions("PackageInstallationCompleted", e.InstallationInfo);
- }
-
- void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
- {
- SendMessageToAdminSessions("PackageInstallationFailed", e.InstallationInfo);
- }
-
- void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- SendMessageToAdminSessions("ScheduledTaskEnded", e.Result);
- }
-
- /// <summary>
- /// Installations the manager_ plugin uninstalled.
- /// </summary>
- /// <param name="sender">The sender.</param>
- /// <param name="e">The e.</param>
- void InstallationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
- {
- SendMessageToAdminSessions("PluginUninstalled", e.Argument.GetPluginInfo());
- }
-
- /// <summary>
- /// Handles the HasPendingRestartChanged event of the kernel control.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
- void kernel_HasPendingRestartChanged(object sender, EventArgs e)
- {
- _sessionManager.SendRestartRequiredNotification(CancellationToken.None);
- }
-
- /// <summary>
- /// Users the manager_ user updated.
- /// </summary>
- /// <param name="sender">The sender.</param>
- /// <param name="e">The e.</param>
- void userManager_UserUpdated(object sender, GenericEventArgs<User> e)
- {
- var dto = _userManager.GetUserDto(e.Argument);
-
- SendMessageToUserSession(e.Argument, "UserUpdated", dto);
- }
-
- /// <summary>
- /// Users the manager_ user deleted.
- /// </summary>
- /// <param name="sender">The sender.</param>
- /// <param name="e">The e.</param>
- void userManager_UserDeleted(object sender, GenericEventArgs<User> e)
- {
- SendMessageToUserSession(e.Argument, "UserDeleted", e.Argument.Id.ToString("N"));
- }
-
- void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
- {
- var dto = _userManager.GetUserDto(e.Argument);
-
- SendMessageToUserSession(e.Argument, "UserPolicyUpdated", dto);
- }
-
- void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
- {
- var dto = _userManager.GetUserDto(e.Argument);
-
- SendMessageToUserSession(e.Argument, "UserConfigurationUpdated", dto);
- }
-
- private async void SendMessageToAdminSessions<T>(string name, T data)
- {
- try
- {
- await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None);
- }
- catch (Exception)
- {
-
- }
- }
-
- private async void SendMessageToUserSession<T>(User user, string name, T data)
- {
- try
- {
- await _sessionManager.SendMessageToUserSessions(new List<Guid> { user.Id }, name, data, CancellationToken.None);
- }
- catch (Exception)
- {
-
- }
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- }
-
- /// <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)
- {
- _userManager.UserDeleted -= userManager_UserDeleted;
- _userManager.UserUpdated -= userManager_UserUpdated;
- _userManager.UserPolicyUpdated -= _userManager_UserPolicyUpdated;
- _userManager.UserConfigurationUpdated -= _userManager_UserConfigurationUpdated;
-
- _installationManager.PluginUninstalled -= InstallationManager_PluginUninstalled;
- _installationManager.PackageInstalling -= _installationManager_PackageInstalling;
- _installationManager.PackageInstallationCancelled -= _installationManager_PackageInstallationCancelled;
- _installationManager.PackageInstallationCompleted -= _installationManager_PackageInstallationCompleted;
- _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
-
- _appHost.HasPendingRestartChanged -= kernel_HasPendingRestartChanged;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
deleted file mode 100644
index 8be6db87d..000000000
--- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Browser;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Plugins;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- /// <summary>
- /// Class StartupWizard
- /// </summary>
- public class StartupWizard : IServerEntryPoint
- {
- /// <summary>
- /// The _app host
- /// </summary>
- private readonly IServerApplicationHost _appHost;
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly ILogger _logger;
-
- private IServerConfigurationManager _config;
-
- public StartupWizard(IServerApplicationHost appHost, ILogger logger, IServerConfigurationManager config)
- {
- _appHost = appHost;
- _logger = logger;
- _config = config;
- }
-
- /// <summary>
- /// Runs this instance.
- /// </summary>
- public Task RunAsync()
- {
- if (!_appHost.CanLaunchWebBrowser)
- {
- return Task.CompletedTask;
- }
-
- if (!_config.Configuration.IsStartupWizardCompleted)
- {
- BrowserLauncher.OpenWebApp(_appHost);
- }
- else if (_config.Configuration.AutoRunWebApp)
- {
- var options = ((ApplicationHost)_appHost).StartupOptions;
-
- if (!options.NoAutoRunWebApp)
- {
- BrowserLauncher.OpenWebApp(_appHost);
- }
- }
-
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
index 5b90dc1fb..feaccf9fa 100644
--- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
+++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
@@ -1,88 +1,95 @@
using System;
+using System.Net.Sockets;
+using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Udp;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
/// <summary>
- /// Class UdpServerEntryPoint
+ /// Class UdpServerEntryPoint.
/// </summary>
- public class UdpServerEntryPoint : IServerEntryPoint
+ public sealed class UdpServerEntryPoint : IServerEntryPoint
{
/// <summary>
- /// Gets or sets the UDP server.
+ /// The port of the UDP server.
/// </summary>
- /// <value>The UDP server.</value>
- private UdpServer UdpServer { get; set; }
+ public const int PortNumber = 7359;
/// <summary>
- /// The _logger
+ /// The logger.
/// </summary>
- private readonly ILogger _logger;
- private readonly ISocketFactory _socketFactory;
+ private readonly ILogger<UdpServerEntryPoint> _logger;
private readonly IServerApplicationHost _appHost;
- private readonly IJsonSerializer _json;
+ private readonly IConfiguration _config;
- public const int PortNumber = 7359;
+ /// <summary>
+ /// The UDP server.
+ /// </summary>
+ private UdpServer? _udpServer;
+ private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
+ private bool _disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="UdpServerEntryPoint" /> class.
/// </summary>
- public UdpServerEntryPoint(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory)
+ /// <param name="logger">Instance of the <see cref="ILogger{UdpServerEntryPoint}"/> interface.</param>
+ /// <param name="appHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
+ /// <param name="configuration">Instance of the <see cref="IConfiguration"/> interface.</param>
+ public UdpServerEntryPoint(
+ ILogger<UdpServerEntryPoint> logger,
+ IServerApplicationHost appHost,
+ IConfiguration configuration)
{
_logger = logger;
_appHost = appHost;
- _json = json;
- _socketFactory = socketFactory;
+ _config = configuration;
}
- /// <summary>
- /// Runs this instance.
- /// </summary>
+ /// <inheritdoc />
public Task RunAsync()
{
- var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory);
+ CheckDisposed();
try
{
- udpServer.Start(PortNumber);
-
- UdpServer = udpServer;
+ _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
+ _udpServer.Start(_cancellationTokenSource.Token);
}
- catch (Exception ex)
+ catch (SocketException ex)
{
- _logger.LogError(ex, "Failed to start UDP Server");
+ _logger.LogWarning(ex, "Unable to start AutoDiscovery listener on UDP port {PortNumber}", PortNumber);
}
return Task.CompletedTask;
}
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
+ private void CheckDisposed()
{
- Dispose(true);
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(this.GetType().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)
+ /// <inheritdoc />
+ public void Dispose()
{
- if (dispose)
+ if (_disposed)
{
- if (UdpServer != null)
- {
- UdpServer.Dispose();
- }
+ return;
}
+
+ _cancellationTokenSource.Cancel();
+ _cancellationTokenSource.Dispose();
+ _udpServer?.Dispose();
+ _udpServer = null;
+
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index a5badacee..d3bcd5e13 100644
--- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -1,5 +1,8 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -8,41 +11,38 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Session;
-using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
- public class UserDataChangeNotifier : IServerEntryPoint
+ public sealed class UserDataChangeNotifier : IServerEntryPoint
{
+ private const int UpdateDuration = 500;
+
private readonly ISessionManager _sessionManager;
- private readonly ILogger _logger;
private readonly IUserDataManager _userDataManager;
private readonly IUserManager _userManager;
- private readonly object _syncLock = new object();
- private Timer UpdateTimer { get; set; }
- private const int UpdateDuration = 500;
-
private readonly Dictionary<Guid, List<BaseItem>> _changedItems = new Dictionary<Guid, List<BaseItem>>();
- public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, ILogger logger, IUserManager userManager)
+ private readonly object _syncLock = new object();
+ private Timer? _updateTimer;
+
+ public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager)
{
_userDataManager = userDataManager;
_sessionManager = sessionManager;
- _logger = logger;
_userManager = userManager;
}
public Task RunAsync()
{
- _userDataManager.UserDataSaved += _userDataManager_UserDataSaved;
+ _userDataManager.UserDataSaved += OnUserDataManagerUserDataSaved;
return Task.CompletedTask;
}
- void _userDataManager_UserDataSaved(object sender, UserDataSaveEventArgs e)
+ private void OnUserDataManagerUserDataSaved(object? sender, UserDataSaveEventArgs e)
{
if (e.SaveReason == UserDataSaveReason.PlaybackProgress)
{
@@ -51,17 +51,20 @@ namespace Emby.Server.Implementations.EntryPoints
lock (_syncLock)
{
- if (UpdateTimer == null)
+ if (_updateTimer == null)
{
- UpdateTimer = new Timer(UpdateTimerCallback, null, UpdateDuration,
- Timeout.Infinite);
+ _updateTimer = new Timer(
+ UpdateTimerCallback,
+ null,
+ UpdateDuration,
+ Timeout.Infinite);
}
else
{
- UpdateTimer.Change(UpdateDuration, Timeout.Infinite);
+ _updateTimer.Change(UpdateDuration, Timeout.Infinite);
}
- if (!_changedItems.TryGetValue(e.UserId, out List<BaseItem> keys))
+ if (!_changedItems.TryGetValue(e.UserId, out List<BaseItem>? keys))
{
keys = new List<BaseItem>();
_changedItems[e.UserId] = keys;
@@ -84,7 +87,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
- private void UpdateTimerCallback(object state)
+ private void UpdateTimerCallback(object? state)
{
lock (_syncLock)
{
@@ -94,10 +97,10 @@ namespace Emby.Server.Implementations.EntryPoints
var task = SendNotifications(changes, CancellationToken.None);
- if (UpdateTimer != null)
+ if (_updateTimer != null)
{
- UpdateTimer.Dispose();
- UpdateTimer = null;
+ _updateTimer.Dispose();
+ _updateTimer = null;
}
}
}
@@ -112,7 +115,7 @@ namespace Emby.Server.Implementations.EntryPoints
private Task SendNotifications(Guid userId, List<BaseItem> changedItems, CancellationToken cancellationToken)
{
- return _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, "UserDataChanged", () => GetUserDataChangeInfo(userId, changedItems), cancellationToken);
+ return _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, SessionMessageType.UserDataChanged, () => GetUserDataChangeInfo(userId, changedItems), cancellationToken);
}
private UserDataChangeInfo GetUserDataChangeInfo(Guid userId, List<BaseItem> changedItems)
@@ -125,12 +128,12 @@ namespace Emby.Server.Implementations.EntryPoints
.Select(i =>
{
var dto = _userDataManager.GetUserDataDto(i, user);
- dto.ItemId = i.Id.ToString("N");
+ dto.ItemId = i.Id.ToString("N", CultureInfo.InvariantCulture);
return dto;
})
.ToArray();
- var userIdString = userId.ToString("N");
+ var userIdString = userId.ToString("N", CultureInfo.InvariantCulture);
return new UserDataChangeInfo
{
@@ -142,13 +145,13 @@ namespace Emby.Server.Implementations.EntryPoints
public void Dispose()
{
- if (UpdateTimer != null)
+ if (_updateTimer != null)
{
- UpdateTimer.Dispose();
- UpdateTimer = null;
+ _updateTimer.Dispose();
+ _updateTimer = null;
}
- _userDataManager.UserDataSaved -= _userDataManager_UserDataSaved;
+ _userDataManager.UserDataSaved -= OnUserDataManagerUserDataSaved;
}
}
}
diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
deleted file mode 100644
index c8104150d..000000000
--- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using MediaBrowser.Model.System;
-
-namespace Emby.Server.Implementations.EnvironmentInfo
-{
- public class EnvironmentInfo : IEnvironmentInfo
- {
- public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem)
- {
- OperatingSystem = operatingSystem;
- }
-
- public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; }
-
- public string OperatingSystemName
- {
- get
- {
- switch (OperatingSystem)
- {
- case MediaBrowser.Model.System.OperatingSystem.Android: return "Android";
- case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD";
- case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux";
- case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS";
- case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows";
- default: throw new Exception($"Unknown OS {OperatingSystem}");
- }
- }
- }
-
- public string OperatingSystemVersion => Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString();
-
- public Architecture SystemArchitecture => RuntimeInformation.OSArchitecture;
- }
-}
diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs b/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs
deleted file mode 100644
index 60cd7b3d7..000000000
--- a/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Emby.Server.Implementations.FFMpeg
-{
- /// <summary>
- /// Class FFMpegInfo
- /// </summary>
- public class FFMpegInfo
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- public string EncoderPath { get; set; }
- /// <summary>
- /// Gets or sets the probe path.
- /// </summary>
- /// <value>The probe path.</value>
- public string ProbePath { get; set; }
- /// <summary>
- /// Gets or sets the version.
- /// </summary>
- /// <value>The version.</value>
- public string Version { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs b/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs
deleted file mode 100644
index fa9cb5e01..000000000
--- a/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace Emby.Server.Implementations.FFMpeg
-{
- public class FFMpegInstallInfo
- {
- public string Version { get; set; }
- public string FFMpegFilename { get; set; }
- public string FFProbeFilename { get; set; }
- public string ArchiveType { get; set; }
-
- public FFMpegInstallInfo()
- {
- Version = "Path";
- FFMpegFilename = "ffmpeg";
- FFProbeFilename = "ffprobe";
- }
- }
-}
diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
deleted file mode 100644
index bbf51dd24..000000000
--- a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
+++ /dev/null
@@ -1,132 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Server.Implementations.FFMpeg
-{
- public class FFMpegLoader
- {
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
- private readonly FFMpegInstallInfo _ffmpegInstallInfo;
-
- public FFMpegLoader(IApplicationPaths appPaths, IFileSystem fileSystem, FFMpegInstallInfo ffmpegInstallInfo)
- {
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- _ffmpegInstallInfo = ffmpegInstallInfo;
- }
-
- public FFMpegInfo GetFFMpegInfo(IStartupOptions options)
- {
- var customffMpegPath = options.FFmpegPath;
- var customffProbePath = options.FFprobePath;
-
- if (!string.IsNullOrWhiteSpace(customffMpegPath) && !string.IsNullOrWhiteSpace(customffProbePath))
- {
- return new FFMpegInfo
- {
- ProbePath = customffProbePath,
- EncoderPath = customffMpegPath,
- Version = "external"
- };
- }
-
- var downloadInfo = _ffmpegInstallInfo;
-
- var prebuiltFolder = _appPaths.ProgramSystemPath;
- var prebuiltffmpeg = Path.Combine(prebuiltFolder, downloadInfo.FFMpegFilename);
- var prebuiltffprobe = Path.Combine(prebuiltFolder, downloadInfo.FFProbeFilename);
- if (File.Exists(prebuiltffmpeg) && File.Exists(prebuiltffprobe))
- {
- return new FFMpegInfo
- {
- ProbePath = prebuiltffprobe,
- EncoderPath = prebuiltffmpeg,
- Version = "external"
- };
- }
-
- var version = downloadInfo.Version;
-
- if (string.Equals(version, "0", StringComparison.OrdinalIgnoreCase))
- {
- return new FFMpegInfo();
- }
-
- var rootEncoderPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
- var versionedDirectoryPath = Path.Combine(rootEncoderPath, version);
-
- var info = new FFMpegInfo
- {
- ProbePath = Path.Combine(versionedDirectoryPath, downloadInfo.FFProbeFilename),
- EncoderPath = Path.Combine(versionedDirectoryPath, downloadInfo.FFMpegFilename),
- Version = version
- };
-
- Directory.CreateDirectory(versionedDirectoryPath);
-
- var excludeFromDeletions = new List<string> { versionedDirectoryPath };
-
- if (!File.Exists(info.ProbePath) || !File.Exists(info.EncoderPath))
- {
- // ffmpeg not present. See if there's an older version we can start with
- var existingVersion = GetExistingVersion(info, rootEncoderPath);
-
- // No older version. Need to download and block until complete
- if (existingVersion == null)
- {
- return new FFMpegInfo();
- }
- else
- {
- info = existingVersion;
- versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
- excludeFromDeletions.Add(versionedDirectoryPath);
- }
- }
-
- // Allow just one of these to be overridden, if desired.
- if (!string.IsNullOrWhiteSpace(customffMpegPath))
- {
- info.EncoderPath = customffMpegPath;
- }
- if (!string.IsNullOrWhiteSpace(customffProbePath))
- {
- info.ProbePath = customffProbePath;
- }
-
- return info;
- }
-
- private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
- {
- var encoderFilename = Path.GetFileName(info.EncoderPath);
- var probeFilename = Path.GetFileName(info.ProbePath);
-
- foreach (var directory in _fileSystem.GetDirectoryPaths(rootEncoderPath))
- {
- var allFiles = _fileSystem.GetFilePaths(directory, true).ToList();
-
- var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
- var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
-
- if (!string.IsNullOrWhiteSpace(encoder) &&
- !string.IsNullOrWhiteSpace(probe))
- {
- return new FFMpegInfo
- {
- EncoderPath = encoder,
- ProbePath = probe,
- Version = Path.GetFileName(Path.GetDirectoryName(probe))
- };
- }
- }
-
- return null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs
deleted file mode 100644
index f747b01b9..000000000
--- a/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System;
-using System.Net.Http;
-
-namespace Emby.Server.Implementations.HttpClientManager
-{
- /// <summary>
- /// Class HttpClientInfo
- /// </summary>
- public class HttpClientInfo
- {
- /// <summary>
- /// Gets or sets the last timeout.
- /// </summary>
- /// <value>The last timeout.</value>
- public DateTime LastTimeout { get; set; }
- public HttpClient HttpClient { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
deleted file mode 100644
index 2e0728136..000000000
--- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
+++ /dev/null
@@ -1,800 +0,0 @@
-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.Cache;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpClientManager
-{
- /// <summary>
- /// Class HttpClientManager
- /// </summary>
- public class HttpClientManager : IHttpClient
- {
- /// <summary>
- /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
- /// </summary>
- private const int TimeoutSeconds = 30;
-
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
- /// <summary>
- /// The _app paths
- /// </summary>
- private readonly IApplicationPaths _appPaths;
-
- private readonly IFileSystem _fileSystem;
- private readonly Func<string> _defaultUserAgentFn;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
- /// </summary>
- public HttpClientManager(
- IApplicationPaths appPaths,
- ILoggerFactory loggerFactory,
- IFileSystem fileSystem,
- Func<string> defaultUserAgentFn)
- {
- if (appPaths == null)
- {
- throw new ArgumentNullException(nameof(appPaths));
- }
- if (loggerFactory == null)
- {
- throw new ArgumentNullException(nameof(loggerFactory));
- }
-
- _logger = loggerFactory.CreateLogger("HttpClient");
- _fileSystem = fileSystem;
- _appPaths = appPaths;
- _defaultUserAgentFn = defaultUserAgentFn;
-
- // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
- ServicePointManager.Expect100Continue = false;
- }
-
- /// <summary>
- /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
- /// DON'T dispose it after use.
- /// </summary>
- /// <value>The HTTP clients.</value>
- private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
-
- /// <summary>
- /// Gets
- /// </summary>
- /// <param name="host">The host.</param>
- /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
- /// <returns>HttpClient.</returns>
- /// <exception cref="ArgumentNullException">host</exception>
- private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
- {
- if (string.IsNullOrEmpty(host))
- {
- throw new ArgumentNullException(nameof(host));
- }
-
- var key = host + enableHttpCompression;
-
- if (!_httpClients.TryGetValue(key, out var client))
- {
- client = new HttpClientInfo();
-
- _httpClients.TryAdd(key, client);
- }
-
- return client;
- }
-
- private WebRequest GetRequest(HttpRequestOptions options, string method)
- {
- string url = options.Url;
-
- var uriAddress = new Uri(url);
- string userInfo = uriAddress.UserInfo;
- if (!string.IsNullOrWhiteSpace(userInfo))
- {
- _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url);
- url = url.Replace(userInfo + "@", string.Empty);
- }
-
- var request = WebRequest.Create(url);
-
- if (request is HttpWebRequest httpWebRequest)
- {
- AddRequestHeaders(httpWebRequest, options);
-
- if (options.EnableHttpCompression)
- {
- httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
- if (options.DecompressionMethod.HasValue
- && options.DecompressionMethod.Value == CompressionMethod.Gzip)
- {
- httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
- }
- }
- else
- {
- httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
- }
-
- httpWebRequest.KeepAlive = options.EnableKeepAlive;
-
- if (!string.IsNullOrEmpty(options.Host))
- {
- httpWebRequest.Host = options.Host;
- }
-
- if (!string.IsNullOrEmpty(options.Referer))
- {
- httpWebRequest.Referer = options.Referer;
- }
- }
-
- request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
-
- request.Method = method;
- request.Timeout = options.TimeoutMs;
-
- if (!string.IsNullOrWhiteSpace(userInfo))
- {
- var parts = userInfo.Split(':');
- if (parts.Length == 2)
- {
- request.Credentials = GetCredential(url, parts[0], parts[1]);
- // TODO: .net core ??
- request.PreAuthenticate = true;
- }
- }
-
- return request;
- }
-
- private static CredentialCache GetCredential(string url, string username, string password)
- {
- //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
- var credentialCache = new CredentialCache();
- credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
- return credentialCache;
- }
-
- private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
- {
- var hasUserAgent = false;
-
- foreach (var header in options.RequestHeaders)
- {
- if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
- {
- request.Accept = header.Value;
- }
- else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
- {
- SetUserAgent(request, header.Value);
- hasUserAgent = true;
- }
- else
- {
- request.Headers.Set(header.Key, header.Value);
- }
- }
-
- if (!hasUserAgent && options.EnableDefaultUserAgent)
- {
- SetUserAgent(request, _defaultUserAgentFn());
- }
- }
-
- private static void SetUserAgent(HttpWebRequest request, string userAgent)
- {
- request.UserAgent = userAgent;
- }
-
- /// <summary>
- /// Gets the response internal.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
- {
- return SendAsync(options, "GET");
- }
-
- /// <summary>
- /// Performs a GET request and returns the resulting stream
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{Stream}.</returns>
- public async Task<Stream> Get(HttpRequestOptions options)
- {
- var response = await GetResponse(options).ConfigureAwait(false);
- return response.Content;
- }
-
- /// <summary>
- /// send as an asynchronous operation.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <param name="httpMethod">The HTTP method.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- /// <exception cref="HttpException">
- /// </exception>
- public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
- {
- if (options.CacheMode == CacheMode.None)
- {
- return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
- }
-
- var url = options.Url;
- var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
-
- var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
-
- var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
- if (response != null)
- {
- return response;
- }
-
- response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
-
- if (response.StatusCode == HttpStatusCode.OK)
- {
- await CacheResponse(response, responseCachePath).ConfigureAwait(false);
- }
-
- return response;
- }
-
- private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
- {
- if (File.Exists(responseCachePath)
- && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
- {
- var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
-
- return new HttpResponseInfo
- {
- ResponseUrl = url,
- Content = stream,
- StatusCode = HttpStatusCode.OK,
- ContentLength = stream.Length
- };
- }
-
- return null;
- }
-
- private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
- {
- Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
-
- using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
- {
- await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
-
- response.Content.Position = 0;
- }
- }
-
- private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
- {
- ValidateParams(options);
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
-
- if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
- {
- throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
- {
- IsTimedOut = true
- };
- }
-
- var httpWebRequest = GetRequest(options, httpMethod);
-
- if (options.RequestContentBytes != null ||
- !string.IsNullOrEmpty(options.RequestContent) ||
- string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
-
- var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
-
- if (options.AppendCharsetToMimeType)
- {
- contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\"";
- }
-
- httpWebRequest.ContentType = contentType;
- httpWebRequest.ContentLength = bytes.Length;
- (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
- }
- catch (Exception ex)
- {
- throw new HttpException(ex.Message) { IsTimedOut = true };
- }
- }
-
- if (options.ResourcePool != null)
- {
- await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
- }
-
- if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
- {
- options.ResourcePool?.Release();
-
- throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true };
- }
-
- if (options.LogRequest)
- {
- if (options.LogRequestAsDebug)
- {
- _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(CultureInfo.CurrentCulture), options.Url);
- }
- else
- {
- _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(CultureInfo.CurrentCulture), options.Url);
- }
- }
-
- try
- {
- options.CancellationToken.ThrowIfCancellationRequested();
-
- if (!options.BufferContent)
- {
- var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
-
- var httpResponse = (HttpWebResponse)response;
-
- EnsureSuccessStatusCode(client, httpResponse, options);
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
- }
-
- using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
- {
- var httpResponse = (HttpWebResponse)response;
-
- EnsureSuccessStatusCode(client, httpResponse, options);
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- using (var stream = httpResponse.GetResponseStream())
- {
- var memoryStream = new MemoryStream();
- await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
-
- memoryStream.Position = 0;
-
- return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
- }
- }
- }
- catch (OperationCanceledException ex)
- {
- throw GetCancellationException(options, client, options.CancellationToken, ex);
- }
- catch (Exception ex)
- {
- throw GetException(ex, options, client);
- }
- finally
- {
- options.ResourcePool?.Release();
- }
- }
-
- private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
- {
- var responseInfo = new HttpResponseInfo(disposable)
- {
- Content = content,
- StatusCode = httpResponse.StatusCode,
- ContentType = httpResponse.ContentType,
- ContentLength = contentLength,
- ResponseUrl = httpResponse.ResponseUri.ToString()
- };
-
- if (httpResponse.Headers != null)
- {
- SetHeaders(httpResponse.Headers, responseInfo);
- }
-
- return responseInfo;
- }
-
- private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
- {
- var responseInfo = new HttpResponseInfo
- {
- TempFilePath = tempFile,
- StatusCode = httpResponse.StatusCode,
- ContentType = httpResponse.ContentType,
- ContentLength = contentLength
- };
-
- if (httpResponse.Headers != null)
- {
- SetHeaders(httpResponse.Headers, responseInfo);
- }
-
- return responseInfo;
- }
-
- private static void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
- {
- foreach (var key in headers.AllKeys)
- {
- responseInfo.Headers[key] = headers[key];
- }
- }
-
- public Task<HttpResponseInfo> Post(HttpRequestOptions options)
- {
- return SendAsync(options, "POST");
- }
-
- /// <summary>
- /// Performs a POST request
- /// </summary>
- /// <param name="options">The options.</param>
- /// <param name="postData">Params to add to the POST data.</param>
- /// <returns>stream on success, null on failure</returns>
- public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
- {
- options.SetPostData(postData);
-
- var response = await Post(options).ConfigureAwait(false);
-
- return response.Content;
- }
-
- /// <summary>
- /// Downloads the contents of a given url into a temporary location
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{System.String}.</returns>
- public async Task<string> GetTempFile(HttpRequestOptions options)
- {
- var response = await GetTempFileResponse(options).ConfigureAwait(false);
-
- return response.TempFilePath;
- }
-
- public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
- {
- ValidateParams(options);
-
- Directory.CreateDirectory(_appPaths.TempDirectory);
-
- var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
-
- if (options.Progress == null)
- {
- throw new ArgumentException("Options did not have a Progress value.", nameof(options));
- }
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- var httpWebRequest = GetRequest(options, "GET");
-
- if (options.ResourcePool != null)
- {
- await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
- }
-
- options.Progress.Report(0);
-
- if (options.LogRequest)
- {
- if (options.LogRequestAsDebug)
- {
- _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
- }
- else
- {
- _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
- }
- }
-
- var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
-
- try
- {
- options.CancellationToken.ThrowIfCancellationRequested();
-
- using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
- {
- var httpResponse = (HttpWebResponse)response;
-
- EnsureSuccessStatusCode(client, httpResponse, options);
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- var contentLength = GetContentLength(httpResponse);
-
- using (var stream = httpResponse.GetResponseStream())
- using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
- }
-
- options.Progress.Report(100);
-
- return GetResponseInfo(httpResponse, tempFile, contentLength);
- }
- }
- catch (Exception ex)
- {
- DeleteTempFile(tempFile);
- throw GetException(ex, options, client);
- }
- finally
- {
- options.ResourcePool?.Release();
- }
- }
-
- private static long? GetContentLength(HttpWebResponse response)
- {
- var length = response.ContentLength;
-
- if (length == 0)
- {
- return null;
- }
-
- return length;
- }
-
- protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
- {
- if (ex is HttpException)
- {
- return ex;
- }
-
- var webException = ex as WebException
- ?? ex.InnerException as WebException;
-
- if (webException != null)
- {
- if (options.LogErrors)
- {
- _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
- }
-
- var exception = new HttpException(webException.Message, webException);
-
- using (var response = webException.Response as HttpWebResponse)
- {
- if (response != null)
- {
- exception.StatusCode = response.StatusCode;
-
- if ((int)response.StatusCode == 429)
- {
- client.LastTimeout = DateTime.UtcNow;
- }
- }
- }
-
- if (!exception.StatusCode.HasValue)
- {
- if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
- webException.Status == WebExceptionStatus.ConnectFailure)
- {
- exception.IsTimedOut = true;
- }
- }
-
- return exception;
- }
-
- var operationCanceledException = ex as OperationCanceledException
- ?? ex.InnerException as OperationCanceledException;
-
- if (operationCanceledException != null)
- {
- return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
- }
-
- if (options.LogErrors)
- {
- _logger.LogError(ex, "Error getting response from {url}", options.Url);
- }
-
- return ex;
- }
-
- private void DeleteTempFile(string file)
- {
- try
- {
- _fileSystem.DeleteFile(file);
- }
- catch (IOException)
- {
- // Might not have been created at all. No need to worry.
- }
- }
-
- private void ValidateParams(HttpRequestOptions options)
- {
- if (string.IsNullOrEmpty(options.Url))
- {
- throw new ArgumentNullException(nameof(options));
- }
- }
-
- /// <summary>
- /// Gets the host from URL.
- /// </summary>
- /// <param name="url">The URL.</param>
- /// <returns>System.String.</returns>
- private static string GetHostFromUrl(string url)
- {
- var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
-
- if (index != -1)
- {
- url = url.Substring(index + 3);
- var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
-
- if (!string.IsNullOrWhiteSpace(host))
- {
- return host;
- }
- }
-
- return url;
- }
-
- /// <summary>
- /// Throws the cancellation exception.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <param name="client">The client.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="exception">The exception.</param>
- /// <returns>Exception.</returns>
- private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
- {
- // If the HttpClient's timeout is reached, it will cancel the Task internally
- if (!cancellationToken.IsCancellationRequested)
- {
- var msg = string.Format("Connection to {0} timed out", options.Url);
-
- if (options.LogErrors)
- {
- _logger.LogError(msg);
- }
-
- client.LastTimeout = DateTime.UtcNow;
-
- // Throw an HttpException so that the caller doesn't think it was cancelled by user code
- return new HttpException(msg, exception)
- {
- IsTimedOut = true
- };
- }
-
- return exception;
- }
-
- private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
- {
- var statusCode = response.StatusCode;
-
- var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
-
- if (isSuccessful)
- {
- return;
- }
-
- if (options.LogErrorResponseBody)
- {
- try
- {
- using (var stream = response.GetResponseStream())
- {
- if (stream != null)
- {
- using (var reader = new StreamReader(stream))
- {
- var msg = reader.ReadToEnd();
-
- _logger.LogError(msg);
- }
- }
- }
- }
- catch
- {
-
- }
- }
-
- throw new HttpException(response.StatusDescription)
- {
- StatusCode = response.StatusCode
- };
- }
-
- private static Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
- {
- var taskCompletion = new TaskCompletionSource<WebResponse>();
-
- var asyncTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
-
- ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
- var callback = new TaskCallback { taskCompletion = taskCompletion };
- asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
-
- // Handle errors
- asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
-
- return taskCompletion.Task;
- }
-
- private static void TimeoutCallback(object state, bool timedOut)
- {
- if (timedOut && state != null)
- {
- var request = (WebRequest)state;
- request.Abort();
- }
- }
-
- private class TaskCallback
- {
- public TaskCompletionSource<WebResponse> taskCompletion;
-
- public void OnSuccess(Task<WebResponse> task)
- {
- taskCompletion.TrySetResult(task.Result);
- }
-
- public void OnError(Task<WebResponse> task)
- {
- if (task.Exception == null)
- {
- taskCompletion.TrySetException(Enumerable.Empty<Exception>());
- }
- else
- {
- taskCompletion.TrySetException(task.Exception);
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs
deleted file mode 100644
index 7aedba9b3..000000000
--- a/Emby.Server.Implementations/HttpServer/FileWriter.cs
+++ /dev/null
@@ -1,210 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public class FileWriter : IHttpResult
- {
- private ILogger Logger { get; set; }
-
- private string RangeHeader { get; set; }
- private bool IsHeadRequest { get; set; }
-
- private long RangeStart { get; set; }
- private long RangeEnd { get; set; }
- private long RangeLength { get; set; }
- public long TotalContentLength { get; set; }
-
- public Action OnComplete { get; set; }
- public Action OnError { get; set; }
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
- public List<Cookie> Cookies { get; private set; }
-
- public FileShareMode FileShare { get; set; }
-
- /// <summary>
- /// The _options
- /// </summary>
- private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
- /// <summary>
- /// Gets the options.
- /// </summary>
- /// <value>The options.</value>
- public IDictionary<string, string> Headers => _options;
-
- public string Path { get; set; }
-
- public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem)
- {
- if (string.IsNullOrEmpty(contentType))
- {
- throw new ArgumentNullException(nameof(contentType));
- }
-
- Path = path;
- Logger = logger;
- RangeHeader = rangeHeader;
-
- Headers["Content-Type"] = contentType;
-
- TotalContentLength = fileSystem.GetFileInfo(path).Length;
- Headers["Accept-Ranges"] = "bytes";
-
- if (string.IsNullOrWhiteSpace(rangeHeader))
- {
- Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
- StatusCode = HttpStatusCode.OK;
- }
- else
- {
- StatusCode = HttpStatusCode.PartialContent;
- SetRangeValues();
- }
-
- FileShare = FileShareMode.Read;
- Cookies = new List<Cookie>();
- }
-
- /// <summary>
- /// Sets the range values.
- /// </summary>
- private void SetRangeValues()
- {
- var requestedRange = RequestedRanges[0];
-
- // If the requested range is "0-", we can optimize by just doing a stream copy
- if (!requestedRange.Value.HasValue)
- {
- RangeEnd = TotalContentLength - 1;
- }
- else
- {
- RangeEnd = requestedRange.Value.Value;
- }
-
- RangeStart = requestedRange.Key;
- RangeLength = 1 + RangeEnd - RangeStart;
-
- // Content-Length is the length of what we're serving, not the original content
- var lengthString = RangeLength.ToString(UsCulture);
- Headers["Content-Length"] = lengthString;
- var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
- Headers["Content-Range"] = rangeString;
-
- Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
- }
-
- /// <summary>
- /// The _requested ranges
- /// </summary>
- private List<KeyValuePair<long, long?>> _requestedRanges;
- /// <summary>
- /// Gets the requested ranges.
- /// </summary>
- /// <value>The requested ranges.</value>
- protected List<KeyValuePair<long, long?>> RequestedRanges
- {
- get
- {
- if (_requestedRanges == null)
- {
- _requestedRanges = new List<KeyValuePair<long, long?>>();
-
- // Example: bytes=0-,32-63
- var ranges = RangeHeader.Split('=')[1].Split(',');
-
- foreach (var range in ranges)
- {
- var vals = range.Split('-');
-
- long start = 0;
- long? end = null;
-
- if (!string.IsNullOrEmpty(vals[0]))
- {
- start = long.Parse(vals[0], UsCulture);
- }
- if (!string.IsNullOrEmpty(vals[1]))
- {
- end = long.Parse(vals[1], UsCulture);
- }
-
- _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
- }
- }
-
- return _requestedRanges;
- }
- }
-
- private string[] SkipLogExtensions = new string[]
- {
- ".js",
- ".html",
- ".css"
- };
-
- public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
- {
- try
- {
- // Headers only
- if (IsHeadRequest)
- {
- return;
- }
-
- var path = Path;
-
- if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
- {
- var extension = System.IO.Path.GetExtension(path);
-
- if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
- {
- Logger.LogDebug("Transmit file {0}", path);
- }
-
- //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
-
- await response.TransmitFile(path, 0, 0, FileShare, cancellationToken).ConfigureAwait(false);
- return;
- }
-
- await response.TransmitFile(path, RangeStart, RangeLength, FileShare, cancellationToken).ConfigureAwait(false);
- }
- finally
- {
- if (OnComplete != null)
- {
- OnComplete();
- }
- }
- }
-
- public string ContentType { get; set; }
-
- public IRequest RequestContext { get; set; }
-
- public object Response { get; set; }
-
- public int Status { get; set; }
-
- public HttpStatusCode StatusCode
- {
- get => (HttpStatusCode)Status;
- set => Status = (int)value;
- }
-
- public string StatusDescription { get; set; }
-
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
deleted file mode 100644
index d78891ac7..000000000
--- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
+++ /dev/null
@@ -1,901 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net.Sockets;
-using System.Reflection;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Net;
-using Emby.Server.Implementations.Services;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
-using ServiceStack.Text.Jsv;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public class HttpListenerHost : IHttpServer, IDisposable
- {
- private string DefaultRedirectPath { get; set; }
-
- private readonly ILogger _logger;
- public string[] UrlPrefixes { get; private set; }
-
- private IHttpListener _listener;
-
- public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
-
- private readonly IServerConfigurationManager _config;
- private readonly INetworkManager _networkManager;
- private readonly IServerApplicationHost _appHost;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IXmlSerializer _xmlSerializer;
- private readonly Func<Type, Func<string, object>> _funcParseFn;
-
- public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
-
- private readonly Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>();
- public static HttpListenerHost Instance { get; protected set; }
-
- private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
- private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
-
- public HttpListenerHost(
- IServerApplicationHost applicationHost,
- ILoggerFactory loggerFactory,
- IServerConfigurationManager config,
- IConfiguration configuration,
- INetworkManager networkManager,
- IJsonSerializer jsonSerializer,
- IXmlSerializer xmlSerializer)
- {
- _appHost = applicationHost;
- _logger = loggerFactory.CreateLogger("HttpServer");
- _config = config;
- DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
- _networkManager = networkManager;
- _jsonSerializer = jsonSerializer;
- _xmlSerializer = xmlSerializer;
-
- _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
-
- Instance = this;
- ResponseFilters = Array.Empty<Action<IRequest, IResponse, object>>();
- }
-
- public string GlobalResponse { get; set; }
-
- protected ILogger Logger => _logger;
-
- public object CreateInstance(Type type)
- {
- return _appHost.CreateInstance(type);
- }
-
- /// <summary>
- /// Applies the request filters. Returns whether or not the request has been handled
- /// and no more processing should be done.
- /// </summary>
- /// <returns></returns>
- public void ApplyRequestFilters(IRequest req, IResponse res, object requestDto)
- {
- //Exec all RequestFilter attributes with Priority < 0
- var attributes = GetRequestFilterAttributes(requestDto.GetType());
-
- int count = attributes.Count;
- int i = 0;
- for (; i < count && attributes[i].Priority < 0; i++)
- {
- var attribute = attributes[i];
- attribute.RequestFilter(req, res, requestDto);
- }
-
- //Exec remaining RequestFilter attributes with Priority >= 0
- for (; i < count && attributes[i].Priority >= 0; i++)
- {
- var attribute = attributes[i];
- attribute.RequestFilter(req, res, requestDto);
- }
- }
-
- public Type GetServiceTypeByRequest(Type requestType)
- {
- ServiceOperationsMap.TryGetValue(requestType, out var serviceType);
- return serviceType;
- }
-
- public void AddServiceInfo(Type serviceType, Type requestType)
- {
- ServiceOperationsMap[requestType] = serviceType;
- }
-
- private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
- {
- var attributes = requestDtoType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
-
- var serviceType = GetServiceTypeByRequest(requestDtoType);
- if (serviceType != null)
- {
- attributes.AddRange(serviceType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>());
- }
-
- attributes.Sort((x, y) => x.Priority - y.Priority);
-
- return attributes;
- }
-
- private void OnWebSocketConnected(WebSocketConnectEventArgs e)
- {
- if (_disposed)
- {
- return;
- }
-
- var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
- {
- OnReceive = ProcessWebSocketMessageReceived,
- Url = e.Url,
- QueryString = e.QueryString ?? new QueryParamCollection()
- };
-
- connection.Closed += Connection_Closed;
-
- lock (_webSocketConnections)
- {
- _webSocketConnections.Add(connection);
- }
-
- WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
- }
-
- private void Connection_Closed(object sender, EventArgs e)
- {
- lock (_webSocketConnections)
- {
- _webSocketConnections.Remove((IWebSocketConnection)sender);
- }
- }
-
- private static Exception GetActualException(Exception ex)
- {
- if (ex is AggregateException agg)
- {
- var inner = agg.InnerException;
- if (inner != null)
- {
- return GetActualException(inner);
- }
- else
- {
- var inners = agg.InnerExceptions;
- if (inners != null && inners.Count > 0)
- {
- return GetActualException(inners[0]);
- }
- }
- }
-
- return ex;
- }
-
- private int GetStatusCode(Exception ex)
- {
- switch (ex)
- {
- case ArgumentException _: return 400;
- case SecurityException _: return 401;
- case DirectoryNotFoundException _:
- case FileNotFoundException _:
- case ResourceNotFoundException _: return 404;
- case RemoteServiceUnavailableException _: return 502;
- default: return 500;
- }
- }
-
- private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage)
- {
- try
- {
- ex = GetActualException(ex);
-
- if (logExceptionStackTrace)
- {
- _logger.LogError(ex, "Error processing request");
- }
- else if (logExceptionMessage)
- {
- _logger.LogError(ex.Message);
- }
-
- var httpRes = httpReq.Response;
-
- if (httpRes.IsClosed)
- {
- return;
- }
-
- var statusCode = GetStatusCode(ex);
- httpRes.StatusCode = statusCode;
-
- httpRes.ContentType = "text/html";
- await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false);
- }
- catch (Exception errorEx)
- {
- _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
- }
- }
-
- private string NormalizeExceptionMessage(string msg)
- {
- if (msg == null)
- {
- return string.Empty;
- }
-
- // Strip any information we don't want to reveal
-
- msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
- msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
-
- return msg;
- }
-
- /// <summary>
- /// Shut down the Web Service
- /// </summary>
- public void Stop()
- {
- List<IWebSocketConnection> connections;
-
- lock (_webSocketConnections)
- {
- connections = _webSocketConnections.ToList();
- _webSocketConnections.Clear();
- }
-
- foreach (var connection in connections)
- {
- try
- {
- connection.Dispose();
- }
- catch
- {
-
- }
- }
-
- if (_listener != null)
- {
- _logger.LogInformation("Stopping HttpListener...");
- var task = _listener.Stop();
- Task.WaitAll(task);
- _logger.LogInformation("HttpListener stopped");
- }
- }
-
- private static readonly string[] _skipLogExtensions =
- {
- ".js",
- ".css",
- ".woff",
- ".woff2",
- ".ttf",
- ".html"
- };
-
- private bool EnableLogging(string url, string localPath)
- {
- var extension = GetExtension(url);
-
- return ((string.IsNullOrEmpty(extension) || !_skipLogExtensions.Contains(extension))
- && (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1));
- }
-
- private static string GetExtension(string url)
- {
- var parts = url.Split(new[] { '?' }, 2);
-
- return Path.GetExtension(parts[0]);
- }
-
- public static string RemoveQueryStringByKey(string url, string key)
- {
- var uri = new Uri(url);
-
- // this gets all the query string key value pairs as a collection
- var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
-
- var originalCount = newQueryString.Count;
-
- if (originalCount == 0)
- {
- return url;
- }
-
- // this removes the key if exists
- newQueryString.Remove(key);
-
- if (originalCount == newQueryString.Count)
- {
- return url;
- }
-
- // this gets the page path from root without QueryString
- string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
-
- return newQueryString.Count > 0
- ? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
- : pagePathWithoutQueryString;
- }
-
- private static string GetUrlToLog(string url)
- {
- url = RemoveQueryStringByKey(url, "api_key");
-
- return url;
- }
-
- private static string NormalizeConfiguredLocalAddress(string address)
- {
- var index = address.Trim('/').IndexOf('/');
-
- if (index != -1)
- {
- address = address.Substring(index + 1);
- }
-
- return address.Trim('/');
- }
-
- private bool ValidateHost(string host)
- {
- var hosts = _config
- .Configuration
- .LocalNetworkAddresses
- .Select(NormalizeConfiguredLocalAddress)
- .ToList();
-
- if (hosts.Count == 0)
- {
- return true;
- }
-
- host = host ?? string.Empty;
-
- if (_networkManager.IsInPrivateAddressSpace(host))
- {
- hosts.Add("localhost");
- hosts.Add("127.0.0.1");
-
- return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
- }
-
- return true;
- }
-
- private bool ValidateRequest(string remoteIp, bool isLocal)
- {
- if (isLocal)
- {
- return true;
- }
-
- if (_config.Configuration.EnableRemoteAccess)
- {
- var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
-
- if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
- {
- if (_config.Configuration.IsRemoteIPFilterBlacklist)
- {
- return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
- }
- else
- {
- return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
- }
- }
- }
- else
- {
- if (!_networkManager.IsInLocalNetwork(remoteIp))
- {
- return false;
- }
- }
-
- return true;
- }
-
- private bool ValidateSsl(string remoteIp, string urlString)
- {
- if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
- {
- if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
- {
- // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
- if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1 ||
- urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return true;
- }
-
- if (!_networkManager.IsInLocalNetwork(remoteIp))
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Overridable method that can be used to implement a custom hnandler
- /// </summary>
- protected async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
- {
- var date = DateTime.Now;
- var httpRes = httpReq.Response;
- bool enableLog = false;
- bool logHeaders = false;
- string urlToLog = null;
- string remoteIp = httpReq.RemoteIp;
-
- try
- {
- if (_disposed)
- {
- httpRes.StatusCode = 503;
- httpRes.ContentType = "text/plain";
- await Write(httpRes, "Server shutting down").ConfigureAwait(false);
- return;
- }
-
- if (!ValidateHost(host))
- {
- httpRes.StatusCode = 400;
- httpRes.ContentType = "text/plain";
- await Write(httpRes, "Invalid host").ConfigureAwait(false);
- return;
- }
-
- if (!ValidateRequest(remoteIp, httpReq.IsLocal))
- {
- httpRes.StatusCode = 403;
- httpRes.ContentType = "text/plain";
- await Write(httpRes, "Forbidden").ConfigureAwait(false);
- return;
- }
-
- if (!ValidateSsl(httpReq.RemoteIp, urlString))
- {
- RedirectToSecureUrl(httpReq, httpRes, urlString);
- return;
- }
-
- if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
- {
- httpRes.StatusCode = 200;
- httpRes.AddHeader("Access-Control-Allow-Origin", "*");
- httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
- httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
- httpRes.ContentType = "text/plain";
- await Write(httpRes, string.Empty).ConfigureAwait(false);
- return;
- }
-
- var operationName = httpReq.OperationName;
-
- enableLog = EnableLogging(urlString, localPath);
- urlToLog = urlString;
- logHeaders = enableLog && urlToLog.IndexOf("/videos/", StringComparison.OrdinalIgnoreCase) != -1;
-
- if (enableLog)
- {
- urlToLog = GetUrlToLog(urlString);
-
- LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent, logHeaders ? httpReq.Headers : null);
- }
-
- if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, DefaultRedirectPath);
- return;
- }
- if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
- return;
- }
-
- if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
- {
- httpRes.StatusCode = 200;
- httpRes.ContentType = "text/html";
- var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
- .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
-
- if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
- {
- await Write(httpRes,
- "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
- newUrl + "\">" + newUrl + "</a></body></html>").ConfigureAwait(false);
- return;
- }
- }
-
- if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
- localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
- {
- httpRes.StatusCode = 200;
- httpRes.ContentType = "text/html";
- var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
- .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
-
- if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
- {
- await Write(httpRes,
- "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
- newUrl + "\">" + newUrl + "</a></body></html>").ConfigureAwait(false);
- return;
- }
- }
-
- if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, DefaultRedirectPath);
- return;
- }
- if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
- return;
- }
- if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, DefaultRedirectPath);
- return;
- }
- if (string.IsNullOrEmpty(localPath))
- {
- RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
- return;
- }
-
- if (!string.Equals(httpReq.QueryString["r"], "0", StringComparison.OrdinalIgnoreCase))
- {
- if (localPath.EndsWith("web/dashboard.html", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "index.html#!/dashboard.html");
- }
-
- if (localPath.EndsWith("web/home.html", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "index.html");
- }
- }
-
- if (!string.IsNullOrEmpty(GlobalResponse))
- {
- // We don't want the address pings in ApplicationHost to fail
- if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
- {
- httpRes.StatusCode = 503;
- httpRes.ContentType = "text/html";
- await Write(httpRes, GlobalResponse).ConfigureAwait(false);
- return;
- }
- }
-
- var handler = GetServiceHandler(httpReq);
-
- if (handler != null)
- {
- await handler.ProcessRequestAsync(this, httpReq, httpRes, Logger, operationName, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- await ErrorHandler(new FileNotFoundException(), httpReq, false, false).ConfigureAwait(false);
- }
- }
- catch (OperationCanceledException ex)
- {
- await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
- }
-
- catch (IOException ex)
- {
- await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
- }
-
- catch (SocketException ex)
- {
- await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
- }
-
- catch (SecurityException ex)
- {
- await ErrorHandler(ex, httpReq, false, true).ConfigureAwait(false);
- }
-
- catch (Exception ex)
- {
- var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
-
- await ErrorHandler(ex, httpReq, logException, false).ConfigureAwait(false);
- }
- finally
- {
- httpRes.Close();
-
- if (enableLog)
- {
- var statusCode = httpRes.StatusCode;
-
- var duration = DateTime.Now - date;
-
- LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration, logHeaders ? httpRes.Headers : null);
- }
- }
- }
-
- // Entry point for HttpListener
- public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
- {
- var pathInfo = httpReq.PathInfo;
-
- var pathParts = pathInfo.TrimStart('/').Split('/');
- if (pathParts.Length == 0)
- {
- _logger.LogError("Path parts empty for PathInfo: {pathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
- return null;
- }
-
- var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out string contentType);
-
- if (restPath != null)
- {
- return new ServiceHandler
- {
- RestPath = restPath,
- ResponseContentType = contentType
- };
- }
-
- _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
- return null;
- }
-
- private static Task Write(IResponse response, string text)
- {
- var bOutput = Encoding.UTF8.GetBytes(text);
- response.SetContentLength(bOutput.Length);
-
- return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
- }
-
- private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url)
- {
- if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
- {
- var builder = new UriBuilder(uri)
- {
- Port = _config.Configuration.PublicHttpsPort,
- Scheme = "https"
- };
- url = builder.Uri.ToString();
-
- RedirectToUrl(httpRes, url);
- }
- else
- {
- var httpsUrl = url
- .Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
- .Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
-
- RedirectToUrl(httpRes, url);
- }
- }
-
- public static void RedirectToUrl(IResponse httpRes, string url)
- {
- httpRes.StatusCode = 302;
- httpRes.AddHeader("Location", url);
- }
-
- public ServiceController ServiceController { get; private set; }
-
- /// <summary>
- /// Adds the rest handlers.
- /// </summary>
- /// <param name="services">The services.</param>
- public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners)
- {
- _webSocketListeners = listeners.ToArray();
-
- ServiceController = new ServiceController();
-
- _logger.LogInformation("Calling ServiceStack AppHost.Init");
-
- var types = services.Select(r => r.GetType()).ToArray();
-
- ServiceController.Init(this, types);
-
- ResponseFilters = new Action<IRequest, IResponse, object>[]
- {
- new ResponseFilter(_logger).FilterResponse
- };
- }
-
- public RouteAttribute[] GetRouteAttributes(Type requestType)
- {
- var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
- var clone = routes.ToList();
-
- foreach (var route in clone)
- {
- routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
- {
- Notes = route.Notes,
- Priority = route.Priority,
- Summary = route.Summary
- });
-
- routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
- {
- Notes = route.Notes,
- Priority = route.Priority,
- Summary = route.Summary
- });
-
- // needed because apps add /emby, and some users also add /emby, thereby double prefixing
- routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
- {
- Notes = route.Notes,
- Priority = route.Priority,
- Summary = route.Summary
- });
- }
-
- return routes.ToArray();
- }
-
- public Func<string, object> GetParseFn(Type propertyType)
- {
- return _funcParseFn(propertyType);
- }
-
- public void SerializeToJson(object o, Stream stream)
- {
- _jsonSerializer.SerializeToStream(o, stream);
- }
-
- public void SerializeToXml(object o, Stream stream)
- {
- _xmlSerializer.SerializeToStream(o, stream);
- }
-
- public Task<object> DeserializeXml(Type type, Stream stream)
- {
- return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
- }
-
- public Task<object> DeserializeJson(Type type, Stream stream)
- {
- return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
- }
-
- //TODO Add Jellyfin Route Path Normalizer
-
- private static string NormalizeEmbyRoutePath(string path)
- {
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/emby" + path;
- }
-
- return "emby/" + path;
- }
-
- private static string NormalizeMediaBrowserRoutePath(string path)
- {
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/mediabrowser" + path;
- }
-
- return "mediabrowser/" + path;
- }
-
- private static string DoubleNormalizeEmbyRoutePath(string path)
- {
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/emby/emby" + path;
- }
-
- return "emby/emby/" + path;
- }
-
- private bool _disposed;
- private readonly object _disposeLock = new object();
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed) return;
-
- lock (_disposeLock)
- {
- if (_disposed) return;
-
- _disposed = true;
-
- if (disposing)
- {
- Stop();
- }
- }
- }
-
- /// <summary>
- /// Processes the web socket message received.
- /// </summary>
- /// <param name="result">The result.</param>
- private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
- {
- if (_disposed)
- {
- return Task.CompletedTask;
- }
-
- _logger.LogDebug("Websocket message received: {0}", result.MessageType);
-
- var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
- {
- try
- {
- await i.ProcessMessage(result).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
- }
- }));
-
- return Task.WhenAll(tasks);
- }
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- public void StartServer(string[] urlPrefixes, IHttpListener httpListener)
- {
- UrlPrefixes = urlPrefixes;
-
- _listener = httpListener;
-
- _listener.WebSocketConnected = OnWebSocketConnected;
- _listener.ErrorHandler = ErrorHandler;
- _listener.RequestHandler = RequestHandler;
-
- _listener.Start(UrlPrefixes);
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
deleted file mode 100644
index 070717d48..000000000
--- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
+++ /dev/null
@@ -1,722 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.IO.Compression;
-using System.Net;
-using System.Runtime.Serialization;
-using System.Security.Cryptography;
-using System.Text;
-using System.Threading.Tasks;
-using System.Xml;
-using Emby.Server.Implementations.Services;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using IRequest = MediaBrowser.Model.Services.IRequest;
-using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- /// <summary>
- /// Class HttpResultFactory
- /// </summary>
- public class HttpResultFactory : IHttpResultFactory
- {
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _jsonSerializer;
-
- private IBrotliCompressor _brotliCompressor;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
- /// </summary>
- public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
- {
- _fileSystem = fileSystem;
- _jsonSerializer = jsonSerializer;
- _brotliCompressor = brotliCompressor;
- _logger = loggerfactory.CreateLogger("HttpResultFactory");
- }
-
- /// <summary>
- /// Gets the result.
- /// </summary>
- /// <param name="content">The content.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <returns>System.Object.</returns>
- public object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null)
- {
- return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
- }
-
- public object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null)
- {
- return GetHttpResult(null, content, contentType, true, responseHeaders);
- }
-
- public object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null)
- {
- return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
- }
-
- public object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null)
- {
- return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
- }
-
- public object GetRedirectResult(string url)
- {
- var responseHeaders = new Dictionary<string, string>();
- responseHeaders["Location"] = url;
-
- var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
-
- AddResponseHeaders(result, responseHeaders);
-
- return result;
- }
-
- /// <summary>
- /// Gets the HTTP result.
- /// </summary>
- private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
- {
- var result = new StreamWriter(content, contentType);
-
- if (responseHeaders == null)
- {
- responseHeaders = new Dictionary<string, string>();
- }
-
- if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
- {
- responseHeaders["Expires"] = "-1";
- }
-
- AddResponseHeaders(result, responseHeaders);
-
- return result;
- }
-
- /// <summary>
- /// Gets the HTTP result.
- /// </summary>
- private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
- {
- string compressionType = null;
- bool isHeadRequest = false;
-
- if (requestContext != null)
- {
- compressionType = GetCompressionType(requestContext, content, contentType);
- isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
- }
-
- IHasHeaders result;
- if (string.IsNullOrEmpty(compressionType))
- {
- var contentLength = content.Length;
-
- if (isHeadRequest)
- {
- content = Array.Empty<byte>();
- }
-
- result = new StreamWriter(content, contentType, contentLength);
- }
- else
- {
- result = GetCompressedResult(content, compressionType, responseHeaders, isHeadRequest, contentType);
- }
-
- if (responseHeaders == null)
- {
- responseHeaders = new Dictionary<string, string>();
- }
-
- if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
- {
- responseHeaders["Expires"] = "-1";
- }
-
- AddResponseHeaders(result, responseHeaders);
-
- return result;
- }
-
- /// <summary>
- /// Gets the HTTP result.
- /// </summary>
- private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
- {
- IHasHeaders result;
-
- var bytes = Encoding.UTF8.GetBytes(content);
-
- var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
-
- var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
-
- if (string.IsNullOrEmpty(compressionType))
- {
- var contentLength = bytes.Length;
-
- if (isHeadRequest)
- {
- bytes = Array.Empty<byte>();
- }
-
- result = new StreamWriter(bytes, contentType, contentLength);
- }
- else
- {
- result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
- }
-
- if (responseHeaders == null)
- {
- responseHeaders = new Dictionary<string, string>();
- }
-
- if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
- {
- responseHeaders["Expires"] = "-1";
- }
-
- AddResponseHeaders(result, responseHeaders);
-
- return result;
- }
-
- /// <summary>
- /// Gets the optimized result.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
- where T : class
- {
- if (result == null)
- {
- throw new ArgumentNullException(nameof(result));
- }
-
- if (responseHeaders == null)
- {
- responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- responseHeaders["Expires"] = "-1";
-
- return ToOptimizedResultInternal(requestContext, result, responseHeaders);
- }
-
- private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
- {
- if (responseContentType == null)
- {
- return null;
- }
-
- // Per apple docs, hls manifests must be compressed
- if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
- responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
- responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
- responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
- responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
- {
- return null;
- }
-
- if (content.Length < 1024)
- {
- return null;
- }
-
- return GetCompressionType(request);
- }
-
- private static string GetCompressionType(IRequest request)
- {
- var acceptEncoding = request.Headers["Accept-Encoding"];
-
- if (acceptEncoding != null)
- {
- //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
- // return "br";
-
- if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
- return "deflate";
-
- if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
- return "gzip";
- }
-
- return null;
- }
-
- /// <summary>
- /// Returns the optimized result for the IRequestContext.
- /// Does not use or store results in any cache.
- /// </summary>
- /// <param name="request"></param>
- /// <param name="dto"></param>
- /// <returns></returns>
- public object ToOptimizedResult<T>(IRequest request, T dto)
- {
- return ToOptimizedResultInternal(request, dto);
- }
-
- private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
- {
- // TODO: @bond use Span and .Equals
- var contentType = request.ResponseContentType?.Split(';')[0].Trim().ToLowerInvariant();
-
- switch (contentType)
- {
- case "application/xml":
- case "text/xml":
- case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
- return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
-
- case "application/json":
- case "text/json":
- return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
- default:
- break;
- }
-
- var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
-
- var ms = new MemoryStream();
- var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
-
- writerFn(dto, ms);
-
- ms.Position = 0;
-
- if (isHeadRequest)
- {
- using (ms)
- {
- return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
- }
- }
-
- return GetHttpResult(request, ms, contentType, true, responseHeaders);
- }
-
- private IHasHeaders GetCompressedResult(byte[] content,
- string requestedCompressionType,
- IDictionary<string, string> responseHeaders,
- bool isHeadRequest,
- string contentType)
- {
- if (responseHeaders == null)
- {
- responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- content = Compress(content, requestedCompressionType);
- responseHeaders["Content-Encoding"] = requestedCompressionType;
-
- responseHeaders["Vary"] = "Accept-Encoding";
-
- var contentLength = content.Length;
-
- if (isHeadRequest)
- {
- var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
- AddResponseHeaders(result, responseHeaders);
- return result;
- }
- else
- {
- var result = new StreamWriter(content, contentType, contentLength);
- AddResponseHeaders(result, responseHeaders);
- return result;
- }
- }
-
- private byte[] Compress(byte[] bytes, string compressionType)
- {
- if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
- {
- return CompressBrotli(bytes);
- }
-
- if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
- {
- return Deflate(bytes);
- }
-
- if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
- {
- return GZip(bytes);
- }
-
- throw new NotSupportedException(compressionType);
- }
-
- private byte[] CompressBrotli(byte[] bytes)
- {
- return _brotliCompressor.Compress(bytes);
- }
-
- private static byte[] Deflate(byte[] bytes)
- {
- // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
- // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
- using (var ms = new MemoryStream())
- using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
- {
- zipStream.Write(bytes, 0, bytes.Length);
- zipStream.Dispose();
-
- return ms.ToArray();
- }
- }
-
- private static byte[] GZip(byte[] buffer)
- {
- using (var ms = new MemoryStream())
- using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
- {
- zipStream.Write(buffer, 0, buffer.Length);
- zipStream.Dispose();
-
- return ms.ToArray();
- }
- }
-
- private static string SerializeToXmlString(object from)
- {
- using (var ms = new MemoryStream())
- {
- var xwSettings = new XmlWriterSettings();
- xwSettings.Encoding = new UTF8Encoding(false);
- xwSettings.OmitXmlDeclaration = false;
-
- using (var xw = XmlWriter.Create(ms, xwSettings))
- {
- var serializer = new DataContractSerializer(from.GetType());
- serializer.WriteObject(xw, from);
- xw.Flush();
- ms.Seek(0, SeekOrigin.Begin);
- using (var reader = new StreamReader(ms))
- {
- return reader.ReadToEnd();
- }
- }
- }
- }
-
- /// <summary>
- /// Pres the process optimized result.
- /// </summary>
- private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
- {
- bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
- AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
-
- if (!noCache)
- {
- DateTime.TryParse(requestContext.Headers.Get("If-Modified-Since"), out var ifModifiedSinceHeader);
-
- if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
- {
- AddAgeHeader(responseHeaders, options.DateLastModified);
-
- var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
-
- AddResponseHeaders(result, responseHeaders);
-
- return result;
- }
- }
-
- return null;
- }
-
- public Task<object> GetStaticFileResult(IRequest requestContext,
- string path,
- FileShareMode fileShare = FileShareMode.Read)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- return GetStaticFileResult(requestContext, new StaticFileResultOptions
- {
- Path = path,
- FileShare = fileShare
- });
- }
-
- public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
- {
- var path = options.Path;
- var fileShare = options.FileShare;
-
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
- {
- throw new ArgumentException("FileShare must be either Read or ReadWrite");
- }
-
- if (string.IsNullOrEmpty(options.ContentType))
- {
- options.ContentType = MimeTypes.GetMimeType(path);
- }
-
- if (!options.DateLastModified.HasValue)
- {
- options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
- }
-
- options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
-
- options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- return GetStaticResult(requestContext, options);
- }
-
- /// <summary>
- /// Gets the file stream.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="fileShare">The file share.</param>
- /// <returns>Stream.</returns>
- private Stream GetFileStream(string path, FileShareMode fileShare)
- {
- return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
- }
-
- public Task<object> GetStaticResult(IRequest requestContext,
- Guid cacheKey,
- DateTime? lastDateModified,
- TimeSpan? cacheDuration,
- string contentType,
- Func<Task<Stream>> factoryFn,
- IDictionary<string, string> responseHeaders = null,
- bool isHeadRequest = false)
- {
- return GetStaticResult(requestContext, new StaticResultOptions
- {
- CacheDuration = cacheDuration,
- ContentFactory = factoryFn,
- ContentType = contentType,
- DateLastModified = lastDateModified,
- IsHeadRequest = isHeadRequest,
- ResponseHeaders = responseHeaders
- });
- }
-
- public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
- {
- options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- var contentType = options.ContentType;
- if (!string.IsNullOrEmpty(requestContext.Headers.Get("If-Modified-Since")))
- {
- // See if the result is already cached in the browser
- var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
-
- if (result != null)
- {
- return result;
- }
- }
-
- // TODO: We don't really need the option value
- var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
- var factoryFn = options.ContentFactory;
- var responseHeaders = options.ResponseHeaders;
- AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
- AddAgeHeader(responseHeaders, options.DateLastModified);
-
- var rangeHeader = requestContext.Headers.Get("Range");
-
- if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
- {
- var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
- {
- OnComplete = options.OnComplete,
- OnError = options.OnError,
- FileShare = options.FileShare
- };
-
- AddResponseHeaders(hasHeaders, options.ResponseHeaders);
- return hasHeaders;
- }
-
- var stream = await factoryFn().ConfigureAwait(false);
-
- var totalContentLength = options.ContentLength;
- if (!totalContentLength.HasValue)
- {
- try
- {
- totalContentLength = stream.Length;
- }
- catch (NotSupportedException)
- {
-
- }
- }
-
- if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
- {
- var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
- {
- OnComplete = options.OnComplete
- };
-
- AddResponseHeaders(hasHeaders, options.ResponseHeaders);
- return hasHeaders;
- }
- else
- {
- if (totalContentLength.HasValue)
- {
- responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
- }
-
- if (isHeadRequest)
- {
- using (stream)
- {
- return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
- }
- }
-
- var hasHeaders = new StreamWriter(stream, contentType)
- {
- OnComplete = options.OnComplete,
- OnError = options.OnError
- };
-
- AddResponseHeaders(hasHeaders, options.ResponseHeaders);
- return hasHeaders;
- }
- }
-
- /// <summary>
- /// The us culture
- /// </summary>
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Adds the caching responseHeaders.
- /// </summary>
- private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
- bool noCache, DateTime? lastModifiedDate)
- {
- if (noCache)
- {
- responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
- responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
- return;
- }
-
- if (cacheDuration.HasValue)
- {
- responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
- }
- else
- {
- responseHeaders["Cache-Control"] = "public";
- }
-
- if (lastModifiedDate.HasValue)
- {
- responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
- }
- }
-
- /// <summary>
- /// Adds the age header.
- /// </summary>
- /// <param name="responseHeaders">The responseHeaders.</param>
- /// <param name="lastDateModified">The last date modified.</param>
- private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
- {
- if (lastDateModified.HasValue)
- {
- responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
- }
- }
-
- /// <summary>
- /// Determines whether [is not modified] [the specified if modified since].
- /// </summary>
- /// <param name="ifModifiedSince">If modified since.</param>
- /// <param name="cacheDuration">Duration of the cache.</param>
- /// <param name="dateModified">The date modified.</param>
- /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
- private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
- {
- if (dateModified.HasValue)
- {
- var lastModified = NormalizeDateForComparison(dateModified.Value);
- ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
-
- return lastModified <= ifModifiedSince;
- }
-
- if (cacheDuration.HasValue)
- {
- var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
-
- if (DateTime.UtcNow < cacheExpirationDate)
- {
- return true;
- }
- }
-
- return false;
- }
-
-
- /// <summary>
- /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
- /// </summary>
- /// <param name="date">The date.</param>
- /// <returns>DateTime.</returns>
- private static DateTime NormalizeDateForComparison(DateTime date)
- {
- return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
- }
-
- /// <summary>
- /// Adds the response headers.
- /// </summary>
- /// <param name="hasHeaders">The has options.</param>
- /// <param name="responseHeaders">The response headers.</param>
- private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
- {
- foreach (var item in responseHeaders)
- {
- hasHeaders.Headers[item.Key] = item.Value;
- }
- }
- }
-
- public interface IBrotliCompressor
- {
- byte[] Compress(byte[] content);
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/IHttpListener.cs b/Emby.Server.Implementations/HttpServer/IHttpListener.cs
deleted file mode 100644
index 835091361..000000000
--- a/Emby.Server.Implementations/HttpServer/IHttpListener.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Net;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public interface IHttpListener : IDisposable
- {
- /// <summary>
- /// Gets or sets the error handler.
- /// </summary>
- /// <value>The error handler.</value>
- Func<Exception, IRequest, bool, bool, Task> ErrorHandler { get; set; }
-
- /// <summary>
- /// Gets or sets the request handler.
- /// </summary>
- /// <value>The request handler.</value>
- Func<IHttpRequest, string, string, string, CancellationToken, Task> RequestHandler { get; set; }
-
- /// <summary>
- /// Gets or sets the web socket handler.
- /// </summary>
- /// <value>The web socket handler.</value>
- Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
-
- /// <summary>
- /// Gets or sets the web socket connecting.
- /// </summary>
- /// <value>The web socket connecting.</value>
- Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
-
- /// <summary>
- /// Starts this instance.
- /// </summary>
- /// <param name="urlPrefixes">The URL prefixes.</param>
- void Start(IEnumerable<string> urlPrefixes);
-
- /// <summary>
- /// Stops this instance.
- /// </summary>
- Task Stop();
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs
deleted file mode 100644
index d22d9db26..000000000
--- a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System;
-using System.Globalization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public static class LoggerUtils
- {
- public static void LogRequest(ILogger logger, string url, string method, string userAgent, QueryParamCollection headers)
- {
- if (headers == null)
- {
- logger.LogInformation("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty);
- }
- else
- {
- var headerText = string.Empty;
- var index = 0;
-
- foreach (var i in headers)
- {
- if (index > 0)
- {
- headerText += ", ";
- }
-
- headerText += i.Name + "=" + i.Value;
-
- index++;
- }
-
- logger.LogInformation("HTTP {0} {1}. {2}", method, url, headerText);
- }
- }
-
- /// <summary>
- /// Logs the response.
- /// </summary>
- /// <param name="logger">The logger.</param>
- /// <param name="statusCode">The status code.</param>
- /// <param name="url">The URL.</param>
- /// <param name="endPoint">The end point.</param>
- /// <param name="duration">The duration.</param>
- public static void LogResponse(ILogger logger, int statusCode, string url, string endPoint, TimeSpan duration, QueryParamCollection headers)
- {
- var durationMs = duration.TotalMilliseconds;
- var logSuffix = durationMs >= 1000 && durationMs < 60000 ? "ms (slow)" : "ms";
-
- //var headerText = headers == null ? string.Empty : "Headers: " + string.Join(", ", headers.Where(i => i.Name.IndexOf("Access-", StringComparison.OrdinalIgnoreCase) == -1).Select(i => i.Name + "=" + i.Value).ToArray());
- var headerText = string.Empty;
- logger.LogInformation("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText);
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
deleted file mode 100644
index 891a76ec2..000000000
--- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
+++ /dev/null
@@ -1,221 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public class RangeRequestWriter : IAsyncStreamWriter, IHttpResult
- {
- /// <summary>
- /// Gets or sets the source stream.
- /// </summary>
- /// <value>The source stream.</value>
- private Stream SourceStream { get; set; }
- private string RangeHeader { get; set; }
- private bool IsHeadRequest { get; set; }
-
- private long RangeStart { get; set; }
- private long RangeEnd { get; set; }
- private long RangeLength { get; set; }
- private long TotalContentLength { get; set; }
-
- public Action OnComplete { get; set; }
- private readonly ILogger _logger;
-
- private const int BufferSize = 81920;
-
- /// <summary>
- /// The _options
- /// </summary>
- private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
-
- /// <summary>
- /// The us culture
- /// </summary>
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Additional HTTP Headers
- /// </summary>
- /// <value>The headers.</value>
- public IDictionary<string, string> Headers => _options;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StreamWriter" /> class.
- /// </summary>
- /// <param name="rangeHeader">The range header.</param>
- /// <param name="source">The source.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger)
- {
- if (string.IsNullOrEmpty(contentType))
- {
- throw new ArgumentNullException(nameof(contentType));
- }
-
- RangeHeader = rangeHeader;
- SourceStream = source;
- IsHeadRequest = isHeadRequest;
- this._logger = logger;
-
- ContentType = contentType;
- Headers["Content-Type"] = contentType;
- Headers["Accept-Ranges"] = "bytes";
- StatusCode = HttpStatusCode.PartialContent;
-
- SetRangeValues(contentLength);
- }
-
- /// <summary>
- /// Sets the range values.
- /// </summary>
- private void SetRangeValues(long contentLength)
- {
- var requestedRange = RequestedRanges[0];
-
- TotalContentLength = contentLength;
-
- // If the requested range is "0-", we can optimize by just doing a stream copy
- if (!requestedRange.Value.HasValue)
- {
- RangeEnd = TotalContentLength - 1;
- }
- else
- {
- RangeEnd = requestedRange.Value.Value;
- }
-
- RangeStart = requestedRange.Key;
- RangeLength = 1 + RangeEnd - RangeStart;
-
- // Content-Length is the length of what we're serving, not the original content
- Headers["Content-Length"] = RangeLength.ToString(UsCulture);
- Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
-
- if (RangeStart > 0 && SourceStream.CanSeek)
- {
- SourceStream.Position = RangeStart;
- }
- }
-
- /// <summary>
- /// The _requested ranges
- /// </summary>
- private List<KeyValuePair<long, long?>> _requestedRanges;
- /// <summary>
- /// Gets the requested ranges.
- /// </summary>
- /// <value>The requested ranges.</value>
- protected List<KeyValuePair<long, long?>> RequestedRanges
- {
- get
- {
- if (_requestedRanges == null)
- {
- _requestedRanges = new List<KeyValuePair<long, long?>>();
-
- // Example: bytes=0-,32-63
- var ranges = RangeHeader.Split('=')[1].Split(',');
-
- foreach (var range in ranges)
- {
- var vals = range.Split('-');
-
- long start = 0;
- long? end = null;
-
- if (!string.IsNullOrEmpty(vals[0]))
- {
- start = long.Parse(vals[0], UsCulture);
- }
- if (!string.IsNullOrEmpty(vals[1]))
- {
- end = long.Parse(vals[1], UsCulture);
- }
-
- _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
- }
- }
-
- return _requestedRanges;
- }
- }
-
- public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
- {
- try
- {
- // Headers only
- if (IsHeadRequest)
- {
- return;
- }
-
- using (var source = SourceStream)
- {
- // If the requested range is "0-", we can optimize by just doing a stream copy
- if (RangeEnd >= TotalContentLength - 1)
- {
- await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false);
- }
- else
- {
- await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false);
- }
- }
- }
- finally
- {
- if (OnComplete != null)
- {
- OnComplete();
- }
- }
- }
-
- private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength)
- {
- var array = new byte[BufferSize];
- int bytesRead;
- while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
- {
- if (bytesRead == 0)
- {
- break;
- }
-
- var bytesToCopy = Math.Min(bytesRead, copyLength);
-
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy)).ConfigureAwait(false);
-
- copyLength -= bytesToCopy;
-
- if (copyLength <= 0)
- {
- break;
- }
- }
- }
-
- public string ContentType { get; set; }
-
- public IRequest RequestContext { get; set; }
-
- public object Response { get; set; }
-
- public int Status { get; set; }
-
- public HttpStatusCode StatusCode
- {
- get => (HttpStatusCode)Status;
- set => Status = (int)value;
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
deleted file mode 100644
index da2bf983a..000000000
--- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-using System;
-using System.Globalization;
-using System.Text;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- public class ResponseFilter
- {
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
- private readonly ILogger _logger;
-
- public ResponseFilter(ILogger logger)
- {
- _logger = logger;
- }
-
- /// <summary>
- /// Filters the response.
- /// </summary>
- /// <param name="req">The req.</param>
- /// <param name="res">The res.</param>
- /// <param name="dto">The dto.</param>
- public void FilterResponse(IRequest req, IResponse res, object dto)
- {
- // Try to prevent compatibility view
- res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization");
- res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
- res.AddHeader("Access-Control-Allow-Origin", "*");
-
- if (dto is Exception exception)
- {
- _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl);
-
- if (!string.IsNullOrEmpty(exception.Message))
- {
- var error = exception.Message.Replace(Environment.NewLine, " ");
- error = RemoveControlCharacters(error);
-
- res.AddHeader("X-Application-Error-Code", error);
- }
- }
-
- if (dto is IHasHeaders hasHeaders)
- {
- if (!hasHeaders.Headers.ContainsKey("Server"))
- {
- hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50";
- }
-
- // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
- if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength)
- && !string.IsNullOrEmpty(contentLength))
- {
- var length = long.Parse(contentLength, UsCulture);
-
- if (length > 0)
- {
- res.SetContentLength(length);
- res.SendChunked = false;
- }
- }
- }
- }
-
- /// <summary>
- /// Removes the control characters.
- /// </summary>
- /// <param name="inString">The in string.</param>
- /// <returns>System.String.</returns>
- public static string RemoveControlCharacters(string inString)
- {
- if (inString == null) return null;
-
- var newString = new StringBuilder();
-
- foreach (var ch in inString)
- {
- if (!char.IsControl(ch))
- {
- newString.Append(ch);
- }
- }
- return newString.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
index 499a334fc..e2ad07177 100644
--- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
@@ -1,239 +1,43 @@
-using System;
-using System.Linq;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
+#pragma warning disable CS1591
+
+using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
namespace Emby.Server.Implementations.HttpServer.Security
{
public class AuthService : IAuthService
{
- private readonly IServerConfigurationManager _config;
-
- public AuthService(IUserManager userManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, ISessionManager sessionManager, INetworkManager networkManager)
- {
- AuthorizationContext = authorizationContext;
- _config = config;
- SessionManager = sessionManager;
- UserManager = userManager;
- NetworkManager = networkManager;
- }
-
- public IUserManager UserManager { get; private set; }
- public IAuthorizationContext AuthorizationContext { get; private set; }
- public ISessionManager SessionManager { get; private set; }
- public INetworkManager NetworkManager { get; private set; }
-
- /// <summary>
- /// Redirect the client to a specific URL if authentication failed.
- /// If this property is null, simply `401 Unauthorized` is returned.
- /// </summary>
- public string HtmlRedirect { get; set; }
+ private readonly IAuthorizationContext _authorizationContext;
- public void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues)
+ public AuthService(
+ IAuthorizationContext authorizationContext)
{
- ValidateUser(request, authAttribtues);
+ _authorizationContext = authorizationContext;
}
- private void ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
+ public async Task<AuthorizationInfo> Authenticate(HttpRequest request)
{
- // This code is executed before the service
- var auth = AuthorizationContext.GetAuthorizationInfo(request);
+ var auth = await _authorizationContext.GetAuthorizationInfo(request).ConfigureAwait(false);
- if (!IsExemptFromAuthenticationToken(auth, authAttribtues, request))
+ if (!auth.HasToken)
{
- ValidateSecurityToken(request, auth.Token);
+ throw new AuthenticationException("Request does not contain a token.");
}
- if (authAttribtues.AllowLocalOnly && !request.IsLocal)
+ if (!auth.IsAuthenticated)
{
- throw new SecurityException("Operation not found.");
+ throw new SecurityException("Invalid token.");
}
- var user = auth.User;
-
- if (user == null & !auth.UserId.Equals(Guid.Empty))
+ if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false)
{
- throw new SecurityException("User with Id " + auth.UserId + " not found");
+ throw new SecurityException("User account has been disabled.");
}
- if (user != null)
- {
- ValidateUserAccess(user, request, authAttribtues, auth);
- }
-
- var info = GetTokenInfo(request);
-
- if (!IsExemptFromRoles(auth, authAttribtues, request, info))
- {
- var roles = authAttribtues.GetRoles();
-
- ValidateRoles(roles, user);
- }
-
- if (!string.IsNullOrEmpty(auth.DeviceId) &&
- !string.IsNullOrEmpty(auth.Client) &&
- !string.IsNullOrEmpty(auth.Device))
- {
- SessionManager.LogSessionActivity(auth.Client,
- auth.Version,
- auth.DeviceId,
- auth.Device,
- request.RemoteIp,
- user);
- }
- }
-
- private void ValidateUserAccess(User user, IRequest request,
- IAuthenticationAttributes authAttribtues,
- AuthorizationInfo auth)
- {
- if (user.Policy.IsDisabled)
- {
- throw new SecurityException("User account has been disabled.")
- {
- SecurityExceptionType = SecurityExceptionType.Unauthenticated
- };
- }
-
- if (!user.Policy.EnableRemoteAccess && !NetworkManager.IsInLocalNetwork(request.RemoteIp))
- {
- throw new SecurityException("User account has been disabled.")
- {
- SecurityExceptionType = SecurityExceptionType.Unauthenticated
- };
- }
-
- if (!user.Policy.IsAdministrator &&
- !authAttribtues.EscapeParentalControl &&
- !user.IsParentalScheduleAllowed())
- {
- request.Response.AddHeader("X-Application-Error-Code", "ParentalControl");
-
- throw new SecurityException("This user account is not allowed access at this time.")
- {
- SecurityExceptionType = SecurityExceptionType.ParentalControl
- };
- }
- }
-
- private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request)
- {
- if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
- {
- return true;
- }
-
- if (authAttribtues.AllowLocal && request.IsLocal)
- {
- return true;
- }
- if (authAttribtues.AllowLocalOnly && request.IsLocal)
- {
- return true;
- }
-
- return false;
- }
-
- private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
- {
- if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
- {
- return true;
- }
-
- if (authAttribtues.AllowLocal && request.IsLocal)
- {
- return true;
- }
-
- if (authAttribtues.AllowLocalOnly && request.IsLocal)
- {
- return true;
- }
-
- if (string.IsNullOrEmpty(auth.Token))
- {
- return true;
- }
-
- if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty))
- {
- return true;
- }
-
- return false;
- }
-
- private static void ValidateRoles(string[] roles, User user)
- {
- if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
- {
- if (user == null || !user.Policy.IsAdministrator)
- {
- throw new SecurityException("User does not have admin access.")
- {
- SecurityExceptionType = SecurityExceptionType.Unauthenticated
- };
- }
- }
- if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
- {
- if (user == null || !user.Policy.EnableContentDeletion)
- {
- throw new SecurityException("User does not have delete access.")
- {
- SecurityExceptionType = SecurityExceptionType.Unauthenticated
- };
- }
- }
- if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
- {
- if (user == null || !user.Policy.EnableContentDownloading)
- {
- throw new SecurityException("User does not have download access.")
- {
- SecurityExceptionType = SecurityExceptionType.Unauthenticated
- };
- }
- }
- }
-
- private static AuthenticationInfo GetTokenInfo(IRequest request)
- {
- request.Items.TryGetValue("OriginalAuthenticationInfo", out var info);
- return info as AuthenticationInfo;
- }
-
- private void ValidateSecurityToken(IRequest request, string token)
- {
- if (string.IsNullOrEmpty(token))
- {
- throw new SecurityException("Access token is required.");
- }
-
- var info = GetTokenInfo(request);
-
- if (info == null)
- {
- throw new SecurityException("Access token is invalid or expired.");
- }
-
- //if (!string.IsNullOrEmpty(info.UserId))
- //{
- // var user = _userManager.GetUserById(info.UserId);
-
- // if (user == null || user.Configuration.IsDisabled)
- // {
- // throw new SecurityException("User account has been disabled.");
- // }
- //}
+ return auth;
}
}
}
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
deleted file mode 100644
index cab41e65b..000000000
--- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
+++ /dev/null
@@ -1,237 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.HttpServer.Security
-{
- public class AuthorizationContext : IAuthorizationContext
- {
- private readonly IAuthenticationRepository _authRepo;
- private readonly IUserManager _userManager;
-
- public AuthorizationContext(IAuthenticationRepository authRepo, IUserManager userManager)
- {
- _authRepo = authRepo;
- _userManager = userManager;
- }
-
- public AuthorizationInfo GetAuthorizationInfo(object requestContext)
- {
- return GetAuthorizationInfo((IRequest)requestContext);
- }
-
- public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext)
- {
- if (requestContext.Items.TryGetValue("AuthorizationInfo", out var cached))
- {
- return (AuthorizationInfo)cached;
- }
-
- return GetAuthorization(requestContext);
- }
-
- /// <summary>
- /// Gets the authorization.
- /// </summary>
- /// <param name="httpReq">The HTTP req.</param>
- /// <returns>Dictionary{System.StringSystem.String}.</returns>
- private AuthorizationInfo GetAuthorization(IRequest httpReq)
- {
- var auth = GetAuthorizationDictionary(httpReq);
-
- string deviceId = null;
- string device = null;
- string client = null;
- string version = null;
- string token = null;
-
- if (auth != null)
- {
- auth.TryGetValue("DeviceId", out deviceId);
- auth.TryGetValue("Device", out device);
- auth.TryGetValue("Client", out client);
- auth.TryGetValue("Version", out version);
- auth.TryGetValue("Token", out token);
- }
-
- if (string.IsNullOrEmpty(token))
- {
- token = httpReq.Headers["X-Emby-Token"];
- }
-
- if (string.IsNullOrEmpty(token))
- {
- token = httpReq.Headers["X-MediaBrowser-Token"];
- }
- if (string.IsNullOrEmpty(token))
- {
- token = httpReq.QueryString["api_key"];
- }
-
- var info = new AuthorizationInfo
- {
- Client = client,
- Device = device,
- DeviceId = deviceId,
- Version = version,
- Token = token
- };
-
- if (!string.IsNullOrWhiteSpace(token))
- {
- var result = _authRepo.Get(new AuthenticationInfoQuery
- {
- AccessToken = token
- });
-
- var tokenInfo = result.Items.Length > 0 ? result.Items[0] : null;
-
- if (tokenInfo != null)
- {
- var updateToken = false;
-
- // TODO: Remove these checks for IsNullOrWhiteSpace
- if (string.IsNullOrWhiteSpace(info.Client))
- {
- info.Client = tokenInfo.AppName;
- }
-
- if (string.IsNullOrWhiteSpace(info.DeviceId))
- {
- info.DeviceId = tokenInfo.DeviceId;
- }
-
- // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
- var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
-
- if (string.IsNullOrWhiteSpace(info.Device))
- {
- info.Device = tokenInfo.DeviceName;
- }
-
- else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
- {
- if (allowTokenInfoUpdate)
- {
- updateToken = true;
- tokenInfo.DeviceName = info.Device;
- }
- }
-
- if (string.IsNullOrWhiteSpace(info.Version))
- {
- info.Version = tokenInfo.AppVersion;
- }
- else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
- {
- if (allowTokenInfoUpdate)
- {
- updateToken = true;
- tokenInfo.AppVersion = info.Version;
- }
- }
-
- if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
- {
- tokenInfo.DateLastActivity = DateTime.UtcNow;
- updateToken = true;
- }
-
- if (!tokenInfo.UserId.Equals(Guid.Empty))
- {
- info.User = _userManager.GetUserById(tokenInfo.UserId);
-
- if (info.User != null && !string.Equals(info.User.Name, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
- {
- tokenInfo.UserName = info.User.Name;
- updateToken = true;
- }
- }
-
- if (updateToken)
- {
- _authRepo.Update(tokenInfo);
- }
- }
- httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
- }
-
- httpReq.Items["AuthorizationInfo"] = info;
-
- return info;
- }
-
- /// <summary>
- /// Gets the auth.
- /// </summary>
- /// <param name="httpReq">The HTTP req.</param>
- /// <returns>Dictionary{System.StringSystem.String}.</returns>
- private Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
- {
- var auth = httpReq.Headers["X-Emby-Authorization"];
-
- if (string.IsNullOrEmpty(auth))
- {
- auth = httpReq.Headers["Authorization"];
- }
-
- return GetAuthorization(auth);
- }
-
- /// <summary>
- /// Gets the authorization.
- /// </summary>
- /// <param name="authorizationHeader">The authorization header.</param>
- /// <returns>Dictionary{System.StringSystem.String}.</returns>
- private Dictionary<string, string> GetAuthorization(string authorizationHeader)
- {
- if (authorizationHeader == null) return null;
-
- var parts = authorizationHeader.Split(new[] { ' ' }, 2);
-
- // There should be at least to parts
- if (parts.Length != 2) return null;
-
- var acceptedNames = new[] { "MediaBrowser", "Emby" };
-
- // It has to be a digest request
- if (!acceptedNames.Contains(parts[0] ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- return null;
- }
-
- // Remove uptil the first space
- authorizationHeader = parts[1];
- parts = authorizationHeader.Split(',');
-
- var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- foreach (var item in parts)
- {
- var param = item.Trim().Split(new[] { '=' }, 2);
-
- if (param.Length == 2)
- {
- var value = NormalizeValue(param[1].Trim(new[] { '"' }));
- result.Add(param[0], value);
- }
- }
-
- return result;
- }
-
- private static string NormalizeValue(string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- return value;
- }
-
- return System.Net.WebUtility.HtmlEncode(value);
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs
index 81e11d312..a7647caf9 100644
--- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs
@@ -1,10 +1,13 @@
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Controller.Entities;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
namespace Emby.Server.Implementations.HttpServer.Security
{
@@ -21,35 +24,35 @@ namespace Emby.Server.Implementations.HttpServer.Security
_sessionManager = sessionManager;
}
- public SessionInfo GetSession(IRequest requestContext)
+ public async Task<SessionInfo> GetSession(HttpContext requestContext)
{
- var authorization = _authContext.GetAuthorizationInfo(requestContext);
+ var authorization = await _authContext.GetAuthorizationInfo(requestContext).ConfigureAwait(false);
var user = authorization.User;
- return _sessionManager.LogSessionActivity(authorization.Client, authorization.Version, authorization.DeviceId, authorization.Device, requestContext.RemoteIp, user);
- }
-
- private AuthenticationInfo GetTokenInfo(IRequest request)
- {
- request.Items.TryGetValue("OriginalAuthenticationInfo", out var info);
- return info as AuthenticationInfo;
+ return await _sessionManager.LogSessionActivity(
+ authorization.Client,
+ authorization.Version,
+ authorization.DeviceId,
+ authorization.Device,
+ requestContext.GetNormalizedRemoteIp().ToString(),
+ user).ConfigureAwait(false);
}
- public SessionInfo GetSession(object requestContext)
+ public Task<SessionInfo> GetSession(object requestContext)
{
- return GetSession((IRequest)requestContext);
+ return GetSession((HttpContext)requestContext);
}
- public User GetUser(IRequest requestContext)
+ public async Task<User?> GetUser(HttpContext requestContext)
{
- var session = GetSession(requestContext);
+ var session = await GetSession(requestContext).ConfigureAwait(false);
return session == null || session.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(session.UserId);
}
- public User GetUser(object requestContext)
+ public Task<User?> GetUser(object requestContext)
{
- return GetUser((IRequest)requestContext);
+ return GetUser(((HttpRequest)requestContext).HttpContext);
}
}
}
diff --git a/Emby.Server.Implementations/HttpServer/StreamWriter.cs b/Emby.Server.Implementations/HttpServer/StreamWriter.cs
deleted file mode 100644
index cb2e3580b..000000000
--- a/Emby.Server.Implementations/HttpServer/StreamWriter.cs
+++ /dev/null
@@ -1,119 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.HttpServer
-{
- /// <summary>
- /// Class StreamWriter
- /// </summary>
- public class StreamWriter : IAsyncStreamWriter, IHasHeaders
- {
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Gets or sets the source stream.
- /// </summary>
- /// <value>The source stream.</value>
- private Stream SourceStream { get; set; }
-
- private byte[] SourceBytes { get; set; }
-
- /// <summary>
- /// The _options
- /// </summary>
- private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
- /// <summary>
- /// Gets the options.
- /// </summary>
- /// <value>The options.</value>
- public IDictionary<string, string> Headers => _options;
-
- public Action OnComplete { get; set; }
- public Action OnError { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StreamWriter" /> class.
- /// </summary>
- /// <param name="source">The source.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="logger">The logger.</param>
- public StreamWriter(Stream source, string contentType)
- {
- if (string.IsNullOrEmpty(contentType))
- {
- throw new ArgumentNullException(nameof(contentType));
- }
-
- SourceStream = source;
-
- Headers["Content-Type"] = contentType;
-
- if (source.CanSeek)
- {
- Headers["Content-Length"] = source.Length.ToString(UsCulture);
- }
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StreamWriter"/> class.
- /// </summary>
- /// <param name="source">The source.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="logger">The logger.</param>
- public StreamWriter(byte[] source, string contentType, int contentLength)
- {
- if (string.IsNullOrEmpty(contentType))
- {
- throw new ArgumentNullException(nameof(contentType));
- }
-
- SourceBytes = source;
-
- Headers["Content-Type"] = contentType;
-
- Headers["Content-Length"] = contentLength.ToString(UsCulture);
- }
-
- public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
- {
- try
- {
- var bytes = SourceBytes;
-
- if (bytes != null)
- {
- await responseStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
- }
- else
- {
- using (var src = SourceStream)
- {
- await src.CopyToAsync(responseStream).ConfigureAwait(false);
- }
- }
- }
- catch
- {
- if (OnError != null)
- {
- OnError();
- }
-
- throw;
- }
- finally
- {
- if (OnComplete != null)
- {
- OnComplete();
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
index e9d0bac74..5f25f6980 100644
--- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
+++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
@@ -1,50 +1,76 @@
-using System;
+using System;
+using System.Buffers;
+using System.IO.Pipelines;
+using System.Net;
using System.Net.WebSockets;
using System.Text;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using Emby.Server.Implementations.Net;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
-using UtfUnknown;
namespace Emby.Server.Implementations.HttpServer
{
/// <summary>
- /// Class WebSocketConnection
+ /// Class WebSocketConnection.
/// </summary>
- public class WebSocketConnection : IWebSocketConnection
+ public class WebSocketConnection : IWebSocketConnection, IDisposable
{
- public event EventHandler<EventArgs> Closed;
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<WebSocketConnection> _logger;
/// <summary>
- /// The _socket
+ /// The json serializer options.
/// </summary>
- private readonly IWebSocket _socket;
+ private readonly JsonSerializerOptions _jsonOptions;
/// <summary>
- /// The _remote end point
+ /// The socket.
/// </summary>
- public string RemoteEndPoint { get; private set; }
+ private readonly WebSocket _socket;
/// <summary>
- /// The logger
+ /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
/// </summary>
- private readonly ILogger _logger;
+ /// <param name="logger">The logger.</param>
+ /// <param name="socket">The socket.</param>
+ /// <param name="remoteEndPoint">The remote end point.</param>
+ /// <param name="query">The query.</param>
+ public WebSocketConnection(
+ ILogger<WebSocketConnection> logger,
+ WebSocket socket,
+ IPAddress? remoteEndPoint,
+ IQueryCollection query)
+ {
+ _logger = logger;
+ _socket = socket;
+ RemoteEndPoint = remoteEndPoint;
+ QueryString = query;
+
+ _jsonOptions = JsonDefaults.Options;
+ LastActivityDate = DateTime.Now;
+ }
+
+ /// <inheritdoc />
+ public event EventHandler<EventArgs>? Closed;
/// <summary>
- /// The _json serializer
+ /// Gets the remote end point.
/// </summary>
- private readonly IJsonSerializer _jsonSerializer;
+ public IPAddress? RemoteEndPoint { get; }
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
- public Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
+ public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
/// <summary>
/// Gets the last activity date.
@@ -52,221 +78,172 @@ namespace Emby.Server.Implementations.HttpServer
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
- /// <summary>
- /// Gets the id.
- /// </summary>
- /// <value>The id.</value>
- public Guid Id { get; private set; }
+ /// <inheritdoc />
+ public DateTime LastKeepAliveDate { get; set; }
/// <summary>
- /// Gets or sets the URL.
+ /// Gets the query string.
/// </summary>
- /// <value>The URL.</value>
- public string Url { get; set; }
+ /// <value>The query string.</value>
+ public IQueryCollection QueryString { get; }
+
/// <summary>
- /// Gets or sets the query string.
+ /// Gets the state.
/// </summary>
- /// <value>The query string.</value>
- public QueryParamCollection QueryString { get; set; }
+ /// <value>The state.</value>
+ public WebSocketState State => _socket.State;
/// <summary>
- /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
+ /// Sends a message asynchronously.
/// </summary>
- /// <param name="socket">The socket.</param>
- /// <param name="remoteEndPoint">The remote end point.</param>
- /// <param name="jsonSerializer">The json serializer.</param>
- /// <param name="logger">The logger.</param>
- /// <exception cref="ArgumentNullException">socket</exception>
- public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
+ /// <typeparam name="T">The type of the message.</typeparam>
+ /// <param name="message">The message.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
{
- if (socket == null)
- {
- throw new ArgumentNullException(nameof(socket));
- }
- if (string.IsNullOrEmpty(remoteEndPoint))
- {
- throw new ArgumentNullException(nameof(remoteEndPoint));
- }
- if (jsonSerializer == null)
- {
- throw new ArgumentNullException(nameof(jsonSerializer));
- }
- if (logger == null)
- {
- throw new ArgumentNullException(nameof(logger));
- }
+ var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
+ return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
+ }
- Id = Guid.NewGuid();
- _jsonSerializer = jsonSerializer;
- _socket = socket;
- _socket.OnReceiveBytes = OnReceiveInternal;
+ /// <inheritdoc />
+ public async Task ProcessAsync(CancellationToken cancellationToken = default)
+ {
+ var pipe = new Pipe();
+ var writer = pipe.Writer;
- var memorySocket = socket as IMemoryWebSocket;
- if (memorySocket != null)
+ ValueWebSocketReceiveResult receiveresult;
+ do
{
- memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
- }
+ // Allocate at least 512 bytes from the PipeWriter
+ Memory<byte> memory = writer.GetMemory(512);
+ try
+ {
+ receiveresult = await _socket.ReceiveAsync(memory, cancellationToken).ConfigureAwait(false);
+ }
+ catch (WebSocketException ex)
+ {
+ _logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
+ break;
+ }
- RemoteEndPoint = remoteEndPoint;
- _logger = logger;
+ int bytesRead = receiveresult.Count;
+ if (bytesRead == 0)
+ {
+ break;
+ }
- socket.Closed += socket_Closed;
- }
+ // Tell the PipeWriter how much was read from the Socket
+ writer.Advance(bytesRead);
- void socket_Closed(object sender, EventArgs e)
- {
- Closed?.Invoke(this, EventArgs.Empty);
- }
+ // Make the data available to the PipeReader
+ FlushResult flushResult = await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
+ if (flushResult.IsCompleted)
+ {
+ // The PipeReader stopped reading
+ break;
+ }
- /// <summary>
- /// Called when [receive].
- /// </summary>
- /// <param name="bytes">The bytes.</param>
- private void OnReceiveInternal(byte[] bytes)
- {
- LastActivityDate = DateTime.UtcNow;
+ LastActivityDate = DateTime.UtcNow;
- if (OnReceive == null)
- {
- return;
+ if (receiveresult.EndOfMessage)
+ {
+ await ProcessInternal(pipe.Reader).ConfigureAwait(false);
+ }
}
- var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
+ while ((_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
+ && receiveresult.MessageType != WebSocketMessageType.Close);
- if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
- {
- OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
- }
- else
+ Closed?.Invoke(this, EventArgs.Empty);
+
+ if (_socket.State == WebSocketState.Open
+ || _socket.State == WebSocketState.CloseReceived
+ || _socket.State == WebSocketState.CloseSent)
{
- OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
+ await _socket.CloseAsync(
+ WebSocketCloseStatus.NormalClosure,
+ string.Empty,
+ cancellationToken).ConfigureAwait(false);
}
}
- /// <summary>
- /// Called when [receive].
- /// </summary>
- /// <param name="memory">The memory block.</param>
- /// <param name="length">The length of the memory block.</param>
- private void OnReceiveInternal(Memory<byte> memory, int length)
+ private async Task ProcessInternal(PipeReader reader)
{
- LastActivityDate = DateTime.UtcNow;
+ ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
+ ReadOnlySequence<byte> buffer = result.Buffer;
if (OnReceive == null)
{
+ // Tell the PipeReader how much of the buffer we have consumed
+ reader.AdvanceTo(buffer.End);
return;
}
- var bytes = memory.Slice(0, length).ToArray();
-
- var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
-
- if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
+ WebSocketMessage<object>? stub;
+ long bytesConsumed = 0;
+ try
{
- OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
+ stub = DeserializeWebSocketMessage(buffer, out bytesConsumed);
}
- else
+ catch (JsonException ex)
{
- OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
- }
- }
-
- private void OnReceiveInternal(string message)
- {
- LastActivityDate = DateTime.UtcNow;
-
- if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
- {
- // This info is useful sometimes but also clogs up the log
- _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
+ // Tell the PipeReader how much of the buffer we have consumed
+ reader.AdvanceTo(buffer.End);
+ _logger.LogError(ex, "Error processing web socket message: {Data}", Encoding.UTF8.GetString(buffer));
return;
}
- if (OnReceive == null)
+ if (stub == null)
{
+ _logger.LogError("Error processing web socket message");
return;
}
- try
- {
- var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
+ // Tell the PipeReader how much of the buffer we have consumed
+ reader.AdvanceTo(buffer.GetPosition(bytesConsumed));
- var info = new WebSocketMessageInfo
- {
- MessageType = stub.MessageType,
- Data = stub.Data == null ? null : stub.Data.ToString(),
- Connection = this
- };
+ _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
- OnReceive(info);
- }
- catch (Exception ex)
+ if (stub.MessageType == SessionMessageType.KeepAlive)
{
- _logger.LogError(ex, "Error processing web socket message");
+ await SendKeepAliveResponse().ConfigureAwait(false);
}
- }
-
- /// <summary>
- /// Sends a message asynchronously.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="message">The message.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">message</exception>
- public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
- {
- if (message == null)
+ else
{
- throw new ArgumentNullException(nameof(message));
+ await OnReceive(
+ new WebSocketMessageInfo
+ {
+ MessageType = stub.MessageType,
+ Data = stub.Data?.ToString(), // Data can be null
+ Connection = this
+ }).ConfigureAwait(false);
}
-
- var json = _jsonSerializer.SerializeToString(message);
-
- return SendAsync(json, cancellationToken);
}
- /// <summary>
- /// Sends a message asynchronously.
- /// </summary>
- /// <param name="buffer">The buffer.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
+ internal WebSocketMessage<object>? DeserializeWebSocketMessage(ReadOnlySequence<byte> bytes, out long bytesConsumed)
{
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- return _socket.SendAsync(buffer, true, cancellationToken);
+ var jsonReader = new Utf8JsonReader(bytes);
+ var ret = JsonSerializer.Deserialize<WebSocketMessage<object>>(ref jsonReader, _jsonOptions);
+ bytesConsumed = jsonReader.BytesConsumed;
+ return ret;
}
- public Task SendAsync(string text, CancellationToken cancellationToken)
+ private Task SendKeepAliveResponse()
{
- if (string.IsNullOrEmpty(text))
- {
- throw new ArgumentNullException(nameof(text));
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- return _socket.SendAsync(text, true, cancellationToken);
+ LastKeepAliveDate = DateTime.UtcNow;
+ return SendAsync(
+ new WebSocketMessage<string>
+ {
+ MessageId = Guid.NewGuid(),
+ MessageType = SessionMessageType.KeepAlive
+ }, CancellationToken.None);
}
- /// <summary>
- /// Gets the state.
- /// </summary>
- /// <value>The state.</value>
- public WebSocketState State => _socket.State;
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
+ /// <inheritdoc />
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
new file mode 100644
index 000000000..f86bfd755
--- /dev/null
+++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
@@ -0,0 +1,90 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.WebSockets;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.HttpServer
+{
+ public class WebSocketManager : IWebSocketManager
+ {
+ private readonly IWebSocketListener[] _webSocketListeners;
+ private readonly IAuthService _authService;
+ private readonly ILogger<WebSocketManager> _logger;
+ private readonly ILoggerFactory _loggerFactory;
+
+ public WebSocketManager(
+ IAuthService authService,
+ IEnumerable<IWebSocketListener> webSocketListeners,
+ ILogger<WebSocketManager> logger,
+ ILoggerFactory loggerFactory)
+ {
+ _webSocketListeners = webSocketListeners.ToArray();
+ _authService = authService;
+ _logger = logger;
+ _loggerFactory = loggerFactory;
+ }
+
+ /// <inheritdoc />
+ public async Task WebSocketRequestHandler(HttpContext context)
+ {
+ _ = await _authService.Authenticate(context.Request).ConfigureAwait(false);
+ try
+ {
+ _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
+
+ WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
+
+ using var connection = new WebSocketConnection(
+ _loggerFactory.CreateLogger<WebSocketConnection>(),
+ webSocket,
+ context.Connection.RemoteIpAddress,
+ context.Request.Query)
+ {
+ OnReceive = ProcessWebSocketMessageReceived
+ };
+
+ var tasks = new Task[_webSocketListeners.Length];
+ for (var i = 0; i < _webSocketListeners.Length; ++i)
+ {
+ tasks[i] = _webSocketListeners[i].ProcessWebSocketConnectedAsync(connection);
+ }
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+
+ await connection.ProcessAsync().ConfigureAwait(false);
+ _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
+ }
+ catch (Exception ex) // Otherwise ASP.Net will ignore the exception
+ {
+ _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
+ if (!context.Response.HasStarted)
+ {
+ context.Response.StatusCode = 500;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Processes the web socket message received.
+ /// </summary>
+ /// <param name="result">The result.</param>
+ private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
+ {
+ var tasks = new Task[_webSocketListeners.Length];
+ for (var i = 0; i < _webSocketListeners.Length; ++i)
+ {
+ tasks[i] = _webSocketListeners[i].ProcessMessageAsync(result);
+ }
+
+ return Task.WhenAll(tasks);
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs
index 48b34a3a0..545d73e05 100644
--- a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs
+++ b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs
@@ -1,9 +1,13 @@
+#pragma warning disable CS1591
+
namespace Emby.Server.Implementations.IO
{
public class ExtendedFileSystemInfo
{
public bool IsHidden { get; set; }
+
public bool IsReadOnly { get; set; }
+
public bool Exists { get; set; }
}
}
diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs
index 73242d0ad..47a83d77c 100644
--- a/Emby.Server.Implementations/IO/FileRefresher.cs
+++ b/Emby.Server.Implementations/IO/FileRefresher.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -6,37 +10,36 @@ using System.Threading;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.IO
{
public class FileRefresher : IDisposable
{
- private ILogger Logger { get; set; }
- private ILibraryManager LibraryManager { get; set; }
- private IServerConfigurationManager ConfigurationManager { get; set; }
+ private readonly ILogger _logger;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IServerConfigurationManager _configurationManager;
+
private readonly List<string> _affectedPaths = new List<string>();
- private Timer _timer;
private readonly object _timerLock = new object();
- public string Path { get; private set; }
-
- public event EventHandler<EventArgs> Completed;
+ private Timer _timer;
+ private bool _disposed;
public FileRefresher(string path, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger logger)
{
logger.LogDebug("New file refresher created for {0}", path);
Path = path;
- ConfigurationManager = configurationManager;
- LibraryManager = libraryManager;
- Logger = logger;
+ _configurationManager = configurationManager;
+ _libraryManager = libraryManager;
+ _logger = logger;
AddPath(path);
}
+ public event EventHandler<EventArgs> Completed;
+
+ public string Path { get; private set; }
+
private void AddAffectedPath(string path)
{
if (string.IsNullOrEmpty(path))
@@ -61,6 +64,7 @@ namespace Emby.Server.Implementations.IO
{
AddAffectedPath(path);
}
+
RestartTimer();
}
@@ -80,11 +84,11 @@ namespace Emby.Server.Implementations.IO
if (_timer == null)
{
- _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
+ _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
}
else
{
- _timer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
+ _timer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
}
}
}
@@ -93,7 +97,7 @@ namespace Emby.Server.Implementations.IO
{
lock (_timerLock)
{
- Logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
+ _logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
Path = path;
AddAffectedPath(path);
@@ -103,6 +107,7 @@ namespace Emby.Server.Implementations.IO
AddAffectedPath(affectedFile);
}
}
+
RestartTimer();
}
@@ -115,7 +120,7 @@ namespace Emby.Server.Implementations.IO
paths = _affectedPaths.ToList();
}
- Logger.LogDebug("Timer stopped.");
+ _logger.LogDebug("Timer stopped.");
DisposeTimer();
Completed?.Invoke(this, EventArgs.Empty);
@@ -126,7 +131,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error processing directory changes");
+ _logger.LogError(ex, "Error processing directory changes");
}
}
@@ -146,7 +151,7 @@ namespace Emby.Server.Implementations.IO
continue;
}
- Logger.LogInformation("{name} ({path}) will be refreshed.", item.Name, item.Path);
+ _logger.LogInformation("{Name} ({Path}) will be refreshed.", item.Name, item.Path);
try
{
@@ -157,11 +162,11 @@ namespace Emby.Server.Implementations.IO
// For now swallow and log.
// Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
// Should we remove it from it's parent?
- Logger.LogError(ex, "Error refreshing {name}", item.Name);
+ _logger.LogError(ex, "Error refreshing {Name}", item.Name);
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error refreshing {name}", item.Name);
+ _logger.LogError(ex, "Error refreshing {Name}", item.Name);
}
}
}
@@ -177,7 +182,7 @@ namespace Emby.Server.Implementations.IO
while (item == null && !string.IsNullOrEmpty(path))
{
- item = LibraryManager.FindByPath(path, null);
+ item = _libraryManager.FindByPath(path, null);
path = System.IO.Path.GetDirectoryName(path);
}
@@ -211,11 +216,12 @@ namespace Emby.Server.Implementations.IO
}
}
- private bool _disposed;
+ /// <inheritdoc />
public void Dispose()
{
_disposed = true;
DisposeTimer();
+ GC.SuppressFinalize(this);
}
}
}
diff --git a/Emby.Server.Implementations/IO/IsoManager.cs b/Emby.Server.Implementations/IO/IsoManager.cs
deleted file mode 100644
index f0a15097c..000000000
--- a/Emby.Server.Implementations/IO/IsoManager.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Server.Implementations.IO
-{
- /// <summary>
- /// Class IsoManager
- /// </summary>
- public class IsoManager : IIsoManager
- {
- /// <summary>
- /// The _mounters
- /// </summary>
- private readonly List<IIsoMounter> _mounters = new List<IIsoMounter>();
-
- /// <summary>
- /// Mounts the specified iso path.
- /// </summary>
- /// <param name="isoPath">The iso path.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>IsoMount.</returns>
- /// <exception cref="ArgumentNullException">isoPath</exception>
- /// <exception cref="ArgumentException"></exception>
- public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(isoPath))
- {
- throw new ArgumentNullException(nameof(isoPath));
- }
-
- var mounter = _mounters.FirstOrDefault(i => i.CanMount(isoPath));
-
- if (mounter == null)
- {
- throw new ArgumentException(string.Format("No mounters are able to mount {0}", isoPath));
- }
-
- return mounter.Mount(isoPath, cancellationToken);
- }
-
- /// <summary>
- /// Determines whether this instance can mount the specified path.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns>
- public bool CanMount(string path)
- {
- return _mounters.Any(i => i.CanMount(path));
- }
-
- /// <summary>
- /// Adds the parts.
- /// </summary>
- /// <param name="mounters">The mounters.</param>
- public void AddParts(IEnumerable<IIsoMounter> mounters)
- {
- _mounters.AddRange(mounters);
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- foreach (var mounter in _mounters)
- {
- mounter.Dispose();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs
index d47342511..e9d069cd3 100644
--- a/Emby.Server.Implementations/IO/LibraryMonitor.cs
+++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs
@@ -1,67 +1,64 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
+using Emby.Server.Implementations.Library;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.IO
{
public class LibraryMonitor : ILibraryMonitor
{
+ private readonly ILogger<LibraryMonitor> _logger;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IServerConfigurationManager _configurationManager;
+ private readonly IFileSystem _fileSystem;
+
/// <summary>
- /// The file system watchers
+ /// The file system watchers.
/// </summary>
private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
+
/// <summary>
- /// The affected paths
+ /// The affected paths.
/// </summary>
private readonly List<FileRefresher> _activeRefreshers = new List<FileRefresher>();
/// <summary>
- /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
+ /// A dynamic list of paths that should be ignored. Added to during our own file system modifications.
/// </summary>
private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ private bool _disposed = false;
+
/// <summary>
- /// Any file name ending in any of these will be ignored by the watchers
+ /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
/// </summary>
- private static readonly HashSet<string> _alwaysIgnoreFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "small.jpg",
- "albumart.jpg",
-
- // WMC temp recording directories that will constantly be written to
- "TempRec",
- "TempSBE"
- };
-
- private static readonly string[] _alwaysIgnoreSubstrings = new string[]
- {
- // Synology
- "eaDir",
- "#recycle",
- ".wd_tv",
- ".actors"
- };
-
- private static readonly HashSet<string> _alwaysIgnoreExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ /// <param name="logger">The logger.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ public LibraryMonitor(
+ ILogger<LibraryMonitor> logger,
+ ILibraryManager libraryManager,
+ IServerConfigurationManager configurationManager,
+ IFileSystem fileSystem)
{
- // thumbs.db
- ".db",
-
- // bts sync files
- ".bts",
- ".sync"
- };
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _configurationManager = configurationManager;
+ _fileSystem = fileSystem;
+ }
/// <summary>
/// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
@@ -97,7 +94,7 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(path));
}
- // This is an arbitraty amount of time, but delay it because file system writes often trigger events long after the file was actually written to.
+ // This is an arbitrary amount of time, but delay it because file system writes often trigger events long after the file was actually written to.
// Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
// But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
await Task.Delay(45000).ConfigureAwait(false);
@@ -112,40 +109,11 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error in ReportFileSystemChanged for {path}", path);
+ _logger.LogError(ex, "Error in ReportFileSystemChanged for {Path}", path);
}
}
}
- /// <summary>
- /// Gets or sets the logger.
- /// </summary>
- /// <value>The logger.</value>
- private ILogger Logger { get; set; }
-
- private ILibraryManager LibraryManager { get; set; }
- private IServerConfigurationManager ConfigurationManager { get; set; }
-
- private readonly IFileSystem _fileSystem;
- private readonly IEnvironmentInfo _environmentInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
- /// </summary>
- public LibraryMonitor(
- ILoggerFactory loggerFactory,
- ILibraryManager libraryManager,
- IServerConfigurationManager configurationManager,
- IFileSystem fileSystem,
- IEnvironmentInfo environmentInfo)
- {
- LibraryManager = libraryManager;
- Logger = loggerFactory.CreateLogger(GetType().Name);
- ConfigurationManager = configurationManager;
- _fileSystem = fileSystem;
- _environmentInfo = environmentInfo;
- }
-
private bool IsLibraryMonitorEnabled(BaseItem item)
{
if (item is BasePluginFolder)
@@ -153,7 +121,7 @@ namespace Emby.Server.Implementations.IO
return false;
}
- var options = LibraryManager.GetLibraryOptions(item);
+ var options = _libraryManager.GetLibraryOptions(item);
if (options != null)
{
@@ -165,12 +133,12 @@ namespace Emby.Server.Implementations.IO
public void Start()
{
- LibraryManager.ItemAdded += LibraryManager_ItemAdded;
- LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
+ _libraryManager.ItemAdded += OnLibraryManagerItemAdded;
+ _libraryManager.ItemRemoved += OnLibraryManagerItemRemoved;
- var pathsToWatch = new List<string> { };
+ var pathsToWatch = new List<string>();
- var paths = LibraryManager
+ var paths = _libraryManager
.RootFolder
.Children
.Where(IsLibraryMonitorEnabled)
@@ -207,7 +175,7 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
- void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
+ private void OnLibraryManagerItemRemoved(object sender, ItemChangeEventArgs e)
{
if (e.Parent is AggregateFolder)
{
@@ -220,7 +188,7 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
- void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
+ private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e)
{
if (e.Parent is AggregateFolder)
{
@@ -235,7 +203,7 @@ namespace Emby.Server.Implementations.IO
/// <param name="lst">The LST.</param>
/// <param name="path">The path.</param>
/// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">path</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="path"/> is <c>null</c>.</exception>
private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
{
if (string.IsNullOrEmpty(path))
@@ -247,7 +215,7 @@ namespace Emby.Server.Implementations.IO
return lst.Any(str =>
{
- //this should be a little quicker than examining each actual parent folder...
+ // this should be a little quicker than examining each actual parent folder...
var compare = str.TrimEnd(Path.DirectorySeparatorChar);
return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
@@ -263,22 +231,7 @@ namespace Emby.Server.Implementations.IO
if (!Directory.Exists(path))
{
// Seeing a crash in the mono runtime due to an exception being thrown on a different thread
- Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path);
- return;
- }
-
- if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
- {
- if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
- {
- // not supported
- return;
- }
- }
-
- if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Android)
- {
- // causing crashing
+ _logger.LogInformation("Skipping realtime monitor for {Path} because the path does not exist", path);
return;
}
@@ -295,38 +248,35 @@ namespace Emby.Server.Implementations.IO
{
var newWatcher = new FileSystemWatcher(path, "*")
{
- IncludeSubdirectories = true
+ IncludeSubdirectories = true,
+ InternalBufferSize = 65536,
+ NotifyFilter = NotifyFilters.CreationTime |
+ NotifyFilters.DirectoryName |
+ NotifyFilters.FileName |
+ NotifyFilters.LastWrite |
+ NotifyFilters.Size |
+ NotifyFilters.Attributes
};
- newWatcher.InternalBufferSize = 65536;
-
- newWatcher.NotifyFilter = NotifyFilters.CreationTime |
- NotifyFilters.DirectoryName |
- NotifyFilters.FileName |
- NotifyFilters.LastWrite |
- NotifyFilters.Size |
- NotifyFilters.Attributes;
-
- newWatcher.Created += watcher_Changed;
- newWatcher.Deleted += watcher_Changed;
- newWatcher.Renamed += watcher_Changed;
- newWatcher.Changed += watcher_Changed;
- newWatcher.Error += watcher_Error;
+ newWatcher.Created += OnWatcherChanged;
+ newWatcher.Deleted += OnWatcherChanged;
+ newWatcher.Renamed += OnWatcherChanged;
+ newWatcher.Changed += OnWatcherChanged;
+ newWatcher.Error += OnWatcherError;
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
- Logger.LogInformation("Watching directory " + path);
+ _logger.LogInformation("Watching directory " + path);
}
else
{
DisposeWatcher(newWatcher, false);
}
-
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error watching path: {path}", path);
+ _logger.LogError(ex, "Error watching path: {path}", path);
}
});
}
@@ -352,33 +302,17 @@ namespace Emby.Server.Implementations.IO
{
using (watcher)
{
- Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path);
+ _logger.LogInformation("Stopping directory watching for path {Path}", watcher.Path);
- watcher.Created -= watcher_Changed;
- watcher.Deleted -= watcher_Changed;
- watcher.Renamed -= watcher_Changed;
- watcher.Changed -= watcher_Changed;
- watcher.Error -= watcher_Error;
+ watcher.Created -= OnWatcherChanged;
+ watcher.Deleted -= OnWatcherChanged;
+ watcher.Renamed -= OnWatcherChanged;
+ watcher.Changed -= OnWatcherChanged;
+ watcher.Error -= OnWatcherError;
- try
- {
- watcher.EnableRaisingEvents = false;
- }
- catch (InvalidOperationException)
- {
- // Seeing this under mono on linux sometimes
- // Collection was modified; enumeration operation may not execute.
- }
+ watcher.EnableRaisingEvents = false;
}
}
- catch (NotImplementedException)
- {
- // the dispose method on FileSystemWatcher is sometimes throwing NotImplementedException on Xamarin Android
- }
- catch
- {
-
- }
finally
{
if (removeFromList)
@@ -394,7 +328,7 @@ namespace Emby.Server.Implementations.IO
/// <param name="watcher">The watcher.</param>
private void RemoveWatcherFromList(FileSystemWatcher watcher)
{
- _fileSystemWatchers.TryRemove(watcher.Path, out var removed);
+ _fileSystemWatchers.TryRemove(watcher.Path, out _);
}
/// <summary>
@@ -402,12 +336,12 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
- void watcher_Error(object sender, ErrorEventArgs e)
+ private void OnWatcherError(object sender, ErrorEventArgs e)
{
var ex = e.GetException();
var dw = (FileSystemWatcher)sender;
- Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path);
+ _logger.LogError(ex, "Error in Directory watcher for: {Path}", dw.Path);
DisposeWatcher(dw, true);
}
@@ -417,19 +351,15 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
- void watcher_Changed(object sender, FileSystemEventArgs e)
+ private void OnWatcherChanged(object sender, FileSystemEventArgs e)
{
try
{
- //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
-
- var path = e.FullPath;
-
- ReportFileSystemChanged(path);
+ ReportFileSystemChanged(e.FullPath);
}
catch (Exception ex)
{
- Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
+ _logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
}
}
@@ -440,12 +370,7 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(path));
}
- var filename = Path.GetFileName(path);
-
- var monitorPath = !string.IsNullOrEmpty(filename) &&
- !_alwaysIgnoreFiles.Contains(filename) &&
- !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path)) &&
- _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
+ var monitorPath = !IgnorePatterns.ShouldIgnore(path);
// Ignore certain files
var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
@@ -455,29 +380,25 @@ namespace Emby.Server.Implementations.IO
{
if (_fileSystem.AreEqual(i, path))
{
- Logger.LogDebug("Ignoring change to {path}", path);
+ _logger.LogDebug("Ignoring change to {Path}", path);
return true;
}
if (_fileSystem.ContainsSubPath(i, path))
{
- Logger.LogDebug("Ignoring change to {path}", path);
+ _logger.LogDebug("Ignoring change to {Path}", path);
return true;
}
// Go up a level
var parent = Path.GetDirectoryName(i);
- if (!string.IsNullOrEmpty(parent))
+ if (!string.IsNullOrEmpty(parent) && _fileSystem.AreEqual(parent, path))
{
- if (_fileSystem.AreEqual(parent, path))
- {
- Logger.LogDebug("Ignoring change to {path}", path);
- return true;
- }
+ _logger.LogDebug("Ignoring change to {Path}", path);
+ return true;
}
return false;
-
}))
{
monitorPath = false;
@@ -496,8 +417,7 @@ namespace Emby.Server.Implementations.IO
lock (_activeRefreshers)
{
- var refreshers = _activeRefreshers.ToList();
- foreach (var refresher in refreshers)
+ foreach (var refresher in _activeRefreshers)
{
// Path is already being refreshed
if (_fileSystem.AreEqual(path, refresher.Path))
@@ -528,7 +448,7 @@ namespace Emby.Server.Implementations.IO
}
}
- var newRefresher = new FileRefresher(path, ConfigurationManager, LibraryManager, Logger);
+ var newRefresher = new FileRefresher(path, _configurationManager, _libraryManager, _logger);
newRefresher.Completed += NewRefresher_Completed;
_activeRefreshers.Add(newRefresher);
}
@@ -545,8 +465,8 @@ namespace Emby.Server.Implementations.IO
/// </summary>
public void Stop()
{
- LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
- LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
+ _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
+ _libraryManager.ItemRemoved -= OnLibraryManagerItemRemoved;
foreach (var watcher in _fileSystemWatchers.Values.ToList())
{
@@ -574,17 +494,18 @@ namespace Emby.Server.Implementations.IO
{
refresher.Dispose();
}
+
_activeRefreshers.Clear();
}
}
- private bool _disposed;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
@@ -606,24 +527,4 @@ namespace Emby.Server.Implementations.IO
_disposed = true;
}
}
-
- public class LibraryMonitorStartup : IServerEntryPoint
- {
- private readonly ILibraryMonitor _monitor;
-
- public LibraryMonitorStartup(ILibraryMonitor monitor)
- {
- _monitor = monitor;
- }
-
- public Task RunAsync()
- {
- _monitor.Start();
- return Task.CompletedTask;
- }
-
- public void Dispose()
- {
- }
- }
}
diff --git a/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs b/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs
new file mode 100644
index 000000000..c51cf0545
--- /dev/null
+++ b/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs
@@ -0,0 +1,35 @@
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Plugins;
+
+namespace Emby.Server.Implementations.IO
+{
+ /// <summary>
+ /// <see cref="IServerEntryPoint" /> which is responsible for starting the library monitor.
+ /// </summary>
+ public sealed class LibraryMonitorStartup : IServerEntryPoint
+ {
+ private readonly ILibraryMonitor _monitor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LibraryMonitorStartup"/> class.
+ /// </summary>
+ /// <param name="monitor">The library monitor.</param>
+ public LibraryMonitorStartup(ILibraryMonitor monitor)
+ {
+ _monitor = monitor;
+ }
+
+ /// <inheritdoc />
+ public Task RunAsync()
+ {
+ _monitor.Start();
+ return Task.CompletedTask;
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
index a64dfb607..eeee28842 100644
--- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs
+++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
@@ -1,46 +1,34 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Diagnostics;
+using System.Globalization;
using System.IO;
using System.Linq;
-using System.Text;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.IO
{
/// <summary>
- /// Class ManagedFileSystem
+ /// Class ManagedFileSystem.
/// </summary>
public class ManagedFileSystem : IFileSystem
{
- protected ILogger Logger;
+ private readonly ILogger<ManagedFileSystem> _logger;
- private readonly bool _supportsAsyncFileStreams;
- private char[] _invalidFileNameChars;
private readonly List<IShortcutHandler> _shortcutHandlers = new List<IShortcutHandler>();
-
private readonly string _tempPath;
-
- private readonly IEnvironmentInfo _environmentInfo;
- private readonly bool _isEnvironmentCaseInsensitive;
+ private static readonly bool _isEnvironmentCaseInsensitive = OperatingSystem.IsWindows();
public ManagedFileSystem(
- ILoggerFactory loggerFactory,
- IEnvironmentInfo environmentInfo,
+ ILogger<ManagedFileSystem> logger,
IApplicationPaths applicationPaths)
{
- Logger = loggerFactory.CreateLogger("FileSystem");
- _supportsAsyncFileStreams = true;
+ _logger = logger;
_tempPath = applicationPaths.TempDirectory;
- _environmentInfo = environmentInfo;
-
- SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
-
- _isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
}
public virtual void AddShortcutHandler(IShortcutHandler handler)
@@ -48,26 +36,12 @@ namespace Emby.Server.Implementations.IO
_shortcutHandlers.Add(handler);
}
- protected void SetInvalidFileNameChars(bool enableManagedInvalidFileNameChars)
- {
- if (enableManagedInvalidFileNameChars)
- {
- _invalidFileNameChars = Path.GetInvalidFileNameChars();
- }
- else
- {
- // Be consistent across platforms because the windows server will fail to query network shares that don't follow windows conventions
- // https://referencesource.microsoft.com/#mscorlib/system/io/path.cs
- _invalidFileNameChars = new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' };
- }
- }
-
/// <summary>
/// Determines whether the specified filename is shortcut.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">filename</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
public virtual bool IsShortcut(string filename)
{
if (string.IsNullOrEmpty(filename))
@@ -84,8 +58,8 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">filename</exception>
- public virtual string ResolveShortcut(string filename)
+ /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
+ public virtual string? ResolveShortcut(string filename)
{
if (string.IsNullOrEmpty(filename))
{
@@ -93,25 +67,27 @@ namespace Emby.Server.Implementations.IO
}
var extension = Path.GetExtension(filename);
- var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
+ var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
- if (handler != null)
- {
- return handler.Resolve(filename);
- }
-
- return null;
+ return handler?.Resolve(filename);
}
public virtual string MakeAbsolutePath(string folderPath, string filePath)
{
- if (string.IsNullOrWhiteSpace(filePath)) return filePath;
+ // path is actually a stream
+ if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.Ordinal))
+ {
+ return filePath;
+ }
- if (filePath.Contains(@"://")) return filePath; //stream
- if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/') return filePath; //absolute local path
+ if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/')
+ {
+ // absolute local path
+ return filePath;
+ }
// unc path
- if (filePath.StartsWith("\\\\"))
+ if (filePath.StartsWith("\\\\", StringComparison.Ordinal))
{
return filePath;
}
@@ -119,18 +95,19 @@ namespace Emby.Server.Implementations.IO
var firstChar = filePath[0];
if (firstChar == '/')
{
- // For this we don't really know.
+ // for this we don't really know
return filePath;
}
- if (firstChar == '\\') //relative path
+
+ // relative path
+ if (firstChar == '\\')
{
filePath = filePath.Substring(1);
}
+
try
{
- string path = System.IO.Path.Combine(folderPath, filePath);
- path = System.IO.Path.GetFullPath(path);
- return path;
+ return Path.GetFullPath(Path.Combine(folderPath, filePath));
}
catch (ArgumentException)
{
@@ -151,11 +128,7 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="shortcutPath">The shortcut path.</param>
/// <param name="target">The target.</param>
- /// <exception cref="ArgumentNullException">
- /// shortcutPath
- /// or
- /// target
- /// </exception>
+ /// <exception cref="ArgumentNullException">The shortcutPath or target is null.</exception>
public virtual void CreateShortcut(string shortcutPath, string target)
{
if (string.IsNullOrEmpty(shortcutPath))
@@ -169,7 +142,7 @@ namespace Emby.Server.Implementations.IO
}
var extension = Path.GetExtension(shortcutPath);
- var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
+ var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
if (handler != null)
{
@@ -247,27 +220,44 @@ namespace Emby.Server.Implementations.IO
private FileSystemMetadata GetFileSystemMetadata(FileSystemInfo info)
{
- var result = new FileSystemMetadata();
-
- result.Exists = info.Exists;
- result.FullName = info.FullName;
- result.Extension = info.Extension;
- result.Name = info.Name;
+ var result = new FileSystemMetadata
+ {
+ Exists = info.Exists,
+ FullName = info.FullName,
+ Extension = info.Extension,
+ Name = info.Name
+ };
if (result.Exists)
{
result.IsDirectory = info is DirectoryInfo || (info.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
- //if (!result.IsDirectory)
- //{
+ // if (!result.IsDirectory)
+ // {
// result.IsHidden = (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
- //}
+ // }
- var fileInfo = info as FileInfo;
- if (fileInfo != null)
+ if (info is FileInfo fileInfo)
{
result.Length = fileInfo.Length;
- result.DirectoryName = fileInfo.DirectoryName;
+
+ // Issue #2354 get the size of files behind symbolic links. Also Enum.HasFlag is bad as it boxes!
+ if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
+ {
+ try
+ {
+ using (var fileHandle = File.OpenHandle(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
+ {
+ result.Length = RandomAccess.GetLength(fileHandle);
+ }
+ }
+ catch (FileNotFoundException ex)
+ {
+ // Dangling symlinks cannot be detected before opening the file unfortunately...
+ _logger.LogError(ex, "Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", fileInfo.FullName);
+ result.Exists = false;
+ }
+ }
}
result.CreationTimeUtc = GetCreationTimeUtc(info);
@@ -301,21 +291,42 @@ namespace Emby.Server.Implementations.IO
}
/// <summary>
- /// Takes a filename and removes invalid characters
+ /// Takes a filename and removes invalid characters.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">filename</exception>
- public virtual string GetValidFilename(string filename)
+ /// <exception cref="ArgumentNullException">The filename is null.</exception>
+ public string GetValidFilename(string filename)
{
- var builder = new StringBuilder(filename);
-
- foreach (var c in _invalidFileNameChars)
+ var invalid = Path.GetInvalidFileNameChars();
+ var first = filename.IndexOfAny(invalid);
+ if (first == -1)
{
- builder = builder.Replace(c, ' ');
+ // Fast path for clean strings
+ return filename;
}
- return builder.ToString();
+ return string.Create(
+ filename.Length,
+ (filename, invalid, first),
+ (chars, state) =>
+ {
+ state.filename.AsSpan().CopyTo(chars);
+
+ chars[state.first++] = ' ';
+
+ var len = chars.Length;
+ foreach (var c in state.invalid)
+ {
+ for (int i = state.first; i < len; i++)
+ {
+ if (chars[i] == c)
+ {
+ chars[i] = ' ';
+ }
+ }
+ }
+ });
}
/// <summary>
@@ -332,7 +343,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
+ _logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -371,7 +382,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
+ _logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -386,90 +397,9 @@ namespace Emby.Server.Implementations.IO
return GetLastWriteTimeUtc(GetFileSystemInfo(path));
}
- /// <summary>
- /// Gets the file stream.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="mode">The mode.</param>
- /// <param name="access">The access.</param>
- /// <param name="share">The share.</param>
- /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
- /// <returns>FileStream.</returns>
- public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
- {
- if (_supportsAsyncFileStreams && isAsync)
- {
- return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
- }
-
- return GetFileStream(path, mode, access, share, FileOpenOptions.None);
- }
-
- public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
- => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions));
-
- private static FileOptions GetFileOptions(FileOpenOptions mode)
- {
- var val = (int)mode;
- return (FileOptions)val;
- }
-
- private static FileMode GetFileMode(FileOpenMode mode)
- {
- switch (mode)
- {
- //case FileOpenMode.Append:
- // return FileMode.Append;
- case FileOpenMode.Create:
- return FileMode.Create;
- case FileOpenMode.CreateNew:
- return FileMode.CreateNew;
- case FileOpenMode.Open:
- return FileMode.Open;
- case FileOpenMode.OpenOrCreate:
- return FileMode.OpenOrCreate;
- //case FileOpenMode.Truncate:
- // return FileMode.Truncate;
- default:
- throw new Exception("Unrecognized FileOpenMode");
- }
- }
-
- private static FileAccess GetFileAccess(FileAccessMode mode)
- {
- switch (mode)
- {
- //case FileAccessMode.ReadWrite:
- // return FileAccess.ReadWrite;
- case FileAccessMode.Write:
- return FileAccess.Write;
- case FileAccessMode.Read:
- return FileAccess.Read;
- default:
- throw new Exception("Unrecognized FileAccessMode");
- }
- }
-
- private static FileShare GetFileShare(FileShareMode mode)
- {
- switch (mode)
- {
- case FileShareMode.ReadWrite:
- return FileShare.ReadWrite;
- case FileShareMode.Write:
- return FileShare.Write;
- case FileShareMode.Read:
- return FileShare.Read;
- case FileShareMode.None:
- return FileShare.None;
- default:
- throw new Exception("Unrecognized FileShareMode");
- }
- }
-
public virtual void SetHidden(string path, bool isHidden)
{
- if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+ if (!OperatingSystem.IsWindows())
{
return;
}
@@ -491,33 +421,9 @@ namespace Emby.Server.Implementations.IO
}
}
- public virtual void SetReadOnly(string path, bool isReadOnly)
+ public virtual void SetAttributes(string path, bool isHidden, bool readOnly)
{
- if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
- {
- return;
- }
-
- var info = GetExtendedFileSystemInfo(path);
-
- if (info.Exists && info.IsReadOnly != isReadOnly)
- {
- if (isReadOnly)
- {
- File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
- }
- else
- {
- var attributes = File.GetAttributes(path);
- attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
- File.SetAttributes(path, attributes);
- }
- }
- }
-
- public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
- {
- if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+ if (!OperatingSystem.IsWindows())
{
return;
}
@@ -529,14 +435,14 @@ namespace Emby.Server.Implementations.IO
return;
}
- if (info.IsReadOnly == isReadOnly && info.IsHidden == isHidden)
+ if (info.IsReadOnly == readOnly && info.IsHidden == isHidden)
{
return;
}
var attributes = File.GetAttributes(path);
- if (isReadOnly)
+ if (readOnly)
{
attributes = attributes | FileAttributes.ReadOnly;
}
@@ -579,7 +485,7 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(file2));
}
- var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
+ var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
// Copying over will fail against hidden files
SetHidden(file1, false);
@@ -604,26 +510,9 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(path));
}
- var separatorChar = Path.DirectorySeparatorChar;
-
- return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
- }
-
- public virtual bool IsRootPath(string path)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- var parent = Path.GetDirectoryName(path);
-
- if (!string.IsNullOrEmpty(parent))
- {
- return false;
- }
-
- return true;
+ return path.Contains(
+ Path.TrimEndingDirectorySeparator(parentPath) + Path.DirectorySeparatorChar,
+ _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
public virtual string NormalizePath(string path)
@@ -638,7 +527,7 @@ namespace Emby.Server.Implementations.IO
return path;
}
- return path.TrimEnd(Path.DirectorySeparatorChar);
+ return Path.TrimEndingDirectorySeparator(path);
}
public virtual bool AreEqual(string path1, string path2)
@@ -653,7 +542,10 @@ namespace Emby.Server.Implementations.IO
return false;
}
- return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
+ return string.Equals(
+ NormalizePath(path1),
+ NormalizePath(path2),
+ _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
@@ -669,7 +561,6 @@ namespace Emby.Server.Implementations.IO
public virtual bool IsPathFile(string path)
{
// Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
-
if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
!path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
@@ -677,8 +568,6 @@ namespace Emby.Server.Implementations.IO
}
return true;
-
- //return Path.IsPathRooted(path);
}
public virtual void DeleteFile(string path)
@@ -689,21 +578,20 @@ namespace Emby.Server.Implementations.IO
public virtual List<FileSystemMetadata> GetDrives()
{
- // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
- return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
- {
- Name = d.Name,
- FullName = d.RootDirectory.FullName,
- IsDirectory = true
-
- }).ToList();
+ // check for ready state to avoid waiting for drives to timeout
+ // some drives on linux have no actual size or are used for other purposes
+ return DriveInfo.GetDrives().Where(d => d.IsReady && d.TotalSize != 0 && d.DriveType != DriveType.Ram)
+ .Select(d => new FileSystemMetadata
+ {
+ Name = d.Name,
+ FullName = d.RootDirectory.FullName,
+ IsDirectory = true
+ }).ToList();
}
public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
-
- return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
+ return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive)));
}
public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
@@ -711,29 +599,30 @@ namespace Emby.Server.Implementations.IO
return GetFiles(path, null, false, recursive);
}
- public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
+ public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string>? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
+ var enumerationOptions = GetEnumerationOptions(recursive);
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
- if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
+ if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
{
- return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
+ return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], enumerationOptions));
}
- var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
+ var files = new DirectoryInfo(path).EnumerateFiles("*", enumerationOptions);
- if (extensions != null && extensions.Length > 0)
+ if (extensions != null && extensions.Count > 0)
{
files = files.Where(i =>
{
- var ext = i.Extension;
- if (ext == null)
+ var ext = i.Extension.AsSpan();
+ if (ext.IsEmpty)
{
return false;
}
- return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
+
+ return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase);
});
}
@@ -743,10 +632,9 @@ namespace Emby.Server.Implementations.IO
public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{
var directoryInfo = new DirectoryInfo(path);
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
+ var enumerationOptions = GetEnumerationOptions(recursive);
- return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
- .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
+ return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", enumerationOptions));
}
private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
@@ -756,8 +644,7 @@ namespace Emby.Server.Implementations.IO
public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
- return Directory.EnumerateDirectories(path, "*", searchOption);
+ return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive));
}
public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false)
@@ -765,29 +652,30 @@ namespace Emby.Server.Implementations.IO
return GetFilePaths(path, null, false, recursive);
}
- public virtual IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
+ public virtual IEnumerable<string> GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
+ var enumerationOptions = GetEnumerationOptions(recursive);
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
{
- return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
+ return Directory.EnumerateFiles(path, "*" + extensions[0], enumerationOptions);
}
- var files = Directory.EnumerateFiles(path, "*", searchOption);
+ var files = Directory.EnumerateFiles(path, "*", enumerationOptions);
if (extensions != null && extensions.Length > 0)
{
files = files.Where(i =>
{
- var ext = Path.GetExtension(i);
- if (ext == null)
+ var ext = Path.GetExtension(i.AsSpan());
+ if (ext.IsEmpty)
{
return false;
}
- return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
+
+ return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase);
});
}
@@ -796,31 +684,18 @@ namespace Emby.Server.Implementations.IO
public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{
- var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
- return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
+ return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive));
}
- public virtual void SetExecutable(string path)
+ private EnumerationOptions GetEnumerationOptions(bool recursive)
{
- if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
+ return new EnumerationOptions
{
- RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
- }
- }
-
- private static void RunProcess(string path, string args, string workingDirectory)
- {
- using (var process = Process.Start(new ProcessStartInfo
- {
- Arguments = args,
- FileName = path,
- CreateNoWindow = true,
- WorkingDirectory = workingDirectory,
- WindowStyle = ProcessWindowStyle.Normal
- }))
- {
- process.WaitForExit();
- }
+ RecurseSubdirectories = recursive,
+ IgnoreInaccessible = true,
+ // Don't skip any files.
+ AttributesToSkip = 0
+ };
}
}
}
diff --git a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs
index 5e5e91bb3..76c58d5dc 100644
--- a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs
+++ b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.IO;
using MediaBrowser.Model.IO;
@@ -15,7 +17,7 @@ namespace Emby.Server.Implementations.IO
public string Extension => ".mblink";
- public string Resolve(string shortcutPath)
+ public string? Resolve(string shortcutPath)
{
if (string.IsNullOrEmpty(shortcutPath))
{
diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs
index 09cf4d4a3..e4f5f4cf0 100644
--- a/Emby.Server.Implementations/IO/StreamHelper.cs
+++ b/Emby.Server.Implementations/IO/StreamHelper.cs
@@ -1,4 +1,7 @@
+#pragma warning disable CS1591
+
using System;
+using System.Buffers;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -8,168 +11,125 @@ namespace Emby.Server.Implementations.IO
{
public class StreamHelper : IStreamHelper
{
- public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
+ public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action? onStarted, CancellationToken cancellationToken)
{
- byte[] buffer = new byte[bufferSize];
- int read;
- while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
-
- if (onStarted != null)
- {
- onStarted();
- onStarted = null;
- }
- }
- }
-
- public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken)
- {
- byte[] buffer = new byte[bufferSize];
-
- if (emptyReadLimit <= 0)
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+ try
{
int read;
- while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
+ while ((read = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
cancellationToken.ThrowIfCancellationRequested();
- await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
- }
+ await destination.WriteAsync(buffer, 0, read, cancellationToken).ConfigureAwait(false);
- return;
+ if (onStarted != null)
+ {
+ onStarted();
+ onStarted = null;
+ }
+ }
}
-
- var eofCount = 0;
-
- while (eofCount < emptyReadLimit)
+ finally
{
- cancellationToken.ThrowIfCancellationRequested();
-
- var bytesRead = source.Read(buffer, 0, buffer.Length);
-
- if (bytesRead == 0)
- {
- eofCount++;
- await Task.Delay(50, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- eofCount = 0;
-
- await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
- }
+ ArrayPool<byte>.Shared.Return(buffer);
}
}
- const int StreamCopyToBufferSize = 81920;
- public async Task<int> CopyToAsync(Stream source, Stream destination, CancellationToken cancellationToken)
+ public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken)
{
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
- int totalBytesRead = 0;
-
- while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+ try
{
- var bytesToWrite = bytesRead;
-
- if (bytesToWrite > 0)
+ if (emptyReadLimit <= 0)
{
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+ int read;
+ while ((read = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ await destination.WriteAsync(buffer, 0, read, cancellationToken).ConfigureAwait(false);
+ }
- totalBytesRead += bytesRead;
+ return;
}
- }
- return totalBytesRead;
- }
+ var eofCount = 0;
- public async Task<int> CopyToAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
- {
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
- int totalBytesRead = 0;
+ while (eofCount < emptyReadLimit)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
- {
- var bytesToWrite = bytesRead;
+ var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
- if (bytesToWrite > 0)
- {
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+ if (bytesRead == 0)
+ {
+ eofCount++;
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ eofCount = 0;
- totalBytesRead += bytesRead;
+ await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
+ }
}
}
-
- return totalBytesRead;
- }
-
- public async Task CopyToAsyncWithSyncRead(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
- {
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
-
- while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
+ finally
{
- var bytesToWrite = Math.Min(bytesRead, copyLength);
-
- if (bytesToWrite > 0)
- {
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
- }
-
- copyLength -= bytesToWrite;
-
- if (copyLength <= 0)
- {
- break;
- }
+ ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task CopyToAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
{
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
-
- while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(IODefaults.CopyToBufferSize);
+ try
{
- var bytesToWrite = Math.Min(bytesRead, copyLength);
+ int bytesRead;
- if (bytesToWrite > 0)
+ while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
- }
+ var bytesToWrite = Math.Min(bytesRead, copyLength);
- copyLength -= bytesToWrite;
+ if (bytesToWrite > 0)
+ {
+ await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+ }
- if (copyLength <= 0)
- {
- break;
+ copyLength -= bytesToWrite;
+
+ if (copyLength <= 0)
+ {
+ break;
+ }
}
}
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
}
public async Task CopyUntilCancelled(Stream source, Stream target, int bufferSize, CancellationToken cancellationToken)
{
- byte[] buffer = new byte[bufferSize];
-
- while (!cancellationToken.IsCancellationRequested)
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+ try
{
- var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
-
- //var position = fs.Position;
- //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
-
- if (bytesRead == 0)
+ while (!cancellationToken.IsCancellationRequested)
{
- await Task.Delay(100).ConfigureAwait(false);
+ var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
+
+ if (bytesRead == 0)
+ {
+ await Task.Delay(100, cancellationToken).ConfigureAwait(false);
+ }
}
}
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
}
private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, byte[] buffer, CancellationToken cancellationToken)
@@ -179,7 +139,7 @@ namespace Emby.Server.Implementations.IO
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
- await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
+ await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
}
diff --git a/Emby.Server.Implementations/IO/ThrottledStream.cs b/Emby.Server.Implementations/IO/ThrottledStream.cs
deleted file mode 100644
index 81e8abc98..000000000
--- a/Emby.Server.Implementations/IO/ThrottledStream.cs
+++ /dev/null
@@ -1,355 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Emby.Server.Implementations.IO
-{
- /// <summary>
- /// Class for streaming data with throttling support.
- /// </summary>
- public class ThrottledStream : Stream
- {
- /// <summary>
- /// A constant used to specify an infinite number of bytes that can be transferred per second.
- /// </summary>
- public const long Infinite = 0;
-
- #region Private members
- /// <summary>
- /// The base stream.
- /// </summary>
- private readonly Stream _baseStream;
-
- /// <summary>
- /// The maximum bytes per second that can be transferred through the base stream.
- /// </summary>
- private long _maximumBytesPerSecond;
-
- /// <summary>
- /// The number of bytes that has been transferred since the last throttle.
- /// </summary>
- private long _byteCount;
-
- /// <summary>
- /// The start time in milliseconds of the last throttle.
- /// </summary>
- private long _start;
- #endregion
-
- #region Properties
- /// <summary>
- /// Gets the current milliseconds.
- /// </summary>
- /// <value>The current milliseconds.</value>
- protected long CurrentMilliseconds => Environment.TickCount;
-
- /// <summary>
- /// Gets or sets the maximum bytes per second that can be transferred through the base stream.
- /// </summary>
- /// <value>The maximum bytes per second.</value>
- public long MaximumBytesPerSecond
- {
- get => _maximumBytesPerSecond;
- set
- {
- if (MaximumBytesPerSecond != value)
- {
- _maximumBytesPerSecond = value;
- Reset();
- }
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether the current stream supports reading.
- /// </summary>
- /// <returns>true if the stream supports reading; otherwise, false.</returns>
- public override bool CanRead => _baseStream.CanRead;
-
- /// <summary>
- /// Gets a value indicating whether the current stream supports seeking.
- /// </summary>
- /// <value></value>
- /// <returns>true if the stream supports seeking; otherwise, false.</returns>
- public override bool CanSeek => _baseStream.CanSeek;
-
- /// <summary>
- /// Gets a value indicating whether the current stream supports writing.
- /// </summary>
- /// <value></value>
- /// <returns>true if the stream supports writing; otherwise, false.</returns>
- public override bool CanWrite => _baseStream.CanWrite;
-
- /// <summary>
- /// Gets the length in bytes of the stream.
- /// </summary>
- /// <value></value>
- /// <returns>A long value representing the length of the stream in bytes.</returns>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- public override long Length => _baseStream.Length;
-
- /// <summary>
- /// Gets or sets the position within the current stream.
- /// </summary>
- /// <value></value>
- /// <returns>The current position within the stream.</returns>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- public override long Position
- {
- get => _baseStream.Position;
- set => _baseStream.Position = value;
- }
- #endregion
-
- public long MinThrottlePosition;
-
- #region Ctor
- /// <summary>
- /// Initializes a new instance of the <see cref="T:ThrottledStream"/> class.
- /// </summary>
- /// <param name="baseStream">The base stream.</param>
- /// <param name="maximumBytesPerSecond">The maximum bytes per second that can be transferred through the base stream.</param>
- /// <exception cref="ArgumentNullException">Thrown when <see cref="baseStream"/> is a null reference.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Thrown when <see cref="maximumBytesPerSecond"/> is a negative value.</exception>
- public ThrottledStream(Stream baseStream, long maximumBytesPerSecond)
- {
- if (baseStream == null)
- {
- throw new ArgumentNullException(nameof(baseStream));
- }
-
- if (maximumBytesPerSecond < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(maximumBytesPerSecond),
- maximumBytesPerSecond, "The maximum number of bytes per second can't be negative.");
- }
-
- _baseStream = baseStream;
- _maximumBytesPerSecond = maximumBytesPerSecond;
- _start = CurrentMilliseconds;
- _byteCount = 0;
- }
- #endregion
-
- #region Public methods
- /// <summary>
- /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
- /// </summary>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs.</exception>
- public override void Flush()
- {
- _baseStream.Flush();
- }
-
- /// <summary>
- /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
- /// </summary>
- /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
- /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
- /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
- /// <returns>
- /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
- /// </returns>
- /// <exception cref="T:System.ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support reading. </exception>
- /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
- public override int Read(byte[] buffer, int offset, int count)
- {
- Throttle(count);
-
- return _baseStream.Read(buffer, offset, count);
- }
-
- /// <summary>
- /// Sets the position within the current stream.
- /// </summary>
- /// <param name="offset">A byte offset relative to the origin parameter.</param>
- /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference point used to obtain the new position.</param>
- /// <returns>
- /// The new position within the current stream.
- /// </returns>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- public override long Seek(long offset, SeekOrigin origin)
- {
- return _baseStream.Seek(offset, origin);
- }
-
- /// <summary>
- /// Sets the length of the current stream.
- /// </summary>
- /// <param name="value">The desired length of the current stream in bytes.</param>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- public override void SetLength(long value)
- {
- _baseStream.SetLength(value);
- }
-
- private long _bytesWritten;
-
- /// <summary>
- /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
- /// </summary>
- /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
- /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
- /// <param name="count">The number of bytes to be written to the current stream.</param>
- /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
- /// <exception cref="T:System.NotSupportedException">The base stream does not support writing. </exception>
- /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
- /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
- /// <exception cref="T:System.ArgumentException">The sum of offset and count is greater than the buffer length. </exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
- public override void Write(byte[] buffer, int offset, int count)
- {
- Throttle(count);
-
- _baseStream.Write(buffer, offset, count);
-
- _bytesWritten += count;
- }
-
- public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- await ThrottleAsync(count, cancellationToken).ConfigureAwait(false);
-
- await _baseStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
-
- _bytesWritten += count;
- }
-
- /// <summary>
- /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
- /// </summary>
- /// <returns>
- /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
- /// </returns>
- public override string ToString()
- {
- return _baseStream.ToString();
- }
- #endregion
-
- private bool ThrottleCheck(int bufferSizeInBytes)
- {
- if (_bytesWritten < MinThrottlePosition)
- {
- return false;
- }
-
- // Make sure the buffer isn't empty.
- if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0)
- {
- return false;
- }
-
- return true;
- }
-
- #region Protected methods
- /// <summary>
- /// Throttles for the specified buffer size in bytes.
- /// </summary>
- /// <param name="bufferSizeInBytes">The buffer size in bytes.</param>
- protected void Throttle(int bufferSizeInBytes)
- {
- if (!ThrottleCheck(bufferSizeInBytes))
- {
- return;
- }
-
- _byteCount += bufferSizeInBytes;
- long elapsedMilliseconds = CurrentMilliseconds - _start;
-
- if (elapsedMilliseconds > 0)
- {
- // Calculate the current bps.
- long bps = _byteCount * 1000L / elapsedMilliseconds;
-
- // If the bps are more then the maximum bps, try to throttle.
- if (bps > _maximumBytesPerSecond)
- {
- // Calculate the time to sleep.
- long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
- int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
-
- if (toSleep > 1)
- {
- try
- {
- // The time to sleep is more then a millisecond, so sleep.
- var task = Task.Delay(toSleep);
- Task.WaitAll(task);
- }
- catch
- {
- // Eatup ThreadAbortException.
- }
-
- // A sleep has been done, reset.
- Reset();
- }
- }
- }
- }
-
- protected async Task ThrottleAsync(int bufferSizeInBytes, CancellationToken cancellationToken)
- {
- if (!ThrottleCheck(bufferSizeInBytes))
- {
- return;
- }
-
- _byteCount += bufferSizeInBytes;
- long elapsedMilliseconds = CurrentMilliseconds - _start;
-
- if (elapsedMilliseconds > 0)
- {
- // Calculate the current bps.
- long bps = _byteCount * 1000L / elapsedMilliseconds;
-
- // If the bps are more then the maximum bps, try to throttle.
- if (bps > _maximumBytesPerSecond)
- {
- // Calculate the time to sleep.
- long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
- int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
-
- if (toSleep > 1)
- {
- // The time to sleep is more then a millisecond, so sleep.
- await Task.Delay(toSleep, cancellationToken).ConfigureAwait(false);
-
- // A sleep has been done, reset.
- Reset();
- }
- }
- }
- }
-
- /// <summary>
- /// Will reset the bytecount to 0 and reset the start time to the current time.
- /// </summary>
- protected void Reset()
- {
- long difference = CurrentMilliseconds - _start;
-
- // Only reset counters when a known history is available of more then 1 second.
- if (difference > 1000)
- {
- _byteCount = 0;
- _start = CurrentMilliseconds;
- }
- }
- #endregion
- }
-}
diff --git a/Emby.Server.Implementations/IStartupOptions.cs b/Emby.Server.Implementations/IStartupOptions.cs
index 24aaa76c0..3769ae4dd 100644
--- a/Emby.Server.Implementations/IStartupOptions.cs
+++ b/Emby.Server.Implementations/IStartupOptions.cs
@@ -1,40 +1,38 @@
namespace Emby.Server.Implementations
{
+ /// <summary>
+ /// Specifies the contract for server startup options.
+ /// </summary>
public interface IStartupOptions
{
/// <summary>
- /// --ffmpeg
+ /// Gets the value of the --ffmpeg command line option.
/// </summary>
- string FFmpegPath { get; }
+ string? FFmpegPath { get; }
/// <summary>
- /// --ffprobe
- /// </summary>
- string FFprobePath { get; }
-
- /// <summary>
- /// --service
+ /// Gets a value indicating whether to run as service by the --service command line option.
/// </summary>
bool IsService { get; }
/// <summary>
- /// --noautorunwebapp
+ /// Gets the value of the --package-name command line option.
/// </summary>
- bool NoAutoRunWebApp { get; }
+ string? PackageName { get; }
/// <summary>
- /// --package-name
+ /// Gets the value of the --restartpath command line option.
/// </summary>
- string PackageName { get; }
+ string? RestartPath { get; }
/// <summary>
- /// --restartpath
+ /// Gets the value of the --restartargs command line option.
/// </summary>
- string RestartPath { get; }
+ string? RestartArgs { get; }
/// <summary>
- /// --restartargs
+ /// Gets the value of the --published-server-url command line option.
/// </summary>
- string RestartArgs { get; }
+ string? PublishedServerUrl { get; }
}
}
diff --git a/Emby.Server.Implementations/Images/ArtistImageProvider.cs b/Emby.Server.Implementations/Images/ArtistImageProvider.cs
new file mode 100644
index 000000000..e96b64595
--- /dev/null
+++ b/Emby.Server.Implementations/Images/ArtistImageProvider.cs
@@ -0,0 +1,46 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Images
+{
+ /// <summary>
+ /// Class ArtistImageProvider.
+ /// </summary>
+ public class ArtistImageProvider : BaseDynamicImageProvider<MusicArtist>
+ {
+ public ArtistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor)
+ : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ }
+
+ /// <summary>
+ /// Get children objects used to create an artist image.
+ /// </summary>
+ /// <param name="item">The artist used to create the image.</param>
+ /// <returns>Any relevant children objects.</returns>
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
+ {
+ return Array.Empty<BaseItem>();
+
+ // TODO enable this when BaseDynamicImageProvider objects are configurable
+ // return _libraryManager.GetItemList(new InternalItemsQuery
+ // {
+ // ArtistIds = new[] { item.Id },
+ // IncludeItemTypes = new[] { nameof(MusicAlbum) },
+ // OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
+ // Limit = 4,
+ // Recursive = true,
+ // ImageTypes = new[] { ImageType.Primary },
+ // DtoOptions = new DtoOptions(false)
+ // });
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
index 109c21f18..758986945 100644
--- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
+++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
@@ -1,5 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -20,11 +25,6 @@ namespace Emby.Server.Implementations.Images
public abstract class BaseDynamicImageProvider<T> : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
where T : BaseItem
{
- protected IFileSystem FileSystem { get; private set; }
- protected IProviderManager ProviderManager { get; private set; }
- protected IApplicationPaths ApplicationPaths { get; private set; }
- protected IImageProcessor ImageProcessor { get; set; }
-
protected BaseDynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor)
{
ApplicationPaths = applicationPaths;
@@ -33,18 +33,25 @@ namespace Emby.Server.Implementations.Images
ImageProcessor = imageProcessor;
}
- protected virtual bool Supports(BaseItem item)
- {
- return true;
- }
+ protected IFileSystem FileSystem { get; }
- public virtual ImageType[] GetSupportedImages(BaseItem item)
- {
- return new ImageType[]
- {
- ImageType.Primary
- };
- }
+ protected IProviderManager ProviderManager { get; }
+
+ protected IApplicationPaths ApplicationPaths { get; }
+
+ protected IImageProcessor ImageProcessor { get; set; }
+
+ protected virtual IReadOnlyCollection<ImageType> SupportedImages { get; }
+ = new ImageType[] { ImageType.Primary };
+
+ /// <inheritdoc />
+ public string Name => "Dynamic Image Provider";
+
+ protected virtual int MaxImageAgeDays => 7;
+
+ public int Order => 0;
+
+ protected virtual bool Supports(BaseItem item) => true;
public async Task<ItemUpdateType> FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
@@ -54,18 +61,17 @@ namespace Emby.Server.Implementations.Images
}
var updateType = ItemUpdateType.None;
- var supportedImages = GetSupportedImages(item);
- if (supportedImages.Contains(ImageType.Primary))
+ if (SupportedImages.Contains(ImageType.Primary))
{
var primaryResult = await FetchAsync(item, ImageType.Primary, options, cancellationToken).ConfigureAwait(false);
- updateType = updateType | primaryResult;
+ updateType |= primaryResult;
}
- if (supportedImages.Contains(ImageType.Thumb))
+ if (SupportedImages.Contains(ImageType.Thumb))
{
var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
- updateType = updateType | thumbResult;
+ updateType |= thumbResult;
}
return updateType;
@@ -93,12 +99,13 @@ namespace Emby.Server.Implementations.Images
return FetchToFileInternal(item, items, imageType, cancellationToken);
}
- protected async Task<ItemUpdateType> FetchToFileInternal(BaseItem item,
- List<BaseItem> itemsWithImages,
+ protected async Task<ItemUpdateType> FetchToFileInternal(
+ BaseItem item,
+ IReadOnlyList<BaseItem> itemsWithImages,
ImageType imageType,
CancellationToken cancellationToken)
{
- var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N"));
+ var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
Directory.CreateDirectory(Path.GetDirectoryName(outputPathWithoutExtension));
string outputPath = CreateImage(item, itemsWithImages, outputPathWithoutExtension, imageType, 0);
@@ -119,51 +126,62 @@ namespace Emby.Server.Implementations.Images
return ItemUpdateType.ImageUpdate;
}
- protected abstract List<BaseItem> GetItemsWithImages(BaseItem item);
+ protected abstract IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item);
- protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+ protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 640, 360);
}
protected virtual IEnumerable<string> GetStripCollageImagePaths(BaseItem primaryItem, IEnumerable<BaseItem> items)
{
+ var useBackdrop = primaryItem is CollectionFolder;
return items
.Select(i =>
{
- var image = i.GetImageInfo(ImageType.Primary, 0);
+ // Use Backdrop instead of Primary image for Library images.
+ if (useBackdrop)
+ {
+ var backdrop = i.GetImageInfo(ImageType.Backdrop, 0);
+ if (backdrop != null && backdrop.IsLocalFile)
+ {
+ return backdrop.Path;
+ }
+ }
+ var image = i.GetImageInfo(ImageType.Primary, 0);
if (image != null && image.IsLocalFile)
{
return image.Path;
}
- image = i.GetImageInfo(ImageType.Thumb, 0);
+ image = i.GetImageInfo(ImageType.Thumb, 0);
if (image != null && image.IsLocalFile)
{
return image.Path;
}
+
return null;
})
.Where(i => !string.IsNullOrEmpty(i));
}
- protected string CreatePosterCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+ protected string CreatePosterCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 400, 600);
}
- protected string CreateSquareCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+ protected string CreateSquareCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 600, 600);
}
- protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
+ protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
{
return CreateCollage(primaryItem, items, outputPath, width, height);
}
- private string CreateCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
+ private string CreateCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
{
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
@@ -175,7 +193,7 @@ namespace Emby.Server.Implementations.Images
InputPaths = GetStripCollageImagePaths(primaryItem, items).ToArray()
};
- if (options.InputPaths.Length == 0)
+ if (options.InputPaths.Count == 0)
{
return null;
}
@@ -185,14 +203,13 @@ namespace Emby.Server.Implementations.Images
return null;
}
- ImageProcessor.CreateImageCollage(options);
+ ImageProcessor.CreateImageCollage(options, primaryItem.Name);
return outputPath;
}
- public string Name => "Dynamic Image Provider";
-
- protected virtual string CreateImage(BaseItem item,
- List<BaseItem> itemsWithImages,
+ protected virtual string CreateImage(
+ BaseItem item,
+ IReadOnlyCollection<BaseItem> itemsWithImages,
string outputPathWithoutExtension,
ImageType imageType,
int imageIndex)
@@ -211,36 +228,35 @@ namespace Emby.Server.Implementations.Images
if (imageType == ImageType.Primary)
{
- if (item is UserView)
- {
- return CreateSquareCollage(item, itemsWithImages, outputPath);
- }
- if (item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
+ if (item is UserView
+ || item is Playlist
+ || item is MusicGenre
+ || item is Genre
+ || item is PhotoAlbum
+ || item is MusicArtist)
{
return CreateSquareCollage(item, itemsWithImages, outputPath);
}
+
return CreatePosterCollage(item, itemsWithImages, outputPath);
}
- throw new ArgumentException("Unexpected image type");
+ throw new ArgumentException("Unexpected image type", nameof(imageType));
}
- protected virtual int MaxImageAgeDays => 7;
-
- public bool HasChanged(BaseItem item, IDirectoryService directoryServicee)
+ public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
if (!Supports(item))
{
return false;
}
- var supportedImages = GetSupportedImages(item);
-
- if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
+ if (SupportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
{
return true;
}
- if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
+
+ if (SupportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
{
return true;
}
@@ -276,16 +292,10 @@ namespace Emby.Server.Implementations.Images
protected virtual bool HasChangedByDate(BaseItem item, ItemImageInfo image)
{
var age = DateTime.UtcNow - image.DateModified;
- if (age.TotalDays <= MaxImageAgeDays)
- {
- return false;
- }
- return true;
+ return age.TotalDays > MaxImageAgeDays;
}
- public int Order => 0;
-
- protected string CreateSingleImage(List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
+ protected string CreateSingleImage(IEnumerable<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
{
var image = itemsWithImages
.Where(i => i.HasImage(imageType) && i.GetImageInfo(imageType, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(imageType)))
diff --git a/Emby.Server.Implementations/Images/BaseFolderImageProvider.cs b/Emby.Server.Implementations/Images/BaseFolderImageProvider.cs
new file mode 100644
index 000000000..1c69056d2
--- /dev/null
+++ b/Emby.Server.Implementations/Images/BaseFolderImageProvider.cs
@@ -0,0 +1,67 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Querying;
+
+namespace Emby.Server.Implementations.Images
+{
+ public abstract class BaseFolderImageProvider<T> : BaseDynamicImageProvider<T>
+ where T : Folder, new()
+ {
+ private readonly ILibraryManager _libraryManager;
+
+ public BaseFolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
+ : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ _libraryManager = libraryManager;
+ }
+
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
+ {
+ return _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Parent = item,
+ DtoOptions = new DtoOptions(true),
+ ImageTypes = new ImageType[] { ImageType.Primary },
+ OrderBy = new (string, SortOrder)[]
+ {
+ (ItemSortBy.IsFolder, SortOrder.Ascending),
+ (ItemSortBy.SortName, SortOrder.Ascending)
+ },
+ Limit = 1
+ });
+ }
+
+ protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+ {
+ return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
+ }
+
+ protected override bool Supports(BaseItem item)
+ {
+ return item is T;
+ }
+
+ protected override bool HasChangedByDate(BaseItem item, ItemImageInfo image)
+ {
+ if (item is MusicAlbum)
+ {
+ return false;
+ }
+
+ return base.HasChangedByDate(item, image);
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/UserViews/CollectionFolderImageProvider.cs b/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs
index ce6c2cd87..0229fbae7 100644
--- a/Emby.Server.Implementations/UserViews/CollectionFolderImageProvider.cs
+++ b/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs
@@ -1,8 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
-using Emby.Server.Implementations.Images;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
@@ -12,7 +15,7 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
-namespace Emby.Server.Implementations.UserViews
+namespace Emby.Server.Implementations.Images
{
public class CollectionFolderImageProvider : BaseDynamicImageProvider<CollectionFolder>
{
@@ -20,34 +23,34 @@ namespace Emby.Server.Implementations.UserViews
{
}
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var view = (CollectionFolder)item;
var viewType = view.CollectionType;
string[] includeItemTypes;
- if (string.Equals(viewType, CollectionType.Movies))
+ if (string.Equals(viewType, CollectionType.Movies, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "Movie" };
}
- else if (string.Equals(viewType, CollectionType.TvShows))
+ else if (string.Equals(viewType, CollectionType.TvShows, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "Series" };
}
- else if (string.Equals(viewType, CollectionType.Music))
+ else if (string.Equals(viewType, CollectionType.Music, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "MusicAlbum" };
}
- else if (string.Equals(viewType, CollectionType.Books))
+ else if (string.Equals(viewType, CollectionType.Books, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "Book", "AudioBook" };
}
- else if (string.Equals(viewType, CollectionType.BoxSets))
+ else if (string.Equals(viewType, CollectionType.BoxSets, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "BoxSet" };
}
- else if (string.Equals(viewType, CollectionType.HomeVideos) || string.Equals(viewType, CollectionType.Photos))
+ else if (string.Equals(viewType, CollectionType.HomeVideos, StringComparison.Ordinal) || string.Equals(viewType, CollectionType.Photos, StringComparison.Ordinal))
{
includeItemTypes = new string[] { "Video", "Photo" };
}
@@ -56,7 +59,7 @@ namespace Emby.Server.Implementations.UserViews
includeItemTypes = new string[] { "Video", "Audio", "Photo", "Movie", "Series" };
}
- var recursive = !new[] { CollectionType.Playlists }.Contains(view.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ var recursive = !string.Equals(CollectionType.Playlists, viewType, StringComparison.OrdinalIgnoreCase);
return view.GetItemList(new InternalItemsQuery
{
@@ -70,8 +73,7 @@ namespace Emby.Server.Implementations.UserViews
new ValueTuple<string, SortOrder>(ItemSortBy.Random, SortOrder.Ascending)
},
IncludeItemTypes = includeItemTypes
-
- }).ToList();
+ });
}
protected override bool Supports(BaseItem item)
@@ -79,7 +81,7 @@ namespace Emby.Server.Implementations.UserViews
return item is CollectionFolder;
}
- protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+ protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ".png");
diff --git a/Emby.Server.Implementations/UserViews/DynamicImageProvider.cs b/Emby.Server.Implementations/Images/DynamicImageProvider.cs
index 4ec68e550..900b3fd9c 100644
--- a/Emby.Server.Implementations/UserViews/DynamicImageProvider.cs
+++ b/Emby.Server.Implementations/Images/DynamicImageProvider.cs
@@ -1,8 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
-using Emby.Server.Implementations.Images;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
@@ -14,21 +17,19 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-namespace Emby.Server.Implementations.UserViews
+namespace Emby.Server.Implementations.Images
{
public class DynamicImageProvider : BaseDynamicImageProvider<UserView>
{
private readonly IUserManager _userManager;
- private readonly ILibraryManager _libraryManager;
- public DynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, IUserManager userManager, ILibraryManager libraryManager)
+ public DynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, IUserManager userManager)
: base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
_userManager = userManager;
- _libraryManager = libraryManager;
}
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var view = (UserView)item;
@@ -46,8 +47,7 @@ namespace Emby.Server.Implementations.UserViews
var items = result.Select(i =>
{
- var episode = i as Episode;
- if (episode != null)
+ if (i is Episode episode)
{
var series = episode.Series;
if (series != null)
@@ -58,8 +58,7 @@ namespace Emby.Server.Implementations.UserViews
return episode;
}
- var season = i as Season;
- if (season != null)
+ if (i is Season season)
{
var series = season.Series;
if (series != null)
@@ -70,8 +69,7 @@ namespace Emby.Server.Implementations.UserViews
return season;
}
- var audio = i as Audio;
- if (audio != null)
+ if (i is Audio audio)
{
var album = audio.AlbumEntity;
if (album != null && album.HasImage(ImageType.Primary))
@@ -81,7 +79,6 @@ namespace Emby.Server.Implementations.UserViews
}
return i;
-
}).GroupBy(x => x.Id)
.Select(x => x.First());
@@ -89,20 +86,17 @@ namespace Emby.Server.Implementations.UserViews
{
return items
.Where(i => i.HasImage(ImageType.Primary) || i.HasImage(ImageType.Thumb))
- .OrderBy(i => Guid.NewGuid())
.ToList();
}
return items
.Where(i => i.HasImage(ImageType.Primary))
- .OrderBy(i => Guid.NewGuid())
.ToList();
}
protected override bool Supports(BaseItem item)
{
- var view = item as UserView;
- if (view != null)
+ if (item is UserView view)
{
return IsUsingCollectionStrip(view);
}
@@ -122,7 +116,7 @@ namespace Emby.Server.Implementations.UserViews
return collectionStripViewTypes.Contains(view.ViewType ?? string.Empty);
}
- protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+ protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
if (itemsWithImages.Count == 0)
{
diff --git a/Emby.Server.Implementations/Images/FolderImageProvider.cs b/Emby.Server.Implementations/Images/FolderImageProvider.cs
new file mode 100644
index 000000000..4376bd356
--- /dev/null
+++ b/Emby.Server.Implementations/Images/FolderImageProvider.cs
@@ -0,0 +1,37 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Images
+{
+ public class FolderImageProvider : BaseFolderImageProvider<Folder>
+ {
+ public FolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
+ : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
+ {
+ }
+
+ protected override bool Supports(BaseItem item)
+ {
+ if (item is PhotoAlbum || item is MusicAlbum)
+ {
+ return false;
+ }
+
+ if (item is Folder && item.IsTopParent)
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/GenreImageProvider.cs b/Emby.Server.Implementations/Images/GenreImageProvider.cs
new file mode 100644
index 000000000..1f5090f7f
--- /dev/null
+++ b/Emby.Server.Implementations/Images/GenreImageProvider.cs
@@ -0,0 +1,55 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Querying;
+
+namespace Emby.Server.Implementations.Images
+{
+ /// <summary>
+ /// Class GenreImageProvider.
+ /// </summary>
+ public class GenreImageProvider : BaseDynamicImageProvider<Genre>
+ {
+ /// <summary>
+ /// The library manager.
+ /// </summary>
+ private readonly ILibraryManager _libraryManager;
+
+ public GenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Get children objects used to create an genre image.
+ /// </summary>
+ /// <param name="item">The genre used to create the image.</param>
+ /// <returns>Any relevant children objects.</returns>
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
+ {
+ return _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Genres = new[] { item.Name },
+ IncludeItemTypes = new[] { nameof(Series), nameof(Movie) },
+ OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
+ Limit = 4,
+ Recursive = true,
+ ImageTypes = new[] { ImageType.Primary },
+ DtoOptions = new DtoOptions(false)
+ });
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/MusicAlbumImageProvider.cs b/Emby.Server.Implementations/Images/MusicAlbumImageProvider.cs
new file mode 100644
index 000000000..ce8367363
--- /dev/null
+++ b/Emby.Server.Implementations/Images/MusicAlbumImageProvider.cs
@@ -0,0 +1,19 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Images
+{
+ public class MusicAlbumImageProvider : BaseFolderImageProvider<MusicAlbum>
+ {
+ public MusicAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
+ : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
+ {
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/MusicGenreImageProvider.cs b/Emby.Server.Implementations/Images/MusicGenreImageProvider.cs
new file mode 100644
index 000000000..baf1c9051
--- /dev/null
+++ b/Emby.Server.Implementations/Images/MusicGenreImageProvider.cs
@@ -0,0 +1,59 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Querying;
+
+namespace Emby.Server.Implementations.Images
+{
+ /// <summary>
+ /// Class MusicGenreImageProvider.
+ /// </summary>
+ public class MusicGenreImageProvider : BaseDynamicImageProvider<MusicGenre>
+ {
+ /// <summary>
+ /// The library manager.
+ /// </summary>
+ private readonly ILibraryManager _libraryManager;
+
+ public MusicGenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Get children objects used to create an music genre image.
+ /// </summary>
+ /// <param name="item">The music genre used to create the image.</param>
+ /// <returns>Any relevant children objects.</returns>
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
+ {
+ return _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Genres = new[] { item.Name },
+ IncludeItemTypes = new[]
+ {
+ nameof(MusicAlbum),
+ nameof(MusicVideo),
+ nameof(Audio)
+ },
+ OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
+ Limit = 4,
+ Recursive = true,
+ ImageTypes = new[] { ImageType.Primary },
+ DtoOptions = new DtoOptions(false)
+ });
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/PhotoAlbumImageProvider.cs b/Emby.Server.Implementations/Images/PhotoAlbumImageProvider.cs
new file mode 100644
index 000000000..1ddb4c757
--- /dev/null
+++ b/Emby.Server.Implementations/Images/PhotoAlbumImageProvider.cs
@@ -0,0 +1,19 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Images
+{
+ public class PhotoAlbumImageProvider : BaseFolderImageProvider<PhotoAlbum>
+ {
+ public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
+ : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
+ {
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Images/PlaylistImageProvider.cs b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs
new file mode 100644
index 000000000..b8f0f0d65
--- /dev/null
+++ b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs
@@ -0,0 +1,66 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Playlists;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Images
+{
+ public class PlaylistImageProvider : BaseDynamicImageProvider<Playlist>
+ {
+ public PlaylistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ }
+
+ protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
+ {
+ var playlist = (Playlist)item;
+
+ return playlist.GetManageableItems()
+ .Select(i =>
+ {
+ var subItem = i.Item2;
+
+ if (subItem is Episode episode)
+ {
+ var series = episode.Series;
+ if (series != null && series.HasImage(ImageType.Primary))
+ {
+ return series;
+ }
+ }
+
+ if (subItem.HasImage(ImageType.Primary))
+ {
+ return subItem;
+ }
+
+ var parent = subItem.GetOwner() ?? subItem.GetParent();
+
+ if (parent != null && parent.HasImage(ImageType.Primary))
+ {
+ if (parent is MusicAlbum)
+ {
+ return parent;
+ }
+ }
+
+ return null;
+ })
+ .Where(i => i != null)
+ .GroupBy(x => x.Id)
+ .Select(x => x.First())
+ .ToList();
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
index c644d13ea..bc5b4499f 100644
--- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
+++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
@@ -1,126 +1,62 @@
using System;
using System.IO;
-using System.Linq;
+using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Resolvers;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Library
{
/// <summary>
- /// Provides the core resolver ignore rules
+ /// Provides the core resolver ignore rules.
/// </summary>
public class CoreResolutionIgnoreRule : IResolverIgnoreRule
{
private readonly ILibraryManager _libraryManager;
-
- private bool _ignoreDotPrefix;
+ private readonly IServerApplicationPaths _serverApplicationPaths;
/// <summary>
- /// Any folder named in this list will be ignored - can be added to at runtime for extensibility
+ /// Initializes a new instance of the <see cref="CoreResolutionIgnoreRule"/> class.
/// </summary>
- public static readonly string[] IgnoreFolders =
- {
- "metadata",
- "ps3_update",
- "ps3_vprm",
- "extrafanart",
- "extrathumbs",
- ".actors",
- ".wd_tv",
-
- // Synology
- "@eaDir",
- "eaDir",
- "#recycle",
-
- // Qnap
- "@Recycle",
- ".@__thumb",
- "$RECYCLE.BIN",
- "System Volume Information",
- ".grab",
-
- // macos
- ".AppleDouble"
-
- };
-
- public CoreResolutionIgnoreRule(ILibraryManager libraryManager)
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="serverApplicationPaths">The server application paths.</param>
+ public CoreResolutionIgnoreRule(ILibraryManager libraryManager, IServerApplicationPaths serverApplicationPaths)
{
_libraryManager = libraryManager;
-
- _ignoreDotPrefix = Environment.OSVersion.Platform != PlatformID.Win32NT;
+ _serverApplicationPaths = serverApplicationPaths;
}
- /// <summary>
- /// Shoulds the ignore.
- /// </summary>
- /// <param name="fileInfo">The file information.</param>
- /// <param name="parent">The parent.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
+ /// <inheritdoc />
public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem parent)
{
+ // Don't ignore application folders
+ if (fileInfo.FullName.Contains(_serverApplicationPaths.RootFolderPath, StringComparison.InvariantCulture))
+ {
+ return false;
+ }
+
// Don't ignore top level folders
if (fileInfo.IsDirectory && parent is AggregateFolder)
{
return false;
}
- var filename = fileInfo.Name;
- var path = fileInfo.FullName;
-
- // Handle mac .DS_Store
- // https://github.com/MediaBrowser/MediaBrowser/issues/427
- if (_ignoreDotPrefix)
+ if (IgnorePatterns.ShouldIgnore(fileInfo.FullName))
{
- if (filename.IndexOf('.') == 0)
- {
- return true;
- }
+ return true;
}
- // Ignore hidden files and folders
- //if (fileInfo.IsHidden)
- //{
- // if (parent == null)
- // {
- // var parentFolderName = Path.GetFileName(_fileSystem.GetDirectoryName(path));
-
- // if (string.Equals(parentFolderName, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
- // {
- // return false;
- // }
- // if (string.Equals(parentFolderName, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
- // {
- // return false;
- // }
- // }
-
- // // Sometimes these are marked hidden
- // if (_fileSystem.IsRootPath(path))
- // {
- // return false;
- // }
-
- // return true;
- //}
+ var filename = fileInfo.Name;
if (fileInfo.IsDirectory)
{
- // Ignore any folders in our list
- if (IgnoreFolders.Contains(filename, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
-
if (parent != null)
{
// Ignore trailer folders but allow it at the collection level
- if (string.Equals(filename, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase) &&
- !(parent is AggregateFolder) && !(parent is UserRootFolder))
+ if (string.Equals(filename, BaseItem.TrailersFolderName, StringComparison.OrdinalIgnoreCase)
+ && !(parent is AggregateFolder)
+ && !(parent is UserRootFolder))
{
return true;
}
@@ -141,22 +77,12 @@ namespace Emby.Server.Implementations.Library
if (parent != null)
{
// Don't resolve these into audio files
- if (string.Equals(Path.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && _libraryManager.IsAudioFile(filename))
+ if (Path.GetFileNameWithoutExtension(filename.AsSpan()).Equals(BaseItem.ThemeSongFileName, StringComparison.Ordinal)
+ && _libraryManager.IsAudioFile(filename))
{
return true;
}
}
-
- // Ignore samples
- var sampleFilename = " " + filename.Replace(".", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("-", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("_", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("!", " ", StringComparison.OrdinalIgnoreCase);
-
- if (sampleFilename.IndexOf(" sample ", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return true;
- }
}
return false;
diff --git a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
deleted file mode 100644
index 4013ac0c8..000000000
--- a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-using System;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Model.Cryptography;
-
-namespace Emby.Server.Implementations.Library
-{
- public class DefaultAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
- {
- private readonly ICryptoProvider _cryptographyProvider;
- public DefaultAuthenticationProvider(ICryptoProvider crypto)
- {
- _cryptographyProvider = crypto;
- }
-
- public string Name => "Default";
-
- public bool IsEnabled => true;
-
- public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
- {
- throw new NotImplementedException();
- }
-
- public Task<ProviderAuthenticationResult> Authenticate(string username, string password, User resolvedUser)
- {
- if (resolvedUser == null)
- {
- throw new Exception("Invalid username or password");
- }
-
- var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
-
- if (!success)
- {
- throw new Exception("Invalid username or password");
- }
-
- return Task.FromResult(new ProviderAuthenticationResult
- {
- Username = username
- });
- }
-
- public Task<bool> HasPassword(User user)
- {
- var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
- return Task.FromResult(hasConfiguredPassword);
- }
-
- private bool IsPasswordEmpty(User user, string passwordHash)
- {
- return string.Equals(passwordHash, GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
- }
-
- public Task ChangePassword(User user, string newPassword)
- {
- string newPasswordHash = null;
-
- if (newPassword != null)
- {
- newPasswordHash = GetHashedString(user, newPassword);
- }
-
- if (string.IsNullOrWhiteSpace(newPasswordHash))
- {
- throw new ArgumentNullException(nameof(newPasswordHash));
- }
-
- user.Password = newPasswordHash;
-
- return Task.CompletedTask;
- }
-
- public string GetPasswordHash(User user)
- {
- return string.IsNullOrEmpty(user.Password)
- ? GetEmptyHashedString(user)
- : user.Password;
- }
-
- public string GetEmptyHashedString(User user)
- {
- return GetHashedString(user, string.Empty);
- }
-
- /// <summary>
- /// Gets the hashed string.
- /// </summary>
- public string GetHashedString(User user, string str)
- {
- var salt = user.Salt;
- if (salt != null)
- {
- // return BCrypt.HashPassword(str, salt);
- }
-
- // legacy
- return BitConverter.ToString(_cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
index 45a33a296..868071a99 100644
--- a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
+++ b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
@@ -1,4 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
@@ -8,30 +14,37 @@ namespace Emby.Server.Implementations.Library
{
public class ExclusiveLiveStream : ILiveStream
{
+ private readonly Func<Task> _closeFn;
+
+ public ExclusiveLiveStream(MediaSourceInfo mediaSource, Func<Task> closeFn)
+ {
+ MediaSource = mediaSource;
+ EnableStreamSharing = false;
+ _closeFn = closeFn;
+ ConsumerCount = 1;
+ UniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ }
+
public int ConsumerCount { get; set; }
+
public string OriginalStreamId { get; set; }
public string TunerHostId => null;
public bool EnableStreamSharing { get; set; }
- public MediaSourceInfo MediaSource { get; set; }
- public string UniqueId { get; private set; }
+ public MediaSourceInfo MediaSource { get; set; }
- private Func<Task> _closeFn;
+ public string UniqueId { get; }
- public ExclusiveLiveStream(MediaSourceInfo mediaSource, Func<Task> closeFn)
+ public Task Close()
{
- MediaSource = mediaSource;
- EnableStreamSharing = false;
- _closeFn = closeFn;
- ConsumerCount = 1;
- UniqueId = Guid.NewGuid().ToString("N");
+ return _closeFn();
}
- public Task Close()
+ public Stream GetStream()
{
- return _closeFn();
+ throw new NotSupportedException();
}
public Task Open(CancellationToken openCancellationToken)
diff --git a/Emby.Server.Implementations/Library/IgnorePatterns.cs b/Emby.Server.Implementations/Library/IgnorePatterns.cs
new file mode 100644
index 000000000..5384c04b3
--- /dev/null
+++ b/Emby.Server.Implementations/Library/IgnorePatterns.cs
@@ -0,0 +1,123 @@
+using System;
+using System.Linq;
+using DotNet.Globbing;
+
+namespace Emby.Server.Implementations.Library
+{
+ /// <summary>
+ /// Glob patterns for files to ignore.
+ /// </summary>
+ public static class IgnorePatterns
+ {
+ /// <summary>
+ /// Files matching these glob patterns will be ignored.
+ /// </summary>
+ private static readonly string[] _patterns =
+ {
+ "**/small.jpg",
+ "**/albumart.jpg",
+
+ // We have neither non-greedy matching or character group repetitions, working around that here.
+ // https://github.com/dazinator/DotNet.Glob#patterns
+ // .*/sample\..{1,5}
+ "**/sample.?",
+ "**/sample.??",
+ "**/sample.???", // Matches sample.mkv
+ "**/sample.????", // Matches sample.webm
+ "**/sample.?????",
+ "**/*.sample.?",
+ "**/*.sample.??",
+ "**/*.sample.???",
+ "**/*.sample.????",
+ "**/*.sample.?????",
+ "**/sample/*",
+
+ // Directories
+ "**/metadata/**",
+ "**/metadata",
+ "**/ps3_update/**",
+ "**/ps3_update",
+ "**/ps3_vprm/**",
+ "**/ps3_vprm",
+ "**/extrafanart/**",
+ "**/extrafanart",
+ "**/extrathumbs/**",
+ "**/extrathumbs",
+ "**/.actors/**",
+ "**/.actors",
+ "**/.wd_tv/**",
+ "**/.wd_tv",
+ "**/lost+found/**",
+ "**/lost+found",
+
+ // WMC temp recording directories that will constantly be written to
+ "**/TempRec/**",
+ "**/TempRec",
+ "**/TempSBE/**",
+ "**/TempSBE",
+
+ // Synology
+ "**/eaDir/**",
+ "**/eaDir",
+ "**/@eaDir/**",
+ "**/@eaDir",
+ "**/#recycle/**",
+ "**/#recycle",
+
+ // Qnap
+ "**/@Recycle/**",
+ "**/@Recycle",
+ "**/.@__thumb/**",
+ "**/.@__thumb",
+ "**/$RECYCLE.BIN/**",
+ "**/$RECYCLE.BIN",
+ "**/System Volume Information/**",
+ "**/System Volume Information",
+ "**/.grab/**",
+ "**/.grab",
+
+ // Unix hidden files
+ "**/.*",
+
+ // Mac - if you ever remove the above.
+ // "**/._*",
+ // "**/.DS_Store",
+
+ // thumbs.db
+ "**/thumbs.db",
+
+ // bts sync files
+ "**/*.bts",
+ "**/*.sync",
+ };
+
+ private static readonly GlobOptions _globOptions = new GlobOptions
+ {
+ Evaluation =
+ {
+ CaseInsensitive = true
+ }
+ };
+
+ private static readonly Glob[] _globs = _patterns.Select(p => Glob.Parse(p, _globOptions)).ToArray();
+
+ /// <summary>
+ /// Returns true if the supplied path should be ignored.
+ /// </summary>
+ /// <param name="path">The path to test.</param>
+ /// <returns>Whether to ignore the path.</returns>
+ public static bool ShouldIgnore(ReadOnlySpan<char> path)
+ {
+ int len = _globs.Length;
+ for (int i = 0; i < len; i++)
+ {
+ if (_globs[i].IsMatch(path))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index 3c2272b56..1326f60fe 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -1,10 +1,14 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
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.Threading;
using System.Threading.Tasks;
using Emby.Naming.Audio;
@@ -15,78 +19,138 @@ using Emby.Server.Implementations.Library.Resolvers;
using Emby.Server.Implementations.Library.Validators;
using Emby.Server.Implementations.Playlists;
using Emby.Server.Implementations.ScheduledTasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Library;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Providers.MediaInfo;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
-using SortOrder = MediaBrowser.Model.Entities.SortOrder;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using EpisodeInfo = Emby.Naming.TV.EpisodeInfo;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Person = MediaBrowser.Controller.Entities.Person;
using VideoResolver = Emby.Naming.Video.VideoResolver;
namespace Emby.Server.Implementations.Library
{
/// <summary>
- /// Class LibraryManager
+ /// Class LibraryManager.
/// </summary>
public class LibraryManager : ILibraryManager
{
- /// <summary>
- /// Gets or sets the postscan tasks.
- /// </summary>
- /// <value>The postscan tasks.</value>
- private ILibraryPostScanTask[] PostscanTasks { get; set; }
+ private const string ShortcutFileExtension = ".mblink";
- /// <summary>
- /// Gets the intro providers.
- /// </summary>
- /// <value>The intro providers.</value>
- private IIntroProvider[] IntroProviders { get; set; }
+ private readonly ILogger<LibraryManager> _logger;
+ private readonly IMemoryCache _memoryCache;
+ private readonly ITaskManager _taskManager;
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataRepository;
+ private readonly IServerConfigurationManager _configurationManager;
+ private readonly Lazy<ILibraryMonitor> _libraryMonitorFactory;
+ private readonly Lazy<IProviderManager> _providerManagerFactory;
+ private readonly Lazy<IUserViewManager> _userviewManagerFactory;
+ private readonly IServerApplicationHost _appHost;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IFileSystem _fileSystem;
+ private readonly IItemRepository _itemRepository;
+ private readonly IImageProcessor _imageProcessor;
/// <summary>
- /// Gets the list of entity resolution ignore rules
+ /// The _root folder sync lock.
/// </summary>
- /// <value>The entity resolution ignore rules.</value>
- private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
+ private readonly object _rootFolderSyncLock = new object();
+ private readonly object _userRootFolderSyncLock = new object();
- /// <summary>
- /// Gets the list of currently registered entity resolvers
- /// </summary>
- /// <value>The entity resolvers enumerable.</value>
- private IItemResolver[] EntityResolvers { get; set; }
- private IMultiItemResolver[] MultiItemResolvers { get; set; }
+ private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
+
+ private NamingOptions _namingOptions;
+ private string[] _videoFileExtensions;
/// <summary>
- /// Gets or sets the comparers.
+ /// The _root folder.
/// </summary>
- /// <value>The comparers.</value>
- private IBaseItemComparer[] Comparers { get; set; }
+ private volatile AggregateFolder _rootFolder;
+ private volatile UserRootFolder _userRootFolder;
+
+ private bool _wizardCompleted;
/// <summary>
- /// Gets the active item repository
+ /// Initializes a new instance of the <see cref="LibraryManager" /> class.
/// </summary>
- /// <value>The item repository.</value>
- public IItemRepository ItemRepository { get; set; }
+ /// <param name="appHost">The application host.</param>
+ /// <param name="logger">The logger.</param>
+ /// <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="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="mediaEncoder">The media encoder.</param>
+ /// <param name="itemRepository">The item repository.</param>
+ /// <param name="imageProcessor">The image processor.</param>
+ /// <param name="memoryCache">The memory cache.</param>
+ public LibraryManager(
+ IServerApplicationHost appHost,
+ ILogger<LibraryManager> logger,
+ ITaskManager taskManager,
+ IUserManager userManager,
+ IServerConfigurationManager configurationManager,
+ IUserDataManager userDataRepository,
+ Lazy<ILibraryMonitor> libraryMonitorFactory,
+ IFileSystem fileSystem,
+ Lazy<IProviderManager> providerManagerFactory,
+ Lazy<IUserViewManager> userviewManagerFactory,
+ IMediaEncoder mediaEncoder,
+ IItemRepository itemRepository,
+ IImageProcessor imageProcessor,
+ IMemoryCache memoryCache)
+ {
+ _appHost = appHost;
+ _logger = logger;
+ _taskManager = taskManager;
+ _userManager = userManager;
+ _configurationManager = configurationManager;
+ _userDataRepository = userDataRepository;
+ _libraryMonitorFactory = libraryMonitorFactory;
+ _fileSystem = fileSystem;
+ _providerManagerFactory = providerManagerFactory;
+ _userviewManagerFactory = userviewManagerFactory;
+ _mediaEncoder = mediaEncoder;
+ _itemRepository = itemRepository;
+ _imageProcessor = imageProcessor;
+ _memoryCache = memoryCache;
+
+ _configurationManager.ConfigurationUpdated += ConfigurationUpdated;
+
+ RecordConfigurationValues(configurationManager.Configuration);
+ }
/// <summary>
/// Occurs when [item added].
@@ -104,85 +168,64 @@ namespace Emby.Server.Implementations.Library
public event EventHandler<ItemChangeEventArgs> ItemRemoved;
/// <summary>
- /// The _logger
+ /// Gets the root folder.
/// </summary>
- private readonly ILogger _logger;
+ /// <value>The root folder.</value>
+ public AggregateFolder RootFolder
+ {
+ get
+ {
+ if (_rootFolder == null)
+ {
+ lock (_rootFolderSyncLock)
+ {
+ _rootFolder ??= CreateRootFolder();
+ }
+ }
- /// <summary>
- /// The _task manager
- /// </summary>
- private readonly ITaskManager _taskManager;
+ return _rootFolder;
+ }
+ }
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
+ private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
+
+ private IProviderManager ProviderManager => _providerManagerFactory.Value;
+
+ private IUserViewManager UserViewManager => _userviewManagerFactory.Value;
/// <summary>
- /// The _user data repository
+ /// Gets or sets the postscan tasks.
/// </summary>
- private readonly IUserDataManager _userDataRepository;
+ /// <value>The postscan tasks.</value>
+ private ILibraryPostScanTask[] PostscanTasks { get; set; } = Array.Empty<ILibraryPostScanTask>();
/// <summary>
- /// Gets or sets the configuration manager.
+ /// Gets or sets the intro providers.
/// </summary>
- /// <value>The configuration manager.</value>
- private IServerConfigurationManager ConfigurationManager { get; set; }
-
- private readonly Func<ILibraryMonitor> _libraryMonitorFactory;
- private readonly Func<IProviderManager> _providerManagerFactory;
- private readonly Func<IUserViewManager> _userviewManager;
- public bool IsScanRunning { get; private set; }
- private IServerApplicationHost _appHost;
+ /// <value>The intro providers.</value>
+ private IIntroProvider[] IntroProviders { get; set; } = Array.Empty<IIntroProvider>();
/// <summary>
- /// The _library items cache
+ /// Gets or sets the list of entity resolution ignore rules.
/// </summary>
- private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
+ /// <value>The entity resolution ignore rules.</value>
+ private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; } = Array.Empty<IResolverIgnoreRule>();
+
/// <summary>
- /// Gets the library items cache.
+ /// Gets or sets the list of currently registered entity resolvers.
/// </summary>
- /// <value>The library items cache.</value>
- private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache => _libraryItemsCache;
+ /// <value>The entity resolvers enumerable.</value>
+ private IItemResolver[] EntityResolvers { get; set; } = Array.Empty<IItemResolver>();
- private readonly IFileSystem _fileSystem;
+ private IMultiItemResolver[] MultiItemResolvers { get; set; } = Array.Empty<IMultiItemResolver>();
/// <summary>
- /// Initializes a new instance of the <see cref="LibraryManager" /> class.
+ /// Gets or sets the comparers.
/// </summary>
- /// <param name="logger">The logger.</param>
- /// <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>
- public LibraryManager(
- IServerApplicationHost appHost,
- ILoggerFactory loggerFactory,
- ITaskManager taskManager,
- IUserManager userManager,
- IServerConfigurationManager configurationManager,
- IUserDataManager userDataRepository,
- Func<ILibraryMonitor> libraryMonitorFactory,
- IFileSystem fileSystem,
- Func<IProviderManager> providerManagerFactory,
- Func<IUserViewManager> userviewManager)
- {
- _logger = loggerFactory.CreateLogger(nameof(LibraryManager));
- _taskManager = taskManager;
- _userManager = userManager;
- ConfigurationManager = configurationManager;
- _userDataRepository = userDataRepository;
- _libraryMonitorFactory = libraryMonitorFactory;
- _fileSystem = fileSystem;
- _providerManagerFactory = providerManagerFactory;
- _userviewManager = userviewManager;
- _appHost = appHost;
- _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
-
- ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
+ /// <value>The comparers.</value>
+ private IBaseItemComparer[] Comparers { get; set; } = Array.Empty<IBaseItemComparer>();
- RecordConfigurationValues(configurationManager.Configuration);
- }
+ public bool IsScanRunning { get; private set; }
/// <summary>
/// Adds the parts.
@@ -191,8 +234,9 @@ 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 postscan tasks.</param>
- public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
+ /// <param name="postscanTasks">The post scan tasks.</param>
+ public void AddParts(
+ IEnumerable<IResolverIgnoreRule> rules,
IEnumerable<IItemResolver> resolvers,
IEnumerable<IIntroProvider> introProviders,
IEnumerable<IBaseItemComparer> itemComparers,
@@ -203,47 +247,9 @@ namespace Emby.Server.Implementations.Library
MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
IntroProviders = introProviders.ToArray();
Comparers = itemComparers.ToArray();
-
- PostscanTasks = postscanTasks.OrderBy(i =>
- {
- var hasOrder = i as IHasOrder;
-
- return hasOrder == null ? 0 : hasOrder.Order;
-
- }).ToArray();
- }
-
- /// <summary>
- /// The _root folder
- /// </summary>
- private volatile AggregateFolder _rootFolder;
- /// <summary>
- /// The _root folder sync lock
- /// </summary>
- private readonly object _rootFolderSyncLock = new object();
- /// <summary>
- /// Gets the root folder.
- /// </summary>
- /// <value>The root folder.</value>
- public AggregateFolder RootFolder
- {
- get
- {
- if (_rootFolder == null)
- {
- lock (_rootFolderSyncLock)
- {
- if (_rootFolder == null)
- {
- _rootFolder = CreateRootFolder();
- }
- }
- }
- return _rootFolder;
- }
+ PostscanTasks = postscanTasks.ToArray();
}
- private bool _wizardCompleted;
/// <summary>
/// Records the configuration values.
/// </summary>
@@ -258,9 +264,9 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
- void ConfigurationUpdated(object sender, EventArgs e)
+ private void ConfigurationUpdated(object sender, EventArgs e)
{
- var config = ConfigurationManager.Configuration;
+ var config = _configurationManager.Configuration;
var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
@@ -278,33 +284,23 @@ namespace Emby.Server.Implementations.Library
{
throw new ArgumentNullException(nameof(item));
}
+
if (item is IItemByName)
{
- if (!(item is MusicArtist))
+ if (item is not MusicArtist)
{
return;
}
}
-
- else if (item.IsFolder)
- {
- //if (!(item is ICollectionFolder) && !(item is UserView) && !(item is Channel) && !(item is AggregateFolder))
- //{
- // if (item.SourceType != SourceType.Library)
- // {
- // return;
- // }
- //}
- }
- else
+ else if (!item.IsFolder)
{
- if (!(item is Video) && !(item is LiveTvChannel))
+ if (item is not Video && item is not LiveTvChannel)
{
return;
}
}
- LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
+ _memoryCache.Set(item.Id, item);
}
public void DeleteItem(BaseItem item, DeleteOptions options)
@@ -345,12 +341,14 @@ namespace Emby.Server.Implementations.Library
// channel no longer installed
}
}
+
options.DeleteFileLocation = false;
}
if (item is LiveTvProgram)
{
- _logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ _logger.LogDebug(
+ "Removing item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -358,7 +356,8 @@ namespace Emby.Server.Implementations.Library
}
else
{
- _logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ _logger.LogInformation(
+ "Removing item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -371,19 +370,25 @@ namespace Emby.Server.Implementations.Library
foreach (var metadataPath in GetMetadataPaths(item, children))
{
- _logger.LogDebug("Deleting path {0}", metadataPath);
+ if (!Directory.Exists(metadataPath))
+ {
+ continue;
+ }
+
+ _logger.LogDebug(
+ "Deleting metadata path, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ item.GetType().Name,
+ item.Name ?? "Unknown name",
+ metadataPath,
+ item.Id);
try
{
Directory.Delete(metadataPath, true);
}
- catch (IOException)
- {
-
- }
catch (Exception ex)
{
- _logger.LogError(ex, "Error deleting {metadataPath}", metadataPath);
+ _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
}
}
@@ -393,13 +398,19 @@ namespace Emby.Server.Implementations.Library
// Add this flag to GetDeletePaths if required in the future
var isRequiredForDelete = true;
- foreach (var fileSystemInfo in item.GetDeletePaths().ToList())
+ foreach (var fileSystemInfo in item.GetDeletePaths())
{
- if (File.Exists(fileSystemInfo.FullName))
+ if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
{
try
{
- _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName);
+ _logger.LogInformation(
+ "Deleting item path, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ item.GetType().Name,
+ item.Name ?? "Unknown name",
+ fileSystemInfo.FullName,
+ item.Id);
+
if (fileSystemInfo.IsDirectory)
{
Directory.Delete(fileSystemInfo.FullName, true);
@@ -431,13 +442,13 @@ namespace Emby.Server.Implementations.Library
item.SetParent(null);
- ItemRepository.DeleteItem(item.Id, CancellationToken.None);
+ _itemRepository.DeleteItem(item.Id);
foreach (var child in children)
{
- ItemRepository.DeleteItem(child.Id, CancellationToken.None);
+ _itemRepository.DeleteItem(child.Id);
}
- _libraryItemsCache.TryRemove(item.Id, out BaseItem removed);
+ _memoryCache.Remove(item.Id);
ReportItemRemoved(item, parent);
}
@@ -497,20 +508,22 @@ namespace Emby.Server.Implementations.Library
{
throw new ArgumentNullException(nameof(key));
}
+
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
- if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath))
+ string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
+ if (key.StartsWith(programDataPath, StringComparison.Ordinal))
{
// Try to normalize paths located underneath program-data in an attempt to make them more portable
- key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
- .TrimStart(new[] { '/', '\\' })
- .Replace("/", "\\");
+ key = key.Substring(programDataPath.Length)
+ .TrimStart('/', '\\')
+ .Replace('/', '\\');
}
- if (forceCaseInsensitive || !ConfigurationManager.Configuration.EnableCaseSensitiveItemIds)
+ if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
{
key = key.ToLowerInvariant();
}
@@ -520,13 +533,11 @@ namespace Emby.Server.Implementations.Library
return key.GetMD5();
}
- public BaseItem ResolvePath(FileSystemMetadata fileInfo,
- Folder parent = null)
- {
- return ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent);
- }
+ public BaseItem ResolvePath(FileSystemMetadata fileInfo, Folder parent = null)
+ => ResolvePath(fileInfo, new DirectoryService(_fileSystem), null, parent);
- private BaseItem ResolvePath(FileSystemMetadata fileInfo,
+ private BaseItem ResolvePath(
+ FileSystemMetadata fileInfo,
IDirectoryService directoryService,
IItemResolver[] resolvers,
Folder parent = null,
@@ -545,10 +556,9 @@ namespace Emby.Server.Implementations.Library
collectionType = GetContentTypeOverride(fullPath, true);
}
- var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
+ var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, directoryService)
{
Parent = parent,
- Path = fullPath,
FileInfo = fileInfo,
CollectionType = collectionType,
LibraryOptions = libraryOptions
@@ -581,7 +591,7 @@ namespace Emby.Server.Implementations.Library
{
_logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
- files = new FileSystemMetadata[] { };
+ files = Array.Empty<FileSystemMetadata>();
}
else
{
@@ -609,13 +619,7 @@ namespace Emby.Server.Implementations.Library
}
public bool IgnoreFile(FileSystemMetadata file, BaseItem parent)
- {
- if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)))
- {
- return true;
- }
- return false;
- }
+ => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
{
@@ -640,10 +644,10 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Determines whether a path should be ignored based on its contents - called after the contents have been read
+ /// 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>
+ /// <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
@@ -655,7 +659,8 @@ namespace Emby.Server.Implementations.Library
return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
}
- public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
+ public IEnumerable<BaseItem> ResolvePaths(
+ IEnumerable<FileSystemMetadata> files,
IDirectoryService directoryService,
Folder parent,
LibraryOptions libraryOptions,
@@ -679,8 +684,9 @@ namespace Emby.Server.Implementations.Library
foreach (var item in items)
{
- ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
+ ResolverHelper.SetInitialItemValues(item, parent, this, directoryService);
}
+
items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
return items;
}
@@ -690,39 +696,49 @@ namespace Emby.Server.Implementations.Library
return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
}
- private IEnumerable<BaseItem> ResolveFileList(IEnumerable<FileSystemMetadata> fileList,
+ private IEnumerable<BaseItem> ResolveFileList(
+ IReadOnlyList<FileSystemMetadata> fileList,
IDirectoryService directoryService,
Folder parent,
string collectionType,
IItemResolver[] resolvers,
LibraryOptions libraryOptions)
{
- return fileList.Select(f =>
+ // Given that fileList is a list we can save enumerator allocations by indexing
+ for (var i = 0; i < fileList.Count; i++)
{
+ var file = fileList[i];
+ BaseItem result = null;
try
{
- return ResolvePath(f, directoryService, resolvers, parent, collectionType, libraryOptions);
+ result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error resolving path {path}", f.FullName);
- return null;
+ _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
}
- }).Where(i => i != null);
+
+ if (result != null)
+ {
+ yield return result;
+ }
+ }
}
/// <summary>
- /// Creates the root media folder
+ /// Creates the root media folder.
/// </summary>
/// <returns>AggregateFolder.</returns>
- /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
+ /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</exception>
public AggregateFolder CreateRootFolder()
{
- var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
Directory.CreateDirectory(rootFolderPath);
- var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy<Folder, AggregateFolder>();
+ var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
+ ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)))
+ .DeepCopy<Folder, AggregateFolder>();
// In case program data folder was moved
if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
@@ -732,7 +748,7 @@ namespace Emby.Server.Implementations.Library
}
// Add in the plug-in folders
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "playlists");
+ var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
Directory.CreateDirectory(path);
@@ -763,7 +779,7 @@ namespace Emby.Server.Implementations.Library
if (folder.ParentId != rootFolder.Id)
{
folder.ParentId = rootFolder.Id;
- folder.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None);
+ folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
}
rootFolder.AddVirtualChild(folder);
@@ -773,24 +789,33 @@ namespace Emby.Server.Implementations.Library
return rootFolder;
}
- private volatile UserRootFolder _userRootFolder;
- private readonly object _syncLock = new object();
public Folder GetUserRootFolder()
{
if (_userRootFolder == null)
{
- lock (_syncLock)
+ lock (_userRootFolderSyncLock)
{
if (_userRootFolder == null)
{
- var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
+ _logger.LogDebug("Creating userRootPath at {path}", userRootPath);
Directory.CreateDirectory(userRootPath);
- var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder;
+ var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
+ UserRootFolder tmpItem = null;
+ try
+ {
+ tmpItem = GetItemById(newItemId) as UserRootFolder;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error creating UserRootFolder {path}", newItemId);
+ }
if (tmpItem == null)
{
+ _logger.LogDebug("Creating new userRootFolder with DeepCopy");
tmpItem = ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath))).DeepCopy<Folder, UserRootFolder>();
}
@@ -802,6 +827,7 @@ namespace Emby.Server.Implementations.Library
}
_userRootFolder = tmpItem;
+ _logger.LogDebug("Setting userRootFolder: {folder}", _userRootFolder);
}
}
}
@@ -813,19 +839,16 @@ namespace Emby.Server.Implementations.Library
{
// If this returns multiple items it could be tricky figuring out which one is correct.
// In most cases, the newest one will be and the others obsolete but not yet cleaned up
-
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
- //_logger.LogInformation("FindByPath {0}", path);
-
var query = new InternalItemsQuery
{
Path = path,
IsFolder = isFolder,
- OrderBy = new[] { ItemSortBy.DateCreated }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(),
+ OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
Limit = 1,
DtoOptions = new DtoOptions(true)
};
@@ -835,17 +858,31 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Gets a Person
+ /// Gets the person.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Task{Person}.</returns>
public Person GetPerson(string name)
{
- return CreateItemByName<Person>(Person.GetPath, name, new DtoOptions(true));
+ var path = Person.GetPath(name);
+ var id = GetItemByNameId<Person>(path);
+ if (GetItemById(id) is not Person item)
+ {
+ item = new Person
+ {
+ Name = name,
+ Id = id,
+ DateCreated = DateTime.UtcNow,
+ DateModified = DateTime.UtcNow,
+ Path = path
+ };
+ }
+
+ return item;
}
/// <summary>
- /// Gets a Studio
+ /// Gets the studio.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Task{Studio}.</returns>
@@ -856,21 +893,21 @@ namespace Emby.Server.Implementations.Library
public Guid GetStudioId(string name)
{
- return GetItemByNameId<Studio>(Studio.GetPath, name);
+ return GetItemByNameId<Studio>(Studio.GetPath(name));
}
public Guid GetGenreId(string name)
{
- return GetItemByNameId<Genre>(Genre.GetPath, name);
+ return GetItemByNameId<Genre>(Genre.GetPath(name));
}
public Guid GetMusicGenreId(string name)
{
- return GetItemByNameId<MusicGenre>(MusicGenre.GetPath, name);
+ return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
}
/// <summary>
- /// Gets a Genre
+ /// Gets the genre.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Task{Genre}.</returns>
@@ -880,7 +917,7 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Gets the genre.
+ /// Gets the music genre.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Task{MusicGenre}.</returns>
@@ -890,11 +927,10 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Gets a Year
+ /// Gets the year.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>Task{Year}.</returns>
- /// <exception cref="ArgumentOutOfRangeException"></exception>
public Year GetYear(int value)
{
if (value <= 0)
@@ -908,7 +944,7 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Gets a Genre
+ /// Gets a Genre.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Task{Genre}.</returns>
@@ -929,10 +965,9 @@ namespace Emby.Server.Implementations.Library
{
var existing = GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(T).Name },
+ IncludeItemTypes = new[] { nameof(MusicArtist) },
Name = name,
DtoOptions = options
-
}).Cast<MusicArtist>()
.OrderBy(i => i.IsAccessedByName ? 1 : 0)
.Cast<T>()
@@ -944,13 +979,11 @@ namespace Emby.Server.Implementations.Library
}
}
- var id = GetItemByNameId<T>(getPathFn, name);
-
+ var path = getPathFn(name);
+ var id = GetItemByNameId<T>(path);
var item = GetItemById(id) as T;
-
if (item == null)
{
- var path = getPathFn(name);
item = new T
{
Name = name,
@@ -966,11 +999,10 @@ namespace Emby.Server.Implementations.Library
return item;
}
- private Guid GetItemByNameId<T>(Func<string, string> getPathFn, string name)
+ private Guid GetItemByNameId<T>(string path)
where T : BaseItem, new()
{
- var path = getPathFn(name);
- var forceCaseInsensitiveId = ConfigurationManager.Configuration.EnableNormalizedItemByNameIds;
+ var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
}
@@ -984,13 +1016,13 @@ namespace Emby.Server.Implementations.Library
public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
{
// Ensure the location is available.
- Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
+ Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
}
/// <summary>
- /// Reloads the root media folder
+ /// Reloads the root media folder.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
@@ -1021,7 +1053,7 @@ namespace Emby.Server.Implementations.Library
public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
{
IsScanRunning = true;
- _libraryMonitorFactory().Stop();
+ LibraryMonitor.Stop();
try
{
@@ -1029,27 +1061,32 @@ namespace Emby.Server.Implementations.Library
}
finally
{
- _libraryMonitorFactory().Start();
+ LibraryMonitor.Start();
IsScanRunning = false;
}
}
private async Task ValidateTopLibraryFolders(CancellationToken cancellationToken)
{
- var rootChildren = RootFolder.Children.ToList();
- rootChildren = GetUserRootFolder().Children.ToList();
-
await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
// Start by just validating the children of the root, but go no further
- await RootFolder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false);
+ await RootFolder.ValidateChildren(
+ new SimpleProgress<double>(),
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
+ recursive: false,
+ cancellationToken).ConfigureAwait(false);
await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
- await GetUserRootFolder().ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false);
+ await GetUserRootFolder().ValidateChildren(
+ new SimpleProgress<double>(),
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
+ recursive: false,
+ cancellationToken).ConfigureAwait(false);
// Quickly scan CollectionFolders for changes
- foreach (var folder in GetUserRootFolder().Children.OfType<Folder>().ToList())
+ foreach (var folder in GetUserRootFolder().Children.OfType<Folder>())
{
await folder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
@@ -1063,10 +1100,10 @@ namespace Emby.Server.Implementations.Library
var innerProgress = new ActionableProgress<double>();
- innerProgress.RegisterAction(pct => progress.Report(pct * .96));
+ innerProgress.RegisterAction(pct => progress.Report(pct * 0.96));
- // Now validate the entire media library
- await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: true).ConfigureAwait(false);
+ // Validate the entire media library
+ await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true, cancellationToken).ConfigureAwait(false);
progress.Report(96);
@@ -1074,7 +1111,6 @@ namespace Emby.Server.Implementations.Library
innerProgress.RegisterAction(pct => progress.Report(96 + (pct * .04)));
- // Run post-scan tasks
await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
progress.Report(100);
@@ -1125,7 +1161,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error running postscan task");
+ _logger.LogError(ex, "Error running post-scan task");
}
numComplete++;
@@ -1134,7 +1170,7 @@ namespace Emby.Server.Implementations.Library
progress.Report(percent * 100);
}
- ItemRepository.UpdateInheritedValues(cancellationToken);
+ _itemRepository.UpdateInheritedValues();
progress.Report(100);
}
@@ -1150,13 +1186,14 @@ namespace Emby.Server.Implementations.Library
public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
{
+ _logger.LogDebug("Getting topLibraryFolders");
var topLibraryFolders = GetUserRootFolder().Children.ToList();
- var refreshQueue = includeRefreshState ? _providerManagerFactory().GetRefreshQueue() : null;
+ _logger.LogDebug("Getting refreshQueue");
+ var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
- return _fileSystem.GetDirectoryPaths(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath)
+ return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
.Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
- .OrderBy(i => i.Name)
.ToList();
}
@@ -1191,12 +1228,12 @@ namespace Emby.Server.Implementations.Library
if (libraryFolder != null && libraryFolder.HasImage(ImageType.Primary))
{
- info.PrimaryImageItemId = libraryFolder.Id.ToString("N");
+ info.PrimaryImageItemId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
}
if (libraryFolder != null)
{
- info.ItemId = libraryFolder.Id.ToString("N");
+ info.ItemId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
info.LibraryOptions = GetLibraryOptions(libraryFolder);
if (refreshQueue != null)
@@ -1210,11 +1247,18 @@ namespace Emby.Server.Implementations.Library
return info;
}
- private string GetCollectionType(string path)
+ private CollectionTypeOptions? GetCollectionType(string path)
{
- return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
- .Select(i => Path.GetFileNameWithoutExtension(i))
- .FirstOrDefault(i => !string.IsNullOrEmpty(i));
+ var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false);
+ foreach (ReadOnlySpan<char> file in files)
+ {
+ if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
+ {
+ return res;
+ }
+ }
+
+ return null;
}
/// <summary>
@@ -1222,15 +1266,15 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="id">The id.</param>
/// <returns>BaseItem.</returns>
- /// <exception cref="ArgumentNullException">id</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
public BaseItem GetItemById(Guid id)
{
if (id == Guid.Empty)
{
- throw new ArgumentException(nameof(id), "Guid can't be empty");
+ throw new ArgumentException("Guid can't be empty", nameof(id));
}
- if (LibraryItemsCache.TryGetValue(id, out BaseItem item))
+ if (_memoryCache.TryGetValue(id, out BaseItem item))
{
return item;
}
@@ -1247,7 +1291,7 @@ namespace Emby.Server.Implementations.Library
public List<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
{
- if (query.Recursive && !query.ParentId.Equals(Guid.Empty))
+ if (query.Recursive && query.ParentId != Guid.Empty)
{
var parent = GetItemById(query.ParentId);
if (parent != null)
@@ -1261,7 +1305,7 @@ namespace Emby.Server.Implementations.Library
AddUserToQuery(query, query.User, allowExternalContent);
}
- return ItemRepository.GetItemList(query);
+ return _itemRepository.GetItemList(query);
}
public List<BaseItem> GetItemList(InternalItemsQuery query)
@@ -1285,7 +1329,7 @@ namespace Emby.Server.Implementations.Library
AddUserToQuery(query, query.User);
}
- return ItemRepository.GetCount(query);
+ return _itemRepository.GetCount(query);
}
public List<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
@@ -1300,7 +1344,7 @@ namespace Emby.Server.Implementations.Library
}
}
- return ItemRepository.GetItemList(query);
+ return _itemRepository.GetItemList(query);
}
public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
@@ -1312,12 +1356,12 @@ namespace Emby.Server.Implementations.Library
if (query.EnableTotalRecordCount)
{
- return ItemRepository.GetItems(query);
+ return _itemRepository.GetItems(query);
}
return new QueryResult<BaseItem>
{
- Items = ItemRepository.GetItemList(query).ToArray()
+ Items = _itemRepository.GetItemList(query)
};
}
@@ -1328,7 +1372,7 @@ namespace Emby.Server.Implementations.Library
AddUserToQuery(query, query.User);
}
- return ItemRepository.GetItemIdsList(query);
+ return _itemRepository.GetItemIdsList(query);
}
public QueryResult<(BaseItem, ItemCounts)> GetStudios(InternalItemsQuery query)
@@ -1339,7 +1383,7 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetStudios(query);
+ return _itemRepository.GetStudios(query);
}
public QueryResult<(BaseItem, ItemCounts)> GetGenres(InternalItemsQuery query)
@@ -1350,7 +1394,7 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetGenres(query);
+ return _itemRepository.GetGenres(query);
}
public QueryResult<(BaseItem, ItemCounts)> GetMusicGenres(InternalItemsQuery query)
@@ -1361,7 +1405,7 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetMusicGenres(query);
+ return _itemRepository.GetMusicGenres(query);
}
public QueryResult<(BaseItem, ItemCounts)> GetAllArtists(InternalItemsQuery query)
@@ -1372,7 +1416,7 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetAllArtists(query);
+ return _itemRepository.GetAllArtists(query);
}
public QueryResult<(BaseItem, ItemCounts)> GetArtists(InternalItemsQuery query)
@@ -1383,39 +1427,36 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetArtists(query);
+ return _itemRepository.GetArtists(query);
}
private void SetTopParentOrAncestorIds(InternalItemsQuery query)
{
- if (query.AncestorIds.Length == 0)
+ var ancestorIds = query.AncestorIds;
+ int len = ancestorIds.Length;
+ if (len == 0)
{
return;
}
- var parents = query.AncestorIds.Select(i => GetItemById(i)).ToList();
-
- if (parents.All(i =>
+ var parents = new BaseItem[len];
+ for (int i = 0; i < len; i++)
{
- if (i is ICollectionFolder || i is UserView)
+ parents[i] = GetItemById(ancestorIds[i]);
+ if (!(parents[i] is ICollectionFolder || parents[i] is UserView))
{
- return true;
+ return;
}
+ }
- //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
- return false;
+ // Optimize by querying against top level views
+ query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
+ query.AncestorIds = Array.Empty<Guid>();
- }))
+ // Prevent searching in all libraries due to empty filter
+ if (query.TopParentIds.Length == 0)
{
- // Optimize by querying against top level views
- query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
- query.AncestorIds = Array.Empty<Guid>();
-
- // Prevent searching in all libraries due to empty filter
- if (query.TopParentIds.Length == 0)
- {
- query.TopParentIds = new[] { Guid.NewGuid() };
- }
+ query.TopParentIds = new[] { Guid.NewGuid() };
}
}
@@ -1427,7 +1468,7 @@ namespace Emby.Server.Implementations.Library
}
SetTopParentOrAncestorIds(query);
- return ItemRepository.GetAlbumArtists(query);
+ return _itemRepository.GetAlbumArtists(query);
}
public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
@@ -1448,30 +1489,18 @@ namespace Emby.Server.Implementations.Library
if (query.EnableTotalRecordCount)
{
- return ItemRepository.GetItems(query);
+ return _itemRepository.GetItems(query);
}
- var list = ItemRepository.GetItemList(query);
-
return new QueryResult<BaseItem>
{
- Items = list.ToArray()
+ Items = _itemRepository.GetItemList(query)
};
}
private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents)
{
- if (parents.All(i =>
- {
- if (i is ICollectionFolder || i is UserView)
- {
- return true;
- }
-
- //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
- return false;
-
- }))
+ if (parents.All(i => i is ICollectionFolder || i is UserView))
{
// Optimize by querying against top level views
query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
@@ -1501,13 +1530,13 @@ namespace Emby.Server.Implementations.Library
{
if (query.AncestorIds.Length == 0 &&
query.ParentId.Equals(Guid.Empty) &&
- query.ChannelIds.Length == 0 &&
+ query.ChannelIds.Count == 0 &&
query.TopParentIds.Length == 0 &&
string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
query.ItemIds.Length == 0)
{
- var userViews = _userviewManager().GetUserViews(new UserViewQuery
+ var userViews = UserViewManager.GetUserViews(new UserViewQuery
{
UserId = user.Id,
IncludeHidden = true,
@@ -1520,11 +1549,9 @@ namespace Emby.Server.Implementations.Library
private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
{
- var view = item as UserView;
-
- if (view != null)
+ if (item is UserView view)
{
- if (string.Equals(view.ViewType, CollectionType.LiveTv))
+ if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.Ordinal))
{
return new[] { view.Id };
}
@@ -1537,8 +1564,10 @@ namespace Emby.Server.Implementations.Library
{
return GetTopParentIdsForQuery(displayParent, user);
}
+
return Array.Empty<Guid>();
}
+
if (!view.ParentId.Equals(Guid.Empty))
{
var displayParent = GetItemById(view.ParentId);
@@ -1546,11 +1575,13 @@ namespace Emby.Server.Implementations.Library
{
return GetTopParentIdsForQuery(displayParent, user);
}
+
return Array.Empty<Guid>();
}
// Handle grouping
- if (user != null && !string.IsNullOrEmpty(view.ViewType) && UserView.IsEligibleForGrouping(view.ViewType) && user.Configuration.GroupedFolders.Length > 0)
+ if (user != null && !string.IsNullOrEmpty(view.ViewType) && UserView.IsEligibleForGrouping(view.ViewType)
+ && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
{
return GetUserRootFolder()
.GetChildren(user, true)
@@ -1559,11 +1590,11 @@ namespace Emby.Server.Implementations.Library
.Where(i => user.IsFolderGrouped(i.Id))
.SelectMany(i => GetTopParentIdsForQuery(i, user));
}
+
return Array.Empty<Guid>();
}
- var collectionFolder = item as CollectionFolder;
- if (collectionFolder != null)
+ if (item is CollectionFolder collectionFolder)
{
return collectionFolder.PhysicalFolderIds;
}
@@ -1573,6 +1604,7 @@ namespace Emby.Server.Implementations.Library
{
return new[] { topParent.Id };
}
+
return Array.Empty<Guid>();
}
@@ -1585,7 +1617,6 @@ namespace Emby.Server.Implementations.Library
public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
{
var tasks = IntroProviders
- .OrderBy(i => i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1)
.Take(1)
.Select(i => GetIntros(i, item, user));
@@ -1728,22 +1759,20 @@ namespace Emby.Server.Implementations.Library
return orderedItems ?? items;
}
- public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<ValueTuple<string, SortOrder>> orderByList)
+ public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<ValueTuple<string, SortOrder>> orderBy)
{
var isFirst = true;
IOrderedEnumerable<BaseItem> orderedItems = null;
- foreach (var orderBy in orderByList)
+ foreach (var (name, sortOrder) in orderBy)
{
- var comparer = GetComparer(orderBy.Item1, user);
+ var comparer = GetComparer(name, user);
if (comparer == null)
{
continue;
}
- var sortOrder = orderBy.Item2;
-
if (isFirst)
{
orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, comparer) : items.OrderBy(i => i, comparer);
@@ -1769,19 +1798,16 @@ namespace Emby.Server.Implementations.Library
{
var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
- if (comparer != null)
+ // If it requires a user, create a new one, and assign the user
+ if (comparer is IUserBaseItemComparer)
{
- // If it requires a user, create a new one, and assign the user
- if (comparer is IUserBaseItemComparer)
- {
- var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
+ var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
- userComparer.User = user;
- userComparer.UserManager = _userManager;
- userComparer.UserDataRepository = _userDataRepository;
+ userComparer.User = user;
+ userComparer.UserManager = _userManager;
+ userComparer.UserDataRepository = _userDataRepository;
- return userComparer;
- }
+ return userComparer;
}
return comparer;
@@ -1792,7 +1818,6 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="item">The item.</param>
/// <param name="parent">The parent item.</param>
- /// <returns>Task.</returns>
public void CreateItem(BaseItem item, BaseItem parent)
{
CreateItems(new[] { item }, parent, CancellationToken.None);
@@ -1802,11 +1827,11 @@ namespace Emby.Server.Implementations.Library
/// Creates the items.
/// </summary>
/// <param name="items">The items.</param>
+ /// <param name="parent">The parent item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
+ public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
{
- ItemRepository.SaveItems(items, cancellationToken);
+ _itemRepository.SaveItems(items, cancellationToken);
foreach (var item in items)
{
@@ -1825,11 +1850,13 @@ namespace Emby.Server.Implementations.Library
try
{
- ItemAdded(this, new ItemChangeEventArgs
- {
- Item = item,
- Parent = parent ?? item.GetParent()
- });
+ ItemAdded(
+ this,
+ new ItemChangeEventArgs
+ {
+ Item = item,
+ Parent = parent ?? item.GetParent()
+ });
}
catch (Exception ex)
{
@@ -1839,34 +1866,119 @@ namespace Emby.Server.Implementations.Library
}
}
- public void UpdateImages(BaseItem item)
+ private bool ImageNeedsRefresh(ItemImageInfo image)
{
- ItemRepository.SaveImages(item);
+ if (image.Path != null && image.IsLocalFile)
+ {
+ if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
+ {
+ return true;
+ }
- RegisterItem(item);
+ try
+ {
+ return _fileSystem.GetLastWriteTimeUtc(image.Path) != image.DateModified;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
+ return false;
+ }
+ }
+
+ return image.Path != null && !image.IsLocalFile;
}
- /// <summary>
- /// Updates the item.
- /// </summary>
- public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
{
- foreach (var item in items)
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ var outdated = forceUpdate ? item.ImageInfos.Where(i => i.Path != null).ToArray() : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
+ // Skip image processing if current or live tv source
+ if (outdated.Length == 0 || item.SourceType != SourceType.Library)
+ {
+ RegisterItem(item);
+ return;
+ }
+
+ foreach (var img in outdated)
{
- if (item.IsFileProtocol)
+ var image = img;
+ if (!img.IsLocalFile)
{
- _providerManagerFactory().SaveMetadata(item, updateReason);
+ try
+ {
+ var index = item.GetImageIndex(img);
+ image = await ConvertImageToLocal(item, img, index).ConfigureAwait(false);
+ }
+ catch (ArgumentException)
+ {
+ _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
+ continue;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException || ex is IOException)
+ {
+ _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
+ continue;
+ }
+ catch (HttpRequestException ex)
+ {
+ _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode);
+ continue;
+ }
}
- item.DateLastSaved = DateTime.UtcNow;
+ try
+ {
+ ImageDimensions size = _imageProcessor.GetImageDimensions(item, image);
+ image.Width = size.Width;
+ image.Height = size.Height;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
+ image.Width = 0;
+ image.Height = 0;
+ continue;
+ }
- RegisterItem(item);
+ try
+ {
+ image.BlurHash = _imageProcessor.GetImageBlurHash(image.Path);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
+ image.BlurHash = string.Empty;
+ }
+
+ try
+ {
+ image.DateModified = _fileSystem.GetLastWriteTimeUtc(image.Path);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
+ }
}
- //var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
- //_logger.LogDebug("Saving {0} to database.", logName);
+ _itemRepository.SaveImages(item);
+ RegisterItem(item);
+ }
+
+ /// <inheritdoc />
+ public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
+ {
+ foreach (var item in items)
+ {
+ await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
+ }
- ItemRepository.SaveItems(items, cancellationToken);
+ _itemRepository.SaveItems(items, cancellationToken);
if (ItemUpdated != null)
{
@@ -1880,12 +1992,14 @@ namespace Emby.Server.Implementations.Library
try
{
- ItemUpdated(this, new ItemChangeEventArgs
- {
- Item = item,
- Parent = parent,
- UpdateReason = updateReason
- });
+ ItemUpdated(
+ this,
+ new ItemChangeEventArgs
+ {
+ Item = item,
+ Parent = parent,
+ UpdateReason = updateReason
+ });
}
catch (Exception ex)
{
@@ -1895,33 +2009,40 @@ namespace Emby.Server.Implementations.Library
}
}
- /// <summary>
- /// Updates the item.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="updateReason">The update reason.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
+ => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken);
+
+ public Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
{
- UpdateItems(new [] { item }, parent, updateReason, cancellationToken);
+ if (item.IsFileProtocol)
+ {
+ ProviderManager.SaveMetadata(item, updateReason);
+ }
+
+ item.DateLastSaved = DateTime.UtcNow;
+
+ return UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate);
}
/// <summary>
/// Reports the item removed.
/// </summary>
/// <param name="item">The item.</param>
+ /// <param name="parent">The parent item.</param>
public void ReportItemRemoved(BaseItem item, BaseItem parent)
{
if (ItemRemoved != null)
{
try
{
- ItemRemoved(this, new ItemChangeEventArgs
- {
- Item = item,
- Parent = parent
- });
+ ItemRemoved(
+ this,
+ new ItemChangeEventArgs
+ {
+ Item = item,
+ Parent = parent
+ });
}
catch (Exception ex)
{
@@ -1937,7 +2058,7 @@ namespace Emby.Server.Implementations.Library
/// <returns>BaseItem.</returns>
public BaseItem RetrieveItem(Guid id)
{
- return ItemRepository.RetrieveItem(id);
+ return _itemRepository.RetrieveItem(id);
}
public List<Folder> GetCollectionFolders(BaseItem item)
@@ -1959,7 +2080,7 @@ namespace Emby.Server.Implementations.Library
return new List<Folder>();
}
- return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType<Folder>().ToList());
+ return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType<Folder>());
}
public List<Folder> GetCollectionFolders(BaseItem item, List<Folder> allUserRootChildren)
@@ -1984,21 +2105,20 @@ namespace Emby.Server.Implementations.Library
return GetCollectionFoldersInternal(item, allUserRootChildren);
}
- private static List<Folder> GetCollectionFoldersInternal(BaseItem item, List<Folder> allUserRootChildren)
+ private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
{
return allUserRootChildren
- .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase))
+ .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path.AsSpan(), StringComparison.OrdinalIgnoreCase))
.ToList();
}
public LibraryOptions GetLibraryOptions(BaseItem item)
{
- var collectionFolder = item as CollectionFolder;
- if (collectionFolder == null)
+ if (item is not CollectionFolder collectionFolder)
{
+ // List.Find is more performant than FirstOrDefault due to enumerator allocation
collectionFolder = GetCollectionFolders(item)
- .OfType<CollectionFolder>()
- .FirstOrDefault();
+ .Find(folder => folder is CollectionFolder) as CollectionFolder;
}
return collectionFolder == null ? new LibraryOptions() : collectionFolder.GetLibraryOptions();
@@ -2047,8 +2167,7 @@ namespace Emby.Server.Implementations.Library
public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
{
- var collectionFolder = item as ICollectionFolder;
- if (collectionFolder != null)
+ if (item is ICollectionFolder collectionFolder)
{
return collectionFolder.CollectionType;
}
@@ -2058,13 +2177,11 @@ namespace Emby.Server.Implementations.Library
private string GetContentTypeOverride(string path, bool inherit)
{
- var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path) || (inherit && !string.IsNullOrEmpty(i.Name) && _fileSystem.ContainsSubPath(i.Name, path)));
- if (nameValuePair != null)
- {
- return nameValuePair.Value;
- }
-
- return null;
+ var nameValuePair = _configurationManager.Configuration.ContentTypes
+ .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
+ || (inherit && !string.IsNullOrEmpty(i.Name)
+ && _fileSystem.ContainsSubPath(i.Name, path)));
+ return nameValuePair?.Value;
}
private string GetTopFolderContentType(BaseItem item)
@@ -2081,6 +2198,7 @@ namespace Emby.Server.Implementations.Library
{
break;
}
+
item = parent;
}
@@ -2091,10 +2209,8 @@ namespace Emby.Server.Implementations.Library
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
- private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
- //private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromMinutes(1);
-
- public UserView GetNamedView(User user,
+ public UserView GetNamedView(
+ User user,
string name,
string viewType,
string sortName)
@@ -2102,13 +2218,15 @@ namespace Emby.Server.Implementations.Library
return GetNamedView(user, name, Guid.Empty, viewType, sortName);
}
- public UserView GetNamedView(string name,
+ public UserView GetNamedView(
+ string name,
string viewType,
string sortName)
{
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath,
- "views",
- _fileSystem.GetValidFilename(viewType));
+ var path = Path.Combine(
+ _configurationManager.ApplicationPaths.InternalMetadataPath,
+ "views",
+ _fileSystem.GetValidFilename(viewType));
var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
@@ -2137,25 +2255,26 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None);
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal);
+ item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
+ ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
}
return item;
}
- public UserView GetNamedView(User user,
+ public UserView GetNamedView(
+ User user,
string name,
Guid parentId,
string viewType,
string sortName)
{
- var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N");
- var idValues = "38_namedview_" + name + user.Id.ToString("N") + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
+ var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
+ var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
var id = GetNewItemId(idValues, typeof(UserView));
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
+ var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
var item = GetItemById(id) as UserView;
@@ -2173,11 +2292,10 @@ namespace Emby.Server.Implementations.Library
Name = name,
ViewType = viewType,
ForcedSortName = sortName,
- UserId = user.Id
+ UserId = user.Id,
+ DisplayParentId = parentId
};
- item.DisplayParentId = parentId;
-
CreateItem(item, null);
isNew = true;
@@ -2193,20 +2311,23 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- // Need to force save to increment DateLastSaved
- ForceSave = true
-
- }, RefreshPriority.Normal);
+ ProviderManager.QueueRefresh(
+ item.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ // Need to force save to increment DateLastSaved
+ ForceSave = true
+ },
+ RefreshPriority.Normal);
}
return item;
}
- public UserView GetShadowView(BaseItem parent,
- string viewType,
- string sortName)
+ public UserView GetShadowView(
+ BaseItem parent,
+ string viewType,
+ string sortName)
{
if (parent == null)
{
@@ -2257,18 +2378,21 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- // Need to force save to increment DateLastSaved
- ForceSave = true
-
- }, RefreshPriority.Normal);
+ ProviderManager.QueueRefresh(
+ item.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ // Need to force save to increment DateLastSaved
+ ForceSave = true
+ },
+ RefreshPriority.Normal);
}
return item;
}
- public UserView GetNamedView(string name,
+ public UserView GetNamedView(
+ string name,
Guid parentId,
string viewType,
string sortName,
@@ -2279,7 +2403,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(name));
}
- var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N");
+ var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
if (!string.IsNullOrEmpty(uniqueId))
{
@@ -2288,7 +2412,7 @@ namespace Emby.Server.Implementations.Library
var id = GetNewItemId(idValues, typeof(UserView));
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
+ var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
var item = GetItemById(id) as UserView;
@@ -2318,7 +2442,7 @@ namespace Emby.Server.Implementations.Library
if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
{
item.ViewType = viewType;
- item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
+ item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult();
}
var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
@@ -2331,54 +2455,71 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- // Need to force save to increment DateLastSaved
- ForceSave = true
- }, RefreshPriority.Normal);
+ ProviderManager.QueueRefresh(
+ item.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ // Need to force save to increment DateLastSaved
+ ForceSave = true
+ },
+ RefreshPriority.Normal);
}
return item;
}
- public void AddExternalSubtitleStreams(List<MediaStream> streams,
+ public void AddExternalSubtitleStreams(
+ List<MediaStream> streams,
string videoPath,
string[] files)
{
- new SubtitleResolver(BaseItem.LocalizationManager, _fileSystem).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files);
+ new SubtitleResolver(BaseItem.LocalizationManager).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files);
}
- public bool IsVideoFile(string path, LibraryOptions libraryOptions)
+ public BaseItem GetParentItem(string parentId, Guid? userId)
{
- var resolver = new VideoResolver(GetNamingOptions());
- return resolver.IsVideoFile(path);
+ if (string.IsNullOrEmpty(parentId))
+ {
+ return GetParentItem((Guid?)null, userId);
+ }
+
+ return GetParentItem(new Guid(parentId), userId);
}
- public bool IsVideoFile(string path)
+ public BaseItem GetParentItem(Guid? parentId, Guid? userId)
{
- return IsVideoFile(path, new LibraryOptions());
+ if (parentId.HasValue)
+ {
+ return GetItemById(parentId.Value);
+ }
+
+ if (userId.HasValue && userId != Guid.Empty)
+ {
+ return GetUserRootFolder();
+ }
+
+ return RootFolder;
}
- public bool IsAudioFile(string path, LibraryOptions libraryOptions)
+ /// <inheritdoc />
+ public bool IsVideoFile(string path)
{
- var parser = new AudioFileParser(GetNamingOptions());
- return parser.IsAudioFile(path);
+ return VideoResolver.IsVideoFile(path, GetNamingOptions());
}
+ /// <inheritdoc />
public bool IsAudioFile(string path)
- {
- return IsAudioFile(path, new LibraryOptions());
- }
+ => AudioFileParser.IsAudioFile(path, GetNamingOptions());
+ /// <inheritdoc />
public int? GetSeasonNumberFromPath(string path)
- {
- return new SeasonPathParser(GetNamingOptions()).Parse(path, true, true).SeasonNumber;
- }
+ => SeasonPathParser.Parse(path, true, true).SeasonNumber;
+ /// <inheritdoc />
public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
{
var series = episode.Series;
- bool? isAbsoluteNaming = series == null ? false : string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
+ bool? isAbsoluteNaming = series != null && string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
if (!isAbsoluteNaming.Value)
{
// In other words, no filter applied
@@ -2389,13 +2530,58 @@ namespace Emby.Server.Implementations.Library
var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
- var episodeInfo = episode.IsFileProtocol ?
- resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) :
- new Naming.TV.EpisodeInfo();
+ // TODO nullable - what are we trying to do there with empty episodeInfo?
+ EpisodeInfo episodeInfo = null;
+ if (episode.IsFileProtocol)
+ {
+ episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
+ // Resolve from parent folder if it's not the Season folder
+ var parent = episode.GetParent();
+ if (episodeInfo == null && parent.GetType() == typeof(Folder))
+ {
+ episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
+ if (episodeInfo != null)
+ {
+ // add the container
+ episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
+ }
+ }
+ }
- if (episodeInfo == null)
+ 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)
{
- episodeInfo = new Naming.TV.EpisodeInfo();
+ _logger.LogError(ex, "Error reading the episode informations with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
}
var changed = false;
@@ -2445,16 +2631,18 @@ namespace Emby.Server.Implementations.Library
{
changed = true;
}
+
episode.IndexNumber = episodeInfo.EpisodeNumber;
}
if (!episode.IndexNumberEnd.HasValue || forceRefresh)
{
- if (episode.IndexNumberEnd != episodeInfo.EndingEpsiodeNumber)
+ if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
{
changed = true;
}
- episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
+
+ episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
}
if (!episode.ParentIndexNumber.HasValue || forceRefresh)
@@ -2463,6 +2651,7 @@ namespace Emby.Server.Implementations.Library
{
changed = true;
}
+
episode.ParentIndexNumber = episodeInfo.SeasonNumber;
}
}
@@ -2475,6 +2664,15 @@ namespace Emby.Server.Implementations.Library
{
episode.ParentIndexNumber = season.IndexNumber;
}
+ else
+ {
+ /*
+ Anime series don't generally have a season in their file name, however,
+ tvdb needs a season to correctly get the metadata.
+ Hence, a null season needs to be filled with something. */
+ // FIXME perhaps this would be better for tvdb parser to ask for season 1 if no season is specified
+ episode.ParentIndexNumber = 1;
+ }
if (episode.ParentIndexNumber.HasValue)
{
@@ -2485,21 +2683,13 @@ namespace Emby.Server.Implementations.Library
return changed;
}
+ /// <inheritdoc />
public NamingOptions GetNamingOptions()
{
- return GetNamingOptionsInternal();
- }
-
- private NamingOptions _namingOptions;
- private string[] _videoFileExtensions;
- private NamingOptions GetNamingOptionsInternal()
- {
if (_namingOptions == null)
{
- var options = new NamingOptions();
-
- _namingOptions = options;
- _videoFileExtensions = _namingOptions.VideoFileExtensions.ToArray();
+ _namingOptions = new NamingOptions();
+ _videoFileExtensions = _namingOptions.VideoFileExtensions;
}
return _namingOptions;
@@ -2507,14 +2697,12 @@ namespace Emby.Server.Implementations.Library
public ItemLookupInfo ParseName(string name)
{
- var resolver = new VideoResolver(GetNamingOptions());
-
- var result = resolver.CleanDateTime(name);
- var cleanName = resolver.CleanString(result.Name);
+ var namingOptions = GetNamingOptions();
+ var result = VideoResolver.CleanDateTime(name, namingOptions);
return new ItemLookupInfo
{
- Name = cleanName.Name,
+ Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName.ToString() : result.Name,
Year = result.Year
};
}
@@ -2524,19 +2712,17 @@ namespace Emby.Server.Implementations.Library
var namingOptions = GetNamingOptions();
var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
- .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
+ .Where(i => string.Equals(i.Name, BaseItem.TrailersFolderName, StringComparison.OrdinalIgnoreCase))
.SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
.ToList();
- var videoListResolver = new VideoListResolver(namingOptions);
-
- var videos = videoListResolver.Resolve(fileSystemChildren);
+ var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions);
- var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
+ var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase));
if (currentVideo != null)
{
- files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
+ files.AddRange(currentVideo.Extras.Where(i => i.ExtraType == ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
}
var resolvers = new IItemResolver[]
@@ -2549,9 +2735,7 @@ namespace Emby.Server.Implementations.Library
.Select(video =>
{
// Try to retrieve it from the db. If we don't find it, use the resolved version
- var dbItem = GetItemById(video.Id) as Trailer;
-
- if (dbItem != null)
+ if (GetItemById(video.Id) is Trailer dbItem)
{
video = dbItem;
}
@@ -2567,26 +2751,22 @@ namespace Emby.Server.Implementations.Library
}).OrderBy(i => i.Path);
}
- private static readonly string[] ExtrasSubfolderNames = new[] { "extras", "specials", "shorts", "scenes", "featurettes", "behind the scenes", "deleted scenes", "interviews" };
-
public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
{
var namingOptions = GetNamingOptions();
var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
- .Where(i => ExtrasSubfolderNames.Contains(i.Name ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ .Where(i => BaseItem.AllExtrasTypesFolderNames.ContainsKey(i.Name ?? string.Empty))
.SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
.ToList();
- var videoListResolver = new VideoListResolver(namingOptions);
-
- var videos = videoListResolver.Resolve(fileSystemChildren);
+ var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions);
- var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
+ var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase));
if (currentVideo != null)
{
- files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
+ files.AddRange(currentVideo.Extras.Where(i => i.ExtraType != ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
}
return ResolvePaths(files, directoryService, null, new LibraryOptions(), null)
@@ -2614,6 +2794,7 @@ namespace Emby.Server.Implementations.Library
public string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem)
{
+ string newPath;
if (ownerItem != null)
{
var libraryOptions = GetLibraryOptions(ownerItem);
@@ -2621,41 +2802,27 @@ namespace Emby.Server.Implementations.Library
{
foreach (var pathInfo in libraryOptions.PathInfos)
{
- if (string.IsNullOrWhiteSpace(pathInfo.Path) || string.IsNullOrWhiteSpace(pathInfo.NetworkPath))
+ if (path.TryReplaceSubPath(pathInfo.Path, pathInfo.NetworkPath, out newPath))
{
- continue;
- }
-
- var substitutionResult = SubstitutePathInternal(path, pathInfo.Path, pathInfo.NetworkPath);
- if (substitutionResult.Item2)
- {
- return substitutionResult.Item1;
+ return newPath;
}
}
}
}
- var metadataPath = ConfigurationManager.Configuration.MetadataPath;
- var metadataNetworkPath = ConfigurationManager.Configuration.MetadataNetworkPath;
+ var metadataPath = _configurationManager.Configuration.MetadataPath;
+ var metadataNetworkPath = _configurationManager.Configuration.MetadataNetworkPath;
- if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath))
+ if (path.TryReplaceSubPath(metadataPath, metadataNetworkPath, out newPath))
{
- var metadataSubstitutionResult = SubstitutePathInternal(path, metadataPath, metadataNetworkPath);
- if (metadataSubstitutionResult.Item2)
- {
- return metadataSubstitutionResult.Item1;
- }
+ return newPath;
}
- foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
+ foreach (var map in _configurationManager.Configuration.PathSubstitutions)
{
- if (!string.IsNullOrWhiteSpace(map.From))
+ if (path.TryReplaceSubPath(map.From, map.To, out newPath))
{
- var substitutionResult = SubstitutePathInternal(path, map.From, map.To);
- if (substitutionResult.Item2)
- {
- return substitutionResult.Item1;
- }
+ return newPath;
}
}
@@ -2664,45 +2831,12 @@ namespace Emby.Server.Implementations.Library
public string SubstitutePath(string path, string from, string to)
{
- return SubstitutePathInternal(path, from, to).Item1;
- }
-
- private Tuple<string, bool> SubstitutePathInternal(string path, string from, string to)
- {
- if (string.IsNullOrWhiteSpace(path))
+ if (path.TryReplaceSubPath(from, to, out var newPath))
{
- throw new ArgumentNullException(nameof(path));
- }
- if (string.IsNullOrWhiteSpace(from))
- {
- throw new ArgumentNullException(nameof(from));
- }
- if (string.IsNullOrWhiteSpace(to))
- {
- throw new ArgumentNullException(nameof(to));
- }
-
- from = from.Trim();
- to = to.Trim();
-
- var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
- var changed = false;
-
- if (!string.Equals(newPath, path))
- {
- if (to.IndexOf('/') != -1)
- {
- newPath = newPath.Replace('\\', '/');
- }
- else
- {
- newPath = newPath.Replace('/', '\\');
- }
-
- changed = true;
+ return newPath;
}
- return new Tuple<string, bool>(newPath, changed);
+ return path;
}
private void SetExtraTypeFromFilename(Video item)
@@ -2711,35 +2845,12 @@ namespace Emby.Server.Implementations.Library
var result = resolver.GetExtraInfo(item.Path);
- if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase))
- {
- item.ExtraType = ExtraType.DeletedScene;
- }
- else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase))
- {
- item.ExtraType = ExtraType.BehindTheScenes;
- }
- else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase))
- {
- item.ExtraType = ExtraType.Interview;
- }
- else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase))
- {
- item.ExtraType = ExtraType.Scene;
- }
- else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase))
- {
- item.ExtraType = ExtraType.Sample;
- }
- else
- {
- item.ExtraType = ExtraType.Clip;
- }
+ item.ExtraType = result.ExtraType;
}
public List<PersonInfo> GetPeople(InternalPeopleQuery query)
{
- return ItemRepository.GetPeople(query);
+ return _itemRepository.GetPeople(query);
}
public List<PersonInfo> GetPeople(BaseItem item)
@@ -2762,7 +2873,7 @@ namespace Emby.Server.Implementations.Library
public List<Person> GetPeopleItems(InternalPeopleQuery query)
{
- return ItemRepository.GetPeopleNames(query).Select(i =>
+ return _itemRepository.GetPeopleNames(query).Select(i =>
{
try
{
@@ -2773,23 +2884,30 @@ namespace Emby.Server.Implementations.Library
_logger.LogError(ex, "Error getting person");
return null;
}
-
}).Where(i => i != null).ToList();
}
public List<string> GetPeopleNames(InternalPeopleQuery query)
{
- return ItemRepository.GetPeopleNames(query);
+ return _itemRepository.GetPeopleNames(query);
}
public void UpdatePeople(BaseItem item, List<PersonInfo> people)
{
+ UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
+ }
+
+ /// <inheritdoc />
+ public async Task UpdatePeopleAsync(BaseItem item, List<PersonInfo> people, CancellationToken cancellationToken)
+ {
if (!item.SupportsPeople)
{
return;
}
- ItemRepository.UpdatePeople(item.Id, people);
+ _itemRepository.UpdatePeople(item.Id, people);
+
+ await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
}
public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex)
@@ -2800,30 +2918,32 @@ namespace Emby.Server.Implementations.Library
{
_logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
- await _providerManagerFactory().SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
+ await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
- item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
return item.GetImageInfo(image.Type, imageIndex);
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
+ if (ex.StatusCode.HasValue
+ && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{
continue;
}
+
throw;
}
}
// Remove this image to prevent it from retrying over and over
item.RemoveImage(image);
- item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
throw new InvalidOperationException();
}
- public async Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary)
+ public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary)
{
if (string.IsNullOrWhiteSpace(name))
{
@@ -2832,7 +2952,7 @@ namespace Emby.Server.Implementations.Library
name = _fileSystem.GetValidFilename(name);
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, name);
while (Directory.Exists(virtualFolderPath))
@@ -2851,15 +2971,15 @@ namespace Emby.Server.Implementations.Library
}
}
- _libraryMonitorFactory().Stop();
+ LibraryMonitor.Stop();
try
{
Directory.CreateDirectory(virtualFolderPath);
- if (!string.IsNullOrEmpty(collectionType))
+ if (collectionType != null)
{
- var path = Path.Combine(virtualFolderPath, collectionType + ".collection");
+ var path = Path.Combine(virtualFolderPath, collectionType.ToString().ToLowerInvariant() + ".collection");
File.WriteAllBytes(path, Array.Empty<byte>());
}
@@ -2886,9 +3006,61 @@ namespace Emby.Server.Implementations.Library
{
// Need to add a delay here or directory watchers may still pick up the changes
await Task.Delay(1000).ConfigureAwait(false);
- _libraryMonitorFactory().Start();
+ LibraryMonitor.Start();
+ }
+ }
+ }
+
+ private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
+ {
+ var personsToSave = new List<BaseItem>();
+
+ foreach (var person in people)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var itemUpdateType = ItemUpdateType.MetadataDownload;
+ var saveEntity = false;
+ var personEntity = GetPerson(person.Name);
+
+ // if PresentationUniqueKey is empty it's likely a new item.
+ if (string.IsNullOrEmpty(personEntity.PresentationUniqueKey))
+ {
+ personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
+ saveEntity = true;
+ }
+
+ foreach (var id in person.ProviderIds)
+ {
+ if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase))
+ {
+ personEntity.SetProviderId(id.Key, id.Value);
+ saveEntity = true;
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
+ {
+ personEntity.SetImage(
+ new ItemImageInfo
+ {
+ Path = person.ImageUrl,
+ Type = ImageType.Primary
+ },
+ 0);
+
+ saveEntity = true;
+ itemUpdateType = ItemUpdateType.ImageUpdate;
+ }
+
+ if (saveEntity)
+ {
+ personsToSave.Add(personEntity);
+ await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
}
}
+
+ CreateItems(personsToSave, null, CancellationToken.None);
}
private void StartScanInBackground()
@@ -2900,25 +3072,9 @@ namespace Emby.Server.Implementations.Library
});
}
- private static bool ValidateNetworkPath(string path)
+ public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
{
- //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- //{
- // // We can't validate protocol-based paths, so just allow them
- // if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
- // {
- // return Directory.Exists(path);
- // }
- //}
-
- // Without native support for unc, we cannot validate this when running under mono
- return true;
- }
-
- private const string ShortcutFileExtension = ".mblink";
- public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
- {
- AddMediaPathInternal(virtualFolderName, pathInfo, true);
+ AddMediaPathInternal(virtualFolderName, mediaPath, true);
}
private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
@@ -2932,7 +3088,7 @@ namespace Emby.Server.Implementations.Library
if (string.IsNullOrWhiteSpace(path))
{
- throw new ArgumentNullException(nameof(path));
+ throw new ArgumentException(nameof(path));
}
if (!Directory.Exists(path))
@@ -2940,12 +3096,7 @@ namespace Emby.Server.Implementations.Library
throw new FileNotFoundException("The path does not exist.");
}
- if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
- {
- throw new FileNotFoundException("The network path does not exist.");
- }
-
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
var shortcutFilename = Path.GetFileNameWithoutExtension(path);
@@ -2976,19 +3127,14 @@ namespace Emby.Server.Implementations.Library
}
}
- public void UpdateMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
+ public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
{
- if (pathInfo == null)
+ if (mediaPath == null)
{
- throw new ArgumentNullException(nameof(pathInfo));
- }
-
- if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
- {
- throw new FileNotFoundException("The network path does not exist.");
+ throw new ArgumentNullException(nameof(mediaPath));
}
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
@@ -2998,9 +3144,9 @@ namespace Emby.Server.Implementations.Library
var list = libraryOptions.PathInfos.ToList();
foreach (var originalPathInfo in list)
{
- if (string.Equals(pathInfo.Path, originalPathInfo.Path, StringComparison.Ordinal))
+ if (string.Equals(mediaPath.Path, originalPathInfo.Path, StringComparison.Ordinal))
{
- originalPathInfo.NetworkPath = pathInfo.NetworkPath;
+ originalPathInfo.NetworkPath = mediaPath.NetworkPath;
break;
}
}
@@ -3023,10 +3169,7 @@ namespace Emby.Server.Implementations.Library
{
if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
{
- list.Add(new MediaPathInfo
- {
- Path = location
- });
+ list.Add(new MediaPathInfo(location));
}
}
@@ -3041,7 +3184,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(name));
}
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
var path = Path.Combine(rootFolderPath, name);
@@ -3050,7 +3193,7 @@ namespace Emby.Server.Implementations.Library
throw new FileNotFoundException("The media folder does not exist");
}
- _libraryMonitorFactory().Stop();
+ LibraryMonitor.Stop();
try
{
@@ -3070,7 +3213,7 @@ namespace Emby.Server.Implementations.Library
{
// Need to add a delay here or directory watchers may still pick up the changes
await Task.Delay(1000).ConfigureAwait(false);
- _libraryMonitorFactory().Start();
+ LibraryMonitor.Start();
}
}
}
@@ -3084,7 +3227,7 @@ namespace Emby.Server.Implementations.Library
var removeList = new List<NameValuePair>();
- foreach (var contentType in ConfigurationManager.Configuration.ContentTypes)
+ foreach (var contentType in _configurationManager.Configuration.ContentTypes)
{
if (string.IsNullOrWhiteSpace(contentType.Name))
{
@@ -3099,11 +3242,11 @@ namespace Emby.Server.Implementations.Library
if (removeList.Count > 0)
{
- ConfigurationManager.Configuration.ContentTypes = ConfigurationManager.Configuration.ContentTypes
+ _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
.Except(removeList)
- .ToArray();
+ .ToArray();
- ConfigurationManager.SaveConfiguration();
+ _configurationManager.SaveConfiguration();
}
}
@@ -3114,12 +3257,13 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(mediaPath));
}
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
if (!Directory.Exists(virtualFolderPath))
{
- throw new FileNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
+ throw new FileNotFoundException(
+ string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolderName));
}
var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
index c3082a78a..83acd8e9f 100644
--- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs
+++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
@@ -1,18 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library
@@ -21,15 +27,13 @@ namespace Emby.Server.Implementations.Library
{
private readonly IMediaEncoder _mediaEncoder;
private readonly ILogger _logger;
+ private readonly IApplicationPaths _appPaths;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- private IJsonSerializer _json;
- private IApplicationPaths _appPaths;
-
- public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IJsonSerializer json, IApplicationPaths appPaths)
+ public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IApplicationPaths appPaths)
{
_mediaEncoder = mediaEncoder;
_logger = logger;
- _json = json;
_appPaths = appPaths;
}
@@ -40,15 +44,16 @@ namespace Emby.Server.Implementations.Library
var now = DateTime.UtcNow;
MediaInfo mediaInfo = null;
- var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N") + ".json");
+ var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
if (!string.IsNullOrEmpty(cacheKey))
{
try
{
- mediaInfo = _json.DeserializeFromFile<MediaInfo>(cacheFilePath);
+ await using FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
+ mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
- //_logger.LogDebug("Found cached media info");
+ // _logger.LogDebug("Found cached media info");
}
catch
{
@@ -70,20 +75,22 @@ namespace Emby.Server.Implementations.Library
mediaSource.AnalyzeDurationMs = 3000;
- mediaInfo = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
- {
- MediaSource = mediaSource,
- MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
- ExtractChapters = false
-
- }, cancellationToken).ConfigureAwait(false);
+ mediaInfo = await _mediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
+ {
+ MediaSource = mediaSource,
+ MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
+ ExtractChapters = false
+ },
+ cancellationToken).ConfigureAwait(false);
if (cacheFilePath != null)
{
Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
- _json.SerializeToFile(mediaInfo, cacheFilePath);
+ await using FileStream createStream = AsyncFile.OpenWrite(cacheFilePath);
+ await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);
- //_logger.LogDebug("Saved media info to {0}", cacheFilePath);
+ // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
}
}
@@ -124,7 +131,7 @@ namespace Emby.Server.Implementations.Library
mediaSource.RunTimeTicks = null;
}
- var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Audio);
+ var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
if (audioStream == null || audioStream.Index == -1)
{
@@ -135,7 +142,7 @@ namespace Emby.Server.Implementations.Library
mediaSource.DefaultAudioStreamIndex = audioStream.Index;
}
- var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Video);
+ var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
if (videoStream != null)
{
if (!videoStream.BitRate.HasValue)
@@ -146,17 +153,14 @@ namespace Emby.Server.Implementations.Library
{
videoStream.BitRate = 30000000;
}
-
else if (width >= 1900)
{
videoStream.BitRate = 20000000;
}
-
else if (width >= 1200)
{
videoStream.BitRate = 8000000;
}
-
else if (width >= 700)
{
videoStream.BitRate = 2000000;
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index 24ab8e761..351fced34 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -1,10 +1,19 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
@@ -12,32 +21,36 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library
{
public class MediaSourceManager : IMediaSourceManager, IDisposable
{
+ // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
+ private const char LiveStreamIdDelimeter = '_';
+
private readonly IItemRepository _itemRepo;
private readonly IUserManager _userManager;
private readonly ILibraryManager _libraryManager;
- private readonly IJsonSerializer _jsonSerializer;
private readonly IFileSystem _fileSystem;
+ private readonly ILogger<MediaSourceManager> _logger;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IApplicationPaths _appPaths;
+
+ private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase);
+ private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private IMediaSourceProvider[] _providers;
- private readonly ILogger _logger;
- private readonly IUserDataManager _userDataManager;
- private readonly Func<IMediaEncoder> _mediaEncoder;
- private ILocalizationManager _localizationManager;
- private IApplicationPaths _appPaths;
public MediaSourceManager(
IItemRepository itemRepo,
@@ -45,17 +58,15 @@ namespace Emby.Server.Implementations.Library
ILocalizationManager localizationManager,
IUserManager userManager,
ILibraryManager libraryManager,
- ILoggerFactory loggerFactory,
- IJsonSerializer jsonSerializer,
+ ILogger<MediaSourceManager> logger,
IFileSystem fileSystem,
IUserDataManager userDataManager,
- Func<IMediaEncoder> mediaEncoder)
+ IMediaEncoder mediaEncoder)
{
_itemRepo = itemRepo;
_userManager = userManager;
_libraryManager = libraryManager;
- _logger = loggerFactory.CreateLogger(nameof(MediaSourceManager));
- _jsonSerializer = jsonSerializer;
+ _logger = logger;
_fileSystem = fileSystem;
_userDataManager = userDataManager;
_mediaEncoder = mediaEncoder;
@@ -128,18 +139,34 @@ namespace Emby.Server.Implementations.Library
return streams;
}
- public async Task<List<MediaSourceInfo>> GetPlayackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
+ {
+ return _itemRepo.GetMediaAttachments(query);
+ }
+
+ /// <inheritdoc />
+ public List<MediaAttachment> GetMediaAttachments(Guid itemId)
+ {
+ return GetMediaAttachments(new MediaAttachmentQuery
+ {
+ ItemId = itemId
+ });
+ }
+
+ public async Task<List<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken)
{
var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video))
{
- await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- EnableRemoteContentProbe = true,
- MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh
-
- }, cancellationToken).ConfigureAwait(false);
+ await item.RefreshMetadata(
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ EnableRemoteContentProbe = true,
+ MetadataRefreshMode = MetadataRefreshMode.FullRefresh
+ },
+ cancellationToken).ConfigureAwait(false);
mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
}
@@ -172,15 +199,17 @@ namespace Emby.Server.Implementations.Library
{
if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
{
- if (!user.Policy.EnableAudioPlaybackTranscoding)
- {
- source.SupportsTranscoding = false;
- }
+ source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding);
+ }
+ else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
+ {
+ source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding);
+ source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing);
}
}
}
- return SortMediaSources(list).Where(i => i.Type != MediaSourceType.Placeholder).ToList();
+ return SortMediaSources(list);
}
public MediaProtocol GetPathProtocol(string path)
@@ -189,22 +218,27 @@ namespace Emby.Server.Implementations.Library
{
return MediaProtocol.Rtsp;
}
+
if (path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
{
return MediaProtocol.Rtmp;
}
+
if (path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
{
return MediaProtocol.Http;
}
+
if (path.StartsWith("rtp", StringComparison.OrdinalIgnoreCase))
{
return MediaProtocol.Rtp;
}
+
if (path.StartsWith("ftp", StringComparison.OrdinalIgnoreCase))
{
return MediaProtocol.Ftp;
}
+
if (path.StartsWith("udp", StringComparison.OrdinalIgnoreCase))
{
return MediaProtocol.Udp;
@@ -269,7 +303,7 @@ namespace Emby.Server.Implementations.Library
private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
{
- var prefix = provider.GetType().FullName.GetMD5().ToString("N") + LiveStreamIdDelimeter;
+ var prefix = provider.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + LiveStreamIdDelimeter;
if (!string.IsNullOrEmpty(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
@@ -289,7 +323,7 @@ namespace Emby.Server.Implementations.Library
return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false);
}
- var sources = await GetPlayackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).ConfigureAwait(false);
+ var sources = await GetPlaybackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).ConfigureAwait(false);
return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
}
@@ -318,7 +352,7 @@ namespace Emby.Server.Implementations.Library
private string[] NormalizeLanguage(string language)
{
- if (language == null)
+ if (string.IsNullOrEmpty(language))
{
return Array.Empty<string>();
}
@@ -334,7 +368,9 @@ namespace Emby.Server.Implementations.Library
private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowRememberingSelection)
{
- if (userData.SubtitleStreamIndex.HasValue && user.Configuration.RememberSubtitleSelections && user.Configuration.SubtitleMode != SubtitlePlaybackMode.None && allowRememberingSelection)
+ if (userData.SubtitleStreamIndex.HasValue
+ && user.RememberSubtitleSelections
+ && user.SubtitleMode != SubtitlePlaybackMode.None && allowRememberingSelection)
{
var index = userData.SubtitleStreamIndex.Value;
// Make sure the saved index is still valid
@@ -345,26 +381,25 @@ namespace Emby.Server.Implementations.Library
}
}
- var preferredSubs = string.IsNullOrEmpty(user.Configuration.SubtitleLanguagePreference)
- ? Array.Empty<string>() : NormalizeLanguage(user.Configuration.SubtitleLanguagePreference);
+ var preferredSubs = NormalizeLanguage(user.SubtitleLanguagePreference);
var defaultAudioIndex = source.DefaultAudioStreamIndex;
var audioLangage = defaultAudioIndex == null
? null
: source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();
- source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(source.MediaStreams,
+ source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(
+ source.MediaStreams,
preferredSubs,
- user.Configuration.SubtitleMode,
+ user.SubtitleMode,
audioLangage);
- MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs,
- user.Configuration.SubtitleMode, audioLangage);
+ MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs, user.SubtitleMode, audioLangage);
}
private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowRememberingSelection)
{
- if (userData.AudioStreamIndex.HasValue && user.Configuration.RememberAudioSelections && allowRememberingSelection)
+ if (userData.AudioStreamIndex.HasValue && user.RememberAudioSelections && allowRememberingSelection)
{
var index = userData.AudioStreamIndex.Value;
// Make sure the saved index is still valid
@@ -375,11 +410,9 @@ namespace Emby.Server.Implementations.Library
}
}
- var preferredAudio = string.IsNullOrEmpty(user.Configuration.AudioLanguagePreference)
- ? Array.Empty<string>()
- : NormalizeLanguage(user.Configuration.AudioLanguagePreference);
+ var preferredAudio = NormalizeLanguage(user.AudioLanguagePreference);
- source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.Configuration.PlayDefaultAudioTrack);
+ source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.PlayDefaultAudioTrack);
}
public void SetDefaultAudioAndSubtitleStreamIndexes(BaseItem item, MediaSourceInfo source, User user)
@@ -407,7 +440,7 @@ namespace Emby.Server.Implementations.Library
}
}
- private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
+ private static List<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
{
return sources.OrderBy(i =>
{
@@ -417,20 +450,17 @@ namespace Emby.Server.Implementations.Library
}
return 1;
-
}).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
.ThenByDescending(i =>
{
var stream = i.VideoStream;
- return stream == null || stream.Width == null ? 0 : stream.Width.Value;
+ return stream?.Width ?? 0;
})
+ .Where(i => i.Type != MediaSourceType.Placeholder)
.ToList();
}
- private readonly Dictionary<string, ILiveStream> _openStreams = new Dictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase);
- private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
-
public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest request, CancellationToken cancellationToken)
{
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -478,7 +508,7 @@ namespace Emby.Server.Implementations.Library
// hack - these two values were taken from LiveTVMediaSourceProvider
string cacheKey = request.OpenToken;
- await new LiveStreamHelper(_mediaEncoder(), _logger, _jsonSerializer, _appPaths)
+ await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths)
.AddMediaInfoWithProbe(mediaSource, isAudio, cacheKey, true, cancellationToken)
.ConfigureAwait(false);
}
@@ -490,9 +520,9 @@ namespace Emby.Server.Implementations.Library
}
// TODO: @bond Fix
- var json = _jsonSerializer.SerializeToString(mediaSource);
- _logger.LogInformation("Live stream opened: " + json);
- var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
+ var json = JsonSerializer.SerializeToUtf8Bytes(mediaSource, _jsonOptions);
+ _logger.LogInformation("Live stream opened: {@MediaSource}", mediaSource);
+ var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions);
if (!request.UserId.Equals(Guid.Empty))
{
@@ -503,11 +533,7 @@ namespace Emby.Server.Implementations.Library
SetDefaultAudioAndSubtitleStreamIndexes(item, clone, user);
}
- return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse
- {
- MediaSource = clone
-
- }, liveStream as IDirectStreamProvider);
+ return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDirectStreamProvider);
}
private static void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio)
@@ -520,7 +546,7 @@ namespace Emby.Server.Implementations.Library
mediaSource.RunTimeTicks = null;
}
- var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Audio);
+ var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
if (audioStream == null || audioStream.Index == -1)
{
@@ -531,7 +557,7 @@ namespace Emby.Server.Implementations.Library
mediaSource.DefaultAudioStreamIndex = audioStream.Index;
}
- var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Video);
+ var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
if (videoStream != null)
{
if (!videoStream.BitRate.HasValue)
@@ -542,17 +568,14 @@ namespace Emby.Server.Implementations.Library
{
videoStream.BitRate = 30000000;
}
-
else if (width >= 1900)
{
videoStream.BitRate = 20000000;
}
-
else if (width >= 1200)
{
videoStream.BitRate = 8000000;
}
-
else if (width >= 700)
{
videoStream.BitRate = 2000000;
@@ -564,31 +587,6 @@ namespace Emby.Server.Implementations.Library
mediaSource.InferTotalBitrate();
}
- public async Task<IDirectStreamProvider> GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken)
- {
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
- {
- var info = _openStreams.Values.FirstOrDefault(i =>
- {
- var liveStream = i as ILiveStream;
- if (liveStream != null)
- {
- return string.Equals(liveStream.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase);
- }
-
- return false;
- });
-
- return info as IDirectStreamProvider;
- }
- finally
- {
- _liveStreamSemaphore.Release();
- }
- }
-
public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationToken)
{
var result = await OpenLiveStreamInternal(request, cancellationToken).ConfigureAwait(false);
@@ -597,19 +595,21 @@ namespace Emby.Server.Implementations.Library
public async Task<MediaSourceInfo> GetLiveStreamMediaInfo(string id, CancellationToken cancellationToken)
{
- var liveStreamInfo = await GetLiveStreamInfo(id, cancellationToken).ConfigureAwait(false);
+ // TODO probably shouldn't throw here but it is kept for "backwards compatibility"
+ var liveStreamInfo = GetLiveStreamInfo(id) ?? throw new ResourceNotFoundException();
var mediaSource = liveStreamInfo.MediaSource;
if (liveStreamInfo is IDirectStreamProvider)
{
- var info = await _mediaEncoder().GetMediaInfo(new MediaInfoRequest
- {
- MediaSource = mediaSource,
- ExtractChapters = false,
- MediaType = DlnaProfileType.Video
-
- }, cancellationToken).ConfigureAwait(false);
+ var info = await _mediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
+ {
+ MediaSource = mediaSource,
+ ExtractChapters = false,
+ MediaType = DlnaProfileType.Video
+ },
+ cancellationToken).ConfigureAwait(false);
mediaSource.MediaStreams = info.MediaStreams;
mediaSource.Container = info.Container;
@@ -626,15 +626,16 @@ namespace Emby.Server.Implementations.Library
var now = DateTime.UtcNow;
MediaInfo mediaInfo = null;
- var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N") + ".json");
+ var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
if (!string.IsNullOrEmpty(cacheKey))
{
try
{
- mediaInfo = _jsonSerializer.DeserializeFromFile<MediaInfo>(cacheFilePath);
+ await using FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
+ mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
- //_logger.LogDebug("Found cached media info");
+ // _logger.LogDebug("Found cached media info");
}
catch (Exception ex)
{
@@ -656,20 +657,22 @@ namespace Emby.Server.Implementations.Library
mediaSource.AnalyzeDurationMs = 3000;
}
- mediaInfo = await _mediaEncoder().GetMediaInfo(new MediaInfoRequest
+ mediaInfo = await _mediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
{
MediaSource = mediaSource,
MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
ExtractChapters = false
-
- }, cancellationToken).ConfigureAwait(false);
+ },
+ cancellationToken).ConfigureAwait(false);
if (cacheFilePath != null)
{
Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
- _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath);
+ await using FileStream createStream = File.Create(cacheFilePath);
+ await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);
- //_logger.LogDebug("Saved media info to {0}", cacheFilePath);
+ // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
}
}
@@ -735,17 +738,14 @@ namespace Emby.Server.Implementations.Library
{
videoStream.BitRate = 30000000;
}
-
else if (width >= 1900)
{
videoStream.BitRate = 20000000;
}
-
else if (width >= 1200)
{
videoStream.BitRate = 8000000;
}
-
else if (width >= 700)
{
videoStream.BitRate = 2000000;
@@ -765,41 +765,37 @@ namespace Emby.Server.Implementations.Library
mediaSource.InferTotalBitrate(true);
}
- public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, CancellationToken cancellationToken)
+ public Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
- var info = await GetLiveStreamInfo(id, cancellationToken).ConfigureAwait(false);
- return new Tuple<MediaSourceInfo, IDirectStreamProvider>(info.MediaSource, info as IDirectStreamProvider);
+ // TODO probably shouldn't throw here but it is kept for "backwards compatibility"
+ var info = GetLiveStreamInfo(id) ?? throw new ResourceNotFoundException();
+ return Task.FromResult(new Tuple<MediaSourceInfo, IDirectStreamProvider>(info.MediaSource, info as IDirectStreamProvider));
}
- private async Task<ILiveStream> GetLiveStreamInfo(string id, CancellationToken cancellationToken)
+ public ILiveStream GetLiveStreamInfo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ if (_openStreams.TryGetValue(id, out ILiveStream info))
{
- if (_openStreams.TryGetValue(id, out ILiveStream info))
- {
- return info;
- }
- else
- {
- throw new ResourceNotFoundException();
- }
- }
- finally
- {
- _liveStreamSemaphore.Release();
+ return info;
}
+
+ return null;
+ }
+
+ /// <inheritdoc />
+ public ILiveStream GetLiveStreamInfoByUniqueId(string uniqueId)
+ {
+ return _openStreams.Values.FirstOrDefault(stream => string.Equals(uniqueId, stream?.UniqueId, StringComparison.OrdinalIgnoreCase));
}
public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken)
@@ -827,7 +823,7 @@ namespace Emby.Server.Implementations.Library
if (liveStream.ConsumerCount <= 0)
{
- _openStreams.Remove(id);
+ _openStreams.TryRemove(id, out _);
_logger.LogInformation("Closing live stream {0}", id);
@@ -842,24 +838,21 @@ namespace Emby.Server.Implementations.Library
}
}
- // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
- private const char LiveStreamIdDelimeter = '_';
-
- private Tuple<IMediaSourceProvider, string> GetProvider(string key)
+ private (IMediaSourceProvider, string) GetProvider(string key)
{
if (string.IsNullOrEmpty(key))
{
- throw new ArgumentException("key");
+ throw new ArgumentException("Key can't be empty.", nameof(key));
}
- var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
+ var keys = key.Split(LiveStreamIdDelimeter, 2);
- var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), keys[0], StringComparison.OrdinalIgnoreCase));
+ var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), keys[0], StringComparison.OrdinalIgnoreCase));
- var splitIndex = key.IndexOf(LiveStreamIdDelimeter);
+ var splitIndex = key.IndexOf(LiveStreamIdDelimeter, StringComparison.Ordinal);
var keyId = key.Substring(splitIndex + 1);
- return new Tuple<IMediaSourceProvider, string>(provider, keyId);
+ return (provider, keyId);
}
/// <summary>
@@ -868,9 +861,9 @@ namespace Emby.Server.Implementations.Library
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
- private readonly object _disposeLock = new object();
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
@@ -879,15 +872,12 @@ namespace Emby.Server.Implementations.Library
{
if (dispose)
{
- lock (_disposeLock)
+ foreach (var key in _openStreams.Keys.ToList())
{
- foreach (var key in _openStreams.Keys.ToList())
- {
- var task = CloseLiveStream(key);
-
- Task.WaitAll(task);
- }
+ CloseLiveStream(key).GetAwaiter().GetResult();
}
+
+ _liveStreamSemaphore.Dispose();
}
}
}
diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs
index 0a6c8845d..b3837fedb 100644
--- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs
+++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs
@@ -1,7 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
-using MediaBrowser.Model.Configuration;
+using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library
@@ -33,14 +37,12 @@ namespace Emby.Server.Implementations.Library
return null;
}
- public static int? GetDefaultSubtitleStreamIndex(List<MediaStream> streams,
+ public static int? GetDefaultSubtitleStreamIndex(
+ IEnumerable<MediaStream> streams,
string[] preferredLanguages,
SubtitlePlaybackMode mode,
string audioTrackLanguage)
{
- streams = GetSortedStreams(streams, MediaStreamType.Subtitle, preferredLanguages)
- .ToList();
-
MediaStream stream = null;
if (mode == SubtitlePlaybackMode.None)
@@ -48,57 +50,53 @@ namespace Emby.Server.Implementations.Library
return null;
}
+ var sortedStreams = streams
+ .Where(i => i.Type == MediaStreamType.Subtitle)
+ .OrderByDescending(x => x.IsExternal)
+ .ThenByDescending(x => x.IsForced && string.Equals(x.Language, audioTrackLanguage, StringComparison.OrdinalIgnoreCase))
+ .ThenByDescending(x => x.IsForced)
+ .ThenByDescending(x => x.IsDefault)
+ .ToList();
+
if (mode == SubtitlePlaybackMode.Default)
{
// Prefer embedded metadata over smart logic
-
- stream = streams.FirstOrDefault(s => s.IsForced && string.Equals(s.Language, audioTrackLanguage, StringComparison.OrdinalIgnoreCase)) ??
- streams.FirstOrDefault(s => s.IsForced) ??
- streams.FirstOrDefault(s => s.IsDefault);
+ stream = sortedStreams.FirstOrDefault(s => s.IsExternal || s.IsForced || s.IsDefault);
// if the audio language is not understood by the user, load their preferred subs, if there are any
if (stream == null && !preferredLanguages.Contains(audioTrackLanguage, StringComparer.OrdinalIgnoreCase))
{
- stream = streams.Where(s => !s.IsForced).FirstOrDefault(s => preferredLanguages.Contains(s.Language, StringComparer.OrdinalIgnoreCase));
+ stream = sortedStreams.FirstOrDefault(s => !s.IsForced && preferredLanguages.Contains(s.Language, StringComparer.OrdinalIgnoreCase));
}
}
else if (mode == SubtitlePlaybackMode.Smart)
{
- // Prefer smart logic over embedded metadata
-
// if the audio language is not understood by the user, load their preferred subs, if there are any
if (!preferredLanguages.Contains(audioTrackLanguage, StringComparer.OrdinalIgnoreCase))
{
- stream = streams.Where(s => !s.IsForced).FirstOrDefault(s => preferredLanguages.Contains(s.Language, StringComparer.OrdinalIgnoreCase)) ??
+ stream = streams.FirstOrDefault(s => !s.IsForced && preferredLanguages.Contains(s.Language, StringComparer.OrdinalIgnoreCase)) ??
streams.FirstOrDefault(s => preferredLanguages.Contains(s.Language, StringComparer.OrdinalIgnoreCase));
}
}
else if (mode == SubtitlePlaybackMode.Always)
{
// always load the most suitable full subtitles
- stream = streams.FirstOrDefault(s => !s.IsForced);
+ stream = sortedStreams.FirstOrDefault(s => !s.IsForced);
}
else if (mode == SubtitlePlaybackMode.OnlyForced)
{
// always load the most suitable full subtitles
- stream = streams.FirstOrDefault(s => s.IsForced && string.Equals(s.Language, audioTrackLanguage, StringComparison.OrdinalIgnoreCase)) ??
- streams.FirstOrDefault(s => s.IsForced);
+ stream = sortedStreams.FirstOrDefault(x => x.IsForced);
}
// load forced subs if we have found no suitable full subtitles
- stream = stream ?? streams.FirstOrDefault(s => s.IsForced && string.Equals(s.Language, audioTrackLanguage, StringComparison.OrdinalIgnoreCase));
-
- if (stream != null)
- {
- return stream.Index;
- }
-
- return null;
+ stream ??= sortedStreams.FirstOrDefault(s => s.IsForced && string.Equals(s.Language, audioTrackLanguage, StringComparison.OrdinalIgnoreCase));
+ return stream?.Index;
}
private static IEnumerable<MediaStream> GetSortedStreams(IEnumerable<MediaStream> streams, MediaStreamType type, string[] languagePreferences)
{
- // Give some preferance to external text subs for better performance
+ // Give some preference to external text subs for better performance
return streams.Where(i => i.Type == type)
.OrderBy(i =>
{
@@ -113,7 +111,8 @@ namespace Emby.Server.Implementations.Library
.ThenBy(i => i.Index);
}
- public static void SetSubtitleStreamScores(List<MediaStream> streams,
+ public static void SetSubtitleStreamScores(
+ List<MediaStream> streams,
string[] preferredLanguages,
SubtitlePlaybackMode mode,
string audioTrackLanguage)
diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs
index 10602fea7..e2f1fb0ad 100644
--- a/Emby.Server.Implementations/Library/MusicManager.cs
+++ b/Emby.Server.Implementations/Library/MusicManager.cs
@@ -1,13 +1,19 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
namespace Emby.Server.Implementations.Library
{
@@ -30,9 +36,10 @@ namespace Emby.Server.Implementations.Library
return list.Concat(GetInstantMixFromGenres(item.Genres, user, dtoOptions)).ToList();
}
- public List<BaseItem> GetInstantMixFromArtist(MusicArtist item, User user, DtoOptions dtoOptions)
+ /// <inheritdoc />
+ public List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User user, DtoOptions dtoOptions)
{
- return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
+ return GetInstantMixFromGenres(artist.Genres, user, dtoOptions);
}
public List<BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User user, DtoOptions dtoOptions)
@@ -45,7 +52,7 @@ namespace Emby.Server.Implementations.Library
var genres = item
.GetRecursiveChildren(user, new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
DtoOptions = dtoOptions
})
.Cast<Audio>()
@@ -73,7 +80,6 @@ namespace Emby.Server.Implementations.Library
{
return Guid.Empty;
}
-
}).Where(i => !i.Equals(Guid.Empty)).ToArray();
return GetInstantMixFromGenreIds(genreIds, user, dtoOptions);
@@ -83,53 +89,46 @@ namespace Emby.Server.Implementations.Library
{
return _libraryManager.GetItemList(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
GenreIds = genreIds.ToArray(),
Limit = 200,
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.Random, SortOrder.Ascending) },
+ OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
DtoOptions = dtoOptions
-
});
}
public List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions)
{
- var genre = item as MusicGenre;
- if (genre != null)
+ if (item is MusicGenre genre)
{
return GetInstantMixFromGenreIds(new[] { item.Id }, user, dtoOptions);
}
- var playlist = item as Playlist;
- if (playlist != null)
+ if (item is Playlist playlist)
{
return GetInstantMixFromPlaylist(playlist, user, dtoOptions);
}
- var album = item as MusicAlbum;
- if (album != null)
+ if (item is MusicAlbum album)
{
return GetInstantMixFromAlbum(album, user, dtoOptions);
}
- var artist = item as MusicArtist;
- if (artist != null)
+ if (item is MusicArtist artist)
{
return GetInstantMixFromArtist(artist, user, dtoOptions);
}
- var song = item as Audio;
- if (song != null)
+ if (item is Audio song)
{
return GetInstantMixFromSong(song, user, dtoOptions);
}
- var folder = item as Folder;
- if (folder != null)
+ if (item is Folder folder)
{
return GetInstantMixFromFolder(folder, user, dtoOptions);
}
diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs
index d3a81f622..d5b855cdf 100644
--- a/Emby.Server.Implementations/Library/PathExtensions.cs
+++ b/Emby.Server.Implementations/Library/PathExtensions.cs
@@ -1,45 +1,117 @@
using System;
-using System.Text.RegularExpressions;
+using System.Diagnostics.CodeAnalysis;
+using MediaBrowser.Common.Providers;
namespace Emby.Server.Implementations.Library
{
+ /// <summary>
+ /// Class providing extension methods for working with paths.
+ /// </summary>
public static class PathExtensions
{
/// <summary>
/// Gets the attribute value.
/// </summary>
/// <param name="str">The STR.</param>
- /// <param name="attrib">The attrib.</param>
+ /// <param name="attribute">The attrib.</param>
/// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">attrib</exception>
- public static string GetAttributeValue(this string str, string attrib)
+ /// <exception cref="ArgumentException"><paramref name="str" /> or <paramref name="attribute" /> is empty.</exception>
+ public static string? GetAttributeValue(this string str, string attribute)
{
- if (string.IsNullOrEmpty(str))
+ if (str.Length == 0)
{
- throw new ArgumentNullException(nameof(str));
+ throw new ArgumentException("String can't be empty.", nameof(str));
}
- if (string.IsNullOrEmpty(attrib))
+ if (attribute.Length == 0)
{
- throw new ArgumentNullException(nameof(attrib));
+ throw new ArgumentException("String can't be empty.", nameof(attribute));
}
- string srch = "[" + attrib + "=";
+ string srch = "[" + attribute + "=";
int start = str.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
- if (start > -1)
+ if (start != -1)
{
start += srch.Length;
int end = str.IndexOf(']', start);
return str.Substring(start, end - start);
}
+
// for imdbid we also accept pattern matching
- if (string.Equals(attrib, "imdbid", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(attribute, "imdbid", StringComparison.OrdinalIgnoreCase))
{
- var m = Regex.Match(str, "tt\\d{7}", RegexOptions.IgnoreCase);
- return m.Success ? m.Value : null;
+ var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
+ return match ? imdbId.ToString() : null;
}
return null;
}
+
+ /// <summary>
+ /// Replaces a sub path with another sub path and normalizes the final path.
+ /// </summary>
+ /// <param name="path">The original path.</param>
+ /// <param name="subPath">The original sub path.</param>
+ /// <param name="newSubPath">The new sub path.</param>
+ /// <param name="newPath">The result of the sub path replacement.</param>
+ /// <returns>The path after replacing the sub path.</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramref name="newSubPath" /> is empty.</exception>
+ public static bool TryReplaceSubPath(
+ [NotNullWhen(true)] this string? path,
+ [NotNullWhen(true)] string? subPath,
+ [NotNullWhen(true)] string? newSubPath,
+ [NotNullWhen(true)] out string? newPath)
+ {
+ newPath = null;
+
+ if (string.IsNullOrEmpty(path)
+ || string.IsNullOrEmpty(subPath)
+ || string.IsNullOrEmpty(newSubPath)
+ || subPath.Length > path.Length)
+ {
+ return false;
+ }
+
+ char oldDirectorySeparatorChar;
+ char newDirectorySeparatorChar;
+ // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
+ // The reasoning behind this is that a forward slash likely means it's a Linux path and
+ // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
+ if (newSubPath.Contains('/', StringComparison.Ordinal))
+ {
+ oldDirectorySeparatorChar = '\\';
+ newDirectorySeparatorChar = '/';
+ }
+ else
+ {
+ oldDirectorySeparatorChar = '/';
+ newDirectorySeparatorChar = '\\';
+ }
+
+ path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
+ subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
+
+ // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
+ // when the sub path matches a similar but in-complete subpath
+ var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
+ if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+
+ if (path.Length > subPath.Length
+ && !oldSubPathEndsWithSeparator
+ && path[subPath.Length] != newDirectorySeparatorChar)
+ {
+ return false;
+ }
+
+ var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
+ // Ensure that the path with the old subpath removed starts with a leading dir separator
+ int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
+ newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
+
+ return true;
+ }
}
}
diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs
index 96d1bff92..ac75e5d3a 100644
--- a/Emby.Server.Implementations/Library/ResolverHelper.cs
+++ b/Emby.Server.Implementations/Library/ResolverHelper.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Library
{
/// <summary>
- /// Class ResolverHelper
+ /// Class ResolverHelper.
/// </summary>
public static class ResolverHelper
{
@@ -18,11 +18,10 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="item">The item.</param>
/// <param name="parent">The parent.</param>
- /// <param name="fileSystem">The file system.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="directoryService">The directory service.</param>
- /// <exception cref="ArgumentException">Item must have a path</exception>
- public static void SetInitialItemValues(BaseItem item, Folder parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService)
+ /// <exception cref="ArgumentException">Item must have a path.</exception>
+ public static void SetInitialItemValues(BaseItem item, Folder? parent, ILibraryManager libraryManager, IDirectoryService directoryService)
{
// This version of the below method has no ItemResolveArgs, so we have to require the path already being set
if (string.IsNullOrEmpty(item.Path))
@@ -43,9 +42,14 @@ namespace Emby.Server.Implementations.Library
// Make sure DateCreated and DateModified have values
var fileInfo = directoryService.GetFile(item.Path);
- SetDateCreated(item, fileSystem, fileInfo);
+ if (fileInfo == null)
+ {
+ throw new FileNotFoundException("Can't find item path.", item.Path);
+ }
- EnsureName(item, item.Path, fileInfo);
+ SetDateCreated(item, fileInfo);
+
+ EnsureName(item, fileInfo);
}
/// <summary>
@@ -72,9 +76,9 @@ namespace Emby.Server.Implementations.Library
item.Id = libraryManager.GetNewItemId(item.Path, item.GetType());
// Make sure the item has a name
- EnsureName(item, item.Path, args.FileInfo);
+ EnsureName(item, args.FileInfo);
- item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 ||
+ item.IsLocked = item.Path.Contains("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) ||
item.GetParents().Any(i => i.IsLocked);
// Make sure DateCreated and DateModified have values
@@ -84,49 +88,23 @@ namespace Emby.Server.Implementations.Library
/// <summary>
/// Ensures the name.
/// </summary>
- private static void EnsureName(BaseItem item, string fullPath, FileSystemMetadata fileInfo)
+ private static void EnsureName(BaseItem item, FileSystemMetadata fileInfo)
{
// If the subclass didn't supply a name, add it here
- if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(fullPath))
+ if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(item.Path))
{
- var fileName = fileInfo == null ? Path.GetFileName(fullPath) : fileInfo.Name;
-
- item.Name = GetDisplayName(fileName, fileInfo != null && fileInfo.IsDirectory);
+ item.Name = fileInfo.IsDirectory ? fileInfo.Name : Path.GetFileNameWithoutExtension(fileInfo.Name);
}
}
/// <summary>
- /// Gets the display name.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="isDirectory">if set to <c>true</c> [is directory].</param>
- /// <returns>System.String.</returns>
- private static string GetDisplayName(string path, bool isDirectory)
- {
- return isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path);
- }
-
- /// <summary>
- /// Ensures DateCreated and DateModified have values
+ /// Ensures DateCreated and DateModified have values.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="item">The item.</param>
/// <param name="args">The args.</param>
private static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args)
{
- if (fileSystem == null)
- {
- throw new ArgumentNullException(nameof(fileSystem));
- }
- if (item == null)
- {
- throw new ArgumentNullException(nameof(item));
- }
- if (args == null)
- {
- throw new ArgumentNullException(nameof(args));
- }
-
// See if a different path came out of the resolver than what went in
if (!fileSystem.AreEqual(args.Path, item.Path))
{
@@ -134,7 +112,7 @@ namespace Emby.Server.Implementations.Library
if (childData != null)
{
- SetDateCreated(item, fileSystem, childData);
+ SetDateCreated(item, childData);
}
else
{
@@ -142,17 +120,17 @@ namespace Emby.Server.Implementations.Library
if (fileData.Exists)
{
- SetDateCreated(item, fileSystem, fileData);
+ SetDateCreated(item, fileData);
}
}
}
else
{
- SetDateCreated(item, fileSystem, args.FileInfo);
+ SetDateCreated(item, args.FileInfo);
}
}
- private static void SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemMetadata info)
+ private static void SetDateCreated(BaseItem item, FileSystemMetadata? info)
{
var config = BaseItem.ConfigurationManager.GetMetadataConfiguration();
@@ -161,7 +139,7 @@ namespace Emby.Server.Implementations.Library
// directoryService.getFile may return null
if (info != null)
{
- var dateCreated = fileSystem.GetCreationTimeUtc(info);
+ var dateCreated = info.CreationTimeUtc;
if (dateCreated.Equals(DateTime.MinValue))
{
diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs
index e39192d28..fd9747b4b 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -13,24 +17,25 @@ using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
/// <summary>
- /// Class AudioResolver
+ /// Class AudioResolver.
/// </summary>
public class AudioResolver : ItemResolver<MediaBrowser.Controller.Entities.Audio.Audio>, IMultiItemResolver
{
- private readonly ILibraryManager LibraryManager;
+ private readonly ILibraryManager _libraryManager;
public AudioResolver(ILibraryManager libraryManager)
{
- LibraryManager = libraryManager;
+ _libraryManager = libraryManager;
}
/// <summary>
/// Gets the priority.
/// </summary>
/// <value>The priority.</value>
- public override ResolverPriority Priority => ResolverPriority.Fourth;
+ public override ResolverPriority Priority => ResolverPriority.Fifth;
- public MultiItemResolverResult ResolveMultiple(Folder parent,
+ public MultiItemResolverResult ResolveMultiple(
+ Folder parent,
List<FileSystemMetadata> files,
string collectionType,
IDirectoryService directoryService)
@@ -48,7 +53,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
return result;
}
- private MultiItemResolverResult ResolveMultipleInternal(Folder parent,
+ private MultiItemResolverResult ResolveMultipleInternal(
+ Folder parent,
List<FileSystemMetadata> files,
string collectionType,
IDirectoryService directoryService)
@@ -70,7 +76,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
// Return audio if the path is a file and has a matching extension
- var libraryOptions = args.GetLibraryOptions();
var collectionType = args.GetCollectionType();
var isBooksCollectionType = string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase);
@@ -83,13 +88,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
}
var files = args.FileSystemChildren
- .Where(i => !LibraryManager.IgnoreFile(i, args.Parent))
+ .Where(i => !_libraryManager.IgnoreFile(i, args.Parent))
.ToList();
return FindAudio<AudioBook>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false);
}
- if (LibraryManager.IsAudioFile(args.Path, libraryOptions))
+ if (_libraryManager.IsAudioFile(args.Path))
{
var extension = Path.GetExtension(args.Path);
@@ -102,7 +107,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
var isMixedCollectionType = string.IsNullOrEmpty(collectionType);
// For conflicting extensions, give priority to videos
- if (isMixedCollectionType && LibraryManager.IsVideoFile(args.Path, libraryOptions))
+ if (isMixedCollectionType && _libraryManager.IsVideoFile(args.Path))
{
return null;
}
@@ -118,7 +123,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
item = new MediaBrowser.Controller.Entities.Audio.Audio();
}
-
else if (isBooksCollectionType)
{
item = new AudioBook();
@@ -178,7 +182,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
}
}
- var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
+ var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions();
var resolver = new AudioBookListResolver(namingOptions);
var resolverResult = resolver.Resolve(files).ToList();
@@ -199,7 +203,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
continue;
}
- var firstMedia = resolvedItem.Files.First();
+ if (resolvedItem.Files.Count == 0)
+ {
+ continue;
+ }
+
+ var firstMedia = resolvedItem.Files[0];
var libraryItem = new T
{
@@ -209,8 +218,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
Name = parseName ?
resolvedItem.Name :
Path.GetFileNameWithoutExtension(firstMedia.Path),
- //AdditionalParts = resolvedItem.Files.Skip(1).Select(i => i.Path).ToArray(),
- //LocalAlternateVersions = resolvedItem.AlternateVersions.Select(i => i.Path).ToArray()
+ // AdditionalParts = resolvedItem.Files.Skip(1).Select(i => i.Path).ToArray(),
+ // LocalAlternateVersions = resolvedItem.AlternateVersions.Select(i => i.Path).ToArray()
};
result.Items.Add(libraryItem);
diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
index 3ce1da81a..60720dd2f 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
@@ -1,11 +1,15 @@
+#nullable disable
+
using System;
using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
using Emby.Naming.Audio;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
@@ -13,15 +17,21 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
/// <summary>
- /// Class MusicAlbumResolver
+ /// Class MusicAlbumResolver.
/// </summary>
public class MusicAlbumResolver : ItemResolver<MusicAlbum>
{
- private readonly ILogger _logger;
+ private readonly ILogger<MusicAlbumResolver> _logger;
private readonly IFileSystem _fileSystem;
private readonly ILibraryManager _libraryManager;
- public MusicAlbumResolver(ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicAlbumResolver"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ public MusicAlbumResolver(ILogger<MusicAlbumResolver> logger, IFileSystem fileSystem, ILibraryManager libraryManager)
{
_logger = logger;
_fileSystem = fileSystem;
@@ -32,7 +42,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
/// Gets the priority.
/// </summary>
/// <value>The priority.</value>
- public override ResolverPriority Priority => ResolverPriority.Second;
+ public override ResolverPriority Priority => ResolverPriority.Third;
/// <summary>
/// Resolves the specified args.
@@ -50,26 +60,38 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
return null;
}
- if (!args.IsDirectory) return null;
+ if (!args.IsDirectory)
+ {
+ return null;
+ }
// Avoid mis-identifying top folders
- if (args.HasParent<MusicAlbum>()) return null;
- if (args.Parent.IsRoot) return null;
+ if (args.HasParent<MusicAlbum>())
+ {
+ return null;
+ }
+
+ if (args.Parent.IsRoot)
+ {
+ return null;
+ }
return IsMusicAlbum(args) ? new MusicAlbum() : null;
}
-
/// <summary>
- /// Determine if the supplied file data points to a music album
+ /// Determine if the supplied file data points to a music album.
/// </summary>
- public bool IsMusicAlbum(string path, IDirectoryService directoryService, LibraryOptions libraryOptions)
+ /// <param name="path">The path to check.</param>
+ /// <param name="directoryService">The directory service.</param>
+ /// <returns><c>true</c> if the provided path points to a music album, <c>false</c> otherwise.</returns>
+ public bool IsMusicAlbum(string path, IDirectoryService directoryService)
{
- return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, libraryOptions, _libraryManager);
+ return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, _libraryManager);
}
/// <summary>
- /// Determine if the supplied resolve args should be considered a music album
+ /// Determine if the supplied resolve args should be considered a music album.
/// </summary>
/// <param name="args">The args.</param>
/// <returns><c>true</c> if [is music album] [the specified args]; otherwise, <c>false</c>.</returns>
@@ -78,83 +100,74 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
// Args points to an album if parent is an Artist folder or it directly contains music
if (args.IsDirectory)
{
- //if (args.Parent is MusicArtist) return true; //saves us from testing children twice
- if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, args.GetLibraryOptions(), _libraryManager)) return true;
+ // if (args.Parent is MusicArtist) return true; // saves us from testing children twice
+ if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, _libraryManager))
+ {
+ return true;
+ }
}
return false;
}
/// <summary>
- /// Determine if the supplied list contains what we should consider music
+ /// Determine if the supplied list contains what we should consider music.
/// </summary>
- private bool ContainsMusic(IEnumerable<FileSystemMetadata> list,
+ private bool ContainsMusic(
+ IEnumerable<FileSystemMetadata> list,
bool allowSubfolders,
IDirectoryService directoryService,
- ILogger logger,
+ ILogger<MusicAlbumResolver> logger,
IFileSystem fileSystem,
- LibraryOptions libraryOptions,
ILibraryManager libraryManager)
{
+ // check for audio files before digging down into directories
+ var foundAudioFile = list.Any(fileSystemInfo => !fileSystemInfo.IsDirectory && libraryManager.IsAudioFile(fileSystemInfo.FullName));
+ if (foundAudioFile)
+ {
+ // at least one audio file exists
+ return true;
+ }
+
+ if (!allowSubfolders)
+ {
+ // not music since no audio file exists and we're not looking into subfolders
+ return false;
+ }
+
var discSubfolderCount = 0;
- var notMultiDisc = false;
- foreach (var fileSystemInfo in list)
+ var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions();
+ var parser = new AlbumParser(namingOptions);
+
+ var directories = list.Where(fileSystemInfo => fileSystemInfo.IsDirectory);
+
+ var result = Parallel.ForEach(directories, (fileSystemInfo, state) =>
{
- if (fileSystemInfo.IsDirectory)
+ var path = fileSystemInfo.FullName;
+ var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryManager);
+
+ if (hasMusic)
{
- if (allowSubfolders)
+ if (parser.IsMultiPart(path))
{
- if (notMultiDisc)
- {
- continue;
- }
-
- var path = fileSystemInfo.FullName;
- var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryOptions, libraryManager);
-
- if (hasMusic)
- {
- if (IsMultiDiscFolder(path, libraryOptions))
- {
- logger.LogDebug("Found multi-disc folder: " + path);
- discSubfolderCount++;
- }
- else
- {
- // If there are folders underneath with music that are not multidisc, then this can't be a multi-disc album
- notMultiDisc = true;
- }
- }
+ logger.LogDebug("Found multi-disc folder: " + path);
+ Interlocked.Increment(ref discSubfolderCount);
}
- }
- else
- {
- var fullName = fileSystemInfo.FullName;
-
- if (libraryManager.IsAudioFile(fullName, libraryOptions))
+ else
{
- return true;
+ // If there are folders underneath with music that are not multidisc, then this can't be a multi-disc album
+ state.Stop();
}
}
- }
+ });
- if (notMultiDisc)
+ if (!result.IsCompleted)
{
return false;
}
return discSubfolderCount > 0;
}
-
- private bool IsMultiDiscFolder(string path, LibraryOptions libraryOptions)
- {
- var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions();
-
- var parser = new AlbumParser(namingOptions);
- var result = parser.ParseMultiPart(path);
-
- return result.IsMultiPart;
- }
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
index 74e9b8304..3d2ae95d2 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
@@ -1,5 +1,8 @@
+#nullable disable
+
using System;
using System.Linq;
+using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
@@ -11,16 +14,27 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
/// <summary>
- /// Class MusicArtistResolver
+ /// Class MusicArtistResolver.
/// </summary>
public class MusicArtistResolver : ItemResolver<MusicArtist>
{
- private readonly ILogger _logger;
+ private readonly ILogger<MusicAlbumResolver> _logger;
private readonly IFileSystem _fileSystem;
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _config;
- public MusicArtistResolver(ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager, IServerConfigurationManager config)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicArtistResolver"/> class.
+ /// </summary>
+ /// <param name="logger">The logger for the created <see cref="MusicAlbumResolver"/> instances.</param>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="config">The configuration manager.</param>
+ public MusicArtistResolver(
+ ILogger<MusicAlbumResolver> logger,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IServerConfigurationManager config)
{
_logger = logger;
_fileSystem = fileSystem;
@@ -41,7 +55,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
/// <returns>MusicArtist.</returns>
protected override MusicArtist Resolve(ItemResolveArgs args)
{
- if (!args.IsDirectory) return null;
+ if (!args.IsDirectory)
+ {
+ return null;
+ }
// Don't allow nested artists
if (args.HasParent<MusicArtist>() || args.HasParent<MusicAlbum>())
@@ -64,21 +81,29 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
return new MusicArtist();
}
- if (_config.Configuration.EnableSimpleArtistDetection)
+ // Avoid mis-identifying top folders
+ if (args.Parent.IsRoot)
{
return null;
}
- // Avoid mis-identifying top folders
- if (args.Parent.IsRoot) return null;
-
var directoryService = args.DirectoryService;
var albumResolver = new MusicAlbumResolver(_logger, _fileSystem, _libraryManager);
// If we contain an album assume we are an artist folder
- return args.FileSystemChildren.Where(i => i.IsDirectory).Any(i => albumResolver.IsMusicAlbum(i.FullName, directoryService, args.GetLibraryOptions())) ? new MusicArtist() : null;
- }
+ var directories = args.FileSystemChildren.Where(i => i.IsDirectory);
+ var result = Parallel.ForEach(directories, (fileSystemInfo, state) =>
+ {
+ if (albumResolver.IsMusicAlbum(fileSystemInfo.FullName, directoryService))
+ {
+ // stop once we see a music album
+ state.Stop();
+ }
+ });
+
+ return !result.IsCompleted ? new MusicArtist() : null;
+ }
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
index 541b13cbe..9ff99fa43 100644
--- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
@@ -1,6 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Linq;
+using DiscUtils.Udf;
using Emby.Naming.Video;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -10,25 +15,25 @@ using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers
{
/// <summary>
- /// Resolves a Path into a Video or Video subclass
+ /// Resolves a Path into a Video or Video subclass.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of item to resolve.</typeparam>
public abstract class BaseVideoResolver<T> : MediaBrowser.Controller.Resolvers.ItemResolver<T>
where T : Video, new()
{
- protected readonly ILibraryManager LibraryManager;
-
protected BaseVideoResolver(ILibraryManager libraryManager)
{
LibraryManager = libraryManager;
}
+ protected ILibraryManager LibraryManager { get; }
+
/// <summary>
/// Resolves the specified args.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>`0.</returns>
- protected override T Resolve(ItemResolveArgs args)
+ public override T Resolve(ItemResolveArgs args)
{
return ResolveVideo<T>(args, false);
}
@@ -40,14 +45,12 @@ namespace Emby.Server.Implementations.Library.Resolvers
/// <param name="args">The args.</param>
/// <param name="parseName">if set to <c>true</c> [parse name].</param>
/// <returns>``0.</returns>
- protected TVideoType ResolveVideo<TVideoType>(ItemResolveArgs args, bool parseName)
+ protected virtual TVideoType ResolveVideo<TVideoType>(ItemResolveArgs args, bool parseName)
where TVideoType : Video, new()
{
- var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
+ var namingOptions = LibraryManager.GetNamingOptions();
// If the path is a file check for a matching extensions
- var parser = new VideoResolver(namingOptions);
-
if (args.IsDirectory)
{
TVideoType video = null;
@@ -62,7 +65,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
if (IsDvdDirectory(child.FullName, filename, args.DirectoryService))
{
- videoInfo = parser.ResolveDirectory(args.Path);
+ videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions);
if (videoInfo == null)
{
@@ -77,9 +80,10 @@ namespace Emby.Server.Implementations.Library.Resolvers
};
break;
}
- if (IsBluRayDirectory(child.FullName, filename, args.DirectoryService))
+
+ if (IsBluRayDirectory(filename))
{
- videoInfo = parser.ResolveDirectory(args.Path);
+ videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions);
if (videoInfo == null)
{
@@ -97,7 +101,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
}
else if (IsDvdFile(filename))
{
- videoInfo = parser.ResolveDirectory(args.Path);
+ videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions);
if (videoInfo == null)
{
@@ -127,14 +131,14 @@ namespace Emby.Server.Implementations.Library.Resolvers
}
else
{
- var videoInfo = parser.Resolve(args.Path, false, false);
+ var videoInfo = VideoResolver.Resolve(args.Path, false, namingOptions, false);
if (videoInfo == null)
{
return null;
}
- if (LibraryManager.IsVideoFile(args.Path, args.GetLibraryOptions()) || videoInfo.IsStub)
+ if (LibraryManager.IsVideoFile(args.Path) || videoInfo.IsStub)
{
var path = args.Path;
@@ -162,13 +166,13 @@ namespace Emby.Server.Implementations.Library.Resolvers
protected void SetVideoType(Video video, VideoFileInfo videoInfo)
{
- var extension = Path.GetExtension(video.Path);
- video.VideoType = string.Equals(extension, ".iso", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(extension, ".img", StringComparison.OrdinalIgnoreCase) ?
- VideoType.Iso :
- VideoType.VideoFile;
+ var extension = Path.GetExtension(video.Path.AsSpan());
+ video.VideoType = extension.Equals(".iso", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".img", StringComparison.OrdinalIgnoreCase)
+ ? VideoType.Iso
+ : VideoType.VideoFile;
- video.IsShortcut = string.Equals(extension, ".strm", StringComparison.OrdinalIgnoreCase);
+ video.IsShortcut = extension.Equals(".strm", StringComparison.OrdinalIgnoreCase);
video.IsPlaceHolder = videoInfo.IsStub;
if (videoInfo.IsStub)
@@ -190,14 +194,30 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
if (video.VideoType == VideoType.Iso)
{
- if (video.Path.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1)
+ if (video.Path.Contains("dvd", StringComparison.OrdinalIgnoreCase))
{
video.IsoType = IsoType.Dvd;
}
- else if (video.Path.IndexOf("bluray", StringComparison.OrdinalIgnoreCase) != -1)
+ else if (video.Path.Contains("bluray", StringComparison.OrdinalIgnoreCase))
{
video.IsoType = IsoType.BluRay;
}
+ else
+ {
+ // use disc-utils, both DVDs and BDs use UDF filesystem
+ using (var videoFileStream = File.Open(video.Path, FileMode.Open, FileAccess.Read))
+ {
+ UdfReader udfReader = new UdfReader(videoFileStream);
+ if (udfReader.DirectoryExists("VIDEO_TS"))
+ {
+ video.IsoType = IsoType.Dvd;
+ }
+ else if (udfReader.DirectoryExists("BDMV"))
+ {
+ video.IsoType = IsoType.BluRay;
+ }
+ }
+ }
}
}
@@ -247,10 +267,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
protected void Set3DFormat(Video video)
{
- var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
-
- var resolver = new Format3DParser(namingOptions);
- var result = resolver.Parse(video.Path);
+ var result = Format3DParser.Parse(video.Path, LibraryManager.GetNamingOptions());
Set3DFormat(video, result.Is3D, result.Format3D);
}
@@ -258,6 +275,10 @@ namespace Emby.Server.Implementations.Library.Resolvers
/// <summary>
/// Determines whether [is DVD directory] [the specified directory name].
/// </summary>
+ /// <param name="fullPath">The full path of the directory.</param>
+ /// <param name="directoryName">The name of the directory.</param>
+ /// <param name="directoryService">The directory service.</param>
+ /// <returns><c>true</c> if the provided directory is a DVD directory, <c>false</c> otherwise.</returns>
protected bool IsDvdDirectory(string fullPath, string directoryName, IDirectoryService directoryService)
{
if (!string.Equals(directoryName, "video_ts", StringComparison.OrdinalIgnoreCase))
@@ -279,25 +300,13 @@ namespace Emby.Server.Implementations.Library.Resolvers
}
/// <summary>
- /// Determines whether [is blu ray directory] [the specified directory name].
+ /// Determines whether [is bluray directory] [the specified directory name].
/// </summary>
- protected bool IsBluRayDirectory(string fullPath, string directoryName, IDirectoryService directoryService)
+ /// <param name="directoryName">The directory name.</param>
+ /// <returns>Whether the directory is a bluray directory.</returns>
+ protected bool IsBluRayDirectory(string directoryName)
{
- if (!string.Equals(directoryName, "bdmv", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- return true;
- //var blurayExtensions = new[]
- //{
- // ".mts",
- // ".m2ts",
- // ".bdmv",
- // ".mpls"
- //};
-
- //return directoryService.GetFiles(fullPath).Any(i => blurayExtensions.Contains(i.Extension ?? string.Empty, StringComparer.OrdinalIgnoreCase));
+ return string.Equals(directoryName, "bdmv", StringComparison.OrdinalIgnoreCase);
}
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs
index f22554ee5..e685c87f1 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Linq;
@@ -7,25 +11,19 @@ using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers.Books
{
- /// <summary>
- ///
- /// </summary>
public class BookResolver : MediaBrowser.Controller.Resolvers.ItemResolver<Book>
{
- private readonly string[] _validExtensions = { ".pdf", ".epub", ".mobi", ".cbr", ".cbz", ".azw3" };
+ private readonly string[] _validExtensions = { ".azw", ".azw3", ".cb7", ".cbr", ".cbt", ".cbz", ".epub", ".mobi", ".pdf" };
- /// <summary>
- ///
- /// </summary>
- /// <param name="args"></param>
- /// <returns></returns>
- protected override Book Resolve(ItemResolveArgs args)
+ public override Book Resolve(ItemResolveArgs args)
{
var collectionType = args.GetCollectionType();
// Only process items that are in a collection folder containing books
if (!string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase))
+ {
return null;
+ }
if (args.IsDirectory)
{
@@ -47,26 +45,23 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books
return null;
}
- /// <summary>
- ///
- /// </summary>
- /// <param name="args"></param>
- /// <returns></returns>
private Book GetBook(ItemResolveArgs args)
{
var bookFiles = args.FileSystemChildren.Where(f =>
{
- var fileExtension = Path.GetExtension(f.FullName) ??
- string.Empty;
+ var fileExtension = Path.GetExtension(f.FullName)
+ ?? string.Empty;
- return _validExtensions.Contains(fileExtension,
- StringComparer
- .OrdinalIgnoreCase);
+ return _validExtensions.Contains(
+ fileExtension,
+ StringComparer.OrdinalIgnoreCase);
}).ToList();
// Don't return a Book if there is more (or less) than one document in the directory
if (bookFiles.Count != 1)
+ {
return null;
+ }
return new Book
{
diff --git a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs
index e48b6c967..db7703cd6 100644
--- a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Resolvers;
@@ -5,9 +7,9 @@ using MediaBrowser.Controller.Resolvers;
namespace Emby.Server.Implementations.Library.Resolvers
{
/// <summary>
- /// Class FolderResolver
+ /// Class FolderResolver.
/// </summary>
- public class FolderResolver : FolderResolver<Folder>
+ public class FolderResolver : GenericFolderResolver<Folder>
{
/// <summary>
/// Gets the priority.
@@ -30,24 +32,4 @@ namespace Emby.Server.Implementations.Library.Resolvers
return null;
}
}
-
- /// <summary>
- /// Class FolderResolver
- /// </summary>
- /// <typeparam name="TItemType">The type of the T item type.</typeparam>
- public abstract class FolderResolver<TItemType> : ItemResolver<TItemType>
- where TItemType : Folder, new()
- {
- /// <summary>
- /// Sets the initial item values.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="args">The args.</param>
- protected override void SetInitialItemValues(TItemType item, ItemResolveArgs args)
- {
- base.SetInitialItemValues(item, args);
-
- item.IsRoot = args.Parent == null;
- }
- }
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/GenericFolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/GenericFolderResolver.cs
new file mode 100644
index 000000000..f109a5e9a
--- /dev/null
+++ b/Emby.Server.Implementations/Library/Resolvers/GenericFolderResolver.cs
@@ -0,0 +1,27 @@
+#nullable disable
+
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+
+namespace Emby.Server.Implementations.Library.Resolvers
+{
+ /// <summary>
+ /// Class FolderResolver.
+ /// </summary>
+ /// <typeparam name="TItemType">The type of the T item type.</typeparam>
+ public abstract class GenericFolderResolver<TItemType> : ItemResolver<TItemType>
+ where TItemType : Folder, new()
+ {
+ /// <summary>
+ /// Sets the initial item values.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="args">The args.</param>
+ protected override void SetInitialItemValues(TItemType item, ItemResolveArgs args)
+ {
+ base.SetInitialItemValues(item, args);
+
+ item.IsRoot = args.Parent == null;
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs
index 68d5d8b2d..9599faea4 100644
--- a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
diff --git a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs
index a6db40714..3f29ab191 100644
--- a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Resolvers;
@@ -5,13 +7,19 @@ using MediaBrowser.Controller.Resolvers;
namespace Emby.Server.Implementations.Library.Resolvers
{
/// <summary>
- /// Class ItemResolver
+ /// Class ItemResolver.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of BaseItem.</typeparam>
public abstract class ItemResolver<T> : IItemResolver
where T : BaseItem, new()
{
/// <summary>
+ /// Gets the priority.
+ /// </summary>
+ /// <value>The priority.</value>
+ public virtual ResolverPriority Priority => ResolverPriority.First;
+
+ /// <summary>
/// Resolves the specified args.
/// </summary>
/// <param name="args">The args.</param>
@@ -22,13 +30,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
}
/// <summary>
- /// Gets the priority.
- /// </summary>
- /// <value>The priority.</value>
- public virtual ResolverPriority Priority => ResolverPriority.First;
-
- /// <summary>
- /// Sets initial values on the newly resolved item
+ /// Sets initial values on the newly resolved item.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="args">The args.</param>
diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs
index 922bd4bbb..e7abe1e6d 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs
@@ -1,17 +1,18 @@
+#nullable disable
+
using System;
using System.IO;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
/// <summary>
- /// Class BoxSetResolver
+ /// Class BoxSetResolver.
/// </summary>
- public class BoxSetResolver : FolderResolver<BoxSet>
+ public class BoxSetResolver : GenericFolderResolver<BoxSet>
{
/// <summary>
/// Resolves the specified args.
@@ -63,14 +64,14 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
/// <param name="item">The item.</param>
private static void SetProviderIdFromPath(BaseItem item)
{
- //we need to only look at the name of this actual item (not parents)
+ // we need to only look at the name of this actual item (not parents)
var justName = Path.GetFileName(item.Path);
var id = justName.GetAttributeValue("tmdbid");
if (!string.IsNullOrEmpty(id))
{
- item.SetProviderId(MetadataProviders.Tmdb, id);
+ item.SetProviderId(MetadataProvider.Tmdb, id);
}
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
index 848563679..f3b6ef0a2 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text.RegularExpressions;
using Emby.Naming.Video;
+using Jellyfin.Extensions;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
@@ -11,23 +15,46 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
/// <summary>
- /// Class MovieResolver
+ /// Class MovieResolver.
/// </summary>
public class MovieResolver : BaseVideoResolver<Video>, IMultiItemResolver
{
+ private readonly IImageProcessor _imageProcessor;
+
+ private string[] _validCollectionTypes = new[]
+ {
+ CollectionType.Movies,
+ CollectionType.HomeVideos,
+ CollectionType.MusicVideos,
+ CollectionType.Movies,
+ CollectionType.Photos
+ };
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovieResolver"/> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="imageProcessor">The image processor.</param>
+ public MovieResolver(ILibraryManager libraryManager, IImageProcessor imageProcessor)
+ : base(libraryManager)
+ {
+ _imageProcessor = imageProcessor;
+ }
+
/// <summary>
/// Gets the priority.
/// </summary>
/// <value>The priority.</value>
- public override ResolverPriority Priority => ResolverPriority.Third;
+ public override ResolverPriority Priority => ResolverPriority.Fourth;
- public MultiItemResolverResult ResolveMultiple(Folder parent,
+ /// <inheritdoc />
+ public MultiItemResolverResult ResolveMultiple(
+ Folder parent,
List<FileSystemMetadata> files,
string collectionType,
IDirectoryService directoryService)
@@ -45,7 +72,112 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
return result;
}
- private MultiItemResolverResult ResolveMultipleInternal(Folder parent,
+ /// <summary>
+ /// Resolves the specified args.
+ /// </summary>
+ /// <param name="args">The args.</param>
+ /// <returns>Video.</returns>
+ public override Video Resolve(ItemResolveArgs args)
+ {
+ var collectionType = args.GetCollectionType();
+
+ // Find movies with their own folders
+ if (args.IsDirectory)
+ {
+ if (IsInvalid(args.Parent, collectionType))
+ {
+ return null;
+ }
+
+ var files = args.FileSystemChildren
+ .Where(i => !LibraryManager.IgnoreFile(i, args.Parent))
+ .ToList();
+
+ if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
+ {
+ return FindMovie<MusicVideo>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false);
+ }
+
+ if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase))
+ {
+ return FindMovie<Video>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false);
+ }
+
+ if (string.IsNullOrEmpty(collectionType))
+ {
+ // Owned items will be caught by the plain video resolver
+ if (args.Parent == null)
+ {
+ // return FindMovie<Video>(args.Path, args.Parent, files, args.DirectoryService, collectionType);
+ return null;
+ }
+
+ if (args.HasParent<Series>())
+ {
+ return null;
+ }
+
+ {
+ return FindMovie<Movie>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, true);
+ }
+ }
+
+ if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
+ {
+ return FindMovie<Movie>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, true);
+ }
+
+ return null;
+ }
+
+ // Handle owned items
+ if (args.Parent == null)
+ {
+ return base.Resolve(args);
+ }
+
+ if (IsInvalid(args.Parent, collectionType))
+ {
+ return null;
+ }
+
+ Video item = null;
+
+ if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
+ {
+ item = ResolveVideo<MusicVideo>(args, false);
+ }
+
+ // To find a movie file, the collection type must be movies or boxsets
+ else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
+ {
+ item = ResolveVideo<Movie>(args, true);
+ }
+ else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
+ {
+ item = ResolveVideo<Video>(args, false);
+ }
+ else if (string.IsNullOrEmpty(collectionType))
+ {
+ if (args.HasParent<Series>())
+ {
+ return null;
+ }
+
+ item = ResolveVideo<Video>(args, false);
+ }
+
+ if (item != null)
+ {
+ item.IsInMixedFolder = true;
+ }
+
+ return item;
+ }
+
+ private MultiItemResolverResult ResolveMultipleInternal(
+ Folder parent,
List<FileSystemMetadata> files,
string collectionType,
IDirectoryService directoryService)
@@ -90,7 +222,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
return null;
}
- private MultiItemResolverResult ResolveVideos<T>(Folder parent, IEnumerable<FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, bool suppportMultiEditions, string collectionType, bool parseName)
+ private MultiItemResolverResult ResolveVideos<T>(
+ Folder parent,
+ IEnumerable<FileSystemMetadata> fileSystemEntries,
+ IDirectoryService directoryService,
+ bool suppportMultiEditions,
+ string collectionType,
+ bool parseName)
where T : Video, new()
{
var files = new List<FileSystemMetadata>();
@@ -103,8 +241,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
// This is a hack but currently no better way to resolve a sometimes ambiguous situation
if (string.IsNullOrEmpty(collectionType))
{
- if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase))
{
return null;
}
@@ -114,20 +252,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
leftOver.Add(child);
}
- else if (IsIgnored(child.Name))
- {
-
- }
- else
+ else if (!IsIgnored(child.Name))
{
files.Add(child);
}
}
- var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
+ var namingOptions = LibraryManager.GetNamingOptions();
- var resolver = new VideoListResolver(namingOptions);
- var resolverResult = resolver.Resolve(files, suppportMultiEditions).ToList();
+ var resolverResult = VideoListResolver.Resolve(files, namingOptions, suppportMultiEditions).ToList();
var result = new MultiItemResolverResult
{
@@ -139,7 +272,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
foreach (var video in resolverResult)
{
- var firstVideo = video.Files.First();
+ var firstVideo = video.Files[0];
var videoItem = new T
{
@@ -167,17 +300,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
private static bool IsIgnored(string filename)
{
// Ignore samples
- var sampleFilename = " " + filename.Replace(".", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("-", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("_", " ", StringComparison.OrdinalIgnoreCase)
- .Replace("!", " ", StringComparison.OrdinalIgnoreCase);
-
- if (sampleFilename.IndexOf(" sample ", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return true;
- }
+ Match m = Regex.Match(filename, @"\bsample\b", RegexOptions.IgnoreCase);
- return false;
+ return m.Success;
}
private bool ContainsFile(List<VideoInfo> result, FileSystemMetadata file)
@@ -198,111 +323,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
}
/// <summary>
- /// Resolves the specified args.
- /// </summary>
- /// <param name="args">The args.</param>
- /// <returns>Video.</returns>
- protected override Video Resolve(ItemResolveArgs args)
- {
- var collectionType = args.GetCollectionType();
-
- // Find movies with their own folders
- if (args.IsDirectory)
- {
- if (IsInvalid(args.Parent, collectionType))
- {
- return null;
- }
-
- var files = args.FileSystemChildren
- .Where(i => !LibraryManager.IgnoreFile(i, args.Parent))
- .ToList();
-
- if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
- {
- return FindMovie<MusicVideo>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false);
- }
-
- if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase))
- {
- return FindMovie<Video>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false);
- }
-
- if (string.IsNullOrEmpty(collectionType))
- {
- // Owned items will be caught by the plain video resolver
- if (args.Parent == null)
- {
- //return FindMovie<Video>(args.Path, args.Parent, files, args.DirectoryService, collectionType);
- return null;
- }
-
- if (args.HasParent<Series>())
- {
- return null;
- }
-
- {
- return FindMovie<Movie>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, true);
- }
- }
-
- if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
- {
- return FindMovie<Movie>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, true);
- }
-
- return null;
- }
-
- // Handle owned items
- if (args.Parent == null)
- {
- return base.Resolve(args);
- }
-
- if (IsInvalid(args.Parent, collectionType))
- {
- return null;
- }
-
- Video item = null;
-
- if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
- {
- item = ResolveVideo<MusicVideo>(args, false);
- }
-
- // To find a movie file, the collection type must be movies or boxsets
- else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
- {
- item = ResolveVideo<Movie>(args, true);
- }
-
- else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
- {
- item = ResolveVideo<Video>(args, false);
- }
- else if (string.IsNullOrEmpty(collectionType))
- {
- if (args.HasParent<Series>())
- {
- return null;
- }
-
- item = ResolveVideo<Video>(args, false);
- }
-
- if (item != null)
- {
- item.IsInMixedFolder = true;
- }
-
- return item;
- }
-
- /// <summary>
/// Sets the initial item values.
/// </summary>
/// <param name="item">The item.</param>
@@ -322,7 +342,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
if (item is Movie || item is MusicVideo)
{
- //we need to only look at the name of this actual item (not parents)
+ // We need to only look at the name of this actual item (not parents)
var justName = item.IsInMixedFolder ? Path.GetFileName(item.Path) : Path.GetFileName(item.ContainingFolderPath);
if (!string.IsNullOrEmpty(justName))
@@ -332,7 +352,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
if (!string.IsNullOrWhiteSpace(tmdbid))
{
- item.SetProviderId(MetadataProviders.Tmdb, tmdbid);
+ item.SetProviderId(MetadataProvider.Tmdb, tmdbid);
}
}
@@ -343,23 +363,22 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
if (!string.IsNullOrWhiteSpace(imdbid))
{
- item.SetProviderId(MetadataProviders.Imdb, imdbid);
+ item.SetProviderId(MetadataProvider.Imdb, imdbid);
}
}
}
}
/// <summary>
- /// Finds a movie based on a child file system entries
+ /// Finds a movie based on a child file system entries.
/// </summary>
- /// <typeparam name="T"></typeparam>
/// <returns>Movie.</returns>
private T FindMovie<T>(ItemResolveArgs args, string path, Folder parent, List<FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool parseName)
where T : Video, new()
{
var multiDiscFolders = new List<FileSystemMetadata>();
- var libraryOptions = args.GetLibraryOptions();
+ var libraryOptions = args.LibraryOptions;
var supportPhotos = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && libraryOptions.EnablePhotos;
var photos = new List<FileSystemMetadata>();
@@ -380,7 +399,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
Set3DFormat(movie);
return movie;
}
- if (IsBluRayDirectory(child.FullName, filename, directoryService))
+
+ if (IsBluRayDirectory(filename))
{
var movie = new T
{
@@ -410,15 +430,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
}
// TODO: Allow GetMultiDiscMovie in here
- const bool supportsMultiVersion = true;
+ const bool SupportsMultiVersion = true;
- var result = ResolveVideos<T>(parent, fileSystemEntries, directoryService, supportsMultiVersion, collectionType, parseName) ??
+ var result = ResolveVideos<T>(parent, fileSystemEntries, directoryService, SupportsMultiVersion, collectionType, parseName) ??
new MultiItemResolverResult();
if (result.Items.Count == 1)
{
var videoPath = result.Items[0].Path;
- var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, libraryOptions, videoPath, i.Name));
+ var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, videoPath, i.Name));
if (!hasPhotos)
{
@@ -428,8 +448,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
return movie;
}
}
-
- if (result.Items.Count == 0 && multiDiscFolders.Count > 0)
+ else if (result.Items.Count == 0 && multiDiscFolders.Count > 0)
{
return GetMultiDiscMovie<T>(multiDiscFolders, directoryService);
}
@@ -440,7 +459,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
/// <summary>
/// Gets the multi disc movie.
/// </summary>
- /// <typeparam name="T"></typeparam>
/// <param name="multiDiscFolders">The folders.</param>
/// <param name="directoryService">The directory service.</param>
/// <returns>``0.</returns>
@@ -454,7 +472,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
var subFileEntries = directoryService.GetFileSystemEntries(i);
var subfolders = subFileEntries
- .Where(e => e.IsDirectory)
+ .Where(e => e.IsDirectory)
.ToList();
if (subfolders.Any(s => IsDvdDirectory(s.FullName, s.Name, directoryService)))
@@ -462,7 +480,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
videoTypes.Add(VideoType.Dvd);
return true;
}
- if (subfolders.Any(s => IsBluRayDirectory(s.FullName, s.Name, directoryService)))
+
+ if (subfolders.Any(s => IsBluRayDirectory(s.Name)))
{
videoTypes.Add(VideoType.BluRay);
return true;
@@ -479,7 +498,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
}
return false;
-
}).OrderBy(i => i).ToList();
// If different video types were found, don't allow this
@@ -494,24 +512,24 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
}
var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
- var resolver = new StackResolver(namingOptions);
- var result = resolver.ResolveDirectories(folderPaths);
+ var result = new StackResolver(namingOptions).ResolveDirectories(folderPaths).ToList();
- if (result.Stacks.Count != 1)
+ if (result.Count != 1)
{
return null;
}
+ int additionalPartsLen = folderPaths.Count - 1;
+ var additionalParts = new string[additionalPartsLen];
+ folderPaths.CopyTo(1, additionalParts, 0, additionalPartsLen);
+
var returnVideo = new T
{
Path = folderPaths[0],
-
- AdditionalParts = folderPaths.Skip(1).ToArray(),
-
+ AdditionalParts = additionalParts,
VideoType = videoTypes[0],
-
- Name = result.Stacks[0].Name
+ Name = result[0].Name
};
SetIsoType(returnVideo);
@@ -519,16 +537,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
return returnVideo;
}
- private string[] ValidCollectionTypes = new[]
- {
- CollectionType.Movies,
- CollectionType.HomeVideos,
- CollectionType.MusicVideos,
- CollectionType.Movies,
- CollectionType.Photos
- };
-
- private bool IsInvalid(Folder parent, string collectionType)
+ private bool IsInvalid(Folder parent, ReadOnlySpan<char> collectionType)
{
if (parent != null)
{
@@ -538,20 +547,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
}
}
- if (string.IsNullOrEmpty(collectionType))
+ if (collectionType.IsEmpty)
{
return false;
}
- return !ValidCollectionTypes.Contains(collectionType, StringComparer.OrdinalIgnoreCase);
- }
-
- private IImageProcessor _imageProcessor;
-
- public MovieResolver(ILibraryManager libraryManager, IImageProcessor imageProcessor)
- : base(libraryManager)
- {
- _imageProcessor = imageProcessor;
+ return !_validCollectionTypes.Contains(collectionType, StringComparison.OrdinalIgnoreCase);
}
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs
index 82779f8d3..1c560e8a6 100644
--- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
@@ -7,17 +9,28 @@ using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers
{
- public class PhotoAlbumResolver : FolderResolver<PhotoAlbum>
+ /// <summary>
+ /// Class PhotoAlbumResolver.
+ /// </summary>
+ public class PhotoAlbumResolver : GenericFolderResolver<PhotoAlbum>
{
private readonly IImageProcessor _imageProcessor;
- private ILibraryManager _libraryManager;
+ private readonly ILibraryManager _libraryManager;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PhotoAlbumResolver"/> class.
+ /// </summary>
+ /// <param name="imageProcessor">The image processor.</param>
+ /// <param name="libraryManager">The library manager.</param>
public PhotoAlbumResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager)
{
_imageProcessor = imageProcessor;
_libraryManager = libraryManager;
}
+ /// <inheritdoc />
+ public override ResolverPriority Priority => ResolverPriority.Second;
+
/// <summary>
/// Resolves the specified args.
/// </summary>
@@ -31,8 +44,8 @@ namespace Emby.Server.Implementations.Library.Resolvers
// Must be an image file within a photo collection
var collectionType = args.GetCollectionType();
- if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) ||
- (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.GetLibraryOptions().EnablePhotos))
+ if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)
+ || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.LibraryOptions.EnablePhotos))
{
if (HasPhotos(args))
{
@@ -55,13 +68,12 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
if (!file.IsDirectory && PhotoResolver.IsImageFile(file.FullName, _imageProcessor))
{
- var libraryOptions = args.GetLibraryOptions();
var filename = file.Name;
var ownedByMedia = false;
foreach (var siblingFile in files)
{
- if (PhotoResolver.IsOwnedByMedia(_libraryManager, libraryOptions, siblingFile.FullName, filename))
+ if (PhotoResolver.IsOwnedByMedia(_libraryManager, siblingFile.FullName, filename))
{
ownedByMedia = true;
break;
@@ -74,9 +86,8 @@ namespace Emby.Server.Implementations.Library.Resolvers
}
}
}
+
return false;
}
-
- public override ResolverPriority Priority => ResolverPriority.Second;
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs
index db270c398..57bf40e9e 100644
--- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -5,7 +9,6 @@ using System.Linq;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers
@@ -14,6 +17,18 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
private readonly IImageProcessor _imageProcessor;
private readonly ILibraryManager _libraryManager;
+ private static readonly HashSet<string> _ignoreFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "folder",
+ "thumb",
+ "landscape",
+ "fanart",
+ "backdrop",
+ "poster",
+ "cover",
+ "logo",
+ "default"
+ };
public PhotoResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager)
{
@@ -31,10 +46,10 @@ namespace Emby.Server.Implementations.Library.Resolvers
if (!args.IsDirectory)
{
// Must be an image file within a photo collection
- var collectionType = args.GetCollectionType();
+ var collectionType = args.CollectionType;
- if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) ||
- (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.GetLibraryOptions().EnablePhotos))
+ if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)
+ || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.LibraryOptions.EnablePhotos))
{
if (IsImageFile(args.Path, _imageProcessor))
{
@@ -42,11 +57,10 @@ namespace Emby.Server.Implementations.Library.Resolvers
// Make sure the image doesn't belong to a video file
var files = args.DirectoryService.GetFiles(Path.GetDirectoryName(args.Path));
- var libraryOptions = args.GetLibraryOptions();
foreach (var file in files)
{
- if (IsOwnedByMedia(_libraryManager, libraryOptions, file.FullName, filename))
+ if (IsOwnedByMedia(_libraryManager, file.FullName, filename))
{
return null;
}
@@ -63,54 +77,40 @@ namespace Emby.Server.Implementations.Library.Resolvers
return null;
}
- internal static bool IsOwnedByMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename)
+ internal static bool IsOwnedByMedia(ILibraryManager libraryManager, string file, string imageFilename)
{
- if (libraryManager.IsVideoFile(file, libraryOptions))
+ if (libraryManager.IsVideoFile(file))
{
- return IsOwnedByResolvedMedia(libraryManager, libraryOptions, file, imageFilename);
+ return IsOwnedByResolvedMedia(libraryManager, file, imageFilename);
}
return false;
}
- internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename)
+ internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, string file, string imageFilename)
+ => imageFilename.StartsWith(Path.GetFileNameWithoutExtension(file), StringComparison.OrdinalIgnoreCase);
+
+ internal static bool IsImageFile(string path, IImageProcessor imageProcessor)
{
- if (imageFilename.StartsWith(Path.GetFileNameWithoutExtension(file), StringComparison.OrdinalIgnoreCase))
+ if (path == null)
{
- return true;
+ throw new ArgumentNullException(nameof(path));
}
- return false;
- }
-
- private static readonly HashSet<string> IgnoreFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
- {
- "folder",
- "thumb",
- "landscape",
- "fanart",
- "backdrop",
- "poster",
- "cover",
- "logo",
- "default"
- };
-
- internal static bool IsImageFile(string path, IImageProcessor imageProcessor)
- {
- var filename = Path.GetFileNameWithoutExtension(path) ?? string.Empty;
+ var filename = Path.GetFileNameWithoutExtension(path);
- if (IgnoreFiles.Contains(filename))
+ if (_ignoreFiles.Contains(filename))
{
return false;
}
- if (IgnoreFiles.Any(i => filename.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1))
+ if (_ignoreFiles.Any(i => filename.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1))
{
return false;
}
- return imageProcessor.SupportedInputFormats.Contains(Path.GetExtension(path).TrimStart('.'), StringComparer.Ordinal);
+ string extension = Path.GetExtension(path).TrimStart('.');
+ return imageProcessor.SupportedInputFormats.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs
index c295894d3..8ce59717d 100644
--- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs
@@ -1,63 +1,74 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Linq;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
+using MediaBrowser.Controller.Resolvers;
+using MediaBrowser.LocalMetadata.Savers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Library.Resolvers
{
- public class PlaylistResolver : FolderResolver<Playlist>
+ /// <summary>
+ /// <see cref="IItemResolver"/> for <see cref="Playlist"/> library items.
+ /// </summary>
+ public class PlaylistResolver : GenericFolderResolver<Playlist>
{
- private string[] SupportedCollectionTypes = new string[] {
-
+ private string[] _musicPlaylistCollectionTypes =
+ {
string.Empty,
CollectionType.Music
};
- /// <summary>
- /// Resolves the specified args.
- /// </summary>
- /// <param name="args">The args.</param>
- /// <returns>BoxSet.</returns>
+ /// <inheritdoc/>
protected override Playlist Resolve(ItemResolveArgs args)
{
- // It's a boxset if all of the following conditions are met:
- // Is a Directory
- // Contains [playlist] in the path
if (args.IsDirectory)
{
- var filename = Path.GetFileName(args.Path);
-
- if (string.IsNullOrEmpty(filename))
+ // It's a boxset if the path is a directory with [playlist] in it's the name
+ // TODO: Should this use Path.GetDirectoryName() instead?
+ bool isBoxSet = Path.GetFileName(args.Path)
+ ?.Contains("[playlist]", StringComparison.OrdinalIgnoreCase)
+ ?? false;
+ if (isBoxSet)
{
- return null;
+ return new Playlist
+ {
+ Path = args.Path,
+ Name = Path.GetFileName(args.Path).Replace("[playlist]", string.Empty, StringComparison.OrdinalIgnoreCase).Trim()
+ };
}
- if (filename.IndexOf("[playlist]", StringComparison.OrdinalIgnoreCase) != -1)
+ // It's a directory-based playlist if the directory contains a playlist file
+ var filePaths = Directory.EnumerateFiles(args.Path, "*", new EnumerationOptions { IgnoreInaccessible = true });
+ if (filePaths.Any(f => f.EndsWith(PlaylistXmlSaver.DefaultPlaylistFilename, StringComparison.OrdinalIgnoreCase)))
{
return new Playlist
{
Path = args.Path,
- Name = Path.GetFileName(args.Path).Replace("[playlist]", string.Empty, StringComparison.OrdinalIgnoreCase).Trim()
+ Name = Path.GetFileName(args.Path)
};
}
}
- else
+
+ // Check if this is a music playlist file
+ // It should have the correct collection type and a supported file extension
+ else if (_musicPlaylistCollectionTypes.Contains(args.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
- if (SupportedCollectionTypes.Contains(args.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ var extension = Path.GetExtension(args.Path);
+ if (Playlist.SupportedExtensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
- var extension = Path.GetExtension(args.Path);
- if (Playlist.SupportedExtensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ return new Playlist
{
- return new Playlist
- {
- Path = args.Path,
- Name = Path.GetFileNameWithoutExtension(args.Path),
- IsInMixedFolder = true
- };
- }
+ Path = args.Path,
+ Name = Path.GetFileNameWithoutExtension(args.Path),
+ IsInMixedFolder = true,
+ PlaylistMediaType = MediaType.Audio
+ };
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs
index 7e4b38b4c..6bb999641 100644
--- a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Linq;
@@ -9,7 +13,7 @@ using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Library.Resolvers
{
- public class SpecialFolderResolver : FolderResolver<Folder>
+ public class SpecialFolderResolver : GenericFolderResolver<Folder>
{
private readonly IFileSystem _fileSystem;
private readonly IServerApplicationPaths _appPaths;
@@ -39,10 +43,12 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
return new AggregateFolder();
}
+
if (string.Equals(args.Path, _appPaths.DefaultUserViewsPath, StringComparison.OrdinalIgnoreCase))
{
- return new UserRootFolder(); //if we got here and still a root - must be user root
+ return new UserRootFolder(); // if we got here and still a root - must be user root
}
+
if (args.IsVf)
{
return new CollectionFolder
@@ -61,7 +67,6 @@ namespace Emby.Server.Implementations.Library.Resolvers
return args.FileSystemChildren
.Where(i =>
{
-
try
{
return !i.IsDirectory &&
@@ -71,7 +76,6 @@ namespace Emby.Server.Implementations.Library.Resolvers
{
return false;
}
-
})
.Select(i => _fileSystem.GetFileNameWithoutExtension(i))
.FirstOrDefault();
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs
index a6d18c9b5..cf2d22f4d 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs
@@ -1,5 +1,8 @@
+#nullable disable
+
using System;
using System.Linq;
+using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
@@ -7,16 +10,25 @@ using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers.TV
{
/// <summary>
- /// Class EpisodeResolver
+ /// Class EpisodeResolver.
/// </summary>
public class EpisodeResolver : BaseVideoResolver<Episode>
{
/// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeResolver"/> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ public EpisodeResolver(ILibraryManager libraryManager)
+ : base(libraryManager)
+ {
+ }
+
+ /// <summary>
/// Resolves the specified args.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>Episode.</returns>
- protected override Episode Resolve(ItemResolveArgs args)
+ public override Episode Resolve(ItemResolveArgs args)
{
var parent = args.Parent;
@@ -25,35 +37,30 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
return null;
}
- var season = parent as Season;
// Just in case the user decided to nest episodes.
// Not officially supported but in some cases we can handle it.
- if (season == null)
- {
- season = parent.GetParents().OfType<Season>().FirstOrDefault();
- }
- // If the parent is a Season or Series, then this is an Episode if the VideoResolver returns something
+ var season = parent as Season ?? parent.GetParents().OfType<Season>().FirstOrDefault();
+
+ // If the parent is a Season or Series and the parent is not an extras folder, then this is an Episode if the VideoResolver returns something
// Also handle flat tv folders
- if (season != null ||
- string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) ||
- args.HasParent<Series>())
+ if ((season != null ||
+ string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) ||
+ args.HasParent<Series>())
+ && (parent is Series || !BaseItem.AllExtrasTypesFolderNames.ContainsKey(parent.Name)))
{
var episode = ResolveVideo<Episode>(args, false);
if (episode != null)
{
- var series = parent as Series;
- if (series == null)
- {
- series = parent.GetParents().OfType<Series>().FirstOrDefault();
- }
+ var series = parent as Series ?? parent.GetParents().OfType<Series>().FirstOrDefault();
if (series != null)
{
episode.SeriesId = series.Id;
episode.SeriesName = series.Name;
}
+
if (season != null)
{
episode.SeasonId = season.Id;
@@ -72,10 +79,5 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
return null;
}
-
- public EpisodeResolver(ILibraryManager libraryManager)
- : base(libraryManager)
- {
- }
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
index ce1386e91..063f67543 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
@@ -1,6 +1,7 @@
+#nullable disable
+
using System.Globalization;
using Emby.Naming.TV;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization;
@@ -9,30 +10,25 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.TV
{
/// <summary>
- /// Class SeasonResolver
+ /// Class SeasonResolver.
/// </summary>
- public class SeasonResolver : FolderResolver<Season>
+ public class SeasonResolver : GenericFolderResolver<Season>
{
- /// <summary>
- /// The _config
- /// </summary>
- private readonly IServerConfigurationManager _config;
-
private readonly ILibraryManager _libraryManager;
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
private readonly ILocalizationManager _localization;
- private readonly ILogger _logger;
+ private readonly ILogger<SeasonResolver> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SeasonResolver"/> class.
/// </summary>
- /// <param name="config">The config.</param>
/// <param name="libraryManager">The library manager.</param>
- /// <param name="localization">The localization</param>
- /// <param name="logger">The logger</param>
- public SeasonResolver(IServerConfigurationManager config, ILibraryManager libraryManager, ILocalizationManager localization, ILogger logger)
+ /// <param name="localization">The localization.</param>
+ /// <param name="logger">The logger.</param>
+ public SeasonResolver(
+ ILibraryManager libraryManager,
+ ILocalizationManager localization,
+ ILogger<SeasonResolver> logger)
{
- _config = config;
_libraryManager = libraryManager;
_localization = localization;
_logger = logger;
@@ -45,14 +41,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
/// <returns>Season.</returns>
protected override Season Resolve(ItemResolveArgs args)
{
- if (args.Parent is Series && args.IsDirectory)
+ if (args.Parent is Series series && args.IsDirectory)
{
var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions();
- var series = ((Series)args.Parent);
var path = args.Path;
- var seasonParserResult = new SeasonPathParser(namingOptions).Parse(path, true, true);
+ var seasonParserResult = SeasonPathParser.Parse(path, true, true);
var season = new Season
{
@@ -74,7 +69,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
{
if (episodeInfo.EpisodeNumber.HasValue && episodeInfo.SeasonNumber.HasValue)
{
- _logger.LogDebug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}",
+ _logger.LogDebug(
+ "Found folder underneath series with episode number: {0}. Season {1}. Episode {2}",
path,
episodeInfo.SeasonNumber.Value,
episodeInfo.EpisodeNumber.Value);
@@ -90,8 +86,11 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
season.Name = seasonNumber == 0 ?
args.LibraryOptions.SeasonZeroDisplayName :
- string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.ToString(UsCulture), args.GetLibraryOptions().PreferredMetadataLanguage);
-
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("NameSeasonNumber"),
+ seasonNumber,
+ args.LibraryOptions.PreferredMetadataLanguage);
}
return season;
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
index 5c95534ec..b7fbe01c5 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
@@ -1,12 +1,14 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using Emby.Naming.TV;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
@@ -14,17 +16,20 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.TV
{
/// <summary>
- /// Class SeriesResolver
+ /// Class SeriesResolver.
/// </summary>
- public class SeriesResolver : FolderResolver<Series>
+ public class SeriesResolver : GenericFolderResolver<Series>
{
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
+ private readonly ILogger<SeriesResolver> _logger;
private readonly ILibraryManager _libraryManager;
- public SeriesResolver(IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeriesResolver"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ public SeriesResolver(ILogger<SeriesResolver> logger, ILibraryManager libraryManager)
{
- _fileSystem = fileSystem;
_logger = logger;
_libraryManager = libraryManager;
}
@@ -52,15 +57,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
var collectionType = args.GetCollectionType();
if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
{
- //if (args.ContainsFileSystemEntryByName("tvshow.nfo"))
- //{
- // return new Series
- // {
- // Path = args.Path,
- // Name = Path.GetFileName(args.Path)
- // };
- //}
-
var configuredContentType = _libraryManager.GetConfiguredContentType(args.Path);
if (!string.Equals(configuredContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
{
@@ -93,7 +89,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
return null;
}
- if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, args.GetLibraryOptions(), false))
+ if (IsSeriesFolder(args.Path, args.FileSystemChildren, _logger, _libraryManager, false))
{
return new Series
{
@@ -110,31 +106,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
public static bool IsSeriesFolder(
string path,
IEnumerable<FileSystemMetadata> fileSystemChildren,
- IDirectoryService directoryService,
- IFileSystem fileSystem,
- ILogger logger,
+ ILogger<SeriesResolver> logger,
ILibraryManager libraryManager,
- LibraryOptions libraryOptions,
bool isTvContentType)
{
foreach (var child in fileSystemChildren)
{
- //if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
- //{
- // //logger.LogDebug("Igoring series file or folder marked hidden: {0}", child.FullName);
- // continue;
- //}
-
- // Can't enforce this because files saved by Bitcasa are always marked System
- //if ((attributes & FileAttributes.System) == FileAttributes.System)
- //{
- // logger.LogDebug("Igoring series subfolder marked system: {0}", child.FullName);
- // continue;
- //}
-
if (child.IsDirectory)
{
- if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager))
+ if (IsSeasonFolder(child.FullName, isTvContentType))
{
logger.LogDebug("{Path} is a series because of season folder {Dir}.", path, child.FullName);
return true;
@@ -143,7 +123,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
else
{
string fullName = child.FullName;
- if (libraryManager.IsVideoFile(fullName, libraryOptions))
+ if (libraryManager.IsVideoFile(fullName))
{
if (isTvContentType)
{
@@ -168,35 +148,14 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
}
/// <summary>
- /// Determines whether [is place holder] [the specified path].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns><c>true</c> if [is place holder] [the specified path]; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">path</exception>
- private static bool IsVideoPlaceHolder(string path)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- var extension = Path.GetExtension(path);
-
- return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
/// Determines whether [is season folder] [the specified path].
/// </summary>
/// <param name="path">The path.</param>
/// <param name="isTvContentType">if set to <c>true</c> [is tv content type].</param>
- /// <param name="libraryManager">The library manager.</param>
/// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns>
- private static bool IsSeasonFolder(string path, bool isTvContentType, ILibraryManager libraryManager)
+ private static bool IsSeasonFolder(string path, bool isTvContentType)
{
- var namingOptions = ((LibraryManager)libraryManager).GetNamingOptions();
-
- var seasonNumber = new SeasonPathParser(namingOptions).Parse(path, isTvContentType, isTvContentType).SeasonNumber;
+ var seasonNumber = SeasonPathParser.Parse(path, isTvContentType, isTvContentType).SeasonNumber;
return seasonNumber.HasValue;
}
@@ -226,7 +185,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
if (!string.IsNullOrEmpty(id))
{
- item.SetProviderId(MetadataProviders.Tvdb, id);
+ item.SetProviderId(MetadataProvider.Tvdb, id);
}
}
}
diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs
index 9c7f7dfcb..bebc25b77 100644
--- a/Emby.Server.Implementations/Library/SearchEngine.cs
+++ b/Emby.Server.Implementations/Library/SearchEngine.cs
@@ -1,42 +1,39 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Diacritics.Extensions;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Extensions;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Search;
-using Microsoft.Extensions.Logging;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Person = MediaBrowser.Controller.Entities.Person;
namespace Emby.Server.Implementations.Library
{
- /// <summary>
- /// </summary>
public class SearchEngine : ISearchEngine
{
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
- private readonly ILogger _logger;
- public SearchEngine(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager)
+ public SearchEngine(ILibraryManager libraryManager, IUserManager userManager)
{
_libraryManager = libraryManager;
_userManager = userManager;
-
- _logger = loggerFactory.CreateLogger("SearchEngine");
}
public QueryResult<SearchHintInfo> GetSearchHints(SearchQuery query)
{
User user = null;
-
- if (query.UserId.Equals(Guid.Empty))
- {
- }
- else
+ if (query.UserId != Guid.Empty)
{
user = _userManager.GetUserById(query.UserId);
}
@@ -46,19 +43,19 @@ namespace Emby.Server.Implementations.Library
if (query.StartIndex.HasValue)
{
- results = results.Skip(query.StartIndex.Value).ToList();
+ results = results.GetRange(query.StartIndex.Value, totalRecordCount - query.StartIndex.Value);
}
if (query.Limit.HasValue)
{
- results = results.Take(query.Limit.Value).ToList();
+ results = results.GetRange(0, Math.Min(query.Limit.Value, results.Count));
}
return new QueryResult<SearchHintInfo>
{
TotalRecordCount = totalRecordCount,
- Items = results.ToArray()
+ Items = results
};
}
@@ -76,14 +73,14 @@ namespace Emby.Server.Implementations.Library
/// <param name="query">The query.</param>
/// <param name="user">The user.</param>
/// <returns>IEnumerable{SearchHintResult}.</returns>
- /// <exception cref="ArgumentNullException">searchTerm</exception>
+ /// <exception cref="ArgumentException"><c>query.SearchTerm</c> is <c>null</c> or empty.</exception>
private List<SearchHintInfo> GetSearchHints(SearchQuery query, User user)
{
var searchTerm = query.SearchTerm;
if (string.IsNullOrEmpty(searchTerm))
{
- throw new ArgumentNullException(nameof(searchTerm));
+ throw new ArgumentException("SearchTerm can't be empty.", nameof(query));
}
searchTerm = searchTerm.Trim().RemoveDiacritics();
@@ -91,61 +88,61 @@ namespace Emby.Server.Implementations.Library
var excludeItemTypes = query.ExcludeItemTypes.ToList();
var includeItemTypes = (query.IncludeItemTypes ?? Array.Empty<string>()).ToList();
- excludeItemTypes.Add(typeof(Year).Name);
- excludeItemTypes.Add(typeof(Folder).Name);
+ excludeItemTypes.Add(nameof(Year));
+ excludeItemTypes.Add(nameof(Folder));
if (query.IncludeGenres && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
{
if (!query.IncludeMedia)
{
- AddIfMissing(includeItemTypes, typeof(Genre).Name);
- AddIfMissing(includeItemTypes, typeof(MusicGenre).Name);
+ AddIfMissing(includeItemTypes, nameof(Genre));
+ AddIfMissing(includeItemTypes, nameof(MusicGenre));
}
}
else
{
- AddIfMissing(excludeItemTypes, typeof(Genre).Name);
- AddIfMissing(excludeItemTypes, typeof(MusicGenre).Name);
+ AddIfMissing(excludeItemTypes, nameof(Genre));
+ AddIfMissing(excludeItemTypes, nameof(MusicGenre));
}
if (query.IncludePeople && (includeItemTypes.Count == 0 || includeItemTypes.Contains("People", StringComparer.OrdinalIgnoreCase) || includeItemTypes.Contains("Person", StringComparer.OrdinalIgnoreCase)))
{
if (!query.IncludeMedia)
{
- AddIfMissing(includeItemTypes, typeof(Person).Name);
+ AddIfMissing(includeItemTypes, nameof(Person));
}
}
else
{
- AddIfMissing(excludeItemTypes, typeof(Person).Name);
+ AddIfMissing(excludeItemTypes, nameof(Person));
}
if (query.IncludeStudios && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
{
if (!query.IncludeMedia)
{
- AddIfMissing(includeItemTypes, typeof(Studio).Name);
+ AddIfMissing(includeItemTypes, nameof(Studio));
}
}
else
{
- AddIfMissing(excludeItemTypes, typeof(Studio).Name);
+ AddIfMissing(excludeItemTypes, nameof(Studio));
}
if (query.IncludeArtists && (includeItemTypes.Count == 0 || includeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
{
if (!query.IncludeMedia)
{
- AddIfMissing(includeItemTypes, typeof(MusicArtist).Name);
+ AddIfMissing(includeItemTypes, nameof(MusicArtist));
}
}
else
{
- AddIfMissing(excludeItemTypes, typeof(MusicArtist).Name);
+ AddIfMissing(excludeItemTypes, nameof(MusicArtist));
}
- AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name);
- AddIfMissing(excludeItemTypes, typeof(Folder).Name);
+ AddIfMissing(excludeItemTypes, nameof(CollectionFolder));
+ AddIfMissing(excludeItemTypes, nameof(Folder));
var mediaTypes = query.MediaTypes.ToList();
if (includeItemTypes.Count > 0)
@@ -160,9 +157,9 @@ namespace Emby.Server.Implementations.Library
ExcludeItemTypes = excludeItemTypes.ToArray(),
IncludeItemTypes = includeItemTypes.ToArray(),
Limit = query.Limit,
- IncludeItemsByName = string.IsNullOrEmpty(query.ParentId),
- ParentId = string.IsNullOrEmpty(query.ParentId) ? Guid.Empty : new Guid(query.ParentId),
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) },
+ IncludeItemsByName = !query.ParentId.HasValue,
+ ParentId = query.ParentId ?? Guid.Empty,
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
Recursive = true,
IsKids = query.IsKids,
@@ -192,6 +189,7 @@ namespace Emby.Server.Implementations.Library
{
searchQuery.AncestorIds = new[] { searchQuery.ParentId };
}
+
searchQuery.ParentId = Guid.Empty;
searchQuery.IncludeItemsByName = true;
searchQuery.IncludeItemTypes = Array.Empty<string>();
@@ -205,7 +203,6 @@ namespace Emby.Server.Implementations.Library
return mediaItems.Select(i => new SearchHintInfo
{
Item = i
-
}).ToList();
}
}
diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs
index dfa1edaff..bb3034142 100644
--- a/Emby.Server.Implementations/Library/UserDataManager.cs
+++ b/Emby.Server.Implementations/Library/UserDataManager.cs
@@ -1,8 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -10,41 +15,38 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using Microsoft.Extensions.Logging;
+using AudioBook = MediaBrowser.Controller.Entities.AudioBook;
+using Book = MediaBrowser.Controller.Entities.Book;
namespace Emby.Server.Implementations.Library
{
/// <summary>
- /// Class UserDataManager
+ /// Class UserDataManager.
/// </summary>
public class UserDataManager : IUserDataManager
{
- public event EventHandler<UserDataSaveEventArgs> UserDataSaved;
-
private readonly ConcurrentDictionary<string, UserItemData> _userData =
new ConcurrentDictionary<string, UserItemData>(StringComparer.OrdinalIgnoreCase);
- private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
+ private readonly IUserManager _userManager;
+ private readonly IUserDataRepository _repository;
- private Func<IUserManager> _userManager;
-
- public UserDataManager(ILoggerFactory loggerFactory, IServerConfigurationManager config, Func<IUserManager> userManager)
+ public UserDataManager(
+ IServerConfigurationManager config,
+ IUserManager userManager,
+ IUserDataRepository repository)
{
_config = config;
- _logger = loggerFactory.CreateLogger(GetType().Name);
_userManager = userManager;
+ _repository = repository;
}
- /// <summary>
- /// Gets or sets the repository.
- /// </summary>
- /// <value>The repository.</value>
- public IUserDataRepository Repository { get; set; }
+ public event EventHandler<UserDataSaveEventArgs> UserDataSaved;
public void SaveUserData(Guid userId, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
{
- var user = _userManager().GetUserById(userId);
+ var user = _userManager.GetUserById(userId);
SaveUserData(user, item, userData, reason, cancellationToken);
}
@@ -55,6 +57,7 @@ namespace Emby.Server.Implementations.Library
{
throw new ArgumentNullException(nameof(userData));
}
+
if (item == null)
{
throw new ArgumentNullException(nameof(item));
@@ -68,7 +71,7 @@ namespace Emby.Server.Implementations.Library
foreach (var key in keys)
{
- Repository.SaveUserData(userId, key, userData, cancellationToken);
+ _repository.SaveUserData(userId, key, userData, cancellationToken);
}
var cacheKey = GetCacheKey(userId, item.Id);
@@ -87,32 +90,31 @@ namespace Emby.Server.Implementations.Library
/// <summary>
/// Save the provided user data for the given user. Batch operation. Does not fire any events or update the cache.
/// </summary>
- /// <param name="userId"></param>
- /// <param name="userData"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <param name="userData">The user item data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
public void SaveAllUserData(Guid userId, UserItemData[] userData, CancellationToken cancellationToken)
{
- var user = _userManager().GetUserById(userId);
+ var user = _userManager.GetUserById(userId);
- Repository.SaveAllUserData(user.InternalId, userData, cancellationToken);
+ _repository.SaveAllUserData(user.InternalId, userData, cancellationToken);
}
/// <summary>
- /// Retrieve all user data for the given user
+ /// Retrieve all user data for the given user.
/// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <returns>A <see cref="List{UserItemData}"/> containing all of the user's item data.</returns>
public List<UserItemData> GetAllUserData(Guid userId)
{
- var user = _userManager().GetUserById(userId);
+ var user = _userManager.GetUserById(userId);
- return Repository.GetAllUserData(user.InternalId);
+ return _repository.GetAllUserData(user.InternalId);
}
public UserItemData GetUserData(Guid userId, Guid itemId, List<string> keys)
{
- var user = _userManager().GetUserById(userId);
+ var user = _userManager.GetUserById(userId);
return GetUserData(user, itemId, keys);
}
@@ -128,7 +130,7 @@ namespace Emby.Server.Implementations.Library
private UserItemData GetUserDataInternal(long internalUserId, List<string> keys)
{
- var userData = Repository.GetUserData(internalUserId, keys);
+ var userData = _repository.GetUserData(internalUserId, keys);
if (userData != null)
{
@@ -152,7 +154,7 @@ namespace Emby.Server.Implementations.Library
/// <returns>System.String.</returns>
private static string GetCacheKey(long internalUserId, Guid itemId)
{
- return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N");
+ return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N", CultureInfo.InvariantCulture);
}
public UserItemData GetUserData(User user, BaseItem item)
@@ -160,11 +162,6 @@ namespace Emby.Server.Implementations.Library
return GetUserData(user, item.Id, item.GetUserDataKeys());
}
- public UserItemData GetUserData(string userId, BaseItem item)
- {
- return GetUserData(new Guid(userId), item);
- }
-
public UserItemData GetUserData(Guid userId, BaseItem item)
{
return GetUserData(userId, item.Id, item.GetUserDataKeys());
@@ -179,6 +176,7 @@ namespace Emby.Server.Implementations.Library
return dto;
}
+ /// <inheritdoc />
public UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto itemDto, User user, DtoOptions options)
{
var userData = GetUserData(user, item);
@@ -189,11 +187,11 @@ namespace Emby.Server.Implementations.Library
}
/// <summary>
- /// Converts a UserItemData to a DTOUserItemData
+ /// Converts a UserItemData to a DTOUserItemData.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>DtoUserItemData.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
private UserItemDataDto GetUserItemDataDto(UserItemData data)
{
if (data == null)
@@ -214,6 +212,7 @@ namespace Emby.Server.Implementations.Library
};
}
+ /// <inheritdoc />
public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
{
var playedToCompletion = false;
@@ -224,28 +223,25 @@ namespace Emby.Server.Implementations.Library
var hasRuntime = runtimeTicks > 0;
// If a position has been reported, and if we know the duration
- if (positionTicks > 0 && hasRuntime)
+ if (positionTicks > 0 && hasRuntime && item is not AudioBook && item is not Book)
{
var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100;
- // Don't track in very beginning
if (pctIn < _config.Configuration.MinResumePct)
{
+ // ignore progress during the beginning
positionTicks = 0;
}
-
- // If we're at the end, assume completed
else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= runtimeTicks)
{
+ // mark as completed close to the end
positionTicks = 0;
data.Played = playedToCompletion = true;
}
-
else
{
// Enforce MinResumeDuration
var durationSeconds = TimeSpan.FromTicks(runtimeTicks).TotalSeconds;
-
if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
{
positionTicks = 0;
@@ -253,6 +249,23 @@ namespace Emby.Server.Implementations.Library
}
}
}
+ else if (positionTicks > 0 && hasRuntime && item is AudioBook)
+ {
+ var playbackPositionInMinutes = TimeSpan.FromTicks(positionTicks).TotalMinutes;
+ var remainingTimeInMinutes = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes;
+
+ if (playbackPositionInMinutes < _config.Configuration.MinAudiobookResume)
+ {
+ // ignore progress during the beginning
+ positionTicks = 0;
+ }
+ else if (remainingTimeInMinutes < _config.Configuration.MaxAudiobookResume || positionTicks >= runtimeTicks)
+ {
+ // mark as completed close to the end
+ positionTicks = 0;
+ data.Played = playedToCompletion = true;
+ }
+ }
else if (!hasRuntime)
{
// If we don't know the runtime we'll just have to assume it was fully played
@@ -265,6 +278,7 @@ namespace Emby.Server.Implementations.Library
positionTicks = 0;
data.Played = false;
}
+
if (!item.SupportsPositionTicksResume)
{
positionTicks = 0;
diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs
deleted file mode 100644
index dfef8e997..000000000
--- a/Emby.Server.Implementations/Library/UserManager.cs
+++ /dev/null
@@ -1,1220 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Library
-{
- /// <summary>
- /// Class UserManager
- /// </summary>
- public class UserManager : IUserManager
- {
- /// <summary>
- /// Gets the users.
- /// </summary>
- /// <value>The users.</value>
- public IEnumerable<User> Users => _users;
-
- private User[] _users;
-
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
- /// <summary>
- /// Gets or sets the configuration manager.
- /// </summary>
- /// <value>The configuration manager.</value>
- private IServerConfigurationManager ConfigurationManager { get; set; }
-
- /// <summary>
- /// Gets the active user repository
- /// </summary>
- /// <value>The user repository.</value>
- private IUserRepository UserRepository { get; set; }
- public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
-
- private readonly IXmlSerializer _xmlSerializer;
- private readonly IJsonSerializer _jsonSerializer;
-
- private readonly INetworkManager _networkManager;
-
- private readonly Func<IImageProcessor> _imageProcessorFactory;
- private readonly Func<IDtoService> _dtoServiceFactory;
- private readonly IServerApplicationHost _appHost;
- private readonly IFileSystem _fileSystem;
-
- private IAuthenticationProvider[] _authenticationProviders;
- private DefaultAuthenticationProvider _defaultAuthenticationProvider;
-
- public UserManager(
- ILoggerFactory loggerFactory,
- IServerConfigurationManager configurationManager,
- IUserRepository userRepository,
- IXmlSerializer xmlSerializer,
- INetworkManager networkManager,
- Func<IImageProcessor> imageProcessorFactory,
- Func<IDtoService> dtoServiceFactory,
- IServerApplicationHost appHost,
- IJsonSerializer jsonSerializer,
- IFileSystem fileSystem)
- {
- _logger = loggerFactory.CreateLogger(nameof(UserManager));
- UserRepository = userRepository;
- _xmlSerializer = xmlSerializer;
- _networkManager = networkManager;
- _imageProcessorFactory = imageProcessorFactory;
- _dtoServiceFactory = dtoServiceFactory;
- _appHost = appHost;
- _jsonSerializer = jsonSerializer;
- _fileSystem = fileSystem;
- ConfigurationManager = configurationManager;
- _users = Array.Empty<User>();
-
- DeletePinFile();
- }
-
- public NameIdPair[] GetAuthenticationProviders()
- {
- return _authenticationProviders
- .Where(i => i.IsEnabled)
- .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
- .ThenBy(i => i.Name)
- .Select(i => new NameIdPair
- {
- Name = i.Name,
- Id = GetAuthenticationProviderId(i)
- })
- .ToArray();
- }
-
- public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders)
- {
- _authenticationProviders = authenticationProviders.ToArray();
-
- _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
- }
-
- #region UserUpdated Event
- /// <summary>
- /// Occurs when [user updated].
- /// </summary>
- public event EventHandler<GenericEventArgs<User>> UserUpdated;
- public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
- public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
- public event EventHandler<GenericEventArgs<User>> UserLockedOut;
-
- /// <summary>
- /// Called when [user updated].
- /// </summary>
- /// <param name="user">The user.</param>
- private void OnUserUpdated(User user)
- {
- UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
- }
- #endregion
-
- #region UserDeleted Event
- /// <summary>
- /// Occurs when [user deleted].
- /// </summary>
- public event EventHandler<GenericEventArgs<User>> UserDeleted;
- /// <summary>
- /// Called when [user deleted].
- /// </summary>
- /// <param name="user">The user.</param>
- private void OnUserDeleted(User user)
- {
- UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
- }
- #endregion
-
- /// <summary>
- /// Gets a User by Id
- /// </summary>
- /// <param name="id">The id.</param>
- /// <returns>User.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- public User GetUserById(Guid id)
- {
- if (id == Guid.Empty)
- {
- throw new ArgumentException(nameof(id), "Guid can't be empty");
- }
-
- return Users.FirstOrDefault(u => u.Id == id);
- }
-
- /// <summary>
- /// Gets the user by identifier.
- /// </summary>
- /// <param name="id">The identifier.</param>
- /// <returns>User.</returns>
- public User GetUserById(string id)
- {
- return GetUserById(new Guid(id));
- }
-
- public User GetUserByName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
- }
-
- public void Initialize()
- {
- _users = LoadUsers();
-
- var users = Users.ToList();
-
- // If there are no local users with admin rights, make them all admins
- if (!users.Any(i => i.Policy.IsAdministrator))
- {
- foreach (var user in users)
- {
- user.Policy.IsAdministrator = true;
- UpdateUserPolicy(user, user.Policy, false);
- }
- }
- }
-
- public bool IsValidUsername(string username)
- {
- // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
- foreach (var currentChar in username)
- {
- if (!IsValidUsernameCharacter(currentChar))
- {
- return false;
- }
- }
- return true;
- }
-
- private static bool IsValidUsernameCharacter(char i)
- {
- return !char.Equals(i, '<') && !char.Equals(i, '>');
- }
-
- public string MakeValidUsername(string username)
- {
- if (IsValidUsername(username))
- {
- return username;
- }
-
- // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
- var builder = new StringBuilder();
-
- foreach (var c in username)
- {
- if (IsValidUsernameCharacter(c))
- {
- builder.Append(c);
- }
- }
- return builder.ToString();
- }
-
- public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
- {
- if (string.IsNullOrWhiteSpace(username))
- {
- throw new ArgumentNullException(nameof(username));
- }
-
- var user = Users
- .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
-
- var success = false;
- IAuthenticationProvider authenticationProvider = null;
-
- if (user != null)
- {
- var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
- authenticationProvider = authResult.Item1;
- success = authResult.Item2;
- }
- else
- {
- // user is null
- var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
- authenticationProvider = authResult.Item1;
- success = authResult.Item2;
-
- if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
- {
- user = await CreateUser(username).ConfigureAwait(false);
-
- var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
- if (hasNewUserPolicy != null)
- {
- var policy = hasNewUserPolicy.GetNewUserPolicy();
- UpdateUserPolicy(user, policy, true);
- }
- }
- }
-
- if (success && user != null && authenticationProvider != null)
- {
- var providerId = GetAuthenticationProviderId(authenticationProvider);
-
- if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
- {
- user.Policy.AuthenticationProviderId = providerId;
- UpdateUserPolicy(user, user.Policy, true);
- }
- }
-
- if (user == null)
- {
- throw new SecurityException("Invalid username or password entered.");
- }
-
- if (user.Policy.IsDisabled)
- {
- throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
- }
-
- if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
- {
- throw new SecurityException("Forbidden.");
- }
-
- if (!user.IsParentalScheduleAllowed())
- {
- throw new SecurityException("User is not allowed access at this time.");
- }
-
- // Update LastActivityDate and LastLoginDate, then save
- if (success)
- {
- if (isUserSession)
- {
- user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
- UpdateUser(user);
- }
- UpdateInvalidLoginAttemptCount(user, 0);
- }
- else
- {
- UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
- }
-
- _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
-
- return success ? user : null;
- }
-
- private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
- {
- return provider.GetType().FullName;
- }
-
- private IAuthenticationProvider GetAuthenticationProvider(User user)
- {
- return GetAuthenticationProviders(user).First();
- }
-
- private IAuthenticationProvider[] GetAuthenticationProviders(User user)
- {
- var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
-
- var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
-
- if (!string.IsNullOrEmpty(authenticationProviderId))
- {
- providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
- }
-
- if (providers.Length == 0)
- {
- providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
- }
-
- return providers;
- }
-
- private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
- {
- try
- {
- var requiresResolvedUser = provider as IRequiresResolvedUser;
- if (requiresResolvedUser != null)
- {
- await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
- }
- else
- {
- await provider.Authenticate(username, password).ConfigureAwait(false);
- }
-
- return true;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
-
- return false;
- }
- }
-
- private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
- {
- bool success = false;
- IAuthenticationProvider authenticationProvider = null;
-
- if (password != null && user != null)
- {
- // Doesn't look like this is even possible to be used, because of password == null checks below
- hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
- }
-
- if (password == null)
- {
- // legacy
- success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- foreach (var provider in GetAuthenticationProviders(user))
- {
- success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
-
- if (success)
- {
- authenticationProvider = provider;
- break;
- }
- }
- }
-
- if (user != null)
- {
- if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
- {
- if (password == null)
- {
- // legacy
- success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
- }
- }
- }
-
- return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
- }
-
- private void UpdateInvalidLoginAttemptCount(User user, int newValue)
- {
- if (user.Policy.InvalidLoginAttemptCount == newValue || newValue <= 0)
- {
- return;
- }
-
- user.Policy.InvalidLoginAttemptCount = newValue;
-
- var maxCount = user.Policy.IsAdministrator ? 3 : 5;
-
- var fireLockout = false;
-
- if (newValue >= maxCount)
- {
- _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
- user.Policy.IsDisabled = true;
-
- fireLockout = true;
- }
-
- UpdateUserPolicy(user, user.Policy, false);
-
- if (fireLockout)
- {
- UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
- }
- }
-
- private string GetLocalPasswordHash(User user)
- {
- return string.IsNullOrEmpty(user.EasyPassword)
- ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
- : user.EasyPassword;
- }
-
- private bool IsPasswordEmpty(User user, string passwordHash)
- {
- return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Loads the users from the repository
- /// </summary>
- /// <returns>IEnumerable{User}.</returns>
- private User[] LoadUsers()
- {
- var users = UserRepository.RetrieveAllUsers();
-
- // There always has to be at least one user.
- if (users.Count == 0)
- {
- var defaultName = Environment.UserName;
- if (string.IsNullOrWhiteSpace(defaultName))
- {
- defaultName = "MyJellyfinUser";
- }
- var name = MakeValidUsername(defaultName);
-
- var user = InstantiateNewUser(name);
-
- user.DateLastSaved = DateTime.UtcNow;
-
- UserRepository.CreateUser(user);
-
- users.Add(user);
-
- user.Policy.IsAdministrator = true;
- user.Policy.EnableContentDeletion = true;
- user.Policy.EnableRemoteControlOfOtherUsers = true;
- UpdateUserPolicy(user, user.Policy, false);
- }
-
- return users.ToArray();
- }
-
- public UserDto GetUserDto(User user, string remoteEndPoint = null)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
- var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
-
- var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
- hasConfiguredEasyPassword :
- hasConfiguredPassword;
-
- var dto = new UserDto
- {
- Id = user.Id,
- Name = user.Name,
- HasPassword = hasPassword,
- HasConfiguredPassword = hasConfiguredPassword,
- HasConfiguredEasyPassword = hasConfiguredEasyPassword,
- LastActivityDate = user.LastActivityDate,
- LastLoginDate = user.LastLoginDate,
- Configuration = user.Configuration,
- ServerId = _appHost.SystemId,
- Policy = user.Policy
- };
-
- if (!hasPassword && Users.Count() == 1)
- {
- dto.EnableAutoLogin = true;
- }
-
- var image = user.GetImageInfo(ImageType.Primary, 0);
-
- if (image != null)
- {
- dto.PrimaryImageTag = GetImageCacheTag(user, image);
-
- try
- {
- _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
- }
- catch (Exception ex)
- {
- // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
- _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
- }
- }
-
- return dto;
- }
-
- public UserDto GetOfflineUserDto(User user)
- {
- var dto = GetUserDto(user);
-
- dto.ServerName = _appHost.FriendlyName;
-
- return dto;
- }
-
- private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
- {
- try
- {
- return _imageProcessorFactory().GetImageCacheTag(item, image);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
- return null;
- }
- }
-
- /// <summary>
- /// Refreshes metadata for each user
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
- {
- foreach (var user in Users)
- {
- await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
- }
- }
-
- /// <summary>
- /// Renames the user.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <param name="newName">The new name.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
- public async Task RenameUser(User user, string newName)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- if (string.IsNullOrEmpty(newName))
- {
- throw new ArgumentNullException(nameof(newName));
- }
-
- if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
- {
- throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
- }
-
- if (user.Name.Equals(newName, StringComparison.Ordinal))
- {
- throw new ArgumentException("The new and old names must be different.");
- }
-
- await user.Rename(newName);
-
- OnUserUpdated(user);
- }
-
- /// <summary>
- /// Updates the user.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
- public void UpdateUser(User user)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
- {
- throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
- }
-
- user.DateModified = DateTime.UtcNow;
- user.DateLastSaved = DateTime.UtcNow;
-
- UserRepository.UpdateUser(user);
-
- OnUserUpdated(user);
- }
-
- public event EventHandler<GenericEventArgs<User>> UserCreated;
-
- private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
-
- /// <summary>
- /// Creates the user.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <returns>User.</returns>
- /// <exception cref="ArgumentNullException">name</exception>
- /// <exception cref="ArgumentException"></exception>
- public async Task<User> CreateUser(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- if (!IsValidUsername(name))
- {
- throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
- }
-
- if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
- {
- throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
- }
-
- await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
-
- try
- {
- var user = InstantiateNewUser(name);
-
- var list = Users.ToList();
- list.Add(user);
- _users = list.ToArray();
-
- user.DateLastSaved = DateTime.UtcNow;
-
- UserRepository.CreateUser(user);
-
- EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
-
- return user;
- }
- finally
- {
- _userListLock.Release();
- }
- }
-
- /// <summary>
- /// Deletes the user.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
- public async Task DeleteUser(User user)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- var allUsers = Users.ToList();
-
- if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
- {
- throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
- }
-
- if (allUsers.Count == 1)
- {
- throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
- }
-
- if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
- {
- throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name));
- }
-
- await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
-
- try
- {
- var configPath = GetConfigurationFilePath(user);
-
- UserRepository.DeleteUser(user);
-
- try
- {
- _fileSystem.DeleteFile(configPath);
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error deleting file {path}", configPath);
- }
-
- DeleteUserPolicy(user);
-
- _users = allUsers.Where(i => i.Id != user.Id).ToArray();
-
- OnUserDeleted(user);
- }
- finally
- {
- _userListLock.Release();
- }
- }
-
- /// <summary>
- /// Resets the password by clearing it.
- /// </summary>
- /// <returns>Task.</returns>
- public Task ResetPassword(User user)
- {
- return ChangePassword(user, string.Empty);
- }
-
- public void ResetEasyPassword(User user)
- {
- ChangeEasyPassword(user, string.Empty, null);
- }
-
- public async Task ChangePassword(User user, string newPassword)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
-
- UpdateUser(user);
-
- UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
- }
-
- public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
- {
- if (user == null)
- {
- throw new ArgumentNullException(nameof(user));
- }
-
- if (newPassword != null)
- {
- newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
- }
-
- if (string.IsNullOrWhiteSpace(newPasswordHash))
- {
- throw new ArgumentNullException(nameof(newPasswordHash));
- }
-
- user.EasyPassword = newPasswordHash;
-
- UpdateUser(user);
-
- UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
- }
-
- /// <summary>
- /// Instantiates the new user.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <returns>User.</returns>
- private static User InstantiateNewUser(string name)
- {
- return new User
- {
- Name = name,
- Id = Guid.NewGuid(),
- DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow,
- UsesIdForConfigurationPath = true,
- //Salt = BCrypt.GenerateSalt()
- };
- }
-
- private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt");
-
- private string _lastPin;
- private PasswordPinCreationResult _lastPasswordPinCreationResult;
- private int _pinAttempts;
-
- private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
- {
- var num = new Random().Next(1, 9999);
-
- var path = PasswordResetFile;
-
- var pin = num.ToString("0000", CultureInfo.InvariantCulture);
- _lastPin = pin;
-
- var time = TimeSpan.FromMinutes(5);
- var expiration = DateTime.UtcNow.Add(time);
-
- var text = new StringBuilder();
-
- var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
-
- text.AppendLine("Use your web browser to visit:");
- text.AppendLine(string.Empty);
- text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html");
- text.AppendLine(string.Empty);
- text.AppendLine("Enter the following pin code:");
- text.AppendLine(string.Empty);
- text.AppendLine(pin);
- text.AppendLine(string.Empty);
-
- var localExpirationTime = expiration.ToLocalTime();
- // Tuesday, 22 August 2006 06:30 AM
- text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
-
- File.WriteAllText(path, text.ToString(), Encoding.UTF8);
-
- var result = new PasswordPinCreationResult
- {
- PinFile = path,
- ExpirationDate = expiration
- };
-
- _lastPasswordPinCreationResult = result;
- _pinAttempts = 0;
-
- return result;
- }
-
- public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
- {
- DeletePinFile();
-
- var user = string.IsNullOrWhiteSpace(enteredUsername) ?
- null :
- GetUserByName(enteredUsername);
-
- var action = ForgotPasswordAction.InNetworkRequired;
- string pinFile = null;
- DateTime? expirationDate = null;
-
- if (user != null && !user.Policy.IsAdministrator)
- {
- action = ForgotPasswordAction.ContactAdmin;
- }
- else
- {
- if (isInNetwork)
- {
- action = ForgotPasswordAction.PinCode;
- }
-
- var result = await CreatePasswordResetPin().ConfigureAwait(false);
- pinFile = result.PinFile;
- expirationDate = result.ExpirationDate;
- }
-
- return new ForgotPasswordResult
- {
- Action = action,
- PinFile = pinFile,
- PinExpirationDate = expirationDate
- };
- }
-
- public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
- {
- DeletePinFile();
-
- var usersReset = new List<string>();
-
- var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
- string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
- _lastPasswordPinCreationResult != null &&
- _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
-
- if (valid)
- {
- _lastPin = null;
- _lastPasswordPinCreationResult = null;
-
- foreach (var user in Users)
- {
- await ResetPassword(user).ConfigureAwait(false);
-
- if (user.Policy.IsDisabled)
- {
- user.Policy.IsDisabled = false;
- UpdateUserPolicy(user, user.Policy, true);
- }
- usersReset.Add(user.Name);
- }
- }
- else
- {
- _pinAttempts++;
- if (_pinAttempts >= 3)
- {
- _lastPin = null;
- _lastPasswordPinCreationResult = null;
- }
- }
-
- return new PinRedeemResult
- {
- Success = valid,
- UsersReset = usersReset.ToArray()
- };
- }
-
- private void DeletePinFile()
- {
- try
- {
- _fileSystem.DeleteFile(PasswordResetFile);
- }
- catch
- {
-
- }
- }
-
- class PasswordPinCreationResult
- {
- public string PinFile { get; set; }
- public DateTime ExpirationDate { get; set; }
- }
-
- public UserPolicy GetUserPolicy(User user)
- {
- var path = GetPolicyFilePath(user);
-
- if (!File.Exists(path))
- {
- return GetDefaultPolicy(user);
- }
-
- try
- {
- lock (_policySyncLock)
- {
- return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
- }
- }
- catch (IOException)
- {
- return GetDefaultPolicy(user);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error reading policy file: {path}", path);
-
- return GetDefaultPolicy(user);
- }
- }
-
- private static UserPolicy GetDefaultPolicy(User user)
- {
- return new UserPolicy
- {
- EnableContentDownloading = true,
- EnableSyncTranscoding = true
- };
- }
-
- private readonly object _policySyncLock = new object();
- public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
- {
- var user = GetUserById(userId);
- UpdateUserPolicy(user, userPolicy, true);
- }
-
- private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
- {
- // The xml serializer will output differently if the type is not exact
- if (userPolicy.GetType() != typeof(UserPolicy))
- {
- var json = _jsonSerializer.SerializeToString(userPolicy);
- userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
- }
-
- var path = GetPolicyFilePath(user);
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- lock (_policySyncLock)
- {
- _xmlSerializer.SerializeToFile(userPolicy, path);
- user.Policy = userPolicy;
- }
-
- if (fireEvent)
- {
- UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
- }
- }
-
- private void DeleteUserPolicy(User user)
- {
- var path = GetPolicyFilePath(user);
-
- try
- {
- lock (_policySyncLock)
- {
- _fileSystem.DeleteFile(path);
- }
- }
- catch (IOException)
- {
-
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error deleting policy file");
- }
- }
-
- private static string GetPolicyFilePath(User user)
- {
- return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
- }
-
- private static string GetConfigurationFilePath(User user)
- {
- return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
- }
-
- public UserConfiguration GetUserConfiguration(User user)
- {
- var path = GetConfigurationFilePath(user);
-
- if (!File.Exists(path))
- {
- return new UserConfiguration();
- }
-
- try
- {
- lock (_configSyncLock)
- {
- return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
- }
- }
- catch (IOException)
- {
- return new UserConfiguration();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error reading policy file: {path}", path);
-
- return new UserConfiguration();
- }
- }
-
- private readonly object _configSyncLock = new object();
- public void UpdateConfiguration(Guid userId, UserConfiguration config)
- {
- var user = GetUserById(userId);
- UpdateConfiguration(user, config);
- }
-
- public void UpdateConfiguration(User user, UserConfiguration config)
- {
- UpdateConfiguration(user, config, true);
- }
-
- private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
- {
- var path = GetConfigurationFilePath(user);
-
- // The xml serializer will output differently if the type is not exact
- if (config.GetType() != typeof(UserConfiguration))
- {
- var json = _jsonSerializer.SerializeToString(config);
- config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- lock (_configSyncLock)
- {
- _xmlSerializer.SerializeToFile(config, path);
- user.Configuration = config;
- }
-
- if (fireEvent)
- {
- UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
- }
- }
- }
-
- public class DeviceAccessEntryPoint : IServerEntryPoint
- {
- private IUserManager _userManager;
- private IAuthenticationRepository _authRepo;
- private IDeviceManager _deviceManager;
- private ISessionManager _sessionManager;
-
- public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
- {
- _userManager = userManager;
- _authRepo = authRepo;
- _deviceManager = deviceManager;
- _sessionManager = sessionManager;
- }
-
- public Task RunAsync()
- {
- _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
-
- return Task.CompletedTask;
- }
-
- private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
- {
- var user = e.Argument;
- if (!user.Policy.EnableAllDevices)
- {
- UpdateDeviceAccess(user);
- }
- }
-
- private void UpdateDeviceAccess(User user)
- {
- var existing = _authRepo.Get(new AuthenticationInfoQuery
- {
- UserId = user.Id
-
- }).Items;
-
- foreach (var authInfo in existing)
- {
- if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
- {
- _sessionManager.Logout(authInfo);
- }
- }
- }
-
- public void Dispose()
- {
-
- }
- }
-}
diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs
index e9ce682ee..711647e7a 100644
--- a/Emby.Server.Implementations/Library/UserViewManager.cs
+++ b/Emby.Server.Implementations/Library/UserViewManager.cs
@@ -1,7 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
@@ -14,6 +20,8 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Person = MediaBrowser.Controller.Entities.Person;
namespace Emby.Server.Implementations.Library
{
@@ -41,6 +49,11 @@ namespace Emby.Server.Implementations.Library
{
var user = _userManager.GetUserById(query.UserId);
+ if (user == null)
+ {
+ throw new ArgumentException("User Id specified in the query does not exist.", nameof(query));
+ }
+
var folders = _libraryManager.GetUserRootFolder()
.GetChildren(user, true)
.OfType<Folder>()
@@ -53,7 +66,7 @@ namespace Emby.Server.Implementations.Library
foreach (var folder in folders)
{
var collectionFolder = folder as ICollectionFolder;
- var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType;
+ var folderViewType = collectionFolder?.CollectionType;
if (UserView.IsUserSpecific(folder))
{
@@ -117,28 +130,23 @@ namespace Emby.Server.Implementations.Library
if (!query.IncludeHidden)
{
- list = list.Where(i => !user.Configuration.MyMediaExcludes.Contains(i.Id.ToString("N"))).ToList();
+ list = list.Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.MyMediaExcludes).Contains(i.Id)).ToList();
}
var sorted = _libraryManager.Sort(list, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).ToList();
- var orders = user.Configuration.OrderedViews.ToList();
+ var orders = user.GetPreferenceValues<Guid>(PreferenceKind.OrderedViews);
return list
.OrderBy(i =>
{
- var index = orders.IndexOf(i.Id.ToString("N"));
+ var index = Array.IndexOf(orders, i.Id);
- if (index == -1)
+ if (index == -1
+ && i is UserView view
+ && view.DisplayParentId != Guid.Empty)
{
- var view = i as UserView;
- if (view != null)
- {
- if (!view.DisplayParentId.Equals(Guid.Empty))
- {
- index = orders.IndexOf(view.DisplayParentId.ToString("N"));
- }
- }
+ index = Array.IndexOf(orders, view.DisplayParentId);
}
return index == -1 ? int.MaxValue : index;
@@ -162,7 +170,13 @@ namespace Emby.Server.Implementations.Library
return GetUserSubViewWithName(name, parentId, type, sortName);
}
- private Folder GetUserView(List<ICollectionFolder> parents, string viewType, string localizationKey, string sortName, User user, string[] presetViews)
+ private Folder GetUserView(
+ List<ICollectionFolder> parents,
+ string viewType,
+ string localizationKey,
+ string sortName,
+ Jellyfin.Data.Entities.User user,
+ string[] presetViews)
{
if (parents.Count == 1 && parents.All(i => string.Equals(i.CollectionType, viewType, StringComparison.OrdinalIgnoreCase)))
{
@@ -223,7 +237,7 @@ namespace Emby.Server.Implementations.Library
return list;
}
- private List<BaseItem> GetItemsForLatestItems(User user, LatestItemsQuery request, DtoOptions options)
+ private IReadOnlyList<BaseItem> GetItemsForLatestItems(User user, LatestItemsQuery request, DtoOptions options)
{
var parentId = request.ParentId;
@@ -235,24 +249,22 @@ namespace Emby.Server.Implementations.Library
if (!parentId.Equals(Guid.Empty))
{
var parentItem = _libraryManager.GetItemById(parentId);
- var parentItemChannel = parentItem as Channel;
- if (parentItemChannel != null)
+ if (parentItem is Channel)
{
- return _channelManager.GetLatestChannelItemsInternal(new InternalItemsQuery(user)
- {
- ChannelIds = new[] { parentId },
- IsPlayed = request.IsPlayed,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- IncludeItemTypes = request.IncludeItemTypes,
- EnableTotalRecordCount = false
-
-
- }, CancellationToken.None).Result.Items.ToList();
+ return _channelManager.GetLatestChannelItemsInternal(
+ new InternalItemsQuery(user)
+ {
+ ChannelIds = new[] { parentId },
+ IsPlayed = request.IsPlayed,
+ StartIndex = request.StartIndex,
+ Limit = request.Limit,
+ IncludeItemTypes = request.IncludeItemTypes,
+ EnableTotalRecordCount = false
+ },
+ CancellationToken.None).GetAwaiter().GetResult().Items;
}
- var parent = parentItem as Folder;
- if (parent != null)
+ if (parentItem is Folder parent)
{
parents.Add(parent);
}
@@ -269,7 +281,8 @@ namespace Emby.Server.Implementations.Library
{
parents = _libraryManager.GetUserRootFolder().GetChildren(user, true)
.Where(i => i is Folder)
- .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N")))
+ .Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes)
+ .Contains(i.Id))
.ToList();
}
@@ -328,20 +341,26 @@ namespace Emby.Server.Implementations.Library
mediaTypes = mediaTypes.Distinct().ToList();
}
- var excludeItemTypes = includeItemTypes.Length == 0 && mediaTypes.Count == 0 ? new[]
- {
- typeof(Person).Name,
- typeof(Studio).Name,
- typeof(Year).Name,
- typeof(MusicGenre).Name,
- typeof(Genre).Name
-
- } : Array.Empty<string>();
+ var excludeItemTypes = includeItemTypes.Length == 0 && mediaTypes.Count == 0
+ ? new[]
+ {
+ nameof(Person),
+ nameof(Studio),
+ nameof(Year),
+ nameof(MusicGenre),
+ nameof(Genre)
+ }
+ : Array.Empty<string>();
var query = new InternalItemsQuery(user)
{
IncludeItemTypes = includeItemTypes,
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
+ OrderBy = new[]
+ {
+ (ItemSortBy.DateCreated, SortOrder.Descending),
+ (ItemSortBy.SortName, SortOrder.Descending),
+ (ItemSortBy.ProductionYear, SortOrder.Descending)
+ },
IsFolder = includeItemTypes.Length == 0 ? false : (bool?)null,
ExcludeItemTypes = excludeItemTypes,
IsVirtualItem = false,
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
index 27261d449..d51f9aaa7 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
@@ -8,22 +8,27 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
/// <summary>
- /// Class ArtistsPostScanTask
+ /// Class ArtistsPostScanTask.
/// </summary>
public class ArtistsPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ 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>
- public ArtistsPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <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;
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
index 294348660..40436d9c5 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -11,27 +12,28 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
/// <summary>
- /// Class ArtistsValidator
+ /// Class ArtistsValidator.
/// </summary>
public class ArtistsValidator
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
/// <summary>
- /// The _logger
+ /// The logger.
/// </summary>
- private readonly ILogger _logger;
+ private readonly ILogger<ArtistsValidator> _logger;
private readonly IItemRepository _itemRepo;
/// <summary>
- /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
+ /// Initializes a new instance of the <see cref="ArtistsValidator" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
/// <param name="logger">The logger.</param>
- public ArtistsValidator(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <param name="itemRepo">The item repository.</param>
+ public ArtistsValidator(ILibraryManager libraryManager, ILogger<ArtistsValidator> logger, IItemRepository itemRepo)
{
_libraryManager = libraryManager;
_logger = logger;
@@ -79,7 +81,7 @@ namespace Emby.Server.Implementations.Library.Validators
var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(MusicArtist).Name },
+ IncludeItemTypes = new[] { nameof(MusicArtist) },
IsDeadArtist = true,
IsLocked = false
}).Cast<MusicArtist>().ToList();
@@ -91,13 +93,15 @@ namespace Emby.Server.Implementations.Library.Validators
continue;
}
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _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);
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
progress.Report(100);
diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
index 056807300..d21d2887b 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
@@ -7,21 +7,28 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
+ /// <summary>
+ /// Class GenresPostScanTask.
+ /// </summary>
public class GenresPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<GenresValidator> _logger;
private readonly IItemRepository _itemRepo;
/// <summary>
- /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
+ /// Initializes a new instance of the <see cref="GenresPostScanTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
/// <param name="logger">The logger.</param>
- public GenresPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <param name="itemRepo">The item repository.</param>
+ public GenresPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<GenresValidator> logger,
+ IItemRepository itemRepo)
{
_libraryManager = libraryManager;
_logger = logger;
diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
index f8459c61f..e59c62e23 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
@@ -7,20 +7,29 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
- class GenresValidator
+ /// <summary>
+ /// Class GenresValidator.
+ /// </summary>
+ public class GenresValidator
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
private readonly IItemRepository _itemRepo;
/// <summary>
- /// The _logger
+ /// The logger.
/// </summary>
- private readonly ILogger _logger;
+ private readonly ILogger<GenresValidator> _logger;
- public GenresValidator(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <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;
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
index d7ab92d30..be119866b 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
@@ -8,23 +8,27 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
/// <summary>
- /// Class MusicGenresPostScanTask
+ /// Class MusicGenresPostScanTask.
/// </summary>
public class MusicGenresPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<MusicGenresValidator> _logger;
private readonly IItemRepository _itemRepo;
/// <summary>
- /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
+ /// Initializes a new instance of the <see cref="MusicGenresPostScanTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
/// <param name="logger">The logger.</param>
- public MusicGenresPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <param name="itemRepo">The item repository.</param>
+ public MusicGenresPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<MusicGenresValidator> logger,
+ IItemRepository itemRepo)
{
_libraryManager = libraryManager;
_logger = logger;
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
index 710e5d043..1ecf4c87c 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
@@ -7,20 +7,29 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
- class MusicGenresValidator
+ /// <summary>
+ /// Class MusicGenresValidator.
+ /// </summary>
+ public class MusicGenresValidator
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
/// <summary>
- /// The _logger
+ /// The logger.
/// </summary>
- private readonly ILogger _logger;
+ private readonly ILogger<MusicGenresValidator> _logger;
private readonly IItemRepository _itemRepo;
- public MusicGenresValidator(ILibraryManager libraryManager, ILogger logger, 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;
diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
index 7899cf01b..8739a9e1b 100644
--- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
@@ -1,7 +1,7 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
@@ -11,16 +11,17 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
/// <summary>
- /// Class PeopleValidator
+ /// Class PeopleValidator.
/// </summary>
public class PeopleValidator
{
/// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
+
/// <summary>
- /// The _logger
+ /// The _logger.
/// </summary>
private readonly ILogger _logger;
@@ -31,6 +32,7 @@ namespace Emby.Server.Implementations.Library.Validators
/// </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;
@@ -62,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Validators
{
var item = _libraryManager.GetPerson(person);
- var options = new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
+ var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem))
{
ImageRefreshMode = MetadataRefreshMode.ValidationOnly,
MetadataRefreshMode = MetadataRefreshMode.ValidationOnly
@@ -89,19 +91,26 @@ namespace Emby.Server.Implementations.Library.Validators
var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Person).Name },
+ IncludeItemTypes = new[] { nameof(Person) },
IsDeadPerson = true,
IsLocked = false
});
foreach (var item in deadEntities)
{
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
-
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = false
- }, false);
+ _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);
}
progress.Report(100);
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
index 4aa5c7e72..c682b156b 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
@@ -8,23 +8,28 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
/// <summary>
- /// Class MusicGenresPostScanTask
+ /// Class MusicGenresPostScanTask.
/// </summary>
public class StudiosPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<StudiosValidator> _logger;
private readonly IItemRepository _itemRepo;
/// <summary>
- /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
+ /// Initializes a new instance of the <see cref="StudiosPostScanTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
- public StudiosPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
+ /// <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;
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
index da4645a11..8577d722e 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -8,20 +9,30 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
- class StudiosValidator
+ /// <summary>
+ /// Class StudiosValidator.
+ /// </summary>
+ public class StudiosValidator
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
private readonly IItemRepository _itemRepo;
+
/// <summary>
- /// The _logger
+ /// The logger.
/// </summary>
- private readonly ILogger _logger;
+ private readonly ILogger<StudiosValidator> _logger;
- public StudiosValidator(ILibraryManager libraryManager, ILogger logger, IItemRepository 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;
@@ -69,20 +80,22 @@ namespace Emby.Server.Implementations.Library.Validators
var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Studio).Name },
+ IncludeItemTypes = new[] { nameof(Studio) },
IsDeadStudio = true,
IsLocked = false
});
foreach (var item in deadEntities)
{
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
-
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = false
+ _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
- }, false);
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
progress.Report(100);
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
index dd636e6cd..6937cc097 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
@@ -1,7 +1,11 @@
+#pragma warning disable CS1591
+
using System;
using System.IO;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Api.Helpers;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
@@ -13,15 +17,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class DirectRecorder : IRecorder
{
private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IStreamHelper _streamHelper;
- public DirectRecorder(ILogger logger, IHttpClient httpClient, IFileSystem fileSystem, IStreamHelper streamHelper)
+ public DirectRecorder(ILogger logger, IHttpClientFactory httpClientFactory, IStreamHelper streamHelper)
{
_logger = logger;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
+ _httpClientFactory = httpClientFactory;
_streamHelper = streamHelper;
}
@@ -30,7 +32,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return targetFile;
}
- public Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
+ public Task Record(IDirectStreamProvider? directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
if (directStreamProvider != null)
{
@@ -42,57 +44,56 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private async Task RecordFromDirectStreamProvider(IDirectStreamProvider directStreamProvider, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
- Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
+ Directory.CreateDirectory(Path.GetDirectoryName(targetFile) ?? throw new ArgumentException("Path can't be a root directory.", nameof(targetFile)));
- using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ using (var output = new FileStream(targetFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous))
{
onStarted();
- _logger.LogInformation("Copying recording stream to file {0}", targetFile);
+ _logger.LogInformation("Copying recording to file {FilePath}", targetFile);
// The media source is infinite so we need to handle stopping ourselves
- var durationToken = new CancellationTokenSource(duration);
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
-
- await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false);
+ using var durationToken = new CancellationTokenSource(duration);
+ using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
+ var linkedCancellationToken = cancellationTokenSource.Token;
+
+ await using var fileStream = new ProgressiveFileStream(directStreamProvider.GetStream());
+ await _streamHelper.CopyToAsync(
+ fileStream,
+ output,
+ IODefaults.CopyToBufferSize,
+ 1000,
+ linkedCancellationToken).ConfigureAwait(false);
}
- _logger.LogInformation("Recording completed to file {0}", targetFile);
+ _logger.LogInformation("Recording completed: {FilePath}", targetFile);
}
private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
- var httpRequestOptions = new HttpRequestOptions
- {
- Url = mediaSource.Path,
- BufferContent = false,
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(mediaSource.Path, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
- // Some remote urls will expect a user agent to be supplied
- UserAgent = "Emby/3.0",
+ _logger.LogInformation("Opened recording stream from tuner provider");
- // Shouldn't matter but may cause issues
- EnableHttpCompression = false
- };
+ Directory.CreateDirectory(Path.GetDirectoryName(targetFile) ?? throw new ArgumentException("Path can't be a root directory.", nameof(targetFile)));
- using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
- {
- _logger.LogInformation("Opened recording stream from tuner provider");
-
- Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
+ await using var output = new FileStream(targetFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read, IODefaults.CopyToBufferSize, FileOptions.Asynchronous);
- using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
- {
- onStarted();
+ onStarted();
- _logger.LogInformation("Copying recording stream to file {0}", targetFile);
+ _logger.LogInformation("Copying recording stream to file {0}", targetFile);
- // The media source if infinite so we need to handle stopping ourselves
- var durationToken = new CancellationTokenSource(duration);
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
+ // The media source if infinite so we need to handle stopping ourselves
+ using var durationToken = new CancellationTokenSource(duration);
+ using var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
+ cancellationToken = linkedCancellationToken.Token;
- await _streamHelper.CopyUntilCancelled(response.Content, output, 81920, cancellationToken).ConfigureAwait(false);
- }
- }
+ await _streamHelper.CopyUntilCancelled(
+ await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false),
+ output,
+ IODefaults.CopyToBufferSize,
+ cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Recording completed to file {0}", targetFile);
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
index fceb82ba1..980b42729 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
@@ -1,17 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Emby.Server.Implementations.Library;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
@@ -23,29 +30,27 @@ using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Reflection;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
public class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable
{
+ public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
+
+ private const int TunerDiscoveryDurationMs = 3000;
+
private readonly IServerApplicationHost _appHost;
- private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
+ private readonly ILogger<EmbyTV> _logger;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerConfigurationManager _config;
- private readonly IJsonSerializer _jsonSerializer;
private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
private readonly TimerManager _timerProvider;
@@ -57,89 +62,104 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private readonly ILibraryManager _libraryManager;
private readonly IProviderManager _providerManager;
private readonly IMediaEncoder _mediaEncoder;
- private readonly IProcessFactory _processFactory;
- private readonly IAssemblyInfo _assemblyInfo;
- private IMediaSourceManager _mediaSourceManager;
-
- public static EmbyTV Current;
-
- public event EventHandler<GenericEventArgs<TimerInfo>> TimerCreated;
- public event EventHandler<GenericEventArgs<string>> TimerCancelled;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IStreamHelper _streamHelper;
private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
- private readonly IStreamHelper _streamHelper;
+ private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels =
+ new ConcurrentDictionary<string, EpgChannelData>(StringComparer.OrdinalIgnoreCase);
+
+ private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
+
+ private bool _disposed = false;
- public EmbyTV(IServerApplicationHost appHost,
+ public EmbyTV(
+ IServerApplicationHost appHost,
IStreamHelper streamHelper,
IMediaSourceManager mediaSourceManager,
- IAssemblyInfo assemblyInfo,
- ILogger logger,
- IJsonSerializer jsonSerializer,
- IHttpClient httpClient,
+ ILogger<EmbyTV> logger,
+ IHttpClientFactory httpClientFactory,
IServerConfigurationManager config,
ILiveTvManager liveTvManager,
IFileSystem fileSystem,
ILibraryManager libraryManager,
ILibraryMonitor libraryMonitor,
IProviderManager providerManager,
- IMediaEncoder mediaEncoder,
- IProcessFactory processFactory)
+ IMediaEncoder mediaEncoder)
{
Current = this;
_appHost = appHost;
_logger = logger;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_config = config;
_fileSystem = fileSystem;
_libraryManager = libraryManager;
_libraryMonitor = libraryMonitor;
_providerManager = providerManager;
_mediaEncoder = mediaEncoder;
- _processFactory = processFactory;
_liveTvManager = (LiveTvManager)liveTvManager;
- _jsonSerializer = jsonSerializer;
- _assemblyInfo = assemblyInfo;
_mediaSourceManager = mediaSourceManager;
_streamHelper = streamHelper;
- _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
- _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
- _timerProvider.TimerFired += _timerProvider_TimerFired;
+ _seriesTimerProvider = new SeriesTimerManager(_logger, Path.Combine(DataPath, "seriestimers.json"));
+ _timerProvider = new TimerManager(_logger, Path.Combine(DataPath, "timers.json"));
+ _timerProvider.TimerFired += OnTimerProviderTimerFired;
- _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
+ _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
}
- private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
+ public event EventHandler<GenericEventArgs<TimerInfo>> TimerCreated;
+
+ public event EventHandler<GenericEventArgs<string>> TimerCancelled;
+
+ public static EmbyTV Current { get; private set; }
+
+ /// <inheritdoc />
+ public string Name => "Emby";
+
+ public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv");
+
+ /// <inheritdoc />
+ public string HomePageUrl => "https://github.com/jellyfin/jellyfin";
+
+ private string DefaultRecordingPath => Path.Combine(DataPath, "recordings");
+
+ private string RecordingPath
{
- if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
+ get
{
- OnRecordingFoldersChanged();
+ var path = GetConfiguration().RecordingPath;
+
+ return string.IsNullOrWhiteSpace(path)
+ ? DefaultRecordingPath
+ : path;
}
}
- public async Task Start()
+ private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
- _timerProvider.RestartTimers();
-
- await CreateRecordingFolders().ConfigureAwait(false);
+ if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
+ {
+ await CreateRecordingFolders().ConfigureAwait(false);
+ }
}
- private async void OnRecordingFoldersChanged()
+ public Task Start()
{
- await CreateRecordingFolders().ConfigureAwait(false);
+ _timerProvider.RestartTimers();
+
+ return CreateRecordingFolders();
}
internal async Task CreateRecordingFolders()
{
try
{
- var recordingFolders = GetRecordingFolders();
-
- var virtualFolders = _libraryManager.GetVirtualFolders()
- .ToList();
+ var recordingFolders = GetRecordingFolders().ToArray();
+ var virtualFolders = _libraryManager.GetVirtualFolders();
var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
@@ -156,7 +176,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
continue;
}
- var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo { Path = i }).ToArray();
+ var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo(i)).ToArray();
var libraryOptions = new LibraryOptions
{
@@ -189,7 +209,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
foreach (var path in pathsToRemove)
{
- await RemovePathFromLibrary(path).ConfigureAwait(false);
+ await RemovePathFromLibraryAsync(path).ConfigureAwait(false);
}
}
catch (Exception ex)
@@ -198,13 +218,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- private async Task RemovePathFromLibrary(string path)
+ private async Task RemovePathFromLibraryAsync(string path)
{
_logger.LogDebug("Removing path from library: {0}", path);
var requiresRefresh = false;
- var virtualFolders = _libraryManager.GetVirtualFolders()
- .ToList();
+ var virtualFolders = _libraryManager.GetVirtualFolders();
foreach (var virtualFolder in virtualFolders)
{
@@ -241,31 +260,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (requiresRefresh)
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
- }
- }
-
- public string Name => "Emby";
-
- public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv");
-
- private string DefaultRecordingPath => Path.Combine(DataPath, "recordings");
-
- private string RecordingPath
- {
- get
- {
- var path = GetConfiguration().RecordingPath;
-
- return string.IsNullOrWhiteSpace(path)
- ? DefaultRecordingPath
- : path;
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
}
}
- public string HomePageUrl => "https://github.com/jellyfin/jellyfin";
-
- public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
+ public async Task RefreshSeriesTimers(CancellationToken cancellationToken)
{
var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
@@ -275,7 +274,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- public async Task RefreshTimers(CancellationToken cancellationToken, IProgress<double> progress)
+ public async Task RefreshTimers(CancellationToken cancellationToken)
{
var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
@@ -343,7 +342,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (NotSupportedException)
{
-
}
catch (Exception ex)
{
@@ -355,7 +353,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return list;
}
- private async Task AddMetadata(IListingsProvider provider, ListingsProviderInfo info, List<ChannelInfo> tunerChannels, bool enableCache, CancellationToken cancellationToken)
+ private async Task AddMetadata(
+ IListingsProvider provider,
+ ListingsProviderInfo info,
+ IEnumerable<ChannelInfo> tunerChannels,
+ bool enableCache,
+ CancellationToken cancellationToken)
{
var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
@@ -367,8 +370,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (!string.IsNullOrWhiteSpace(epgChannel.Name))
{
- //tunerChannel.Name = epgChannel.Name;
+ // tunerChannel.Name = epgChannel.Name;
}
+
if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
{
tunerChannel.ImageUrl = epgChannel.ImageUrl;
@@ -377,10 +381,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels =
- new ConcurrentDictionary<string, EpgChannelData>(StringComparer.OrdinalIgnoreCase);
-
- private async Task<EpgChannelData> GetEpgChannels(IListingsProvider provider, ListingsProviderInfo info, bool enableCache, CancellationToken cancellationToken)
+ private async Task<EpgChannelData> GetEpgChannels(
+ IListingsProvider provider,
+ ListingsProviderInfo info,
+ bool enableCache,
+ CancellationToken cancellationToken)
{
if (!enableCache || !_epgChannels.TryGetValue(info.Id, out var result))
{
@@ -398,59 +403,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return result;
}
- private class EpgChannelData
- {
- public EpgChannelData(List<ChannelInfo> channels)
- {
- ChannelsById = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
- ChannelsByNumber = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
- ChannelsByName = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
-
- foreach (var channel in channels)
- {
- ChannelsById[channel.Id] = channel;
-
- if (!string.IsNullOrEmpty(channel.Number))
- {
- ChannelsByNumber[channel.Number] = channel;
- }
-
- var normalizedName = NormalizeName(channel.Name ?? string.Empty);
- if (!string.IsNullOrWhiteSpace(normalizedName))
- {
- ChannelsByName[normalizedName] = channel;
- }
- }
- }
-
- private Dictionary<string, ChannelInfo> ChannelsById { get; set; }
- private Dictionary<string, ChannelInfo> ChannelsByNumber { get; set; }
- private Dictionary<string, ChannelInfo> ChannelsByName { get; set; }
-
- public ChannelInfo GetChannelById(string id)
- {
- ChannelInfo result = null;
-
- ChannelsById.TryGetValue(id, out result);
-
- return result;
- }
-
- public ChannelInfo GetChannelByNumber(string number)
- {
- ChannelsByNumber.TryGetValue(number, out var result);
-
- return result;
- }
-
- public ChannelInfo GetChannelByName(string name)
- {
- ChannelsByName.TryGetValue(name, out var result);
-
- return result;
- }
- }
-
private async Task<ChannelInfo> GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken)
{
var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false);
@@ -462,11 +414,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
foreach (NameValuePair mapping in mappings)
{
- if (StringHelper.EqualsIgnoreCase(mapping.Name, channelId))
+ if (string.Equals(mapping.Name, channelId, StringComparison.OrdinalIgnoreCase))
{
return mapping.Value;
}
}
+
return channelId;
}
@@ -480,7 +433,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return GetEpgChannelFromTunerChannel(info.ChannelMappings, tunerChannel, epgChannels);
}
- private ChannelInfo GetEpgChannelFromTunerChannel(NameValuePair[] mappings, ChannelInfo tunerChannel, EpgChannelData epgChannelData)
+ private ChannelInfo GetEpgChannelFromTunerChannel(
+ NameValuePair[] mappings,
+ ChannelInfo tunerChannel,
+ EpgChannelData epgChannelData)
{
if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
{
@@ -502,7 +458,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
{
var tunerChannelId = tunerChannel.TunerChannelId;
- if (tunerChannelId.IndexOf(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase) != -1)
+ if (tunerChannelId.Contains(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase))
{
tunerChannelId = tunerChannelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
}
@@ -541,7 +497,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
{
- var normalizedName = NormalizeName(tunerChannel.Name);
+ var normalizedName = EpgChannelData.NormalizeName(tunerChannel.Name);
var channel = epgChannelData.GetChannelByName(normalizedName);
@@ -554,11 +510,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return null;
}
- private static string NormalizeName(string value)
- {
- return value.Replace(" ", string.Empty).Replace("-", string.Empty);
- }
-
public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
{
var list = new List<ChannelInfo>();
@@ -604,6 +555,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
_seriesTimerProvider.Delete(remove);
}
+
return Task.CompletedTask;
}
@@ -648,11 +600,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return Task.CompletedTask;
}
- public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
- {
- return Task.CompletedTask;
- }
-
public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
{
throw new NotImplementedException();
@@ -663,16 +610,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new NotImplementedException();
}
- public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
+ public Task<string> CreateTimer(TimerInfo info, CancellationToken cancellationToken)
{
- var existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId) ?
+ var existingTimer = string.IsNullOrWhiteSpace(info.ProgramId) ?
null :
- _timerProvider.GetTimerByProgramId(timer.ProgramId);
+ _timerProvider.GetTimerByProgramId(info.ProgramId);
if (existingTimer != null)
{
- if (existingTimer.Status == RecordingStatus.Cancelled ||
- existingTimer.Status == RecordingStatus.Completed)
+ if (existingTimer.Status == RecordingStatus.Cancelled
+ || existingTimer.Status == RecordingStatus.Completed)
{
existingTimer.Status = RecordingStatus.New;
existingTimer.IsManual = true;
@@ -685,39 +632,37 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- timer.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
LiveTvProgram programInfo = null;
- if (!string.IsNullOrWhiteSpace(timer.ProgramId))
+ if (!string.IsNullOrWhiteSpace(info.ProgramId))
{
- programInfo = GetProgramInfoFromCache(timer);
+ programInfo = GetProgramInfoFromCache(info);
}
+
if (programInfo == null)
{
- _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
- programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
+ _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", info.ProgramId);
+ programInfo = GetProgramInfoFromCache(info.ChannelId, info.StartDate);
}
if (programInfo != null)
{
- CopyProgramInfoToTimerInfo(programInfo, timer);
+ CopyProgramInfoToTimerInfo(programInfo, info);
}
- timer.IsManual = true;
- _timerProvider.Add(timer);
+ info.IsManual = true;
+ _timerProvider.Add(info);
- if (TimerCreated != null)
- {
- TimerCreated(this, new GenericEventArgs<TimerInfo>(timer));
- }
+ TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(info));
- return Task.FromResult(timer.Id);
+ return Task.FromResult(info.Id);
}
public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
// populate info.seriesID
var program = GetProgramInfoFromCache(info.ProgramId);
@@ -804,7 +749,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
// Only update if not currently active
- if (!_activeRecordings.TryGetValue(updatedTimer.Id, out var activeRecordingInfo))
+ if (!_activeRecordings.TryGetValue(updatedTimer.Id, out _))
{
existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds;
existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds;
@@ -850,33 +795,31 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
return info.Path;
}
- return null;
- }
- public IEnumerable<ActiveRecordingInfo> GetAllActiveRecordings()
- {
- return _activeRecordings.Values.Where(i => i.Timer.Status == RecordingStatus.InProgress && !i.CancellationTokenSource.IsCancellationRequested);
+ return null;
}
public ActiveRecordingInfo GetActiveRecordingInfo(string path)
{
- if (string.IsNullOrWhiteSpace(path))
+ if (string.IsNullOrWhiteSpace(path) || _activeRecordings.IsEmpty)
{
return null;
}
- foreach (var recording in _activeRecordings.Values)
+ foreach (var (_, recordingInfo) in _activeRecordings)
{
- if (string.Equals(recording.Path, path, StringComparison.Ordinal) && !recording.CancellationTokenSource.IsCancellationRequested)
+ if (string.Equals(recordingInfo.Path, path, StringComparison.Ordinal) && !recordingInfo.CancellationTokenSource.IsCancellationRequested)
{
- var timer = recording.Timer;
+ var timer = recordingInfo.Timer;
if (timer.Status != RecordingStatus.InProgress)
{
return null;
}
- return recording;
+
+ return recordingInfo;
}
}
+
return null;
}
@@ -968,18 +911,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
- List<ProgramInfo> programs;
-
if (epgChannel == null)
{
_logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
- programs = new List<ProgramInfo>();
+ continue;
}
- else
- {
- programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
+
+ List<ProgramInfo> programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
.ConfigureAwait(false)).ToList();
- }
// Replace the value that came from the provider with a normalized value
foreach (var program in programs)
@@ -995,7 +934,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- return new List<ProgramInfo>();
+ return Enumerable.Empty<ProgramInfo>();
}
private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
@@ -1058,23 +997,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new Exception("Tuner not found.");
}
- private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, bool enableStreamSharing)
- {
- var json = _jsonSerializer.SerializeToString(mediaSource);
- mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
-
- mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
-
- //if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
- //{
- // var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks;
- // ticks = Math.Max(0, ticks);
- // mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture);
- //}
-
- return mediaSource;
- }
-
public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(channelId))
@@ -1095,7 +1017,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (NotImplementedException)
{
-
}
}
@@ -1106,7 +1027,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var stream = new MediaSourceInfo
{
- EncoderPath = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
+ EncoderPath = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
EncoderProtocol = MediaProtocol.Http,
Path = info.Path,
Protocol = MediaProtocol.File,
@@ -1122,7 +1043,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
IgnoreIndex = true
};
- await new LiveStreamHelper(_mediaEncoder, _logger, _jsonSerializer, _config.CommonApplicationPaths)
+ await new LiveStreamHelper(_mediaEncoder, _logger, _config.CommonApplicationPaths)
.AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false);
return new List<MediaSourceInfo>
@@ -1146,7 +1067,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return Task.CompletedTask;
}
- async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
+ private async void OnTimerProviderTimerFired(object sender, GenericEventArgs<TimerInfo> e)
{
var timer = e.Argument;
@@ -1181,7 +1102,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (OperationCanceledException)
{
-
}
catch (Exception ex)
{
@@ -1225,7 +1145,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (timer.SeasonNumber.HasValue)
{
- folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
+ folderName = string.Format(
+ CultureInfo.InvariantCulture,
+ "Season {0}",
+ timer.SeasonNumber.Value);
recordPath = Path.Combine(recordPath, folderName);
}
}
@@ -1279,6 +1202,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
recordPath = Path.Combine(recordPath, "Sports");
}
+
recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
}
else
@@ -1287,6 +1211,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
recordPath = Path.Combine(recordPath, "Other");
}
+
recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
}
@@ -1308,6 +1233,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
programInfo = GetProgramInfoFromCache(timer);
}
+
if (programInfo == null)
{
_logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
@@ -1319,9 +1245,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
CopyProgramInfoToTimerInfo(programInfo, timer);
}
- string seriesPath = null;
var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false);
- var recordPath = GetRecordingPath(timer, remoteMetadata, out seriesPath);
+ var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath);
var recordingStatus = RecordingStatus.New;
string liveStreamId = null;
@@ -1330,19 +1255,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
try
{
- var allMediaSources = await _mediaSourceManager.GetPlayackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false);
+ var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false);
var mediaStreamInfo = allMediaSources[0];
IDirectStreamProvider directStreamProvider = null;
if (mediaStreamInfo.RequiresOpening)
{
- var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal(new LiveStreamRequest
- {
- ItemId = channelItem.Id,
- OpenToken = mediaStreamInfo.OpenToken
-
- }, CancellationToken.None).ConfigureAwait(false);
+ var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal(
+ new LiveStreamRequest
+ {
+ ItemId = channelItem.Id,
+ OpenToken = mediaStreamInfo.OpenToken
+ },
+ CancellationToken.None).ConfigureAwait(false);
mediaStreamInfo = liveStreamResponse.Item1.MediaSource;
liveStreamId = mediaStreamInfo.LiveStreamId;
@@ -1360,7 +1286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
- _logger.LogInformation("Writing file to path: " + recordPath);
+ _logger.LogInformation("Writing file to: {Path}", recordPath);
Action onStarted = async () =>
{
@@ -1376,7 +1302,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
await CreateRecordingFolders().ConfigureAwait(false);
TriggerRefresh(recordPath);
- EnforceKeepUpTo(timer, seriesPath);
+ await EnforceKeepUpTo(timer, seriesPath).ConfigureAwait(false);
};
await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
@@ -1416,12 +1342,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
{
- const int retryIntervalSeconds = 60;
- _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds);
+ const int RetryIntervalSeconds = 60;
+ _logger.LogInformation("Retrying recording in {0} seconds.", RetryIntervalSeconds);
timer.Status = RecordingStatus.New;
timer.PrePaddingSeconds = 0;
- timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
+ timer.StartDate = DateTime.UtcNow.AddSeconds(RetryIntervalSeconds);
timer.RetryCount++;
_timerProvider.AddOrUpdate(timer);
}
@@ -1485,24 +1411,26 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private void TriggerRefresh(string path)
{
- _logger.LogInformation("Triggering refresh on {path}", path);
+ _logger.LogInformation("Triggering refresh on {Path}", path);
var item = GetAffectedBaseItem(Path.GetDirectoryName(path));
if (item != null)
{
- _logger.LogInformation("Refreshing recording parent {path}", item.Path);
+ _logger.LogInformation("Refreshing recording parent {Path}", item.Path);
- _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- RefreshPaths = new string[]
+ _providerManager.QueueRefresh(
+ item.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
{
- path,
- Path.GetDirectoryName(path),
- Path.GetDirectoryName(Path.GetDirectoryName(path))
- }
-
- }, RefreshPriority.High);
+ RefreshPaths = new string[]
+ {
+ path,
+ Path.GetDirectoryName(path),
+ Path.GetDirectoryName(Path.GetDirectoryName(path))
+ }
+ },
+ RefreshPriority.High);
}
}
@@ -1524,7 +1452,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (item.GetType() == typeof(Folder) && string.Equals(item.Path, parentPath, StringComparison.OrdinalIgnoreCase))
{
var parentItem = item.GetParent();
- if (parentItem != null && !(parentItem is AggregateFolder))
+ if (parentItem != null && parentItem is not AggregateFolder)
{
item = parentItem;
}
@@ -1534,12 +1462,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return item;
}
- private async void EnforceKeepUpTo(TimerInfo timer, string seriesPath)
+ private async Task EnforceKeepUpTo(TimerInfo timer, string seriesPath)
{
if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
{
return;
}
+
if (string.IsNullOrWhiteSpace(seriesPath))
{
return;
@@ -1577,22 +1506,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
DeleteLibraryItemsForTimers(timersToDelete);
- var librarySeries = _libraryManager.FindByPath(seriesPath, true) as Folder;
-
- if (librarySeries == null)
+ if (_libraryManager.FindByPath(seriesPath, true) is not Folder librarySeries)
{
return;
}
- var episodesToDelete = (librarySeries.GetItemList(new InternalItemsQuery
- {
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
- IsVirtualItem = false,
- IsFolder = false,
- Recursive = true,
- DtoOptions = new DtoOptions(true)
-
- }))
+ var episodesToDelete = librarySeries.GetItemList(
+ new InternalItemsQuery
+ {
+ OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
+ IsVirtualItem = false,
+ IsFolder = false,
+ Recursive = true,
+ DtoOptions = new DtoOptions(true)
+ })
.Where(i => i.IsFileProtocol && File.Exists(i.Path))
.Skip(seriesTimer.KeepUpTo - 1)
.ToList();
@@ -1601,11 +1528,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
try
{
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = true
-
- }, true);
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = true
+ },
+ true);
}
catch (Exception ex)
{
@@ -1619,7 +1548,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
private void DeleteLibraryItemsForTimers(List<TimerInfo> timers)
{
foreach (var timer in timers)
@@ -1646,22 +1574,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (libraryItem != null)
{
- _libraryManager.DeleteItem(libraryItem, new DeleteOptions
- {
- DeleteFileLocation = true
-
- }, true);
+ _libraryManager.DeleteItem(
+ libraryItem,
+ new DeleteOptions
+ {
+ DeleteFileLocation = true
+ },
+ true);
}
- else
+ else if (File.Exists(timer.RecordingPath))
{
- try
- {
- _fileSystem.DeleteFile(timer.RecordingPath);
- }
- catch (IOException)
- {
-
- }
+ _fileSystem.DeleteFile(timer.RecordingPath);
}
_timerProvider.Delete(timer);
@@ -1692,26 +1615,18 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return true;
}
- var hasRecordingAtPath = _activeRecordings
- .Values
- .ToList()
- .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
-
- if (hasRecordingAtPath)
- {
- return true;
- }
- return false;
+ return _activeRecordings
+ .Any(i => string.Equals(i.Value.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Value.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
}
private IRecorder GetRecorder(MediaSourceInfo mediaSource)
{
if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http))
{
- return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _processFactory, _config);
+ return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _config);
}
- return new DirectRecorder(_logger, _httpClient, _fileSystem, _streamHelper);
+ return new DirectRecorder(_logger, _httpClientFactory, _streamHelper);
}
private void OnSuccessfulRecording(TimerInfo timer, string path)
@@ -1729,20 +1644,23 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
try
{
- var process = _processFactory.Create(new ProcessOptions
+ var process = new Process
{
- Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
- CreateNoWindow = true,
- EnableRaisingEvents = true,
- ErrorDialog = false,
- FileName = options.RecordingPostProcessor,
- IsHidden = true,
- UseShellExecute = false
- });
+ StartInfo = new ProcessStartInfo
+ {
+ Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
+ CreateNoWindow = true,
+ ErrorDialog = false,
+ FileName = options.RecordingPostProcessor,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ UseShellExecute = false
+ },
+ EnableRaisingEvents = true
+ };
_logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
- process.Exited += Process_Exited;
+ process.Exited += OnProcessExited;
process.Start();
}
catch (Exception ex)
@@ -1756,19 +1674,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
}
- private void Process_Exited(object sender, EventArgs e)
+ private void OnProcessExited(object sender, EventArgs e)
{
- var process = (IProcess)sender;
- try
+ using (var process = (Process)sender)
{
_logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode);
}
- catch
- {
-
- }
-
- process.Dispose();
}
private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
@@ -1778,44 +1689,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
}
- string imageSaveFilenameWithoutExtension = null;
-
- switch (image.Type)
+ string imageSaveFilenameWithoutExtension = image.Type switch
{
- case ImageType.Primary:
-
- if (program.IsSeries)
- {
- imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
- }
- else
- {
- imageSaveFilenameWithoutExtension = "poster";
- }
-
- break;
- case ImageType.Logo:
- imageSaveFilenameWithoutExtension = "logo";
- break;
- case ImageType.Thumb:
- if (program.IsSeries)
- {
- imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
- }
- else
- {
- imageSaveFilenameWithoutExtension = "landscape";
- }
-
- break;
- case ImageType.Backdrop:
- imageSaveFilenameWithoutExtension = "fanart";
- break;
- default:
- break;
- }
+ ImageType.Primary => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "poster",
+ ImageType.Logo => "logo",
+ ImageType.Thumb => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "landscape",
+ ImageType.Backdrop => "fanart",
+ _ => null
+ };
- if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
+ if (imageSaveFilenameWithoutExtension == null)
{
return;
}
@@ -1895,11 +1778,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new[] { nameof(LiveTvProgram) },
Limit = 1,
ExternalId = timer.ProgramId,
DtoOptions = new DtoOptions(true)
-
}).FirstOrDefault() as LiveTvProgram;
// dummy this up
@@ -1923,11 +1805,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
program.AddGenre("Sports");
}
+
if (timer.IsKids)
{
program.AddGenre("Kids");
program.AddGenre("Children");
}
+
if (timer.IsNews)
{
program.AddGenre("News");
@@ -1964,13 +1848,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return;
}
- using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ using (var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
var settings = new XmlWriterSettings
{
Indent = true,
- Encoding = Encoding.UTF8,
- CloseOutput = false
+ Encoding = Encoding.UTF8
};
using (var writer = XmlWriter.Create(stream, settings))
@@ -1978,19 +1861,22 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
writer.WriteStartDocument(true);
writer.WriteStartElement("tvshow");
string id;
- if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out id))
+ if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out id))
{
writer.WriteElementString("id", id);
}
- if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out id))
+
+ if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out id))
{
writer.WriteElementString("imdb_id", id);
}
- if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Tmdb.ToString(), out id))
+
+ if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out id))
{
writer.WriteElementString("tmdbid", id);
}
- if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out id))
+
+ if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out id))
{
writer.WriteElementString("zap2itid", id);
}
@@ -2016,7 +1902,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
{
var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
@@ -2026,13 +1911,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return;
}
- using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ using (var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
var settings = new XmlWriterSettings
{
Indent = true,
- Encoding = Encoding.UTF8,
- CloseOutput = false
+ Encoding = Encoding.UTF8
};
var options = _config.GetNfoConfiguration();
@@ -2058,7 +1942,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var formatString = options.ReleaseDateFormat;
- writer.WriteElementString("aired", premiereDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString(
+ "aired",
+ premiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
if (item.IndexNumber.HasValue)
@@ -2089,12 +1975,18 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var formatString = options.ReleaseDateFormat;
- writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
- writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString(
+ "premiered",
+ item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
+ writer.WriteElementString(
+ "releasedate",
+ item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
}
- writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
+ writer.WriteElementString(
+ "dateadded",
+ DateTime.Now.ToString(DateAddedFormat, CultureInfo.InvariantCulture));
if (item.ProductionYear.HasValue)
{
@@ -2108,7 +2000,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var overview = (item.Overview ?? string.Empty)
.StripHtml()
- .Replace("&quot;", "'");
+ .Replace("&quot;", "'", StringComparison.Ordinal);
writer.WriteElementString("plot", overview);
@@ -2150,14 +2042,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
writer.WriteElementString("credits", person);
}
- var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
+ var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
if (!string.IsNullOrEmpty(tmdbCollection))
{
writer.WriteElementString("collectionnumber", tmdbCollection);
}
- var imdb = item.GetProviderId(MetadataProviders.Imdb);
+ var imdb = item.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdb))
{
if (!isSeriesEpisode)
@@ -2171,7 +2063,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
lockData = false;
}
- var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
+ var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
if (!string.IsNullOrEmpty(tvdb))
{
writer.WriteElementString("tvdbid", tvdb);
@@ -2180,7 +2072,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
lockData = false;
}
- var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
+ var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(tmdb))
{
writer.WriteElementString("tmdbid", tmdb);
@@ -2216,17 +2108,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
private static bool IsPersonType(PersonInfo person, string type)
- {
- return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
- }
-
- private void AddGenre(List<string> genres, string genre)
- {
- if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
- {
- genres.Add(genre);
- }
- }
+ => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
private LiveTvProgram GetProgramInfoFromCache(string programId)
{
@@ -2254,7 +2137,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var query = new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
Limit = 1,
DtoOptions = new DtoOptions(true)
{
@@ -2262,7 +2145,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
},
MinStartDate = startDateUtc.AddMinutes(-3),
MaxStartDate = startDateUtc.AddMinutes(3),
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) }
+ OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) }
};
if (!string.IsNullOrWhiteSpace(channelId))
@@ -2285,25 +2168,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return false;
}
- if (!seriesTimer.RecordAnyTime)
+ if (!seriesTimer.RecordAnyTime
+ && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
{
- if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
- {
- return true;
- }
+ return true;
}
- //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
- //{
- // return true;
- //}
-
if (seriesTimer.RecordNewOnly && timer.IsRepeat)
{
return true;
}
- if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
+ if (!seriesTimer.RecordAnyChannel
+ && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
{
return true;
}
@@ -2348,18 +2225,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var allTimers = GetTimersForSeries(seriesTimer).ToList();
-
var enabledTimersForSeries = new List<TimerInfo>();
foreach (var timer in allTimers)
{
- var existingTimer = _timerProvider.GetTimer(timer.Id);
-
- if (existingTimer == null)
- {
- existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId)
+ var existingTimer = _timerProvider.GetTimer(timer.Id)
+ ?? (string.IsNullOrWhiteSpace(timer.ProgramId)
? null
- : _timerProvider.GetTimerByProgramId(timer.ProgramId);
- }
+ : _timerProvider.GetTimerByProgramId(timer.ProgramId));
if (existingTimer == null)
{
@@ -2371,10 +2243,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
enabledTimersForSeries.Add(timer);
}
+
_timerProvider.Add(timer);
TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
}
+
// Only update if not currently active - test both new timer and existing in case Id's are different
// Id's could be different if the timer was created manually prior to series timer creation
else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
@@ -2478,7 +2352,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var query = new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
ExternalSeriesId = seriesTimer.SeriesId,
DtoOptions = new DtoOptions(true)
{
@@ -2510,13 +2384,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel))
{
- channel = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name },
- ItemIds = new[] { parent.ChannelId },
- DtoOptions = new DtoOptions()
-
- }).Cast<LiveTvChannel>().FirstOrDefault();
+ channel = _libraryManager.GetItemList(
+ new InternalItemsQuery
+ {
+ IncludeItemTypes = new string[] { nameof(LiveTvChannel) },
+ ItemIds = new[] { parent.ChannelId },
+ DtoOptions = new DtoOptions()
+ }).FirstOrDefault() as LiveTvChannel;
if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
{
@@ -2533,7 +2407,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var timer = new TimerInfo
{
ChannelId = channelId,
- Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N"),
+ Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
StartDate = parent.StartDate,
EndDate = parent.EndDate.Value,
ProgramId = parent.ExternalId,
@@ -2569,13 +2443,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel))
{
- channel = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name },
- ItemIds = new[] { programInfo.ChannelId },
- DtoOptions = new DtoOptions()
-
- }).Cast<LiveTvChannel>().FirstOrDefault();
+ channel = _libraryManager.GetItemList(
+ new InternalItemsQuery
+ {
+ IncludeItemTypes = new string[] { nameof(LiveTvChannel) },
+ ItemIds = new[] { programInfo.ChannelId },
+ DtoOptions = new DtoOptions()
+ }).FirstOrDefault() as LiveTvChannel;
if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
{
@@ -2620,10 +2494,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
foreach (var providerId in timerInfo.ProviderIds)
{
- var srch = "Series";
- if (providerId.Key.StartsWith(srch, StringComparison.OrdinalIgnoreCase))
+ const string Search = "Series";
+ if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase))
{
- seriesProviderIds[providerId.Key.Substring(srch.Length)] = providerId.Value;
+ seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value;
}
}
@@ -2634,12 +2508,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
{
- var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(Series).Name },
- Name = program.Name
-
- }).ToArray();
+ var seriesIds = _libraryManager.GetItemIds(
+ new InternalItemsQuery
+ {
+ IncludeItemTypes = new[] { nameof(Series) },
+ Name = program.Name
+ }).ToArray();
if (seriesIds.Length == 0)
{
@@ -2650,7 +2524,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var result = _libraryManager.GetItemIds(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Episode).Name },
+ IncludeItemTypes = new[] { nameof(Episode) },
ParentIndexNumber = program.SeasonNumber.Value,
IndexNumber = program.EpisodeNumber.Value,
AncestorIds = seriesIds,
@@ -2668,59 +2542,70 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return false;
}
- private bool _disposed;
+ /// <inheritdoc />
public void Dispose()
{
- _disposed = true;
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
+ {
+ _recordingDeleteSemaphore.Dispose();
+ }
+
foreach (var pair in _activeRecordings.ToList())
{
pair.Value.CancellationTokenSource.Cancel();
}
+
+ _disposed = true;
}
- public List<VirtualFolderInfo> GetRecordingFolders()
+ public IEnumerable<VirtualFolderInfo> GetRecordingFolders()
{
- var list = new List<VirtualFolderInfo>();
-
var defaultFolder = RecordingPath;
var defaultName = "Recordings";
if (Directory.Exists(defaultFolder))
{
- list.Add(new VirtualFolderInfo
+ yield return new VirtualFolderInfo
{
Locations = new string[] { defaultFolder },
Name = defaultName
- });
+ };
}
var customPath = GetConfiguration().MovieRecordingPath;
- if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
+ if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
{
- list.Add(new VirtualFolderInfo
+ yield return new VirtualFolderInfo
{
Locations = new string[] { customPath },
Name = "Recorded Movies",
- CollectionType = CollectionType.Movies
- });
+ CollectionType = CollectionTypeOptions.Movies
+ };
}
customPath = GetConfiguration().SeriesRecordingPath;
- if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
+ if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
{
- list.Add(new VirtualFolderInfo
+ yield return new VirtualFolderInfo
{
Locations = new string[] { customPath },
Name = "Recorded Shows",
- CollectionType = CollectionType.TvShows
- });
+ CollectionType = CollectionTypeOptions.TvShows
+ };
}
-
- return list;
}
- private const int TunerDiscoveryDurationMs = 3000;
-
public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
{
var list = new List<TunerHostInfo>();
@@ -2739,6 +2624,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparer.OrdinalIgnoreCase))
.ToList();
}
+
list.AddRange(discoveredDevices);
}
@@ -2775,11 +2661,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDuationMs, CancellationToken cancellationToken)
+ private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken)
{
try
{
- var discoveredDevices = await host.DiscoverDevices(discoveryDuationMs, cancellationToken).ConfigureAwait(false);
+ var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false);
foreach (var device in discoveredDevices)
{
@@ -2796,11 +2682,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
}
- public static class ConfigurationExtension
- {
- public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
- {
- return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
- }
- }
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
index 9a9bae215..835028b92 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
@@ -1,22 +1,25 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
-using System.Linq;
using System.Text;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
@@ -24,34 +27,26 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class EncodedRecorder : IRecorder
{
private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
private readonly IMediaEncoder _mediaEncoder;
private readonly IServerApplicationPaths _appPaths;
+ private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private bool _hasExited;
private Stream _logFileStream;
private string _targetPath;
- private IProcess _process;
- private readonly IProcessFactory _processFactory;
- private readonly IJsonSerializer _json;
- private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
- private readonly IServerConfigurationManager _config;
+ private Process _process;
public EncodedRecorder(
ILogger logger,
- IFileSystem fileSystem,
IMediaEncoder mediaEncoder,
IServerApplicationPaths appPaths,
- IJsonSerializer json,
- IProcessFactory processFactory,
- IServerConfigurationManager config)
+ IServerConfigurationManager serverConfigurationManager)
{
_logger = logger;
- _fileSystem = fileSystem;
_mediaEncoder = mediaEncoder;
_appPaths = appPaths;
- _json = json;
- _processFactory = processFactory;
- _config = config;
+ _serverConfigurationManager = serverConfigurationManager;
}
private static bool CopySubtitles => false;
@@ -64,73 +59,63 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
// The media source is infinite so we need to handle stopping ourselves
- var durationToken = new CancellationTokenSource(duration);
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
+ using var durationToken = new CancellationTokenSource(duration);
+ using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
- await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
+ await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationTokenSource.Token).ConfigureAwait(false);
_logger.LogInformation("Recording completed to file {0}", targetFile);
}
- private EncodingOptions GetEncodingOptions()
- {
- return _config.GetConfiguration<EncodingOptions>("encoding");
- }
-
- private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
+ private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
_targetPath = targetFile;
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
- var process = _processFactory.Create(new ProcessOptions
+ var processStartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
- // Must consume both stdout and stderr or deadlocks may occur
- //RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
FileName = _mediaEncoder.EncoderPath,
Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
- IsHidden = true,
- ErrorDialog = false,
- EnableRaisingEvents = true
- });
-
- _process = process;
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false
+ };
- var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
+ var commandLineLogMessage = processStartInfo.FileName + " " + processStartInfo.Arguments;
_logger.LogInformation(commandLineLogMessage);
var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
- _logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
+ _logFileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
- var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
- _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
+ await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false);
- process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
+ _process = new Process
+ {
+ StartInfo = processStartInfo,
+ EnableRaisingEvents = true
+ };
+ _process.Exited += (sender, args) => OnFfMpegProcessExited(_process);
- process.Start();
+ _process.Start();
cancellationToken.Register(Stop);
- // MUST read both stdout and stderr asynchronously or a deadlock may occurr
- //process.BeginOutputReadLine();
-
onStarted();
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
- StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
+ _ = StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
_logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
-
- return _taskCompletionSource.Task;
}
private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
@@ -138,11 +123,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
string videoArgs;
if (EncodeVideo(mediaSource))
{
- var maxBitrate = 25000000;
+ const int MaxBitrate = 25000000;
videoArgs = string.Format(
- "-codec:v:0 libx264 -force_key_frames \"expr:gte(t,n_forced*5)\" {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41",
- GetOutputSizeParam(),
- maxBitrate.ToString(CultureInfo.InvariantCulture));
+ CultureInfo.InvariantCulture,
+ "-codec:v:0 libx264 -force_key_frames \"expr:gte(t,n_forced*5)\" {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41",
+ GetOutputSizeParam(),
+ MaxBitrate);
}
else
{
@@ -151,18 +137,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
videoArgs += " -fflags +genpts";
- var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
- durationParam = string.Empty;
-
var flags = new List<string>();
if (mediaSource.IgnoreDts)
{
flags.Add("+igndts");
}
+
if (mediaSource.IgnoreIndex)
{
flags.Add("+ignidx");
}
+
if (mediaSource.GenPtsInput)
{
flags.Add("+genpts");
@@ -172,11 +157,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (flags.Count > 0)
{
- inputModifier += " -fflags " + string.Join("", flags.ToArray());
+ inputModifier += " -fflags " + string.Join(string.Empty, flags);
}
- var videoStream = mediaSource.VideoStream;
-
if (mediaSource.ReadAtNativeFramerate)
{
inputModifier += " -re";
@@ -194,38 +177,38 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
- //var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
+ // var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
// " -f mp4 -movflags frag_keyframe+empty_moov" :
// string.Empty;
var outputParam = string.Empty;
- var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
+ var threads = EncodingHelper.GetNumberOfThreads(null, _serverConfigurationManager.GetEncodingOptions(), null);
+ var commandLineArgs = string.Format(
+ CultureInfo.InvariantCulture,
+ "-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"",
inputTempFile,
- targetFile,
+ targetFile.Replace("\"", "\\\""), // Escape quotes in filename
videoArgs,
GetAudioArgs(mediaSource),
subtitleArgs,
- durationParam,
- outputParam);
+ outputParam,
+ threads);
return inputModifier + " " + commandLineArgs;
}
private static string GetAudioArgs(MediaSourceInfo mediaSource)
{
- var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
- var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
-
return "-codec:a:0 copy";
- //var audioChannels = 2;
- //var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
- //if (audioStream != null)
- //{
+ // var audioChannels = 2;
+ // var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
+ // if (audioStream != null)
+ // {
// audioChannels = audioStream.Channels ?? audioChannels;
- //}
- //return "-codec:a:0 aac -strict experimental -ab 320000";
+ // }
+ // return "-codec:a:0 aac -strict experimental -ab 320000";
}
private static bool EncodeVideo(MediaSourceInfo mediaSource)
@@ -234,20 +217,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
protected string GetOutputSizeParam()
- {
- var filters = new List<string>();
-
- filters.Add("yadif=0:-1:0");
-
- var output = string.Empty;
-
- if (filters.Count > 0)
- {
- output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
- }
-
- return output;
- }
+ => "-vf \"yadif=0:-1:0\"";
private void Stop()
{
@@ -257,7 +227,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
_logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
- //process.Kill();
_process.StandardInput.WriteLine("q");
}
catch (Exception ex)
@@ -305,17 +274,18 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
/// <summary>
/// Processes the exited.
/// </summary>
- private void OnFfMpegProcessExited(IProcess process, string inputFile)
+ private void OnFfMpegProcessExited(Process process)
{
- _hasExited = true;
+ using (process)
+ {
+ _hasExited = true;
- DisposeLogStream();
+ _logFileStream?.Dispose();
+ _logFileStream = null;
- try
- {
var exitCode = process.ExitCode;
- _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath);
+ _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
if (exitCode == 0)
{
@@ -323,55 +293,32 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
else
{
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode)));
- }
- }
- catch
- {
- _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath);
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath)));
- }
- }
-
- private void DisposeLogStream()
- {
- if (_logFileStream != null)
- {
- try
- {
- _logFileStream.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error disposing recording log stream");
+ _taskCompletionSource.TrySetException(
+ new Exception(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Recording for {0} failed. Exit code {1}",
+ _targetPath,
+ exitCode)));
}
-
- _logFileStream = null;
}
}
- private async void StartStreamingLog(Stream source, Stream target)
+ private async Task StartStreamingLog(Stream source, Stream target)
{
try
{
using (var reader = new StreamReader(source))
{
- while (!reader.EndOfStream)
+ await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
- var line = await reader.ReadLineAsync().ConfigureAwait(false);
-
var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
- await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
+ await target.WriteAsync(bytes.AsMemory()).ConfigureAwait(false);
await target.FlushAsync().ConfigureAwait(false);
}
}
}
- catch (ObjectDisposedException)
- {
- // TODO Investigate and properly fix.
- // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
- }
catch (Exception ex)
{
_logger.LogError(ex, "Error reading ffmpeg recording log");
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs
index 9c9ba09f5..a2ec2df37 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs
@@ -1,15 +1,19 @@
+#pragma warning disable CS1591
+
using System.Threading.Tasks;
using MediaBrowser.Controller.Plugins;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
- public class EntryPoint : IServerEntryPoint
+ public sealed class EntryPoint : IServerEntryPoint
{
+ /// <inheritdoc />
public Task RunAsync()
{
return EmbyTV.Current.Start();
}
+ /// <inheritdoc />
public void Dispose()
{
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs
new file mode 100644
index 000000000..20a8213a7
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs
@@ -0,0 +1,54 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Controller.LiveTv;
+
+namespace Emby.Server.Implementations.LiveTv.EmbyTV
+{
+ internal class EpgChannelData
+ {
+ private readonly Dictionary<string, ChannelInfo> _channelsById;
+
+ private readonly Dictionary<string, ChannelInfo> _channelsByNumber;
+
+ private readonly Dictionary<string, ChannelInfo> _channelsByName;
+
+ public EpgChannelData(IEnumerable<ChannelInfo> channels)
+ {
+ _channelsById = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
+ _channelsByNumber = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
+ _channelsByName = new Dictionary<string, ChannelInfo>(StringComparer.OrdinalIgnoreCase);
+
+ foreach (var channel in channels)
+ {
+ _channelsById[channel.Id] = channel;
+
+ if (!string.IsNullOrEmpty(channel.Number))
+ {
+ _channelsByNumber[channel.Number] = channel;
+ }
+
+ var normalizedName = NormalizeName(channel.Name ?? string.Empty);
+ if (!string.IsNullOrWhiteSpace(normalizedName))
+ {
+ _channelsByName[normalizedName] = channel;
+ }
+ }
+ }
+
+ public ChannelInfo? GetChannelById(string id)
+ => _channelsById.GetValueOrDefault(id);
+
+ public ChannelInfo? GetChannelByNumber(string number)
+ => _channelsByNumber.GetValueOrDefault(number);
+
+ public ChannelInfo? GetChannelByName(string name)
+ => _channelsByName.GetValueOrDefault(name);
+
+ public static string NormalizeName(string value)
+ {
+ return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs
index 6eced3050..7705132da 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -11,7 +13,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
/// <summary>
/// Records the specified media source.
/// </summary>
- Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken);
+ /// <param name="directStreamProvider">The direct stream provider, or <c>null</c>.</param>
+ /// <param name="mediaSource">The media source.</param>
+ /// <param name="targetFile">The target file.</param>
+ /// <param name="duration">The duration to record.</param>
+ /// <param name="onStarted">An action to perform when recording starts.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>A <see cref="Task"/> that represents the recording operation.</returns>
+ Task Record(IDirectStreamProvider? directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken);
string GetOutputPath(MediaSourceInfo mediaSource, string targetFile);
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
index a2ac60b31..46979bfc5 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
@@ -1,9 +1,12 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
+using System.Text.Json;
+using Jellyfin.Extensions.Json;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
@@ -11,72 +14,71 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class ItemDataProvider<T>
where T : class
{
- private readonly object _fileDataLock = new object();
- private List<T> _items;
- private readonly IJsonSerializer _jsonSerializer;
- protected readonly ILogger Logger;
private readonly string _dataPath;
- protected readonly Func<T, T, bool> EqualityComparer;
+ private readonly object _fileDataLock = new object();
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private T[]? _items;
- public ItemDataProvider(IJsonSerializer jsonSerializer, ILogger logger, string dataPath, Func<T, T, bool> equalityComparer)
+ public ItemDataProvider(
+ ILogger logger,
+ string dataPath,
+ Func<T, T, bool> equalityComparer)
{
Logger = logger;
_dataPath = dataPath;
EqualityComparer = equalityComparer;
- _jsonSerializer = jsonSerializer;
}
- public IReadOnlyList<T> GetAll()
- {
- lock (_fileDataLock)
- {
- if (_items == null)
- {
- Logger.LogInformation("Loading live tv data from {0}", _dataPath);
- _items = GetItemsFromFile(_dataPath);
- }
- return _items.ToList();
- }
- }
+ protected ILogger Logger { get; }
- private List<T> GetItemsFromFile(string path)
- {
- var jsonFile = path + ".json";
+ protected Func<T, T, bool> EqualityComparer { get; }
- if (!File.Exists(jsonFile))
+ [MemberNotNull(nameof(_items))]
+ private void EnsureLoaded()
+ {
+ if (_items != null)
{
- return new List<T>();
+ return;
}
- try
- {
- return _jsonSerializer.DeserializeFromFile<List<T>>(jsonFile) ?? new List<T>();
- }
- catch (IOException)
+ if (File.Exists(_dataPath))
{
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
+ Logger.LogInformation("Loading live tv data from {Path}", _dataPath);
+
+ try
+ {
+ var bytes = File.ReadAllBytes(_dataPath);
+ _items = JsonSerializer.Deserialize<T[]>(bytes, _jsonOptions);
+ if (_items == null)
+ {
+ Logger.LogError("Error deserializing {Path}, data was null", _dataPath);
+ _items = Array.Empty<T>();
+ }
+
+ return;
+ }
+ catch (JsonException ex)
+ {
+ Logger.LogError(ex, "Error deserializing {Path}", _dataPath);
+ }
}
- return new List<T>();
+ _items = Array.Empty<T>();
}
- private void UpdateList(List<T> newList)
+ private void SaveList()
{
- if (newList == null)
- {
- throw new ArgumentNullException(nameof(newList));
- }
-
- var file = _dataPath + ".json";
- Directory.CreateDirectory(Path.GetDirectoryName(file));
+ Directory.CreateDirectory(Path.GetDirectoryName(_dataPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(_dataPath)));
+ var jsonString = JsonSerializer.Serialize(_items, _jsonOptions);
+ File.WriteAllText(_dataPath, jsonString);
+ }
+ public IReadOnlyList<T> GetAll()
+ {
lock (_fileDataLock)
{
- _jsonSerializer.SerializeToFile(newList, file);
- _items = newList;
+ EnsureLoaded();
+ return (T[])_items.Clone();
}
}
@@ -87,18 +89,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new ArgumentNullException(nameof(item));
}
- var list = GetAll().ToList();
-
- var index = list.FindIndex(i => EqualityComparer(i, item));
-
- if (index == -1)
+ lock (_fileDataLock)
{
- throw new ArgumentException("item not found");
- }
+ EnsureLoaded();
- list[index] = item;
+ var index = Array.FindIndex(_items, i => EqualityComparer(i, item));
+ if (index == -1)
+ {
+ throw new ArgumentException("item not found");
+ }
- UpdateList(list);
+ _items[index] = item;
+
+ SaveList();
+ }
}
public virtual void Add(T item)
@@ -108,37 +112,58 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new ArgumentNullException(nameof(item));
}
- var list = GetAll().ToList();
-
- if (list.Any(i => EqualityComparer(i, item)))
+ lock (_fileDataLock)
{
- throw new ArgumentException("item already exists");
- }
+ EnsureLoaded();
- list.Add(item);
+ if (_items.Any(i => EqualityComparer(i, item)))
+ {
+ throw new ArgumentException("item already exists", nameof(item));
+ }
+
+ int oldLen = _items.Length;
+ var newList = new T[oldLen + 1];
+ _items.CopyTo(newList, 0);
+ newList[oldLen] = item;
+ _items = newList;
- UpdateList(list);
+ SaveList();
+ }
}
- public void AddOrUpdate(T item)
+ public virtual void AddOrUpdate(T item)
{
- var list = GetAll().ToList();
-
- if (!list.Any(i => EqualityComparer(i, item)))
- {
- Add(item);
- }
- else
+ lock (_fileDataLock)
{
- Update(item);
+ EnsureLoaded();
+
+ int index = Array.FindIndex(_items, i => EqualityComparer(i, item));
+ if (index == -1)
+ {
+ int oldLen = _items.Length;
+ var newList = new T[oldLen + 1];
+ _items.CopyTo(newList, 0);
+ newList[oldLen] = item;
+ _items = newList;
+ }
+ else
+ {
+ _items[index] = item;
+ }
+
+ SaveList();
}
}
public virtual void Delete(T item)
{
- var list = GetAll().Where(i => !EqualityComparer(i, item)).ToList();
+ lock (_fileDataLock)
+ {
+ EnsureLoaded();
+ _items = _items.Where(i => !EqualityComparer(i, item)).ToArray();
- UpdateList(list);
+ SaveList();
+ }
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs
new file mode 100644
index 000000000..83f5e8413
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs
@@ -0,0 +1,19 @@
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Configuration;
+
+namespace Emby.Server.Implementations.LiveTv.EmbyTV
+{
+ /// <summary>
+ /// Class containing extension methods for working with the nfo configuration.
+ /// </summary>
+ public static class NfoConfigurationExtensions
+ {
+ /// <summary>
+ /// Gets the nfo configuration.
+ /// </summary>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <returns>The nfo configuration.</returns>
+ public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager configurationManager)
+ => configurationManager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
index ded3c7607..32245f899 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
@@ -1,10 +1,12 @@
+#pragma warning disable CS1591
+
using System;
using System.Globalization;
using MediaBrowser.Controller.LiveTv;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
- internal class RecordingHelper
+ internal static class RecordingHelper
{
public static DateTime GetStartTime(TimerInfo timer)
{
@@ -21,7 +23,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (info.SeasonNumber.HasValue && info.EpisodeNumber.HasValue)
{
- name += string.Format(" S{0}E{1}", info.SeasonNumber.Value.ToString("00", CultureInfo.InvariantCulture), info.EpisodeNumber.Value.ToString("00", CultureInfo.InvariantCulture));
+ name += string.Format(
+ CultureInfo.InvariantCulture,
+ " S{0}E{1}",
+ info.SeasonNumber.Value.ToString("00", CultureInfo.InvariantCulture),
+ info.EpisodeNumber.Value.ToString("00", CultureInfo.InvariantCulture));
addHyphen = false;
}
else if (info.OriginalAirDate.HasValue)
@@ -32,7 +38,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
else
{
- name += " " + info.OriginalAirDate.Value.ToLocalTime().ToString("yyyy-MM-dd");
+ name += " " + info.OriginalAirDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
}
else
@@ -50,7 +56,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
name += " " + info.EpisodeTitle;
}
}
-
else if (info.IsMovie && info.ProductionYear != null)
{
name += " (" + info.ProductionYear + ")";
@@ -65,16 +70,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private static string GetDateString(DateTime date)
{
- date = date.ToLocalTime();
-
- return string.Format("{0}_{1}_{2}_{3}_{4}_{5}",
- date.Year.ToString("0000", CultureInfo.InvariantCulture),
- date.Month.ToString("00", CultureInfo.InvariantCulture),
- date.Day.ToString("00", CultureInfo.InvariantCulture),
- date.Hour.ToString("00", CultureInfo.InvariantCulture),
- date.Minute.ToString("00", CultureInfo.InvariantCulture),
- date.Second.ToString("00", CultureInfo.InvariantCulture)
- );
+ return date.ToLocalTime().ToString("yyyy_MM_dd_HH_mm_ss", CultureInfo.InvariantCulture);
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
index 520b44404..b1259de23 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
@@ -1,17 +1,19 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
public class SeriesTimerManager : ItemDataProvider<SeriesTimerInfo>
{
- public SeriesTimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath)
- : base(jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
+ public SeriesTimerManager(ILogger logger, string dataPath)
+ : base(logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
{
}
+ /// <inheritdoc />
public override void Add(SeriesTimerInfo item)
{
if (string.IsNullOrEmpty(item.Id))
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
index 3c807a8ea..a861e6ae4 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
@@ -1,12 +1,13 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Linq;
using System.Threading;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
@@ -14,21 +15,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class TimerManager : ItemDataProvider<TimerInfo>
{
private readonly ConcurrentDictionary<string, Timer> _timers = new ConcurrentDictionary<string, Timer>(StringComparer.OrdinalIgnoreCase);
- private readonly ILogger _logger;
-
- public event EventHandler<GenericEventArgs<TimerInfo>> TimerFired;
- public TimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1)
- : base(jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
+ public TimerManager(ILogger logger, string dataPath)
+ : base(logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
{
- _logger = logger1;
}
+ public event EventHandler<GenericEventArgs<TimerInfo>>? TimerFired;
+
public void RestartTimers()
{
StopTimers();
- foreach (var item in GetAll().ToList())
+ foreach (var item in GetAll())
{
AddOrUpdateSystemTimer(item);
}
@@ -64,16 +63,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return;
}
- var list = GetAll().ToList();
+ base.AddOrUpdate(item);
+ }
- if (!list.Any(i => EqualityComparer(i, item)))
- {
- base.Add(item);
- }
- else
- {
- base.Update(item);
- }
+ public override void AddOrUpdate(TimerInfo item)
+ {
+ base.AddOrUpdate(item);
+ AddOrUpdateSystemTimer(item);
}
public override void Add(TimerInfo item)
@@ -89,8 +85,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private static bool ShouldStartTimer(TimerInfo item)
{
- if (item.Status == RecordingStatus.Completed ||
- item.Status == RecordingStatus.Cancelled)
+ if (item.Status == RecordingStatus.Completed
+ || item.Status == RecordingStatus.Cancelled)
{
return false;
}
@@ -112,7 +108,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (startDate < now)
{
- TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = item });
+ TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo>(item));
return;
}
@@ -126,12 +122,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (_timers.TryAdd(item.Id, timer))
{
- _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ Logger.LogInformation(
+ "Creating recording timer for {Id}, {Name}. Timer will fire in {Minutes} minutes",
+ item.Id,
+ item.Name,
+ dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
}
else
{
timer.Dispose();
- _logger.LogWarning("Timer already exists for item {id}", item.Id);
+ Logger.LogWarning("Timer already exists for item {Id}", item.Id);
}
}
@@ -143,23 +143,23 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- private void TimerCallback(object state)
+ private void TimerCallback(object? state)
{
- var timerId = (string)state;
+ var timerId = (string?)state ?? throw new ArgumentNullException(nameof(state));
var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase));
if (timer != null)
{
- TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = timer });
+ TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
}
}
- public TimerInfo GetTimer(string id)
+ public TimerInfo? GetTimer(string id)
{
return GetAll().FirstOrDefault(r => string.Equals(r.Id, id, StringComparison.OrdinalIgnoreCase));
}
- public TimerInfo GetTimerByProgramId(string programId)
+ public TimerInfo? GetTimerByProgramId(string programId)
{
return GetAll().FirstOrDefault(r => string.Equals(r.ProgramId, programId, StringComparison.OrdinalIgnoreCase));
}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
index 0bbffb824..1f963e4a2 100644
--- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
@@ -1,44 +1,61 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
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.Http.Headers;
+using System.Net.Mime;
+using System.Text;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common;
+using Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.Listings
{
public class SchedulesDirect : IListingsProvider
{
- private readonly ILogger _logger;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
+ private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
+
+ private readonly ILogger<SchedulesDirect> _logger;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
- private readonly IApplicationHost _appHost;
+ private readonly ICryptoProvider _cryptoProvider;
- private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
+ private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private DateTime _lastErrorResponse;
- public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
+ public SchedulesDirect(
+ ILogger<SchedulesDirect> logger,
+ IHttpClientFactory httpClientFactory,
+ ICryptoProvider cryptoProvider)
{
_logger = logger;
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _appHost = appHost;
+ _httpClientFactory = httpClientFactory;
+ _cryptoProvider = cryptoProvider;
}
- private string UserAgent => _appHost.ApplicationUserAgent;
+ /// <inheritdoc />
+ public string Name => "Schedules Direct";
+
+ /// <inheritdoc />
+ public string Type => nameof(SchedulesDirect);
private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
{
@@ -49,7 +66,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
while (start <= end)
{
- dates.Add(start.ToString("yyyy-MM-dd"));
+ dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
start = start.AddDays(1);
}
@@ -78,173 +95,170 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
_logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
- var requestList = new List<ScheduleDirect.RequestScheduleForChannel>()
+ var requestList = new List<RequestScheduleForChannelDto>()
{
- new ScheduleDirect.RequestScheduleForChannel()
+ new RequestScheduleForChannelDto()
{
- stationID = channelId,
- date = dates
+ StationId = channelId,
+ Date = dates
}
};
- var requestString = _jsonSerializer.SerializeToString(requestList);
+ var requestString = JsonSerializer.Serialize(requestList, _jsonOptions);
_logger.LogDebug("Request string for schedules is: {RequestString}", requestString);
- var httpOptions = new HttpRequestOptions()
+ using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
+ options.Content = new StringContent(requestString, Encoding.UTF8, MediaTypeNames.Application.Json);
+ options.Headers.TryAddWithoutValidation("token", token);
+ using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
+ await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var dailySchedules = await JsonSerializer.DeserializeAsync<IReadOnlyList<DayDto>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (dailySchedules == null)
{
- Url = ApiUrl + "/schedules",
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- // The data can be large so give it some extra time
- TimeoutMs = 60000,
- LogErrorResponseBody = true,
- RequestContent = requestString
- };
-
- httpOptions.RequestHeaders["token"] = token;
-
- using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
- using (var reader = new StreamReader(response.Content))
- {
- var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(response.Content).ConfigureAwait(false);
- _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
+ return Array.Empty<ProgramInfo>();
+ }
- httpOptions = new HttpRequestOptions()
- {
- Url = ApiUrl + "/programs",
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true,
- // The data can be large so give it some extra time
- TimeoutMs = 60000
- };
+ _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
- httpOptions.RequestHeaders["token"] = token;
+ using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs");
+ programRequestOptions.Headers.TryAddWithoutValidation("token", token);
- var programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct();
- httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]";
+ var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();
+ programRequestOptions.Content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(programIds, _jsonOptions));
+ programRequestOptions.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
- using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
- using (var innerReader = new StreamReader(innerResponse.Content))
- {
- var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponse.Content).ConfigureAwait(false);
- var programDict = programDetails.ToDictionary(p => p.programID, y => y);
+ using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
+ await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var programDetails = await JsonSerializer.DeserializeAsync<IReadOnlyList<ProgramDetailsDto>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (programDetails == null)
+ {
+ return Array.Empty<ProgramInfo>();
+ }
- var programIdsWithImages =
- programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID)
- .ToList();
+ var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y);
- var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
+ var programIdsWithImages = programDetails
+ .Where(p => p.HasImageArtwork).Select(p => p.ProgramId)
+ .ToList();
- var programsInfo = new List<ProgramInfo>();
- foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs))
- {
- //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
- // " which corresponds to channel " + channelNumber + " and program id " +
- // schedule.programID + " which says it has images? " +
- // programDict[schedule.programID].hasImageArtwork);
+ var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
- if (images != null)
- {
- var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
- if (imageIndex > -1)
- {
- var programEntry = programDict[schedule.programID];
+ var programsInfo = new List<ProgramInfo>();
+ foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs))
+ {
+ // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
+ // " which corresponds to channel " + channelNumber + " and program id " +
+ // schedule.ProgramId + " which says it has images? " +
+ // programDict[schedule.ProgramId].hasImageArtwork);
- var allImages = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>();
- var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase));
- var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase));
+ if (string.IsNullOrEmpty(schedule.ProgramId))
+ {
+ continue;
+ }
- const double desiredAspect = 0.666666667;
+ if (images != null)
+ {
+ var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
+ if (imageIndex > -1)
+ {
+ var programEntry = programDict[schedule.ProgramId];
- programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ??
- GetProgramImage(ApiUrl, allImages, true, desiredAspect);
+ var allImages = images[imageIndex].Data;
+ var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase));
+ var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase));
- const double wideAspect = 1.77777778;
+ const double DesiredAspect = 2.0 / 3;
- programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect);
+ programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, true, DesiredAspect) ??
+ GetProgramImage(ApiUrl, allImages, true, DesiredAspect);
- // Don't supply the same image twice
- if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
- {
- programEntry.thumbImage = null;
- }
+ const double WideAspect = 16.0 / 9;
- programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, wideAspect);
+ programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, true, WideAspect);
- //programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
- // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
- // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
- // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
- }
+ // Don't supply the same image twice
+ if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal))
+ {
+ programEntry.ThumbImage = null;
}
- programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
+ programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, WideAspect);
+
+ // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
}
- return programsInfo;
}
+
+ programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId]));
}
+
+ return programsInfo;
}
- private static int GetSizeOrder(ScheduleDirect.ImageData image)
+ private static int GetSizeOrder(ImageDataDto image)
{
- if (!string.IsNullOrWhiteSpace(image.height))
+ if (int.TryParse(image.Height, out int value))
{
- if (int.TryParse(image.height, out int value))
- {
- return value;
- }
+ return value;
}
return 0;
}
- private static string GetChannelNumber(ScheduleDirect.Map map)
+ private static string GetChannelNumber(MapDto map)
{
- var channelNumber = map.logicalChannelNumber;
+ var channelNumber = map.LogicalChannelNumber;
if (string.IsNullOrWhiteSpace(channelNumber))
{
- channelNumber = map.channel;
+ channelNumber = map.Channel;
}
+
if (string.IsNullOrWhiteSpace(channelNumber))
{
- channelNumber = map.atscMajor + "." + map.atscMinor;
+ channelNumber = map.AtscMajor + "." + map.AtscMinor;
}
return channelNumber.TrimStart('0');
}
- private static bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
+ private static bool IsMovie(ProgramDetailsDto programInfo)
{
- return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase);
+ return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase);
}
- private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
+ private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details)
{
- var startAt = GetDate(programInfo.airDateTime);
- var endAt = startAt.AddSeconds(programInfo.duration);
+ if (programInfo.AirDateTime == null)
+ {
+ return null;
+ }
+
+ var startAt = programInfo.AirDateTime.Value;
+ var endAt = startAt.AddSeconds(programInfo.Duration);
var audioType = ProgramAudio.Stereo;
- var programId = programInfo.programID ?? string.Empty;
+ var programId = programInfo.ProgramId ?? string.Empty;
string newID = programId + "T" + startAt.Ticks + "C" + channelId;
- if (programInfo.audioProperties != null)
+ if (programInfo.AudioProperties.Count != 0)
{
- if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
+ if (programInfo.AudioProperties.Contains("atmos", StringComparer.OrdinalIgnoreCase))
{
audioType = ProgramAudio.Atmos;
}
- else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
+ else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparer.OrdinalIgnoreCase))
{
audioType = ProgramAudio.DolbyDigital;
}
- else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
+ else if (programInfo.AudioProperties.Contains("dd", StringComparer.OrdinalIgnoreCase))
{
audioType = ProgramAudio.DolbyDigital;
}
- else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
+ else if (programInfo.AudioProperties.Contains("stereo", StringComparer.OrdinalIgnoreCase))
{
audioType = ProgramAudio.Stereo;
}
@@ -255,9 +269,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
string episodeTitle = null;
- if (details.episodeTitle150 != null)
+ if (details.EpisodeTitle150 != null)
{
- episodeTitle = details.episodeTitle150;
+ episodeTitle = details.EpisodeTitle150;
}
var info = new ProgramInfo
@@ -266,22 +280,22 @@ namespace Emby.Server.Implementations.LiveTv.Listings
Id = newID,
StartDate = startAt,
EndDate = endAt,
- Name = details.titles[0].title120 ?? "Unkown",
+ Name = details.Titles[0].Title120 ?? "Unknown",
OfficialRating = null,
CommunityRating = null,
EpisodeTitle = episodeTitle,
Audio = audioType,
- //IsNew = programInfo.@new ?? false,
- IsRepeat = programInfo.@new == null,
- IsSeries = string.Equals(details.entityType, "episode", StringComparison.OrdinalIgnoreCase),
- ImageUrl = details.primaryImage,
- ThumbImageUrl = details.thumbImage,
- IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
- IsSports = string.Equals(details.entityType, "sports", StringComparison.OrdinalIgnoreCase),
+ // IsNew = programInfo.@new ?? false,
+ IsRepeat = programInfo.New == null,
+ IsSeries = string.Equals(details.EntityType, "episode", StringComparison.OrdinalIgnoreCase),
+ ImageUrl = details.PrimaryImage,
+ ThumbImageUrl = details.ThumbImage,
+ IsKids = string.Equals(details.Audience, "children", StringComparison.OrdinalIgnoreCase),
+ IsSports = string.Equals(details.EntityType, "sports", StringComparison.OrdinalIgnoreCase),
IsMovie = IsMovie(details),
- Etag = programInfo.md5,
- IsLive = string.Equals(programInfo.liveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
- IsPremiere = programInfo.premiere || (programInfo.isPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
+ Etag = programInfo.Md5,
+ IsLive = string.Equals(programInfo.LiveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
+ IsPremiere = programInfo.Premiere || (programInfo.IsPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
};
var showId = programId;
@@ -304,15 +318,16 @@ namespace Emby.Server.Implementations.LiveTv.Listings
info.ShowId = showId;
- if (programInfo.videoProperties != null)
+ if (programInfo.VideoProperties != null)
{
- info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
- info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
+ info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
+ info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
}
- if (details.contentRating != null && details.contentRating.Count > 0)
+ if (details.ContentRating != null && details.ContentRating.Count > 0)
{
- info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
+ info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal)
+ .Replace("--", "-", StringComparison.Ordinal);
var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
@@ -321,15 +336,15 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- if (details.descriptions != null)
+ if (details.Descriptions != null)
{
- if (details.descriptions.description1000 != null && details.descriptions.description1000.Count > 0)
+ if (details.Descriptions.Description1000 != null && details.Descriptions.Description1000.Count > 0)
{
- info.Overview = details.descriptions.description1000[0].description;
+ info.Overview = details.Descriptions.Description1000[0].Description;
}
- else if (details.descriptions.description100 != null && details.descriptions.description100.Count > 0)
+ else if (details.Descriptions.Description100 != null && details.Descriptions.Description100.Count > 0)
{
- info.Overview = details.descriptions.description100[0].description;
+ info.Overview = details.Descriptions.Description100[0].Description;
}
}
@@ -337,20 +352,20 @@ namespace Emby.Server.Implementations.LiveTv.Listings
{
info.SeriesId = programId.Substring(0, 10);
- info.SeriesProviderIds[MetadataProviders.Zap2It.ToString()] = info.SeriesId;
+ info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
- if (details.metadata != null)
+ if (details.Metadata != null)
{
- foreach (var metadataProgram in details.metadata)
+ foreach (var metadataProgram in details.Metadata)
{
var gracenote = metadataProgram.Gracenote;
if (gracenote != null)
{
- info.SeasonNumber = gracenote.season;
+ info.SeasonNumber = gracenote.Season;
- if (gracenote.episode > 0)
+ if (gracenote.Episode > 0)
{
- info.EpisodeNumber = gracenote.episode;
+ info.EpisodeNumber = gracenote.Episode;
}
break;
@@ -359,24 +374,25 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- if (!string.IsNullOrWhiteSpace(details.originalAirDate))
+ if (details.OriginalAirDate != null)
{
- info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
+ info.OriginalAirDate = details.OriginalAirDate;
info.ProductionYear = info.OriginalAirDate.Value.Year;
}
- if (details.movie != null)
+ if (details.Movie != null)
{
- if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out int year))
+ if (!string.IsNullOrEmpty(details.Movie.Year)
+ && int.TryParse(details.Movie.Year, out int year))
{
info.ProductionYear = year;
}
}
- if (details.genres != null)
+ if (details.Genres != null)
{
- info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
- info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
+ info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
+ info.IsNews = details.Genres.Contains("news", StringComparer.OrdinalIgnoreCase);
if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
{
@@ -387,22 +403,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return info;
}
- private static DateTime GetDate(string value)
- {
- var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
-
- if (date.Kind != DateTimeKind.Utc)
- {
- date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
- }
- return date;
- }
-
- private string GetProgramImage(string apiUrl, IEnumerable<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
+ private string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, bool returnDefaultImage, double desiredAspect)
{
var match = images
.OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
- .ThenByDescending(GetSizeOrder)
+ .ThenByDescending(i => GetSizeOrder(i))
.FirstOrDefault();
if (match == null)
@@ -410,7 +415,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return null;
}
- var uri = match.uri;
+ var uri = match.Uri;
if (string.IsNullOrWhiteSpace(uri))
{
@@ -426,19 +431,19 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- private static double GetAspectRatio(ScheduleDirect.ImageData i)
+ private static double GetAspectRatio(ImageDataDto i)
{
int width = 0;
int height = 0;
- if (!string.IsNullOrWhiteSpace(i.width))
+ if (!string.IsNullOrWhiteSpace(i.Width))
{
- int.TryParse(i.width, out width);
+ _ = int.TryParse(i.Width, out width);
}
- if (!string.IsNullOrWhiteSpace(i.height))
+ if (!string.IsNullOrWhiteSpace(i.Height))
{
- int.TryParse(i.height, out height);
+ _ = int.TryParse(i.Height, out height);
}
if (height == 0 || width == 0)
@@ -451,60 +456,50 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return result;
}
- private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
+ private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
ListingsProviderInfo info,
- List<string> programIds,
- CancellationToken cancellationToken)
+ IReadOnlyList<string> programIds,
+ CancellationToken cancellationToken)
{
if (programIds.Count == 0)
{
- return new List<ScheduleDirect.ShowImages>();
+ return Array.Empty<ShowImagesDto>();
}
- var imageIdString = "[";
-
- foreach (var i in programIds)
+ StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
+ foreach (ReadOnlySpan<char> i in programIds)
{
- var imageId = i.Substring(0, 10);
-
- if (!imageIdString.Contains(imageId))
- {
- imageIdString += "\"" + imageId + "\",";
- }
+ str.Append('"')
+ .Append(i.Slice(0, 10))
+ .Append("\",");
}
- imageIdString = imageIdString.TrimEnd(',') + "]";
+ // Remove last ,
+ str.Length--;
+ str.Append(']');
- var httpOptions = new HttpRequestOptions()
+ using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
{
- Url = ApiUrl + "/metadata/programs",
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- RequestContent = imageIdString,
- LogErrorResponseBody = true,
- // The data can be large so give it some extra time
- TimeoutMs = 60000
+ Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
};
try
{
- using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
- {
- return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(
- innerResponse2.Content).ConfigureAwait(false);
- }
+ using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
+ await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ return await JsonSerializer.DeserializeAsync<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting image info from schedules direct");
- return new List<ScheduleDirect.ShowImages>();
+ return Array.Empty<ShowImagesDto>();
}
}
public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
{
- var token = await GetToken(info, cancellationToken);
+ var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
var lineups = new List<NameIdPair>();
@@ -513,41 +508,33 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return lineups;
}
- var options = new HttpRequestOptions()
- {
- Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true
- };
-
- options.RequestHeaders["token"] = token;
+ using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
+ options.Headers.TryAddWithoutValidation("token", token);
try
{
- using (var httpResponse = await Get(options, false, info).ConfigureAwait(false))
- using (Stream responce = httpResponse.Content)
- {
- var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false);
+ using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
+ await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+
+ var root = await JsonSerializer.DeserializeAsync<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
- if (root != null)
+ if (root != null)
+ {
+ foreach (HeadendsDto headend in root)
{
- foreach (ScheduleDirect.Headends headend in root)
+ foreach (LineupDto lineup in headend.Lineups)
{
- foreach (ScheduleDirect.Lineup lineup in headend.lineups)
+ lineups.Add(new NameIdPair
{
- lineups.Add(new NameIdPair
- {
- Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
- Id = lineup.uri.Substring(18)
- });
- }
+ Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name,
+ Id = lineup.Uri?[18..]
+ });
}
}
- else
- {
- _logger.LogInformation("No lineups available");
- }
+ }
+ else
+ {
+ _logger.LogInformation("No lineups available");
}
}
catch (Exception ex)
@@ -558,8 +545,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return lineups;
}
- private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
- private DateTime _lastErrorResponse;
private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
{
var username = info.Username;
@@ -582,8 +567,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return null;
}
- NameValuePair savedToken = null;
- if (!_tokens.TryGetValue(username, out savedToken))
+ if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
{
savedToken = new NameValuePair();
_tokens.TryAdd(username, savedToken);
@@ -609,7 +593,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
return result;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
if (ex.StatusCode.HasValue)
{
@@ -619,6 +603,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
_lastErrorResponse = DateTime.UtcNow;
}
}
+
throw;
}
finally
@@ -627,112 +612,64 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
+ private async Task<HttpResponseMessage> Send(
+ HttpRequestMessage options,
bool enableRetry,
- ListingsProviderInfo providerInfo)
+ ListingsProviderInfo providerInfo,
+ CancellationToken cancellationToken,
+ HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
- // Schedules direct requires that the client support compression and will return a 400 response without it
- options.EnableHttpCompression = true;
-
- // On windows 7 under .net core, this header is not getting added
-#if NETSTANDARD2_0
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+ var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
+ if (response.IsSuccessStatusCode)
{
- options.RequestHeaders["Accept-Encoding"] = "deflate";
+ return response;
}
-#endif
- try
+ // Response is automatically disposed in the calling function,
+ // so dispose manually if not returning.
+ response.Dispose();
+ if (!enableRetry || (int)response.StatusCode >= 500)
{
- return await _httpClient.Post(options).ConfigureAwait(false);
+ throw new HttpRequestException(
+ string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
+ null,
+ response.StatusCode);
}
- catch (HttpException ex)
- {
- _tokens.Clear();
- if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
- {
- enableRetry = false;
- }
-
- if (!enableRetry)
- {
- throw;
- }
- }
-
- options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
- return await Post(options, false, providerInfo).ConfigureAwait(false);
+ _tokens.Clear();
+ options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
+ return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
}
- private async Task<HttpResponseInfo> Get(HttpRequestOptions options,
- bool enableRetry,
- ListingsProviderInfo providerInfo)
- {
- // Schedules direct requires that the client support compression and will return a 400 response without it
- options.EnableHttpCompression = true;
-
- // On windows 7 under .net core, this header is not getting added
-#if NETSTANDARD2_0
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- options.RequestHeaders["Accept-Encoding"] = "deflate";
- }
-#endif
-
- try
- {
- return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- _tokens.Clear();
-
- if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
- {
- enableRetry = false;
- }
-
- if (!enableRetry)
- {
- throw;
- }
- }
-
- options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
- return await Get(options, false, providerInfo).ConfigureAwait(false);
- }
-
- private async Task<string> GetTokenInternal(string username, string password,
+ private async Task<string> GetTokenInternal(
+ string username,
+ string password,
CancellationToken cancellationToken)
{
- var httpOptions = new HttpRequestOptions()
- {
- Url = ApiUrl + "/token",
- UserAgent = UserAgent,
- RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true
- };
- //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
- // httpOptions.RequestContent);
+ using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
+ var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>());
+ // TODO: remove ToLower when Convert.ToHexString supports lowercase
+ // Schedules Direct requires the hex to be lowercase
+ string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
+ options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
- using (var response = await Post(httpOptions, false, null).ConfigureAwait(false))
+ using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
{
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(response.Content).ConfigureAwait(false);
- if (root.message == "OK")
- {
- _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
- return root.token;
- }
-
- throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
+ _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
+ return root.Token;
}
+
+ throw new Exception("Could not authenticate with Schedules Direct Error: " + root.Message);
}
private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
{
- var token = await GetToken(info, cancellationToken);
+ var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(token))
{
@@ -746,27 +683,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings
_logger.LogInformation("Adding new LineUp ");
- var httpOptions = new HttpRequestOptions()
- {
- Url = ApiUrl + "/lineups/" + info.ListingsId,
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true,
- BufferContent = false
- };
-
- httpOptions.RequestHeaders["token"] = token;
-
- using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
- {
- }
+ using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
+ options.Headers.TryAddWithoutValidation("token", token);
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
- public string Name => "Schedules Direct";
-
- public static string TypeName = "SchedulesDirect";
- public string Type => TypeName;
-
private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(info.ListingsId))
@@ -774,7 +695,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
throw new ArgumentException("Listings Id required");
}
- var token = await GetToken(info, cancellationToken);
+ var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(token))
{
@@ -783,30 +704,23 @@ namespace Emby.Server.Implementations.LiveTv.Listings
_logger.LogInformation("Headends on account ");
- var options = new HttpRequestOptions()
- {
- Url = ApiUrl + "/lineups",
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true
- };
-
- options.RequestHeaders["token"] = token;
+ using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
+ options.Headers.TryAddWithoutValidation("token", token);
try
{
- using (var httpResponse = await Get(options, false, null).ConfigureAwait(false))
- using (var response = httpResponse.Content)
- {
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false);
+ using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
+ httpResponse.EnsureSuccessStatusCode();
+ await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var response = httpResponse.Content;
+ var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
- return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
- }
+ return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
- // Apparently we're supposed to swallow this
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
+ // SchedulesDirect returns 400 if no lineups are configured.
+ if (ex.StatusCode is HttpStatusCode.BadRequest)
{
return false;
}
@@ -823,11 +737,13 @@ namespace Emby.Server.Implementations.LiveTv.Listings
{
throw new ArgumentException("Username is required");
}
+
if (string.IsNullOrEmpty(info.Password))
{
throw new ArgumentException("Password is required");
}
}
+
if (validateListings)
{
if (string.IsNullOrEmpty(info.ListingsId))
@@ -857,388 +773,62 @@ namespace Emby.Server.Implementations.LiveTv.Listings
throw new Exception("ListingsId required");
}
- var token = await GetToken(info, cancellationToken);
+ var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(token))
{
throw new Exception("token required");
}
- var httpOptions = new HttpRequestOptions()
+ using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
+ options.Headers.TryAddWithoutValidation("token", token);
+
+ using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
+ await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (root == null)
{
- Url = ApiUrl + "/lineups/" + listingsId,
- UserAgent = UserAgent,
- CancellationToken = cancellationToken,
- LogErrorResponseBody = true,
- // The data can be large so give it some extra time
- TimeoutMs = 60000
- };
+ return new List<ChannelInfo>();
+ }
- httpOptions.RequestHeaders["token"] = token;
+ _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count);
+ _logger.LogInformation("Mapping Stations to Channel");
- var list = new List<ChannelInfo>();
+ var allStations = root.Stations;
- using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false))
- using (var response = httpResponse.Content)
+ var map = root.Map;
+ var list = new List<ChannelInfo>(map.Count);
+ foreach (var channel in map)
{
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false);
- _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
- _logger.LogInformation("Mapping Stations to Channel");
+ var channelNumber = GetChannelNumber(channel);
- var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>();
+ var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase));
+ var station = stationIndex == -1
+ ? new StationDto { StationId = channel.StationId }
+ : allStations[stationIndex];
- foreach (ScheduleDirect.Map map in root.map)
+ var channelInfo = new ChannelInfo
{
- var channelNumber = GetChannelNumber(map);
-
- var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
- if (station == null)
- {
- station = new ScheduleDirect.Station
- {
- stationID = map.stationID
- };
- }
-
- var channelInfo = new ChannelInfo
- {
- Id = station.stationID,
- CallSign = station.callsign,
- Number = channelNumber,
- Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
- };
-
- if (station.logo != null)
- {
- channelInfo.ImageUrl = station.logo.URL;
- }
-
- list.Add(channelInfo);
- }
- }
-
- return list;
- }
-
- private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
- {
- if (!string.IsNullOrWhiteSpace(channelName))
- {
- channelName = NormalizeName(channelName);
-
- var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
+ Id = station.StationId,
+ CallSign = station.Callsign,
+ Number = channelNumber,
+ Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name
+ };
- if (result != null)
+ if (station.Logo != null)
{
- return result;
+ channelInfo.ImageUrl = station.Logo.Url;
}
- }
- if (!string.IsNullOrWhiteSpace(channelNumber))
- {
- return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
+ list.Add(channelInfo);
}
- return null;
+ return list;
}
private static string NormalizeName(string value)
{
- return value.Replace(" ", string.Empty).Replace("-", string.Empty);
- }
-
- public class ScheduleDirect
- {
- public class Token
- {
- public int code { get; set; }
- public string message { get; set; }
- public string serverID { get; set; }
- public string token { get; set; }
- }
- public class Lineup
- {
- public string lineup { get; set; }
- public string name { get; set; }
- public string transport { get; set; }
- public string location { get; set; }
- public string uri { get; set; }
- }
-
- public class Lineups
- {
- public int code { get; set; }
- public string serverID { get; set; }
- public string datetime { get; set; }
- public List<Lineup> lineups { get; set; }
- }
-
-
- public class Headends
- {
- public string headend { get; set; }
- public string transport { get; set; }
- public string location { get; set; }
- public List<Lineup> lineups { get; set; }
- }
-
-
-
- public class Map
- {
- public string stationID { get; set; }
- public string channel { get; set; }
- public string logicalChannelNumber { get; set; }
- public int uhfVhf { get; set; }
- public int atscMajor { get; set; }
- public int atscMinor { get; set; }
- }
-
- public class Broadcaster
- {
- public string city { get; set; }
- public string state { get; set; }
- public string postalcode { get; set; }
- public string country { get; set; }
- }
-
- public class Logo
- {
- public string URL { get; set; }
- public int height { get; set; }
- public int width { get; set; }
- public string md5 { get; set; }
- }
-
- public class Station
- {
- public string stationID { get; set; }
- public string name { get; set; }
- public string callsign { get; set; }
- public List<string> broadcastLanguage { get; set; }
- public List<string> descriptionLanguage { get; set; }
- public Broadcaster broadcaster { get; set; }
- public string affiliate { get; set; }
- public Logo logo { get; set; }
- public bool? isCommercialFree { get; set; }
- }
-
- public class Metadata
- {
- public string lineup { get; set; }
- public string modified { get; set; }
- public string transport { get; set; }
- }
-
- public class Channel
- {
- public List<Map> map { get; set; }
- public List<Station> stations { get; set; }
- public Metadata metadata { get; set; }
- }
-
- public class RequestScheduleForChannel
- {
- public string stationID { get; set; }
- public List<string> date { get; set; }
- }
-
-
-
-
- public class Rating
- {
- public string body { get; set; }
- public string code { get; set; }
- }
-
- public class Multipart
- {
- public int partNumber { get; set; }
- public int totalParts { get; set; }
- }
-
- public class Program
- {
- public string programID { get; set; }
- public string airDateTime { get; set; }
- public int duration { get; set; }
- public string md5 { get; set; }
- public List<string> audioProperties { get; set; }
- public List<string> videoProperties { get; set; }
- public List<Rating> ratings { get; set; }
- public bool? @new { get; set; }
- public Multipart multipart { get; set; }
- public string liveTapeDelay { get; set; }
- public bool premiere { get; set; }
- public bool repeat { get; set; }
- public string isPremiereOrFinale { get; set; }
- }
-
-
-
- public class MetadataSchedule
- {
- public string modified { get; set; }
- public string md5 { get; set; }
- public string startDate { get; set; }
- public string endDate { get; set; }
- public int days { get; set; }
- }
-
- public class Day
- {
- public string stationID { get; set; }
- public List<Program> programs { get; set; }
- public MetadataSchedule metadata { get; set; }
-
- public Day()
- {
- programs = new List<Program>();
- }
- }
-
- //
- public class Title
- {
- public string title120 { get; set; }
- }
-
- public class EventDetails
- {
- public string subType { get; set; }
- }
-
- public class Description100
- {
- public string descriptionLanguage { get; set; }
- public string description { get; set; }
- }
-
- public class Description1000
- {
- public string descriptionLanguage { get; set; }
- public string description { get; set; }
- }
-
- public class DescriptionsProgram
- {
- public List<Description100> description100 { get; set; }
- public List<Description1000> description1000 { get; set; }
- }
-
- public class Gracenote
- {
- public int season { get; set; }
- public int episode { get; set; }
- }
-
- public class MetadataPrograms
- {
- public Gracenote Gracenote { get; set; }
- }
-
- public class ContentRating
- {
- public string body { get; set; }
- public string code { get; set; }
- }
-
- public class Cast
- {
- public string billingOrder { get; set; }
- public string role { get; set; }
- public string nameId { get; set; }
- public string personId { get; set; }
- public string name { get; set; }
- public string characterName { get; set; }
- }
-
- public class Crew
- {
- public string billingOrder { get; set; }
- public string role { get; set; }
- public string nameId { get; set; }
- public string personId { get; set; }
- public string name { get; set; }
- }
-
- public class QualityRating
- {
- public string ratingsBody { get; set; }
- public string rating { get; set; }
- public string minRating { get; set; }
- public string maxRating { get; set; }
- public string increment { get; set; }
- }
-
- public class Movie
- {
- public string year { get; set; }
- public int duration { get; set; }
- public List<QualityRating> qualityRating { get; set; }
- }
-
- public class Recommendation
- {
- public string programID { get; set; }
- public string title120 { get; set; }
- }
-
- public class ProgramDetails
- {
- public string audience { get; set; }
- public string programID { get; set; }
- public List<Title> titles { get; set; }
- public EventDetails eventDetails { get; set; }
- public DescriptionsProgram descriptions { get; set; }
- public string originalAirDate { get; set; }
- public List<string> genres { get; set; }
- public string episodeTitle150 { get; set; }
- public List<MetadataPrograms> metadata { get; set; }
- public List<ContentRating> contentRating { get; set; }
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- public string entityType { get; set; }
- public string showType { get; set; }
- public bool hasImageArtwork { get; set; }
- public string primaryImage { get; set; }
- public string thumbImage { get; set; }
- public string backdropImage { get; set; }
- public string bannerImage { get; set; }
- public string imageID { get; set; }
- public string md5 { get; set; }
- public List<string> contentAdvisory { get; set; }
- public Movie movie { get; set; }
- public List<Recommendation> recommendations { get; set; }
- }
-
- public class Caption
- {
- public string content { get; set; }
- public string lang { get; set; }
- }
-
- public class ImageData
- {
- public string width { get; set; }
- public string height { get; set; }
- public string uri { get; set; }
- public string size { get; set; }
- public string aspect { get; set; }
- public string category { get; set; }
- public string text { get; set; }
- public string primary { get; set; }
- public string tier { get; set; }
- public Caption caption { get; set; }
- }
-
- public class ShowImages
- {
- public string programID { get; set; }
- public List<ImageData> data { get; set; }
- }
-
+ return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/BroadcasterDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/BroadcasterDto.cs
new file mode 100644
index 000000000..95ac996e0
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/BroadcasterDto.cs
@@ -0,0 +1,34 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Broadcaster dto.
+ /// </summary>
+ public class BroadcasterDto
+ {
+ /// <summary>
+ /// Gets or sets the city.
+ /// </summary>
+ [JsonPropertyName("city")]
+ public string? City { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state.
+ /// </summary>
+ [JsonPropertyName("state")]
+ public string? State { get; set; }
+
+ /// <summary>
+ /// Gets or sets the postal code.
+ /// </summary>
+ [JsonPropertyName("postalCode")]
+ public string? Postalcode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the country.
+ /// </summary>
+ [JsonPropertyName("country")]
+ public string? Country { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CaptionDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CaptionDto.cs
new file mode 100644
index 000000000..f6251b9ad
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CaptionDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Caption dto.
+ /// </summary>
+ public class CaptionDto
+ {
+ /// <summary>
+ /// Gets or sets the content.
+ /// </summary>
+ [JsonPropertyName("content")]
+ public string? Content { get; set; }
+
+ /// <summary>
+ /// Gets or sets the lang.
+ /// </summary>
+ [JsonPropertyName("lang")]
+ public string? Lang { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CastDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CastDto.cs
new file mode 100644
index 000000000..0b7a2c63a
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CastDto.cs
@@ -0,0 +1,46 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Cast dto.
+ /// </summary>
+ public class CastDto
+ {
+ /// <summary>
+ /// Gets or sets the billing order.
+ /// </summary>
+ [JsonPropertyName("billingOrder")]
+ public string? BillingOrder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the role.
+ /// </summary>
+ [JsonPropertyName("role")]
+ public string? Role { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name id.
+ /// </summary>
+ [JsonPropertyName("nameId")]
+ public string? NameId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the person id.
+ /// </summary>
+ [JsonPropertyName("personId")]
+ public string? PersonId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the character name.
+ /// </summary>
+ [JsonPropertyName("characterName")]
+ public string? CharacterName { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ChannelDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ChannelDto.cs
new file mode 100644
index 000000000..87c327ed8
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ChannelDto.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Channel dto.
+ /// </summary>
+ public class ChannelDto
+ {
+ /// <summary>
+ /// Gets or sets the list of maps.
+ /// </summary>
+ [JsonPropertyName("map")]
+ public IReadOnlyList<MapDto> Map { get; set; } = Array.Empty<MapDto>();
+
+ /// <summary>
+ /// Gets or sets the list of stations.
+ /// </summary>
+ [JsonPropertyName("stations")]
+ public IReadOnlyList<StationDto> Stations { get; set; } = Array.Empty<StationDto>();
+
+ /// <summary>
+ /// Gets or sets the metadata.
+ /// </summary>
+ [JsonPropertyName("metadata")]
+ public MetadataDto? Metadata { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ContentRatingDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ContentRatingDto.cs
new file mode 100644
index 000000000..c19cd2e48
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ContentRatingDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Content rating dto.
+ /// </summary>
+ public class ContentRatingDto
+ {
+ /// <summary>
+ /// Gets or sets the body.
+ /// </summary>
+ [JsonPropertyName("body")]
+ public string? Body { get; set; }
+
+ /// <summary>
+ /// Gets or sets the code.
+ /// </summary>
+ [JsonPropertyName("code")]
+ public string? Code { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CrewDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CrewDto.cs
new file mode 100644
index 000000000..f00c9accd
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/CrewDto.cs
@@ -0,0 +1,40 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Crew dto.
+ /// </summary>
+ public class CrewDto
+ {
+ /// <summary>
+ /// Gets or sets the billing order.
+ /// </summary>
+ [JsonPropertyName("billingOrder")]
+ public string? BillingOrder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the role.
+ /// </summary>
+ [JsonPropertyName("role")]
+ public string? Role { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name id.
+ /// </summary>
+ [JsonPropertyName("nameId")]
+ public string? NameId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the person id.
+ /// </summary>
+ [JsonPropertyName("personId")]
+ public string? PersonId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DayDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DayDto.cs
new file mode 100644
index 000000000..1a371965c
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DayDto.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Day dto.
+ /// </summary>
+ public class DayDto
+ {
+ /// <summary>
+ /// Gets or sets the station id.
+ /// </summary>
+ [JsonPropertyName("stationID")]
+ public string? StationId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of programs.
+ /// </summary>
+ [JsonPropertyName("programs")]
+ public IReadOnlyList<ProgramDto> Programs { get; set; } = Array.Empty<ProgramDto>();
+
+ /// <summary>
+ /// Gets or sets the metadata schedule.
+ /// </summary>
+ [JsonPropertyName("metadata")]
+ public MetadataScheduleDto? Metadata { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description1000Dto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description1000Dto.cs
new file mode 100644
index 000000000..ca6ae7fb1
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description1000Dto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Description 1_000 dto.
+ /// </summary>
+ public class Description1000Dto
+ {
+ /// <summary>
+ /// Gets or sets the description language.
+ /// </summary>
+ [JsonPropertyName("descriptionLanguage")]
+ public string? DescriptionLanguage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the description.
+ /// </summary>
+ [JsonPropertyName("description")]
+ public string? Description { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description100Dto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description100Dto.cs
new file mode 100644
index 000000000..1577219ed
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/Description100Dto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Description 100 dto.
+ /// </summary>
+ public class Description100Dto
+ {
+ /// <summary>
+ /// Gets or sets the description language.
+ /// </summary>
+ [JsonPropertyName("descriptionLanguage")]
+ public string? DescriptionLanguage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the description.
+ /// </summary>
+ [JsonPropertyName("description")]
+ public string? Description { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DescriptionsProgramDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DescriptionsProgramDto.cs
new file mode 100644
index 000000000..eaf4a340b
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/DescriptionsProgramDto.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Descriptions program dto.
+ /// </summary>
+ public class DescriptionsProgramDto
+ {
+ /// <summary>
+ /// Gets or sets the list of description 100.
+ /// </summary>
+ [JsonPropertyName("description100")]
+ public IReadOnlyList<Description100Dto> Description100 { get; set; } = Array.Empty<Description100Dto>();
+
+ /// <summary>
+ /// Gets or sets the list of description1000.
+ /// </summary>
+ [JsonPropertyName("description1000")]
+ public IReadOnlyList<Description1000Dto> Description1000 { get; set; } = Array.Empty<Description1000Dto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/EventDetailsDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/EventDetailsDto.cs
new file mode 100644
index 000000000..fbdfb1f71
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/EventDetailsDto.cs
@@ -0,0 +1,16 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Event details dto.
+ /// </summary>
+ public class EventDetailsDto
+ {
+ /// <summary>
+ /// Gets or sets the sub type.
+ /// </summary>
+ [JsonPropertyName("subType")]
+ public string? SubType { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/GracenoteDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/GracenoteDto.cs
new file mode 100644
index 000000000..6852d89d7
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/GracenoteDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Gracenote dto.
+ /// </summary>
+ public class GracenoteDto
+ {
+ /// <summary>
+ /// Gets or sets the season.
+ /// </summary>
+ [JsonPropertyName("season")]
+ public int Season { get; set; }
+
+ /// <summary>
+ /// Gets or sets the episode.
+ /// </summary>
+ [JsonPropertyName("episode")]
+ public int Episode { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/HeadendsDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/HeadendsDto.cs
new file mode 100644
index 000000000..b9844562f
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/HeadendsDto.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Headends dto.
+ /// </summary>
+ public class HeadendsDto
+ {
+ /// <summary>
+ /// Gets or sets the headend.
+ /// </summary>
+ [JsonPropertyName("headend")]
+ public string? Headend { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transport.
+ /// </summary>
+ [JsonPropertyName("transport")]
+ public string? Transport { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location.
+ /// </summary>
+ [JsonPropertyName("location")]
+ public string? Location { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of lineups.
+ /// </summary>
+ [JsonPropertyName("lineups")]
+ public IReadOnlyList<LineupDto> Lineups { get; set; } = Array.Empty<LineupDto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ImageDataDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ImageDataDto.cs
new file mode 100644
index 000000000..a1ae3ca6d
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ImageDataDto.cs
@@ -0,0 +1,70 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Image data dto.
+ /// </summary>
+ public class ImageDataDto
+ {
+ /// <summary>
+ /// Gets or sets the width.
+ /// </summary>
+ [JsonPropertyName("width")]
+ public string? Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height.
+ /// </summary>
+ [JsonPropertyName("height")]
+ public string? Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets the uri.
+ /// </summary>
+ [JsonPropertyName("uri")]
+ public string? Uri { get; set; }
+
+ /// <summary>
+ /// Gets or sets the size.
+ /// </summary>
+ [JsonPropertyName("size")]
+ public string? Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the aspect.
+ /// </summary>
+ [JsonPropertyName("aspect")]
+ public string? Aspect { get; set; }
+
+ /// <summary>
+ /// Gets or sets the category.
+ /// </summary>
+ [JsonPropertyName("category")]
+ public string? Category { get; set; }
+
+ /// <summary>
+ /// Gets or sets the text.
+ /// </summary>
+ [JsonPropertyName("text")]
+ public string? Text { get; set; }
+
+ /// <summary>
+ /// Gets or sets the primary.
+ /// </summary>
+ [JsonPropertyName("primary")]
+ public string? Primary { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tier.
+ /// </summary>
+ [JsonPropertyName("tier")]
+ public string? Tier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the caption.
+ /// </summary>
+ [JsonPropertyName("caption")]
+ public CaptionDto? Caption { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupDto.cs
new file mode 100644
index 000000000..3dc64e5d8
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupDto.cs
@@ -0,0 +1,46 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// The lineup dto.
+ /// </summary>
+ public class LineupDto
+ {
+ /// <summary>
+ /// Gets or sets the linup.
+ /// </summary>
+ [JsonPropertyName("lineup")]
+ public string? Lineup { get; set; }
+
+ /// <summary>
+ /// Gets or sets the lineup name.
+ /// </summary>
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transport.
+ /// </summary>
+ [JsonPropertyName("transport")]
+ public string? Transport { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location.
+ /// </summary>
+ [JsonPropertyName("location")]
+ public string? Location { get; set; }
+
+ /// <summary>
+ /// Gets or sets the uri.
+ /// </summary>
+ [JsonPropertyName("uri")]
+ public string? Uri { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this lineup was deleted.
+ /// </summary>
+ [JsonPropertyName("isDeleted")]
+ public bool? IsDeleted { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupsDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupsDto.cs
new file mode 100644
index 000000000..f19081781
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LineupsDto.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Lineups dto.
+ /// </summary>
+ public class LineupsDto
+ {
+ /// <summary>
+ /// Gets or sets the response code.
+ /// </summary>
+ [JsonPropertyName("code")]
+ public int Code { get; set; }
+
+ /// <summary>
+ /// Gets or sets the server id.
+ /// </summary>
+ [JsonPropertyName("serverID")]
+ public string? ServerId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the datetime.
+ /// </summary>
+ [JsonPropertyName("datetime")]
+ public DateTime? LineupTimestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of lineups.
+ /// </summary>
+ [JsonPropertyName("lineups")]
+ public IReadOnlyList<LineupDto> Lineups { get; set; } = Array.Empty<LineupDto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LogoDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LogoDto.cs
new file mode 100644
index 000000000..fecc55e03
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/LogoDto.cs
@@ -0,0 +1,34 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Logo dto.
+ /// </summary>
+ public class LogoDto
+ {
+ /// <summary>
+ /// Gets or sets the url.
+ /// </summary>
+ [JsonPropertyName("URL")]
+ public string? Url { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height.
+ /// </summary>
+ [JsonPropertyName("height")]
+ public int Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets the width.
+ /// </summary>
+ [JsonPropertyName("width")]
+ public int Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets the md5.
+ /// </summary>
+ [JsonPropertyName("md5")]
+ public string? Md5 { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MapDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MapDto.cs
new file mode 100644
index 000000000..ffd02d474
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MapDto.cs
@@ -0,0 +1,58 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Map dto.
+ /// </summary>
+ public class MapDto
+ {
+ /// <summary>
+ /// Gets or sets the station id.
+ /// </summary>
+ [JsonPropertyName("stationID")]
+ public string? StationId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the channel.
+ /// </summary>
+ [JsonPropertyName("channel")]
+ public string? Channel { get; set; }
+
+ /// <summary>
+ /// Gets or sets the provider callsign.
+ /// </summary>
+ [JsonPropertyName("providerCallsign")]
+ public string? ProvderCallsign { get; set; }
+
+ /// <summary>
+ /// Gets or sets the logical channel number.
+ /// </summary>
+ [JsonPropertyName("logicalChannelNumber")]
+ public string? LogicalChannelNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the uhfvhf.
+ /// </summary>
+ [JsonPropertyName("uhfVhf")]
+ public int UhfVhf { get; set; }
+
+ /// <summary>
+ /// Gets or sets the atsc major.
+ /// </summary>
+ [JsonPropertyName("atscMajor")]
+ public int AtscMajor { get; set; }
+
+ /// <summary>
+ /// Gets or sets the atsc minor.
+ /// </summary>
+ [JsonPropertyName("atscMinor")]
+ public int AtscMinor { get; set; }
+
+ /// <summary>
+ /// Gets or sets the match type.
+ /// </summary>
+ [JsonPropertyName("matchType")]
+ public string? MatchType { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataDto.cs
new file mode 100644
index 000000000..40faa493c
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataDto.cs
@@ -0,0 +1,28 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Metadata dto.
+ /// </summary>
+ public class MetadataDto
+ {
+ /// <summary>
+ /// Gets or sets the linup.
+ /// </summary>
+ [JsonPropertyName("lineup")]
+ public string? Lineup { get; set; }
+
+ /// <summary>
+ /// Gets or sets the modified timestamp.
+ /// </summary>
+ [JsonPropertyName("modified")]
+ public string? Modified { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transport.
+ /// </summary>
+ [JsonPropertyName("transport")]
+ public string? Transport { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataProgramsDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataProgramsDto.cs
new file mode 100644
index 000000000..43f290156
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataProgramsDto.cs
@@ -0,0 +1,16 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Metadata programs dto.
+ /// </summary>
+ public class MetadataProgramsDto
+ {
+ /// <summary>
+ /// Gets or sets the gracenote object.
+ /// </summary>
+ [JsonPropertyName("Gracenote")]
+ public GracenoteDto? Gracenote { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataScheduleDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataScheduleDto.cs
new file mode 100644
index 000000000..04560ab55
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MetadataScheduleDto.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Metadata schedule dto.
+ /// </summary>
+ public class MetadataScheduleDto
+ {
+ /// <summary>
+ /// Gets or sets the modified timestamp.
+ /// </summary>
+ [JsonPropertyName("modified")]
+ public string? Modified { get; set; }
+
+ /// <summary>
+ /// Gets or sets the md5.
+ /// </summary>
+ [JsonPropertyName("md5")]
+ public string? Md5 { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start date.
+ /// </summary>
+ [JsonPropertyName("startDate")]
+ public DateTime? StartDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the end date.
+ /// </summary>
+ [JsonPropertyName("endDate")]
+ public DateTime? EndDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the days count.
+ /// </summary>
+ [JsonPropertyName("days")]
+ public int Days { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MovieDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MovieDto.cs
new file mode 100644
index 000000000..31bef423b
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MovieDto.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Movie dto.
+ /// </summary>
+ public class MovieDto
+ {
+ /// <summary>
+ /// Gets or sets the year.
+ /// </summary>
+ [JsonPropertyName("year")]
+ public string? Year { get; set; }
+
+ /// <summary>
+ /// Gets or sets the duration.
+ /// </summary>
+ [JsonPropertyName("duration")]
+ public int Duration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of quality rating.
+ /// </summary>
+ [JsonPropertyName("qualityRating")]
+ public IReadOnlyList<QualityRatingDto> QualityRating { get; set; } = Array.Empty<QualityRatingDto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MultipartDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MultipartDto.cs
new file mode 100644
index 000000000..e8b15dc07
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/MultipartDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Multipart dto.
+ /// </summary>
+ public class MultipartDto
+ {
+ /// <summary>
+ /// Gets or sets the part number.
+ /// </summary>
+ [JsonPropertyName("partNumber")]
+ public int PartNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the total parts.
+ /// </summary>
+ [JsonPropertyName("totalParts")]
+ public int TotalParts { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs
new file mode 100644
index 000000000..84c48f67f
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs
@@ -0,0 +1,156 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Program details dto.
+ /// </summary>
+ public class ProgramDetailsDto
+ {
+ /// <summary>
+ /// Gets or sets the audience.
+ /// </summary>
+ [JsonPropertyName("audience")]
+ public string? Audience { get; set; }
+
+ /// <summary>
+ /// Gets or sets the program id.
+ /// </summary>
+ [JsonPropertyName("programID")]
+ public string? ProgramId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of titles.
+ /// </summary>
+ [JsonPropertyName("titles")]
+ public IReadOnlyList<TitleDto> Titles { get; set; } = Array.Empty<TitleDto>();
+
+ /// <summary>
+ /// Gets or sets the event details object.
+ /// </summary>
+ [JsonPropertyName("eventDetails")]
+ public EventDetailsDto? EventDetails { get; set; }
+
+ /// <summary>
+ /// Gets or sets the descriptions.
+ /// </summary>
+ [JsonPropertyName("descriptions")]
+ public DescriptionsProgramDto? Descriptions { get; set; }
+
+ /// <summary>
+ /// Gets or sets the original air date.
+ /// </summary>
+ [JsonPropertyName("originalAirDate")]
+ public DateTime? OriginalAirDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of genres.
+ /// </summary>
+ [JsonPropertyName("genres")]
+ public IReadOnlyList<string> Genres { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the episode title.
+ /// </summary>
+ [JsonPropertyName("episodeTitle150")]
+ public string? EpisodeTitle150 { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of metadata.
+ /// </summary>
+ [JsonPropertyName("metadata")]
+ public IReadOnlyList<MetadataProgramsDto> Metadata { get; set; } = Array.Empty<MetadataProgramsDto>();
+
+ /// <summary>
+ /// Gets or sets the list of content raitings.
+ /// </summary>
+ [JsonPropertyName("contentRating")]
+ public IReadOnlyList<ContentRatingDto> ContentRating { get; set; } = Array.Empty<ContentRatingDto>();
+
+ /// <summary>
+ /// Gets or sets the list of cast.
+ /// </summary>
+ [JsonPropertyName("cast")]
+ public IReadOnlyList<CastDto> Cast { get; set; } = Array.Empty<CastDto>();
+
+ /// <summary>
+ /// Gets or sets the list of crew.
+ /// </summary>
+ [JsonPropertyName("crew")]
+ public IReadOnlyList<CrewDto> Crew { get; set; } = Array.Empty<CrewDto>();
+
+ /// <summary>
+ /// Gets or sets the entity type.
+ /// </summary>
+ [JsonPropertyName("entityType")]
+ public string? EntityType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the show type.
+ /// </summary>
+ [JsonPropertyName("showType")]
+ public string? ShowType { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether there is image artwork.
+ /// </summary>
+ [JsonPropertyName("hasImageArtwork")]
+ public bool HasImageArtwork { get; set; }
+
+ /// <summary>
+ /// Gets or sets the primary image.
+ /// </summary>
+ [JsonPropertyName("primaryImage")]
+ public string? PrimaryImage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the thumb image.
+ /// </summary>
+ [JsonPropertyName("thumbImage")]
+ public string? ThumbImage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the backdrop image.
+ /// </summary>
+ [JsonPropertyName("backdropImage")]
+ public string? BackdropImage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the banner image.
+ /// </summary>
+ [JsonPropertyName("bannerImage")]
+ public string? BannerImage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the image id.
+ /// </summary>
+ [JsonPropertyName("imageID")]
+ public string? ImageId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the md5.
+ /// </summary>
+ [JsonPropertyName("md5")]
+ public string? Md5 { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of content advisory.
+ /// </summary>
+ [JsonPropertyName("contentAdvisory")]
+ public IReadOnlyList<string> ContentAdvisory { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the movie object.
+ /// </summary>
+ [JsonPropertyName("movie")]
+ public MovieDto? Movie { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of recommendations.
+ /// </summary>
+ [JsonPropertyName("recommendations")]
+ public IReadOnlyList<RecommendationDto> Recommendations { get; set; } = Array.Empty<RecommendationDto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDto.cs
new file mode 100644
index 000000000..60389b45b
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ProgramDto.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Program dto.
+ /// </summary>
+ public class ProgramDto
+ {
+ /// <summary>
+ /// Gets or sets the program id.
+ /// </summary>
+ [JsonPropertyName("programID")]
+ public string? ProgramId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the air date time.
+ /// </summary>
+ [JsonPropertyName("airDateTime")]
+ public DateTime? AirDateTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the duration.
+ /// </summary>
+ [JsonPropertyName("duration")]
+ public int Duration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the md5.
+ /// </summary>
+ [JsonPropertyName("md5")]
+ public string? Md5 { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of audio properties.
+ /// </summary>
+ [JsonPropertyName("audioProperties")]
+ public IReadOnlyList<string> AudioProperties { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the list of video properties.
+ /// </summary>
+ [JsonPropertyName("videoProperties")]
+ public IReadOnlyList<string> VideoProperties { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the list of ratings.
+ /// </summary>
+ [JsonPropertyName("ratings")]
+ public IReadOnlyList<RatingDto> Ratings { get; set; } = Array.Empty<RatingDto>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this program is new.
+ /// </summary>
+ [JsonPropertyName("new")]
+ public bool? New { get; set; }
+
+ /// <summary>
+ /// Gets or sets the multipart object.
+ /// </summary>
+ [JsonPropertyName("multipart")]
+ public MultipartDto? Multipart { get; set; }
+
+ /// <summary>
+ /// Gets or sets the live tape delay.
+ /// </summary>
+ [JsonPropertyName("liveTapeDelay")]
+ public string? LiveTapeDelay { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this is the premiere.
+ /// </summary>
+ [JsonPropertyName("premiere")]
+ public bool Premiere { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this is a repeat.
+ /// </summary>
+ [JsonPropertyName("repeat")]
+ public bool Repeat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the premiere or finale.
+ /// </summary>
+ [JsonPropertyName("isPremiereOrFinale")]
+ public string? IsPremiereOrFinale { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/QualityRatingDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/QualityRatingDto.cs
new file mode 100644
index 000000000..c5ddcf7c5
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/QualityRatingDto.cs
@@ -0,0 +1,40 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Quality rating dto.
+ /// </summary>
+ public class QualityRatingDto
+ {
+ /// <summary>
+ /// Gets or sets the ratings body.
+ /// </summary>
+ [JsonPropertyName("ratingsBody")]
+ public string? RatingsBody { get; set; }
+
+ /// <summary>
+ /// Gets or sets the rating.
+ /// </summary>
+ [JsonPropertyName("rating")]
+ public string? Rating { get; set; }
+
+ /// <summary>
+ /// Gets or sets the min rating.
+ /// </summary>
+ [JsonPropertyName("minRating")]
+ public string? MinRating { get; set; }
+
+ /// <summary>
+ /// Gets or sets the max rating.
+ /// </summary>
+ [JsonPropertyName("maxRating")]
+ public string? MaxRating { get; set; }
+
+ /// <summary>
+ /// Gets or sets the increment.
+ /// </summary>
+ [JsonPropertyName("increment")]
+ public string? Increment { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RatingDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RatingDto.cs
new file mode 100644
index 000000000..e04b619a4
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RatingDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Rating dto.
+ /// </summary>
+ public class RatingDto
+ {
+ /// <summary>
+ /// Gets or sets the body.
+ /// </summary>
+ [JsonPropertyName("body")]
+ public string? Body { get; set; }
+
+ /// <summary>
+ /// Gets or sets the code.
+ /// </summary>
+ [JsonPropertyName("code")]
+ public string? Code { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RecommendationDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RecommendationDto.cs
new file mode 100644
index 000000000..c8f79fd1c
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RecommendationDto.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Recommendation dto.
+ /// </summary>
+ public class RecommendationDto
+ {
+ /// <summary>
+ /// Gets or sets the program id.
+ /// </summary>
+ [JsonPropertyName("programID")]
+ public string? ProgramId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the title.
+ /// </summary>
+ [JsonPropertyName("title120")]
+ public string? Title120 { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RequestScheduleForChannelDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RequestScheduleForChannelDto.cs
new file mode 100644
index 000000000..0cd05709b
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/RequestScheduleForChannelDto.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Request schedule for channel dto.
+ /// </summary>
+ public class RequestScheduleForChannelDto
+ {
+ /// <summary>
+ /// Gets or sets the station id.
+ /// </summary>
+ [JsonPropertyName("stationID")]
+ public string? StationId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of dates.
+ /// </summary>
+ [JsonPropertyName("date")]
+ public IReadOnlyList<string> Date { get; set; } = Array.Empty<string>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ShowImagesDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ShowImagesDto.cs
new file mode 100644
index 000000000..84e224b71
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/ShowImagesDto.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Show image dto.
+ /// </summary>
+ public class ShowImagesDto
+ {
+ /// <summary>
+ /// Gets or sets the program id.
+ /// </summary>
+ [JsonPropertyName("programID")]
+ public string? ProgramId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of data.
+ /// </summary>
+ [JsonPropertyName("data")]
+ public IReadOnlyList<ImageDataDto> Data { get; set; } = Array.Empty<ImageDataDto>();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/StationDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/StationDto.cs
new file mode 100644
index 000000000..d797fd49b
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/StationDto.cs
@@ -0,0 +1,66 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Station dto.
+ /// </summary>
+ public class StationDto
+ {
+ /// <summary>
+ /// Gets or sets the station id.
+ /// </summary>
+ [JsonPropertyName("stationID")]
+ public string? StationId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the callsign.
+ /// </summary>
+ [JsonPropertyName("callsign")]
+ public string? Callsign { get; set; }
+
+ /// <summary>
+ /// Gets or sets the broadcast language.
+ /// </summary>
+ [JsonPropertyName("broadcastLanguage")]
+ public IReadOnlyList<string> BroadcastLanguage { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the description language.
+ /// </summary>
+ [JsonPropertyName("descriptionLanguage")]
+ public IReadOnlyList<string> DescriptionLanguage { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the broadcaster.
+ /// </summary>
+ [JsonPropertyName("broadcaster")]
+ public BroadcasterDto? Broadcaster { get; set; }
+
+ /// <summary>
+ /// Gets or sets the affiliate.
+ /// </summary>
+ [JsonPropertyName("affiliate")]
+ public string? Affiliate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the logo.
+ /// </summary>
+ [JsonPropertyName("logo")]
+ public LogoDto? Logo { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether it is commercial free.
+ /// </summary>
+ [JsonPropertyName("isCommercialFree")]
+ public bool? IsCommercialFree { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TitleDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TitleDto.cs
new file mode 100644
index 000000000..61cd4a9b0
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TitleDto.cs
@@ -0,0 +1,16 @@
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// Title dto.
+ /// </summary>
+ public class TitleDto
+ {
+ /// <summary>
+ /// Gets or sets the title.
+ /// </summary>
+ [JsonPropertyName("title120")]
+ public string? Title120 { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TokenDto.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TokenDto.cs
new file mode 100644
index 000000000..afb999486
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirectDtos/TokenDto.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Text.Json.Serialization;
+
+namespace Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos
+{
+ /// <summary>
+ /// The token dto.
+ /// </summary>
+ public class TokenDto
+ {
+ /// <summary>
+ /// Gets or sets the response code.
+ /// </summary>
+ [JsonPropertyName("code")]
+ public int Code { get; set; }
+
+ /// <summary>
+ /// Gets or sets the response message.
+ /// </summary>
+ [JsonPropertyName("message")]
+ public string? Message { get; set; }
+
+ /// <summary>
+ /// Gets or sets the server id.
+ /// </summary>
+ [JsonPropertyName("serverID")]
+ public string? ServerId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the token.
+ /// </summary>
+ [JsonPropertyName("token")]
+ public string? Token { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current datetime.
+ /// </summary>
+ [JsonPropertyName("datetime")]
+ public DateTime? TokenTimestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the response message.
+ /// </summary>
+ [JsonPropertyName("response")]
+ public string? Response { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
index 69b10e6da..0c0ec48d9 100644
--- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
@@ -1,15 +1,20 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using Emby.XmlTv.Classes;
-using Emby.XmlTv.Entities;
+using Jellyfin.Extensions;
+using Jellyfin.XmlTv;
+using Jellyfin.XmlTv.Entities;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
@@ -22,15 +27,20 @@ namespace Emby.Server.Implementations.LiveTv.Listings
public class XmlTvListingsProvider : IListingsProvider
{
private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILogger<XmlTvListingsProvider> _logger;
private readonly IFileSystem _fileSystem;
private readonly IZipClient _zipClient;
- public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IFileSystem fileSystem, IZipClient zipClient)
+ public XmlTvListingsProvider(
+ IServerConfigurationManager config,
+ IHttpClientFactory httpClientFactory,
+ ILogger<XmlTvListingsProvider> logger,
+ IFileSystem fileSystem,
+ IZipClient zipClient)
{
_config = config;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_logger = logger;
_fileSystem = fileSystem;
_zipClient = zipClient;
@@ -50,51 +60,41 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return _config.Configuration.PreferredMetadataLanguage;
}
- private async Task<string> GetXml(string path, CancellationToken cancellationToken)
+ private async Task<string> GetXml(ListingsProviderInfo info, CancellationToken cancellationToken)
{
- _logger.LogInformation("xmltv path: {path}", path);
+ _logger.LogInformation("xmltv path: {Path}", info.Path);
- if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
+ if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- return UnzipIfNeeded(path, path);
+ return UnzipIfNeeded(info.Path, info.Path);
}
- string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml";
+ string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + "-" + info.Id + ".xml";
string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename);
if (File.Exists(cacheFile))
{
- return UnzipIfNeeded(path, cacheFile);
+ return UnzipIfNeeded(info.Path, cacheFile);
}
- _logger.LogInformation("Downloading xmltv listings from {path}", path);
-
- string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = path,
- Progress = new SimpleProgress<double>(),
- DecompressionMethod = CompressionMethod.Gzip,
-
- // It's going to come back gzipped regardless of this value
- // So we need to make sure the decompression method is set to gzip
- EnableHttpCompression = true,
-
- UserAgent = "Emby/3.0"
-
- }).ConfigureAwait(false);
+ _logger.LogInformation("Downloading xmltv listings from {Path}", info.Path);
Directory.CreateDirectory(Path.GetDirectoryName(cacheFile));
- File.Copy(tempFile, cacheFile, true);
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(info.Path, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await using (var fileStream = new FileStream(cacheFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.CopyToBufferSize, FileOptions.Asynchronous))
+ {
+ await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
+ }
- return UnzipIfNeeded(path, cacheFile);
+ return UnzipIfNeeded(info.Path, cacheFile);
}
- private string UnzipIfNeeded(string originalUrl, string file)
+ private string UnzipIfNeeded(ReadOnlySpan<char> originalUrl, string file)
{
- string ext = Path.GetExtension(originalUrl.Split('?')[0]);
+ ReadOnlySpan<char> ext = Path.GetExtension(originalUrl.LeftPart('?'));
- if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase))
+ if (ext.Equals(".gz", StringComparison.OrdinalIgnoreCase))
{
try
{
@@ -103,7 +103,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error extracting from gz file {file}", file);
+ _logger.LogError(ex, "Error extracting from gz file {File}", file);
}
try
@@ -113,7 +113,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error extracting from zip file {file}", file);
+ _logger.LogError(ex, "Error extracting from zip file {File}", file);
}
}
@@ -161,20 +161,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings
throw new ArgumentNullException(nameof(channelId));
}
- /*
- if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false))
- {
- var length = endDateUtc - startDateUtc;
- if (length.TotalDays > 1)
- {
- endDateUtc = startDateUtc.AddDays(1);
- }
- }*/
+ _logger.LogDebug("Getting xmltv programs for channel {Id}", channelId);
- _logger.LogDebug("Getting xmltv programs for channel {id}", channelId);
-
- string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
- _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {Path}", path);
var reader = new XmlTvReader(path, GetLanguage(info));
return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken)
@@ -208,7 +198,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
HasImage = program.Icon != null && !string.IsNullOrEmpty(program.Icon.Source),
OfficialRating = program.Rating != null && !string.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null,
CommunityRating = program.StarRating,
- SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N")
+ SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N", CultureInfo.InvariantCulture)
};
if (string.IsNullOrWhiteSpace(program.ProgramId))
@@ -219,19 +209,20 @@ namespace Emby.Server.Implementations.LiveTv.Listings
{
uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture);
}
+
if (programInfo.EpisodeNumber.HasValue)
{
uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
}
- programInfo.ShowId = uniqueString.GetMD5().ToString("N");
+ programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture);
// If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
if (programInfo.IsSeries
&& !programInfo.IsRepeat
&& (programInfo.EpisodeNumber ?? 0) == 0)
{
- programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
+ programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
}
}
else
@@ -240,7 +231,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
// Construct an id from the channel and start date
- programInfo.Id = string.Format("{0}_{1:O}", program.ChannelId, program.StartDate);
+ programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDate);
if (programInfo.IsMovie)
{
@@ -266,8 +257,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings
public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
{
// In theory this should never be called because there is always only one lineup
- string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false);
- _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {Path}", path);
var reader = new XmlTvReader(path, GetLanguage(info));
IEnumerable<XmlTvChannel> results = reader.GetChannels();
@@ -278,8 +269,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings
public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
{
// In theory this should never be called because there is always only one lineup
- string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
- _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {Path}", path);
var reader = new XmlTvReader(path, GetLanguage(info));
var results = reader.GetChannels();
@@ -290,7 +281,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings
Name = c.DisplayName,
ImageUrl = c.Icon != null && !string.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null,
Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number
-
}).ToList();
}
}
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs
index f9b274acb..098f193fb 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs
@@ -4,16 +4,20 @@ using MediaBrowser.Model.LiveTv;
namespace Emby.Server.Implementations.LiveTv
{
+ /// <summary>
+ /// <see cref="IConfigurationFactory" /> implementation for <see cref="LiveTvOptions" />.
+ /// </summary>
public class LiveTvConfigurationFactory : IConfigurationFactory
{
+ /// <inheritdoc />
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new ConfigurationStore[]
{
new ConfigurationStore
{
- ConfigurationType = typeof(LiveTvOptions),
- Key = "livetv"
+ ConfigurationType = typeof(LiveTvOptions),
+ Key = "livetv"
}
};
}
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
index 1144c9ab1..21e1409ac 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
@@ -1,4 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -19,9 +24,12 @@ namespace Emby.Server.Implementations.LiveTv
{
public class LiveTvDtoService
{
- private readonly ILogger _logger;
- private readonly IImageProcessor _imageProcessor;
+ private const string InternalVersionNumber = "4";
+
+ private const string ServiceName = "Emby";
+ private readonly ILogger<LiveTvDtoService> _logger;
+ private readonly IImageProcessor _imageProcessor;
private readonly IDtoService _dtoService;
private readonly IApplicationHost _appHost;
private readonly ILibraryManager _libraryManager;
@@ -29,13 +37,13 @@ namespace Emby.Server.Implementations.LiveTv
public LiveTvDtoService(
IDtoService dtoService,
IImageProcessor imageProcessor,
- ILoggerFactory loggerFactory,
+ ILogger<LiveTvDtoService> logger,
IApplicationHost appHost,
ILibraryManager libraryManager)
{
_dtoService = dtoService;
_imageProcessor = imageProcessor;
- _logger = loggerFactory.CreateLogger(nameof(LiveTvDtoService));
+ _logger = logger;
_appHost = appHost;
_libraryManager = libraryManager;
}
@@ -52,7 +60,7 @@ namespace Emby.Server.Implementations.LiveTv
ExternalId = info.Id,
ChannelId = GetInternalChannelId(service.Name, info.ChannelId),
Status = info.Status,
- SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId) ? null : GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N"),
+ SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId) ? null : GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N", CultureInfo.InvariantCulture),
PrePaddingSeconds = info.PrePaddingSeconds,
PostPaddingSeconds = info.PostPaddingSeconds,
IsPostPaddingRequired = info.IsPostPaddingRequired,
@@ -69,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(info.ProgramId))
{
- dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N");
+ dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N", CultureInfo.InvariantCulture);
}
if (program != null)
@@ -107,7 +115,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var dto = new SeriesTimerInfoDto
{
- Id = GetInternalSeriesTimerId(info.Id).ToString("N"),
+ Id = GetInternalSeriesTimerId(info.Id).ToString("N", CultureInfo.InvariantCulture),
Overview = info.Overview,
EndDate = info.EndDate,
Name = info.Name,
@@ -139,7 +147,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(info.ProgramId))
{
- dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N");
+ dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N", CultureInfo.InvariantCulture);
}
dto.DayPattern = info.Days == null ? null : GetDayPattern(info.Days.ToArray());
@@ -153,12 +161,11 @@ namespace Emby.Server.Implementations.LiveTv
{
var librarySeries = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(Series).Name },
+ IncludeItemTypes = new string[] { nameof(Series) },
Name = seriesName,
Limit = 1,
ImageTypes = new ImageType[] { ImageType.Thumb },
DtoOptions = new DtoOptions(false)
-
}).FirstOrDefault();
if (librarySeries != null)
@@ -169,13 +176,14 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
- dto.ParentThumbItemId = librarySeries.Id.ToString("N");
+ dto.ParentThumbItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error");
}
}
+
image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
if (image != null)
{
@@ -185,7 +193,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(librarySeries, image)
};
- dto.ParentBackdropItemId = librarySeries.Id.ToString("N");
+ dto.ParentBackdropItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -196,13 +204,12 @@ namespace Emby.Server.Implementations.LiveTv
var program = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
ExternalSeriesId = programSeriesId,
Limit = 1,
ImageTypes = new ImageType[] { ImageType.Primary },
DtoOptions = new DtoOptions(false),
Name = string.IsNullOrEmpty(programSeriesId) ? seriesName : null
-
}).FirstOrDefault();
if (program != null)
@@ -213,7 +220,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N");
+ dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -229,10 +236,11 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentBackdropImageTags = new string[]
- {
+ {
_imageProcessor.GetImageCacheTag(program, image)
- };
- dto.ParentBackdropItemId = program.Id.ToString("N");
+ };
+
+ dto.ParentBackdropItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -247,12 +255,11 @@ namespace Emby.Server.Implementations.LiveTv
{
var librarySeries = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(Series).Name },
+ IncludeItemTypes = new string[] { nameof(Series) },
Name = seriesName,
Limit = 1,
ImageTypes = new ImageType[] { ImageType.Thumb },
DtoOptions = new DtoOptions(false)
-
}).FirstOrDefault();
if (librarySeries != null)
@@ -263,13 +270,14 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
- dto.ParentThumbItemId = librarySeries.Id.ToString("N");
+ dto.ParentThumbItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error");
}
}
+
image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
if (image != null)
{
@@ -279,7 +287,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(librarySeries, image)
};
- dto.ParentBackdropItemId = librarySeries.Id.ToString("N");
+ dto.ParentBackdropItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -290,25 +298,23 @@ namespace Emby.Server.Implementations.LiveTv
var program = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(Series).Name },
+ IncludeItemTypes = new string[] { nameof(Series) },
Name = seriesName,
Limit = 1,
ImageTypes = new ImageType[] { ImageType.Primary },
DtoOptions = new DtoOptions(false)
-
}).FirstOrDefault();
if (program == null)
{
program = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
ExternalSeriesId = programSeriesId,
Limit = 1,
ImageTypes = new ImageType[] { ImageType.Primary },
DtoOptions = new DtoOptions(false),
Name = string.IsNullOrEmpty(programSeriesId) ? seriesName : null
-
}).FirstOrDefault();
}
@@ -320,7 +326,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N");
+ dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -339,7 +345,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(program, image)
};
- dto.ParentBackdropItemId = program.Id.ToString("N");
+ dto.ParentBackdropItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -393,8 +399,6 @@ namespace Emby.Server.Implementations.LiveTv
return null;
}
- private const string InternalVersionNumber = "4";
-
public Guid GetInternalChannelId(string serviceName, string externalId)
{
var name = serviceName + externalId + InternalVersionNumber;
@@ -402,12 +406,11 @@ namespace Emby.Server.Implementations.LiveTv
return _libraryManager.GetNewItemId(name.ToLowerInvariant(), typeof(LiveTvChannel));
}
- private const string ServiceName = "Emby";
public string GetInternalTimerId(string externalId)
{
var name = ServiceName + externalId + InternalVersionNumber;
- return name.ToLowerInvariant().GetMD5().ToString("N");
+ return name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
public Guid GetInternalSeriesTimerId(string externalId)
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
index f7ef16fb0..ea1a28fe8 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
@@ -1,20 +1,25 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Library;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Persistence;
@@ -22,96 +27,102 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
namespace Emby.Server.Implementations.LiveTv
{
/// <summary>
- /// Class LiveTvManager
+ /// Class LiveTvManager.
/// </summary>
public class LiveTvManager : ILiveTvManager, IDisposable
{
+ private const int MaxGuideDays = 14;
+ private const string ExternalServiceTag = "ExternalServiceId";
+
+ private const string EtagKey = "ProgramEtag";
+
private readonly IServerConfigurationManager _config;
- private readonly ILogger _logger;
+ private readonly ILogger<LiveTvManager> _logger;
private readonly IItemRepository _itemRepo;
private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
private readonly IUserDataManager _userDataManager;
private readonly ILibraryManager _libraryManager;
private readonly ITaskManager _taskManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly Func<IChannelManager> _channelManager;
-
- private readonly IDtoService _dtoService;
private readonly ILocalizationManager _localization;
-
+ private readonly IFileSystem _fileSystem;
+ private readonly IChannelManager _channelManager;
private readonly LiveTvDtoService _tvDtoService;
private ILiveTvService[] _services = Array.Empty<ILiveTvService>();
-
private ITunerHost[] _tunerHosts = Array.Empty<ITunerHost>();
private IListingsProvider[] _listingProviders = Array.Empty<IListingsProvider>();
- private readonly IFileSystem _fileSystem;
- public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
- public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
- public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
- public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
-
- public string GetEmbyTvActiveRecordingPath(string id)
- {
- return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
- }
+ private bool _disposed = false;
public LiveTvManager(
- IServerApplicationHost appHost,
IServerConfigurationManager config,
- ILoggerFactory loggerFactory,
+ ILogger<LiveTvManager> logger,
IItemRepository itemRepo,
- IImageProcessor imageProcessor,
IUserDataManager userDataManager,
IDtoService dtoService,
IUserManager userManager,
ILibraryManager libraryManager,
ITaskManager taskManager,
ILocalizationManager localization,
- IJsonSerializer jsonSerializer,
IFileSystem fileSystem,
- Func<IChannelManager> channelManager)
+ IChannelManager channelManager,
+ LiveTvDtoService liveTvDtoService)
{
_config = config;
- _logger = loggerFactory.CreateLogger(nameof(LiveTvManager));
+ _logger = logger;
_itemRepo = itemRepo;
_userManager = userManager;
_libraryManager = libraryManager;
_taskManager = taskManager;
_localization = localization;
- _jsonSerializer = jsonSerializer;
_fileSystem = fileSystem;
_dtoService = dtoService;
_userDataManager = userDataManager;
_channelManager = channelManager;
-
- _tvDtoService = new LiveTvDtoService(dtoService, imageProcessor, loggerFactory, appHost, _libraryManager);
+ _tvDtoService = liveTvDtoService;
}
+ public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
+
+ public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
+
+ public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
+
+ public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
+
/// <summary>
/// Gets the services.
/// </summary>
/// <value>The services.</value>
public IReadOnlyList<ILiveTvService> Services => _services;
+ public ITunerHost[] TunerHosts => _tunerHosts;
+
+ public IListingsProvider[] ListingProviders => _listingProviders;
+
private LiveTvOptions GetConfiguration()
{
return _config.GetConfiguration<LiveTvOptions>("livetv");
}
+ public string GetEmbyTvActiveRecordingPath(string id)
+ {
+ return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
+ }
+
/// <summary>
/// Adds the parts.
/// </summary>
@@ -129,51 +140,36 @@ namespace Emby.Server.Implementations.LiveTv
{
if (service is EmbyTV.EmbyTV embyTv)
{
- embyTv.TimerCreated += EmbyTv_TimerCreated;
- embyTv.TimerCancelled += EmbyTv_TimerCancelled;
+ embyTv.TimerCreated += OnEmbyTvTimerCreated;
+ embyTv.TimerCancelled += OnEmbyTvTimerCancelled;
}
}
}
- private void EmbyTv_TimerCancelled(object sender, GenericEventArgs<string> e)
+ private void OnEmbyTvTimerCancelled(object sender, GenericEventArgs<string> e)
{
var timerId = e.Argument;
- TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
- {
- Id = timerId
- }
- });
+ TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(timerId)));
}
- private void EmbyTv_TimerCreated(object sender, GenericEventArgs<TimerInfo> e)
+ private void OnEmbyTvTimerCreated(object sender, GenericEventArgs<TimerInfo> e)
{
var timer = e.Argument;
- var service = sender as ILiveTvService;
- TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
+ TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
+ new TimerEventInfo(timer.Id)
{
- ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId),
- Id = timer.Id
- }
- });
+ ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId)
+ }));
}
- public ITunerHost[] TunerHosts => _tunerHosts;
-
- public IListingsProvider[] ListingProviders => _listingProviders;
-
public List<NameIdPair> GetTunerHostTypes()
{
return _tunerHosts.OrderBy(i => i.Name).Select(i => new NameIdPair
{
Name = i.Name,
Id = i.Type
-
}).ToList();
}
@@ -195,7 +191,7 @@ namespace Emby.Server.Implementations.LiveTv
IsKids = query.IsKids,
IsSports = query.IsSports,
IsSeries = query.IsSeries,
- IncludeItemTypes = new[] { typeof(LiveTvChannel).Name },
+ IncludeItemTypes = new[] { nameof(LiveTvChannel) },
TopParentIds = new[] { topFolder.Id },
IsFavorite = query.IsFavorite,
IsLiked = query.IsLiked,
@@ -206,16 +202,16 @@ namespace Emby.Server.Implementations.LiveTv
var orderBy = internalQuery.OrderBy.ToList();
- orderBy.AddRange(query.SortBy.Select(i => new ValueTuple<string, SortOrder>(i, query.SortOrder ?? SortOrder.Ascending)));
+ orderBy.AddRange(query.SortBy.Select(i => (i, query.SortOrder ?? SortOrder.Ascending)));
if (query.EnableFavoriteSorting)
{
- orderBy.Insert(0, new ValueTuple<string, SortOrder>(ItemSortBy.IsFavoriteOrLiked, SortOrder.Descending));
+ orderBy.Insert(0, (ItemSortBy.IsFavoriteOrLiked, SortOrder.Descending));
}
if (!internalQuery.OrderBy.Any(i => string.Equals(i.Item1, ItemSortBy.SortName, StringComparison.OrdinalIgnoreCase)))
{
- orderBy.Add(new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending));
+ orderBy.Add((ItemSortBy.SortName, SortOrder.Ascending));
}
internalQuery.OrderBy = orderBy.ToArray();
@@ -256,9 +252,10 @@ namespace Emby.Server.Implementations.LiveTv
var endTime = DateTime.UtcNow;
_logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
}
+
info.RequiresClosing = true;
- var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
+ var idPrefix = service.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + "_";
info.LiveStreamId = idPrefix + info.Id;
@@ -301,9 +298,12 @@ namespace Emby.Server.Implementations.LiveTv
}
private ILiveTvService GetService(string name)
- {
- return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
- }
+ => Array.Find(_services, x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase))
+ ?? throw new KeyNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "No service with the name '{0}' can be found.",
+ name));
private static void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo)
{
@@ -354,30 +354,37 @@ namespace Emby.Server.Implementations.LiveTv
{
stream.BitRate = null;
}
+
if (stream.Channels.HasValue && stream.Channels <= 0)
{
stream.Channels = null;
}
+
if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
{
stream.AverageFrameRate = null;
}
+
if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
{
stream.RealFrameRate = null;
}
+
if (stream.Width.HasValue && stream.Width <= 0)
{
stream.Width = null;
}
+
if (stream.Height.HasValue && stream.Height <= 0)
{
stream.Height = null;
}
+
if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
{
stream.SampleRate = null;
}
+
if (stream.Level.HasValue && stream.Level <= 0)
{
stream.Level = null;
@@ -398,11 +405,11 @@ namespace Emby.Server.Implementations.LiveTv
// Set the total bitrate if not already supplied
mediaSource.InferTotalBitrate();
- if (!(service is EmbyTV.EmbyTV))
+ if (service is not EmbyTV.EmbyTV)
{
// We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
- //mediaSource.SupportsDirectPlay = false;
- //mediaSource.SupportsDirectStream = false;
+ // mediaSource.SupportsDirectPlay = false;
+ // mediaSource.SupportsDirectStream = false;
mediaSource.SupportsTranscoding = true;
foreach (var stream in mediaSource.MediaStreams)
{
@@ -419,8 +426,7 @@ namespace Emby.Server.Implementations.LiveTv
}
}
- private const string ExternalServiceTag = "ExternalServiceId";
- private LiveTvChannel GetChannel(ChannelInfo channelInfo, string serviceName, BaseItem parentFolder, CancellationToken cancellationToken)
+ private async Task<LiveTvChannel> GetChannelAsync(ChannelInfo channelInfo, string serviceName, BaseItem parentFolder, CancellationToken cancellationToken)
{
var parentFolderId = parentFolder.Id;
var isNew = false;
@@ -448,6 +454,7 @@ namespace Emby.Server.Implementations.LiveTv
{
isNew = true;
}
+
item.Tags = channelInfo.Tags;
}
@@ -455,6 +462,7 @@ namespace Emby.Server.Implementations.LiveTv
{
isNew = true;
}
+
item.ParentId = parentFolderId;
item.ChannelType = channelInfo.ChannelType;
@@ -464,24 +472,28 @@ namespace Emby.Server.Implementations.LiveTv
{
forceUpdate = true;
}
+
item.SetProviderId(ExternalServiceTag, serviceName);
if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal))
{
forceUpdate = true;
}
+
item.ExternalId = channelInfo.Id;
if (!string.Equals(channelInfo.Number, item.Number, StringComparison.Ordinal))
{
forceUpdate = true;
}
+
item.Number = channelInfo.Number;
if (!string.Equals(channelInfo.Name, item.Name, StringComparison.Ordinal))
{
forceUpdate = true;
}
+
item.Name = channelInfo.Name;
if (!item.HasImage(ImageType.Primary))
@@ -504,15 +516,13 @@ namespace Emby.Server.Implementations.LiveTv
}
else if (forceUpdate)
{
- _libraryManager.UpdateItem(item, parentFolder, ItemUpdateType.MetadataImport, cancellationToken);
+ await _libraryManager.UpdateItemAsync(item, parentFolder, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
}
return item;
}
- private const string EtagKey = "ProgramEtag";
-
- private Tuple<LiveTvProgram, bool, bool> GetProgram(ProgramInfo info, Dictionary<Guid, LiveTvProgram> allExistingPrograms, LiveTvChannel channel, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
+ private (LiveTvProgram item, bool isNew, bool isUpdated) GetProgram(ProgramInfo info, Dictionary<Guid, LiveTvProgram> allExistingPrograms, LiveTvChannel channel)
{
var id = _tvDtoService.GetInternalProgramId(info.Id);
@@ -548,13 +558,12 @@ namespace Emby.Server.Implementations.LiveTv
{
forceUpdate = true;
}
- item.ParentId = channel.Id;
- //item.ChannelType = channelType;
+ item.ParentId = channel.Id;
item.Audio = info.Audio;
item.ChannelId = channel.Id;
- item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
+ item.CommunityRating ??= info.CommunityRating;
if ((item.CommunityRating ?? 0).Equals(0))
{
item.CommunityRating = null;
@@ -567,6 +576,7 @@ namespace Emby.Server.Implementations.LiveTv
{
forceUpdate = true;
}
+
item.ExternalSeriesId = seriesId;
var isSeries = info.IsSeries || !string.IsNullOrEmpty(info.EpisodeTitle);
@@ -581,30 +591,37 @@ namespace Emby.Server.Implementations.LiveTv
{
tags.Add("Live");
}
+
if (info.IsPremiere)
{
tags.Add("Premiere");
}
+
if (info.IsNews)
{
tags.Add("News");
}
+
if (info.IsSports)
{
tags.Add("Sports");
}
+
if (info.IsKids)
{
tags.Add("Kids");
}
+
if (info.IsRepeat)
{
tags.Add("Repeat");
}
+
if (info.IsMovie)
{
tags.Add("Movie");
}
+
if (isSeries)
{
tags.Add("Series");
@@ -627,11 +644,12 @@ namespace Emby.Server.Implementations.LiveTv
{
forceUpdate = true;
}
+
item.IsSeries = isSeries;
item.Name = info.Name;
- item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
- item.Overview = item.Overview ?? info.Overview;
+ item.OfficialRating ??= info.OfficialRating;
+ item.Overview ??= info.Overview;
item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
item.ProviderIds = info.ProviderIds;
@@ -644,12 +662,14 @@ namespace Emby.Server.Implementations.LiveTv
{
forceUpdate = true;
}
+
item.StartDate = info.StartDate;
if (item.EndDate != info.EndDate)
{
forceUpdate = true;
}
+
item.EndDate = info.EndDate;
item.ProductionYear = info.ProductionYear;
@@ -666,19 +686,23 @@ namespace Emby.Server.Implementations.LiveTv
{
if (!string.IsNullOrWhiteSpace(info.ImagePath))
{
- item.SetImage(new ItemImageInfo
- {
- Path = info.ImagePath,
- Type = ImageType.Primary
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ImagePath,
+ Type = ImageType.Primary
+ },
+ 0);
}
else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
{
- item.SetImage(new ItemImageInfo
- {
- Path = info.ImageUrl,
- Type = ImageType.Primary
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ImageUrl,
+ Type = ImageType.Primary
+ },
+ 0);
}
}
@@ -686,12 +710,13 @@ namespace Emby.Server.Implementations.LiveTv
{
if (!string.IsNullOrWhiteSpace(info.ThumbImageUrl))
{
- item.SetImage(new ItemImageInfo
- {
- Path = info.ThumbImageUrl,
- Type = ImageType.Thumb
-
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ThumbImageUrl,
+ Type = ImageType.Thumb
+ },
+ 0);
}
}
@@ -699,12 +724,13 @@ namespace Emby.Server.Implementations.LiveTv
{
if (!string.IsNullOrWhiteSpace(info.LogoImageUrl))
{
- item.SetImage(new ItemImageInfo
- {
- Path = info.LogoImageUrl,
- Type = ImageType.Logo
-
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.LogoImageUrl,
+ Type = ImageType.Logo
+ },
+ 0);
}
}
@@ -712,12 +738,13 @@ namespace Emby.Server.Implementations.LiveTv
{
if (!string.IsNullOrWhiteSpace(info.BackdropImageUrl))
{
- item.SetImage(new ItemImageInfo
- {
- Path = info.BackdropImageUrl,
- Type = ImageType.Backdrop
-
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.BackdropImageUrl,
+ Type = ImageType.Backdrop
+ },
+ 0);
}
}
@@ -745,7 +772,7 @@ namespace Emby.Server.Implementations.LiveTv
item.OnMetadataChanged();
}
- return new Tuple<LiveTvProgram, bool, bool>(item, isNew, isUpdated);
+ return (item, isNew, isUpdated);
}
public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
@@ -754,7 +781,8 @@ namespace Emby.Server.Implementations.LiveTv
var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
- var list = new List<Tuple<BaseItemDto, string, string>>() {
+ var list = new List<Tuple<BaseItemDto, string, string>>
+ {
new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId)
};
@@ -769,31 +797,20 @@ namespace Emby.Server.Implementations.LiveTv
var topFolder = GetInternalLiveTvFolder(cancellationToken);
- if (query.OrderBy.Length == 0)
+ if (query.OrderBy.Count == 0)
{
- if (query.IsAiring ?? false)
- {
- // Unless something else was specified, order by start date to take advantage of a specialized index
- query.OrderBy = new ValueTuple<string, SortOrder>[]
- {
- new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending)
- };
- }
- else
+ // Unless something else was specified, order by start date to take advantage of a specialized index
+ query.OrderBy = new[]
{
- // Unless something else was specified, order by start date to take advantage of a specialized index
- query.OrderBy = new ValueTuple<string, SortOrder>[]
- {
- new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending)
- };
- }
+ (ItemSortBy.StartDate, SortOrder.Ascending)
+ };
}
RemoveFields(options);
var internalQuery = new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new[] { nameof(LiveTvProgram) },
MinEndDate = query.MinEndDate,
MinStartDate = query.MinStartDate,
MaxEndDate = query.MaxEndDate,
@@ -819,8 +836,8 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
{
- var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery { }, cancellationToken).ConfigureAwait(false);
- var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
+ var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
+ var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.Id).ToString("N", CultureInfo.InvariantCulture), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
if (seriesTimer != null)
{
internalQuery.ExternalSeriesId = seriesTimer.SeriesId;
@@ -842,13 +859,11 @@ namespace Emby.Server.Implementations.LiveTv
var returnArray = _dtoService.GetBaseItemDtos(queryResult.Items, options, user);
- var result = new QueryResult<BaseItemDto>
+ return new QueryResult<BaseItemDto>
{
Items = returnArray,
TotalRecordCount = queryResult.TotalRecordCount
};
-
- return result;
}
public QueryResult<BaseItem> GetRecommendedProgramsInternal(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken)
@@ -859,7 +874,7 @@ namespace Emby.Server.Implementations.LiveTv
var internalQuery = new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new[] { nameof(LiveTvProgram) },
IsAiring = query.IsAiring,
HasAired = query.HasAired,
IsNews = query.IsNews,
@@ -868,7 +883,7 @@ namespace Emby.Server.Implementations.LiveTv
IsSports = query.IsSports,
IsKids = query.IsKids,
EnableTotalRecordCount = query.EnableTotalRecordCount,
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) },
+ OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) },
TopParentIds = new[] { topFolder.Id },
DtoOptions = options,
GenreIds = query.GenreIds
@@ -880,7 +895,7 @@ namespace Emby.Server.Implementations.LiveTv
}
var programList = _libraryManager.QueryItems(internalQuery).Items;
- var totalCount = programList.Length;
+ var totalCount = programList.Count;
var orderedPrograms = programList.Cast<LiveTvProgram>().OrderBy(i => i.StartDate.Date);
@@ -965,11 +980,8 @@ namespace Emby.Server.Implementations.LiveTv
private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
{
- var timers = new Dictionary<string, List<TimerInfo>>();
- var seriesTimers = new Dictionary<string, List<SeriesTimerInfo>>();
-
- TimerInfo[] timerList = null;
- SeriesTimerInfo[] seriesTimerList = null;
+ IReadOnlyList<TimerInfo> timerList = null;
+ IReadOnlyList<SeriesTimerInfo> seriesTimerList = null;
foreach (var programTuple in programs)
{
@@ -977,10 +989,7 @@ namespace Emby.Server.Implementations.LiveTv
var externalProgramId = programTuple.Item2;
string externalSeriesId = programTuple.Item3;
- if (timerList == null)
- {
- timerList = (await GetTimersInternal(new TimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
- }
+ timerList ??= (await GetTimersInternal(new TimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
var foundSeriesTimer = false;
@@ -997,7 +1006,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(timer.SeriesTimerId))
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(timer.SeriesTimerId)
- .ToString("N");
+ .ToString("N", CultureInfo.InvariantCulture);
foundSeriesTimer = true;
}
@@ -1008,17 +1017,14 @@ namespace Emby.Server.Implementations.LiveTv
continue;
}
- if (seriesTimerList == null)
- {
- seriesTimerList = (await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
- }
+ seriesTimerList ??= (await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
var seriesTimer = seriesTimerList.FirstOrDefault(i => string.Equals(i.SeriesId, externalSeriesId, StringComparison.OrdinalIgnoreCase));
if (seriesTimer != null)
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(seriesTimer.Id)
- .ToString("N");
+ .ToString("N", CultureInfo.InvariantCulture);
}
}
}
@@ -1079,16 +1085,16 @@ namespace Emby.Server.Implementations.LiveTv
if (cleanDatabase)
{
- CleanDatabaseInternal(newChannelIdList.ToArray(), new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken);
- CleanDatabaseInternal(newProgramIdList.ToArray(), new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken);
+ CleanDatabaseInternal(newChannelIdList.ToArray(), new[] { nameof(LiveTvChannel) }, progress, cancellationToken);
+ CleanDatabaseInternal(newProgramIdList.ToArray(), new[] { nameof(LiveTvProgram) }, progress, cancellationToken);
}
var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
if (coreService != null)
{
- await coreService.RefreshSeriesTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
- await coreService.RefreshTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
+ await coreService.RefreshSeriesTimers(cancellationToken).ConfigureAwait(false);
+ await coreService.RefreshTimers(cancellationToken).ConfigureAwait(false);
}
// Load these now which will prefetch metadata
@@ -1119,7 +1125,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
- var item = GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolder, cancellationToken);
+ var item = await GetChannelAsync(channelInfo.Item2, channelInfo.Item1, parentFolder, cancellationToken).ConfigureAwait(false);
list.Add(item);
}
@@ -1136,7 +1142,7 @@ namespace Emby.Server.Implementations.LiveTv
double percent = numComplete;
percent /= allChannelsList.Count;
- progress.Report(5 * percent + 10);
+ progress.Report((5 * percent) + 10);
}
progress.Report(15);
@@ -1171,11 +1177,9 @@ namespace Emby.Server.Implementations.LiveTv
var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery
{
-
- IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
ChannelIds = new Guid[] { currentChannel.Id },
DtoOptions = new DtoOptions(true)
-
}).Cast<LiveTvProgram>().ToDictionary(i => i.Id);
var newPrograms = new List<LiveTvProgram>();
@@ -1183,14 +1187,14 @@ namespace Emby.Server.Implementations.LiveTv
foreach (var program in channelPrograms)
{
- var programTuple = GetProgram(program, existingPrograms, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken);
- var programItem = programTuple.Item1;
+ var programTuple = GetProgram(program, existingPrograms, currentChannel);
+ var programItem = programTuple.item;
- if (programTuple.Item2)
+ if (programTuple.isNew)
{
newPrograms.Add(programItem);
}
- else if (programTuple.Item3)
+ else if (programTuple.isUpdated)
{
updatedPrograms.Add(programItem);
}
@@ -1213,7 +1217,11 @@ namespace Emby.Server.Implementations.LiveTv
if (updatedPrograms.Count > 0)
{
- _libraryManager.UpdateItems(updatedPrograms, currentChannel, ItemUpdateType.MetadataImport, cancellationToken);
+ await _libraryManager.UpdateItemsAsync(
+ updatedPrograms,
+ currentChannel,
+ ItemUpdateType.MetadataImport,
+ cancellationToken).ConfigureAwait(false);
}
currentChannel.IsMovie = isMovie;
@@ -1226,12 +1234,13 @@ namespace Emby.Server.Implementations.LiveTv
currentChannel.AddTag("Kids");
}
- //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken);
- await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- ForceSave = true
-
- }, cancellationToken).ConfigureAwait(false);
+ await currentChannel.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
+ await currentChannel.RefreshMetadata(
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = true
+ },
+ cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -1245,7 +1254,7 @@ namespace Emby.Server.Implementations.LiveTv
numComplete++;
double percent = numComplete / (double)allChannelsList.Count;
- progress.Report(85 * percent + 15);
+ progress.Report((85 * percent) + 15);
}
progress.Report(100);
@@ -1278,12 +1287,14 @@ namespace Emby.Server.Implementations.LiveTv
if (item != null)
{
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = false,
- DeleteFromExternalProvider = false
-
- }, false);
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false,
+ DeleteFromExternalProvider = false
+ },
+ false);
}
}
@@ -1294,7 +1305,6 @@ namespace Emby.Server.Implementations.LiveTv
}
}
- private const int MaxGuideDays = 14;
private double GetGuideDays()
{
var config = GetConfiguration();
@@ -1332,28 +1342,31 @@ namespace Emby.Server.Implementations.LiveTv
{
if (query.IsMovie.Value)
{
- includeItemTypes.Add(typeof(Movie).Name);
+ includeItemTypes.Add(nameof(Movie));
}
else
{
- excludeItemTypes.Add(typeof(Movie).Name);
+ excludeItemTypes.Add(nameof(Movie));
}
}
+
if (query.IsSeries.HasValue)
{
if (query.IsSeries.Value)
{
- includeItemTypes.Add(typeof(Episode).Name);
+ includeItemTypes.Add(nameof(Episode));
}
else
{
- excludeItemTypes.Add(typeof(Episode).Name);
+ excludeItemTypes.Add(nameof(Episode));
}
}
+
if (query.IsSports ?? false)
{
genres.Add("Sports");
}
+
if (query.IsKids ?? false)
{
genres.Add("Kids");
@@ -1368,14 +1381,14 @@ namespace Emby.Server.Implementations.LiveTv
// limit = (query.Limit ?? 10) * 2;
limit = null;
- //var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray();
- //var items = allActivePaths.Select(i => _libraryManager.FindByPath(i, false)).Where(i => i != null).ToArray();
+ // var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray();
+ // var items = allActivePaths.Select(i => _libraryManager.FindByPath(i, false)).Where(i => i != null).ToArray();
- //return new QueryResult<BaseItem>
- //{
+ // return new QueryResult<BaseItem>
+ // {
// Items = items,
// TotalRecordCount = items.Length
- //};
+ // };
dtoOptions.Fields = dtoOptions.Fields.Concat(new[] { ItemFields.Tags }).Distinct().ToArray();
}
@@ -1389,7 +1402,7 @@ namespace Emby.Server.Implementations.LiveTv
IsVirtualItem = false,
Limit = limit,
StartIndex = query.StartIndex,
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
+ OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
EnableTotalRecordCount = query.EnableTotalRecordCount,
IncludeItemTypes = includeItemTypes.ToArray(),
ExcludeItemTypes = excludeItemTypes.ToArray(),
@@ -1399,29 +1412,28 @@ namespace Emby.Server.Implementations.LiveTv
if (query.IsInProgress ?? false)
{
- //TODO Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues.
+ // TODO: Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues.
result.Items = result
.Items
.OfType<Video>()
.Where(i => !i.IsCompleteMedia)
.ToArray();
- result.TotalRecordCount = result.Items.Length;
+ result.TotalRecordCount = result.Items.Count;
}
return result;
}
- public Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, ItemFields[] fields, User user = null)
+ public Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, IReadOnlyList<ItemFields> fields, User user = null)
{
var programTuples = new List<Tuple<BaseItemDto, string, string>>();
var hasChannelImage = fields.Contains(ItemFields.ChannelImage);
var hasChannelInfo = fields.Contains(ItemFields.ChannelInfo);
- foreach (var tuple in tuples)
+ foreach (var (item, dto) in programs)
{
- var program = (LiveTvProgram)tuple.Item1;
- var dto = tuple.Item2;
+ var program = (LiveTvProgram)item;
dto.StartDate = program.StartDate;
dto.EpisodeTitle = program.EpisodeTitle;
@@ -1472,7 +1484,7 @@ namespace Emby.Server.Implementations.LiveTv
dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
? null
- : _tvDtoService.GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N");
+ : _tvDtoService.GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N", CultureInfo.InvariantCulture);
dto.TimerId = string.IsNullOrEmpty(info.Id)
? null
@@ -1596,8 +1608,6 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(query.Id))
{
- var guid = new Guid(query.Id);
-
timers = timers
.Where(i => string.Equals(_tvDtoService.GetInternalTimerId(i.Item1.Id), query.Id, StringComparison.OrdinalIgnoreCase));
}
@@ -1706,22 +1716,16 @@ namespace Emby.Server.Implementations.LiveTv
if (timer == null)
{
- throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
+ throw new ResourceNotFoundException(string.Format(CultureInfo.InvariantCulture, "Timer with Id {0} not found", id));
}
var service = GetService(timer.ServiceName);
await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
- if (!(service is EmbyTV.EmbyTV))
+ if (service is not EmbyTV.EmbyTV)
{
- TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
- {
- Id = id
- }
- });
+ TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(id)));
}
}
@@ -1731,29 +1735,24 @@ namespace Emby.Server.Implementations.LiveTv
if (timer == null)
{
- throw new ResourceNotFoundException(string.Format("SeriesTimer with Id {0} not found", id));
+ throw new ResourceNotFoundException(string.Format(CultureInfo.InvariantCulture, "SeriesTimer with Id {0} not found", id));
}
var service = GetService(timer.ServiceName);
await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
- SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
- {
- Id = id
- }
- });
+ SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(id)));
}
public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
{
- var results = await GetTimers(new TimerQuery
- {
- Id = id
-
- }, cancellationToken).ConfigureAwait(false);
+ var results = await GetTimers(
+ new TimerQuery
+ {
+ Id = id
+ },
+ cancellationToken).ConfigureAwait(false);
return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
}
@@ -1801,11 +1800,7 @@ namespace Emby.Server.Implementations.LiveTv
}
var returnArray = timers
- .Select(i =>
- {
- return i.Item1;
-
- })
+ .Select(i => i.Item1)
.ToArray();
return new QueryResult<SeriesTimerInfo>
@@ -1859,7 +1854,6 @@ namespace Emby.Server.Implementations.LiveTv
}
return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
-
})
.ToArray();
@@ -1876,23 +1870,22 @@ namespace Emby.Server.Implementations.LiveTv
return _libraryManager.GetItemById(internalChannelId);
}
- public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
+ public void AddChannelInfo(IReadOnlyCollection<(BaseItemDto, LiveTvChannel)> items, DtoOptions options, User user)
{
var now = DateTime.UtcNow;
- var channelIds = tuples.Select(i => i.Item2.Id).Distinct().ToArray();
+ var channelIds = items.Select(i => i.Item2.Id).Distinct().ToArray();
var programs = options.AddCurrentProgram ? _libraryManager.GetItemList(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
+ IncludeItemTypes = new[] { nameof(LiveTvProgram) },
ChannelIds = channelIds,
MaxStartDate = now,
MinEndDate = now,
Limit = channelIds.Length,
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) },
+ OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) },
TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Id },
DtoOptions = options
-
}) : new List<BaseItem>();
RemoveFields(options);
@@ -1902,7 +1895,7 @@ namespace Emby.Server.Implementations.LiveTv
var addCurrentProgram = options.AddCurrentProgram;
- foreach (var tuple in tuples)
+ foreach (var tuple in items)
{
var dto = tuple.Item1;
var channel = tuple.Item2;
@@ -1930,7 +1923,7 @@ namespace Emby.Server.Implementations.LiveTv
foreach (var programDto in currentProgramDtos)
{
- if (currentChannelsDict.TryGetValue(programDto.ChannelId, out BaseItemDto channelDto))
+ if (programDto.ChannelId.HasValue && currentChannelsDict.TryGetValue(programDto.ChannelId.Value, out BaseItemDto channelDto))
{
channelDto.CurrentProgram = programDto;
}
@@ -1970,16 +1963,13 @@ namespace Emby.Server.Implementations.LiveTv
OriginalAirDate = program.PremiereDate,
Overview = program.Overview,
StartDate = program.StartDate,
- //ImagePath = program.ExternalImagePath,
+ // ImagePath = program.ExternalImagePath,
Name = program.Name,
OfficialRating = program.OfficialRating
};
}
- if (service == null)
- {
- service = _services.First();
- }
+ service ??= _services[0];
var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
@@ -2004,9 +1994,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
- var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
-
- return obj;
+ return _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
}
public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
@@ -2022,12 +2010,12 @@ namespace Emby.Server.Implementations.LiveTv
info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
info.Name = program.Name;
- info.ChannelId = programDto.ChannelId;
+ info.ChannelId = programDto.ChannelId ?? Guid.Empty;
info.ChannelName = programDto.ChannelName;
info.StartDate = program.StartDate;
info.Name = program.Name;
info.Overview = program.Overview;
- info.ProgramId = programDto.Id.ToString("N");
+ info.ProgramId = programDto.Id.ToString("N", CultureInfo.InvariantCulture);
info.ExternalProgramId = program.ExternalId;
if (program.EndDate.HasValue)
@@ -2061,16 +2049,13 @@ namespace Emby.Server.Implementations.LiveTv
_logger.LogInformation("New recording scheduled");
- if (!(service is EmbyTV.EmbyTV))
+ if (service is not EmbyTV.EmbyTV)
{
- TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
+ TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
+ new TimerEventInfo(newTimerId)
{
- ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
- Id = newTimerId
- }
- });
+ ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId)
+ }));
}
}
@@ -2088,21 +2073,18 @@ namespace Emby.Server.Implementations.LiveTv
if (service is ISupportsNewTimerIds supportsNewTimerIds)
{
newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
- newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N");
+ newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N", CultureInfo.InvariantCulture);
}
else
{
await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
}
- SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
- {
- Argument = new TimerEventInfo
+ SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
+ new TimerEventInfo(newTimerId)
{
- ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
- Id = newTimerId
- }
- });
+ ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId)
+ }));
}
public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
@@ -2135,15 +2117,13 @@ namespace Emby.Server.Implementations.LiveTv
};
}
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
+ /// <inheritdoc />
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
- private bool _disposed = false;
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
@@ -2187,20 +2167,19 @@ namespace Emby.Server.Implementations.LiveTv
var info = new LiveTvInfo
{
Services = services,
- IsEnabled = services.Length > 0
+ IsEnabled = services.Length > 0,
+ EnabledUsers = _userManager.Users
+ .Where(IsLiveTvEnabled)
+ .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
+ .ToArray()
};
- info.EnabledUsers = _userManager.Users
- .Where(IsLiveTvEnabled)
- .Select(i => i.Id.ToString("N"))
- .ToArray();
-
return info;
}
private bool IsLiveTvEnabled(User user)
{
- return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Length > 0);
+ return user.HasPermission(PermissionKind.EnableLiveTvAccess) && (Services.Count > 1 || GetConfiguration().TunerHosts.Length > 0);
}
public IEnumerable<User> GetEnabledUsers()
@@ -2217,9 +2196,9 @@ namespace Emby.Server.Implementations.LiveTv
/// <returns>Task.</returns>
public Task ResetTuner(string id, CancellationToken cancellationToken)
{
- var parts = id.Split(new[] { '_' }, 2);
+ var parts = id.Split('_', 2);
- var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
+ var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), parts[0], StringComparison.OrdinalIgnoreCase));
if (service == null)
{
@@ -2248,7 +2227,7 @@ namespace Emby.Server.Implementations.LiveTv
public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true)
{
- info = _jsonSerializer.DeserializeFromString<TunerHostInfo>(_jsonSerializer.SerializeToString(info));
+ info = JsonSerializer.Deserialize<TunerHostInfo>(JsonSerializer.SerializeToUtf8Bytes(info));
var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
@@ -2269,7 +2248,7 @@ namespace Emby.Server.Implementations.LiveTv
if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info);
config.TunerHosts = list.ToArray();
}
@@ -2282,7 +2261,7 @@ namespace Emby.Server.Implementations.LiveTv
if (dataSourceChanged)
{
- _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
}
return info;
@@ -2292,15 +2271,17 @@ namespace Emby.Server.Implementations.LiveTv
{
// Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider
// ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider
- info = _jsonSerializer.DeserializeFromString<ListingsProviderInfo>(_jsonSerializer.SerializeToString(info));
+ info = JsonSerializer.Deserialize<ListingsProviderInfo>(JsonSerializer.SerializeToUtf8Bytes(info));
var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
if (provider == null)
{
throw new ResourceNotFoundException(
- string.Format("Couldn't find provider of type: '{0}'", info.Type)
- );
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Couldn't find provider of type: '{0}'",
+ info.Type));
}
await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
@@ -2312,7 +2293,7 @@ namespace Emby.Server.Implementations.LiveTv
if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info);
config.ListingProviders = list.ToArray();
}
@@ -2323,7 +2304,7 @@ namespace Emby.Server.Implementations.LiveTv
_config.SaveConfiguration("livetv", config);
- _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
return info;
}
@@ -2335,23 +2316,23 @@ namespace Emby.Server.Implementations.LiveTv
config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
_config.SaveConfiguration("livetv", config);
- _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
}
- public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelId, string providerChannelId)
+ public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
{
var config = GetConfiguration();
var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
- listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelId, StringComparison.OrdinalIgnoreCase)).ToArray();
+ listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
- if (!string.Equals(tunerChannelId, providerChannelId, StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
{
var list = listingsProviderInfo.ChannelMappings.ToList();
list.Add(new NameValuePair
{
- Name = tunerChannelId,
- Value = providerChannelId
+ Name = tunerChannelNumber,
+ Value = providerChannelNumber
});
listingsProviderInfo.ChannelMappings = list.ToArray();
}
@@ -2369,12 +2350,12 @@ namespace Emby.Server.Implementations.LiveTv
var tunerChannelMappings =
tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
- _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
- return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelId, StringComparison.OrdinalIgnoreCase));
+ return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
}
- public TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> epgChannels)
+ public TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> providerChannels)
{
var result = new TunerChannelMapping
{
@@ -2387,7 +2368,7 @@ namespace Emby.Server.Implementations.LiveTv
result.Name = tunerChannel.Number + " " + result.Name;
}
- var providerChannel = EmbyTV.EmbyTV.Current.GetEpgChannelFromTunerChannel(mappings, tunerChannel, epgChannels);
+ var providerChannel = EmbyTV.EmbyTV.Current.GetEpgChannelFromTunerChannel(mappings, tunerChannel, providerChannels);
if (providerChannel != null)
{
@@ -2462,20 +2443,18 @@ namespace Emby.Server.Implementations.LiveTv
.SelectMany(i => i.Locations)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(i => _libraryManager.FindByPath(i, true))
- .Where(i => i != null)
- .Where(i => i.IsVisibleStandalone(user))
+ .Where(i => i != null && i.IsVisibleStandalone(user))
.SelectMany(i => _libraryManager.GetCollectionFolders(i))
.GroupBy(x => x.Id)
.Select(x => x.First())
.OrderBy(i => i.SortName)
.ToList();
- folders.AddRange(_channelManager().GetChannelsInternal(new MediaBrowser.Model.Channels.ChannelQuery
+ folders.AddRange(_channelManager.GetChannelsInternal(new MediaBrowser.Model.Channels.ChannelQuery
{
UserId = user.Id,
IsRecordingsFolder = true,
RefreshLatestChannelItems = refreshChannels
-
}).Items);
return folders.Cast<BaseItem>().ToList();
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
index cd1731de5..ecd28097d 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
@@ -1,63 +1,56 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv
{
public class LiveTvMediaSourceProvider : IMediaSourceProvider
{
+ // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
+ private const char StreamIdDelimiter = '_';
+
private readonly ILiveTvManager _liveTvManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly ILogger _logger;
+ private readonly ILogger<LiveTvMediaSourceProvider> _logger;
private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IMediaEncoder _mediaEncoder;
private readonly IServerApplicationHost _appHost;
- private IApplicationPaths _appPaths;
- public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost)
+ public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, ILogger<LiveTvMediaSourceProvider> logger, IMediaSourceManager mediaSourceManager, IServerApplicationHost appHost)
{
_liveTvManager = liveTvManager;
- _jsonSerializer = jsonSerializer;
+ _logger = logger;
_mediaSourceManager = mediaSourceManager;
- _mediaEncoder = mediaEncoder;
_appHost = appHost;
- _logger = loggerFactory.CreateLogger(GetType().Name);
- _appPaths = appPaths;
}
public Task<IEnumerable<MediaSourceInfo>> GetMediaSources(BaseItem item, CancellationToken cancellationToken)
{
- var baseItem = (BaseItem)item;
-
- if (baseItem.SourceType == SourceType.LiveTV)
+ if (item.SourceType == SourceType.LiveTV)
{
var activeRecordingInfo = _liveTvManager.GetActiveRecordingInfo(item.Path);
- if (string.IsNullOrEmpty(baseItem.Path) || activeRecordingInfo != null)
+ if (string.IsNullOrEmpty(item.Path) || activeRecordingInfo != null)
{
return GetMediaSourcesInternal(item, activeRecordingInfo, cancellationToken);
}
}
- return Task.FromResult<IEnumerable<MediaSourceInfo>>(Array.Empty<MediaSourceInfo>());
+ return Task.FromResult(Enumerable.Empty<MediaSourceInfo>());
}
- // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
- private const char StreamIdDelimeter = '_';
- private const string StreamIdDelimeterString = "_";
-
private async Task<IEnumerable<MediaSourceInfo>> GetMediaSourcesInternal(BaseItem item, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
{
IEnumerable<MediaSourceInfo> sources;
@@ -85,12 +78,11 @@ namespace Emby.Server.Implementations.LiveTv
}
var list = sources.ToList();
- var serverUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
foreach (var source in list)
{
source.Type = MediaSourceType.Default;
- source.BufferMs = source.BufferMs ?? 1500;
+ source.BufferMs ??= 1500;
if (source.RequiresOpening || forceRequireOpening)
{
@@ -99,28 +91,32 @@ namespace Emby.Server.Implementations.LiveTv
if (source.RequiresOpening)
{
- var openKeys = new List<string>();
- openKeys.Add(item.GetType().Name);
- openKeys.Add(item.Id.ToString("N"));
- openKeys.Add(source.Id ?? string.Empty);
- source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray());
+ var openKeys = new List<string>
+ {
+ item.GetType().Name,
+ item.Id.ToString("N", CultureInfo.InvariantCulture),
+ source.Id ?? string.Empty
+ };
+
+ source.OpenToken = string.Join(StreamIdDelimiter, openKeys);
}
// Dummy this up so that direct play checks can still run
if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http)
{
- source.Path = serverUrl;
+ source.Path = _appHost.GetSmartApiUrl(string.Empty);
}
}
- _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list));
+ _logger.LogDebug("MediaSources: {@MediaSources}", list);
return list;
}
+ /// <inheritdoc />
public async Task<ILiveStream> OpenMediaSource(string openToken, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
- var keys = openToken.Split(new[] { StreamIdDelimeter }, 3);
+ var keys = openToken.Split(StreamIdDelimiter, 3);
var mediaSourceId = keys.Length >= 3 ? keys[2] : null;
var info = await _liveTvManager.GetChannelStream(keys[1], mediaSourceId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/LiveTv/RefreshGuideScheduledTask.cs
index 542951de4..15df0dcf1 100644
--- a/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs
+++ b/Emby.Server.Implementations/LiveTv/RefreshGuideScheduledTask.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.LiveTv;
@@ -8,40 +9,61 @@ using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.LiveTv
{
- public class RefreshChannelsScheduledTask : IScheduledTask, IConfigurableScheduledTask
+ /// <summary>
+ /// The "Refresh Guide" scheduled task.
+ /// </summary>
+ public class RefreshGuideScheduledTask : IScheduledTask, IConfigurableScheduledTask
{
private readonly ILiveTvManager _liveTvManager;
private readonly IConfigurationManager _config;
- public RefreshChannelsScheduledTask(ILiveTvManager liveTvManager, IConfigurationManager config)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshGuideScheduledTask"/> class.
+ /// </summary>
+ /// <param name="liveTvManager">The live tv manager.</param>
+ /// <param name="config">The configuration manager.</param>
+ public RefreshGuideScheduledTask(ILiveTvManager liveTvManager, IConfigurationManager config)
{
_liveTvManager = liveTvManager;
_config = config;
}
+ /// <inheritdoc />
public string Name => "Refresh Guide";
+ /// <inheritdoc />
public string Description => "Downloads channel information from live tv services.";
+ /// <inheritdoc />
public string Category => "Live TV";
- public Task Execute(System.Threading.CancellationToken cancellationToken, IProgress<double> progress)
+ /// <inheritdoc />
+ public bool IsHidden => _liveTvManager.Services.Count == 1 && GetConfiguration().TunerHosts.Length == 0;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
+ /// <inheritdoc />
+ public string Key => "RefreshGuide";
+
+ /// <inheritdoc />
+ public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
var manager = (LiveTvManager)_liveTvManager;
return manager.RefreshChannels(progress, cancellationToken);
}
- /// <summary>
- /// Creates the triggers that define when the task will run
- /// </summary>
- /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
+ /// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
+ return new[]
+ {
// Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
};
}
@@ -49,13 +71,5 @@ namespace Emby.Server.Implementations.LiveTv
{
return _config.GetConfiguration<LiveTvOptions>("livetv");
}
-
- public bool IsHidden => _liveTvManager.Services.Count == 1 && GetConfiguration().TunerHosts.Length == 0;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
-
- public string Key => "RefreshGuide";
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
index 715f600a1..2b82f2462 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
@@ -12,53 +16,52 @@ using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public abstract class BaseTunerHost
{
- protected readonly IServerConfigurationManager Config;
- protected readonly ILogger Logger;
- protected IJsonSerializer JsonSerializer;
- protected readonly IFileSystem FileSystem;
-
- private readonly ConcurrentDictionary<string, ChannelCache> _channelCache =
- new ConcurrentDictionary<string, ChannelCache>(StringComparer.OrdinalIgnoreCase);
+ private readonly IMemoryCache _memoryCache;
- protected BaseTunerHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IFileSystem fileSystem)
+ protected BaseTunerHost(IServerConfigurationManager config, ILogger<BaseTunerHost> logger, IFileSystem fileSystem, IMemoryCache memoryCache)
{
Config = config;
Logger = logger;
- JsonSerializer = jsonSerializer;
+ _memoryCache = memoryCache;
FileSystem = fileSystem;
}
+ protected IServerConfigurationManager Config { get; }
+
+ protected ILogger<BaseTunerHost> Logger { get; }
+
+ protected IFileSystem FileSystem { get; }
+
public virtual bool IsSupported => true;
- protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
public abstract string Type { get; }
+ protected virtual string ChannelIdPrefix => Type + "_";
+
+ protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
+
public async Task<List<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)
{
- ChannelCache cache = null;
var key = tuner.Id;
- if (enableCache && !string.IsNullOrEmpty(key) && _channelCache.TryGetValue(key, out cache))
+ if (enableCache && !string.IsNullOrEmpty(key) && _memoryCache.TryGetValue(key, out List<ChannelInfo> cache))
{
- return cache.Channels.ToList();
+ return cache;
}
- var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
- var list = result.ToList();
- //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
+ var list = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
+ // logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
if (!string.IsNullOrEmpty(key) && list.Count > 0)
{
- cache = cache ?? new ChannelCache();
- cache.Channels = list;
- _channelCache.AddOrUpdate(key, cache, (k, v) => cache);
+ _memoryCache.Set(key, list);
}
return list;
@@ -93,11 +96,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
try
{
Directory.CreateDirectory(Path.GetDirectoryName(channelCacheFile));
- JsonSerializer.SerializeToFile(channels, channelCacheFile);
+ await using var writeStream = AsyncFile.OpenWrite(channelCacheFile);
+ await JsonSerializer.SerializeAsync(writeStream, channels, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (IOException)
{
-
}
}
}
@@ -109,12 +112,13 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
try
{
- var channels = JsonSerializer.DeserializeFromFile<List<ChannelInfo>>(channelCacheFile);
+ await using var readStream = AsyncFile.OpenRead(channelCacheFile);
+ var channels = await JsonSerializer.DeserializeAsync<List<ChannelInfo>>(readStream, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
list.AddRange(channels);
}
catch (IOException)
{
-
}
}
}
@@ -158,7 +162,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return new List<MediaSourceInfo>();
}
- protected abstract Task<ILiveStream> GetChannelStream(TunerHostInfo tuner, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
+ protected abstract Task<ILiveStream> GetChannelStream(TunerHostInfo tunerHost, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
public async Task<ILiveStream> GetChannelStream(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
@@ -217,8 +221,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
throw new LiveTvConflictException();
}
- protected virtual string ChannelIdPrefix => Type + "_";
-
protected virtual bool IsValidChannelId(string channelId)
{
if (string.IsNullOrEmpty(channelId))
@@ -233,10 +235,5 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
return Config.GetConfiguration<LiveTvOptions>("livetv");
}
-
- private class ChannelCache
- {
- public List<ChannelInfo> Channels;
- }
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs
new file mode 100644
index 000000000..0f0453189
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs
@@ -0,0 +1,23 @@
+#nullable disable
+
+namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ internal class Channels
+ {
+ public string GuideNumber { get; set; }
+
+ public string GuideName { get; set; }
+
+ public string VideoCodec { get; set; }
+
+ public string AudioCodec { get; set; }
+
+ public string URL { get; set; }
+
+ public bool Favorite { get; set; }
+
+ public bool DRM { get; set; }
+
+ public bool HD { get; set; }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs
new file mode 100644
index 000000000..42068cd34
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs
@@ -0,0 +1,42 @@
+#nullable disable
+
+using System;
+
+namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ internal class DiscoverResponse
+ {
+ public string FriendlyName { get; set; }
+
+ public string ModelNumber { get; set; }
+
+ public string FirmwareName { get; set; }
+
+ public string FirmwareVersion { get; set; }
+
+ public string DeviceID { get; set; }
+
+ public string DeviceAuth { get; set; }
+
+ public string BaseURL { get; set; }
+
+ public string LineupURL { get; set; }
+
+ public int TunerCount { get; set; }
+
+ public bool SupportsTranscoding
+ {
+ get
+ {
+ var model = ModelNumber ?? string.Empty;
+
+ if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunChannelCommands.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunChannelCommands.cs
new file mode 100644
index 000000000..069b4fab6
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunChannelCommands.cs
@@ -0,0 +1,35 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+
+namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ public class HdHomerunChannelCommands : IHdHomerunChannelCommands
+ {
+ private string? _channel;
+ private string? _profile;
+
+ public HdHomerunChannelCommands(string? channel, string? profile)
+ {
+ _channel = channel;
+ _profile = profile;
+ }
+
+ public IEnumerable<(string, string)> GetCommands()
+ {
+ if (!string.IsNullOrEmpty(_channel))
+ {
+ if (!string.IsNullOrEmpty(_profile)
+ && !string.Equals(_profile, "native", StringComparison.OrdinalIgnoreCase))
+ {
+ yield return ("vchannel", $"{_channel} transcode={_profile}");
+ }
+ else
+ {
+ yield return ("vchannel", _channel);
+ }
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
index 24b100edd..78ea7bd0f 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
@@ -1,123 +1,113 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.System;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
public class HdHomerunHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
{
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerApplicationHost _appHost;
private readonly ISocketFactory _socketFactory;
- private readonly INetworkManager _networkManager;
+ private readonly IStreamHelper _streamHelper;
+
+ private readonly JsonSerializerOptions _jsonOptions;
+
+ private readonly Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>();
public HdHomerunHost(
IServerConfigurationManager config,
- ILogger logger,
- IJsonSerializer jsonSerializer,
+ ILogger<HdHomerunHost> logger,
IFileSystem fileSystem,
- IHttpClient httpClient,
+ IHttpClientFactory httpClientFactory,
IServerApplicationHost appHost,
ISocketFactory socketFactory,
- INetworkManager networkManager)
- : base(config, logger, jsonSerializer, fileSystem)
+ IStreamHelper streamHelper,
+ IMemoryCache memoryCache)
+ : base(config, logger, fileSystem, memoryCache)
{
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_appHost = appHost;
_socketFactory = socketFactory;
- _networkManager = networkManager;
+ _streamHelper = streamHelper;
+
+ _jsonOptions = JsonDefaults.Options;
}
public string Name => "HD Homerun";
- public override string Type => DeviceType;
-
- public static string DeviceType => "hdhomerun";
+ public override string Type => "hdhomerun";
protected override string ChannelIdPrefix => "hdhr_";
- private string GetChannelId(TunerHostInfo info, Channels i)
- {
- var id = ChannelIdPrefix + i.GuideNumber;
+ private string GetChannelId(Channels i)
+ => ChannelIdPrefix + i.GuideNumber;
- return id;
- }
-
- private async Task<List<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken)
+ internal async Task<List<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken)
{
var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
- var options = new HttpRequestOptions
- {
- Url = model.LineupURL,
- CancellationToken = cancellationToken,
- BufferContent = false
- };
- using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- var lineup = await JsonSerializer.DeserializeFromStreamAsync<List<Channels>>(stream).ConfigureAwait(false) ?? new List<Channels>();
-
- if (info.ImportFavoritesOnly)
- {
- lineup = lineup.Where(i => i.Favorite).ToList();
- }
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL ?? model.BaseURL + "/lineup.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var lineup = await JsonSerializer.DeserializeAsync<List<Channels>>(stream, _jsonOptions, cancellationToken)
+ .ConfigureAwait(false) ?? new List<Channels>();
- return lineup.Where(i => !i.DRM).ToList();
- }
+ if (info.ImportFavoritesOnly)
+ {
+ lineup = lineup.Where(i => i.Favorite).ToList();
}
- }
- private class HdHomerunChannelInfo : ChannelInfo
- {
- public bool IsLegacyTuner { get; set; }
+ return lineup.Where(i => !i.DRM).ToList();
}
- protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
+ protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken)
{
- var lineup = await GetLineup(info, cancellationToken).ConfigureAwait(false);
+ var lineup = await GetLineup(tuner, cancellationToken).ConfigureAwait(false);
return lineup.Select(i => new HdHomerunChannelInfo
{
Name = i.GuideName,
Number = i.GuideNumber,
- Id = GetChannelId(info, i),
+ Id = GetChannelId(i),
IsFavorite = i.Favorite,
- TunerHostId = info.Id,
- IsHD = i.HD == 1,
+ TunerHostId = tuner.Id,
+ IsHD = i.HD,
AudioCodec = i.AudioCodec,
VideoCodec = i.VideoCodec,
ChannelType = ChannelType.TV,
IsLegacyTuner = (i.URL ?? string.Empty).StartsWith("hdhomerun", StringComparison.OrdinalIgnoreCase),
Path = i.URL
-
}).Cast<ChannelInfo>().ToList();
}
- private readonly Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>();
- private async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken)
+ internal async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken)
{
var cacheKey = info.Id;
@@ -134,39 +124,32 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
try
{
- using (var response = await _httpClient.SendAsync(new HttpRequestOptions()
- {
- Url = string.Format("{0}/discover.json", GetApiUrl(info)),
- CancellationToken = cancellationToken,
- TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(10).TotalMilliseconds),
- BufferContent = false
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(GetApiUrl(info) + "/discover.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken)
+ .ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, _jsonOptions, cancellationToken)
+ .ConfigureAwait(false);
- }, "GET").ConfigureAwait(false))
+ if (!string.IsNullOrEmpty(cacheKey))
{
- using (var stream = response.Content)
+ lock (_modelCache)
{
- var discoverResponse = await JsonSerializer.DeserializeFromStreamAsync<DiscoverResponse>(stream).ConfigureAwait(false);
-
- if (!string.IsNullOrEmpty(cacheKey))
- {
- lock (_modelCache)
- {
- _modelCache[cacheKey] = discoverResponse;
- }
- }
-
- return discoverResponse;
+ _modelCache[cacheKey] = discoverResponse;
}
}
+
+ return discoverResponse;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
- if (!throwAllExceptions && ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
+ if (!throwAllExceptions && ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{
- var defaultValue = "HDHR";
+ const string DefaultValue = "HDHR";
var response = new DiscoverResponse
{
- ModelNumber = defaultValue
+ ModelNumber = DefaultValue
};
if (!string.IsNullOrEmpty(cacheKey))
{
@@ -176,6 +159,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
_modelCache[cacheKey] = response;
}
}
+
return response;
}
@@ -187,43 +171,50 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
- using (var stream = await _httpClient.Get(new HttpRequestOptions()
- {
- Url = string.Format("{0}/tuners.html", GetApiUrl(info)),
- CancellationToken = cancellationToken,
- TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds),
- BufferContent = false
- }))
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/tuners.html", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken)
+ .ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var sr = new StreamReader(stream, System.Text.Encoding.UTF8);
+ var tuners = new List<LiveTvTunerInfo>();
+ await foreach (var line in sr.ReadAllLinesAsync().ConfigureAwait(false))
{
- var tuners = new List<LiveTvTunerInfo>();
- using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8))
+ string stripedLine = StripXML(line);
+ if (stripedLine.Contains("Channel", StringComparison.Ordinal))
{
- while (!sr.EndOfStream)
+ LiveTvTunerStatus status;
+ var index = stripedLine.IndexOf("Channel", StringComparison.OrdinalIgnoreCase);
+ var name = stripedLine.Substring(0, index - 1);
+ var currentChannel = stripedLine.Substring(index + 7);
+ if (string.Equals(currentChannel, "none", StringComparison.Ordinal))
{
- string line = StripXML(sr.ReadLine());
- if (line.Contains("Channel"))
- {
- LiveTvTunerStatus status;
- var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase);
- var name = line.Substring(0, index - 1);
- var currentChannel = line.Substring(index + 7);
- if (currentChannel != "none") { status = LiveTvTunerStatus.LiveTv; } else { status = LiveTvTunerStatus.Available; }
- tuners.Add(new LiveTvTunerInfo
- {
- Name = name,
- SourceType = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
- ProgramName = currentChannel,
- Status = status
- });
- }
+ status = LiveTvTunerStatus.LiveTv;
+ }
+ else
+ {
+ status = LiveTvTunerStatus.Available;
}
+
+ tuners.Add(new LiveTvTunerInfo
+ {
+ Name = name,
+ SourceType = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
+ ProgramName = currentChannel,
+ Status = status
+ });
}
- return tuners;
}
+
+ return tuners;
}
private static string StripXML(string source)
{
+ if (string.IsNullOrEmpty(source))
+ {
+ return string.Empty;
+ }
+
char[] buffer = new char[source.Length];
int bufferIndex = 0;
bool inside = false;
@@ -236,17 +227,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
inside = true;
continue;
}
+
if (let == '>')
{
inside = false;
continue;
}
+
if (!inside)
{
- buffer[bufferIndex] = let;
- bufferIndex++;
+ buffer[bufferIndex++] = let;
}
}
+
return new string(buffer, 0, bufferIndex);
}
@@ -254,19 +247,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
- var tuners = new List<LiveTvTunerInfo>();
+ var tuners = new List<LiveTvTunerInfo>(model.TunerCount);
var uri = new Uri(GetApiUrl(info));
- using (var manager = new HdHomerunManager(_socketFactory, Logger))
+ using (var manager = new HdHomerunManager())
{
// Legacy HdHomeruns are IPv4 only
- var ipInfo = _networkManager.ParseIpAddress(uri.Host);
+ var ipInfo = IPAddress.Parse(uri.Host);
- for (int i = 0; i < model.TunerCount; ++i)
+ for (int i = 0; i < model.TunerCount; i++)
{
- var name = string.Format("Tuner {0}", i + 1);
- var currentChannel = "none"; /// @todo Get current channel and map back to Station Id
+ var name = string.Format(CultureInfo.InvariantCulture, "Tuner {0}", i + 1);
+ var currentChannel = "none"; // TODO: Get current channel and map back to Station Id
var isAvailable = await manager.CheckTunerAvailability(ipInfo, i, cancellationToken).ConfigureAwait(false);
var status = isAvailable ? LiveTvTunerStatus.Available : LiveTvTunerStatus.LiveTv;
tuners.Add(new LiveTvTunerInfo
@@ -278,6 +271,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
});
}
}
+
return tuners;
}
@@ -304,7 +298,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
public async Task<List<LiveTvTunerInfo>> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken)
{
// TODO Need faster way to determine UDP vs HTTP
- var channels = await GetChannels(info, true, cancellationToken);
+ var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false);
var hdHomerunChannelInfo = channels.FirstOrDefault() as HdHomerunChannelInfo;
@@ -333,23 +327,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return new Uri(url).AbsoluteUri.TrimEnd('/');
}
- private class Channels
- {
- public string GuideNumber { get; set; }
- public string GuideName { get; set; }
- public string VideoCodec { get; set; }
- public string AudioCodec { get; set; }
- public string URL { get; set; }
- public bool Favorite { get; set; }
- public bool DRM { get; set; }
- public int HD { get; set; }
- }
-
- protected EncodingOptions GetEncodingOptions()
- {
- return Config.GetConfiguration<EncodingOptions>("encoding");
- }
-
private static string GetHdHrIdFromChannelId(string channelId)
{
return channelId.Split('_')[1];
@@ -436,12 +413,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
videoCodec = channelInfo.VideoCodec;
}
+
string audioCodec = channelInfo.AudioCodec;
- if (!videoBitrate.HasValue)
- {
- videoBitrate = isHd ? 15000000 : 2000000;
- }
+ videoBitrate ??= isHd ? 15000000 : 2000000;
+
int? audioBitrate = isHd ? 448000 : 192000;
// normalize
@@ -463,36 +439,36 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
id = "native";
}
- id += "_" + channelId.GetMD5().ToString("N") + "_" + url.GetMD5().ToString("N");
+
+ id += "_" + channelId.GetMD5().ToString("N", CultureInfo.InvariantCulture) + "_" + url.GetMD5().ToString("N", CultureInfo.InvariantCulture);
var mediaSource = new MediaSourceInfo
{
Path = url,
Protocol = MediaProtocol.Udp,
MediaStreams = new List<MediaStream>
- {
- new MediaStream
- {
- Type = MediaStreamType.Video,
- // Set the index to -1 because we don't know the exact index of the video stream within the container
- Index = -1,
- IsInterlaced = isInterlaced,
- Codec = videoCodec,
- Width = width,
- Height = height,
- BitRate = videoBitrate,
- NalLengthSize = nal
-
- },
- new MediaStream
- {
- Type = MediaStreamType.Audio,
- // Set the index to -1 because we don't know the exact index of the audio stream within the container
- Index = -1,
- Codec = audioCodec,
- BitRate = audioBitrate
- }
- },
+ {
+ new MediaStream
+ {
+ Type = MediaStreamType.Video,
+ // Set the index to -1 because we don't know the exact index of the video stream within the container
+ Index = -1,
+ IsInterlaced = isInterlaced,
+ Codec = videoCodec,
+ Width = width,
+ Height = height,
+ BitRate = videoBitrate,
+ NalLengthSize = nal
+ },
+ new MediaStream
+ {
+ Type = MediaStreamType.Audio,
+ // Set the index to -1 because we don't know the exact index of the audio stream within the container
+ Index = -1,
+ Codec = audioCodec,
+ BitRate = audioBitrate
+ }
+ },
RequiresOpening = true,
RequiresClosing = true,
BufferMs = 0,
@@ -503,8 +479,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
SupportsTranscoding = true,
IsInfiniteStream = true,
IgnoreDts = true,
- //IgnoreIndex = true,
- //ReadAtNativeFramerate = true
+ // IgnoreIndex = true,
+ // ReadAtNativeFramerate = true
};
mediaSource.InferTotalBitrate();
@@ -512,79 +488,91 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return mediaSource;
}
- protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
+ protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, ChannelInfo channel, CancellationToken cancellationToken)
{
var list = new List<MediaSourceInfo>();
- var channelId = channelInfo.Id;
+ var channelId = channel.Id;
var hdhrId = GetHdHrIdFromChannelId(channelId);
- var hdHomerunChannelInfo = channelInfo as HdHomerunChannelInfo;
-
- var isLegacyTuner = hdHomerunChannelInfo != null && hdHomerunChannelInfo.IsLegacyTuner;
-
- if (isLegacyTuner)
+ if (channel is HdHomerunChannelInfo hdHomerunChannelInfo && hdHomerunChannelInfo.IsLegacyTuner)
{
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "native"));
}
else
{
- try
- {
- var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
+ var modelInfo = await GetModelInfo(tuner, false, cancellationToken).ConfigureAwait(false);
- if (modelInfo != null && modelInfo.SupportsTranscoding)
+ if (modelInfo != null && modelInfo.SupportsTranscoding)
+ {
+ if (tuner.AllowHWTranscoding)
{
- if (info.AllowHWTranscoding)
- {
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "heavy"));
-
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet540"));
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet480"));
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet360"));
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet240"));
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "mobile"));
- }
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "heavy"));
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "internet540"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "internet480"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "internet360"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "internet240"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "mobile"));
}
- }
- catch
- {
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "native"));
}
if (list.Count == 0)
{
- list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
+ list.Add(GetMediaSource(tuner, hdhrId, channel, "native"));
}
}
return list;
}
- protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
+ protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo tunerHost, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
- var profile = streamId.Split('_')[0];
+ var tunerCount = tunerHost.TunerCount;
+
+ if (tunerCount > 0)
+ {
+ var tunerHostId = tunerHost.Id;
+ var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
+
+ if (liveStreams.Count() >= tunerCount)
+ {
+ throw new LiveTvConflictException("HDHomeRun simultaneous stream limit has been reached.");
+ }
+ }
+
+ var profile = streamId.AsSpan().LeftPart('_').ToString();
- Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile);
+ Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channel.Id, streamId, profile);
- var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id);
+ var hdhrId = GetHdHrIdFromChannelId(channel.Id);
- var hdhomerunChannel = channelInfo as HdHomerunChannelInfo;
+ var hdhomerunChannel = channel as HdHomerunChannelInfo;
- var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
+ var modelInfo = await GetModelInfo(tunerHost, false, cancellationToken).ConfigureAwait(false);
if (!modelInfo.SupportsTranscoding)
{
profile = "native";
}
- var mediaSource = GetMediaSource(info, hdhrId, channelInfo, profile);
+ var mediaSource = GetMediaSource(tunerHost, hdhrId, channel, profile);
if (hdhomerunChannel != null && hdhomerunChannel.IsLegacyTuner)
{
- return new HdHomerunUdpStream(mediaSource, info, streamId, new LegacyHdHomerunChannelCommands(hdhomerunChannel.Path), modelInfo.TunerCount, FileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost, _socketFactory, _networkManager);
+ return new HdHomerunUdpStream(
+ mediaSource,
+ tunerHost,
+ streamId,
+ new LegacyHdHomerunChannelCommands(hdhomerunChannel.Path),
+ modelInfo.TunerCount,
+ FileSystem,
+ Logger,
+ Config,
+ _appHost,
+ _streamHelper);
}
var enableHttpStream = true;
@@ -592,19 +580,39 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
mediaSource.Protocol = MediaProtocol.Http;
- var httpUrl = channelInfo.Path;
+ var httpUrl = channel.Path;
// If raw was used, the tuner doesn't support params
if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase))
{
httpUrl += "?transcode=" + profile;
}
- mediaSource.Path = httpUrl;
- return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost);
- }
+ mediaSource.Path = httpUrl;
- return new HdHomerunUdpStream(mediaSource, info, streamId, new HdHomerunChannelCommands(hdhomerunChannel.Number, profile), modelInfo.TunerCount, FileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost, _socketFactory, _networkManager);
+ return new SharedHttpStream(
+ mediaSource,
+ tunerHost,
+ streamId,
+ FileSystem,
+ _httpClientFactory,
+ Logger,
+ Config,
+ _appHost,
+ _streamHelper);
+ }
+
+ return new HdHomerunUdpStream(
+ mediaSource,
+ tunerHost,
+ streamId,
+ new HdHomerunChannelCommands(hdhomerunChannel.Number, profile),
+ modelInfo.TunerCount,
+ FileSystem,
+ Logger,
+ Config,
+ _appHost,
+ _streamHelper);
}
public async Task Validate(TunerHostInfo info)
@@ -620,7 +628,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var modelInfo = await GetModelInfo(info, true, CancellationToken.None).ConfigureAwait(false);
info.DeviceId = modelInfo.DeviceID;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
{
@@ -632,34 +640,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
- public class DiscoverResponse
- {
- public string FriendlyName { get; set; }
- public string ModelNumber { get; set; }
- public string FirmwareName { get; set; }
- public string FirmwareVersion { get; set; }
- public string DeviceID { get; set; }
- public string DeviceAuth { get; set; }
- public string BaseURL { get; set; }
- public string LineupURL { get; set; }
- public int TunerCount { get; set; }
-
- public bool SupportsTranscoding
- {
- get
- {
- var model = ModelNumber ?? string.Empty;
-
- if ((model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1))
- {
- return true;
- }
-
- return false;
- }
- }
- }
-
public async Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
{
lock (_modelCache)
@@ -667,7 +647,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
_modelCache.Clear();
}
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(discoveryDurationMs).Token, cancellationToken).Token;
+ using var timedCancellationToken = new CancellationTokenSource(discoveryDurationMs);
+ using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timedCancellationToken.Token, cancellationToken);
+ cancellationToken = linkedCancellationTokenSource.Token;
var list = new List<TunerHostInfo>();
// Create udp broadcast discovery message
@@ -677,13 +659,13 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
// Need a way to set the Receive timeout on the socket otherwise this might never timeout?
try
{
- await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IpEndPointInfo(new IpAddressInfo("255.255.255.255", IpAddressFamily.InterNetwork), 65001), cancellationToken);
+ await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false);
var receiveBuffer = new byte[8192];
while (!cancellationToken.IsCancellationRequested)
{
var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
- var deviceIp = response.RemoteEndPoint.IpAddress.Address;
+ var deviceIp = response.RemoteEndPoint.Address.ToString();
// check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte
if (response.ReceivedBytes > 13 && response.Buffer[1] == 3)
@@ -698,21 +680,21 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
}
-
}
catch (OperationCanceledException)
{
}
- catch
+ catch (Exception ex)
{
// Socket timeout indicates all messages have been received.
+ Logger.LogError(ex, "Error while sending discovery message");
}
}
return list;
}
- private async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken)
+ internal async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken)
{
var hostInfo = new TunerHostInfo
{
@@ -720,21 +702,18 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
Url = url
};
- try
- {
- var modelInfo = await GetModelInfo(hostInfo, false, cancellationToken).ConfigureAwait(false);
+ var modelInfo = await GetModelInfo(hostInfo, false, cancellationToken).ConfigureAwait(false);
- hostInfo.DeviceId = modelInfo.DeviceID;
- hostInfo.FriendlyName = modelInfo.FriendlyName;
+ hostInfo.DeviceId = modelInfo.DeviceID;
+ hostInfo.FriendlyName = modelInfo.FriendlyName;
+ hostInfo.TunerCount = modelInfo.TunerCount;
- return hostInfo;
- }
- catch
- {
- // logged at lower levels
- }
+ return hostInfo;
+ }
- return null;
+ private class HdHomerunChannelInfo : ChannelInfo
+ {
+ public bool IsLegacyTuner { get; set; }
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
index 2205c0ecc..f9d151a81 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
@@ -1,203 +1,150 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Generic;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Globalization;
using System.Net;
+using System.Net.Sockets;
using System.Text;
-using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Common;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
- public interface IHdHomerunChannelCommands
- {
- IEnumerable<Tuple<string, string>> GetCommands();
- }
-
- public class LegacyHdHomerunChannelCommands : IHdHomerunChannelCommands
- {
- private string _channel;
- private string _program;
- public LegacyHdHomerunChannelCommands(string url)
- {
- // parse url for channel and program
- var regExp = new Regex(@"\/ch(\d+)-?(\d*)");
- var match = regExp.Match(url);
- if (match.Success)
- {
- _channel = match.Groups[1].Value;
- _program = match.Groups[2].Value;
- }
- }
-
- public IEnumerable<Tuple<string, string>> GetCommands()
- {
- var commands = new List<Tuple<string, string>>();
-
- if (!string.IsNullOrEmpty(_channel))
- commands.Add(Tuple.Create("channel", _channel));
-
- if (!string.IsNullOrEmpty(_program))
- commands.Add(Tuple.Create("program", _program));
- return commands;
- }
- }
-
- public class HdHomerunChannelCommands : IHdHomerunChannelCommands
+ public sealed class HdHomerunManager : IDisposable
{
- private string _channel;
- private string _profile;
+ public const int HdHomeRunPort = 65001;
- public HdHomerunChannelCommands(string channel, string profile)
- {
- _channel = channel;
- _profile = profile;
- }
-
- public IEnumerable<Tuple<string, string>> GetCommands()
- {
- var commands = new List<Tuple<string, string>>();
-
- if (!string.IsNullOrEmpty(_channel))
- {
- if (!string.IsNullOrEmpty(_profile) && !string.Equals(_profile, "native", StringComparison.OrdinalIgnoreCase))
- {
- commands.Add(Tuple.Create("vchannel", string.Format("{0} transcode={1}", _channel, _profile)));
- }
- else
- {
- commands.Add(Tuple.Create("vchannel", _channel));
- }
- }
-
- return commands;
- }
- }
-
- public class HdHomerunManager : IDisposable
- {
- public static int HdHomeRunPort = 65001;
// Message constants
- private static byte GetSetName = 3;
- private static byte GetSetValue = 4;
- private static byte GetSetLockkey = 21;
- private static ushort GetSetRequest = 4;
- private static ushort GetSetReply = 5;
+ private const byte GetSetName = 3;
+ private const byte GetSetValue = 4;
+ private const byte GetSetLockkey = 21;
+ private const ushort GetSetRequest = 4;
+ private const ushort GetSetReply = 5;
private uint? _lockkey = null;
private int _activeTuner = -1;
- private readonly ISocketFactory _socketFactory;
- private IpAddressInfo _remoteIp;
+ private IPEndPoint _remoteEndPoint;
- private ILogger _logger;
- private ISocket _currentTcpSocket;
-
- public HdHomerunManager(ISocketFactory socketFactory, ILogger logger)
- {
- _socketFactory = socketFactory;
- _logger = logger;
- }
+ private TcpClient _tcpClient;
public void Dispose()
{
- using (var socket = _currentTcpSocket)
+ using (var socket = _tcpClient)
{
if (socket != null)
{
- _currentTcpSocket = null;
+ _tcpClient = null;
- var task = StopStreaming(socket);
- Task.WaitAll(task);
+ StopStreaming(socket).GetAwaiter().GetResult();
}
}
- }
- public async Task<bool> CheckTunerAvailability(IpAddressInfo remoteIp, int tuner, CancellationToken cancellationToken)
- {
- using (var socket = _socketFactory.CreateTcpSocket(remoteIp, HdHomeRunPort))
- {
- return await CheckTunerAvailability(socket, remoteIp, tuner, cancellationToken).ConfigureAwait(false);
- }
+ GC.SuppressFinalize(this);
}
- private static async Task<bool> CheckTunerAvailability(ISocket socket, IpAddressInfo remoteIp, int tuner, CancellationToken cancellationToken)
+ public async Task<bool> CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken)
{
- var ipEndPoint = new IpEndPointInfo(remoteIp, HdHomeRunPort);
+ using var client = new TcpClient();
+ client.Connect(remoteIp, HdHomeRunPort);
- var lockkeyMsg = CreateGetMessage(tuner, "lockkey");
- await socket.SendToAsync(lockkeyMsg, 0, lockkeyMsg.Length, ipEndPoint, cancellationToken);
+ using var stream = client.GetStream();
+ return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false);
+ }
- var receiveBuffer = new byte[8192];
- var response = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
+ private static async Task<bool> CheckTunerAvailability(NetworkStream stream, int tuner, CancellationToken cancellationToken)
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
+ try
+ {
+ var msgLen = WriteGetMessage(buffer, tuner, "lockkey");
+ await stream.WriteAsync(buffer.AsMemory(0, msgLen), cancellationToken).ConfigureAwait(false);
- ParseReturnMessage(response.Buffer, response.ReceivedBytes, out string returnVal);
+ int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
- return string.Equals(returnVal, "none", StringComparison.OrdinalIgnoreCase);
+ return VerifyReturnValueOfGetSet(buffer.AsSpan(receivedBytes), "none");
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
}
- public async Task StartStreaming(IpAddressInfo remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken)
+ public async Task StartStreaming(IPAddress remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken)
{
- _remoteIp = remoteIp;
-
- var tcpClient = _socketFactory.CreateTcpSocket(_remoteIp, HdHomeRunPort);
- _currentTcpSocket = tcpClient;
+ _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort);
- var receiveBuffer = new byte[8192];
+ _tcpClient = new TcpClient();
+ _tcpClient.Connect(_remoteEndPoint);
if (!_lockkey.HasValue)
{
- var rand = new Random();
- _lockkey = (uint)rand.Next();
+ _lockkey = (uint)Random.Shared.Next();
}
var lockKeyValue = _lockkey.Value;
+ var stream = _tcpClient.GetStream();
- var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort);
-
- for (int i = 0; i < numTuners; ++i)
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
+ try
{
- if (!await CheckTunerAvailability(tcpClient, _remoteIp, i, cancellationToken).ConfigureAwait(false))
- continue;
-
- _activeTuner = i;
- var lockKeyString = string.Format("{0:d}", lockKeyValue);
- var lockkeyMsg = CreateSetMessage(i, "lockkey", lockKeyString, null);
- await tcpClient.SendToAsync(lockkeyMsg, 0, lockkeyMsg.Length, ipEndPoint, cancellationToken).ConfigureAwait(false);
- var response = await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
- // parse response to make sure it worked
- if (!ParseReturnMessage(response.Buffer, response.ReceivedBytes, out var returnVal))
- continue;
-
- var commandList = commands.GetCommands();
- foreach (Tuple<string, string> command in commandList)
+ for (int i = 0; i < numTuners; ++i)
{
- var channelMsg = CreateSetMessage(i, command.Item1, command.Item2, lockKeyValue);
- await tcpClient.SendToAsync(channelMsg, 0, channelMsg.Length, ipEndPoint, cancellationToken).ConfigureAwait(false);
- response = await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
+ if (!await CheckTunerAvailability(stream, i, cancellationToken).ConfigureAwait(false))
+ {
+ continue;
+ }
+
+ _activeTuner = i;
+ var lockKeyString = string.Format(CultureInfo.InvariantCulture, "{0:d}", lockKeyValue);
+ var lockkeyMsgLen = WriteSetMessage(buffer, i, "lockkey", lockKeyString, null);
+ await stream.WriteAsync(buffer.AsMemory(0, lockkeyMsgLen), cancellationToken).ConfigureAwait(false);
+ int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
+
// parse response to make sure it worked
- if (!ParseReturnMessage(response.Buffer, response.ReceivedBytes, out returnVal))
+ if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
{
- await ReleaseLockkey(tcpClient, lockKeyValue).ConfigureAwait(false);
continue;
}
- }
+ foreach (var command in commands.GetCommands())
+ {
+ var channelMsgLen = WriteSetMessage(buffer, i, command.Item1, command.Item2, lockKeyValue);
+ await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false);
+ receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
+
+ // parse response to make sure it worked
+ if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
+ {
+ await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false);
+ continue;
+ }
+ }
- var targetValue = string.Format("rtp://{0}:{1}", localIp, localPort);
- var targetMsg = CreateSetMessage(i, "target", targetValue, lockKeyValue);
+ var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort);
+ var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue);
- await tcpClient.SendToAsync(targetMsg, 0, targetMsg.Length, ipEndPoint, cancellationToken).ConfigureAwait(false);
- response = await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
- // parse response to make sure it worked
- if (!ParseReturnMessage(response.Buffer, response.ReceivedBytes, out returnVal))
- {
- await ReleaseLockkey(tcpClient, lockKeyValue).ConfigureAwait(false);
- continue;
- }
+ await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false);
+ receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
- return;
+ // parse response to make sure it worked
+ if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
+ {
+ await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false);
+ continue;
+ }
+
+ return;
+ }
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
}
_activeTuner = -1;
@@ -207,286 +154,201 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
public async Task ChangeChannel(IHdHomerunChannelCommands commands, CancellationToken cancellationToken)
{
if (!_lockkey.HasValue)
+ {
return;
+ }
- using (var tcpClient = _socketFactory.CreateTcpSocket(_remoteIp, HdHomeRunPort))
- {
- var commandList = commands.GetCommands();
- var receiveBuffer = new byte[8192];
+ using var tcpClient = new TcpClient();
+ tcpClient.Connect(_remoteEndPoint);
- foreach (Tuple<string, string> command in commandList)
+ using var stream = tcpClient.GetStream();
+ var commandList = commands.GetCommands();
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
+ try
+ {
+ foreach (var command in commandList)
{
- var channelMsg = CreateSetMessage(_activeTuner, command.Item1, command.Item2, _lockkey);
- await tcpClient.SendToAsync(channelMsg, 0, channelMsg.Length, new IpEndPointInfo(_remoteIp, HdHomeRunPort), cancellationToken).ConfigureAwait(false);
- var response = await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
+ var channelMsgLen = WriteSetMessage(buffer, _activeTuner, command.Item1, command.Item2, _lockkey);
+ await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false);
+ int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
+
// parse response to make sure it worked
- if (!ParseReturnMessage(response.Buffer, response.ReceivedBytes, out string returnVal))
+ if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
{
return;
}
}
}
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
}
- public Task StopStreaming(ISocket socket)
+ public Task StopStreaming(TcpClient client)
{
var lockKey = _lockkey;
if (!lockKey.HasValue)
+ {
return Task.CompletedTask;
+ }
- return ReleaseLockkey(socket, lockKey.Value);
+ return ReleaseLockkey(client, lockKey.Value);
}
- private async Task ReleaseLockkey(ISocket tcpClient, uint lockKeyValue)
+ private async Task ReleaseLockkey(TcpClient client, uint lockKeyValue)
{
- _logger.LogInformation("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue);
+ var stream = client.GetStream();
- var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort);
-
- var releaseTarget = CreateSetMessage(_activeTuner, "target", "none", lockKeyValue);
- await tcpClient.SendToAsync(releaseTarget, 0, releaseTarget.Length, ipEndPoint, CancellationToken.None).ConfigureAwait(false);
-
- var receiveBuffer = new byte[8192];
-
- await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false);
- var releaseKeyMsg = CreateSetMessage(_activeTuner, "lockkey", "none", lockKeyValue);
- _lockkey = null;
- await tcpClient.SendToAsync(releaseKeyMsg, 0, releaseKeyMsg.Length, ipEndPoint, CancellationToken.None).ConfigureAwait(false);
- await tcpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false);
+ var buffer = ArrayPool<byte>.Shared.Rent(8192);
+ try
+ {
+ var releaseTargetLen = WriteSetMessage(buffer, _activeTuner, "target", "none", lockKeyValue);
+ await stream.WriteAsync(buffer.AsMemory(0, releaseTargetLen)).ConfigureAwait(false);
+
+ await stream.ReadAsync(buffer).ConfigureAwait(false);
+ var releaseKeyMsgLen = WriteSetMessage(buffer, _activeTuner, "lockkey", "none", lockKeyValue);
+ _lockkey = null;
+ await stream.WriteAsync(buffer.AsMemory(0, releaseKeyMsgLen)).ConfigureAwait(false);
+ await stream.ReadAsync(buffer).ConfigureAwait(false);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
}
- private static byte[] CreateGetMessage(int tuner, string name)
+ internal static int WriteGetMessage(Span<byte> buffer, int tuner, string name)
{
- var byteName = Encoding.UTF8.GetBytes(string.Format("/tuner{0}/{1}\0", tuner, name));
- int messageLength = byteName.Length + 10; // 4 bytes for header + 4 bytes for crc + 2 bytes for tag name and length
-
- var message = new byte[messageLength];
-
- int offset = InsertHeaderAndName(byteName, messageLength, message);
-
- bool flipEndian = BitConverter.IsLittleEndian;
-
- // calculate crc and insert at the end of the message
- var crcBytes = BitConverter.GetBytes(HdHomerunCrc.GetCrc32(message, messageLength - 4));
- if (flipEndian)
- Array.Reverse(crcBytes);
- Buffer.BlockCopy(crcBytes, 0, message, offset, 4);
-
- return message;
+ var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name);
+ int offset = WriteHeaderAndPayload(buffer, byteName);
+ return FinishPacket(buffer, offset);
}
- private static byte[] CreateSetMessage(int tuner, string name, string value, uint? lockkey)
+ internal static int WriteSetMessage(Span<byte> buffer, int tuner, string name, string value, uint? lockkey)
{
- var byteName = Encoding.UTF8.GetBytes(string.Format("/tuner{0}/{1}\0", tuner, name));
- var byteValue = Encoding.UTF8.GetBytes(string.Format("{0}\0", value));
-
- int messageLength = byteName.Length + byteValue.Length + 12;
- if (lockkey.HasValue)
- messageLength += 6;
-
- var message = new byte[messageLength];
-
- int offset = InsertHeaderAndName(byteName, messageLength, message);
+ var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name);
+ int offset = WriteHeaderAndPayload(buffer, byteName);
- bool flipEndian = BitConverter.IsLittleEndian;
+ buffer[offset++] = GetSetValue;
+ offset += WriteNullTerminatedString(buffer.Slice(offset), value);
- message[offset] = GetSetValue;
- offset++;
- message[offset] = Convert.ToByte(byteValue.Length);
- offset++;
- Buffer.BlockCopy(byteValue, 0, message, offset, byteValue.Length);
- offset += byteValue.Length;
if (lockkey.HasValue)
{
- message[offset] = GetSetLockkey;
- offset++;
- message[offset] = (byte)4;
- offset++;
- var lockKeyBytes = BitConverter.GetBytes(lockkey.Value);
- if (flipEndian)
- Array.Reverse(lockKeyBytes);
- Buffer.BlockCopy(lockKeyBytes, 0, message, offset, 4);
+ buffer[offset++] = GetSetLockkey;
+ buffer[offset++] = 4;
+ BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset), lockkey.Value);
offset += 4;
}
- // calculate crc and insert at the end of the message
- var crcBytes = BitConverter.GetBytes(HdHomerunCrc.GetCrc32(message, messageLength - 4));
- if (flipEndian)
- Array.Reverse(crcBytes);
- Buffer.BlockCopy(crcBytes, 0, message, offset, 4);
-
- return message;
+ return FinishPacket(buffer, offset);
}
- private static int InsertHeaderAndName(byte[] byteName, int messageLength, byte[] message)
+ internal static int WriteNullTerminatedString(Span<byte> buffer, ReadOnlySpan<char> payload)
{
- // check to see if we need to flip endiannes
- bool flipEndian = BitConverter.IsLittleEndian;
- int offset = 0;
+ int len = Encoding.UTF8.GetBytes(payload, buffer.Slice(1)) + 1;
- // create header bytes
- var getSetBytes = BitConverter.GetBytes(GetSetRequest);
- var msgLenBytes = BitConverter.GetBytes((ushort)(messageLength - 8)); // Subtrace 4 bytes for header and 4 bytes for crc
+ // TODO: variable length: this can be 2 bytes if len > 127
+ // Write length in front of value
+ buffer[0] = Convert.ToByte(len);
- if (flipEndian)
- {
- Array.Reverse(getSetBytes);
- Array.Reverse(msgLenBytes);
- }
+ // null-terminate
+ buffer[len++] = 0;
+
+ return len;
+ }
+
+ private static int WriteHeaderAndPayload(Span<byte> buffer, ReadOnlySpan<char> payload)
+ {
+ // Packet type
+ BinaryPrimitives.WriteUInt16BigEndian(buffer, GetSetRequest);
- // insert header bytes into message
- Buffer.BlockCopy(getSetBytes, 0, message, offset, 2);
- offset += 2;
- Buffer.BlockCopy(msgLenBytes, 0, message, offset, 2);
- offset += 2;
+ // We write the payload length at the end
+ int offset = 4;
- // insert tag name and length
- message[offset] = GetSetName;
- offset++;
- message[offset] = Convert.ToByte(byteName.Length);
- offset++;
+ // Tag
+ buffer[offset++] = GetSetName;
- // insert name string
- Buffer.BlockCopy(byteName, 0, message, offset, byteName.Length);
- offset += byteName.Length;
+ // Payload length + data
+ int strLen = WriteNullTerminatedString(buffer.Slice(offset), payload);
+ offset += strLen;
return offset;
}
- private static bool ParseReturnMessage(byte[] buf, int numBytes, out string returnVal)
+ private static int FinishPacket(Span<byte> buffer, int offset)
{
- returnVal = string.Empty;
+ // Payload length
+ BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(2), (ushort)(offset - 4));
- if (numBytes < 4)
- return false;
+ // calculate crc and insert at the end of the message
+ var crc = Crc32.Compute(buffer.Slice(0, offset));
+ BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc);
- var flipEndian = BitConverter.IsLittleEndian;
- int offset = 0;
- byte[] msgTypeBytes = new byte[2];
- Buffer.BlockCopy(buf, offset, msgTypeBytes, 0, msgTypeBytes.Length);
+ return offset + 4;
+ }
- if (flipEndian)
- Array.Reverse(msgTypeBytes);
+ internal static bool VerifyReturnValueOfGetSet(ReadOnlySpan<byte> buffer, string expected)
+ {
+ return TryGetReturnValueOfGetSet(buffer, out var value)
+ && string.Equals(Encoding.UTF8.GetString(value), expected, StringComparison.OrdinalIgnoreCase);
+ }
- var msgType = BitConverter.ToUInt16(msgTypeBytes, 0);
- offset += 2;
+ internal static bool TryGetReturnValueOfGetSet(ReadOnlySpan<byte> buffer, out ReadOnlySpan<byte> value)
+ {
+ value = ReadOnlySpan<byte>.Empty;
- if (msgType != GetSetReply)
+ if (buffer.Length < 8)
+ {
return false;
+ }
- byte[] msgLengthBytes = new byte[2];
- Buffer.BlockCopy(buf, offset, msgLengthBytes, 0, msgLengthBytes.Length);
- if (flipEndian)
- Array.Reverse(msgLengthBytes);
+ uint crc = BinaryPrimitives.ReadUInt32LittleEndian(buffer[^4..]);
+ if (crc != Crc32.Compute(buffer[..^4]))
+ {
+ return false;
+ }
- var msgLength = BitConverter.ToUInt16(msgLengthBytes, 0);
- offset += 2;
+ if (BinaryPrimitives.ReadUInt16BigEndian(buffer) != GetSetReply)
+ {
+ return false;
+ }
- if (numBytes < msgLength + 8)
+ var msgLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(2));
+ if (buffer.Length != 2 + 2 + 4 + msgLength)
+ {
return false;
+ }
- var nameTag = buf[offset];
- offset++;
+ var offset = 4;
+ if (buffer[offset++] != GetSetName)
+ {
+ return false;
+ }
- var nameLength = buf[offset];
- offset++;
+ var nameLength = buffer[offset++];
+ if (buffer.Length < 4 + 1 + offset + nameLength)
+ {
+ return false;
+ }
- // skip the name field to get to value for return
offset += nameLength;
- var valueTag = buf[offset];
- offset++;
-
- var valueLength = buf[offset];
- offset++;
-
- returnVal = Encoding.UTF8.GetString(buf, offset, valueLength - 1); // remove null terminator
- return true;
- }
+ if (buffer[offset++] != GetSetValue)
+ {
+ return false;
+ }
- private class HdHomerunCrc
- {
- private static uint[] crc_table = {
- 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
- 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
- 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
- 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
- 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
- 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
- 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
- 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
- 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
- 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
- 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
- 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
- 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
- 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
- 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
- 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
- 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
- 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
- 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
- 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
- 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
- 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
- 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
- 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
- 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
- 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
- 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
- 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
- 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
- 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
- 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
- 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
- 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
- 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
- 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
- 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
- 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
- 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
- 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
- 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
- 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
- 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
- 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
- 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
- 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
- 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
- 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
- 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
- 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
- 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
- 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
- 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
- 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
- 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
- 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
- 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
- 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
- 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
- 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
- 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
- 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
- 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
- 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
- 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d };
-
- public static uint GetCrc32(byte[] bytes, int numBytes)
+ var valueLength = buffer[offset++];
+ if (buffer.Length < 4 + offset + valueLength)
{
- var hash = 0xffffffff;
- for (var i = 0; i < numBytes; i++)
- hash = (hash >> 8) ^ crc_table[(hash ^ bytes[i]) & 0xff];
-
- var tmp = ~hash & 0xffffffff;
- var b0 = tmp & 0xff;
- var b1 = (tmp >> 8) & 0xff;
- var b2 = (tmp >> 16) & 0xff;
- var b3 = (tmp >> 24) & 0xff;
- hash = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
- return hash;
+ return false;
}
+
+ // remove null terminator
+ value = buffer.Slice(offset, valueLength - 1);
+ return true;
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
index 8774371d5..31445e1ec 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
@@ -1,11 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Net;
+using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
@@ -18,30 +24,50 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
{
- private readonly IServerApplicationHost _appHost;
- private readonly MediaBrowser.Model.Net.ISocketFactory _socketFactory;
+ private const int RtpHeaderBytes = 12;
+ private readonly IServerApplicationHost _appHost;
private readonly IHdHomerunChannelCommands _channelCommands;
private readonly int _numTuners;
- private readonly INetworkManager _networkManager;
- public HdHomerunUdpStream(MediaSourceInfo mediaSource, TunerHostInfo tunerHostInfo, string originalStreamId, IHdHomerunChannelCommands channelCommands, int numTuners, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost, MediaBrowser.Model.Net.ISocketFactory socketFactory, INetworkManager networkManager)
- : base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths)
+ public HdHomerunUdpStream(
+ MediaSourceInfo mediaSource,
+ TunerHostInfo tunerHostInfo,
+ string originalStreamId,
+ IHdHomerunChannelCommands channelCommands,
+ int numTuners,
+ IFileSystem fileSystem,
+ ILogger logger,
+ IConfigurationManager configurationManager,
+ IServerApplicationHost appHost,
+ IStreamHelper streamHelper)
+ : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
{
_appHost = appHost;
- _socketFactory = socketFactory;
- _networkManager = networkManager;
OriginalStreamId = originalStreamId;
_channelCommands = channelCommands;
_numTuners = numTuners;
EnableStreamSharing = true;
}
- private static Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
+ /// <summary>
+ /// Returns an unused UDP port number in the range specified.
+ /// Temporarily placed here until future network PR merged.
+ /// </summary>
+ /// <param name="range">Upper and Lower boundary of ports to select.</param>
+ /// <returns>System.Int32.</returns>
+ private static int GetUdpPortFromRange((int Min, int Max) range)
{
- var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
+ var properties = IPGlobalProperties.GetIPGlobalProperties();
+
+ // Get active udp listeners.
+ var udpListenerPorts = properties.GetActiveUdpListeners()
+ .Where(n => n.Port >= range.Min && n.Port <= range.Max)
+ .Select(n => n.Port);
- return socket;
+ return Enumerable
+ .Range(range.Min, range.Max)
+ .FirstOrDefault(i => !udpListenerPorts.Contains(i));
}
public override async Task Open(CancellationToken openCancellationToken)
@@ -51,22 +77,22 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var mediaSource = OriginalMediaSource;
var uri = new Uri(mediaSource.Path);
- var localPort = _networkManager.GetRandomUnusedUdpPort();
+ // Temporary code to reduce PR size. This will be updated by a future network pr.
+ var localPort = GetUdpPortFromRange((49152, 65535));
Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);
var remoteAddress = IPAddress.Parse(uri.Host);
- var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host);
IPAddress localAddress = null;
- using (var tcpSocket = CreateSocket(remoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
+ using (var tcpClient = new TcpClient())
{
try
{
- tcpSocket.Connect(new IPEndPoint(remoteAddress, HdHomerunManager.HdHomeRunPort));
- localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address;
- tcpSocket.Close();
+ await tcpClient.ConnectAsync(remoteAddress, HdHomerunManager.HdHomeRunPort, openCancellationToken).ConfigureAwait(false);
+ localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address;
+ tcpClient.Close();
}
catch (Exception ex)
{
@@ -75,237 +101,129 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
- var udpClient = _socketFactory.CreateUdpSocket(localPort);
- var hdHomerunManager = new HdHomerunManager(_socketFactory, Logger);
+ if (localAddress.IsIPv4MappedToIPv6)
+ {
+ localAddress = localAddress.MapToIPv4();
+ }
+
+ var udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);
+ var hdHomerunManager = new HdHomerunManager();
try
{
// send url to start streaming
- await hdHomerunManager.StartStreaming(embyRemoteAddress, localAddress, localPort, _channelCommands, _numTuners, openCancellationToken).ConfigureAwait(false);
+ await hdHomerunManager.StartStreaming(
+ remoteAddress,
+ localAddress,
+ localPort,
+ _channelCommands,
+ _numTuners,
+ openCancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
using (udpClient)
using (hdHomerunManager)
{
- if (!(ex is OperationCanceledException))
+ if (ex is not OperationCanceledException)
{
Logger.LogError(ex, "Error opening live stream:");
}
+
throw;
}
}
var taskCompletionSource = new TaskCompletionSource<bool>();
- await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
+ _ = StartStreaming(
+ udpClient,
+ hdHomerunManager,
+ remoteAddress,
+ taskCompletionSource,
+ LiveStreamCancellationTokenSource.Token);
- //OpenedMediaSource.Protocol = MediaProtocol.File;
- //OpenedMediaSource.Path = tempFile;
- //OpenedMediaSource.ReadAtNativeFramerate = true;
+ // OpenedMediaSource.Protocol = MediaProtocol.File;
+ // OpenedMediaSource.Path = tempFile;
+ // OpenedMediaSource.ReadAtNativeFramerate = true;
- MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
+ MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
MediaSource.Protocol = MediaProtocol.Http;
- //OpenedMediaSource.SupportsDirectPlay = false;
- //OpenedMediaSource.SupportsDirectStream = true;
- //OpenedMediaSource.SupportsTranscoding = true;
+ // OpenedMediaSource.SupportsDirectPlay = false;
+ // OpenedMediaSource.SupportsDirectStream = true;
+ // OpenedMediaSource.SupportsTranscoding = true;
- //await Task.Delay(5000).ConfigureAwait(false);
+ // await Task.Delay(5000).ConfigureAwait(false);
await taskCompletionSource.Task.ConfigureAwait(false);
}
- private Task StartStreaming(MediaBrowser.Model.Net.ISocket udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
+ private async Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
{
- return Task.Run(async () =>
+ using (udpClient)
+ using (hdHomerunManager)
{
- using (udpClient)
- using (hdHomerunManager)
+ try
{
- try
- {
- await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException ex)
- {
- Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
- openTaskCompletionSource.TrySetException(ex);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error opening live stream:");
- openTaskCompletionSource.TrySetException(ex);
- }
-
- EnableStreamSharing = false;
+ await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException ex)
+ {
+ Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
+ openTaskCompletionSource.TrySetException(ex);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error opening live stream:");
+ openTaskCompletionSource.TrySetException(ex);
}
- await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
- });
- }
+ EnableStreamSharing = false;
+ }
- private static void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
- {
- Task.Run(() =>
- {
- openTaskCompletionSource.TrySetResult(true);
- });
+ await DeleteTempFiles(TempFilePath).ConfigureAwait(false);
}
- private static int RtpHeaderBytes = 12;
- private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
+ private async Task CopyTo(UdpClient udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
{
- var bufferSize = 81920;
-
- byte[] buffer = new byte[bufferSize];
- int read;
var resolved = false;
- using (var source = _socketFactory.CreateNetworkStream(udpClient, false))
- using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
+ using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
{
- var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token;
-
- while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
+ while (true)
{
cancellationToken.ThrowIfCancellationRequested();
-
- currentCancellationToken = cancellationToken;
-
- read -= RtpHeaderBytes;
-
- if (read > 0)
+ using (var timeOutSource = new CancellationTokenSource())
+ using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(
+ cancellationToken,
+ timeOutSource.Token))
{
- fileStream.Write(buffer, RtpHeaderBytes, read);
+ var resTask = udpClient.ReceiveAsync(linkedSource.Token).AsTask();
+ if (await Task.WhenAny(resTask, Task.Delay(30000, linkedSource.Token)).ConfigureAwait(false) != resTask)
+ {
+ resTask.Dispose();
+ break;
+ }
+
+ // We don't want all these delay tasks to keep running
+ timeOutSource.Cancel();
+ var res = await resTask.ConfigureAwait(false);
+ var buffer = res.Buffer;
+
+ var read = buffer.Length - RtpHeaderBytes;
+
+ if (read > 0)
+ {
+ fileStream.Write(buffer, RtpHeaderBytes, read);
+ }
+
+ if (!resolved)
+ {
+ resolved = true;
+ DateOpened = DateTime.UtcNow;
+ openTaskCompletionSource.TrySetResult(true);
+ }
}
-
- if (!resolved)
- {
- resolved = true;
- DateOpened = DateTime.UtcNow;
- Resolve(openTaskCompletionSource);
- }
- }
- }
- }
-
- public class UdpClientStream : Stream
- {
- private static int RtpHeaderBytes = 12;
- private static int PacketSize = 1316;
- private readonly MediaBrowser.Model.Net.ISocket _udpClient;
- bool disposed;
-
- public UdpClientStream(MediaBrowser.Model.Net.ISocket udpClient) : base()
- {
- _udpClient = udpClient;
- }
-
- public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer));
-
- if (offset + count < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), "offset + count must not be negative");
-
- if (offset + count > buffer.Length)
- throw new ArgumentException("offset + count must not be greater than the length of buffer");
-
- if (disposed)
- throw new ObjectDisposedException(nameof(UdpClientStream));
-
- // This will always receive a 1328 packet size (PacketSize + RtpHeaderSize)
- // The RTP header will be stripped so see how many reads we need to make to fill the buffer.
- int numReads = count / PacketSize;
- int totalBytesRead = 0;
- byte[] receiveBuffer = new byte[81920];
-
- for (int i = 0; i < numReads; ++i)
- {
- var data = await _udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
-
- var bytesRead = data.ReceivedBytes - RtpHeaderBytes;
-
- // remove rtp header
- Buffer.BlockCopy(data.Buffer, RtpHeaderBytes, buffer, offset, bytesRead);
- offset += bytesRead;
- totalBytesRead += bytesRead;
}
- return totalBytesRead;
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer));
-
- if (offset + count < 0)
- throw new ArgumentOutOfRangeException("offset + count must not be negative", "offset+count");
-
- if (offset + count > buffer.Length)
- throw new ArgumentException("offset + count must not be greater than the length of buffer");
-
- if (disposed)
- throw new ObjectDisposedException(nameof(UdpClientStream));
-
- // This will always receive a 1328 packet size (PacketSize + RtpHeaderSize)
- // The RTP header will be stripped so see how many reads we need to make to fill the buffer.
- int numReads = count / PacketSize;
- int totalBytesRead = 0;
- byte[] receiveBuffer = new byte[81920];
-
- for (int i = 0; i < numReads; ++i)
- {
- var receivedBytes = _udpClient.Receive(receiveBuffer, 0, receiveBuffer.Length);
-
- var bytesRead = receivedBytes - RtpHeaderBytes;
-
- // remove rtp header
- Buffer.BlockCopy(receiveBuffer, RtpHeaderBytes, buffer, offset, bytesRead);
- offset += bytesRead;
- totalBytesRead += bytesRead;
- }
- return totalBytesRead;
- }
-
- protected override void Dispose(bool disposing)
- {
- disposed = true;
- }
-
- public override bool CanRead => throw new NotImplementedException();
-
- public override bool CanSeek => throw new NotImplementedException();
-
- public override bool CanWrite => throw new NotImplementedException();
-
- public override long Length => throw new NotImplementedException();
-
- public override long Position
- {
- get => throw new NotImplementedException();
-
- set => throw new NotImplementedException();
- }
-
- public override void Flush()
- {
- throw new NotImplementedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new NotImplementedException();
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/IHdHomerunChannelCommands.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/IHdHomerunChannelCommands.cs
new file mode 100644
index 000000000..153354932
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/IHdHomerunChannelCommands.cs
@@ -0,0 +1,11 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+
+namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ public interface IHdHomerunChannelCommands
+ {
+ IEnumerable<(string, string)> GetCommands();
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/LegacyHdHomerunChannelCommands.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/LegacyHdHomerunChannelCommands.cs
new file mode 100644
index 000000000..26627b8aa
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/LegacyHdHomerunChannelCommands.cs
@@ -0,0 +1,38 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ public class LegacyHdHomerunChannelCommands : IHdHomerunChannelCommands
+ {
+ private string? _channel;
+ private string? _program;
+
+ public LegacyHdHomerunChannelCommands(string url)
+ {
+ // parse url for channel and program
+ var regExp = new Regex(@"\/ch([0-9]+)-?([0-9]*)");
+ var match = regExp.Match(url);
+ if (match.Success)
+ {
+ _channel = match.Groups[1].Value;
+ _program = match.Groups[2].Value;
+ }
+ }
+
+ public IEnumerable<(string, string)> GetCommands()
+ {
+ if (!string.IsNullOrEmpty(_channel))
+ {
+ yield return ("channel", _channel);
+ }
+
+ if (!string.IsNullOrEmpty(_program))
+ {
+ yield return ("program", _program);
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
index 1f8ca276e..5581ba87c 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
@@ -1,10 +1,13 @@
+#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 MediaBrowser.Controller;
+using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
@@ -15,51 +18,64 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class LiveStream : ILiveStream
{
- public MediaSourceInfo OriginalMediaSource { get; set; }
- public MediaSourceInfo MediaSource { get; set; }
-
- public int ConsumerCount { get; set; }
-
- public string OriginalStreamId { get; set; }
- public bool EnableStreamSharing { get; set; }
- public string UniqueId { get; private set; }
-
- protected readonly IFileSystem FileSystem;
- protected readonly IServerApplicationPaths AppPaths;
-
- protected string TempFilePath;
- protected readonly ILogger Logger;
- protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
-
- public string TunerHostId { get; private set; }
-
- public DateTime DateOpened { get; protected set; }
-
- public Func<Task> OnClose { get; set; }
-
- public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
+ private readonly IConfigurationManager _configurationManager;
+
+ public LiveStream(
+ MediaSourceInfo mediaSource,
+ TunerHostInfo tuner,
+ IFileSystem fileSystem,
+ ILogger logger,
+ IConfigurationManager configurationManager,
+ IStreamHelper streamHelper)
{
OriginalMediaSource = mediaSource;
FileSystem = fileSystem;
MediaSource = mediaSource;
Logger = logger;
EnableStreamSharing = true;
- UniqueId = Guid.NewGuid().ToString("N");
+ UniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
if (tuner != null)
{
TunerHostId = tuner.Id;
}
- AppPaths = appPaths;
+ _configurationManager = configurationManager;
+ StreamHelper = streamHelper;
ConsumerCount = 1;
SetTempFilePath("ts");
}
+ protected IFileSystem FileSystem { get; }
+
+ protected IStreamHelper StreamHelper { get; }
+
+ protected ILogger Logger { get; }
+
+ protected CancellationTokenSource LiveStreamCancellationTokenSource { get; } = new CancellationTokenSource();
+
+ protected string TempFilePath { get; set; }
+
+ public MediaSourceInfo OriginalMediaSource { get; set; }
+
+ public MediaSourceInfo MediaSource { get; set; }
+
+ public int ConsumerCount { get; set; }
+
+ public string OriginalStreamId { get; set; }
+
+ public bool EnableStreamSharing { get; set; }
+
+ public string UniqueId { get; }
+
+ public string TunerHostId { get; }
+
+ public DateTime DateOpened { get; protected set; }
+
protected void SetTempFilePath(string extension)
{
- TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension);
+ TempFilePath = Path.Combine(_configurationManager.GetTranscodePath(), UniqueId + "." + extension);
}
public virtual Task Open(CancellationToken openCancellationToken)
@@ -72,164 +88,72 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
EnableStreamSharing = false;
- Logger.LogInformation("Closing " + GetType().Name);
+ Logger.LogInformation("Closing {Type}", GetType().Name);
LiveStreamCancellationTokenSource.Cancel();
- if (OnClose != null)
- {
- return CloseWithExternalFn();
- }
-
return Task.CompletedTask;
}
- private async Task CloseWithExternalFn()
+ public Stream GetStream()
{
- try
- {
- await OnClose().ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error closing live stream");
- }
- }
-
- protected Stream GetInputStream(string path, bool allowAsyncFileRead)
- {
- var fileOpenOptions = FileOpenOptions.SequentialScan;
-
- if (allowAsyncFileRead)
+ var stream = GetInputStream(TempFilePath);
+ bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
+ if (seekFile)
{
- fileOpenOptions |= FileOpenOptions.Asynchronous;
+ TrySeek(stream, -20000);
}
- return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
+ return stream;
}
- public Task DeleteTempFiles()
- {
- return DeleteTempFiles(GetStreamFilePaths());
- }
+ protected FileStream GetInputStream(string path)
+ => new FileStream(
+ path,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.ReadWrite,
+ IODefaults.FileStreamBufferSize,
+ FileOptions.SequentialScan | FileOptions.Asynchronous);
- protected async Task DeleteTempFiles(List<string> paths, int retryCount = 0)
+ protected async Task DeleteTempFiles(string path, int retryCount = 0)
{
if (retryCount == 0)
{
- Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
- }
-
- var failedFiles = new List<string>();
-
- foreach (var path in paths)
- {
- try
- {
- FileSystem.DeleteFile(path);
- }
- catch (DirectoryNotFoundException)
- {
- }
- catch (FileNotFoundException)
- {
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error deleting file {path}", path);
- failedFiles.Add(path);
- }
+ Logger.LogInformation("Deleting temp file {FilePath}", path);
}
- if (failedFiles.Count > 0 && retryCount <= 40)
- {
- await Task.Delay(500).ConfigureAwait(false);
- await DeleteTempFiles(failedFiles, retryCount + 1).ConfigureAwait(false);
- }
- }
-
- protected virtual List<string> GetStreamFilePaths()
- {
- return new List<string> { TempFilePath };
- }
-
- public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
- {
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
-
- var allowAsync = false;
- // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
-
- bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
-
- var nextFileInfo = GetNextFile(null);
- var nextFile = nextFileInfo.Item1;
- var isLastFile = nextFileInfo.Item2;
-
- while (!string.IsNullOrEmpty(nextFile))
+ try
{
- var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
-
- await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
-
- seekFile = false;
- nextFileInfo = GetNextFile(nextFile);
- nextFile = nextFileInfo.Item1;
- isLastFile = nextFileInfo.Item2;
+ FileSystem.DeleteFile(path);
}
-
- Logger.LogInformation("Live Stream ended.");
- }
-
- private Tuple<string, bool> GetNextFile(string currentFile)
- {
- var files = GetStreamFilePaths();
-
- //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
-
- if (string.IsNullOrEmpty(currentFile))
+ catch (Exception ex)
{
- return new Tuple<string, bool>(files.Last(), true);
+ Logger.LogError(ex, "Error deleting file {FilePath}", path);
+ if (retryCount <= 40)
+ {
+ await Task.Delay(500).ConfigureAwait(false);
+ await DeleteTempFiles(path, retryCount + 1).ConfigureAwait(false);
+ }
}
-
- var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
-
- var isLastFile = nextIndex == files.Count - 1;
-
- return new Tuple<string, bool>(files.ElementAtOrDefault(nextIndex), isLastFile);
}
- private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
+ private void TrySeek(Stream stream, long offset)
{
- //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
-
- using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
+ if (!stream.CanSeek)
{
- if (seekFile)
- {
- TrySeek(inputStream, -20000);
- }
-
- await ApplicationHost.StreamHelper.CopyToAsync(inputStream, stream, 81920, emptyReadLimit, cancellationToken).ConfigureAwait(false);
+ return;
}
- }
-
- protected virtual int EmptyReadLimit => 1000;
- private void TrySeek(FileStream stream, long offset)
- {
- //logger.LogInformation("TrySeek live stream");
try
{
stream.Seek(offset, SeekOrigin.End);
}
catch (IOException)
{
-
}
catch (ArgumentException)
{
-
}
catch (Exception ex)
{
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
index fdaaf0bae..08b9260b9 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
@@ -1,7 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
@@ -10,32 +16,50 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.System;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class M3UTunerHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
{
- private readonly IHttpClient _httpClient;
+ private static readonly string[] _disallowedSharedStreamExtensions =
+ {
+ ".mkv",
+ ".mp4",
+ ".m3u8",
+ ".mpd"
+ };
+
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerApplicationHost _appHost;
private readonly INetworkManager _networkManager;
private readonly IMediaSourceManager _mediaSourceManager;
-
- public M3UTunerHost(IServerConfigurationManager config, IMediaSourceManager mediaSourceManager, ILogger logger, IJsonSerializer jsonSerializer, IFileSystem fileSystem, IHttpClient httpClient, IServerApplicationHost appHost, INetworkManager networkManager)
- : base(config, logger, jsonSerializer, fileSystem)
+ private readonly IStreamHelper _streamHelper;
+
+ public M3UTunerHost(
+ IServerConfigurationManager config,
+ IMediaSourceManager mediaSourceManager,
+ ILogger<M3UTunerHost> logger,
+ IFileSystem fileSystem,
+ IHttpClientFactory httpClientFactory,
+ IServerApplicationHost appHost,
+ INetworkManager networkManager,
+ IStreamHelper streamHelper,
+ IMemoryCache memoryCache)
+ : base(config, logger, fileSystem, memoryCache)
{
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_appHost = appHost;
_networkManager = networkManager;
_mediaSourceManager = mediaSourceManager;
+ _streamHelper = streamHelper;
}
public override string Type => "m3u";
@@ -44,16 +68,16 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private string GetFullChannelIdPrefix(TunerHostInfo info)
{
- return ChannelIdPrefix + info.Url.GetMD5().ToString("N");
+ return ChannelIdPrefix + info.Url.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
- protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
+ protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken)
{
- var channelIdPrefix = GetFullChannelIdPrefix(info);
+ var channelIdPrefix = GetFullChannelIdPrefix(tuner);
- var result = await new M3uParser(Logger, _httpClient, _appHost).Parse(info.Url, channelIdPrefix, info.Id, cancellationToken).ConfigureAwait(false);
-
- return result.Cast<ChannelInfo>().ToList();
+ return await new M3uParser(Logger, _httpClientFactory)
+ .Parse(tuner, channelIdPrefix, cancellationToken)
+ .ConfigureAwait(false);
}
public Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
@@ -64,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
Name = Name,
SourceType = Type,
Status = LiveTvTunerStatus.Available,
- Id = i.Url.GetMD5().ToString("N"),
+ Id = i.Url.GetMD5().ToString("N", CultureInfo.InvariantCulture),
Url = i.Url
})
.ToList();
@@ -72,32 +96,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return Task.FromResult(list);
}
- private string[] _disallowedSharedStreamExtensions = new string[]
+ protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo tunerHost, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
- ".mkv",
- ".mp4",
- ".m3u8",
- ".mpd"
- };
-
- protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
- {
- var tunerCount = info.TunerCount;
+ var tunerCount = tunerHost.TunerCount;
if (tunerCount > 0)
{
- var tunerHostId = info.Id;
- var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase)).ToList();
+ var tunerHostId = tunerHost.Id;
+ var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
- if (liveStreams.Count >= tunerCount)
+ if (liveStreams.Count() >= tunerCount)
{
throw new LiveTvConflictException("M3U simultaneous stream limit has been reached.");
}
}
- var sources = await GetChannelStreamMediaSources(info, channelInfo, cancellationToken).ConfigureAwait(false);
+ var sources = await GetChannelStreamMediaSources(tunerHost, channel, cancellationToken).ConfigureAwait(false);
- var mediaSource = sources.First();
+ var mediaSource = sources[0];
if (mediaSource.Protocol == MediaProtocol.Http && !mediaSource.RequiresLooping)
{
@@ -105,24 +121,23 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
if (!_disallowedSharedStreamExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
- return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost);
+ return new SharedHttpStream(mediaSource, tunerHost, streamId, FileSystem, _httpClientFactory, Logger, Config, _appHost, _streamHelper);
}
}
- return new LiveStream(mediaSource, info, FileSystem, Logger, Config.ApplicationPaths);
+ return new LiveStream(mediaSource, tunerHost, FileSystem, Logger, Config, _streamHelper);
}
public async Task Validate(TunerHostInfo info)
{
- using (var stream = await new M3uParser(Logger, _httpClient, _appHost).GetListingsStream(info.Url, CancellationToken.None).ConfigureAwait(false))
+ using (var stream = await new M3uParser(Logger, _httpClientFactory).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false))
{
-
}
}
- protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
+ protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, ChannelInfo channel, CancellationToken cancellationToken)
{
- return Task.FromResult(new List<MediaSourceInfo> { CreateMediaSourceInfo(info, channelInfo) });
+ return Task.FromResult(new List<MediaSourceInfo> { CreateMediaSourceInfo(tuner, channel) });
}
protected virtual MediaSourceInfo CreateMediaSourceInfo(TunerHostInfo info, ChannelInfo channel)
@@ -145,7 +160,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
if (protocol == MediaProtocol.Http)
{
// Use user-defined user-agent. If there isn't one, make it look like a browser.
- httpHeaders["User-Agent"] = string.IsNullOrWhiteSpace(info.UserAgent) ?
+ httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
info.UserAgent;
}
@@ -176,7 +191,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
ReadAtNativeFramerate = false,
- Id = channel.Path.GetMD5().ToString("N"),
+ Id = channel.Path.GetMD5().ToString("N", CultureInfo.InvariantCulture),
IsInfiniteStream = true,
IsRemote = isRemote,
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
index ad124bb0f..506ef5548 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
@@ -1,107 +1,112 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
-using System.Linq;
+using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
+using MediaBrowser.Model.LiveTv;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class M3uParser
{
+ private const string ExtInfPrefix = "#EXTINF:";
+
private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
- private readonly IServerApplicationHost _appHost;
+ private readonly IHttpClientFactory _httpClientFactory;
- public M3uParser(ILogger logger, IHttpClient httpClient, IServerApplicationHost appHost)
+ public M3uParser(ILogger logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
- _httpClient = httpClient;
- _appHost = appHost;
+ _httpClientFactory = httpClientFactory;
}
- public async Task<List<ChannelInfo>> Parse(string url, string channelIdPrefix, string tunerHostId, CancellationToken cancellationToken)
+ public async Task<List<ChannelInfo>> Parse(TunerHostInfo info, string channelIdPrefix, CancellationToken cancellationToken)
{
// Read the file and display it line by line.
- using (var reader = new StreamReader(await GetListingsStream(url, cancellationToken).ConfigureAwait(false)))
+ using (var reader = new StreamReader(await GetListingsStream(info, cancellationToken).ConfigureAwait(false)))
{
- return GetChannels(reader, channelIdPrefix, tunerHostId);
+ return await GetChannelsAsync(reader, channelIdPrefix, info.Id).ConfigureAwait(false);
}
}
- public List<ChannelInfo> ParseString(string text, string channelIdPrefix, string tunerHostId)
+ public async Task<Stream> GetListingsStream(TunerHostInfo info, CancellationToken cancellationToken)
{
- // Read the file and display it line by line.
- using (var reader = new StringReader(text))
+ if (info == null)
{
- return GetChannels(reader, channelIdPrefix, tunerHostId);
+ throw new ArgumentNullException(nameof(info));
}
- }
- public Task<Stream> GetListingsStream(string url, CancellationToken cancellationToken)
- {
- if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
+ if (!info.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- return _httpClient.Get(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- // Some data providers will require a user agent
- UserAgent = _appHost.ApplicationUserAgent
- });
+ return AsyncFile.OpenRead(info.Url);
+ }
+
+ using var requestMessage = new HttpRequestMessage(HttpMethod.Get, info.Url);
+ if (!string.IsNullOrEmpty(info.UserAgent))
+ {
+ requestMessage.Headers.UserAgent.TryParseAdd(info.UserAgent);
}
- return Task.FromResult((Stream)File.OpenRead(url));
+
+ // Set HttpCompletionOption.ResponseHeadersRead to prevent timeouts on larger files
+ var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
+ .ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+
+ return await response.Content.ReadAsStreamAsync(cancellationToken);
}
- const string ExtInfPrefix = "#EXTINF:";
- private List<ChannelInfo> GetChannels(TextReader reader, string channelIdPrefix, string tunerHostId)
+ private async Task<List<ChannelInfo>> GetChannelsAsync(TextReader reader, string channelIdPrefix, string tunerHostId)
{
var channels = new List<ChannelInfo>();
- string line;
- string extInf = "";
+ string extInf = string.Empty;
- while ((line = reader.ReadLine()) != null)
+ await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
- line = line.Trim();
- if (string.IsNullOrWhiteSpace(line))
+ var trimmedLine = line.Trim();
+ if (string.IsNullOrWhiteSpace(trimmedLine))
{
continue;
}
- if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase))
+ if (trimmedLine.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase))
{
continue;
}
- if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase))
+ if (trimmedLine.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase))
{
- extInf = line.Substring(ExtInfPrefix.Length).Trim();
- _logger.LogInformation("Found m3u channel: {0}", extInf);
+ extInf = trimmedLine.Substring(ExtInfPrefix.Length).Trim();
}
- else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase))
+ else if (!string.IsNullOrWhiteSpace(extInf) && !trimmedLine.StartsWith('#'))
{
- var channel = GetChannelnfo(extInf, tunerHostId, line);
+ var channel = GetChannelnfo(extInf, tunerHostId, trimmedLine);
if (string.IsNullOrWhiteSpace(channel.Id))
{
- channel.Id = channelIdPrefix + line.GetMD5().ToString("N");
+ channel.Id = channelIdPrefix + trimmedLine.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
else
{
- channel.Id = channelIdPrefix + channel.Id.GetMD5().ToString("N");
+ channel.Id = channelIdPrefix + channel.Id.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
- channel.Path = line;
+ channel.Path = trimmedLine;
channels.Add(channel);
- extInf = "";
+ _logger.LogInformation("Parsed channel: {ChannelName}", channel.Name);
+ extInf = string.Empty;
}
}
@@ -110,8 +115,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private ChannelInfo GetChannelnfo(string extInf, string tunerHostId, string mediaUrl)
{
- var channel = new ChannelInfo();
- channel.TunerHostId = tunerHostId;
+ var channel = new ChannelInfo()
+ {
+ TunerHostId = tunerHostId
+ };
extInf = extInf.Trim();
@@ -123,6 +130,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
channel.ImageUrl = value;
}
+ if (attributes.TryGetValue("group-title", out string groupTitle))
+ {
+ channel.ChannelGroup = groupTitle;
+ }
+
channel.Name = GetChannelName(extInf, attributes);
channel.Number = GetChannelNumber(extInf, attributes, mediaUrl);
@@ -137,13 +149,15 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
channelIdValues.Add(channelId);
}
+
if (!string.IsNullOrWhiteSpace(tvgId))
{
channelIdValues.Add(tvgId);
}
+
if (channelIdValues.Count > 0)
{
- channel.Id = string.Join("_", channelIdValues.ToArray());
+ channel.Id = string.Join('_', channelIdValues);
}
return channel;
@@ -151,16 +165,15 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private string GetChannelNumber(string extInf, Dictionary<string, string> attributes, string mediaUrl)
{
- var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- var nameInExtInf = nameParts.Length > 1 ? nameParts.Last().Trim() : null;
+ var nameParts = extInf.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ var nameInExtInf = nameParts.Length > 1 ? nameParts[^1].AsSpan().Trim() : ReadOnlySpan<char>.Empty;
string numberString = null;
string attributeValue;
- double doubleValue;
if (attributes.TryGetValue("tvg-chno", out attributeValue))
{
- if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out doubleValue))
+ if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
numberString = attributeValue;
}
@@ -170,41 +183,40 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
if (attributes.TryGetValue("tvg-id", out attributeValue))
{
- if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out doubleValue))
+ if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
numberString = attributeValue;
}
else if (attributes.TryGetValue("channel-id", out attributeValue))
{
- if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out doubleValue))
+ if (double.TryParse(attributeValue, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
numberString = attributeValue;
}
}
}
- if (String.IsNullOrWhiteSpace(numberString))
+ if (string.IsNullOrWhiteSpace(numberString))
{
// Using this as a fallback now as this leads to Problems with channels like "5 USA"
- // where 5 isnt ment to be the channel number
+ // where 5 isn't ment to be the channel number
// Check for channel number with the format from SatIp
// #EXTINF:0,84. VOX Schweiz
// #EXTINF:0,84.0 - VOX Schweiz
- if (!string.IsNullOrWhiteSpace(nameInExtInf))
+ if (!nameInExtInf.IsEmpty && !nameInExtInf.IsWhiteSpace())
{
var numberIndex = nameInExtInf.IndexOf(' ');
if (numberIndex > 0)
{
- var numberPart = nameInExtInf.Substring(0, numberIndex).Trim(new[] { ' ', '.' });
+ var numberPart = nameInExtInf.Slice(0, numberIndex).Trim(new[] { ' ', '.' });
- if (double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out var number))
+ if (double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
- numberString = numberPart;
+ numberString = numberPart.ToString();
}
}
}
}
-
}
if (!IsValidChannelNumber(numberString))
@@ -226,7 +238,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
try
{
- numberString = Path.GetFileNameWithoutExtension(mediaUrl.Split('/').Last());
+ numberString = Path.GetFileNameWithoutExtension(mediaUrl.AsSpan().RightPart('/')).ToString();
if (!IsValidChannelNumber(numberString))
{
@@ -253,7 +265,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return false;
}
- if (!double.TryParse(numberString, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
+ if (!double.TryParse(numberString, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
return false;
}
@@ -263,8 +275,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private static string GetChannelName(string extInf, Dictionary<string, string> attributes)
{
- var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- var nameInExtInf = nameParts.Length > 1 ? nameParts.Last().Trim() : null;
+ var nameParts = extInf.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ var nameInExtInf = nameParts.Length > 1 ? nameParts[^1].Trim() : null;
// Check for channel number with the format from SatIp
// #EXTINF:0,84. VOX Schweiz
@@ -276,19 +288,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
var numberPart = nameInExtInf.Substring(0, numberIndex).Trim(new[] { ' ', '.' });
- if (double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out var number))
+ if (double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out _))
{
- //channel.Number = number.ToString();
+ // channel.Number = number.ToString();
nameInExtInf = nameInExtInf.Substring(numberIndex + 1).Trim(new[] { ' ', '-' });
}
}
}
- attributes.TryGetValue("tvg-name", out string name);
+ string name = nameInExtInf;
if (string.IsNullOrWhiteSpace(name))
{
- name = nameInExtInf;
+ attributes.TryGetValue("tvg-name", out name);
}
if (string.IsNullOrWhiteSpace(name))
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
index d74cf3be2..3b69e55b0 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
@@ -1,8 +1,14 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Generic;
+using System.Globalization;
using System.IO;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
@@ -16,13 +22,22 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class SharedHttpStream : LiveStream, IDirectStreamProvider
{
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerApplicationHost _appHost;
- public SharedHttpStream(MediaSourceInfo mediaSource, TunerHostInfo tunerHostInfo, string originalStreamId, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost)
- : base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths)
+ public SharedHttpStream(
+ MediaSourceInfo mediaSource,
+ TunerHostInfo tunerHostInfo,
+ string originalStreamId,
+ IFileSystem fileSystem,
+ IHttpClientFactory httpClientFactory,
+ ILogger logger,
+ IConfigurationManager configurationManager,
+ IServerApplicationHost appHost,
+ IStreamHelper streamHelper)
+ : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
{
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_appHost = appHost;
OriginalStreamId = originalStreamId;
EnableStreamSharing = true;
@@ -39,105 +54,95 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
var typeName = GetType().Name;
- Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url);
-
- var httpRequestOptions = new HttpRequestOptions
- {
- Url = url,
- CancellationToken = CancellationToken.None,
- BufferContent = false,
-
- // Increase a little bit
- TimeoutMs = 30000,
-
- EnableHttpCompression = false,
-
- LogResponse = true,
- LogResponseHeaders = true
- };
-
- foreach (var header in mediaSource.RequiredHttpHeaders)
- {
- httpRequestOptions.RequestHeaders[header.Key] = header.Value;
- }
-
- var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false);
-
- var extension = "ts";
- var requiresRemux = false;
-
- var contentType = response.ContentType ?? string.Empty;
- if (contentType.IndexOf("matroska", StringComparison.OrdinalIgnoreCase) != -1)
- {
- requiresRemux = true;
- }
- else if (contentType.IndexOf("mp4", StringComparison.OrdinalIgnoreCase) != -1 ||
- contentType.IndexOf("dash", StringComparison.OrdinalIgnoreCase) != -1 ||
- contentType.IndexOf("mpegURL", StringComparison.OrdinalIgnoreCase) != -1 ||
- contentType.IndexOf("text/", StringComparison.OrdinalIgnoreCase) != -1)
- {
- requiresRemux = true;
- }
-
- // Close the stream without any sharing features
- if (requiresRemux)
+ Logger.LogInformation("Opening {StreamType} Live stream from {Url}", typeName, url);
+
+ // Response stream is disposed manually.
+ var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var contentType = response.Content.Headers.ContentType?.ToString() ?? string.Empty;
+ if (contentType.Contains("matroska", StringComparison.OrdinalIgnoreCase)
+ || contentType.Contains("mp4", StringComparison.OrdinalIgnoreCase)
+ || contentType.Contains("dash", StringComparison.OrdinalIgnoreCase)
+ || contentType.Contains("mpegURL", StringComparison.OrdinalIgnoreCase)
+ || contentType.Contains("text/", StringComparison.OrdinalIgnoreCase))
{
- using (response)
- {
- return;
- }
+ // Close the stream without any sharing features
+ response.Dispose();
+ return;
}
- SetTempFilePath(extension);
+ SetTempFilePath("ts");
var taskCompletionSource = new TaskCompletionSource<bool>();
- var now = DateTime.UtcNow;
-
_ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
- //OpenedMediaSource.Protocol = MediaProtocol.File;
- //OpenedMediaSource.Path = tempFile;
- //OpenedMediaSource.ReadAtNativeFramerate = true;
+ // OpenedMediaSource.Protocol = MediaProtocol.File;
+ // OpenedMediaSource.Path = tempFile;
+ // OpenedMediaSource.ReadAtNativeFramerate = true;
- MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
+ MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
MediaSource.Protocol = MediaProtocol.Http;
- //OpenedMediaSource.Path = TempFilePath;
- //OpenedMediaSource.Protocol = MediaProtocol.File;
+ // OpenedMediaSource.Path = TempFilePath;
+ // OpenedMediaSource.Protocol = MediaProtocol.File;
- //OpenedMediaSource.Path = _tempFilePath;
- //OpenedMediaSource.Protocol = MediaProtocol.File;
- //OpenedMediaSource.SupportsDirectPlay = false;
- //OpenedMediaSource.SupportsDirectStream = true;
- //OpenedMediaSource.SupportsTranscoding = true;
+ // OpenedMediaSource.Path = _tempFilePath;
+ // OpenedMediaSource.Protocol = MediaProtocol.File;
+ // OpenedMediaSource.SupportsDirectPlay = false;
+ // OpenedMediaSource.SupportsDirectStream = true;
+ // OpenedMediaSource.SupportsTranscoding = true;
await taskCompletionSource.Task.ConfigureAwait(false);
+ if (taskCompletionSource.Task.Exception != null)
+ {
+ // Error happened while opening the stream so raise the exception again to inform the caller
+ throw taskCompletionSource.Task.Exception;
+ }
+
+ if (!taskCompletionSource.Task.Result)
+ {
+ Logger.LogWarning("Zero bytes copied from stream {StreamType} to {FilePath} but no exception raised", GetType().Name, TempFilePath);
+ throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name));
+ }
}
- private Task StartStreaming(HttpResponseInfo response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
+ private Task StartStreaming(HttpResponseMessage response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
{
- return Task.Run(async () =>
- {
- try
+ return Task.Run(
+ async () =>
{
- Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
- using (response)
- using (var stream = response.Content)
- using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
+ try
{
- await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false);
+ Logger.LogInformation("Beginning {StreamType} stream to {FilePath}", GetType().Name, TempFilePath);
+ using var message = response;
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ await StreamHelper.CopyToAsync(
+ stream,
+ fileStream,
+ IODefaults.CopyToBufferSize,
+ () => Resolve(openTaskCompletionSource),
+ cancellationToken).ConfigureAwait(false);
}
- }
- catch (OperationCanceledException)
- {
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error copying live stream.");
- }
- EnableStreamSharing = false;
- await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
- });
+ catch (OperationCanceledException ex)
+ {
+ Logger.LogInformation("Copying of {StreamType} to {FilePath} was canceled", GetType().Name, TempFilePath);
+ openTaskCompletionSource.TrySetException(ex);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error copying live stream {StreamType} to {FilePath}", GetType().Name, TempFilePath);
+ openTaskCompletionSource.TrySetException(ex);
+ }
+
+ openTaskCompletionSource.TrySetResult(false);
+
+ EnableStreamSharing = false;
+ await DeleteTempFiles(TempFilePath).ConfigureAwait(false);
+ },
+ CancellationToken.None);
}
private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
diff --git a/Emby.Server.Implementations/Localization/Core/af.json b/Emby.Server.Implementations/Localization/Core/af.json
new file mode 100644
index 000000000..18f17dda9
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/af.json
@@ -0,0 +1,123 @@
+{
+ "Artists": "Kunstenare",
+ "Channels": "Kanale",
+ "Folders": "Lêergidse",
+ "Favorites": "Gunstelinge",
+ "HeaderFavoriteShows": "Gunsteling Vertonings",
+ "ValueSpecialEpisodeName": "Spesiale - {0}",
+ "HeaderAlbumArtists": "Kunstenaars se Album",
+ "Books": "Boeke",
+ "HeaderNextUp": "Volgende",
+ "Movies": "Flieks",
+ "Shows": "Televisie Reekse",
+ "HeaderContinueWatching": "Kyk Verder",
+ "HeaderFavoriteEpisodes": "Gunsteling Episodes",
+ "Photos": "Foto's",
+ "Playlists": "Snitlyste",
+ "HeaderFavoriteArtists": "Gunsteling Kunstenaars",
+ "HeaderFavoriteAlbums": "Gunsteling Albums",
+ "Sync": "Sinkroniseer",
+ "HeaderFavoriteSongs": "Gunsteling Liedjies",
+ "Songs": "Liedjies",
+ "DeviceOnlineWithName": "{0} is gekoppel",
+ "DeviceOfflineWithName": "{0} is ontkoppel",
+ "Collections": "Versamelings",
+ "Inherit": "Ontvang",
+ "HeaderLiveTV": "Lewendige TV",
+ "Application": "Program",
+ "AppDeviceValues": "App: {0}, Toestel: {1}",
+ "VersionNumber": "Weergawe {0}",
+ "ValueHasBeenAddedToLibrary": "{0} is by jou media biblioteek bygevoeg",
+ "UserStoppedPlayingItemWithValues": "{0} het klaar {1} op {2} gespeel",
+ "UserStartedPlayingItemWithValues": "{0} is besig om {1} op {2} te speel",
+ "UserPolicyUpdatedWithName": "Gebruiker beleid is verander vir {0}",
+ "UserPasswordChangedWithName": "Gebruiker {0} se wagwoord is verander",
+ "UserOnlineFromDevice": "{0} is aanlyn van {1}",
+ "UserOfflineFromDevice": "{0} is ontkoppel van {1}",
+ "UserLockedOutWithName": "Gebruiker {0} is uitgesluit",
+ "UserDownloadingItemWithValues": "{0} is besig om {1} af te laai",
+ "UserDeletedWithName": "Gebruiker {0} is verwyder",
+ "UserCreatedWithName": "Gebruiker {0} is geskep",
+ "User": "Gebruiker",
+ "TvShows": "TV Programme",
+ "System": "Stelsel",
+ "SubtitleDownloadFailureFromForItem": "Ondertitels het misluk om af te laai van {0} vir {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin Bediener is besig om te laai. Probeer weer in 'n kort tyd.",
+ "ServerNameNeedsToBeRestarted": "{0} moet herbegin word",
+ "ScheduledTaskStartedWithName": "{0} het begin",
+ "ScheduledTaskFailedWithName": "{0} het misluk",
+ "ProviderValue": "Voorsiener: {0}",
+ "PluginUpdatedWithName": "{0} was opgedateer",
+ "PluginUninstalledWithName": "{0} was verwyder",
+ "PluginInstalledWithName": "{0} is geïnstalleer",
+ "Plugin": "Inprop module",
+ "NotificationOptionVideoPlaybackStopped": "Video terugspeel het gestop",
+ "NotificationOptionVideoPlayback": "Video terugspeel het begin",
+ "NotificationOptionUserLockedOut": "Gebruiker uitgeslyt",
+ "NotificationOptionTaskFailed": "Geskeduleerde taak het misluk",
+ "NotificationOptionServerRestartRequired": "Bediener herbegin nodig",
+ "NotificationOptionPluginUpdateInstalled": "Nuwe inprop module geïnstalleer",
+ "NotificationOptionPluginUninstalled": "Inprop module verwyder",
+ "NotificationOptionPluginInstalled": "Inprop module geïnstalleer",
+ "NotificationOptionPluginError": "Inprop module het misluk",
+ "NotificationOptionNewLibraryContent": "Nuwe inhoud bygevoeg",
+ "NotificationOptionInstallationFailed": "Installering het misluk",
+ "NotificationOptionCameraImageUploaded": "Kamera foto is opgelaai",
+ "NotificationOptionAudioPlaybackStopped": "Oudio terugspeel het gestop",
+ "NotificationOptionAudioPlayback": "Oudio terugspeel het begin",
+ "NotificationOptionApplicationUpdateInstalled": "Nuwe program weergawe geïnstalleer",
+ "NotificationOptionApplicationUpdateAvailable": "Nuwe program weergawe beskikbaar",
+ "NewVersionIsAvailable": "'n Nuwe Jellyfin Bedienaar weergawe kan afgelaai word.",
+ "NameSeasonUnknown": "Seisoen Onbekend",
+ "NameSeasonNumber": "Seisoen {0}",
+ "NameInstallFailed": "{0} installering het misluk",
+ "MusicVideos": "Musiek Videos",
+ "Music": "Musiek",
+ "MixedContent": "Gemengde inhoud",
+ "MessageServerConfigurationUpdated": "Bediener konfigurasie is opgedateer",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Bediener konfigurasie seksie {0} is opgedateer",
+ "MessageApplicationUpdatedTo": "Jellyfin Bediener is opgedateer na {0}",
+ "MessageApplicationUpdated": "Jellyfin Bediener is opgedateer",
+ "Latest": "Nuutste",
+ "LabelRunningTimeValue": "Werktyd: {0}",
+ "LabelIpAddressValue": "IP adres: {0}",
+ "ItemRemovedWithName": "{0} is uit versameling verwyder",
+ "ItemAddedWithName": "{0} is by die versameling gevoeg",
+ "HomeVideos": "Tuis Videos",
+ "HeaderRecordingGroups": "Groep Opnames",
+ "Genres": "Genres",
+ "FailedLoginAttemptWithUserName": "Mislukte aansluiting van {0}",
+ "ChapterNameValue": "Hoofstuk {0}",
+ "CameraImageUploadedFrom": "'n Nuwe kamera photo opgelaai van {0}",
+ "AuthenticationSucceededWithUserName": "{0} suksesvol geverifieer",
+ "Albums": "Albums",
+ "TasksChannelsCategory": "Internet kanale",
+ "TasksApplicationCategory": "aansoek",
+ "TasksLibraryCategory": "biblioteek",
+ "TasksMaintenanceCategory": "onderhoud",
+ "TaskCleanCacheDescription": "Vee kasregister lêers uit wat nie meer deur die stelsel benodig word nie.",
+ "TaskCleanCache": "Reinig Kasgeheue Lêergids",
+ "TaskDownloadMissingSubtitlesDescription": "Soek aanlyn vir vermiste onderskrifte gebasseer op metadata verstellings.",
+ "TaskDownloadMissingSubtitles": "Laai vermiste onderskrifte af",
+ "TaskRefreshChannelsDescription": "Vervris internet kanaal inligting.",
+ "TaskRefreshChannels": "Vervris Kanale",
+ "TaskCleanTranscodeDescription": "Vee transkodering lêers uit wat ouer is as een dag.",
+ "TaskCleanTranscode": "Reinig Transkoderings Leêrbinder",
+ "TaskUpdatePluginsDescription": "Laai opgedateerde inprop-sagteware af en installeer inprop-sagteware wat verstel is om outomaties op te dateer.",
+ "TaskUpdatePlugins": "Dateer Inprop-Sagteware Op",
+ "TaskRefreshPeopleDescription": "Vervris metadata oor akteurs en regisseurs in u media versameling.",
+ "TaskRefreshPeople": "Vervris Mense",
+ "TaskCleanLogsDescription": "Vee loglêers wat ouer as {0} dae is uit.",
+ "TaskCleanLogs": "Reinig Loglêer Lêervouer",
+ "TaskRefreshLibraryDescription": "Skandeer u media versameling vir nuwe lêers en verfris metadata.",
+ "TaskRefreshLibrary": "Skandeer Media Versameling",
+ "TaskRefreshChapterImagesDescription": "Maak kleinkiekeis (fotos) vir films wat hoofstukke het.",
+ "TaskRefreshChapterImages": "Verkry Hoofstuk Beelde",
+ "Undefined": "Ongedefineerd",
+ "Forced": "Geforseer",
+ "Default": "Oorspronklik",
+ "TaskCleanActivityLogDescription": "Verwyder aktiwiteitsaantekeninge ouer as die opgestelde ouderdom.",
+ "TaskCleanActivityLog": "Maak Aktiwiteitsaantekeninge Skoon",
+ "TaskOptimizeDatabaseDescription": "Komprimeer databasis en verkort vrye ruimte. As hierdie taak uitgevoer word nadat die media versameling geskandeer is of ander veranderings aangebring is wat databasisaanpassings impliseer, kan dit die prestasie verbeter.",
+ "TaskOptimizeDatabase": "Optimaliseer databasis"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ar.json b/Emby.Server.Implementations/Localization/Core/ar.json
index eb145b4fe..a83a453b4 100644
--- a/Emby.Server.Implementations/Localization/Core/ar.json
+++ b/Emby.Server.Implementations/Localization/Core/ar.json
@@ -1,61 +1,60 @@
{
- "Albums": "الألبومات",
- "AppDeviceValues": "التطبيق: {0}. الجهاز: {1}.",
- "Application": "التطبيق",
- "Artists": "الفنانون",
- "AuthenticationSucceededWithUserName": "تم التأكد من {0} بنجاح",
+ "Albums": "ألبومات",
+ "AppDeviceValues": "تطبيق: {0}, جهاز: {1}",
+ "Application": "تطبيق",
+ "Artists": "الفنانين",
+ "AuthenticationSucceededWithUserName": "{0} سجل الدخول بنجاح",
"Books": "الكتب",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "صورة كاميرا جديدة تم رفعها من {0}",
"Channels": "القنوات",
- "ChapterNameValue": "الباب {0}",
- "Collections": "المجاميع",
- "DeviceOfflineWithName": "تم قطع الاتصال بـ{0}",
+ "ChapterNameValue": "الفصل {0}",
+ "Collections": "التجميعات",
+ "DeviceOfflineWithName": "قُطِع الاتصال ب{0}",
"DeviceOnlineWithName": "{0} متصل",
"FailedLoginAttemptWithUserName": "عملية تسجيل الدخول فشلت من {0}",
- "Favorites": "المفضلات",
+ "Favorites": "مفضلات",
"Folders": "المجلدات",
- "Genres": "أنواع الأفلام",
- "HeaderAlbumArtists": "فنانو الألبومات",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "استئناف المشاهدة",
+ "Genres": "التضنيفات",
+ "HeaderAlbumArtists": "ألبوم الفنان",
+ "HeaderContinueWatching": "استمر بالمشاهدة",
"HeaderFavoriteAlbums": "الألبومات المفضلة",
"HeaderFavoriteArtists": "الفنانون المفضلون",
"HeaderFavoriteEpisodes": "الحلقات المفضلة",
"HeaderFavoriteShows": "المسلسلات المفضلة",
"HeaderFavoriteSongs": "الأغاني المفضلة",
"HeaderLiveTV": "التلفاز المباشر",
- "HeaderNextUp": "التشغيل التالي",
+ "HeaderNextUp": "التالي",
"HeaderRecordingGroups": "مجموعات التسجيل",
- "HomeVideos": "الفيديوهات المنزلية",
+ "HomeVideos": "الفيديوهات الشخصية",
"Inherit": "توريث",
"ItemAddedWithName": "تم إضافة {0} للمكتبة",
"ItemRemovedWithName": "تم إزالة {0} من المكتبة",
"LabelIpAddressValue": "عنوان الآي بي: {0}",
- "LabelRunningTimeValue": "وقت التشغيل: {0}",
+ "LabelRunningTimeValue": "المدة: {0}",
"Latest": "الأحدث",
- "MessageApplicationUpdated": "لقد تم تحديث خادم أمبي",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdated": "لقد تم تحديث خادم Jellyfin",
+ "MessageApplicationUpdatedTo": "تم تحديث خادم Jellyfin الى {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "تم تحديث إعدادات الخادم في قسم {0}",
"MessageServerConfigurationUpdated": "تم تحديث إعدادات الخادم",
- "MixedContent": "محتوى مخلوط",
+ "MixedContent": "محتوى مختلط",
"Movies": "الأفلام",
"Music": "الموسيقى",
"MusicVideos": "الفيديوهات الموسيقية",
- "NameInstallFailed": "{0} installation failed",
+ "NameInstallFailed": "فشل التثبيت {0}",
"NameSeasonNumber": "الموسم {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameSeasonUnknown": "الموسم غير معروف",
+ "NewVersionIsAvailable": "نسخة جديدة من خادم Jellyfin متوفرة للتحميل.",
"NotificationOptionApplicationUpdateAvailable": "يوجد تحديث للتطبيق",
"NotificationOptionApplicationUpdateInstalled": "تم تحديث التطبيق",
"NotificationOptionAudioPlayback": "بدأ تشغيل المقطع الصوتي",
"NotificationOptionAudioPlaybackStopped": "تم إيقاف تشغيل المقطع الصوتي",
- "NotificationOptionCameraImageUploaded": "تم رقع صورة الكاميرا",
- "NotificationOptionInstallationFailed": "عملية التنصيب فشلت",
+ "NotificationOptionCameraImageUploaded": "تم رفع صورة الكاميرا",
+ "NotificationOptionInstallationFailed": "فشل التثبيت",
"NotificationOptionNewLibraryContent": "تم إضافة محتوى جديد",
- "NotificationOptionPluginError": "فشل في الملحق",
+ "NotificationOptionPluginError": "فشل في البرنامج المضاف",
"NotificationOptionPluginInstalled": "تم تثبيت الملحق",
"NotificationOptionPluginUninstalled": "تمت إزالة الملحق",
- "NotificationOptionPluginUpdateInstalled": "تم تحديث الملحق",
+ "NotificationOptionPluginUpdateInstalled": "تم تثبيت تحديثات الملحق",
"NotificationOptionServerRestartRequired": "يجب إعادة تشغيل الخادم",
"NotificationOptionTaskFailed": "فشل في المهمة المجدولة",
"NotificationOptionUserLockedOut": "تم إقفال حساب المستخدم",
@@ -70,28 +69,56 @@
"ProviderValue": "المزود: {0}",
"ScheduledTaskFailedWithName": "العملية {0} فشلت",
"ScheduledTaskStartedWithName": "تم بدء {0}",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
+ "ServerNameNeedsToBeRestarted": "يحتاج لإعادة تشغيله {0}",
+ "Shows": "الحلقات",
"Songs": "الأغاني",
- "StartupEmbyServerIsLoading": "خادم أمبي قيد التحميل. الرجاء المحاوية بعد حين",
+ "StartupEmbyServerIsLoading": "خادم Jellyfin قيد التشغيل . الرجاء المحاولة بعد قليل.",
"SubtitleDownloadFailureForItem": "عملية إنزال الترجمة فشلت لـ{0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "تم إنزال الترجمات لـ {0}",
+ "SubtitleDownloadFailureFromForItem": "الترجمات فشلت في التحميل من {0} الى {1}",
"Sync": "مزامنة",
"System": "النظام",
- "TvShows": "TV Shows",
+ "TvShows": "البرامج التلفزيونية",
"User": "المستخدم",
"UserCreatedWithName": "تم إنشاء المستخدم {0}",
"UserDeletedWithName": "تم حذف المستخدم {0}",
"UserDownloadingItemWithValues": "{0} يقوم بإنزال {1}",
"UserLockedOutWithName": "المستخدم {0} تم منعه من الدخول",
"UserOfflineFromDevice": "تم قطع اتصال {0} من {1}",
- "UserOnlineFromDevice": "{0} متصلة عبر {1}",
+ "UserOnlineFromDevice": "{0} متصل عبر {1}",
"UserPasswordChangedWithName": "تم تغيير كلمة السر للمستخدم {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "قام {0} ببدء تشغيل {1}",
- "UserStoppedPlayingItemWithValues": "قام {0} بإيقاف تشغيل {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserPolicyUpdatedWithName": "تم تحديث سياسة المستخدم {0}",
+ "UserStartedPlayingItemWithValues": "قام {0} ببدء تشغيل {1} على {2}",
+ "UserStoppedPlayingItemWithValues": "قام {0} بإيقاف تشغيل {1} على {2}",
+ "ValueHasBeenAddedToLibrary": "تمت اضافت {0} إلى مكتبة الوسائط",
"ValueSpecialEpisodeName": "خاص - {0}",
- "VersionNumber": "الإصدار رقم {0}"
+ "VersionNumber": "النسخة {0}",
+ "TaskCleanCacheDescription": "يحذف ملفات ذاكرة التخزين المؤقت التي لم يعد النظام بحاجة إليها.",
+ "TaskCleanCache": "احذف مجلد ذاكرة التخزين المؤقت",
+ "TasksChannelsCategory": "قنوات الإنترنت",
+ "TasksLibraryCategory": "مكتبة",
+ "TasksMaintenanceCategory": "صيانة",
+ "TaskRefreshLibraryDescription": "يقوم بفصح مكتبة الوسائط الخاصة بك بحثًا عن ملفات جديدة وتحديث البيانات الوصفية.",
+ "TaskRefreshLibrary": "افحص مكتبة الوسائط",
+ "TaskRefreshChapterImagesDescription": "إنشاء صور مصغرة لمقاطع الفيديو ذات فصول.",
+ "TaskRefreshChapterImages": "استخراج صور الفصل",
+ "TasksApplicationCategory": "تطبيق",
+ "TaskDownloadMissingSubtitlesDescription": "ابحث في الإنترنت على الترجمات المفقودة إستنادا على الميتاداتا.",
+ "TaskDownloadMissingSubtitles": "تحميل الترجمات المفقودة",
+ "TaskRefreshChannelsDescription": "تحديث معلومات قنوات الإنترنت.",
+ "TaskRefreshChannels": "إعادة تحديث القنوات",
+ "TaskCleanTranscodeDescription": "حذف ملفات الترميز الأقدم من يوم واحد.",
+ "TaskCleanTranscode": "حذف سجلات الترميز",
+ "TaskUpdatePluginsDescription": "تحميل وتثبيت الإضافات التي تم تفعيل التحديث التلقائي لها.",
+ "TaskUpdatePlugins": "تحديث الإضافات",
+ "TaskRefreshPeopleDescription": "تحديث البيانات الوصفية للممثلين والمخرجين في مكتبة الوسائط الخاصة بك.",
+ "TaskRefreshPeople": "إعادة تحميل الأشخاص",
+ "TaskCleanLogsDescription": "حذف السجلات الأقدم من {0} يوم.",
+ "TaskCleanLogs": "حذف دليل السجل",
+ "TaskCleanActivityLogDescription": "يحذف سجل الأنشطة الأقدم من الوقت الموضوع.",
+ "TaskCleanActivityLog": "حذف سجل الأنشطة",
+ "Default": "الإعدادات الافتراضية",
+ "Undefined": "غير معرف",
+ "Forced": "ملحقة",
+ "TaskOptimizeDatabaseDescription": "يضغط قاعدة البيانات ويقتطع المساحة الحرة. تشغيل هذه المهمة بعد فحص المكتبة أو إجراء تغييرات أخرى تشير ضمنًا إلى أن تعديلات قاعدة البيانات قد تؤدي إلى تحسين الأداء.",
+ "TaskOptimizeDatabase": "تحسين قاعدة البيانات"
}
diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json
index a71dc9346..e1c923308 100644
--- a/Emby.Server.Implementations/Localization/Core/bg-BG.json
+++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json
@@ -2,21 +2,20 @@
"Albums": "Албуми",
"AppDeviceValues": "Програма: {0}, Устройство: {1}",
"Application": "Програма",
- "Artists": "Изпълнители",
+ "Artists": "Артисти",
"AuthenticationSucceededWithUserName": "{0} се удостовери успешно",
"Books": "Книги",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Нова снимка от камера беше качена от {0}",
"Channels": "Канали",
"ChapterNameValue": "Глава {0}",
"Collections": "Колекции",
"DeviceOfflineWithName": "{0} се разкачи",
"DeviceOnlineWithName": "{0} е свързан",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
+ "FailedLoginAttemptWithUserName": "Неуспешен опит за влизане от {0}",
"Favorites": "Любими",
"Folders": "Папки",
"Genres": "Жанрове",
"HeaderAlbumArtists": "Изпълнители на албуми",
- "HeaderCameraUploads": "Camera Uploads",
"HeaderContinueWatching": "Продължаване на гледането",
"HeaderFavoriteAlbums": "Любими албуми",
"HeaderFavoriteArtists": "Любими изпълнители",
@@ -25,26 +24,26 @@
"HeaderFavoriteSongs": "Любими песни",
"HeaderLiveTV": "Телевизия на живо",
"HeaderNextUp": "Следва",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Домашни клипове",
+ "HeaderRecordingGroups": "Запис групи",
+ "HomeVideos": "Домашни Клипове",
"Inherit": "Наследяване",
"ItemAddedWithName": "{0} е добавено към библиотеката",
"ItemRemovedWithName": "{0} е премахнато от библиотеката",
- "LabelIpAddressValue": "ИП адрес: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
+ "LabelIpAddressValue": "IP адрес: {0}",
+ "LabelRunningTimeValue": "Продължителност: {0}",
"Latest": "Последни",
- "MessageApplicationUpdated": "Сървърът е обновен",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
+ "MessageApplicationUpdated": "Сървърът беше обновен",
+ "MessageApplicationUpdatedTo": "Сървърът беше обновен до {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Секцията {0} от сървърната конфигурация беше актуализирана",
+ "MessageServerConfigurationUpdated": "Конфигурацията на сървъра беше актуализирана",
"MixedContent": "Смесено съдържание",
"Movies": "Филми",
"Music": "Музика",
- "MusicVideos": "Музикални клипове",
- "NameInstallFailed": "{0} installation failed",
+ "MusicVideos": "Музикални Видеа",
+ "NameInstallFailed": "{0} не можа да се инсталира",
"NameSeasonNumber": "Сезон {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameSeasonUnknown": "Неразпознат сезон",
+ "NewVersionIsAvailable": "Нова версия на Jellyfin сървъра е достъпна за сваляне.",
"NotificationOptionApplicationUpdateAvailable": "Налично е обновление на програмата",
"NotificationOptionApplicationUpdateInstalled": "Обновлението на програмата е инсталирано",
"NotificationOptionAudioPlayback": "Възпроизвеждането на звук започна",
@@ -56,42 +55,70 @@
"NotificationOptionPluginInstalled": "Приставката е инсталирана",
"NotificationOptionPluginUninstalled": "Приставката е деинсталирана",
"NotificationOptionPluginUpdateInstalled": "Обновлението на приставката е инсталирано",
- "NotificationOptionServerRestartRequired": "Нужно е повторно пускане на сървъра",
+ "NotificationOptionServerRestartRequired": "Сървърът трябва да се рестартира",
"NotificationOptionTaskFailed": "Грешка в планирана задача",
- "NotificationOptionUserLockedOut": "User locked out",
+ "NotificationOptionUserLockedOut": "Потребителят е заключен",
"NotificationOptionVideoPlayback": "Възпроизвеждането на видео започна",
"NotificationOptionVideoPlaybackStopped": "Възпроизвеждането на видео е спряно",
"Photos": "Снимки",
"Playlists": "Списъци",
- "Plugin": "Приставка",
- "PluginInstalledWithName": "{0} е инсталирано",
- "PluginUninstalledWithName": "{0} е деинсталирано",
- "PluginUpdatedWithName": "{0} е обновено",
+ "Plugin": "Добавка",
+ "PluginInstalledWithName": "{0} е инсталиранa",
+ "PluginUninstalledWithName": "{0} е деинсталиранa",
+ "PluginUpdatedWithName": "{0} е обновенa",
"ProviderValue": "Доставчик: {0}",
"ScheduledTaskFailedWithName": "{0} се провали",
"ScheduledTaskStartedWithName": "{0} започна",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "ServerNameNeedsToBeRestarted": "{0} трябва да се рестартира",
"Shows": "Сериали",
"Songs": "Песни",
"StartupEmbyServerIsLoading": "Сървърът зарежда. Моля, опитайте отново след малко.",
"SubtitleDownloadFailureForItem": "Неуспешно изтегляне на субтитри за {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Изтеглени са субтитри за {0}",
+ "SubtitleDownloadFailureFromForItem": "Субтитрите за {1} от {0} не можаха да бъдат изтеглени",
"Sync": "Синхронизиране",
"System": "Система",
"TvShows": "Телевизионни сериали",
"User": "Потребител",
"UserCreatedWithName": "Потребителят {0} е създаден",
"UserDeletedWithName": "Потребителят {0} е изтрит",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
+ "UserDownloadingItemWithValues": "{0} изтегля {1}",
+ "UserLockedOutWithName": "Потребител {0} се заключи",
"UserOfflineFromDevice": "{0} се разкачи от {1}",
"UserOnlineFromDevice": "{0} е на линия от {1}",
"UserPasswordChangedWithName": "Паролата на потребителя {0} е променена",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
+ "UserPolicyUpdatedWithName": "Потребителската политика за {0} се актуализира",
"UserStartedPlayingItemWithValues": "{0} пусна {1}",
"UserStoppedPlayingItemWithValues": "{0} спря {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "ValueHasBeenAddedToLibrary": "{0} беше добавен във Вашата библиотека",
"ValueSpecialEpisodeName": "Специални - {0}",
- "VersionNumber": "Версия {0}"
+ "VersionNumber": "Версия {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Търси Интернет за липсващи субтитри, на база конфигурацията за мета-данни.",
+ "TaskDownloadMissingSubtitles": "Изтегляне на липсващи субтитри",
+ "TaskRefreshChannelsDescription": "Обновява информацията за интернет канала.",
+ "TaskRefreshChannels": "Обновяване на Канали",
+ "TaskCleanTranscodeDescription": "Изтрива транскодирани файлове по-стари от един ден.",
+ "TaskCleanTranscode": "Изчиства директорията за транскодиране",
+ "TaskUpdatePluginsDescription": "Изтегля и инсталира актуализации за добавките, които са настроени за автоматична актуализация.",
+ "TaskUpdatePlugins": "Актуализира добавките",
+ "TaskRefreshPeopleDescription": "Актуализира мета-данните за артистите и режисьорите за Вашата медийна библиотека.",
+ "TaskRefreshPeople": "Обновяване на участниците",
+ "TaskCleanLogsDescription": "Изтрива лог файлове по-стари от {0} дни.",
+ "TaskCleanLogs": "Изчисти директорията с логове",
+ "TaskRefreshLibraryDescription": "Сканира Вашата библиотека с медия за нови файлове и обновява мета-данните.",
+ "TaskRefreshLibrary": "Сканиране на библиотеката с медия",
+ "TaskRefreshChapterImagesDescription": "Създава иконки за видеа, които имат епизоди.",
+ "TaskRefreshChapterImages": "Извличане на изображения за епизода",
+ "TaskCleanCacheDescription": "Изтриване на ненужните от системата файлове.",
+ "TaskCleanCache": "Изчистване на Кеш-директорията",
+ "TasksChannelsCategory": "Интернет Канали",
+ "TasksApplicationCategory": "Приложение",
+ "TasksLibraryCategory": "Библиотека",
+ "TasksMaintenanceCategory": "Поддръжка",
+ "Undefined": "Неопределено",
+ "Forced": "Принудително",
+ "Default": "По подразбиране",
+ "TaskCleanActivityLogDescription": "Изтрива записите в дневника с активност по стари от конфигурираната възраст.",
+ "TaskCleanActivityLog": "Изчисти дневника с активност",
+ "TaskOptimizeDatabaseDescription": "Прави базата данни по-компактна и освобождава място. Пускането на тази задача след сканиране на библиотеката или правене на други промени, свързани с модификации на базата данни, може да подобри производителността.",
+ "TaskOptimizeDatabase": "Оптимизирай базата данни"
}
diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json
new file mode 100644
index 000000000..c3fbe2408
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/bn.json
@@ -0,0 +1,121 @@
+{
+ "DeviceOnlineWithName": "{0}-এর সাথে সংযুক্ত হয়েছে",
+ "DeviceOfflineWithName": "{0}-এর সাথে সংযোগ বিচ্ছিন্ন হয়েছে",
+ "Collections": "সংগ্রহ",
+ "ChapterNameValue": "অধ্যায় {0}",
+ "Channels": "চ্যানেল",
+ "CameraImageUploadedFrom": "{0} থেকে একটি নতুন ক্যামেরার চিত্র আপলোড করা হয়েছে",
+ "Books": "বই",
+ "AuthenticationSucceededWithUserName": "{0} অনুমোদন সফল",
+ "Artists": "শিল্পীরা",
+ "Application": "অ্যাপ্লিকেশন",
+ "Albums": "অ্যালবামগুলো",
+ "HeaderFavoriteEpisodes": "প্রিব পর্বগুলো",
+ "HeaderFavoriteArtists": "প্রিয় শিল্পীরা",
+ "HeaderFavoriteAlbums": "প্রিয় এলবামগুলো",
+ "HeaderContinueWatching": "দেখতে থাকুন",
+ "HeaderAlbumArtists": "এলবাম শিল্পীবৃন্দ",
+ "Genres": "শৈলী",
+ "Folders": "ফোল্ডারগুলো",
+ "Favorites": "পছন্দসমূহ",
+ "FailedLoginAttemptWithUserName": "{0} লগিন করতে ব্যর্থ হয়েছে",
+ "AppDeviceValues": "অ্যাপ: {0}, ডিভাইস: {0}",
+ "VersionNumber": "সংস্করণ {0}",
+ "ValueSpecialEpisodeName": "বিশেষ - {0}",
+ "ValueHasBeenAddedToLibrary": "আপনার লাইব্রেরিতে {0} যোগ করা হয়েছে",
+ "UserStoppedPlayingItemWithValues": "{2}তে {1} বাজানো শেষ করেছেন {0}",
+ "UserStartedPlayingItemWithValues": "{2}তে {1} বাজাচ্ছেন {0}",
+ "UserPolicyUpdatedWithName": "{0} এর জন্য ব্যবহার নীতি আপডেট করা হয়েছে",
+ "UserPasswordChangedWithName": "ব্যবহারকারী {0} এর পাসওয়ার্ড পরিবর্তিত হয়েছে",
+ "UserOnlineFromDevice": "{0}, {1} থেকে অনলাইন",
+ "UserOfflineFromDevice": "{0} {1} থেকে বিযুক্ত হয়ে গেছে",
+ "UserLockedOutWithName": "ব্যবহারকারী {0} ঢুকতে পারছে না",
+ "UserDownloadingItemWithValues": "{0}, {1} ডাউনলোড করছে",
+ "UserDeletedWithName": "ব্যবহারকারী {0}কে বাদ দেয়া হয়েছে",
+ "UserCreatedWithName": "ব্যবহারকারী {0} সৃষ্টি করা হয়েছে",
+ "User": "ব্যবহারকারী",
+ "TvShows": "টিভি শোগুলো",
+ "System": "সিস্টেম",
+ "Sync": "সিংক",
+ "SubtitleDownloadFailureFromForItem": "{2} থেকে {1} এর জন্য সাবটাইটেল ডাউনলোড ব্যর্থ",
+ "StartupEmbyServerIsLoading": "জেলিফিন সার্ভার লোড হচ্ছে। দয়া করে একটু পরে আবার চেষ্টা করুন।",
+ "Songs": "গানগুলো",
+ "Shows": "টিভি পর্ব",
+ "ServerNameNeedsToBeRestarted": "{0} রিস্টার্ট করা প্রয়োজন",
+ "ScheduledTaskStartedWithName": "{0} শুরু হয়েছে",
+ "ScheduledTaskFailedWithName": "{0} ব্যর্থ",
+ "ProviderValue": "প্রদানকারী: {0}",
+ "PluginUpdatedWithName": "{0} আপডেট করা হয়েছে",
+ "PluginUninstalledWithName": "{0} বাদ দেয়া হয়েছে",
+ "PluginInstalledWithName": "{0} ইন্সটল করা হয়েছে",
+ "Plugin": "প্লাগিন",
+ "Playlists": "প্লেলিস্ট",
+ "Photos": "ছবিগুলো",
+ "NotificationOptionVideoPlaybackStopped": "ভিডিও চলা বন্ধ",
+ "NotificationOptionVideoPlayback": "ভিডিও চলা শুরু হয়েছে",
+ "NotificationOptionUserLockedOut": "ব্যবহারকারী ঢুকতে পারছে না",
+ "NotificationOptionTaskFailed": "পরিকল্পিত কাজটি ব্যর্থ",
+ "NotificationOptionServerRestartRequired": "সার্ভার রিস্টার্ট বাধ্যতামূলক",
+ "NotificationOptionPluginUpdateInstalled": "প্লাগিন আপডেট ইন্সটল করা হয়েছে",
+ "NotificationOptionPluginUninstalled": "প্লাগিন বাদ দেয়া হয়েছে",
+ "NotificationOptionPluginInstalled": "প্লাগিন ইন্সটল করা হয়েছে",
+ "NotificationOptionPluginError": "প্লাগিন ব্যর্থ",
+ "NotificationOptionNewLibraryContent": "নতুন কন্টেন্ট যোগ করা হয়েছে",
+ "NotificationOptionInstallationFailed": "ইন্সটল ব্যর্থ হয়েছে",
+ "NotificationOptionCameraImageUploaded": "ক্যামেরার ছবি আপলোড হয়েছে",
+ "NotificationOptionAudioPlaybackStopped": "গান বাজা বন্ধ হয়েছে",
+ "NotificationOptionAudioPlayback": "গান বাজা শুরু হয়েছে",
+ "NotificationOptionApplicationUpdateInstalled": "এপ্লিকেশনের আপডেট ইনস্টল করা হয়েছে",
+ "NotificationOptionApplicationUpdateAvailable": "এপ্লিকেশনের আপডেট রয়েছে",
+ "NewVersionIsAvailable": "জেলিফিন সার্ভারের একটি নতুন ভার্শন ডাউনলোডের জন্য তৈরী।",
+ "NameSeasonUnknown": "সিজন অজানা",
+ "NameSeasonNumber": "সিজন {0}",
+ "NameInstallFailed": "{0} ইন্সটল ব্যর্থ",
+ "MusicVideos": "গানের ভিডিও",
+ "Music": "গান",
+ "Movies": "চলচ্চিত্র",
+ "MixedContent": "মিশ্র কন্টেন্ট",
+ "MessageServerConfigurationUpdated": "সার্ভারের কনফিগারেশন আপডেট করা হয়েছে",
+ "HeaderRecordingGroups": "রেকর্ডিং দল",
+ "MessageNamedServerConfigurationUpdatedWithValue": "সার্ভারের {0} কনফিগারেসনের অংশ আপডেট করা হয়েছে",
+ "MessageApplicationUpdatedTo": "জেলিফিন সার্ভার {0} তে আপডেট করা হয়েছে",
+ "MessageApplicationUpdated": "জেলিফিন সার্ভার আপডেট করা হয়েছে",
+ "Latest": "সর্বশেষ",
+ "LabelRunningTimeValue": "চলার সময়: {0}",
+ "LabelIpAddressValue": "আইপি এড্রেস: {0}",
+ "ItemRemovedWithName": "{0} লাইব্রেরি থেকে বাদ দেয়া হয়েছে",
+ "ItemAddedWithName": "{0} লাইব্রেরিতে যোগ করা হয়েছে",
+ "Inherit": "থেকে পাওয়া",
+ "HomeVideos": "হোম ভিডিও",
+ "HeaderNextUp": "এরপরে আসছে",
+ "HeaderLiveTV": "লাইভ টিভি",
+ "HeaderFavoriteSongs": "প্রিয় গানগুলো",
+ "HeaderFavoriteShows": "প্রিয় শোগুলো",
+ "TasksLibraryCategory": "গ্রন্থাগার",
+ "TasksMaintenanceCategory": "রক্ষণাবেক্ষণ",
+ "TaskRefreshLibrary": "স্ক্যান মিডিয়া লাইব্রেরি",
+ "TaskRefreshChapterImagesDescription": "অধ্যায়গুলিতে থাকা ভিডিওগুলির জন্য থাম্বনেইল তৈরি ।",
+ "TaskRefreshChapterImages": "অধ্যায়ের চিত্রগুলি বের করুন",
+ "TaskCleanCacheDescription": "সিস্টেমে আর প্রয়োজন নেই ক্যাশ, ফাইলগুলি মুছে ফেলুন।",
+ "TaskCleanCache": "ক্লিন ক্যাশ ডিরেক্টরি",
+ "TasksChannelsCategory": "ইন্টারনেট চ্যানেল",
+ "TasksApplicationCategory": "আবেদন",
+ "TaskDownloadMissingSubtitlesDescription": "মেটাডেটা কনফিগারেশনের উপর ভিত্তি করে অনুপস্থিত সাবটাইটেলগুলির জন্য ইন্টারনেট অনুসন্ধান করে।",
+ "TaskDownloadMissingSubtitles": "অনুপস্থিত সাবটাইটেলগুলি ডাউনলোড করুন",
+ "TaskRefreshChannelsDescription": "ইন্টারনেট চ্যানেল তথ্য রিফ্রেশ করুন।",
+ "TaskRefreshChannels": "চ্যানেল রিফ্রেশ করুন",
+ "TaskCleanTranscodeDescription": "এক দিনেরও বেশি পুরানো ট্রান্সকোড ফাইলগুলি মুছে ফেলুন।",
+ "TaskCleanTranscode": "ট্রান্সকোড ডিরেক্টরি ক্লিন করুন",
+ "TaskUpdatePluginsDescription": "স্বয়ংক্রিয়ভাবে আপডেট কনফিগার করা প্লাগইনগুলির জন্য আপডেট ডাউনলোড এবং ইনস্টল করুন।",
+ "TaskUpdatePlugins": "প্লাগইন আপডেট করুন",
+ "TaskRefreshPeopleDescription": "আপনার মিডিয়া লাইব্রেরিতে অভিনেতা এবং পরিচালকদের জন্য মেটাডাটা আপডেট করুন।",
+ "TaskRefreshPeople": "পিপল রিফ্রেশ করুন",
+ "TaskCleanLogsDescription": "{0} দিনের বেশী পুরানো লগ ফাইলগুলি মুছে ফেলুন।",
+ "TaskCleanLogs": "লগ ডিরেক্টরি ক্লিন করুন",
+ "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।",
+ "Undefined": "অসঙ্গায়িত",
+ "Forced": "জোরকরে",
+ "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন.",
+ "TaskCleanActivityLog": "কাজের ফাইল খালি করুন",
+ "Default": "প্রাথমিক"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ca.json b/Emby.Server.Implementations/Localization/Core/ca.json
index 74406a064..db3c13d80 100644
--- a/Emby.Server.Implementations/Localization/Core/ca.json
+++ b/Emby.Server.Implementations/Localization/Core/ca.json
@@ -1,97 +1,124 @@
{
"Albums": "Àlbums",
- "AppDeviceValues": "App: {0}, Dispositiu: {1}",
- "Application": "Application",
+ "AppDeviceValues": "Aplicació: {0}, Dispositiu: {1}",
+ "Application": "Aplicació",
"Artists": "Artistes",
"AuthenticationSucceededWithUserName": "{0} s'ha autenticat correctament",
"Books": "Llibres",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "S'ha pujat una nova imatge des de la camera desde {0}",
"Channels": "Canals",
- "ChapterNameValue": "Episodi {0}",
+ "ChapterNameValue": "Capítol {0}",
"Collections": "Col·leccions",
"DeviceOfflineWithName": "{0} s'ha desconnectat",
"DeviceOnlineWithName": "{0} està connectat",
"FailedLoginAttemptWithUserName": "Intent de connexió fallit des de {0}",
"Favorites": "Preferits",
- "Folders": "Directoris",
+ "Folders": "Carpetes",
"Genres": "Gèneres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
+ "HeaderAlbumArtists": "Àlbum de l'artista",
"HeaderContinueWatching": "Continua Veient",
"HeaderFavoriteAlbums": "Àlbums Preferits",
- "HeaderFavoriteArtists": "Artistes Preferits",
- "HeaderFavoriteEpisodes": "Episodis Preferits",
- "HeaderFavoriteShows": "Programes Preferits",
- "HeaderFavoriteSongs": "Cançons Preferides",
+ "HeaderFavoriteArtists": "Artistes Predilectes",
+ "HeaderFavoriteEpisodes": "Episodis Predilectes",
+ "HeaderFavoriteShows": "Programes Predilectes",
+ "HeaderFavoriteSongs": "Cançons Predilectes",
"HeaderLiveTV": "TV en Directe",
"HeaderNextUp": "A continuació",
"HeaderRecordingGroups": "Grups d'Enregistrament",
"HomeVideos": "Vídeos domèstics",
- "Inherit": "Heretat",
- "ItemAddedWithName": "{0} afegit a la biblioteca",
- "ItemRemovedWithName": "{0} eliminat de la biblioteca",
+ "Inherit": "Hereta",
+ "ItemAddedWithName": "{0} ha estat afegit a la biblioteca",
+ "ItemRemovedWithName": "{0} ha estat eliminat de la biblioteca",
"LabelIpAddressValue": "Adreça IP: {0}",
- "LabelRunningTimeValue": "Temps en marxa: {0}",
+ "LabelRunningTimeValue": "Temps en funcionament: {0}",
"Latest": "Darreres",
- "MessageApplicationUpdated": "El Servidor d'Jellyfin ha estat actualitzat",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "La secció de configuració {0} ha estat actualitzada",
+ "MessageApplicationUpdated": "El Servidor de Jellyfin ha estat actualitzat",
+ "MessageApplicationUpdatedTo": "El Servidor de Jellyfin ha estat actualitzat a {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "La secció {0} de la configuració del servidor ha estat actualitzada",
"MessageServerConfigurationUpdated": "S'ha actualitzat la configuració del servidor",
- "MixedContent": "Contingut mesclat",
+ "MixedContent": "Contingut barrejat",
"Movies": "Pel·lícules",
"Music": "Música",
"MusicVideos": "Vídeos musicals",
- "NameInstallFailed": "{0} installation failed",
+ "NameInstallFailed": "Instalació de {0} fallida",
"NameSeasonNumber": "Temporada {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameSeasonUnknown": "Temporada Desconeguda",
+ "NewVersionIsAvailable": "Una nova versió del Servidor Jellyfin està disponible per descarregar.",
"NotificationOptionApplicationUpdateAvailable": "Actualització d'aplicació disponible",
"NotificationOptionApplicationUpdateInstalled": "Actualització d'aplicació instal·lada",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Un component ha fallat",
- "NotificationOptionPluginInstalled": "Complement instal·lat",
- "NotificationOptionPluginUninstalled": "Complement desinstal·lat",
- "NotificationOptionPluginUpdateInstalled": "Actualització de complement instal·lada",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
+ "NotificationOptionAudioPlayback": "Reproducció d'audio iniciada",
+ "NotificationOptionAudioPlaybackStopped": "Reproducció d'audio aturada",
+ "NotificationOptionCameraImageUploaded": "Imatge de càmera pujada",
+ "NotificationOptionInstallationFailed": "Instalació fallida",
+ "NotificationOptionNewLibraryContent": "Nou contingut afegit",
+ "NotificationOptionPluginError": "Un connector ha fallat",
+ "NotificationOptionPluginInstalled": "Connector instal·lat",
+ "NotificationOptionPluginUninstalled": "Connector desinstal·lat",
+ "NotificationOptionPluginUpdateInstalled": "Actualització de connector instal·lada",
+ "NotificationOptionServerRestartRequired": "Reinici del servidor requerit",
+ "NotificationOptionTaskFailed": "Tasca programada fallida",
+ "NotificationOptionUserLockedOut": "Usuari tancat",
+ "NotificationOptionVideoPlayback": "Reproducció de video iniciada",
+ "NotificationOptionVideoPlaybackStopped": "Reproducció de video aturada",
"Photos": "Fotos",
"Playlists": "Llistes de reproducció",
- "Plugin": "Plugin",
+ "Plugin": "Connector",
"PluginInstalledWithName": "{0} ha estat instal·lat",
"PluginUninstalledWithName": "{0} ha estat desinstal·lat",
"PluginUpdatedWithName": "{0} ha estat actualitzat",
"ProviderValue": "Proveïdor: {0}",
"ScheduledTaskFailedWithName": "{0} ha fallat",
"ScheduledTaskStartedWithName": "{0} iniciat",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Espectacles",
+ "ServerNameNeedsToBeRestarted": "{0} necessita ser reiniciat",
+ "Shows": "Programes",
"Songs": "Cançons",
"StartupEmbyServerIsLoading": "El Servidor d'Jellyfin est&agrave; carregant. Si et plau, prova de nou en breus.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtítols descarregats per a {0}",
- "Sync": "Sync",
- "System": "System",
+ "SubtitleDownloadFailureFromForItem": "Els subtítols no s'han pogut baixar de {0} per {1}",
+ "Sync": "Sincronitzar",
+ "System": "Sistema",
"TvShows": "Espectacles de TV",
"User": "User",
"UserCreatedWithName": "S'ha creat l'usuari {0}",
"UserDeletedWithName": "L'usuari {0} ha estat eliminat",
"UserDownloadingItemWithValues": "{0} està descarregant {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
+ "UserLockedOutWithName": "L'usuari {0} ha sigut tancat",
"UserOfflineFromDevice": "{0} s'ha desconnectat de {1}",
"UserOnlineFromDevice": "{0} està connectat des de {1}",
"UserPasswordChangedWithName": "La contrasenya ha estat canviada per a l'usuari {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
+ "UserPolicyUpdatedWithName": "La política d'usuari s'ha actualitzat per {0}",
"UserStartedPlayingItemWithValues": "{0} ha començat a reproduir {1}",
"UserStoppedPlayingItemWithValues": "{0} ha parat de reproduir {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "ValueHasBeenAddedToLibrary": "{0} ha sigut afegit a la teva llibreria",
"ValueSpecialEpisodeName": "Especial - {0}",
- "VersionNumber": "Versió {0}"
+ "VersionNumber": "Versió {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Cerca a internet els subtítols que faltin a partir de la configuració de metadades.",
+ "TaskDownloadMissingSubtitles": "Descarrega els subtítols que faltin",
+ "TaskRefreshChannelsDescription": "Actualitza la informació dels canals d'internet.",
+ "TaskRefreshChannels": "Actualitza Canals",
+ "TaskCleanTranscodeDescription": "Elimina els arxius temporals de transcodificacions que tinguin més d'un dia.",
+ "TaskCleanTranscode": "Neteja les transcodificacions",
+ "TaskUpdatePluginsDescription": "Actualitza les extensions que estan configurades per actualitzar-se automàticament.",
+ "TaskUpdatePlugins": "Actualitza les extensions",
+ "TaskRefreshPeopleDescription": "Actualitza les metadades dels actors i directors de la teva mediateca.",
+ "TaskRefreshPeople": "Actualitza Persones",
+ "TaskCleanLogsDescription": "Esborra els logs que tinguin més de {0} dies.",
+ "TaskCleanLogs": "Neteja els registres",
+ "TaskRefreshLibraryDescription": "Escaneja la mediateca buscant fitxers nous i refresca les metadades.",
+ "TaskRefreshLibrary": "Escaneja la biblioteca de mitjans",
+ "TaskRefreshChapterImagesDescription": "Crea les miniatures dels vídeos que tinguin capítols.",
+ "TaskRefreshChapterImages": "Extreure les imatges dels capítols",
+ "TaskCleanCacheDescription": "Elimina els arxius temporals que ja no són necessaris per al servidor.",
+ "TaskCleanCache": "Elimina arxius temporals",
+ "TasksChannelsCategory": "Canals d'internet",
+ "TasksApplicationCategory": "Aplicació",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Manteniment",
+ "TaskCleanActivityLogDescription": "Eliminat entrades del registre d'activitats mes antigues que l'antiguitat configurada.",
+ "TaskCleanActivityLog": "Buidar Registre d'Activitat",
+ "Undefined": "Indefinit",
+ "Forced": "Forçat",
+ "Default": "Defecto",
+ "TaskOptimizeDatabaseDescription": "Compacta la base de dades i trunca l'espai lliure. Executar aquesta tasca després d’escanejar la biblioteca o fer altres canvis que impliquin modificacions a la base de dades pot millorar el rendiment.",
+ "TaskOptimizeDatabase": "Optimitzar la base de dades"
}
diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json
index a8b4a4424..1ea378321 100644
--- a/Emby.Server.Implementations/Localization/Core/cs.json
+++ b/Emby.Server.Implementations/Localization/Core/cs.json
@@ -5,7 +5,7 @@
"Artists": "Umělci",
"AuthenticationSucceededWithUserName": "{0} úspěšně ověřen",
"Books": "Knihy",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Z {0} byla nahrána nová fotografie z fotoaparátu",
"Channels": "Kanály",
"ChapterNameValue": "Kapitola {0}",
"Collections": "Kolekce",
@@ -15,18 +15,17 @@
"Favorites": "Oblíbené",
"Folders": "Složky",
"Genres": "Žánry",
- "HeaderAlbumArtists": "Umělci alba",
- "HeaderCameraUploads": "Camera Uploads",
+ "HeaderAlbumArtists": "Album umělce",
"HeaderContinueWatching": "Pokračovat ve sledování",
"HeaderFavoriteAlbums": "Oblíbená alba",
- "HeaderFavoriteArtists": "Oblíbení umělci",
+ "HeaderFavoriteArtists": "Oblíbení interpreti",
"HeaderFavoriteEpisodes": "Oblíbené epizody",
"HeaderFavoriteShows": "Oblíbené seriály",
- "HeaderFavoriteSongs": "Oblíbené písně",
- "HeaderLiveTV": "Živá TV",
+ "HeaderFavoriteSongs": "Oblíbená hudba",
+ "HeaderLiveTV": "Televize",
"HeaderNextUp": "Nadcházející",
"HeaderRecordingGroups": "Skupiny nahrávek",
- "HomeVideos": "Domáci videa",
+ "HomeVideos": "Domácí videa",
"Inherit": "Zdědit",
"ItemAddedWithName": "{0} byl přidán do knihovny",
"ItemRemovedWithName": "{0} byl odstraněn z knihovny",
@@ -34,17 +33,17 @@
"LabelRunningTimeValue": "Délka média: {0}",
"Latest": "Nejnovější",
"MessageApplicationUpdated": "Jellyfin Server byl aktualizován",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin server byl aktualizován na verzi {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Konfigurace sekce {0} na serveru byla aktualizována",
"MessageServerConfigurationUpdated": "Konfigurace serveru aktualizována",
"MixedContent": "Smíšený obsah",
"Movies": "Filmy",
"Music": "Hudba",
- "MusicVideos": "Hudební klipy",
- "NameInstallFailed": "{0} installation failed",
+ "MusicVideos": "Hudební videa",
+ "NameInstallFailed": "Instalace {0} selhala",
"NameSeasonNumber": "Sezóna {0}",
"NameSeasonUnknown": "Neznámá sezóna",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NewVersionIsAvailable": "Nová verze Jellyfin serveru je k dispozici ke stažení.",
"NotificationOptionApplicationUpdateAvailable": "Dostupná aktualizace aplikace",
"NotificationOptionApplicationUpdateInstalled": "Aktualizace aplikace instalována",
"NotificationOptionAudioPlayback": "Přehrávání audia zahájeno",
@@ -70,13 +69,12 @@
"ProviderValue": "Poskytl: {0}",
"ScheduledTaskFailedWithName": "{0} selhalo",
"ScheduledTaskStartedWithName": "{0} zahájeno",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "ServerNameNeedsToBeRestarted": "{0} vyžaduje restart",
"Shows": "Seriály",
"Songs": "Skladby",
"StartupEmbyServerIsLoading": "Jellyfin Server je spouštěn. Zkuste to prosím v brzké době znovu.",
"SubtitleDownloadFailureForItem": "Stahování titulků selhalo pro {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Staženy titulky pro {0}",
+ "SubtitleDownloadFailureFromForItem": "Stažení titulků pro {1} z {0} selhalo",
"Sync": "Synchronizace",
"System": "Systém",
"TvShows": "TV seriály",
@@ -88,10 +86,39 @@
"UserOfflineFromDevice": "{0} se odpojil od {1}",
"UserOnlineFromDevice": "{0} se připojil z {1}",
"UserPasswordChangedWithName": "Provedena změna hesla pro uživatele {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
+ "UserPolicyUpdatedWithName": "Zásady uživatele pro {0} byly aktualizovány",
"UserStartedPlayingItemWithValues": "{0} spustil přehrávání {1}",
"UserStoppedPlayingItemWithValues": "{0} zastavil přehrávání {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "ValueHasBeenAddedToLibrary": "{0} byl přidán do vaší knihovny médií",
"ValueSpecialEpisodeName": "Speciál - {0}",
- "VersionNumber": "Verze {0}"
+ "VersionNumber": "Verze {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Vyhledá na internetu chybějící titulky na základě nastavení metadat.",
+ "TaskDownloadMissingSubtitles": "Stáhnout chybějící titulky",
+ "TaskRefreshChannelsDescription": "Obnoví informace o internetových kanálech.",
+ "TaskRefreshChannels": "Obnovit kanály",
+ "TaskCleanTranscodeDescription": "Odstraní více než 1 den staré transkódované soubory.",
+ "TaskCleanTranscode": "Vyčistit adresář s transkódovaným obsahem",
+ "TaskUpdatePluginsDescription": "Stáhne a nainstaluje aktualizace zásuvných modulů, které mají nastavenou automatickou aktualizaci.",
+ "TaskUpdatePlugins": "Aktualizovat zásuvné moduly",
+ "TaskRefreshPeopleDescription": "Aktualizuje metadata umělců a režisérů ve Vaší knihovně médií.",
+ "TaskRefreshPeople": "Obnovit umělce",
+ "TaskCleanLogsDescription": "Odstraní soubory protokolu, které jsou starší více než {0} dní.",
+ "TaskCleanLogs": "Vyčistit adresář se souborem protokolu",
+ "TaskRefreshLibraryDescription": "Prohledá Vaši knihovnu médií zda neobsahuje nové soubory a obnoví metadatada.",
+ "TaskRefreshLibrary": "Prohledat knihovnu médií",
+ "TaskRefreshChapterImagesDescription": "Vytvoří náhledy videí, které obsahují kapitoly.",
+ "TaskRefreshChapterImages": "Extrahovat obrázky kapitol",
+ "TaskCleanCacheDescription": "Odstraní soubory mezipaměti, které systém již nebude potřebovat.",
+ "TaskCleanCache": "Vyčistit složku s mezipamětí",
+ "TasksChannelsCategory": "Internetové kanály",
+ "TasksApplicationCategory": "Aplikace",
+ "TasksLibraryCategory": "Knihovna",
+ "TasksMaintenanceCategory": "Údržba",
+ "TaskCleanActivityLogDescription": "Smazat záznamy o aktivitě, které jsou starší než zadaná doba.",
+ "TaskCleanActivityLog": "Smazat záznam aktivity",
+ "Undefined": "Nedefinované",
+ "Forced": "Vynucené",
+ "Default": "Výchozí",
+ "TaskOptimizeDatabaseDescription": "Zmenší databázi a odstraní prázdné místo. Spuštění této úlohy po skenování knihovny či jiných změnách databáze může zlepšit výkon.",
+ "TaskOptimizeDatabase": "Optimalizovat databázi"
}
diff --git a/Emby.Server.Implementations/Localization/Core/cy.json b/Emby.Server.Implementations/Localization/Core/cy.json
new file mode 100644
index 000000000..0fa72dea4
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/cy.json
@@ -0,0 +1,14 @@
+{
+ "DeviceOnlineWithName": "Mae {0} wedi'i gysylltu",
+ "DeviceOfflineWithName": "Mae {0} wedi datgysylltu",
+ "Default": "Diofyn",
+ "Collections": "Casgliadau",
+ "ChapterNameValue": "Pennod {0}",
+ "Channels": "Sianeli",
+ "CameraImageUploadedFrom": "Mae delwedd camera newydd wedi'i lanlwytho o {0}",
+ "Books": "Llyfrau",
+ "AuthenticationSucceededWithUserName": "{0} wedi’i ddilysu’n llwyddiannus",
+ "Artists": "Artistiaid",
+ "AppDeviceValues": "Ap: {0}, Dyfais: {1}",
+ "Albums": "Albwmau"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/da.json b/Emby.Server.Implementations/Localization/Core/da.json
index 9d4d74099..cfe365f57 100644
--- a/Emby.Server.Implementations/Localization/Core/da.json
+++ b/Emby.Server.Implementations/Localization/Core/da.json
@@ -1,9 +1,9 @@
{
- "Albums": "Album",
+ "Albums": "Albummer",
"AppDeviceValues": "App: {0}, Enhed: {1}",
"Application": "Applikation",
"Artists": "Kunstnere",
- "AuthenticationSucceededWithUserName": "{0} bekræftet med succes",
+ "AuthenticationSucceededWithUserName": "{0} succesfuldt autentificeret",
"Books": "Bøger",
"CameraImageUploadedFrom": "Et nyt kamerabillede er blevet uploadet fra {0}",
"Channels": "Kanaler",
@@ -15,15 +15,14 @@
"Favorites": "Favoritter",
"Folders": "Mapper",
"Genres": "Genrer",
- "HeaderAlbumArtists": "Albumkunstnere",
- "HeaderCameraUploads": "Kamera Uploads",
+ "HeaderAlbumArtists": "Kunstnerens album",
"HeaderContinueWatching": "Fortsæt Afspilning",
- "HeaderFavoriteAlbums": "Favoritalbum",
+ "HeaderFavoriteAlbums": "Favoritalbummer",
"HeaderFavoriteArtists": "Favoritkunstnere",
- "HeaderFavoriteEpisodes": "Favorit-afsnit",
- "HeaderFavoriteShows": "Favorit-serier",
- "HeaderFavoriteSongs": "Favorit-sange",
- "HeaderLiveTV": "Live TV",
+ "HeaderFavoriteEpisodes": "Favoritepisoder",
+ "HeaderFavoriteShows": "Favoritserier",
+ "HeaderFavoriteSongs": "Favoritsange",
+ "HeaderLiveTV": "Live-TV",
"HeaderNextUp": "Næste",
"HeaderRecordingGroups": "Optagelsesgrupper",
"HomeVideos": "Hjemmevideoer",
@@ -35,12 +34,12 @@
"Latest": "Seneste",
"MessageApplicationUpdated": "Jellyfin Server er blevet opdateret",
"MessageApplicationUpdatedTo": "Jellyfin Server er blevet opdateret til {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Serverkonfigurationsafsnit {0} er blevet opdateret",
- "MessageServerConfigurationUpdated": "Serverkonfigurationen er blevet opdateret",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Server konfiguration sektion {0} er blevet opdateret",
+ "MessageServerConfigurationUpdated": "Server konfigurationen er blevet opdateret",
"MixedContent": "Blandet indhold",
"Movies": "Film",
"Music": "Musik",
- "MusicVideos": "Musikvideoer",
+ "MusicVideos": "Musik videoer",
"NameInstallFailed": "{0} installationen mislykkedes",
"NameSeasonNumber": "Sæson {0}",
"NameSeasonUnknown": "Ukendt Sæson",
@@ -50,7 +49,7 @@
"NotificationOptionAudioPlayback": "Lydafspilning påbegyndt",
"NotificationOptionAudioPlaybackStopped": "Lydafspilning stoppet",
"NotificationOptionCameraImageUploaded": "Kamerabillede uploadet",
- "NotificationOptionInstallationFailed": "Installationsfejl",
+ "NotificationOptionInstallationFailed": "Installationen fejlede",
"NotificationOptionNewLibraryContent": "Nyt indhold tilføjet",
"NotificationOptionPluginError": "Pluginfejl",
"NotificationOptionPluginInstalled": "Plugin installeret",
@@ -61,8 +60,8 @@
"NotificationOptionUserLockedOut": "Bruger låst ude",
"NotificationOptionVideoPlayback": "Videoafspilning påbegyndt",
"NotificationOptionVideoPlaybackStopped": "Videoafspilning stoppet",
- "Photos": "Fotos",
- "Playlists": "Spillelister",
+ "Photos": "Fotoer",
+ "Playlists": "Afspilningslister",
"Plugin": "Plugin",
"PluginInstalledWithName": "{0} blev installeret",
"PluginUninstalledWithName": "{0} blev afinstalleret",
@@ -76,7 +75,6 @@
"StartupEmbyServerIsLoading": "Jellyfin Server er i gang med at starte op. Prøv venligst igen om lidt.",
"SubtitleDownloadFailureForItem": "Fejlet i download af undertekster for {0}",
"SubtitleDownloadFailureFromForItem": "Undertekster kunne ikke downloades fra {0} til {1}",
- "SubtitlesDownloadedForItem": "Undertekster downloadet for {0}",
"Sync": "Synk",
"System": "System",
"TvShows": "TV serier",
@@ -93,5 +91,34 @@
"UserStoppedPlayingItemWithValues": "{0} har afsluttet afspilning af {1} på {2}",
"ValueHasBeenAddedToLibrary": "{0} er blevet tilføjet til dit mediebibliotek",
"ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Søger på internettet efter manglende undertekster baseret på metadata konfiguration.",
+ "TaskDownloadMissingSubtitles": "Download manglende undertekster",
+ "TaskUpdatePluginsDescription": "Downloader og installere opdateringer for plugins som er konfigureret til at opdatere automatisk.",
+ "TaskUpdatePlugins": "Opdater Plugins",
+ "TaskCleanLogsDescription": "Sletter log filer som er mere end {0} dage gammle.",
+ "TaskCleanLogs": "Ryd Log Mappe",
+ "TaskRefreshLibraryDescription": "Scanner dit medie bibliotek for nye filer og opdaterer metadata.",
+ "TaskRefreshLibrary": "Scan Medie Bibliotek",
+ "TaskCleanCacheDescription": "Sletter cache filer som systemet ikke har brug for længere.",
+ "TaskCleanCache": "Ryd Cache Mappe",
+ "TasksChannelsCategory": "Internet Kanaler",
+ "TasksApplicationCategory": "Applikation",
+ "TasksLibraryCategory": "Bibliotek",
+ "TasksMaintenanceCategory": "Vedligeholdelse",
+ "TaskRefreshChapterImages": "Udtræk Kapitel billeder",
+ "TaskRefreshChapterImagesDescription": "Lav miniaturebilleder for videoer der har kapitler.",
+ "TaskRefreshChannelsDescription": "Genopfrisker internet kanal information.",
+ "TaskRefreshChannels": "Genopfrisk Kanaler",
+ "TaskCleanTranscodeDescription": "Fjern transcode filer som er mere end en dag gammel.",
+ "TaskCleanTranscode": "Rengør Transcode Mappen",
+ "TaskRefreshPeople": "Genopfrisk Personer",
+ "TaskRefreshPeopleDescription": "Opdatere metadata for skuespillere og instruktører i dit bibliotek.",
+ "TaskCleanActivityLogDescription": "Sletter linjer i aktivitetsloggen ældre end den konfigureret alder.",
+ "TaskCleanActivityLog": "Ryd Aktivitetslog",
+ "Undefined": "Udefineret",
+ "Forced": "Tvunget",
+ "Default": "Standard",
+ "TaskOptimizeDatabaseDescription": "Kompakter database og forkorter fri plads. Ved at køre denne proces efter at scanne biblioteket eller efter at ændre noget som kunne have indflydelse på databasen, kan forbedre ydeevne.",
+ "TaskOptimizeDatabase": "Optimér database"
}
diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json
index 6fd63a514..c924e5c15 100644
--- a/Emby.Server.Implementations/Localization/Core/de.json
+++ b/Emby.Server.Implementations/Localization/Core/de.json
@@ -3,31 +3,30 @@
"AppDeviceValues": "App: {0}, Gerät: {1}",
"Application": "Anwendung",
"Artists": "Interpreten",
- "AuthenticationSucceededWithUserName": "{0} hat sich angemeldet",
+ "AuthenticationSucceededWithUserName": "{0} erfolgreich authentifiziert",
"Books": "Bücher",
- "CameraImageUploadedFrom": "Ein neues Foto wurde hochgeladen von {0}",
+ "CameraImageUploadedFrom": "Ein neues Kamerafoto wurde von {0} hochgeladen",
"Channels": "Kanäle",
"ChapterNameValue": "Kapitel {0}",
"Collections": "Sammlungen",
- "DeviceOfflineWithName": "{0} wurde getrennt",
- "DeviceOnlineWithName": "{0} hat sich verbunden",
+ "DeviceOfflineWithName": "{0} hat die Verbindung getrennt",
+ "DeviceOnlineWithName": "{0} ist verbunden",
"FailedLoginAttemptWithUserName": "Fehlgeschlagener Anmeldeversuch von {0}",
"Favorites": "Favoriten",
"Folders": "Verzeichnisse",
"Genres": "Genres",
"HeaderAlbumArtists": "Album-Interpreten",
- "HeaderCameraUploads": "Kamera-Uploads",
"HeaderContinueWatching": "Weiterschauen",
"HeaderFavoriteAlbums": "Lieblingsalben",
"HeaderFavoriteArtists": "Lieblings-Interpreten",
"HeaderFavoriteEpisodes": "Lieblingsepisoden",
"HeaderFavoriteShows": "Lieblingsserien",
"HeaderFavoriteSongs": "Lieblingslieder",
- "HeaderLiveTV": "Live-TV",
+ "HeaderLiveTV": "Live TV",
"HeaderNextUp": "Als Nächstes",
"HeaderRecordingGroups": "Aufnahme-Gruppen",
"HomeVideos": "Heimvideos",
- "Inherit": "Übernehmen",
+ "Inherit": "Vererben",
"ItemAddedWithName": "{0} wurde der Bibliothek hinzugefügt",
"ItemRemovedWithName": "{0} wurde aus der Bibliothek entfernt",
"LabelIpAddressValue": "IP-Adresse: {0}",
@@ -35,7 +34,7 @@
"Latest": "Neueste",
"MessageApplicationUpdated": "Jellyfin-Server wurde aktualisiert",
"MessageApplicationUpdatedTo": "Jellyfin-Server wurde auf Version {0} aktualisiert",
- "MessageNamedServerConfigurationUpdatedWithValue": "Der Server Einstellungsbereich {0} wurde aktualisiert",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Der Server-Einstellungsbereich {0} wurde aktualisiert",
"MessageServerConfigurationUpdated": "Servereinstellungen wurden aktualisiert",
"MixedContent": "Gemischte Inhalte",
"Movies": "Filme",
@@ -50,7 +49,7 @@
"NotificationOptionAudioPlayback": "Audiowiedergabe gestartet",
"NotificationOptionAudioPlaybackStopped": "Audiowiedergabe gestoppt",
"NotificationOptionCameraImageUploaded": "Foto hochgeladen",
- "NotificationOptionInstallationFailed": "Installationsfehler",
+ "NotificationOptionInstallationFailed": "Installation fehlgeschlagen",
"NotificationOptionNewLibraryContent": "Neuer Inhalt hinzugefügt",
"NotificationOptionPluginError": "Plugin-Fehler",
"NotificationOptionPluginInstalled": "Plugin installiert",
@@ -76,7 +75,6 @@
"StartupEmbyServerIsLoading": "Jellyfin-Server startet, 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",
- "SubtitlesDownloadedForItem": "Untertitel heruntergeladen für {0}",
"Sync": "Synchronisation",
"System": "System",
"TvShows": "TV-Sendungen",
@@ -93,5 +91,34 @@
"UserStoppedPlayingItemWithValues": "{0} hat die Wiedergabe von {1} auf {2} beendet",
"ValueHasBeenAddedToLibrary": "{0} wurde deiner Bibliothek hinzugefügt",
"ValueSpecialEpisodeName": "Extra - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Durchsucht das Internet nach fehlenden Untertiteln, basierend auf den Meta Einstellungen.",
+ "TaskDownloadMissingSubtitles": "Lade fehlende Untertitel herunter",
+ "TaskRefreshChannelsDescription": "Aktualisiere Internet Kanal Informationen.",
+ "TaskRefreshChannels": "Aktualisiere Kanäle",
+ "TaskCleanTranscodeDescription": "Löscht Transkodierdateien, welche älter als einen Tag sind.",
+ "TaskCleanTranscode": "Lösche Transkodier-Pfad",
+ "TaskUpdatePluginsDescription": "Lädt Updates für Plugins herunter, welche für automatische Updates konfiguriert sind und installiert diese.",
+ "TaskUpdatePlugins": "Aktualisiere Plugins",
+ "TaskRefreshPeopleDescription": "Aktualisiert Metadaten für Schauspieler und Regisseure in deinen Bibliotheken.",
+ "TaskRefreshPeople": "Aktualisiere Schauspieler",
+ "TaskCleanLogsDescription": "Lösche Log Dateien, die älter als {0} Tage sind.",
+ "TaskCleanLogs": "Lösche Log-Verzeichnis",
+ "TaskRefreshLibraryDescription": "Scanne alle Bibliotheken nach neu hinzugefügten Dateien und aktualisiere Metadaten.",
+ "TaskRefreshLibrary": "Scanne Medien-Bibliothek",
+ "TaskRefreshChapterImagesDescription": "Erstellt Vorschaubilder für Videos, welche Kapitel besitzen.",
+ "TaskRefreshChapterImages": "Extrahiert Kapitel-Bilder",
+ "TaskCleanCacheDescription": "Löscht nicht mehr benötigte Zwischenspeicherdateien.",
+ "TaskCleanCache": "Leere Zwischenspeicher",
+ "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",
+ "Undefined": "Undefiniert",
+ "Forced": "Erzwungen",
+ "Default": "Standard",
+ "TaskOptimizeDatabaseDescription": "Komprimiert die Datenbank und trimmt den freien Speicherplatz. Die Ausführung dieser Aufgabe nach dem Scannen der Bibliothek oder nach anderen Änderungen, die Datenbankänderungen implizieren, kann die Leistung verbessern.",
+ "TaskOptimizeDatabase": "Datenbank optimieren"
}
diff --git a/Emby.Server.Implementations/Localization/Core/el.json b/Emby.Server.Implementations/Localization/Core/el.json
index 91ca34edc..697063f26 100644
--- a/Emby.Server.Implementations/Localization/Core/el.json
+++ b/Emby.Server.Implementations/Localization/Core/el.json
@@ -3,7 +3,7 @@
"AppDeviceValues": "Εφαρμογή: {0}, Συσκευή: {1}",
"Application": "Εφαρμογή",
"Artists": "Καλλιτέχνες",
- "AuthenticationSucceededWithUserName": "{0} επιτυχείς σύνδεση",
+ "AuthenticationSucceededWithUserName": "Ο χρήστης {0} επαληθεύτηκε επιτυχώς",
"Books": "Βιβλία",
"CameraImageUploadedFrom": "Μια νέα εικόνα κάμερας έχει αποσταλεί από {0}",
"Channels": "Κανάλια",
@@ -15,9 +15,8 @@
"Favorites": "Αγαπημένα",
"Folders": "Φάκελοι",
"Genres": "Είδη",
- "HeaderAlbumArtists": "Άλμπουμ Καλλιτεχνών",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Συνεχίστε να παρακολουθείτε",
+ "HeaderAlbumArtists": "Άλμπουμ Καλλιτέχνη",
+ "HeaderContinueWatching": "Συνεχίστε την παρακολούθηση",
"HeaderFavoriteAlbums": "Αγαπημένα Άλμπουμ",
"HeaderFavoriteArtists": "Αγαπημένοι Καλλιτέχνες",
"HeaderFavoriteEpisodes": "Αγαπημένα Επεισόδια",
@@ -27,20 +26,20 @@
"HeaderNextUp": "Επόμενο",
"HeaderRecordingGroups": "Γκρουπ Εγγραφών",
"HomeVideos": "Προσωπικά βίντεο",
- "Inherit": "Inherit",
+ "Inherit": "Κληρονόμηση",
"ItemAddedWithName": "{0} προστέθηκε στη βιβλιοθήκη",
"ItemRemovedWithName": "{0} διαγράφηκε από τη βιβλιοθήκη",
"LabelIpAddressValue": "Διεύθυνση IP: {0}",
"LabelRunningTimeValue": "Διάρκεια: {0}",
"Latest": "Πρόσφατα",
"MessageApplicationUpdated": "Ο Jellyfin Server έχει ενημερωθεί",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Ο server Jellyfin αναβαθμίστηκε σε έκδοση {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Η ενότητα {0} ρύθμισης παραμέτρων του server έχει ενημερωθεί",
"MessageServerConfigurationUpdated": "Η ρύθμιση παραμέτρων του server έχει ενημερωθεί",
"MixedContent": "Ανάμεικτο Περιεχόμενο",
"Movies": "Ταινίες",
"Music": "Μουσική",
- "MusicVideos": "Μουσικά βίντεο",
+ "MusicVideos": "Μουσικά Βίντεο",
"NameInstallFailed": "{0} η εγκατάσταση απέτυχε",
"NameSeasonNumber": "Κύκλος {0}",
"NameSeasonUnknown": "Άγνωστος Κύκλος",
@@ -49,7 +48,7 @@
"NotificationOptionApplicationUpdateInstalled": "Η ενημέρωση εφαρμογής εγκαταστάθηκε",
"NotificationOptionAudioPlayback": "Η αναπαραγωγή ήχου ξεκίνησε",
"NotificationOptionAudioPlaybackStopped": "Η αναπαραγωγή ήχου σταμάτησε",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
+ "NotificationOptionCameraImageUploaded": "Μεταφορτώθηκε φωτογραφία απο κάμερα",
"NotificationOptionInstallationFailed": "Αποτυχία εγκατάστασης",
"NotificationOptionNewLibraryContent": "Προστέθηκε νέο περιεχόμενο",
"NotificationOptionPluginError": "Αποτυχία του plugin",
@@ -63,7 +62,7 @@
"NotificationOptionVideoPlaybackStopped": "Η αναπαραγωγή βίντεο σταμάτησε",
"Photos": "Φωτογραφίες",
"Playlists": "Λίστες αναπαραγωγής",
- "Plugin": "Plugin",
+ "Plugin": "Πρόσθετο",
"PluginInstalledWithName": "{0} εγκαταστήθηκε",
"PluginUninstalledWithName": "{0} έχει απεγκατασταθεί",
"PluginUpdatedWithName": "{0} έχει αναβαθμιστεί",
@@ -75,8 +74,7 @@
"Songs": "Τραγούδια",
"StartupEmbyServerIsLoading": "Ο Jellyfin Server φορτώνει. Παρακαλώ δοκιμάστε σε λίγο.",
"SubtitleDownloadFailureForItem": "Οι υπότιτλοι απέτυχαν να κατέβουν για {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Οι υπότιτλοι κατέβηκαν για {0}",
+ "SubtitleDownloadFailureFromForItem": "Αποτυχίες μεταφόρτωσης υποτίτλων από {0} για {1}",
"Sync": "Συγχρονισμός",
"System": "Σύστημα",
"TvShows": "Τηλεοπτικές Σειρές",
@@ -92,6 +90,35 @@
"UserStartedPlayingItemWithValues": "{0} παίζει {1} σε {2}",
"UserStoppedPlayingItemWithValues": "{0} τελείωσε να παίζει {1} σε {2}",
"ValueHasBeenAddedToLibrary": "{0} προστέθηκαν στη βιβλιοθήκη πολυμέσων σας",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Έκδοση {0}"
+ "ValueSpecialEpisodeName": "Σπέσιαλ - {0}",
+ "VersionNumber": "Έκδοση {0}",
+ "TaskRefreshPeople": "Ανανέωση Ατόμων",
+ "TaskCleanLogsDescription": "Διαγράφει τα αρχεία καταγραφής που είναι άνω των {0} ημερών.",
+ "TaskCleanLogs": "Καθαρισμός Καταλόγου Καταγραφής",
+ "TaskRefreshLibraryDescription": "Σαρώνει την βιβλιοθήκη πολυμέσων σας για νέα αρχεία και αναζωογονεί τα μεταδεδομένα.",
+ "TaskRefreshLibrary": "Βιβλιοθήκη Σάρωσης Πολυμέσων",
+ "TaskRefreshChapterImagesDescription": "Δημιουργεί μικρογραφίες για βίντεο με κεφάλαια.",
+ "TaskRefreshChapterImages": "Εξαγωγή Εικόνων Κεφαλαίου",
+ "TaskCleanCacheDescription": "Τα διαγραμμένα αρχεία προσωρινής μνήμης που δεν χρειάζονται πλέον από το σύστημα.",
+ "TaskCleanCache": "Καθαρισμός Καταλόγου Προσωρινής Μνήμης",
+ "TasksChannelsCategory": "Κανάλια Διαδικτύου",
+ "TasksApplicationCategory": "Εφαρμογή",
+ "TasksLibraryCategory": "Βιβλιοθήκη",
+ "TasksMaintenanceCategory": "Συντήρηση",
+ "TaskDownloadMissingSubtitlesDescription": "Αναζητήσεις στο διαδίκτυο όπου λείπουν υπότιτλους με βάση τη διαμόρφωση μεταδεδομένων.",
+ "TaskDownloadMissingSubtitles": "Λήψη υπότιτλων που λείπουν",
+ "TaskRefreshChannelsDescription": "Ανανεώνει τις πληροφορίες καναλιού στο διαδικτύου.",
+ "TaskRefreshChannels": "Ανανέωση Καναλιών",
+ "TaskCleanTranscodeDescription": "Διαγράφει αρχείου διακωδικοποιητή περισσότερο από μία ημέρα.",
+ "TaskCleanTranscode": "Καθαρισμός Kαταλόγου Διακωδικοποιητή",
+ "TaskUpdatePluginsDescription": "Κατεβάζει και εγκαθιστά ενημερώσεις για τις προσθήκες που έχουν ρυθμιστεί για αυτόματη ενημέρωση.",
+ "TaskUpdatePlugins": "Ενημέρωση Προσθηκών",
+ "TaskRefreshPeopleDescription": "Ενημερώνει μεταδεδομένα για ηθοποιούς και σκηνοθέτες στην βιβλιοθήκη των πολυμέσων σας.",
+ "TaskCleanActivityLogDescription": "Διαγράφει καταχωρήσεις απο το αρχείο καταγραφής παλαιότερες από την επιλεγμένη ηλικία.",
+ "TaskCleanActivityLog": "Καθαρό Αρχείο Καταγραφής Δραστηριοτήτων",
+ "Undefined": "Απροσδιόριστο",
+ "Forced": "Εξαναγκασμένο",
+ "Default": "Προεπιλογή",
+ "TaskOptimizeDatabaseDescription": "Συμπιέζει τη βάση δεδομένων και δημιουργεί ελεύθερο χώρο. Η εκτέλεση αυτής της εργασίας μετά τη σάρωση της βιβλιοθήκης ή την πραγματοποίηση άλλων αλλαγών που συνεπάγονται τροποποιήσεις της βάσης δεδομένων μπορεί να βελτιώσει την απόδοση.",
+ "TaskOptimizeDatabase": "Βελτιστοποίηση βάσης δεδομένων"
}
diff --git a/Emby.Server.Implementations/Localization/Core/en-GB.json b/Emby.Server.Implementations/Localization/Core/en-GB.json
index 67d4068cf..86ce9240e 100644
--- a/Emby.Server.Implementations/Localization/Core/en-GB.json
+++ b/Emby.Server.Implementations/Localization/Core/en-GB.json
@@ -15,8 +15,7 @@
"Favorites": "Favourites",
"Folders": "Folders",
"Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
+ "HeaderAlbumArtists": "Artist's Album",
"HeaderContinueWatching": "Continue Watching",
"HeaderFavoriteAlbums": "Favourite Albums",
"HeaderFavoriteArtists": "Favourite Artists",
@@ -26,7 +25,7 @@
"HeaderLiveTV": "Live TV",
"HeaderNextUp": "Next Up",
"HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
+ "HomeVideos": "Home Videos",
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
@@ -40,7 +39,7 @@
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
- "MusicVideos": "Music videos",
+ "MusicVideos": "Music Videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
@@ -76,7 +75,6 @@
"StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
"Sync": "Sync",
"System": "System",
"TvShows": "TV Shows",
@@ -93,5 +91,34 @@
"UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Searches the internet for missing subtitles based on metadata configuration.",
+ "TaskDownloadMissingSubtitles": "Download missing subtitles",
+ "TaskRefreshChannelsDescription": "Refreshes internet channel information.",
+ "TaskRefreshChannels": "Refresh Channels",
+ "TaskCleanTranscodeDescription": "Deletes transcode files more than one day old.",
+ "TaskCleanTranscode": "Clean Transcode Directory",
+ "TaskUpdatePluginsDescription": "Downloads and installs updates for plugins that are configured to update automatically.",
+ "TaskUpdatePlugins": "Update Plugins",
+ "TaskRefreshPeopleDescription": "Updates metadata for actors and directors in your media library.",
+ "TaskRefreshPeople": "Refresh People",
+ "TaskCleanLogsDescription": "Deletes log files that are more than {0} days old.",
+ "TaskCleanLogs": "Clean Log Directory",
+ "TaskRefreshLibraryDescription": "Scans your media library for new files and refreshes metadata.",
+ "TaskRefreshLibrary": "Scan Media Library",
+ "TaskRefreshChapterImagesDescription": "Creates thumbnails for videos that have chapters.",
+ "TaskRefreshChapterImages": "Extract Chapter Images",
+ "TaskCleanCacheDescription": "Deletes cache files no longer needed by the system.",
+ "TaskCleanCache": "Clean Cache Directory",
+ "TasksChannelsCategory": "Internet Channels",
+ "TasksApplicationCategory": "Application",
+ "TasksLibraryCategory": "Library",
+ "TasksMaintenanceCategory": "Maintenance",
+ "TaskCleanActivityLogDescription": "Deletes activity log entries older than the configured age.",
+ "TaskCleanActivityLog": "Clean Activity Log",
+ "Undefined": "Undefined",
+ "Forced": "Forced",
+ "Default": "Default",
+ "TaskOptimizeDatabaseDescription": "Compacts database and truncates free space. Running this task after scanning the library or doing other changes that imply database modifications might improve performance.",
+ "TaskOptimizeDatabase": "Optimise database"
}
diff --git a/Emby.Server.Implementations/Localization/Core/en-US.json b/Emby.Server.Implementations/Localization/Core/en-US.json
index aa855ed21..ca127cdb8 100644
--- a/Emby.Server.Implementations/Localization/Core/en-US.json
+++ b/Emby.Server.Implementations/Localization/Core/en-US.json
@@ -9,14 +9,15 @@
"Channels": "Channels",
"ChapterNameValue": "Chapter {0}",
"Collections": "Collections",
+ "Default": "Default",
"DeviceOfflineWithName": "{0} has disconnected",
"DeviceOnlineWithName": "{0} is connected",
"FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
"Favorites": "Favorites",
"Folders": "Folders",
+ "Forced": "Forced",
"Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
+ "HeaderAlbumArtists": "Artist's Album",
"HeaderContinueWatching": "Continue Watching",
"HeaderFavoriteAlbums": "Favorite Albums",
"HeaderFavoriteArtists": "Favorite Artists",
@@ -26,7 +27,7 @@
"HeaderLiveTV": "Live TV",
"HeaderNextUp": "Next Up",
"HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
+ "HomeVideos": "Home Videos",
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
@@ -40,7 +41,7 @@
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
- "MusicVideos": "Music videos",
+ "MusicVideos": "Music Videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
@@ -75,10 +76,10 @@
"Songs": "Songs",
"StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
"Sync": "Sync",
"System": "System",
"TvShows": "TV Shows",
+ "Undefined": "Undefined",
"User": "User",
"UserCreatedWithName": "User {0} has been created",
"UserDeletedWithName": "User {0} has been deleted",
@@ -92,5 +93,31 @@
"UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TasksMaintenanceCategory": "Maintenance",
+ "TasksLibraryCategory": "Library",
+ "TasksApplicationCategory": "Application",
+ "TasksChannelsCategory": "Internet Channels",
+ "TaskCleanActivityLog": "Clean Activity Log",
+ "TaskCleanActivityLogDescription": "Deletes activity log entries older than the configured age.",
+ "TaskCleanCache": "Clean Cache Directory",
+ "TaskCleanCacheDescription": "Deletes cache files no longer needed by the system.",
+ "TaskRefreshChapterImages": "Extract Chapter Images",
+ "TaskRefreshChapterImagesDescription": "Creates thumbnails for videos that have chapters.",
+ "TaskRefreshLibrary": "Scan Media Library",
+ "TaskRefreshLibraryDescription": "Scans your media library for new files and refreshes metadata.",
+ "TaskCleanLogs": "Clean Log Directory",
+ "TaskCleanLogsDescription": "Deletes log files that are more than {0} days old.",
+ "TaskRefreshPeople": "Refresh People",
+ "TaskRefreshPeopleDescription": "Updates metadata for actors and directors in your media library.",
+ "TaskUpdatePlugins": "Update Plugins",
+ "TaskUpdatePluginsDescription": "Downloads and installs updates for plugins that are configured to update automatically.",
+ "TaskCleanTranscode": "Clean Transcode Directory",
+ "TaskCleanTranscodeDescription": "Deletes transcode files more than one day old.",
+ "TaskRefreshChannels": "Refresh Channels",
+ "TaskRefreshChannelsDescription": "Refreshes internet channel information.",
+ "TaskDownloadMissingSubtitles": "Download missing subtitles",
+ "TaskDownloadMissingSubtitlesDescription": "Searches the internet for missing subtitles based on metadata configuration.",
+ "TaskOptimizeDatabase": "Optimize database",
+ "TaskOptimizeDatabaseDescription": "Compacts database and truncates free space. Running this task after scanning the library or doing other changes that imply database modifications might improve performance."
}
diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json
new file mode 100644
index 000000000..f92b5f673
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/eo.json
@@ -0,0 +1,123 @@
+{
+ "NotificationOptionInstallationFailed": "Instalada fiasko",
+ "NotificationOptionAudioPlaybackStopped": "Ludado de sono haltis",
+ "NotificationOptionAudioPlayback": "Ludado de sono lanĉis",
+ "NameSeasonUnknown": "Sezono Nekonata",
+ "NameSeasonNumber": "Sezono {0}",
+ "NameInstallFailed": "{0} instalado fiaskis",
+ "Music": "Muziko",
+ "Movies": "Filmoj",
+ "ItemRemovedWithName": "{0} forigis el la plurmediteko",
+ "ItemAddedWithName": "{0} aldonis al la plurmediteko",
+ "HeaderLiveTV": "TV-etero",
+ "HeaderContinueWatching": "Daŭrigi Spektadon",
+ "HeaderAlbumArtists": "Albumo de artisto",
+ "Folders": "Dosierujoj",
+ "DeviceOnlineWithName": "{0} estas konektita",
+ "Default": "Defaŭlte",
+ "Collections": "Kolektoj",
+ "ChapterNameValue": "Ĉapitro {0}",
+ "Channels": "Kanaloj",
+ "Books": "Libroj",
+ "Artists": "Artistoj",
+ "Application": "Aplikaĵo",
+ "AppDeviceValues": "Aplikaĵo: {0}, Aparato: {1}",
+ "Albums": "Albumoj",
+ "TasksLibraryCategory": "Plurmediteko",
+ "VersionNumber": "Versio {0}",
+ "UserDownloadingItemWithValues": "{0} elŝutas {1}",
+ "UserCreatedWithName": "Uzanto {0} kreiĝis",
+ "User": "Uzanto",
+ "System": "Sistemo",
+ "Songs": "Kantoj",
+ "ScheduledTaskStartedWithName": "{0} lanĉis",
+ "ScheduledTaskFailedWithName": "{0} malsukcesis",
+ "PluginUninstalledWithName": "{0} malinstaliĝis",
+ "PluginInstalledWithName": "{0} instaliĝis",
+ "Plugin": "Kromprogramo",
+ "Playlists": "Ludlistoj",
+ "Photos": "Fotoj",
+ "NotificationOptionPluginUninstalled": "Kromprogramo malinstaliĝis",
+ "NotificationOptionNewLibraryContent": "Nova enhavo aldoniĝis",
+ "NotificationOptionPluginInstalled": "Kromprogramo instaliĝis",
+ "MusicVideos": "Muzikvideoj",
+ "LabelIpAddressValue": "IP-adreso: {0}",
+ "Genres": "Ĝenroj",
+ "DeviceOfflineWithName": "{0} malkonektis",
+ "HeaderFavoriteArtists": "Favorataj Artistoj",
+ "Shows": "Serioj",
+ "HeaderFavoriteShows": "Favorataj Serioj",
+ "TvShows": "TV-serioj",
+ "Favorites": "Favoratoj",
+ "TaskCleanLogs": "Purigi Ĵurnalan Katalogon",
+ "TaskRefreshLibrary": "Skanu Plurmeditekon",
+ "ValueSpecialEpisodeName": "Speciala - {0}",
+ "TaskOptimizeDatabase": "Optimigi datumbazon",
+ "TaskRefreshChannels": "Refreŝigi Kanalojn",
+ "TaskUpdatePlugins": "Ĝisdatigi Kromprogramojn",
+ "TaskRefreshPeople": "Refreŝigi Homojn",
+ "TasksChannelsCategory": "Interretaj Kanaloj",
+ "ProviderValue": "Provizanto: {0}",
+ "NotificationOptionPluginError": "Kromprograma malsukceso",
+ "MixedContent": "Miksita enhavo",
+ "TasksApplicationCategory": "Aplikaĵo",
+ "TasksMaintenanceCategory": "Prizorgado",
+ "Undefined": "Nedifinita",
+ "Sync": "Sinkronigo",
+ "Latest": "Plej novaj",
+ "Inherit": "Hereda",
+ "HomeVideos": "Hejmaj Videoj",
+ "HeaderNextUp": "Sekva Plue",
+ "HeaderFavoriteSongs": "Favorataj Kantoj",
+ "HeaderFavoriteEpisodes": "Favorataj Epizodoj",
+ "HeaderFavoriteAlbums": "Favorataj Albumoj",
+ "Forced": "Forcita",
+ "ServerNameNeedsToBeRestarted": "{0} devas esti relanĉita",
+ "NotificationOptionVideoPlayback": "La videoludado lanĉis",
+ "NotificationOptionServerRestartRequired": "Servila relanĉigo bezonata",
+ "TaskOptimizeDatabaseDescription": "Kompaktigas datenbazon kaj trunkas liberan lokon. Lanĉi ĉi tiun taskon post la teka skanado aŭ fari aliajn ŝanĝojn, kiuj implicas datenbazajn modifojn, povus plibonigi rendimenton.",
+ "TaskUpdatePluginsDescription": "Elŝutas kaj instalas ĝisdatigojn por kromprogramojn, kiuj estas agorditaj por ĝisdatigi aŭtomate.",
+ "TaskDownloadMissingSubtitlesDescription": "Serĉas en interreto mankantajn subtekstojn surbaze de metadatena agordaro.",
+ "TaskRefreshPeopleDescription": "Ĝisdatigas metadatenojn por aktoroj kaj reĵisoroj en via plurmediteko.",
+ "TaskCleanLogsDescription": "Forigas ĵurnalajn dosierojn aĝajn pli ol {0} tagojn.",
+ "TaskRefreshLibraryDescription": "Skanas vian plurmeditekon por novaj dosieroj kaj refreŝigas metadatenaron.",
+ "NewVersionIsAvailable": "Nova versio de Jellyfin Server estas elŝutebla.",
+ "TaskCleanCacheDescription": "Forigas stapla dosierojn ne plu necesajn de la sistemo.",
+ "TaskCleanActivityLogDescription": "Forigas aktivecan ĵurnalaĵojn pli malnovajn ol la agordita aĝo.",
+ "TaskCleanTranscodeDescription": "Forigas transkodajn dosierojn aĝajn pli ol unu tagon.",
+ "ValueHasBeenAddedToLibrary": "{0} estis aldonita al via plurmediteko",
+ "SubtitleDownloadFailureFromForItem": "Subtekstoj malsukcesis elŝuti de {0} por {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin Server ŝarĝas. Provi denove baldaŭ.",
+ "TaskRefreshChapterImagesDescription": "Kreas bildetojn por videoj kiuj havas ĉapitrojn.",
+ "UserStoppedPlayingItemWithValues": "{0} finis ludi {1} ĉe {2}",
+ "UserPolicyUpdatedWithName": "Uzanta politiko estis ĝisdatigita por {0}",
+ "UserPasswordChangedWithName": "Pasvorto estis ŝanĝita por uzanto {0}",
+ "UserStartedPlayingItemWithValues": "{0} ludas {1} ĉe {2}",
+ "UserLockedOutWithName": "Uzanto {0} estas elŝlosita",
+ "UserOnlineFromDevice": "{0} estas enreta de {1}",
+ "UserOfflineFromDevice": "{0} malkonektis de {1}",
+ "UserDeletedWithName": "Uzanto {0} estis forigita",
+ "MessageServerConfigurationUpdated": "Servila agordaro estis ĝisdatigita",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Servila agorda sekcio {0} estis ĝisdatigita",
+ "MessageApplicationUpdatedTo": "Jellyfin Server estis ĝisdatigita al {0}",
+ "MessageApplicationUpdated": "Jellyfin Server estis ĝisdatigita",
+ "TaskRefreshChannelsDescription": "Refreŝigas informon pri interretaj kanaloj.",
+ "TaskDownloadMissingSubtitles": "Elŝutu mankantajn subtekstojn",
+ "TaskCleanTranscode": "Malplenigi Transkodadan Katalogon",
+ "TaskRefreshChapterImages": "Eltiru Ĉapitro-Bildojn",
+ "TaskCleanCache": "Malplenigi Staplan Katalogon",
+ "TaskCleanActivityLog": "Malplenigi Aktivecan Ĵurnalon",
+ "PluginUpdatedWithName": "{0} estis ĝisdatigita",
+ "NotificationOptionVideoPlaybackStopped": "La videoludado haltis",
+ "NotificationOptionUserLockedOut": "Uzanto ŝlosita",
+ "NotificationOptionTaskFailed": "Planita tasko malsukcesis",
+ "NotificationOptionPluginUpdateInstalled": "Ĝisdatigo de kromprogramo instalita",
+ "NotificationOptionCameraImageUploaded": "Kamera bildo alŝutita",
+ "NotificationOptionApplicationUpdateInstalled": "Aplikaĵa ĝisdatigo instalita",
+ "NotificationOptionApplicationUpdateAvailable": "Ĝisdatigo de aplikaĵo havebla",
+ "LabelRunningTimeValue": "Ludada tempo: {0}",
+ "HeaderRecordingGroups": "Rikordadaj Grupoj",
+ "FailedLoginAttemptWithUserName": "Malsukcesa ensaluta provo de {0}",
+ "CameraImageUploadedFrom": "Nova kamera bildo estis alŝutita de {0}",
+ "AuthenticationSucceededWithUserName": "{0} sukcese aŭtentikigis"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/es-AR.json b/Emby.Server.Implementations/Localization/Core/es-AR.json
index c01bb0c50..6321f695c 100644
--- a/Emby.Server.Implementations/Localization/Core/es-AR.json
+++ b/Emby.Server.Implementations/Localization/Core/es-AR.json
@@ -1,97 +1,124 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Series",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Albums": "Álbumes",
+ "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}",
+ "Application": "Aplicación",
+ "Artists": "Artistas",
+ "AuthenticationSucceededWithUserName": "{0} autenticado correctamente",
+ "Books": "Libros",
+ "CameraImageUploadedFrom": "Se ha subido una nueva imagen de cámara desde {0}",
+ "Channels": "Canales",
+ "ChapterNameValue": "Capítulo {0}",
+ "Collections": "Colecciones",
+ "DeviceOfflineWithName": "{0} se ha desconectado",
+ "DeviceOnlineWithName": "{0} está conectado",
+ "FailedLoginAttemptWithUserName": "Error al intentar iniciar sesión de {0}",
+ "Favorites": "Favoritos",
+ "Folders": "Carpetas",
+ "Genres": "Géneros",
+ "HeaderAlbumArtists": "Artistas de álbum",
+ "HeaderContinueWatching": "Seguir viendo",
+ "HeaderFavoriteAlbums": "Álbumes favoritos",
+ "HeaderFavoriteArtists": "Artistas favoritos",
+ "HeaderFavoriteEpisodes": "Capítulos favoritos",
+ "HeaderFavoriteShows": "Programas favoritos",
+ "HeaderFavoriteSongs": "Canciones favoritas",
+ "HeaderLiveTV": "TV en vivo",
+ "HeaderNextUp": "Siguiente",
+ "HeaderRecordingGroups": "Grupos de grabación",
+ "HomeVideos": "Videos caseros",
+ "Inherit": "Heredar",
+ "ItemAddedWithName": "{0} se ha añadido a la biblioteca",
+ "ItemRemovedWithName": "{0} ha sido eliminado de la biblioteca",
+ "LabelIpAddressValue": "Dirección IP: {0}",
+ "LabelRunningTimeValue": "Tiempo de funcionamiento: {0}",
+ "Latest": "Últimos",
+ "MessageApplicationUpdated": "El servidor Jellyfin fue actualizado",
+ "MessageApplicationUpdatedTo": "Se ha actualizado el servidor Jellyfin a la versión {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Se ha actualizado la sección {0} de la configuración del servidor",
+ "MessageServerConfigurationUpdated": "Se ha actualizado la configuración del servidor",
+ "MixedContent": "Contenido mezclado",
+ "Movies": "Películas",
+ "Music": "Música",
+ "MusicVideos": "Videos musicales",
+ "NameInstallFailed": "{0} instalación fallida",
+ "NameSeasonNumber": "Temporada {0}",
+ "NameSeasonUnknown": "Temporada desconocida",
+ "NewVersionIsAvailable": "Una nueva versión del servidor Jellyfin está disponible para descargar.",
+ "NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
+ "NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
+ "NotificationOptionAudioPlayback": "Se inició la reproducción de audio",
+ "NotificationOptionAudioPlaybackStopped": "Se detuvo la reproducción de audio",
+ "NotificationOptionCameraImageUploaded": "Imagen de la cámara subida",
+ "NotificationOptionInstallationFailed": "Error de instalación",
+ "NotificationOptionNewLibraryContent": "Nuevo contenido añadido",
+ "NotificationOptionPluginError": "Falla de complemento",
+ "NotificationOptionPluginInstalled": "Complemento instalado",
+ "NotificationOptionPluginUninstalled": "Complemento desinstalado",
+ "NotificationOptionPluginUpdateInstalled": "Actualización de complemento instalada",
+ "NotificationOptionServerRestartRequired": "Se necesita reiniciar el servidor",
+ "NotificationOptionTaskFailed": "Falla de tarea programada",
+ "NotificationOptionUserLockedOut": "Usuario bloqueado",
+ "NotificationOptionVideoPlayback": "Se inició la reproducción de video",
+ "NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
+ "Photos": "Fotos",
+ "Playlists": "Listas de reproducción",
+ "Plugin": "Complemento",
+ "PluginInstalledWithName": "{0} fue instalado",
+ "PluginUninstalledWithName": "{0} fue desinstalado",
+ "PluginUpdatedWithName": "{0} fue actualizado",
+ "ProviderValue": "Proveedor: {0}",
+ "ScheduledTaskFailedWithName": "{0} falló",
+ "ScheduledTaskStartedWithName": "{0} iniciado",
+ "ServerNameNeedsToBeRestarted": "{0} necesita ser reiniciado",
+ "Shows": "Programas",
+ "Songs": "Canciones",
+ "StartupEmbyServerIsLoading": "El servidor Jellyfin se está cargando. Vuelve a intentarlo en breve.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "SubtitleDownloadFailureFromForItem": "Falló la descarga de subtitulos desde {0} para {1}",
+ "Sync": "Sincronizar",
+ "System": "Sistema",
+ "TvShows": "Series de TV",
+ "User": "Usuario",
+ "UserCreatedWithName": "El usuario {0} ha sido creado",
+ "UserDeletedWithName": "El usuario {0} ha sido borrado",
+ "UserDownloadingItemWithValues": "{0} está descargando {1}",
+ "UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
+ "UserOfflineFromDevice": "{0} se ha desconectado de {1}",
+ "UserOnlineFromDevice": "{0} está en línea desde {1}",
+ "UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
+ "UserPolicyUpdatedWithName": "Las política de usuario ha sido actualizada para {0}",
+ "UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
+ "UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
+ "ValueHasBeenAddedToLibrary": "{0} ha sido añadido a tu biblioteca multimedia",
+ "ValueSpecialEpisodeName": "Especial - {0}",
+ "VersionNumber": "Versión {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Busca en internet los subtítulos que falten basándose en la configuración de los metadatos.",
+ "TaskDownloadMissingSubtitles": "Descargar subtítulos faltantes",
+ "TaskRefreshChannelsDescription": "Actualizar información de canales de internet.",
+ "TaskRefreshChannels": "Actualizar canales",
+ "TaskCleanTranscodeDescription": "Eliminar archivos transcodificados con mas de un día de antigüedad.",
+ "TaskCleanTranscode": "Limpiar directorio de transcodificación",
+ "TaskUpdatePluginsDescription": "Descargar e instalar actualizaciones para complementos que estén configurados en actualizar automáticamente.",
+ "TaskUpdatePlugins": "Actualizar complementos",
+ "TaskRefreshPeopleDescription": "Actualizar metadatos de actores y directores en su biblioteca multimedia.",
+ "TaskRefreshPeople": "Actualizar personas",
+ "TaskCleanLogsDescription": "Eliminar archivos de registro que tengan mas de {0} días de antigüedad.",
+ "TaskCleanLogs": "Limpiar directorio de registros",
+ "TaskRefreshLibraryDescription": "Escanear su biblioteca multimedia por nuevos archivos y refrescar metadatos.",
+ "TaskRefreshLibrary": "Escanear biblioteca multimedia",
+ "TaskRefreshChapterImagesDescription": "Crear miniaturas de videos que tengan capítulos.",
+ "TaskRefreshChapterImages": "Extraer imágenes de capítulo",
+ "TaskCleanCacheDescription": "Eliminar archivos de caché que no se necesiten en el sistema.",
+ "TaskCleanCache": "Limpiar directorio caché",
+ "TasksChannelsCategory": "Canales de internet",
+ "TasksApplicationCategory": "Aplicación",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Mantenimiento",
+ "TaskCleanActivityLogDescription": "Borrar log de actividades anteriores a la fecha establecida.",
+ "TaskCleanActivityLog": "Borrar log de actividades",
+ "Undefined": "Indefinido",
+ "Forced": "Forzado",
+ "Default": "Por Defecto",
+ "TaskOptimizeDatabaseDescription": "Compacta la base de datos y restaura el espacio libre. Ejecutar esta tarea después de actualizar las librerías o realizar otros cambios que impliquen modificar las bases de datos puede mejorar la performance.",
+ "TaskOptimizeDatabase": "Optimización de base de datos"
}
diff --git a/Emby.Server.Implementations/Localization/Core/es-MX.json b/Emby.Server.Implementations/Localization/Core/es-MX.json
index 2285f2808..432814dac 100644
--- a/Emby.Server.Implementations/Localization/Core/es-MX.json
+++ b/Emby.Server.Implementations/Localization/Core/es-MX.json
@@ -11,27 +11,26 @@
"Collections": "Colecciones",
"DeviceOfflineWithName": "{0} se ha desconectado",
"DeviceOnlineWithName": "{0} está conectado",
- "FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión de {0}",
+ "FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión desde {0}",
"Favorites": "Favoritos",
"Folders": "Carpetas",
"Genres": "Géneros",
"HeaderAlbumArtists": "Artistas del Álbum",
- "HeaderCameraUploads": "Subidos desde Camara",
- "HeaderContinueWatching": "Continuar Viendo",
- "HeaderFavoriteAlbums": "Álbumes Favoritos",
- "HeaderFavoriteArtists": "Artistas Favoritos",
- "HeaderFavoriteEpisodes": "Episodios Preferidos",
- "HeaderFavoriteShows": "Programas Preferidos",
- "HeaderFavoriteSongs": "Canciones Favoritas",
- "HeaderLiveTV": "TV en Vivo",
- "HeaderNextUp": "A Continuación",
- "HeaderRecordingGroups": "Grupos de Grabaciones",
- "HomeVideos": "Videos caseros",
+ "HeaderContinueWatching": "Continuar viendo",
+ "HeaderFavoriteAlbums": "Álbumes favoritos",
+ "HeaderFavoriteArtists": "Artistas favoritos",
+ "HeaderFavoriteEpisodes": "Episodios favoritos",
+ "HeaderFavoriteShows": "Programas favoritos",
+ "HeaderFavoriteSongs": "Canciones favoritas",
+ "HeaderLiveTV": "TV en vivo",
+ "HeaderNextUp": "A continuación",
+ "HeaderRecordingGroups": "Grupos de grabación",
+ "HomeVideos": "Videos Caseros",
"Inherit": "Heredar",
"ItemAddedWithName": "{0} fue agregado a la biblioteca",
"ItemRemovedWithName": "{0} fue removido de la biblioteca",
"LabelIpAddressValue": "Dirección IP: {0}",
- "LabelRunningTimeValue": "Duración: {0}",
+ "LabelRunningTimeValue": "Tiempo de reproducción: {0}",
"Latest": "Recientes",
"MessageApplicationUpdated": "El servidor Jellyfin ha sido actualizado",
"MessageApplicationUpdatedTo": "El servidor Jellyfin ha sido actualizado a {0}",
@@ -40,23 +39,23 @@
"MixedContent": "Contenido mezclado",
"Movies": "Películas",
"Music": "Música",
- "MusicVideos": "Videos musicales",
- "NameInstallFailed": "{0} instalación fallida",
+ "MusicVideos": "Videos Musicales",
+ "NameInstallFailed": "Falló la instalación de {0}",
"NameSeasonNumber": "Temporada {0}",
- "NameSeasonUnknown": "Temporada Desconocida",
+ "NameSeasonUnknown": "Temporada desconocida",
"NewVersionIsAvailable": "Una nueva versión del Servidor Jellyfin está disponible para descargar.",
- "NotificationOptionApplicationUpdateAvailable": "Actualización de aplicación disponible",
- "NotificationOptionApplicationUpdateInstalled": "Actualización de aplicación instalada",
+ "NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
+ "NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
"NotificationOptionAudioPlayback": "Reproducción de audio iniciada",
"NotificationOptionAudioPlaybackStopped": "Reproducción de audio detenida",
"NotificationOptionCameraImageUploaded": "Imagen de la cámara subida",
- "NotificationOptionInstallationFailed": "Falla de instalación",
+ "NotificationOptionInstallationFailed": "Fallo en la instalación",
"NotificationOptionNewLibraryContent": "Nuevo contenido agregado",
"NotificationOptionPluginError": "Falla de complemento",
"NotificationOptionPluginInstalled": "Complemento instalado",
"NotificationOptionPluginUninstalled": "Complemento desinstalado",
"NotificationOptionPluginUpdateInstalled": "Actualización de complemento instalada",
- "NotificationOptionServerRestartRequired": "Se necesita reiniciar el Servidor",
+ "NotificationOptionServerRestartRequired": "Se necesita reiniciar el servidor",
"NotificationOptionTaskFailed": "Falla de tarea programada",
"NotificationOptionUserLockedOut": "Usuario bloqueado",
"NotificationOptionVideoPlayback": "Reproducción de video iniciada",
@@ -69,29 +68,57 @@
"PluginUpdatedWithName": "{0} fue actualizado",
"ProviderValue": "Proveedor: {0}",
"ScheduledTaskFailedWithName": "{0} falló",
- "ScheduledTaskStartedWithName": "{0} Iniciado",
- "ServerNameNeedsToBeRestarted": "{0} debe ser reiniciado",
+ "ScheduledTaskStartedWithName": "{0} iniciado",
+ "ServerNameNeedsToBeRestarted": "{0} necesita ser reiniciado",
"Shows": "Programas",
"Songs": "Canciones",
- "StartupEmbyServerIsLoading": "El servidor Jellyfin esta cargando. Por favor intente de nuevo dentro de poco.",
+ "StartupEmbyServerIsLoading": "El servidor Jellyfin está cargando. Por favor, intente de nuevo pronto.",
"SubtitleDownloadFailureForItem": "Falló la descarga de subtítulos para {0}",
- "SubtitleDownloadFailureFromForItem": "Falló la descarga de subtitulos desde {0} para {1}",
- "SubtitlesDownloadedForItem": "Subtítulos descargados para {0}",
+ "SubtitleDownloadFailureFromForItem": "Falló la descarga de subtítulos desde {0} para {1}",
"Sync": "Sincronizar",
"System": "Sistema",
"TvShows": "Programas de TV",
"User": "Usuario",
- "UserCreatedWithName": "Se ha creado el usuario {0}",
- "UserDeletedWithName": "Se ha eliminado el usuario {0}",
- "UserDownloadingItemWithValues": "{0} esta descargando {1}",
+ "UserCreatedWithName": "El usuario {0} ha sido creado",
+ "UserDeletedWithName": "El usuario {0} ha sido eliminado",
+ "UserDownloadingItemWithValues": "{0} está descargando {1}",
"UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
"UserOfflineFromDevice": "{0} se ha desconectado desde {1}",
"UserOnlineFromDevice": "{0} está en línea desde {1}",
"UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
- "UserPolicyUpdatedWithName": "Las política de usuario ha sido actualizada por {0}",
- "UserStartedPlayingItemWithValues": "{0} está reproduciéndose {1} en {2}",
- "UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducirse {1} en {2}",
- "ValueHasBeenAddedToLibrary": "{0} se han añadido a su biblioteca de medios",
+ "UserPolicyUpdatedWithName": "La política de usuario ha sido actualizada para {0}",
+ "UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
+ "UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
+ "ValueHasBeenAddedToLibrary": "{0} se ha añadido a tu biblioteca de medios",
"ValueSpecialEpisodeName": "Especial - {0}",
- "VersionNumber": "Versión {0}"
+ "VersionNumber": "Versión {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Busca subtítulos faltantes en Internet basándose en la configuración de metadatos.",
+ "TaskDownloadMissingSubtitles": "Descargar subtítulos faltantes",
+ "TaskRefreshChannelsDescription": "Actualiza la información de los canales de Internet.",
+ "TaskRefreshChannels": "Actualizar canales",
+ "TaskCleanTranscodeDescription": "Elimina archivos transcodificados que tengan más de un día de antigüedad.",
+ "TaskCleanTranscode": "Limpiar directorio de transcodificado",
+ "TaskUpdatePluginsDescription": "Descarga e instala actualizaciones para complementos que están configurados para actualizarse automáticamente.",
+ "TaskUpdatePlugins": "Actualizar complementos",
+ "TaskRefreshPeopleDescription": "Actualiza metadatos de actores y directores en tu biblioteca de medios.",
+ "TaskRefreshPeople": "Actualizar personas",
+ "TaskCleanLogsDescription": "Elimina archivos de registro con más de {0} días de antigüedad.",
+ "TaskCleanLogs": "Limpiar directorio de registros",
+ "TaskRefreshLibraryDescription": "Escanea tu biblioteca de medios por archivos nuevos y actualiza los metadatos.",
+ "TaskRefreshLibrary": "Escanear biblioteca de medios",
+ "TaskRefreshChapterImagesDescription": "Crea miniaturas para videos que tienen capítulos.",
+ "TaskRefreshChapterImages": "Extraer imágenes de los capítulos",
+ "TaskCleanCacheDescription": "Elimina archivos caché que ya no son necesarios para el sistema.",
+ "TaskCleanCache": "Limpiar directorio caché",
+ "TasksChannelsCategory": "Canales de Internet",
+ "TasksApplicationCategory": "Aplicación",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Mantenimiento",
+ "TaskCleanActivityLogDescription": "Elimina entradas del registro de actividad que sean más antiguas al periodo establecido.",
+ "TaskCleanActivityLog": "Limpiar registro de actividades",
+ "Undefined": "Sin definir",
+ "Forced": "Forzado",
+ "Default": "Predeterminado",
+ "TaskOptimizeDatabase": "Optimizar base de datos",
+ "TaskOptimizeDatabaseDescription": "Compacta la base de datos y trunca el espacio libre. Puede mejorar el rendimiento si se realiza esta tarea después de escanear la biblioteca o después de realizar otros cambios que impliquen modificar la base de datos."
}
diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json
index 1850b8f25..d3d9d2703 100644
--- a/Emby.Server.Implementations/Localization/Core/es.json
+++ b/Emby.Server.Implementations/Localization/Core/es.json
@@ -3,7 +3,7 @@
"AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}",
"Application": "Aplicación",
"Artists": "Artistas",
- "AuthenticationSucceededWithUserName": "{0} autenticado correctamente",
+ "AuthenticationSucceededWithUserName": "{0} identificado correctamente",
"Books": "Libros",
"CameraImageUploadedFrom": "Se ha subido una nueva imagen de cámara desde {0}",
"Channels": "Canales",
@@ -15,16 +15,15 @@
"Favorites": "Favoritos",
"Folders": "Carpetas",
"Genres": "Géneros",
- "HeaderAlbumArtists": "Artistas del álbum",
- "HeaderCameraUploads": "Subidas desde cámara",
+ "HeaderAlbumArtists": "Artista del álbum",
"HeaderContinueWatching": "Continuar viendo",
"HeaderFavoriteAlbums": "Álbumes favoritos",
"HeaderFavoriteArtists": "Artistas favoritos",
"HeaderFavoriteEpisodes": "Episodios favoritos",
- "HeaderFavoriteShows": "Programas favoritos",
+ "HeaderFavoriteShows": "Series favoritas",
"HeaderFavoriteSongs": "Canciones favoritas",
- "HeaderLiveTV": "TV en directo",
- "HeaderNextUp": "Siguiendo",
+ "HeaderLiveTV": "Televisión en directo",
+ "HeaderNextUp": "Siguiente",
"HeaderRecordingGroups": "Grupos de grabación",
"HomeVideos": "Vídeos caseros",
"Inherit": "Heredar",
@@ -50,7 +49,7 @@
"NotificationOptionAudioPlayback": "Se inició la reproducción de audio",
"NotificationOptionAudioPlaybackStopped": "Se detuvo la reproducción de audio",
"NotificationOptionCameraImageUploaded": "Imagen de la cámara cargada",
- "NotificationOptionInstallationFailed": "Error de instalación",
+ "NotificationOptionInstallationFailed": "Error en la instalación",
"NotificationOptionNewLibraryContent": "Nuevo contenido añadido",
"NotificationOptionPluginError": "Error en plugin",
"NotificationOptionPluginInstalled": "Plugin instalado",
@@ -76,16 +75,15 @@
"StartupEmbyServerIsLoading": "Jellyfin Server se está cargando. Vuelve a intentarlo en breve.",
"SubtitleDownloadFailureForItem": "Error al descargar subtítulos para {0}",
"SubtitleDownloadFailureFromForItem": "Fallo de descarga de subtítulos desde {0} para {1}",
- "SubtitlesDownloadedForItem": "Descargar subtítulos para {0}",
"Sync": "Sincronizar",
"System": "Sistema",
- "TvShows": "Series de TV",
+ "TvShows": "Series",
"User": "Usuario",
"UserCreatedWithName": "El usuario {0} ha sido creado",
"UserDeletedWithName": "El usuario {0} ha sido borrado",
"UserDownloadingItemWithValues": "{0} está descargando {1}",
"UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
- "UserOfflineFromDevice": "{0} se ha desconectado de {1}",
+ "UserOfflineFromDevice": "{0} se ha desconectado desde {1}",
"UserOnlineFromDevice": "{0} está en línea desde {1}",
"UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
"UserPolicyUpdatedWithName": "Actualizada política de usuario para {0}",
@@ -93,5 +91,34 @@
"UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
"ValueHasBeenAddedToLibrary": "{0} ha sido añadido a tu biblioteca multimedia",
"ValueSpecialEpisodeName": "Especial - {0}",
- "VersionNumber": "Versión {0}"
+ "VersionNumber": "Versión {0}",
+ "TasksMaintenanceCategory": "Mantenimiento",
+ "TasksLibraryCategory": "Librería",
+ "TasksApplicationCategory": "Aplicación",
+ "TasksChannelsCategory": "Canales de internet",
+ "TaskCleanCache": "Eliminar archivos temporales",
+ "TaskCleanCacheDescription": "Elimina los archivos temporales que ya no son necesarios para el servidor.",
+ "TaskRefreshChapterImages": "Extraer imágenes de los capítulos",
+ "TaskRefreshChapterImagesDescription": "Crea las miniaturas de los vídeos que tengan capítulos.",
+ "TaskRefreshLibrary": "Escanear la biblioteca",
+ "TaskRefreshLibraryDescription": "Añade los archivos que se hayan añadido a la biblioteca y actualiza las etiquetas de los ya presentes.",
+ "TaskCleanLogs": "Limpiar registros",
+ "TaskCleanLogsDescription": "Elimina los archivos de registro que tengan más de {0} días.",
+ "TaskRefreshPeople": "Actualizar personas",
+ "TaskRefreshPeopleDescription": "Actualiza las etiquetas de los intérpretes y directores presentes en tus bibliotecas.",
+ "TaskUpdatePlugins": "Actualizar extensiones",
+ "TaskUpdatePluginsDescription": "Actualiza las extensiones que están configuradas para actualizarse automáticamente.",
+ "TaskCleanTranscode": "Limpiar las transcodificaciones",
+ "TaskCleanTranscodeDescription": "Elimina los archivos temporales de transcodificación anteriores a un día de antigüedad.",
+ "TaskRefreshChannels": "Actualizar canales",
+ "TaskRefreshChannelsDescription": "Actualiza la información de los canales de internet.",
+ "TaskDownloadMissingSubtitles": "Descargar los subtítulos que faltan",
+ "TaskDownloadMissingSubtitlesDescription": "Busca en internet los subtítulos que falten en el contenido de tus bibliotecas, basándose en la configuración de los metadatos.",
+ "TaskCleanActivityLogDescription": "Elimina todos los registros de actividad anteriores a la fecha configurada.",
+ "TaskCleanActivityLog": "Limpiar registro de actividad",
+ "Undefined": "Indefinido",
+ "Forced": "Forzado",
+ "Default": "Predeterminado",
+ "TaskOptimizeDatabase": "Optimizar la base de datos",
+ "TaskOptimizeDatabaseDescription": "Compacta y libera el espacio libre en la base de datos. Ejecutar esta tarea tras escanear la biblioteca o hacer cambios que impliquen modificaciones en la base de datos puede mejorar el rendimiento."
}
diff --git a/Emby.Server.Implementations/Localization/Core/es_419.json b/Emby.Server.Implementations/Localization/Core/es_419.json
new file mode 100644
index 000000000..a968c6dab
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/es_419.json
@@ -0,0 +1,123 @@
+{
+ "LabelRunningTimeValue": "Tiempo en ejecución: {0}",
+ "ValueSpecialEpisodeName": "Especial - {0}",
+ "Sync": "Sincronizar",
+ "Songs": "Canciones",
+ "Shows": "Programas",
+ "Playlists": "Listas de reproducción",
+ "Photos": "Fotos",
+ "Movies": "Películas",
+ "HeaderNextUp": "A continuación",
+ "HeaderLiveTV": "TV en vivo",
+ "HeaderFavoriteSongs": "Canciones favoritas",
+ "HeaderFavoriteArtists": "Artistas favoritos",
+ "HeaderFavoriteAlbums": "Álbumes favoritos",
+ "HeaderFavoriteEpisodes": "Episodios favoritos",
+ "HeaderFavoriteShows": "Programas favoritos",
+ "HeaderContinueWatching": "Continuar viendo",
+ "HeaderAlbumArtists": "Artistas del álbum",
+ "Genres": "Géneros",
+ "Folders": "Carpetas",
+ "Favorites": "Favoritos",
+ "Collections": "Colecciones",
+ "Channels": "Canales",
+ "Books": "Libros",
+ "Artists": "Artistas",
+ "Albums": "Álbumes",
+ "TaskDownloadMissingSubtitlesDescription": "Busca subtítulos faltantes en Internet basándose en la configuración de metadatos.",
+ "TaskDownloadMissingSubtitles": "Descargar subtítulos faltantes",
+ "TaskRefreshChannelsDescription": "Actualiza la información de canales de Internet.",
+ "TaskRefreshChannels": "Actualizar canales",
+ "TaskCleanTranscodeDescription": "Elimina archivos transcodificados que tengan más de un día.",
+ "TaskCleanTranscode": "Limpiar directorio de transcodificado",
+ "TaskUpdatePluginsDescription": "Descarga e instala actualizaciones para complementos que están configurados para actualizarse automáticamente.",
+ "TaskUpdatePlugins": "Actualizar complementos",
+ "TaskRefreshPeopleDescription": "Actualiza metadatos de actores y directores en tu biblioteca de medios.",
+ "TaskRefreshPeople": "Actualizar personas",
+ "TaskCleanLogsDescription": "Elimina archivos de registro con más de {0} días de antigüedad.",
+ "TaskCleanLogs": "Limpiar directorio de registros",
+ "TaskRefreshLibraryDescription": "Escanea tu biblioteca de medios por archivos nuevos y actualiza los metadatos.",
+ "TaskRefreshLibrary": "Escanear biblioteca de medios",
+ "TaskRefreshChapterImagesDescription": "Crea miniaturas para videos que tienen capítulos.",
+ "TaskRefreshChapterImages": "Extraer imágenes de los capítulos",
+ "TaskCleanCacheDescription": "Elimina archivos caché que ya no son necesarios para el sistema.",
+ "TaskCleanCache": "Limpiar directorio caché",
+ "TasksChannelsCategory": "Canales de Internet",
+ "TasksApplicationCategory": "Aplicación",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Mantenimiento",
+ "VersionNumber": "Versión {0}",
+ "ValueHasBeenAddedToLibrary": "{0} se ha añadido a tu biblioteca de medios",
+ "UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
+ "UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
+ "UserPolicyUpdatedWithName": "La política de usuario ha sido actualizada para {0}",
+ "UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
+ "UserOnlineFromDevice": "{0} está en línea desde {1}",
+ "UserOfflineFromDevice": "{0} se ha desconectado desde {1}",
+ "UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
+ "UserDownloadingItemWithValues": "{0} está descargando {1}",
+ "UserDeletedWithName": "El usuario {0} ha sido eliminado",
+ "UserCreatedWithName": "El usuario {0} ha sido creado",
+ "User": "Usuario",
+ "TvShows": "Programas de TV",
+ "System": "Sistema",
+ "SubtitleDownloadFailureFromForItem": "Falló la descarga de subtítulos desde {0} para {1}",
+ "StartupEmbyServerIsLoading": "El servidor Jellyfin está cargando. Por favor, intente de nuevo pronto.",
+ "ServerNameNeedsToBeRestarted": "{0} debe ser reiniciado",
+ "ScheduledTaskStartedWithName": "{0} iniciado",
+ "ScheduledTaskFailedWithName": "{0} falló",
+ "ProviderValue": "Proveedor: {0}",
+ "PluginUpdatedWithName": "{0} fue actualizado",
+ "PluginUninstalledWithName": "{0} fue desinstalado",
+ "PluginInstalledWithName": "{0} fue instalado",
+ "Plugin": "Complemento",
+ "NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
+ "NotificationOptionVideoPlayback": "Reproducción de video iniciada",
+ "NotificationOptionUserLockedOut": "Usuario bloqueado",
+ "NotificationOptionTaskFailed": "Falla de tarea programada",
+ "NotificationOptionServerRestartRequired": "Se necesita reiniciar el servidor",
+ "NotificationOptionPluginUpdateInstalled": "Actualización de complemento instalada",
+ "NotificationOptionPluginUninstalled": "Complemento desinstalado",
+ "NotificationOptionPluginInstalled": "Complemento instalado",
+ "NotificationOptionPluginError": "Falla de complemento",
+ "NotificationOptionNewLibraryContent": "Nuevo contenido agregado",
+ "NotificationOptionInstallationFailed": "Falla de instalación",
+ "NotificationOptionCameraImageUploaded": "Imagen de la cámara subida",
+ "NotificationOptionAudioPlaybackStopped": "Reproducción de audio detenida",
+ "NotificationOptionAudioPlayback": "Reproducción de audio iniciada",
+ "NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
+ "NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
+ "NewVersionIsAvailable": "Una nueva versión del Servidor Jellyfin está disponible para descargar.",
+ "NameSeasonUnknown": "Temporada desconocida",
+ "NameSeasonNumber": "Temporada {0}",
+ "NameInstallFailed": "Falló la instalación de {0}",
+ "MusicVideos": "Videos musicales",
+ "Music": "Música",
+ "MixedContent": "Contenido mezclado",
+ "MessageServerConfigurationUpdated": "Se ha actualizado la configuración del servidor",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Se ha actualizado la sección {0} de la configuración del servidor",
+ "MessageApplicationUpdatedTo": "El servidor Jellyfin ha sido actualizado a {0}",
+ "MessageApplicationUpdated": "El servidor Jellyfin ha sido actualizado",
+ "Latest": "Recientes",
+ "LabelIpAddressValue": "Dirección IP: {0}",
+ "ItemRemovedWithName": "{0} fue removido de la biblioteca",
+ "ItemAddedWithName": "{0} fue agregado a la biblioteca",
+ "Inherit": "Heredar",
+ "HomeVideos": "Videos caseros",
+ "HeaderRecordingGroups": "Grupos de grabación",
+ "FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión desde {0}",
+ "DeviceOnlineWithName": "{0} está conectado",
+ "DeviceOfflineWithName": "{0} se ha desconectado",
+ "ChapterNameValue": "Capítulo {0}",
+ "CameraImageUploadedFrom": "Una nueva imagen de cámara ha sido subida desde {0}",
+ "AuthenticationSucceededWithUserName": "{0} autenticado con éxito",
+ "Application": "Aplicación",
+ "AppDeviceValues": "App: {0}, Dispositivo: {1}",
+ "TaskCleanActivityLogDescription": "Elimina las entradas del registro de actividad anteriores al periodo configurado.",
+ "TaskCleanActivityLog": "Limpiar Registro de Actividades",
+ "Undefined": "Sin definir",
+ "Forced": "Forzado",
+ "Default": "Por Defecto",
+ "TaskOptimizeDatabaseDescription": "Compacta la base de datos y restaura el espacio libre. Ejecutar esta tarea después de actualizar las librerías o realizar otros cambios que impliquen modificar las bases de datos puede mejorar la performance.",
+ "TaskOptimizeDatabase": "Optimización de base de datos"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/es_DO.json b/Emby.Server.Implementations/Localization/Core/es_DO.json
new file mode 100644
index 000000000..b64ffbfbb
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/es_DO.json
@@ -0,0 +1,23 @@
+{
+ "Channels": "Canales",
+ "Books": "Libros",
+ "Albums": "Álbumes",
+ "Collections": "Colecciones",
+ "Artists": "Artistas",
+ "DeviceOnlineWithName": "{0} está conectado",
+ "DeviceOfflineWithName": "{0} se ha desconectado",
+ "ChapterNameValue": "Capítulo {0}",
+ "CameraImageUploadedFrom": "Se ha subido una nueva imagen de cámara desde {0}",
+ "AuthenticationSucceededWithUserName": "{0} autenticado con éxito",
+ "Application": "Aplicación",
+ "AppDeviceValues": "App: {0}, Dispositivo: {1}",
+ "HeaderContinueWatching": "Continuar Viendo",
+ "HeaderAlbumArtists": "Artistas del Álbum",
+ "Genres": "Géneros",
+ "Folders": "Carpetas",
+ "Favorites": "Favoritos",
+ "FailedLoginAttemptWithUserName": "Intento de inicio de sesión fallido de {0}",
+ "HeaderFavoriteSongs": "Canciones Favoritas",
+ "HeaderFavoriteEpisodes": "Episodios Favoritos",
+ "HeaderFavoriteArtists": "Artistas Favoritos"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/et.json b/Emby.Server.Implementations/Localization/Core/et.json
new file mode 100644
index 000000000..c3596ecf1
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/et.json
@@ -0,0 +1,118 @@
+{
+ "TaskCleanActivityLogDescription": "Kustutab määratud ajast vanemad tegevuslogi kirjed.",
+ "UserDownloadingItemWithValues": "{0} laeb alla {1}",
+ "HeaderRecordingGroups": "Salvestusrühmad",
+ "TaskOptimizeDatabaseDescription": "Tihendab ja puhastab andmebaasi. Selle toimingu tegemine pärast meediakogu andmebaasiga seotud muudatuste skannimist võib jõudlust parandada.",
+ "TaskOptimizeDatabase": "Optimeeri andmebaasi",
+ "TaskDownloadMissingSubtitlesDescription": "Otsib veebist puuduvaid subtiitreid vastavalt määratud metaandmete seadetele.",
+ "TaskDownloadMissingSubtitles": "Laadi alla puuduvad subtiitrid",
+ "TaskRefreshChannelsDescription": "Värskendab veebikanalite teavet.",
+ "TaskRefreshChannels": "Värskenda kanaleid",
+ "TaskCleanTranscodeDescription": "Kustutab üle ühe päeva vanused transkodeerimisfailid.",
+ "TaskCleanTranscode": "Puhasta transkoodimise kataloog",
+ "TaskUpdatePluginsDescription": "Laadib alla ja paigaldab nende pluginate uuendused, mis on seadistatud automaatselt uuenduma.",
+ "TaskUpdatePlugins": "Uuenda pluginaid",
+ "TaskRefreshPeopleDescription": "Värskendab meediakogus näitlejate ja režissööride metaandmeid.",
+ "TaskRefreshPeople": "Värskenda inimesi",
+ "TaskCleanLogsDescription": "Kustutab logifailid, mis on vanemad kui {0} päeva.",
+ "TaskCleanLogs": "Puhasta logikataloog",
+ "TaskRefreshLibraryDescription": "Otsib meedikogust uusi faile ja värskendab metaandmeid.",
+ "Collections": "Kollektsioonid",
+ "TaskRefreshLibrary": "Skaneeri meediakogu",
+ "TaskRefreshChapterImagesDescription": "Loob peatükkidega videote jaoks pisipildid.",
+ "TaskRefreshChapterImages": "Eralda peatükipildid",
+ "TaskCleanCacheDescription": "Kustutab vahemälufailid, mida süsteem enam ei vaja.",
+ "TaskCleanCache": "Puhasta vahemälu kataloog",
+ "TaskCleanActivityLog": "Puhasta tegevuslogi",
+ "TasksChannelsCategory": "Veebikanalid",
+ "TasksApplicationCategory": "Rakendus",
+ "TasksLibraryCategory": "Meediakogu",
+ "TasksMaintenanceCategory": "Hooldus",
+ "VersionNumber": "Versioon {0}",
+ "ValueSpecialEpisodeName": "Eriepisood - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} lisati meediakogusse",
+ "UserStartedPlayingItemWithValues": "{0} taasesitab {1} serveris {2}",
+ "UserPasswordChangedWithName": "Kasutaja {0} parooli on muudetud",
+ "UserLockedOutWithName": "Kasutaja {0} on lukustatud",
+ "UserDeletedWithName": "Kasutaja {0} on kustutatud",
+ "UserCreatedWithName": "Kasutaja {0} on loodud",
+ "ScheduledTaskStartedWithName": "{0} käivitati",
+ "ProviderValue": "Allikas: {0}",
+ "StartupEmbyServerIsLoading": "Jellyfin server laadib. Proovi varsti uuesti.",
+ "User": "Kasutaja",
+ "Undefined": "Määratlemata",
+ "TvShows": "Seriaalid",
+ "System": "Süsteem",
+ "Sync": "Sünkrooni",
+ "Songs": "Laulud",
+ "Shows": "Sarjad",
+ "ServerNameNeedsToBeRestarted": "{0} tuleb taaskäivitada",
+ "ScheduledTaskFailedWithName": "{0} nurjus",
+ "PluginUpdatedWithName": "{0} uuendati",
+ "PluginUninstalledWithName": "{0} eemaldati",
+ "PluginInstalledWithName": "{0} paigaldati",
+ "Plugin": "Plugin",
+ "Playlists": "Pleilistid",
+ "Photos": "Fotod",
+ "NotificationOptionVideoPlaybackStopped": "Video taasesitus on peatatud",
+ "NotificationOptionVideoPlayback": "Video taasesitus algas",
+ "NotificationOptionUserLockedOut": "Kasutaja on lukustatud",
+ "NotificationOptionTaskFailed": "Ajastatud ülesanne nurjus",
+ "NotificationOptionServerRestartRequired": "Vajalik on serveri taaskäivitamine",
+ "NotificationOptionPluginUpdateInstalled": "Paigaldati plugina uuendus",
+ "NotificationOptionPluginUninstalled": "Plugin eemaldati",
+ "NotificationOptionPluginInstalled": "Plugin paigaldati",
+ "NotificationOptionPluginError": "Plugina tõrge",
+ "NotificationOptionNewLibraryContent": "Lisati uut sisu",
+ "NotificationOptionInstallationFailed": "Paigaldamine nurjus",
+ "NotificationOptionCameraImageUploaded": "Kaamera pilt on üles laaditud",
+ "NotificationOptionAudioPlaybackStopped": "Heli taasesitus peatati",
+ "NotificationOptionAudioPlayback": "Heli taasesitus algas",
+ "NotificationOptionApplicationUpdateInstalled": "Rakenduse uuendus paigaldati",
+ "NotificationOptionApplicationUpdateAvailable": "Rakenduse uuendus on saadaval",
+ "NewVersionIsAvailable": "Jellyfin serveri uus versioon on allalaadimiseks saadaval.",
+ "NameSeasonUnknown": "Tundmatu hooaeg",
+ "NameSeasonNumber": "Hooaeg {0}",
+ "NameInstallFailed": "{0} paigaldamine nurjus",
+ "MusicVideos": "Muusikavideod",
+ "Music": "Muusika",
+ "Movies": "Filmid",
+ "MixedContent": "Segatud sisu",
+ "MessageServerConfigurationUpdated": "Serveri seadistust uuendati",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Serveri seadistusosa {0} uuendati",
+ "MessageApplicationUpdatedTo": "Jellyfin server uuendati versioonile {0}",
+ "MessageApplicationUpdated": "Jellyfin server uuendati",
+ "Latest": "Uusimad",
+ "LabelRunningTimeValue": "Kestus: {0}",
+ "LabelIpAddressValue": "IP aadress: {0}",
+ "ItemRemovedWithName": "{0} eemaldati meediakogust",
+ "ItemAddedWithName": "{0} lisati meediakogusse",
+ "Inherit": "Päri",
+ "HomeVideos": "Koduvideod",
+ "HeaderNextUp": "Järgmisena",
+ "HeaderLiveTV": "Otse TV",
+ "HeaderFavoriteSongs": "Lemmiklood",
+ "HeaderFavoriteShows": "Lemmikseriaalid",
+ "HeaderFavoriteEpisodes": "Lemmikepisoodid",
+ "HeaderFavoriteArtists": "Lemmikesitajad",
+ "HeaderFavoriteAlbums": "Lemmikalbumid",
+ "HeaderContinueWatching": "Jätka vaatamist",
+ "HeaderAlbumArtists": "Albumi esitaja",
+ "Genres": "Žanrid",
+ "Forced": "Sunnitud",
+ "Folders": "Kaustad",
+ "Favorites": "Lemmikud",
+ "FailedLoginAttemptWithUserName": "Ebaõnnestunud sisselogimiskatse kasutajalt {0}",
+ "DeviceOnlineWithName": "{0} on ühendatud",
+ "DeviceOfflineWithName": "{0} katkestas ühenduse",
+ "Default": "Vaikimisi",
+ "ChapterNameValue": "Peatükk {0}",
+ "Channels": "Kanalid",
+ "CameraImageUploadedFrom": "Uus kaamera pilt laaditi üles allikalt {0}",
+ "Books": "Raamatud",
+ "AuthenticationSucceededWithUserName": "{0} autentimine õnnestus",
+ "Artists": "Esitajad",
+ "Application": "Rakendus",
+ "AppDeviceValues": "Rakendus: {0}, seade: {1}",
+ "Albums": "Albumid"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/fa.json b/Emby.Server.Implementations/Localization/Core/fa.json
index 0a0c7553b..8ab657e5b 100644
--- a/Emby.Server.Implementations/Localization/Core/fa.json
+++ b/Emby.Server.Implementations/Localization/Core/fa.json
@@ -1,56 +1,55 @@
{
- "Albums": "آلبوم ها",
+ "Albums": "آلبوم‌ها",
"AppDeviceValues": "برنامه: {0} ، دستگاه: {1}",
"Application": "برنامه",
"Artists": "هنرمندان",
"AuthenticationSucceededWithUserName": "{0} با موفقیت تایید اعتبار شد",
- "Books": "کتاب ها",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "کانال ها",
- "ChapterNameValue": "فصل {0}",
- "Collections": "کلکسیون ها",
+ "Books": "کتاب‌ها",
+ "CameraImageUploadedFrom": "یک عکس جدید از دوربین ارسال شده است {0}",
+ "Channels": "کانال‌ها",
+ "ChapterNameValue": "قسمت {0}",
+ "Collections": "مجموعه‌ها",
"DeviceOfflineWithName": "ارتباط {0} قطع شد",
- "DeviceOnlineWithName": "{0} متصل شده",
+ "DeviceOnlineWithName": "{0} متصل شد",
"FailedLoginAttemptWithUserName": "تلاش برای ورود از {0} ناموفق بود",
- "Favorites": "مورد علاقه ها",
- "Folders": "پوشه ها",
+ "Favorites": "مورد علاقه‌ها",
+ "Folders": "پوشه‌ها",
"Genres": "ژانرها",
"HeaderAlbumArtists": "هنرمندان آلبوم",
- "HeaderCameraUploads": "آپلودهای دوربین",
"HeaderContinueWatching": "ادامه تماشا",
- "HeaderFavoriteAlbums": "آلبوم های مورد علاقه",
+ "HeaderFavoriteAlbums": "آلبوم‌های مورد علاقه",
"HeaderFavoriteArtists": "هنرمندان مورد علاقه",
- "HeaderFavoriteEpisodes": "قسمت های مورد علاقه",
- "HeaderFavoriteShows": "سریال های مورد علاقه",
- "HeaderFavoriteSongs": "آهنگ های مورد علاقه",
- "HeaderLiveTV": "پخش زنده تلویزیون",
- "HeaderNextUp": "بعدی چیه",
- "HeaderRecordingGroups": "گروه های ضبط",
+ "HeaderFavoriteEpisodes": "قسمت‌های مورد علاقه",
+ "HeaderFavoriteShows": "سریال‌های مورد علاقه",
+ "HeaderFavoriteSongs": "آهنگ‌های مورد علاقه",
+ "HeaderLiveTV": "پخش زنده",
+ "HeaderNextUp": "قسمت بعدی",
+ "HeaderRecordingGroups": "گروه‌های ضبط",
"HomeVideos": "ویدیوهای خانگی",
"Inherit": "به ارث برده",
"ItemAddedWithName": "{0} به کتابخانه افزوده شد",
"ItemRemovedWithName": "{0} از کتابخانه حذف شد",
"LabelIpAddressValue": "آدرس آی پی: {0}",
"LabelRunningTimeValue": "زمان اجرا: {0}",
- "Latest": "آخرین",
+ "Latest": "جدیدترین‌ها",
"MessageApplicationUpdated": "سرور Jellyfin بروزرسانی شد",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "پکربندی بخش {0} سرور بروزرسانی شد",
+ "MessageApplicationUpdatedTo": "سرور Jellyfin به نسخه {0} بروزرسانی شد",
+ "MessageNamedServerConfigurationUpdatedWithValue": "پکربندی بخش {0} سرور بروزرسانی شد",
"MessageServerConfigurationUpdated": "پیکربندی سرور بروزرسانی شد",
- "MixedContent": "محتوای درهم",
- "Movies": "فیلم های سینمایی",
+ "MixedContent": "محتوای مخلوط",
+ "Movies": "فیلم‌ها",
"Music": "موسیقی",
"MusicVideos": "موزیک ویدیوها",
- "NameInstallFailed": "{0} installation failed",
+ "NameInstallFailed": "{0} نصب با مشکل مواجه شد",
"NameSeasonNumber": "فصل {0}",
- "NameSeasonUnknown": "فصل های ناشناخته",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameSeasonUnknown": "فصل ناشناخته",
+ "NewVersionIsAvailable": "یک نسخه جدید Jellyfin برای بروزرسانی آماده می‌باشد.",
"NotificationOptionApplicationUpdateAvailable": "بروزرسانی برنامه موجود است",
"NotificationOptionApplicationUpdateInstalled": "بروزرسانی برنامه نصب شد",
"NotificationOptionAudioPlayback": "پخش صدا آغاز شد",
"NotificationOptionAudioPlaybackStopped": "پخش صدا متوقف شد",
"NotificationOptionCameraImageUploaded": "تصاویر دوربین آپلود شد",
- "NotificationOptionInstallationFailed": "شکست نصب",
+ "NotificationOptionInstallationFailed": "نصب ناموفق",
"NotificationOptionNewLibraryContent": "محتوای جدید افزوده شد",
"NotificationOptionPluginError": "خرابی افزونه",
"NotificationOptionPluginInstalled": "افزونه نصب شد",
@@ -58,40 +57,66 @@
"NotificationOptionPluginUpdateInstalled": "بروزرسانی افزونه نصب شد",
"NotificationOptionServerRestartRequired": "شروع مجدد سرور نیاز است",
"NotificationOptionTaskFailed": "شکست وظیفه برنامه ریزی شده",
- "NotificationOptionUserLockedOut": "کاربر از سیستم خارج شد",
+ "NotificationOptionUserLockedOut": "کاربر قفل شد",
"NotificationOptionVideoPlayback": "پخش ویدیو آغاز شد",
"NotificationOptionVideoPlaybackStopped": "پخش ویدیو متوقف شد",
- "Photos": "عکس ها",
- "Playlists": "لیست های پخش",
+ "Photos": "عکس‌ها",
+ "Playlists": "لیست‌های پخش",
"Plugin": "افزونه",
"PluginInstalledWithName": "{0} نصب شد",
"PluginUninstalledWithName": "{0} حذف شد",
"PluginUpdatedWithName": "{0} آپدیت شد",
"ProviderValue": "ارائه دهنده: {0}",
- "ScheduledTaskFailedWithName": "{0} ناموفق بود",
+ "ScheduledTaskFailedWithName": "{0} شکست خورد",
"ScheduledTaskStartedWithName": "{0} شروع شد",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "سریال ها",
- "Songs": "آهنگ ها",
+ "ServerNameNeedsToBeRestarted": "{0} نیاز به راه اندازی مجدد دارد",
+ "Shows": "سریال‌ها",
+ "Songs": "موسیقی‌ها",
"StartupEmbyServerIsLoading": "سرور Jellyfin در حال بارگیری است. لطفا کمی بعد دوباره تلاش کنید.",
"SubtitleDownloadFailureForItem": "دانلود زیرنویس برای {0} ناموفق بود",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "زیرنویس {0} دانلود شد",
- "Sync": "همگامسازی",
+ "SubtitleDownloadFailureFromForItem": "بارگیری زیرنویس برای {1} از {0} شکست خورد",
+ "Sync": "همگام‌سازی",
"System": "سیستم",
- "TvShows": "سریال های تلویزیونی",
+ "TvShows": "سریال‌های تلویزیونی",
"User": "کاربر",
"UserCreatedWithName": "کاربر {0} ایجاد شد",
"UserDeletedWithName": "کاربر {0} حذف شد",
- "UserDownloadingItemWithValues": "{0} در حال دانلود است {1}",
- "UserLockedOutWithName": "کاربر {0} از سیستم خارج شد",
+ "UserDownloadingItemWithValues": "{0} در حال بارگیری {1} می‌باشد",
+ "UserLockedOutWithName": "کاربر {0} قفل شده است",
"UserOfflineFromDevice": "ارتباط {0} از {1} قطع شد",
- "UserOnlineFromDevice": "{0}از {1} آنلاین میباشد",
- "UserPasswordChangedWithName": "رمز برای کاربر {0} تغییر یافت",
+ "UserOnlineFromDevice": "{0} از {1} آنلاین می‌باشد",
+ "UserPasswordChangedWithName": "گذرواژه برای کاربر {0} تغییر کرد",
"UserPolicyUpdatedWithName": "سیاست کاربری برای {0} بروزرسانی شد",
- "UserStartedPlayingItemWithValues": "{0} شروع به پخش {1} کرد",
- "UserStoppedPlayingItemWithValues": "{0} پخش {1} را متوقف کرد",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "ویژه- {0}",
- "VersionNumber": "نسخه {0}"
+ "UserStartedPlayingItemWithValues": "{0} در حال پخش {1} بر روی {2} است",
+ "UserStoppedPlayingItemWithValues": "{0} پخش {1} را بر روی {2} به پایان رساند",
+ "ValueHasBeenAddedToLibrary": "{0} به کتابخانه‌ی رسانه‌ی شما افزوده شد",
+ "ValueSpecialEpisodeName": "ویژه - {0}",
+ "VersionNumber": "نسخه {0}",
+ "TaskCleanTranscodeDescription": "فایل‌های کدگذاری که قدیمی‌تر از یک روز هستند را حذف می‌کند.",
+ "TaskCleanTranscode": "پاکسازی مسیر کد گذاری",
+ "TaskUpdatePluginsDescription": "دانلود و نصب به روز رسانی افزونه‌هایی که برای به روز رسانی خودکار پیکربندی شده‌اند.",
+ "TaskDownloadMissingSubtitlesDescription": "جستجوی زیرنویس‌های ناموجود در اینترنت بر اساس پیکربندی ابرداده‌ها.",
+ "TaskDownloadMissingSubtitles": "دانلود زیرنویس‌های ناموجود",
+ "TaskRefreshChannelsDescription": "اطلاعات کانال اینترنتی را تازه سازی می‌کند.",
+ "TaskRefreshChannels": "تازه سازی کانال‌ها",
+ "TaskUpdatePlugins": "به روز رسانی افزونه‌ها",
+ "TaskRefreshPeopleDescription": "ابرداده‌ها برای بازیگران و کارگردانان در کتابخانه رسانه شما به روزرسانی می شوند.",
+ "TaskRefreshPeople": "تازه سازی افراد",
+ "TaskCleanLogsDescription": "واقعه نگارهایی را که قدیمی تر {0} روز هستند را حذف می کند.",
+ "TaskCleanLogs": "پاکسازی مسیر واقعه نگار",
+ "TaskRefreshLibraryDescription": "کتابخانه رسانه شما را اسکن می‌کند و ابرداده‌ها را تازه سازی می‌کند.",
+ "TaskRefreshLibrary": "اسکن کتابخانه رسانه",
+ "TaskRefreshChapterImagesDescription": "عکس‌های کوچک برای ویدیوهایی که سکانس دارند ایجاد می‌کند.",
+ "TaskRefreshChapterImages": "استخراج عکس‌های سکانس",
+ "TaskCleanCacheDescription": "فایل‌های حافظه موقت که توسط سیستم دیگر مورد نیاز نیستند حذف می‌شوند.",
+ "TaskCleanCache": "پاکسازی مسیر حافظه موقت",
+ "TasksChannelsCategory": "کانال‌های داخلی",
+ "TasksApplicationCategory": "برنامه",
+ "TasksLibraryCategory": "کتابخانه",
+ "TasksMaintenanceCategory": "تعمیر",
+ "Forced": "اجباری",
+ "Default": "پیشفرض",
+ "TaskCleanActivityLogDescription": "ورودی‌های قدیمی‌تر از سن تنظیم شده در سیاهه فعالیت را حذف می‌کند.",
+ "TaskCleanActivityLog": "پاکسازی سیاهه فعالیت",
+ "Undefined": "تعریف نشده"
}
diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json
new file mode 100644
index 000000000..4a1f4f1d5
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/fi.json
@@ -0,0 +1,123 @@
+{
+ "HeaderLiveTV": "Suora TV",
+ "NewVersionIsAvailable": "Uusi versio Jellyfin-palvelimesta on ladattavissa.",
+ "NameSeasonUnknown": "Tuntematon kausi",
+ "NameSeasonNumber": "Kausi {0}",
+ "NameInstallFailed": "{0} asennus epäonnistui",
+ "MusicVideos": "Musiikkivideot",
+ "Music": "Musiikki",
+ "Movies": "Elokuvat",
+ "MixedContent": "Sekalainen sisältö",
+ "MessageServerConfigurationUpdated": "Palvelimen asetukset on päivitetty",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Palvelimen asetusten osio {0} on päivitetty",
+ "MessageApplicationUpdatedTo": "Jellyfin-palvelin on päivitetty versioon {0}",
+ "MessageApplicationUpdated": "Jellyfin-palvelin on päivitetty",
+ "Latest": "Viimeisimmät",
+ "LabelRunningTimeValue": "Kesto: {0}",
+ "LabelIpAddressValue": "IP-osoite: {0}",
+ "ItemRemovedWithName": "{0} poistettiin kirjastosta",
+ "ItemAddedWithName": "{0} lisättiin kirjastoon",
+ "Inherit": "Peri",
+ "HomeVideos": "Kotivideot",
+ "HeaderRecordingGroups": "Tallennusryhmät",
+ "HeaderNextUp": "Seuraavaksi",
+ "HeaderFavoriteSongs": "Suosikkikappaleet",
+ "HeaderFavoriteShows": "Suosikkisarjat",
+ "HeaderFavoriteEpisodes": "Suosikkijaksot",
+ "HeaderFavoriteArtists": "Suosikkiesittäjät",
+ "HeaderFavoriteAlbums": "Suosikkialbumit",
+ "HeaderContinueWatching": "Jatka katselua",
+ "HeaderAlbumArtists": "Albumin esittäjät",
+ "Genres": "Tyylilajit",
+ "Folders": "Kansiot",
+ "Favorites": "Suosikit",
+ "FailedLoginAttemptWithUserName": "Epäonnistunut kirjautumisyritys lähteestä \"{0}\"",
+ "DeviceOnlineWithName": "{0} on yhdistetty",
+ "DeviceOfflineWithName": "{0} on katkaissut yhteyden",
+ "Collections": "Kokoelmat",
+ "ChapterNameValue": "Kappale {0}",
+ "Channels": "Kanavat",
+ "CameraImageUploadedFrom": "Uusi kameran kuva on sirretty lähteestä {0}",
+ "Books": "Kirjat",
+ "AuthenticationSucceededWithUserName": "{0} on todennettu",
+ "Artists": "Esittäjät",
+ "Application": "Sovellus",
+ "AppDeviceValues": "Sovellus: {0}, Laite: {1}",
+ "Albums": "Albumit",
+ "User": "Käyttäjä",
+ "System": "Järjestelmä",
+ "ScheduledTaskFailedWithName": "{0} epäonnistui",
+ "PluginUpdatedWithName": "{0} päivitettiin",
+ "PluginInstalledWithName": "{0} asennettiin",
+ "Photos": "Valokuvat",
+ "ScheduledTaskStartedWithName": "\"{0}\" käynnistetty",
+ "PluginUninstalledWithName": "{0} poistettiin",
+ "Playlists": "Soittolistat",
+ "VersionNumber": "Versio {0}",
+ "ValueSpecialEpisodeName": "Erikoisjakso - {0}",
+ "ValueHasBeenAddedToLibrary": "\"{0}\" on lisätty mediakirjastoon",
+ "UserStoppedPlayingItemWithValues": "{0} lopetti kohteen \"{1}\" toiston sijainnissa \"{2}\"",
+ "UserStartedPlayingItemWithValues": "{0} toistaa kohdetta \"{1}\" sijainnissa \"{2}\"",
+ "UserPolicyUpdatedWithName": "Käyttäjän {0} käyttöoikeudet on päivitetty",
+ "UserPasswordChangedWithName": "Käyttäjän {0} salasana on vaihdettu",
+ "UserOnlineFromDevice": "{0} on yhdistänyt sijainnista \"{1}\"",
+ "UserOfflineFromDevice": "{0} on katkaissut yhteyden sijainnista \"{1}\"",
+ "UserLockedOutWithName": "Käyttäjä {0} on lukittu",
+ "UserDownloadingItemWithValues": "{0} lataa kohdetta \"{1}\"",
+ "UserDeletedWithName": "Käyttäjä {0} on poistettu",
+ "UserCreatedWithName": "Käyttäjä {0} on luotu",
+ "TvShows": "Sarjat",
+ "Sync": "Synkronointi",
+ "SubtitleDownloadFailureFromForItem": "Tekstityksen lataus lähteestä \"{0}\" kohteelle \"{1}\" epäonnistui",
+ "StartupEmbyServerIsLoading": "Jellyfin-palvelin latautuu. Yritä hetken kuluttua uudelleen.",
+ "Songs": "Kappaleet",
+ "Shows": "Sarjat",
+ "ServerNameNeedsToBeRestarted": "\"{0}\" on käynnistettävä uudelleen",
+ "ProviderValue": "Lähde: {0}",
+ "Plugin": "Laajennus",
+ "NotificationOptionVideoPlaybackStopped": "Videon toisto lopetettu",
+ "NotificationOptionVideoPlayback": "Videon toisto aloitettu",
+ "NotificationOptionUserLockedOut": "Käyttäjä on lukittu",
+ "NotificationOptionTaskFailed": "Ajoitettu tehtävä epäonnistui",
+ "NotificationOptionServerRestartRequired": "Tarvitaan palvelimen uudelleenkäynnistys",
+ "NotificationOptionPluginUpdateInstalled": "Laajennus on päivitetty",
+ "NotificationOptionPluginUninstalled": "Laajennus on poistettu",
+ "NotificationOptionPluginInstalled": "Laajennus on asennettu",
+ "NotificationOptionPluginError": "Laajennuksen virhe",
+ "NotificationOptionNewLibraryContent": "Sisältöä on lisätty",
+ "NotificationOptionInstallationFailed": "Asennus epäonnistui",
+ "NotificationOptionCameraImageUploaded": "Kameran kuva on tallennettu",
+ "NotificationOptionAudioPlaybackStopped": "Äänen toisto lopetettu",
+ "NotificationOptionAudioPlayback": "Äänen toisto aloitettu",
+ "NotificationOptionApplicationUpdateInstalled": "Sovelluspäivitys asennettiin",
+ "NotificationOptionApplicationUpdateAvailable": "Sovelluspäivitys on saatavilla",
+ "TasksMaintenanceCategory": "Ylläpito",
+ "TaskDownloadMissingSubtitlesDescription": "Etsii puuttuvia tekstityksiä määritettyjen metatietoasetusten mukaisesti.",
+ "TaskDownloadMissingSubtitles": "Lataa puuttuvat tekstitykset",
+ "TaskRefreshChannelsDescription": "Päivittää internet-kanavien tiedot.",
+ "TaskRefreshChannels": "Päivitä kanavat",
+ "TaskCleanTranscodeDescription": "Poistaa päivää vanhemmat transkoodaustiedostot.",
+ "TaskCleanTranscode": "Puhdista transkoodauskansio",
+ "TaskUpdatePluginsDescription": "Lataa ja asentaa päivitykset laajennuksille, jotka on määritetty päivittymään automaattisesti.",
+ "TaskUpdatePlugins": "Päivitä laajennukset",
+ "TaskRefreshPeopleDescription": "Päivittää mediakirjaston näyttelijöiden ja ohjaajien metatiedot.",
+ "TaskRefreshPeople": "Päivitä henkilöt",
+ "TaskCleanLogsDescription": "Poistaa {0} päivää vanhemmat lokitiedostot.",
+ "TaskCleanLogs": "Siivoa lokikansio",
+ "TaskRefreshLibraryDescription": "Tarkastaa mediakirjastosi sisällön uusien tiedostojen varalta ja päivittää metatiedot.",
+ "TaskRefreshLibrary": "Päivitä mediakirjasto",
+ "TaskRefreshChapterImagesDescription": "Luo esikatselukuvat videoille, jotka sisältävät kappalejaon.",
+ "TaskRefreshChapterImages": "Pura kappalejaon kuvat",
+ "TaskCleanCacheDescription": "Poistaa tarpeettomiksi jääneet väliaikaistiedostot.",
+ "TaskCleanCache": "Tyhjennä välimuistikansio",
+ "TasksChannelsCategory": "Internet-kanavat",
+ "TasksApplicationCategory": "Sovellus",
+ "TasksLibraryCategory": "Kirjasto",
+ "Forced": "Pakotettu",
+ "Default": "Oletus",
+ "TaskCleanActivityLogDescription": "Poistaa määritettyä ikää vanhemmat tapahtumat toimintahistoriasta.",
+ "TaskCleanActivityLog": "Tyhjennä toimintahistoria",
+ "Undefined": "Määrittelemätön",
+ "TaskOptimizeDatabaseDescription": "Tiivistää ja puhdistaa tietokannan. Tämän toiminnon suorittaminen kirjastojen skannauksen tai muiden tietokantaan liittyvien muutoksien jälkeen voi parantaa suorituskykyä.",
+ "TaskOptimizeDatabase": "Optimoi tietokanta"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/fil.json b/Emby.Server.Implementations/Localization/Core/fil.json
new file mode 100644
index 000000000..f18a1c030
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/fil.json
@@ -0,0 +1,121 @@
+{
+ "VersionNumber": "Bersyon {0}",
+ "ValueSpecialEpisodeName": "Espesyal - {0}",
+ "ValueHasBeenAddedToLibrary": "Naidagdag na ang {0} sa iyong librerya ng medya",
+ "UserStoppedPlayingItemWithValues": "Natapos ni {0} ang {1} sa {2}",
+ "UserStartedPlayingItemWithValues": "Si {0} ay nagpla-play ng {1} sa {2}",
+ "UserPolicyUpdatedWithName": "Ang user policy ay nai-update para kay {0}",
+ "UserPasswordChangedWithName": "Napalitan na ang password ni {0}",
+ "UserOnlineFromDevice": "Si {0} ay naka-konekta galing sa {1}",
+ "UserOfflineFromDevice": "Si {0} ay na-diskonekta galing sa {1}",
+ "UserLockedOutWithName": "Si {0} ay nalock out",
+ "UserDownloadingItemWithValues": "Nagdadownload si {0} ng {1}",
+ "UserDeletedWithName": "Natanggal na is user {0}",
+ "UserCreatedWithName": "Nagawa na si user {0}",
+ "User": "User",
+ "TvShows": "Mga Palabas sa Telebisyon",
+ "System": "Sistema",
+ "Sync": "Pag-sync",
+ "SubtitleDownloadFailureFromForItem": "Hindi nai-download ang subtitles {0} para sa {1}",
+ "StartupEmbyServerIsLoading": "Naglo-load ang Jellyfin Server. Mangyaring subukan ulit sandali.",
+ "Songs": "Mga Kanta",
+ "Shows": "Mga Pelikula",
+ "ServerNameNeedsToBeRestarted": "Kailangan irestart ang {0}",
+ "ScheduledTaskStartedWithName": "Nagsimula na ang {0}",
+ "ScheduledTaskFailedWithName": "Hindi gumana ang {0}",
+ "ProviderValue": "Tagapagtustos: {0}",
+ "PluginUpdatedWithName": "Naiupdate na ang {0}",
+ "PluginUninstalledWithName": "Naiuninstall na ang {0}",
+ "PluginInstalledWithName": "Nainstall na ang {0}",
+ "Plugin": "Plugin",
+ "Playlists": "Mga Playlist",
+ "Photos": "Mga Larawan",
+ "NotificationOptionVideoPlaybackStopped": "Huminto na ang pelikula",
+ "NotificationOptionVideoPlayback": "Nagsimula na ang pelikula",
+ "NotificationOptionUserLockedOut": "Naka-lock out ang user",
+ "NotificationOptionTaskFailed": "Hindi gumana ang scheduled task",
+ "NotificationOptionServerRestartRequired": "Kailangan i-restart ang server",
+ "NotificationOptionPluginUpdateInstalled": "Nai-update na ang plugin",
+ "NotificationOptionPluginUninstalled": "Nai-uninstall na ang plugin",
+ "NotificationOptionPluginInstalled": "Nainstall na ang plugin",
+ "NotificationOptionPluginError": "Hindi gumagana ang plugin",
+ "NotificationOptionNewLibraryContent": "May bagong content na naidagdag",
+ "NotificationOptionInstallationFailed": "Hindi nainstall ng mabuti",
+ "NotificationOptionCameraImageUploaded": "Naiupload na ang litrato",
+ "NotificationOptionAudioPlaybackStopped": "Huminto na ang patugtog",
+ "NotificationOptionAudioPlayback": "Nagsimula na ang patugtog",
+ "NotificationOptionApplicationUpdateInstalled": "Naiupdate na ang aplikasyon",
+ "NotificationOptionApplicationUpdateAvailable": "May bagong update ang aplikasyon",
+ "NewVersionIsAvailable": "May bagong version ng Jellyfin Server na pwede i-download.",
+ "NameSeasonUnknown": "Hindi matukoy ang season",
+ "NameSeasonNumber": "Season {0}",
+ "NameInstallFailed": "Hindi nainstall ang {0}",
+ "MusicVideos": "Mga Music video",
+ "Music": "Mga Kanta",
+ "Movies": "Mga Pelikula",
+ "MixedContent": "Halo-halong content",
+ "MessageServerConfigurationUpdated": "Naiupdate na ang server configuration",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Naiupdate na ang server configuration section {0}",
+ "MessageApplicationUpdatedTo": "Ang bersyon ng Jellyfin Server ay naiupdate sa {0}",
+ "MessageApplicationUpdated": "Naiupdate na ang Jellyfin Server",
+ "Latest": "Pinakabago",
+ "LabelRunningTimeValue": "Oras: {0}",
+ "LabelIpAddressValue": "IP address: {0}",
+ "ItemRemovedWithName": "Naitanggal ang {0} sa librerya",
+ "ItemAddedWithName": "Naidagdag ang {0} sa librerya",
+ "Inherit": "Manahin",
+ "HeaderRecordingGroups": "Pagtatalang Grupo",
+ "HeaderNextUp": "Susunod",
+ "HeaderLiveTV": "Live TV",
+ "HeaderFavoriteSongs": "Mga Paboritong Kanta",
+ "HeaderFavoriteShows": "Mga Paboritong Pelikula",
+ "HeaderFavoriteEpisodes": "Mga Paboritong Episode",
+ "HeaderFavoriteArtists": "Mga Paboritong Artista",
+ "HeaderFavoriteAlbums": "Mga Paboritong Album",
+ "HeaderContinueWatching": "Magpatuloy sa Panonood",
+ "HeaderAlbumArtists": "Mga Artista ng Album",
+ "Genres": "Mga Kategorya",
+ "Folders": "Mga Folder",
+ "Favorites": "Mga Paborito",
+ "FailedLoginAttemptWithUserName": "Maling login galing kay/sa {0}",
+ "DeviceOnlineWithName": "Nakakonekta si/ang {0}",
+ "DeviceOfflineWithName": "Nadiskonekta si/ang {0}",
+ "Collections": "Mga Koleksyon",
+ "ChapterNameValue": "Kabanata {0}",
+ "Channels": "Mga Channel",
+ "CameraImageUploadedFrom": "May bagong larawan na naupload galing sa/kay {0}",
+ "Books": "Mga Libro",
+ "AuthenticationSucceededWithUserName": "Napatunayan si/ang {0}",
+ "Artists": "Mga Artista",
+ "Application": "Aplikasyon",
+ "AppDeviceValues": "Aplikasyon: {0}, Aparato: {1}",
+ "Albums": "Mga Album",
+ "TaskRefreshLibrary": "Suriin and Librerya ng Medya",
+ "TaskRefreshChapterImagesDescription": "Gumawa ng larawan para sa mga pelikula na may kabanata.",
+ "TaskRefreshChapterImages": "Kunin ang mga larawan ng kabanata",
+ "TaskCleanCacheDescription": "Tanggalin ang mga cache file na hindi na kailangan ng sistema.",
+ "TasksChannelsCategory": "Palabas sa internet",
+ "TasksLibraryCategory": "Librerya",
+ "TasksMaintenanceCategory": "Pagpapanatili",
+ "HomeVideos": "Sariling video/pelikula",
+ "TaskRefreshPeopleDescription": "Ini-update ang metadata para sa mga aktor at direktor sa iyong librerya ng medya.",
+ "TaskRefreshPeople": "I-refresh ang Tauhan",
+ "TaskDownloadMissingSubtitlesDescription": "Hinahanap sa internet ang mga nawawalang subtiles base sa metadata configuration.",
+ "TaskDownloadMissingSubtitles": "I-download and nawawalang subtitles",
+ "TaskRefreshChannelsDescription": "Ni-rerefresh ang impormasyon sa internet channels.",
+ "TaskRefreshChannels": "I-refresh ang Channels",
+ "TaskCleanTranscodeDescription": "Binubura ang transcode files na mas matanda ng isang araw.",
+ "TaskUpdatePluginsDescription": "Nag download at install ng updates sa plugins na naka configure para sa awtomatikong pag-update.",
+ "TaskUpdatePlugins": "I-update ang Plugins",
+ "TaskCleanLogsDescription": "Binubura and files ng talaan na mas mantanda ng {0} araw.",
+ "TaskCleanTranscode": "Linisin and Direktoryo ng Transcode",
+ "TaskCleanLogs": "Linisin and Direktoryo ng Talaan",
+ "TaskRefreshLibraryDescription": "Sinusuri ang iyong librerya ng medya para sa bagong files at irefresh ang metadata.",
+ "TaskCleanCache": "Linisin and Direktoryo ng Cache",
+ "TasksApplicationCategory": "Aplikasyon",
+ "TaskCleanActivityLog": "Linisin ang Tala ng Aktibidad",
+ "TaskCleanActivityLogDescription": "Tanggalin ang mga tala ng aktibidad na mas luma sa nakatakda na edad.",
+ "Default": "Default",
+ "Undefined": "Hindi tiyak",
+ "Forced": "Sapilitan"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/fr-CA.json b/Emby.Server.Implementations/Localization/Core/fr-CA.json
index 7202be9f5..2a56d0745 100644
--- a/Emby.Server.Implementations/Localization/Core/fr-CA.json
+++ b/Emby.Server.Implementations/Localization/Core/fr-CA.json
@@ -1,97 +1,124 @@
{
"Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
+ "AppDeviceValues": "App : {0}, Appareil : {1}",
"Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
+ "Artists": "Artistes",
+ "AuthenticationSucceededWithUserName": "{0} authentifié avec succès",
+ "Books": "Livres",
+ "CameraImageUploadedFrom": "Une nouvelle image de caméra a été téléchargée depuis {0}",
+ "Channels": "Chaînes",
+ "ChapterNameValue": "Chapitre {0}",
"Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
+ "DeviceOfflineWithName": "{0} s'est déconnecté",
+ "DeviceOnlineWithName": "{0} est connecté",
+ "FailedLoginAttemptWithUserName": "Tentative de connexion échoué par {0}",
+ "Favorites": "Favoris",
+ "Folders": "Dossiers",
"Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continuer à regarder",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
+ "HeaderAlbumArtists": "Artistes de l'album",
+ "HeaderContinueWatching": "Reprendre le visionnement",
+ "HeaderFavoriteAlbums": "Albums favoris",
+ "HeaderFavoriteArtists": "Artistes favoris",
+ "HeaderFavoriteEpisodes": "Épisodes favoris",
+ "HeaderFavoriteShows": "Séries favorites",
+ "HeaderFavoriteSongs": "Chansons favorites",
+ "HeaderLiveTV": "TV en direct",
"HeaderNextUp": "À Suivre",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
+ "HeaderRecordingGroups": "Groupes d'enregistrements",
+ "HomeVideos": "Vidéos personnelles",
+ "Inherit": "Hérite",
+ "ItemAddedWithName": "{0} a été ajouté à la médiathèque",
+ "ItemRemovedWithName": "{0} a été supprimé de la médiathèque",
+ "LabelIpAddressValue": "Adresse IP : {0}",
+ "LabelRunningTimeValue": "Durée : {0}",
+ "Latest": "Plus récent",
+ "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour",
+ "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers la version {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour",
+ "MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour",
+ "MixedContent": "Contenu mixte",
+ "Movies": "Films",
+ "Music": "Musique",
+ "MusicVideos": "Vidéos musicales",
+ "NameInstallFailed": "échec d'installation de {0}",
+ "NameSeasonNumber": "Saison {0}",
+ "NameSeasonUnknown": "Saison Inconnue",
+ "NewVersionIsAvailable": "Une nouvelle version du serveur Jellyfin est disponible.",
+ "NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
+ "NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
+ "NotificationOptionAudioPlayback": "Lecture audio démarrée",
+ "NotificationOptionAudioPlaybackStopped": "Lecture audio arrêtée",
+ "NotificationOptionCameraImageUploaded": "Image d'appareil photo transférée",
+ "NotificationOptionInstallationFailed": "Échec d'installation",
+ "NotificationOptionNewLibraryContent": "Nouveau contenu ajouté",
+ "NotificationOptionPluginError": "Erreur d'extension",
+ "NotificationOptionPluginInstalled": "Extension installée",
+ "NotificationOptionPluginUninstalled": "Extension désinstallée",
+ "NotificationOptionPluginUpdateInstalled": "Mise à jour d'extension installée",
+ "NotificationOptionServerRestartRequired": "Un redémarrage du serveur est requis",
+ "NotificationOptionTaskFailed": "Échec de tâche planifiée",
+ "NotificationOptionUserLockedOut": "Utilisateur verrouillé",
+ "NotificationOptionVideoPlayback": "Lecture vidéo démarrée",
+ "NotificationOptionVideoPlaybackStopped": "Lecture vidéo arrêtée",
"Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Series",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Playlists": "Listes de lecture",
+ "Plugin": "Extension",
+ "PluginInstalledWithName": "{0} a été installé",
+ "PluginUninstalledWithName": "{0} a été désinstallé",
+ "PluginUpdatedWithName": "{0} a été mis à jour",
+ "ProviderValue": "Fournisseur : {0}",
+ "ScheduledTaskFailedWithName": "{0} a échoué",
+ "ScheduledTaskStartedWithName": "{0} a commencé",
+ "ServerNameNeedsToBeRestarted": "{0} doit être redémarré",
+ "Shows": "Séries",
+ "Songs": "Chansons",
+ "StartupEmbyServerIsLoading": "Serveur Jellyfin en cours de chargement. Réessayez dans quelques instants.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "SubtitleDownloadFailureFromForItem": "Échec du téléchargement des sous-titres depuis {0} pour {1}",
+ "Sync": "Synchroniser",
+ "System": "Système",
+ "TvShows": "Séries Télé",
+ "User": "Utilisateur",
+ "UserCreatedWithName": "L'utilisateur {0} a été créé",
+ "UserDeletedWithName": "L'utilisateur {0} supprimé",
+ "UserDownloadingItemWithValues": "{0} télécharge {1}",
+ "UserLockedOutWithName": "L'utilisateur {0} a été verrouillé",
+ "UserOfflineFromDevice": "{0} s'est déconnecté de {1}",
+ "UserOnlineFromDevice": "{0} s'est connecté de {1}",
+ "UserPasswordChangedWithName": "Le mot de passe de utilisateur {0} a été modifié",
+ "UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
+ "UserStartedPlayingItemWithValues": "{0} joue {1} sur {2}",
+ "UserStoppedPlayingItemWithValues": "{0} a terminé la lecture de {1} sur {2}",
+ "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque",
"ValueSpecialEpisodeName": "Spécial - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TasksLibraryCategory": "Médiathèque",
+ "TasksMaintenanceCategory": "Entretien",
+ "TaskDownloadMissingSubtitlesDescription": "Recherche les sous-titres manquant sur l'internet selon la configuration des métadonnées.",
+ "TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquants",
+ "TaskRefreshChannelsDescription": "Rafraîchit les informations des chaines internet.",
+ "TaskRefreshChannels": "Rafraîchir les chaines",
+ "TaskCleanTranscodeDescription": "Supprime les fichiers de transcodage datant de plus d'un jour.",
+ "TaskCleanTranscode": "Nettoyer le répertoire de transcodage",
+ "TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurés pour les m.à.j. automatiques.",
+ "TaskUpdatePlugins": "Mise à jour des extensions",
+ "TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre médiathèque.",
+ "TaskRefreshPeople": "Rafraîchir les personnes",
+ "TaskCleanLogsDescription": "Supprime les journaux plus vieux que {0} jours.",
+ "TaskCleanLogs": "Nettoyer le répertoire des journaux",
+ "TaskRefreshLibraryDescription": "Analyse votre médiathèque pour trouver de nouveaux fichiers et rafraîchit les métadonnées.",
+ "TaskRefreshChapterImages": "Extraire les images de chapitre",
+ "TaskRefreshChapterImagesDescription": "Créer des vignettes pour les vidéos qui ont des chapitres.",
+ "TaskRefreshLibrary": "Analyser la médiathèque",
+ "TaskCleanCache": "Nettoyer le répertoire des fichiers temporaires",
+ "TasksApplicationCategory": "Application",
+ "TaskCleanCacheDescription": "Supprime les fichiers temporaires qui ne sont plus nécessaire pour le système.",
+ "TasksChannelsCategory": "Chaines Internet",
+ "Default": "Par défaut",
+ "TaskCleanActivityLogDescription": "Éfface les entrées du journal plus anciennes que l'âge configuré.",
+ "TaskCleanActivityLog": "Nettoyer le journal d'activité",
+ "Undefined": "Indéfini",
+ "Forced": "Forcé",
+ "TaskOptimizeDatabaseDescription": "Compacte la base de données et tronque l'espace libre. Lancer cette tâche après avoir scanné la bibliothèque ou faire d'autres changements impliquant des modifications de la base peuvent ameliorer les performances.",
+ "TaskOptimizeDatabase": "Optimiser la base de données"
}
diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json
index 52afb4e49..1265b6ef5 100644
--- a/Emby.Server.Implementations/Localization/Core/fr.json
+++ b/Emby.Server.Implementations/Localization/Core/fr.json
@@ -1,30 +1,29 @@
{
"Albums": "Albums",
"AppDeviceValues": "Application : {0}, Appareil : {1}",
- "Application": "Application",
+ "Application": "Applications",
"Artists": "Artistes",
- "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès",
+ "AuthenticationSucceededWithUserName": "{0} authentifié avec succès",
"Books": "Livres",
- "CameraImageUploadedFrom": "Une image de caméra a été chargée depuis {0}",
+ "CameraImageUploadedFrom": "Une photo a été chargée depuis {0}",
"Channels": "Chaînes",
"ChapterNameValue": "Chapitre {0}",
"Collections": "Collections",
"DeviceOfflineWithName": "{0} s'est déconnecté",
"DeviceOnlineWithName": "{0} est connecté",
- "FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}",
+ "FailedLoginAttemptWithUserName": "Échec de connexion depuis {0}",
"Favorites": "Favoris",
"Folders": "Dossiers",
"Genres": "Genres",
"HeaderAlbumArtists": "Artistes de l'album",
- "HeaderCameraUploads": "Photos transférées",
"HeaderContinueWatching": "Continuer à regarder",
"HeaderFavoriteAlbums": "Albums favoris",
- "HeaderFavoriteArtists": "Artistes favoris",
+ "HeaderFavoriteArtists": "Artistes préférés",
"HeaderFavoriteEpisodes": "Épisodes favoris",
"HeaderFavoriteShows": "Séries favorites",
- "HeaderFavoriteSongs": "Chansons favorites",
+ "HeaderFavoriteSongs": "Chansons préférées",
"HeaderLiveTV": "TV en direct",
- "HeaderNextUp": "En Cours",
+ "HeaderNextUp": "À suivre",
"HeaderRecordingGroups": "Groupes d'enregistrements",
"HomeVideos": "Vidéos personnelles",
"Inherit": "Hériter",
@@ -34,23 +33,23 @@
"LabelRunningTimeValue": "Durée : {0}",
"Latest": "Derniers",
"MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour",
- "MessageApplicationUpdatedTo": "Jellyfin Serveur a été mis à jour en version {0}",
+ "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour en version {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour",
"MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour",
"MixedContent": "Contenu mixte",
"Movies": "Films",
"Music": "Musique",
- "MusicVideos": "Vidéos musicales",
- "NameInstallFailed": "{0} échec d'installation",
+ "MusicVideos": "Clips musicaux",
+ "NameInstallFailed": "{0} échec de l'installation",
"NameSeasonNumber": "Saison {0}",
"NameSeasonUnknown": "Saison Inconnue",
- "NewVersionIsAvailable": "Une nouvelle version d'Jellyfin Serveur est disponible au téléchargement.",
+ "NewVersionIsAvailable": "Une nouvelle version de Jellyfin Serveur est disponible au téléchargement.",
"NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
"NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
"NotificationOptionAudioPlayback": "Lecture audio démarrée",
"NotificationOptionAudioPlaybackStopped": "Lecture audio arrêtée",
"NotificationOptionCameraImageUploaded": "L'image de l'appareil photo a été transférée",
- "NotificationOptionInstallationFailed": "Échec d'installation",
+ "NotificationOptionInstallationFailed": "Échec de l'installation",
"NotificationOptionNewLibraryContent": "Nouveau contenu ajouté",
"NotificationOptionPluginError": "Erreur d'extension",
"NotificationOptionPluginInstalled": "Extension installée",
@@ -69,14 +68,13 @@
"PluginUpdatedWithName": "{0} a été mis à jour",
"ProviderValue": "Fournisseur : {0}",
"ScheduledTaskFailedWithName": "{0} a échoué",
- "ScheduledTaskStartedWithName": "{0} a commencé",
+ "ScheduledTaskStartedWithName": "{0} a démarré",
"ServerNameNeedsToBeRestarted": "{0} doit être redémarré",
"Shows": "Émissions",
"Songs": "Chansons",
"StartupEmbyServerIsLoading": "Le serveur Jellyfin est en cours de chargement. Veuillez réessayer dans quelques instants.",
"SubtitleDownloadFailureForItem": "Le téléchargement des sous-titres pour {0} a échoué.",
"SubtitleDownloadFailureFromForItem": "Échec du téléchargement des sous-titres depuis {0} pour {1}",
- "SubtitlesDownloadedForItem": "Les sous-titres de {0} ont été téléchargés",
"Sync": "Synchroniser",
"System": "Système",
"TvShows": "Séries Télé",
@@ -89,9 +87,38 @@
"UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
"UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
"UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
- "UserStartedPlayingItemWithValues": "{0} est entrain de lire {1} sur {2}",
+ "UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}",
"UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
- "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre librairie",
+ "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque",
"ValueSpecialEpisodeName": "Spécial - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TasksChannelsCategory": "Chaines en ligne",
+ "TaskDownloadMissingSubtitlesDescription": "Recherche les sous-titres manquants sur internet en se basant sur la configuration des métadonnées.",
+ "TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquants",
+ "TaskRefreshChannelsDescription": "Rafraîchit les informations des chaines en ligne.",
+ "TaskRefreshChannels": "Rafraîchir les chaines",
+ "TaskCleanTranscodeDescription": "Supprime les fichiers transcodés de plus d'un jour.",
+ "TaskCleanTranscode": "Nettoyer les dossier des transcodages",
+ "TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurées pour être mises à jour automatiquement.",
+ "TaskUpdatePlugins": "Mettre à jour les extensions",
+ "TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre bibliothèque.",
+ "TaskRefreshPeople": "Rafraîchir les acteurs",
+ "TaskCleanLogsDescription": "Supprime les journaux de plus de {0} jours.",
+ "TaskCleanLogs": "Nettoyer le répertoire des journaux",
+ "TaskRefreshLibraryDescription": "Scanne votre médiathèque pour trouver les nouveaux fichiers et rafraîchit les métadonnées.",
+ "TaskRefreshLibrary": "Scanner la médiathèque",
+ "TaskRefreshChapterImagesDescription": "Crée des vignettes pour les vidéos ayant des chapitres.",
+ "TaskRefreshChapterImages": "Extraire les images de chapitre",
+ "TaskCleanCacheDescription": "Supprime les fichiers de cache dont le système n'a plus besoin.",
+ "TaskCleanCache": "Vider le répertoire cache",
+ "TasksApplicationCategory": "Application",
+ "TasksLibraryCategory": "Bibliothèque",
+ "TasksMaintenanceCategory": "Maintenance",
+ "TaskCleanActivityLogDescription": "Supprime les entrées du journal d'activité antérieures à l'âge configuré.",
+ "TaskCleanActivityLog": "Nettoyer le journal d'activité",
+ "Undefined": "Non défini",
+ "Forced": "Forcé",
+ "Default": "Par défaut",
+ "TaskOptimizeDatabaseDescription": "Réduit les espaces vides/inutiles et compacte la base de données. Utiliser cette fonction après une mise à jour de la bibliothèque ou toute autre modification de la base de données peut améliorer les performances du serveur.",
+ "TaskOptimizeDatabase": "Optimiser la base de données"
}
diff --git a/Emby.Server.Implementations/Localization/Core/gl.json b/Emby.Server.Implementations/Localization/Core/gl.json
new file mode 100644
index 000000000..b433c6f68
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/gl.json
@@ -0,0 +1,123 @@
+{
+ "Albums": "Álbumes",
+ "Collections": "Colecións",
+ "ChapterNameValue": "Capítulos {0}",
+ "Channels": "Canles",
+ "CameraImageUploadedFrom": "Cargouse unha nova imaxe da cámara desde {0}",
+ "Books": "Libros",
+ "AuthenticationSucceededWithUserName": "{0} autenticouse correctamente",
+ "Artists": "Artistas",
+ "Application": "Aplicativo",
+ "NotificationOptionServerRestartRequired": "Necesario un reinicio do servidor",
+ "NotificationOptionPluginUpdateInstalled": "Actualización do Plugin instalada",
+ "NotificationOptionPluginUninstalled": "Plugin desinstalado",
+ "NotificationOptionPluginInstalled": "Plugin instalado",
+ "NotificationOptionPluginError": "Fallo do Plugin",
+ "NotificationOptionNewLibraryContent": "Novo contido engadido",
+ "NotificationOptionInstallationFailed": "Fallo na instalación",
+ "NotificationOptionCameraImageUploaded": "Imaxe da cámara subida",
+ "NotificationOptionAudioPlaybackStopped": "Reproducción de audio parada",
+ "NotificationOptionAudioPlayback": "Reproducción de audio comezada",
+ "NotificationOptionApplicationUpdateInstalled": "Actualización da aplicación instalada",
+ "NotificationOptionApplicationUpdateAvailable": "Actualización da aplicación dispoñible",
+ "NewVersionIsAvailable": "Unha nova versión do Servidor Jellyfin está dispoñible para descarga.",
+ "NameSeasonUnknown": "Tempada descoñecida",
+ "NameSeasonNumber": "Tempada {0}",
+ "NameInstallFailed": "{0} instalación fallida",
+ "MusicVideos": "Vídeos Musicais",
+ "Music": "Música",
+ "Movies": "Películas",
+ "MixedContent": "Contido Mixto",
+ "MessageServerConfigurationUpdated": "A configuración do servidor foi actualizada",
+ "MessageNamedServerConfigurationUpdatedWithValue": "A sección de configuración {0} do servidor foi actualizada",
+ "MessageApplicationUpdatedTo": "O servidor Jellyfin foi actualizado a {0}",
+ "MessageApplicationUpdated": "O servidor Jellyfin foi actualizado",
+ "Latest": "Último",
+ "LabelRunningTimeValue": "Tempo de execución: {0}",
+ "LabelIpAddressValue": "Enderezo IP: {0}",
+ "ItemRemovedWithName": "{0} foi eliminado da biblioteca",
+ "ItemAddedWithName": "{0} foi engadido a biblioteca",
+ "Inherit": "Herdar",
+ "HomeVideos": "Videos caseiros",
+ "HeaderRecordingGroups": "Grupos de Grabación",
+ "HeaderNextUp": "De seguido",
+ "HeaderLiveTV": "TV en directo",
+ "HeaderFavoriteSongs": "Cancións Favoritas",
+ "HeaderFavoriteShows": "Series de TV Favoritas",
+ "HeaderFavoriteEpisodes": "Episodios Favoritos",
+ "HeaderFavoriteArtists": "Artistas Favoritos",
+ "HeaderFavoriteAlbums": "Álbunes Favoritos",
+ "HeaderContinueWatching": "Seguir mirando",
+ "HeaderAlbumArtists": "Artistas do Album",
+ "Genres": "Xéneros",
+ "Forced": "Forzado",
+ "Folders": "Cartafoles",
+ "Favorites": "Favoritos",
+ "FailedLoginAttemptWithUserName": "Intento de incio de sesión fallido {0}",
+ "DeviceOnlineWithName": "{0} conectouse",
+ "DeviceOfflineWithName": "{0} desconectouse",
+ "Default": "Por defecto",
+ "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}",
+ "TaskCleanLogs": "Limpar Carpeta de Rexistros",
+ "TaskCleanActivityLog": "Limpar Rexistro de Actividade",
+ "TasksChannelsCategory": "Canáis de Internet",
+ "TaskUpdatePlugins": "Actualizar Plugins",
+ "User": "Usuario",
+ "Undefined": "Sen definir",
+ "TvShows": "Programas de TV",
+ "System": "Sistema",
+ "Sync": "Sincronizar",
+ "SubtitleDownloadFailureFromForItem": "Fallou a descarga de subtítulos para {1} dende {0}",
+ "StartupEmbyServerIsLoading": "O Servidor Jellyfin está cargando. Por favor, reinténteo en breve.",
+ "Songs": "Cancións",
+ "Shows": "Programas",
+ "ServerNameNeedsToBeRestarted": "{0} precisa ser reiniciado",
+ "ScheduledTaskStartedWithName": "{0} comezou",
+ "ScheduledTaskFailedWithName": "{0} fallou",
+ "ProviderValue": "Provedor: {0}",
+ "PluginUpdatedWithName": "{0} foi actualizado",
+ "PluginUninstalledWithName": "{0} foi desinstalado",
+ "PluginInstalledWithName": "{0} foi instalado",
+ "Playlists": "Listas de reproducción",
+ "Photos": "Fotos",
+ "UserLockedOutWithName": "O usuario {0} foi bloqueado",
+ "UserDownloadingItemWithValues": "{0} está a ser transferido {1}",
+ "UserDeletedWithName": "O usuario {0} foi borrado",
+ "UserCreatedWithName": "O usuario {0} foi creado",
+ "Plugin": "Plugin",
+ "NotificationOptionVideoPlaybackStopped": "Reproducción de vídeo parada",
+ "NotificationOptionVideoPlayback": "Reproducción de vídeo iniciada",
+ "NotificationOptionUserLockedOut": "Usuario bloqueado",
+ "NotificationOptionTaskFailed": "Falla na tarefa axendada",
+ "TaskCleanTranscodeDescription": "Borra os arquivos de transcode anteriores a un día.",
+ "TaskCleanTranscode": "Limpar Directorio de Transcode",
+ "UserStoppedPlayingItemWithValues": "{0} rematou de reproducir {1} en {2}",
+ "UserStartedPlayingItemWithValues": "{0} está reproducindo {1} en {2}",
+ "TaskDownloadMissingSubtitlesDescription": "Busca en internet por subtítulos que faltan baseado na configuración de metadatos.",
+ "TaskDownloadMissingSubtitles": "Descargar subtítulos que faltan",
+ "TaskRefreshChannelsDescription": "Refresca a información do canle de internet.",
+ "TaskRefreshChannels": "Refrescar Canles",
+ "TaskUpdatePluginsDescription": "Descarga e instala actualizacións para plugins que están configurados para actualizarse automáticamente.",
+ "TaskRefreshPeopleDescription": "Actualiza os metadatos dos actores e directores na túa libraría multimedia.",
+ "TaskRefreshPeople": "Refrescar Persoas",
+ "TaskCleanLogsDescription": "Borra arquivos de rexistro que son mais antigos que {0} días.",
+ "TaskRefreshLibraryDescription": "Escanea a tua libraría multimedia buscando novos arquivos e refrescando os metadatos.",
+ "TaskRefreshLibrary": "Escanear Libraría Multimedia",
+ "TaskRefreshChapterImagesDescription": "Crea previsualizacións para videos que teñen capítulos.",
+ "TaskRefreshChapterImages": "Extraer Imaxes dos Capítulos",
+ "TaskCleanCacheDescription": "Borra ficheiros da caché que xa non son necesarios para o sistema.",
+ "TaskCleanCache": "Limpa Directorio de Caché",
+ "TaskCleanActivityLogDescription": "Borra as entradas no rexistro de actividade anteriores á data configurada.",
+ "TasksApplicationCategory": "Aplicación",
+ "ValueSpecialEpisodeName": "Especial - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} foi engadido a túa libraría multimedia",
+ "TasksLibraryCategory": "Libraría",
+ "TasksMaintenanceCategory": "Mantemento",
+ "VersionNumber": "Versión {0}",
+ "UserPolicyUpdatedWithName": "A política de usuario foi actualizada para {0}",
+ "UserPasswordChangedWithName": "Cambiouse o contrasinal para o usuario {0}",
+ "UserOnlineFromDevice": "{0} está en liña desde {1}",
+ "UserOfflineFromDevice": "{0} desconectouse desde {1}",
+ "TaskOptimizeDatabaseDescription": "Compacta e libera o espazo libre da base de datos. Executar esta tarefa logo de realizar mudanzas que impliquen modificacións da base de datos ou despois de escanear a biblioteca pode traer mellorías de desempeño.",
+ "TaskOptimizeDatabase": "Optimizar base de datos"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/gsw.json b/Emby.Server.Implementations/Localization/Core/gsw.json
index 728002a56..3364ee333 100644
--- a/Emby.Server.Implementations/Localization/Core/gsw.json
+++ b/Emby.Server.Implementations/Localization/Core/gsw.json
@@ -1,97 +1,122 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Büecher",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
+ "Albums": "Alben",
+ "AppDeviceValues": "App: {0}, Gerät: {1}",
+ "Application": "Anwendung",
+ "Artists": "Künstler",
+ "AuthenticationSucceededWithUserName": "{0} hat sich angemeldet",
+ "Books": "Bücher",
+ "CameraImageUploadedFrom": "Ein neues Foto wurde von {0} hochgeladen",
+ "Channels": "Kanäle",
+ "ChapterNameValue": "Kapitel {0}",
+ "Collections": "Sammlungen",
+ "DeviceOfflineWithName": "{0} wurde getrennt",
+ "DeviceOnlineWithName": "{0} ist verbunden",
+ "FailedLoginAttemptWithUserName": "Fehlgeschlagener Anmeldeversuch von {0}",
+ "Favorites": "Favoriten",
+ "Folders": "Ordner",
"Genres": "Genres",
- "HeaderAlbumArtists": "Albuminterprete",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Wiiterluege",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Besti Interpret",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Besti Lieder",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Ufnahmegruppe",
- "HomeVideos": "Heimfilmli",
- "Inherit": "Hinzuefüege",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Letschte",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Gmischte Inhalt",
- "Movies": "Movies",
+ "HeaderAlbumArtists": "Album-Künstler",
+ "HeaderContinueWatching": "weiter schauen",
+ "HeaderFavoriteAlbums": "Lieblingsalben",
+ "HeaderFavoriteArtists": "Lieblings-Künstler",
+ "HeaderFavoriteEpisodes": "Lieblingsepisoden",
+ "HeaderFavoriteShows": "Lieblingsserien",
+ "HeaderFavoriteSongs": "Lieblingslieder",
+ "HeaderLiveTV": "Live-Fernseh",
+ "HeaderNextUp": "Als Nächstes",
+ "HeaderRecordingGroups": "Aufnahme-Gruppen",
+ "HomeVideos": "Heimvideos",
+ "Inherit": "Vererben",
+ "ItemAddedWithName": "{0} wurde der Bibliothek hinzugefügt",
+ "ItemRemovedWithName": "{0} wurde aus der Bibliothek entfernt",
+ "LabelIpAddressValue": "IP-Adresse: {0}",
+ "LabelRunningTimeValue": "Laufzeit: {0}",
+ "Latest": "Neueste",
+ "MessageApplicationUpdated": "Jellyfin-Server wurde aktualisiert",
+ "MessageApplicationUpdatedTo": "Jellyfin-Server wurde auf Version {0} aktualisiert",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Der Server-Einstellungsbereich {0} wurde aktualisiert",
+ "MessageServerConfigurationUpdated": "Serveriistöuige send aktualisiert worde",
+ "MixedContent": "Gmeschti Inhäut",
+ "Movies": "Film",
"Music": "Musig",
- "MusicVideos": "Musigfilm",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
+ "MusicVideos": "Musigvideos",
+ "NameInstallFailed": "Installation vo {0} fäugschlage",
+ "NameSeasonNumber": "Staffle {0}",
+ "NameSeasonUnknown": "Staffle unbekannt",
+ "NewVersionIsAvailable": "E nöi Version vo Jellyfin Server esch zom Download parat.",
+ "NotificationOptionApplicationUpdateAvailable": "Aawändigsupdate verfüegbar",
+ "NotificationOptionApplicationUpdateInstalled": "Aawändigsupdate installiert",
+ "NotificationOptionAudioPlayback": "Audiowedergab gstartet",
+ "NotificationOptionAudioPlaybackStopped": "Audiwedergab gstoppt",
+ "NotificationOptionCameraImageUploaded": "Foti ueglade",
+ "NotificationOptionInstallationFailed": "Installationsfehler",
+ "NotificationOptionNewLibraryContent": "Nöie Inhaut hinzuegfüegt",
+ "NotificationOptionPluginError": "Plugin-Fäuer",
+ "NotificationOptionPluginInstalled": "Plugin installiert",
+ "NotificationOptionPluginUninstalled": "Plugin deinstalliert",
+ "NotificationOptionPluginUpdateInstalled": "Pluginupdate installiert",
+ "NotificationOptionServerRestartRequired": "Serverneustart notwändig",
+ "NotificationOptionTaskFailed": "Planti Uufgab fäugschlage",
+ "NotificationOptionUserLockedOut": "Benotzer usgschlosse",
+ "NotificationOptionVideoPlayback": "Videowedergab gstartet",
+ "NotificationOptionVideoPlaybackStopped": "Videowedergab gstoppt",
"Photos": "Fotis",
- "Playlists": "Abspielliste",
+ "Playlists": "Wedergabeliste",
"Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "PluginInstalledWithName": "{0} esch installiert worde",
+ "PluginUninstalledWithName": "{0} esch deinstalliert worde",
+ "PluginUpdatedWithName": "{0} esch updated worde",
+ "ProviderValue": "Aabieter: {0}",
+ "ScheduledTaskFailedWithName": "{0} esch fäugschlage",
+ "ScheduledTaskStartedWithName": "{0} het gstartet",
+ "ServerNameNeedsToBeRestarted": "{0} mues nöi gstartet wärde",
+ "Shows": "Serie",
+ "Songs": "Lieder",
+ "StartupEmbyServerIsLoading": "Jellyfin Server ladt. Bitte grad noeinisch probiere.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
+ "SubtitleDownloadFailureFromForItem": "Ondertetle vo {0} för {1} hend ned chönne abeglade wärde",
+ "Sync": "Synchronisation",
"System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Spezial - {0}",
- "VersionNumber": "Version {0}"
+ "TvShows": "Färnsehserie",
+ "User": "Benotzer",
+ "UserCreatedWithName": "Benotzer {0} esch erstöut worde",
+ "UserDeletedWithName": "Benotzer {0} esch glösche worde",
+ "UserDownloadingItemWithValues": "{0} ladt {1} abe",
+ "UserLockedOutWithName": "Benotzer {0} esch usgschlosse worde",
+ "UserOfflineFromDevice": "{0} esch vo {1} trennt worde",
+ "UserOnlineFromDevice": "{0} esch online vo {1}",
+ "UserPasswordChangedWithName": "S'Passwort för Benotzer {0} esch gänderet worde",
+ "UserPolicyUpdatedWithName": "Benotzerrechtlinie för {0} esch aktualisiert worde",
+ "UserStartedPlayingItemWithValues": "{0} hed d'Wedergab vo {1} of {2} gstartet",
+ "UserStoppedPlayingItemWithValues": "{0} het d'Wedergab vo {1} of {2} gstoppt",
+ "ValueHasBeenAddedToLibrary": "{0} esch dinnere Biblithek hinzuegfüegt worde",
+ "ValueSpecialEpisodeName": "Extra - {0}",
+ "VersionNumber": "Version {0}",
+ "TaskCleanLogs": "Lösche Log Pfad",
+ "TaskRefreshLibraryDescription": "Scanne alle Bibliotheken für hinzugefügte Datein und erneuere Metadaten.",
+ "TaskRefreshLibrary": "Scanne alle Bibliotheken",
+ "TaskRefreshChapterImagesDescription": "Kreiert Vorschaubilder für Videos welche Kapitel haben.",
+ "TaskRefreshChapterImages": "Extrahiere Kapitel-Bilder",
+ "TaskCleanCacheDescription": "Löscht Zwischenspeicherdatein die nicht länger von System gebraucht werden.",
+ "TaskCleanCache": "Leere Cache Pfad",
+ "TasksChannelsCategory": "Internet Kanäle",
+ "TasksApplicationCategory": "Applikation",
+ "TasksLibraryCategory": "Bibliothek",
+ "TasksMaintenanceCategory": "Verwaltung",
+ "TaskDownloadMissingSubtitlesDescription": "Durchsucht das Internet nach fehlenden Untertiteln, basierend auf den Metadaten Einstellungen.",
+ "TaskDownloadMissingSubtitles": "Lade fehlende Untertitel herunter",
+ "TaskRefreshChannelsDescription": "Aktualisiert Internet Kanal Informationen.",
+ "TaskRefreshChannels": "Aktualisiere Kanäle",
+ "TaskCleanTranscodeDescription": "Löscht Transkodierdateien welche älter als ein Tag sind.",
+ "TaskCleanTranscode": "Räume Transcodier Verzeichnis auf",
+ "TaskUpdatePluginsDescription": "Lädt Aktualisierungen für Erweiterungen herunter und installiert diese, für welche automatische Aktualisierungen konfiguriert sind.",
+ "TaskUpdatePlugins": "Aktualisiere Erweiterungen",
+ "TaskRefreshPeopleDescription": "Aktualisiert Metadaten für Schausteller und Regisseure in deiner Bibliothek.",
+ "TaskRefreshPeople": "Aktualisiere Schauspieler",
+ "TaskCleanLogsDescription": "Löscht Log Dateien die älter als {0} Tage sind.",
+ "TaskCleanActivityLogDescription": "Löscht Aktivitätsprotokolleinträge, die älter als das konfigurierte Alter sind.",
+ "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen",
+ "Undefined": "Undefiniert",
+ "Forced": "Erzwungen",
+ "Default": "Standard"
}
diff --git a/Emby.Server.Implementations/Localization/Core/he.json b/Emby.Server.Implementations/Localization/Core/he.json
index fff1d1f0e..981e8a06e 100644
--- a/Emby.Server.Implementations/Localization/Core/he.json
+++ b/Emby.Server.Implementations/Localization/Core/he.json
@@ -1,97 +1,122 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
+ "Albums": "אלבומים",
+ "AppDeviceValues": "יישום: {0}, מכשיר: {1}",
+ "Application": "יישום",
+ "Artists": "אומנים",
+ "AuthenticationSucceededWithUserName": "{0} אומת בהצלחה",
"Books": "ספרים",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
+ "CameraImageUploadedFrom": "תמונת מצלמה חדשה הועלתה מ {0}",
+ "Channels": "ערוצים",
+ "ChapterNameValue": "פרק {0}",
+ "Collections": "אוספים",
+ "DeviceOfflineWithName": "{0} התנתק",
+ "DeviceOnlineWithName": "{0} מחובר",
+ "FailedLoginAttemptWithUserName": "ניסיון כניסה שגוי מ{0}",
+ "Favorites": "מועדפים",
+ "Folders": "תיקיות",
"Genres": "ז'אנרים",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "המשך בצפייה",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
+ "HeaderAlbumArtists": "אמני האלבום",
+ "HeaderContinueWatching": "המשך לצפות",
+ "HeaderFavoriteAlbums": "אלבומים מועדפים",
+ "HeaderFavoriteArtists": "אמנים מועדפים",
+ "HeaderFavoriteEpisodes": "פרקים מועדפים",
+ "HeaderFavoriteShows": "תוכניות מועדפות",
+ "HeaderFavoriteSongs": "שירים מועדפים",
+ "HeaderLiveTV": "שידורים חיים",
+ "HeaderNextUp": "הבא בתור",
"HeaderRecordingGroups": "קבוצות הקלטה",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
+ "HomeVideos": "סרטונים בייתים",
+ "Inherit": "הורש",
+ "ItemAddedWithName": "{0} הוסף לספרייה",
+ "ItemRemovedWithName": "{0} נמחק מהספרייה",
+ "LabelIpAddressValue": "Ip כתובת: {0}",
+ "LabelRunningTimeValue": "משך צפייה: {0}",
"Latest": "אחרון",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
+ "MessageApplicationUpdated": "שרת הJellyfin עודכן",
+ "MessageApplicationUpdatedTo": "שרת הJellyfin עודכן לגרסא {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "הגדרת השרת {0} שונתה",
+ "MessageServerConfigurationUpdated": "תצורת השרת עודכנה",
"MixedContent": "תוכן מעורב",
"Movies": "סרטים",
"Music": "מוזיקה",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
+ "MusicVideos": "קליפים",
+ "NameInstallFailed": "התקנת {0} נכשלה",
+ "NameSeasonNumber": "עונה {0}",
+ "NameSeasonUnknown": "עונה לא ידועה",
+ "NewVersionIsAvailable": "גרסה חדשה של שרת Jellyfin זמינה להורדה.",
+ "NotificationOptionApplicationUpdateAvailable": "קיים עדכון זמין ליישום",
+ "NotificationOptionApplicationUpdateInstalled": "עדכון ליישום הותקן",
+ "NotificationOptionAudioPlayback": "ניגון שמע החל",
+ "NotificationOptionAudioPlaybackStopped": "ניגון שמע הופסק",
+ "NotificationOptionCameraImageUploaded": "תמונת מצלמה הועלתה",
+ "NotificationOptionInstallationFailed": "התקנה נכשלה",
+ "NotificationOptionNewLibraryContent": "תוכן חדש הוסף",
+ "NotificationOptionPluginError": "כשלון בתוסף",
+ "NotificationOptionPluginInstalled": "התוסף הותקן",
+ "NotificationOptionPluginUninstalled": "התוסף הוסר",
+ "NotificationOptionPluginUpdateInstalled": "העדכון לתוסף הותקן",
+ "NotificationOptionServerRestartRequired": "יש לאתחל את השרת",
+ "NotificationOptionTaskFailed": "משימה מתוזמנת נכשלה",
+ "NotificationOptionUserLockedOut": "משתמש ננעל",
+ "NotificationOptionVideoPlayback": "ניגון וידאו החל",
+ "NotificationOptionVideoPlaybackStopped": "ניגון וידאו הופסק",
"Photos": "תמונות",
- "Playlists": "רשימות ניגון",
+ "Playlists": "רשימות הפעלה",
"Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
+ "PluginInstalledWithName": "{0} הותקן",
+ "PluginUninstalledWithName": "{0} הוסר",
+ "PluginUpdatedWithName": "{0} עודכן",
"ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "ScheduledTaskFailedWithName": "{0} נכשל",
+ "ScheduledTaskStartedWithName": "{0} החל",
+ "ServerNameNeedsToBeRestarted": "{0} דורש הפעלה מחדש",
+ "Shows": "סדרות",
+ "Songs": "שירים",
+ "StartupEmbyServerIsLoading": "שרת Jellyfin בהליכי טעינה. אנא נסה שנית בעוד זמן קצר.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
+ "SubtitleDownloadFailureFromForItem": "הורדת כתוביות נכשלה מ-{0} עבור {1}",
"Sync": "סנכרן",
"System": "System",
- "TvShows": "TV Shows",
+ "TvShows": "סדרות טלוויזיה",
"User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserCreatedWithName": "המשתמש {0} נוצר",
+ "UserDeletedWithName": "המשתמש {0} הוסר",
+ "UserDownloadingItemWithValues": "{0} מוריד את {1}",
+ "UserLockedOutWithName": "המשתמש {0} ננעל",
+ "UserOfflineFromDevice": "{0} התנתק מ-{1}",
+ "UserOnlineFromDevice": "{0} מחובר מ-{1}",
+ "UserPasswordChangedWithName": "הסיסמה שונתה עבור המשתמש {0}",
+ "UserPolicyUpdatedWithName": "מדיניות המשתמש {0} עודכנה",
+ "UserStartedPlayingItemWithValues": "{0} מנגן את {1} על {2}",
+ "UserStoppedPlayingItemWithValues": "{0} סיים לנגן את {1} על {2}",
+ "ValueHasBeenAddedToLibrary": "{0} התווסף לספריית המדיה שלך",
"ValueSpecialEpisodeName": "מיוחד- {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskRefreshLibrary": "סרוק ספריית מדיה",
+ "TaskRefreshChapterImages": "חלץ תמונות פרקים",
+ "TaskCleanCacheDescription": "מחק קבצי מטמון שלא בשימוש המערכת.",
+ "TaskCleanCache": "נקה תיקיית מטמון",
+ "TasksApplicationCategory": "יישום",
+ "TasksLibraryCategory": "ספרייה",
+ "TasksMaintenanceCategory": "תחזוקה",
+ "TaskUpdatePlugins": "עדכן תוספים",
+ "TaskRefreshPeopleDescription": "מעדכן מטא נתונים עבור שחקנים ובמאים בספריית המדיה שלך.",
+ "TaskRefreshPeople": "רענן אנשים",
+ "TaskCleanLogsDescription": "מוחק קבצי יומן בני יותר מ- {0} ימים.",
+ "TaskCleanLogs": "נקה תיקיית יומן",
+ "TaskRefreshLibraryDescription": "סורק את ספריית המדיה שלך אחר קבצים חדשים ומרענן מטא נתונים.",
+ "TaskRefreshChapterImagesDescription": "יוצר תמונות ממוזערות לסרטונים שיש להם פרקים.",
+ "TasksChannelsCategory": "ערוצי אינטרנט",
+ "TaskDownloadMissingSubtitlesDescription": "חפש באינטרנט עבור הכתוביות החסרות בהתבסס על המטה-דיאטה.",
+ "TaskDownloadMissingSubtitles": "הורד כתוביות חסרות",
+ "TaskRefreshChannelsDescription": "רענן פרטי ערוץ אינטרנטי.",
+ "TaskRefreshChannels": "רענן ערוץ",
+ "TaskCleanTranscodeDescription": "מחק קבצי transcode שנוצרו מלפני יותר מיום.",
+ "TaskCleanTranscode": "נקה תקיית Transcode",
+ "TaskUpdatePluginsDescription": "הורד והתקן עדכונים עבור תוספים שמוגדרים לעדכון אוטומטי.",
+ "TaskCleanActivityLogDescription": "מחק רשומת פעילות הישנה יותר מהגיל המוגדר.",
+ "TaskCleanActivityLog": "נקה רשומת פעילות",
+ "Undefined": "לא מוגדר",
+ "Forced": "כפוי",
+ "Default": "ברירת מחדל"
}
diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json
new file mode 100644
index 000000000..82dc601bc
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/hi.json
@@ -0,0 +1,64 @@
+{
+ "Albums": "एल्बम",
+ "HeaderRecordingGroups": "रिकॉर्डिंग समूह",
+ "HeaderNextUp": "इसके बाद",
+ "HeaderLiveTV": "लाइव टीवी",
+ "HeaderFavoriteSongs": "पसंदीदा गीत",
+ "HeaderFavoriteShows": "पसंदीदा शोज",
+ "HeaderFavoriteEpisodes": "पसंदीदा एपिसोड्स",
+ "HeaderFavoriteArtists": "पसंदीदा कलाकारसमूह",
+ "HeaderFavoriteAlbums": "पसंदीदा एलबम्स",
+ "HeaderContinueWatching": "देखते रहिए",
+ "HeaderAlbumArtists": "एल्बम कलकरसमुह",
+ "Genres": "शैली",
+ "Forced": "बलपूर्वक",
+ "Folders": "फोल्डेरें",
+ "Favorites": "पसंदीदा",
+ "FailedLoginAttemptWithUserName": "{0} से लॉगिन असफल हुआ है",
+ "DeviceOnlineWithName": "{0} से संयोग हो गया है",
+ "DeviceOfflineWithName": "{0} से संयोग विच्छिन्न हो गया है",
+ "Default": "प्राथमिक",
+ "Collections": "संग्रह",
+ "ChapterNameValue": "अध्याय",
+ "Channels": "चैनल",
+ "CameraImageUploadedFrom": "कैमरा से एक नया चित्र अपलोड किया गया है",
+ "Books": "किताब",
+ "AuthenticationSucceededWithUserName": "सफलता से प्रमाणीकृत",
+ "Artists": "कलाकारों",
+ "Application": "एप्लिकेशन",
+ "AppDeviceValues": "एप: {0}, उपकरण: {1}",
+ "NotificationOptionPluginUninstalled": "प्लगइन अनइंस्टाल हो गया",
+ "NotificationOptionPluginInstalled": "प्लगइन इनस्टॉल हो गया",
+ "NotificationOptionPluginError": "प्लगइन फ़ैल हो गया",
+ "NotificationOptionInstallationFailed": "इंस्टालेशन फ़ैल हो गया",
+ "NotificationOptionAudioPlaybackStopped": "संगीत बंद कर दिया गया",
+ "NotificationOptionAudioPlayback": "संगीत शुरू कर दिया गया",
+ "NotificationOptionCameraImageUploaded": "कैमरा फोटो अपलोड किया गया",
+ "NotificationOptionApplicationUpdateInstalled": "एप्लीकेशन अपडेट इनस्टॉल कर दिया है",
+ "NotificationOptionApplicationUpdateAvailable": "एप्लीकेशन अपडेट उपलभ्द है",
+ "NewVersionIsAvailable": "जेलीफिन सर्वर का एक नया वर्जन डाउनलोड के लिए उपलब्ध है।",
+ "NameSeasonUnknown": "अनजान भाग",
+ "NameSeasonNumber": "भाग {0}",
+ "NameInstallFailed": "{0} इनस्टॉल करते समय फेल हो गया है",
+ "MusicVideos": "संगीत वीडियो",
+ "Music": "संगीत",
+ "Movies": "फ़िल्म",
+ "MixedContent": "मिला-जुला कंटेंट",
+ "MessageServerConfigurationUpdated": "सर्वर कॉन्फ़िगरेशन अपडेट हो गया है",
+ "MessageNamedServerConfigurationUpdatedWithValue": "सर्वर कॉन्फ़िगरेशन भाग {0} अपडेट हो गया है",
+ "MessageApplicationUpdatedTo": "जैलीफिन सर्वर {0} में अपडेट हो गया है",
+ "MessageApplicationUpdated": "जैलीफिन सर्वर अपडेट हो गया है",
+ "Latest": "सबसे नया",
+ "LabelIpAddressValue": "आई पी एड्रेस: {0}",
+ "ItemRemovedWithName": "{0} लाइब्रेरी में से निकाल दिया है",
+ "HomeVideos": "होम वीडियोस",
+ "NotificationOptionVideoPlayback": "वीडियो प्लेबैक शुरू हुआ",
+ "NotificationOptionUserLockedOut": "उपयोगकर्ता लॉक हो गया",
+ "NotificationOptionTaskFailed": "निर्धारित कार्य विफलता",
+ "NotificationOptionServerRestartRequired": "सर्वर पुनरारंभ आवश्यक है",
+ "NotificationOptionPluginUpdateInstalled": "प्लगइन अद्यतन स्थापित",
+ "NotificationOptionNewLibraryContent": "नई सामग्री जोड़ी गई",
+ "LabelRunningTimeValue": "चलने का समय: {0}",
+ "ItemAddedWithName": "{0} को लाइब्रेरी में जोड़ा गया",
+ "Inherit": "इनहेरिट"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json
index f284b3cd9..d7cda61da 100644
--- a/Emby.Server.Implementations/Localization/Core/hr.json
+++ b/Emby.Server.Implementations/Localization/Core/hr.json
@@ -5,93 +5,118 @@
"Artists": "Izvođači",
"AuthenticationSucceededWithUserName": "{0} uspješno ovjerena",
"Books": "Knjige",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Nova fotografija sa kamere je učitana iz {0}",
"Channels": "Kanali",
"ChapterNameValue": "Poglavlje {0}",
"Collections": "Kolekcije",
- "DeviceOfflineWithName": "{0} se odspojilo",
- "DeviceOnlineWithName": "{0} je spojeno",
- "FailedLoginAttemptWithUserName": "Neuspjeli pokušaj prijave za {0}",
- "Favorites": "Omiljeni",
+ "DeviceOfflineWithName": "{0} je prekinuo vezu",
+ "DeviceOnlineWithName": "{0} je povezan",
+ "FailedLoginAttemptWithUserName": "Neuspjeli pokušaj prijave od {0}",
+ "Favorites": "Favoriti",
"Folders": "Mape",
"Genres": "Žanrovi",
- "HeaderAlbumArtists": "Izvođači albuma",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
+ "HeaderAlbumArtists": "Album od izvođača",
+ "HeaderContinueWatching": "Nastavi gledati",
"HeaderFavoriteAlbums": "Omiljeni albumi",
"HeaderFavoriteArtists": "Omiljeni izvođači",
"HeaderFavoriteEpisodes": "Omiljene epizode",
- "HeaderFavoriteShows": "Omiljene emisije",
+ "HeaderFavoriteShows": "Omiljene serije",
"HeaderFavoriteSongs": "Omiljene pjesme",
"HeaderLiveTV": "TV uživo",
- "HeaderNextUp": "Sljedeće je",
+ "HeaderNextUp": "Slijedi",
"HeaderRecordingGroups": "Grupa snimka",
- "HomeVideos": "Kućni videi",
+ "HomeVideos": "Kućni video",
"Inherit": "Naslijedi",
"ItemAddedWithName": "{0} je dodano u biblioteku",
- "ItemRemovedWithName": "{0} je uklonjen iz biblioteke",
- "LabelIpAddressValue": "Ip adresa: {0}",
+ "ItemRemovedWithName": "{0} je uklonjeno iz biblioteke",
+ "LabelIpAddressValue": "IP adresa: {0}",
"LabelRunningTimeValue": "Vrijeme rada: {0}",
"Latest": "Najnovije",
- "MessageApplicationUpdated": "Jellyfin Server je ažuriran",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Odjeljak postavka servera {0} je ažuriran",
- "MessageServerConfigurationUpdated": "Postavke servera su ažurirane",
+ "MessageApplicationUpdated": "Jellyfin server je ažuriran",
+ "MessageApplicationUpdatedTo": "Jellyfin server je ažuriran na {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Dio konfiguracije servera {0} je ažuriran",
+ "MessageServerConfigurationUpdated": "Konfiguracija servera je ažurirana",
"MixedContent": "Miješani sadržaj",
"Movies": "Filmovi",
"Music": "Glazba",
"MusicVideos": "Glazbeni spotovi",
- "NameInstallFailed": "{0} installation failed",
+ "NameInstallFailed": "{0} neuspješnih instalacija",
"NameSeasonNumber": "Sezona {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Dostupno ažuriranje aplikacije",
- "NotificationOptionApplicationUpdateInstalled": "Instalirano ažuriranje aplikacije",
- "NotificationOptionAudioPlayback": "Reprodukcija glazbe započeta",
- "NotificationOptionAudioPlaybackStopped": "Reprodukcija audiozapisa je zaustavljena",
- "NotificationOptionCameraImageUploaded": "Slike kamere preuzete",
- "NotificationOptionInstallationFailed": "Instalacija nije izvršena",
- "NotificationOptionNewLibraryContent": "Novi sadržaj je dodan",
- "NotificationOptionPluginError": "Dodatak otkazao",
+ "NameSeasonUnknown": "Sezona nepoznata",
+ "NewVersionIsAvailable": "Nova verzija Jellyfin servera je dostupna za preuzimanje.",
+ "NotificationOptionApplicationUpdateAvailable": "Dostupno je ažuriranje aplikacije",
+ "NotificationOptionApplicationUpdateInstalled": "Instalirano je ažuriranje aplikacije",
+ "NotificationOptionAudioPlayback": "Reprodukcija glazbe započela",
+ "NotificationOptionAudioPlaybackStopped": "Reprodukcija glazbe zaustavljena",
+ "NotificationOptionCameraImageUploaded": "Slika s kamere učitana",
+ "NotificationOptionInstallationFailed": "Instalacija nije uspjela",
+ "NotificationOptionNewLibraryContent": "Novi sadržaj dodan",
+ "NotificationOptionPluginError": "Dodatak zakazao",
"NotificationOptionPluginInstalled": "Dodatak instaliran",
- "NotificationOptionPluginUninstalled": "Dodatak uklonjen",
- "NotificationOptionPluginUpdateInstalled": "Instalirano ažuriranje za dodatak",
- "NotificationOptionServerRestartRequired": "Potrebno ponovo pokretanje servera",
- "NotificationOptionTaskFailed": "Zakazan zadatak nije izvršen",
+ "NotificationOptionPluginUninstalled": "Dodatak deinstaliran",
+ "NotificationOptionPluginUpdateInstalled": "Instalirano ažuriranje dodatka",
+ "NotificationOptionServerRestartRequired": "Ponovno pokrenite server",
+ "NotificationOptionTaskFailed": "Greška zakazanog zadatka",
"NotificationOptionUserLockedOut": "Korisnik zaključan",
- "NotificationOptionVideoPlayback": "Reprodukcija videa započeta",
- "NotificationOptionVideoPlaybackStopped": "Reprodukcija videozapisa je zaustavljena",
- "Photos": "Slike",
- "Playlists": "Popisi",
+ "NotificationOptionVideoPlayback": "Reprodukcija videa započela",
+ "NotificationOptionVideoPlaybackStopped": "Reprodukcija videa zaustavljena",
+ "Photos": "Fotografije",
+ "Playlists": "Popisi za reprodukciju",
"Plugin": "Dodatak",
"PluginInstalledWithName": "{0} je instalirano",
"PluginUninstalledWithName": "{0} je deinstalirano",
"PluginUpdatedWithName": "{0} je ažurirano",
- "ProviderValue": "Pružitelj: {0}",
+ "ProviderValue": "Pružatelj: {0}",
"ScheduledTaskFailedWithName": "{0} neuspjelo",
"ScheduledTaskStartedWithName": "{0} pokrenuto",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
+ "ServerNameNeedsToBeRestarted": "{0} treba ponovno pokrenuti",
+ "Shows": "Serije",
"Songs": "Pjesme",
- "StartupEmbyServerIsLoading": "Jellyfin Server se učitava. Pokušajte ponovo kasnije.",
+ "StartupEmbyServerIsLoading": "Jellyfin server se učitava. Pokušajte ponovo uskoro.",
"SubtitleDownloadFailureForItem": "Titlovi prijevoda nisu preuzeti za {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Titlovi prijevoda preuzeti za {0}",
- "Sync": "Sink.",
- "System": "Sistem",
- "TvShows": "TV Shows",
+ "SubtitleDownloadFailureFromForItem": "Prijevod nije uspješno preuzet od {0} za {1}",
+ "Sync": "Sinkronizacija",
+ "System": "Sustav",
+ "TvShows": "Serije",
"User": "Korisnik",
- "UserCreatedWithName": "Korisnik {0} je stvoren",
+ "UserCreatedWithName": "Korisnik {0} je kreiran",
"UserDeletedWithName": "Korisnik {0} je obrisan",
- "UserDownloadingItemWithValues": "{0} se preuzima {1}",
+ "UserDownloadingItemWithValues": "{0} preuzima {1}",
"UserLockedOutWithName": "Korisnik {0} je zaključan",
- "UserOfflineFromDevice": "{0} se odspojilo od {1}",
- "UserOnlineFromDevice": "{0} je online od {1}",
+ "UserOfflineFromDevice": "{0} prekinuo vezu od {1}",
+ "UserOnlineFromDevice": "{0} povezan od {1}",
"UserPasswordChangedWithName": "Lozinka je promijenjena za korisnika {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} je pokrenuo {1}",
- "UserStoppedPlayingItemWithValues": "{0} je zaustavio {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Specijal - {0}",
- "VersionNumber": "Verzija {0}"
+ "UserPolicyUpdatedWithName": "Pravila za korisnika ažurirana su za {0}",
+ "UserStartedPlayingItemWithValues": "{0} je pokrenuo reprodukciju {1} na {2}",
+ "UserStoppedPlayingItemWithValues": "{0} je završio reprodukciju {1} na {2}",
+ "ValueHasBeenAddedToLibrary": "{0} je dodano u medijsku biblioteku",
+ "ValueSpecialEpisodeName": "Posebno - {0}",
+ "VersionNumber": "Verzija {0}",
+ "TaskRefreshLibraryDescription": "Skenira medijsku biblioteku radi novih datoteka i osvježava metapodatke.",
+ "TaskRefreshLibrary": "Skeniraj medijsku biblioteku",
+ "TaskRefreshChapterImagesDescription": "Kreira sličice za videozapise koji imaju poglavlja.",
+ "TaskRefreshChapterImages": "Izdvoji slike poglavlja",
+ "TaskCleanCacheDescription": "Briše nepotrebne datoteke iz predmemorije.",
+ "TaskCleanCache": "Očisti mapu predmemorije",
+ "TasksApplicationCategory": "Aplikacija",
+ "TasksMaintenanceCategory": "Održavanje",
+ "TaskDownloadMissingSubtitlesDescription": "Pretraži Internet za prijevodima koji nedostaju prema konfiguraciji metapodataka.",
+ "TaskDownloadMissingSubtitles": "Preuzmi prijevod koji nedostaje",
+ "TaskRefreshChannelsDescription": "Osvježava informacije Internet kanala.",
+ "TaskRefreshChannels": "Osvježi kanale",
+ "TaskCleanTranscodeDescription": "Briše transkodirane datoteke starije od jednog dana.",
+ "TaskCleanTranscode": "Očisti mapu transkodiranja",
+ "TaskUpdatePluginsDescription": "Preuzima i instalira ažuriranja za dodatke koji su konfigurirani da se ažuriraju automatski.",
+ "TaskUpdatePlugins": "Ažuriraj dodatke",
+ "TaskRefreshPeopleDescription": "Ažurira metapodatke za glumce i redatelje u medijskoj biblioteci.",
+ "TaskRefreshPeople": "Osvježi osobe",
+ "TaskCleanLogsDescription": "Briše zapise dnevnika koji su stariji od {0} dana.",
+ "TaskCleanLogs": "Očisti mapu dnevnika zapisa",
+ "TasksChannelsCategory": "Internet kanali",
+ "TasksLibraryCategory": "Biblioteka",
+ "TaskCleanActivityLogDescription": "Briše zapise dnevnika aktivnosti starije od navedenog vremena.",
+ "TaskCleanActivityLog": "Očisti dnevnik aktivnosti",
+ "Undefined": "Nedefinirano",
+ "Forced": "Forsirani",
+ "Default": "Zadano"
}
diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json
index c0f988abe..85ab1511a 100644
--- a/Emby.Server.Implementations/Localization/Core/hu.json
+++ b/Emby.Server.Implementations/Localization/Core/hu.json
@@ -1,56 +1,55 @@
{
"Albums": "Albumok",
"AppDeviceValues": "Program: {0}, Eszköz: {1}",
- "Application": "Program",
+ "Application": "Alkalmazás",
"Artists": "Előadók",
"AuthenticationSucceededWithUserName": "{0} sikeresen azonosítva",
"Books": "Könyvek",
- "CameraImageUploadedFrom": "Új kamerakép került feltöltésre {0}",
+ "CameraImageUploadedFrom": "Új kamerakép került feltöltésre innen: {0}",
"Channels": "Csatornák",
- "ChapterNameValue": "Jelenet {0}",
+ "ChapterNameValue": "{0}. jelenet",
"Collections": "Gyűjtemények",
"DeviceOfflineWithName": "{0} kijelentkezett",
"DeviceOnlineWithName": "{0} belépett",
- "FailedLoginAttemptWithUserName": "Sikertelen bejelentkezési kísérlet {0}",
+ "FailedLoginAttemptWithUserName": "Sikertelen bejelentkezési kísérlet tőle: {0}",
"Favorites": "Kedvencek",
"Folders": "Könyvtárak",
"Genres": "Műfajok",
- "HeaderAlbumArtists": "Album Előadók",
- "HeaderCameraUploads": "Kamera feltöltések",
- "HeaderContinueWatching": "Folyamatban lévő filmek",
- "HeaderFavoriteAlbums": "Kedvenc Albumok",
- "HeaderFavoriteArtists": "Kedvenc Művészek",
- "HeaderFavoriteEpisodes": "Kedvenc Epizódok",
- "HeaderFavoriteShows": "Kedvenc Műsorok",
- "HeaderFavoriteSongs": "Kedvenc Dalok",
+ "HeaderAlbumArtists": "Előadó albumai",
+ "HeaderContinueWatching": "Megtekintés folytatása",
+ "HeaderFavoriteAlbums": "Kedvenc albumok",
+ "HeaderFavoriteArtists": "Kedvenc előadók",
+ "HeaderFavoriteEpisodes": "Kedvenc epizódok",
+ "HeaderFavoriteShows": "Kedvenc sorozatok",
+ "HeaderFavoriteSongs": "Kedvenc dalok",
"HeaderLiveTV": "Élő TV",
"HeaderNextUp": "Következik",
"HeaderRecordingGroups": "Felvételi csoportok",
"HomeVideos": "Házi videók",
- "Inherit": "Inherit",
+ "Inherit": "Örökölt",
"ItemAddedWithName": "{0} hozzáadva a könyvtárhoz",
"ItemRemovedWithName": "{0} eltávolítva a könyvtárból",
"LabelIpAddressValue": "IP cím: {0}",
"LabelRunningTimeValue": "Futási idő: {0}",
"Latest": "Legújabb",
"MessageApplicationUpdated": "Jellyfin Szerver frissítve",
- "MessageApplicationUpdatedTo": "Jellyfin Szerver frissítve lett a következőre {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Szerver konfigurációs rész {0} frissítve",
+ "MessageApplicationUpdatedTo": "Jellyfin Szerver frissítve lett a következőre: {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Szerver konfigurációs rész frissítve: {0}",
"MessageServerConfigurationUpdated": "Szerver konfiguráció frissítve",
"MixedContent": "Vegyes tartalom",
"Movies": "Filmek",
"Music": "Zene",
- "MusicVideos": "Zenei Videók",
+ "MusicVideos": "Zenei videóklippek",
"NameInstallFailed": "{0} sikertelen telepítés",
- "NameSeasonNumber": "Évad {0}",
+ "NameSeasonNumber": "{0}. évad",
"NameSeasonUnknown": "Ismeretlen évad",
"NewVersionIsAvailable": "Letölthető a Jellyfin Szerver új verziója.",
- "NotificationOptionApplicationUpdateAvailable": "Új programfrissítés érhető el",
- "NotificationOptionApplicationUpdateInstalled": "Programfrissítés telepítve",
+ "NotificationOptionApplicationUpdateAvailable": "Frissítés érhető el az alkalmazáshoz",
+ "NotificationOptionApplicationUpdateInstalled": "Alkalmazásfrissítés telepítve",
"NotificationOptionAudioPlayback": "Audió lejátszás elkezdve",
- "NotificationOptionAudioPlaybackStopped": "Audió lejátszás befejezve",
+ "NotificationOptionAudioPlaybackStopped": "Audió lejátszás leállítva",
"NotificationOptionCameraImageUploaded": "Kamera kép feltöltve",
- "NotificationOptionInstallationFailed": "Telepítési hiba",
+ "NotificationOptionInstallationFailed": "Telepítés sikertelen",
"NotificationOptionNewLibraryContent": "Új tartalom hozzáadva",
"NotificationOptionPluginError": "Bővítmény hiba",
"NotificationOptionPluginInstalled": "Bővítmény telepítve",
@@ -60,38 +59,66 @@
"NotificationOptionTaskFailed": "Ütemezett feladat hiba",
"NotificationOptionUserLockedOut": "Felhasználó tiltva",
"NotificationOptionVideoPlayback": "Videó lejátszás elkezdve",
- "NotificationOptionVideoPlaybackStopped": "Videó lejátszás befejezve",
+ "NotificationOptionVideoPlaybackStopped": "Videó lejátszás leállítva",
"Photos": "Fényképek",
"Playlists": "Lejátszási listák",
"Plugin": "Bővítmény",
"PluginInstalledWithName": "{0} telepítve",
"PluginUninstalledWithName": "{0} eltávolítva",
"PluginUpdatedWithName": "{0} frissítve",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} hiba",
+ "ProviderValue": "Szolgáltató: {0}",
+ "ScheduledTaskFailedWithName": "{0} sikertelen",
"ScheduledTaskStartedWithName": "{0} elkezdve",
"ServerNameNeedsToBeRestarted": "{0}-t újra kell indítani",
- "Shows": "Műsorok",
+ "Shows": "Sorozatok",
"Songs": "Dalok",
- "StartupEmbyServerIsLoading": "A Jellyfin Szerver betöltődik. Kérlek próbáld újra később.",
+ "StartupEmbyServerIsLoading": "A Jellyfin Szerver betöltődik. Kérlek, próbáld újra hamarosan.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Nem sikerült a felirat letöltése innen: {0} ehhez: {1}",
- "SubtitlesDownloadedForItem": "Letöltött feliratok a következőhöz {0}",
+ "SubtitleDownloadFailureFromForItem": "Nem sikerült a felirat letöltése innen: {0} ehhez: {1}",
"Sync": "Szinkronizál",
"System": "Rendszer",
- "TvShows": "TV Műsorok",
+ "TvShows": "TV műsorok",
"User": "Felhasználó",
"UserCreatedWithName": "{0} felhasználó létrehozva",
"UserDeletedWithName": "{0} felhasználó törölve",
"UserDownloadingItemWithValues": "{0} letölti {1}",
- "UserLockedOutWithName": "{0} felhasználó zárolva van",
- "UserOfflineFromDevice": "{0} kijelentkezett innen: {1}",
- "UserOnlineFromDevice": "{0} online itt: {1}",
+ "UserLockedOutWithName": "{0} felhasználó zárolva van",
+ "UserOfflineFromDevice": "{0} kijelentkezett innen: {1}",
+ "UserOnlineFromDevice": "{0} online innen: {1}",
"UserPasswordChangedWithName": "Jelszó megváltozott a következő felhasználó számára: {0}",
- "UserPolicyUpdatedWithName": "A felhasználói házirend frissítve lett {0}",
- "UserStartedPlayingItemWithValues": "{0} elkezdte játszani a következőt: {1} itt: {2}",
- "UserStoppedPlayingItemWithValues": "{0} befejezte a következőt: {1} itt: {2}",
+ "UserPolicyUpdatedWithName": "A felhasználói házirend frissítve lett neki: {0}",
+ "UserStartedPlayingItemWithValues": "{0} elkezdte játszani a következőt: {1} itt: {2}",
+ "UserStoppedPlayingItemWithValues": "{0} befejezte {1} lejátászását itt: {2}",
"ValueHasBeenAddedToLibrary": "{0} hozzáadva a médiatárhoz",
"ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Verzió: {0}"
+ "VersionNumber": "Verzió: {0}",
+ "TaskCleanTranscode": "Átkódolási könyvtár ürítése",
+ "TaskUpdatePluginsDescription": "Letölti és telepíti a frissítéseket azokhoz a bővítményekhez, amelyeknél az automatikus frissítés engedélyezve van.",
+ "TaskUpdatePlugins": "Bővítmények frissítése",
+ "TaskRefreshPeopleDescription": "Frissíti a szereplők és a stábok metaadatait a könyvtáradban.",
+ "TaskRefreshPeople": "Személyek frissítése",
+ "TaskCleanLogsDescription": "Törli azokat a naplófájlokat, amelyek {0} napnál régebbiek.",
+ "TaskCleanLogs": "Naplózási könyvtár ürítése",
+ "TaskRefreshLibraryDescription": "Átvizsgálja a könyvtáraidat új fájlokért és frissíti a metaadatokat.",
+ "TaskRefreshLibrary": "Média könyvtár beolvasása",
+ "TaskRefreshChapterImagesDescription": "Miniatűröket generál olyan videókhoz, amely tartalmaz fejezeteket.",
+ "TaskRefreshChapterImages": "Fejezetek képeinek generálása",
+ "TaskCleanCacheDescription": "Törli azokat a gyorsítótárazott fájlokat, amikre a rendszernek már nincs szüksége.",
+ "TaskCleanCache": "Gyorsítótár könyvtárának ürítése",
+ "TasksChannelsCategory": "Internetes csatornák",
+ "TasksApplicationCategory": "Alkalmazás",
+ "TasksLibraryCategory": "Könyvtár",
+ "TasksMaintenanceCategory": "Karbantartás",
+ "TaskDownloadMissingSubtitlesDescription": "A metaadat konfiguráció alapján ellenőrzi és letölti a hiányzó feliratokat az internetről.",
+ "TaskDownloadMissingSubtitles": "Hiányzó feliratok letöltése",
+ "TaskRefreshChannelsDescription": "Frissíti az internetes csatornák adatait.",
+ "TaskRefreshChannels": "Csatornák frissítése",
+ "TaskCleanTranscodeDescription": "Törli az egy napnál régebbi átkódolási fájlokat.",
+ "TaskCleanActivityLogDescription": "A beállítottnál korábbi bejegyzések törlése a tevékenységnaplóból.",
+ "TaskCleanActivityLog": "Tevékenységnapló törlése",
+ "Undefined": "Meghatározatlan",
+ "Forced": "Kényszerített",
+ "Default": "Alapértelmezett",
+ "TaskOptimizeDatabaseDescription": "Tömöríti az adatbázist és csonkolja a szabad helyet. A feladat futtatása a könyvtár beolvasása után, vagy egyéb, adatbázis-módosítást igénylő változtatások végrehajtása javíthatja a teljesítményt.",
+ "TaskOptimizeDatabase": "Adatbázis optimalizálása"
}
diff --git a/Emby.Server.Implementations/Localization/Core/id.json b/Emby.Server.Implementations/Localization/Core/id.json
new file mode 100644
index 000000000..ba3513870
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/id.json
@@ -0,0 +1,121 @@
+{
+ "Albums": "Album",
+ "AuthenticationSucceededWithUserName": "{0} berhasil diautentikasi",
+ "AppDeviceValues": "Aplikasi : {0}, Perangkat : {1}",
+ "LabelRunningTimeValue": "Waktu berjalan: {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin Server sudah diperbarui ke {0}",
+ "MessageApplicationUpdated": "Jellyfin Server sudah diperbarui",
+ "Latest": "Terbaru",
+ "LabelIpAddressValue": "Alamat IP: {0}",
+ "ItemRemovedWithName": "{0} sudah dikeluarkan dari pustaka",
+ "ItemAddedWithName": "{0} telah dimasukkan ke dalam pustaka",
+ "Inherit": "Warisan",
+ "HomeVideos": "Video Rumah",
+ "HeaderRecordingGroups": "Grup Rekaman",
+ "HeaderNextUp": "Selanjutnya",
+ "HeaderLiveTV": "TV Live",
+ "HeaderFavoriteSongs": "Lagu Favorit",
+ "HeaderFavoriteShows": "Tayangan Favorit",
+ "HeaderFavoriteEpisodes": "Episode Favorit",
+ "HeaderFavoriteArtists": "Artis Favorit",
+ "HeaderFavoriteAlbums": "Album Favorit",
+ "HeaderContinueWatching": "Lanjut Menonton",
+ "HeaderAlbumArtists": "Album Artis",
+ "Genres": "Aliran",
+ "Folders": "Folder",
+ "Favorites": "Favorit",
+ "Collections": "Koleksi",
+ "Books": "Buku",
+ "Artists": "Artis",
+ "Application": "Aplikasi",
+ "ChapterNameValue": "Bagian {0}",
+ "Channels": "Saluran",
+ "TvShows": "Seri TV",
+ "SubtitleDownloadFailureFromForItem": "Subtitel gagal diunduh dari {0} untuk {1}",
+ "StartupEmbyServerIsLoading": "Server Jellyfin sedang dimuat. Silakan coba lagi nanti.",
+ "Songs": "Lagu",
+ "Playlists": "Daftar putar",
+ "NotificationOptionPluginUninstalled": "Plugin dihapus",
+ "MusicVideos": "Video musik",
+ "VersionNumber": "Versi {0}",
+ "ValueSpecialEpisodeName": "Spesial - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} telah ditambahkan ke pustaka media Anda",
+ "UserStoppedPlayingItemWithValues": "{0} telah selesai memutar {1} pada {2}",
+ "UserStartedPlayingItemWithValues": "{0} sedang memutar {1} pada {2}",
+ "UserPolicyUpdatedWithName": "Kebijakan pengguna telah diperbarui untuk {0}",
+ "UserPasswordChangedWithName": "Kata sandi telah diubah untuk pengguna {0}",
+ "UserOnlineFromDevice": "{0} sedang daring dari {1}",
+ "UserOfflineFromDevice": "{0} telah terputus dari {1}",
+ "UserLockedOutWithName": "Pengguna {0} telah dikunci",
+ "UserDownloadingItemWithValues": "{0} sedang mengunduh {1}",
+ "UserDeletedWithName": "Pengguna {0} telah dihapus",
+ "UserCreatedWithName": "Pengguna {0} telah dibuat",
+ "User": "Pengguna",
+ "System": "Sistem",
+ "Sync": "Sinkron",
+ "Shows": "Tayangan",
+ "ServerNameNeedsToBeRestarted": "{0} perlu dimuat ulang",
+ "ScheduledTaskStartedWithName": "{0} dimulai",
+ "ScheduledTaskFailedWithName": "{0} gagal",
+ "ProviderValue": "Penyedia: {0}",
+ "PluginUpdatedWithName": "{0} telah diperbarui",
+ "PluginInstalledWithName": "{0} telah dipasang",
+ "Plugin": "Plugin",
+ "Photos": "Foto",
+ "NotificationOptionUserLockedOut": "Pengguna terkunci",
+ "NotificationOptionTaskFailed": "Kegagalan tugas terjadwal",
+ "NotificationOptionServerRestartRequired": "Muat ulang server dibutuhkan",
+ "NotificationOptionPluginUpdateInstalled": "Pembaruan plugin terpasang",
+ "NotificationOptionPluginInstalled": "Plugin terpasang",
+ "NotificationOptionPluginError": "Kegagalan plugin",
+ "NotificationOptionNewLibraryContent": "Konten baru ditambahkan",
+ "NotificationOptionInstallationFailed": "Kegagalan pemasangan",
+ "NotificationOptionCameraImageUploaded": "Gambar kamera terunggah",
+ "NotificationOptionApplicationUpdateInstalled": "Pembaruan aplikasi terpasang",
+ "NotificationOptionApplicationUpdateAvailable": "Pembaruan aplikasi tersedia",
+ "NewVersionIsAvailable": "Versi baru dari Jellyfin Server tersedia untuk diunduh.",
+ "NameSeasonUnknown": "Musim tak diketahui",
+ "NameSeasonNumber": "Musim {0}",
+ "NameInstallFailed": "{0} penginstalan gagal",
+ "Music": "Musik",
+ "Movies": "Film",
+ "MessageServerConfigurationUpdated": "Konfigurasi server telah diperbarui",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Bagian konfigurasi server {0} telah diperbarui",
+ "FailedLoginAttemptWithUserName": "Percobaan login gagal dari {0}",
+ "CameraImageUploadedFrom": "Sebuah gambar baru telah diunggah dari {0}",
+ "DeviceOfflineWithName": "{0} telah terputus",
+ "DeviceOnlineWithName": "{0} telah terhubung",
+ "NotificationOptionVideoPlaybackStopped": "Pemutaran video berhenti",
+ "NotificationOptionVideoPlayback": "Pemutaran video dimulai",
+ "NotificationOptionAudioPlaybackStopped": "Pemutaran audio berhenti",
+ "NotificationOptionAudioPlayback": "Pemutaran audio dimulai",
+ "MixedContent": "Konten campuran",
+ "PluginUninstalledWithName": "{0} telah dihapus",
+ "TaskRefreshChapterImagesDescription": "Membuat gambar mini untuk video yang memiliki bagian.",
+ "TaskRefreshChapterImages": "Ekstrak Gambar Bagian",
+ "TaskCleanCacheDescription": "Menghapus file cache yang tidak lagi dibutuhkan oleh sistem.",
+ "TaskCleanCache": "Bersihkan Cache Direktori",
+ "TasksLibraryCategory": "Pustaka",
+ "TasksMaintenanceCategory": "Perbaikan",
+ "TasksApplicationCategory": "Aplikasi",
+ "TaskRefreshPeopleDescription": "Memperbarui metadata untuk aktor dan sutradara di pustaka media Anda.",
+ "TaskRefreshLibraryDescription": "Memindai Pustaka media Anda untuk mencari file baru dan memperbarui metadata.",
+ "TasksChannelsCategory": "Saluran Online",
+ "TaskDownloadMissingSubtitlesDescription": "Mencari di internet untuk subtitle yang hilang berdasarkan konfigurasi metadata.",
+ "TaskDownloadMissingSubtitles": "Unduh subtitle yang hilang",
+ "TaskRefreshChannelsDescription": "Segarkan informasi saluran internet.",
+ "TaskRefreshChannels": "Segarkan Saluran",
+ "TaskCleanTranscodeDescription": "Menghapus file transcode yang berumur lebih dari satu hari.",
+ "TaskCleanTranscode": "Bersihkan Direktori Transcode",
+ "TaskUpdatePluginsDescription": "Unduh dan instal pembaruan untuk plugin yang dikonfigurasi untuk memperbarui secara otomatis.",
+ "TaskUpdatePlugins": "Perbarui Plugin",
+ "TaskRefreshPeople": "Muat ulang Orang",
+ "TaskCleanLogsDescription": "Menghapus file log yang lebih dari {0} hari.",
+ "TaskCleanLogs": "Bersihkan Log Direktori",
+ "TaskRefreshLibrary": "Pindai Pustaka Media",
+ "TaskCleanActivityLogDescription": "Menghapus log aktivitas yang lebih tua dari umur yang dikonfigurasi.",
+ "TaskCleanActivityLog": "Bersihkan Log Aktivitas",
+ "Undefined": "Tidak terdefinisi",
+ "Forced": "Dipaksa",
+ "Default": "Bawaan"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/is.json b/Emby.Server.Implementations/Localization/Core/is.json
new file mode 100644
index 000000000..b262a8b42
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/is.json
@@ -0,0 +1,111 @@
+{
+ "LabelIpAddressValue": "IP tala: {0}",
+ "ItemRemovedWithName": "{0} var fjarlægt úr safninu",
+ "ItemAddedWithName": "{0} var bætt í safnið",
+ "Inherit": "Erfa",
+ "HomeVideos": "Heimamyndbönd",
+ "HeaderRecordingGroups": "Upptökuhópar",
+ "HeaderNextUp": "Næst á dagskrá",
+ "HeaderLiveTV": "Sjónvarp í beinni útsendingu",
+ "HeaderFavoriteSongs": "Uppáhalds Lög",
+ "HeaderFavoriteShows": "Uppáhalds Sjónvarpsþættir",
+ "HeaderFavoriteEpisodes": "Uppáhalds Þættir",
+ "HeaderFavoriteArtists": "Uppáhalds Listamenn",
+ "HeaderFavoriteAlbums": "Uppáhalds Plötur",
+ "HeaderContinueWatching": "Halda áfram að horfa",
+ "HeaderAlbumArtists": "Höfundur plötu",
+ "Genres": "Tegundir",
+ "Folders": "Möppur",
+ "Favorites": "Uppáhalds",
+ "FailedLoginAttemptWithUserName": "{0} reyndi að auðkenna sig",
+ "DeviceOnlineWithName": "{0} hefur tengst",
+ "DeviceOfflineWithName": "{0} hefur aftengst",
+ "Collections": "Söfn",
+ "ChapterNameValue": "Kafli {0}",
+ "Channels": "Stöðvar",
+ "CameraImageUploadedFrom": "Ný ljósmynd frá myndavél hefur verið hlaðið upp frá {0}",
+ "Books": "Bækur",
+ "AuthenticationSucceededWithUserName": "{0} auðkenning tókst",
+ "Artists": "Listamaður",
+ "Application": "Forrit",
+ "AppDeviceValues": "Snjallforrit: {0}, Tæki: {1}",
+ "Albums": "Plötur",
+ "Plugin": "Viðbót",
+ "Photos": "Myndir",
+ "NotificationOptionVideoPlaybackStopped": "Myndbandafspilun stöðvuð",
+ "NotificationOptionVideoPlayback": "Myndbandafspilun hafin",
+ "NotificationOptionUserLockedOut": "Notandi læstur úti",
+ "NotificationOptionServerRestartRequired": "Endurræsing þjóns er nauðsynileg",
+ "NotificationOptionPluginUpdateInstalled": "Viðbótar uppfærsla uppsett",
+ "NotificationOptionPluginUninstalled": "Viðbót fjarlægð",
+ "NotificationOptionPluginInstalled": "Viðbót sett upp",
+ "NotificationOptionPluginError": "Bilun í viðbót",
+ "NotificationOptionInstallationFailed": "Uppsetning tókst ekki",
+ "NotificationOptionCameraImageUploaded": "Myndavélarmynd hlaðið upp",
+ "NotificationOptionAudioPlaybackStopped": "Hljóðafspilun stöðvuð",
+ "NotificationOptionAudioPlayback": "Hljóðafspilun hafin",
+ "NotificationOptionApplicationUpdateInstalled": "Uppfærsla uppsett",
+ "NotificationOptionApplicationUpdateAvailable": "Uppfærsla í boði",
+ "NameSeasonUnknown": "Sería óþekkt",
+ "NameSeasonNumber": "Sería {0}",
+ "MixedContent": "Blandað efni",
+ "MessageServerConfigurationUpdated": "Stillingar þjóns hafa verið uppfærðar",
+ "MessageApplicationUpdatedTo": "Jellyfin þjónn hefur verið uppfærður í {0}",
+ "MessageApplicationUpdated": "Jellyfin þjónn hefur verið uppfærður",
+ "Latest": "Nýjasta",
+ "LabelRunningTimeValue": "spilunartími: {0}",
+ "User": "Notandi",
+ "System": "Kerfi",
+ "NotificationOptionNewLibraryContent": "Nýju efni bætt við",
+ "NewVersionIsAvailable": "Ný útgáfa af Jellyfin þjón er fáanleg til niðurhals.",
+ "NameInstallFailed": "{0} uppsetning mistókst",
+ "MusicVideos": "Tónlistarmyndbönd",
+ "Music": "Tónlist",
+ "Movies": "Kvikmyndir",
+ "UserDeletedWithName": "Notanda {0} hefur verið eytt",
+ "UserCreatedWithName": "Notandi {0} hefur verið stofnaður",
+ "TvShows": "Þættir",
+ "Sync": "Samstilla",
+ "Songs": "Lög",
+ "ServerNameNeedsToBeRestarted": "{0} þarf að endurræsa",
+ "ScheduledTaskStartedWithName": "{0} hafin",
+ "ScheduledTaskFailedWithName": "{0} mistókst",
+ "PluginUpdatedWithName": "{0} var uppfært",
+ "PluginUninstalledWithName": "{0} var fjarlægt",
+ "PluginInstalledWithName": "{0} var sett upp",
+ "NotificationOptionTaskFailed": "Tímasett verkefni mistókst",
+ "StartupEmbyServerIsLoading": "Jellyfin netþjónnin er að hlaðast. Vinsamlega prufaðu aftur fljótlega.",
+ "VersionNumber": "Útgáfa {0}",
+ "ValueHasBeenAddedToLibrary": "{0} hefur verið bætt við í gagnasafnið þitt",
+ "UserStoppedPlayingItemWithValues": "{0} hefur lokið spilunar af {1} á {2}",
+ "UserStartedPlayingItemWithValues": "{0} er að spila {1} á {2}",
+ "UserPolicyUpdatedWithName": "Notandaregla hefur verið uppfærð fyrir {0}",
+ "UserPasswordChangedWithName": "Lykilorði fyrir notandann {0} hefur verið breytt",
+ "UserOnlineFromDevice": "{0} hefur verið virkur síðan {1}",
+ "UserOfflineFromDevice": "{0} hefur aftengst frá {1}",
+ "UserLockedOutWithName": "Notanda {0} hefur verið heflaður aðgangur",
+ "UserDownloadingItemWithValues": "{0} Hleður niður {1}",
+ "SubtitleDownloadFailureFromForItem": "Tókst ekki að hala niður skjátextum frá {0} til {1}",
+ "ProviderValue": "Veitandi: {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Stilling {0} hefur verið uppfærð á netþjón",
+ "ValueSpecialEpisodeName": "Sérstakt - {0}",
+ "Shows": "Sýningar",
+ "Playlists": "Spilunarlisti",
+ "TaskRefreshChannelsDescription": "Endurhlaða upplýsingum netrása.",
+ "TaskRefreshChannels": "Endurhlaða Rásir",
+ "TaskCleanTranscodeDescription": "Eyða umkóðuðum skrám sem eru meira en einum degi eldri.",
+ "TaskCleanTranscode": "Hreinsa Umkóðunarmöppu",
+ "TaskUpdatePluginsDescription": "Sækja og setja upp uppfærslur fyrir viðbætur sem eru stilltar til að uppfæra sjálfkrafa.",
+ "TaskUpdatePlugins": "Uppfæra viðbætur",
+ "TaskRefreshPeopleDescription": "Uppfærir lýsigögn fyrir leikara og leikstjóra í miðlasafninu þínu.",
+ "TaskRefreshLibraryDescription": "Skannar miðlasafnið þitt fyrir nýjum skrám og uppfærir lýsigögn.",
+ "TaskRefreshLibrary": "Skanna miðlasafn",
+ "TaskRefreshChapterImagesDescription": "Býr til smámyndir fyrir myndbönd sem hafa kaflaskil.",
+ "TaskCleanCacheDescription": "Eyðir skrám í skyndiminni sem ekki er lengur þörf fyrir í kerfinu.",
+ "TaskCleanCache": "Hreinsa skráasafn skyndiminnis",
+ "TasksChannelsCategory": "Netrásir",
+ "TasksApplicationCategory": "Forrit",
+ "TasksLibraryCategory": "Miðlasafn",
+ "TasksMaintenanceCategory": "Viðhald",
+ "Default": "Sjálfgefið"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json
index a5f1e8f94..5e28cf09f 100644
--- a/Emby.Server.Implementations/Localization/Core/it.json
+++ b/Emby.Server.Implementations/Localization/Core/it.json
@@ -5,20 +5,19 @@
"Artists": "Artisti",
"AuthenticationSucceededWithUserName": "{0} autenticato con successo",
"Books": "Libri",
- "CameraImageUploadedFrom": "È stata caricata una nuova immagine della fotocamera {0}",
+ "CameraImageUploadedFrom": "È stata caricata una nuova fotografia da {0}",
"Channels": "Canali",
"ChapterNameValue": "Capitolo {0}",
"Collections": "Collezioni",
- "DeviceOfflineWithName": "{0} è stato disconnesso",
+ "DeviceOfflineWithName": "{0} si è disconnesso",
"DeviceOnlineWithName": "{0} è connesso",
"FailedLoginAttemptWithUserName": "Tentativo di accesso fallito da {0}",
"Favorites": "Preferiti",
"Folders": "Cartelle",
"Genres": "Generi",
- "HeaderAlbumArtists": "Artisti Album",
- "HeaderCameraUploads": "Caricamenti Fotocamera",
+ "HeaderAlbumArtists": "Artisti dell'Album",
"HeaderContinueWatching": "Continua a guardare",
- "HeaderFavoriteAlbums": "Album preferiti",
+ "HeaderFavoriteAlbums": "Album Preferiti",
"HeaderFavoriteArtists": "Artisti Preferiti",
"HeaderFavoriteEpisodes": "Episodi Preferiti",
"HeaderFavoriteShows": "Serie TV Preferite",
@@ -26,25 +25,25 @@
"HeaderLiveTV": "Diretta TV",
"HeaderNextUp": "Prossimo",
"HeaderRecordingGroups": "Gruppi di Registrazione",
- "HomeVideos": "Video personali",
+ "HomeVideos": "Video Personali",
"Inherit": "Eredita",
"ItemAddedWithName": "{0} è stato aggiunto alla libreria",
"ItemRemovedWithName": "{0} è stato rimosso dalla libreria",
"LabelIpAddressValue": "Indirizzo IP: {0}",
"LabelRunningTimeValue": "Durata: {0}",
- "Latest": "Più recenti",
+ "Latest": "Novità",
"MessageApplicationUpdated": "Il Server Jellyfin è stato aggiornato",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin Server è stato aggiornato a {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "La sezione {0} della configurazione server è stata aggiornata",
"MessageServerConfigurationUpdated": "La configurazione del server è stata aggiornata",
"MixedContent": "Contenuto misto",
"Movies": "Film",
"Music": "Musica",
- "MusicVideos": "Video musicali",
- "NameInstallFailed": "{0} installation failed",
+ "MusicVideos": "Video Musicali",
+ "NameInstallFailed": "{0} installazione fallita",
"NameSeasonNumber": "Stagione {0}",
- "NameSeasonUnknown": "Stagione sconosciuto",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameSeasonUnknown": "Stagione sconosciuta",
+ "NewVersionIsAvailable": "Una nuova versione di Jellyfin Server è disponibile per il download.",
"NotificationOptionApplicationUpdateAvailable": "Aggiornamento dell'applicazione disponibile",
"NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato",
"NotificationOptionAudioPlayback": "La riproduzione audio è iniziata",
@@ -63,20 +62,19 @@
"NotificationOptionVideoPlaybackStopped": "La riproduzione video è stata interrotta",
"Photos": "Foto",
"Playlists": "Playlist",
- "Plugin": "Plug-in",
+ "Plugin": "Plugin",
"PluginInstalledWithName": "{0} è stato Installato",
"PluginUninstalledWithName": "{0} è stato disinstallato",
"PluginUpdatedWithName": "{0} è stato aggiornato",
"ProviderValue": "Provider: {0}",
"ScheduledTaskFailedWithName": "{0} fallito",
"ScheduledTaskStartedWithName": "{0} avviati",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Programmi",
+ "ServerNameNeedsToBeRestarted": "{0} deve essere riavviato",
+ "Shows": "Serie TV",
"Songs": "Canzoni",
"StartupEmbyServerIsLoading": "Jellyfin server si sta avviando. Per favore riprova più tardi.",
"SubtitleDownloadFailureForItem": "Impossibile scaricare i sottotitoli per {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Sottotitoli scaricati per {0}",
+ "SubtitleDownloadFailureFromForItem": "Impossibile scaricare i sottotitoli da {0} per {1}",
"Sync": "Sincronizza",
"System": "Sistema",
"TvShows": "Serie TV",
@@ -85,13 +83,42 @@
"UserDeletedWithName": "L'utente {0} è stato rimosso",
"UserDownloadingItemWithValues": "{0} sta scaricando {1}",
"UserLockedOutWithName": "L'utente {0} è stato bloccato",
- "UserOfflineFromDevice": "{0} è stato disconnesso da {1}",
- "UserOnlineFromDevice": "{0} è online da {1}",
+ "UserOfflineFromDevice": "{0} si è disconnesso su {1}",
+ "UserOnlineFromDevice": "{0} è online su {1}",
"UserPasswordChangedWithName": "La password è stata cambiata per l'utente {0}",
- "UserPolicyUpdatedWithName": "La politica dell'utente è stata aggiornata per {0}",
- "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1}",
- "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserPolicyUpdatedWithName": "La policy dell'utente è stata aggiornata per {0}",
+ "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di \"{1}\" su {2}",
+ "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1} su {2}",
+ "ValueHasBeenAddedToLibrary": "{0} è stato aggiunto alla tua libreria multimediale",
"ValueSpecialEpisodeName": "Speciale - {0}",
- "VersionNumber": "Versione {0}"
+ "VersionNumber": "Versione {0}",
+ "TaskRefreshChannelsDescription": "Aggiorna le informazioni dei canali Internet.",
+ "TaskDownloadMissingSubtitlesDescription": "Cerca su internet i sottotitoli mancanti basandosi sulle configurazioni dei metadati.",
+ "TaskDownloadMissingSubtitles": "Scarica i sottotitoli mancanti",
+ "TaskRefreshChannels": "Aggiorna i canali",
+ "TaskCleanTranscodeDescription": "Cancella i file di transcode più vecchi di un giorno.",
+ "TaskCleanTranscode": "Svuota la cartella del transcoding",
+ "TaskUpdatePluginsDescription": "Scarica e installa gli aggiornamenti per i plugin che sono stati configurati per essere aggiornati contemporaneamente.",
+ "TaskUpdatePlugins": "Aggiorna i Plugin",
+ "TaskRefreshPeopleDescription": "Aggiorna i metadati per gli attori e registi nella tua libreria multimediale.",
+ "TaskRefreshPeople": "Aggiornamento Persone",
+ "TaskCleanLogsDescription": "Rimuovi i file di log più vecchi di {0} giorni.",
+ "TaskCleanLogs": "Pulisci la cartella dei log",
+ "TaskRefreshLibraryDescription": "Analizza la tua libreria multimediale per nuovi file e rinnova i metadati.",
+ "TaskRefreshLibrary": "Scan Librerie",
+ "TaskRefreshChapterImagesDescription": "Crea le thumbnail per i video che hanno capitoli.",
+ "TaskRefreshChapterImages": "Estrai immagini capitolo",
+ "TaskCleanCacheDescription": "Cancella i file di cache non più necessari al sistema.",
+ "TaskCleanCache": "Pulisci la directory della cache",
+ "TasksChannelsCategory": "Canali su Internet",
+ "TasksApplicationCategory": "Applicazione",
+ "TasksLibraryCategory": "Libreria",
+ "TasksMaintenanceCategory": "Manutenzione",
+ "TaskCleanActivityLog": "Attività di Registro Completate",
+ "TaskCleanActivityLogDescription": "Elimina gli inserimenti nel registro delle attività più vecchie dell’età configurata.",
+ "Undefined": "Non Definito",
+ "Forced": "Forzato",
+ "Default": "Predefinito",
+ "TaskOptimizeDatabaseDescription": "Compatta Database e tronca spazi liberi. Eseguire questa azione dopo la scansione o dopo aver fatto altri cambiamenti inerenti il database potrebbe aumentarne la performance.",
+ "TaskOptimizeDatabase": "Ottimizza Database"
}
diff --git a/Emby.Server.Implementations/Localization/Core/ja.json b/Emby.Server.Implementations/Localization/Core/ja.json
new file mode 100644
index 000000000..c689bc58a
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ja.json
@@ -0,0 +1,123 @@
+{
+ "Albums": "アルバム",
+ "AppDeviceValues": "アプリ: {0}, デバイス: {1}",
+ "Application": "アプリケーション",
+ "Artists": "アーティスト",
+ "AuthenticationSucceededWithUserName": "{0} 認証に成功しました",
+ "Books": "ブックス",
+ "CameraImageUploadedFrom": "新しいカメライメージが {0}からアップロードされました",
+ "Channels": "チャンネル",
+ "ChapterNameValue": "チャプター {0}",
+ "Collections": "コレクション",
+ "DeviceOfflineWithName": "{0} が切断されました",
+ "DeviceOnlineWithName": "{0} が接続されました",
+ "FailedLoginAttemptWithUserName": "ログインを試行しましたが {0}によって失敗しました",
+ "Favorites": "お気に入り",
+ "Folders": "フォルダー",
+ "Genres": "ジャンル",
+ "HeaderAlbumArtists": "アーティストのアルバム",
+ "HeaderContinueWatching": "視聴を続ける",
+ "HeaderFavoriteAlbums": "お気に入りのアルバム",
+ "HeaderFavoriteArtists": "お気に入りのアーティスト",
+ "HeaderFavoriteEpisodes": "お気に入りのエピソード",
+ "HeaderFavoriteShows": "お気に入りの番組",
+ "HeaderFavoriteSongs": "お気に入りの曲",
+ "HeaderLiveTV": "ライブTV",
+ "HeaderNextUp": "次",
+ "HeaderRecordingGroups": "レコーディンググループ",
+ "HomeVideos": "ホームビデオ",
+ "Inherit": "継承",
+ "ItemAddedWithName": "{0} をライブラリに追加しました",
+ "ItemRemovedWithName": "{0} をライブラリから削除しました",
+ "LabelIpAddressValue": "IPアドレス: {0}",
+ "LabelRunningTimeValue": "稼働時間: {0}",
+ "Latest": "最新",
+ "MessageApplicationUpdated": "Jellyfin Server が更新されました",
+ "MessageApplicationUpdatedTo": "Jellyfin Server が {0}に更新されました",
+ "MessageNamedServerConfigurationUpdatedWithValue": "サーバー設定項目の {0} が更新されました",
+ "MessageServerConfigurationUpdated": "サーバー設定が更新されました",
+ "MixedContent": "ミックスコンテンツ",
+ "Movies": "ムービー",
+ "Music": "ミュージック",
+ "MusicVideos": "ミュージックビデオ",
+ "NameInstallFailed": "{0}のインストールに失敗しました",
+ "NameSeasonNumber": "シーズン {0}",
+ "NameSeasonUnknown": "不明なシーズン",
+ "NewVersionIsAvailable": "新しいバージョンの Jellyfin Server がダウンロード可能です。",
+ "NotificationOptionApplicationUpdateAvailable": "アプリケーションの更新があります",
+ "NotificationOptionApplicationUpdateInstalled": "アプリケーションは最新です",
+ "NotificationOptionAudioPlayback": "オーディオの再生を開始",
+ "NotificationOptionAudioPlaybackStopped": "オーディオの再生をストップしました",
+ "NotificationOptionCameraImageUploaded": "カメライメージがアップロードされました",
+ "NotificationOptionInstallationFailed": "インストール失敗",
+ "NotificationOptionNewLibraryContent": "新しいコンテンツを追加しました",
+ "NotificationOptionPluginError": "プラグインに障害が発生しました",
+ "NotificationOptionPluginInstalled": "プラグインがインストールされました",
+ "NotificationOptionPluginUninstalled": "プラグインがアンインストールされました",
+ "NotificationOptionPluginUpdateInstalled": "プラグインのアップデートをインストールしました",
+ "NotificationOptionServerRestartRequired": "サーバーを再起動してください",
+ "NotificationOptionTaskFailed": "スケジュールされていたタスクの失敗",
+ "NotificationOptionUserLockedOut": "ユーザーはロックされています",
+ "NotificationOptionVideoPlayback": "ビデオの再生を開始しました",
+ "NotificationOptionVideoPlaybackStopped": "ビデオを停止しました",
+ "Photos": "フォト",
+ "Playlists": "プレイリスト",
+ "Plugin": "プラグイン",
+ "PluginInstalledWithName": "{0} がインストールされました",
+ "PluginUninstalledWithName": "{0} がアンインストールされました",
+ "PluginUpdatedWithName": "{0} が更新されました",
+ "ProviderValue": "プロバイダ: {0}",
+ "ScheduledTaskFailedWithName": "{0} が失敗しました",
+ "ScheduledTaskStartedWithName": "{0} が開始されました",
+ "ServerNameNeedsToBeRestarted": "{0} を再起動してください",
+ "Shows": "番組",
+ "Songs": "曲",
+ "StartupEmbyServerIsLoading": "Jellyfin Server は現在読み込み中です。しばらくしてからもう一度お試しください。",
+ "SubtitleDownloadFailureFromForItem": "{0} から {1}の字幕のダウンロードに失敗しました",
+ "Sync": "同期",
+ "System": "システム",
+ "TvShows": "テレビ番組",
+ "User": "ユーザー",
+ "UserCreatedWithName": "ユーザー {0} が作成されました",
+ "UserDeletedWithName": "User {0} を削除しました",
+ "UserDownloadingItemWithValues": "{0} が {1} をダウンロードしています",
+ "UserLockedOutWithName": "ユーザー {0} はロックされています",
+ "UserOfflineFromDevice": "{0} は {1} から切断しました",
+ "UserOnlineFromDevice": "{0} は {1} からオンラインになりました",
+ "UserPasswordChangedWithName": "ユーザー {0} のパスワードは変更されました",
+ "UserPolicyUpdatedWithName": "ユーザーポリシーが{0}に更新されました",
+ "UserStartedPlayingItemWithValues": "{0} は {2}で{1} を再生しています",
+ "UserStoppedPlayingItemWithValues": "{0} は{2}で{1} の再生が終わりました",
+ "ValueHasBeenAddedToLibrary": "{0}はあなたのメディアライブラリに追加されました",
+ "ValueSpecialEpisodeName": "スペシャル - {0}",
+ "VersionNumber": "バージョン {0}",
+ "TaskCleanLogsDescription": "{0} 日以上前のログを消去します。",
+ "TaskCleanLogs": "ログの掃除",
+ "TaskRefreshLibraryDescription": "メディアライブラリをスキャンして新しいファイルを探し、メタデータをリフレッシュします。",
+ "TaskRefreshLibrary": "メディアライブラリのスキャン",
+ "TaskCleanCacheDescription": "不要なキャッシュを消去します。",
+ "TaskCleanCache": "キャッシュを消去",
+ "TasksChannelsCategory": "ネットチャンネル",
+ "TasksApplicationCategory": "アプリケーション",
+ "TasksLibraryCategory": "ライブラリ",
+ "TasksMaintenanceCategory": "メンテナンス",
+ "TaskRefreshChannelsDescription": "ネットチャンネルの情報をリフレッシュします。",
+ "TaskRefreshChannels": "チャンネルのリフレッシュ",
+ "TaskCleanTranscodeDescription": "1日以上経過したトランスコードファイルを削除します。",
+ "TaskCleanTranscode": "トランスコードディレクトリの削除",
+ "TaskUpdatePluginsDescription": "自動更新可能なプラグインのアップデートをダウンロードしてインストールします。",
+ "TaskUpdatePlugins": "プラグインの更新",
+ "TaskRefreshPeopleDescription": "メディアライブラリで俳優や監督のメタデータを更新します。",
+ "TaskRefreshPeople": "俳優や監督のデータの更新",
+ "TaskDownloadMissingSubtitlesDescription": "メタデータ構成に基づいて、欠落している字幕をインターネットで検索します。",
+ "TaskRefreshChapterImagesDescription": "チャプターのあるビデオのサムネイルを作成します。",
+ "TaskRefreshChapterImages": "チャプター画像を抽出する",
+ "TaskDownloadMissingSubtitles": "不足している字幕をダウンロードする",
+ "TaskCleanActivityLogDescription": "設定された期間よりも古いアクティビティの履歴を削除します。",
+ "TaskCleanActivityLog": "アクティビティの履歴を消去",
+ "Undefined": "未定義",
+ "Forced": "強制",
+ "Default": "デフォルト",
+ "TaskOptimizeDatabaseDescription": "データベースをコンパクトにして、空き領域を切り詰めます。メディアライブラリのスキャン後でこのタスクを実行するとパフォーマンスが向上する可能性があります。",
+ "TaskOptimizeDatabase": "データベースの最適化"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json
index 658d168e9..d28564a7c 100644
--- a/Emby.Server.Implementations/Localization/Core/kk.json
+++ b/Emby.Server.Implementations/Localization/Core/kk.json
@@ -1,97 +1,124 @@
{
- "Albums": "Álbomdar",
- "AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}",
+ "Albums": "Älbomdar",
+ "AppDeviceValues": "Qoldanba: {0}, Qūrylğy: {1}",
"Application": "Qoldanba",
- "Artists": "Oryndaýshylar",
- "AuthenticationSucceededWithUserName": "{0} túpnusqalyǵyn rastalýy sátti",
- "Books": "Kitaptar",
- "CameraImageUploadedFrom": "Jańa sýret {0} kamerasynan júktep alyndy",
+ "Artists": "Oryndauşylar",
+ "AuthenticationSucceededWithUserName": "{0} tüpnūsqalyq rastaluy sättı aiaqtaldy",
+ "Books": "Kıtaptar",
+ "CameraImageUploadedFrom": "{0} kamerasynan jaña suret jüktep salyndy",
"Channels": "Arnalar",
"ChapterNameValue": "{0}-sahna",
- "Collections": "Jıyntyqtar",
- "DeviceOfflineWithName": "{0} ajyratylǵan",
- "DeviceOnlineWithName": "{0} qosylǵan",
- "FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz",
- "Favorites": "Tańdaýlylar",
+ "Collections": "Jiyntyqtar",
+ "DeviceOfflineWithName": "{0} ajyratylğan",
+ "DeviceOnlineWithName": "{0} qosylğan",
+ "FailedLoginAttemptWithUserName": "{0} tarapynan kıru äreketı sätsız aiaqtaldy",
+ "Favorites": "Tañdaulylar",
"Folders": "Qaltalar",
"Genres": "Janrlar",
- "HeaderAlbumArtists": "Álbom oryndaýshylary",
- "HeaderCameraUploads": "Kameradan júktelgender",
- "HeaderContinueWatching": "Qaraýdy jalǵastyrý",
- "HeaderFavoriteAlbums": "Tańdaýly álbomdar",
- "HeaderFavoriteArtists": "Tańdaýly oryndaýshylar",
- "HeaderFavoriteEpisodes": "Tańdaýly bólimder",
- "HeaderFavoriteShows": "Tańdaýly kórsetimder",
- "HeaderFavoriteSongs": "Tańdaýly áýender",
- "HeaderLiveTV": "Efır",
- "HeaderNextUp": "Kezekti",
+ "HeaderAlbumArtists": "Oryndauşynyñ älbomy",
+ "HeaderContinueWatching": "Qaraudy jalğastyru",
+ "HeaderFavoriteAlbums": "Tañdauly älbomdar",
+ "HeaderFavoriteArtists": "Tañdauly oryndauşylar",
+ "HeaderFavoriteEpisodes": "Tañdauly telebölımder",
+ "HeaderFavoriteShows": "Tañdauly körsetımder",
+ "HeaderFavoriteSongs": "Tañdauly äuender",
+ "HeaderLiveTV": "Efir",
+ "HeaderNextUp": "Kezektı",
"HeaderRecordingGroups": "Jazba toptary",
- "HomeVideos": "Úılik beıneler",
- "Inherit": "Muraǵa ıelený",
- "ItemAddedWithName": "{0} tasyǵyshhanaǵa ústelindi",
- "ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy",
- "LabelIpAddressValue": "IP-mekenjaıy: {0}",
- "LabelRunningTimeValue": "Oınatý ýaqyty: {0}",
- "Latest": "Eń keıingi",
- "MessageApplicationUpdated": "Jellyfin Serveri jańartyldy",
- "MessageApplicationUpdatedTo": "Jellyfin Serveri {0} deńgeıge jańartyldy",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server teńsheliminiń {0} bólimi jańartyldy",
- "MessageServerConfigurationUpdated": "Server teńshelimi jańartyldy",
- "MixedContent": "Aralas mazmun",
- "Movies": "Fılmder",
- "Music": "Mýzyka",
- "MusicVideos": "Mýzykalyq beıneler",
- "NameInstallFailed": "{0} ornatylýy sátsiz",
- "NameSeasonNumber": "{0}-maýsym",
- "NameSeasonUnknown": "Belgisiz maýsym",
- "NewVersionIsAvailable": "Jańa Jellyfin Server nusqasy júktep alýǵa qoljetimdi.",
- "NotificationOptionApplicationUpdateAvailable": "Qoldanba jańartýy qoljetimdi",
- "NotificationOptionApplicationUpdateInstalled": "Qoldanba jańartýy ornatyldy",
- "NotificationOptionAudioPlayback": "Dybys oınatýy bastaldy",
- "NotificationOptionAudioPlaybackStopped": "Dybys oınatýy toqtatyldy",
- "NotificationOptionCameraImageUploaded": "Kameradan fotosýret keri qotarylǵan",
- "NotificationOptionInstallationFailed": "Ornatý sátsizdigi",
- "NotificationOptionNewLibraryContent": "Jańa mazmun ústelgen",
- "NotificationOptionPluginError": "Plagın sátsizdigi",
- "NotificationOptionPluginInstalled": "Plagın ornatyldy",
- "NotificationOptionPluginUninstalled": "Plagın ornatýy boldyrylmady",
- "NotificationOptionPluginUpdateInstalled": "Plagın jańartýy ornatyldy",
- "NotificationOptionServerRestartRequired": "Serverdi qaıta iske qosý qajet",
- "NotificationOptionTaskFailed": "Josparlaǵan tapsyrma sátsizdigi",
- "NotificationOptionUserLockedOut": "Paıdalanýshy qursaýly",
- "NotificationOptionVideoPlayback": "Beıne oınatýy bastaldy",
- "NotificationOptionVideoPlaybackStopped": "Beıne oınatýy toqtatyldy",
- "Photos": "Fotosýretter",
- "Playlists": "Oınatý tizimderi",
- "Plugin": "Plagın",
+ "HomeVideos": "Üilık beineler",
+ "Inherit": "İelenu",
+ "ItemAddedWithName": "{0} tasyğyşhanağa üstelindı",
+ "ItemRemovedWithName": "{0} tasyğyşhanadan alastaldy",
+ "LabelIpAddressValue": "IP-mekenjaiy: {0}",
+ "LabelRunningTimeValue": "Oinatu uaqyty: {0}",
+ "Latest": "Eñ keiıngı",
+ "MessageApplicationUpdated": "Jellyfin Serverı jañartyldy",
+ "MessageApplicationUpdatedTo": "Jellyfin Serverı {0} nūsqasyna jañartyldy",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Server teñşelımderınıñ {0} bölımı jañartyldy",
+ "MessageServerConfigurationUpdated": "Server teñşelımderı jañartyldy",
+ "MixedContent": "Aralas mazmūn",
+ "Movies": "Filmder",
+ "Music": "Muzyka",
+ "MusicVideos": "Muzykalyq beineler",
+ "NameInstallFailed": "{0} ornatyluy sätsız",
+ "NameSeasonNumber": "{0}-mausym",
+ "NameSeasonUnknown": "Belgısız mausym",
+ "NewVersionIsAvailable": "Jaña Jellyfin Server nūsqasy jüktep aluğa qoljetımdı.",
+ "NotificationOptionApplicationUpdateAvailable": "Qoldanba jañartuy qoljetımdı",
+ "NotificationOptionApplicationUpdateInstalled": "Qoldanba jañartuy ornatyldy",
+ "NotificationOptionAudioPlayback": "Dybys oinatuy bastaldy",
+ "NotificationOptionAudioPlaybackStopped": "Dybys oinatuy toqtatyldy",
+ "NotificationOptionCameraImageUploaded": "Kameradan fotosuret jüktep salynğan",
+ "NotificationOptionInstallationFailed": "Ornatu sätsızdıgı",
+ "NotificationOptionNewLibraryContent": "Jaña mazmūn üstelıngen",
+ "NotificationOptionPluginError": "Plagin sätsızdıgı",
+ "NotificationOptionPluginInstalled": "Plagin ornatyldy",
+ "NotificationOptionPluginUninstalled": "Plagin ornatuy boldyrylmady",
+ "NotificationOptionPluginUpdateInstalled": "Plagin jañartuy ornatyldy",
+ "NotificationOptionServerRestartRequired": "Serverdı qaita ıske qosu qajet",
+ "NotificationOptionTaskFailed": "Josparlağan tapsyrma sätsızdıgı",
+ "NotificationOptionUserLockedOut": "Paidalanuşy qūrsauly",
+ "NotificationOptionVideoPlayback": "Beine oinatuy bastaldy",
+ "NotificationOptionVideoPlaybackStopped": "Beine oinatuy toqtatyldy",
+ "Photos": "Fotosuretter",
+ "Playlists": "Oinatu tızımderı",
+ "Plugin": "Plagin",
"PluginInstalledWithName": "{0} ornatyldy",
- "PluginUninstalledWithName": "{0} joıyldy",
- "PluginUpdatedWithName": "{0} jańartyldy",
- "ProviderValue": "Jetkizýshi: {0}",
- "ScheduledTaskFailedWithName": "{0} sátsiz",
- "ScheduledTaskStartedWithName": "{0} iske qosyldy",
- "ServerNameNeedsToBeRestarted": "{0} qaıta iske qosý qajet",
- "Shows": "Kórsetimder",
- "Songs": "Áýender",
- "StartupEmbyServerIsLoading": "Jellyfin Server júktelýde. Áreketti kóp uzamaı qaıtalańyz.",
+ "PluginUninstalledWithName": "{0} joiyldy",
+ "PluginUpdatedWithName": "{0} jañartyldy",
+ "ProviderValue": "Jetkızuşı: {0}",
+ "ScheduledTaskFailedWithName": "{0} sätsız",
+ "ScheduledTaskStartedWithName": "{0} ıske qosyldy",
+ "ServerNameNeedsToBeRestarted": "{0} qaita ıske qosu qajet",
+ "Shows": "Körsetımder",
+ "Songs": "Äuender",
+ "StartupEmbyServerIsLoading": "Jellyfin Server jüktelude. Ärekettı köp ūzamai qaitalañyz.",
"SubtitleDownloadFailureForItem": "Субтитрлер {0} үшін жүктеліп алынуы сәтсіз",
- "SubtitleDownloadFailureFromForItem": "{1} úshin sýbtıtrlerdi {0} kózinen júktep alý sátsiz",
- "SubtitlesDownloadedForItem": "{0} úshin sýbtıtrler júktelip alyndy",
- "Sync": "Úndestirý",
- "System": "Júıe",
- "TvShows": "TD-kórsetimder",
- "User": "Paıdalanýshy",
- "UserCreatedWithName": "Paıdalanýshy {0} jasalǵan",
- "UserDeletedWithName": "Paıdalanýshy {0} joıylǵan",
- "UserDownloadingItemWithValues": "{0} mynany júktep alýda: {1}",
- "UserLockedOutWithName": "Paıdalanýshy {0} qursaýly",
- "UserOfflineFromDevice": "{0} - {1} tarapynan ajyratylǵan",
- "UserOnlineFromDevice": "{0} - {1} arqyly qosylǵan",
- "UserPasswordChangedWithName": "Paıdalanýshy {0} úshin paról ózgertildi",
- "UserPolicyUpdatedWithName": "Paıdalanýshy {0} úshin saıasattary jańartyldy",
- "UserStartedPlayingItemWithValues": "{0} - {1} oınatýyn {2} bastady",
- "UserStoppedPlayingItemWithValues": "{0} - {1} oınatýyn {2} toqtatty",
- "ValueHasBeenAddedToLibrary": "{0} (tasyǵyshhanaǵa ústelindi)",
- "ValueSpecialEpisodeName": "Arnaıy - {0}",
- "VersionNumber": "Nusqasy {0}"
+ "SubtitleDownloadFailureFromForItem": "{1} üşın subtitrlerdı {0} közınen jüktep alu sätsız",
+ "Sync": "Ündestıru",
+ "System": "Jüie",
+ "TvShows": "TD-körsetımder",
+ "User": "Paidalanuşy",
+ "UserCreatedWithName": "Paidalanuşy {0} jasalğan",
+ "UserDeletedWithName": "Paidalanuşy {0} joiylğan",
+ "UserDownloadingItemWithValues": "{0} — {1} jüktep aluda",
+ "UserLockedOutWithName": "Paidalanuşy {0} qūrsaulanğan",
+ "UserOfflineFromDevice": "{0} — {1} tarapynan ajyratyldy",
+ "UserOnlineFromDevice": "{0} — {1} tarapynan qosyldy",
+ "UserPasswordChangedWithName": "Paidalanuşy {0} üşın paröl özgertıldı",
+ "UserPolicyUpdatedWithName": "Paidalanuşy {0} üşın saiasattary jañartyldy",
+ "UserStartedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuda",
+ "UserStoppedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuyn toqtatty",
+ "ValueHasBeenAddedToLibrary": "{0} tasyğyşhanağa üstelındı",
+ "ValueSpecialEpisodeName": "Arnaiy - {0}",
+ "VersionNumber": "Nūsqasy {0}",
+ "Default": "Ädepkı",
+ "TaskDownloadMissingSubtitles": "Joq subtitrlerdı jüktep alu",
+ "TaskRefreshChannels": "Arnalardy jañğyrtu",
+ "TaskCleanTranscode": "Qaita kodtau katalogyn tazalau",
+ "TaskUpdatePlugins": "Plaginderdı jañartu",
+ "TaskRefreshPeople": "Adamdardy jañğyrtu",
+ "TaskCleanLogs": "Jūrnal katalogyn tazalau",
+ "TaskRefreshLibrary": "Tasyğyşhanany skanerleu",
+ "TaskRefreshChapterImages": "Sahna suretterın şyğaryp alu",
+ "TaskCleanCache": "Keş katalogyn tazalau",
+ "TaskCleanActivityLog": "Äreket jūrnalyn tazalau",
+ "TasksChannelsCategory": "Internet-arnalar",
+ "TasksApplicationCategory": "Qoldanba",
+ "TasksLibraryCategory": "Tasyğyşhana",
+ "TasksMaintenanceCategory": "Qyzmet körsetu",
+ "Undefined": "Anyqtalmağan",
+ "Forced": "Mäjbürlı",
+ "TaskDownloadMissingSubtitlesDescription": "Metaderekter teñşelımderı negızınde joq subtitrlerdı İnternetten ızdeidı.",
+ "TaskRefreshChannelsDescription": "Internet-arnalar mälımetterın jañğyrtady.",
+ "TaskCleanTranscodeDescription": "Bіr künnen asqan qaita kodtau faildaryn joiady.",
+ "TaskUpdatePluginsDescription": "Avtomatty türde jañartuğa teñşelgen plaginder üşın jañartulardy jüktep alady jäne ornatady.",
+ "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterın jañartady.",
+ "TaskCleanLogsDescription": "{0} künnen asqan jūrnal faildaryn joiady.",
+ "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaña faildardy skanerleidі jäne metaderekterdı jañğyrtady.",
+ "TaskRefreshChapterImagesDescription": "Sahnalary bar beineler üşın nobailar jasaidy.",
+ "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.",
+ "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teñşelgen jasynan asqan jazbalary joiady.",
+ "TaskOptimizeDatabaseDescription": "Derekqordy qysyp, bos oryndy qysqartady. Būl tapsyrmany tasyğyşhanany skanerlegennen keiın nemese derekqorğa meñzeitın basqa özgertuler ıstelgennen keiın oryndau önımdılıktı damytuy mümkın.",
+ "TaskOptimizeDatabase": "Derekqordy oñtailandyru"
}
diff --git a/Emby.Server.Implementations/Localization/Core/ko.json b/Emby.Server.Implementations/Localization/Core/ko.json
index 21808fd18..a37de0748 100644
--- a/Emby.Server.Implementations/Localization/Core/ko.json
+++ b/Emby.Server.Implementations/Localization/Core/ko.json
@@ -1,97 +1,124 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "앨범 아티스트",
- "HeaderCameraUploads": "Camera Uploads",
+ "Albums": "앨범",
+ "AppDeviceValues": "앱: {0}, 장치: {1}",
+ "Application": "애플리케이션",
+ "Artists": "아티스트",
+ "AuthenticationSucceededWithUserName": "{0}이 성공적으로 인증됨",
+ "Books": "도서",
+ "CameraImageUploadedFrom": "{0}에서 새로운 카메라 이미지가 업로드됨",
+ "Channels": "채널",
+ "ChapterNameValue": "챕터 {0}",
+ "Collections": "컬렉션",
+ "DeviceOfflineWithName": "{0}의 연결 끊김",
+ "DeviceOnlineWithName": "{0}이 연결됨",
+ "FailedLoginAttemptWithUserName": "{0}에서 로그인 실패",
+ "Favorites": "즐겨찾기",
+ "Folders": "폴더",
+ "Genres": "장르",
+ "HeaderAlbumArtists": "아티스트의 앨범",
"HeaderContinueWatching": "계속 시청하기",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
+ "HeaderFavoriteAlbums": "즐겨찾는 앨범",
+ "HeaderFavoriteArtists": "즐겨찾는 아티스트",
+ "HeaderFavoriteEpisodes": "즐겨찾는 에피소드",
"HeaderFavoriteShows": "즐겨찾는 쇼",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin 서버를 불러오고 있습니다. 잠시후 다시시도 해주세요.",
+ "HeaderFavoriteSongs": "즐겨찾는 노래",
+ "HeaderLiveTV": "실시간 TV",
+ "HeaderNextUp": "다음으로",
+ "HeaderRecordingGroups": "녹화 그룹",
+ "HomeVideos": "홈 비디오",
+ "Inherit": "상속",
+ "ItemAddedWithName": "{0}가 라이브러리에 추가되었습니다",
+ "ItemRemovedWithName": "{0}가 라이브러리에서 제거됨",
+ "LabelIpAddressValue": "IP 주소: {0}",
+ "LabelRunningTimeValue": "상영 시간: {0}",
+ "Latest": "최근",
+ "MessageApplicationUpdated": "Jellyfin 서버가 업데이트되었습니다",
+ "MessageApplicationUpdatedTo": "Jellyfin 서버가 {0}로 업데이트되었습니다",
+ "MessageNamedServerConfigurationUpdatedWithValue": "서버 환경 설정 {0} 섹션이 업데이트되었습니다",
+ "MessageServerConfigurationUpdated": "서버 환경 설정이 업데이트되었습니다",
+ "MixedContent": "혼합 콘텐츠",
+ "Movies": "영화",
+ "Music": "음악",
+ "MusicVideos": "뮤직비디오",
+ "NameInstallFailed": "{0} 설치 실패",
+ "NameSeasonNumber": "시즌 {0}",
+ "NameSeasonUnknown": "알 수 없는 시즌",
+ "NewVersionIsAvailable": "새로운 버전의 Jellyfin 서버를 사용할 수 있습니다.",
+ "NotificationOptionApplicationUpdateAvailable": "애플리케이션 업데이트 가능",
+ "NotificationOptionApplicationUpdateInstalled": "애플리케이션 업데이트 완료",
+ "NotificationOptionAudioPlayback": "오디오 재생 시작됨",
+ "NotificationOptionAudioPlaybackStopped": "오디오 재생 중지됨",
+ "NotificationOptionCameraImageUploaded": "카메라 이미지가 업로드됨",
+ "NotificationOptionInstallationFailed": "설치 실패",
+ "NotificationOptionNewLibraryContent": "새 콘텐츠가 추가됨",
+ "NotificationOptionPluginError": "플러그인 실패",
+ "NotificationOptionPluginInstalled": "플러그인 설치됨",
+ "NotificationOptionPluginUninstalled": "플러그인 제거됨",
+ "NotificationOptionPluginUpdateInstalled": "플러그인 업데이트 완료",
+ "NotificationOptionServerRestartRequired": "서버 재시작 필요",
+ "NotificationOptionTaskFailed": "예약 작업 실패",
+ "NotificationOptionUserLockedOut": "잠긴 사용자",
+ "NotificationOptionVideoPlayback": "비디오 재생 시작됨",
+ "NotificationOptionVideoPlaybackStopped": "비디오 재생 중지됨",
+ "Photos": "사진",
+ "Playlists": "재생목록",
+ "Plugin": "플러그인",
+ "PluginInstalledWithName": "{0} 설치됨",
+ "PluginUninstalledWithName": "{0} 제거됨",
+ "PluginUpdatedWithName": "{0} 업데이트됨",
+ "ProviderValue": "제공자: {0}",
+ "ScheduledTaskFailedWithName": "{0} 실패",
+ "ScheduledTaskStartedWithName": "{0} 시작",
+ "ServerNameNeedsToBeRestarted": "{0}를 재시작해야합니다",
+ "Shows": "쇼",
+ "Songs": "노래",
+ "StartupEmbyServerIsLoading": "Jellyfin 서버를 불러오고 있습니다. 잠시 후에 다시 시도하십시오.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "SubtitleDownloadFailureFromForItem": "{0}에서 {1} 자막 다운로드에 실패했습니다",
+ "Sync": "동기화",
+ "System": "시스템",
+ "TvShows": "TV 쇼",
+ "User": "사용자",
+ "UserCreatedWithName": "사용자 {0} 생성됨",
+ "UserDeletedWithName": "사용자 {0} 삭제됨",
+ "UserDownloadingItemWithValues": "{0}이(가) {1}을 다운로드 중입니다",
+ "UserLockedOutWithName": "유저 {0} 은(는) 잠금처리 되었습니다",
+ "UserOfflineFromDevice": "{1}에서 {0}의 연결이 끊킴",
+ "UserOnlineFromDevice": "{0}이 {1}으로 접속",
+ "UserPasswordChangedWithName": "사용자 {0}의 비밀번호가 변경되었습니다",
+ "UserPolicyUpdatedWithName": "{0}의 사용자 정책이 업데이트되었습니다",
+ "UserStartedPlayingItemWithValues": "{2}에서 {0}이 {1} 재생 중",
+ "UserStoppedPlayingItemWithValues": "{2}에서 {0}이 {1} 재생을 마침",
+ "ValueHasBeenAddedToLibrary": "{0}가 미디어 라이브러리에 추가되었습니다",
+ "ValueSpecialEpisodeName": "스페셜 - {0}",
+ "VersionNumber": "버전 {0}",
+ "TasksApplicationCategory": "어플리케이션",
+ "TasksMaintenanceCategory": "유지 보수",
+ "TaskDownloadMissingSubtitlesDescription": "메타 데이터 기반으로 누락 된 자막이 있는지 인터넷을 검색합니다.",
+ "TaskDownloadMissingSubtitles": "누락 된 자막 다운로드",
+ "TaskRefreshChannelsDescription": "인터넷 채널 정보를 새로 고칩니다.",
+ "TaskRefreshChannels": "채널 새로고침",
+ "TaskCleanTranscodeDescription": "하루 이상 지난 트랜스 코드 파일을 삭제합니다.",
+ "TaskCleanTranscode": "트랜스코드 폴더 청소",
+ "TaskUpdatePluginsDescription": "자동으로 업데이트되도록 구성된 플러그인 업데이트를 다운로드하여 설치합니다.",
+ "TaskUpdatePlugins": "플러그인 업데이트",
+ "TaskRefreshPeopleDescription": "미디어 라이브러리에서 배우 및 감독의 메타 데이터를 업데이트합니다.",
+ "TaskRefreshPeople": "인물 새로고침",
+ "TaskCleanLogsDescription": "{0} 일이 지난 로그 파일을 삭제합니다.",
+ "TaskCleanLogs": "로그 폴더 청소",
+ "TaskRefreshLibraryDescription": "미디어 라이브러리에서 새 파일을 검색하고 메타 데이터를 새로 고칩니다.",
+ "TaskRefreshLibrary": "미디어 라이브러리 스캔",
+ "TaskRefreshChapterImagesDescription": "챕터가있는 비디오의 썸네일을 만듭니다.",
+ "TaskRefreshChapterImages": "챕터 이미지 추출",
+ "TaskCleanCacheDescription": "시스템에서 더 이상 필요하지 않은 캐시 파일을 삭제합니다.",
+ "TaskCleanCache": "캐시 폴더 청소",
+ "TasksChannelsCategory": "인터넷 채널",
+ "TasksLibraryCategory": "라이브러리",
+ "TaskCleanActivityLogDescription": "구성된 기간보다 오래된 활동내역 삭제.",
+ "TaskCleanActivityLog": "활동내역청소",
+ "Undefined": "일치하지 않음",
+ "Forced": "강제하기",
+ "Default": "기본 설정",
+ "TaskOptimizeDatabaseDescription": "데이터베이스를 압축하고 사용 가능한 공간을 늘립니다. 라이브러리를 검색한 후 이 작업을 실행하거나 데이터베이스 수정같은 비슷한 작업을 수행하면 성능이 향상될 수 있습니다.",
+ "TaskOptimizeDatabase": "데이터베이스 최적화"
}
diff --git a/Emby.Server.Implementations/Localization/Core/lt-LT.json b/Emby.Server.Implementations/Localization/Core/lt-LT.json
index 558904f06..f3a131d40 100644
--- a/Emby.Server.Implementations/Localization/Core/lt-LT.json
+++ b/Emby.Server.Implementations/Localization/Core/lt-LT.json
@@ -1,97 +1,122 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
+ "Albums": "Albumai",
+ "AppDeviceValues": "Programa: {0}, Įrenginys: {1}",
+ "Application": "Programa",
+ "Artists": "Atlikėjai",
+ "AuthenticationSucceededWithUserName": "{0} sėkmingai autentifikuota",
+ "Books": "Knygos",
+ "CameraImageUploadedFrom": "Nauja nuotrauka įkelta iš kameros {0}",
+ "Channels": "Kanalai",
+ "ChapterNameValue": "Scena{0}",
+ "Collections": "Kolekcijos",
+ "DeviceOfflineWithName": "{0} buvo atjungtas",
+ "DeviceOnlineWithName": "{0} prisijungęs",
+ "FailedLoginAttemptWithUserName": "{0} - nesėkmingas bandymas prisijungti",
+ "Favorites": "Mėgstami",
+ "Folders": "Katalogai",
"Genres": "Žanrai",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
+ "HeaderAlbumArtists": "Albumo atlikėjai",
"HeaderContinueWatching": "Žiūrėti toliau",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
+ "HeaderFavoriteAlbums": "Mėgstami Albumai",
+ "HeaderFavoriteArtists": "Mėgstami Atlikėjai",
+ "HeaderFavoriteEpisodes": "Mėgstamiausios serijos",
+ "HeaderFavoriteShows": "Mėgstamiausi serialai",
+ "HeaderFavoriteSongs": "Mėgstamos dainos",
+ "HeaderLiveTV": "TV gyvai",
+ "HeaderNextUp": "Toliau eilėje",
+ "HeaderRecordingGroups": "Įrašų grupės",
+ "HomeVideos": "Namų vaizdo įrašai",
+ "Inherit": "Paveldėti",
+ "ItemAddedWithName": "{0} - buvo įkeltas į mediateką",
+ "ItemRemovedWithName": "{0} - buvo pašalinta iš mediatekos",
+ "LabelIpAddressValue": "IP adresas: {0}",
+ "LabelRunningTimeValue": "Trukmė: {0}",
+ "Latest": "Naujausi",
+ "MessageApplicationUpdated": "\"Jellyfin Server\" atnaujintas",
+ "MessageApplicationUpdatedTo": "\"Jellyfin Server\" buvo atnaujinta iki {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Serverio nustatymai (skyrius {0}) buvo atnaujinti",
+ "MessageServerConfigurationUpdated": "Serverio nustatymai buvo atnaujinti",
"MixedContent": "Mixed content",
"Movies": "Filmai",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
+ "Music": "Muzika",
+ "MusicVideos": "Muzikiniai klipai",
+ "NameInstallFailed": "{0} diegimo klaida",
+ "NameSeasonNumber": "Sezonas {0}",
+ "NameSeasonUnknown": "Sezonas neatpažintas",
+ "NewVersionIsAvailable": "Nauja \"Jellyfin Server\" versija yra prieinama atsisiuntimui.",
+ "NotificationOptionApplicationUpdateAvailable": "Galimi programos atnaujinimai",
+ "NotificationOptionApplicationUpdateInstalled": "Programos atnaujinimai įdiegti",
+ "NotificationOptionAudioPlayback": "Garso atkūrimas pradėtas",
+ "NotificationOptionAudioPlaybackStopped": "Garso atkūrimas sustabdytas",
+ "NotificationOptionCameraImageUploaded": "Kameros vaizdai įkelti",
+ "NotificationOptionInstallationFailed": "Diegimo klaida",
+ "NotificationOptionNewLibraryContent": "Naujas turinys įkeltas",
+ "NotificationOptionPluginError": "Įskiepio klaida",
+ "NotificationOptionPluginInstalled": "Įskiepis įdiegtas",
+ "NotificationOptionPluginUninstalled": "Įskiepis pašalintas",
+ "NotificationOptionPluginUpdateInstalled": "Įskiepio atnaujinimas įdiegtas",
+ "NotificationOptionServerRestartRequired": "Reikalingas serverio perleidimas",
+ "NotificationOptionTaskFailed": "Suplanuotos užduoties klaida",
+ "NotificationOptionUserLockedOut": "Vartotojas užblokuotas",
+ "NotificationOptionVideoPlayback": "Vaizdo įrašo atkūrimas pradėtas",
+ "NotificationOptionVideoPlaybackStopped": "Vaizdo įrašo atkūrimas sustabdytas",
+ "Photos": "Nuotraukos",
+ "Playlists": "Grojaraštis",
"Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
+ "PluginInstalledWithName": "{0} buvo įdiegtas",
+ "PluginUninstalledWithName": "{0} buvo pašalintas",
+ "PluginUpdatedWithName": "{0} buvo atnaujintas",
"ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "ScheduledTaskFailedWithName": "{0} klaida",
+ "ScheduledTaskStartedWithName": "{0} paleista",
+ "ServerNameNeedsToBeRestarted": "{0} reikia iš naujo paleisti",
+ "Shows": "Laidos",
+ "Songs": "Kūriniai",
+ "StartupEmbyServerIsLoading": "Jellyfin Server kraunasi. Netrukus pabandykite dar kartą.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
+ "SubtitleDownloadFailureFromForItem": "{1} subtitrai buvo nesėkmingai parsiųsti iš {0}",
"Sync": "Sinchronizuoti",
"System": "System",
- "TvShows": "TV Shows",
+ "TvShows": "TV Serialai",
"User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserCreatedWithName": "Vartotojas {0} buvo sukurtas",
+ "UserDeletedWithName": "Vartotojas {0} ištrintas",
+ "UserDownloadingItemWithValues": "{0} siunčiasi {1}",
+ "UserLockedOutWithName": "Vartotojas {0} užblokuotas",
+ "UserOfflineFromDevice": "{0} buvo atjungtas nuo {1}",
+ "UserOnlineFromDevice": "{0} prisijungęs iš {1}",
+ "UserPasswordChangedWithName": "Slaptažodis pakeistas vartotojui {0}",
+ "UserPolicyUpdatedWithName": "Vartotojo {0} teisės buvo pakeistos",
+ "UserStartedPlayingItemWithValues": "{0} leidžia {1} į {2}",
+ "UserStoppedPlayingItemWithValues": "{0} baigė leisti {1} į {2}",
+ "ValueHasBeenAddedToLibrary": "{0} pridėtas į mediateką",
"ValueSpecialEpisodeName": "Ypatinga - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskUpdatePluginsDescription": "Atsisiųsti ir įdiegti atnaujinimus priedams kuriem yra nustatytas automatiškas atnaujinimas.",
+ "TaskUpdatePlugins": "Atnaujinti Priedus",
+ "TaskDownloadMissingSubtitlesDescription": "Ieško internete trūkstamų subtitrų remiantis metaduomenų konfigūracija.",
+ "TaskCleanTranscodeDescription": "Ištrina dienos senumo perkodavimo failus.",
+ "TaskCleanTranscode": "Išvalyti Perkodavimo Direktorija",
+ "TaskRefreshLibraryDescription": "Ieškoti naujų failų jūsų mediatekoje ir atnaujina metaduomenis.",
+ "TaskRefreshLibrary": "Skenuoti Mediateka",
+ "TaskDownloadMissingSubtitles": "Atsisiųsti trūkstamus subtitrus",
+ "TaskRefreshChannelsDescription": "Atnaujina internetinių kanalų informacija.",
+ "TaskRefreshChannels": "Atnaujinti Kanalus",
+ "TaskRefreshPeopleDescription": "Atnaujina metaduomenis apie aktorius ir režisierius jūsų mediatekoje.",
+ "TaskRefreshPeople": "Atnaujinti Žmones",
+ "TaskCleanLogsDescription": "Ištrina žurnalo failus kurie yra senesni nei {0} dienos.",
+ "TaskCleanLogs": "Išvalyti Žurnalą",
+ "TaskRefreshChapterImagesDescription": "Sukuria miniatiūras vaizdo įrašam, kurie turi scenas.",
+ "TaskRefreshChapterImages": "Ištraukti Scenų Paveikslus",
+ "TaskCleanCache": "Išvalyti Talpyklą",
+ "TaskCleanCacheDescription": "Ištrina talpyklos failus, kurių daugiau nereikia sistemai.",
+ "TasksChannelsCategory": "Internetiniai Kanalai",
+ "TasksApplicationCategory": "Programa",
+ "TasksLibraryCategory": "Mediateka",
+ "TasksMaintenanceCategory": "Priežiūra",
+ "TaskCleanActivityLog": "Išvalyti veiklos žurnalą",
+ "Undefined": "Neapibrėžtas",
+ "Forced": "Priverstas",
+ "Default": "Numatytas",
+ "TaskCleanActivityLogDescription": "Ištrina veiklos žuranlo įrašus, kurie yra senesni nei nustatytas amžius."
}
diff --git a/Emby.Server.Implementations/Localization/Core/lv.json b/Emby.Server.Implementations/Localization/Core/lv.json
new file mode 100644
index 000000000..443a74a10
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/lv.json
@@ -0,0 +1,123 @@
+{
+ "ServerNameNeedsToBeRestarted": "{0} ir vajadzīgs restarts",
+ "NotificationOptionTaskFailed": "Plānota uzdevuma kļūme",
+ "HeaderRecordingGroups": "Ierakstu Grupas",
+ "UserPolicyUpdatedWithName": "Lietotāju politika atjaunota priekš {0}",
+ "SubtitleDownloadFailureFromForItem": "Subtitru lejupielāde no {0} priekš {1} neizdevās",
+ "NotificationOptionVideoPlaybackStopped": "Video atskaņošana apturēta",
+ "NotificationOptionVideoPlayback": "Video atskaņošana sākta",
+ "NotificationOptionInstallationFailed": "Instalācija neizdevās",
+ "AuthenticationSucceededWithUserName": "{0} veiksmīgi autentificējies",
+ "ValueSpecialEpisodeName": "Speciālais - {0}",
+ "ScheduledTaskStartedWithName": "{0} iesākts",
+ "ScheduledTaskFailedWithName": "{0} neizdevās",
+ "Photos": "Attēli",
+ "NotificationOptionUserLockedOut": "Lietotājs bloķēts",
+ "LabelRunningTimeValue": "Garums: {0}",
+ "Inherit": "Mantot",
+ "AppDeviceValues": "Lietotne: {0}, Ierīce: {1}",
+ "VersionNumber": "Versija {0}",
+ "ValueHasBeenAddedToLibrary": "{0} ir ticis pievienots jūsu multvides bibliotēkai",
+ "UserStoppedPlayingItemWithValues": "{0} ir beidzis atskaņot {1} uz {2}",
+ "UserStartedPlayingItemWithValues": "{0} atskaņo {1} uz {2}",
+ "UserPasswordChangedWithName": "Parole nomainīta lietotājam {0}",
+ "UserOnlineFromDevice": "{0} ir tiešsaistē no {1}",
+ "UserOfflineFromDevice": "{0} ir atvienojies no {1}",
+ "UserLockedOutWithName": "Lietotājs {0} ir ticis bloķēts",
+ "UserDownloadingItemWithValues": "{0} lejupielādē {1}",
+ "UserDeletedWithName": "Lietotājs {0} ir izdzēsts",
+ "UserCreatedWithName": "Lietotājs {0} ir ticis izveidots",
+ "User": "Lietotājs",
+ "TvShows": "TV Raidījumi",
+ "Sync": "Sinhronizācija",
+ "System": "Sistēma",
+ "StartupEmbyServerIsLoading": "Jellyfin Serveris lādējas. Lūdzu mēģiniet vēlreiz pēc brīža.",
+ "Songs": "Dziesmas",
+ "Shows": "Raidījumi",
+ "PluginUpdatedWithName": "{0} tika atjaunots",
+ "PluginUninstalledWithName": "{0} tika noņemts",
+ "PluginInstalledWithName": "{0} tika uzstādīts",
+ "Plugin": "Paplašinājums",
+ "Playlists": "Atskaņošanas Saraksti",
+ "MixedContent": "Jaukts saturs",
+ "HomeVideos": "Mājas Video",
+ "HeaderNextUp": "Nākamais",
+ "ChapterNameValue": "Nodaļa {0}",
+ "Application": "Lietotne",
+ "NotificationOptionServerRestartRequired": "Vajadzīgs servera restarts",
+ "NotificationOptionPluginUpdateInstalled": "Paplašinājuma atjauninājums uzstādīts",
+ "NotificationOptionPluginUninstalled": "Paplašinājums noņemts",
+ "NotificationOptionPluginInstalled": "Paplašinājums uzstādīts",
+ "NotificationOptionPluginError": "Paplašinājuma kļūda",
+ "NotificationOptionNewLibraryContent": "Jauns saturs pievienots",
+ "NotificationOptionCameraImageUploaded": "Kameras attēls augšupielādēts",
+ "NotificationOptionAudioPlaybackStopped": "Audio atskaņošana apturēta",
+ "NotificationOptionAudioPlayback": "Audio atskaņošana sākta",
+ "NotificationOptionApplicationUpdateInstalled": "Lietotnes atjauninājums uzstādīts",
+ "NotificationOptionApplicationUpdateAvailable": "Lietotnes atjauninājums pieejams",
+ "NewVersionIsAvailable": "Lejupielādei ir pieejama jauna Jellyfin Server versija.",
+ "NameSeasonUnknown": "Nezināma Sezona",
+ "NameSeasonNumber": "Sezona {0}",
+ "NameInstallFailed": "{0} instalācija neizdevās",
+ "MusicVideos": "Mūzikas video",
+ "Music": "Mūzika",
+ "Movies": "Filmas",
+ "MessageServerConfigurationUpdated": "Servera konfigurācija ir tikusi atjaunota",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Servera konfigurācijas sadaļa {0} ir tikusi atjaunota",
+ "MessageApplicationUpdatedTo": "Jellyfin Server ir ticis atjaunots uz {0}",
+ "MessageApplicationUpdated": "Jellyfin Server ir ticis atjaunots",
+ "Latest": "Jaunākais",
+ "LabelIpAddressValue": "IP adrese: {0}",
+ "ItemRemovedWithName": "{0} tika noņemts no bibliotēkas",
+ "ItemAddedWithName": "{0} tika pievienots bibliotēkai",
+ "HeaderLiveTV": "Tiešraides TV",
+ "HeaderContinueWatching": "Turpināt Skatīšanos",
+ "HeaderAlbumArtists": "Albumu Izpildītāji",
+ "Genres": "Žanri",
+ "Folders": "Mapes",
+ "Favorites": "Favorīti",
+ "FailedLoginAttemptWithUserName": "Neizdevies pieslēgšanās mēģinājums no {0}",
+ "DeviceOnlineWithName": "{0} ir pievienojies",
+ "DeviceOfflineWithName": "{0} ir atvienojies",
+ "Collections": "Kolekcijas",
+ "Channels": "Kanāli",
+ "CameraImageUploadedFrom": "Jauns kameras attēls ir ticis augšupielādēts no {0}",
+ "Books": "Grāmatas",
+ "Artists": "Izpildītāji",
+ "Albums": "Albumi",
+ "ProviderValue": "Provider: {0}",
+ "HeaderFavoriteSongs": "Dziesmu Favorīti",
+ "HeaderFavoriteShows": "Raidījumu Favorīti",
+ "HeaderFavoriteEpisodes": "Episožu Favorīti",
+ "HeaderFavoriteArtists": "Izpildītāju Favorīti",
+ "HeaderFavoriteAlbums": "Albumu Favorīti",
+ "TaskCleanCacheDescription": "Nodzēš keša datnes, kas vairs nav sistēmai vajadzīgas.",
+ "TaskRefreshChapterImages": "Izvilkt Nodaļu Attēlus",
+ "TasksApplicationCategory": "Lietotne",
+ "TasksLibraryCategory": "Bibliotēka",
+ "TaskDownloadMissingSubtitlesDescription": "Internetā meklē trūkstošus subtitrus balstoties uz metadatu uzstādījumiem.",
+ "TaskDownloadMissingSubtitles": "Lejupielādēt trūkstošus subtitrus",
+ "TaskRefreshChannelsDescription": "Atjauno interneta kanālu informāciju.",
+ "TaskRefreshChannels": "Atjaunot Kanālus",
+ "TaskCleanTranscodeDescription": "Izdzēš trans-kodēšanas datnes, kas ir vecākas par vienu dienu.",
+ "TaskCleanTranscode": "Iztīrīt Trans-kodēšanas Mapi",
+ "TaskUpdatePluginsDescription": "Lejupielādē un uzstāda atjauninājumus paplašinājumiem, kam ir uzstādīta automātiskā atjaunināšana.",
+ "TaskUpdatePlugins": "Atjaunot Paplašinājumus",
+ "TaskRefreshPeopleDescription": "Atjauno metadatus aktieriem un direktoriem jūsu multivides bibliotēkā.",
+ "TaskRefreshPeople": "Atjaunot Cilvēkus",
+ "TaskCleanLogsDescription": "Nodzēš log datnes, kas ir vairāk par {0} dienām vecas.",
+ "TaskCleanLogs": "Iztīrīt Logdatņu Mapi",
+ "TaskRefreshLibraryDescription": "Skenē jūsu multivides bibliotēku, lai atrastu jaunas datnes, un atsvaidzina metadatus.",
+ "TaskRefreshLibrary": "Skenēt Multivides Bibliotēku",
+ "TaskRefreshChapterImagesDescription": "Izveido sīktēlus priekš video ar sadaļām.",
+ "TaskCleanCache": "Iztīrīt Kešošanas Mapi",
+ "TasksChannelsCategory": "Interneta Kanāli",
+ "TasksMaintenanceCategory": "Apkope",
+ "Forced": "Piespiests",
+ "TaskCleanActivityLogDescription": "Nodzēš darbību žurnāla ierakstus, kuri ir vecāki par doto vecumu.",
+ "TaskCleanActivityLog": "Notīrīt Darbību Žurnālu",
+ "Undefined": "Nenoteikts",
+ "Default": "Noklusējums",
+ "TaskOptimizeDatabaseDescription": "Saspiež datubāzi un atbrīvo atmiņu. Uzdevum palaišana pēc bibliotēku skenēšanas vai citām, ar datubāzi saistītām, izmaiņām iespējams uzlabos ātrdarbību.",
+ "TaskOptimizeDatabase": "Optimizēt datubāzi"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/mk.json b/Emby.Server.Implementations/Localization/Core/mk.json
new file mode 100644
index 000000000..b780ef498
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/mk.json
@@ -0,0 +1,101 @@
+{
+ "ScheduledTaskFailedWithName": "{0} неуспешно",
+ "ProviderValue": "Провајдер: {0}",
+ "PluginUpdatedWithName": "{0} беше надоградено",
+ "PluginUninstalledWithName": "{0} беше успешно деинсталирано",
+ "PluginInstalledWithName": "{0} беше успешно инсталирано",
+ "Plugin": "Додатоци",
+ "Playlists": "Листи",
+ "Photos": "Слики",
+ "NotificationOptionVideoPlaybackStopped": "Видео стопирано",
+ "NotificationOptionVideoPlayback": "Видео пуштено",
+ "NotificationOptionUserLockedOut": "Корисникот е ослободен",
+ "NotificationOptionTaskFailed": "Закажани задачи неуспешно",
+ "NotificationOptionServerRestartRequired": "Задолжително рестартирање на серверот",
+ "NotificationOptionPluginUpdateInstalled": "Надоградба на Додаток успешна",
+ "NotificationOptionPluginUninstalled": "Додаток успешно деинсталиран",
+ "NotificationOptionPluginInstalled": "Додаток успешно инсталиран",
+ "NotificationOptionPluginError": "Грешка на додаток",
+ "NotificationOptionNewLibraryContent": "Додадена нова содржина",
+ "NotificationOptionInstallationFailed": "Неуспешна Инсталација",
+ "NotificationOptionCameraImageUploaded": "Слика од камера поставена",
+ "NotificationOptionAudioPlaybackStopped": "Аудио стопирано",
+ "NotificationOptionAudioPlayback": "Аудио стартувано",
+ "NotificationOptionApplicationUpdateInstalled": "Надоградбата на Апликацијата е иснталирана",
+ "NotificationOptionApplicationUpdateAvailable": "Возможна надоградба на Апликацијата",
+ "NewVersionIsAvailable": "Нова верзија од Jellyfin е возможна за спуштање.",
+ "NameSeasonUnknown": "Непозната Сезона",
+ "NameSeasonNumber": "Сезона {0}",
+ "NameInstallFailed": "{0} неуспешна инсталација",
+ "MusicVideos": "Музички видеа",
+ "Music": "Музика",
+ "Movies": "Филмови",
+ "MixedContent": "Мешана содржина",
+ "MessageServerConfigurationUpdated": "Серверската конфигурација беше надградена",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Секцијата на конфигурација на сервер {0} беше надоградена",
+ "MessageApplicationUpdatedTo": "Jellyfin беше надограден до {0}",
+ "MessageApplicationUpdated": "Jellyfin Серверот беше надограден",
+ "Latest": "Последно",
+ "LabelRunningTimeValue": "Време на работа: {0}",
+ "LabelIpAddressValue": "ИП Адреса: {0}",
+ "ItemRemovedWithName": "{0} е избришано до Библиотеката",
+ "ItemAddedWithName": "{0} беше додадено во Библиотеката",
+ "Inherit": "Следно",
+ "HomeVideos": "Домашни Видеа",
+ "HeaderRecordingGroups": "Групи на снимање",
+ "HeaderNextUp": "Следно",
+ "HeaderLiveTV": "ТВ",
+ "HeaderFavoriteSongs": "Омилени Песни",
+ "HeaderFavoriteShows": "Омилени Серии",
+ "HeaderFavoriteEpisodes": "Омилени Епизоди",
+ "HeaderFavoriteArtists": "Омилени Изведувачи",
+ "HeaderFavoriteAlbums": "Омилени Албуми",
+ "HeaderContinueWatching": "Продолжи со гледање",
+ "HeaderAlbumArtists": "Изведувачи од Албуми",
+ "Genres": "Жанрови",
+ "Folders": "Папки",
+ "Favorites": "Омилени",
+ "FailedLoginAttemptWithUserName": "Неуспешно поврзување од {0}",
+ "DeviceOnlineWithName": "{0} е приклучен",
+ "DeviceOfflineWithName": "{0} се исклучи",
+ "Collections": "Колекции",
+ "ChapterNameValue": "Дел {0}",
+ "Channels": "Канали",
+ "CameraImageUploadedFrom": "Нова слика од камера беше поставена од {0}",
+ "Books": "Книги",
+ "AuthenticationSucceededWithUserName": "{0} успешно поврзан",
+ "Artists": "Изведувач",
+ "Application": "Апликација",
+ "AppDeviceValues": "Аплиакција: {0}, Уред: {1}",
+ "Albums": "Албуми",
+ "VersionNumber": "Верзија {0}",
+ "ValueSpecialEpisodeName": "Специјално - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} е додадено во твојата библиотека",
+ "UserStoppedPlayingItemWithValues": "{0} заврши со репродукција {1} во {2}",
+ "UserStartedPlayingItemWithValues": "{0} пушти {1} на {2}",
+ "UserPolicyUpdatedWithName": "Полисата на користење беше надоградена за {0}",
+ "UserPasswordChangedWithName": "Лозинката е сменета за корисникот {0}",
+ "UserOnlineFromDevice": "{0} е приклучен од {1}",
+ "UserOfflineFromDevice": "{0} е дисконектиран од {1}",
+ "UserLockedOutWithName": "Корисникот {0} е заклучен",
+ "UserDownloadingItemWithValues": "{0} се спушта {1}",
+ "UserDeletedWithName": "Корисникот {0} е избришан",
+ "UserCreatedWithName": "Корисникот {0} е креиран",
+ "User": "Корисник",
+ "TvShows": "ТВ Серии",
+ "System": "Систем",
+ "Sync": "Синхронизација",
+ "SubtitleDownloadFailureFromForItem": "Преводот неуспешно се спушти од {0} за {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin Server се пушта. Ве молиме причекајте.",
+ "Songs": "Песни",
+ "Shows": "Серии",
+ "ServerNameNeedsToBeRestarted": "{0} треба да се рестартира",
+ "ScheduledTaskStartedWithName": "{0} започна",
+ "TaskRefreshChapterImages": "Извези Слики од Поглавје",
+ "TaskCleanCacheDescription": "Ги брише кешираните фајлови што не се повеќе потребни од системот.",
+ "TaskCleanCache": "Исчисти Го Кешот",
+ "TasksChannelsCategory": "Интернет Канали",
+ "TasksApplicationCategory": "Апликација",
+ "TasksLibraryCategory": "Библиотека",
+ "TasksMaintenanceCategory": "Одржување"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ml.json b/Emby.Server.Implementations/Localization/Core/ml.json
new file mode 100644
index 000000000..09ef34913
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ml.json
@@ -0,0 +1,123 @@
+{
+ "AppDeviceValues": "അപ്ലിക്കേഷൻ: {0}, ഉപകരണം: {1}",
+ "Application": "അപ്ലിക്കേഷൻ",
+ "AuthenticationSucceededWithUserName": "{0} വിജയകരമായി പ്രാമാണീകരിച്ചു",
+ "CameraImageUploadedFrom": "Camera 0 from എന്നതിൽ നിന്ന് ഒരു പുതിയ ക്യാമറ ചിത്രം അപ്‌ലോഡുചെയ്‌തു",
+ "ChapterNameValue": "അധ്യായം {0}",
+ "DeviceOfflineWithName": "{0} വിച്ഛേദിച്ചു",
+ "DeviceOnlineWithName": "{0} ബന്ധിപ്പിച്ചു",
+ "FailedLoginAttemptWithUserName": "Log 0 from എന്നതിൽ നിന്നുള്ള പ്രവേശന ശ്രമം പരാജയപ്പെട്ടു",
+ "Forced": "നിർബന്ധിച്ചു",
+ "HeaderFavoriteAlbums": "പ്രിയപ്പെട്ട ആൽബങ്ങൾ",
+ "HeaderFavoriteArtists": "പ്രിയപ്പെട്ട കലാകാരന്മാർ",
+ "HeaderFavoriteEpisodes": "പ്രിയപ്പെട്ട എപ്പിസോഡുകൾ",
+ "HeaderFavoriteShows": "പ്രിയപ്പെട്ട ഷോകൾ",
+ "HeaderFavoriteSongs": "പ്രിയപ്പെട്ട ഗാനങ്ങൾ",
+ "HeaderLiveTV": "തത്സമയ ടിവി",
+ "HeaderNextUp": "അടുത്തത്",
+ "HeaderRecordingGroups": "ഗ്രൂപ്പുകൾ റെക്കോർഡുചെയ്യുന്നു",
+ "HomeVideos": "ഹോം വീഡിയോകൾ",
+ "Inherit": "അനന്തരാവകാശം",
+ "ItemAddedWithName": "{0} ലൈബ്രറിയിൽ ചേർത്തു",
+ "ItemRemovedWithName": "{0} ലൈബ്രറിയിൽ നിന്ന് നീക്കംചെയ്തു",
+ "LabelIpAddressValue": "IP വിലാസം: {0}",
+ "LabelRunningTimeValue": "പ്രവർത്തന സമയം: {0}",
+ "Latest": "ഏറ്റവും പുതിയ",
+ "MessageApplicationUpdated": "ജെല്ലിഫിൻ സെർവർ അപ്‌ഡേറ്റുചെയ്‌തു",
+ "MessageApplicationUpdatedTo": "ജെല്ലിഫിൻ സെർവർ {0 to ലേക്ക് അപ്‌ഡേറ്റുചെയ്‌തു",
+ "MessageNamedServerConfigurationUpdatedWithValue": "സെർവർ കോൺഫിഗറേഷൻ വിഭാഗം {0 അപ്‌ഡേറ്റുചെയ്‌തു",
+ "MessageServerConfigurationUpdated": "സെർവർ കോൺഫിഗറേഷൻ അപ്‌ഡേറ്റുചെയ്‌തു",
+ "MixedContent": "മിശ്രിത ഉള്ളടക്കം",
+ "Music": "സംഗീതം",
+ "MusicVideos": "സംഗീത വീഡിയോകൾ",
+ "NameInstallFailed": "{0} ഇൻസ്റ്റാളേഷൻ പരാജയപ്പെട്ടു",
+ "NameSeasonNumber": "സീസൺ {0}",
+ "NameSeasonUnknown": "സീസൺ അജ്ഞാതം",
+ "NewVersionIsAvailable": "ജെല്ലിഫിൻ സെർവറിന്റെ പുതിയ പതിപ്പ് ഡ .ൺ‌ലോഡിനായി ലഭ്യമാണ്.",
+ "NotificationOptionApplicationUpdateAvailable": "അപ്ലിക്കേഷൻ അപ്‌ഡേറ്റ് ലഭ്യമാണ്",
+ "NotificationOptionApplicationUpdateInstalled": "അപ്ലിക്കേഷൻ അപ്‌ഡേറ്റ് ഇൻസ്റ്റാളുചെയ്‌തു",
+ "NotificationOptionAudioPlayback": "ഓഡിയോ പ്ലേബാക്ക് ആരംഭിച്ചു",
+ "NotificationOptionAudioPlaybackStopped": "ഓഡിയോ പ്ലേബാക്ക് നിർത്തി",
+ "NotificationOptionCameraImageUploaded": "ക്യാമറ ചിത്രം അപ്‌ലോഡുചെയ്‌തു",
+ "NotificationOptionInstallationFailed": "ഇൻസ്റ്റാളേഷൻ പരാജയം",
+ "NotificationOptionNewLibraryContent": "പുതിയ ഉള്ളടക്കം ചേർത്തു",
+ "NotificationOptionPluginError": "പ്ലഗിൻ പരാജയം",
+ "NotificationOptionPluginInstalled": "പ്ലഗിൻ ഇൻസ്റ്റാളുചെയ്‌തു",
+ "NotificationOptionPluginUninstalled": "പ്ലഗിൻ അൺഇൻസ്റ്റാൾ ചെയ്തു",
+ "NotificationOptionPluginUpdateInstalled": "പ്ലഗിൻ അപ്‌ഡേറ്റ് ഇൻസ്റ്റാളുചെയ്‌തു",
+ "NotificationOptionServerRestartRequired": "സെർവർ പുനരാരംഭിക്കൽ ആവശ്യമാണ്",
+ "NotificationOptionTaskFailed": "ഷെഡ്യൂൾ ചെയ്ത ടാസ്‌ക് പരാജയം",
+ "NotificationOptionUserLockedOut": "ഉപയോക്താവ് ലോക്ക് out ട്ട് ചെയ്‌തു",
+ "NotificationOptionVideoPlayback": "വീഡിയോ പ്ലേബാക്ക് ആരംഭിച്ചു",
+ "NotificationOptionVideoPlaybackStopped": "വീഡിയോ പ്ലേബാക്ക് നിർത്തി",
+ "Plugin": "പ്ലഗിൻ",
+ "PluginInstalledWithName": "{0} ഇൻസ്റ്റാളുചെയ്‌തു",
+ "PluginUninstalledWithName": "{0 un അൺഇൻസ്റ്റാൾ ചെയ്തു",
+ "PluginUpdatedWithName": "{0} അപ്‌ഡേറ്റുചെയ്‌തു",
+ "ProviderValue": "ദാതാവ്: {0}",
+ "ScheduledTaskFailedWithName": "{0} പരാജയപ്പെട്ടു",
+ "ScheduledTaskStartedWithName": "{0} ആരംഭിച്ചു",
+ "ServerNameNeedsToBeRestarted": "{0} പുനരാരംഭിക്കേണ്ടതുണ്ട്",
+ "StartupEmbyServerIsLoading": "ജെല്ലിഫിൻ സെർവർ ലോഡുചെയ്യുന്നു. ഉടൻ തന്നെ വീണ്ടും ശ്രമിക്കുക.",
+ "SubtitleDownloadFailureFromForItem": "സബ്ടൈറ്റിലുകൾ {1} ന് {0 from ൽ നിന്ന് ഡ download ൺലോഡ് ചെയ്യുന്നതിൽ പരാജയപ്പെട്ടു",
+ "System": "സിസ്റ്റം",
+ "TvShows": "ടിവി ഷോകൾ",
+ "Undefined": "നിർവചിച്ചിട്ടില്ല",
+ "User": "ഉപയോക്താവ്",
+ "UserCreatedWithName": "ഉപയോക്താവ് {0 created സൃഷ്ടിച്ചു",
+ "UserDeletedWithName": "ഉപയോക്താവ് {0 deleted ഇല്ലാതാക്കി",
+ "UserDownloadingItemWithValues": "{0} ഡൗൺലോഡുചെയ്യുന്നു {1}",
+ "UserLockedOutWithName": "{0} ഉപയോക്താവ് ലോക്ക് out ട്ട് ചെയ്‌തു",
+ "UserOfflineFromDevice": "{0} {1} ൽ നിന്ന് വിച്ഛേദിച്ചു",
+ "UserOnlineFromDevice": "{0} {1} മുതൽ ഓൺ‌ലൈനിലാണ്",
+ "UserPasswordChangedWithName": "{0} ഉപയോക്താവിനായി പാസ്‌വേഡ് മാറ്റി",
+ "UserPolicyUpdatedWithName": "{0} എന്നതിനായി ഉപയോക്തൃ നയം അപ്‌ഡേറ്റുചെയ്‌തു",
+ "UserStartedPlayingItemWithValues": "{0} {2} ൽ {1} പ്ലേ ചെയ്യുന്നു",
+ "UserStoppedPlayingItemWithValues": "{0} {2} ൽ {1 play കളിക്കുന്നത് പൂർത്തിയാക്കി",
+ "ValueHasBeenAddedToLibrary": "Media 0 your നിങ്ങളുടെ മീഡിയ ലൈബ്രറിയിലേക്ക് ചേർത്തു",
+ "VersionNumber": "പതിപ്പ് {0}",
+ "TasksMaintenanceCategory": "പരിപാലനം",
+ "TasksLibraryCategory": "പുസ്തകശാല",
+ "TasksApplicationCategory": "അപ്ലിക്കേഷൻ",
+ "TasksChannelsCategory": "ഇന്റർനെറ്റ് ചാനലുകൾ",
+ "TaskCleanActivityLog": "പ്രവർത്തന ലോഗ് വൃത്തിയാക്കുക",
+ "TaskCleanActivityLogDescription": "കോൺഫിഗർ ചെയ്‌ത പ്രായത്തേക്കാൾ പഴയ പ്രവർത്തന ലോഗ് എൻട്രികൾ ഇല്ലാതാക്കുന്നു.",
+ "TaskCleanCache": "കാഷെ ഡയറക്ടറി വൃത്തിയാക്കുക",
+ "TaskCleanCacheDescription": "സിസ്റ്റത്തിന് ഇനി ആവശ്യമില്ലാത്ത കാഷെ ഫയലുകൾ ഇല്ലാതാക്കുന്നു.",
+ "TaskRefreshChapterImages": "ചാപ്റ്റർ ഇമേജുകൾ എക്‌സ്‌ട്രാക്റ്റുചെയ്യുക",
+ "TaskRefreshChapterImagesDescription": "അധ്യായങ്ങളുള്ള വീഡിയോകൾക്കായി ലഘുചിത്രങ്ങൾ സൃഷ്ടിക്കുന്നു.",
+ "TaskRefreshLibrary": "മീഡിയ ലൈബ്രറി സ്കാൻ ചെയ്യുക",
+ "TaskRefreshLibraryDescription": "പുതിയ ഫയലുകൾക്കായി നിങ്ങളുടെ മീഡിയ ലൈബ്രറി സ്കാൻ ചെയ്യുകയും മെറ്റാഡാറ്റ പുതുക്കുകയും ചെയ്യുന്നു.",
+ "TaskCleanLogs": "ലോഗ് ഡയറക്ടറി വൃത്തിയാക്കുക",
+ "TaskCleanLogsDescription": "Log 0} ദിവസത്തിൽ കൂടുതൽ പഴക്കമുള്ള ലോഗ് ഫയലുകൾ ഇല്ലാതാക്കുന്നു.",
+ "TaskRefreshPeople": "ആളുകളെ പുതുക്കുക",
+ "TaskRefreshPeopleDescription": "നിങ്ങളുടെ മീഡിയ ലൈബ്രറിയിലെ അഭിനേതാക്കൾക്കും സംവിധായകർക്കും മെറ്റാഡാറ്റ അപ്‌ഡേറ്റുചെയ്യുന്നു.",
+ "TaskUpdatePlugins": "പ്ലഗിനുകൾ അപ്‌ഡേറ്റുചെയ്യുക",
+ "TaskUpdatePluginsDescription": "യാന്ത്രികമായി അപ്‌ഡേറ്റുചെയ്യുന്നതിന് കോൺഫിഗർ ചെയ്‌തിരിക്കുന്ന പ്ലഗിനുകൾക്കായുള്ള അപ്‌ഡേറ്റുകൾ ഡൗൺലോഡുചെയ്യുകയും ഇൻസ്റ്റാളുചെയ്യുകയും ചെയ്യുന്നു.",
+ "TaskCleanTranscode": "ട്രാൻസ്‌കോഡ് ഡയറക്‌ടറി വൃത്തിയാക്കുക",
+ "TaskCleanTranscodeDescription": "ഒരു ദിവസത്തിൽ കൂടുതൽ പഴക്കമുള്ള ട്രാൻസ്‌കോഡ് ഫയലുകൾ ഇല്ലാതാക്കുന്നു.",
+ "TaskRefreshChannels": "ചാനലുകൾ പുതുക്കുക",
+ "TaskRefreshChannelsDescription": "ഇന്റർനെറ്റ് ചാനൽ വിവരങ്ങൾ പുതുക്കുന്നു.",
+ "TaskDownloadMissingSubtitles": "നഷ്‌ടമായ സബ്‌ടൈറ്റിലുകൾ ഡൗൺലോഡുചെയ്യുക",
+ "TaskDownloadMissingSubtitlesDescription": "മെറ്റാഡാറ്റ കോൺഫിഗറേഷനെ അടിസ്ഥാനമാക്കി നഷ്‌ടമായ സബ്‌ടൈറ്റിലുകൾക്കായി ഇന്റർനെറ്റ് തിരയുന്നു.",
+ "ValueSpecialEpisodeName": "പ്രത്യേക - {0}",
+ "Collections": "ശേഖരങ്ങൾ",
+ "Folders": "ഫോൾഡറുകൾ",
+ "HeaderAlbumArtists": "കലാകാരന്റെ ആൽബം",
+ "Sync": "സമന്വയിപ്പിക്കുക",
+ "Movies": "സിനിമകൾ",
+ "Photos": "ഫോട്ടോകൾ",
+ "Albums": "ആൽബങ്ങൾ",
+ "Playlists": "പ്ലേലിസ്റ്റുകൾ",
+ "Songs": "ഗാനങ്ങൾ",
+ "HeaderContinueWatching": "കാണുന്നത് തുടരുക",
+ "Artists": "കലാകാരന്മാർ",
+ "Shows": "ഷോകൾ",
+ "Default": "സ്ഥിരസ്ഥിതി",
+ "Favorites": "പ്രിയങ്കരങ്ങൾ",
+ "Books": "പുസ്തകങ്ങൾ",
+ "Genres": "വിഭാഗങ്ങൾ",
+ "Channels": "ചാനലുകൾ",
+ "TaskOptimizeDatabaseDescription": "ഡാറ്റാബേസ് ചുരുക്കുകയും സ്വതന്ത്ര ഇടം വെട്ടിച്ചുരുക്കുകയും ചെയ്യുന്നു. ലൈബ്രറി സ്‌കാൻ ചെയ്‌തതിനുശേഷം അല്ലെങ്കിൽ ഡാറ്റാബേസ് പരിഷ്‌ക്കരണങ്ങളെ സൂചിപ്പിക്കുന്ന മറ്റ് മാറ്റങ്ങൾ ചെയ്‌തതിന് ശേഷം ഈ ടാസ്‌ക് പ്രവർത്തിപ്പിക്കുന്നത് പ്രകടനം മെച്ചപ്പെടുത്തും.",
+ "TaskOptimizeDatabase": "ഡാറ്റാബേസ് ഒപ്റ്റിമൈസ് ചെയ്യുക"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/mr.json b/Emby.Server.Implementations/Localization/Core/mr.json
new file mode 100644
index 000000000..fdb4171b5
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/mr.json
@@ -0,0 +1,62 @@
+{
+ "Books": "पुस्तकं",
+ "Artists": "संगीतकार",
+ "Albums": "अल्बम",
+ "Playlists": "प्लेलिस्ट",
+ "HeaderAlbumArtists": "अल्बम संगीतकार",
+ "Folders": "फोल्डर",
+ "HeaderFavoriteEpisodes": "आवडते भाग",
+ "HeaderFavoriteSongs": "आवडती गाणी",
+ "Movies": "चित्रपट",
+ "HeaderFavoriteArtists": "आवडते संगीतकार",
+ "Shows": "कार्यक्रम",
+ "HeaderFavoriteAlbums": "आवडते अल्बम",
+ "Channels": "वाहिन्या",
+ "ValueSpecialEpisodeName": "विशेष - {0}",
+ "HeaderFavoriteShows": "आवडते कार्यक्रम",
+ "Favorites": "आवडीचे",
+ "HeaderNextUp": "यानंतर",
+ "Songs": "गाणी",
+ "HeaderLiveTV": "लाइव्ह टीव्ही",
+ "Genres": "जाँनरे",
+ "Photos": "चित्र",
+ "TaskDownloadMissingSubtitles": "नसलेले सबटायटल डाउनलोड करा",
+ "TaskCleanTranscodeDescription": "एक दिवसापेक्षा जुन्या ट्रान्सकोड फायली काढून टाका.",
+ "TaskCleanTranscode": "ट्रान्सकोड डिरेक्टरी साफ करून टाका",
+ "TaskUpdatePlugins": "प्लगइन अपडेट करा",
+ "TaskCleanLogs": "लॉग डिरेक्टरी साफ करून टाका",
+ "TaskCleanCache": "कॅश डिरेक्टरी साफ करून टाका",
+ "TasksChannelsCategory": "इंटरनेट वाहिन्या",
+ "TasksApplicationCategory": "अ‍ॅप्लिकेशन",
+ "TasksLibraryCategory": "संग्रहालय",
+ "VersionNumber": "आवृत्ती {0}",
+ "UserPasswordChangedWithName": "{0} या प्रयोक्त्याचे पासवर्ड बदलण्यात आले आहे",
+ "UserOnlineFromDevice": "{0} हे {1} येथून ऑनलाइन आहेत",
+ "UserDeletedWithName": "प्रयोक्ता {0} काढून टाकण्यात आले आहे",
+ "UserCreatedWithName": "प्रयोक्ता {0} बनवण्यात आले आहे",
+ "User": "प्रयोक्ता",
+ "TvShows": "टीव्ही कार्यक्रम",
+ "StartupEmbyServerIsLoading": "जेलिफिन सर्व्हर लोड होत आहे. कृपया थोड्या वेळात पुन्हा प्रयत्न करा.",
+ "Plugin": "प्लगइन",
+ "NotificationOptionCameraImageUploaded": "कॅमेरा चित्र अपलोड केले आहे",
+ "NotificationOptionApplicationUpdateInstalled": "अ‍ॅप्लिकेशन अपडेट इन्स्टॉल केले आहे",
+ "NotificationOptionApplicationUpdateAvailable": "अ‍ॅप्लिकेशन अपडेट उपलब्ध आहे",
+ "NewVersionIsAvailable": "जेलिफिन सर्व्हरची एक नवीन आवृत्ती डाउनलोड करण्यास उपलब्ध आहे.",
+ "NameSeasonUnknown": "अज्ञात सीझन",
+ "NameSeasonNumber": "सीझन {0}",
+ "MusicVideos": "संगीत व्हिडीयो",
+ "Music": "संगीत",
+ "MessageApplicationUpdatedTo": "जेलिफिन सर्व्हर अपडेट होऊन {0} आवृत्तीवर पोहोचला आहे",
+ "MessageApplicationUpdated": "जेलिफिन सर्व्हर अपडेट केला गेला आहे",
+ "Latest": "नवीनतम",
+ "LabelIpAddressValue": "आयपी पत्ता: {0}",
+ "ItemRemovedWithName": "{0} हे संग्रहालयातून काढून टाकण्यात आले",
+ "ItemAddedWithName": "{0} हे संग्रहालयात जोडले गेले",
+ "HomeVideos": "घरचे व्हिडीयो",
+ "HeaderRecordingGroups": "रेकॉर्डिंग गट",
+ "CameraImageUploadedFrom": "एक नवीन कॅमेरा चित्र {0} येथून अपलोड केले आहे",
+ "Application": "अ‍ॅप्लिकेशन",
+ "AppDeviceValues": "अ‍ॅप: {0}, यंत्र: {1}",
+ "Collections": "संग्रह",
+ "ChapterNameValue": "धडा {0}"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json
index c10fbe58f..b2dcf270c 100644
--- a/Emby.Server.Implementations/Localization/Core/ms.json
+++ b/Emby.Server.Implementations/Localization/Core/ms.json
@@ -1,97 +1,113 @@
{
"Albums": "Album-album",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artis-artis",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
+ "AppDeviceValues": "Apl: {0}, Peranti: {1}",
+ "Application": "Aplikasi",
+ "Artists": "Artis",
+ "AuthenticationSucceededWithUserName": "{0} berjaya disahkan",
"Books": "Buku-buku",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
+ "CameraImageUploadedFrom": "Gambar baharu telah dimuat naik melalui {0}",
+ "Channels": "Saluran",
+ "ChapterNameValue": "Bab {0}",
+ "Collections": "Koleksi",
+ "DeviceOfflineWithName": "{0} telah diputuskan sambungan",
+ "DeviceOnlineWithName": "{0} telah disambung",
+ "FailedLoginAttemptWithUserName": "Cubaan log masuk gagal dari {0}",
+ "Favorites": "Kegemaran",
+ "Folders": "Fail-fail",
+ "Genres": "Genre-genre",
+ "HeaderAlbumArtists": "Album Artis-artis",
+ "HeaderContinueWatching": "Terus Menonton",
+ "HeaderFavoriteAlbums": "Album-album Kegemaran",
+ "HeaderFavoriteArtists": "Artis-artis Kegemaran",
+ "HeaderFavoriteEpisodes": "Episod-episod Kegemaran",
+ "HeaderFavoriteShows": "Rancangan-rancangan Kegemaran",
+ "HeaderFavoriteSongs": "Lagu-lagu Kegemaran",
+ "HeaderLiveTV": "TV Siaran Langsung",
+ "HeaderNextUp": "Seterusnya",
+ "HeaderRecordingGroups": "Kumpulan-kumpulan Rakaman",
+ "HomeVideos": "Video Personal",
+ "Inherit": "Mewarisi",
+ "ItemAddedWithName": "{0} telah ditambahkan 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",
+ "MessageServerConfigurationUpdated": "Konfigurasi pelayan telah dikemas kini",
+ "MixedContent": "Kandungan campuran",
+ "Movies": "Filem",
+ "Music": "Muzik",
+ "MusicVideos": "Muzik video",
+ "NameInstallFailed": "{0} pemasangan gagal",
+ "NameSeasonNumber": "Musim {0}",
+ "NameSeasonUnknown": "Musim Tidak Diketahui",
+ "NewVersionIsAvailable": "Versi terbaru Jellyfin Server bersedia untuk dimuat turunkan.",
+ "NotificationOptionApplicationUpdateAvailable": "Kemas kini aplikasi telah sedia",
+ "NotificationOptionApplicationUpdateInstalled": "Kemas kini aplikasi telah dipasang",
+ "NotificationOptionAudioPlayback": "Ulangmain audio bermula",
+ "NotificationOptionAudioPlaybackStopped": "Ulangmain audio dihentikan",
+ "NotificationOptionCameraImageUploaded": "Imej kamera telah dimuatnaik",
+ "NotificationOptionInstallationFailed": "Pemasangan gagal",
+ "NotificationOptionNewLibraryContent": "Kandungan baru telah ditambah",
+ "NotificationOptionPluginError": "Kegagalan plugin",
+ "NotificationOptionPluginInstalled": "Plugin telah dipasang",
"NotificationOptionPluginUninstalled": "Plugin uninstalled",
"NotificationOptionPluginUpdateInstalled": "Plugin update installed",
"NotificationOptionServerRestartRequired": "Server restart required",
"NotificationOptionTaskFailed": "Scheduled task failure",
"NotificationOptionUserLockedOut": "User locked out",
"NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
+ "NotificationOptionVideoPlaybackStopped": "Ulangmain video dihentikan",
+ "Photos": "Gambar-gambar",
+ "Playlists": "Senarai main",
"Plugin": "Plugin",
"PluginInstalledWithName": "{0} was installed",
"PluginUninstalledWithName": "{0} was uninstalled",
"PluginUpdatedWithName": "{0} was updated",
"ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
+ "ScheduledTaskFailedWithName": "{0} gagal",
+ "ScheduledTaskStartedWithName": "{0} bermula",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"Shows": "Series",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Songs": "Lagu-lagu",
+ "StartupEmbyServerIsLoading": "Pelayan Jellyfin sedang dimuatkan. Sila cuba sebentar lagi.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
+ "SubtitleDownloadFailureFromForItem": "Muat turun sarikata gagal dari {0} untuk {1}",
"Sync": "Sync",
- "System": "System",
+ "System": "Sistem",
"TvShows": "TV Shows",
"User": "User",
"UserCreatedWithName": "User {0} has been created",
"UserDeletedWithName": "User {0} has been deleted",
"UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
+ "UserLockedOutWithName": "Pengguna {0} telah dikunci",
+ "UserOfflineFromDevice": "{0} telah terputus dari {1}",
+ "UserOnlineFromDevice": "{0} berada dalam talian dari {1}",
+ "UserPasswordChangedWithName": "Kata laluan telah ditukar bagi pengguna {0}",
+ "UserPolicyUpdatedWithName": "Dasar pengguna telah dikemas kini untuk {0}",
"UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
"UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "ValueSpecialEpisodeName": "Khas - {0}",
+ "VersionNumber": "Versi {0}",
+ "TaskCleanActivityLog": "Log Aktiviti Bersih",
+ "TasksChannelsCategory": "Saluran Internet",
+ "TasksApplicationCategory": "Aplikasi",
+ "TasksLibraryCategory": "Perpustakaan",
+ "TasksMaintenanceCategory": "Penyelenggaraan",
+ "Undefined": "Tidak ditentukan",
+ "Forced": "Paksa",
+ "Default": "Asal",
+ "TaskCleanCache": "Bersihkan Direktori Cache",
+ "TaskCleanActivityLogDescription": "Padamkan entri log aktiviti yang lebih tua daripada usia yang dikonfigurasi.",
+ "TaskRefreshPeople": "Segarkan Orang",
+ "TaskCleanLogsDescription": "Padamkan fail log yang berumur lebih dari {0} hari.",
+ "TaskCleanLogs": "Bersihkan Direktotri Log",
+ "TaskRefreshLibraryDescription": "Imbas perpustakaan media untuk mencari fail-fail baru dan menyegarkan metadata.",
+ "TaskRefreshLibrary": "Imbas Perpustakaan Media",
+ "TaskRefreshChapterImagesDescription": "Membuat gambaran kecil untuk video yang mempunyai bab.",
+ "TaskRefreshChapterImages": "Ekstrak Gambar-gambar Bab",
+ "TaskCleanCacheDescription": "Menghapuskan fail cache yang tidak lagi diperlukan oleh sistem."
}
diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json
index dbda794ad..317bdcfcb 100644
--- a/Emby.Server.Implementations/Localization/Core/nb.json
+++ b/Emby.Server.Implementations/Localization/Core/nb.json
@@ -1,11 +1,11 @@
{
"Albums": "Album",
- "AppDeviceValues": "App:{0}, Enhet {1}",
- "Application": "Applikasjon",
+ "AppDeviceValues": "App:{0}, Enhet: {1}",
+ "Application": "Program",
"Artists": "Artister",
- "AuthenticationSucceededWithUserName": "{0} vellykkede autentisert",
+ "AuthenticationSucceededWithUserName": "{0} har logget inn",
"Books": "Bøker",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Et nytt kamerabilde er lastet opp fra {0}",
"Channels": "Kanaler",
"ChapterNameValue": "Kapittel {0}",
"Collections": "Samlinger",
@@ -14,72 +14,70 @@
"FailedLoginAttemptWithUserName": "Mislykket påloggingsforsøk fra {0}",
"Favorites": "Favoritter",
"Folders": "Mapper",
- "Genres": "Sjanger",
- "HeaderAlbumArtists": "Albumartist",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Forsett og see på",
- "HeaderFavoriteAlbums": "Favoritt albumer",
+ "Genres": "Sjangre",
+ "HeaderAlbumArtists": "Albumartister",
+ "HeaderContinueWatching": "Fortsett å se",
+ "HeaderFavoriteAlbums": "Favorittalbum",
"HeaderFavoriteArtists": "Favorittartister",
- "HeaderFavoriteEpisodes": "Favoritt episode",
+ "HeaderFavoriteEpisodes": "Favorittepisoder",
"HeaderFavoriteShows": "Favorittserier",
"HeaderFavoriteSongs": "Favorittsanger",
- "HeaderLiveTV": "Direkte TV",
+ "HeaderLiveTV": "Direkte-TV",
"HeaderNextUp": "Neste",
- "HeaderRecordingGroups": "Opptak Grupper",
- "HomeVideos": "Hjemmelaget filmer",
+ "HeaderRecordingGroups": "Opptaksgrupper",
+ "HomeVideos": "Hjemmelagde filmer",
"Inherit": "Arve",
"ItemAddedWithName": "{0} ble lagt til i biblioteket",
"ItemRemovedWithName": "{0} ble fjernet fra biblioteket",
- "LabelIpAddressValue": "IP adresse: {0}",
- "LabelRunningTimeValue": "Løpetid {0}",
+ "LabelIpAddressValue": "IP-adresse: {0}",
+ "LabelRunningTimeValue": "Spilletid {0}",
"Latest": "Siste",
- "MessageApplicationUpdated": "Jellyfin server har blitt oppdatert",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server konfigurasjon seksjon {0} har blitt oppdatert",
- "MessageServerConfigurationUpdated": "Server konfigurasjon er oppdatert",
+ "MessageApplicationUpdated": "Jellyfin-tjeneren har blitt oppdatert",
+ "MessageApplicationUpdatedTo": "Jellyfin-tjeneren ble oppdatert til {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Tjenerkonfigurasjonsseksjon {0} har blitt oppdatert",
+ "MessageServerConfigurationUpdated": "Tjenerkonfigurasjon er oppdatert",
"MixedContent": "Blandet innhold",
"Movies": "Filmer",
"Music": "Musikk",
"MusicVideos": "Musikkvideoer",
- "NameInstallFailed": "{0} installation failed",
+ "NameInstallFailed": "Installasjonen av {0} mislyktes",
"NameSeasonNumber": "Sesong {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Applikasjon oppdatering tilgjengelig",
- "NotificationOptionApplicationUpdateInstalled": "Applikasjon oppdatering installert.",
- "NotificationOptionAudioPlayback": "Lyd tilbakespilling startet",
- "NotificationOptionAudioPlaybackStopped": "Lyd avspilling stoppet",
- "NotificationOptionCameraImageUploaded": "Kamera bilde lastet opp",
- "NotificationOptionInstallationFailed": "Installasjon feil",
- "NotificationOptionNewLibraryContent": "Ny innhold er lagt til",
- "NotificationOptionPluginError": "Plugin feil",
- "NotificationOptionPluginInstalled": "Plugin installert",
- "NotificationOptionPluginUninstalled": "Plugin avinstallert",
- "NotificationOptionPluginUpdateInstalled": "Plugin oppdatering installert",
- "NotificationOptionServerRestartRequired": "Server omstart er nødvendig",
- "NotificationOptionTaskFailed": "Feil under utføring av planlagt oppgaver",
+ "NameSeasonUnknown": "Ukjent sesong",
+ "NewVersionIsAvailable": "En ny versjon av Jellyfin-tjeneren er tilgjengelig for nedlasting.",
+ "NotificationOptionApplicationUpdateAvailable": "En programvareoppdatering er tilgjengelig",
+ "NotificationOptionApplicationUpdateInstalled": "Applikasjonsoppdatering installert",
+ "NotificationOptionAudioPlayback": "Lydavspilling startet",
+ "NotificationOptionAudioPlaybackStopped": "Lydavspilling stoppet",
+ "NotificationOptionCameraImageUploaded": "Kamerabilde lastet opp",
+ "NotificationOptionInstallationFailed": "Installasjonen feilet",
+ "NotificationOptionNewLibraryContent": "Nytt innhold lagt til",
+ "NotificationOptionPluginError": "Programvareutvidelsesfeil",
+ "NotificationOptionPluginInstalled": "Programvareutvidelse installert",
+ "NotificationOptionPluginUninstalled": "Programvareutvidelse avinstallert",
+ "NotificationOptionPluginUpdateInstalled": "Programvareutvidelsesoppdatering installert",
+ "NotificationOptionServerRestartRequired": "Tjeneromstart er nødvendig",
+ "NotificationOptionTaskFailed": "Feil under utføring av planlagt oppgave",
"NotificationOptionUserLockedOut": "Bruker er utestengt",
- "NotificationOptionVideoPlayback": "Video tilbakespilling startet",
- "NotificationOptionVideoPlaybackStopped": "Video avspilling stoppet",
- "Photos": "BIlder",
- "Playlists": "Spilleliste",
- "Plugin": "Plugin",
+ "NotificationOptionVideoPlayback": "Videoavspilling startet",
+ "NotificationOptionVideoPlaybackStopped": "Videoavspilling stoppet",
+ "Photos": "Bilder",
+ "Playlists": "Spillelister",
+ "Plugin": "Programvareutvidelse",
"PluginInstalledWithName": "{0} ble installert",
"PluginUninstalledWithName": "{0} ble avinstallert",
"PluginUpdatedWithName": "{0} ble oppdatert",
- "ProviderValue": "Leverandører: {0}",
- "ScheduledTaskFailedWithName": "{0} Mislykkes",
- "ScheduledTaskStartedWithName": "{0} Startet",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Programmer",
+ "ProviderValue": "Leverandør: {0}",
+ "ScheduledTaskFailedWithName": "{0} mislykkes",
+ "ScheduledTaskStartedWithName": "{0} startet",
+ "ServerNameNeedsToBeRestarted": "{0} må startes på nytt",
+ "Shows": "Program",
"Songs": "Sanger",
- "StartupEmbyServerIsLoading": "Jellyfin server laster. Prøv igjen snart.",
+ "StartupEmbyServerIsLoading": "Jellyfin-tjener laster. Prøv igjen snart.",
"SubtitleDownloadFailureForItem": "En feil oppstå under nedlasting av undertekster for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Undertekster lastet ned for {0}",
- "Sync": "Synk",
+ "SubtitleDownloadFailureFromForItem": "Kunne ikke laste ned undertekster fra {0} for {1}",
+ "Sync": "Synkroniser",
"System": "System",
- "TvShows": "TV Shows",
+ "TvShows": "TV-serier",
"User": "Bruker",
"UserCreatedWithName": "Bruker {0} er opprettet",
"UserDeletedWithName": "Bruker {0} har blitt slettet",
@@ -88,10 +86,39 @@
"UserOfflineFromDevice": "{0} har koblet fra {1}",
"UserOnlineFromDevice": "{0} er tilkoblet fra {1}",
"UserPasswordChangedWithName": "Passordet for {0} er oppdatert",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} har startet avspilling {1}",
- "UserStoppedPlayingItemWithValues": "{0} har stoppet avspilling {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Spesial - {0}",
- "VersionNumber": "Versjon {0}"
+ "UserPolicyUpdatedWithName": "Brukerretningslinjene har blitt oppdatert for {0}",
+ "UserStartedPlayingItemWithValues": "{0} har startet avspilling {1} på {2}",
+ "UserStoppedPlayingItemWithValues": "{0} har stoppet avspilling {1}",
+ "ValueHasBeenAddedToLibrary": "{0} har blitt lagt til i mediebiblioteket ditt",
+ "ValueSpecialEpisodeName": "Spesialepisode - {0}",
+ "VersionNumber": "Versjon {0}",
+ "TasksChannelsCategory": "Internettkanaler",
+ "TasksApplicationCategory": "Applikasjon",
+ "TasksLibraryCategory": "Bibliotek",
+ "TasksMaintenanceCategory": "Vedlikehold",
+ "TaskCleanCache": "Tøm hurtigbuffer",
+ "TaskRefreshLibrary": "Skann mediebibliotek",
+ "TaskRefreshChapterImagesDescription": "Lager forhåndsvisningsbilder for videoer som har kapitler.",
+ "TaskRefreshChapterImages": "Trekk ut kapittelbilder",
+ "TaskCleanCacheDescription": "Sletter mellomlagrede filer som ikke lengre trengs av systemet.",
+ "TaskDownloadMissingSubtitlesDescription": "Søker etter manglende undertekster på nett basert på metadatakonfigurasjon.",
+ "TaskDownloadMissingSubtitles": "Last ned manglende undertekster",
+ "TaskRefreshChannelsDescription": "Oppdaterer internettkanalinformasjon.",
+ "TaskRefreshChannels": "Oppdater kanaler",
+ "TaskCleanTranscodeDescription": "Sletter omkodede filer som er mer enn én dag gamle.",
+ "TaskCleanTranscode": "Tøm transkodingmappe",
+ "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringer for programvareutvidelser som er stilt inn til å oppdatere automatisk.",
+ "TaskUpdatePlugins": "Oppdater programvareutvidelse",
+ "TaskRefreshPeopleDescription": "Oppdaterer metadata for skuespillere og regissører i mediebiblioteket ditt.",
+ "TaskRefreshPeople": "Oppdater personer",
+ "TaskCleanLogsDescription": "Sletter loggfiler som er eldre enn {0} dager gamle.",
+ "TaskCleanLogs": "Tøm loggmappe",
+ "TaskRefreshLibraryDescription": "Skanner mediebibliotekene dine for nye filer og oppdaterer metadata.",
+ "TaskCleanActivityLog": "Tøm aktivitetslogg",
+ "Undefined": "Udefinert",
+ "Forced": "Tvunget",
+ "Default": "Standard",
+ "TaskCleanActivityLogDescription": "Sletter oppføringer i aktivitetsloggen som er eldre enn den konfigurerte alderen.",
+ "TaskOptimizeDatabase": "Optimiser database",
+ "TaskOptimizeDatabaseDescription": "Komprimerer database og frigjør plass. Denne prosessen kan forbedre ytelsen etter skanning av bibliotek eller andre handlinger som fører til databaseendringer."
}
diff --git a/Emby.Server.Implementations/Localization/Core/ne.json b/Emby.Server.Implementations/Localization/Core/ne.json
new file mode 100644
index 000000000..8e820d40c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ne.json
@@ -0,0 +1,85 @@
+{
+ "NotificationOptionUserLockedOut": "प्रयोगकर्ता प्रतिबन्धित",
+ "NotificationOptionTaskFailed": "निर्धारित कार्य विफलता",
+ "NotificationOptionServerRestartRequired": "सर्भर रिस्टार्ट आवाश्यक छ",
+ "NotificationOptionPluginUpdateInstalled": "प्लगइन अद्यावधिक स्थापना भयो",
+ "NotificationOptionPluginUninstalled": "प्लगइन विस्थापित",
+ "NotificationOptionPluginInstalled": "प्लगइन स्थापना भयो",
+ "NotificationOptionPluginError": "प्लगइन असफलता",
+ "NotificationOptionNewLibraryContent": "नयाँ सामग्री थपियो",
+ "NotificationOptionInstallationFailed": "स्थापना असफलता",
+ "NotificationOptionCameraImageUploaded": "क्यामेरा फोटो अपलोड गरियो",
+ "NotificationOptionAudioPlaybackStopped": "ध्वनि प्रक्षेपण रोकियो",
+ "NotificationOptionAudioPlayback": "ध्वनि प्रक्षेपण शुरू भयो",
+ "NotificationOptionApplicationUpdateInstalled": "अनुप्रयोग अद्यावधिक स्थापना भयो",
+ "NotificationOptionApplicationUpdateAvailable": "अनुप्रयोग अपडेट उपलब्ध छ",
+ "NewVersionIsAvailable": "जेलीफिन सर्भर को नयाँ संस्करण डाउनलोड को लागी उपलब्ध छ।",
+ "NameSeasonUnknown": "अज्ञात श्रृंखला",
+ "NameSeasonNumber": "श्रृंखला {0}",
+ "NameInstallFailed": "{0} स्थापना असफल भयो",
+ "MusicVideos": "सांगीतिक भिडियोहरू",
+ "Music": "संगीत",
+ "Movies": "चलचित्रहरू",
+ "MixedContent": "मिश्रित सामग्री",
+ "MessageServerConfigurationUpdated": "सर्भर कन्फिगरेसन अद्यावधिक गरिएको छ",
+ "MessageNamedServerConfigurationUpdatedWithValue": "सर्भर कन्फिगरेसन विभाग {0} अद्यावधिक गरिएको छ",
+ "MessageApplicationUpdatedTo": "जेलीफिन सर्भर {0} मा अद्यावधिक गरिएको छ",
+ "MessageApplicationUpdated": "जेलीफिन सर्भर अपडेट गरिएको छ",
+ "Latest": "नविनतम",
+ "LabelRunningTimeValue": "कुल समय: {0}",
+ "LabelIpAddressValue": "आईपी ठेगाना: {0}",
+ "ItemRemovedWithName": "{0}लाई पुस्तकालयबाट हटाईयो",
+ "ItemAddedWithName": "{0} लाईब्रेरीमा थपियो",
+ "Inherit": "इनहेरिट",
+ "HomeVideos": "घरेलु भिडियोहरू",
+ "HeaderRecordingGroups": "रेकर्ड समूहहरू",
+ "HeaderNextUp": "आगामी",
+ "HeaderLiveTV": "प्रत्यक्ष टिभी",
+ "HeaderFavoriteSongs": "मनपर्ने गीतहरू",
+ "HeaderFavoriteShows": "मनपर्ने कार्यक्रमहरू",
+ "HeaderFavoriteEpisodes": "मनपर्ने एपिसोडहरू",
+ "HeaderFavoriteArtists": "मनपर्ने कलाकारहरू",
+ "HeaderFavoriteAlbums": "मनपर्ने एल्बमहरू",
+ "HeaderContinueWatching": "हेर्न जारी राख्नुहोस्",
+ "HeaderAlbumArtists": "एल्बमका कलाकारहरू",
+ "Genres": "विधाहरू",
+ "Folders": "फोल्डरहरू",
+ "Favorites": "मनपर्ने",
+ "FailedLoginAttemptWithUserName": "{0}को लग इन प्रयास असफल",
+ "DeviceOnlineWithName": "{0}को साथ जडित",
+ "DeviceOfflineWithName": "{0}बाट विच्छेदन भयो",
+ "Collections": "संग्रह",
+ "ChapterNameValue": "अध्याय {0}",
+ "Channels": "च्यानलहरू",
+ "AppDeviceValues": "अनुप्रयोग: {0}, उपकरण: {1}",
+ "AuthenticationSucceededWithUserName": "{0} सफलतापूर्वक प्रमाणीकरण गरियो",
+ "CameraImageUploadedFrom": "{0}बाट नयाँ क्यामेरा छवि अपलोड गरिएको छ",
+ "Books": "पुस्तकहरु",
+ "Artists": "कलाकारहरू",
+ "Application": "अनुप्रयोगहरू",
+ "Albums": "एल्बमहरू",
+ "TasksLibraryCategory": "पुस्तकालय",
+ "TasksApplicationCategory": "अनुप्रयोग",
+ "TasksMaintenanceCategory": "मर्मत",
+ "UserPolicyUpdatedWithName": "प्रयोगकर्ता नीति को लागी अद्यावधिक गरिएको छ {0}",
+ "UserPasswordChangedWithName": "पासवर्ड प्रयोगकर्ताका लागि परिवर्तन गरिएको छ {0}",
+ "UserOnlineFromDevice": "{0} बाट अनलाइन छ {1}",
+ "UserOfflineFromDevice": "{0} बाट विच्छेदन भएको छ {1}",
+ "UserLockedOutWithName": "प्रयोगकर्ता {0} लक गरिएको छ",
+ "UserDeletedWithName": "प्रयोगकर्ता {0} हटाइएको छ",
+ "UserCreatedWithName": "प्रयोगकर्ता {0} सिर्जना गरिएको छ",
+ "User": "प्रयोगकर्ता",
+ "PluginInstalledWithName": "",
+ "StartupEmbyServerIsLoading": "Jellyfin सर्भर लोड हुँदैछ। कृपया छिट्टै फेरि प्रयास गर्नुहोस्।",
+ "Songs": "गीतहरू",
+ "Shows": "शोहरू",
+ "ServerNameNeedsToBeRestarted": "{0} लाई पुन: सुरु गर्नु पर्छ",
+ "ScheduledTaskStartedWithName": "{0} सुरु भयो",
+ "ScheduledTaskFailedWithName": "{0} असफल",
+ "ProviderValue": "प्रदायक: {0}",
+ "Plugin": "प्लगइनहरू",
+ "Playlists": "प्लेलिस्टहरू",
+ "Photos": "तस्बिरहरु",
+ "NotificationOptionVideoPlaybackStopped": "भिडियो प्लेब्याक रोकियो",
+ "NotificationOptionVideoPlayback": "भिडियो प्लेब्याक सुरु भयो"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json
index 24af1839f..79f921bcb 100644
--- a/Emby.Server.Implementations/Localization/Core/nl.json
+++ b/Emby.Server.Implementations/Localization/Core/nl.json
@@ -3,20 +3,19 @@
"AppDeviceValues": "App: {0}, Apparaat: {1}",
"Application": "Toepassing",
"Artists": "Artiesten",
- "AuthenticationSucceededWithUserName": "{0} is succesvol geverifieerd",
+ "AuthenticationSucceededWithUserName": "{0} is succesvol geauthenticeerd",
"Books": "Boeken",
- "CameraImageUploadedFrom": "Er is een nieuwe foto toegevoegd via {0}",
+ "CameraImageUploadedFrom": "Nieuwe camera afbeelding toegevoegd vanaf {0}",
"Channels": "Kanalen",
"ChapterNameValue": "Hoofdstuk {0}",
- "Collections": "Collecties",
- "DeviceOfflineWithName": "{0} heeft de verbinding verbroken",
+ "Collections": "Verzamelingen",
+ "DeviceOfflineWithName": "Verbinding met {0} is verbroken",
"DeviceOnlineWithName": "{0} is verbonden",
"FailedLoginAttemptWithUserName": "Mislukte aanmeld poging van {0}",
"Favorites": "Favorieten",
"Folders": "Mappen",
"Genres": "Genres",
- "HeaderAlbumArtists": "Albumartiesten",
- "HeaderCameraUploads": "Camera-uploads",
+ "HeaderAlbumArtists": "Artiests Album",
"HeaderContinueWatching": "Kijken hervatten",
"HeaderFavoriteAlbums": "Favoriete albums",
"HeaderFavoriteArtists": "Favoriete artiesten",
@@ -26,11 +25,11 @@
"HeaderLiveTV": "Live TV",
"HeaderNextUp": "Volgende",
"HeaderRecordingGroups": "Opnamegroepen",
- "HomeVideos": "Start video's",
- "Inherit": "Overerven",
+ "HomeVideos": "Thuis video's",
+ "Inherit": "Erven",
"ItemAddedWithName": "{0} is toegevoegd aan de bibliotheek",
"ItemRemovedWithName": "{0} is verwijderd uit de bibliotheek",
- "LabelIpAddressValue": "IP adres: {0}",
+ "LabelIpAddressValue": "IP-adres: {0}",
"LabelRunningTimeValue": "Looptijd: {0}",
"Latest": "Nieuwste",
"MessageApplicationUpdated": "Jellyfin Server is bijgewerkt",
@@ -58,7 +57,7 @@
"NotificationOptionPluginUpdateInstalled": "Plug-in-update geïnstalleerd",
"NotificationOptionServerRestartRequired": "Server herstart nodig",
"NotificationOptionTaskFailed": "Geplande taak mislukt",
- "NotificationOptionUserLockedOut": "Gebruikersaccount vergrendeld",
+ "NotificationOptionUserLockedOut": "Gebruiker is vergrendeld",
"NotificationOptionVideoPlayback": "Video gestart",
"NotificationOptionVideoPlaybackStopped": "Video gestopt",
"Photos": "Foto's",
@@ -76,7 +75,6 @@
"StartupEmbyServerIsLoading": "Jellyfin Server is aan het laden, probeer het later opnieuw.",
"SubtitleDownloadFailureForItem": "Downloaden van ondertiteling voor {0} is mislukt",
"SubtitleDownloadFailureFromForItem": "Ondertitels konden niet gedownload worden van {0} voor {1}",
- "SubtitlesDownloadedForItem": "Ondertiteling voor {0} is gedownload",
"Sync": "Synchronisatie",
"System": "Systeem",
"TvShows": "TV-series",
@@ -89,9 +87,38 @@
"UserOnlineFromDevice": "{0} heeft verbinding met {1}",
"UserPasswordChangedWithName": "Wachtwoord voor {0} is gewijzigd",
"UserPolicyUpdatedWithName": "Gebruikersbeleid gewijzigd voor {0}",
- "UserStartedPlayingItemWithValues": "{0} heeft afspelen van {1} gestart op {2}",
+ "UserStartedPlayingItemWithValues": "{0} speelt {1} af op {2}",
"UserStoppedPlayingItemWithValues": "{0} heeft afspelen van {1} gestopt op {2}",
"ValueHasBeenAddedToLibrary": "{0} is toegevoegd aan je mediabibliotheek",
"ValueSpecialEpisodeName": "Speciaal - {0}",
- "VersionNumber": "Versie {0}"
+ "VersionNumber": "Versie {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Zoekt op het internet naar missende ondertiteling gebaseerd op metadata configuratie.",
+ "TaskDownloadMissingSubtitles": "Download missende ondertiteling",
+ "TaskRefreshChannelsDescription": "Vernieuwt informatie van internet kanalen.",
+ "TaskRefreshChannels": "Vernieuw Kanalen",
+ "TaskCleanTranscodeDescription": "Verwijdert transcode bestanden ouder dan 1 dag.",
+ "TaskCleanLogs": "Log Folder Opschonen",
+ "TaskCleanTranscode": "Transcode Folder Opschonen",
+ "TaskUpdatePluginsDescription": "Download en installeert updates voor plugins waar automatisch updaten aan staat.",
+ "TaskUpdatePlugins": "Update Plugins",
+ "TaskRefreshPeopleDescription": "Update metadata for acteurs en regisseurs in de media bibliotheek.",
+ "TaskRefreshPeople": "Vernieuw Personen",
+ "TaskCleanLogsDescription": "Verwijdert log bestanden ouder dan {0} dagen.",
+ "TaskRefreshLibraryDescription": "Scant de media bibliotheek voor nieuwe bestanden en vernieuwt de metadata.",
+ "TaskRefreshLibrary": "Scan Media Bibliotheek",
+ "TaskRefreshChapterImagesDescription": "Maakt thumbnails aan voor videos met hoofdstukken.",
+ "TaskRefreshChapterImages": "Hoofdstukafbeeldingen Uitpakken",
+ "TaskCleanCacheDescription": "Verwijdert gecachte bestanden die het systeem niet langer nodig heeft.",
+ "TaskCleanCache": "Cache Folder Opschonen",
+ "TasksChannelsCategory": "Internet Kanalen",
+ "TasksApplicationCategory": "Applicatie",
+ "TasksLibraryCategory": "Bibliotheek",
+ "TasksMaintenanceCategory": "Onderhoud",
+ "TaskCleanActivityLogDescription": "Verwijdert activiteiten logs ouder dan de ingestelde tijd.",
+ "TaskCleanActivityLog": "Leeg activiteiten logboek",
+ "Undefined": "Niet gedefinieerd",
+ "Forced": "Geforceerd",
+ "Default": "Standaard",
+ "TaskOptimizeDatabaseDescription": "Comprimeert de database en trimt vrije ruimte. Het uitvoeren van deze taak kan de prestaties verbeteren, na het scannen van de bibliotheek of andere aanpassingen die invloed hebben op de database.",
+ "TaskOptimizeDatabase": "Database optimaliseren"
}
diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json
new file mode 100644
index 000000000..32d4f3a8b
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/nn.json
@@ -0,0 +1,121 @@
+{
+ "MessageServerConfigurationUpdated": "Tenarkonfigurasjonen har blitt oppdatert",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Tenar konfigurasjon seksjon {0} har blitt oppdatert",
+ "MessageApplicationUpdatedTo": "Jellyfin-tenaren har blitt oppdatert til {0}",
+ "MessageApplicationUpdated": "Jellyfin-tenaren har blitt oppdatert",
+ "Latest": "Nyaste",
+ "LabelRunningTimeValue": "Speletid: {0}",
+ "LabelIpAddressValue": "IP-adresse: {0}",
+ "ItemRemovedWithName": "{0} vart fjerna frå biblioteket",
+ "ItemAddedWithName": "{0} vart lagt til i biblioteket",
+ "Inherit": "Arve",
+ "HomeVideos": "Heimevideoar",
+ "HeaderRecordingGroups": "Innspelingsgrupper",
+ "HeaderNextUp": "Neste",
+ "HeaderLiveTV": "Direkte TV",
+ "HeaderFavoriteSongs": "Favorittsongar",
+ "HeaderFavoriteShows": "Favorittseriar",
+ "HeaderFavoriteEpisodes": "Favorittepisodar",
+ "HeaderFavoriteArtists": "Favorittartistar",
+ "HeaderFavoriteAlbums": "Favorittalbum",
+ "HeaderContinueWatching": "Fortsett å sjå",
+ "HeaderAlbumArtists": "Albumartist",
+ "Genres": "Sjangrar",
+ "Folders": "Mapper",
+ "Favorites": "Favorittar",
+ "FailedLoginAttemptWithUserName": "Mislukka påloggingsforsøk frå {0}",
+ "DeviceOnlineWithName": "{0} er tilkopla",
+ "DeviceOfflineWithName": "{0} har kopla frå",
+ "Collections": "Samlingar",
+ "ChapterNameValue": "Kapittel {0}",
+ "Channels": "Kanalar",
+ "CameraImageUploadedFrom": "Eit nytt kamerabilete har blitt lasta opp frå {0}",
+ "Books": "Bøker",
+ "AuthenticationSucceededWithUserName": "{0} har logga inn",
+ "Artists": "Artistar",
+ "Application": "Program",
+ "AppDeviceValues": "App: {0}, Eining: {1}",
+ "Albums": "Album",
+ "NotificationOptionServerRestartRequired": "Tenaren krev omstart",
+ "NotificationOptionPluginUpdateInstalled": "Programvaretilleggoppdatering vart installert",
+ "NotificationOptionPluginUninstalled": "Programvaretillegg avinstallert",
+ "NotificationOptionPluginInstalled": "Programvaretillegg installert",
+ "NotificationOptionPluginError": "Programvaretillegg feila",
+ "NotificationOptionNewLibraryContent": "Nytt innhald er lagt til",
+ "NotificationOptionInstallationFailed": "Installasjonsfeil",
+ "NotificationOptionCameraImageUploaded": "Kamerabilde vart lasta opp",
+ "NotificationOptionAudioPlaybackStopped": "Lydavspilling stoppa",
+ "NotificationOptionAudioPlayback": "Lydavspilling påbyrja",
+ "NotificationOptionApplicationUpdateInstalled": "Applikasjonsoppdatering er installert",
+ "NotificationOptionApplicationUpdateAvailable": "Applikasjonsoppdatering er tilgjengeleg",
+ "NewVersionIsAvailable": "Ein ny versjon av Jellyfin-tjenaren er tilgjengeleg for nedlasting.",
+ "NameSeasonUnknown": "Ukjend sesong",
+ "NameSeasonNumber": "Sesong {0}",
+ "NameInstallFailed": "Installasjonen av {0} feila",
+ "MusicVideos": "Musikkvideoar",
+ "Music": "Musikk",
+ "Movies": "Filmar",
+ "MixedContent": "Blanda innhald",
+ "Sync": "Synkroniser",
+ "TaskDownloadMissingSubtitlesDescription": "Søk Internettet for manglande undertekstar basert på metadatainnstillingar.",
+ "TaskDownloadMissingSubtitles": "Last ned manglande undertekstar",
+ "TaskRefreshChannelsDescription": "Oppdater internettkanalinformasjon.",
+ "TaskRefreshChannels": "Oppdater kanalar",
+ "TaskCleanTranscodeDescription": "Slett transkodefiler som er meir enn ein dag gammal.",
+ "TaskCleanTranscode": "Fjern transkodemappe",
+ "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringar for programtillegg som er sette opp til å oppdaterast automatisk.",
+ "TaskUpdatePlugins": "Oppdaterer programvaretillegg",
+ "TaskRefreshPeopleDescription": "Oppdaterer metadata for skodespelarar og regissørar i mediebiblioteket ditt.",
+ "TaskRefreshPeople": "Oppdater personar",
+ "TaskCleanLogsDescription": "Slett loggfiler som er meir enn {0} dagar gamle.",
+ "TaskCleanLogs": "Slett loggmappa",
+ "TaskRefreshLibraryDescription": "Skannar mediebiblioteket ditt for nye filer og oppdaterer metadata.",
+ "TaskRefreshLibrary": "Skann mediebibliotek",
+ "TaskRefreshChapterImagesDescription": "Lager miniatyrbilete for videoar som har kapittel.",
+ "TaskRefreshChapterImages": "Trekk ut kapittelbilete",
+ "TaskCleanCacheDescription": "Sletter mellomlagra filer som ikkje lengre trengst av systemet.",
+ "TaskCleanCache": "Fjern hurtigbuffer",
+ "TasksChannelsCategory": "Internettkanalar",
+ "TasksApplicationCategory": "Applikasjon",
+ "TasksLibraryCategory": "Bibliotek",
+ "TasksMaintenanceCategory": "Vedlikehald",
+ "VersionNumber": "Versjon {0}",
+ "ValueSpecialEpisodeName": "Spesialepisode - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} har blitt lagt til i mediebiblioteket ditt",
+ "UserStoppedPlayingItemWithValues": "{0} har fullført avspeling {1} på {2}",
+ "UserStartedPlayingItemWithValues": "{0} spelar {1} på {2}",
+ "UserPolicyUpdatedWithName": "Brukarreglar har blitt oppdatert for {0}",
+ "UserPasswordChangedWithName": "Passordet for {0} er oppdatert",
+ "UserOnlineFromDevice": "{0} er direktekopla frå {1}",
+ "UserOfflineFromDevice": "{0} har kopla frå {1}",
+ "UserLockedOutWithName": "Brukar {0} har blitt utestengd",
+ "UserDownloadingItemWithValues": "{0} lastar ned {1}",
+ "UserDeletedWithName": "Brukar {0} er sletta",
+ "UserCreatedWithName": "Brukar {0} er oppretta",
+ "User": "Brukar",
+ "TvShows": "TV-seriar",
+ "System": "System",
+ "SubtitleDownloadFailureFromForItem": "Feila å laste ned undertekstar frå {0} for {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin-tenaren laster. Prøv igjen seinare.",
+ "Songs": "Sangar",
+ "Shows": "Seriar",
+ "ServerNameNeedsToBeRestarted": "{0} må omstartast",
+ "ScheduledTaskStartedWithName": "{0} starta",
+ "ScheduledTaskFailedWithName": "{0} feila",
+ "ProviderValue": "Leverandør: {0}",
+ "PluginUpdatedWithName": "{0} blei oppdatert",
+ "PluginUninstalledWithName": "{0} blei avinstallert",
+ "PluginInstalledWithName": "{0} blei installert",
+ "Plugin": "Programvaretillegg",
+ "Playlists": "Spelelister",
+ "Photos": "Bilete",
+ "NotificationOptionVideoPlaybackStopped": "Videoavspeling stoppa",
+ "NotificationOptionVideoPlayback": "Videoavspeling starta",
+ "NotificationOptionUserLockedOut": "Brukar er utestengd",
+ "NotificationOptionTaskFailed": "Planlagt oppgåve feila",
+ "TaskCleanActivityLogDescription": "Sletter aktivitetslogginnlegg som er eldre enn den konfigurerte alderen.",
+ "TaskCleanActivityLog": "Slett aktivitetslogg",
+ "Undefined": "Udefinert",
+ "Forced": "Tvungen",
+ "Default": "Standard"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/pa.json b/Emby.Server.Implementations/Localization/Core/pa.json
new file mode 100644
index 000000000..d1db09232
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/pa.json
@@ -0,0 +1,121 @@
+{
+ "TaskRefreshChapterImages": "ਐਕਸਟਰੈਕਟ ਚੈਪਟਰ ਚਿੱਤਰ",
+ "TaskDownloadMissingSubtitlesDescription": "ਮੈਟਾਡੇਟਾ ਕੌਂਫਿਗਰੇਸ਼ਨ ਦੇ ਅਧਾਰ ਤੇ ਗਾਇਬ ਉਪਸਿਰਲੇਖਾਂ ਲਈ ਇੰਟਰਨੈਟ ਦੀ ਭਾਲ ਕਰਦਾ ਹੈ.",
+ "TaskDownloadMissingSubtitles": "ਗਾਇਬ ਉਪਸਿਰਲੇਖ ਡਾ Download ਨਲੋਡ ਕਰੋ",
+ "TaskRefreshChannelsDescription": "ਇੰਟਰਨੈੱਟ ਚੈਨਲ ਦੀ ਜਾਣਕਾਰੀ ਨੂੰ ਤਾਜ਼ਾ ਕਰਦਾ ਹੈ.",
+ "TaskRefreshChannels": "ਚੈਨਲਾਂ ਨੂੰ ਤਾਜ਼ਾ ਕਰੋ",
+ "TaskCleanTranscodeDescription": "ਇੱਕ ਦਿਨ ਤੋਂ ਵੱਧ ਪੁਰਾਣੀ ਟ੍ਰਾਂਸਕੋਡ ਫਾਈਲਾਂ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ.",
+ "TaskCleanTranscode": "ਕਲੀਨ ਟ੍ਰਾਂਸਕੋਡ ਡਾਇਰੈਕਟਰੀ",
+ "TaskUpdatePluginsDescription": "ਪਲਗਇੰਸਾਂ ਲਈ ਡਾਉਨਲੋਡ ਅਤੇ ਸਥਾਪਨਾ ਅਪਡੇਟਾਂ ਜੋ ਆਪਣੇ ਆਪ ਅਪਡੇਟ ਕਰਨ ਲਈ ਕੌਂਫਿਗਰ ਕੀਤੀਆਂ ਜਾਂਦੀਆਂ ਹਨ.",
+ "TaskUpdatePlugins": "ਪਲੱਗਇਨ ਅਪਡੇਟ ਕਰੋ",
+ "TaskRefreshPeopleDescription": "ਤੁਹਾਡੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਅਦਾਕਾਰਾਂ ਅਤੇ ਨਿਰਦੇਸ਼ਕਾਂ ਲਈ ਮੈਟਾਡੇਟਾ ਨੂੰ ਅਪਡੇਟ ਕਰਦਾ ਹੈ.",
+ "TaskRefreshPeople": "ਲੋਕਾਂ ਨੂੰ ਤਾਜ਼ਾ ਕਰੋ",
+ "TaskCleanLogsDescription": "ਲੌਗ ਫਾਈਲਾਂ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ ਜੋ {0} ਦਿਨਾਂ ਤੋਂ ਵੱਧ ਪੁਰਾਣੀਆਂ ਹਨ.",
+ "TaskCleanLogs": "ਕਲੀਨ ਲਾਗ ਡਾਇਰੈਕਟਰੀ",
+ "TaskRefreshLibraryDescription": "ਨਵੀਆਂ ਫਾਈਲਾਂ ਲਈ ਆਪਣੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਨੂੰ ਸਕੈਨ ਕਰਦਾ ਹੈ ਅਤੇ ਮੈਟਾਡੇਟਾ ਨੂੰ ਤਾਜ਼ਾ ਕਰਦਾ ਹੈ.",
+ "TaskRefreshLibrary": "ਸਕੈਨ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ",
+ "TaskRefreshChapterImagesDescription": "ਚੈਪਟਰਾਂ ਵਾਲੇ ਵੀਡੀਓ ਲਈ ਥੰਬਨੇਲ ਬਣਾਉਂਦੇ ਹਨ.",
+ "TaskCleanCacheDescription": "ਸਿਸਟਮ ਦੁਆਰਾ ਹੁਣ ਕੈਚੇ ਫਾਈਲਾਂ ਦੀ ਜਰੂਰਤ ਨਹੀਂ ਹੈ.",
+ "TaskCleanCache": "ਸਾਫ਼ ਕੈਸ਼ ਡਾਇਰੈਕਟਰੀ",
+ "TaskCleanActivityLogDescription": "ਕੌਂਫਿਗਰ ਕੀਤੀ ਉਮਰ ਤੋਂ ਪੁਰਾਣੀ ਗਤੀਵਿਧੀ ਲੌਗ ਐਂਟਰੀਜ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ.",
+ "TaskCleanActivityLog": "ਸਾਫ਼ ਗਤੀਵਿਧੀ ਲਾਗ",
+ "TasksChannelsCategory": "ਇੰਟਰਨੈੱਟ ਚੈਨਲ",
+ "TasksApplicationCategory": "ਐਪਲੀਕੇਸ਼ਨ",
+ "TasksLibraryCategory": "ਲਾਇਬ੍ਰੇਰੀ",
+ "TasksMaintenanceCategory": "ਰੱਖ-ਰਖਾਅ",
+ "VersionNumber": "ਵਰਜਨ {0}",
+ "ValueSpecialEpisodeName": "ਵਿਸ਼ੇਸ਼ - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} ਤੁਹਾਡੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ ਹੈ",
+ "UserStoppedPlayingItemWithValues": "{0} ਨੇ {2} 'ਤੇ {1} ਖੇਡਣਾ ਪੂਰਾ ਕਰ ਲਿਆ ਹੈ",
+ "UserStartedPlayingItemWithValues": "{0} {2} 'ਤੇ {1} ਖੇਡ ਰਿਹਾ ਹੈ",
+ "UserPolicyUpdatedWithName": "ਉਪਭੋਗਤਾ ਨੀਤੀ ਨੂੰ {0} ਲਈ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ",
+ "UserPasswordChangedWithName": "ਪਾਸਵਰਡ ਯੂਜ਼ਰ ਲਈ ਬਦਲਿਆ ਗਿਆ ਹੈ {0}",
+ "UserOnlineFromDevice": "{0} ਤੋਂ isਨਲਾਈਨ ਹੈ {1}",
+ "UserOfflineFromDevice": "{0} ਤੋਂ ਡਿਸਕਨੈਕਟ ਹੋ ਗਿਆ ਹੈ {1}",
+ "UserLockedOutWithName": "ਯੂਜ਼ਰ {0} ਨੂੰ ਲਾਕ ਆਉਟ ਕਰ ਦਿੱਤਾ ਗਿਆ ਹੈ",
+ "UserDownloadingItemWithValues": "{0} ਡਾ{ਨਲੋਡ ਕਰ ਰਿਹਾ ਹੈ {1}",
+ "UserDeletedWithName": "ਯੂਜ਼ਰ {0} ਨੂੰ ਮਿਟਾ ਦਿੱਤਾ ਗਿਆ ਹੈ",
+ "UserCreatedWithName": "ਯੂਜ਼ਰ {0} ਬਣਾਇਆ ਗਿਆ ਹੈ",
+ "User": "ਯੂਜ਼ਰ",
+ "Undefined": "ਪਰਿਭਾਸ਼ਤ",
+ "TvShows": "ਟੀਵੀ ਸ਼ੋਅਜ਼",
+ "System": "ਸਿਸਟਮ",
+ "Sync": "ਸਿੰਕ",
+ "SubtitleDownloadFailureFromForItem": "ਉਪਸਿਰਲੇਖ {1} ਲਈ {0} ਤੋਂ ਡਾ toਨਲੋਡ ਕਰਨ ਵਿੱਚ ਅਸਫਲ ਰਹੇ",
+ "StartupEmbyServerIsLoading": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਲੋਡ ਹੋ ਰਿਹਾ ਹੈ. ਕਿਰਪਾ ਕਰਕੇ ਜਲਦੀ ਹੀ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ.",
+ "Songs": "ਗਾਣੇ",
+ "Shows": "ਸ਼ੋਅਜ਼",
+ "ServerNameNeedsToBeRestarted": "{0} ਮੁੜ ਚਾਲੂ ਕਰਨ ਦੀ ਲੋੜ ਹੈ",
+ "ScheduledTaskStartedWithName": "{0} ਸ਼ੁਰੂ ਹੋਇਆ",
+ "ScheduledTaskFailedWithName": "{0} ਅਸਫਲ",
+ "ProviderValue": "ਦੇਣ ਵਾਲੇ: {0}",
+ "PluginUpdatedWithName": "{0} ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਸੀ",
+ "PluginUninstalledWithName": "{0} ਅਣਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ ਸੀ",
+ "PluginInstalledWithName": "{0} ਲਗਾਇਆ ਗਿਆ ਸੀ",
+ "Plugin": "ਪਲੱਗਇਨ",
+ "Playlists": "ਪਲੇਲਿਸਟਸ",
+ "Photos": "ਫੋਟੋਆਂ",
+ "NotificationOptionVideoPlaybackStopped": "ਵੀਡੀਓ ਪਲੇਬੈਕ ਰੋਕਿਆ ਗਿਆ",
+ "NotificationOptionVideoPlayback": "ਵੀਡੀਓ ਪਲੇਬੈਕ ਸ਼ੁਰੂ ਹੋਇਆ",
+ "NotificationOptionUserLockedOut": "ਉਪਭੋਗਤਾ ਨੂੰ ਲਾਕ ਆਉਟ ਕੀਤਾ ਗਿਆ",
+ "NotificationOptionTaskFailed": "ਨਿਰਧਾਰਤ ਕਾਰਜ ਅਸਫਲਤਾ",
+ "NotificationOptionServerRestartRequired": "ਸਰਵਰ ਨੂੰ ਮੁੜ ਚਾਲੂ ਕਰਨ ਦੀ ਲੋੜ ਹੈ",
+ "NotificationOptionPluginUpdateInstalled": "ਪਲੱਗਇਨ ਅਪਡੇਟ ਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ",
+ "NotificationOptionPluginUninstalled": "ਪਲੱਗਇਨ ਅਣਇੰਸਟੌਲ ਕੀਤਾ",
+ "NotificationOptionPluginInstalled": "ਪਲੱਗਇਨ ਸਥਾਪਿਤ ਕੀਤਾ",
+ "NotificationOptionPluginError": "ਪਲੱਗਇਨ ਅਸਫਲ",
+ "NotificationOptionNewLibraryContent": "ਨਵੀਂ ਸਮੱਗਰੀ ਸ਼ਾਮਲ ਕੀਤੀ ਗਈ",
+ "NotificationOptionInstallationFailed": "ਇੰਸਟਾਲੇਸ਼ਨ ਅਸਫਲ",
+ "NotificationOptionCameraImageUploaded": "ਕੈਮਰਾ ਤਸਵੀਰ ਅਪਲੋਡ ਕੀਤੀ ਗਈ",
+ "NotificationOptionAudioPlaybackStopped": "ਆਡੀਓ ਪਲੇਅਬੈਕ ਰੋਕਿਆ ਗਿਆ",
+ "NotificationOptionAudioPlayback": "ਆਡੀਓ ਪਲੇਅਬੈਕ ਸ਼ੁਰੂ ਹੋਇਆ",
+ "NotificationOptionApplicationUpdateInstalled": "ਐਪਲੀਕੇਸ਼ਨ ਅਪਡੇਟ ਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ",
+ "NotificationOptionApplicationUpdateAvailable": "ਐਪਲੀਕੇਸ਼ਨ ਅਪਡੇਟ ਉਪਲਬਧ ਹੈ",
+ "NewVersionIsAvailable": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਦਾ ਨਵਾਂ ਸੰਸਕਰਣ ਡਾਉਨਲੋਡ ਲਈ ਉਪਲਬਧ ਹੈ.",
+ "NameSeasonUnknown": "ਸੀਜ਼ਨ ਅਣਜਾਣ",
+ "NameSeasonNumber": "ਸੀਜ਼ਨ {0}",
+ "NameInstallFailed": "{0} ਇੰਸਟਾਲੇਸ਼ਨ ਫੇਲ੍ਹ ਹੋਈ",
+ "MusicVideos": "ਸੰਗੀਤ ਵੀਡੀਓ",
+ "Music": "ਸੰਗੀਤ",
+ "Movies": "ਫਿਲਮਾਂ",
+ "MixedContent": "ਮਿਸ਼ਰਤ ਸਮੱਗਰੀ",
+ "MessageServerConfigurationUpdated": "ਸਰਵਰ ਕੌਂਫਿਗਰੇਸ਼ਨ ਨੂੰ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ",
+ "MessageNamedServerConfigurationUpdatedWithValue": "ਸਰਵਰ ਕੌਂਫਿਗਰੇਸ਼ਨ ਸੈਕਸ਼ਨ {0} ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ",
+ "MessageApplicationUpdatedTo": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਨੂੰ ਅੱਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ {0}",
+ "MessageApplicationUpdated": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ",
+ "Latest": "ਤਾਜ਼ਾ",
+ "LabelRunningTimeValue": "ਚੱਲਦਾ ਸਮਾਂ: {0}",
+ "LabelIpAddressValue": "IP ਪਤਾ: {0}",
+ "ItemRemovedWithName": "{0} ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚੋਂ ਹਟਾ ਦਿੱਤਾ ਗਿਆ ਸੀ",
+ "ItemAddedWithName": "{0} ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ ਸੀ",
+ "Inherit": "ਵਿਰਾਸਤ",
+ "HomeVideos": "ਘਰੇਲੂ ਵੀਡੀਓ",
+ "HeaderRecordingGroups": "ਰਿਕਾਰਡਿੰਗ ਸਮੂਹ",
+ "HeaderNextUp": "ਅੱਗੇ",
+ "HeaderLiveTV": "ਲਾਈਵ ਟੀ",
+ "HeaderFavoriteSongs": "ਮਨਪਸੰਦ ਗਾਣੇ",
+ "HeaderFavoriteShows": "ਮਨਪਸੰਦ ਸ਼ੋਅ",
+ "HeaderFavoriteEpisodes": "ਮਨਪਸੰਦ ਐਪੀਸੋਡ",
+ "HeaderFavoriteArtists": "ਮਨਪਸੰਦ ਕਲਾਕਾਰ",
+ "HeaderFavoriteAlbums": "ਮਨਪਸੰਦ ਐਲਬਮ",
+ "HeaderContinueWatching": "ਵੇਖਣਾ ਜਾਰੀ ਰੱਖੋ",
+ "HeaderAlbumArtists": "ਐਲਬਮ ਕਲਾਕਾਰ",
+ "Genres": "ਸ਼ੈਲੀਆਂ",
+ "Forced": "ਮਜਬੂਰ",
+ "Folders": "ਫੋਲਡਰ",
+ "Favorites": "ਮਨਪਸੰਦ",
+ "FailedLoginAttemptWithUserName": "ਤੋਂ ਲਾਗਇਨ ਕੋਸ਼ਿਸ਼ ਫੇਲ ਹੋਈ {0}",
+ "DeviceOnlineWithName": "{0} ਜੁੜਿਆ ਹੋਇਆ ਹੈ",
+ "DeviceOfflineWithName": "{0} ਡਿਸਕਨੈਕਟ ਹੋ ਗਿਆ ਹੈ",
+ "Default": "ਮੂਲ",
+ "Collections": "ਸੰਗ੍ਰਹਿ",
+ "ChapterNameValue": "ਅਧਿਆਇ {0}",
+ "Channels": "ਚੈਨਲ",
+ "CameraImageUploadedFrom": "ਤੋਂ ਇੱਕ ਨਵਾਂ ਕੈਮਰਾ ਚਿੱਤਰ ਅਪਲੋਡ ਕੀਤਾ ਗਿਆ ਹੈ {0}",
+ "Books": "ਕਿਤਾਬਾਂ",
+ "AuthenticationSucceededWithUserName": "{0} ਸਫਲਤਾਪੂਰਕ ਪ੍ਰਮਾਣਿਤ",
+ "Artists": "ਕਲਾਕਾਰ",
+ "Application": "ਐਪਲੀਕੇਸ਼ਨ",
+ "AppDeviceValues": "ਐਪ: {0}, ਜੰਤਰ: {1}",
+ "Albums": "ਐਲਬਮਾਂ"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/pl.json b/Emby.Server.Implementations/Localization/Core/pl.json
index 92b12409d..e8a32a13e 100644
--- a/Emby.Server.Implementations/Localization/Core/pl.json
+++ b/Emby.Server.Implementations/Localization/Core/pl.json
@@ -15,18 +15,17 @@
"Favorites": "Ulubione",
"Folders": "Foldery",
"Genres": "Gatunki",
- "HeaderAlbumArtists": "Wykonawcy albumów",
- "HeaderCameraUploads": "Przekazane obrazy",
+ "HeaderAlbumArtists": "Album artysty",
"HeaderContinueWatching": "Kontynuuj odtwarzanie",
- "HeaderFavoriteAlbums": "Albumy ulubione",
- "HeaderFavoriteArtists": "Wykonawcy ulubieni",
- "HeaderFavoriteEpisodes": "Odcinki ulubione",
- "HeaderFavoriteShows": "Seriale ulubione",
- "HeaderFavoriteSongs": "Utwory ulubione",
+ "HeaderFavoriteAlbums": "Ulubione albumy",
+ "HeaderFavoriteArtists": "Ulubieni wykonawcy",
+ "HeaderFavoriteEpisodes": "Ulubione odcinki",
+ "HeaderFavoriteShows": "Ulubione seriale",
+ "HeaderFavoriteSongs": "Ulubione utwory",
"HeaderLiveTV": "Telewizja",
"HeaderNextUp": "Do obejrzenia",
"HeaderRecordingGroups": "Grupy nagrań",
- "HomeVideos": "Nagrania prywatne",
+ "HomeVideos": "Nagrania domowe",
"Inherit": "Dziedzicz",
"ItemAddedWithName": "{0} zostało dodane do biblioteki",
"ItemRemovedWithName": "{0} zostało usunięte z biblioteki",
@@ -41,26 +40,26 @@
"Movies": "Filmy",
"Music": "Muzyka",
"MusicVideos": "Teledyski",
- "NameInstallFailed": "Instalacja {0} nieudana.",
+ "NameInstallFailed": "Instalacja {0} nieudana",
"NameSeasonNumber": "Sezon {0}",
- "NameSeasonUnknown": "Sezon nieznany",
+ "NameSeasonUnknown": "Nieznany sezon",
"NewVersionIsAvailable": "Nowa wersja serwera Jellyfin jest dostępna do pobrania.",
"NotificationOptionApplicationUpdateAvailable": "Dostępna aktualizacja aplikacji",
- "NotificationOptionApplicationUpdateInstalled": "Zainstalowano aktualizację aplikacji",
+ "NotificationOptionApplicationUpdateInstalled": "Zaktualizowano aplikację",
"NotificationOptionAudioPlayback": "Rozpoczęto odtwarzanie muzyki",
"NotificationOptionAudioPlaybackStopped": "Odtwarzane dźwięku zatrzymane",
- "NotificationOptionCameraImageUploaded": "Przekazano obraz z urządzenia mobilnego",
- "NotificationOptionInstallationFailed": "Niepowodzenie instalacji",
+ "NotificationOptionCameraImageUploaded": "Przekazano obraz z urządzenia przenośnego",
+ "NotificationOptionInstallationFailed": "Nieudana instalacja",
"NotificationOptionNewLibraryContent": "Dodano nową zawartość",
"NotificationOptionPluginError": "Awaria wtyczki",
"NotificationOptionPluginInstalled": "Zainstalowano wtyczkę",
"NotificationOptionPluginUninstalled": "Odinstalowano wtyczkę",
- "NotificationOptionPluginUpdateInstalled": "Zainstalowano aktualizację wtyczki",
+ "NotificationOptionPluginUpdateInstalled": "Zaktualizowano wtyczkę",
"NotificationOptionServerRestartRequired": "Wymagane ponowne uruchomienie serwera",
"NotificationOptionTaskFailed": "Awaria zaplanowanego zadania",
"NotificationOptionUserLockedOut": "Użytkownik zablokowany",
"NotificationOptionVideoPlayback": "Rozpoczęto odtwarzanie wideo",
- "NotificationOptionVideoPlaybackStopped": "Odtwarzanie wideo zatrzymane",
+ "NotificationOptionVideoPlaybackStopped": "Zatrzymano odtwarzanie wideo",
"Photos": "Zdjęcia",
"Playlists": "Listy odtwarzania",
"Plugin": "Wtyczka",
@@ -73,10 +72,9 @@
"ServerNameNeedsToBeRestarted": "{0} wymaga ponownego uruchomienia",
"Shows": "Seriale",
"Songs": "Utwory",
- "StartupEmbyServerIsLoading": "Twa wczytywanie serwera Jellyfin. Spróbuj ponownie za chwilę.",
+ "StartupEmbyServerIsLoading": "Trwa wczytywanie serwera Jellyfin. Spróbuj ponownie za chwilę.",
"SubtitleDownloadFailureForItem": "Pobieranie napisów dla {0} zakończone niepowodzeniem",
"SubtitleDownloadFailureFromForItem": "Nieudane pobieranie napisów z {0} dla {1}",
- "SubtitlesDownloadedForItem": "Pobrano napisy dla {0}",
"Sync": "Synchronizacja",
"System": "System",
"TvShows": "Seriale",
@@ -91,7 +89,36 @@
"UserPolicyUpdatedWithName": "Zmieniono zasady użytkowania dla {0}",
"UserStartedPlayingItemWithValues": "{0} odtwarza {1} na {2}",
"UserStoppedPlayingItemWithValues": "{0} zakończył odtwarzanie {1} na {2}",
- "ValueHasBeenAddedToLibrary": "{0} został dodany to biblioteki mediów",
+ "ValueHasBeenAddedToLibrary": "{0} został dodany do biblioteki mediów",
"ValueSpecialEpisodeName": "Specjalne - {0}",
- "VersionNumber": "Wersja {0}"
+ "VersionNumber": "Wersja {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Przeszukuje internet w poszukiwaniu brakujących napisów w oparciu o konfigurację metadanych.",
+ "TaskDownloadMissingSubtitles": "Pobierz brakujące napisy",
+ "TaskRefreshChannelsDescription": "Odświeża informacje o kanałach internetowych.",
+ "TaskRefreshChannels": "Odśwież kanały",
+ "TaskCleanTranscodeDescription": "Usuwa transkodowane pliki starsze niż 1 dzień.",
+ "TaskCleanTranscode": "Wyczyść folder transkodowania",
+ "TaskUpdatePluginsDescription": "Pobiera i instaluje aktualizacje dla pluginów które są skonfigurowane do automatycznej aktualizacji.",
+ "TaskUpdatePlugins": "Aktualizuj pluginy",
+ "TaskRefreshPeopleDescription": "Odświeża metadane o aktorów i reżyserów w Twojej bibliotece mediów.",
+ "TaskRefreshPeople": "Odśwież obsadę",
+ "TaskCleanLogsDescription": "Kasuje pliki logów starsze niż {0} dni.",
+ "TaskCleanLogs": "Wyczyść folder logów",
+ "TaskRefreshLibraryDescription": "Skanuje Twoją bibliotekę mediów dla nowych plików i odświeżenia metadanych.",
+ "TaskRefreshLibrary": "Skanuj bibliotekę mediów",
+ "TaskRefreshChapterImagesDescription": "Tworzy miniatury dla filmów posiadających rozdziały.",
+ "TaskRefreshChapterImages": "Wydobądź grafiki rozdziałów",
+ "TaskCleanCacheDescription": "Usuwa niepotrzebne i przestarzałe pliki cache.",
+ "TaskCleanCache": "Wyczyść folder Cache",
+ "TasksChannelsCategory": "Kanały internetowe",
+ "TasksApplicationCategory": "Aplikacja",
+ "TasksLibraryCategory": "Biblioteka",
+ "TasksMaintenanceCategory": "Konserwacja",
+ "TaskCleanActivityLogDescription": "Usuwa wpisy dziennika aktywności starsze niż skonfigurowany wiek.",
+ "TaskCleanActivityLog": "Czyść dziennik aktywności",
+ "Undefined": "Nieustalony",
+ "Forced": "Wymuszony",
+ "Default": "Domyślne",
+ "TaskOptimizeDatabase": "Optymalizuj bazę danych",
+ "TaskOptimizeDatabaseDescription": "Kompaktuje bazę danych i obcina wolne miejsce. Uruchomienie tego zadania po przeskanowaniu biblioteki lub dokonaniu innych zmian, które pociągają za sobą modyfikacje bazy danych, może poprawić wydajność."
}
diff --git a/Emby.Server.Implementations/Localization/Core/pr.json b/Emby.Server.Implementations/Localization/Core/pr.json
new file mode 100644
index 000000000..e3a3bfaf1
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/pr.json
@@ -0,0 +1,5 @@
+{
+ "Books": "Libros",
+ "AuthenticationSucceededWithUserName": "{0} autentificado correctamente",
+ "Artists": "Artistas"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/pt-BR.json b/Emby.Server.Implementations/Localization/Core/pt-BR.json
index aaedf0850..be71289b1 100644
--- a/Emby.Server.Implementations/Localization/Core/pt-BR.json
+++ b/Emby.Server.Implementations/Localization/Core/pt-BR.json
@@ -5,51 +5,50 @@
"Artists": "Artistas",
"AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
"Books": "Livros",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Uma nova imagem da câmera foi enviada de {0}",
"Channels": "Canais",
"ChapterNameValue": "Capítulo {0}",
"Collections": "Coletâneas",
"DeviceOfflineWithName": "{0} se desconectou",
- "DeviceOnlineWithName": "{0} está conectado",
+ "DeviceOnlineWithName": "{0} se conectou",
"FailedLoginAttemptWithUserName": "Falha na tentativa de login de {0}",
"Favorites": "Favoritos",
"Folders": "Pastas",
"Genres": "Gêneros",
"HeaderAlbumArtists": "Artistas do Álbum",
- "HeaderCameraUploads": "Uploads da Câmera",
- "HeaderContinueWatching": "Continuar Assistindo",
+ "HeaderContinueWatching": "Continuar assistindo",
"HeaderFavoriteAlbums": "Álbuns Favoritos",
- "HeaderFavoriteArtists": "Artistas Favoritos",
- "HeaderFavoriteEpisodes": "Episódios Favoritos",
- "HeaderFavoriteShows": "Séries Favoritas",
- "HeaderFavoriteSongs": "Músicas Favoritas",
+ "HeaderFavoriteArtists": "Artistas favoritos",
+ "HeaderFavoriteEpisodes": "Episódios favoritos",
+ "HeaderFavoriteShows": "Séries favoritas",
+ "HeaderFavoriteSongs": "Músicas favoritas",
"HeaderLiveTV": "TV ao Vivo",
- "HeaderNextUp": "Próximos",
+ "HeaderNextUp": "A Seguir",
"HeaderRecordingGroups": "Grupos de Gravação",
"HomeVideos": "Vídeos caseiros",
"Inherit": "Herdar",
"ItemAddedWithName": "{0} foi adicionado à biblioteca",
"ItemRemovedWithName": "{0} foi removido da biblioteca",
- "LabelIpAddressValue": "Endereço ip: {0}",
+ "LabelIpAddressValue": "Endereço IP: {0}",
"LabelRunningTimeValue": "Tempo de execução: {0}",
- "Latest": "Recente",
- "MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "Latest": "Recentes",
+ "MessageApplicationUpdated": "Servidor Jellyfin atualizado",
+ "MessageApplicationUpdatedTo": "Servidor Jellyfin atualizado para {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "A seção {0} da configuração do servidor foi atualizada",
"MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
"MixedContent": "Conteúdo misto",
"Movies": "Filmes",
"Music": "Música",
- "MusicVideos": "Vídeos musicais",
- "NameInstallFailed": "{0} installation failed",
+ "MusicVideos": "Videoclipes",
+ "NameInstallFailed": "A instalação de {0} falhou",
"NameSeasonNumber": "Temporada {0}",
"NameSeasonUnknown": "Temporada Desconhecida",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Atualização de aplicativo disponível",
- "NotificationOptionApplicationUpdateInstalled": "Atualização de aplicativo instalada",
+ "NewVersionIsAvailable": "Uma nova versão do Servidor Jellyfin está disponível para download.",
+ "NotificationOptionApplicationUpdateAvailable": "Atualização do aplicativo disponível",
+ "NotificationOptionApplicationUpdateInstalled": "Atualização do aplicativo instalada",
"NotificationOptionAudioPlayback": "Reprodução de áudio iniciada",
"NotificationOptionAudioPlaybackStopped": "Reprodução de áudio parada",
- "NotificationOptionCameraImageUploaded": "Imagem de câmera enviada",
+ "NotificationOptionCameraImageUploaded": "Imagem da câmera enviada",
"NotificationOptionInstallationFailed": "Falha na instalação",
"NotificationOptionNewLibraryContent": "Novo conteúdo adicionado",
"NotificationOptionPluginError": "Falha de plugin",
@@ -70,28 +69,56 @@
"ProviderValue": "Provedor: {0}",
"ScheduledTaskFailedWithName": "{0} falhou",
"ScheduledTaskStartedWithName": "{0} iniciada",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "ServerNameNeedsToBeRestarted": "O servidor {0} precisa ser reiniciado",
"Shows": "Séries",
"Songs": "Músicas",
- "StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor tente novamente em breve.",
+ "StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor, tente novamente mais tarde.",
"SubtitleDownloadFailureForItem": "Download de legendas falhou para {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Legendas baixadas para {0}",
+ "SubtitleDownloadFailureFromForItem": "Houve um problema ao baixar as legendas de {0} para {1}",
"Sync": "Sincronizar",
"System": "Sistema",
- "TvShows": "Séries de TV",
+ "TvShows": "Séries",
"User": "Usuário",
"UserCreatedWithName": "O usuário {0} foi criado",
"UserDeletedWithName": "O usuário {0} foi excluído",
"UserDownloadingItemWithValues": "{0} está baixando {1}",
"UserLockedOutWithName": "Usuário {0} foi bloqueado",
"UserOfflineFromDevice": "{0} se desconectou de {1}",
- "UserOnlineFromDevice": "{0} está ativo em {1}",
+ "UserOnlineFromDevice": "{0} está online em {1}",
"UserPasswordChangedWithName": "A senha foi alterada para o usuário {0}",
"UserPolicyUpdatedWithName": "A política de usuário foi atualizada para {0}",
- "UserStartedPlayingItemWithValues": "{0} iniciou a reprodução de {1}",
- "UserStoppedPlayingItemWithValues": "{0} parou de reproduzir {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserStartedPlayingItemWithValues": "{0} está reproduzindo {1} em {2}",
+ "UserStoppedPlayingItemWithValues": "{0} parou de reproduzir {1} em {2}",
+ "ValueHasBeenAddedToLibrary": "{0} foi adicionado à sua biblioteca de mídia",
"ValueSpecialEpisodeName": "Especial - {0}",
- "VersionNumber": "Versão {0}"
+ "VersionNumber": "Versão {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Procurar na internet por legendas faltando baseado na configuração de metadados.",
+ "TaskDownloadMissingSubtitles": "Baixar legendas que estão faltando",
+ "TaskRefreshChannelsDescription": "Atualizar informação de canais da internet .",
+ "TaskRefreshChannels": "Atualizar Canais",
+ "TaskCleanTranscodeDescription": "Deletar arquivos de transcodificação com mais de um dia de criação.",
+ "TaskCleanTranscode": "Limpar pasta de transcodificação",
+ "TaskUpdatePluginsDescription": "Baixa e instala atualizações para plugins que estão configurados para atualizar automaticamente.",
+ "TaskUpdatePlugins": "Atualizar Plugins",
+ "TaskRefreshPeopleDescription": "Atualiza metadados para atores e diretores na sua biblioteca de mídia.",
+ "TaskRefreshPeople": "Atualizar pessoas",
+ "TaskCleanLogsDescription": "Deletar arquivos temporários com mais de {0} dias.",
+ "TaskCleanLogs": "Limpar pasta de logs",
+ "TaskRefreshLibraryDescription": "Escaneie a sua biblioteca de mídia para arquivos novos e atualize os metadados.",
+ "TaskRefreshLibrary": "Escanear a Biblioteca de Mídia",
+ "TaskRefreshChapterImagesDescription": "Criar miniaturas para vídeos que tem capítulos.",
+ "TaskRefreshChapterImages": "Extrair imagens dos capítulos",
+ "TaskCleanCacheDescription": "Deletar arquivos temporários que não são mais necessários para o sistema.",
+ "TaskCleanCache": "Limpar Arquivos Temporários",
+ "TasksChannelsCategory": "Canais da Internet",
+ "TasksApplicationCategory": "Aplicativo",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Manutenção",
+ "TaskCleanActivityLogDescription": "Apaga o registro de atividades mais antigo que a idade configurada.",
+ "TaskCleanActivityLog": "Limpar Registro de Atividades",
+ "Undefined": "Indefinido",
+ "Forced": "Forçado",
+ "Default": "Padrão",
+ "TaskOptimizeDatabaseDescription": "Compactar base de dados e liberar espaço livre. Executar esta tarefa após realizar mudanças que impliquem em modificações da base de dados pode trazer melhorias de desempenho.",
+ "TaskOptimizeDatabase": "Otimizar base de dados"
}
diff --git a/Emby.Server.Implementations/Localization/Core/pt-PT.json b/Emby.Server.Implementations/Localization/Core/pt-PT.json
index dc69d8af2..8c41edf96 100644
--- a/Emby.Server.Implementations/Localization/Core/pt-PT.json
+++ b/Emby.Server.Implementations/Localization/Core/pt-PT.json
@@ -1,97 +1,122 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
+ "Albums": "Álbuns",
+ "AppDeviceValues": "Aplicação {0}, Dispositivo: {1}",
"Application": "Aplicação",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continuar a ver",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
+ "Artists": "Artistas",
+ "AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
+ "Books": "Livros",
+ "CameraImageUploadedFrom": "Uma nova imagem de câmara foi enviada a partir de {0}",
+ "Channels": "Canais",
+ "ChapterNameValue": "Capítulo {0}",
+ "Collections": "Coleções",
+ "DeviceOfflineWithName": "{0} desligou-se",
+ "DeviceOnlineWithName": "{0} ligou-se",
+ "FailedLoginAttemptWithUserName": "Tentativa de login falhada a partir de {0}",
+ "Favorites": "Favoritos",
+ "Folders": "Pastas",
+ "Genres": "Géneros",
+ "HeaderAlbumArtists": "Artistas do Álbum",
+ "HeaderContinueWatching": "Continuar a Ver",
+ "HeaderFavoriteAlbums": "Álbuns Favoritos",
+ "HeaderFavoriteArtists": "Artistas Favoritos",
+ "HeaderFavoriteEpisodes": "Episódios Favoritos",
"HeaderFavoriteShows": "Séries Favoritas",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
+ "HeaderFavoriteSongs": "Músicas Favoritas",
+ "HeaderLiveTV": "TV em Direto",
+ "HeaderNextUp": "A Seguir",
+ "HeaderRecordingGroups": "Grupos de Gravação",
+ "HomeVideos": "Vídeos Caseiros",
+ "Inherit": "Herdar",
+ "ItemAddedWithName": "{0} foi adicionado à biblioteca",
+ "ItemRemovedWithName": "{0} foi removido da biblioteca",
+ "LabelIpAddressValue": "Endereço IP: {0}",
+ "LabelRunningTimeValue": "Duração: {0}",
+ "Latest": "Mais Recente",
+ "MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
+ "MessageApplicationUpdatedTo": "O servidor Jellyfin foi atualizado para a versão {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Configurações de servidor na secção {0} foram atualizadas",
+ "MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
+ "MixedContent": "Conteúdo Misto",
+ "Movies": "Filmes",
+ "Music": "Música",
+ "MusicVideos": "Videoclips",
+ "NameInstallFailed": "{0} falha na instalação",
+ "NameSeasonNumber": "Temporada {0}",
+ "NameSeasonUnknown": "Temporada Desconhecida",
+ "NewVersionIsAvailable": "Está disponível para transferência uma nova versão do servidor Jellyfin.",
+ "NotificationOptionApplicationUpdateAvailable": "Atualização de aplicação disponível",
+ "NotificationOptionApplicationUpdateInstalled": "Atualização de aplicação instalada",
+ "NotificationOptionAudioPlayback": "Reprodução Iniciada",
+ "NotificationOptionAudioPlaybackStopped": "Reprodução Parada",
+ "NotificationOptionCameraImageUploaded": "Imagem da câmara enviada",
+ "NotificationOptionInstallationFailed": "Falha na instalação",
+ "NotificationOptionNewLibraryContent": "Novo conteúdo adicionado",
+ "NotificationOptionPluginError": "Falha na extensão",
+ "NotificationOptionPluginInstalled": "Extensão instalada",
+ "NotificationOptionPluginUninstalled": "Extensão desinstalada",
+ "NotificationOptionPluginUpdateInstalled": "Extensão atualizada",
+ "NotificationOptionServerRestartRequired": "Necessário reiniciar o servidor",
+ "NotificationOptionTaskFailed": "Falha em tarefa agendada",
+ "NotificationOptionUserLockedOut": "Utilizador bloqueado",
+ "NotificationOptionVideoPlayback": "Reprodução do vídeo iniciada",
+ "NotificationOptionVideoPlaybackStopped": "Reprodução do vídeo parada",
+ "Photos": "Fotografias",
+ "Playlists": "Listas de Reprodução",
+ "Plugin": "Extensão",
+ "PluginInstalledWithName": "{0} foi instalado",
+ "PluginUninstalledWithName": "{0} foi desinstalado",
+ "PluginUpdatedWithName": "{0} foi atualizado",
"ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "ScheduledTaskFailedWithName": "{0} falhou",
+ "ScheduledTaskStartedWithName": "{0} iniciou",
+ "ServerNameNeedsToBeRestarted": "{0} necessita de ser reiniciado",
+ "Shows": "Séries",
+ "Songs": "Músicas",
+ "StartupEmbyServerIsLoading": "O servidor Jellyfin está a iniciar. Tente novamente mais tarde.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Especial - {0}",
- "VersionNumber": "Version {0}"
+ "SubtitleDownloadFailureFromForItem": "Falha na transferência de legendas a partir de {0} para {1}",
+ "Sync": "Sincronização",
+ "System": "Sistema",
+ "TvShows": "Programas TV",
+ "User": "Utilizador",
+ "UserCreatedWithName": "Utilizador {0} criado",
+ "UserDeletedWithName": "Utilizador {0} apagado",
+ "UserDownloadingItemWithValues": "{0} está a transferir {1}",
+ "UserLockedOutWithName": "Utilizador {0} bloqueado",
+ "UserOfflineFromDevice": "{0} desligou-se a partir de {1}",
+ "UserOnlineFromDevice": "{0} ligou-se a partir de {1}",
+ "UserPasswordChangedWithName": "Palavra-passe alterada para o utilizador {0}",
+ "UserPolicyUpdatedWithName": "Política de utilizador alterada para {0}",
+ "UserStartedPlayingItemWithValues": "{0} está a reproduzir {1} em {2}",
+ "UserStoppedPlayingItemWithValues": "{0} terminou a reprodução de {1} em {2}",
+ "ValueHasBeenAddedToLibrary": "{0} foi adicionado à sua biblioteca multimédia",
+ "ValueSpecialEpisodeName": "Especial - {0}",
+ "VersionNumber": "Versão {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Procurar na internet por legendas em falta baseado na configuração de metadados.",
+ "TaskDownloadMissingSubtitles": "Fazer download de legendas em falta",
+ "TaskRefreshChannelsDescription": "Atualizar informação sobre canais da Internet.",
+ "TaskRefreshChannels": "Atualizar Canais",
+ "TaskCleanTranscodeDescription": "Apagar ficheiros de transcode com mais de um dia.",
+ "TaskCleanTranscode": "Limpar a Diretoria de Transcode",
+ "TaskUpdatePluginsDescription": "Faz o download e instala updates para os plugins que estão configurados para atualizar automaticamente.",
+ "TaskUpdatePlugins": "Atualizar Plugins",
+ "TaskRefreshPeopleDescription": "Atualizar metadados para atores e diretores na biblioteca.",
+ "TaskRefreshPeople": "Atualizar Pessoas",
+ "TaskCleanLogsDescription": "Apagar ficheiros de log que têm mais de {0} dias.",
+ "TaskCleanLogs": "Limpar a Diretoria de Logs",
+ "TaskRefreshLibraryDescription": "Scannear a biblioteca de música para novos ficheiros e atualizar os metadados.",
+ "TaskRefreshLibrary": "Scannear Biblioteca de Música",
+ "TaskRefreshChapterImagesDescription": "Criar thumbnails para os vídeos que têm capítulos.",
+ "TaskRefreshChapterImages": "Extrair Imagens dos Capítulos",
+ "TaskCleanCacheDescription": "Apagar ficheiros em cache que já não são necessários.",
+ "TaskCleanCache": "Limpar Cache",
+ "TasksChannelsCategory": "Canais da Internet",
+ "TasksApplicationCategory": "Aplicação",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Manutenção",
+ "TaskCleanActivityLogDescription": "Apaga as entradas do registo de atividade anteriores à data configurada.",
+ "TaskCleanActivityLog": "Limpar registo de atividade",
+ "Undefined": "Indefinido",
+ "Forced": "Forçado",
+ "Default": "Padrão"
}
diff --git a/Emby.Server.Implementations/Localization/Core/pt.json b/Emby.Server.Implementations/Localization/Core/pt.json
new file mode 100644
index 000000000..a9dbd53ea
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/pt.json
@@ -0,0 +1,123 @@
+{
+ "HeaderLiveTV": "TV Ao Vivo",
+ "Collections": "Coleções",
+ "Books": "Livros",
+ "Artists": "Artistas",
+ "Albums": "Álbuns",
+ "HeaderNextUp": "A Seguir",
+ "HeaderFavoriteSongs": "Músicas Favoritas",
+ "HeaderFavoriteArtists": "Artistas Favoritos",
+ "HeaderFavoriteAlbums": "Álbuns Favoritos",
+ "HeaderFavoriteEpisodes": "Episódios Favoritos",
+ "HeaderFavoriteShows": "Séries Favoritas",
+ "HeaderContinueWatching": "Continuar assistindo",
+ "HeaderAlbumArtists": "Artistas do Álbum",
+ "Genres": "Gêneros",
+ "Folders": "Diretórios",
+ "Favorites": "Favoritos",
+ "Channels": "Canais",
+ "UserDownloadingItemWithValues": "{0} está sendo baixado {1}",
+ "VersionNumber": "Versão {0}",
+ "ValueHasBeenAddedToLibrary": "{0} foi adicionado à sua biblioteca multimédia",
+ "UserStoppedPlayingItemWithValues": "{0} terminou a reprodução de {1} em {2}",
+ "UserStartedPlayingItemWithValues": "{0} está reproduzindo {1} em {2}",
+ "UserPolicyUpdatedWithName": "A política do usuário {0} foi alterada",
+ "UserPasswordChangedWithName": "A senha do usuário {0} foi alterada",
+ "UserOnlineFromDevice": "{0} está online a partir de {1}",
+ "UserOfflineFromDevice": "{0} desconectou-se a partir de {1}",
+ "UserLockedOutWithName": "O usuário {0} foi bloqueado",
+ "UserDeletedWithName": "O usuário {0} foi removido",
+ "UserCreatedWithName": "O usuário {0} foi criado",
+ "User": "Usuário",
+ "TvShows": "Séries",
+ "System": "Sistema",
+ "SubtitleDownloadFailureFromForItem": "Falha na transferência de legendas de {0} para {1}",
+ "StartupEmbyServerIsLoading": "O servidor Jellyfin está iniciando. Tente novamente dentro de momentos.",
+ "ServerNameNeedsToBeRestarted": "{0} necessita ser reiniciado",
+ "ScheduledTaskStartedWithName": "{0} iniciou",
+ "ScheduledTaskFailedWithName": "{0} falhou",
+ "ProviderValue": "Fornecedor: {0}",
+ "PluginUpdatedWithName": "{0} foi atualizado",
+ "PluginUninstalledWithName": "{0} foi desinstalado",
+ "PluginInstalledWithName": "{0} foi instalado",
+ "Plugin": "Plugin",
+ "NotificationOptionVideoPlaybackStopped": "Reprodução de vídeo parada",
+ "NotificationOptionVideoPlayback": "Reprodução de vídeo iniciada",
+ "NotificationOptionUserLockedOut": "Usuário bloqueado",
+ "NotificationOptionTaskFailed": "Falha na tarefa agendada",
+ "NotificationOptionServerRestartRequired": "É necessário reiniciar o servidor",
+ "NotificationOptionPluginUpdateInstalled": "Plugin atualizado",
+ "NotificationOptionPluginUninstalled": "Plugin desinstalado",
+ "NotificationOptionPluginInstalled": "Plugin instalado",
+ "NotificationOptionPluginError": "Falha no plugin",
+ "NotificationOptionNewLibraryContent": "Novo conteúdo adicionado",
+ "NotificationOptionInstallationFailed": "Falha de instalação",
+ "NotificationOptionCameraImageUploaded": "Imagem de câmera enviada",
+ "NotificationOptionAudioPlaybackStopped": "Reprodução Parada",
+ "NotificationOptionAudioPlayback": "Reprodução Iniciada",
+ "NotificationOptionApplicationUpdateInstalled": "A atualização do aplicativo foi instalada",
+ "NotificationOptionApplicationUpdateAvailable": "Uma atualização do aplicativo está disponível",
+ "NewVersionIsAvailable": "Uma nova versão do servidor Jellyfin está disponível para download.",
+ "NameSeasonUnknown": "Temporada Desconhecida",
+ "NameSeasonNumber": "Temporada {0}",
+ "NameInstallFailed": "Falha na instalação de {0}",
+ "MusicVideos": "Videoclipes",
+ "Music": "Música",
+ "MixedContent": "Conteúdo diverso",
+ "MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
+ "MessageNamedServerConfigurationUpdatedWithValue": "As configurações do servidor na seção {0} foram atualizadas",
+ "MessageApplicationUpdatedTo": "O servidor Jellyfin foi atualizado para a versão {0}",
+ "MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
+ "Latest": "Mais Recente",
+ "LabelRunningTimeValue": "Duração: {0}",
+ "LabelIpAddressValue": "Endereço de IP: {0}",
+ "ItemRemovedWithName": "{0} foi removido da biblioteca",
+ "ItemAddedWithName": "{0} foi adicionado à biblioteca",
+ "Inherit": "Herdar",
+ "HomeVideos": "Vídeos principais",
+ "HeaderRecordingGroups": "Grupos de Gravação",
+ "ValueSpecialEpisodeName": "Episódio Especial - {0}",
+ "Sync": "Sincronização",
+ "Songs": "Músicas",
+ "Shows": "Séries",
+ "Playlists": "Listas de Reprodução",
+ "Photos": "Fotografias",
+ "Movies": "Filmes",
+ "FailedLoginAttemptWithUserName": "Tentativa falha de login a partir de {0}",
+ "DeviceOnlineWithName": "{0} está conectado",
+ "DeviceOfflineWithName": "{0} desconectou-se",
+ "ChapterNameValue": "Capítulo {0}",
+ "CameraImageUploadedFrom": "Uma nova imagem da câmara foi enviada a partir de {0}",
+ "AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
+ "Application": "Aplicativo",
+ "AppDeviceValues": "Aplicativo {0}, Dispositivo: {1}",
+ "TaskCleanCache": "Limpar Diretório de Cache",
+ "TasksApplicationCategory": "Aplicativo",
+ "TasksLibraryCategory": "Biblioteca",
+ "TasksMaintenanceCategory": "Manutenção",
+ "TaskRefreshChannels": "Atualizar Canais",
+ "TaskUpdatePlugins": "Atualizar Plugins",
+ "TaskCleanLogsDescription": "Deletar arquivos de log que existe a mais de {0} dias.",
+ "TaskCleanLogs": "Limpar diretório de logs",
+ "TaskRefreshLibrary": "Escanear biblioteca de mídias",
+ "TaskRefreshChapterImagesDescription": "Cria miniaturas para vídeos que têm capítulos.",
+ "TaskCleanCacheDescription": "Apaga ficheiros em cache que já não são usados pelo sistema.",
+ "TasksChannelsCategory": "Canais de Internet",
+ "TaskRefreshChapterImages": "Extrair Imagens do Capítulo",
+ "TaskDownloadMissingSubtitlesDescription": "Pesquisa na Internet as legendas em falta com base na configuração de metadados.",
+ "TaskDownloadMissingSubtitles": "Download das legendas em falta",
+ "TaskRefreshChannelsDescription": "Atualiza as informações do canal da Internet.",
+ "TaskCleanTranscodeDescription": "Apagar os ficheiros com mais de um dia, de Transcode.",
+ "TaskCleanTranscode": "Limpar o diretório de Transcode",
+ "TaskUpdatePluginsDescription": "Baixa e instala as atualizações para plug-ins configurados para atualização automática.",
+ "TaskRefreshPeopleDescription": "Atualiza os metadados para atores e diretores na tua biblioteca de media.",
+ "TaskRefreshPeople": "Atualizar pessoas",
+ "TaskRefreshLibraryDescription": "Pesquisa sua biblioteca de media por novos arquivos e atualiza os metadados.",
+ "TaskCleanActivityLog": "Limpar registro de atividade",
+ "Undefined": "Indefinido",
+ "Forced": "Forçado",
+ "Default": "Predefinição",
+ "TaskCleanActivityLogDescription": "Apaga itens no registro com idade acima do que é configurado.",
+ "TaskOptimizeDatabase": "Otimizar base de dados",
+ "TaskOptimizeDatabaseDescription": "Base de dados compacta e corta espaço livre. A execução desta tarefa depois de digitalizar a biblioteca ou de fazer outras alterações que impliquem modificações na base de dados pode melhorar o desempenho."
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json
new file mode 100644
index 000000000..510aac11c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ro.json
@@ -0,0 +1,121 @@
+{
+ "HeaderNextUp": "Urmează",
+ "VersionNumber": "Versiunea {0}",
+ "ValueSpecialEpisodeName": "Special - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} a fost adăugat la biblioteca multimedia",
+ "UserStoppedPlayingItemWithValues": "{0} a terminat rularea {1} pe {2}",
+ "UserStartedPlayingItemWithValues": "{0} ruleaza {1} pe {2}",
+ "UserPolicyUpdatedWithName": "Politica utilizatorului {0} a fost actualizată",
+ "UserPasswordChangedWithName": "Parola utilizatorului {0} a fost schimbată",
+ "UserOnlineFromDevice": "{0} este conectat de la {1}",
+ "UserOfflineFromDevice": "{0} s-a deconectat de la {1}",
+ "UserLockedOutWithName": "Utilizatorul {0} a fost blocat",
+ "UserDownloadingItemWithValues": "{0} descarcă {1}",
+ "UserDeletedWithName": "Utilizatorul {0} a fost eliminat",
+ "UserCreatedWithName": "Utilizatorul {0} a fost creat",
+ "User": "Utilizator",
+ "TvShows": "Spectacole TV",
+ "System": "Sistem",
+ "Sync": "Sincronizare",
+ "SubtitleDownloadFailureFromForItem": "Subtitrările nu au putut fi descărcate de la {0} pentru {1}",
+ "StartupEmbyServerIsLoading": "Se încarcă serverul Jellyfin. Încercați din nou în scurt timp.",
+ "Songs": "Melodii",
+ "Shows": "Spectacole",
+ "ServerNameNeedsToBeRestarted": "{0} trebuie repornit",
+ "ScheduledTaskStartedWithName": "{0} pornit/ă",
+ "ScheduledTaskFailedWithName": "{0} eșuat/ă",
+ "ProviderValue": "Furnizor: {0}",
+ "PluginUpdatedWithName": "{0} a fost actualizat/ă",
+ "PluginUninstalledWithName": "{0} a fost dezinstalat",
+ "PluginInstalledWithName": "{0} a fost instalat",
+ "Plugin": "Complement",
+ "Playlists": "Liste redare",
+ "Photos": "Fotografii",
+ "NotificationOptionVideoPlaybackStopped": "Redarea video oprită",
+ "NotificationOptionVideoPlayback": "Începută redarea video",
+ "NotificationOptionUserLockedOut": "Utilizatorul a fost blocat",
+ "NotificationOptionTaskFailed": "Activitate programata eșuată",
+ "NotificationOptionServerRestartRequired": "Este necesară repornirea Serverului",
+ "NotificationOptionPluginUpdateInstalled": "Actualizare plugin instalată",
+ "NotificationOptionPluginUninstalled": "Plugin dezinstalat",
+ "NotificationOptionPluginInstalled": "Plugin instalat",
+ "NotificationOptionPluginError": "Plugin-ul a eșuat",
+ "NotificationOptionNewLibraryContent": "Adăugat conținut nou",
+ "NotificationOptionInstallationFailed": "Eșec la instalare",
+ "NotificationOptionCameraImageUploaded": "Încarcată imagine cameră",
+ "NotificationOptionAudioPlaybackStopped": "Redare audio oprită",
+ "NotificationOptionAudioPlayback": "A inceput redarea audio",
+ "NotificationOptionApplicationUpdateInstalled": "Actualizarea aplicației a fost instalată",
+ "NotificationOptionApplicationUpdateAvailable": "Disponibilă o actualizare a aplicației",
+ "NewVersionIsAvailable": "O nouă versiune a Jellyfin Server este disponibilă pentru descărcare.",
+ "NameSeasonUnknown": "Sezon Necunoscut",
+ "NameSeasonNumber": "Sezonul {0}",
+ "NameInstallFailed": "{0} instalare eșuată",
+ "MusicVideos": "Videoclipuri muzicale",
+ "Music": "Muzică",
+ "Movies": "Filme",
+ "MixedContent": "Conținut mixt",
+ "MessageServerConfigurationUpdated": "Configurația serverului a fost actualizată",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Secțiunea de configurare a serverului {0} a fost acualizata",
+ "MessageApplicationUpdatedTo": "Jellyfin Server a fost actualizat la {0}",
+ "MessageApplicationUpdated": "Jellyfin Server a fost actualizat",
+ "Latest": "Cele mai recente",
+ "LabelRunningTimeValue": "Durată: {0}",
+ "LabelIpAddressValue": "Adresa IP: {0}",
+ "ItemRemovedWithName": "{0} a fost eliminat din bibliotecă",
+ "ItemAddedWithName": "{0} a fost adăugat în bibliotecă",
+ "Inherit": "Moștenit",
+ "HomeVideos": "Filme personale",
+ "HeaderRecordingGroups": "Grupuri de înregistrare",
+ "HeaderLiveTV": "TV în Direct",
+ "HeaderFavoriteSongs": "Melodii Favorite",
+ "HeaderFavoriteShows": "Spectacole Favorite",
+ "HeaderFavoriteEpisodes": "Episoade Favorite",
+ "HeaderFavoriteArtists": "Artiști Favoriți",
+ "HeaderFavoriteAlbums": "Albume Favorite",
+ "HeaderContinueWatching": "Vizionează în continuare",
+ "HeaderAlbumArtists": "Album Artiști",
+ "Genres": "Genuri",
+ "Folders": "Dosare",
+ "Favorites": "Favorite",
+ "FailedLoginAttemptWithUserName": "Încercare de conectare nereușită de la {0}",
+ "DeviceOnlineWithName": "{0} este conectat",
+ "DeviceOfflineWithName": "{0} s-a deconectat",
+ "Collections": "Colecții",
+ "ChapterNameValue": "Capitol {0}",
+ "Channels": "Canale",
+ "CameraImageUploadedFrom": "O nouă fotografie a fost încărcată din {0}",
+ "Books": "Cărți",
+ "AuthenticationSucceededWithUserName": "{0} autentificare reușită",
+ "Artists": "Artiști",
+ "Application": "Aplicație",
+ "AppDeviceValues": "Aplicație: {0}, Dispozitiv: {1}",
+ "Albums": "Albume",
+ "TaskDownloadMissingSubtitlesDescription": "Caută pe internet subtitrările lipsă pe baza configurației metadatelor.",
+ "TaskDownloadMissingSubtitles": "Descarcă subtitrările lipsă",
+ "TaskRefreshChannelsDescription": "Actualizează informațiile despre canalul de internet.",
+ "TaskRefreshChannels": "Actualizează canale",
+ "TaskCleanTranscodeDescription": "Șterge fișierele de transcodare mai vechi de o zi.",
+ "TaskCleanTranscode": "Curățați directorul de transcodare",
+ "TaskUpdatePluginsDescription": "Descarcă și instalează actualizări pentru pluginuri care sunt configurate să se actualizeze automat.",
+ "TaskUpdatePlugins": "Actualizați plugin-uri",
+ "TaskRefreshPeopleDescription": "Actualizează metadatele pentru actori și regizori din biblioteca media.",
+ "TaskRefreshPeople": "Actualizează oamenii",
+ "TaskCleanLogsDescription": "Șterge fișierele jurnal care au mai mult de {0} zile.",
+ "TaskCleanLogs": "Curățare director jurnal",
+ "TaskRefreshLibraryDescription": "Scanează biblioteca media pentru fișiere noi și reîmprospătează metadatele.",
+ "TaskRefreshLibrary": "Scanează Biblioteca Media",
+ "TaskRefreshChapterImagesDescription": "Creează miniaturi pentru videourile care au capitole.",
+ "TaskRefreshChapterImages": "Extrage Imaginile de Capitol",
+ "TaskCleanCacheDescription": "Șterge fișierele cache care nu mai sunt necesare sistemului.",
+ "TaskCleanCache": "Curățați directorul cache",
+ "TasksChannelsCategory": "Canale de pe Internet",
+ "TasksApplicationCategory": "Aplicație",
+ "TasksLibraryCategory": "Librărie",
+ "TasksMaintenanceCategory": "Mentenanță",
+ "TaskCleanActivityLogDescription": "Șterge intrările din jurnalul de activitate mai vechi de data configurată.",
+ "TaskCleanActivityLog": "Curăță Jurnalul de Activitate",
+ "Undefined": "Nedefinit",
+ "Forced": "Forțat",
+ "Default": "Implicit"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json
index c0465def8..cd016b51b 100644
--- a/Emby.Server.Implementations/Localization/Core/ru.json
+++ b/Emby.Server.Implementations/Localization/Core/ru.json
@@ -1,42 +1,41 @@
{
"Albums": "Альбомы",
- "AppDeviceValues": "Прил.: {0}, Устр.: {1}",
+ "AppDeviceValues": "Приложение.: {0}, Устройство.: {1}",
"Application": "Приложение",
"Artists": "Исполнители",
"AuthenticationSucceededWithUserName": "{0} - авторизация успешна",
- "Books": "Литература",
- "CameraImageUploadedFrom": "Новое фото было выложено с камеры {0}",
+ "Books": "Книги",
+ "CameraImageUploadedFrom": "Новое фото загружено с камеры {0}",
"Channels": "Каналы",
"ChapterNameValue": "Сцена {0}",
"Collections": "Коллекции",
- "DeviceOfflineWithName": "{0} - подкл. разъ-но",
- "DeviceOnlineWithName": "{0} - подкл. уст-но",
+ "DeviceOfflineWithName": "{0} - отключено",
+ "DeviceOnlineWithName": "{0} - подключено",
"FailedLoginAttemptWithUserName": "{0} - попытка входа неудачна",
"Favorites": "Избранное",
"Folders": "Папки",
"Genres": "Жанры",
- "HeaderAlbumArtists": "Исп-ли альбома",
- "HeaderCameraUploads": "Камеры",
+ "HeaderAlbumArtists": "Исполнители альбома",
"HeaderContinueWatching": "Продолжение просмотра",
"HeaderFavoriteAlbums": "Избранные альбомы",
"HeaderFavoriteArtists": "Избранные исполнители",
"HeaderFavoriteEpisodes": "Избранные эпизоды",
- "HeaderFavoriteShows": "Избранные передачи",
+ "HeaderFavoriteShows": "Избранные сериалы",
"HeaderFavoriteSongs": "Избранные композиции",
"HeaderLiveTV": "Эфир",
"HeaderNextUp": "Очередное",
"HeaderRecordingGroups": "Группы записей",
- "HomeVideos": "Дом. видео",
+ "HomeVideos": "Домашние видео",
"Inherit": "Наследуемое",
"ItemAddedWithName": "{0} - добавлено в медиатеку",
"ItemRemovedWithName": "{0} - изъято из медиатеки",
"LabelIpAddressValue": "IP-адрес: {0}",
"LabelRunningTimeValue": "Длительность: {0}",
- "Latest": "Новейшее",
+ "Latest": "Последнее",
"MessageApplicationUpdated": "Jellyfin Server был обновлён",
"MessageApplicationUpdatedTo": "Jellyfin Server был обновлён до {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Конфиг-ия сервера (раздел {0}) была обновлена",
- "MessageServerConfigurationUpdated": "Конфиг-ия сервера была обновлена",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Конфигурация сервера (раздел {0}) была обновлена",
+ "MessageServerConfigurationUpdated": "Конфигурация сервера была обновлена",
"MixedContent": "Смешанное содержимое",
"Movies": "Кино",
"Music": "Музыка",
@@ -47,9 +46,9 @@
"NewVersionIsAvailable": "Новая версия Jellyfin Server доступна для загрузки.",
"NotificationOptionApplicationUpdateAvailable": "Имеется обновление приложения",
"NotificationOptionApplicationUpdateInstalled": "Обновление приложения установлено",
- "NotificationOptionAudioPlayback": "Воспр-ие аудио зап-но",
- "NotificationOptionAudioPlaybackStopped": "Восп-ие аудио ост-но",
- "NotificationOptionCameraImageUploaded": "Произведена выкладка отснятого с камеры",
+ "NotificationOptionAudioPlayback": "Воспроизведение аудио запущено",
+ "NotificationOptionAudioPlaybackStopped": "Воспроизведение аудио остановлено",
+ "NotificationOptionCameraImageUploaded": "Изображения с камеры загружены",
"NotificationOptionInstallationFailed": "Сбой установки",
"NotificationOptionNewLibraryContent": "Новое содержание добавлено",
"NotificationOptionPluginError": "Сбой плагина",
@@ -59,8 +58,8 @@
"NotificationOptionServerRestartRequired": "Требуется перезапуск сервера",
"NotificationOptionTaskFailed": "Сбой назначенной задачи",
"NotificationOptionUserLockedOut": "Пользователь заблокирован",
- "NotificationOptionVideoPlayback": "Воспр-ие видео зап-но",
- "NotificationOptionVideoPlaybackStopped": "Восп-ие видео ост-но",
+ "NotificationOptionVideoPlayback": "Воспроизведение видео запущено",
+ "NotificationOptionVideoPlaybackStopped": "Воспроизведение видео остановлено",
"Photos": "Фото",
"Playlists": "Плей-листы",
"Plugin": "Плагин",
@@ -76,22 +75,50 @@
"StartupEmbyServerIsLoading": "Jellyfin Server загружается. Повторите попытку в ближайшее время.",
"SubtitleDownloadFailureForItem": "Субтитры к {0} не удалось загрузить",
"SubtitleDownloadFailureFromForItem": "Субтитры к {1} не удалось загрузить с {0}",
- "SubtitlesDownloadedForItem": "Субтитры к {0} загружены",
"Sync": "Синхро",
"System": "Система",
"TvShows": "ТВ",
- "User": "Польз-ль",
+ "User": "Пользователь",
"UserCreatedWithName": "Пользователь {0} был создан",
"UserDeletedWithName": "Пользователь {0} был удалён",
"UserDownloadingItemWithValues": "{0} загружает {1}",
"UserLockedOutWithName": "Пользователь {0} был заблокирован",
- "UserOfflineFromDevice": "{0} - подкл. с {1} разъ-но",
- "UserOnlineFromDevice": "{0} - подкл. с {1} уст-но",
- "UserPasswordChangedWithName": "Пароль польз-ля {0} был изменён",
- "UserPolicyUpdatedWithName": "Польз-ие политики {0} были обновлены",
- "UserStartedPlayingItemWithValues": "{0} - воспр. «{1}» на {2}",
- "UserStoppedPlayingItemWithValues": "{0} - воспр. «{1}» ост-но на {2}",
- "ValueHasBeenAddedToLibrary": "{0} (добавлено в медиатеку)",
+ "UserOfflineFromDevice": "{0} отключился с {1}",
+ "UserOnlineFromDevice": "{0} подключился с {1}",
+ "UserPasswordChangedWithName": "Пароль пользователя {0} был изменён",
+ "UserPolicyUpdatedWithName": "Политики пользователя {0} были обновлены",
+ "UserStartedPlayingItemWithValues": "{0} - воспроизведение «{1}» на {2}",
+ "UserStoppedPlayingItemWithValues": "{0} - воспроизведение остановлено «{1}» на {2}",
+ "ValueHasBeenAddedToLibrary": "{0} добавлено в медиатеку",
"ValueSpecialEpisodeName": "Спецэпизод - {0}",
- "VersionNumber": "Версия {0}"
+ "VersionNumber": "Версия {0}",
+ "TaskDownloadMissingSubtitles": "Загрузка отсутствующих субтитров",
+ "TaskRefreshChannels": "Обновление каналов",
+ "TaskCleanTranscode": "Очистка каталога перекодировки",
+ "TaskUpdatePlugins": "Обновление плагинов",
+ "TaskRefreshPeople": "Подновить людей",
+ "TaskCleanLogs": "Очистка каталога журналов",
+ "TaskRefreshLibrary": "Сканирование медиатеки",
+ "TaskRefreshChapterImages": "Извлечение изображений сцен",
+ "TaskCleanCache": "Очистка каталога кеша",
+ "TasksChannelsCategory": "Интернет-каналы",
+ "TasksApplicationCategory": "Приложение",
+ "TasksLibraryCategory": "Медиатека",
+ "TasksMaintenanceCategory": "Обслуживание",
+ "TaskDownloadMissingSubtitlesDescription": "Выполняется поиск в Интернете отсутствующих субтитров на основе конфигурации метаданных.",
+ "TaskRefreshChannelsDescription": "Обновляются данные интернет-каналов.",
+ "TaskCleanTranscodeDescription": "Удаляются файлы перекодировки старше одного дня.",
+ "TaskUpdatePluginsDescription": "Загружаются и устанавливаются обновления для плагинов, у которых включено автоматическое обновление.",
+ "TaskRefreshPeopleDescription": "Обновляются метаданные для актёров и режиссёров в медиатеке.",
+ "TaskCleanLogsDescription": "Удаляются файлы журнала, возраст которых превышает {0} дн(я/ей).",
+ "TaskRefreshLibraryDescription": "Сканируется медиатека на новые файлы и обновляются метаданные.",
+ "TaskRefreshChapterImagesDescription": "Создаются эскизы для видео, которые содержат сцены.",
+ "TaskCleanCacheDescription": "Удаляются файлы кэша, которые больше не нужны системе.",
+ "TaskCleanActivityLogDescription": "Удаляет записи журнала активности старше установленного возраста.",
+ "TaskCleanActivityLog": "Очистить журнал активности",
+ "Undefined": "Не определено",
+ "Forced": "Форсир-ые",
+ "Default": "По умолчанию",
+ "TaskOptimizeDatabaseDescription": "Сжимает базу данных и обрезает свободное место. Выполнение этой задачи после сканирования библиотеки или внесения других изменений, предполагающих модификации базы данных, может повысить производительность.",
+ "TaskOptimizeDatabase": "Оптимизировать базу данных"
}
diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json
index bc7e7184e..ad90bd813 100644
--- a/Emby.Server.Implementations/Localization/Core/sk.json
+++ b/Emby.Server.Implementations/Localization/Core/sk.json
@@ -2,30 +2,29 @@
"Albums": "Albumy",
"AppDeviceValues": "Aplikácia: {0}, Zariadenie: {1}",
"Application": "Aplikácia",
- "Artists": "Umelci",
+ "Artists": "Interpreti",
"AuthenticationSucceededWithUserName": "{0} úspešne overený",
"Books": "Knihy",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "Z {0} bola nahraná nová fotografia",
"Channels": "Kanály",
"ChapterNameValue": "Kapitola {0}",
- "Collections": "Zbierky",
- "DeviceOfflineWithName": "{0} je odpojený",
+ "Collections": "Kolekcie",
+ "DeviceOfflineWithName": "{0} sa odpojil",
"DeviceOnlineWithName": "{0} je pripojený",
"FailedLoginAttemptWithUserName": "Neúspešný pokus o prihlásenie z {0}",
"Favorites": "Obľúbené",
"Folders": "Priečinky",
"Genres": "Žánre",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Pokračujte v pozeraní",
+ "HeaderAlbumArtists": "Interpreti albumu",
+ "HeaderContinueWatching": "Pokračovať v pozeraní",
"HeaderFavoriteAlbums": "Obľúbené albumy",
- "HeaderFavoriteArtists": "Obľúbení umelci",
+ "HeaderFavoriteArtists": "Obľúbení interpreti",
"HeaderFavoriteEpisodes": "Obľúbené epizódy",
"HeaderFavoriteShows": "Obľúbené seriály",
- "HeaderFavoriteSongs": "Obľúbené pesničky",
+ "HeaderFavoriteSongs": "Obľúbené skladby",
"HeaderLiveTV": "Živá TV",
"HeaderNextUp": "Nasleduje",
- "HeaderRecordingGroups": "Recording Groups",
+ "HeaderRecordingGroups": "Skupiny nahrávok",
"HomeVideos": "Domáce videá",
"Inherit": "Zdediť",
"ItemAddedWithName": "{0} bol pridaný do knižnice",
@@ -34,64 +33,92 @@
"LabelRunningTimeValue": "Dĺžka: {0}",
"Latest": "Najnovšie",
"MessageApplicationUpdated": "Jellyfin Server bol aktualizovaný",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin Server bol aktualizovaný na verziu {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Sekcia {0} konfigurácie servera bola aktualizovaná",
- "MessageServerConfigurationUpdated": "Konfigurácia servera aktualizovaná",
+ "MessageServerConfigurationUpdated": "Konfigurácia servera bola aktualizovaná",
"MixedContent": "Zmiešaný obsah",
"Movies": "Filmy",
"Music": "Hudba",
"MusicVideos": "Hudobné videá",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Sezóna {0}",
- "NameSeasonUnknown": "Neznáma sezóna",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NameInstallFailed": "Inštalácia {0} zlyhala",
+ "NameSeasonNumber": "Séria {0}",
+ "NameSeasonUnknown": "Neznáma séria",
+ "NewVersionIsAvailable": "Nová verzia Jellyfin Serveru je dostupná na stiahnutie.",
"NotificationOptionApplicationUpdateAvailable": "Je dostupná aktualizácia aplikácie",
- "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie nainštalovaná",
- "NotificationOptionAudioPlayback": "Spustené prehrávanie audia",
- "NotificationOptionAudioPlaybackStopped": "Zastavené prehrávanie audia",
- "NotificationOptionCameraImageUploaded": "Nahraný obrázok z fotoaparátu",
+ "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie bola nainštalovaná",
+ "NotificationOptionAudioPlayback": "Prehrávanie zvuku bolo spustené",
+ "NotificationOptionAudioPlaybackStopped": "Prehrávanie zvuku bolo zastavené",
+ "NotificationOptionCameraImageUploaded": "Obrázok z fotoaparátu bol nahraný",
"NotificationOptionInstallationFailed": "Chyba inštalácie",
- "NotificationOptionNewLibraryContent": "Pridaný nový obsah",
- "NotificationOptionPluginError": "Chyba rozšírenia",
- "NotificationOptionPluginInstalled": "Rozšírenie nainštalované",
- "NotificationOptionPluginUninstalled": "Rozšírenie odinštalované",
- "NotificationOptionPluginUpdateInstalled": "Aktualizácia rozšírenia nainštalovaná",
+ "NotificationOptionNewLibraryContent": "Bol pridaný nový obsah",
+ "NotificationOptionPluginError": "Chyba zásuvného modulu",
+ "NotificationOptionPluginInstalled": "Bol nainštalovaný zásuvný modul",
+ "NotificationOptionPluginUninstalled": "Zásuvný modul bol odinštalovaný",
+ "NotificationOptionPluginUpdateInstalled": "Bola nainštalovaná aktualizácia zásuvného modulu",
"NotificationOptionServerRestartRequired": "Vyžaduje sa reštart servera",
"NotificationOptionTaskFailed": "Naplánovaná úloha zlyhala",
- "NotificationOptionUserLockedOut": "User locked out",
+ "NotificationOptionUserLockedOut": "Používateľ je uzamknutý",
"NotificationOptionVideoPlayback": "Spustené prehrávanie videa",
"NotificationOptionVideoPlaybackStopped": "Zastavené prehrávanie videa",
"Photos": "Fotky",
- "Playlists": "Zoznamy skladieb",
- "Plugin": "Rozšírenie",
+ "Playlists": "Playlisty",
+ "Plugin": "Zásuvný modul",
"PluginInstalledWithName": "{0} bol nainštalovaný",
"PluginUninstalledWithName": "{0} bol odinštalovaný",
"PluginUpdatedWithName": "{0} bol aktualizovaný",
"ProviderValue": "Poskytovateľ: {0}",
"ScheduledTaskFailedWithName": "{0} zlyhalo",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Series",
+ "ScheduledTaskStartedWithName": "{0} zahájených",
+ "ServerNameNeedsToBeRestarted": "{0} vyžaduje reštart",
+ "Shows": "Seriály",
"Songs": "Skladby",
- "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Skúste to prosím o chvíľu znova.",
+ "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Prosím, skúste to o chvíľu znova.",
"SubtitleDownloadFailureForItem": "Sťahovanie titulkov pre {0} zlyhalo",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Titulky pre {0} stiahnuté",
- "Sync": "Sync",
+ "SubtitleDownloadFailureFromForItem": "Sťahovanie titulkov z {0} pre {1} zlyhalo",
+ "Sync": "Synchronizácia",
"System": "Systém",
- "TvShows": "TV Shows",
+ "TvShows": "TV seriály",
"User": "Používateľ",
"UserCreatedWithName": "Používateľ {0} bol vytvorený",
"UserDeletedWithName": "Používateľ {0} bol vymazaný",
"UserDownloadingItemWithValues": "{0} sťahuje {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
+ "UserLockedOutWithName": "Používateľ {0} bol vymknutý",
"UserOfflineFromDevice": "{0} sa odpojil od {1}",
"UserOnlineFromDevice": "{0} je online z {1}",
- "UserPasswordChangedWithName": "Heslo používateľa {0} zmenené",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1}",
- "UserStoppedPlayingItemWithValues": "{0} zastavil prehrávanie {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserPasswordChangedWithName": "Heslo používateľa {0} bolo zmenené",
+ "UserPolicyUpdatedWithName": "Používateľské zásady pre {0} boli aktualizované",
+ "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1} na {2}",
+ "UserStoppedPlayingItemWithValues": "{0} ukončil prehrávanie {1} na {2}",
+ "ValueHasBeenAddedToLibrary": "{0} bol pridaný do vašej knižnice médií",
"ValueSpecialEpisodeName": "Špeciál - {0}",
- "VersionNumber": "Verzia {0}"
+ "VersionNumber": "Verzia {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Vyhľadá na internete chýbajúce titulky podľa toho, ako sú nakonfigurované metadáta.",
+ "TaskDownloadMissingSubtitles": "Stiahnuť chýbajúce titulky",
+ "TaskRefreshChannelsDescription": "Obnoví informácie o internetových kanáloch.",
+ "TaskRefreshChannels": "Obnoviť kanály",
+ "TaskCleanTranscodeDescription": "Vymaže prekódované súbory, ktoré sú staršie ako jeden deň.",
+ "TaskCleanTranscode": "Vyčistiť priečinok pre prekódovanie",
+ "TaskUpdatePluginsDescription": "Stiahne a nainštaluje aktualizácie pre zásuvné moduly, ktoré sú nastavené tak, aby sa aktualizovali automaticky.",
+ "TaskUpdatePlugins": "Aktualizovať zásuvné moduly",
+ "TaskRefreshPeopleDescription": "Aktualizuje metadáta pre hercov a režisérov vo vašej mediálnej knižnici.",
+ "TaskRefreshPeople": "Obnoviť osoby",
+ "TaskCleanLogsDescription": "Vymaže log súbory, ktoré sú staršie ako {0} deň/dni/dní.",
+ "TaskCleanLogs": "Vyčistiť priečinok s logmi",
+ "TaskRefreshLibraryDescription": "Hľadá vo vašej mediálnej knižnici nové súbory a obnovuje metadáta.",
+ "TaskRefreshLibrary": "Prehľadávať knižnicu medií",
+ "TaskRefreshChapterImagesDescription": "Vytvorí náhľady pre videá, ktoré majú kapitoly.",
+ "TaskRefreshChapterImages": "Extrahovať obrázky kapitol",
+ "TaskCleanCacheDescription": "Vymaže súbory vyrovnávacej pamäte, ktoré už nie sú potrebné pre systém.",
+ "TaskCleanCache": "Vyčistiť priečinok vyrovnávacej pamäte",
+ "TasksChannelsCategory": "Internetové kanály",
+ "TasksApplicationCategory": "Aplikácia",
+ "TasksLibraryCategory": "Knižnica",
+ "TasksMaintenanceCategory": "Údržba",
+ "TaskCleanActivityLogDescription": "Vymaže záznamy aktivít v logu, ktoré sú staršie ako zadaná doba.",
+ "TaskCleanActivityLog": "Vyčistiť log aktivít",
+ "Undefined": "Nedefinované",
+ "Forced": "Vynútené",
+ "Default": "Predvolené",
+ "TaskOptimizeDatabaseDescription": "Zmenší databázu a odstráni prázdne miesto. Spustenie tejto úlohy po skenovaní knižnice alebo po iných zmenách zahŕňajúcich úpravy databáze môže zlepšiť výkon.",
+ "TaskOptimizeDatabase": "Optimalizovať databázu"
}
diff --git a/Emby.Server.Implementations/Localization/Core/sl-SI.json b/Emby.Server.Implementations/Localization/Core/sl-SI.json
index e850257d4..a6fcbd3e2 100644
--- a/Emby.Server.Implementations/Localization/Core/sl-SI.json
+++ b/Emby.Server.Implementations/Localization/Core/sl-SI.json
@@ -1,97 +1,124 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "Albums": "Albumi",
+ "AppDeviceValues": "Aplikacija: {0}, Naprava: {1}",
+ "Application": "Aplikacija",
+ "Artists": "Izvajalci",
+ "AuthenticationSucceededWithUserName": "{0} se je uspešno prijavil",
+ "Books": "Knjige",
+ "CameraImageUploadedFrom": "Nova fotografija je bila naložena iz {0}",
+ "Channels": "Kanali",
+ "ChapterNameValue": "Poglavje {0}",
+ "Collections": "Zbirke",
+ "DeviceOfflineWithName": "{0} je prekinil povezavo",
+ "DeviceOnlineWithName": "{0} je povezan",
+ "FailedLoginAttemptWithUserName": "Neuspešen poskus prijave iz {0}",
+ "Favorites": "Priljubljeno",
+ "Folders": "Mape",
+ "Genres": "Zvrsti",
+ "HeaderAlbumArtists": "Izvajalci albuma",
+ "HeaderContinueWatching": "Nadaljuj ogled",
+ "HeaderFavoriteAlbums": "Priljubljeni albumi",
+ "HeaderFavoriteArtists": "Priljubljeni izvajalci",
+ "HeaderFavoriteEpisodes": "Priljubljene epizode",
+ "HeaderFavoriteShows": "Priljubljene serije",
+ "HeaderFavoriteSongs": "Priljubljene pesmi",
+ "HeaderLiveTV": "TV v živo",
+ "HeaderNextUp": "Sledi",
+ "HeaderRecordingGroups": "Zbirke posnetkov",
+ "HomeVideos": "Domači posnetki",
+ "Inherit": "Podeduj",
+ "ItemAddedWithName": "{0} je dodan v knjižnico",
+ "ItemRemovedWithName": "{0} je bil odstranjen iz knjižnice",
+ "LabelIpAddressValue": "IP naslov: {0}",
+ "LabelRunningTimeValue": "Čas trajanja: {0}",
+ "Latest": "Najnovejše",
+ "MessageApplicationUpdated": "Jellyfin strežnik je bil posodobljen",
+ "MessageApplicationUpdatedTo": "Jellyfin strežnik je bil posodobljen na {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Oddelek nastavitev {0} je bil posodobljen",
+ "MessageServerConfigurationUpdated": "Nastavitve strežnika so bile posodobljene",
+ "MixedContent": "Mešane vsebine",
+ "Movies": "Filmi",
+ "Music": "Glasba",
+ "MusicVideos": "Glasbeni videi",
+ "NameInstallFailed": "{0} namestitev neuspešna",
+ "NameSeasonNumber": "Sezona {0}",
+ "NameSeasonUnknown": "Neznana sezona",
+ "NewVersionIsAvailable": "Nova različica Jellyfin strežnika je na voljo za prenos.",
+ "NotificationOptionApplicationUpdateAvailable": "Posodobitev aplikacije je na voljo",
+ "NotificationOptionApplicationUpdateInstalled": "Posodobitev aplikacije je bila nameščena",
+ "NotificationOptionAudioPlayback": "Predvajanje zvoka se je začelo",
+ "NotificationOptionAudioPlaybackStopped": "Predvajanje zvoka se je ustavilo",
+ "NotificationOptionCameraImageUploaded": "Fotografija naložena",
+ "NotificationOptionInstallationFailed": "Namestitev neuspešna",
+ "NotificationOptionNewLibraryContent": "Nove vsebine dodane",
+ "NotificationOptionPluginError": "Napaka dodatka",
+ "NotificationOptionPluginInstalled": "Dodatek nameščen",
+ "NotificationOptionPluginUninstalled": "Dodatek odstranjen",
+ "NotificationOptionPluginUpdateInstalled": "Posodobitev dodatka nameščena",
+ "NotificationOptionServerRestartRequired": "Potreben je ponovni zagon strežnika",
+ "NotificationOptionTaskFailed": "Načrtovano opravilo neuspešno",
+ "NotificationOptionUserLockedOut": "Uporabnik zaklenjen",
+ "NotificationOptionVideoPlayback": "Predvajanje videa se je začelo",
+ "NotificationOptionVideoPlaybackStopped": "Predvajanje videa se je ustavilo",
+ "Photos": "Fotografije",
+ "Playlists": "Seznami predvajanja",
+ "Plugin": "Dodatek",
+ "PluginInstalledWithName": "{0} je bil nameščen",
+ "PluginUninstalledWithName": "{0} je bil odstranjen",
+ "PluginUpdatedWithName": "{0} je bil posodobljen",
+ "ProviderValue": "Ponudnik: {0}",
+ "ScheduledTaskFailedWithName": "{0} ni uspelo",
+ "ScheduledTaskStartedWithName": "{0} začeto",
+ "ServerNameNeedsToBeRestarted": "{0} mora biti ponovno zagnan",
"Shows": "Serije",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Songs": "Pesmi",
+ "StartupEmbyServerIsLoading": "Jellyfin strežnik se zaganja. Poskusite ponovno kasneje.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "SubtitleDownloadFailureFromForItem": "Neuspešen prenos podnapisov iz {0} za {1}",
+ "Sync": "Sinhroniziraj",
+ "System": "Sistem",
+ "TvShows": "TV serije",
+ "User": "Uporabnik",
+ "UserCreatedWithName": "Uporabnik {0} je bil ustvarjen",
+ "UserDeletedWithName": "Uporabnik {0} je bil izbrisan",
+ "UserDownloadingItemWithValues": "{0} prenaša {1}",
+ "UserLockedOutWithName": "Uporabnik {0} je bil zaklenjen",
+ "UserOfflineFromDevice": "{0} je prekinil povezavo z {1}",
+ "UserOnlineFromDevice": "{0} je aktiven na {1}",
+ "UserPasswordChangedWithName": "Geslo za uporabnika {0} je bilo spremenjeno",
+ "UserPolicyUpdatedWithName": "Pravilnik uporabe je bil posodobljen za uporabnika {0}",
+ "UserStartedPlayingItemWithValues": "{0} predvaja {1} na {2}",
+ "UserStoppedPlayingItemWithValues": "{0} je nehal predvajati {1} na {2}",
+ "ValueHasBeenAddedToLibrary": "{0} je bil dodan vaši knjižnici",
+ "ValueSpecialEpisodeName": "Bonus - {0}",
+ "VersionNumber": "Različica {0}",
+ "TaskDownloadMissingSubtitles": "Prenesi manjkajoče podnapise",
+ "TaskRefreshChannelsDescription": "Osveži podatke spletnih kanalov.",
+ "TaskRefreshChannels": "Osveži kanale",
+ "TaskCleanTranscodeDescription": "Izbriše več kot dan stare datoteke prekodiranja.",
+ "TaskCleanTranscode": "Počisti mapo prekodiranja",
+ "TaskUpdatePluginsDescription": "Prenese in namesti posodobitve za dodatke, ki imajo omogočene samodejne posodobitve.",
+ "TaskUpdatePlugins": "Posodobi dodatke",
+ "TaskRefreshPeopleDescription": "Osveži metapodatke za igralce in režiserje v vaši knjižnici.",
+ "TaskRefreshPeople": "Osveži osebe",
+ "TaskCleanLogsDescription": "Izbriše dnevniške datoteke starejše od {0} dni.",
+ "TaskCleanLogs": "Počisti mapo dnevnikov",
+ "TaskRefreshLibraryDescription": "Preišče vašo knjižnico za nove datoteke in osveži metapodatke.",
+ "TaskRefreshLibrary": "Preišči knjižnico predstavnosti",
+ "TaskRefreshChapterImagesDescription": "Ustvari sličice za poglavja videoposnetkov.",
+ "TaskRefreshChapterImages": "Izvleči slike poglavij",
+ "TaskCleanCacheDescription": "Izbriše predpomnjene datoteke, ki niso več potrebne.",
+ "TaskCleanCache": "Počisti mapo predpomnilnika",
+ "TasksChannelsCategory": "Spletni kanali",
+ "TasksApplicationCategory": "Aplikacija",
+ "TasksLibraryCategory": "Knjižnica",
+ "TasksMaintenanceCategory": "Vzdrževanje",
+ "TaskDownloadMissingSubtitlesDescription": "Na podlagi nastavitev metapodatkov poišče manjkajoče podnapise na internetu.",
+ "TaskCleanActivityLogDescription": "Počisti zapise v dnevniku aktivnosti starejše od nastavljenega časa.",
+ "TaskCleanActivityLog": "Počisti dnevnik aktivnosti",
+ "Undefined": "Nedoločen",
+ "Forced": "Prisilno",
+ "Default": "Privzeto",
+ "TaskOptimizeDatabaseDescription": "Stisne bazo podatkov in uredi prazen prostor. Zagon tega opravila po iskanju predstavnosti ali drugih spremembah ki vplivajo na bazo podatkov lahko izboljša hitrost delovanja.",
+ "TaskOptimizeDatabase": "Optimiziraj bazo podatkov"
}
diff --git a/Emby.Server.Implementations/Localization/Core/sq.json b/Emby.Server.Implementations/Localization/Core/sq.json
new file mode 100644
index 000000000..066ef5587
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/sq.json
@@ -0,0 +1,123 @@
+{
+ "MessageApplicationUpdatedTo": "Serveri Jellyfin u përditesua në versionin {0}",
+ "Inherit": "Trashgimi",
+ "TaskDownloadMissingSubtitlesDescription": "Kërkon në internet për titra që mungojnë bazuar tek konfigurimi i metadata-ve.",
+ "TaskDownloadMissingSubtitles": "Shkarko titra që mungojnë",
+ "TaskRefreshChannelsDescription": "Rifreskon informacionin e kanaleve të internetit.",
+ "TaskRefreshChannels": "Rifresko Kanalet",
+ "TaskCleanTranscodeDescription": "Fshin skedarët e transkodimit që janë më të vjetër se një ditë.",
+ "TaskCleanTranscode": "Fshi dosjen e transkodimit",
+ "TaskUpdatePluginsDescription": "Shkarkon dhe instalon përditësimi për plugin që janë konfiguruar të përditësohen automatikisht.",
+ "TaskUpdatePlugins": "Përditëso Plugin",
+ "TaskRefreshPeopleDescription": "Përditëson metadata të aktorëve dhe regjizorëve në librarinë tuaj.",
+ "TaskRefreshPeople": "Rifresko aktorët",
+ "TaskCleanLogsDescription": "Fshin skëdarët log që janë më të vjetër se {0} ditë.",
+ "TaskCleanLogs": "Fshi dosjen Log",
+ "TaskRefreshLibraryDescription": "Skanon librarinë media për skedarë të rinj dhe rifreskon metadata.",
+ "TaskRefreshLibrary": "Skano librarinë media",
+ "TaskRefreshChapterImagesDescription": "Krijon imazh për videot që kanë kapituj.",
+ "TaskRefreshChapterImages": "Ekstrakto Imazhet e Kapitullit",
+ "TaskCleanCacheDescription": "Fshi skedarët e cache-s që nuk i duhen më sistemit.",
+ "TaskCleanCache": "Pastro memorjen cache",
+ "TasksChannelsCategory": "Kanalet nga interneti",
+ "TasksApplicationCategory": "Aplikacioni",
+ "TasksLibraryCategory": "Libraria",
+ "TasksMaintenanceCategory": "Mirëmbajtje",
+ "VersionNumber": "Versioni {0}",
+ "ValueSpecialEpisodeName": "Speciale - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} u shtua tek libraria juaj",
+ "UserStoppedPlayingItemWithValues": "{0} mbaroi së shikuari {1} tek {2}",
+ "UserStartedPlayingItemWithValues": "{0} po shikon {1} tek {2}",
+ "UserPolicyUpdatedWithName": "Politika e përdoruesit u përditësua për {0}",
+ "UserPasswordChangedWithName": "Fjalëkalimi u ndryshua për përdoruesin {0}",
+ "UserOnlineFromDevice": "{0} është në linjë nga {1}",
+ "UserOfflineFromDevice": "{0} u shkëput nga {1}",
+ "UserLockedOutWithName": "Përdoruesi {0} u përjashtua",
+ "UserDownloadingItemWithValues": "{0} po shkarkon {1}",
+ "UserDeletedWithName": "Përdoruesi {0} u fshi",
+ "UserCreatedWithName": "Përdoruesi {0} u krijua",
+ "User": "Përdoruesi",
+ "TvShows": "Seriale TV",
+ "System": "Sistemi",
+ "Sync": "Sinkronizo",
+ "SubtitleDownloadFailureFromForItem": "Titrat deshtuan të shkarkohen nga {0} për {1}",
+ "StartupEmbyServerIsLoading": "Serveri Jellyfin po ngarkohet. Ju lutemi provoni përseri pas pak.",
+ "Songs": "Këngët",
+ "Shows": "Serialet",
+ "ServerNameNeedsToBeRestarted": "{0} duhet të ristartoj",
+ "ScheduledTaskStartedWithName": "{0} filloi",
+ "ScheduledTaskFailedWithName": "{0} dështoi",
+ "ProviderValue": "Ofruesi: {0}",
+ "PluginUpdatedWithName": "{0} u përditësua",
+ "PluginUninstalledWithName": "{0} u çinstalua",
+ "PluginInstalledWithName": "{0} u instalua",
+ "Plugin": "Plugin",
+ "Playlists": "Listat për luajtje",
+ "Photos": "Fotografitë",
+ "NotificationOptionVideoPlaybackStopped": "Luajtja e videos ndaloi",
+ "NotificationOptionVideoPlayback": "Luajtja e videos filloi",
+ "NotificationOptionUserLockedOut": "Përdoruesi u përjashtua",
+ "NotificationOptionTaskFailed": "Ushtrimi i planifikuar dështoi",
+ "NotificationOptionServerRestartRequired": "Kërkohet ristartim i serverit",
+ "NotificationOptionPluginUpdateInstalled": "Përditësimi i plugin u instalua",
+ "NotificationOptionPluginUninstalled": "Plugin u çinstalua",
+ "NotificationOptionPluginInstalled": "Plugin u instalua",
+ "NotificationOptionPluginError": "Plugin dështoi",
+ "NotificationOptionNewLibraryContent": "Një përmbajtje e re u shtua",
+ "NotificationOptionInstallationFailed": "Instalimi dështoi",
+ "NotificationOptionCameraImageUploaded": "Fotoja nga kamera u ngarkua",
+ "NotificationOptionAudioPlaybackStopped": "Luajtja e audios ndaloi",
+ "NotificationOptionAudioPlayback": "Luajtja e audios filloi",
+ "NotificationOptionApplicationUpdateInstalled": "Përditësimi i aplikacionit u instalua",
+ "NotificationOptionApplicationUpdateAvailable": "Një perditësim i aplikacionit është gati",
+ "NewVersionIsAvailable": "Një version i ri i Jellyfin është gati për tu shkarkuar.",
+ "NameSeasonUnknown": "Sezon i panjohur",
+ "NameSeasonNumber": "Sezoni {0}",
+ "NameInstallFailed": "Instalimi i {0} dështoi",
+ "MusicVideos": "Video muzikore",
+ "Music": "Muzikë",
+ "Movies": "Filmat",
+ "MixedContent": "Përmbajtje e përzier",
+ "MessageServerConfigurationUpdated": "Konfigurimet e serverit u përditësuan",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Seksioni i konfigurimit të serverit {0} u përditësua",
+ "MessageApplicationUpdated": "Serveri Jellyfin u përditësua",
+ "Latest": "Të fundit",
+ "LabelRunningTimeValue": "Kohëzgjatja: {0}",
+ "LabelIpAddressValue": "Adresa IP: {0}",
+ "ItemRemovedWithName": "{0} u fshi nga libraria",
+ "ItemAddedWithName": "{0} u shtua tek libraria",
+ "HomeVideos": "Video personale",
+ "HeaderRecordingGroups": "Grupet e regjistrimit",
+ "HeaderNextUp": "Në vazhdim",
+ "HeaderLiveTV": "TV Live",
+ "HeaderFavoriteSongs": "Kënget e preferuara",
+ "HeaderFavoriteShows": "Serialet e preferuar",
+ "HeaderFavoriteEpisodes": "Episodet e preferuar",
+ "HeaderFavoriteArtists": "Artistët e preferuar",
+ "HeaderFavoriteAlbums": "Albumet e preferuar",
+ "HeaderContinueWatching": "Vazhdo të shikosh",
+ "HeaderAlbumArtists": "Artistët e Albumeve",
+ "Genres": "Zhanret",
+ "Folders": "Skedarët",
+ "Favorites": "Të preferuarat",
+ "FailedLoginAttemptWithUserName": "Përpjekja për hyrje dështoi nga {0}",
+ "DeviceOnlineWithName": "{0} u lidh",
+ "DeviceOfflineWithName": "{0} u shkëput",
+ "Collections": "Koleksionet",
+ "ChapterNameValue": "Kapituj",
+ "Channels": "Kanalet",
+ "CameraImageUploadedFrom": "Një foto e re nga kamera u ngarkua nga {0}",
+ "Books": "Librat",
+ "AuthenticationSucceededWithUserName": "{0} u identifikua me sukses",
+ "Artists": "Artistët",
+ "Application": "Aplikacioni",
+ "AppDeviceValues": "Aplikacioni: {0}, Pajisja: {1}",
+ "Albums": "Albumet",
+ "TaskCleanActivityLogDescription": "Pastro të dhënat mbi aktivitetin më të vjetra sesa koha e përcaktuar.",
+ "TaskCleanActivityLog": "Pastro të dhënat mbi aktivitetin",
+ "Undefined": "I papërcaktuar",
+ "Forced": "I detyruar",
+ "Default": "Parazgjedhur",
+ "TaskOptimizeDatabaseDescription": "Kompakton bazën e të dhënave dhe shkurton hapësirën e lirë. Drejtimi i kësaj detyre pasi skanoni bibliotekën ose bëni ndryshime të tjera që nënkuptojnë modifikime të bazës së të dhënave mund të përmirësojë performancën.",
+ "TaskOptimizeDatabase": "Optimizo databazën"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json
new file mode 100644
index 000000000..15fb34186
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/sr.json
@@ -0,0 +1,121 @@
+{
+ "UserPolicyUpdatedWithName": "Корисничке смернице ажуриране за {0}",
+ "NotificationOptionUserLockedOut": "Корисник закључан",
+ "VersionNumber": "Верзија {0}",
+ "ValueSpecialEpisodeName": "Специјал - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} је додато у вашу медијску библиотеку",
+ "UserStoppedPlayingItemWithValues": "{0} завршио пуштање {1} на {2}",
+ "UserStartedPlayingItemWithValues": "{0} пушта {1} на {2}",
+ "UserPasswordChangedWithName": "Лозинка је промењена за корисника {0}",
+ "UserOnlineFromDevice": "{0} је на вези од {1}",
+ "UserOfflineFromDevice": "{0} је прекинуо/а везу са {1}",
+ "UserLockedOutWithName": "Корисник {0} је закључан",
+ "UserDownloadingItemWithValues": "{0} преузима {1}",
+ "UserDeletedWithName": "Корисник {0} је обрисан",
+ "UserCreatedWithName": "Корисник {0} је направљен",
+ "User": "Корисник",
+ "TvShows": "ТВ серије",
+ "System": "Систем",
+ "Sync": "Усклади",
+ "SubtitleDownloadFailureFromForItem": "Неуспело преузимање титлова за {1} са {0}",
+ "StartupEmbyServerIsLoading": "Џелифин сервер се подиже. Покушајте поново убрзо.",
+ "Songs": "Песме",
+ "Shows": "Серије",
+ "ServerNameNeedsToBeRestarted": "{0} треба поново покренути",
+ "ScheduledTaskStartedWithName": "{0} покренуто",
+ "ScheduledTaskFailedWithName": "{0} неуспело",
+ "ProviderValue": "Пружалац: {0}",
+ "PluginUpdatedWithName": "{0} ажуриран",
+ "PluginUninstalledWithName": "{0} деинсталиран",
+ "PluginInstalledWithName": "{0} инсталиран",
+ "Plugin": "Прикључак",
+ "Playlists": "Листе",
+ "Photos": "Фотографије",
+ "NotificationOptionVideoPlaybackStopped": "Заустављено пуштање видеа",
+ "NotificationOptionVideoPlayback": "Покренуто пуштање видеа",
+ "NotificationOptionTaskFailed": "Неуспешан заказани посао",
+ "NotificationOptionServerRestartRequired": "Потребан је рестарт сервера",
+ "NotificationOptionPluginUpdateInstalled": "Ажурирање прикључка инсталирано",
+ "NotificationOptionPluginUninstalled": "Прикључак уклоњен",
+ "NotificationOptionPluginInstalled": "Прикључак инсталиран",
+ "NotificationOptionPluginError": "Грешка прикључка",
+ "NotificationOptionNewLibraryContent": "Додат нови садржај",
+ "NotificationOptionInstallationFailed": "Неуспела инсталација",
+ "NotificationOptionCameraImageUploaded": "Слика са камере отпремљена",
+ "NotificationOptionAudioPlaybackStopped": "Заустављено пуштање звука",
+ "NotificationOptionAudioPlayback": "Покренуто пуштање звука",
+ "NotificationOptionApplicationUpdateInstalled": "Ажурирање инсталирано",
+ "NotificationOptionApplicationUpdateAvailable": "Доступно је ажурирање за апликацију",
+ "NewVersionIsAvailable": "Нова верзија Џелифин сервера је доступна за преузимање.",
+ "NameSeasonUnknown": "Непозната сезона",
+ "NameSeasonNumber": "Сезона {0}",
+ "NameInstallFailed": "Инсталација {0} није успела",
+ "MusicVideos": "Музички спотови",
+ "Music": "Музика",
+ "Movies": "Филмови",
+ "MixedContent": "Мешовит садржај",
+ "MessageServerConfigurationUpdated": "Серверска поставка је ажурирана",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Одељак серверске поставке {0} је ажуриран",
+ "MessageApplicationUpdatedTo": "Џелифин сервер је ажуриран на {0}",
+ "MessageApplicationUpdated": "Џелифин сервер је ажуриран",
+ "Latest": "Последње",
+ "LabelRunningTimeValue": "Време рада: {0}",
+ "LabelIpAddressValue": "ИП адреса: {0}",
+ "ItemRemovedWithName": "{0} уклоњено из библиотеке",
+ "ItemAddedWithName": "{0} додато у библиотеку",
+ "Inherit": "Наследи",
+ "HomeVideos": "Кућни видео",
+ "HeaderRecordingGroups": "Групе снимања",
+ "HeaderNextUp": "Следи",
+ "HeaderLiveTV": "ТВ уживо",
+ "HeaderFavoriteSongs": "Омиљене песме",
+ "HeaderFavoriteShows": "Омиљене серије",
+ "HeaderFavoriteEpisodes": "Омиљене епизоде",
+ "HeaderFavoriteArtists": "Омиљени извођачи",
+ "HeaderFavoriteAlbums": "Омиљени албуми",
+ "HeaderContinueWatching": "Настави гледање",
+ "HeaderAlbumArtists": "Извођачи албума",
+ "Genres": "Жанрови",
+ "Folders": "Фасцикле",
+ "Favorites": "Омиљено",
+ "FailedLoginAttemptWithUserName": "Неуспела пријава са {0}",
+ "DeviceOnlineWithName": "{0} је повезан",
+ "DeviceOfflineWithName": "{0} је прекинуо везу",
+ "Collections": "Колекције",
+ "ChapterNameValue": "Поглавље {0}",
+ "Channels": "Канали",
+ "CameraImageUploadedFrom": "Нова фотографија је учитана са {0}",
+ "Books": "Књиге",
+ "AuthenticationSucceededWithUserName": "{0} Успешна аутентикација",
+ "Artists": "Извођачи",
+ "Application": "Апликација",
+ "AppDeviceValues": "Апликација: {0}, Уређај: {1}",
+ "Albums": "Албуми",
+ "TaskDownloadMissingSubtitlesDescription": "Претражује интернет за недостајуће титлове на основу конфигурације метаподатака.",
+ "TaskDownloadMissingSubtitles": "Преузмите недостајуће титлове",
+ "TaskRefreshChannelsDescription": "Освежава информације о интернет каналу.",
+ "TaskRefreshChannels": "Освежи канале",
+ "TaskCleanTranscodeDescription": "Брише датотеке за кодирање старије од једног дана.",
+ "TaskCleanTranscode": "Очистите директоријум преноса",
+ "TaskUpdatePluginsDescription": "Преузима и инсталира исправке за додатке који су конфигурисани за аутоматско ажурирање.",
+ "TaskUpdatePlugins": "Ажурирајте додатке",
+ "TaskRefreshPeopleDescription": "Ажурира метаподатке за глумце и редитеље у вашој медијској библиотеци.",
+ "TaskRefreshPeople": "Освежите кориснике",
+ "TaskCleanLogsDescription": "Брише логове старије од {0} дана.",
+ "TaskCleanLogs": "Очистите директоријум логова",
+ "TaskRefreshLibraryDescription": "Скенира вашу медијску библиотеку за нове датотеке и освежава метаподатке.",
+ "TaskRefreshLibrary": "Скенирај библиотеку медија",
+ "TaskRefreshChapterImagesDescription": "Ствара сличице за видео записе који имају поглавља.",
+ "TaskRefreshChapterImages": "Издвоји слике из поглавља",
+ "TaskCleanCacheDescription": "Брише Кеш фајлове који више нису потребни систему.",
+ "TaskCleanCache": "Очистите Кеш Директоријум",
+ "TasksChannelsCategory": "Интернет канали",
+ "TasksApplicationCategory": "Апликација",
+ "TasksLibraryCategory": "Библиотека",
+ "TasksMaintenanceCategory": "Одржавање",
+ "TaskCleanActivityLogDescription": "Брише историју активности старију од конфигурисаног броја година.",
+ "TaskCleanActivityLog": "Очисти историју активности",
+ "Undefined": "Недефинисано",
+ "Forced": "Принудно",
+ "Default": "Подразумевано"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json
index fb2761a7d..6c772c6a2 100644
--- a/Emby.Server.Implementations/Localization/Core/sv.json
+++ b/Emby.Server.Implementations/Localization/Core/sv.json
@@ -1,32 +1,31 @@
{
"Albums": "Album",
- "AppDeviceValues": "App: {0}, Enhet: {1}",
- "Application": "App",
+ "AppDeviceValues": "Applikation: {0}, Enhet: {1}",
+ "Application": "Applikation",
"Artists": "Artister",
"AuthenticationSucceededWithUserName": "{0} har autentiserats",
"Books": "Böcker",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "En ny kamerabild har laddats upp från {0}",
"Channels": "Kanaler",
"ChapterNameValue": "Kapitel {0}",
"Collections": "Samlingar",
- "DeviceOfflineWithName": "{0} har tappat anslutningen",
+ "DeviceOfflineWithName": "{0} har kopplat ner",
"DeviceOnlineWithName": "{0} är ansluten",
"FailedLoginAttemptWithUserName": "Misslyckat inloggningsförsök från {0}",
"Favorites": "Favoriter",
"Folders": "Mappar",
"Genres": "Genrer",
- "HeaderAlbumArtists": "Albumartister",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Fortsätt kolla på",
+ "HeaderAlbumArtists": "Artistens album",
+ "HeaderContinueWatching": "Fortsätt kolla",
"HeaderFavoriteAlbums": "Favoritalbum",
"HeaderFavoriteArtists": "Favoritartister",
"HeaderFavoriteEpisodes": "Favoritavsnitt",
"HeaderFavoriteShows": "Favoritserier",
"HeaderFavoriteSongs": "Favoritlåtar",
"HeaderLiveTV": "Live-TV",
- "HeaderNextUp": "Nästa på tur",
+ "HeaderNextUp": "Nästa",
"HeaderRecordingGroups": "Inspelningsgrupper",
- "HomeVideos": "Hemvideor",
+ "HomeVideos": "Hemmavideor",
"Inherit": "Ärv",
"ItemAddedWithName": "{0} lades till i biblioteket",
"ItemRemovedWithName": "{0} togs bort från biblioteket",
@@ -34,23 +33,23 @@
"LabelRunningTimeValue": "Speltid: {0}",
"Latest": "Senaste",
"MessageApplicationUpdated": "Jellyfin Server har uppdaterats",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin Server har uppdaterats till {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Serverinställningarna {0} har uppdaterats",
- "MessageServerConfigurationUpdated": "Server konfigurationen har uppdaterats",
+ "MessageServerConfigurationUpdated": "Serverkonfigurationen har uppdaterats",
"MixedContent": "Blandat innehåll",
"Movies": "Filmer",
"Music": "Musik",
- "MusicVideos": "Musikvideos",
- "NameInstallFailed": "{0} installation failed",
+ "MusicVideos": "Musikvideor",
+ "NameInstallFailed": "{0} installationen misslyckades",
"NameSeasonNumber": "Säsong {0}",
"NameSeasonUnknown": "Okänd säsong",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NewVersionIsAvailable": "En ny version av Jellyfin Server är tillgänglig att hämta.",
"NotificationOptionApplicationUpdateAvailable": "Ny programversion tillgänglig",
"NotificationOptionApplicationUpdateInstalled": "Programuppdatering installerad",
"NotificationOptionAudioPlayback": "Ljuduppspelning har påbörjats",
- "NotificationOptionAudioPlaybackStopped": "Ljuduppspelning stoppad",
+ "NotificationOptionAudioPlaybackStopped": "Ljuduppspelning stoppades",
"NotificationOptionCameraImageUploaded": "Kamerabild har laddats upp",
- "NotificationOptionInstallationFailed": "Fel vid installation",
+ "NotificationOptionInstallationFailed": "Installationen misslyckades",
"NotificationOptionNewLibraryContent": "Nytt innehåll har lagts till",
"NotificationOptionPluginError": "Fel uppstod med tillägget",
"NotificationOptionPluginInstalled": "Tillägg har installerats",
@@ -60,7 +59,7 @@
"NotificationOptionTaskFailed": "Schemalagd aktivitet har misslyckats",
"NotificationOptionUserLockedOut": "Användare har låsts ut",
"NotificationOptionVideoPlayback": "Videouppspelning har påbörjats",
- "NotificationOptionVideoPlaybackStopped": "Videouppspelning stoppad",
+ "NotificationOptionVideoPlaybackStopped": "Videouppspelning stoppades",
"Photos": "Bilder",
"Playlists": "Spellistor",
"Plugin": "Tillägg",
@@ -69,14 +68,13 @@
"PluginUpdatedWithName": "{0} uppdaterades",
"ProviderValue": "Källa: {0}",
"ScheduledTaskFailedWithName": "{0} misslyckades",
- "ScheduledTaskStartedWithName": "{0} startad",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "ScheduledTaskStartedWithName": "{0} startades",
+ "ServerNameNeedsToBeRestarted": "{0} behöver startas om",
"Shows": "Serier",
"Songs": "Låtar",
- "StartupEmbyServerIsLoading": "Jellyfin server arbetar. Pröva igen inom kort.",
+ "StartupEmbyServerIsLoading": "Jellyfin Server arbetar. Pröva igen snart.",
"SubtitleDownloadFailureForItem": "Nerladdning av undertexter för {0} misslyckades",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Undertexter har laddats ner till {0}",
+ "SubtitleDownloadFailureFromForItem": "Undertexter kunde inte laddas ner från {0} för {1}",
"Sync": "Synk",
"System": "System",
"TvShows": "TV-serier",
@@ -89,9 +87,38 @@
"UserOnlineFromDevice": "{0} är uppkopplad från {1}",
"UserPasswordChangedWithName": "Lösenordet för {0} har ändrats",
"UserPolicyUpdatedWithName": "Användarpolicyn har uppdaterats för {0}",
- "UserStartedPlayingItemWithValues": "{0} har börjat spela upp {1}",
- "UserStoppedPlayingItemWithValues": "{0} har avslutat uppspelningen av {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserStartedPlayingItemWithValues": "{0} spelar upp {1} på {2}",
+ "UserStoppedPlayingItemWithValues": "{0} har avslutat uppspelningen av {1} på {2}",
+ "ValueHasBeenAddedToLibrary": "{0} har lagts till i ditt mediebibliotek",
"ValueSpecialEpisodeName": "Specialavsnitt - {0}",
- "VersionNumber": "Version {0}"
+ "VersionNumber": "Version {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Söker på internet efter saknade undertexter baserad på metadatas konfiguration.",
+ "TaskDownloadMissingSubtitles": "Ladda ned saknade undertexter",
+ "TaskRefreshChannelsDescription": "Uppdaterar information för internetkanaler.",
+ "TaskRefreshChannels": "Uppdatera kanaler",
+ "TaskCleanTranscodeDescription": "Raderar transkodningsfiler som är mer än en dag gamla.",
+ "TaskCleanTranscode": "Töm transkodningskatalog",
+ "TaskUpdatePluginsDescription": "Laddar ned och installerar uppdateringar till insticksprogram som är konfigurerade att uppdateras automatiskt.",
+ "TaskUpdatePlugins": "Uppdatera insticksprogram",
+ "TaskRefreshPeopleDescription": "Uppdaterar metadata för skådespelare och regissörer i ditt mediabibliotek.",
+ "TaskCleanLogsDescription": "Raderar loggfiler som är mer än {0} dagar gamla.",
+ "TaskCleanLogs": "Töm loggkatalog",
+ "TaskRefreshLibraryDescription": "Söker igenom ditt mediabibliotek efter nya filer och förnyar metadata.",
+ "TaskRefreshLibrary": "Genomsök mediabibliotek",
+ "TaskRefreshChapterImagesDescription": "Skapa miniatyrbilder för videor med kapitel.",
+ "TaskRefreshChapterImages": "Extrahera kapitelbilder",
+ "TaskCleanCacheDescription": "Radera cachade filer som systemet inte längre behöver.",
+ "TaskCleanCache": "Rensa cachekatalog",
+ "TasksChannelsCategory": "Internetkanaler",
+ "TasksApplicationCategory": "Applikation",
+ "TasksLibraryCategory": "Bibliotek",
+ "TasksMaintenanceCategory": "Underhåll",
+ "TaskRefreshPeople": "Uppdatera Personer",
+ "TaskCleanActivityLogDescription": "Radera aktivitets logg inlägg som är äldre än definerad ålder.",
+ "TaskCleanActivityLog": "Rensa Aktivitets Logg",
+ "Undefined": "odefinierad",
+ "Forced": "Tvingad",
+ "Default": "Standard",
+ "TaskOptimizeDatabase": "Optimera databasen",
+ "TaskOptimizeDatabaseDescription": "Komprimerar databasen och trunkerar ledigt utrymme. Prestandan kan förbättras genom att köra denna task efter att du har skannat biblioteket eller gjort andra förändringar som indikerar att databasen har modifierats."
}
diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json
new file mode 100644
index 000000000..d6e9aa8e5
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ta.json
@@ -0,0 +1,123 @@
+{
+ "VersionNumber": "பதிப்பு {0}",
+ "ValueSpecialEpisodeName": "சிறப்பு - {0}",
+ "TasksMaintenanceCategory": "பராமரிப்பு",
+ "TaskCleanCache": "தற்காலிக சேமிப்பு கோப்பகத்தை சுத்தம் செய்யவும்",
+ "TaskRefreshChapterImages": "அத்தியாயப் படங்களை பிரித்தெடுக்கவும்",
+ "TaskRefreshPeople": "மக்களைப் புதுப்பிக்கவும்",
+ "TaskCleanTranscode": "டிரான்ஸ்கோட் கோப்பகத்தை சுத்தம் செய்யவும்",
+ "TaskRefreshChannelsDescription": "இணையச் சேனல் தகவல்களைப் புதுப்பிக்கிறது.",
+ "System": "ஒருங்கியம்",
+ "NotificationOptionTaskFailed": "திட்டமிடப்பட்ட பணி தோல்வியடைந்தது",
+ "NotificationOptionPluginUpdateInstalled": "உட்செருகி புதுப்பிக்கப்பட்டது",
+ "NotificationOptionPluginUninstalled": "உட்செருகி நீக்கப்பட்டது",
+ "NotificationOptionPluginInstalled": "உட்செருகி நிறுவப்பட்டது",
+ "NotificationOptionPluginError": "உட்செருகி செயலிழந்தது",
+ "NotificationOptionCameraImageUploaded": "புகைப்படம் பதிவேற்றப்பட்டது",
+ "MixedContent": "கலப்பு உள்ளடக்கங்கள்",
+ "MessageServerConfigurationUpdated": "சேவையக அமைப்புகள் புதுப்பிக்கப்பட்டன",
+ "MessageApplicationUpdatedTo": "ஜெல்லிஃபின் சேவையகம் {0} இற்கு புதுப்பிக்கப்பட்டது",
+ "MessageApplicationUpdated": "ஜெல்லிஃபின் சேவையகம் புதுப்பிக்கப்பட்டது",
+ "Inherit": "மரபுரிமையாகப் பெறு",
+ "HeaderRecordingGroups": "பதிவு குழுக்கள்",
+ "Folders": "கோப்புறைகள்",
+ "FailedLoginAttemptWithUserName": "{0} இல் இருந்து உள்நுழைவு முயற்சி தோல்வியடைந்தது",
+ "DeviceOnlineWithName": "{0} இணைக்கப்பட்டது",
+ "DeviceOfflineWithName": "{0} துண்டிக்கப்பட்டது",
+ "Collections": "தொகுப்புகள்",
+ "CameraImageUploadedFrom": "{0} இல் இருந்து புதிய புகைப்படம் பதிவேற்றப்பட்டது",
+ "AppDeviceValues": "செயலி: {0}, சாதனம்: {1}",
+ "TaskDownloadMissingSubtitles": "விடுபட்டுபோன வசன வரிகளைப் பதிவிறக்கு",
+ "TaskRefreshChannels": "சேனல்களை புதுப்பி",
+ "TaskUpdatePlugins": "உட்செருகிகளை புதுப்பி",
+ "TaskRefreshLibrary": "ஊடக நூலகத்தை ஆராய்",
+ "TasksChannelsCategory": "இணைய சேனல்கள்",
+ "TasksApplicationCategory": "செயலி",
+ "TasksLibraryCategory": "நூலகம்",
+ "UserPolicyUpdatedWithName": "பயனர் கொள்கை {0} இற்கு புதுப்பிக்கப்பட்டுள்ளது",
+ "UserPasswordChangedWithName": "{0} பயனருக்கு கடவுச்சொல் மாற்றப்பட்டுள்ளது",
+ "UserLockedOutWithName": "பயனர் {0} முடக்கப்பட்டார்",
+ "UserDownloadingItemWithValues": "{0} ஆல் {1} பதிவிறக்கப்படுகிறது",
+ "UserDeletedWithName": "பயனர் {0} நீக்கப்பட்டார்",
+ "UserCreatedWithName": "பயனர் {0} உருவாக்கப்பட்டார்",
+ "User": "பயனர்",
+ "TvShows": "தொலைக்காட்சித் தொடர்கள்",
+ "Sync": "ஒத்திசைவு",
+ "StartupEmbyServerIsLoading": "ஜெல்லிஃபின் சேவையகம் துவங்குகிறது. சிறிது நேரம் கழித்து முயற்சிக்கவும்.",
+ "Songs": "பாடல்கள்",
+ "Shows": "நிகழ்ச்சிகள்",
+ "ServerNameNeedsToBeRestarted": "{0} மறுதொடக்கம் செய்யப்பட வேண்டும்",
+ "ScheduledTaskStartedWithName": "{0} துவங்கியது",
+ "ScheduledTaskFailedWithName": "{0} தோல்வியடைந்தது",
+ "ProviderValue": "வழங்குநர்: {0}",
+ "PluginUpdatedWithName": "{0} புதுப்பிக்கப்பட்டது",
+ "PluginUninstalledWithName": "{0} நீக்கப்பட்டது",
+ "PluginInstalledWithName": "{0} நிறுவப்பட்டது",
+ "Plugin": "உட்செருகி",
+ "Playlists": "தொடர் பட்டியல்கள்",
+ "Photos": "புகைப்படங்கள்",
+ "NotificationOptionVideoPlaybackStopped": "நிகழ்பட ஒளிபரப்பு நிறுத்தப்பட்டது",
+ "NotificationOptionVideoPlayback": "நிகழ்பட ஒளிபரப்பு துவங்கியது",
+ "NotificationOptionUserLockedOut": "பயனர் கணக்கு முடக்கப்பட்டது",
+ "NotificationOptionServerRestartRequired": "சேவையக மறுதொடக்கம் தேவை",
+ "NotificationOptionNewLibraryContent": "புதிய உள்ளடக்கங்கள் சேர்க்கப்பட்டன",
+ "NotificationOptionInstallationFailed": "நிறுவல் தோல்வியடைந்தது",
+ "NotificationOptionAudioPlaybackStopped": "ஒலி இசைத்தல் நிறுத்தப்பட்டது",
+ "NotificationOptionAudioPlayback": "ஒலி இசைக்கத் துவங்கியுள்ளது",
+ "NotificationOptionApplicationUpdateInstalled": "செயலி புதுப்பிக்கப்பட்டது",
+ "NotificationOptionApplicationUpdateAvailable": "செயலியினை புதுப்பிக்கலாம்",
+ "NameSeasonUnknown": "அறியப்படாத பருவம்",
+ "NameSeasonNumber": "பருவம் {0}",
+ "NameInstallFailed": "{0} நிறுவல் தோல்வியடைந்தது",
+ "MusicVideos": "இசை கானொளி",
+ "Music": "இசை",
+ "Movies": "திரைப்படங்கள்",
+ "Latest": "புதியவை",
+ "LabelRunningTimeValue": "ஓடும் நேரம்: {0}",
+ "LabelIpAddressValue": "ஐபி முகவரி: {0}",
+ "ItemRemovedWithName": "{0} நூலகத்திலிருந்து அகற்றப்பட்டது",
+ "ItemAddedWithName": "{0} நூலகத்தில் சேர்க்கப்பட்டது",
+ "HeaderNextUp": "அடுத்தது",
+ "HeaderLiveTV": "நேரடித் தொலைக்காட்சி",
+ "HeaderFavoriteSongs": "பிடித்த பாடல்கள்",
+ "HeaderFavoriteShows": "பிடித்த தொடர்கள்",
+ "HeaderFavoriteEpisodes": "பிடித்த அத்தியாயங்கள்",
+ "HeaderFavoriteArtists": "பிடித்த கலைஞர்கள்",
+ "HeaderFavoriteAlbums": "பிடித்த ஆல்பங்கள்",
+ "HeaderContinueWatching": "தொடர்ந்து பார்",
+ "HeaderAlbumArtists": "இசைக் கலைஞர்கள்",
+ "Genres": "வகைகள்",
+ "Favorites": "பிடித்தவை",
+ "ChapterNameValue": "அத்தியாயம் {0}",
+ "Channels": "சேனல்கள்",
+ "Books": "புத்தகங்கள்",
+ "AuthenticationSucceededWithUserName": "{0} வெற்றிகரமாக அங்கீகரிக்கப்பட்டது",
+ "Artists": "கலைஞர்கள்",
+ "Application": "செயலி",
+ "Albums": "ஆல்பங்கள்",
+ "NewVersionIsAvailable": "ஜெல்லிஃபின் சேவையகத்தின் புதிய பதிப்பு பதிவிறக்கத்திற்கு கிடைக்கிறது.",
+ "MessageNamedServerConfigurationUpdatedWithValue": "சேவையக உள்ளமைவு பிரிவு {0} புதுப்பிக்கப்பட்டது",
+ "TaskCleanCacheDescription": "கணினிக்கு இனி தேவைப்படாத தற்காலிக கோப்புகளை நீக்கு.",
+ "UserOfflineFromDevice": "{0} இலிருந்து {1} துண்டிக்கப்பட்டுள்ளது",
+ "SubtitleDownloadFailureFromForItem": "வசன வரிகள் {0} இல் இருந்து {1} க்கு பதிவிறக்கத் தவறிவிட்டன",
+ "TaskDownloadMissingSubtitlesDescription": "மீத்தரவு உள்ளமைவின் அடிப்படையில் வசன வரிகள் காணாமல் போனதற்கு இணையத்தைத் தேடுகிறது.",
+ "TaskCleanTranscodeDescription": "ஒரு நாளைக்கு மேற்பட்ட பழைய டிரான்ஸ்கோட் கோப்புகளை நீக்குகிறது.",
+ "TaskUpdatePluginsDescription": "தானாகவே புதுப்பிக்க கட்டமைக்கப்பட்ட உட்செருகிகளுக்கான புதுப்பிப்புகளை பதிவிறக்குகிறது மற்றும் நிறுவுகிறது.",
+ "TaskRefreshPeopleDescription": "உங்கள் ஊடக நூலகத்தில் உள்ள நடிகர்கள் மற்றும் இயக்குனர்களுக்கான மீத்தரவை புதுப்பிக்கும்.",
+ "TaskCleanLogsDescription": "{0} நாட்களுக்கு மேல் இருக்கும் பதிவு கோப்புகளை நீக்கும்.",
+ "TaskCleanLogs": "பதிவு அடைவை சுத்தம் செய்யுங்கள்",
+ "TaskRefreshLibraryDescription": "புதிய கோப்புகளுக்காக உங்கள் ஊடக நூலகத்தை ஆராய்ந்து மீத்தரவை புதுப்பிக்கும்.",
+ "TaskRefreshChapterImagesDescription": "அத்தியாயங்களைக் கொண்ட வீடியோக்களுக்கான சிறு உருவங்களை உருவாக்குகிறது.",
+ "ValueHasBeenAddedToLibrary": "உங்கள் மீடியா நூலகத்தில் {0} சேர்க்கப்பட்டது",
+ "UserOnlineFromDevice": "{1} இருந்து {0} ஆன்லைன்",
+ "HomeVideos": "முகப்பு வீடியோக்கள்",
+ "UserStoppedPlayingItemWithValues": "{0} {2} இல் {1} முடித்துவிட்டது",
+ "UserStartedPlayingItemWithValues": "{0} {2}இல் {1} ஐ இயக்குகிறது",
+ "TaskCleanActivityLogDescription": "உள்ளமைக்கப்பட்ட வயதை விட பழைய செயல்பாட்டு பதிவு உள்ளீடுகளை நீக்குகிறது.",
+ "TaskCleanActivityLog": "செயல்பாட்டு பதிவை அழி",
+ "Undefined": "வரையறுக்கப்படாத",
+ "Forced": "கட்டாயப்படுத்தப்பட்டது",
+ "Default": "இயல்புநிலை",
+ "TaskOptimizeDatabaseDescription": "தரவுத்தளத்தை சுருக்கி, இலவச இடத்தை குறைக்கிறது. நூலகத்தை ஸ்கேன் செய்தபின் அல்லது தரவுத்தள மாற்றங்களைக் குறிக்கும் பிற மாற்றங்களைச் செய்தபின் இந்த பணியை இயக்குவது செயல்திறனை மேம்படுத்தக்கூடும்.",
+ "TaskOptimizeDatabase": "தரவுத்தளத்தை மேம்படுத்தவும்"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/th.json b/Emby.Server.Implementations/Localization/Core/th.json
new file mode 100644
index 000000000..e26010423
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/th.json
@@ -0,0 +1,121 @@
+{
+ "ProviderValue": "ผู้ให้บริการ: {0}",
+ "PluginUpdatedWithName": "อัปเดต {0} แล้ว",
+ "PluginUninstalledWithName": "ถอนการติดตั้ง {0} แล้ว",
+ "PluginInstalledWithName": "ติดตั้ง {0} แล้ว",
+ "Plugin": "ปลั๊กอิน",
+ "Playlists": "เพลย์ลิสต์",
+ "Photos": "รูปภาพ",
+ "NotificationOptionVideoPlaybackStopped": "หยุดเล่นวิดีโอ",
+ "NotificationOptionVideoPlayback": "เริ่มเล่นวิดีโอ",
+ "NotificationOptionUserLockedOut": "ผู้ใช้ถูกล็อก",
+ "NotificationOptionTaskFailed": "งานตามกำหนดการล้มเหลว",
+ "NotificationOptionServerRestartRequired": "จำเป็นต้องรีสตาร์ทเซิร์ฟเวอร์",
+ "NotificationOptionPluginUpdateInstalled": "ติดตั้งการอัปเดตปลั๊กอินแล้ว",
+ "NotificationOptionPluginUninstalled": "ถอนการติดตั้งปลั๊กอินแล้ว",
+ "NotificationOptionPluginInstalled": "ติดตั้งปลั๊กอินแล้ว",
+ "NotificationOptionPluginError": "ปลั๊กอินล้มเหลว",
+ "NotificationOptionNewLibraryContent": "เพิ่มเนื้อหาใหม่แล้ว",
+ "NotificationOptionInstallationFailed": "การติดตั้งล้มเหลว",
+ "NotificationOptionCameraImageUploaded": "อัปโหลดภาพถ่ายแล้ว",
+ "NotificationOptionAudioPlaybackStopped": "หยุดเล่นเสียง",
+ "NotificationOptionAudioPlayback": "เริ่มเล่นเสียง",
+ "NotificationOptionApplicationUpdateInstalled": "ติดตั้งการอัปเดตแอปพลิเคชันแล้ว",
+ "NotificationOptionApplicationUpdateAvailable": "มีการอัปเดตแอปพลิเคชัน",
+ "NewVersionIsAvailable": "เวอร์ชันใหม่ของเซิร์ฟเวอร์ Jellyfin พร้อมให้ดาวน์โหลดแล้ว",
+ "NameSeasonUnknown": "ไม่ทราบซีซัน",
+ "NameSeasonNumber": "ซีซัน {0}",
+ "NameInstallFailed": "การติดตั้ง {0} ล้มเหลว",
+ "MusicVideos": "มิวสิควิดีโอ",
+ "Music": "ดนตรี",
+ "Movies": "ภาพยนตร์",
+ "MixedContent": "เนื้อหาผสม",
+ "MessageServerConfigurationUpdated": "อัปเดตการกำหนดค่าเซิร์ฟเวอร์แล้ว",
+ "MessageNamedServerConfigurationUpdatedWithValue": "อัปเดตการกำหนดค่าเซิร์ฟเวอร์ในส่วน {0} แล้ว",
+ "MessageApplicationUpdatedTo": "เซิร์ฟเวอร์ Jellyfin ได้รับการอัปเดตเป็น {0}",
+ "MessageApplicationUpdated": "อัพเดตเซิร์ฟเวอร์ Jellyfin แล้ว",
+ "Latest": "ล่าสุด",
+ "LabelRunningTimeValue": "ผ่านไปแล้ว: {0}",
+ "LabelIpAddressValue": "ที่อยู่ IP: {0}",
+ "ItemRemovedWithName": "{0} ถูกลบออกจากไลบรารี",
+ "ItemAddedWithName": "{0} ถูกเพิ่มลงในไลบรารีแล้ว",
+ "Inherit": "สืบทอด",
+ "HomeVideos": "โฮมวิดีโอ",
+ "HeaderRecordingGroups": "กลุ่มการบันทึก",
+ "HeaderNextUp": "ถัดไป",
+ "HeaderLiveTV": "ทีวีสด",
+ "HeaderFavoriteSongs": "เพลงที่ชื่นชอบ",
+ "HeaderFavoriteShows": "รายการที่ชื่นชอบ",
+ "HeaderFavoriteEpisodes": "ตอนที่ชื่นชอบ",
+ "HeaderFavoriteArtists": "ศิลปินที่ชื่นชอบ",
+ "HeaderFavoriteAlbums": "อัมบั้มที่ชื่นชอบ",
+ "HeaderContinueWatching": "ดูต่อ",
+ "HeaderAlbumArtists": "ศิลปินอัลบั้ม",
+ "Genres": "ประเภท",
+ "Folders": "โฟลเดอร์",
+ "Favorites": "รายการโปรด",
+ "FailedLoginAttemptWithUserName": "ความพยายามในการเข้าสู่ระบบล้มเหลวจาก {0}",
+ "DeviceOnlineWithName": "{0} เชื่อมต่อสำเร็จแล้ว",
+ "DeviceOfflineWithName": "{0} ยกเลิกการเชื่อมต่อแล้ว",
+ "Collections": "คอลเลกชัน",
+ "ChapterNameValue": "บท {0}",
+ "Channels": "ช่อง",
+ "CameraImageUploadedFrom": "ภาพถ่ายใหม่ได้ถูกอัปโหลดมาจาก {0}",
+ "Books": "หนังสือ",
+ "AuthenticationSucceededWithUserName": "{0} ยืนยันตัวสำเร็จแล้ว",
+ "Artists": "ศิลปิน",
+ "Application": "แอปพลิเคชัน",
+ "AppDeviceValues": "แอป: {0}, อุปกรณ์: {1}",
+ "Albums": "อัลบั้ม",
+ "ScheduledTaskStartedWithName": "{0} เริ่มต้น",
+ "ScheduledTaskFailedWithName": "{0} ล้มเหลว",
+ "Songs": "เพลง",
+ "Shows": "รายการ",
+ "ServerNameNeedsToBeRestarted": "{0} ต้องการการรีสตาร์ท",
+ "TaskDownloadMissingSubtitlesDescription": "ค้นหาคำบรรยายที่หายไปในอินเทอร์เน็ตตามค่ากำหนดในข้อมูลเมตา",
+ "TaskDownloadMissingSubtitles": "ดาวน์โหลดคำบรรยายที่ขาดหายไป",
+ "TaskRefreshChannelsDescription": "รีเฟรชข้อมูลช่องอินเทอร์เน็ต",
+ "TaskRefreshChannels": "รีเฟรชช่อง",
+ "TaskCleanTranscodeDescription": "ลบไฟล์ทรานส์โค้ดที่มีอายุมากกว่าหนึ่งวัน",
+ "TaskCleanTranscode": "ล้างไดเรกทอรีทรานส์โค้ด",
+ "TaskUpdatePluginsDescription": "ดาวน์โหลดและติดตั้งโปรแกรมปรับปรุงให้กับปลั๊กอินที่กำหนดค่าให้อัปเดตโดยอัตโนมัติ",
+ "TaskUpdatePlugins": "อัปเดตปลั๊กอิน",
+ "TaskRefreshPeopleDescription": "อัปเดตข้อมูลเมตานักแสดงและผู้กำกับในไลบรารีสื่อ",
+ "TaskRefreshPeople": "รีเฟรชบุคคล",
+ "TaskCleanLogsDescription": "ลบไฟล์บันทึกที่เก่ากว่า {0} วัน",
+ "TaskCleanLogs": "ล้างไดเรกทอรีบันทึก",
+ "TaskRefreshLibraryDescription": "สแกนไลบรารีสื่อของคุณเพื่อหาไฟล์ใหม่และรีเฟรชข้อมูลเมตา",
+ "TaskRefreshLibrary": "สแกนไลบรารีสื่อ",
+ "TaskRefreshChapterImagesDescription": "สร้างภาพขนาดย่อสำหรับวิดีโอที่มีบท",
+ "TaskRefreshChapterImages": "แตกรูปภาพบท",
+ "TaskCleanCacheDescription": "ลบไฟล์แคชที่ระบบไม่ต้องการ",
+ "TaskCleanCache": "ล้างไดเรกทอรีแคช",
+ "TasksChannelsCategory": "ช่องอินเทอร์เน็ต",
+ "TasksApplicationCategory": "แอปพลิเคชัน",
+ "TasksLibraryCategory": "ไลบรารี",
+ "TasksMaintenanceCategory": "ปิดซ่อมบำรุง",
+ "VersionNumber": "เวอร์ชัน {0}",
+ "ValueSpecialEpisodeName": "พิเศษ - {0}",
+ "ValueHasBeenAddedToLibrary": "เพิ่ม {0} ลงในไลบรารีสื่อของคุณแล้ว",
+ "UserStoppedPlayingItemWithValues": "{0} เล่นเสร็จแล้ว {1} บน {2}",
+ "UserStartedPlayingItemWithValues": "{0} กำลังเล่น {1} บน {2}",
+ "UserPolicyUpdatedWithName": "มีการอัปเดตนโยบายผู้ใช้ของ {0}",
+ "UserPasswordChangedWithName": "มีการเปลี่ยนรหัสผ่านของผู้ใช้ {0}",
+ "UserOnlineFromDevice": "{0} ออนไลน์จาก {1}",
+ "UserOfflineFromDevice": "{0} ได้ยกเลิกการเชื่อมต่อจาก {1}",
+ "UserLockedOutWithName": "ผู้ใช้ {0} ถูกล็อก",
+ "UserDownloadingItemWithValues": "{0} กำลังดาวน์โหลด {1}",
+ "UserDeletedWithName": "ลบผู้ใช้ {0} แล้ว",
+ "UserCreatedWithName": "สร้างผู้ใช้ {0} แล้ว",
+ "User": "ผู้ใช้งาน",
+ "TvShows": "รายการทีวี",
+ "System": "ระบบ",
+ "Sync": "ซิงค์",
+ "SubtitleDownloadFailureFromForItem": "ไม่สามารถดาวน์โหลดคำบรรยายจาก {0} สำหรับ {1} ได้",
+ "StartupEmbyServerIsLoading": "กำลังโหลดเซิร์ฟเวอร์ Jellyfin โปรดลองอีกครั้งในอีกสักครู่",
+ "Default": "ค่าเริ่มต้น",
+ "TaskCleanActivityLogDescription": "ลบบันทึกกิจกรรมที่เก่ากว่าค่าที่กำหนดไว้",
+ "TaskCleanActivityLog": "ล้างบันทึกกิจกรรม",
+ "Undefined": "ไม่ได้กำหนด",
+ "Forced": "บังคับใช้"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json
index 495f82db6..e661299c4 100644
--- a/Emby.Server.Implementations/Localization/Core/tr.json
+++ b/Emby.Server.Implementations/Localization/Core/tr.json
@@ -1,97 +1,124 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favori Showlar",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Albums": "Albümler",
+ "AppDeviceValues": "Uygulama: {0}, Aygıt: {1}",
+ "Application": "Uygulama",
+ "Artists": "Sanatçılar",
+ "AuthenticationSucceededWithUserName": "{0} kimlik başarıyla doğrulandı",
+ "Books": "Kitaplar",
+ "CameraImageUploadedFrom": "{0} 'den yeni bir kamera resmi yüklendi",
+ "Channels": "Kanallar",
+ "ChapterNameValue": "Bölüm {0}",
+ "Collections": "Koleksiyon",
+ "DeviceOfflineWithName": "{0} bağlantısı kesildi",
+ "DeviceOnlineWithName": "{0} bağlı",
+ "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu",
+ "Favorites": "Favoriler",
+ "Folders": "Klasörler",
+ "Genres": "Türler",
+ "HeaderAlbumArtists": "Albüm Sanatçıları",
+ "HeaderContinueWatching": "İzlemeye Devam Et",
+ "HeaderFavoriteAlbums": "Favori Albümler",
+ "HeaderFavoriteArtists": "Favori Sanatçılar",
+ "HeaderFavoriteEpisodes": "Favori Bölümler",
+ "HeaderFavoriteShows": "Favori Diziler",
+ "HeaderFavoriteSongs": "Favori Şarkılar",
+ "HeaderLiveTV": "Canlı TV",
+ "HeaderNextUp": "Gelecek Hafta",
+ "HeaderRecordingGroups": "Kayıt Grupları",
+ "HomeVideos": "Ana sayfa videoları",
+ "Inherit": "Devral",
+ "ItemAddedWithName": "{0} kütüphaneye eklendi",
+ "ItemRemovedWithName": "{0} kütüphaneden silindi",
+ "LabelIpAddressValue": "IP adresi: {0}",
+ "LabelRunningTimeValue": "Çalışma süresi: {0}",
+ "Latest": "En son",
+ "MessageApplicationUpdated": "Jellyfin Sunucusu güncellendi",
+ "MessageApplicationUpdatedTo": "Jellyfin Sunucusu {0} sürümüne güncellendi",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Sunucu ayar kısmı {0} güncellendi",
+ "MessageServerConfigurationUpdated": "Sunucu ayarları güncellendi",
+ "MixedContent": "Karışık içerik",
+ "Movies": "Filmler",
+ "Music": "Müzik",
+ "MusicVideos": "Müzik videoları",
+ "NameInstallFailed": "{0} kurulumu başarısız",
+ "NameSeasonNumber": "Sezon {0}",
+ "NameSeasonUnknown": "Bilinmeyen Sezon",
+ "NewVersionIsAvailable": "Jellyfin Sunucusunun yeni bir sürümü indirmek için hazır.",
+ "NotificationOptionApplicationUpdateAvailable": "Uygulama güncellemesi mevcut",
+ "NotificationOptionApplicationUpdateInstalled": "Uygulama güncellemesi yüklendi",
+ "NotificationOptionAudioPlayback": "Ses çalma başladı",
+ "NotificationOptionAudioPlaybackStopped": "Ses çalma durduruldu",
+ "NotificationOptionCameraImageUploaded": "Kamera fotoğrafı yüklendi",
+ "NotificationOptionInstallationFailed": "Kurulum hatası",
+ "NotificationOptionNewLibraryContent": "Yeni içerik eklendi",
+ "NotificationOptionPluginError": "Eklenti hatası",
+ "NotificationOptionPluginInstalled": "Eklenti yüklendi",
+ "NotificationOptionPluginUninstalled": "Eklenti kaldırıldı",
+ "NotificationOptionPluginUpdateInstalled": "Eklenti güncellemesi yüklendi",
+ "NotificationOptionServerRestartRequired": "Sunucu yeniden başlatma gerekli",
+ "NotificationOptionTaskFailed": "Zamanlanmış görev hatası",
+ "NotificationOptionUserLockedOut": "Kullanıcı kitlendi",
+ "NotificationOptionVideoPlayback": "Video oynatma başladı",
+ "NotificationOptionVideoPlaybackStopped": "Video oynatma durduruldu",
+ "Photos": "Fotoğraflar",
+ "Playlists": "Çalma listeleri",
+ "Plugin": "Eklenti",
+ "PluginInstalledWithName": "{0} yüklendi",
+ "PluginUninstalledWithName": "{0} kaldırıldı",
+ "PluginUpdatedWithName": "{0} güncellendi",
+ "ProviderValue": "Sağlayıcı: {0}",
+ "ScheduledTaskFailedWithName": "{0} başarısız oldu",
+ "ScheduledTaskStartedWithName": "{0} başladı",
+ "ServerNameNeedsToBeRestarted": "{0} yeniden başlatılması gerekiyor",
+ "Shows": "Diziler",
+ "Songs": "Şarkılar",
+ "StartupEmbyServerIsLoading": "Jellyfin Sunucusu yükleniyor. Lütfen kısa süre sonra tekrar deneyin.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "Version {0}"
+ "SubtitleDownloadFailureFromForItem": "{1} için alt yazılar {0} 'dan indirilemedi",
+ "Sync": "Eşzamanlama",
+ "System": "Sistem",
+ "TvShows": "Diziler",
+ "User": "Kullanıcı",
+ "UserCreatedWithName": "{0} kullanıcısı oluşturuldu",
+ "UserDeletedWithName": "Kullanıcı {0} silindi",
+ "UserDownloadingItemWithValues": "{0} indiriliyor {1}",
+ "UserLockedOutWithName": "Kullanıcı {0} kitlendi",
+ "UserOfflineFromDevice": "{0}, {1} ile bağlantısı kesildi",
+ "UserOnlineFromDevice": "{0}, {1} çevrimiçi",
+ "UserPasswordChangedWithName": "{0} kullanıcısı için şifre değiştirildi",
+ "UserPolicyUpdatedWithName": "Kullanıcı politikası {0} için güncellendi",
+ "UserStartedPlayingItemWithValues": "{0}, {2} cihazında {1} izliyor",
+ "UserStoppedPlayingItemWithValues": "{0}, {2} cihazında {1} izlemeyi bitirdi",
+ "ValueHasBeenAddedToLibrary": "Medya kütüphanenize {0} eklendi",
+ "ValueSpecialEpisodeName": "Özel - {0}",
+ "VersionNumber": "Sürüm {0}",
+ "TaskCleanCache": "Geçici dosya klasörünü temizle",
+ "TasksChannelsCategory": "İnternet kanalları",
+ "TasksApplicationCategory": "Uygulama",
+ "TasksLibraryCategory": "Kütüphane",
+ "TasksMaintenanceCategory": "Bakım",
+ "TaskRefreshPeopleDescription": "Medya kütüphanenizdeki videoların oyuncu ve yönetmen bilgilerini günceller.",
+ "TaskDownloadMissingSubtitlesDescription": "Metadata ayarlarını baz alarak eksik altyazıları internette arar.",
+ "TaskDownloadMissingSubtitles": "Eksik altyazıları indir",
+ "TaskRefreshChannelsDescription": "Internet kanal bilgilerini yenile.",
+ "TaskRefreshChannels": "Kanalları Yenile",
+ "TaskCleanTranscodeDescription": "Bir günden daha eski dönüştürme dosyalarını siler.",
+ "TaskCleanTranscode": "Dönüşüm Dizinini Temizle",
+ "TaskUpdatePluginsDescription": "Otomatik güncellenmeye ayarlanmış eklentilerin güncellemelerini indirir ve kurar.",
+ "TaskUpdatePlugins": "Eklentileri Güncelle",
+ "TaskRefreshPeople": "Kullanıcıları Yenile",
+ "TaskCleanLogsDescription": "{0} günden eski günlük dosyalarını siler.",
+ "TaskCleanLogs": "Günlük Dizinini Temizle",
+ "TaskRefreshLibraryDescription": "Medya kütüphanenize eklenen yeni dosyaları arar ve ortam bilgilerini yeniler.",
+ "TaskRefreshLibrary": "Medya Kütüphanesini Tara",
+ "TaskRefreshChapterImagesDescription": "Sahnelere ayrılmış videolar için küçük resimler oluştur.",
+ "TaskRefreshChapterImages": "Bölüm Resimlerini Çıkar",
+ "TaskCleanCacheDescription": "Sistem tarafından artık ihtiyaç duyulmayan önbellek dosyalarını siler.",
+ "TaskCleanActivityLog": "Etkinlik Günlüğünü Temizle",
+ "TaskCleanActivityLogDescription": "Yapılandırılan tarihten daha eski olan etkinlik günlüğü girişlerini siler.",
+ "Undefined": "Bilinmeyen",
+ "Default": "Varsayılan",
+ "Forced": "Zorla",
+ "TaskOptimizeDatabaseDescription": "Veritabanını sıkıştırır ve boş alanı keser. Kitaplığı taradıktan sonra veya veritabanında değişiklik anlamına gelen diğer işlemleri yaptıktan sonra bu görevi çalıştırmak performansı artırabilir.",
+ "TaskOptimizeDatabase": "Veritabanını optimize et"
}
diff --git a/Emby.Server.Implementations/Localization/Core/uk.json b/Emby.Server.Implementations/Localization/Core/uk.json
new file mode 100644
index 000000000..e99ed6f0b
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/uk.json
@@ -0,0 +1,123 @@
+{
+ "MusicVideos": "Відеокліпи",
+ "Music": "Музика",
+ "Movies": "Фільми",
+ "MessageApplicationUpdatedTo": "Jellyfin Server оновлено до версії {0}",
+ "MessageApplicationUpdated": "Jellyfin Server оновлено",
+ "Latest": "Останні",
+ "LabelIpAddressValue": "IP-адреса: {0}",
+ "ItemRemovedWithName": "{0} видалено з медіатеки",
+ "ItemAddedWithName": "{0} додано до медіатеки",
+ "HeaderNextUp": "Наступний",
+ "HeaderLiveTV": "Ефірне ТБ",
+ "HeaderFavoriteSongs": "Улюблені пісні",
+ "HeaderFavoriteShows": "Улюблені шоу",
+ "HeaderFavoriteEpisodes": "Улюблені серії",
+ "HeaderFavoriteArtists": "Улюблені виконавці",
+ "HeaderFavoriteAlbums": "Улюблені альбоми",
+ "HeaderContinueWatching": "Продовжити перегляд",
+ "HeaderAlbumArtists": "Виконавці альбомів",
+ "Genres": "Жанри",
+ "Folders": "Каталоги",
+ "Favorites": "Улюблені",
+ "DeviceOnlineWithName": "Пристрій {0} підключився",
+ "DeviceOfflineWithName": "Пристрій {0} відключився",
+ "Collections": "Колекції",
+ "ChapterNameValue": "Розділ {0}",
+ "Channels": "Канали",
+ "CameraImageUploadedFrom": "Нова фотографія завантажена з {0}",
+ "Books": "Книги",
+ "AuthenticationSucceededWithUserName": "{0} успішно автентифіковано",
+ "Artists": "Виконавці",
+ "Application": "Додаток",
+ "AppDeviceValues": "Додаток: {0}, Пристрій: {1}",
+ "Albums": "Альбоми",
+ "NotificationOptionServerRestartRequired": "Необхідно перезапустити сервер",
+ "NotificationOptionPluginUpdateInstalled": "Встановлено оновлення плагіна",
+ "NotificationOptionPluginUninstalled": "Плагін видалено",
+ "NotificationOptionPluginInstalled": "Плагін встановлено",
+ "NotificationOptionPluginError": "Помилка плагіна",
+ "NotificationOptionNewLibraryContent": "Додано новий контент",
+ "HomeVideos": "Мої відео",
+ "FailedLoginAttemptWithUserName": "Невдала спроба входу від {0}",
+ "LabelRunningTimeValue": "Тривалість: {0}",
+ "TaskDownloadMissingSubtitlesDescription": "Шукає в Інтернеті відсутні субтитри на основі конфігурації метаданих.",
+ "TaskDownloadMissingSubtitles": "Завантажити відсутні субтитри",
+ "TaskRefreshChannelsDescription": "Оновлення інформації про Інтернет-канали.",
+ "TaskRefreshChannels": "Оновити канали",
+ "TaskCleanTranscodeDescription": "Вилучає файли для перекодування старше одного дня.",
+ "TaskCleanTranscode": "Очистити каталог перекодування",
+ "TaskUpdatePluginsDescription": "Завантажує та встановлює оновлення для плагінів, налаштованих на автоматичне оновлення.",
+ "TaskUpdatePlugins": "Оновити плагіни",
+ "TaskRefreshPeopleDescription": "Оновлення метаданих для акторів та режисерів у вашій медіатеці.",
+ "TaskRefreshPeople": "Оновити людей",
+ "TaskCleanLogsDescription": "Видаляє файли журналу, яким більше {0} днів.",
+ "TaskCleanLogs": "Очистити журнали",
+ "TaskRefreshLibraryDescription": "Сканує медіатеку на нові файли та оновлює метадані.",
+ "TaskRefreshLibrary": "Сканувати медіатеку",
+ "TaskRefreshChapterImagesDescription": "Створює ескізи для відео, які мають розділи.",
+ "TaskRefreshChapterImages": "Створити ескізи розділів",
+ "TaskCleanCacheDescription": "Видаляє файли кешу, які більше не потрібні системі.",
+ "TaskCleanCache": "Очистити кеш",
+ "TasksChannelsCategory": "Інтернет-канали",
+ "TasksApplicationCategory": "Додаток",
+ "TasksLibraryCategory": "Медіатека",
+ "TasksMaintenanceCategory": "Обслуговування",
+ "VersionNumber": "Версія {0}",
+ "ValueSpecialEpisodeName": "Спецепізод - {0}",
+ "ValueHasBeenAddedToLibrary": "{0} додано до медіатеки",
+ "UserStoppedPlayingItemWithValues": "{0} закінчив відтворення {1} на {2}",
+ "UserStartedPlayingItemWithValues": "{0} відтворює {1} на {2}",
+ "UserPolicyUpdatedWithName": "Політика користувача оновлена для {0}",
+ "UserPasswordChangedWithName": "Пароль змінено для користувача {0}",
+ "UserOnlineFromDevice": "{0} підключився з {1}",
+ "UserOfflineFromDevice": "{0} відключився від {1}",
+ "UserLockedOutWithName": "Користувача {0} заблоковано",
+ "UserDownloadingItemWithValues": "{0} завантажує {1}",
+ "UserDeletedWithName": "Користувача {0} видалено",
+ "UserCreatedWithName": "Користувача {0} створено",
+ "User": "Користувач",
+ "TvShows": "ТВ-шоу",
+ "System": "Система",
+ "Sync": "Синхронізація",
+ "SubtitleDownloadFailureFromForItem": "Не вдалося завантажити субтитри з {0} для {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin Server завантажується. Будь ласка, спробуйте трішки пізніше.",
+ "Songs": "Пісні",
+ "Shows": "Шоу",
+ "ServerNameNeedsToBeRestarted": "{0} потрібно перезапустити",
+ "ScheduledTaskStartedWithName": "{0} розпочато",
+ "ScheduledTaskFailedWithName": "Помилка {0}",
+ "ProviderValue": "Постачальник: {0}",
+ "PluginUpdatedWithName": "{0} оновлено",
+ "PluginUninstalledWithName": "{0} видалено",
+ "PluginInstalledWithName": "{0} встановлено",
+ "Plugin": "Плагін",
+ "Playlists": "Плейлисти",
+ "Photos": "Фотографії",
+ "NotificationOptionVideoPlaybackStopped": "Відтворення відео зупинено",
+ "NotificationOptionVideoPlayback": "Розпочато відтворення відео",
+ "NotificationOptionUserLockedOut": "Користувача заблоковано",
+ "NotificationOptionTaskFailed": "Помилка запланованого завдання",
+ "NotificationOptionInstallationFailed": "Помилка встановлення",
+ "NotificationOptionCameraImageUploaded": "Фотографію завантажено",
+ "NotificationOptionAudioPlaybackStopped": "Відтворення аудіо зупинено",
+ "NotificationOptionAudioPlayback": "Розпочато відтворення аудіо",
+ "NotificationOptionApplicationUpdateInstalled": "Встановлено оновлення додатка",
+ "NotificationOptionApplicationUpdateAvailable": "Доступне оновлення додатка",
+ "NewVersionIsAvailable": "Для завантаження доступна нова версія Jellyfin Server.",
+ "NameSeasonUnknown": "Сезон Невідомий",
+ "NameSeasonNumber": "Сезон {0}",
+ "NameInstallFailed": "Не вдалося встановити {0}",
+ "MixedContent": "Змішаний контент",
+ "MessageServerConfigurationUpdated": "Конфігурація сервера оновлена",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Розділ конфігурації сервера {0} оновлено",
+ "Inherit": "Успадкувати",
+ "HeaderRecordingGroups": "Групи запису",
+ "Forced": "Форсовані",
+ "TaskCleanActivityLogDescription": "Видаляє старші за встановлений термін записи з журналу активності.",
+ "TaskCleanActivityLog": "Очистити журнал активності",
+ "Undefined": "Не визначено",
+ "Default": "За замовчуванням",
+ "TaskOptimizeDatabase": "Оптимізувати базу даних",
+ "TaskOptimizeDatabaseDescription": "Стиснення бази даних та збільшення вільного простору. Виконання цього завдання після сканування бібліотеки або внесення інших змін, які передбачають модифікацію бази даних, може покращити продуктивність."
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ur_PK.json b/Emby.Server.Implementations/Localization/Core/ur_PK.json
new file mode 100644
index 000000000..11af9fc98
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ur_PK.json
@@ -0,0 +1,117 @@
+{
+ "HeaderFavoriteAlbums": "پسندیدہ البمز",
+ "HeaderNextUp": "اگلا",
+ "HeaderFavoriteArtists": "پسندیدہ فنکار",
+ "HeaderAlbumArtists": "البم کے فنکار",
+ "Movies": "فلمیں",
+ "HeaderFavoriteEpisodes": "پسندیدہ اقساط",
+ "Collections": "مجموعہ",
+ "Folders": "فولڈرز",
+ "HeaderLiveTV": "براہ راست ٹی وی",
+ "Channels": "چینلز",
+ "HeaderContinueWatching": "دیکھنا جاری رکھیں",
+ "Playlists": "پلے لسٹس",
+ "ValueSpecialEpisodeName": "خاص - {0}",
+ "Shows": "شوز",
+ "Genres": "انواع",
+ "Artists": "فنکار",
+ "Sync": "مطابقت",
+ "Photos": "تصوریں",
+ "Albums": "البمز",
+ "Favorites": "پسندیدہ",
+ "Songs": "گانے",
+ "Books": "کتابیں",
+ "HeaderFavoriteSongs": "پسندیدہ گانے",
+ "HeaderFavoriteShows": "پسندیدہ شوز",
+ "TaskDownloadMissingSubtitlesDescription": "میٹا ڈیٹا کی تشکیل پر مبنی ذیلی عنوانات کے غائب عنوانات انٹرنیٹ پے تلاش کرتا ہے۔",
+ "TaskDownloadMissingSubtitles": "غائب سب ٹائٹلز ڈاؤن لوڈ کریں",
+ "TaskRefreshChannelsDescription": "انٹرنیٹ چینل کی معلومات کو تازہ دم کرتا ہے۔",
+ "TaskRefreshChannels": "چینلز ریفریش کریں",
+ "TaskCleanTranscodeDescription": "ایک دن سے زیادہ پرانی ٹرانسکوڈ فائلوں کو حذف کرتا ہے۔",
+ "TaskCleanTranscode": "ٹرانس کوڈ ڈائرکٹری صاف کریں",
+ "TaskUpdatePluginsDescription": "پلگ انز کے لئے اپ ڈیٹس ڈاؤن لوڈ اور انسٹال کرتے ہیں جو خود بخود اپ ڈیٹ کرنے کیلئے تشکیل شدہ ہیں۔",
+ "TaskUpdatePlugins": "پلگ انز کو اپ ڈیٹ کریں",
+ "TaskRefreshPeopleDescription": "آپ کی میڈیا لائبریری میں اداکاروں اور ہدایت کاروں کے لئے میٹا ڈیٹا کی تازہ کاری۔",
+ "TaskRefreshPeople": "لوگوں کو تروتازہ کریں",
+ "TaskCleanLogsDescription": "لاگ فائلوں کو حذف کریں جو {0} دن سے زیادہ پرانی ہیں۔",
+ "TaskCleanLogs": "لاگ ڈائرکٹری کو صاف کریں",
+ "TaskRefreshLibraryDescription": "میڈیا لائبریری کو اسکین کرتا ھے ہر میٹا دیٹا کہ تازہ دم کرتا ھے.",
+ "TaskRefreshLibrary": "اسکین میڈیا لائبریری",
+ "TaskRefreshChapterImagesDescription": "بابوں والی ویڈیوز کے لئے تمبنیل بنایں۔",
+ "TaskRefreshChapterImages": "باب کی تصاویر نکالیں",
+ "TaskCleanCacheDescription": "فائلوں کو حذف کریں جنکی ضرورت نھیں ھے۔",
+ "TaskCleanCache": "کیش ڈائرکٹری کلیر کریں",
+ "TasksChannelsCategory": "انٹرنیٹ چینلز",
+ "TasksApplicationCategory": "پروگرام",
+ "TasksLibraryCategory": "لآیبریری",
+ "TasksMaintenanceCategory": "مرمت",
+ "VersionNumber": "ورژن {0}",
+ "ValueHasBeenAddedToLibrary": "{0} آپ کی میڈیا لائبریری میں شامل کر دیا گیا ہے",
+ "UserStoppedPlayingItemWithValues": "{0} نے {1} چلانا ختم کر دیا ھے {2} پے",
+ "UserStartedPlayingItemWithValues": "{0} چلا رہا ہے {1} {2} پے",
+ "UserPolicyUpdatedWithName": "صارف {0} کی پالیسی کیلئے تازہ کاری کی گئی ہے",
+ "UserPasswordChangedWithName": "صارف {0} کے لئے پاس ورڈ تبدیل کر دیا گیا ہے",
+ "UserOnlineFromDevice": "{0} آن لائن ہے {1} سے",
+ "UserOfflineFromDevice": "{0} سے منقطع ہوگیا ہے {1}",
+ "UserLockedOutWithName": "صارف {0} کو لاک آؤٹ کردیا گیا ہے",
+ "UserDownloadingItemWithValues": "{0} ڈاؤن لوڈ کر رھا ھے {1}",
+ "UserDeletedWithName": "صارف {0} کو ہٹا دیا گیا ہے",
+ "UserCreatedWithName": "صارف {0} تشکیل دیا گیا ہے",
+ "User": "صارف",
+ "TvShows": "ٹی وی کے پروگرام",
+ "System": "نظام",
+ "SubtitleDownloadFailureFromForItem": "ذیلی عنوانات {0} سے ڈاؤن لوڈ کرنے میں ناکام {1} کے لیے",
+ "StartupEmbyServerIsLoading": "جیلیفن سرور لوڈ ہورہا ہے۔ براہ کرم جلد ہی دوبارہ کوشش کریں۔",
+ "ServerNameNeedsToBeRestarted": "{0} دوبارہ چلانے کرنے کی ضرورت ہے",
+ "ScheduledTaskStartedWithName": "{0} شروع",
+ "ScheduledTaskFailedWithName": "{0} ناکام",
+ "ProviderValue": "فراہم کرنے والا: {0}",
+ "PluginUpdatedWithName": "{0} تازہ کاری کی گئی تھی",
+ "PluginUninstalledWithName": "[0} ہٹا دیا گیا تھا",
+ "PluginInstalledWithName": "{0} انسٹال کیا گیا تھا",
+ "Plugin": "پلگن",
+ "NotificationOptionVideoPlaybackStopped": "ویڈیو پلے بیک رک گیا",
+ "NotificationOptionVideoPlayback": "ویڈیو پلے بیک شروع ہوا",
+ "NotificationOptionUserLockedOut": "صارف کو لاک آؤٹ کیا گیا",
+ "NotificationOptionTaskFailed": "طے شدہ کام کی ناکامی",
+ "NotificationOptionServerRestartRequired": "سرور دوبارہ چلانے کرنے کی ضرورت ہے",
+ "NotificationOptionPluginUpdateInstalled": "پلگ ان اپ ڈیٹ انسٹال",
+ "NotificationOptionPluginUninstalled": "پلگ ان ہٹا دیا گیا",
+ "NotificationOptionPluginInstalled": "پلگ ان انسٹال ہوا",
+ "NotificationOptionPluginError": "پلگ ان کی ناکامی",
+ "NotificationOptionNewLibraryContent": "نیا مواد شامل کیا گیا",
+ "NotificationOptionInstallationFailed": "تنصیب کی ناکامی",
+ "NotificationOptionCameraImageUploaded": "کیمرے کی تصویر اپ لوڈ ہوگئی",
+ "NotificationOptionAudioPlaybackStopped": "آڈیو پلے بیک رک گیا",
+ "NotificationOptionAudioPlayback": "آڈیو پلے بیک شروع ہوا",
+ "NotificationOptionApplicationUpdateInstalled": "پروگرام اپ ڈیٹ انسٹال ہوچکا ھے",
+ "NotificationOptionApplicationUpdateAvailable": "پروگرام کی تازہ کاری دستیاب ہے",
+ "NewVersionIsAvailable": "جیلیفن سرور کا ایک نیا ورژن ڈاؤن لوڈ کے لئے دستیاب ہے۔",
+ "NameSeasonUnknown": "نامعلوم باب",
+ "NameSeasonNumber": "باب {0}",
+ "NameInstallFailed": "{0} تنصیب ناکام ہوگئی",
+ "MusicVideos": "ویڈیو موسیقی",
+ "Music": "موسیقی",
+ "MixedContent": "مخلوط مواد",
+ "MessageServerConfigurationUpdated": "سرور کو اپ ڈیٹ کر دیا گیا ہے",
+ "MessageNamedServerConfigurationUpdatedWithValue": "سرور ضمن {0} کو ترتیب دے دیا گیا ھے",
+ "MessageApplicationUpdatedTo": "جیلیفن سرور کو اپ ڈیٹ کیا ہے {0}",
+ "MessageApplicationUpdated": "جیلیفن سرور کو اپ ڈیٹ کر دیا گیا ہے",
+ "Latest": "تازہ ترین",
+ "LabelRunningTimeValue": "چلانے کی مدت",
+ "LabelIpAddressValue": "آئ پی ایڈریس {0}",
+ "ItemRemovedWithName": "لائبریری سے ہٹا دیا گیا ھے",
+ "ItemAddedWithName": "[0} لائبریری میں شامل کیا گیا ھے",
+ "Inherit": "وراثت میں",
+ "HomeVideos": "ہوم ویڈیو",
+ "HeaderRecordingGroups": "ریکارڈنگ گروپس",
+ "FailedLoginAttemptWithUserName": "{0} سے لاگ ان کی ناکام کوشش",
+ "DeviceOnlineWithName": "{0} متصل ھو چکا ھے",
+ "DeviceOfflineWithName": "{0} منقطع ھو چکا ھے",
+ "ChapterNameValue": "باب",
+ "AuthenticationSucceededWithUserName": "{0} کامیابی کے ساتھ تصدیق ھوچکی ھے",
+ "CameraImageUploadedFrom": "ایک نئی کیمرہ تصویر اپ لوڈ کی گئی ہے {0}",
+ "Application": "پروگرام",
+ "AppDeviceValues": "پروگرام:{0}, ڈیوائس:{1}",
+ "Forced": "جَبری"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json
new file mode 100644
index 000000000..33aa0eea0
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/vi.json
@@ -0,0 +1,123 @@
+{
+ "Collections": "Bộ Sưu Tập",
+ "Favorites": "Yêu Thích",
+ "Folders": "Thư Mục",
+ "Genres": "Thể Loại",
+ "HeaderAlbumArtists": "Album Nghệ sĩ",
+ "HeaderContinueWatching": "Xem Tiếp",
+ "HeaderLiveTV": "TV Trực Tiếp",
+ "Movies": "Phim",
+ "Photos": "Ảnh",
+ "Playlists": "Danh sách phát",
+ "Shows": "Chương Trình TV",
+ "Songs": "Bài Hát",
+ "Sync": "Đồng Bộ",
+ "ValueSpecialEpisodeName": "Đặc Biệt - {0}",
+ "Albums": "Tuyển Tập",
+ "Artists": "Ca Sĩ",
+ "TaskDownloadMissingSubtitlesDescription": "Tìm kiếm phụ đề bị thiếu trên Internet dựa trên cấu hình dữ liệu mô tả.",
+ "TaskDownloadMissingSubtitles": "Tải Xuống Phụ Đề Bị Thiếu",
+ "TaskRefreshChannelsDescription": "Làm mới thông tin kênh internet.",
+ "TaskRefreshChannels": "Làm Mới Kênh",
+ "TaskCleanTranscodeDescription": "Xóa các tệp chuyển mã cũ hơn một ngày.",
+ "TaskCleanTranscode": "Làm Sạch Thư Mục Chuyển Mã",
+ "TaskUpdatePluginsDescription": "Tải xuống và cài đặt các bản cập nhật cho các plugin được định cấu hình để cập nhật tự động.",
+ "TaskUpdatePlugins": "Cập Nhật Plugins",
+ "TaskRefreshPeopleDescription": "Cập nhật thông tin chi tiết cho diễn viên và đạo diễn trong thư viện phương tiện của bạn.",
+ "TaskRefreshPeople": "Làm Mới Người Dùng",
+ "TaskCleanLogsDescription": "Xóa tập tin nhật ký cũ hơn {0} ngày.",
+ "TaskCleanLogs": "Làm Sạch Thư Mục Nhật Ký",
+ "TaskRefreshLibraryDescription": "Quét thư viện phương tiện của bạn để tìm tệp mới và làm mới dữ liệu mô tả.",
+ "TaskRefreshLibrary": "Quét Thư Viện Phương Tiện",
+ "TaskRefreshChapterImagesDescription": "Tạo hình thu nhỏ cho video có các phân cảnh.",
+ "TaskRefreshChapterImages": "Trích Xuất Ảnh Phân Cảnh",
+ "TaskCleanCacheDescription": "Xóa các tệp cache không còn cần thiết của hệ thống.",
+ "TaskCleanCache": "Làm Sạch Thư Mục Bộ Nhớ Đệm",
+ "TasksChannelsCategory": "Kênh Internet",
+ "TasksApplicationCategory": "Ứng Dụng",
+ "TasksLibraryCategory": "Thư Viện",
+ "TasksMaintenanceCategory": "Bảo Trì",
+ "VersionNumber": "Phiên Bản {0}",
+ "ValueHasBeenAddedToLibrary": "{0} đã được thêm vào thư viện của bạn",
+ "UserStoppedPlayingItemWithValues": "{0} đã phát xong {1} trên {2}",
+ "UserStartedPlayingItemWithValues": "{0} đang phát {1} trên {2}",
+ "UserPolicyUpdatedWithName": "Chính sách người dùng đã được cập nhật cho {0}",
+ "UserPasswordChangedWithName": "Mật khẩu đã được thay đổi cho người dùng {0}",
+ "UserOnlineFromDevice": "{0} trực tuyến từ {1}",
+ "UserOfflineFromDevice": "{0} đã ngắt kết nối từ {1}",
+ "UserLockedOutWithName": "User {0} đã bị khóa",
+ "UserDownloadingItemWithValues": "{0} đang tải xuống {1}",
+ "UserDeletedWithName": "Người Dùng {0} đã được xóa",
+ "UserCreatedWithName": "Người Dùng {0} đã được tạo",
+ "User": "Người Dùng",
+ "TvShows": "Chương Trình TV",
+ "System": "Hệ Thống",
+ "SubtitleDownloadFailureFromForItem": "Không thể tải xuống phụ đề từ {0} cho {1}",
+ "StartupEmbyServerIsLoading": "Jellyfin Server đang tải. Vui lòng thử lại trong thời gian ngắn.",
+ "ServerNameNeedsToBeRestarted": "{0} cần được khởi động lại",
+ "ScheduledTaskStartedWithName": "{0} đã bắt đầu",
+ "ScheduledTaskFailedWithName": "{0} đã thất bại",
+ "ProviderValue": "Provider: {0}",
+ "PluginUpdatedWithName": "{0} đã cập nhật",
+ "PluginUninstalledWithName": "{0} đã được gỡ bỏ",
+ "PluginInstalledWithName": "{0} đã được cài đặt",
+ "Plugin": "Plugin",
+ "NotificationOptionVideoPlaybackStopped": "Phát lại video đã dừng",
+ "NotificationOptionVideoPlayback": "Đã bắt đầu phát lại video",
+ "NotificationOptionUserLockedOut": "Người dùng bị khóa",
+ "NotificationOptionTaskFailed": "Lỗi tác vụ đã lên lịch",
+ "NotificationOptionServerRestartRequired": "Yêu cầu khởi động lại Server",
+ "NotificationOptionPluginUpdateInstalled": "Cập nhật Plugin đã được cài đặt",
+ "NotificationOptionPluginUninstalled": "Đã gỡ bỏ Plugin",
+ "NotificationOptionPluginInstalled": "Đã cài đặt Plugin",
+ "NotificationOptionPluginError": "Thất bại Plugin",
+ "NotificationOptionNewLibraryContent": "Nội dung mới được thêm vào",
+ "NotificationOptionInstallationFailed": "Cài đặt thất bại",
+ "NotificationOptionCameraImageUploaded": "Đã tải lên hình ảnh máy ảnh",
+ "NotificationOptionAudioPlaybackStopped": "Phát lại âm thanh đã dừng",
+ "NotificationOptionAudioPlayback": "Phát lại âm thanh đã bắt đầu",
+ "NotificationOptionApplicationUpdateInstalled": "Bản cập nhật ứng dụng đã được cài đặt",
+ "NotificationOptionApplicationUpdateAvailable": "Bản cập nhật ứng dụng hiện sẵn có",
+ "NewVersionIsAvailable": "Một phiên bản mới của Jellyfin Server sẵn có để tải.",
+ "NameSeasonUnknown": "Không Rõ Mùa",
+ "NameSeasonNumber": "Phần {0}",
+ "NameInstallFailed": "{0} cài đặt thất bại",
+ "MusicVideos": "Videos Nhạc",
+ "Music": "Nhạc",
+ "MixedContent": "Nội dung hỗn hợp",
+ "MessageServerConfigurationUpdated": "Cấu hình máy chủ đã được cập nhật",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Phần cấu hình máy chủ {0} đã được cập nhật",
+ "MessageApplicationUpdatedTo": "Jellyfin Server đã được cập nhật lên {0}",
+ "MessageApplicationUpdated": "Jellyfin Server đã được cập nhật",
+ "Latest": "Gần Nhất",
+ "LabelRunningTimeValue": "Thời Gian Chạy: {0}",
+ "LabelIpAddressValue": "Địa Chỉ IP: {0}",
+ "ItemRemovedWithName": "{0} đã xóa khỏi thư viện",
+ "ItemAddedWithName": "{0} được thêm vào thư viện",
+ "Inherit": "Thừa hưởng",
+ "HomeVideos": "Video nhà",
+ "HeaderRecordingGroups": "Nhóm Ghi Video",
+ "HeaderNextUp": "Tiếp Theo",
+ "HeaderFavoriteSongs": "Bài Hát Yêu Thích",
+ "HeaderFavoriteShows": "Chương Trình Yêu Thích",
+ "HeaderFavoriteEpisodes": "Tập Phim Yêu Thích",
+ "HeaderFavoriteArtists": "Nghệ Sĩ Yêu Thích",
+ "HeaderFavoriteAlbums": "Album Ưa Thích",
+ "FailedLoginAttemptWithUserName": "Nỗ lực đăng nhập thất bại từ {0}",
+ "DeviceOnlineWithName": "{0} đã kết nối",
+ "DeviceOfflineWithName": "{0} đã ngắt kết nối",
+ "ChapterNameValue": "Phân Cảnh {0}",
+ "Channels": "Các Kênh",
+ "CameraImageUploadedFrom": "Một hình ảnh máy ảnh mới đã được tải lên từ {0}",
+ "Books": "Sách",
+ "AuthenticationSucceededWithUserName": "{0} xác thực thành công",
+ "Application": "Ứng Dụng",
+ "AppDeviceValues": "Ứng Dụng: {0}, Thiết Bị: {1}",
+ "TaskCleanActivityLogDescription": "Xóa các mục nhật ký hoạt động cũ hơn độ tuổi đã cài đặt.",
+ "TaskCleanActivityLog": "Xóa Nhật Ký Hoạt Động",
+ "Undefined": "Không Xác Định",
+ "Forced": "Bắt Buộc",
+ "Default": "Mặc Định",
+ "TaskOptimizeDatabaseDescription": "Thu gọn cơ sở dữ liệu và cắt bớt dung lượng trống. Chạy tác vụ này sau khi quét thư viện hoặc thực hiện các thay đổi khác ngụ ý sửa đổi cơ sở dữ liệu có thể cải thiện hiệu suất.",
+ "TaskOptimizeDatabase": "Tối ưu hóa cơ sở dữ liệu"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json
index 8910a6bce..f9df62724 100644
--- a/Emby.Server.Implementations/Localization/Core/zh-CN.json
+++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json
@@ -3,24 +3,23 @@
"AppDeviceValues": "应用: {0}, 设备: {1}",
"Application": "应用程序",
"Artists": "艺术家",
- "AuthenticationSucceededWithUserName": "{0} 成功验证",
+ "AuthenticationSucceededWithUserName": "{0} 认证成功",
"Books": "书籍",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+ "CameraImageUploadedFrom": "新的相机图像已从 {0} 上传",
"Channels": "频道",
"ChapterNameValue": "章节 {0}",
"Collections": "合集",
"DeviceOfflineWithName": "{0} 已断开",
"DeviceOnlineWithName": "{0} 已连接",
"FailedLoginAttemptWithUserName": "来自 {0} 的失败登入",
- "Favorites": "最爱",
+ "Favorites": "我的最爱",
"Folders": "文件夹",
"Genres": "风格",
- "HeaderAlbumArtists": "专辑作家",
- "HeaderCameraUploads": "相机上传",
+ "HeaderAlbumArtists": "专辑艺术家",
"HeaderContinueWatching": "继续观看",
- "HeaderFavoriteAlbums": "最爱的专辑",
- "HeaderFavoriteArtists": "最爱作家",
- "HeaderFavoriteEpisodes": "最爱的集",
+ "HeaderFavoriteAlbums": "收藏的专辑",
+ "HeaderFavoriteArtists": "最爱的艺术家",
+ "HeaderFavoriteEpisodes": "最爱的剧集",
"HeaderFavoriteShows": "最爱的节目",
"HeaderFavoriteSongs": "最爱的歌曲",
"HeaderLiveTV": "电视直播",
@@ -30,21 +29,21 @@
"Inherit": "继承",
"ItemAddedWithName": "{0} 已添加到媒体库",
"ItemRemovedWithName": "{0} 已从媒体库中移除",
- "LabelIpAddressValue": "Ip 地址:{0}",
+ "LabelIpAddressValue": "IP 地址:{0}",
"LabelRunningTimeValue": "运行时间:{0}",
"Latest": "最新",
"MessageApplicationUpdated": "Jellyfin 服务器已更新",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+ "MessageApplicationUpdatedTo": "Jellyfin Server 版本已更新为 {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "服务器配置 {0} 部分已更新",
"MessageServerConfigurationUpdated": "服务器配置已更新",
"MixedContent": "混合内容",
"Movies": "电影",
"Music": "音乐",
"MusicVideos": "音乐视频",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "季 {0}",
+ "NameInstallFailed": "{0} 安装失败",
+ "NameSeasonNumber": "第 {0} 季",
"NameSeasonUnknown": "未知季",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+ "NewVersionIsAvailable": "Jellyfin Server 有新版本可以下载。",
"NotificationOptionApplicationUpdateAvailable": "有可用的应用程序更新",
"NotificationOptionApplicationUpdateInstalled": "应用程序更新已安装",
"NotificationOptionAudioPlayback": "音频开始播放",
@@ -70,16 +69,15 @@
"ProviderValue": "提供商:{0}",
"ScheduledTaskFailedWithName": "{0} 已失败",
"ScheduledTaskStartedWithName": "{0} 已开始",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+ "ServerNameNeedsToBeRestarted": "{0} 需要重新启动",
"Shows": "节目",
"Songs": "歌曲",
"StartupEmbyServerIsLoading": "Jellyfin 服务器加载中。请稍后再试。",
"SubtitleDownloadFailureForItem": "为 {0} 下载字幕失败",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "已为 {0} 下载了字幕",
+ "SubtitleDownloadFailureFromForItem": "无法从 {0} 下载 {1} 的字幕",
"Sync": "同步",
"System": "系统",
- "TvShows": "电视节目",
+ "TvShows": "电视剧",
"User": "用户",
"UserCreatedWithName": "用户 {0} 已创建",
"UserDeletedWithName": "用户 {0} 已删除",
@@ -89,9 +87,38 @@
"UserOnlineFromDevice": "{0} 在线,来自 {1}",
"UserPasswordChangedWithName": "已为用户 {0} 更改密码",
"UserPolicyUpdatedWithName": "用户协议已经被更新为 {0}",
- "UserStartedPlayingItemWithValues": "{0} 已开始播放 {1}",
- "UserStoppedPlayingItemWithValues": "{0} 已停止播放 {1}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+ "UserStartedPlayingItemWithValues": "{0} 已在 {2} 上开始播放 {1}",
+ "UserStoppedPlayingItemWithValues": "{0} 已在 {2} 上停止播放 {1}",
+ "ValueHasBeenAddedToLibrary": "{0} 已添加至您的媒体库中",
"ValueSpecialEpisodeName": "特典 - {0}",
- "VersionNumber": "版本 {0}"
+ "VersionNumber": "版本 {0}",
+ "TaskUpdatePluginsDescription": "为已设置为自动更新的插件下载和安装更新。",
+ "TaskRefreshPeople": "刷新人员",
+ "TasksChannelsCategory": "互联网频道",
+ "TasksLibraryCategory": "媒体库",
+ "TaskDownloadMissingSubtitlesDescription": "根据元数据设置在互联网上搜索缺少的字幕。",
+ "TaskDownloadMissingSubtitles": "下载缺少的字幕",
+ "TaskRefreshChannelsDescription": "刷新互联网频道信息。",
+ "TaskRefreshChannels": "刷新频道",
+ "TaskCleanTranscodeDescription": "删除存在超过 1 天的转码文件。",
+ "TaskCleanTranscode": "清理转码目录",
+ "TaskUpdatePlugins": "更新插件",
+ "TaskRefreshPeopleDescription": "更新媒体库中演员和导演的元数据。",
+ "TaskCleanLogsDescription": "删除存在超过 {0} 天的的日志文件。",
+ "TaskCleanLogs": "清理日志目录",
+ "TaskRefreshLibraryDescription": "扫描你的媒体库以获取新文件并刷新元数据。",
+ "TaskRefreshLibrary": "扫描媒体库",
+ "TaskRefreshChapterImagesDescription": "为包含章节的视频提取缩略图。",
+ "TaskRefreshChapterImages": "提取章节图片",
+ "TaskCleanCacheDescription": "删除系统不再需要的缓存文件。",
+ "TaskCleanCache": "清理缓存目录",
+ "TasksApplicationCategory": "应用程序",
+ "TasksMaintenanceCategory": "维护",
+ "TaskCleanActivityLog": "清理程序日志",
+ "TaskCleanActivityLogDescription": "删除早于设置时间的活动日志条目。",
+ "Undefined": "未定义",
+ "Forced": "强制的",
+ "Default": "默认",
+ "TaskOptimizeDatabaseDescription": "压缩数据库并优化可用空间,在扫描库或执行其他数据库修改后运行此任务可能会提高性能。",
+ "TaskOptimizeDatabase": "优化数据库"
}
diff --git a/Emby.Server.Implementations/Localization/Core/zh-HK.json b/Emby.Server.Implementations/Localization/Core/zh-HK.json
index 387fc2b92..1cc97bc27 100644
--- a/Emby.Server.Implementations/Localization/Core/zh-HK.json
+++ b/Emby.Server.Implementations/Localization/Core/zh-HK.json
@@ -1,97 +1,124 @@
{
- "Albums": "Albums",
- "AppDeviceValues": "App: {0}, Device: {1}",
- "Application": "Application",
- "Artists": "Artists",
- "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
- "Books": "Books",
- "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
- "Channels": "Channels",
- "ChapterNameValue": "Chapter {0}",
- "Collections": "Collections",
- "DeviceOfflineWithName": "{0} has disconnected",
- "DeviceOnlineWithName": "{0} is connected",
- "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
- "Favorites": "Favorites",
- "Folders": "Folders",
- "Genres": "Genres",
- "HeaderAlbumArtists": "Album Artists",
- "HeaderCameraUploads": "Camera Uploads",
- "HeaderContinueWatching": "Continue Watching",
- "HeaderFavoriteAlbums": "Favorite Albums",
- "HeaderFavoriteArtists": "Favorite Artists",
- "HeaderFavoriteEpisodes": "Favorite Episodes",
- "HeaderFavoriteShows": "Favorite Shows",
- "HeaderFavoriteSongs": "Favorite Songs",
- "HeaderLiveTV": "Live TV",
- "HeaderNextUp": "Next Up",
- "HeaderRecordingGroups": "Recording Groups",
- "HomeVideos": "Home videos",
- "Inherit": "Inherit",
- "ItemAddedWithName": "{0} was added to the library",
- "ItemRemovedWithName": "{0} was removed from the library",
- "LabelIpAddressValue": "Ip address: {0}",
- "LabelRunningTimeValue": "Running time: {0}",
- "Latest": "Latest",
- "MessageApplicationUpdated": "Jellyfin Server has been updated",
- "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
- "MessageServerConfigurationUpdated": "Server configuration has been updated",
- "MixedContent": "Mixed content",
- "Movies": "Movies",
- "Music": "Music",
- "MusicVideos": "Music videos",
- "NameInstallFailed": "{0} installation failed",
- "NameSeasonNumber": "Season {0}",
- "NameSeasonUnknown": "Season Unknown",
- "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
- "NotificationOptionApplicationUpdateAvailable": "Application update available",
- "NotificationOptionApplicationUpdateInstalled": "Application update installed",
- "NotificationOptionAudioPlayback": "Audio playback started",
- "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
- "NotificationOptionCameraImageUploaded": "Camera image uploaded",
- "NotificationOptionInstallationFailed": "Installation failure",
- "NotificationOptionNewLibraryContent": "New content added",
- "NotificationOptionPluginError": "Plugin failure",
- "NotificationOptionPluginInstalled": "Plugin installed",
- "NotificationOptionPluginUninstalled": "Plugin uninstalled",
- "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
- "NotificationOptionServerRestartRequired": "Server restart required",
- "NotificationOptionTaskFailed": "Scheduled task failure",
- "NotificationOptionUserLockedOut": "User locked out",
- "NotificationOptionVideoPlayback": "Video playback started",
- "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
- "Photos": "Photos",
- "Playlists": "Playlists",
- "Plugin": "Plugin",
- "PluginInstalledWithName": "{0} was installed",
- "PluginUninstalledWithName": "{0} was uninstalled",
- "PluginUpdatedWithName": "{0} was updated",
- "ProviderValue": "Provider: {0}",
- "ScheduledTaskFailedWithName": "{0} failed",
- "ScheduledTaskStartedWithName": "{0} started",
- "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
- "Shows": "Shows",
- "Songs": "Songs",
- "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+ "Albums": "專輯",
+ "AppDeviceValues": "程式: {0}, 設備: {1}",
+ "Application": "應用程式",
+ "Artists": "藝人",
+ "AuthenticationSucceededWithUserName": "{0} 授權成功",
+ "Books": "圖書",
+ "CameraImageUploadedFrom": "{0} 成功上傳一張新相片",
+ "Channels": "頻道",
+ "ChapterNameValue": "章節 {0}",
+ "Collections": "合輯",
+ "DeviceOfflineWithName": "{0} 已經斷開連結",
+ "DeviceOnlineWithName": "{0} 已經連接",
+ "FailedLoginAttemptWithUserName": "來自 {0} 的登入失敗",
+ "Favorites": "我的最愛",
+ "Folders": "資料夾",
+ "Genres": "風格",
+ "HeaderAlbumArtists": "專輯藝人",
+ "HeaderContinueWatching": "繼續觀看",
+ "HeaderFavoriteAlbums": "最愛專輯",
+ "HeaderFavoriteArtists": "最愛的藝人",
+ "HeaderFavoriteEpisodes": "最愛的劇集",
+ "HeaderFavoriteShows": "最愛的節目",
+ "HeaderFavoriteSongs": "最愛的歌曲",
+ "HeaderLiveTV": "電視直播",
+ "HeaderNextUp": "接下來",
+ "HeaderRecordingGroups": "錄製組",
+ "HomeVideos": "家庭影片",
+ "Inherit": "繼承",
+ "ItemAddedWithName": "{0} 已添加至媒體庫",
+ "ItemRemovedWithName": "{0} 已從媒體庫移除",
+ "LabelIpAddressValue": "IP 地址: {0}",
+ "LabelRunningTimeValue": "運行時間: {0}",
+ "Latest": "最新",
+ "MessageApplicationUpdated": "Jellyfin 伺服器已更新",
+ "MessageApplicationUpdatedTo": "Jellyfin 伺服器已更新至 {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "伺服器設定 {0} 已更新",
+ "MessageServerConfigurationUpdated": "伺服器設定已經更新",
+ "MixedContent": "混合內容",
+ "Movies": "電影",
+ "Music": "音樂",
+ "MusicVideos": "音樂影片",
+ "NameInstallFailed": "{0} 安裝失敗",
+ "NameSeasonNumber": "第 {0} 季",
+ "NameSeasonUnknown": "未知季數",
+ "NewVersionIsAvailable": "新版本的 Jellyfin 伺服器可供下載。",
+ "NotificationOptionApplicationUpdateAvailable": "有可用的應用程式更新",
+ "NotificationOptionApplicationUpdateInstalled": "應用程式已更新",
+ "NotificationOptionAudioPlayback": "開始播放音頻",
+ "NotificationOptionAudioPlaybackStopped": "已停止播放音頻",
+ "NotificationOptionCameraImageUploaded": "相片已上傳",
+ "NotificationOptionInstallationFailed": "安裝失敗",
+ "NotificationOptionNewLibraryContent": "已添加新内容",
+ "NotificationOptionPluginError": "擴充元件錯誤",
+ "NotificationOptionPluginInstalled": "擴充元件已安裝",
+ "NotificationOptionPluginUninstalled": "擴充元件已移除",
+ "NotificationOptionPluginUpdateInstalled": "擴充元件更新已安裝",
+ "NotificationOptionServerRestartRequired": "伺服器需要重啓",
+ "NotificationOptionTaskFailed": "計劃任務失敗",
+ "NotificationOptionUserLockedOut": "用家已鎖定",
+ "NotificationOptionVideoPlayback": "開始播放視頻",
+ "NotificationOptionVideoPlaybackStopped": "已停止播放視頻",
+ "Photos": "相片",
+ "Playlists": "播放清單",
+ "Plugin": "插件",
+ "PluginInstalledWithName": "已安裝 {0}",
+ "PluginUninstalledWithName": "已移除 {0}",
+ "PluginUpdatedWithName": "已更新 {0}",
+ "ProviderValue": "提供者: {0}",
+ "ScheduledTaskFailedWithName": "{0} 任務失敗",
+ "ScheduledTaskStartedWithName": "{0} 任務開始",
+ "ServerNameNeedsToBeRestarted": "{0} 需要重啓",
+ "Shows": "節目",
+ "Songs": "歌曲",
+ "StartupEmbyServerIsLoading": "Jellyfin 伺服器載入中,請稍後再試。",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
- "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
- "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
- "Sync": "Sync",
- "System": "System",
- "TvShows": "TV Shows",
- "User": "User",
- "UserCreatedWithName": "User {0} has been created",
- "UserDeletedWithName": "User {0} has been deleted",
- "UserDownloadingItemWithValues": "{0} is downloading {1}",
- "UserLockedOutWithName": "User {0} has been locked out",
- "UserOfflineFromDevice": "{0} has disconnected from {1}",
- "UserOnlineFromDevice": "{0} is online from {1}",
- "UserPasswordChangedWithName": "Password has been changed for user {0}",
- "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
- "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
- "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
- "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
- "ValueSpecialEpisodeName": "Special - {0}",
- "VersionNumber": "版本{0}"
+ "SubtitleDownloadFailureFromForItem": "無法從 {0} 下載 {1} 的字幕",
+ "Sync": "同步",
+ "System": "系統",
+ "TvShows": "電視節目",
+ "User": "使用者",
+ "UserCreatedWithName": "使用者 {0} 已創建",
+ "UserDeletedWithName": "使用者 {0} 已移除",
+ "UserDownloadingItemWithValues": "{0} 正在下載 {1}",
+ "UserLockedOutWithName": "使用者 {0} 已被鎖定",
+ "UserOfflineFromDevice": "{0} 已從 {1} 斷開",
+ "UserOnlineFromDevice": "{0} 已連綫,來自 {1}",
+ "UserPasswordChangedWithName": "使用者 {0} 的密碼已變更",
+ "UserPolicyUpdatedWithName": "使用者協議已更新為 {0}",
+ "UserStartedPlayingItemWithValues": "{0} 正在 {2} 上播放 {1}",
+ "UserStoppedPlayingItemWithValues": "{0} 已在 {2} 上停止播放 {1}",
+ "ValueHasBeenAddedToLibrary": "{0} 已添加到你的媒體庫",
+ "ValueSpecialEpisodeName": "特典 - {0}",
+ "VersionNumber": "版本{0}",
+ "TaskDownloadMissingSubtitles": "下載遺失的字幕",
+ "TaskUpdatePlugins": "更新插件",
+ "TasksApplicationCategory": "應用程式",
+ "TaskRefreshLibraryDescription": "掃描媒體庫以查找新文件並刷新metadata。",
+ "TasksMaintenanceCategory": "維護",
+ "TaskDownloadMissingSubtitlesDescription": "根據metadata配置在互聯網上搜索缺少的字幕。",
+ "TaskRefreshChannelsDescription": "刷新互聯網頻道信息。",
+ "TaskRefreshChannels": "刷新頻道",
+ "TaskCleanTranscodeDescription": "刪除超過一天的轉碼文件。",
+ "TaskCleanTranscode": "清理轉碼目錄",
+ "TaskUpdatePluginsDescription": "下載並安裝配置為自動更新的插件的更新。",
+ "TaskRefreshPeopleDescription": "更新媒體庫中演員和導演的metadata。",
+ "TaskCleanLogsDescription": "刪除超過{0}天的日誌文件。",
+ "TaskCleanLogs": "清理日誌目錄",
+ "TaskRefreshLibrary": "掃描媒體庫",
+ "TaskRefreshChapterImagesDescription": "為帶有章節的視頻創建縮略圖。",
+ "TaskRefreshChapterImages": "提取章節圖像",
+ "TaskCleanCacheDescription": "刪除系統不再需要的緩存文件。",
+ "TaskCleanCache": "清理緩存目錄",
+ "TasksChannelsCategory": "互聯網頻道",
+ "TasksLibraryCategory": "庫",
+ "TaskRefreshPeople": "刷新人物",
+ "TaskCleanActivityLog": "清理活動記錄",
+ "Undefined": "未定義",
+ "Forced": "強制",
+ "Default": "預設",
+ "TaskOptimizeDatabaseDescription": "壓縮數據庫並截斷可用空間。在掃描媒體庫或執行其他數據庫的修改後運行此任務可能會提高性能。",
+ "TaskOptimizeDatabase": "最佳化數據庫",
+ "TaskCleanActivityLogDescription": "刪除早於設定時間的日誌記錄。"
}
diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json
new file mode 100644
index 000000000..585d81450
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json
@@ -0,0 +1,123 @@
+{
+ "Albums": "專輯",
+ "AppDeviceValues": "App:{0},裝置:{1}",
+ "Application": "應用程式",
+ "Artists": "演出者",
+ "AuthenticationSucceededWithUserName": "{0} 成功授權",
+ "Books": "圖書",
+ "CameraImageUploadedFrom": "{0} 已經成功上傳一張相片",
+ "Channels": "頻道",
+ "ChapterNameValue": "章節 {0}",
+ "Collections": "合輯",
+ "DeviceOfflineWithName": "{0} 已經斷線",
+ "DeviceOnlineWithName": "{0} 已經連線",
+ "FailedLoginAttemptWithUserName": "來自使用者 {0} 的失敗登入",
+ "Favorites": "我的最愛",
+ "Folders": "資料夾",
+ "Genres": "風格",
+ "HeaderAlbumArtists": "專輯演出者",
+ "HeaderContinueWatching": "繼續觀賞",
+ "HeaderFavoriteAlbums": "最愛專輯",
+ "HeaderFavoriteArtists": "最愛演出者",
+ "HeaderFavoriteEpisodes": "最愛影集",
+ "HeaderFavoriteShows": "最愛節目",
+ "HeaderFavoriteSongs": "最愛歌曲",
+ "HeaderLiveTV": "電視直播",
+ "HeaderNextUp": "接下來",
+ "HomeVideos": "家庭影片",
+ "ItemAddedWithName": "{0} 已新增至媒體庫",
+ "ItemRemovedWithName": "{0} 已從媒體庫移除",
+ "LabelIpAddressValue": "IP 位址:{0}",
+ "LabelRunningTimeValue": "運行時間:{0}",
+ "Latest": "最新",
+ "MessageApplicationUpdated": "Jellyfin Server 已經更新",
+ "MessageApplicationUpdatedTo": "Jellyfin Server 已經更新至 {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "伺服器設定 {0} 部分已經更新",
+ "MessageServerConfigurationUpdated": "伺服器設定已經更新",
+ "MixedContent": "混合內容",
+ "Movies": "電影",
+ "Music": "音樂",
+ "MusicVideos": "音樂錄影帶",
+ "NameInstallFailed": "{0} 安裝失敗",
+ "NameSeasonNumber": "第 {0} 季",
+ "NameSeasonUnknown": "未知季數",
+ "NewVersionIsAvailable": "新版本的 Jellyfin Server 軟體已經可供下載。",
+ "NotificationOptionApplicationUpdateAvailable": "有可用的應用程式更新",
+ "NotificationOptionApplicationUpdateInstalled": "軟體更新已安裝",
+ "NotificationOptionAudioPlayback": "音樂開始播放",
+ "NotificationOptionAudioPlaybackStopped": "音樂停止播放",
+ "NotificationOptionCameraImageUploaded": "相機相片已上傳",
+ "NotificationOptionInstallationFailed": "安裝失敗",
+ "NotificationOptionNewLibraryContent": "已新增新內容",
+ "NotificationOptionPluginError": "外掛安裝失敗",
+ "NotificationOptionPluginInstalled": "外掛已安裝",
+ "NotificationOptionPluginUninstalled": "外掛已移除",
+ "NotificationOptionPluginUpdateInstalled": "外掛已更新",
+ "NotificationOptionServerRestartRequired": "伺服器需要重新啟動",
+ "NotificationOptionTaskFailed": "排程任務失敗",
+ "NotificationOptionUserLockedOut": "使用者已鎖定",
+ "NotificationOptionVideoPlayback": "影片開始播放",
+ "NotificationOptionVideoPlaybackStopped": "影片停止播放",
+ "Photos": "相片",
+ "Playlists": "播放清單",
+ "Plugin": "外掛",
+ "PluginInstalledWithName": "{0} 已安裝",
+ "PluginUninstalledWithName": "{0} 已移除",
+ "PluginUpdatedWithName": "{0} 已更新",
+ "ProviderValue": "提供商: {0}",
+ "ScheduledTaskFailedWithName": "排程任務 {0} 已失敗",
+ "ScheduledTaskStartedWithName": "排程任務 {0} 已開始",
+ "ServerNameNeedsToBeRestarted": "伺服器 {0} 需要重新啟動",
+ "Shows": "節目",
+ "Songs": "歌曲",
+ "StartupEmbyServerIsLoading": "Jellyfin Server正在啟動,請稍後再試一次。",
+ "Sync": "同步",
+ "System": "系統",
+ "TvShows": "電視節目",
+ "User": "使用者",
+ "UserCreatedWithName": "使用者 {0} 已建立",
+ "UserDeletedWithName": "使用者 {0} 已移除",
+ "UserDownloadingItemWithValues": "使用者 {0} 正在下載 {1}",
+ "UserLockedOutWithName": "使用者 {0} 已鎖定",
+ "UserOfflineFromDevice": "使用者 {0} 已從 {1} 斷線",
+ "UserOnlineFromDevice": "使用者 {0} 已從 {1} 連線",
+ "UserPasswordChangedWithName": "使用者 {0} 的密碼已變更",
+ "UserPolicyUpdatedWithName": "使用者條約已更新為 {0}",
+ "UserStartedPlayingItemWithValues": "{0}正在使用 {2} 播放 {1}",
+ "UserStoppedPlayingItemWithValues": "{0} 已停止在 {2} 播放 {1}",
+ "ValueHasBeenAddedToLibrary": "{0} 已新增至您的媒體庫",
+ "ValueSpecialEpisodeName": "特典 - {0}",
+ "VersionNumber": "版本 {0}",
+ "HeaderRecordingGroups": "錄製組",
+ "Inherit": "繼承",
+ "SubtitleDownloadFailureFromForItem": "無法為 {1} 從 {0} 下載字幕",
+ "TaskDownloadMissingSubtitlesDescription": "在網路上透過中繼資料搜尋遺失的字幕。",
+ "TaskDownloadMissingSubtitles": "下載遺失的字幕",
+ "TaskRefreshChannels": "重新整理頻道",
+ "TaskUpdatePlugins": "更新外掛",
+ "TaskRefreshPeople": "刷新用戶",
+ "TaskCleanLogsDescription": "刪除超過 {0} 天的舊紀錄檔。",
+ "TaskCleanLogs": "清空紀錄資料夾",
+ "TaskRefreshLibraryDescription": "重新掃描媒體庫的新檔案並更新描述資料。",
+ "TaskRefreshLibrary": "重新掃描媒體庫",
+ "TaskRefreshChapterImages": "擷取章節圖片",
+ "TaskCleanCacheDescription": "刪除系統已不需要的快取。",
+ "TaskCleanCache": "清除快取資料夾",
+ "TasksLibraryCategory": "媒體庫",
+ "TaskRefreshChannelsDescription": "重新整理網路頻道資料。",
+ "TaskCleanTranscodeDescription": "刪除超過一天的轉碼檔案。",
+ "TaskCleanTranscode": "清除轉碼資料夾",
+ "TaskUpdatePluginsDescription": "為設置自動更新的外掛下載並安裝更新。",
+ "TaskRefreshPeopleDescription": "更新媒體庫中演員和導演的中繼資料。",
+ "TaskRefreshChapterImagesDescription": "為有章節的影片建立縮圖。",
+ "TasksChannelsCategory": "網路頻道",
+ "TasksApplicationCategory": "應用程式",
+ "TasksMaintenanceCategory": "維護",
+ "TaskCleanActivityLogDescription": "刪除超過所設時間的活動紀錄。",
+ "TaskCleanActivityLog": "清除活動紀錄",
+ "Undefined": "未定義的",
+ "Forced": "強制",
+ "Default": "原本",
+ "TaskOptimizeDatabaseDescription": "縮小資料庫並釋放可用空間。在掃描資料庫或進行資料庫相關的更動後使用此功能會增加效能。",
+ "TaskOptimizeDatabase": "最佳化資料庫"
+}
diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs
index 31217730b..03919197e 100644
--- a/Emby.Server.Implementations/Localization/LocalizationManager.cs
+++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs
@@ -3,268 +3,199 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
-using System.Linq;
using System.Reflection;
-using System.Text;
+using System.Text.Json;
using System.Threading.Tasks;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Localization
{
/// <summary>
- /// Class LocalizationManager
+ /// Class LocalizationManager.
/// </summary>
public class LocalizationManager : ILocalizationManager
{
- /// <summary>
- /// The _configuration manager
- /// </summary>
- private readonly IServerConfigurationManager _configurationManager;
+ private const string DefaultCulture = "en-US";
+ private const string RatingsPath = "Emby.Server.Implementations.Localization.Ratings.";
+ 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" };
- /// <summary>
- /// The us culture
- /// </summary>
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
+ 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 IFileSystem _fileSystem;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly ILogger _logger;
- private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
+ private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
+ new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
+
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+
+ private List<CultureDto> _cultures = new List<CultureDto>();
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
- /// <param name="fileSystem">The file system.</param>
- /// <param name="jsonSerializer">The json serializer.</param>
+ /// <param name="logger">The logger.</param>
public LocalizationManager(
IServerConfigurationManager configurationManager,
- IFileSystem fileSystem,
- IJsonSerializer jsonSerializer,
- ILoggerFactory loggerFactory)
+ ILogger<LocalizationManager> logger)
{
_configurationManager = configurationManager;
- _fileSystem = fileSystem;
- _jsonSerializer = jsonSerializer;
- _logger = loggerFactory.CreateLogger(nameof(LocalizationManager));
+ _logger = logger;
}
+ /// <summary>
+ /// Loads all resources into memory.
+ /// </summary>
+ /// <returns><see cref="Task" />.</returns>
public async Task LoadAll()
{
- const string ratingsResource = "Emby.Server.Implementations.Localization.Ratings.";
-
- Directory.CreateDirectory(LocalizationPath);
-
- var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName);
-
// Extract from the assembly
foreach (var resource in _assembly.GetManifestResourceNames())
{
- if (!resource.StartsWith(ratingsResource))
+ if (!resource.StartsWith(RatingsPath, StringComparison.Ordinal))
{
continue;
}
- string filename = "ratings-" + resource.Substring(ratingsResource.Length);
-
- if (existingFiles.Contains(filename))
- {
- continue;
- }
+ string countryCode = resource.Substring(RatingsPath.Length, 2);
+ var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
- using (var stream = _assembly.GetManifestResourceStream(resource))
+ await using var stream = _assembly.GetManifestResourceStream(resource);
+ using var reader = new StreamReader(stream!); // shouldn't be null here, we just got the resource path from Assembly.GetManifestResourceNames()
+ await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
- string target = Path.Combine(LocalizationPath, filename);
- _logger.LogInformation("Extracting ratings to {0}", target);
+ if (string.IsNullOrWhiteSpace(line))
+ {
+ continue;
+ }
- using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ 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));
+ }
+#if DEBUG
+ else
{
- await stream.CopyToAsync(fs);
+ _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
}
+#endif
}
- }
- foreach (var file in GetRatingsFiles(LocalizationPath))
- {
- await LoadRatings(file);
+ _allParentalRatings[countryCode] = dict;
}
- LoadAdditionalRatings();
-
- await LoadCultures();
- }
-
- private void LoadAdditionalRatings()
- {
- LoadRatings("au", new[]
- {
- new ParentalRating("AU-G", 1),
- new ParentalRating("AU-PG", 5),
- new ParentalRating("AU-M", 6),
- new ParentalRating("AU-MA15+", 7),
- new ParentalRating("AU-M15+", 8),
- new ParentalRating("AU-R18+", 9),
- new ParentalRating("AU-X18+", 10),
- new ParentalRating("AU-RC", 11)
- });
-
- LoadRatings("be", new[]
- {
- new ParentalRating("BE-AL", 1),
- new ParentalRating("BE-MG6", 2),
- new ParentalRating("BE-6", 3),
- new ParentalRating("BE-9", 5),
- new ParentalRating("BE-12", 6),
- new ParentalRating("BE-16", 8)
- });
-
- LoadRatings("de", new[]
- {
- new ParentalRating("DE-0", 1),
- new ParentalRating("FSK-0", 1),
- new ParentalRating("DE-6", 5),
- new ParentalRating("FSK-6", 5),
- new ParentalRating("DE-12", 7),
- new ParentalRating("FSK-12", 7),
- new ParentalRating("DE-16", 8),
- new ParentalRating("FSK-16", 8),
- new ParentalRating("DE-18", 9),
- new ParentalRating("FSK-18", 9)
- });
-
- LoadRatings("ru", new[]
- {
- new ParentalRating("RU-0+", 1),
- new ParentalRating("RU-6+", 3),
- new ParentalRating("RU-12+", 7),
- new ParentalRating("RU-16+", 9),
- new ParentalRating("RU-18+", 10)
- });
+ await LoadCultures().ConfigureAwait(false);
}
- private void LoadRatings(string country, ParentalRating[] ratings)
- {
- _allParentalRatings[country] = ratings.ToDictionary(i => i.Name);
- }
-
- private IEnumerable<string> GetRatingsFiles(string directory)
- => _fileSystem.GetFilePaths(directory, false)
- .Where(i => string.Equals(Path.GetExtension(i), ".csv", StringComparison.OrdinalIgnoreCase))
- .Where(i => Path.GetFileName(i).StartsWith("ratings-", StringComparison.OrdinalIgnoreCase));
-
- /// <summary>
- /// Gets the localization path.
- /// </summary>
- /// <value>The localization path.</value>
- public string LocalizationPath
- => Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
-
- public string NormalizeFormKD(string text)
- => text.Normalize(NormalizationForm.FormKD);
-
- private CultureDto[] _cultures;
-
/// <summary>
/// Gets the cultures.
/// </summary>
- /// <returns>IEnumerable{CultureDto}.</returns>
- public CultureDto[] GetCultures()
+ /// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
+ public IEnumerable<CultureDto> GetCultures()
=> _cultures;
private async Task LoadCultures()
{
List<CultureDto> list = new List<CultureDto>();
- const string path = "Emby.Server.Implementations.Localization.iso6392.txt";
-
- using (var stream = _assembly.GetManifestResourceStream(path))
- using (var reader = new StreamReader(stream))
+ 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))
{
- while (!reader.EndOfStream)
+ if (string.IsNullOrWhiteSpace(line))
{
- var line = await reader.ReadLineAsync();
+ continue;
+ }
- if (string.IsNullOrWhiteSpace(line))
+ var parts = line.Split('|');
+
+ if (parts.Length == 5)
+ {
+ string name = parts[3];
+ if (string.IsNullOrWhiteSpace(name))
{
continue;
}
- var parts = line.Split('|');
+ string twoCharName = parts[2];
+ if (string.IsNullOrWhiteSpace(twoCharName))
+ {
+ continue;
+ }
- if (parts.Length == 5)
+ string[] threeletterNames;
+ if (string.IsNullOrWhiteSpace(parts[1]))
+ {
+ threeletterNames = new[] { parts[0] };
+ }
+ else
{
- string name = parts[3];
- if (string.IsNullOrWhiteSpace(name))
- {
- continue;
- }
-
- string twoCharName = parts[2];
- if (string.IsNullOrWhiteSpace(twoCharName))
- {
- continue;
- }
-
- string[] threeletterNames;
- if (string.IsNullOrWhiteSpace(parts[1]))
- {
- threeletterNames = new [] { parts[0] };
- }
- else
- {
- threeletterNames = new [] { parts[0], parts[1] };
- }
-
- list.Add(new CultureDto
- {
- DisplayName = name,
- Name = name,
- ThreeLetterISOLanguageNames = threeletterNames,
- TwoLetterISOLanguageName = twoCharName
- });
+ threeletterNames = new[] { parts[0], parts[1] };
}
+
+ list.Add(new CultureDto
+ {
+ DisplayName = name,
+ Name = name,
+ ThreeLetterISOLanguageNames = threeletterNames,
+ TwoLetterISOLanguageName = twoCharName
+ });
}
}
- _cultures = list.ToArray();
+ _cultures = list;
}
- public CultureDto FindLanguageInfo(string language)
- => GetCultures()
- .FirstOrDefault(i =>
- string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase)
- || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase)
- || i.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)
- || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
+ /// <inheritdoc />
+ public CultureDto? FindLanguageInfo(string language)
+ {
+ // TODO language should ideally be a ReadOnlySpan but moq cannot mock ref structs
+ for (var i = 0; i < _cultures.Count; i++)
+ {
+ var culture = _cultures[i];
+ if (language.Equals(culture.DisplayName, StringComparison.OrdinalIgnoreCase)
+ || language.Equals(culture.Name, StringComparison.OrdinalIgnoreCase)
+ || culture.ThreeLetterISOLanguageNames.Contains(language, StringComparison.OrdinalIgnoreCase)
+ || language.Equals(culture.TwoLetterISOLanguageName, StringComparison.OrdinalIgnoreCase))
+ {
+ return culture;
+ }
+ }
+
+ return default;
+ }
- /// <summary>
- /// Gets the countries.
- /// </summary>
- /// <returns>IEnumerable{CountryInfo}.</returns>
- public Task<CountryInfo[]> GetCountries()
- => _jsonSerializer.DeserializeFromStreamAsync<CountryInfo[]>(
- _assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json"));
+ /// <inheritdoc />
+ public IEnumerable<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}'");
+ }
- /// <summary>
- /// Gets the parental ratings.
- /// </summary>
- /// <returns>IEnumerable{ParentalRating}.</returns>
+ /// <inheritdoc />
public IEnumerable<ParentalRating> GetParentalRatings()
=> GetParentalRatingsDictionary().Values;
/// <summary>
/// Gets the parental ratings dictionary.
/// </summary>
- /// <returns>Dictionary{System.StringParentalRating}.</returns>
+ /// <returns><see cref="Dictionary{String, ParentalRating}" />.</returns>
private Dictionary<string, ParentalRating> GetParentalRatingsDictionary()
{
var countryCode = _configurationManager.Configuration.MetadataCountryCode;
@@ -274,66 +205,24 @@ namespace Emby.Server.Implementations.Localization
countryCode = "us";
}
- return GetRatings(countryCode) ?? GetRatings("us");
+ return GetRatings(countryCode)
+ ?? GetRatings("us")
+ ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'");
}
/// <summary>
/// Gets the ratings.
/// </summary>
/// <param name="countryCode">The country code.</param>
- private Dictionary<string, ParentalRating> GetRatings(string countryCode)
+ /// <returns>The ratings.</returns>
+ private Dictionary<string, ParentalRating>? GetRatings(string countryCode)
{
_allParentalRatings.TryGetValue(countryCode, out var value);
return value;
}
- /// <summary>
- /// Loads the ratings.
- /// </summary>
- /// <param name="file">The file.</param>
- /// <returns>Dictionary{System.StringParentalRating}.</returns>
- private async Task LoadRatings(string file)
- {
- Dictionary<string, ParentalRating> dict
- = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
-
- using (var str = File.OpenRead(file))
- using (var reader = new StreamReader(str))
- {
- string line;
- while ((line = await reader.ReadLineAsync()) != null)
- {
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
-
- string[] parts = line.Split(',');
- if (parts.Length == 2
- && int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out var value))
- {
- dict.Add(parts[0], (new ParentalRating { Name = parts[0], Value = value }));
- }
-#if DEBUG
- else
- {
- _logger.LogWarning("Misformed line in {Path}", file);
- }
-#endif
- }
- }
-
- var countryCode = Path.GetFileNameWithoutExtension(file).Split('-')[1];
-
- _allParentalRatings[countryCode] = dict;
- }
-
- private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
-
- /// <summary>
- /// Gets the rating level.
- /// </summary>
+ /// <inheritdoc />
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
@@ -341,7 +230,7 @@ namespace Emby.Server.Implementations.Localization
throw new ArgumentNullException(nameof(rating));
}
- if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase))
+ if (_unratedValues.Contains(rating.AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return null;
}
@@ -351,7 +240,7 @@ namespace Emby.Server.Implementations.Localization
var ratingsDictionary = GetParentalRatingsDictionary();
- if (ratingsDictionary.TryGetValue(rating, out ParentalRating value))
+ if (ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
{
return value.Value;
}
@@ -366,14 +255,14 @@ namespace Emby.Server.Implementations.Localization
}
// Try splitting by : to handle "Germany: FSK 18"
- var index = rating.IndexOf(':');
+ var index = rating.IndexOf(':', StringComparison.Ordinal);
if (index != -1)
{
- rating = rating.Substring(index).TrimStart(':').Trim();
+ var trimmedRating = rating.AsSpan(index).TrimStart(':').Trim();
- if (!string.IsNullOrWhiteSpace(rating))
+ if (!trimmedRating.IsEmpty)
{
- return GetRatingLevel(rating);
+ return GetRatingLevel(trimmedRating.ToString());
}
}
@@ -381,30 +270,20 @@ namespace Emby.Server.Implementations.Localization
return null;
}
- public bool HasUnicodeCategory(string value, UnicodeCategory category)
- {
- foreach (var chr in value)
- {
- if (char.GetUnicodeCategory(chr) == category)
- {
- return true;
- }
- }
-
- return false;
- }
-
+ /// <inheritdoc />
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
+ /// <inheritdoc />
public string GetLocalizedString(string phrase, string culture)
{
if (string.IsNullOrEmpty(culture))
{
culture = _configurationManager.Configuration.UICulture;
}
+
if (string.IsNullOrEmpty(culture))
{
culture = DefaultCulture;
@@ -420,23 +299,19 @@ namespace Emby.Server.Implementations.Localization
return phrase;
}
- private const string DefaultCulture = "en-US";
-
- private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
- new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
-
- public Dictionary<string, string> GetLocalizationDictionary(string culture)
+ private Dictionary<string, string> GetLocalizationDictionary(string culture)
{
if (string.IsNullOrEmpty(culture))
{
throw new ArgumentNullException(nameof(culture));
}
- const string prefix = "Core";
- var key = prefix + culture;
+ const string Prefix = "Core";
- return _dictionaries.GetOrAdd(key,
- f => GetDictionary(prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult());
+ return _dictionaries.GetOrAdd(
+ culture,
+ (key, localizationManager) => localizationManager.GetDictionary(Prefix, key, DefaultCulture + ".json").GetAwaiter().GetResult(),
+ this);
}
private async Task<Dictionary<string, string>> GetDictionary(string prefix, string culture, string baseFilename)
@@ -450,30 +325,31 @@ namespace Emby.Server.Implementations.Localization
var namespaceName = GetType().Namespace + "." + prefix;
- await CopyInto(dictionary, namespaceName + "." + baseFilename);
- await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture));
+ await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
+ await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
return dictionary;
}
private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
{
- using (var stream = _assembly.GetManifestResourceStream(resourcePath))
+ await 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 == null)
{
- // 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 != null)
- {
- var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream);
+ _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
+ return;
+ }
- foreach (var key in dict.Keys)
- {
- dictionary[key] = dict[key];
- }
- }
- else
- {
- _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
- }
+ var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false);
+ if (dict == null)
+ {
+ throw new InvalidOperationException($"Resource contains invalid data: '{stream}'");
+ }
+
+ foreach (var key in dict.Keys)
+ {
+ dictionary[key] = dict[key];
}
}
@@ -493,45 +369,46 @@ namespace Emby.Server.Implementations.Localization
return culture + ".json";
}
- public LocalizationOption[] GetLocalizationOptions()
- => new LocalizationOption[]
- {
- new LocalizationOption("Arabic", "ar"),
- new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG"),
- new LocalizationOption("Catalan", "ca"),
- new LocalizationOption("Chinese Simplified", "zh-CN"),
- new LocalizationOption("Chinese Traditional", "zh-TW"),
- new LocalizationOption("Croatian", "hr"),
- new LocalizationOption("Czech", "cs"),
- new LocalizationOption("Danish", "da"),
- new LocalizationOption("Dutch", "nl"),
- new LocalizationOption("English (United Kingdom)", "en-GB"),
- new LocalizationOption("English (United States)", "en-US"),
- new LocalizationOption("French", "fr"),
- new LocalizationOption("French (Canada)", "fr-CA"),
- new LocalizationOption("German", "de"),
- new LocalizationOption("Greek", "el"),
- new LocalizationOption("Hebrew", "he"),
- new LocalizationOption("Hungarian", "hu"),
- new LocalizationOption("Italian", "it"),
- new LocalizationOption("Kazakh", "kk"),
- new LocalizationOption("Korean", "ko"),
- new LocalizationOption("Lithuanian", "lt-LT"),
- new LocalizationOption("Malay", "ms"),
- new LocalizationOption("Norwegian Bokmål", "nb"),
- new LocalizationOption("Persian", "fa"),
- new LocalizationOption("Polish", "pl"),
- new LocalizationOption("Portuguese (Brazil)", "pt-BR"),
- new LocalizationOption("Portuguese (Portugal)", "pt-PT"),
- new LocalizationOption("Russian", "ru"),
- new LocalizationOption("Slovak", "sk"),
- new LocalizationOption("Slovenian (Slovenia)", "sl-SI"),
- new LocalizationOption("Spanish", "es"),
- new LocalizationOption("Spanish (Argentina)", "es-AR"),
- new LocalizationOption("Spanish (Mexico)", "es-MX"),
- new LocalizationOption("Swedish", "sv"),
- new LocalizationOption("Swiss German", "gsw"),
- new LocalizationOption("Turkish", "tr")
- };
+ /// <inheritdoc />
+ public IEnumerable<LocalizationOption> GetLocalizationOptions()
+ {
+ yield return new LocalizationOption("Arabic", "ar");
+ yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG");
+ yield return new LocalizationOption("Catalan", "ca");
+ yield return new LocalizationOption("Chinese Simplified", "zh-CN");
+ yield return new LocalizationOption("Chinese Traditional", "zh-TW");
+ yield return new LocalizationOption("Croatian", "hr");
+ yield return new LocalizationOption("Czech", "cs");
+ yield return new LocalizationOption("Danish", "da");
+ yield return new LocalizationOption("Dutch", "nl");
+ yield return new LocalizationOption("English (United Kingdom)", "en-GB");
+ yield return new LocalizationOption("English (United States)", "en-US");
+ yield return new LocalizationOption("French", "fr");
+ yield return new LocalizationOption("French (Canada)", "fr-CA");
+ yield return new LocalizationOption("German", "de");
+ yield return new LocalizationOption("Greek", "el");
+ yield return new LocalizationOption("Hebrew", "he");
+ yield return new LocalizationOption("Hungarian", "hu");
+ yield return new LocalizationOption("Italian", "it");
+ yield return new LocalizationOption("Kazakh", "kk");
+ yield return new LocalizationOption("Korean", "ko");
+ yield return new LocalizationOption("Lithuanian", "lt-LT");
+ yield return new LocalizationOption("Malay", "ms");
+ yield return new LocalizationOption("Norwegian Bokmål", "nb");
+ yield return new LocalizationOption("Persian", "fa");
+ yield return new LocalizationOption("Polish", "pl");
+ yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR");
+ yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT");
+ yield return new LocalizationOption("Russian", "ru");
+ yield return new LocalizationOption("Slovak", "sk");
+ yield return new LocalizationOption("Slovenian (Slovenia)", "sl-SI");
+ yield return new LocalizationOption("Spanish", "es");
+ yield return new LocalizationOption("Spanish (Argentina)", "es-AR");
+ yield return new LocalizationOption("Spanish (Mexico)", "es-MX");
+ yield return new LocalizationOption("Swedish", "sv");
+ yield return new LocalizationOption("Swiss German", "gsw");
+ yield return new LocalizationOption("Turkish", "tr");
+ yield return new LocalizationOption("Tiếng Việt", "vi");
+ }
}
}
diff --git a/Emby.Server.Implementations/Localization/Ratings/au.csv b/Emby.Server.Implementations/Localization/Ratings/au.csv
new file mode 100644
index 000000000..940375e26
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/au.csv
@@ -0,0 +1,8 @@
+AU-G,1
+AU-PG,5
+AU-M,6
+AU-MA15+,7
+AU-M15+,8
+AU-R18+,9
+AU-X18+,10
+AU-RC,11
diff --git a/Emby.Server.Implementations/Localization/Ratings/be.csv b/Emby.Server.Implementations/Localization/Ratings/be.csv
new file mode 100644
index 000000000..d3937caf7
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/be.csv
@@ -0,0 +1,6 @@
+BE-AL,1
+BE-MG6,2
+BE-6,3
+BE-9,5
+BE-12,6
+BE-16,8
diff --git a/Emby.Server.Implementations/Localization/Ratings/de.csv b/Emby.Server.Implementations/Localization/Ratings/de.csv
new file mode 100644
index 000000000..f944a140d
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/de.csv
@@ -0,0 +1,10 @@
+DE-0,1
+FSK-0,1
+DE-6,5
+FSK-6,5
+DE-12,7
+FSK-12,7
+DE-16,8
+FSK-16,8
+DE-18,9
+FSK-18,9
diff --git a/Emby.Server.Implementations/Localization/Ratings/ru.csv b/Emby.Server.Implementations/Localization/Ratings/ru.csv
new file mode 100644
index 000000000..1bc94affd
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ru.csv
@@ -0,0 +1,5 @@
+RU-0+,1
+RU-6+,3
+RU-12+,7
+RU-16+,9
+RU-18+,10
diff --git a/Emby.Server.Implementations/Localization/countries.json b/Emby.Server.Implementations/Localization/countries.json
index 581e9f835..b08a3ae79 100644
--- a/Emby.Server.Implementations/Localization/countries.json
+++ b/Emby.Server.Implementations/Localization/countries.json
@@ -558,6 +558,12 @@
"TwoLetterISORegionName": "OM"
},
{
+ "DisplayName": "Palestine",
+ "Name": "PS",
+ "ThreeLetterISORegionName": "PSE",
+ "TwoLetterISORegionName": "PS"
+ },
+ {
"DisplayName": "Panama",
"Name": "PA",
"ThreeLetterISORegionName": "PAN",
diff --git a/Emby.Server.Implementations/Localization/iso6392.txt b/Emby.Server.Implementations/Localization/iso6392.txt
index 40f8614f1..488901822 100644
--- a/Emby.Server.Implementations/Localization/iso6392.txt
+++ b/Emby.Server.Implementations/Localization/iso6392.txt
@@ -77,6 +77,8 @@ chb|||Chibcha|chibcha
che||ce|Chechen|tchétchène
chg|||Chagatai|djaghataï
chi|zho|zh|Chinese|chinois
+chi|zho|zh-tw|Chinese; Traditional|chinois
+chi|zho|zh-hk|Chinese; Hong Kong|chinois
chk|||Chuukese|chuuk
chm|||Mari|mari
chn|||Chinook jargon|chinook, jargon
diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
index e68046f6d..ac6606d39 100644
--- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
+++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -10,30 +14,35 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.MediaEncoder
{
public class EncodingManager : IEncodingManager
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
+ private readonly ILogger<EncodingManager> _logger;
private readonly IMediaEncoder _encoder;
private readonly IChapterManager _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,
- ILoggerFactory loggerFactory,
IMediaEncoder encoder,
- IChapterManager chapterManager, ILibraryManager libraryManager)
+ IChapterManager chapterManager,
+ ILibraryManager libraryManager)
{
+ _logger = logger;
_fileSystem = fileSystem;
- _logger = loggerFactory.CreateLogger(nameof(EncodingManager));
_encoder = encoder;
_chapterManager = chapterManager;
_libraryManager = libraryManager;
@@ -73,16 +82,6 @@ namespace Emby.Server.Implementations.MediaEncoder
return false;
}
- if (video.VideoType == VideoType.Iso)
- {
- return false;
- }
-
- if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
- {
- return false;
- }
-
if (video.IsShortcut)
{
return false;
@@ -97,12 +96,7 @@ namespace Emby.Server.Implementations.MediaEncoder
return video.DefaultVideoStreamIndex.HasValue;
}
- /// <summary>
- /// The first chapter ticks
- /// </summary>
- private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
-
- public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
+ public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
{
if (!IsEligibleForChapterImageExtraction(video))
{
@@ -135,26 +129,30 @@ namespace Emby.Server.Implementations.MediaEncoder
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 time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
- var protocol = MediaProtocol.File;
-
- var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, Array.Empty<string>());
+ 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, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
+ 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
+ catch (IOException ex)
{
-
+ _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
}
chapter.ImagePath = path;
@@ -163,7 +161,7 @@ namespace Emby.Server.Implementations.MediaEncoder
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path));
+ _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
success = false;
break;
}
@@ -184,7 +182,7 @@ namespace Emby.Server.Implementations.MediaEncoder
if (saveChapters && changesMade)
{
- _chapterManager.SaveChapters(video.Id.ToString(), chapters);
+ _chapterManager.SaveChapters(video.Id, chapters);
}
DeleteDeadImages(currentImages, chapters);
@@ -194,23 +192,26 @@ namespace Emby.Server.Implementations.MediaEncoder
private string GetChapterImagePath(Video video, long chapterPositionTicks)
{
- var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
+ var filename = video.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
return Path.Combine(GetChapterImagesPath(video), filename);
}
- private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
+ 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)
- .ToList();
+ return directoryService.GetFilePaths(path);
}
catch (IOException)
{
- return new List<string>();
+ return Array.Empty<string>();
}
}
@@ -223,7 +224,7 @@ namespace Emby.Server.Implementations.MediaEncoder
foreach (var image in deadImages)
{
- _logger.LogDebug("Deleting dead chapter image {path}", image);
+ _logger.LogDebug("Deleting dead chapter image {Path}", image);
try
{
@@ -231,7 +232,7 @@ namespace Emby.Server.Implementations.MediaEncoder
}
catch (IOException ex)
{
- _logger.LogError(ex, "Error deleting {path}.", image);
+ _logger.LogError(ex, "Error deleting {Path}.", image);
}
}
}
diff --git a/Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs b/Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs
deleted file mode 100644
index 304b44565..000000000
--- a/Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-using System;
-
-namespace Emby.Server.Implementations.Net
-{
- /// <summary>
- /// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
- /// </summary>
- public abstract class DisposableManagedObjectBase : IDisposable
- {
-
- #region Public Methods
-
- /// <summary>
- /// Override this method and dispose any objects you own the lifetime of if disposing is true;
- /// </summary>
- /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
- protected abstract void Dispose(bool disposing);
-
-
- //TODO Remove and reimplement using the IsDisposed property directly.
- /// <summary>
- /// Throws an <see cref="ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
- /// </summary>
- /// <seealso cref="IsDisposed"/>
- /// <exception cref="ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
- /// <seealso cref="Dispose()"/>
- protected virtual void ThrowIfDisposed()
- {
- if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
- }
-
- #endregion
-
- #region Public Properties
-
- /// <summary>
- /// Sets or returns a boolean indicating whether or not this instance has been disposed.
- /// </summary>
- /// <seealso cref="Dispose()"/>
- public bool IsDisposed
- {
- get;
- private set;
- }
-
- #endregion
-
- #region IDisposable Members
-
- /// <summary>
- /// Disposes this object instance and all internally managed resources.
- /// </summary>
- /// <remarks>
- /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
- /// </remarks>
- /// <seealso cref="IsDisposed"/>
- public void Dispose()
- {
- IsDisposed = true;
-
- Dispose(true);
- }
-
- #endregion
- }
-}
diff --git a/Emby.Server.Implementations/Net/IWebSocket.cs b/Emby.Server.Implementations/Net/IWebSocket.cs
deleted file mode 100644
index 4671de07c..000000000
--- a/Emby.Server.Implementations/Net/IWebSocket.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-using System;
-using System.Net.WebSockets;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Emby.Server.Implementations.Net
-{
- /// <summary>
- /// Interface IWebSocket
- /// </summary>
- public interface IWebSocket : IDisposable
- {
- /// <summary>
- /// Occurs when [closed].
- /// </summary>
- event EventHandler<EventArgs> Closed;
-
- /// <summary>
- /// Gets or sets the state.
- /// </summary>
- /// <value>The state.</value>
- WebSocketState State { get; }
-
- /// <summary>
- /// Gets or sets the receive action.
- /// </summary>
- /// <value>The receive action.</value>
- Action<byte[]> OnReceiveBytes { get; set; }
-
- /// <summary>
- /// Sends the async.
- /// </summary>
- /// <param name="bytes">The bytes.</param>
- /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken);
-
- /// <summary>
- /// Sends the asynchronous.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken);
- }
-
- public interface IMemoryWebSocket
- {
- Action<Memory<byte>, int> OnReceiveMemoryBytes { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs
index 6beb14f55..6d0c8731e 100644
--- a/Emby.Server.Implementations/Net/SocketFactory.cs
+++ b/Emby.Server.Implementations/Net/SocketFactory.cs
@@ -1,84 +1,28 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.IO;
using System.Net;
using System.Net.Sockets;
-using Emby.Server.Implementations.Networking;
using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Net
{
public class SocketFactory : ISocketFactory
{
- // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
- // Be careful to check any changes compile and work for all platform projects it is shared in.
-
- // Not entirely happy with this. Would have liked to have done something more generic/reusable,
- // but that wasn't really the point so kept to YAGNI principal for now, even if the
- // interfaces are a bit ugly, specific and make assumptions.
-
- public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
- {
- if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
-
- var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
- ? AddressFamily.InterNetwork
- : AddressFamily.InterNetworkV6;
-
- var retVal = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
-
- try
- {
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- }
- catch (SocketException)
- {
- // This is not supported on all operating systems (qnap)
- }
-
- try
- {
- return new UdpSocket(retVal, new IpEndPointInfo(remoteAddress, remotePort));
- }
- catch
- {
- if (retVal != null)
- retVal.Dispose();
-
- throw;
- }
- }
-
- /// <summary>
- /// Creates a new UDP acceptSocket and binds it to the specified local port.
- /// </summary>
- /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
- public ISocket CreateUdpSocket(int localPort)
+ /// <inheritdoc />
+ public ISocket CreateUdpBroadcastSocket(int localPort)
{
- if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
-
- var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
- try
+ if (localPort < 0)
{
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- return new UdpSocket(retVal, localPort, IPAddress.Any);
+ throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
- catch
- {
- if (retVal != null)
- retVal.Dispose();
-
- throw;
- }
- }
-
- public ISocket CreateUdpBroadcastSocket(int localPort)
- {
- if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
{
+ retVal.EnableBroadcast = true;
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
@@ -86,54 +30,60 @@ namespace Emby.Server.Implementations.Net
}
catch
{
- if (retVal != null)
- retVal.Dispose();
+ retVal?.Dispose();
throw;
}
}
- /// <summary>
- /// Creates a new UDP acceptSocket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
- /// </summary>
- /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
- public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
+ /// <inheritdoc />
+ public ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort)
{
- if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+ if (localPort < 0)
+ {
+ throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+ }
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
{
+ retVal.EnableBroadcast = true;
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
- var localIp = NetworkManager.ToIPAddress(localIpAddress);
-
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
return new UdpSocket(retVal, localPort, localIp);
}
catch
{
- if (retVal != null)
- retVal.Dispose();
+ retVal?.Dispose();
throw;
}
}
- /// <summary>
- /// Creates a new UDP acceptSocket that is a member of the specified multicast IP address, and binds it to the specified local port.
- /// </summary>
- /// <param name="ipAddress">The multicast IP address to make the acceptSocket a member of.</param>
- /// <param name="multicastTimeToLive">The multicast time to live value for the acceptSocket.</param>
- /// <param name="localPort">The number of the local port to bind to.</param>
- /// <returns></returns>
+ /// <inheritdoc />
public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
{
- if (ipAddress == null) throw new ArgumentNullException(nameof(ipAddress));
- if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
- if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
- if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+ if (ipAddress == null)
+ {
+ throw new ArgumentNullException(nameof(ipAddress));
+ }
+
+ if (ipAddress.Length == 0)
+ {
+ throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
+ }
+
+ if (multicastTimeToLive <= 0)
+ {
+ throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
+ }
+
+ if (localPort < 0)
+ {
+ throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+ }
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
@@ -144,7 +94,6 @@ namespace Emby.Server.Implementations.Net
}
catch (SocketException)
{
-
}
try
@@ -155,12 +104,12 @@ namespace Emby.Server.Implementations.Net
}
catch (SocketException)
{
-
}
try
{
- //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
+ retVal.EnableBroadcast = true;
+ // retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
var localIp = IPAddress.Any;
@@ -172,87 +121,10 @@ namespace Emby.Server.Implementations.Net
}
catch
{
- if (retVal != null)
- retVal.Dispose();
+ retVal?.Dispose();
throw;
}
}
-
- public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
- {
- var netSocket = (UdpSocket)socket;
-
- return new SocketStream(netSocket.Socket, ownsSocket);
- }
}
-
- public class SocketStream : Stream
- {
- private readonly Socket _socket;
-
- public SocketStream(Socket socket, bool ownsSocket)
- {
- _socket = socket;
- }
-
- public override void Flush()
- {
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => false;
-
- public override bool CanWrite => true;
-
- public override long Length => throw new NotImplementedException();
-
- public override long Position
- {
- get => throw new NotImplementedException();
- set => throw new NotImplementedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- _socket.Send(buffer, offset, count, SocketFlags.None);
- }
-
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
- }
-
- public override void EndWrite(IAsyncResult asyncResult)
- {
- _socket.EndSend(asyncResult);
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- return _socket.Receive(buffer, offset, count, SocketFlags.None);
- }
-
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- return _socket.EndReceive(asyncResult);
- }
- }
-
}
diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs
index d48855486..0c451ccb6 100644
--- a/Emby.Server.Implementations/Net/UdpSocket.cs
+++ b/Emby.Server.Implementations/Net/UdpSocket.cs
@@ -1,9 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
-using Emby.Server.Implementations.Networking;
using MediaBrowser.Model.Net;
namespace Emby.Server.Implementations.Net
@@ -11,12 +14,9 @@ namespace Emby.Server.Implementations.Net
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
// Be careful to check any changes compile and work for all platform projects it is shared in.
- public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
+ public sealed class UdpSocket : ISocket, IDisposable
{
- private Socket _Socket;
- private int _LocalPort;
-
- public Socket Socket => _Socket;
+ private readonly int _localPort;
private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
@@ -28,34 +28,56 @@ namespace Emby.Server.Implementations.Net
SocketFlags = SocketFlags.None
};
+ private Socket _socket;
+ private bool _disposed = false;
private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
private TaskCompletionSource<int> _currentSendTaskCompletionSource;
public UdpSocket(Socket socket, int localPort, IPAddress ip)
{
- if (socket == null) throw new ArgumentNullException(nameof(socket));
+ if (socket == null)
+ {
+ throw new ArgumentNullException(nameof(socket));
+ }
- _Socket = socket;
- _LocalPort = localPort;
- LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
+ _socket = socket;
+ _localPort = localPort;
+ LocalIPAddress = ip;
- _Socket.Bind(new IPEndPoint(ip, _LocalPort));
+ _socket.Bind(new IPEndPoint(ip, _localPort));
InitReceiveSocketAsyncEventArgs();
}
+ public UdpSocket(Socket socket, IPEndPoint endPoint)
+ {
+ if (socket == null)
+ {
+ throw new ArgumentNullException(nameof(socket));
+ }
+
+ _socket = socket;
+ _socket.Connect(endPoint);
+
+ InitReceiveSocketAsyncEventArgs();
+ }
+
+ public Socket Socket => _socket;
+
+ public IPAddress LocalIPAddress { get; }
+
private void InitReceiveSocketAsyncEventArgs()
{
var receiveBuffer = new byte[8192];
_receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
- _receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
+ _receiveSocketAsyncEventArgs.Completed += OnReceiveSocketAsyncEventArgsCompleted;
var sendBuffer = new byte[8192];
_sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
- _sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
+ _sendSocketAsyncEventArgs.Completed += OnSendSocketAsyncEventArgsCompleted;
}
- private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
+ private void OnReceiveSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
@@ -68,7 +90,7 @@ namespace Emby.Server.Implementations.Net
{
Buffer = e.Buffer,
ReceivedBytes = e.BytesTransferred,
- RemoteEndPoint = ToIpEndPointInfo(e.RemoteEndPoint as IPEndPoint),
+ RemoteEndPoint = e.RemoteEndPoint as IPEndPoint,
LocalIPAddress = LocalIPAddress
});
}
@@ -79,7 +101,7 @@ namespace Emby.Server.Implementations.Net
}
}
- private void _sendSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
+ private void OnSendSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentSendTaskCompletionSource;
if (tcs != null)
@@ -97,36 +119,20 @@ namespace Emby.Server.Implementations.Net
}
}
- public UdpSocket(Socket socket, IpEndPointInfo endPoint)
- {
- if (socket == null) throw new ArgumentNullException(nameof(socket));
-
- _Socket = socket;
- _Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
-
- InitReceiveSocketAsyncEventArgs();
- }
-
- public IpAddressInfo LocalIPAddress
- {
- get;
- private set;
- }
-
public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
{
ThrowIfDisposed();
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
- return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
+ return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
}
public int Receive(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
- return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
+ return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
}
public SocketReceiveResult EndReceive(IAsyncResult result)
@@ -136,14 +142,14 @@ namespace Emby.Server.Implementations.Net
var sender = new IPEndPoint(IPAddress.Any, 0);
var remoteEndPoint = (EndPoint)sender;
- var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
+ var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
var buffer = (byte[])result.AsyncState;
return new SocketReceiveResult
{
ReceivedBytes = receivedBytes,
- RemoteEndPoint = ToIpEndPointInfo((IPEndPoint)remoteEndPoint),
+ RemoteEndPoint = (IPEndPoint)remoteEndPoint,
Buffer = buffer,
LocalIPAddress = LocalIPAddress
};
@@ -185,16 +191,7 @@ namespace Emby.Server.Implementations.Net
return taskCompletion.Task;
}
- public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
- {
- ThrowIfDisposed();
-
- var buffer = new byte[8192];
-
- return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
- }
-
- public Task SendToAsync(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
+ public Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken)
{
ThrowIfDisposed();
@@ -217,7 +214,7 @@ namespace Emby.Server.Implementations.Net
}
};
- var result = BeginSendTo(buffer, offset, size, endPoint, new AsyncCallback(callback), null);
+ var result = BeginSendTo(buffer, offset, bytes, endPoint, new AsyncCallback(callback), null);
if (result.CompletedSynchronously)
{
@@ -230,51 +227,47 @@ namespace Emby.Server.Implementations.Net
return taskCompletion.Task;
}
- public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, AsyncCallback callback, object state)
+ public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state)
{
ThrowIfDisposed();
- var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
-
- return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
+ return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state);
}
public int EndSendTo(IAsyncResult result)
{
ThrowIfDisposed();
- return _Socket.EndSendTo(result);
+ return _socket.EndSendTo(result);
}
- protected override void Dispose(bool disposing)
+ private void ThrowIfDisposed()
{
- if (disposing)
+ if (_disposed)
{
- var socket = _Socket;
- if (socket != null)
- socket.Dispose();
-
- var tcs = _currentReceiveTaskCompletionSource;
- if (tcs != null)
- {
- tcs.TrySetCanceled();
- }
- var sendTcs = _currentSendTaskCompletionSource;
- if (sendTcs != null)
- {
- sendTcs.TrySetCanceled();
- }
+ throw new ObjectDisposedException(nameof(UdpSocket));
}
}
- private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
+ /// <inheritdoc />
+ public void Dispose()
{
- if (endpoint == null)
+ if (_disposed)
{
- return null;
+ return;
}
- return NetworkManager.ToIpEndPointInfo(endpoint);
+ _socket?.Dispose();
+ _receiveSocketAsyncEventArgs.Dispose();
+ _sendSocketAsyncEventArgs.Dispose();
+ _currentReceiveTaskCompletionSource?.TrySetCanceled();
+ _currentSendTaskCompletionSource?.TrySetCanceled();
+
+ _socket = null;
+ _currentReceiveTaskCompletionSource = null;
+ _currentSendTaskCompletionSource = null;
+
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/Net/WebSocketConnectEventArgs.cs b/Emby.Server.Implementations/Net/WebSocketConnectEventArgs.cs
deleted file mode 100644
index 3ab8e854a..000000000
--- a/Emby.Server.Implementations/Net/WebSocketConnectEventArgs.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using System;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Net
-{
- public class WebSocketConnectEventArgs : EventArgs
- {
- /// <summary>
- /// Gets or sets the URL.
- /// </summary>
- /// <value>The URL.</value>
- public string Url { get; set; }
- /// <summary>
- /// Gets or sets the query string.
- /// </summary>
- /// <value>The query string.</value>
- public QueryParamCollection QueryString { get; set; }
- /// <summary>
- /// Gets or sets the web socket.
- /// </summary>
- /// <value>The web socket.</value>
- public IWebSocket WebSocket { get; set; }
- /// <summary>
- /// Gets or sets the endpoint.
- /// </summary>
- /// <value>The endpoint.</value>
- public string Endpoint { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/BigIntegerExt.cs b/Emby.Server.Implementations/Networking/IPNetwork/BigIntegerExt.cs
deleted file mode 100644
index e4e944839..000000000
--- a/Emby.Server.Implementations/Networking/IPNetwork/BigIntegerExt.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Numerics;
-using System.Text;
-
-namespace Emby.Server.Implementations.Networking.IPNetwork
-{
- /// <summary>
- /// Extension methods to convert <see cref="BigInteger"/>
- /// instances to hexadecimal, octal, and binary strings.
- /// </summary>
- public static class BigIntegerExtensions
- {
- /// <summary>
- /// Converts a <see cref="BigInteger"/> to a binary string.
- /// </summary>
- /// <param name="bigint">A <see cref="BigInteger"/>.</param>
- /// <returns>
- /// A <see cref="string"/> containing a binary
- /// representation of the supplied <see cref="BigInteger"/>.
- /// </returns>
- public static string ToBinaryString(this BigInteger bigint)
- {
- var bytes = bigint.ToByteArray();
- var idx = bytes.Length - 1;
-
- // Create a StringBuilder having appropriate capacity.
- var base2 = new StringBuilder(bytes.Length * 8);
-
- // Convert first byte to binary.
- var binary = Convert.ToString(bytes[idx], 2);
-
- // Ensure leading zero exists if value is positive.
- if (binary[0] != '0' && bigint.Sign == 1)
- {
- base2.Append('0');
- }
-
- // Append binary string to StringBuilder.
- base2.Append(binary);
-
- // Convert remaining bytes adding leading zeros.
- for (idx--; idx >= 0; idx--)
- {
- base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));
- }
-
- return base2.ToString();
- }
-
- /// <summary>
- /// Converts a <see cref="BigInteger"/> to a hexadecimal string.
- /// </summary>
- /// <param name="bigint">A <see cref="BigInteger"/>.</param>
- /// <returns>
- /// A <see cref="string"/> containing a hexadecimal
- /// representation of the supplied <see cref="BigInteger"/>.
- /// </returns>
- public static string ToHexadecimalString(this BigInteger bigint)
- {
- return bigint.ToString("X");
- }
-
- /// <summary>
- /// Converts a <see cref="BigInteger"/> to a octal string.
- /// </summary>
- /// <param name="bigint">A <see cref="BigInteger"/>.</param>
- /// <returns>
- /// A <see cref="string"/> containing an octal
- /// representation of the supplied <see cref="BigInteger"/>.
- /// </returns>
- public static string ToOctalString(this BigInteger bigint)
- {
- var bytes = bigint.ToByteArray();
- var idx = bytes.Length - 1;
-
- // Create a StringBuilder having appropriate capacity.
- var base8 = new StringBuilder(((bytes.Length / 3) + 1) * 8);
-
- // Calculate how many bytes are extra when byte array is split
- // into three-byte (24-bit) chunks.
- var extra = bytes.Length % 3;
-
- // If no bytes are extra, use three bytes for first chunk.
- if (extra == 0)
- {
- extra = 3;
- }
-
- // Convert first chunk (24-bits) to integer value.
- int int24 = 0;
- for (; extra != 0; extra--)
- {
- int24 <<= 8;
- int24 += bytes[idx--];
- }
-
- // Convert 24-bit integer to octal without adding leading zeros.
- var octal = Convert.ToString(int24, 8);
-
- // Ensure leading zero exists if value is positive.
- if (octal[0] != '0')
- {
- if (bigint.Sign == 1)
- {
- base8.Append('0');
- }
- }
-
- // Append first converted chunk to StringBuilder.
- base8.Append(octal);
-
- // Convert remaining 24-bit chunks, adding leading zeros.
- for (; idx >= 0; idx -= 3)
- {
- int24 = (bytes[idx] << 16) + (bytes[idx - 1] << 8) + bytes[idx - 2];
- base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0'));
- }
-
- return base8.ToString();
- }
-
- /// <summary>
- ///
- /// Reverse a Positive BigInteger ONLY
- /// Bitwise ~ operator
- ///
- /// Input : FF FF FF FF
- /// Width : 4
- /// Result : 00 00 00 00
- ///
- ///
- /// Input : 00 00 00 00
- /// Width : 4
- /// Result : FF FF FF FF
- ///
- /// Input : FF FF FF FF
- /// Width : 8
- /// Result : FF FF FF FF 00 00 00 00
- ///
- ///
- /// Input : 00 00 00 00
- /// Width : 8
- /// Result : FF FF FF FF FF FF FF FF
- ///
- /// </summary>
- /// <param name="input"></param>
- /// <param name="width"></param>
- /// <returns></returns>
- public static BigInteger PositiveReverse(this BigInteger input, int width)
- {
-
- var result = new List<byte>();
- var bytes = input.ToByteArray();
- var work = new byte[width];
- Array.Copy(bytes, 0, work, 0, bytes.Length - 1); // Length -1 : positive BigInteger
-
- for (int i = 0; i < work.Length; i++)
- {
- result.Add((byte)(~work[i]));
- }
- result.Add(0); // positive BigInteger
- return new BigInteger(result.ToArray());
-
- }
- }
-}
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/IPAddressCollection.cs b/Emby.Server.Implementations/Networking/IPNetwork/IPAddressCollection.cs
deleted file mode 100644
index a0c5f73af..000000000
--- a/Emby.Server.Implementations/Networking/IPNetwork/IPAddressCollection.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Net;
-using System.Numerics;
-
-namespace Emby.Server.Implementations.Networking.IPNetwork
-{
- public class IPAddressCollection : IEnumerable<IPAddress>, IEnumerator<IPAddress>
- {
-
- private IPNetwork _ipnetwork;
- private BigInteger _enumerator;
-
- internal IPAddressCollection(IPNetwork ipnetwork)
- {
- this._ipnetwork = ipnetwork;
- this._enumerator = -1;
- }
-
-
- #region Count, Array, Enumerator
-
- public BigInteger Count => this._ipnetwork.Total;
-
- public IPAddress this[BigInteger i]
- {
- get
- {
- if (i >= this.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(i));
- }
- byte width = this._ipnetwork.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? (byte)32 : (byte)128;
- var ipn = this._ipnetwork.Subnet(width);
- return ipn[i].Network;
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- IEnumerator<IPAddress> IEnumerable<IPAddress>.GetEnumerator()
- {
- return this;
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this;
- }
-
- #region IEnumerator<IPNetwork> Members
-
- public IPAddress Current => this[this._enumerator];
-
- #endregion
-
- #region IDisposable Members
-
- public void Dispose()
- {
- // nothing to dispose
- return;
- }
-
- #endregion
-
- #region IEnumerator Members
-
- object IEnumerator.Current => this.Current;
-
- public bool MoveNext()
- {
- this._enumerator++;
- if (this._enumerator >= this.Count)
- {
- return false;
- }
- return true;
-
- }
-
- public void Reset()
- {
- this._enumerator = -1;
- }
-
- #endregion
-
- #endregion
- }
-}
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs b/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs
deleted file mode 100644
index d6de61c0c..000000000
--- a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs
+++ /dev/null
@@ -1,2008 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Numerics;
-using System.Text.RegularExpressions;
-
-namespace Emby.Server.Implementations.Networking.IPNetwork
-{
- /// <summary>
- /// IP Network utility class.
- /// Use IPNetwork.Parse to create instances.
- /// </summary>
- public class IPNetwork : IComparable<IPNetwork>
- {
-
- #region properties
-
- //private uint _network;
- private BigInteger _ipaddress;
- private AddressFamily _family;
- //private uint _netmask;
- //private uint _broadcast;
- //private uint _firstUsable;
- //private uint _lastUsable;
- //private uint _usable;
- private byte _cidr;
-
- #endregion
-
- #region accessors
-
- private BigInteger _network
- {
- get
- {
- var uintNetwork = this._ipaddress & this._netmask;
- return uintNetwork;
- }
- }
-
- /// <summary>
- /// Network address
- /// </summary>
- public IPAddress Network => IPNetwork.ToIPAddress(this._network, this._family);
-
- /// <summary>
- /// Address Family
- /// </summary>
- public AddressFamily AddressFamily => this._family;
-
- private BigInteger _netmask => IPNetwork.ToUint(this._cidr, this._family);
-
- /// <summary>
- /// Netmask
- /// </summary>
- public IPAddress Netmask => IPNetwork.ToIPAddress(this._netmask, this._family);
-
- private BigInteger _broadcast
- {
- get
- {
-
- int width = this._family == System.Net.Sockets.AddressFamily.InterNetwork ? 4 : 16;
- var uintBroadcast = this._network + this._netmask.PositiveReverse(width);
- return uintBroadcast;
- }
- }
-
- /// <summary>
- /// Broadcast address
- /// </summary>
- public IPAddress Broadcast
- {
- get
- {
- if (this._family == System.Net.Sockets.AddressFamily.InterNetworkV6)
- {
- return null;
- }
- return IPNetwork.ToIPAddress(this._broadcast, this._family);
- }
- }
-
- /// <summary>
- /// First usable IP adress in Network
- /// </summary>
- public IPAddress FirstUsable
- {
- get
- {
- var fisrt = this._family == System.Net.Sockets.AddressFamily.InterNetworkV6
- ? this._network
- : (this.Usable <= 0) ? this._network : this._network + 1;
- return IPNetwork.ToIPAddress(fisrt, this._family);
- }
- }
-
- /// <summary>
- /// Last usable IP adress in Network
- /// </summary>
- public IPAddress LastUsable
- {
- get
- {
- var last = this._family == System.Net.Sockets.AddressFamily.InterNetworkV6
- ? this._broadcast
- : (this.Usable <= 0) ? this._network : this._broadcast - 1;
- return IPNetwork.ToIPAddress(last, this._family);
- }
- }
-
- /// <summary>
- /// Number of usable IP adress in Network
- /// </summary>
- public BigInteger Usable
- {
- get
- {
-
- if (this._family == System.Net.Sockets.AddressFamily.InterNetworkV6)
- {
- return this.Total;
- }
- byte[] mask = new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00 };
- var bmask = new BigInteger(mask);
- var usableIps = (_cidr > 30) ? 0 : ((bmask >> _cidr) - 1);
- return usableIps;
- }
- }
-
- /// <summary>
- /// Number of IP adress in Network
- /// </summary>
- public BigInteger Total
- {
- get
- {
-
- int max = this._family == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
- var count = BigInteger.Pow(2, (max - _cidr));
- return count;
- }
- }
-
-
- /// <summary>
- /// The CIDR netmask notation
- /// </summary>
- public byte Cidr => this._cidr;
-
- #endregion
-
- #region constructor
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
-
- IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr)
- {
-
- int maxCidr = family == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
- if (cidr > maxCidr)
- {
- throw new ArgumentOutOfRangeException(nameof(cidr));
- }
-
- this._ipaddress = ipaddress;
- this._family = family;
- this._cidr = cidr;
-
- }
-
- #endregion
-
- #region parsers
-
- /// <summary>
- /// 192.168.168.100 - 255.255.255.0
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static IPNetwork Parse(string ipaddress, string netmask)
- {
-
- IPNetwork ipnetwork = null;
- IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
- return ipnetwork;
- }
-
- /// <summary>
- /// 192.168.168.100/24
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static IPNetwork Parse(string ipaddress, byte cidr)
- {
-
- IPNetwork ipnetwork = null;
- IPNetwork.InternalParse(false, ipaddress, cidr, out ipnetwork);
- return ipnetwork;
-
- }
-
- /// <summary>
- /// 192.168.168.100 255.255.255.0
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static IPNetwork Parse(IPAddress ipaddress, IPAddress netmask)
- {
-
- IPNetwork ipnetwork = null;
- IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
- return ipnetwork;
-
- }
-
- /// <summary>
- /// 192.168.0.1/24
- /// 192.168.0.1 255.255.255.0
- ///
- /// Network : 192.168.0.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.0.1
- /// End : 192.168.0.254
- /// Broadcast : 192.168.0.255
- /// </summary>
- /// <param name="network"></param>
- /// <returns></returns>
- public static IPNetwork Parse(string network)
- {
-
- IPNetwork ipnetwork = null;
- IPNetwork.InternalParse(false, network, out ipnetwork);
- return ipnetwork;
-
- }
-
- #endregion
-
- #region TryParse
-
-
-
- /// <summary>
- /// 192.168.168.100 - 255.255.255.0
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static bool TryParse(string ipaddress, string netmask, out IPNetwork ipnetwork)
- {
-
- IPNetwork ipnetwork2 = null;
- IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
- bool parsed = (ipnetwork2 != null);
- ipnetwork = ipnetwork2;
- return parsed;
-
- }
-
-
-
- /// <summary>
- /// 192.168.168.100/24
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static bool TryParse(string ipaddress, byte cidr, out IPNetwork ipnetwork)
- {
-
- IPNetwork ipnetwork2 = null;
- IPNetwork.InternalParse(true, ipaddress, cidr, out ipnetwork2);
- bool parsed = (ipnetwork2 != null);
- ipnetwork = ipnetwork2;
- return parsed;
-
- }
-
- /// <summary>
- /// 192.168.0.1/24
- /// 192.168.0.1 255.255.255.0
- ///
- /// Network : 192.168.0.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.0.1
- /// End : 192.168.0.254
- /// Broadcast : 192.168.0.255
- /// </summary>
- /// <param name="network"></param>
- /// <param name="ipnetwork"></param>
- /// <returns></returns>
- public static bool TryParse(string network, out IPNetwork ipnetwork)
- {
-
- IPNetwork ipnetwork2 = null;
- IPNetwork.InternalParse(true, network, out ipnetwork2);
- bool parsed = (ipnetwork2 != null);
- ipnetwork = ipnetwork2;
- return parsed;
-
- }
-
- /// <summary>
- /// 192.168.0.1/24
- /// 192.168.0.1 255.255.255.0
- ///
- /// Network : 192.168.0.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.0.1
- /// End : 192.168.0.254
- /// Broadcast : 192.168.0.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <param name="ipnetwork"></param>
- /// <returns></returns>
- public static bool TryParse(IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
- {
-
- IPNetwork ipnetwork2 = null;
- IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
- bool parsed = (ipnetwork2 != null);
- ipnetwork = ipnetwork2;
- return parsed;
-
- }
-
-
- #endregion
-
- #region InternalParse
-
- /// <summary>
- /// 192.168.168.100 - 255.255.255.0
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <returns></returns>
- private static void InternalParse(bool tryParse, string ipaddress, string netmask, out IPNetwork ipnetwork)
- {
-
- if (string.IsNullOrEmpty(ipaddress))
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
- ipnetwork = null;
- return;
- }
-
- if (string.IsNullOrEmpty(netmask))
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(netmask));
- }
- ipnetwork = null;
- return;
- }
-
- IPAddress ip = null;
- bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
- if (ipaddressParsed == false)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("ipaddress");
- }
- ipnetwork = null;
- return;
- }
-
- IPAddress mask = null;
- bool netmaskParsed = IPAddress.TryParse(netmask, out mask);
- if (netmaskParsed == false)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("netmask");
- }
- ipnetwork = null;
- return;
- }
-
- IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
- }
-
- private static void InternalParse(bool tryParse, string network, out IPNetwork ipnetwork)
- {
-
- if (string.IsNullOrEmpty(network))
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(network));
- }
- ipnetwork = null;
- return;
- }
-
- network = Regex.Replace(network, @"[^0-9a-fA-F\.\/\s\:]+", "");
- network = Regex.Replace(network, @"\s{2,}", " ");
- network = network.Trim();
- string[] args = network.Split(new char[] { ' ', '/' });
- byte cidr = 0;
- if (args.Length == 1)
- {
-
- if (IPNetwork.TryGuessCidr(args[0], out cidr))
- {
- IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
- return;
- }
-
- if (tryParse == false)
- {
- throw new ArgumentException("network");
- }
- ipnetwork = null;
- return;
- }
-
- if (byte.TryParse(args[1], out cidr))
- {
- IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
- return;
- }
-
- IPNetwork.InternalParse(tryParse, args[0], args[1], out ipnetwork);
- return;
-
- }
-
-
-
- /// <summary>
- /// 192.168.168.100 255.255.255.0
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="netmask"></param>
- /// <returns></returns>
- private static void InternalParse(bool tryParse, IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
- {
-
- if (ipaddress == null)
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
- ipnetwork = null;
- return;
- }
-
- if (netmask == null)
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(netmask));
- }
- ipnetwork = null;
- return;
- }
-
- var uintIpAddress = IPNetwork.ToBigInteger(ipaddress);
- bool parsed = IPNetwork.TryToCidr(netmask, out var cidr2);
- if (parsed == false)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("netmask");
- }
- ipnetwork = null;
- return;
- }
- byte cidr = (byte)cidr2;
-
- var ipnet = new IPNetwork(uintIpAddress, ipaddress.AddressFamily, cidr);
- ipnetwork = ipnet;
-
- return;
- }
-
-
-
- /// <summary>
- /// 192.168.168.100/24
- ///
- /// Network : 192.168.168.0
- /// Netmask : 255.255.255.0
- /// Cidr : 24
- /// Start : 192.168.168.1
- /// End : 192.168.168.254
- /// Broadcast : 192.168.168.255
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <param name="cidr"></param>
- /// <returns></returns>
- private static void InternalParse(bool tryParse, string ipaddress, byte cidr, out IPNetwork ipnetwork)
- {
-
- if (string.IsNullOrEmpty(ipaddress))
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
- ipnetwork = null;
- return;
- }
-
-
- IPAddress ip = null;
- bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
- if (ipaddressParsed == false)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("ipaddress");
- }
- ipnetwork = null;
- return;
- }
-
- IPAddress mask = null;
- bool parsedNetmask = IPNetwork.TryToNetmask(cidr, ip.AddressFamily, out mask);
- if (parsedNetmask == false)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("cidr");
- }
- ipnetwork = null;
- return;
- }
-
-
- IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
- }
-
- #endregion
-
- #region converters
-
- #region ToUint
-
- /// <summary>
- /// Convert an ipadress to decimal
- /// 0.0.0.0 -> 0
- /// 0.0.1.0 -> 256
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <returns></returns>
- public static BigInteger ToBigInteger(IPAddress ipaddress)
- {
- IPNetwork.InternalToBigInteger(false, ipaddress, out var uintIpAddress);
- return (BigInteger)uintIpAddress;
-
- }
-
- /// <summary>
- /// Convert an ipadress to decimal
- /// 0.0.0.0 -> 0
- /// 0.0.1.0 -> 256
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <returns></returns>
- public static bool TryToBigInteger(IPAddress ipaddress, out BigInteger? uintIpAddress)
- {
- IPNetwork.InternalToBigInteger(true, ipaddress, out var uintIpAddress2);
- bool parsed = (uintIpAddress2 != null);
- uintIpAddress = uintIpAddress2;
- return parsed;
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static void InternalToBigInteger(bool tryParse, IPAddress ipaddress, out BigInteger? uintIpAddress)
- {
-
- if (ipaddress == null)
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
- uintIpAddress = null;
- return;
- }
-
- byte[] bytes = ipaddress.GetAddressBytes();
- /// 20180217 lduchosal
- /// code impossible to reach, GetAddressBytes returns either 4 or 16 bytes length addresses
- /// if (bytes.Length != 4 && bytes.Length != 16) {
- /// if (tryParse == false) {
- /// throw new ArgumentException("bytes");
- /// }
- /// uintIpAddress = null;
- /// return;
- /// }
-
- Array.Reverse(bytes);
- var unsigned = new List<byte>(bytes);
- unsigned.Add(0);
- uintIpAddress = new BigInteger(unsigned.ToArray());
- return;
- }
-
-
- /// <summary>
- /// Convert a cidr to BigInteger netmask
- /// </summary>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static BigInteger ToUint(byte cidr, AddressFamily family)
- {
- IPNetwork.InternalToBigInteger(false, cidr, family, out var uintNetmask);
- return (BigInteger)uintNetmask;
- }
-
-
- /// <summary>
- /// Convert a cidr to uint netmask
- /// </summary>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static bool TryToUint(byte cidr, AddressFamily family, out BigInteger? uintNetmask)
- {
- IPNetwork.InternalToBigInteger(true, cidr, family, out var uintNetmask2);
- bool parsed = (uintNetmask2 != null);
- uintNetmask = uintNetmask2;
- return parsed;
- }
-
- /// <summary>
- /// Convert a cidr to uint netmask
- /// </summary>
- /// <param name="cidr"></param>
- /// <returns></returns>
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static void InternalToBigInteger(bool tryParse, byte cidr, AddressFamily family, out BigInteger? uintNetmask)
- {
-
- if (family == AddressFamily.InterNetwork && cidr > 32)
- {
- if (tryParse == false)
- {
- throw new ArgumentOutOfRangeException(nameof(cidr));
- }
- uintNetmask = null;
- return;
- }
-
- if (family == AddressFamily.InterNetworkV6 && cidr > 128)
- {
- if (tryParse == false)
- {
- throw new ArgumentOutOfRangeException(nameof(cidr));
- }
- uintNetmask = null;
- return;
- }
-
- if (family != AddressFamily.InterNetwork
- && family != AddressFamily.InterNetworkV6)
- {
- if (tryParse == false)
- {
- throw new NotSupportedException(family.ToString());
- }
- uintNetmask = null;
- return;
- }
-
- if (family == AddressFamily.InterNetwork)
- {
-
- uintNetmask = cidr == 0 ? 0 : 0xffffffff << (32 - cidr);
- return;
- }
-
- var mask = new BigInteger(new byte[] {
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0x00
- });
-
- var masked = cidr == 0 ? 0 : mask << (128 - cidr);
- byte[] m = masked.ToByteArray();
- byte[] bmask = new byte[17];
- int copy = m.Length > 16 ? 16 : m.Length;
- Array.Copy(m, 0, bmask, 0, copy);
- uintNetmask = new BigInteger(bmask);
-
-
- }
-
- #endregion
-
- #region ToCidr
-
- /// <summary>
- /// Convert netmask to CIDR
- /// 255.255.255.0 -> 24
- /// 255.255.0.0 -> 16
- /// 255.0.0.0 -> 8
- /// </summary>
- /// <param name="netmask"></param>
- /// <returns></returns>
- private static void InternalToCidr(bool tryParse, BigInteger netmask, AddressFamily family, out byte? cidr)
- {
-
- if (!IPNetwork.InternalValidNetmask(netmask, family))
- {
- if (tryParse == false)
- {
- throw new ArgumentException("netmask");
- }
- cidr = null;
- return;
- }
-
- byte cidr2 = IPNetwork.BitsSet(netmask, family);
- cidr = cidr2;
- return;
-
- }
- /// <summary>
- /// Convert netmask to CIDR
- /// 255.255.255.0 -> 24
- /// 255.255.0.0 -> 16
- /// 255.0.0.0 -> 8
- /// </summary>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static byte ToCidr(IPAddress netmask)
- {
- IPNetwork.InternalToCidr(false, netmask, out var cidr);
- return (byte)cidr;
- }
-
- /// <summary>
- /// Convert netmask to CIDR
- /// 255.255.255.0 -> 24
- /// 255.255.0.0 -> 16
- /// 255.0.0.0 -> 8
- /// </summary>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static bool TryToCidr(IPAddress netmask, out byte? cidr)
- {
- IPNetwork.InternalToCidr(true, netmask, out var cidr2);
- bool parsed = (cidr2 != null);
- cidr = cidr2;
- return parsed;
- }
-
- private static void InternalToCidr(bool tryParse, IPAddress netmask, out byte? cidr)
- {
-
- if (netmask == null)
- {
- if (tryParse == false)
- {
- throw new ArgumentNullException(nameof(netmask));
- }
- cidr = null;
- return;
- }
-
- bool parsed = IPNetwork.TryToBigInteger(netmask, out var uintNetmask2);
-
- /// 20180217 lduchosal
- /// impossible to reach code.
- /// if (parsed == false) {
- /// if (tryParse == false) {
- /// throw new ArgumentException("netmask");
- /// }
- /// cidr = null;
- /// return;
- /// }
- var uintNetmask = (BigInteger)uintNetmask2;
-
- IPNetwork.InternalToCidr(tryParse, uintNetmask, netmask.AddressFamily, out var cidr2);
- cidr = cidr2;
-
- return;
-
- }
-
-
- #endregion
-
- #region ToNetmask
-
- /// <summary>
- /// Convert CIDR to netmask
- /// 24 -> 255.255.255.0
- /// 16 -> 255.255.0.0
- /// 8 -> 255.0.0.0
- /// </summary>
- /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static IPAddress ToNetmask(byte cidr, AddressFamily family)
- {
-
- IPAddress netmask = null;
- IPNetwork.InternalToNetmask(false, cidr, family, out netmask);
- return netmask;
- }
-
- /// <summary>
- /// Convert CIDR to netmask
- /// 24 -> 255.255.255.0
- /// 16 -> 255.255.0.0
- /// 8 -> 255.0.0.0
- /// </summary>
- /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static bool TryToNetmask(byte cidr, AddressFamily family, out IPAddress netmask)
- {
-
- IPAddress netmask2 = null;
- IPNetwork.InternalToNetmask(true, cidr, family, out netmask2);
- bool parsed = (netmask2 != null);
- netmask = netmask2;
- return parsed;
- }
-
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static void InternalToNetmask(bool tryParse, byte cidr, AddressFamily family, out IPAddress netmask)
- {
-
- if (family != AddressFamily.InterNetwork
- && family != AddressFamily.InterNetworkV6)
- {
- if (tryParse == false)
- {
- throw new ArgumentException("family");
- }
- netmask = null;
- return;
- }
-
- /// 20180217 lduchosal
- /// impossible to reach code, byte cannot be negative :
- ///
- /// if (cidr < 0) {
- /// if (tryParse == false) {
- /// throw new ArgumentOutOfRangeException("cidr");
- /// }
- /// netmask = null;
- /// return;
- /// }
-
- int maxCidr = family == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
- if (cidr > maxCidr)
- {
- if (tryParse == false)
- {
- throw new ArgumentOutOfRangeException(nameof(cidr));
- }
- netmask = null;
- return;
- }
-
- var mask = IPNetwork.ToUint(cidr, family);
- var netmask2 = IPNetwork.ToIPAddress(mask, family);
- netmask = netmask2;
-
- return;
- }
-
- #endregion
-
- #endregion
-
- #region utils
-
- #region BitsSet
-
- /// <summary>
- /// Count bits set to 1 in netmask
- /// </summary>
- /// <see cref="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer"/>
- /// <param name="netmask"></param>
- /// <returns></returns>
- private static byte BitsSet(BigInteger netmask, AddressFamily family)
- {
-
- string s = netmask.ToBinaryString();
- return (byte)s.Replace("0", "")
- .ToCharArray()
- .Length;
-
- }
-
-
- /// <summary>
- /// Count bits set to 1 in netmask
- /// </summary>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static uint BitsSet(IPAddress netmask)
- {
- var uintNetmask = IPNetwork.ToBigInteger(netmask);
- uint bits = IPNetwork.BitsSet(uintNetmask, netmask.AddressFamily);
- return bits;
- }
-
- #endregion
-
- #region ValidNetmask
-
- /// <summary>
- /// return true if netmask is a valid netmask
- /// 255.255.255.0, 255.0.0.0, 255.255.240.0, ...
- /// </summary>
- /// <see cref="http://www.actionsnip.com/snippets/tomo_atlacatl/calculate-if-a-netmask-is-valid--as2-"/>
- /// <param name="netmask"></param>
- /// <returns></returns>
- public static bool ValidNetmask(IPAddress netmask)
- {
-
- if (netmask == null)
- {
- throw new ArgumentNullException(nameof(netmask));
- }
- var uintNetmask = IPNetwork.ToBigInteger(netmask);
- bool valid = IPNetwork.InternalValidNetmask(uintNetmask, netmask.AddressFamily);
- return valid;
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static bool InternalValidNetmask(BigInteger netmask, AddressFamily family)
- {
-
- if (family != AddressFamily.InterNetwork
- && family != AddressFamily.InterNetworkV6)
- {
- throw new ArgumentException("family");
- }
-
- var mask = family == AddressFamily.InterNetwork
- ? new BigInteger(0x0ffffffff)
- : new BigInteger(new byte[]{
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff,
- 0x00
- });
-
- var neg = ((~netmask) & (mask));
- bool isNetmask = ((neg + 1) & neg) == 0;
- return isNetmask;
-
- }
-
- #endregion
-
- #region ToIPAddress
-
- /// <summary>
- /// Transform a uint ipaddress into IPAddress object
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <returns></returns>
- public static IPAddress ToIPAddress(BigInteger ipaddress, AddressFamily family)
- {
-
- int width = family == AddressFamily.InterNetwork ? 4 : 16;
- byte[] bytes = ipaddress.ToByteArray();
- byte[] bytes2 = new byte[width];
- int copy = bytes.Length > width ? width : bytes.Length;
- Array.Copy(bytes, 0, bytes2, 0, copy);
- Array.Reverse(bytes2);
-
- byte[] sized = Resize(bytes2, family);
- var ip = new IPAddress(sized);
- return ip;
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static byte[] Resize(byte[] bytes, AddressFamily family)
- {
-
- if (family != AddressFamily.InterNetwork
- && family != AddressFamily.InterNetworkV6)
- {
- throw new ArgumentException("family");
- }
-
- int width = family == AddressFamily.InterNetwork ? 4 : 16;
-
- if (bytes.Length > width)
- {
- throw new ArgumentException("bytes");
- }
-
- byte[] result = new byte[width];
- Array.Copy(bytes, 0, result, 0, bytes.Length);
- return result;
- }
-
- #endregion
-
- #endregion
-
- #region contains
-
- /// <summary>
- /// return true if ipaddress is contained in network
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <returns></returns>
- public bool Contains(IPAddress ipaddress)
- {
-
- if (ipaddress == null)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
-
- if (AddressFamily != ipaddress.AddressFamily)
- {
- return false;
- }
-
- var uintNetwork = _network;
- var uintBroadcast = _broadcast;
- var uintAddress = IPNetwork.ToBigInteger(ipaddress);
-
- bool contains = (uintAddress >= uintNetwork
- && uintAddress <= uintBroadcast);
-
- return contains;
-
- }
-
- /// <summary>
- /// return true is network2 is fully contained in network
- /// </summary>
- /// <param name="network2"></param>
- /// <returns></returns>
- public bool Contains(IPNetwork network2)
- {
-
- if (network2 == null)
- {
- throw new ArgumentNullException(nameof(network2));
- }
-
- var uintNetwork = _network;
- var uintBroadcast = _broadcast;
-
- var uintFirst = network2._network;
- var uintLast = network2._broadcast;
-
- bool contains = (uintFirst >= uintNetwork
- && uintLast <= uintBroadcast);
-
- return contains;
- }
-
- #endregion
-
- #region overlap
-
- /// <summary>
- /// return true is network2 overlap network
- /// </summary>
- /// <param name="network2"></param>
- /// <returns></returns>
- public bool Overlap(IPNetwork network2)
- {
-
- if (network2 == null)
- {
- throw new ArgumentNullException(nameof(network2));
- }
-
- var uintNetwork = _network;
- var uintBroadcast = _broadcast;
-
- var uintFirst = network2._network;
- var uintLast = network2._broadcast;
-
- bool overlap =
- (uintFirst >= uintNetwork && uintFirst <= uintBroadcast)
- || (uintLast >= uintNetwork && uintLast <= uintBroadcast)
- || (uintFirst <= uintNetwork && uintLast >= uintBroadcast)
- || (uintFirst >= uintNetwork && uintLast <= uintBroadcast);
-
- return overlap;
- }
-
- #endregion
-
- #region ToString
-
- public override string ToString()
- {
- return string.Format("{0}/{1}", this.Network, this.Cidr);
- }
-
- #endregion
-
- #region IANA block
-
- private static readonly Lazy<IPNetwork> _iana_ablock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("10.0.0.0/8"));
- private static readonly Lazy<IPNetwork> _iana_bblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("172.16.0.0/12"));
- private static readonly Lazy<IPNetwork> _iana_cblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("192.168.0.0/16"));
-
- /// <summary>
- /// 10.0.0.0/8
- /// </summary>
- /// <returns></returns>
- public static IPNetwork IANA_ABLK_RESERVED1 => _iana_ablock_reserved.Value;
-
- /// <summary>
- /// 172.12.0.0/12
- /// </summary>
- /// <returns></returns>
- public static IPNetwork IANA_BBLK_RESERVED1 => _iana_bblock_reserved.Value;
-
- /// <summary>
- /// 192.168.0.0/16
- /// </summary>
- /// <returns></returns>
- public static IPNetwork IANA_CBLK_RESERVED1 => _iana_cblock_reserved.Value;
-
- /// <summary>
- /// return true if ipaddress is contained in
- /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
- /// </summary>
- /// <param name="ipaddress"></param>
- /// <returns></returns>
- public static bool IsIANAReserved(IPAddress ipaddress)
- {
-
- if (ipaddress == null)
- {
- throw new ArgumentNullException(nameof(ipaddress));
- }
-
- return IPNetwork.IANA_ABLK_RESERVED1.Contains(ipaddress)
- || IPNetwork.IANA_BBLK_RESERVED1.Contains(ipaddress)
- || IPNetwork.IANA_CBLK_RESERVED1.Contains(ipaddress);
- }
-
- /// <summary>
- /// return true if ipnetwork is contained in
- /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
- /// </summary>
- /// <returns></returns>
- public bool IsIANAReserved()
- {
- return IPNetwork.IANA_ABLK_RESERVED1.Contains(this)
- || IPNetwork.IANA_BBLK_RESERVED1.Contains(this)
- || IPNetwork.IANA_CBLK_RESERVED1.Contains(this);
- }
-
- #endregion
-
- #region Subnet
-
- /// <summary>
- /// Subnet a network into multiple nets of cidr mask
- /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
- /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
- /// </summary>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public IPNetworkCollection Subnet(byte cidr)
- {
- IPNetworkCollection ipnetworkCollection = null;
- IPNetwork.InternalSubnet(false, this, cidr, out ipnetworkCollection);
- return ipnetworkCollection;
- }
-
- /// <summary>
- /// Subnet a network into multiple nets of cidr mask
- /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
- /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
- /// </summary>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public bool TrySubnet(byte cidr, out IPNetworkCollection ipnetworkCollection)
- {
- IPNetworkCollection inc = null;
- IPNetwork.InternalSubnet(true, this, cidr, out inc);
- if (inc == null)
- {
- ipnetworkCollection = null;
- return false;
- }
-
- ipnetworkCollection = inc;
- return true;
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static void InternalSubnet(bool trySubnet, IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
- {
-
- if (network == null)
- {
- if (trySubnet == false)
- {
- throw new ArgumentNullException(nameof(network));
- }
- ipnetworkCollection = null;
- return;
- }
-
- int maxCidr = network._family == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
- if (cidr > maxCidr)
- {
- if (trySubnet == false)
- {
- throw new ArgumentOutOfRangeException(nameof(cidr));
- }
- ipnetworkCollection = null;
- return;
- }
-
- if (cidr < network.Cidr)
- {
- if (trySubnet == false)
- {
- throw new ArgumentException("cidr");
- }
- ipnetworkCollection = null;
- return;
- }
-
- ipnetworkCollection = new IPNetworkCollection(network, cidr);
- return;
- }
-
-
-
- #endregion
-
- #region Supernet
-
- /// <summary>
- /// Supernet two consecutive cidr equal subnet into a single one
- /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
- /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
- /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
- /// </summary>
- /// <param name="network2"></param>
- /// <returns></returns>
- public IPNetwork Supernet(IPNetwork network2)
- {
- IPNetwork supernet = null;
- IPNetwork.InternalSupernet(false, this, network2, out supernet);
- return supernet;
- }
-
- /// <summary>
- /// Try to supernet two consecutive cidr equal subnet into a single one
- /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
- /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
- /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
- /// </summary>
- /// <param name="network2"></param>
- /// <returns></returns>
- public bool TrySupernet(IPNetwork network2, out IPNetwork supernet)
- {
-
- IPNetwork outSupernet = null;
- IPNetwork.InternalSupernet(true, this, network2, out outSupernet);
- bool parsed = (outSupernet != null);
- supernet = outSupernet;
- return parsed;
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static void InternalSupernet(bool trySupernet, IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
- {
-
- if (network1 == null)
- {
- if (trySupernet == false)
- {
- throw new ArgumentNullException(nameof(network1));
- }
- supernet = null;
- return;
- }
-
- if (network2 == null)
- {
- if (trySupernet == false)
- {
- throw new ArgumentNullException(nameof(network2));
- }
- supernet = null;
- return;
- }
-
-
- if (network1.Contains(network2))
- {
- supernet = new IPNetwork(network1._network, network1._family, network1.Cidr);
- return;
- }
-
- if (network2.Contains(network1))
- {
- supernet = new IPNetwork(network2._network, network2._family, network2.Cidr);
- return;
- }
-
- if (network1._cidr != network2._cidr)
- {
- if (trySupernet == false)
- {
- throw new ArgumentException("cidr");
- }
- supernet = null;
- return;
- }
-
- var first = (network1._network < network2._network) ? network1 : network2;
- var last = (network1._network > network2._network) ? network1 : network2;
-
- /// Starting from here :
- /// network1 and network2 have the same cidr,
- /// network1 does not contain network2,
- /// network2 does not contain network1,
- /// first is the lower subnet
- /// last is the higher subnet
-
-
- if ((first._broadcast + 1) != last._network)
- {
- if (trySupernet == false)
- {
- throw new ArgumentOutOfRangeException(nameof(trySupernet), "TrySupernet was false while the first and last networks are not adjacent.");
- }
- supernet = null;
- return;
- }
-
- var uintSupernet = first._network;
- byte cidrSupernet = (byte)(first._cidr - 1);
-
- var networkSupernet = new IPNetwork(uintSupernet, first._family, cidrSupernet);
- if (networkSupernet._network != first._network)
- {
- if (trySupernet == false)
- {
- throw new ArgumentException("network");
- }
- supernet = null;
- return;
- }
- supernet = networkSupernet;
- return;
- }
-
- #endregion
-
- #region GetHashCode
-
- public override int GetHashCode()
- {
- return string.Format("{0}|{1}|{2}",
- this._ipaddress.GetHashCode(),
- this._network.GetHashCode(),
- this._cidr.GetHashCode()).GetHashCode();
- }
-
- #endregion
-
- #region SupernetArray
-
- /// <summary>
- /// Supernet a list of subnet
- /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
- /// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
- /// </summary>
- /// <param name="ipnetworks">The IP networks</param>
- /// <returns></returns>
- public static IPNetwork[] Supernet(IPNetwork[] ipnetworks)
- {
- InternalSupernet(false, ipnetworks, out var supernet);
- return supernet;
- }
-
- /// <summary>
- /// Supernet a list of subnet
- /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
- /// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
- /// </summary>
- /// <param name="ipnetworks"></param>
- /// <param name="supernet"></param>
- /// <returns></returns>
- public static bool TrySupernet(IPNetwork[] ipnetworks, out IPNetwork[] supernet)
- {
- bool supernetted = InternalSupernet(true, ipnetworks, out supernet);
- return supernetted;
-
- }
-
-#if TRAVISCI
- public
-#else
- internal
-#endif
- static bool InternalSupernet(bool trySupernet, IPNetwork[] ipnetworks, out IPNetwork[] supernet)
- {
-
- if (ipnetworks == null)
- {
- if (trySupernet == false)
- {
- throw new ArgumentNullException(nameof(ipnetworks));
- }
- supernet = null;
- return false;
- }
-
- if (ipnetworks.Length <= 0)
- {
- supernet = new IPNetwork[0];
- return true;
- }
-
- var supernetted = new List<IPNetwork>();
- var ipns = IPNetwork.Array2List(ipnetworks);
- var current = IPNetwork.List2Stack(ipns);
- int previousCount = 0;
- int currentCount = current.Count;
-
- while (previousCount != currentCount)
- {
-
- supernetted.Clear();
- while (current.Count > 1)
- {
- var ipn1 = current.Pop();
- var ipn2 = current.Peek();
-
- IPNetwork outNetwork = null;
- bool success = ipn1.TrySupernet(ipn2, out outNetwork);
- if (success)
- {
- current.Pop();
- current.Push(outNetwork);
- }
- else
- {
- supernetted.Add(ipn1);
- }
- }
- if (current.Count == 1)
- {
- supernetted.Add(current.Pop());
- }
-
- previousCount = currentCount;
- currentCount = supernetted.Count;
- current = IPNetwork.List2Stack(supernetted);
-
- }
- supernet = supernetted.ToArray();
- return true;
- }
-
- private static Stack<IPNetwork> List2Stack(List<IPNetwork> list)
- {
- var stack = new Stack<IPNetwork>();
- list.ForEach(new Action<IPNetwork>(
- delegate (IPNetwork ipn)
- {
- stack.Push(ipn);
- }
- ));
- return stack;
- }
-
- private static List<IPNetwork> Array2List(IPNetwork[] array)
- {
- var ipns = new List<IPNetwork>();
- ipns.AddRange(array);
- IPNetwork.RemoveNull(ipns);
- ipns.Sort(new Comparison<IPNetwork>(
- delegate (IPNetwork ipn1, IPNetwork ipn2)
- {
- int networkCompare = ipn1._network.CompareTo(ipn2._network);
- if (networkCompare == 0)
- {
- int cidrCompare = ipn1._cidr.CompareTo(ipn2._cidr);
- return cidrCompare;
- }
- return networkCompare;
- }
- ));
- ipns.Reverse();
-
- return ipns;
- }
-
- private static void RemoveNull(List<IPNetwork> ipns)
- {
- ipns.RemoveAll(new Predicate<IPNetwork>(
- delegate (IPNetwork ipn)
- {
- if (ipn == null)
- {
- return true;
- }
- return false;
- }
- ));
-
- }
-
- #endregion
-
- #region WideSubnet
-
- public static IPNetwork WideSubnet(string start, string end)
- {
-
- if (string.IsNullOrEmpty(start))
- {
- throw new ArgumentNullException(nameof(start));
- }
-
- if (string.IsNullOrEmpty(end))
- {
- throw new ArgumentNullException(nameof(end));
- }
-
- if (!IPAddress.TryParse(start, out var startIP))
- {
- throw new ArgumentException("start");
- }
-
- if (!IPAddress.TryParse(end, out var endIP))
- {
- throw new ArgumentException("end");
- }
-
- if (startIP.AddressFamily != endIP.AddressFamily)
- {
- throw new NotSupportedException("MixedAddressFamily");
- }
-
- var ipnetwork = new IPNetwork(0, startIP.AddressFamily, 0);
- for (byte cidr = 32; cidr >= 0; cidr--)
- {
- var wideSubnet = IPNetwork.Parse(start, cidr);
- if (wideSubnet.Contains(endIP))
- {
- ipnetwork = wideSubnet;
- break;
- }
- }
- return ipnetwork;
-
- }
-
- public static bool TryWideSubnet(IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
- {
- IPNetwork ipn = null;
- IPNetwork.InternalWideSubnet(true, ipnetworks, out ipn);
- if (ipn == null)
- {
- ipnetwork = null;
- return false;
- }
- ipnetwork = ipn;
- return true;
- }
-
- public static IPNetwork WideSubnet(IPNetwork[] ipnetworks)
- {
- IPNetwork ipn = null;
- IPNetwork.InternalWideSubnet(false, ipnetworks, out ipn);
- return ipn;
- }
-
- internal static void InternalWideSubnet(bool tryWide, IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
- {
-
- if (ipnetworks == null)
- {
- if (tryWide == false)
- {
- throw new ArgumentNullException(nameof(ipnetworks));
- }
- ipnetwork = null;
- return;
- }
-
-
- IPNetwork[] nnin = Array.FindAll(ipnetworks, new Predicate<IPNetwork>(
- delegate (IPNetwork ipnet)
- {
- return ipnet != null;
- }
- ));
-
- if (nnin.Length <= 0)
- {
- if (tryWide == false)
- {
- throw new ArgumentException("ipnetworks");
- }
- ipnetwork = null;
- return;
- }
-
- if (nnin.Length == 1)
- {
- var ipn0 = nnin[0];
- ipnetwork = ipn0;
- return;
- }
-
- Array.Sort(nnin);
- var nnin0 = nnin[0];
- var uintNnin0 = nnin0._ipaddress;
-
- var nninX = nnin[nnin.Length - 1];
- var ipaddressX = nninX.Broadcast;
-
- var family = ipnetworks[0]._family;
- foreach (var ipnx in ipnetworks)
- {
- if (ipnx._family != family)
- {
- throw new ArgumentException("MixedAddressFamily");
- }
- }
-
- var ipn = new IPNetwork(0, family, 0);
- for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
- {
- var wideSubnet = new IPNetwork(uintNnin0, family, cidr);
- if (wideSubnet.Contains(ipaddressX))
- {
- ipn = wideSubnet;
- break;
- }
- }
-
- ipnetwork = ipn;
- return;
- }
-
- #endregion
-
- #region Print
-
- /// <summary>
- /// Print an ipnetwork in a clear representation string
- /// </summary>
- /// <returns></returns>
- public string Print()
- {
-
- var sw = new StringWriter();
-
- sw.WriteLine("IPNetwork : {0}", ToString());
- sw.WriteLine("Network : {0}", Network);
- sw.WriteLine("Netmask : {0}", Netmask);
- sw.WriteLine("Cidr : {0}", Cidr);
- sw.WriteLine("Broadcast : {0}", Broadcast);
- sw.WriteLine("FirstUsable : {0}", FirstUsable);
- sw.WriteLine("LastUsable : {0}", LastUsable);
- sw.WriteLine("Usable : {0}", Usable);
-
- return sw.ToString();
- }
-
- #endregion
-
- #region TryGuessCidr
-
- /// <summary>
- ///
- /// Class Leading bits Default netmask
- /// A (CIDR /8) 00 255.0.0.0
- /// A (CIDR /8) 01 255.0.0.0
- /// B (CIDR /16) 10 255.255.0.0
- /// C (CIDR /24) 11 255.255.255.0
- ///
- /// </summary>
- /// <param name="ip"></param>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static bool TryGuessCidr(string ip, out byte cidr)
- {
-
- IPAddress ipaddress = null;
- bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
- if (parsed == false)
- {
- cidr = 0;
- return false;
- }
-
- if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
- {
- cidr = 64;
- return true;
- }
- var uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
- uintIPAddress = uintIPAddress >> 29;
- if (uintIPAddress <= 3)
- {
- cidr = 8;
- return true;
- }
- else if (uintIPAddress <= 5)
- {
- cidr = 16;
- return true;
- }
- else if (uintIPAddress <= 6)
- {
- cidr = 24;
- return true;
- }
-
- cidr = 0;
- return false;
-
- }
-
- /// <summary>
- /// Try to parse cidr. Have to be >= 0 and <= 32 or 128
- /// </summary>
- /// <param name="sidr"></param>
- /// <param name="cidr"></param>
- /// <returns></returns>
- public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
- {
-
- byte b = 0;
- if (!byte.TryParse(sidr, out b))
- {
- cidr = null;
- return false;
- }
-
- IPAddress netmask = null;
- if (!IPNetwork.TryToNetmask(b, family, out netmask))
- {
- cidr = null;
- return false;
- }
-
- cidr = b;
- return true;
- }
-
- #endregion
-
- #region ListIPAddress
-
- public IPAddressCollection ListIPAddress()
- {
- return new IPAddressCollection(this);
- }
-
- #endregion
-
- /**
- * Need a better way to do it
- *
-#region TrySubstractNetwork
-
- public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
-
- if (ipnetworks == null) {
- result = null;
- return false;
- }
- if (ipnetworks.Length <= 0) {
- result = null;
- return false;
- }
- if (substract == null) {
- result = null;
- return false;
- }
- var results = new List<IPNetwork>();
- foreach (var ipn in ipnetworks) {
- if (!Overlap(ipn, substract)) {
- results.Add(ipn);
- continue;
- }
-
- var collection = ipn.Subnet(substract.Cidr);
- var rtemp = new List<IPNetwork>();
- foreach(var subnet in collection) {
- if (subnet != substract) {
- rtemp.Add(subnet);
- }
- }
- var supernets = Supernet(rtemp.ToArray());
- results.AddRange(supernets);
- }
- result = results;
- return true;
- }
-#endregion
- * **/
-
- #region IComparable<IPNetwork> Members
-
- public static int Compare(IPNetwork left, IPNetwork right)
- {
- // two null IPNetworks are equal
- if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
-
- // two same IPNetworks are equal
- if (ReferenceEquals(left, right)) return 0;
-
- // null is always sorted first
- if (ReferenceEquals(left, null)) return -1;
- if (ReferenceEquals(right, null)) return 1;
-
- // first test the network
- var result = left._network.CompareTo(right._network);
- if (result != 0) return result;
-
- // then test the cidr
- result = left._cidr.CompareTo(right._cidr);
- return result;
- }
-
- public int CompareTo(IPNetwork other)
- {
- return Compare(this, other);
- }
-
- public int CompareTo(object obj)
- {
- // null is at less
- if (obj == null) return 1;
-
- // convert to a proper Cidr object
- var other = obj as IPNetwork;
-
- // type problem if null
- if (other == null)
- {
- throw new ArgumentException(
- "The supplied parameter is an invalid type. Please supply an IPNetwork type.",
- nameof(obj));
- }
-
- // perform the comparision
- return CompareTo(other);
- }
-
- #endregion
-
- #region IEquatable<IPNetwork> Members
-
- public static bool Equals(IPNetwork left, IPNetwork right)
- {
- return Compare(left, right) == 0;
- }
-
- public bool Equals(IPNetwork other)
- {
- return Equals(this, other);
- }
-
- public override bool Equals(object obj)
- {
- return Equals(this, obj as IPNetwork);
- }
-
- #endregion
-
- #region Operators
-
- public static bool operator ==(IPNetwork left, IPNetwork right)
- {
- return Equals(left, right);
- }
-
- public static bool operator !=(IPNetwork left, IPNetwork right)
- {
- return !Equals(left, right);
- }
-
- public static bool operator <(IPNetwork left, IPNetwork right)
- {
- return Compare(left, right) < 0;
- }
-
- public static bool operator >(IPNetwork left, IPNetwork right)
- {
- return Compare(left, right) > 0;
- }
-
- #endregion
-
- }
-}
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/IPNetworkCollection.cs b/Emby.Server.Implementations/Networking/IPNetwork/IPNetworkCollection.cs
deleted file mode 100644
index 4cda421e5..000000000
--- a/Emby.Server.Implementations/Networking/IPNetwork/IPNetworkCollection.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Numerics;
-
-namespace Emby.Server.Implementations.Networking.IPNetwork
-{
- public class IPNetworkCollection : IEnumerable<IPNetwork>, IEnumerator<IPNetwork>
- {
-
- private BigInteger _enumerator;
- private byte _cidrSubnet;
- private IPNetwork _ipnetwork;
-
- private byte _cidr => this._ipnetwork.Cidr;
-
- private BigInteger _broadcast => IPNetwork.ToBigInteger(this._ipnetwork.Broadcast);
-
- private BigInteger _lastUsable => IPNetwork.ToBigInteger(this._ipnetwork.LastUsable);
- private BigInteger _network => IPNetwork.ToBigInteger(this._ipnetwork.Network);
-#if TRAVISCI
- public
-#else
- internal
-#endif
- IPNetworkCollection(IPNetwork ipnetwork, byte cidrSubnet)
- {
-
- int maxCidr = ipnetwork.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
- if (cidrSubnet > maxCidr)
- {
- throw new ArgumentOutOfRangeException(nameof(cidrSubnet));
- }
-
- if (cidrSubnet < ipnetwork.Cidr)
- {
- throw new ArgumentException("cidr");
- }
-
- this._cidrSubnet = cidrSubnet;
- this._ipnetwork = ipnetwork;
- this._enumerator = -1;
- }
-
- #region Count, Array, Enumerator
-
- public BigInteger Count
- {
- get
- {
- var count = BigInteger.Pow(2, this._cidrSubnet - this._cidr);
- return count;
- }
- }
-
- public IPNetwork this[BigInteger i]
- {
- get
- {
- if (i >= this.Count)
- {
- throw new ArgumentOutOfRangeException(nameof(i));
- }
-
- var last = this._ipnetwork.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6
- ? this._lastUsable : this._broadcast;
- var increment = (last - this._network) / this.Count;
- var uintNetwork = this._network + ((increment + 1) * i);
- var ipn = new IPNetwork(uintNetwork, this._ipnetwork.AddressFamily, this._cidrSubnet);
- return ipn;
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- IEnumerator<IPNetwork> IEnumerable<IPNetwork>.GetEnumerator()
- {
- return this;
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this;
- }
-
- #region IEnumerator<IPNetwork> Members
-
- public IPNetwork Current => this[this._enumerator];
-
- #endregion
-
- #region IDisposable Members
-
- public void Dispose()
- {
- // nothing to dispose
- return;
- }
-
- #endregion
-
- #region IEnumerator Members
-
- object IEnumerator.Current => this.Current;
-
- public bool MoveNext()
- {
- this._enumerator++;
- if (this._enumerator >= this.Count)
- {
- return false;
- }
- return true;
-
- }
-
- public void Reset()
- {
- this._enumerator = -1;
- }
-
- #endregion
-
- #endregion
-
- }
-}
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/LICENSE.txt b/Emby.Server.Implementations/Networking/IPNetwork/LICENSE.txt
deleted file mode 100644
index 45d7392ac..000000000
--- a/Emby.Server.Implementations/Networking/IPNetwork/LICENSE.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2015, lduchosal
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs
deleted file mode 100644
index 60cc9b88e..000000000
--- a/Emby.Server.Implementations/Networking/NetworkManager.cs
+++ /dev/null
@@ -1,727 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Net.NetworkInformation;
-using System.Net.Sockets;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Networking
-{
- public class NetworkManager : INetworkManager
- {
- protected ILogger Logger { get; private set; }
-
- public event EventHandler NetworkChanged;
- public Func<string[]> LocalSubnetsFn { get; set; }
-
- public NetworkManager(
- ILoggerFactory loggerFactory,
- IEnvironmentInfo environment)
- {
- Logger = loggerFactory.CreateLogger(nameof(NetworkManager));
-
- // In FreeBSD these events cause a crash
- if (environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.BSD)
- {
- try
- {
- NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error binding to NetworkAddressChanged event");
- }
-
- try
- {
- NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error binding to NetworkChange_NetworkAvailabilityChanged event");
- }
- }
- }
-
- private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
- {
- Logger.LogDebug("NetworkAvailabilityChanged");
- OnNetworkChanged();
- }
-
- private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
- {
- Logger.LogDebug("NetworkAddressChanged");
- OnNetworkChanged();
- }
-
- private void OnNetworkChanged()
- {
- lock (_localIpAddressSyncLock)
- {
- _localIpAddresses = null;
- _macAddresses = null;
- }
- if (NetworkChanged != null)
- {
- NetworkChanged(this, EventArgs.Empty);
- }
- }
-
- private IpAddressInfo[] _localIpAddresses;
- private readonly object _localIpAddressSyncLock = new object();
-
- public IpAddressInfo[] GetLocalIpAddresses()
- {
- lock (_localIpAddressSyncLock)
- {
- if (_localIpAddresses == null)
- {
- var addresses = GetLocalIpAddressesInternal().Result.Select(ToIpAddressInfo).ToArray();
-
- _localIpAddresses = addresses;
-
- return addresses;
- }
- return _localIpAddresses;
- }
- }
-
- private async Task<List<IPAddress>> GetLocalIpAddressesInternal()
- {
- var list = GetIPsDefault()
- .ToList();
-
- if (list.Count == 0)
- {
- list.AddRange(await GetLocalIpAddressesFallback().ConfigureAwait(false));
- }
-
- var listClone = list.ToList();
-
- return list
- .OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
- .ThenBy(i => listClone.IndexOf(i))
- .Where(FilterIpAddress)
- .GroupBy(i => i.ToString())
- .Select(x => x.First())
- .ToList();
- }
-
- private static bool FilterIpAddress(IPAddress address)
- {
- var addressString = address.ToString();
-
- if (addressString.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- return true;
- }
-
- public bool IsInPrivateAddressSpace(string endpoint)
- {
- return IsInPrivateAddressSpace(endpoint, true);
- }
-
- private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
- {
- if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- // ipv6
- if (endpoint.Split('.').Length > 4)
- {
- // Handle ipv4 mapped to ipv6
- var originalEndpoint = endpoint;
- endpoint = endpoint.Replace("::ffff:", string.Empty);
-
- if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- }
-
- // Private address space:
- // http://en.wikipedia.org/wiki/Private_network
-
- if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
- {
- return Is172AddressPrivate(endpoint);
- }
-
- if (endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
- endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
- endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- if (checkSubnets && endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
- {
- return true;
- }
-
- return false;
- }
-
- public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
- {
- if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
- {
- var endpointFirstPart = endpoint.Split('.')[0];
-
- var subnets = GetSubnets(endpointFirstPart);
-
- foreach (var subnet_Match in subnets)
- {
- //logger.LogDebug("subnet_Match:" + subnet_Match);
-
- if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- private Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
- private List<string> GetSubnets(string endpointFirstPart)
- {
- lock (_subnetLookup)
- {
- if (_subnetLookup.TryGetValue(endpointFirstPart, out var subnets))
- {
- return subnets;
- }
-
- subnets = new List<string>();
-
- foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
- {
- foreach (var unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
- {
- if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && endpointFirstPart == unicastIPAddressInformation.Address.ToString().Split('.')[0])
- {
- int subnet_Test = 0;
- foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.'))
- {
- if (part.Equals("0")) break;
- subnet_Test++;
- }
-
- var subnet_Match = string.Join(".", unicastIPAddressInformation.Address.ToString().Split('.').Take(subnet_Test).ToArray());
-
- // TODO: Is this check necessary?
- if (adapter.OperationalStatus == OperationalStatus.Up)
- {
- subnets.Add(subnet_Match);
- }
- }
- }
- }
-
- _subnetLookup[endpointFirstPart] = subnets;
-
- return subnets;
- }
- }
-
- private static bool Is172AddressPrivate(string endpoint)
- {
- for (var i = 16; i <= 31; i++)
- {
- if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public bool IsInLocalNetwork(string endpoint)
- {
- return IsInLocalNetworkInternal(endpoint, true);
- }
-
- public bool IsAddressInSubnets(string addressString, string[] subnets)
- {
- return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets);
- }
-
- private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
- {
- foreach (var subnet in subnets)
- {
- var normalizedSubnet = subnet.Trim();
-
- if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- if (normalizedSubnet.IndexOf('/') != -1)
- {
- var ipnetwork = IPNetwork.IPNetwork.Parse(normalizedSubnet);
- if (ipnetwork.Contains(address))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- private bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
- {
- if (string.IsNullOrEmpty(endpoint))
- {
- throw new ArgumentNullException(nameof(endpoint));
- }
-
- if (IPAddress.TryParse(endpoint, out var address))
- {
- var addressString = address.ToString();
-
- var localSubnetsFn = LocalSubnetsFn;
- if (localSubnetsFn != null)
- {
- var localSubnets = localSubnetsFn();
- foreach (var subnet in localSubnets)
- {
- // only validate if there's at least one valid entry
- if (!string.IsNullOrWhiteSpace(subnet))
- {
- return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
- }
- }
- }
-
- int lengthMatch = 100;
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- lengthMatch = 4;
- if (IsInPrivateAddressSpace(addressString, true))
- {
- return true;
- }
- }
- else if (address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- lengthMatch = 9;
- if (IsInPrivateAddressSpace(endpoint, true))
- {
- return true;
- }
- }
-
- // Should be even be doing this with ipv6?
- if (addressString.Length >= lengthMatch)
- {
- var prefix = addressString.Substring(0, lengthMatch);
-
- if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
- {
- return true;
- }
- }
- }
- else if (resolveHost)
- {
- if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out var uri))
- {
- try
- {
- var host = uri.DnsSafeHost;
- Logger.LogDebug("Resolving host {0}", host);
-
- address = GetIpAddresses(host).Result.FirstOrDefault();
-
- if (address != null)
- {
- Logger.LogDebug("{0} resolved to {1}", host, address);
-
- return IsInLocalNetworkInternal(address.ToString(), false);
- }
- }
- catch (InvalidOperationException)
- {
- // Can happen with reverse proxy or IIS url rewriting
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error resolving hostname");
- }
- }
- }
-
- return false;
- }
-
- private static Task<IPAddress[]> GetIpAddresses(string hostName)
- {
- return Dns.GetHostAddressesAsync(hostName);
- }
-
- private List<IPAddress> GetIPsDefault()
- {
- NetworkInterface[] interfaces;
-
- try
- {
- var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
-
- interfaces = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => validStatuses.Contains(i.OperationalStatus))
- .ToArray();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error in GetAllNetworkInterfaces");
- return new List<IPAddress>();
- }
-
- return interfaces.SelectMany(network =>
- {
-
- try
- {
- // suppress logging because it might be causing nas device wake up
- //logger.LogDebug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
-
- var ipProperties = network.GetIPProperties();
-
- // Try to exclude virtual adapters
- // http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
- var addr = ipProperties.GatewayAddresses.FirstOrDefault();
- if (addr == null || string.Equals(addr.Address.ToString(), "0.0.0.0", StringComparison.OrdinalIgnoreCase))
- {
- return new List<IPAddress>();
- }
-
- return ipProperties.UnicastAddresses
- .Select(i => i.Address)
- .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6)
- .ToList();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error querying network interface");
- return new List<IPAddress>();
- }
-
- }).GroupBy(i => i.ToString())
- .Select(x => x.First())
- .ToList();
- }
-
- private static async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
- {
- var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
-
- // Reverse them because the last one is usually the correct one
- // It's not fool-proof so ultimately the consumer will have to examine them and decide
- return host.AddressList
- .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6)
- .Reverse();
- }
-
- /// <summary>
- /// Gets a random port number that is currently available
- /// </summary>
- /// <returns>System.Int32.</returns>
- public int GetRandomUnusedTcpPort()
- {
- var listener = new TcpListener(IPAddress.Any, 0);
- listener.Start();
- var port = ((IPEndPoint)listener.LocalEndpoint).Port;
- listener.Stop();
- return port;
- }
-
- public int GetRandomUnusedUdpPort()
- {
- var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
- using (var udpClient = new UdpClient(localEndPoint))
- {
- var port = ((IPEndPoint)(udpClient.Client.LocalEndPoint)).Port;
- return port;
- }
- }
-
- private List<string> _macAddresses;
- public List<string> GetMacAddresses()
- {
- if (_macAddresses == null)
- {
- _macAddresses = GetMacAddressesInternal();
- }
- return _macAddresses;
- }
-
- private static List<string> GetMacAddressesInternal()
- {
- return NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
- .Select(i =>
- {
- try
- {
- var physicalAddress = i.GetPhysicalAddress();
-
- if (physicalAddress == null)
- {
- return null;
- }
-
- return physicalAddress.ToString();
- }
- catch (Exception)
- {
- //TODO Log exception.
- return null;
- }
- })
- .Where(i => i != null)
- .ToList();
- }
-
- /// <summary>
- /// Parses the specified endpointstring.
- /// </summary>
- /// <param name="endpointstring">The endpointstring.</param>
- /// <returns>IPEndPoint.</returns>
- public IPEndPoint Parse(string endpointstring)
- {
- return Parse(endpointstring, -1).Result;
- }
-
- /// <summary>
- /// Parses the specified endpointstring.
- /// </summary>
- /// <param name="endpointstring">The endpointstring.</param>
- /// <param name="defaultport">The defaultport.</param>
- /// <returns>IPEndPoint.</returns>
- /// <exception cref="ArgumentException">Endpoint descriptor may not be empty.</exception>
- /// <exception cref="FormatException"></exception>
- private static async Task<IPEndPoint> Parse(string endpointstring, int defaultport)
- {
- if (string.IsNullOrEmpty(endpointstring)
- || endpointstring.Trim().Length == 0)
- {
- throw new ArgumentException("Endpoint descriptor may not be empty.");
- }
-
- if (defaultport != -1 &&
- (defaultport < IPEndPoint.MinPort
- || defaultport > IPEndPoint.MaxPort))
- {
- throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport));
- }
-
- string[] values = endpointstring.Split(new char[] { ':' });
- IPAddress ipaddy;
- int port = -1;
-
- //check if we have an IPv6 or ports
- if (values.Length <= 2) // ipv4 or hostname
- {
- port = values.Length == 1 ? defaultport : GetPort(values[1]);
-
- //try to use the address as IPv4, otherwise get hostname
- if (!IPAddress.TryParse(values[0], out ipaddy))
- ipaddy = await GetIPfromHost(values[0]).ConfigureAwait(false);
- }
- else if (values.Length > 2) //ipv6
- {
- //could [a:b:c]:d
- if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
- {
- string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray());
- ipaddy = IPAddress.Parse(ipaddressstring);
- port = GetPort(values[values.Length - 1]);
- }
- else //[a:b:c] or a:b:c
- {
- ipaddy = IPAddress.Parse(endpointstring);
- port = defaultport;
- }
- }
- else
- {
- throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
- }
-
- if (port == -1)
- throw new ArgumentException(string.Format("No port specified: '{0}'", endpointstring));
-
- return new IPEndPoint(ipaddy, port);
- }
-
- protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Gets the port.
- /// </summary>
- /// <param name="p">The p.</param>
- /// <returns>System.Int32.</returns>
- /// <exception cref="FormatException"></exception>
- private static int GetPort(string p)
- {
- if (!int.TryParse(p, out var port)
- || port < IPEndPoint.MinPort
- || port > IPEndPoint.MaxPort)
- {
- throw new FormatException(string.Format("Invalid end point port '{0}'", p));
- }
-
- return port;
- }
-
- /// <summary>
- /// Gets the I pfrom host.
- /// </summary>
- /// <param name="p">The p.</param>
- /// <returns>IPAddress.</returns>
- /// <exception cref="ArgumentException"></exception>
- private static async Task<IPAddress> GetIPfromHost(string p)
- {
- var hosts = await Dns.GetHostAddressesAsync(p).ConfigureAwait(false);
-
- if (hosts == null || hosts.Length == 0)
- throw new ArgumentException(string.Format("Host not found: {0}", p));
-
- return hosts[0];
- }
-
- public IpAddressInfo ParseIpAddress(string ipAddress)
- {
- if (TryParseIpAddress(ipAddress, out var info))
- {
- return info;
- }
-
- throw new ArgumentException("Invalid ip address: " + ipAddress);
- }
-
- public bool TryParseIpAddress(string ipAddress, out IpAddressInfo ipAddressInfo)
- {
- if (IPAddress.TryParse(ipAddress, out var address))
- {
- ipAddressInfo = ToIpAddressInfo(address);
- return true;
- }
-
- ipAddressInfo = null;
- return false;
- }
-
- public static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
- {
- if (endpoint == null)
- {
- return null;
- }
-
- return new IpEndPointInfo(ToIpAddressInfo(endpoint.Address), endpoint.Port);
- }
-
- public static IPEndPoint ToIPEndPoint(IpEndPointInfo endpoint)
- {
- if (endpoint == null)
- {
- return null;
- }
-
- return new IPEndPoint(ToIPAddress(endpoint.IpAddress), endpoint.Port);
- }
-
- public static IPAddress ToIPAddress(IpAddressInfo address)
- {
- if (address.Equals(IpAddressInfo.Any))
- {
- return IPAddress.Any;
- }
- if (address.Equals(IpAddressInfo.IPv6Any))
- {
- return IPAddress.IPv6Any;
- }
- if (address.Equals(IpAddressInfo.Loopback))
- {
- return IPAddress.Loopback;
- }
- if (address.Equals(IpAddressInfo.IPv6Loopback))
- {
- return IPAddress.IPv6Loopback;
- }
-
- return IPAddress.Parse(address.Address);
- }
-
- public static IpAddressInfo ToIpAddressInfo(IPAddress address)
- {
- if (address.Equals(IPAddress.Any))
- {
- return IpAddressInfo.Any;
- }
- if (address.Equals(IPAddress.IPv6Any))
- {
- return IpAddressInfo.IPv6Any;
- }
- if (address.Equals(IPAddress.Loopback))
- {
- return IpAddressInfo.Loopback;
- }
- if (address.Equals(IPAddress.IPv6Loopback))
- {
- return IpAddressInfo.IPv6Loopback;
- }
- return new IpAddressInfo(address.ToString(), address.AddressFamily == AddressFamily.InterNetworkV6 ? IpAddressFamily.InterNetworkV6 : IpAddressFamily.InterNetwork);
- }
-
- public async Task<IpAddressInfo[]> GetHostAddressesAsync(string host)
- {
- var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
- return addresses.Select(ToIpAddressInfo).ToArray();
- }
-
- /// <summary>
- /// Gets the network shares.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns>IEnumerable{NetworkShare}.</returns>
- public virtual IEnumerable<NetworkShare> GetNetworkShares(string path)
- {
- return new List<NetworkShare>();
- }
-
- /// <summary>
- /// Gets available devices within the domain
- /// </summary>
- /// <returns>PC's in the Domain</returns>
- public virtual IEnumerable<FileSystemEntryInfo> GetNetworkDevices()
- {
- return new List<FileSystemEntryInfo>();
- }
- }
-}
diff --git a/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs b/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs
deleted file mode 100644
index 8a7c1492d..000000000
--- a/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs
+++ /dev/null
@@ -1,126 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Emby.Server.Implementations.Images;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-
-namespace Emby.Server.Implementations.Playlists
-{
- public class PlaylistImageProvider : BaseDynamicImageProvider<Playlist>
- {
- public PlaylistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
- {
- }
-
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
- {
- var playlist = (Playlist)item;
-
- return playlist.GetManageableItems()
- .Select(i =>
- {
- var subItem = i.Item2;
-
- var episode = subItem as Episode;
-
- if (episode != null)
- {
- var series = episode.Series;
- if (series != null && series.HasImage(ImageType.Primary))
- {
- return series;
- }
- }
-
- if (subItem.HasImage(ImageType.Primary))
- {
- return subItem;
- }
-
- var parent = subItem.GetOwner() ?? subItem.GetParent();
-
- if (parent != null && parent.HasImage(ImageType.Primary))
- {
- if (parent is MusicAlbum)
- {
- return parent;
- }
- }
-
- return null;
- })
- .Where(i => i != null)
- .OrderBy(i => Guid.NewGuid())
- .GroupBy(x => x.Id)
- .Select(x => x.First())
- .ToList();
- }
- }
-
- public class MusicGenreImageProvider : BaseDynamicImageProvider<MusicGenre>
- {
- private readonly ILibraryManager _libraryManager;
-
- public MusicGenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
- {
- _libraryManager = libraryManager;
- }
-
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
- {
- return _libraryManager.GetItemList(new InternalItemsQuery
- {
- Genres = new[] { item.Name },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name, typeof(MusicVideo).Name, typeof(Audio).Name },
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.Random, SortOrder.Ascending) },
- Limit = 4,
- Recursive = true,
- ImageTypes = new[] { ImageType.Primary },
- DtoOptions = new DtoOptions(false)
-
- });
- }
- }
-
- public class GenreImageProvider : BaseDynamicImageProvider<Genre>
- {
- private readonly ILibraryManager _libraryManager;
-
- public GenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
- {
- _libraryManager = libraryManager;
- }
-
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
- {
- return _libraryManager.GetItemList(new InternalItemsQuery
- {
- Genres = new[] { item.Name },
- IncludeItemTypes = new[] { typeof(Series).Name, typeof(Movie).Name },
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.Random, SortOrder.Ascending) },
- Limit = 4,
- Recursive = true,
- ImageTypes = new[] { ImageType.Primary },
- DtoOptions = new DtoOptions(false)
- });
- }
-
- //protected override Task<string> CreateImage(IHasMetadata item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
- //{
- // return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
- //}
- }
-
-}
diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
index 29836e0bf..b07798fa4 100644
--- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs
+++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
@@ -1,21 +1,31 @@
+#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.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Playlists;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using PlaylistsNET.Content;
using PlaylistsNET.Models;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
namespace Emby.Server.Implementations.Playlists
{
@@ -24,24 +34,27 @@ namespace Emby.Server.Implementations.Playlists
private readonly ILibraryManager _libraryManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _iLibraryMonitor;
- private readonly ILogger _logger;
+ private readonly ILogger<PlaylistManager> _logger;
private readonly IUserManager _userManager;
private readonly IProviderManager _providerManager;
+ private readonly IConfiguration _appConfig;
public PlaylistManager(
ILibraryManager libraryManager,
IFileSystem fileSystem,
ILibraryMonitor iLibraryMonitor,
- ILoggerFactory loggerFactory,
+ ILogger<PlaylistManager> logger,
IUserManager userManager,
- IProviderManager providerManager)
+ IProviderManager providerManager,
+ IConfiguration appConfig)
{
_libraryManager = libraryManager;
_fileSystem = fileSystem;
_iLibraryMonitor = iLibraryMonitor;
- _logger = loggerFactory.CreateLogger(nameof(PlaylistManager));
+ _logger = logger;
_userManager = userManager;
_providerManager = providerManager;
+ _appConfig = appConfig;
}
public IEnumerable<Playlist> GetPlaylists(Guid userId)
@@ -55,10 +68,8 @@ namespace Emby.Server.Implementations.Playlists
{
var name = options.Name;
- var folderName = _fileSystem.GetValidFilename(name) + " [playlist]";
-
+ var folderName = _fileSystem.GetValidFilename(name);
var parentFolder = GetPlaylistsFolder(Guid.Empty);
-
if (parentFolder == null)
{
throw new ArgumentException();
@@ -89,8 +100,7 @@ namespace Emby.Server.Implementations.Playlists
}
else
{
- var folder = item as Folder;
- if (folder != null)
+ if (item is Folder folder)
{
options.MediaType = folder.GetRecursiveChildren(i => !i.IsFolder && i.SupportsAddingToPlaylist)
.Select(i => i.MediaType)
@@ -129,7 +139,7 @@ namespace Emby.Server.Implementations.Playlists
{
new Share
{
- UserId = options.UserId.Equals(Guid.Empty) ? null : options.UserId.ToString("N"),
+ UserId = options.UserId.Equals(Guid.Empty) ? null : options.UserId.ToString("N", CultureInfo.InvariantCulture),
CanEdit = true
}
}
@@ -137,23 +147,20 @@ namespace Emby.Server.Implementations.Playlists
playlist.SetMediaType(options.MediaType);
- parentFolder.AddChild(playlist, CancellationToken.None);
+ parentFolder.AddChild(playlist);
- await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, CancellationToken.None)
+ await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = true }, CancellationToken.None)
.ConfigureAwait(false);
- if (options.ItemIdList.Length > 0)
+ if (options.ItemIdList.Count > 0)
{
- AddToPlaylistInternal(playlist.Id.ToString("N"), options.ItemIdList, user, new DtoOptions(false)
+ await AddToPlaylistInternal(playlist.Id, options.ItemIdList, user, new DtoOptions(false)
{
EnableImages = true
- });
+ }).ConfigureAwait(false);
}
- return new PlaylistCreationResult
- {
- Id = playlist.Id.ToString("N")
- };
+ return new PlaylistCreationResult(playlist.Id.ToString("N", CultureInfo.InvariantCulture));
}
finally
{
@@ -179,59 +186,81 @@ namespace Emby.Server.Implementations.Playlists
return Playlist.GetPlaylistItems(playlistMediaType, items, user, options);
}
- public void AddToPlaylist(string playlistId, IEnumerable<Guid> itemIds, Guid userId)
+ public Task AddToPlaylistAsync(Guid playlistId, IReadOnlyCollection<Guid> itemIds, Guid userId)
{
var user = userId.Equals(Guid.Empty) ? null : _userManager.GetUserById(userId);
- AddToPlaylistInternal(playlistId, itemIds, user, new DtoOptions(false)
+ return AddToPlaylistInternal(playlistId, itemIds, user, new DtoOptions(false)
{
EnableImages = true
});
}
- private void AddToPlaylistInternal(string playlistId, IEnumerable<Guid> itemIds, User user, DtoOptions options)
+ private async Task AddToPlaylistInternal(Guid playlistId, IReadOnlyCollection<Guid> newItemIds, User user, DtoOptions options)
{
- var playlist = _libraryManager.GetItemById(playlistId) as Playlist;
+ // Retrieve the existing playlist
+ var playlist = _libraryManager.GetItemById(playlistId) as Playlist
+ ?? throw new ArgumentException("No Playlist exists with Id " + playlistId);
- if (playlist == null)
+ // Retrieve all the items to be added to the playlist
+ var newItems = GetPlaylistItems(newItemIds, playlist.MediaType, user, options)
+ .Where(i => i.SupportsAddingToPlaylist);
+
+ // Filter out duplicate items, if necessary
+ if (!_appConfig.DoPlaylistsAllowDuplicates())
{
- throw new ArgumentException("No Playlist exists with the supplied Id");
+ var existingIds = playlist.LinkedChildren.Select(c => c.ItemId).ToHashSet();
+ newItems = newItems
+ .Where(i => !existingIds.Contains(i.Id))
+ .Distinct();
}
- var list = new List<LinkedChild>();
-
- var items = (GetPlaylistItems(itemIds, playlist.MediaType, user, options))
- .Where(i => i.SupportsAddingToPlaylist)
+ // Create a list of the new linked children to add to the playlist
+ var childrenToAdd = newItems
+ .Select(LinkedChild.Create)
.ToList();
- foreach (var item in items)
+ // Log duplicates that have been ignored, if any
+ int numDuplicates = newItemIds.Count - childrenToAdd.Count;
+ if (numDuplicates > 0)
{
- list.Add(LinkedChild.Create(item));
+ _logger.LogWarning("Ignored adding {DuplicateCount} duplicate items to playlist {PlaylistName}.", numDuplicates, playlist.Name);
}
- var newList = playlist.LinkedChildren.ToList();
- newList.AddRange(list);
- playlist.LinkedChildren = newList.ToArray();
+ // Do nothing else if there are no items to add to the playlist
+ if (childrenToAdd.Count == 0)
+ {
+ return;
+ }
+
+ // Create a new array with the updated playlist items
+ var newLinkedChildren = new LinkedChild[playlist.LinkedChildren.Length + childrenToAdd.Count];
+ playlist.LinkedChildren.CopyTo(newLinkedChildren, 0);
+ childrenToAdd.CopyTo(newLinkedChildren, playlist.LinkedChildren.Length);
- playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
+ // Update the playlist in the repository
+ playlist.LinkedChildren = newLinkedChildren;
+ await playlist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ // Update the playlist on disk
if (playlist.IsFile)
{
SavePlaylistFile(playlist);
}
- _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- ForceSave = true
-
- }, RefreshPriority.High);
+ // Refresh playlist metadata
+ _providerManager.QueueRefresh(
+ playlist.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = true
+ },
+ RefreshPriority.High);
}
- public void RemoveFromPlaylist(string playlistId, IEnumerable<string> entryIds)
+ public async Task RemoveFromPlaylistAsync(string playlistId, IEnumerable<string> entryIds)
{
- var playlist = _libraryManager.GetItemById(playlistId) as Playlist;
-
- if (playlist == null)
+ if (_libraryManager.GetItemById(playlistId) is not Playlist playlist)
{
throw new ArgumentException("No Playlist exists with the supplied Id");
}
@@ -246,25 +275,25 @@ namespace Emby.Server.Implementations.Playlists
.Select(i => i.Item1)
.ToArray();
- playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
+ await playlist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
if (playlist.IsFile)
{
SavePlaylistFile(playlist);
}
- _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- ForceSave = true
-
- }, RefreshPriority.High);
+ _providerManager.QueueRefresh(
+ playlist.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = true
+ },
+ RefreshPriority.High);
}
- public void MoveItem(string playlistId, string entryId, int newIndex)
+ public async Task MoveItemAsync(string playlistId, string entryId, int newIndex)
{
- var playlist = _libraryManager.GetItemById(playlistId) as Playlist;
-
- if (playlist == null)
+ if (_libraryManager.GetItemById(playlistId) is not Playlist playlist)
{
throw new ArgumentException("No Playlist exists with the supplied Id");
}
@@ -295,7 +324,7 @@ namespace Emby.Server.Implementations.Playlists
playlist.LinkedChildren = newList.ToArray();
- playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
+ await playlist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
if (playlist.IsFile)
{
@@ -305,7 +334,8 @@ namespace Emby.Server.Implementations.Playlists
private void SavePlaylistFile(Playlist item)
{
- // This is probably best done as a metatata provider, but saving a file over itself will first require some core work to prevent this from happening when not needed
+ // this is probably best done as a metadata provider
+ // saving a file over itself will require some work to prevent this from happening when not needed
var playlistPath = item.Path;
var extension = Path.GetExtension(playlistPath);
@@ -321,28 +351,28 @@ namespace Emby.Server.Implementations.Playlists
AlbumTitle = child.Album
};
- var hasAlbumArtist = child as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (child is IHasAlbumArtist hasAlbumArtist)
{
- entry.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
+ entry.AlbumArtist = hasAlbumArtist.AlbumArtists.Count > 0 ? hasAlbumArtist.AlbumArtists[0] : null;
}
- var hasArtist = child as IHasArtist;
- if (hasArtist != null)
+ if (child is IHasArtist hasArtist)
{
- entry.TrackArtist = hasArtist.Artists.FirstOrDefault();
+ entry.TrackArtist = hasArtist.Artists.Count > 0 ? hasArtist.Artists[0] : null;
}
if (child.RunTimeTicks.HasValue)
{
entry.Duration = TimeSpan.FromTicks(child.RunTimeTicks.Value);
}
+
playlist.PlaylistEntries.Add(entry);
}
string text = new WplContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
}
+
if (string.Equals(".zpl", extension, StringComparison.OrdinalIgnoreCase))
{
var playlist = new ZplPlaylist();
@@ -355,32 +385,34 @@ namespace Emby.Server.Implementations.Playlists
AlbumTitle = child.Album
};
- var hasAlbumArtist = child as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (child is IHasAlbumArtist hasAlbumArtist)
{
- entry.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
+ entry.AlbumArtist = hasAlbumArtist.AlbumArtists.Count > 0 ? hasAlbumArtist.AlbumArtists[0] : null;
}
- var hasArtist = child as IHasArtist;
- if (hasArtist != null)
+ if (child is IHasArtist hasArtist)
{
- entry.TrackArtist = hasArtist.Artists.FirstOrDefault();
+ entry.TrackArtist = hasArtist.Artists.Count > 0 ? hasArtist.Artists[0] : null;
}
if (child.RunTimeTicks.HasValue)
{
entry.Duration = TimeSpan.FromTicks(child.RunTimeTicks.Value);
}
+
playlist.PlaylistEntries.Add(entry);
}
string text = new ZplContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
}
+
if (string.Equals(".m3u", extension, StringComparison.OrdinalIgnoreCase))
{
- var playlist = new M3uPlaylist();
- playlist.IsExtended = true;
+ var playlist = new M3uPlaylist
+ {
+ IsExtended = true
+ };
foreach (var child in item.GetLinkedChildren())
{
var entry = new M3uPlaylistEntry()
@@ -390,22 +422,23 @@ namespace Emby.Server.Implementations.Playlists
Album = child.Album
};
- var hasAlbumArtist = child as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (child is IHasAlbumArtist hasAlbumArtist)
{
- entry.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
+ entry.AlbumArtist = hasAlbumArtist.AlbumArtists.Count > 0 ? hasAlbumArtist.AlbumArtists[0] : null;
}
if (child.RunTimeTicks.HasValue)
{
entry.Duration = TimeSpan.FromTicks(child.RunTimeTicks.Value);
}
+
playlist.PlaylistEntries.Add(entry);
}
string text = new M3uContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
}
+
if (string.Equals(".m3u8", extension, StringComparison.OrdinalIgnoreCase))
{
var playlist = new M3uPlaylist();
@@ -419,22 +452,23 @@ namespace Emby.Server.Implementations.Playlists
Album = child.Album
};
- var hasAlbumArtist = child as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (child is IHasAlbumArtist hasAlbumArtist)
{
- entry.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
+ entry.AlbumArtist = hasAlbumArtist.AlbumArtists.Count > 0 ? hasAlbumArtist.AlbumArtists[0] : null;
}
if (child.RunTimeTicks.HasValue)
{
entry.Duration = TimeSpan.FromTicks(child.RunTimeTicks.Value);
}
+
playlist.PlaylistEntries.Add(entry);
}
- string text = new M3u8Content().ToText(playlist);
+ string text = new M3uContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
}
+
if (string.Equals(".pls", extension, StringComparison.OrdinalIgnoreCase))
{
var playlist = new PlsPlaylist();
@@ -450,6 +484,7 @@ namespace Emby.Server.Implementations.Playlists
{
entry.Length = TimeSpan.FromTicks(child.RunTimeTicks.Value);
}
+
playlist.PlaylistEntries.Add(entry);
}
@@ -475,15 +510,19 @@ namespace Emby.Server.Implementations.Playlists
throw new ArgumentException("File absolute path was null or empty.", nameof(fileAbsolutePath));
}
- if (!folderPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
+ if (!folderPath.EndsWith(Path.DirectorySeparatorChar))
{
- folderPath = folderPath + Path.DirectorySeparatorChar;
+ folderPath += Path.DirectorySeparatorChar;
}
var folderUri = new Uri(folderPath);
var fileAbsoluteUri = new Uri(fileAbsolutePath);
- if (folderUri.Scheme != fileAbsoluteUri.Scheme) { return fileAbsolutePath; } // path can't be made relative.
+ // path can't be made relative
+ if (folderUri.Scheme != fileAbsoluteUri.Scheme)
+ {
+ return fileAbsolutePath;
+ }
var relativeUri = folderUri.MakeRelativeUri(fileAbsoluteUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
@@ -496,24 +535,12 @@ namespace Emby.Server.Implementations.Playlists
return relativePath;
}
- private static string UnEscape(string content)
- {
- if (content == null) return content;
- return content.Replace("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<");
- }
-
- private static string Escape(string content)
- {
- if (content == null) return null;
- return content.Replace("&", "&amp;").Replace("'", "&apos;").Replace("\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;");
- }
-
public Folder GetPlaylistsFolder(Guid userId)
{
- var typeName = "PlaylistsFolder";
+ const string TypeName = "PlaylistsFolder";
- return _libraryManager.RootFolder.Children.OfType<Folder>().FirstOrDefault(i => string.Equals(i.GetType().Name, typeName, StringComparison.Ordinal)) ??
- _libraryManager.GetUserRootFolder().Children.OfType<Folder>().FirstOrDefault(i => string.Equals(i.GetType().Name, typeName, StringComparison.Ordinal));
+ return _libraryManager.RootFolder.Children.OfType<Folder>().FirstOrDefault(i => string.Equals(i.GetType().Name, TypeName, StringComparison.Ordinal)) ??
+ _libraryManager.GetUserRootFolder().Children.OfType<Folder>().FirstOrDefault(i => string.Equals(i.GetType().Name, TypeName, StringComparison.Ordinal));
}
}
}
diff --git a/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs b/Emby.Server.Implementations/Playlists/PlaylistsFolder.cs
index f4decc856..8b1cee89d 100644
--- a/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs
+++ b/Emby.Server.Implementations/Playlists/PlaylistsFolder.cs
@@ -1,9 +1,12 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
namespace Emby.Server.Implementations.Playlists
{
@@ -14,6 +17,15 @@ namespace Emby.Server.Implementations.Playlists
Name = "Playlists";
}
+ [JsonIgnore]
+ public override bool IsHidden => true;
+
+ [JsonIgnore]
+ public override bool SupportsInheritedParentImages => false;
+
+ [JsonIgnore]
+ public override string CollectionType => MediaBrowser.Model.Entities.CollectionType.Playlists;
+
public override bool IsVisible(User user)
{
return base.IsVisible(user) && GetChildren(user, true).Any();
@@ -24,15 +36,6 @@ namespace Emby.Server.Implementations.Playlists
return base.GetEligibleChildrenForRecursiveChildren(user).OfType<Playlist>();
}
- [IgnoreDataMember]
- public override bool IsHidden => true;
-
- [IgnoreDataMember]
- public override bool SupportsInheritedParentImages => false;
-
- [IgnoreDataMember]
- public override string CollectionType => MediaBrowser.Model.Entities.CollectionType.Playlists;
-
protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
{
if (query.User == null)
@@ -42,10 +45,14 @@ namespace Emby.Server.Implementations.Playlists
}
query.Recursive = true;
- query.IncludeItemTypes = new string[] { "Playlist" };
+ query.IncludeItemTypes = new[] { "Playlist" };
query.Parent = null;
return LibraryManager.GetItemsResult(query);
}
+
+ public override string GetClientTypeName()
+ {
+ return "ManualPlaylistsFolder";
+ }
}
}
-
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
new file mode 100644
index 000000000..d52c0b2a1
--- /dev/null
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -0,0 +1,757 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Reflection;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
+using Jellyfin.Extensions.Json.Converters;
+using MediaBrowser.Common;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Updates;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.Plugins
+{
+ /// <summary>
+ /// Defines the <see cref="PluginManager" />.
+ /// </summary>
+ public class PluginManager : IPluginManager
+ {
+ private readonly string _pluginsPath;
+ private readonly Version _appVersion;
+ private readonly JsonSerializerOptions _jsonOptions;
+ private readonly ILogger<PluginManager> _logger;
+ private readonly IApplicationHost _appHost;
+ private readonly ServerConfiguration _config;
+ private readonly List<LocalPlugin> _plugins;
+ private readonly Version _minimumVersion;
+
+ private IHttpClientFactory? _httpClientFactory;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginManager"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger"/>.</param>
+ /// <param name="appHost">The <see cref="IApplicationHost"/>.</param>
+ /// <param name="config">The <see cref="ServerConfiguration"/>.</param>
+ /// <param name="pluginsPath">The plugin path.</param>
+ /// <param name="appVersion">The application version.</param>
+ public PluginManager(
+ ILogger<PluginManager> logger,
+ IApplicationHost appHost,
+ ServerConfiguration config,
+ string pluginsPath,
+ Version appVersion)
+ {
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _pluginsPath = pluginsPath;
+ _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
+ _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options)
+ {
+ WriteIndented = true
+ };
+
+ // We need to use the default GUID converter, so we need to remove any custom ones.
+ for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--)
+ {
+ if (_jsonOptions.Converters[a] is JsonGuidConverter convertor)
+ {
+ _jsonOptions.Converters.Remove(convertor);
+ break;
+ }
+ }
+
+ _config = config;
+ _appHost = appHost;
+ _minimumVersion = new Version(0, 0, 0, 1);
+ _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
+ }
+
+ private IHttpClientFactory HttpClientFactory
+ {
+ get
+ {
+ return _httpClientFactory ??= _appHost.Resolve<IHttpClientFactory>();
+ }
+ }
+
+ /// <summary>
+ /// Gets the Plugins.
+ /// </summary>
+ public IReadOnlyList<LocalPlugin> Plugins => _plugins;
+
+ /// <summary>
+ /// Returns all the assemblies.
+ /// </summary>
+ /// <returns>An IEnumerable{Assembly}.</returns>
+ public IEnumerable<Assembly> LoadAssemblies()
+ {
+ // Attempt to remove any deleted plugins and change any successors to be active.
+ for (int i = _plugins.Count - 1; i >= 0; i--)
+ {
+ var plugin = _plugins[i];
+ if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin))
+ {
+ // See if there is another version, and if so make that active.
+ ProcessAlternative(plugin);
+ }
+ }
+
+ // Now load the assemblies..
+ foreach (var plugin in _plugins)
+ {
+ UpdatePluginSuperceedStatus(plugin);
+
+ if (plugin.IsEnabledAndSupported == false)
+ {
+ _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name);
+ continue;
+ }
+
+ foreach (var file in plugin.DllFiles)
+ {
+ Assembly assembly;
+ try
+ {
+ assembly = Assembly.LoadFrom(file);
+
+ assembly.GetExportedTypes();
+ }
+ catch (FileLoadException ex)
+ {
+ _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin.", file);
+ ChangePluginState(plugin, PluginStatus.Malfunctioned);
+ continue;
+ }
+ catch (TypeLoadException ex) // Undocumented exception
+ {
+ _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin.", file);
+ ChangePluginState(plugin, PluginStatus.NotSupported);
+ continue;
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin.", file);
+ ChangePluginState(plugin, PluginStatus.Malfunctioned);
+ continue;
+ }
+
+ _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file);
+ yield return assembly;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Creates all the plugin instances.
+ /// </summary>
+ public void CreatePlugins()
+ {
+ _ = _appHost.GetExports<IPlugin>(CreatePluginInstance);
+ }
+
+ /// <summary>
+ /// Registers the plugin's services with the DI.
+ /// Note: DI is not yet instantiated yet.
+ /// </summary>
+ /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
+ public void RegisterServices(IServiceCollection serviceCollection)
+ {
+ foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>())
+ {
+ var plugin = GetPluginByAssembly(pluginServiceRegistrator.Assembly);
+ if (plugin == null)
+ {
+ _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName);
+ continue;
+ }
+
+ UpdatePluginSuperceedStatus(plugin);
+ if (!plugin.IsEnabledAndSupported)
+ {
+ continue;
+ }
+
+ try
+ {
+ var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator);
+ instance?.RegisterServices(serviceCollection);
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName);
+ if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
+ {
+ _logger.LogInformation("Disabling plugin {Path}", plugin.Path);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Imports a plugin manifest from <paramref name="folder"/>.
+ /// </summary>
+ /// <param name="folder">Folder of the plugin.</param>
+ public void ImportPluginFrom(string folder)
+ {
+ if (string.IsNullOrEmpty(folder))
+ {
+ throw new ArgumentNullException(nameof(folder));
+ }
+
+ // Load the plugin.
+ var plugin = LoadManifest(folder);
+ // Make sure we haven't already loaded this.
+ if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest)))
+ {
+ return;
+ }
+
+ _plugins.Add(plugin);
+ EnablePlugin(plugin);
+ }
+
+ /// <summary>
+ /// Removes the plugin reference '<paramref name="plugin"/>.
+ /// </summary>
+ /// <param name="plugin">The plugin.</param>
+ /// <returns>Outcome of the operation.</returns>
+ public bool RemovePlugin(LocalPlugin plugin)
+ {
+ if (plugin == null)
+ {
+ throw new ArgumentNullException(nameof(plugin));
+ }
+
+ if (DeletePlugin(plugin))
+ {
+ ProcessAlternative(plugin);
+ return true;
+ }
+
+ _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
+ // Unable to delete, so disable.
+ if (ChangePluginState(plugin, PluginStatus.Deleted))
+ {
+ ProcessAlternative(plugin);
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to find the plugin with and id of <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The <see cref="Guid"/> of plugin.</param>
+ /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
+ /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
+ public LocalPlugin? GetPlugin(Guid id, Version? version = null)
+ {
+ LocalPlugin? plugin;
+
+ if (version == null)
+ {
+ // If no version is given, return the current instance.
+ var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList();
+
+ plugin = plugins.FirstOrDefault(p => p.Instance != null) ?? plugins.OrderByDescending(p => p.Version).FirstOrDefault();
+ }
+ else
+ {
+ // Match id and version number.
+ plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
+ }
+
+ return plugin;
+ }
+
+ /// <summary>
+ /// Enables the plugin, disabling all other versions.
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
+ public void EnablePlugin(LocalPlugin plugin)
+ {
+ if (plugin == null)
+ {
+ throw new ArgumentNullException(nameof(plugin));
+ }
+
+ if (ChangePluginState(plugin, PluginStatus.Active))
+ {
+ // See if there is another version, and if so, supercede it.
+ ProcessAlternative(plugin);
+ }
+ }
+
+ /// <summary>
+ /// Disable the plugin.
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
+ public void DisablePlugin(LocalPlugin plugin)
+ {
+ if (plugin == null)
+ {
+ throw new ArgumentNullException(nameof(plugin));
+ }
+
+ // Update the manifest on disk
+ if (ChangePluginState(plugin, PluginStatus.Disabled))
+ {
+ // If there is another version, activate it.
+ ProcessAlternative(plugin);
+ }
+ }
+
+ /// <summary>
+ /// Disable the plugin.
+ /// </summary>
+ /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
+ public void FailPlugin(Assembly assembly)
+ {
+ // Only save if disabled.
+ if (assembly == null)
+ {
+ throw new ArgumentNullException(nameof(assembly));
+ }
+
+ var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
+ if (plugin == null)
+ {
+ // A plugin's assembly didn't cause this issue, so ignore it.
+ return;
+ }
+
+ ChangePluginState(plugin, PluginStatus.Malfunctioned);
+ }
+
+ /// <inheritdoc/>
+ public bool SaveManifest(PluginManifest manifest, string path)
+ {
+ try
+ {
+ var data = JsonSerializer.Serialize(manifest, _jsonOptions);
+ File.WriteAllText(Path.Combine(path, "meta.json"), data);
+ return true;
+ }
+ catch (ArgumentException e)
+ {
+ _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path);
+ return false;
+ }
+ }
+
+ /// <inheritdoc/>
+ public async Task<bool> GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
+ {
+ if (packageInfo == null)
+ {
+ return false;
+ }
+
+ var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
+ var imagePath = string.Empty;
+
+ if (!string.IsNullOrEmpty(packageInfo.ImageUrl))
+ {
+ var url = new Uri(packageInfo.ImageUrl);
+ imagePath = Path.Join(path, url.Segments[^1]);
+
+ await using var fileStream = AsyncFile.OpenWrite(imagePath);
+
+ try
+ {
+ await using var downloadStream = await HttpClientFactory
+ .CreateClient(NamedClient.Default)
+ .GetStreamAsync(url)
+ .ConfigureAwait(false);
+
+ await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
+ }
+ catch (HttpRequestException ex)
+ {
+ _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath);
+ imagePath = string.Empty;
+ }
+ }
+
+ var manifest = new PluginManifest
+ {
+ Category = packageInfo.Category,
+ Changelog = versionInfo.Changelog ?? string.Empty,
+ Description = packageInfo.Description,
+ Id = packageInfo.Id,
+ Name = packageInfo.Name,
+ Overview = packageInfo.Overview,
+ Owner = packageInfo.Owner,
+ TargetAbi = versionInfo.TargetAbi ?? string.Empty,
+ Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp, CultureInfo.InvariantCulture),
+ Version = versionInfo.Version,
+ Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state.
+ AutoUpdate = true,
+ ImagePath = imagePath
+ };
+
+ return SaveManifest(manifest, path);
+ }
+
+ /// <summary>
+ /// Changes a plugin's load status.
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
+ /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
+ /// <returns>Success of the task.</returns>
+ private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
+ {
+ if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
+ {
+ // No need to save as the state hasn't changed.
+ return true;
+ }
+
+ plugin.Manifest.Status = state;
+ return SaveManifest(plugin.Manifest, plugin.Path);
+ }
+
+ /// <summary>
+ /// Finds the plugin record using the assembly.
+ /// </summary>
+ /// <param name="assembly">The <see cref="Assembly"/> being sought.</param>
+ /// <returns>The matching record, or null if not found.</returns>
+ private LocalPlugin? GetPluginByAssembly(Assembly assembly)
+ {
+ // Find which plugin it is by the path.
+ return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal));
+ }
+
+ /// <summary>
+ /// Creates the instance safe.
+ /// </summary>
+ /// <param name="type">The type.</param>
+ /// <returns>System.Object.</returns>
+ private IPlugin? CreatePluginInstance(Type type)
+ {
+ // Find the record for this plugin.
+ var plugin = GetPluginByAssembly(type.Assembly);
+ if (plugin?.Manifest.Status < PluginStatus.Active)
+ {
+ return null;
+ }
+
+ try
+ {
+ _logger.LogDebug("Creating instance of {Type}", type);
+ // _appHost.ServiceProvider is already assigned when we create the plugins
+ var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
+ if (plugin == null)
+ {
+ // Create a dummy record for the providers.
+ // TODO: remove this code once all provided have been released as separate plugins.
+ plugin = new LocalPlugin(
+ instance.AssemblyFilePath,
+ true,
+ new PluginManifest
+ {
+ Id = instance.Id,
+ Status = PluginStatus.Active,
+ Name = instance.Name,
+ Version = instance.Version.ToString()
+ })
+ {
+ Instance = instance
+ };
+
+ _plugins.Add(plugin);
+
+ plugin.Manifest.Status = PluginStatus.Active;
+ }
+ else
+ {
+ plugin.Instance = instance;
+ var manifest = plugin.Manifest;
+ var pluginStr = instance.Version.ToString();
+ bool changed = false;
+ if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)
+ || manifest.Id != instance.Id)
+ {
+ // If a plugin without a manifest failed to load due to an external issue (eg config),
+ // this updates the manifest to the actual plugin values.
+ manifest.Version = pluginStr;
+ manifest.Name = plugin.Instance.Name;
+ manifest.Description = plugin.Instance.Description;
+ manifest.Id = plugin.Instance.Id;
+ changed = true;
+ }
+
+ changed = changed || manifest.Status != PluginStatus.Active;
+ manifest.Status = PluginStatus.Active;
+
+ if (changed)
+ {
+ SaveManifest(manifest, plugin.Path);
+ }
+ }
+
+ _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
+
+ return instance;
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ _logger.LogError(ex, "Error creating {Type}", type.FullName);
+ if (plugin != null)
+ {
+ if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
+ {
+ _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
+ return null;
+ }
+ }
+
+ _logger.LogDebug("Unable to auto-disable.");
+ return null;
+ }
+ }
+
+ private void UpdatePluginSuperceedStatus(LocalPlugin plugin)
+ {
+ if (plugin.Manifest.Status != PluginStatus.Superceded)
+ {
+ return;
+ }
+
+ var predecessor = _plugins.OrderByDescending(p => p.Version)
+ .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
+ if (predecessor != null)
+ {
+ return;
+ }
+
+ plugin.Manifest.Status = PluginStatus.Active;
+ }
+
+ /// <summary>
+ /// Attempts to delete a plugin.
+ /// </summary>
+ /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
+ /// <returns>True if successful.</returns>
+ private bool DeletePlugin(LocalPlugin plugin)
+ {
+ // Attempt a cleanup of old folders.
+ try
+ {
+ Directory.Delete(plugin.Path, true);
+ _logger.LogDebug("Deleted {Path}", plugin.Path);
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ return false;
+ }
+
+ return _plugins.Remove(plugin);
+ }
+
+ internal LocalPlugin LoadManifest(string dir)
+ {
+ Version? version;
+ PluginManifest? manifest = null;
+ var metafile = Path.Combine(dir, "meta.json");
+ if (File.Exists(metafile))
+ {
+ // Only path where this stays null is when File.ReadAllBytes throws an IOException
+ byte[] data = null!;
+ try
+ {
+ data = File.ReadAllBytes(metafile);
+ manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error reading file {Path}.", dir);
+ }
+ catch (JsonException ex)
+ {
+ _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data!));
+ }
+
+ if (manifest != null)
+ {
+ if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
+ {
+ targetAbi = _minimumVersion;
+ }
+
+ if (!Version.TryParse(manifest.Version, out version))
+ {
+ manifest.Version = _minimumVersion.ToString();
+ }
+
+ return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
+ }
+ }
+
+ // No metafile, so lets see if the folder is versioned.
+ // TODO: Phase this support out in future versions.
+ metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
+ int versionIndex = dir.LastIndexOf('_');
+ if (versionIndex != -1)
+ {
+ // Get the version number from the filename if possible.
+ metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex];
+ version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
+ }
+ else
+ {
+ // Un-versioned folder - Add it under the path name and version it suitable for this instance.
+ version = _appVersion;
+ }
+
+ // Auto-create a plugin manifest, so we can disable it, if it fails to load.
+ manifest = new PluginManifest
+ {
+ Status = PluginStatus.Active,
+ Name = metafile,
+ AutoUpdate = false,
+ Id = metafile.GetMD5(),
+ TargetAbi = _appVersion.ToString(),
+ Version = version.ToString()
+ };
+
+ return new LocalPlugin(dir, true, manifest);
+ }
+
+ /// <summary>
+ /// Gets the list of local plugins.
+ /// </summary>
+ /// <returns>Enumerable of local plugins.</returns>
+ private IEnumerable<LocalPlugin> DiscoverPlugins()
+ {
+ var versions = new List<LocalPlugin>();
+
+ if (!Directory.Exists(_pluginsPath))
+ {
+ // Plugin path doesn't exist, don't try to enumerate sub-folders.
+ return Enumerable.Empty<LocalPlugin>();
+ }
+
+ var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
+ foreach (var dir in directories)
+ {
+ versions.Add(LoadManifest(dir));
+ }
+
+ string lastName = string.Empty;
+ versions.Sort(LocalPlugin.Compare);
+ // Traverse backwards through the list.
+ // The first item will be the latest version.
+ for (int x = versions.Count - 1; x >= 0; x--)
+ {
+ var entry = versions[x];
+ if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
+ {
+ entry.DllFiles = Directory.GetFiles(entry.Path, "*.dll", SearchOption.AllDirectories);
+ if (entry.IsEnabledAndSupported)
+ {
+ lastName = entry.Name;
+ continue;
+ }
+ }
+
+ if (string.IsNullOrEmpty(lastName))
+ {
+ continue;
+ }
+
+ var manifest = entry.Manifest;
+ var cleaned = false;
+ var path = entry.Path;
+ if (_config.RemoveOldPlugins)
+ {
+ // Attempt a cleanup of old folders.
+ try
+ {
+ _logger.LogDebug("Deleting {Path}", path);
+ Directory.Delete(path, true);
+ cleaned = true;
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception e)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ _logger.LogWarning(e, "Unable to delete {Path}", path);
+ }
+
+ if (cleaned)
+ {
+ versions.RemoveAt(x);
+ }
+ else
+ {
+ if (manifest == null)
+ {
+ _logger.LogWarning("Unable to disable plugin {Path}", entry.Path);
+ continue;
+ }
+
+ ChangePluginState(entry, PluginStatus.Deleted);
+ }
+ }
+ }
+
+ // Only want plugin folders which have files.
+ return versions.Where(p => p.DllFiles.Count != 0);
+ }
+
+ /// <summary>
+ /// Changes the status of the other versions of the plugin to "Superceded".
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
+ private void ProcessAlternative(LocalPlugin plugin)
+ {
+ // Detect whether there is another version of this plugin that needs disabling.
+ var previousVersion = _plugins.OrderByDescending(p => p.Version)
+ .FirstOrDefault(
+ p => p.Id.Equals(plugin.Id)
+ && p.IsEnabledAndSupported
+ && p.Version != plugin.Version);
+
+ if (previousVersion == null)
+ {
+ // This value is memory only - so that the web will show restart required.
+ plugin.Manifest.Status = PluginStatus.Restart;
+ return;
+ }
+
+ if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Superceded))
+ {
+ _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
+ }
+ else if (plugin.Manifest.Status == PluginStatus.Superceded && !ChangePluginState(previousVersion, PluginStatus.Active))
+ {
+ _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
+ }
+
+ // This value is memory only - so that the web will show restart required.
+ plugin.Manifest.Status = PluginStatus.Restart;
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Properties/AssemblyInfo.cs b/Emby.Server.Implementations/Properties/AssemblyInfo.cs
index 79ba9374c..41c396ac1 100644
--- a/Emby.Server.Implementations/Properties/AssemblyInfo.cs
+++ b/Emby.Server.Implementations/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -10,10 +11,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
[assembly: AssemblyProduct("Jellyfin Server")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.Server.Implementations.Tests")]
+[assembly: InternalsVisibleTo("Emby.Server.Implementations.Fuzz")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs
new file mode 100644
index 000000000..c81c26994
--- /dev/null
+++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs
@@ -0,0 +1,246 @@
+using System;
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.QuickConnect;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.QuickConnect;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.QuickConnect
+{
+ /// <summary>
+ /// Quick connect implementation.
+ /// </summary>
+ public class QuickConnectManager : IQuickConnect
+ {
+ /// <summary>
+ /// The length of user facing codes.
+ /// </summary>
+ private const int CodeLength = 6;
+
+ /// <summary>
+ /// The time (in minutes) that the quick connect token is valid.
+ /// </summary>
+ private const int Timeout = 10;
+
+ private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new ();
+ private readonly ConcurrentDictionary<string, (DateTime Timestamp, AuthenticationResult AuthenticationResult)> _authorizedSecrets = new ();
+
+ private readonly IServerConfigurationManager _config;
+ private readonly ILogger<QuickConnectManager> _logger;
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QuickConnectManager"/> class.
+ /// Should only be called at server startup when a singleton is created.
+ /// </summary>
+ /// <param name="config">Configuration.</param>
+ /// <param name="logger">Logger.</param>
+ /// <param name="sessionManager">Session Manager.</param>
+ public QuickConnectManager(
+ IServerConfigurationManager config,
+ ILogger<QuickConnectManager> logger,
+ ISessionManager sessionManager)
+ {
+ _config = config;
+ _logger = logger;
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public bool IsEnabled => _config.Configuration.QuickConnectAvailable;
+
+ /// <summary>
+ /// Assert that quick connect is currently active and throws an exception if it is not.
+ /// </summary>
+ private void AssertActive()
+ {
+ if (!IsEnabled)
+ {
+ throw new AuthenticationException("Quick connect is not active on this server");
+ }
+ }
+
+ /// <inheritdoc/>
+ public QuickConnectResult TryConnect(AuthorizationInfo authorizationInfo)
+ {
+ if (string.IsNullOrEmpty(authorizationInfo.DeviceId))
+ {
+ throw new ArgumentException(nameof(authorizationInfo.DeviceId) + " is required");
+ }
+
+ if (string.IsNullOrEmpty(authorizationInfo.Device))
+ {
+ throw new ArgumentException(nameof(authorizationInfo.Device) + " is required");
+ }
+
+ if (string.IsNullOrEmpty(authorizationInfo.Client))
+ {
+ throw new ArgumentException(nameof(authorizationInfo.Client) + " is required");
+ }
+
+ if (string.IsNullOrEmpty(authorizationInfo.Version))
+ {
+ throw new ArgumentException(nameof(authorizationInfo.Version) + "is required");
+ }
+
+ AssertActive();
+ ExpireRequests();
+
+ var secret = GenerateSecureRandom();
+ var code = GenerateCode();
+ var result = new QuickConnectResult(
+ secret,
+ code,
+ DateTime.UtcNow,
+ authorizationInfo.DeviceId,
+ authorizationInfo.Device,
+ authorizationInfo.Client,
+ authorizationInfo.Version);
+
+ _currentRequests[code] = result;
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public QuickConnectResult CheckRequestStatus(string secret)
+ {
+ AssertActive();
+ ExpireRequests();
+
+ string code = _currentRequests.Where(x => x.Value.Secret == secret).Select(x => x.Value.Code).DefaultIfEmpty(string.Empty).First();
+
+ if (!_currentRequests.TryGetValue(code, out QuickConnectResult? result))
+ {
+ throw new ResourceNotFoundException("Unable to find request with provided secret");
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Generates a short code to display to the user to uniquely identify this request.
+ /// </summary>
+ /// <returns>A short, unique alphanumeric string.</returns>
+ private string GenerateCode()
+ {
+ Span<byte> raw = stackalloc byte[4];
+
+ int min = (int)Math.Pow(10, CodeLength - 1);
+ int max = (int)Math.Pow(10, CodeLength);
+
+ uint scale = uint.MaxValue;
+ while (scale == uint.MaxValue)
+ {
+ RandomNumberGenerator.Fill(raw);
+ scale = BitConverter.ToUInt32(raw);
+ }
+
+ int code = (int)(min + ((max - min) * (scale / (double)uint.MaxValue)));
+ return code.ToString(CultureInfo.InvariantCulture);
+ }
+
+ /// <inheritdoc/>
+ public async Task<bool> AuthorizeRequest(Guid userId, string code)
+ {
+ AssertActive();
+ ExpireRequests();
+
+ if (!_currentRequests.TryGetValue(code, out QuickConnectResult? result))
+ {
+ throw new ResourceNotFoundException("Unable to find request");
+ }
+
+ if (result.Authenticated)
+ {
+ throw new InvalidOperationException("Request is already authorized");
+ }
+
+ // Change the time on the request so it expires one minute into the future. It can't expire immediately as otherwise some clients wouldn't ever see that they have been authenticated.
+ result.DateAdded = DateTime.UtcNow.Add(TimeSpan.FromMinutes(1));
+
+ var authenticationResult = await _sessionManager.AuthenticateDirect(new AuthenticationRequest
+ {
+ UserId = userId,
+ DeviceId = result.DeviceId,
+ DeviceName = result.DeviceName,
+ App = result.AppName,
+ AppVersion = result.AppVersion
+ }).ConfigureAwait(false);
+
+ _authorizedSecrets[result.Secret] = (DateTime.UtcNow, authenticationResult);
+ result.Authenticated = true;
+ _currentRequests[code] = result;
+
+ _logger.LogDebug("Authorizing device with code {Code} to login as user {UserId}", code, userId);
+
+ return true;
+ }
+
+ /// <inheritdoc/>
+ public AuthenticationResult GetAuthorizedRequest(string secret)
+ {
+ AssertActive();
+ ExpireRequests();
+
+ if (!_authorizedSecrets.TryGetValue(secret, out var result))
+ {
+ throw new ResourceNotFoundException("Unable to find request");
+ }
+
+ return result.AuthenticationResult;
+ }
+
+ private string GenerateSecureRandom(int length = 32)
+ {
+ Span<byte> bytes = stackalloc byte[length];
+ RandomNumberGenerator.Fill(bytes);
+
+ return Convert.ToHexString(bytes);
+ }
+
+ /// <summary>
+ /// Expire quick connect requests that are over the time limit. If <paramref name="expireAll"/> is true, all requests are unconditionally expired.
+ /// </summary>
+ /// <param name="expireAll">If true, all requests will be expired.</param>
+ private void ExpireRequests(bool expireAll = false)
+ {
+ // All requests before this timestamp have expired
+ var minTime = DateTime.UtcNow.AddMinutes(-Timeout);
+
+ // Expire stale connection requests
+ foreach (var (_, currentRequest) in _currentRequests)
+ {
+ if (expireAll || currentRequest.DateAdded < minTime)
+ {
+ var code = currentRequest.Code;
+ _logger.LogDebug("Removing expired request {Code}", code);
+
+ if (!_currentRequests.TryRemove(code, out _))
+ {
+ _logger.LogWarning("Request {Code} already expired", code);
+ }
+ }
+ }
+
+ foreach (var (secret, (timestamp, _)) in _authorizedSecrets)
+ {
+ if (expireAll || timestamp < minTime)
+ {
+ _logger.LogDebug("Removing expired secret {Secret}", secret);
+ if (!_authorizedSecrets.TryRemove(secret, out _))
+ {
+ _logger.LogWarning("Secret {Secret} already expired", secret);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Reflection/AssemblyInfo.cs b/Emby.Server.Implementations/Reflection/AssemblyInfo.cs
deleted file mode 100644
index 9d16fe43f..000000000
--- a/Emby.Server.Implementations/Reflection/AssemblyInfo.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-using MediaBrowser.Model.Reflection;
-
-namespace Emby.Server.Implementations.Reflection
-{
- public class AssemblyInfo : IAssemblyInfo
- {
- public Stream GetManifestResourceStream(Type type, string resource)
- {
- return type.Assembly.GetManifestResourceStream(resource);
- }
-
- public string[] GetManifestResourceNames(Type type)
- {
- return type.Assembly.GetManifestResourceNames();
- }
-
- public Assembly[] GetCurrentAssemblies()
- {
- return AppDomain.CurrentDomain.GetAssemblies();
- }
- }
-}
diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs
deleted file mode 100644
index 890d848f4..000000000
--- a/Emby.Server.Implementations/ResourceFileManager.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations
-{
- public class ResourceFileManager : IResourceFileManager
- {
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
- private readonly IHttpResultFactory _resultFactory;
-
- public ResourceFileManager(
- IHttpResultFactory resultFactory,
- ILoggerFactory loggerFactory,
- IFileSystem fileSystem)
- {
- _resultFactory = resultFactory;
- _logger = loggerFactory.CreateLogger("ResourceManager");
- _fileSystem = fileSystem;
- }
-
- public Stream GetResourceFileStream(string basePath, string virtualPath)
- {
- return _fileSystem.GetFileStream(GetResourcePath(basePath, virtualPath), FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
- }
-
- public Task<object> GetStaticFileResult(IRequest request, string basePath, string virtualPath, string contentType, TimeSpan? cacheDuration)
- {
- return _resultFactory.GetStaticFileResult(request, GetResourcePath(basePath, virtualPath));
- }
-
- public string ReadAllText(string basePath, string virtualPath)
- {
- return File.ReadAllText(GetResourcePath(basePath, virtualPath));
- }
-
- private string GetResourcePath(string basePath, string virtualPath)
- {
- var fullPath = Path.Combine(basePath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
-
- try
- {
- fullPath = Path.GetFullPath(fullPath);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in Path.GetFullPath");
- }
-
- // Don't allow file system access outside of the source folder
- if (!_fileSystem.ContainsSubPath(basePath, fullPath))
- {
- throw new SecurityException("Access denied");
- }
-
- return fullPath;
- }
- }
-}
diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
index 08bb39578..f2cdfeb16 100644
--- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
@@ -1,57 +1,75 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Events;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class ScheduledTaskWorker
+ /// Class ScheduledTaskWorker.
/// </summary>
public class ScheduledTaskWorker : IScheduledTaskWorker
{
- public event EventHandler<GenericEventArgs<double>> TaskProgress;
-
- /// <summary>
- /// Gets or sets the scheduled task.
- /// </summary>
- /// <value>The scheduled task.</value>
- public IScheduledTask ScheduledTask { get; private set; }
-
/// <summary>
- /// Gets or sets the json serializer.
+ /// The options for the json Serializer.
/// </summary>
- /// <value>The json serializer.</value>
- private IJsonSerializer JsonSerializer { get; set; }
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
/// <summary>
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
- private IApplicationPaths ApplicationPaths { get; set; }
+ private readonly IApplicationPaths _applicationPaths;
/// <summary>
- /// Gets the logger.
+ /// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
- private ILogger Logger { get; set; }
+ private readonly ILogger _logger;
/// <summary>
- /// Gets the task manager.
+ /// Gets or sets the task manager.
/// </summary>
/// <value>The task manager.</value>
- private ITaskManager TaskManager { get; set; }
- private readonly IFileSystem _fileSystem;
+ private readonly ITaskManager _taskManager;
+
+ /// <summary>
+ /// The _last execution result sync lock.
+ /// </summary>
+ private readonly object _lastExecutionResultSyncLock = new object();
+
+ private bool _readFromFile = false;
+
+ /// <summary>
+ /// The _last execution result.
+ /// </summary>
+ private TaskResult _lastExecutionResult;
+
+ private Task _currentTask;
+
+ /// <summary>
+ /// The _triggers.
+ /// </summary>
+ private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
+
+ /// <summary>
+ /// The _id.
+ /// </summary>
+ private string _id;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
@@ -59,7 +77,6 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="scheduledTask">The scheduled task.</param>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="taskManager">The task manager.</param>
- /// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">
/// scheduledTask
@@ -70,50 +87,46 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// or
/// jsonSerializer
/// or
- /// logger
+ /// logger.
/// </exception>
- public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem)
+ public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
{
if (scheduledTask == null)
{
throw new ArgumentNullException(nameof(scheduledTask));
}
+
if (applicationPaths == null)
{
throw new ArgumentNullException(nameof(applicationPaths));
}
+
if (taskManager == null)
{
throw new ArgumentNullException(nameof(taskManager));
}
- if (jsonSerializer == null)
- {
- throw new ArgumentNullException(nameof(jsonSerializer));
- }
+
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
ScheduledTask = scheduledTask;
- ApplicationPaths = applicationPaths;
- TaskManager = taskManager;
- JsonSerializer = jsonSerializer;
- Logger = logger;
- _fileSystem = fileSystem;
+ _applicationPaths = applicationPaths;
+ _taskManager = taskManager;
+ _logger = logger;
InitTriggerEvents();
}
- private bool _readFromFile = false;
- /// <summary>
- /// The _last execution result
- /// </summary>
- private TaskResult _lastExecutionResult;
+ public event EventHandler<GenericEventArgs<double>> TaskProgress;
+
/// <summary>
- /// The _last execution result sync lock
+ /// Gets the scheduled task.
/// </summary>
- private readonly object _lastExecutionResultSyncLock = new object();
+ /// <value>The scheduled task.</value>
+ public IScheduledTask ScheduledTask { get; private set; }
+
/// <summary>
/// Gets the last execution result.
/// </summary>
@@ -130,21 +143,31 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
if (File.Exists(path))
{
- try
+ var bytes = File.ReadAllBytes(path);
+ if (bytes.Length > 0)
{
- _lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
+ try
+ {
+ _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
+ }
+ catch (JsonException ex)
+ {
+ _logger.LogError(ex, "Error deserializing {File}", path);
+ }
}
- catch (Exception ex)
+ else
{
- Logger.LogError(ex, "Error deserializing {File}", path);
+ _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
}
}
+
_readFromFile = true;
}
}
return _lastExecutionResult;
}
+
private set
{
_lastExecutionResult = value;
@@ -154,7 +177,9 @@ namespace Emby.Server.Implementations.ScheduledTasks
lock (_lastExecutionResultSyncLock)
{
- JsonSerializer.SerializeToFile(value, path);
+ using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
+ using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
+ JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
}
}
}
@@ -178,7 +203,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
public string Category => ScheduledTask.Category;
/// <summary>
- /// Gets the current cancellation token
+ /// Gets or sets the current cancellation token.
/// </summary>
/// <value>The current cancellation token source.</value>
private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
@@ -215,11 +240,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
public double? CurrentProgress { get; private set; }
/// <summary>
- /// The _triggers
- /// </summary>
- private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
- /// <summary>
- /// Gets the triggers that define when the task will run
+ /// Gets or sets the triggers that define when the task will run.
/// </summary>
/// <value>The triggers.</value>
private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
@@ -245,10 +266,10 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Gets the triggers that define when the task will run
+ /// Gets or sets the triggers that define when the task will run.
/// </summary>
/// <value>The triggers.</value>
- /// <exception cref="ArgumentNullException">value</exception>
+ /// <exception cref="ArgumentNullException"><c>value</c> is <c>null</c>.</exception>
public TaskTriggerInfo[] Triggers
{
get
@@ -256,6 +277,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var triggers = InternalTriggers;
return triggers.Select(i => i.Item1).ToArray();
}
+
set
{
if (value == null)
@@ -273,11 +295,6 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// The _id
- /// </summary>
- private string _id;
-
- /// <summary>
/// Gets the unique id.
/// </summary>
/// <value>The unique id.</value>
@@ -285,12 +302,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
get
{
- if (_id == null)
- {
- _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N");
- }
-
- return _id;
+ return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
}
@@ -317,9 +329,9 @@ namespace Emby.Server.Implementations.ScheduledTasks
trigger.Stop();
- trigger.Triggered -= trigger_Triggered;
- trigger.Triggered += trigger_Triggered;
- trigger.Start(LastExecutionResult, Logger, Name, isApplicationStartup);
+ trigger.Triggered -= OnTriggerTriggered;
+ trigger.Triggered += OnTriggerTriggered;
+ trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
}
}
@@ -328,36 +340,32 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
- async void trigger_Triggered(object sender, EventArgs e)
+ private async void OnTriggerTriggered(object sender, EventArgs e)
{
var trigger = (ITaskTrigger)sender;
- var configurableTask = ScheduledTask as IConfigurableScheduledTask;
-
- if (configurableTask != null && !configurableTask.IsEnabled)
+ if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
{
return;
}
- Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
+ _logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
trigger.Stop();
- TaskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
+ _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
await Task.Delay(1000).ConfigureAwait(false);
- trigger.Start(LastExecutionResult, Logger, Name, false);
+ trigger.Start(LastExecutionResult, _logger, Name, false);
}
- private Task _currentTask;
-
/// <summary>
- /// Executes the task
+ /// 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>
+ /// <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));
@@ -387,11 +395,11 @@ namespace Emby.Server.Implementations.ScheduledTasks
CurrentCancellationTokenSource = new CancellationTokenSource();
- Logger.LogInformation("Executing {0}", Name);
+ _logger.LogInformation("Executing {0}", Name);
- ((TaskManager)TaskManager).OnTaskExecuting(this);
+ ((TaskManager)_taskManager).OnTaskExecuting(this);
- progress.ProgressChanged += progress_ProgressChanged;
+ progress.ProgressChanged += OnProgressChanged;
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
@@ -415,7 +423,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error");
+ _logger.LogError(ex, "Error");
failureException = ex;
@@ -425,7 +433,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var startTime = CurrentExecutionStartTime;
var endTime = DateTime.UtcNow;
- progress.ProgressChanged -= progress_ProgressChanged;
+ progress.ProgressChanged -= OnProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
@@ -438,20 +446,17 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
- void progress_ProgressChanged(object sender, double e)
+ private void OnProgressChanged(object sender, double e)
{
e = Math.Min(e, 100);
CurrentProgress = e;
- TaskProgress?.Invoke(this, new GenericEventArgs<double>
- {
- Argument = e
- });
+ TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
}
/// <summary>
- /// Stops the task if it is currently executing
+ /// 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()
@@ -471,7 +476,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
if (State == TaskState.Running)
{
- Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
+ _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
CurrentCancellationTokenSource.Cancel();
}
}
@@ -482,7 +487,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <returns>System.String.</returns>
private string GetScheduledTasksConfigurationDirectory()
{
- return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
+ return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
}
/// <summary>
@@ -491,7 +496,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <returns>System.String.</returns>
private string GetScheduledTasksDataDirectory()
{
- return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
+ return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
}
/// <summary>
@@ -530,7 +535,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
TaskTriggerInfo[] list = null;
if (File.Exists(path))
{
- list = JsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path);
+ var bytes = File.ReadAllBytes(path);
+ list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
}
// Return defaults if file doesn't exist.
@@ -565,8 +571,9 @@ namespace Emby.Server.Implementations.ScheduledTasks
var path = GetConfigurationFilePath();
Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- JsonSerializer.SerializeToFile(triggers, path);
+ using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
+ using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
+ JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
}
/// <summary>
@@ -575,11 +582,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <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;
- Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
+ _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
var result = new TaskResult
{
@@ -600,7 +608,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
LastExecutionResult = result;
- ((TaskManager)TaskManager).OnTaskCompleted(this, result);
+ ((TaskManager)_taskManager).OnTaskCompleted(this, result);
}
/// <summary>
@@ -609,6 +617,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
@@ -629,34 +638,35 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
try
{
- Logger.LogInformation(Name + ": Cancelling");
+ _logger.LogInformation(Name + ": Cancelling");
token.Cancel();
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error calling CancellationToken.Cancel();");
+ _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
}
}
+
var task = _currentTask;
if (task != null)
{
try
{
- Logger.LogInformation(Name + ": Waiting on Task");
- var exited = Task.WaitAll(new[] { task }, 2000);
+ _logger.LogInformation(Name + ": Waiting on Task");
+ var exited = task.Wait(2000);
if (exited)
{
- Logger.LogInformation(Name + ": Task exited");
+ _logger.LogInformation(Name + ": Task exited");
}
else
{
- Logger.LogInformation(Name + ": Timed out waiting for task to stop");
+ _logger.LogInformation(Name + ": Timed out waiting for task to stop");
}
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error calling Task.WaitAll();");
+ _logger.LogError(ex, "Error calling Task.WaitAll();");
}
}
@@ -664,14 +674,15 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
try
{
- Logger.LogDebug(Name + ": Disposing CancellationToken");
+ _logger.LogDebug(Name + ": Disposing CancellationToken");
token.Dispose();
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error calling CancellationToken.Dispose();");
+ _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
}
}
+
if (wassRunning)
{
OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
@@ -680,12 +691,11 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger
+ /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>BaseTaskTrigger.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- /// <exception cref="ArgumentException">Invalid trigger type: + info.Type</exception>
+ /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
private ITaskTrigger GetTrigger(TaskTriggerInfo info)
{
var options = new TaskOptions
@@ -693,21 +703,17 @@ namespace Emby.Server.Implementations.ScheduledTasks
MaxRuntimeTicks = info.MaxRuntimeTicks
};
- if (info.Type.Equals(typeof(DailyTrigger).Name, StringComparison.OrdinalIgnoreCase))
+ if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
{
if (!info.TimeOfDayTicks.HasValue)
{
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
}
- return new DailyTrigger
- {
- TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
- TaskOptions = options
- };
+ return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
}
- if (info.Type.Equals(typeof(WeeklyTrigger).Name, StringComparison.OrdinalIgnoreCase))
+ if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
{
if (!info.TimeOfDayTicks.HasValue)
{
@@ -719,45 +725,36 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
}
- return new WeeklyTrigger
- {
- TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
- DayOfWeek = info.DayOfWeek.Value,
- TaskOptions = options
- };
+ return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
}
- if (info.Type.Equals(typeof(IntervalTrigger).Name, StringComparison.OrdinalIgnoreCase))
+ if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
{
if (!info.IntervalTicks.HasValue)
{
throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
}
- return new IntervalTrigger
- {
- Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
- TaskOptions = options
- };
+ return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
}
- if (info.Type.Equals(typeof(StartupTrigger).Name, StringComparison.OrdinalIgnoreCase))
+ if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
{
- return new StartupTrigger();
+ return new StartupTrigger(options);
}
throw new ArgumentException("Unrecognized trigger type: " + info.Type);
}
/// <summary>
- /// Disposes each trigger
+ /// Disposes each trigger.
/// </summary>
private void DisposeTriggers()
{
foreach (var triggerInfo in InternalTriggers)
{
var trigger = triggerInfo.Item2;
- trigger.Triggered -= trigger_Triggered;
+ trigger.Triggered -= OnTriggerTriggered;
trigger.Stop();
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
index 595c3037d..0431858fc 100644
--- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
@@ -1,84 +1,65 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class TaskManager
+ /// Class TaskManager.
/// </summary>
public class TaskManager : ITaskManager
{
- public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
- public event EventHandler<TaskCompletionEventArgs> TaskCompleted;
-
- /// <summary>
- /// Gets the list of Scheduled Tasks
- /// </summary>
- /// <value>The scheduled tasks.</value>
- public IScheduledTaskWorker[] ScheduledTasks { get; private set; }
-
/// <summary>
- /// The _task queue
+ /// The _task queue.
/// </summary>
private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
new ConcurrentQueue<Tuple<Type, TaskOptions>>();
- /// <summary>
- /// Gets or sets the json serializer.
- /// </summary>
- /// <value>The json serializer.</value>
- private IJsonSerializer JsonSerializer { get; set; }
-
- /// <summary>
- /// Gets or sets the application paths.
- /// </summary>
- /// <value>The application paths.</value>
- private IApplicationPaths ApplicationPaths { get; set; }
-
- /// <summary>
- /// Gets the logger.
- /// </summary>
- /// <value>The logger.</value>
- private ILogger Logger { get; set; }
- private readonly IFileSystem _fileSystem;
+ 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="jsonSerializer">The json serializer.</param>
- /// <param name="loggerFactory">The logger factory.</param>
- /// <exception cref="System.ArgumentException">kernel</exception>
+ /// <param name="logger">The logger.</param>
public TaskManager(
IApplicationPaths applicationPaths,
- IJsonSerializer jsonSerializer,
- ILoggerFactory loggerFactory,
- IFileSystem fileSystem)
+ ILogger<TaskManager> logger)
{
- ApplicationPaths = applicationPaths;
- JsonSerializer = jsonSerializer;
- Logger = loggerFactory.CreateLogger(nameof(TaskManager));
- _fileSystem = fileSystem;
+ _applicationPaths = applicationPaths;
+ _logger = logger;
- ScheduledTasks = new IScheduledTaskWorker[] { };
+ ScheduledTasks = Array.Empty<IScheduledTaskWorker>();
}
+ public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
+
+ public event EventHandler<TaskCompletionEventArgs> TaskCompleted;
+
+ /// <summary>
+ /// Gets the list of Scheduled Tasks.
+ /// </summary>
+ /// <value>The scheduled tasks.</value>
+ public IScheduledTaskWorker[] ScheduledTasks { get; private set; }
+
/// <summary>
/// Cancels if running and queue.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The task type.</typeparam>
/// <param name="options">Task options.</param>
public void CancelIfRunningAndQueue<T>(TaskOptions options)
- where T : IScheduledTask
+ where T : IScheduledTask
{
var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
((ScheduledTaskWorker)task).CancelIfRunning();
@@ -93,9 +74,9 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Cancels if running
+ /// Cancels if running.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The task type.</typeparam>
public void CancelIfRunning<T>()
where T : IScheduledTask
{
@@ -106,8 +87,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary>
/// Queues the scheduled task.
/// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="options">Task options</param>
+ /// <typeparam name="T">The task type.</typeparam>
+ /// <param name="options">Task options.</param>
public void QueueScheduledTask<T>(TaskOptions options)
where T : IScheduledTask
{
@@ -115,7 +96,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
+ _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
}
else
{
@@ -147,13 +128,13 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
+ _logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
}
else
{
var type = scheduledTask.ScheduledTask.GetType();
- Logger.LogInformation("Queueing task {0}", type.Name);
+ _logger.LogInformation("Queuing task {0}", type.Name);
lock (_taskQueue)
{
@@ -176,7 +157,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
+ _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
}
else
{
@@ -193,7 +174,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
var type = task.ScheduledTask.GetType();
- Logger.LogInformation("Queueing task {0}", type.Name);
+ _logger.LogInformation("Queuing task {0}", type.Name);
lock (_taskQueue)
{
@@ -213,7 +194,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="tasks">The tasks.</param>
public void AddTasks(IEnumerable<IScheduledTask> tasks)
{
- var list = tasks.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem));
+ var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _logger));
ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
}
@@ -224,6 +205,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
@@ -254,10 +236,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="task">The task.</param>
internal void OnTaskExecuting(IScheduledTaskWorker task)
{
- TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
- {
- Argument = task
- });
+ TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
}
/// <summary>
@@ -267,11 +246,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="result">The result.</param>
internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
{
- TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
- {
- Result = result,
- Task = task
- });
+ TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
ExecuteQueuedTasks();
}
@@ -281,7 +256,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void ExecuteQueuedTasks()
{
- Logger.LogInformation("ExecuteQueuedTasks");
+ _logger.LogInformation("ExecuteQueuedTasks");
// Execute queued tasks
lock (_taskQueue)
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
index 2f07ff15a..09ea6271d 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
@@ -12,23 +12,19 @@ using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
-using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class ChapterImagesTask
+ /// Class ChapterImagesTask.
/// </summary>
public class ChapterImagesTask : IScheduledTask
{
/// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
- /// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
@@ -38,27 +34,50 @@ namespace Emby.Server.Implementations.ScheduledTasks
private readonly IEncodingManager _encodingManager;
private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
/// </summary>
- public ChapterImagesTask(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem)
+ /// <param name="libraryManager">The library manager.</param>.
+ /// <param name="itemRepo">The item repository.</param>
+ /// <param name="appPaths">The application paths.</param>
+ /// <param name="encodingManager">The encoding manager.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="localization">The localization manager.</param>
+ public ChapterImagesTask(
+ ILibraryManager libraryManager,
+ IItemRepository itemRepo,
+ IApplicationPaths appPaths,
+ IEncodingManager encodingManager,
+ IFileSystem fileSystem,
+ ILocalizationManager localization)
{
- _logger = loggerFactory.CreateLogger(GetType().Name);
_libraryManager = libraryManager;
_itemRepo = itemRepo;
_appPaths = appPaths;
_encodingManager = encodingManager;
_fileSystem = fileSystem;
+ _localization = localization;
}
- /// <summary>
- /// Creates the triggers that define when the task will run
- /// </summary>
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskRefreshChapterImages");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskRefreshChapterImagesDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+
+ /// <inheritdoc />
+ public string Key => "RefreshChapterImages";
+
+ /// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
+ return new[]
+ {
new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerDaily,
@@ -69,7 +88,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Returns the task to be executed
+ /// Returns the task to be executed.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
@@ -88,7 +107,6 @@ namespace Emby.Server.Implementations.ScheduledTasks
SourceTypes = new SourceType[] { SourceType.Library },
HasChapterImages = false,
IsVirtualItem = false
-
})
.OfType<Video>()
.ToList();
@@ -104,7 +122,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
try
{
previouslyFailedImages = File.ReadAllText(failHistoryPath)
- .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
+ .Split('|', StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
catch (IOException)
@@ -117,7 +135,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
previouslyFailedImages = new List<string>();
}
- var directoryService = new DirectoryService(_logger, _fileSystem);
+ var directoryService = new DirectoryService(_fileSystem);
foreach (var video in videos)
{
@@ -138,10 +156,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
previouslyFailedImages.Add(key);
var parentPath = Path.GetDirectoryName(failHistoryPath);
+ if (parentPath != null)
+ {
+ Directory.CreateDirectory(parentPath);
+ }
- Directory.CreateDirectory(parentPath);
-
- string text = string.Join("|", previouslyFailedImages);
+ string text = string.Join('|', previouslyFailedImages);
File.WriteAllText(failHistoryPath, text);
}
@@ -153,24 +173,10 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
catch (ObjectDisposedException)
{
- //TODO Investigate and properly fix.
+ // TODO Investigate and properly fix.
break;
}
}
}
-
- public string Name => "Chapter image extraction";
-
- public string Description => "Creates thumbnails for videos that have chapters.";
-
- public string Category => "Library";
-
- public string Key => "RefreshChapterImages";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs
new file mode 100644
index 000000000..79886cb52
--- /dev/null
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.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>
+ /// 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;
+ }
+
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanActivityLog");
+
+ /// <inheritdoc />
+ public string Key => "CleanActivityLog";
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanActivityLogDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
+ /// <inheritdoc />
+ public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
+ {
+ var retentionDays = _serverConfigurationManager.Configuration.ActivityLogRetentionDays;
+ if (!retentionDays.HasValue || retentionDays < 0)
+ {
+ throw new Exception($"Activity Log Retention days must be at least 0. Currently: {retentionDays}");
+ }
+
+ var startDate = DateTime.UtcNow.AddDays(-retentionDays.Value);
+ return _activityManager.CleanAsync(startDate);
+ }
+
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ return Enumerable.Empty<TaskTriggerInfo>();
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
index 6ec83b5c0..a575b260c 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@@ -12,7 +13,7 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{
/// <summary>
- /// Deletes old cache files
+ /// Deletes old cache files.
/// </summary>
public class DeleteCacheFileTask : IScheduledTask, IConfigurableScheduledTask
{
@@ -20,37 +21,66 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
- private IApplicationPaths ApplicationPaths { get; set; }
-
- private readonly ILogger _logger;
-
+ 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 DeleteCacheFileTask(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
+ /// <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;
+ _applicationPaths = appPaths;
_logger = logger;
_fileSystem = fileSystem;
+ _localization = localization;
}
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanCache");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+
+ /// <inheritdoc />
+ public string Key => "DeleteCacheFiles";
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
/// <summary>
- /// Creates the triggers that define when the task will run
+ /// Creates the triggers that define when the task will run.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
+ return new[]
+ {
// Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
};
}
/// <summary>
- /// Returns the task to be executed
+ /// Returns the task to be executed.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
@@ -61,7 +91,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
try
{
- DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.CachePath, minDateModified, progress);
+ DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.CachePath, minDateModified, progress);
}
catch (DirectoryNotFoundException)
{
@@ -74,7 +104,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
try
{
- DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.TempDirectory, minDateModified, progress);
+ DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.TempDirectory, minDateModified, progress);
}
catch (DirectoryNotFoundException)
{
@@ -84,9 +114,8 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
return Task.CompletedTask;
}
-
/// <summary>
- /// Deletes the cache files from directory with a last write time less than a given date
+ /// Deletes the cache files from directory with a last write time less than a given date.
/// </summary>
/// <param name="cancellationToken">The task cancellation token.</param>
/// <param name="directory">The directory.</param>
@@ -157,19 +186,5 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
_logger.LogError(ex, "Error deleting file {path}", path);
}
}
-
- public string Name => "Cache file cleanup";
-
- public string Description => "Deletes cache files no longer needed by the system";
-
- public string Category => "Maintenance";
-
- public string Key => "DeleteCacheFiles";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
index e468c301a..fedb5deb0 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
@@ -1,52 +1,76 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{
/// <summary>
- /// Deletes old log files
+ /// Deletes old log files.
/// </summary>
public class DeleteLogFileTask : IScheduledTask, IConfigurableScheduledTask
{
- /// <summary>
- /// Gets or sets the configuration manager.
- /// </summary>
- /// <value>The configuration manager.</value>
- private IConfigurationManager ConfigurationManager { get; set; }
-
+ 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">The configuration manager.</param>
- public DeleteLogFileTask(IConfigurationManager configurationManager, IFileSystem fileSystem)
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="localization">The localization manager.</param>
+ public DeleteLogFileTask(IConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization)
{
- ConfigurationManager = configurationManager;
+ _configurationManager = configurationManager;
_fileSystem = fileSystem;
+ _localization = localization;
}
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanLogs");
+
+ /// <inheritdoc />
+ public string Description => string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("TaskCleanLogsDescription"),
+ _configurationManager.CommonConfiguration.LogFileRetentionDays);
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+
+ /// <inheritdoc />
+ public string Key => "CleanLogFiles";
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
/// <summary>
- /// Creates the triggers that define when the task will run
+ /// Creates the triggers that define when the task will run.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ return new[]
+ {
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
};
}
/// <summary>
- /// Returns the task to be executed
+ /// Returns the task to be executed.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
@@ -54,12 +78,13 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
// Delete log files more than n days old
- var minDateModified = DateTime.UtcNow.AddDays(-ConfigurationManager.CommonConfiguration.LogFileRetentionDays);
+ var minDateModified = DateTime.UtcNow.AddDays(-_configurationManager.CommonConfiguration.LogFileRetentionDays);
- // Only delete the .txt log files, the *.log files created by serilog get managed by itself
- var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, new[] { ".txt" }, true, true)
- .Where(f => _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;
@@ -80,19 +105,5 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
return Task.CompletedTask;
}
-
- public string Name => "Log file cleanup";
-
- public string Description => string.Format("Deletes log files that are more than {0} days old.", ConfigurationManager.CommonConfiguration.LogFileRetentionDays);
-
- public string Category => "Maintenance";
-
- public string Key => "CleanLogFiles";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs
new file mode 100644
index 000000000..b13fc7fc6
--- /dev/null
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs
@@ -0,0 +1,170 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Tasks;
+using Microsoft.Extensions.Logging;
+
+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>
+ /// 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;
+ }
+
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanTranscode");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+
+ /// <inheritdoc />
+ public string Key => "DeleteTranscodeFiles";
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
+ /// <summary>
+ /// Creates the triggers that define when the task will run.
+ /// </summary>
+ /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ return new[]
+ {
+ new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfo.TriggerInterval,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ }
+ };
+ }
+
+ /// <summary>
+ /// Returns the task to be executed.
+ /// </summary>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <param name="progress">The progress.</param>
+ /// <returns>Task.</returns>
+ public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
+ {
+ var minDateModified = DateTime.UtcNow.AddDays(-1);
+ progress.Report(50);
+
+ DeleteTempFilesFromDirectory(cancellationToken, _configurationManager.GetTranscodePath(), minDateModified, progress);
+
+ return Task.CompletedTask;
+ }
+
+ /// <summary>
+ /// Deletes the transcoded temp files from directory with a last write time less than a given date.
+ /// </summary>
+ /// <param name="cancellationToken">The task cancellation token.</param>
+ /// <param name="directory">The directory.</param>
+ /// <param name="minDateModified">The min date modified.</param>
+ /// <param name="progress">The progress.</param>
+ private void DeleteTempFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
+ {
+ var filesToDelete = _fileSystem.GetFiles(directory, true)
+ .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
+ .ToList();
+
+ var index = 0;
+
+ foreach (var file in filesToDelete)
+ {
+ double percent = index;
+ percent /= filesToDelete.Count;
+
+ progress.Report(100 * percent);
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ DeleteFile(file.FullName);
+
+ index++;
+ }
+
+ DeleteEmptyFolders(directory);
+
+ progress.Report(100);
+ }
+
+ private void DeleteEmptyFolders(string parent)
+ {
+ foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
+ {
+ DeleteEmptyFolders(directory);
+ if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
+ {
+ try
+ {
+ Directory.Delete(directory, false);
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ _logger.LogError(ex, "Error deleting directory {path}", directory);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting directory {path}", directory);
+ }
+ }
+ }
+ }
+
+ private void DeleteFile(string path)
+ {
+ try
+ {
+ _fileSystem.DeleteFile(path);
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ _logger.LogError(ex, "Error deleting file {path}", path);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting file {path}", path);
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs
new file mode 100644
index 000000000..35a4aeef6
--- /dev/null
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs
@@ -0,0 +1,104 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Server.Implementations;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+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 JellyfinDbProvider _provider;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OptimizeDatabaseTask" /> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="localization">The localization manager.</param>
+ /// <param name="provider">The jellyfin DB context provider.</param>
+ public OptimizeDatabaseTask(
+ ILogger<OptimizeDatabaseTask> logger,
+ ILocalizationManager localization,
+ JellyfinDbProvider provider)
+ {
+ _logger = logger;
+ _localization = localization;
+ _provider = provider;
+ }
+
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskOptimizeDatabase");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskOptimizeDatabaseDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+
+ /// <inheritdoc />
+ public string Key => "OptimizeDatabaseTask";
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
+ /// <summary>
+ /// Creates the triggers that define when the task will run.
+ /// </summary>
+ /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ return new[]
+ {
+ // Every so often
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
+ };
+ }
+
+ /// <summary>
+ /// Returns the task to be executed.
+ /// </summary>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <param name="progress">The progress.</param>
+ /// <returns>Task.</returns>
+ public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
+ {
+ _logger.LogInformation("Optimizing and vacuuming jellyfin.db...");
+
+ try
+ {
+ using var context = _provider.CreateContext();
+ if (context.Database.IsSqlite())
+ {
+ context.Database.ExecuteSqlRaw("PRAGMA optimize");
+ context.Database.ExecuteSqlRaw("VACUUM");
+ _logger.LogInformation("jellyfin.db optimized successfully!");
+ }
+ else
+ {
+ _logger.LogInformation("This database doesn't support optimization");
+ }
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Error while optimizing jellyfin.db");
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
index d70799c47..53c692a46 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
@@ -1,44 +1,59 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class PeopleValidationTask
+ /// Class PeopleValidationTask.
/// </summary>
public class PeopleValidationTask : IScheduledTask
{
/// <summary>
- /// The _library manager
+ /// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
-
- private readonly IServerApplicationHost _appHost;
+ private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="PeopleValidationTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
- /// <param name="appHost">The server application host</param>
- public PeopleValidationTask(ILibraryManager libraryManager, IServerApplicationHost appHost)
+ /// <param name="localization">The localization manager.</param>
+ public PeopleValidationTask(ILibraryManager libraryManager, ILocalizationManager localization)
{
_libraryManager = libraryManager;
- _appHost = appHost;
+ _localization = localization;
}
+ public string Name => _localization.GetLocalizedString("TaskRefreshPeople");
+
+ public string Description => _localization.GetLocalizedString("TaskRefreshPeopleDescription");
+
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+
+ public string Key => "RefreshPeople";
+
+ public bool IsHidden => false;
+
+ public bool IsEnabled => true;
+
+ public bool IsLogged => true;
+
/// <summary>
- /// Creates the triggers that define when the task will run
+ /// 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()
{
return new[]
{
- // Every so often
new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerInterval,
@@ -48,7 +63,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Returns the task to be executed
+ /// Returns the task to be executed.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
@@ -57,19 +72,5 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
return _libraryManager.ValidatePeople(cancellationToken, progress);
}
-
- public string Name => "Refresh people";
-
- public string Description => "Updates metadata for actors and directors in your media library.";
-
- public string Category => "Library";
-
- public string Key => "RefreshPeople";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
index c6431c311..11a5fb79f 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
@@ -1,66 +1,85 @@
-using MediaBrowser.Common;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Model.Net;
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Plugin Update Task
+ /// Plugin Update Task.
/// </summary>
public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask
{
/// <summary>
- /// The _logger
+ /// The _logger.
/// </summary>
- private readonly ILogger _logger;
+ private readonly ILogger<PluginUpdateTask> _logger;
private readonly IInstallationManager _installationManager;
+ private readonly ILocalizationManager _localization;
- private readonly IApplicationHost _appHost;
-
- public PluginUpdateTask(ILogger logger, IInstallationManager installationManager, IApplicationHost appHost)
+ public PluginUpdateTask(ILogger<PluginUpdateTask> logger, IInstallationManager installationManager, ILocalizationManager localization)
{
_logger = logger;
_installationManager = installationManager;
- _appHost = appHost;
+ _localization = localization;
}
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskUpdatePlugins");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskUpdatePluginsDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksApplicationCategory");
+
+ /// <inheritdoc />
+ public string Key => "PluginUpdates";
+
+ /// <inheritdoc />
+ public bool IsHidden => false;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
/// <summary>
- /// Creates the triggers that define when the task will run
+ /// Creates the triggers that define when the task will run.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
- // At startup
- new TaskTriggerInfo {Type = TaskTriggerInfo.TriggerStartup},
-
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
- };
+ // At startup
+ yield return new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerStartup };
+
+ // Every so often
+ yield return new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks };
}
/// <summary>
- /// Update installed plugins
+ /// Update installed plugins.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
- /// <returns>Task.</returns>
+ /// <returns><see cref="Task" />.</returns>
public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
progress.Report(0);
- var packagesToInstall = (await _installationManager.GetAvailablePluginUpdates(typeof(PluginUpdateTask).Assembly.GetName().Version, true, cancellationToken).ConfigureAwait(false)).ToList();
+ var packageFetchTask = _installationManager.GetAvailablePluginUpdates(cancellationToken);
+ var packagesToInstall = (await packageFetchTask.ConfigureAwait(false)).ToList();
progress.Report(10);
@@ -72,7 +91,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
try
{
- await _installationManager.InstallPackage(package, true, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
+ await _installationManager.InstallPackage(package, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -82,38 +101,23 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw;
}
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
- _logger.LogError(ex, "Error downloading {0}", package.name);
+ _logger.LogError(ex, "Error downloading {0}", package.Name);
}
catch (IOException ex)
{
- _logger.LogError(ex, "Error updating {0}", package.name);
+ _logger.LogError(ex, "Error updating {0}", package.Name);
}
// Update progress
lock (progress)
{
- numComplete++;
- progress.Report(90.0 * numComplete / packagesToInstall.Count + 10);
+ progress.Report((90.0 * ++numComplete / packagesToInstall.Count) + 10);
}
}
progress.Report(100);
}
-
- public string Name => "Check for plugin updates";
-
- public string Description => "Downloads and installs updates for plugins that are configured to update automatically.";
-
- public string Category => "Application";
-
- public string Key => "PluginUpdates";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
index 1a3d85ad7..2184b3d03 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
@@ -1,45 +1,60 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Library;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class RefreshMediaLibraryTask
+ /// Class RefreshMediaLibraryTask.
/// </summary>
public class RefreshMediaLibraryTask : IScheduledTask
{
/// <summary>
- /// The _library manager
+ /// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
- private readonly IServerConfigurationManager _config;
+ private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="RefreshMediaLibraryTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
- public RefreshMediaLibraryTask(ILibraryManager libraryManager, IServerConfigurationManager config)
+ /// <param name="localization">The localization manager.</param>
+ public RefreshMediaLibraryTask(ILibraryManager libraryManager, ILocalizationManager localization)
{
_libraryManager = libraryManager;
- _config = config;
+ _localization = localization;
}
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskRefreshLibrary");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskRefreshLibraryDescription");
+
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+
+ /// <inheritdoc />
+ public string Key => "RefreshLibrary";
+
/// <summary>
- /// Creates the triggers that define when the task will run
+ /// Creates the triggers that define when the task will run.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(12).Ticks}
+ yield return new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfo.TriggerInterval,
+ IntervalTicks = TimeSpan.FromHours(12).Ticks
};
}
@@ -57,19 +72,5 @@ namespace Emby.Server.Implementations.ScheduledTasks
return ((LibraryManager)_libraryManager).ValidateMediaLibraryInternal(progress, cancellationToken);
}
-
- public string Name => "Scan media library";
-
- public string Description => "Scans your media library and refreshes metatata based on configuration.";
-
- public string Category => "Library";
-
- public string Key => "RefreshLibrary";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
index 98685cebe..29ab6a73d 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
@@ -1,5 +1,4 @@
using System;
-using System.Globalization;
using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@@ -7,31 +6,40 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Represents a task trigger that fires everyday
+ /// Represents a task trigger that fires everyday.
/// </summary>
- public class DailyTrigger : ITaskTrigger
+ public sealed class DailyTrigger : ITaskTrigger
{
+ private readonly TimeSpan _timeOfDay;
+ private Timer? _timer;
+
/// <summary>
- /// Get the time of day to trigger the task to run
+ /// Initializes a new instance of the <see cref="DailyTrigger"/> class.
/// </summary>
- /// <value>The time of day.</value>
- public TimeSpan TimeOfDay { get; set; }
+ /// <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;
+ }
/// <summary>
- /// Gets or sets the options of this task.
+ /// Occurs when [triggered].
/// </summary>
- public TaskOptions TaskOptions { get; set; }
+ public event EventHandler<EventArgs>? Triggered;
/// <summary>
- /// Gets or sets the timer.
+ /// Gets the options of this task.
/// </summary>
- /// <value>The timer.</value>
- private Timer Timer { get; set; }
+ public TaskOptions TaskOptions { get; }
/// <summary>
- /// Stars waiting for the trigger action
+ /// Stars waiting for the trigger action.
/// </summary>
/// <param name="lastResult">The last result.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
@@ -39,18 +47,18 @@ namespace Emby.Server.Implementations.ScheduledTasks
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;
- logger.LogInformation("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ 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(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
+ _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
/// <summary>
- /// Stops waiting for the trigger action
+ /// Stops waiting for the trigger action.
/// </summary>
public void Stop()
{
@@ -62,26 +70,15 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void DisposeTimer()
{
- if (Timer != null)
- {
- Timer.Dispose();
- }
+ _timer?.Dispose();
}
/// <summary>
- /// Occurs when [triggered].
- /// </summary>
- public event EventHandler<EventArgs> Triggered;
-
- /// <summary>
/// Called when [triggered].
/// </summary>
private void OnTriggered()
{
- if (Triggered != null)
- {
- Triggered(this, EventArgs.Empty);
- }
+ Triggered?.Invoke(this, EventArgs.Empty);
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
index 3a34da3af..30568e809 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
@@ -7,33 +7,41 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Represents a task trigger that runs repeatedly on an interval
+ /// Represents a task trigger that runs repeatedly on an interval.
/// </summary>
- public class IntervalTrigger : ITaskTrigger
+ public sealed class IntervalTrigger : ITaskTrigger
{
+ private readonly TimeSpan _interval;
+ private DateTime _lastStartDate;
+ private Timer? _timer;
+
/// <summary>
- /// Gets or sets the interval.
+ /// Initializes a new instance of the <see cref="IntervalTrigger"/> class.
/// </summary>
- /// <value>The interval.</value>
- public TimeSpan Interval { get; set; }
+ /// <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;
+ }
/// <summary>
- /// Gets or sets the options of this task.
+ /// Occurs when [triggered].
/// </summary>
- public TaskOptions TaskOptions { get; set; }
+ public event EventHandler<EventArgs>? Triggered;
/// <summary>
- /// Gets or sets the timer.
+ /// Gets the options of this task.
/// </summary>
- /// <value>The timer.</value>
- private Timer Timer { get; set; }
-
- private DateTime _lastStartDate;
+ public TaskOptions TaskOptions { get; }
/// <summary>
- /// Stars waiting for the trigger action
+ /// Stars waiting for the trigger action.
/// </summary>
/// <param name="lastResult">The last result.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
@@ -48,7 +56,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
else
{
- triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(Interval);
+ triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(_interval);
}
if (DateTime.UtcNow > triggerDate)
@@ -64,11 +72,11 @@ namespace Emby.Server.Implementations.ScheduledTasks
dueTime = maxDueTime;
}
- Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
+ _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
/// <summary>
- /// Stops waiting for the trigger action
+ /// Stops waiting for the trigger action.
/// </summary>
public void Stop()
{
@@ -80,18 +88,10 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void DisposeTimer()
{
- if (Timer != null)
- {
- Timer.Dispose();
- }
+ _timer?.Dispose();
}
/// <summary>
- /// Occurs when [triggered].
- /// </summary>
- public event EventHandler<EventArgs> Triggered;
-
- /// <summary>
/// Called when [triggered].
/// </summary>
private void OnTriggered()
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
index 08ff4f55f..18b9a8b75 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading.Tasks;
using MediaBrowser.Model.Tasks;
@@ -6,26 +8,37 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Class StartupTaskTrigger
+ /// Class StartupTaskTrigger.
/// </summary>
- public class StartupTrigger : ITaskTrigger
+ public sealed class StartupTrigger : ITaskTrigger
{
- public int DelayMs { get; set; }
+ public const int DelayMs = 3000;
/// <summary>
- /// Gets or sets the options of this task.
+ /// Initializes a new instance of the <see cref="StartupTrigger"/> class.
/// </summary>
- public TaskOptions TaskOptions { get; set; }
-
- public StartupTrigger()
+ /// <param name="taskOptions">The options of this task.</param>
+ public StartupTrigger(TaskOptions taskOptions)
{
- DelayMs = 3000;
+ TaskOptions = taskOptions;
}
/// <summary>
- /// Stars waiting for the trigger action
+ /// Occurs when [triggered].
+ /// </summary>
+ public event EventHandler<EventArgs>? Triggered;
+
+ /// <summary>
+ /// Gets the options of this task.
+ /// </summary>
+ public TaskOptions TaskOptions { get; }
+
+ /// <summary>
+ /// Stars waiting for the trigger action.
/// </summary>
/// <param name="lastResult">The last result.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public async void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
@@ -38,26 +51,18 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
/// <summary>
- /// Stops waiting for the trigger action
+ /// Stops waiting for the trigger action.
/// </summary>
public void Stop()
{
}
/// <summary>
- /// Occurs when [triggered].
- /// </summary>
- public event EventHandler<EventArgs> Triggered;
-
- /// <summary>
/// Called when [triggered].
/// </summary>
private void OnTriggered()
{
- if (Triggered != null)
- {
- Triggered(this, EventArgs.Empty);
- }
+ Triggered?.Invoke(this, EventArgs.Empty);
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
index 2a6a7b13c..36ae190b0 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
@@ -6,37 +6,43 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
- /// Represents a task trigger that fires on a weekly basis
+ /// Represents a task trigger that fires on a weekly basis.
/// </summary>
- public class WeeklyTrigger : ITaskTrigger
+ public sealed class WeeklyTrigger : ITaskTrigger
{
- /// <summary>
- /// Get the time of day to trigger the task to run
- /// </summary>
- /// <value>The time of day.</value>
- public TimeSpan TimeOfDay { get; set; }
+ private readonly TimeSpan _timeOfDay;
+ private readonly DayOfWeek _dayOfWeek;
+ private Timer? _timer;
/// <summary>
- /// Gets or sets the day of week.
+ /// Initializes a new instance of the <see cref="WeeklyTrigger"/> class.
/// </summary>
- /// <value>The day of week.</value>
- public DayOfWeek DayOfWeek { get; set; }
+ /// <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;
+ }
/// <summary>
- /// Gets or sets the options of this task.
+ /// Occurs when [triggered].
/// </summary>
- public TaskOptions TaskOptions { get; set; }
+ public event EventHandler<EventArgs>? Triggered;
/// <summary>
- /// Gets or sets the timer.
+ /// Gets the options of this task.
/// </summary>
- /// <value>The timer.</value>
- private Timer Timer { get; set; }
+ public TaskOptions TaskOptions { get; }
/// <summary>
- /// Stars waiting for the trigger action
+ /// Stars waiting for the trigger action.
/// </summary>
/// <param name="lastResult">The last result.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
@@ -44,7 +50,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var triggerDate = GetNextTriggerDateTime();
- Timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
+ _timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
}
/// <summary>
@@ -56,26 +62,26 @@ namespace Emby.Server.Implementations.ScheduledTasks
var now = DateTime.Now;
// If it's on the same day
- if (now.DayOfWeek == DayOfWeek)
+ 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);
+ return now.TimeOfDay < _timeOfDay ? now.Date.Add(_timeOfDay) : now.Date.AddDays(7).Add(_timeOfDay);
}
var triggerDate = now.Date;
// Walk the date forward until we get to the trigger day
- while (triggerDate.DayOfWeek != DayOfWeek)
+ while (triggerDate.DayOfWeek != _dayOfWeek)
{
triggerDate = triggerDate.AddDays(1);
}
// Return the trigger date plus the time offset
- return triggerDate.Add(TimeOfDay);
+ return triggerDate.Add(_timeOfDay);
}
/// <summary>
- /// Stops waiting for the trigger action
+ /// Stops waiting for the trigger action.
/// </summary>
public void Stop()
{
@@ -87,26 +93,15 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void DisposeTimer()
{
- if (Timer != null)
- {
- Timer.Dispose();
- }
+ _timer?.Dispose();
}
/// <summary>
- /// Occurs when [triggered].
- /// </summary>
- public event EventHandler<EventArgs> Triggered;
-
- /// <summary>
/// Called when [triggered].
/// </summary>
private void OnTriggered()
{
- if (Triggered != null)
- {
- Triggered(this, EventArgs.Empty);
- }
+ Triggered?.Invoke(this, EventArgs.Empty);
}
}
}
diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs
deleted file mode 100644
index c81a93767..000000000
--- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs
+++ /dev/null
@@ -1,427 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Emby.Server.Implementations.Data;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Model.Devices;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-using SQLitePCL.pretty;
-
-namespace Emby.Server.Implementations.Security
-{
- public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository
- {
- private readonly IServerConfigurationManager _config;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public AuthenticationRepository(ILoggerFactory loggerFactory, IServerConfigurationManager config)
- : base(loggerFactory.CreateLogger(nameof(AuthenticationRepository)))
- {
- _config = config;
- DbFilePath = Path.Combine(config.ApplicationPaths.DataPath, "authentication.db");
- }
-
- public void Initialize()
- {
- using (var connection = CreateConnection())
- {
- RunDefaultInitialization(connection);
-
- var tableNewlyCreated = !TableExists(connection, "Tokens");
-
- string[] queries = {
-
- "create table if not exists Tokens (Id INTEGER PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT NOT NULL, AppName TEXT NOT NULL, AppVersion TEXT NOT NULL, DeviceName TEXT NOT NULL, UserId TEXT, UserName TEXT, IsActive BIT NOT NULL, DateCreated DATETIME NOT NULL, DateLastActivity DATETIME NOT NULL)",
- "create table if not exists Devices (Id TEXT NOT NULL PRIMARY KEY, CustomName TEXT, Capabilities TEXT)",
-
- "drop index if exists idx_AccessTokens",
- "drop index if exists Tokens1",
- "drop index if exists Tokens2",
- "create index if not exists Tokens3 on Tokens (AccessToken, DateLastActivity)",
- "create index if not exists Tokens4 on Tokens (Id, DateLastActivity)",
- "create index if not exists Devices1 on Devices (Id)"
- };
-
- connection.RunQueries(queries);
-
- TryMigrate(connection, tableNewlyCreated);
- }
- }
-
- private void TryMigrate(ManagedConnection connection, bool tableNewlyCreated)
- {
- try
- {
- if (tableNewlyCreated && TableExists(connection, "AccessTokens"))
- {
- connection.RunInTransaction(db =>
- {
- var existingColumnNames = GetColumnNames(db, "AccessTokens");
-
- AddColumn(db, "AccessTokens", "UserName", "TEXT", existingColumnNames);
- AddColumn(db, "AccessTokens", "DateLastActivity", "DATETIME", existingColumnNames);
- AddColumn(db, "AccessTokens", "AppVersion", "TEXT", existingColumnNames);
-
- }, TransactionMode);
-
- connection.RunQueries(new[]
- {
- "update accesstokens set DateLastActivity=DateCreated where DateLastActivity is null",
- "update accesstokens set DeviceName='Unknown' where DeviceName is null",
- "update accesstokens set AppName='Unknown' where AppName is null",
- "update accesstokens set AppVersion='1' where AppVersion is null",
- "INSERT INTO Tokens (AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity) SELECT AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity FROM AccessTokens where deviceid not null and devicename not null and appname not null and isactive=1"
- });
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error migrating authentication database");
- }
- }
-
- public void Create(AuthenticationInfo info)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("insert into Tokens (AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity) values (@AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @UserName, @IsActive, @DateCreated, @DateLastActivity)"))
- {
- statement.TryBind("@AccessToken", info.AccessToken);
-
- statement.TryBind("@DeviceId", info.DeviceId);
- statement.TryBind("@AppName", info.AppName);
- statement.TryBind("@AppVersion", info.AppVersion);
- statement.TryBind("@DeviceName", info.DeviceName);
- statement.TryBind("@UserId", (info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N")));
- statement.TryBind("@UserName", info.UserName);
- statement.TryBind("@IsActive", true);
- statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
- statement.TryBind("@DateLastActivity", info.DateLastActivity.ToDateTimeParamValue());
-
- statement.MoveNext();
- }
-
- }, TransactionMode);
- }
- }
- }
-
- public void Update(AuthenticationInfo info)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("Update Tokens set AccessToken=@AccessToken, DeviceId=@DeviceId, AppName=@AppName, AppVersion=@AppVersion, DeviceName=@DeviceName, UserId=@UserId, UserName=@UserName, DateCreated=@DateCreated, DateLastActivity=@DateLastActivity where Id=@Id"))
- {
- statement.TryBind("@Id", info.Id);
-
- statement.TryBind("@AccessToken", info.AccessToken);
-
- statement.TryBind("@DeviceId", info.DeviceId);
- statement.TryBind("@AppName", info.AppName);
- statement.TryBind("@AppVersion", info.AppVersion);
- statement.TryBind("@DeviceName", info.DeviceName);
- statement.TryBind("@UserId", (info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N")));
- statement.TryBind("@UserName", info.UserName);
- statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
- statement.TryBind("@DateLastActivity", info.DateLastActivity.ToDateTimeParamValue());
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
- }
-
- public void Delete(AuthenticationInfo info)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("Delete from Tokens where Id=@Id"))
- {
- statement.TryBind("@Id", info.Id);
-
- statement.MoveNext();
- }
- }, TransactionMode);
- }
- }
- }
-
- private const string BaseSelectText = "select Tokens.Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, DateCreated, DateLastActivity, Devices.CustomName from Tokens left join Devices on Tokens.DeviceId=Devices.Id";
-
- private static void BindAuthenticationQueryParams(AuthenticationInfoQuery query, IStatement statement)
- {
- if (!string.IsNullOrEmpty(query.AccessToken))
- {
- statement.TryBind("@AccessToken", query.AccessToken);
- }
-
- if (!query.UserId.Equals(Guid.Empty))
- {
- statement.TryBind("@UserId", query.UserId.ToString("N"));
- }
-
- if (!string.IsNullOrEmpty(query.DeviceId))
- {
- statement.TryBind("@DeviceId", query.DeviceId);
- }
- }
-
- public QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query)
- {
- if (query == null)
- {
- throw new ArgumentNullException(nameof(query));
- }
-
- var commandText = BaseSelectText;
-
- var whereClauses = new List<string>();
-
- if (!string.IsNullOrEmpty(query.AccessToken))
- {
- whereClauses.Add("AccessToken=@AccessToken");
- }
-
- if (!string.IsNullOrEmpty(query.DeviceId))
- {
- whereClauses.Add("DeviceId=@DeviceId");
- }
-
- if (!query.UserId.Equals(Guid.Empty))
- {
- whereClauses.Add("UserId=@UserId");
- }
-
- if (query.HasUser.HasValue)
- {
- if (query.HasUser.Value)
- {
- whereClauses.Add("UserId not null");
- }
- else
- {
- whereClauses.Add("UserId is null");
- }
- }
-
- var whereTextWithoutPaging = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- commandText += whereTextWithoutPaging;
-
- commandText += " ORDER BY DateLastActivity desc";
-
- if (query.Limit.HasValue || query.StartIndex.HasValue)
- {
- var offset = query.StartIndex ?? 0;
-
- if (query.Limit.HasValue || offset > 0)
- {
- commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture);
- }
-
- if (offset > 0)
- {
- commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture);
- }
- }
-
- var list = new List<AuthenticationInfo>();
-
- using (WriteLock.Read())
- {
- using (var connection = CreateConnection(true))
- {
- return connection.RunInTransaction(db =>
- {
- var result = new QueryResult<AuthenticationInfo>();
-
- var statementTexts = new List<string>();
- statementTexts.Add(commandText);
- statementTexts.Add("select count (Id) from Tokens" + whereTextWithoutPaging);
-
- var statements = PrepareAllSafe(db, statementTexts)
- .ToList();
-
- using (var statement = statements[0])
- {
- BindAuthenticationQueryParams(query, statement);
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(Get(row));
- }
-
- using (var totalCountStatement = statements[1])
- {
- BindAuthenticationQueryParams(query, totalCountStatement);
-
- result.TotalRecordCount = totalCountStatement.ExecuteQuery()
- .SelectScalarInt()
- .First();
- }
- }
-
- result.Items = list.ToArray();
- return result;
-
- }, ReadTransactionMode);
- }
- }
- }
-
- private static AuthenticationInfo Get(IReadOnlyList<IResultSetValue> reader)
- {
- var info = new AuthenticationInfo
- {
- Id = reader[0].ToInt64(),
- AccessToken = reader[1].ToString()
- };
-
- if (reader[2].SQLiteType != SQLiteType.Null)
- {
- info.DeviceId = reader[2].ToString();
- }
-
- if (reader[3].SQLiteType != SQLiteType.Null)
- {
- info.AppName = reader[3].ToString();
- }
-
- if (reader[4].SQLiteType != SQLiteType.Null)
- {
- info.AppVersion = reader[4].ToString();
- }
-
- if (reader[5].SQLiteType != SQLiteType.Null)
- {
- info.DeviceName = reader[5].ToString();
- }
-
- if (reader[6].SQLiteType != SQLiteType.Null)
- {
- info.UserId = new Guid(reader[6].ToString());
- }
-
- if (reader[7].SQLiteType != SQLiteType.Null)
- {
- info.UserName = reader[7].ToString();
- }
-
- info.DateCreated = reader[8].ReadDateTime();
-
- if (reader[9].SQLiteType != SQLiteType.Null)
- {
- info.DateLastActivity = reader[9].ReadDateTime();
- }
- else
- {
- info.DateLastActivity = info.DateCreated;
- }
-
- if (reader[10].SQLiteType != SQLiteType.Null)
- {
- info.DeviceName = reader[10].ToString();
- }
-
- return info;
- }
-
- public DeviceOptions GetDeviceOptions(string deviceId)
- {
- using (WriteLock.Read())
- {
- using (var connection = CreateConnection(true))
- {
- return connection.RunInTransaction(db =>
- {
- using (var statement = PrepareStatementSafe(db, "select CustomName from Devices where Id=@DeviceId"))
- {
- statement.TryBind("@DeviceId", deviceId);
-
- var result = new DeviceOptions();
-
- foreach (var row in statement.ExecuteQuery())
- {
- if (row[0].SQLiteType != SQLiteType.Null)
- {
- result.CustomName = row[0].ToString();
- }
- }
-
- return result;
- }
-
- }, ReadTransactionMode);
- }
- }
- }
-
- public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
- {
- if (options == null)
- {
- throw new ArgumentNullException(nameof(options));
- }
-
- using (WriteLock.Write())
- {
- using (var connection = CreateConnection())
- {
- connection.RunInTransaction(db =>
- {
- using (var statement = db.PrepareStatement("replace into devices (Id, CustomName, Capabilities) VALUES (@Id, @CustomName, (Select Capabilities from Devices where Id=@Id))"))
- {
- statement.TryBind("@Id", deviceId);
-
- if (string.IsNullOrWhiteSpace(options.CustomName))
- {
- statement.TryBindNull("@CustomName");
- }
- else
- {
- statement.TryBind("@CustomName", options.CustomName);
- }
-
- statement.MoveNext();
- }
-
- }, TransactionMode);
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Security/EncryptionManager.cs b/Emby.Server.Implementations/Security/EncryptionManager.cs
deleted file mode 100644
index fa8872ccc..000000000
--- a/Emby.Server.Implementations/Security/EncryptionManager.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-using System;
-using System.Text;
-using MediaBrowser.Controller.Security;
-
-namespace Emby.Server.Implementations.Security
-{
- public class EncryptionManager : IEncryptionManager
- {
- /// <summary>
- /// Encrypts the string.
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">value</exception>
- public string EncryptString(string value)
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- return EncryptStringUniversal(value);
- }
-
- /// <summary>
- /// Decrypts the string.
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">value</exception>
- public string DecryptString(string value)
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- return DecryptStringUniversal(value);
- }
-
- private static string EncryptStringUniversal(string value)
- {
- // Yes, this isn't good, but ProtectedData in mono is throwing exceptions, so use this for now
-
- var bytes = Encoding.UTF8.GetBytes(value);
- return Convert.ToBase64String(bytes);
- }
-
- private static string DecryptStringUniversal(string value)
- {
- // Yes, this isn't good, but ProtectedData in mono is throwing exceptions, so use this for now
-
- var bytes = Convert.FromBase64String(value);
- return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs
deleted file mode 100644
index 8ae7fd90c..000000000
--- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs
+++ /dev/null
@@ -1,289 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-
-namespace Emby.Server.Implementations.Serialization
-{
- /// <summary>
- /// Provides a wrapper around third party json serialization.
- /// </summary>
- public class JsonSerializer : IJsonSerializer
- {
- private readonly IFileSystem _fileSystem;
-
- public JsonSerializer(
- IFileSystem fileSystem)
- {
- _fileSystem = fileSystem;
- Configure();
- }
-
- /// <summary>
- /// Serializes to stream.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="stream">The stream.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- public void SerializeToStream(object obj, Stream stream)
- {
- if (obj == null)
- {
- throw new ArgumentNullException(nameof(obj));
- }
-
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
- ServiceStack.Text.JsonSerializer.SerializeToStream(obj, obj.GetType(), stream);
- }
-
- /// <summary>
- /// Serializes to stream.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="stream">The stream.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- public void SerializeToStream<T>(T obj, Stream stream)
- {
- if (obj == null)
- {
- throw new ArgumentNullException(nameof(obj));
- }
-
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
- ServiceStack.Text.JsonSerializer.SerializeToStream<T>(obj, stream);
- }
-
- /// <summary>
- /// Serializes to file.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="file">The file.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- public void SerializeToFile(object obj, string file)
- {
- if (obj == null)
- {
- throw new ArgumentNullException(nameof(obj));
- }
-
- if (string.IsNullOrEmpty(file))
- {
- throw new ArgumentNullException(nameof(file));
- }
-
- using (var stream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
- {
- SerializeToStream(obj, stream);
- }
- }
-
- private static Stream OpenFile(string path)
- {
- return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072);
- }
-
- /// <summary>
- /// Deserializes from file.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <param name="file">The file.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">type</exception>
- public object DeserializeFromFile(Type type, string file)
- {
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
-
- if (string.IsNullOrEmpty(file))
- {
- throw new ArgumentNullException(nameof(file));
- }
-
- using (var stream = OpenFile(file))
- {
- return DeserializeFromStream(stream, type);
- }
- }
-
- /// <summary>
- /// Deserializes from file.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="file">The file.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">file</exception>
- public T DeserializeFromFile<T>(string file)
- where T : class
- {
- if (string.IsNullOrEmpty(file))
- {
- throw new ArgumentNullException(nameof(file));
- }
-
- using (var stream = OpenFile(file))
- {
- return DeserializeFromStream<T>(stream);
- }
- }
-
- /// <summary>
- /// Deserializes from stream.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="stream">The stream.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">stream</exception>
- public T DeserializeFromStream<T>(Stream stream)
- {
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream);
- }
-
- public Task<T> DeserializeFromStreamAsync<T>(Stream stream)
- {
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromStreamAsync<T>(stream);
- }
-
- /// <summary>
- /// Deserializes from string.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="text">The text.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">text</exception>
- public T DeserializeFromString<T>(string text)
- {
- if (string.IsNullOrEmpty(text))
- {
- throw new ArgumentNullException(nameof(text));
- }
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(text);
- }
-
- /// <summary>
- /// Deserializes from stream.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">stream</exception>
- public object DeserializeFromStream(Stream stream, Type type)
- {
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromStream(type, stream);
- }
-
- public async Task<object> DeserializeFromStreamAsync(Stream stream, Type type)
- {
- if (stream == null)
- {
- throw new ArgumentNullException(nameof(stream));
- }
-
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
-
- using (var reader = new StreamReader(stream))
- {
- var json = await reader.ReadToEndAsync().ConfigureAwait(false);
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromString(json, type);
- }
- }
-
- /// <summary>
- /// Configures this instance.
- /// </summary>
- private void Configure()
- {
- ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601;
- ServiceStack.Text.JsConfig.ExcludeTypeInfo = true;
- ServiceStack.Text.JsConfig.IncludeNullValues = false;
- ServiceStack.Text.JsConfig.AlwaysUseUtc = true;
- ServiceStack.Text.JsConfig.AssumeUtc = true;
-
- ServiceStack.Text.JsConfig<Guid>.SerializeFn = SerializeGuid;
- }
-
- private static string SerializeGuid(Guid guid)
- {
- if (guid.Equals(Guid.Empty))
- {
- return null;
- }
-
- return guid.ToString("N");
- }
-
- /// <summary>
- /// Deserializes from string.
- /// </summary>
- /// <param name="json">The json.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">json</exception>
- public object DeserializeFromString(string json, Type type)
- {
- if (string.IsNullOrEmpty(json))
- {
- throw new ArgumentNullException(nameof(json));
- }
-
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
-
- return ServiceStack.Text.JsonSerializer.DeserializeFromString(json, type);
- }
-
- /// <summary>
- /// Serializes to string.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">obj</exception>
- public string SerializeToString(object obj)
- {
- if (obj == null)
- {
- throw new ArgumentNullException(nameof(obj));
- }
-
- return ServiceStack.Text.JsonSerializer.SerializeToString(obj, obj.GetType());
- }
- }
-}
diff --git a/Emby.Server.Implementations/Serialization/XmlSerializer.cs b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs
index 6400ec16e..059211a0b 100644
--- a/Emby.Server.Implementations/Serialization/XmlSerializer.cs
+++ b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs
@@ -1,11 +1,10 @@
using System;
-using System.Collections.Generic;
+using System.Collections.Concurrent;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Serialization
{
@@ -14,35 +13,16 @@ namespace Emby.Server.Implementations.Serialization
/// </summary>
public class MyXmlSerializer : IXmlSerializer
{
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
-
- public MyXmlSerializer(
- IFileSystem fileSystem,
- ILoggerFactory loggerFactory)
- {
- _fileSystem = fileSystem;
- _logger = loggerFactory.CreateLogger("XmlSerializer");
- }
-
// Need to cache these
// http://dotnetcodebox.blogspot.com/2013/01/xmlserializer-class-may-result-in.html
- private readonly Dictionary<string, XmlSerializer> _serializers =
- new Dictionary<string, XmlSerializer>();
+ private static readonly ConcurrentDictionary<string, XmlSerializer> _serializers =
+ new ConcurrentDictionary<string, XmlSerializer>();
- private XmlSerializer GetSerializer(Type type)
- {
- var key = type.FullName;
- lock (_serializers)
- {
- if (!_serializers.TryGetValue(key, out var serializer))
- {
- serializer = new XmlSerializer(type);
- _serializers[key] = serializer;
- }
- return serializer;
- }
- }
+ private static XmlSerializer GetSerializer(Type type)
+ => _serializers.GetOrAdd(
+ type.FullName ?? throw new ArgumentException($"Invalid type {type}."),
+ (_, t) => new XmlSerializer(t),
+ type);
/// <summary>
/// Serializes to writer.
@@ -61,7 +41,7 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="type">The type.</param>
/// <param name="stream">The stream.</param>
/// <returns>System.Object.</returns>
- public object DeserializeFromStream(Type type, Stream stream)
+ public object? DeserializeFromStream(Type type, Stream stream)
{
using (var reader = XmlReader.Create(stream))
{
@@ -77,10 +57,11 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="stream">The stream.</param>
public void SerializeToStream(object obj, Stream stream)
{
- using (var writer = new XmlTextWriter(stream, null))
+ using (var writer = new StreamWriter(stream, null, IODefaults.StreamWriterBufferSize, true))
+ using (var textWriter = new XmlTextWriter(writer))
{
- writer.Formatting = Formatting.Indented;
- SerializeToWriter(obj, writer);
+ textWriter.Formatting = Formatting.Indented;
+ SerializeToWriter(obj, textWriter);
}
}
@@ -91,8 +72,7 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="file">The file.</param>
public void SerializeToFile(object obj, string file)
{
- _logger.LogDebug("Serializing to file {0}", file);
- using (var stream = new FileStream(file, FileMode.Create))
+ using (var stream = new FileStream(file, FileMode.Create, FileAccess.Write))
{
SerializeToStream(obj, stream);
}
@@ -104,9 +84,8 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="type">The type.</param>
/// <param name="file">The file.</param>
/// <returns>System.Object.</returns>
- public object DeserializeFromFile(Type type, string file)
+ public object? DeserializeFromFile(Type type, string file)
{
- _logger.LogDebug("Deserializing file {0}", file);
using (var stream = File.OpenRead(file))
{
return DeserializeFromStream(type, stream);
@@ -119,9 +98,9 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="type">The type.</param>
/// <param name="buffer">The buffer.</param>
/// <returns>System.Object.</returns>
- public object DeserializeFromBytes(Type type, byte[] buffer)
+ public object? DeserializeFromBytes(Type type, byte[] buffer)
{
- using (var stream = new MemoryStream(buffer))
+ using (var stream = new MemoryStream(buffer, 0, buffer.Length, false, true))
{
return DeserializeFromStream(type, stream);
}
diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs
index 05f6469ec..369a2b0d8 100644
--- a/Emby.Server.Implementations/ServerApplicationPaths.cs
+++ b/Emby.Server.Implementations/ServerApplicationPaths.cs
@@ -1,4 +1,3 @@
-using System;
using System.IO;
using Emby.Server.Implementations.AppBase;
using MediaBrowser.Controller;
@@ -6,85 +5,91 @@ using MediaBrowser.Controller;
namespace Emby.Server.Implementations
{
/// <summary>
- /// Extends BaseApplicationPaths to add paths that are only applicable on the server
+ /// Extends BaseApplicationPaths to add paths that are only applicable on the server.
/// </summary>
public class ServerApplicationPaths : BaseApplicationPaths, IServerApplicationPaths
{
/// <summary>
- /// Initializes a new instance of the <see cref="BaseApplicationPaths" /> class.
+ /// Initializes a new instance of the <see cref="ServerApplicationPaths" /> class.
/// </summary>
+ /// <param name="programDataPath">The path for Jellyfin's data.</param>
+ /// <param name="logDirectoryPath">The path for Jellyfin's logging directory.</param>
+ /// <param name="configurationDirectoryPath">The path for Jellyfin's configuration directory.</param>
+ /// <param name="cacheDirectoryPath">The path for Jellyfin's cache directory.</param>
+ /// <param name="webDirectoryPath">The path for Jellyfin's web UI.</param>
public ServerApplicationPaths(
string programDataPath,
string logDirectoryPath,
string configurationDirectoryPath,
- string cacheDirectoryPath)
- : base(programDataPath,
+ string cacheDirectoryPath,
+ string webDirectoryPath)
+ : base(
+ programDataPath,
logDirectoryPath,
configurationDirectoryPath,
- cacheDirectoryPath)
+ cacheDirectoryPath,
+ webDirectoryPath)
{
+ // ProgramDataPath cannot change when the server is running, so cache these to avoid allocations.
+ RootFolderPath = Path.Join(ProgramDataPath, "root");
+ DefaultUserViewsPath = Path.Combine(RootFolderPath, "default");
+ DefaultInternalMetadataPath = Path.Combine(ProgramDataPath, "metadata");
+ InternalMetadataPath = DefaultInternalMetadataPath;
}
- public string ApplicationResourcesPath { get; } = AppContext.BaseDirectory;
-
/// <summary>
- /// Gets the path to the base root media directory
+ /// Gets the path to the base root media directory.
/// </summary>
/// <value>The root folder path.</value>
- public string RootFolderPath => Path.Combine(ProgramDataPath, "root");
+ public string RootFolderPath { get; }
/// <summary>
/// Gets the path to the default user view directory. Used if no specific user view is defined.
/// </summary>
/// <value>The default user views path.</value>
- public string DefaultUserViewsPath => Path.Combine(RootFolderPath, "default");
-
- /// <summary>
- /// Gets the path to localization data.
- /// </summary>
- /// <value>The localization path.</value>
- public string LocalizationPath => Path.Combine(ProgramDataPath, "localization");
+ public string DefaultUserViewsPath { get; }
/// <summary>
- /// Gets the path to the People directory
+ /// Gets the path to the People directory.
/// </summary>
/// <value>The people path.</value>
public string PeoplePath => Path.Combine(InternalMetadataPath, "People");
+ /// <inheritdoc />
public string ArtistsPath => Path.Combine(InternalMetadataPath, "artists");
/// <summary>
- /// Gets the path to the Genre directory
+ /// Gets the path to the Genre directory.
/// </summary>
/// <value>The genre path.</value>
public string GenrePath => Path.Combine(InternalMetadataPath, "Genre");
/// <summary>
- /// Gets the path to the Genre directory
+ /// Gets the path to the Genre directory.
/// </summary>
/// <value>The genre path.</value>
public string MusicGenrePath => Path.Combine(InternalMetadataPath, "MusicGenre");
/// <summary>
- /// Gets the path to the Studio directory
+ /// Gets the path to the Studio directory.
/// </summary>
/// <value>The studio path.</value>
public string StudioPath => Path.Combine(InternalMetadataPath, "Studio");
/// <summary>
- /// Gets the path to the Year directory
+ /// Gets the path to the Year directory.
/// </summary>
/// <value>The year path.</value>
public string YearPath => Path.Combine(InternalMetadataPath, "Year");
/// <summary>
- /// Gets the path to the General IBN directory
+ /// Gets the path to the General IBN directory.
/// </summary>
/// <value>The general path.</value>
public string GeneralPath => Path.Combine(InternalMetadataPath, "general");
/// <summary>
- /// Gets the path to the Ratings IBN directory
+ /// Gets the path to the Ratings IBN directory.
/// </summary>
/// <value>The ratings path.</value>
public string RatingsPath => Path.Combine(InternalMetadataPath, "ratings");
@@ -96,54 +101,18 @@ namespace Emby.Server.Implementations
public string MediaInfoImagesPath => Path.Combine(InternalMetadataPath, "mediainfo");
/// <summary>
- /// Gets the path to the user configuration directory
+ /// Gets the path to the user configuration directory.
/// </summary>
/// <value>The user configuration directory path.</value>
public string UserConfigurationDirectoryPath => Path.Combine(ConfigurationDirectoryPath, "users");
- private string _defaultTranscodingTempPath;
- public string DefaultTranscodingTempPath => _defaultTranscodingTempPath ?? (_defaultTranscodingTempPath = Path.Combine(ProgramDataPath, "transcoding-temp"));
-
- private string _transcodingTempPath;
- public string TranscodingTempPath
- {
- get => _transcodingTempPath ?? (_transcodingTempPath = DefaultTranscodingTempPath);
- set => _transcodingTempPath = value;
- }
-
- public string GetTranscodingTempPath()
- {
- var path = TranscodingTempPath;
-
- if (!string.Equals(path, DefaultTranscodingTempPath, StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- Directory.CreateDirectory(path);
-
- var testPath = Path.Combine(path, Guid.NewGuid().ToString());
- Directory.CreateDirectory(testPath);
- Directory.Delete(testPath);
-
- return path;
- }
- catch
- {
- }
- }
-
- path = DefaultTranscodingTempPath;
- Directory.CreateDirectory(path);
- return path;
- }
+ /// <inheritdoc/>
+ public string DefaultInternalMetadataPath { get; }
- private string _internalMetadataPath;
- public string InternalMetadataPath
- {
- get => _internalMetadataPath ?? (_internalMetadataPath = Path.Combine(DataPath, "metadata"));
- set => _internalMetadataPath = value;
- }
+ /// <inheritdoc />
+ public string InternalMetadataPath { get; set; }
- public string VirtualInternalMetadataPath { get; } = "%MetadataPath%";
+ /// <inheritdoc />
+ public string VirtualInternalMetadataPath => "%MetadataPath%";
}
}
diff --git a/Emby.Server.Implementations/Services/HttpResult.cs b/Emby.Server.Implementations/Services/HttpResult.cs
deleted file mode 100644
index 296da2f7a..000000000
--- a/Emby.Server.Implementations/Services/HttpResult.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Services
-{
- public class HttpResult
- : IHttpResult, IAsyncStreamWriter
- {
- public object Response { get; set; }
-
- public HttpResult(object response, string contentType, HttpStatusCode statusCode)
- {
- this.Headers = new Dictionary<string, string>();
-
- this.Response = response;
- this.ContentType = contentType;
- this.StatusCode = statusCode;
- }
-
- public string ContentType { get; set; }
-
- public IDictionary<string, string> Headers { get; private set; }
-
- public int Status { get; set; }
-
- public HttpStatusCode StatusCode
- {
- get => (HttpStatusCode)Status;
- set => Status = (int)value;
- }
-
- public IRequest RequestContext { get; set; }
-
- public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
- {
- var response = RequestContext == null ? null : RequestContext.Response;
-
- if (this.Response is byte[] bytesResponse)
- {
- var contentLength = bytesResponse.Length;
-
- if (response != null)
- {
- response.SetContentLength(contentLength);
- }
-
- if (contentLength > 0)
- {
- await responseStream.WriteAsync(bytesResponse, 0, contentLength).ConfigureAwait(false);
- }
- return;
- }
-
- await ResponseHelper.WriteObject(this.RequestContext, this.Response, response).ConfigureAwait(false);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/RequestHelper.cs b/Emby.Server.Implementations/Services/RequestHelper.cs
deleted file mode 100644
index 2563cac99..000000000
--- a/Emby.Server.Implementations/Services/RequestHelper.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.HttpServer;
-
-namespace Emby.Server.Implementations.Services
-{
- public class RequestHelper
- {
- public static Func<Type, Stream, Task<object>> GetRequestReader(HttpListenerHost host, string contentType)
- {
- switch (GetContentTypeWithoutEncoding(contentType))
- {
- case "application/xml":
- case "text/xml":
- case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
- return host.DeserializeXml;
-
- case "application/json":
- case "text/json":
- return host.DeserializeJson;
- }
-
- return null;
- }
-
- public static Action<object, Stream> GetResponseWriter(HttpListenerHost host, string contentType)
- {
- switch (GetContentTypeWithoutEncoding(contentType))
- {
- case "application/xml":
- case "text/xml":
- case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
- return host.SerializeToXml;
-
- case "application/json":
- case "text/json":
- return host.SerializeToJson;
- }
-
- return null;
- }
-
- private static string GetContentTypeWithoutEncoding(string contentType)
- {
- return contentType == null
- ? null
- : contentType.Split(';')[0].ToLowerInvariant().Trim();
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/Services/ResponseHelper.cs b/Emby.Server.Implementations/Services/ResponseHelper.cs
deleted file mode 100644
index dc9975347..000000000
--- a/Emby.Server.Implementations/Services/ResponseHelper.cs
+++ /dev/null
@@ -1,163 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Services
-{
- public static class ResponseHelper
- {
- public static Task WriteToResponse(IResponse response, IRequest request, object result, CancellationToken cancellationToken)
- {
- if (result == null)
- {
- if (response.StatusCode == (int)HttpStatusCode.OK)
- {
- response.StatusCode = (int)HttpStatusCode.NoContent;
- }
-
- response.SetContentLength(0);
- return Task.CompletedTask;
- }
-
- var httpResult = result as IHttpResult;
- if (httpResult != null)
- {
- httpResult.RequestContext = request;
- request.ResponseContentType = httpResult.ContentType ?? request.ResponseContentType;
- }
-
- var defaultContentType = request.ResponseContentType;
-
- if (httpResult != null)
- {
- if (httpResult.RequestContext == null)
- httpResult.RequestContext = request;
-
- response.StatusCode = httpResult.Status;
- response.StatusDescription = httpResult.StatusCode.ToString();
- //if (string.IsNullOrEmpty(httpResult.ContentType))
- //{
- // httpResult.ContentType = defaultContentType;
- //}
- //response.ContentType = httpResult.ContentType;
- }
-
- var responseOptions = result as IHasHeaders;
- if (responseOptions != null)
- {
- foreach (var responseHeaders in responseOptions.Headers)
- {
- if (string.Equals(responseHeaders.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
- {
- response.SetContentLength(long.Parse(responseHeaders.Value));
- continue;
- }
-
- response.AddHeader(responseHeaders.Key, responseHeaders.Value);
- }
- }
-
- //ContentType='text/html' is the default for a HttpResponse
- //Do not override if another has been set
- if (response.ContentType == null || response.ContentType == "text/html")
- {
- response.ContentType = defaultContentType;
- }
-
- if (response.ContentType == "application/json")
- {
- response.ContentType += "; charset=utf-8";
- }
-
- var asyncStreamWriter = result as IAsyncStreamWriter;
- if (asyncStreamWriter != null)
- {
- return asyncStreamWriter.WriteToAsync(response.OutputStream, cancellationToken);
- }
-
- var streamWriter = result as IStreamWriter;
- if (streamWriter != null)
- {
- streamWriter.WriteTo(response.OutputStream);
- return Task.CompletedTask;
- }
-
- var fileWriter = result as FileWriter;
- if (fileWriter != null)
- {
- return fileWriter.WriteToAsync(response, cancellationToken);
- }
-
- var stream = result as Stream;
- if (stream != null)
- {
- return CopyStream(stream, response.OutputStream);
- }
-
- var bytes = result as byte[];
- if (bytes != null)
- {
- response.ContentType = "application/octet-stream";
- response.SetContentLength(bytes.Length);
-
- if (bytes.Length > 0)
- {
- return response.OutputStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
- }
- return Task.CompletedTask;
- }
-
- var responseText = result as string;
- if (responseText != null)
- {
- bytes = Encoding.UTF8.GetBytes(responseText);
- response.SetContentLength(bytes.Length);
- if (bytes.Length > 0)
- {
- return response.OutputStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
- }
- return Task.CompletedTask;
- }
-
- return WriteObject(request, result, response);
- }
-
- private static async Task CopyStream(Stream src, Stream dest)
- {
- using (src)
- {
- await src.CopyToAsync(dest).ConfigureAwait(false);
- }
- }
-
- public static async Task WriteObject(IRequest request, object result, IResponse response)
- {
- var contentType = request.ResponseContentType;
- var serializer = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
-
- using (var ms = new MemoryStream())
- {
- serializer(result, ms);
-
- ms.Position = 0;
-
- var contentLength = ms.Length;
-
- response.SetContentLength(contentLength);
-
- if (contentLength > 0)
- {
- await ms.CopyToAsync(response.OutputStream).ConfigureAwait(false);
- }
- }
-
- //serializer(result, outputStream);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs
deleted file mode 100644
index 5796956d8..000000000
--- a/Emby.Server.Implementations/Services/ServiceController.cs
+++ /dev/null
@@ -1,184 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Services
-{
- public delegate Task<object> InstanceExecFn(IRequest requestContext, object intance, object request);
- public delegate object ActionInvokerFn(object intance, object request);
- public delegate void VoidActionInvokerFn(object intance, object request);
-
- public class ServiceController
- {
- public static ServiceController Instance;
-
- public ServiceController()
- {
- Instance = this;
- }
-
- public void Init(HttpListenerHost appHost, Type[] serviceTypes)
- {
- foreach (var serviceType in serviceTypes)
- {
- RegisterService(appHost, serviceType);
- }
- }
-
- public void RegisterService(HttpListenerHost appHost, Type serviceType)
- {
- var processedReqs = new HashSet<Type>();
-
- var actions = ServiceExecGeneral.Reset(serviceType);
-
- foreach (var mi in serviceType.GetActions())
- {
- var requestType = mi.GetParameters()[0].ParameterType;
- if (processedReqs.Contains(requestType)) continue;
- processedReqs.Add(requestType);
-
- ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions);
-
- //var returnMarker = GetTypeWithGenericTypeDefinitionOf(requestType, typeof(IReturn<>));
- //var responseType = returnMarker != null ?
- // GetGenericArguments(returnMarker)[0]
- // : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ?
- // mi.ReturnType
- // : Type.GetType(requestType.FullName + "Response");
-
- RegisterRestPaths(appHost, requestType, serviceType);
-
- appHost.AddServiceInfo(serviceType, requestType);
- }
- }
-
- public static Type FirstGenericType(Type type)
- {
- while (type != null)
- {
- if (type.GetTypeInfo().IsGenericType)
- return type;
-
- type = type.GetTypeInfo().BaseType;
- }
- return null;
- }
-
- public readonly RestPath.RestPathMap RestPathMap = new RestPath.RestPathMap();
-
- public void RegisterRestPaths(HttpListenerHost appHost, Type requestType, Type serviceType)
- {
- var attrs = appHost.GetRouteAttributes(requestType);
- foreach (var attr in attrs)
- {
- var restPath = new RestPath(appHost.CreateInstance, appHost.GetParseFn, requestType, serviceType, attr.Path, attr.Verbs, attr.IsHidden, attr.Summary, attr.Description);
-
- RegisterRestPath(restPath);
- }
- }
-
- private static readonly char[] InvalidRouteChars = new[] { '?', '&' };
-
- public void RegisterRestPath(RestPath restPath)
- {
- if (!restPath.Path.StartsWith("/"))
- throw new ArgumentException(string.Format("Route '{0}' on '{1}' must start with a '/'", restPath.Path, restPath.RequestType.GetMethodName()));
- if (restPath.Path.IndexOfAny(InvalidRouteChars) != -1)
- throw new ArgumentException(string.Format("Route '{0}' on '{1}' contains invalid chars. ", restPath.Path, restPath.RequestType.GetMethodName()));
-
- if (!RestPathMap.TryGetValue(restPath.FirstMatchHashKey, out List<RestPath> pathsAtFirstMatch))
- {
- pathsAtFirstMatch = new List<RestPath>();
- RestPathMap[restPath.FirstMatchHashKey] = pathsAtFirstMatch;
- }
- pathsAtFirstMatch.Add(restPath);
- }
-
- public RestPath GetRestPathForRequest(string httpMethod, string pathInfo)
- {
- var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo);
-
- List<RestPath> firstMatches;
-
- var yieldedHashMatches = RestPath.GetFirstMatchHashKeys(matchUsingPathParts);
- foreach (var potentialHashMatch in yieldedHashMatches)
- {
- if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches))
- {
- continue;
- }
-
- var bestScore = -1;
- RestPath bestMatch = null;
- foreach (var restPath in firstMatches)
- {
- var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
- if (score > bestScore)
- {
- bestScore = score;
- bestMatch = restPath;
- }
- }
-
- if (bestScore > 0 && bestMatch != null)
- {
- return bestMatch;
- }
- }
-
- var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts);
- foreach (var potentialHashMatch in yieldedWildcardMatches)
- {
- if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
-
- var bestScore = -1;
- RestPath bestMatch = null;
- foreach (var restPath in firstMatches)
- {
- var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
- if (score > bestScore)
- {
- bestScore = score;
- bestMatch = restPath;
- }
- }
-
- if (bestScore > 0 && bestMatch != null)
- {
- return bestMatch;
- }
- }
-
- return null;
- }
-
- public Task<object> Execute(HttpListenerHost appHost, object requestDto, IRequest req)
- {
- req.Dto = requestDto;
- var requestType = requestDto.GetType();
- req.OperationName = requestType.Name;
-
- var serviceType = appHost.GetServiceTypeByRequest(requestType);
-
- var service = appHost.CreateInstance(serviceType);
-
- //var service = typeFactory.CreateInstance(serviceType);
-
- var serviceRequiresContext = service as IRequiresRequest;
- if (serviceRequiresContext != null)
- {
- serviceRequiresContext.Request = req;
- }
-
- if (req.Dto == null) // Don't override existing batched DTO[]
- req.Dto = requestDto;
-
- //Executes the service and returns the result
- return ServiceExecGeneral.Execute(serviceType, req, service, requestDto, requestType.GetMethodName());
- }
- }
-
-}
diff --git a/Emby.Server.Implementations/Services/ServiceExec.cs b/Emby.Server.Implementations/Services/ServiceExec.cs
deleted file mode 100644
index 79f5c59e6..000000000
--- a/Emby.Server.Implementations/Services/ServiceExec.cs
+++ /dev/null
@@ -1,219 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Services
-{
- public static class ServiceExecExtensions
- {
- public static string[] AllVerbs = new[] {
- "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", // RFC 2616
- "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", // RFC 2518
- "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
- "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY", // RFC 3253
- "ORDERPATCH", // RFC 3648
- "ACL", // RFC 3744
- "PATCH", // https://datatracker.ietf.org/doc/draft-dusseault-http-patch/
- "SEARCH", // https://datatracker.ietf.org/doc/draft-reschke-webdav-search/
- "BCOPY", "BDELETE", "BMOVE", "BPROPFIND", "BPROPPATCH", "NOTIFY",
- "POLL", "SUBSCRIBE", "UNSUBSCRIBE"
- };
-
- public static List<MethodInfo> GetActions(this Type serviceType)
- {
- var list = new List<MethodInfo>();
-
- foreach (var mi in serviceType.GetRuntimeMethods())
- {
- if (!mi.IsPublic)
- {
- continue;
- }
-
- if (mi.IsStatic)
- {
- continue;
- }
-
- if (mi.GetParameters().Length != 1)
- continue;
-
- var actionName = mi.Name;
- if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase))
- continue;
-
- list.Add(mi);
- }
-
- return list;
- }
- }
-
- internal static class ServiceExecGeneral
- {
- private static Dictionary<string, ServiceMethod> execMap = new Dictionary<string, ServiceMethod>();
-
- public static void CreateServiceRunnersFor(Type requestType, List<ServiceMethod> actions)
- {
- foreach (var actionCtx in actions)
- {
- if (execMap.ContainsKey(actionCtx.Id)) continue;
-
- execMap[actionCtx.Id] = actionCtx;
- }
- }
-
- public static Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName)
- {
- var actionName = request.Verb ?? "POST";
-
- if (execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out ServiceMethod actionContext))
- {
- if (actionContext.RequestFilters != null)
- {
- foreach (var requestFilter in actionContext.RequestFilters)
- {
- requestFilter.RequestFilter(request, request.Response, requestDto);
- if (request.Response.IsClosed)
- {
- Task.FromResult<object>(null);
- }
- }
- }
-
- var response = actionContext.ServiceAction(instance, requestDto);
-
- var taskResponse = response as Task;
- if (taskResponse != null)
- {
- return GetTaskResult(taskResponse);
- }
-
- return Task.FromResult(response);
- }
-
- var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLowerInvariant();
- throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName()));
- }
-
- private static async Task<object> GetTaskResult(Task task)
- {
- try
- {
- var taskObject = task as Task<object>;
- if (taskObject != null)
- {
- return await taskObject.ConfigureAwait(false);
- }
-
- await task.ConfigureAwait(false);
-
- var type = task.GetType().GetTypeInfo();
- if (!type.IsGenericType)
- {
- return null;
- }
-
- var resultProperty = type.GetDeclaredProperty("Result");
- if (resultProperty == null)
- {
- return null;
- }
-
- var result = resultProperty.GetValue(task);
-
- // hack alert
- if (result.GetType().Name.IndexOf("voidtaskresult", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return null;
- }
-
- return result;
- }
- catch (TypeAccessException)
- {
- return null; //return null for void Task's
- }
- }
-
- public static List<ServiceMethod> Reset(Type serviceType)
- {
- var actions = new List<ServiceMethod>();
-
- foreach (var mi in serviceType.GetActions())
- {
- var actionName = mi.Name;
- var args = mi.GetParameters();
-
- var requestType = args[0].ParameterType;
- var actionCtx = new ServiceMethod
- {
- Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
- };
-
- try
- {
- actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
- }
- catch
- {
- //Potential problems with MONO, using reflection for fallback
- actionCtx.ServiceAction = (service, request) =>
- mi.Invoke(service, new[] { request });
- }
-
- var reqFilters = new List<IHasRequestFilter>();
-
- foreach (var attr in mi.GetCustomAttributes(true))
- {
- var hasReqFilter = attr as IHasRequestFilter;
-
- if (hasReqFilter != null)
- reqFilters.Add(hasReqFilter);
- }
-
- if (reqFilters.Count > 0)
- actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray();
-
- actions.Add(actionCtx);
- }
-
- return actions;
- }
-
- private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
- {
- var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
- var serviceStrong = Expression.Convert(serviceParam, serviceType);
-
- var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
- var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
-
- Expression callExecute = Expression.Call(
- serviceStrong, mi, requestDtoStrong);
-
- if (mi.ReturnType != typeof(void))
- {
- var executeFunc = Expression.Lambda<ActionInvokerFn>
- (callExecute, serviceParam, requestDtoParam).Compile();
-
- return executeFunc;
- }
- else
- {
- var executeFunc = Expression.Lambda<VoidActionInvokerFn>
- (callExecute, serviceParam, requestDtoParam).Compile();
-
- return (service, request) =>
- {
- executeFunc(service, request);
- return null;
- };
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs
deleted file mode 100644
index 7e836e22c..000000000
--- a/Emby.Server.Implementations/Services/ServiceHandler.cs
+++ /dev/null
@@ -1,245 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Services
-{
- public class ServiceHandler
- {
- protected static Task<object> CreateContentTypeRequest(HttpListenerHost host, IRequest httpReq, Type requestType, string contentType)
- {
- if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0)
- {
- var deserializer = RequestHelper.GetRequestReader(host, contentType);
- if (deserializer != null)
- {
- return deserializer(requestType, httpReq.InputStream);
- }
- }
- return Task.FromResult(host.CreateInstance(requestType));
- }
-
- public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, out string contentType)
- {
- pathInfo = GetSanitizedPathInfo(pathInfo, out contentType);
-
- return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo);
- }
-
- public static string GetSanitizedPathInfo(string pathInfo, out string contentType)
- {
- contentType = null;
- var pos = pathInfo.LastIndexOf('.');
- if (pos >= 0)
- {
- var format = pathInfo.Substring(pos + 1);
- contentType = GetFormatContentType(format);
- if (contentType != null)
- {
- pathInfo = pathInfo.Substring(0, pos);
- }
- }
- return pathInfo;
- }
-
- private static string GetFormatContentType(string format)
- {
- //built-in formats
- if (format == "json")
- return "application/json";
- if (format == "xml")
- return "application/xml";
-
- return null;
- }
-
- public RestPath GetRestPath(string httpMethod, string pathInfo)
- {
- if (this.RestPath == null)
- {
- this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, out string contentType);
-
- if (contentType != null)
- ResponseContentType = contentType;
- }
- return this.RestPath;
- }
-
- public RestPath RestPath { get; set; }
-
- // Set from SSHHF.GetHandlerForPathInfo()
- public string ResponseContentType { get; set; }
-
- public async Task ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, ILogger logger, string operationName, CancellationToken cancellationToken)
- {
- var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
- if (restPath == null)
- {
- throw new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo);
- }
-
- SetRoute(httpReq, restPath);
-
- if (ResponseContentType != null)
- httpReq.ResponseContentType = ResponseContentType;
-
- var request = httpReq.Dto = await CreateRequest(appHost, httpReq, restPath, logger).ConfigureAwait(false);
-
- appHost.ApplyRequestFilters(httpReq, httpRes, request);
-
- var response = await appHost.ServiceController.Execute(appHost, request, httpReq).ConfigureAwait(false);
-
- // Apply response filters
- foreach (var responseFilter in appHost.ResponseFilters)
- {
- responseFilter(httpReq, httpRes, response);
- }
-
- await ResponseHelper.WriteToResponse(httpRes, httpReq, response, cancellationToken).ConfigureAwait(false);
- }
-
- public static async Task<object> CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
- {
- var requestType = restPath.RequestType;
-
- if (RequireqRequestStream(requestType))
- {
- // Used by IRequiresRequestStream
- var requestParams = await GetRequestParams(httpReq).ConfigureAwait(false);
- var request = ServiceHandler.CreateRequest(httpReq, restPath, requestParams, host.CreateInstance(requestType));
-
- var rawReq = (IRequiresRequestStream)request;
- rawReq.RequestStream = httpReq.InputStream;
- return rawReq;
- }
- else
- {
- var requestParams = await GetFlattenedRequestParams(httpReq).ConfigureAwait(false);
-
- var requestDto = await CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType).ConfigureAwait(false);
-
- return CreateRequest(httpReq, restPath, requestParams, requestDto);
- }
- }
-
- public static bool RequireqRequestStream(Type requestType)
- {
- var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
-
- return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
- }
-
- public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
- {
- var pathInfo = !restPath.IsWildCardPath
- ? GetSanitizedPathInfo(httpReq.PathInfo, out string contentType)
- : httpReq.PathInfo;
-
- return restPath.CreateRequest(pathInfo, requestParams, requestDto);
- }
-
- /// <summary>
- /// Duplicate Params are given a unique key by appending a #1 suffix
- /// </summary>
- private static async Task<Dictionary<string, string>> GetRequestParams(IRequest request)
- {
- var map = new Dictionary<string, string>();
-
- foreach (var name in request.QueryString.Keys)
- {
- if (name == null) continue; //thank you ASP.NET
-
- var values = request.QueryString.GetValues(name);
- if (values.Count == 1)
- {
- map[name] = values[0];
- }
- else
- {
- for (var i = 0; i < values.Count; i++)
- {
- map[name + (i == 0 ? "" : "#" + i)] = values[i];
- }
- }
- }
-
- if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
- {
- var formData = await request.GetFormData().ConfigureAwait(false);
- if (formData != null)
- {
- foreach (var name in formData.Keys)
- {
- if (name == null) continue; //thank you ASP.NET
-
- var values = formData.GetValues(name);
- if (values.Count == 1)
- {
- map[name] = values[0];
- }
- else
- {
- for (var i = 0; i < values.Count; i++)
- {
- map[name + (i == 0 ? "" : "#" + i)] = values[i];
- }
- }
- }
- }
- }
-
- return map;
- }
-
- private static bool IsMethod(string method, string expected)
- {
- return string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Duplicate params have their values joined together in a comma-delimited string
- /// </summary>
- private static async Task<Dictionary<string, string>> GetFlattenedRequestParams(IRequest request)
- {
- var map = new Dictionary<string, string>();
-
- foreach (var name in request.QueryString.Keys)
- {
- if (name == null) continue; //thank you ASP.NET
- map[name] = request.QueryString[name];
- }
-
- if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
- {
- var formData = await request.GetFormData().ConfigureAwait(false);
- if (formData != null)
- {
- foreach (var name in formData.Keys)
- {
- if (name == null) continue; //thank you ASP.NET
- map[name] = formData[name];
- }
- }
- }
-
- return map;
- }
-
- private static void SetRoute(IRequest req, RestPath route)
- {
- req.Items["__route"] = route;
- }
-
- private static RestPath GetRoute(IRequest req)
- {
- req.Items.TryGetValue("__route", out var route);
- return route as RestPath;
- }
- }
-
-}
diff --git a/Emby.Server.Implementations/Services/ServiceMethod.cs b/Emby.Server.Implementations/Services/ServiceMethod.cs
deleted file mode 100644
index 5018bf4a2..000000000
--- a/Emby.Server.Implementations/Services/ServiceMethod.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-
-namespace Emby.Server.Implementations.Services
-{
- public class ServiceMethod
- {
- public string Id { get; set; }
-
- public ActionInvokerFn ServiceAction { get; set; }
- public MediaBrowser.Model.Services.IHasRequestFilter[] RequestFilters { get; set; }
-
- public static string Key(Type serviceType, string method, string requestDtoName)
- {
- return serviceType.FullName + " " + method.ToUpperInvariant() + " " + requestDtoName;
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs
deleted file mode 100644
index f575baca3..000000000
--- a/Emby.Server.Implementations/Services/ServicePath.cs
+++ /dev/null
@@ -1,564 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Text;
-
-namespace Emby.Server.Implementations.Services
-{
- public class RestPath
- {
- private const string WildCard = "*";
- private const char WildCardChar = '*';
- private const string PathSeperator = "/";
- private const char PathSeperatorChar = '/';
- private const char ComponentSeperator = '.';
- private const string VariablePrefix = "{";
-
- readonly bool[] componentsWithSeparators;
-
- private readonly string restPath;
- public bool IsWildCardPath { get; private set; }
-
- private readonly string[] literalsToMatch;
-
- private readonly string[] variablesNames;
-
- private readonly bool[] isWildcard;
- private readonly int wildcardCount = 0;
-
- public int VariableArgsCount { get; set; }
-
- /// <summary>
- /// The number of segments separated by '/' determinable by path.Split('/').Length
- /// e.g. /path/to/here.ext == 3
- /// </summary>
- public int PathComponentsCount { get; set; }
-
- /// <summary>
- /// The total number of segments after subparts have been exploded ('.')
- /// e.g. /path/to/here.ext == 4
- /// </summary>
- public int TotalComponentsCount { get; set; }
-
- public string[] Verbs { get; private set; }
-
- public Type RequestType { get; private set; }
-
- public Type ServiceType { get; private set; }
-
- public string Path => this.restPath;
-
- public string Summary { get; private set; }
- public string Description { get; private set; }
- public bool IsHidden { get; private set; }
-
- public int Priority { get; set; } //passed back to RouteAttribute
-
- public IEnumerable<string> PathVariables => this.variablesNames.Where(e => !string.IsNullOrWhiteSpace(e));
-
- public static string[] GetPathPartsForMatching(string pathInfo)
- {
- return pathInfo.ToLowerInvariant().Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public static List<string> GetFirstMatchHashKeys(string[] pathPartsForMatching)
- {
- var hashPrefix = pathPartsForMatching.Length + PathSeperator;
- return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
- }
-
- public static List<string> GetFirstMatchWildCardHashKeys(string[] pathPartsForMatching)
- {
- const string hashPrefix = WildCard + PathSeperator;
- return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
- }
-
- private static List<string> GetPotentialMatchesWithPrefix(string hashPrefix, string[] pathPartsForMatching)
- {
- var list = new List<string>();
-
- foreach (var part in pathPartsForMatching)
- {
- list.Add(hashPrefix + part);
-
- var subParts = part.Split(ComponentSeperator);
- if (subParts.Length == 1) continue;
-
- foreach (var subPart in subParts)
- {
- list.Add(hashPrefix + subPart);
- }
- }
-
- return list;
- }
-
- public RestPath(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type requestType, Type serviceType, string path, string verbs, bool isHidden = false, string summary = null, string description = null)
- {
- this.RequestType = requestType;
- this.ServiceType = serviceType;
- this.Summary = summary;
- this.IsHidden = isHidden;
- this.Description = description;
- this.restPath = path;
-
- this.Verbs = string.IsNullOrWhiteSpace(verbs) ? ServiceExecExtensions.AllVerbs : verbs.ToUpperInvariant().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
-
- var componentsList = new List<string>();
-
- //We only split on '.' if the restPath has them. Allows for /{action}.{type}
- var hasSeparators = new List<bool>();
- foreach (var component in this.restPath.Split(PathSeperatorChar))
- {
- if (string.IsNullOrEmpty(component)) continue;
-
- if (StringContains(component, VariablePrefix)
- && component.IndexOf(ComponentSeperator) != -1)
- {
- hasSeparators.Add(true);
- componentsList.AddRange(component.Split(ComponentSeperator));
- }
- else
- {
- hasSeparators.Add(false);
- componentsList.Add(component);
- }
- }
-
- var components = componentsList.ToArray();
- this.TotalComponentsCount = components.Length;
-
- this.literalsToMatch = new string[this.TotalComponentsCount];
- this.variablesNames = new string[this.TotalComponentsCount];
- this.isWildcard = new bool[this.TotalComponentsCount];
- this.componentsWithSeparators = hasSeparators.ToArray();
- this.PathComponentsCount = this.componentsWithSeparators.Length;
- string firstLiteralMatch = null;
-
- for (var i = 0; i < components.Length; i++)
- {
- var component = components[i];
-
- if (component.StartsWith(VariablePrefix))
- {
- var variableName = component.Substring(1, component.Length - 2);
- if (variableName[variableName.Length - 1] == WildCardChar)
- {
- this.isWildcard[i] = true;
- variableName = variableName.Substring(0, variableName.Length - 1);
- }
- this.variablesNames[i] = variableName;
- this.VariableArgsCount++;
- }
- else
- {
- this.literalsToMatch[i] = component.ToLowerInvariant();
-
- if (firstLiteralMatch == null)
- {
- firstLiteralMatch = this.literalsToMatch[i];
- }
- }
- }
-
- for (var i = 0; i < components.Length - 1; i++)
- {
- if (!this.isWildcard[i]) continue;
- if (this.literalsToMatch[i + 1] == null)
- {
- throw new ArgumentException(
- "A wildcard path component must be at the end of the path or followed by a literal path component.");
- }
- }
-
- this.wildcardCount = this.isWildcard.Count(x => x);
- this.IsWildCardPath = this.wildcardCount > 0;
-
- this.FirstMatchHashKey = !this.IsWildCardPath
- ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
- : WildCardChar + PathSeperator + firstLiteralMatch;
-
- this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType);
- RegisterCaseInsenstivePropertyNameMappings();
- }
-
- private void RegisterCaseInsenstivePropertyNameMappings()
- {
- foreach (var propertyInfo in GetSerializableProperties(RequestType))
- {
- var propertyName = propertyInfo.Name;
- propertyNamesMap.Add(propertyName.ToLowerInvariant(), propertyName);
- }
- }
-
- internal static string[] IgnoreAttributesNamed = new[] {
- "IgnoreDataMemberAttribute",
- "JsonIgnoreAttribute"
- };
-
-
- private static Type excludeType = typeof(Stream);
-
- internal static List<PropertyInfo> GetSerializableProperties(Type type)
- {
- var list = new List<PropertyInfo>();
- var props = GetPublicProperties(type);
-
- foreach (var prop in props)
- {
- if (prop.GetMethod == null)
- {
- continue;
- }
-
- if (excludeType == prop.PropertyType)
- {
- continue;
- }
-
- var ignored = false;
- foreach (var attr in prop.GetCustomAttributes(true))
- {
- if (IgnoreAttributesNamed.Contains(attr.GetType().Name))
- {
- ignored = true;
- break;
- }
- }
-
- if (!ignored)
- {
- list.Add(prop);
- }
- }
-
- // else return those properties that are not decorated with IgnoreDataMember
- return list;
- }
-
- private static List<PropertyInfo> GetPublicProperties(Type type)
- {
- if (type.GetTypeInfo().IsInterface)
- {
- var propertyInfos = new List<PropertyInfo>();
-
- var considered = new List<Type>();
- var queue = new Queue<Type>();
- considered.Add(type);
- queue.Enqueue(type);
-
- while (queue.Count > 0)
- {
- var subType = queue.Dequeue();
- foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces)
- {
- if (considered.Contains(subInterface)) continue;
-
- considered.Add(subInterface);
- queue.Enqueue(subInterface);
- }
-
- var typeProperties = GetTypesPublicProperties(subType);
-
- var newPropertyInfos = typeProperties
- .Where(x => !propertyInfos.Contains(x));
-
- propertyInfos.InsertRange(0, newPropertyInfos);
- }
-
- return propertyInfos;
- }
-
- var list = new List<PropertyInfo>();
-
- foreach (var t in GetTypesPublicProperties(type))
- {
- if (t.GetIndexParameters().Length == 0)
- {
- list.Add(t);
- }
- }
- return list;
- }
-
- private static PropertyInfo[] GetTypesPublicProperties(Type subType)
- {
- var pis = new List<PropertyInfo>();
- foreach (var pi in subType.GetRuntimeProperties())
- {
- var mi = pi.GetMethod ?? pi.SetMethod;
- if (mi != null && mi.IsStatic) continue;
- pis.Add(pi);
- }
- return pis.ToArray();
- }
-
- /// <summary>
- /// Provide for quick lookups based on hashes that can be determined from a request url
- /// </summary>
- public string FirstMatchHashKey { get; private set; }
-
- private readonly StringMapTypeDeserializer typeDeserializer;
-
- private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
-
- public int MatchScore(string httpMethod, string[] withPathInfoParts)
- {
- var isMatch = IsMatch(httpMethod, withPathInfoParts, out var wildcardMatchCount);
- if (!isMatch)
- {
- return -1;
- }
-
- var score = 0;
-
- //Routes with least wildcard matches get the highest score
- score += Math.Max((100 - wildcardMatchCount), 1) * 1000;
-
- //Routes with less variable (and more literal) matches
- score += Math.Max((10 - VariableArgsCount), 1) * 100;
-
- //Exact verb match is better than ANY
- if (Verbs.Length == 1 && string.Equals(httpMethod, Verbs[0], StringComparison.OrdinalIgnoreCase))
- {
- score += 10;
- }
- else
- {
- score += 1;
- }
-
- return score;
- }
-
- private bool StringContains(string str1, string str2)
- {
- return str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) != -1;
- }
-
- /// <summary>
- /// For performance withPathInfoParts should already be a lower case string
- /// to minimize redundant matching operations.
- /// </summary>
- public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
- {
- wildcardMatchCount = 0;
-
- if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
- {
- return false;
- }
-
- if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
-
- if (!ExplodeComponents(ref withPathInfoParts))
- {
- return false;
- }
-
- if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
- {
- return false;
- }
-
- int pathIx = 0;
- for (var i = 0; i < this.TotalComponentsCount; i++)
- {
- if (this.isWildcard[i])
- {
- if (i < this.TotalComponentsCount - 1)
- {
- // Continue to consume up until a match with the next literal
- while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1]))
- {
- pathIx++;
- wildcardMatchCount++;
- }
-
- // Ensure there are still enough parts left to match the remainder
- if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
- {
- return false;
- }
- }
- else
- {
- // A wildcard at the end matches the remainder of path
- wildcardMatchCount += withPathInfoParts.Length - pathIx;
- pathIx = withPathInfoParts.Length;
- }
- }
- else
- {
- var literalToMatch = this.literalsToMatch[i];
- if (literalToMatch == null)
- {
- // Matching an ordinary (non-wildcard) variable consumes a single part
- pathIx++;
- continue;
- }
-
- if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
- {
- return false;
- }
- pathIx++;
- }
- }
-
- return pathIx == withPathInfoParts.Length;
- }
-
- private static bool LiteralsEqual(string str1, string str2)
- {
- // Most cases
- if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- // Handle turkish i
- str1 = str1.ToUpperInvariant();
- str2 = str2.ToUpperInvariant();
-
- // Invariant IgnoreCase would probably be better but it's not available in PCL
- return string.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase);
- }
-
- private bool ExplodeComponents(ref string[] withPathInfoParts)
- {
- var totalComponents = new List<string>();
- for (var i = 0; i < withPathInfoParts.Length; i++)
- {
- var component = withPathInfoParts[i];
- if (string.IsNullOrEmpty(component)) continue;
-
- if (this.PathComponentsCount != this.TotalComponentsCount
- && this.componentsWithSeparators[i])
- {
- var subComponents = component.Split(ComponentSeperator);
- if (subComponents.Length < 2) return false;
- totalComponents.AddRange(subComponents);
- }
- else
- {
- totalComponents.Add(component);
- }
- }
-
- withPathInfoParts = totalComponents.ToArray();
- return true;
- }
-
- public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
- {
- var requestComponents = pathInfo.Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
-
- ExplodeComponents(ref requestComponents);
-
- if (requestComponents.Length != this.TotalComponentsCount)
- {
- var isValidWildCardPath = this.IsWildCardPath
- && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
-
- if (!isValidWildCardPath)
- throw new ArgumentException(string.Format(
- "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
- pathInfo, this.restPath));
- }
-
- var requestKeyValuesMap = new Dictionary<string, string>();
- var pathIx = 0;
- for (var i = 0; i < this.TotalComponentsCount; i++)
- {
- var variableName = this.variablesNames[i];
- if (variableName == null)
- {
- pathIx++;
- continue;
- }
-
- if (!this.propertyNamesMap.TryGetValue(variableName.ToLowerInvariant(), out var propertyNameOnRequest))
- {
- if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
- {
- pathIx++;
- continue;
- }
-
- throw new ArgumentException("Could not find property "
- + variableName + " on " + RequestType.GetMethodName());
- }
-
- var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
- if (value != null && this.isWildcard[i])
- {
- if (i == this.TotalComponentsCount - 1)
- {
- // Wildcard at end of path definition consumes all the rest
- var sb = new StringBuilder();
- sb.Append(value);
- for (var j = pathIx + 1; j < requestComponents.Length; j++)
- {
- sb.Append(PathSeperatorChar + requestComponents[j]);
- }
- value = sb.ToString();
- }
- else
- {
- // Wildcard in middle of path definition consumes up until it
- // hits a match for the next element in the definition (which must be a literal)
- // It may consume 0 or more path parts
- var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
- if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
- {
- var sb = new StringBuilder();
- sb.Append(value);
- pathIx++;
- while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
- {
- sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
- }
- value = sb.ToString();
- }
- else
- {
- value = null;
- }
- }
- }
- else
- {
- // Variable consumes single path item
- pathIx++;
- }
-
- requestKeyValuesMap[propertyNameOnRequest] = value;
- }
-
- if (queryStringAndFormData != null)
- {
- //Query String and form data can override variable path matches
- //path variables < query string < form data
- foreach (var name in queryStringAndFormData)
- {
- requestKeyValuesMap[name.Key] = name.Value;
- }
- }
-
- return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
- }
-
- public class RestPathMap : SortedDictionary<string, List<RestPath>>
- {
- public RestPathMap() : base(StringComparer.OrdinalIgnoreCase)
- {
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs b/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs
deleted file mode 100644
index d13935fba..000000000
--- a/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs
+++ /dev/null
@@ -1,128 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-
-namespace Emby.Server.Implementations.Services
-{
- /// <summary>
- /// Serializer cache of delegates required to create a type from a string map (e.g. for REST urls)
- /// </summary>
- public class StringMapTypeDeserializer
- {
- internal class PropertySerializerEntry
- {
- public PropertySerializerEntry(Action<object, object> propertySetFn, Func<string, object> propertyParseStringFn)
- {
- PropertySetFn = propertySetFn;
- PropertyParseStringFn = propertyParseStringFn;
- }
-
- public Action<object, object> PropertySetFn;
- public Func<string, object> PropertyParseStringFn;
- public Type PropertyType;
- }
-
- private readonly Type type;
- private readonly Dictionary<string, PropertySerializerEntry> propertySetterMap
- = new Dictionary<string, PropertySerializerEntry>(StringComparer.OrdinalIgnoreCase);
-
- public Func<string, object> GetParseFn(Type propertyType)
- {
- if (propertyType == typeof(string))
- return s => s;
-
- return _GetParseFn(propertyType);
- }
-
- private readonly Func<Type, object> _CreateInstanceFn;
- private readonly Func<Type, Func<string, object>> _GetParseFn;
-
- public StringMapTypeDeserializer(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type type)
- {
- _CreateInstanceFn = createInstanceFn;
- _GetParseFn = getParseFn;
- this.type = type;
-
- foreach (var propertyInfo in RestPath.GetSerializableProperties(type))
- {
- var propertySetFn = TypeAccessor.GetSetPropertyMethod(type, propertyInfo);
- var propertyType = propertyInfo.PropertyType;
- var propertyParseStringFn = GetParseFn(propertyType);
- var propertySerializer = new PropertySerializerEntry(propertySetFn, propertyParseStringFn) { PropertyType = propertyType };
-
- propertySetterMap[propertyInfo.Name] = propertySerializer;
- }
- }
-
- public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs)
- {
- string propertyName = null;
- string propertyTextValue = null;
- PropertySerializerEntry propertySerializerEntry = null;
-
- if (instance == null)
- instance = _CreateInstanceFn(type);
-
- foreach (var pair in keyValuePairs)
- {
- propertyName = pair.Key;
- propertyTextValue = pair.Value;
-
- if (string.IsNullOrEmpty(propertyTextValue))
- {
- continue;
- }
-
- if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
- {
- if (propertyName == "v")
- {
- continue;
- }
-
- continue;
- }
-
- if (propertySerializerEntry.PropertySetFn == null)
- {
- continue;
- }
-
- if (propertySerializerEntry.PropertyType == typeof(bool))
- {
- //InputExtensions.cs#530 MVC Checkbox helper emits extra hidden input field, generating 2 values, first is the real value
- propertyTextValue = LeftPart(propertyTextValue, ',');
- }
-
- var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
- if (value == null)
- {
- continue;
- }
- propertySerializerEntry.PropertySetFn(instance, value);
- }
-
- return instance;
- }
-
- public static string LeftPart(string strVal, char needle)
- {
- if (strVal == null) return null;
- var pos = strVal.IndexOf(needle);
- return pos == -1
- ? strVal
- : strVal.Substring(0, pos);
- }
- }
-
- internal class TypeAccessor
- {
- public static Action<object, object> GetSetPropertyMethod(Type type, PropertyInfo propertyInfo)
- {
- if (!propertyInfo.CanWrite || propertyInfo.GetIndexParameters().Length > 0) return null;
-
- var setMethodInfo = propertyInfo.SetMethod;
- return (instance, value) => setMethodInfo.Invoke(instance, new[] { value });
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/SwaggerService.cs b/Emby.Server.Implementations/Services/SwaggerService.cs
deleted file mode 100644
index 3e6970eef..000000000
--- a/Emby.Server.Implementations/Services/SwaggerService.cs
+++ /dev/null
@@ -1,247 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-namespace Emby.Server.Implementations.Services
-{
- [Route("/swagger", "GET", Summary = "Gets the swagger specifications")]
- [Route("/swagger.json", "GET", Summary = "Gets the swagger specifications")]
- public class GetSwaggerSpec : IReturn<SwaggerSpec>
- {
- }
-
- public class SwaggerSpec
- {
- public string swagger { get; set; }
- public string[] schemes { get; set; }
- public SwaggerInfo info { get; set; }
- public string host { get; set; }
- public string basePath { get; set; }
- public SwaggerTag[] tags { get; set; }
- public IDictionary<string, Dictionary<string, SwaggerMethod>> paths { get; set; }
- public Dictionary<string, SwaggerDefinition> definitions { get; set; }
- public SwaggerComponents components { get; set; }
- }
-
- public class SwaggerComponents
- {
- public Dictionary<string, SwaggerSecurityScheme> securitySchemes { get; set; }
- }
-
- public class SwaggerSecurityScheme
- {
- public string name { get; set; }
- public string type { get; set; }
- public string @in { get; set; }
- }
-
- public class SwaggerInfo
- {
- public string description { get; set; }
- public string version { get; set; }
- public string title { get; set; }
- public string termsOfService { get; set; }
-
- public SwaggerConcactInfo contact { get; set; }
- }
-
- public class SwaggerConcactInfo
- {
- public string email { get; set; }
- public string name { get; set; }
- public string url { get; set; }
- }
-
- public class SwaggerTag
- {
- public string description { get; set; }
- public string name { get; set; }
- }
-
- public class SwaggerMethod
- {
- public string summary { get; set; }
- public string description { get; set; }
- public string[] tags { get; set; }
- public string operationId { get; set; }
- public string[] consumes { get; set; }
- public string[] produces { get; set; }
- public SwaggerParam[] parameters { get; set; }
- public Dictionary<string, SwaggerResponse> responses { get; set; }
- public Dictionary<string, string[]>[] security { get; set; }
- }
-
- public class SwaggerParam
- {
- public string @in { get; set; }
- public string name { get; set; }
- public string description { get; set; }
- public bool required { get; set; }
- public string type { get; set; }
- public string collectionFormat { get; set; }
- }
-
- public class SwaggerResponse
- {
- public string description { get; set; }
-
- // ex. "$ref":"#/definitions/Pet"
- public Dictionary<string, string> schema { get; set; }
- }
-
- public class SwaggerDefinition
- {
- public string type { get; set; }
- public Dictionary<string, SwaggerProperty> properties { get; set; }
- }
-
- public class SwaggerProperty
- {
- public string type { get; set; }
- public string format { get; set; }
- public string description { get; set; }
- public string[] @enum { get; set; }
- public string @default { get; set; }
- }
-
- public class SwaggerService : IService, IRequiresRequest
- {
- private SwaggerSpec _spec;
-
- public IRequest Request { get; set; }
-
- public object Get(GetSwaggerSpec request)
- {
- return _spec ?? (_spec = GetSpec());
- }
-
- private SwaggerSpec GetSpec()
- {
- string host = null;
- Uri uri;
- if (Uri.TryCreate(Request.RawUrl, UriKind.Absolute, out uri))
- {
- host = uri.Host;
- }
-
- var securitySchemes = new Dictionary<string, SwaggerSecurityScheme>();
-
- securitySchemes["api_key"] = new SwaggerSecurityScheme
- {
- name = "api_key",
- type = "apiKey",
- @in = "query"
- };
-
- var spec = new SwaggerSpec
- {
- schemes = new[] { "http" },
- tags = GetTags(),
- swagger = "2.0",
- info = new SwaggerInfo
- {
- title = "Jellyfin Server API",
- version = "1.0.0",
- description = "Explore the Jellyfin Server API",
- contact = new SwaggerConcactInfo
- {
- name = "Jellyfin Community",
- url = "https://jellyfin.readthedocs.io/en/latest/user-docs/getting-help/"
- }
- },
- paths = GetPaths(),
- definitions = GetDefinitions(),
- basePath = "/jellyfin",
- host = host,
-
- components = new SwaggerComponents
- {
- securitySchemes = securitySchemes
- }
- };
-
- return spec;
- }
-
-
- private SwaggerTag[] GetTags()
- {
- return new SwaggerTag[] { };
- }
-
- private Dictionary<string, SwaggerDefinition> GetDefinitions()
- {
- return new Dictionary<string, SwaggerDefinition>();
- }
-
- private IDictionary<string, Dictionary<string, SwaggerMethod>> GetPaths()
- {
- var paths = new SortedDictionary<string, Dictionary<string, SwaggerMethod>>();
-
- var all = ServiceController.Instance.RestPathMap.OrderBy(i => i.Key, StringComparer.OrdinalIgnoreCase).ToList();
-
- foreach (var current in all)
- {
- foreach (var info in current.Value)
- {
- if (info.IsHidden)
- {
- continue;
- }
-
- if (info.Path.StartsWith("/mediabrowser", StringComparison.OrdinalIgnoreCase))
- {
- continue;
- }
- if (info.Path.StartsWith("/jellyfin", StringComparison.OrdinalIgnoreCase))
- {
- continue;
- }
-
- paths[info.Path] = GetPathInfo(info);
- }
- }
-
- return paths;
- }
-
- private Dictionary<string, SwaggerMethod> GetPathInfo(RestPath info)
- {
- var result = new Dictionary<string, SwaggerMethod>();
-
- foreach (var verb in info.Verbs)
- {
- var responses = new Dictionary<string, SwaggerResponse>
- {
- { "200", new SwaggerResponse { description = "OK" } }
- };
-
- var apiKeySecurity = new Dictionary<string, string[]>
- {
- { "api_key", Array.Empty<string>() }
- };
-
- result[verb.ToLowerInvariant()] = new SwaggerMethod
- {
- summary = info.Summary,
- description = info.Description,
- produces = new[] { "application/json" },
- consumes = new[] { "application/json" },
- operationId = info.RequestType.Name,
- tags = Array.Empty<string>(),
-
- parameters = Array.Empty<SwaggerParam>(),
-
- responses = responses,
-
- security = new [] { apiKeySecurity }
- };
- }
-
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/Services/UrlExtensions.cs b/Emby.Server.Implementations/Services/UrlExtensions.cs
deleted file mode 100644
index 8899fbfa3..000000000
--- a/Emby.Server.Implementations/Services/UrlExtensions.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System;
-
-namespace Emby.Server.Implementations.Services
-{
- /// <summary>
- /// Donated by Ivan Korneliuk from his post:
- /// http://korneliuk.blogspot.com/2012/08/servicestack-reusing-dtos.html
- ///
- /// Modified to only allow using routes matching the supplied HTTP Verb
- /// </summary>
- public static class UrlExtensions
- {
- public static string GetMethodName(this Type type)
- {
- var typeName = type.FullName != null //can be null, e.g. generic types
- ? LeftPart(type.FullName, "[[") //Generic Fullname
- .Replace(type.Namespace + ".", "") //Trim Namespaces
- .Replace("+", ".") //Convert nested into normal type
- : type.Name;
-
- return type.IsGenericParameter ? "'" + typeName : typeName;
- }
-
- private static string LeftPart(string strVal, string needle)
- {
- if (strVal == null) return null;
- var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
- return pos == -1
- ? strVal
- : strVal.Substring(0, pos);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Session/HttpSessionController.cs b/Emby.Server.Implementations/Session/HttpSessionController.cs
deleted file mode 100644
index 9281f82b3..000000000
--- a/Emby.Server.Implementations/Session/HttpSessionController.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Session;
-
-namespace Emby.Server.Implementations.Session
-{
- public class HttpSessionController : ISessionController
- {
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
- private readonly ISessionManager _sessionManager;
-
- public SessionInfo Session { get; private set; }
-
- private readonly string _postUrl;
-
- public HttpSessionController(IHttpClient httpClient,
- IJsonSerializer json,
- SessionInfo session,
- string postUrl, ISessionManager sessionManager)
- {
- _httpClient = httpClient;
- _json = json;
- Session = session;
- _postUrl = postUrl;
- _sessionManager = sessionManager;
- }
-
- private string PostUrl => string.Format("http://{0}{1}", Session.RemoteEndPoint, _postUrl);
-
- public bool IsSessionActive => (DateTime.UtcNow - Session.LastActivityDate).TotalMinutes <= 5;
-
- public bool SupportsMediaControl => true;
-
- private Task SendMessage(string name, string messageId, CancellationToken cancellationToken)
- {
- return SendMessage(name, messageId, new Dictionary<string, string>(), cancellationToken);
- }
-
- private Task SendMessage(string name, string messageId, Dictionary<string, string> args, CancellationToken cancellationToken)
- {
- args["messageId"] = messageId;
- var url = PostUrl + "/" + name + ToQueryString(args);
-
- return SendRequest(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = false
- });
- }
-
- private Task SendPlayCommand(PlayRequest command, string messageId, CancellationToken cancellationToken)
- {
- var dict = new Dictionary<string, string>();
-
- dict["ItemIds"] = string.Join(",", command.ItemIds.Select(i => i.ToString("N")).ToArray());
-
- if (command.StartPositionTicks.HasValue)
- {
- dict["StartPositionTicks"] = command.StartPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
- }
- if (command.AudioStreamIndex.HasValue)
- {
- dict["AudioStreamIndex"] = command.AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture);
- }
- if (command.SubtitleStreamIndex.HasValue)
- {
- dict["SubtitleStreamIndex"] = command.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture);
- }
- if (command.StartIndex.HasValue)
- {
- dict["StartIndex"] = command.StartIndex.Value.ToString(CultureInfo.InvariantCulture);
- }
- if (!string.IsNullOrEmpty(command.MediaSourceId))
- {
- dict["MediaSourceId"] = command.MediaSourceId;
- }
-
- return SendMessage(command.PlayCommand.ToString(), messageId, dict, cancellationToken);
- }
-
- private Task SendPlaystateCommand(PlaystateRequest command, string messageId, CancellationToken cancellationToken)
- {
- var args = new Dictionary<string, string>();
-
- if (command.Command == PlaystateCommand.Seek)
- {
- if (!command.SeekPositionTicks.HasValue)
- {
- throw new ArgumentException("SeekPositionTicks cannot be null");
- }
-
- args["SeekPositionTicks"] = command.SeekPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
- }
-
- return SendMessage(command.Command.ToString(), messageId, args, cancellationToken);
- }
-
- private string[] _supportedMessages = new string[] { };
- public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
- {
- if (!IsSessionActive)
- {
- return Task.CompletedTask;
- }
-
- if (string.Equals(name, "Play", StringComparison.OrdinalIgnoreCase))
- {
- return SendPlayCommand(data as PlayRequest, messageId, cancellationToken);
- }
- if (string.Equals(name, "PlayState", StringComparison.OrdinalIgnoreCase))
- {
- return SendPlaystateCommand(data as PlaystateRequest, messageId, cancellationToken);
- }
- if (string.Equals(name, "GeneralCommand", StringComparison.OrdinalIgnoreCase))
- {
- var command = data as GeneralCommand;
- return SendMessage(command.Name, messageId, command.Arguments, cancellationToken);
- }
-
- if (!_supportedMessages.Contains(name, StringComparer.OrdinalIgnoreCase))
- {
- return Task.CompletedTask;
- }
-
- var url = PostUrl + "/" + name;
-
- url += "?messageId=" + messageId;
-
- var options = new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = false
- };
-
- if (data != null)
- {
- if (typeof(T) == typeof(string))
- {
- var str = data as string;
- if (!string.IsNullOrEmpty(str))
- {
- options.RequestContent = str;
- options.RequestContentType = "application/json";
- }
- }
- else
- {
- options.RequestContent = _json.SerializeToString(data);
- options.RequestContentType = "application/json";
- }
- }
-
- return SendRequest(options);
- }
-
- private async Task SendRequest(HttpRequestOptions options)
- {
- using (var response = await _httpClient.Post(options).ConfigureAwait(false))
- {
-
- }
- }
-
- private static string ToQueryString(Dictionary<string, string> nvc)
- {
- var array = (from item in nvc
- select string.Format("{0}={1}", WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)))
- .ToArray();
-
- var args = string.Join("&", array);
-
- if (string.IsNullOrEmpty(args))
- {
- return args;
- }
-
- return "?" + args;
- }
- }
-}
diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs
index fa0ab62d3..341d2c8e6 100644
--- a/Emby.Server.Implementations/Session/SessionManager.cs
+++ b/Emby.Server.Implementations/Session/SessionManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -5,125 +9,139 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Session;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
namespace Emby.Server.Implementations.Session
{
/// <summary>
- /// Class SessionManager
+ /// Class SessionManager.
/// </summary>
public class SessionManager : ISessionManager, IDisposable
{
- /// <summary>
- /// The _user data repository
- /// </summary>
private readonly IUserDataManager _userDataManager;
-
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
+ private readonly ILogger<SessionManager> _logger;
+ private readonly IEventManager _eventManager;
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
private readonly IMusicManager _musicManager;
private readonly IDtoService _dtoService;
private readonly IImageProcessor _imageProcessor;
private readonly IMediaSourceManager _mediaSourceManager;
-
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _jsonSerializer;
private readonly IServerApplicationHost _appHost;
-
- private readonly IAuthenticationRepository _authRepo;
private readonly IDeviceManager _deviceManager;
/// <summary>
- /// The _active connections
+ /// The active connections.
/// </summary>
- private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
- new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections = new (StringComparer.OrdinalIgnoreCase);
- public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
-
- public event EventHandler<GenericEventArgs<AuthenticationResult>> AuthenticationSucceeded;
-
- /// <summary>
- /// Occurs when [playback start].
- /// </summary>
- public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
- /// <summary>
- /// Occurs when [playback progress].
- /// </summary>
- public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
- /// <summary>
- /// Occurs when [playback stopped].
- /// </summary>
- public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
+ private Timer _idleTimer;
- public event EventHandler<SessionEventArgs> SessionStarted;
- public event EventHandler<SessionEventArgs> CapabilitiesChanged;
- public event EventHandler<SessionEventArgs> SessionEnded;
- public event EventHandler<SessionEventArgs> SessionActivity;
+ private DtoOptions _itemInfoDtoOptions;
+ private bool _disposed = false;
public SessionManager(
+ ILogger<SessionManager> logger,
+ IEventManager eventManager,
IUserDataManager userDataManager,
- ILoggerFactory loggerFactory,
ILibraryManager libraryManager,
IUserManager userManager,
IMusicManager musicManager,
IDtoService dtoService,
IImageProcessor imageProcessor,
- IJsonSerializer jsonSerializer,
IServerApplicationHost appHost,
- IHttpClient httpClient,
- IAuthenticationRepository authRepo,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager)
{
+ _logger = logger;
+ _eventManager = eventManager;
_userDataManager = userDataManager;
- _logger = loggerFactory.CreateLogger(nameof(SessionManager));
_libraryManager = libraryManager;
_userManager = userManager;
_musicManager = musicManager;
_dtoService = dtoService;
_imageProcessor = imageProcessor;
- _jsonSerializer = jsonSerializer;
_appHost = appHost;
- _httpClient = httpClient;
- _authRepo = authRepo;
_deviceManager = deviceManager;
_mediaSourceManager = mediaSourceManager;
- _deviceManager.DeviceOptionsUpdated += _deviceManager_DeviceOptionsUpdated;
+
+ _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated;
}
- private void _deviceManager_DeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
+ /// <inheritdoc />
+ public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
+
+ /// <inheritdoc />
+ public event EventHandler<GenericEventArgs<AuthenticationResult>> AuthenticationSucceeded;
+
+ /// <summary>
+ /// Occurs when playback has started.
+ /// </summary>
+ public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
+
+ /// <summary>
+ /// Occurs when playback has progressed.
+ /// </summary>
+ public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
+
+ /// <summary>
+ /// Occurs when playback has stopped.
+ /// </summary>
+ public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
+
+ /// <inheritdoc />
+ public event EventHandler<SessionEventArgs> SessionStarted;
+
+ /// <inheritdoc />
+ public event EventHandler<SessionEventArgs> CapabilitiesChanged;
+
+ /// <inheritdoc />
+ public event EventHandler<SessionEventArgs> SessionEnded;
+
+ /// <inheritdoc />
+ public event EventHandler<SessionEventArgs> SessionActivity;
+
+ /// <inheritdoc />
+ public event EventHandler<SessionEventArgs> SessionControllerConnected;
+
+ /// <summary>
+ /// Gets all connections.
+ /// </summary>
+ /// <value>All connections.</value>
+ public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate);
+
+ private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
{
foreach (var session in Sessions)
{
- if (string.Equals(session.DeviceId, e.Argument.Item1))
+ if (string.Equals(session.DeviceId, e.Argument.Item1, StringComparison.Ordinal))
{
if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName))
{
@@ -138,14 +156,37 @@ namespace Emby.Server.Implementations.Session
}
}
- private bool _disposed;
+ /// <inheritdoc />
public void Dispose()
{
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
+ {
+ _idleTimer?.Dispose();
+ }
+
+ _idleTimer = null;
+
+ _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated;
+
_disposed = true;
- _deviceManager.DeviceOptionsUpdated -= _deviceManager_DeviceOptionsUpdated;
}
- public void CheckDisposed()
+ private void CheckDisposed()
{
if (_disposed)
{
@@ -153,17 +194,11 @@ namespace Emby.Server.Implementations.Session
}
}
- /// <summary>
- /// Gets all connections.
- /// </summary>
- /// <value>All connections.</value>
- public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList();
-
private void OnSessionStarted(SessionInfo info)
{
if (!string.IsNullOrEmpty(info.DeviceId))
{
- var capabilities = GetSavedCapabilities(info.DeviceId);
+ var capabilities = _deviceManager.GetCapabilities(info.DeviceId);
if (capabilities != null)
{
@@ -171,33 +206,41 @@ namespace Emby.Server.Implementations.Session
}
}
- EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
- {
- SessionInfo = info
+ _eventManager.Publish(new SessionStartedEventArgs(info));
- }, _logger);
+ EventHelper.QueueEventIfNotNull(
+ SessionStarted,
+ this,
+ new SessionEventArgs
+ {
+ SessionInfo = info
+ },
+ _logger);
}
private void OnSessionEnded(SessionInfo info)
{
- EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
- {
- SessionInfo = info
+ EventHelper.QueueEventIfNotNull(
+ SessionEnded,
+ this,
+ new SessionEventArgs
+ {
+ SessionInfo = info
+ },
+ _logger);
- }, _logger);
+ _eventManager.Publish(new SessionEndedEventArgs(info));
info.Dispose();
}
- public void UpdateDeviceName(string sessionId, string deviceName)
+ /// <inheritdoc />
+ public void UpdateDeviceName(string sessionId, string reportedDeviceName)
{
var session = GetSession(sessionId);
-
- var key = GetSessionKey(session.Client, session.DeviceId);
-
if (session != null)
{
- session.DeviceName = deviceName;
+ session.DeviceName = reportedDeviceName;
}
}
@@ -210,10 +253,9 @@ namespace Emby.Server.Implementations.Session
/// <param name="deviceName">Name of the device.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="UnauthorizedAccessException"></exception>
- public SessionInfo LogSessionActivity(string appName,
+ /// <returns>SessionInfo.</returns>
+ public async Task<SessionInfo> LogSessionActivity(
+ string appName,
string appVersion,
string deviceId,
string deviceName,
@@ -226,61 +268,80 @@ namespace Emby.Server.Implementations.Session
{
throw new ArgumentNullException(nameof(appName));
}
+
if (string.IsNullOrEmpty(appVersion))
{
throw new ArgumentNullException(nameof(appVersion));
}
+
if (string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
}
var activityDate = DateTime.UtcNow;
- var session = GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
+ var session = await GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
var lastActivityDate = session.LastActivityDate;
session.LastActivityDate = activityDate;
if (user != null)
{
var userLastActivityDate = user.LastActivityDate ?? DateTime.MinValue;
- user.LastActivityDate = activityDate;
if ((activityDate - userLastActivityDate).TotalSeconds > 60)
{
try
{
- _userManager.UpdateUser(user);
+ user.LastActivityDate = activityDate;
+ await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
}
- catch (Exception ex)
+ catch (DbUpdateConcurrencyException e)
{
- _logger.LogError("Error updating user", ex);
+ _logger.LogDebug(e, "Error updating user's last activity date.");
}
}
}
if ((activityDate - lastActivityDate).TotalSeconds > 10)
{
- SessionActivity?.Invoke(this, new SessionEventArgs
- {
- SessionInfo = session
- });
+ SessionActivity?.Invoke(
+ this,
+ new SessionEventArgs
+ {
+ SessionInfo = session
+ });
}
return session;
}
+ /// <inheritdoc />
+ public void OnSessionControllerConnected(SessionInfo session)
+ {
+ EventHelper.QueueEventIfNotNull(
+ SessionControllerConnected,
+ this,
+ new SessionEventArgs
+ {
+ SessionInfo = session
+ },
+ _logger);
+ }
+
+ /// <inheritdoc />
public void CloseIfNeeded(SessionInfo session)
{
if (!session.SessionControllers.Any(i => i.IsSessionActive))
{
var key = GetSessionKey(session.Client, session.DeviceId);
- _activeConnections.TryRemove(key, out var removed);
+ _activeConnections.TryRemove(key, out _);
OnSessionEnded(session);
}
}
+ /// <inheritdoc />
public void ReportSessionEnded(string sessionId)
{
CheckDisposed();
@@ -290,7 +351,7 @@ namespace Emby.Server.Implementations.Session
{
var key = GetSessionKey(session.Client, session.DeviceId);
- _activeConnections.TryRemove(key, out var removed);
+ _activeConnections.TryRemove(key, out _);
OnSessionEnded(session);
}
@@ -304,11 +365,12 @@ namespace Emby.Server.Implementations.Session
/// <summary>
/// Updates the now playing item id.
/// </summary>
+ /// <returns>Task.</returns>
private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bool updateLastCheckInTime)
{
if (string.IsNullOrEmpty(info.MediaSourceId))
{
- info.MediaSourceId = info.ItemId.ToString("N");
+ info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture);
}
if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
@@ -320,8 +382,7 @@ namespace Emby.Server.Implementations.Session
var runtimeTicks = libraryItem.RunTimeTicks;
MediaSourceInfo mediaSource = null;
- var hasMediaSources = libraryItem as IHasMediaSources;
- if (hasMediaSources != null)
+ if (libraryItem is IHasMediaSources)
{
mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
@@ -373,7 +434,6 @@ namespace Emby.Server.Implementations.Session
/// Removes the now playing item id.
/// </summary>
/// <param name="session">The session.</param>
- /// <exception cref="ArgumentNullException">item</exception>
private void RemoveNowPlayingItem(SessionInfo session)
{
session.NowPlayingItem = null;
@@ -386,9 +446,7 @@ namespace Emby.Server.Implementations.Session
}
private static string GetSessionKey(string appName, string deviceId)
- {
- return appName + deviceId;
- }
+ => appName + deviceId;
/// <summary>
/// Gets the connection.
@@ -400,7 +458,13 @@ namespace Emby.Server.Implementations.Session
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="user">The user.</param>
/// <returns>SessionInfo.</returns>
- private SessionInfo GetSessionInfo(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
+ private async Task<SessionInfo> GetSessionInfo(
+ string appName,
+ string appVersion,
+ string deviceId,
+ string deviceName,
+ string remoteEndPoint,
+ User user)
{
CheckDisposed();
@@ -408,18 +472,20 @@ namespace Emby.Server.Implementations.Session
{
throw new ArgumentNullException(nameof(deviceId));
}
+
var key = GetSessionKey(appName, deviceId);
CheckDisposed();
- var sessionInfo = _activeConnections.GetOrAdd(key, k =>
+ if (!_activeConnections.TryGetValue(key, out var sessionInfo))
{
- return CreateSession(k, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
- });
+ _activeConnections[key] = await CreateSession(key, appName, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
+ sessionInfo = _activeConnections[key];
+ }
- sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
- sessionInfo.UserName = user == null ? null : user.Name;
- sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
+ sessionInfo.UserId = user?.Id ?? Guid.Empty;
+ sessionInfo.UserName = user?.Username;
+ sessionInfo.UserPrimaryImageTag = user?.ProfileImage == null ? null : GetImageCacheTag(user);
sessionInfo.RemoteEndPoint = remoteEndPoint;
sessionInfo.Client = appName;
@@ -432,28 +498,35 @@ namespace Emby.Server.Implementations.Session
if (user == null)
{
- sessionInfo.AdditionalUsers = new SessionUserInfo[] { };
+ sessionInfo.AdditionalUsers = Array.Empty<SessionUserInfo>();
}
return sessionInfo;
}
- private SessionInfo CreateSession(string key, string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
+ private async Task<SessionInfo> CreateSession(
+ string key,
+ string appName,
+ string appVersion,
+ string deviceId,
+ string deviceName,
+ string remoteEndPoint,
+ User user)
{
var sessionInfo = new SessionInfo(this, _logger)
{
Client = appName,
DeviceId = deviceId,
ApplicationVersion = appVersion,
- Id = key.GetMD5().ToString("N"),
+ Id = key.GetMD5().ToString("N", CultureInfo.InvariantCulture),
ServerId = _appHost.SystemId
};
- var username = user == null ? null : user.Name;
+ var username = user?.Username;
- sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
+ sessionInfo.UserId = user?.Id ?? Guid.Empty;
sessionInfo.UserName = username;
- sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
+ sessionInfo.UserPrimaryImageTag = user?.ProfileImage == null ? null : GetImageCacheTag(user);
sessionInfo.RemoteEndPoint = remoteEndPoint;
if (string.IsNullOrEmpty(deviceName))
@@ -461,7 +534,7 @@ namespace Emby.Server.Implementations.Session
deviceName = "Network Device";
}
- var deviceOptions = _deviceManager.GetDeviceOptions(deviceId);
+ var deviceOptions = await _deviceManager.GetDeviceOptions(deviceId).ConfigureAwait(false);
if (string.IsNullOrEmpty(deviceOptions.CustomName))
{
sessionInfo.DeviceName = deviceName;
@@ -480,7 +553,7 @@ namespace Emby.Server.Implementations.Session
{
var users = new List<User>();
- if (!session.UserId.Equals(Guid.Empty))
+ if (session.UserId != Guid.Empty)
{
var user = _userManager.GetUserById(session.UserId);
@@ -499,15 +572,11 @@ namespace Emby.Server.Implementations.Session
return users;
}
- private Timer _idleTimer;
-
private void StartIdleCheckTimer()
{
- if (_idleTimer == null)
- {
- _idleTimer = new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
- }
+ _idleTimer ??= new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
}
+
private void StopIdleCheckTimer()
{
if (_idleTimer != null)
@@ -539,9 +608,9 @@ namespace Emby.Server.Implementations.Session
Item = session.NowPlayingItem,
ItemId = session.NowPlayingItem == null ? Guid.Empty : session.NowPlayingItem.Id,
SessionId = session.Id,
- MediaSourceId = session.PlayState == null ? null : session.PlayState.MediaSourceId,
- PositionTicks = session.PlayState == null ? null : session.PlayState.PositionTicks
- });
+ MediaSourceId = session.PlayState?.MediaSourceId,
+ PositionTicks = session.PlayState?.PositionTicks
+ }).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -575,11 +644,11 @@ namespace Emby.Server.Implementations.Session
}
/// <summary>
- /// Used to report that playback has started for an item
+ /// Used to report that playback has started for an item.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">info</exception>
+ /// <exception cref="ArgumentNullException"><c>info</c> is <c>null</c>.</exception>
public async Task OnPlaybackStart(PlaybackStartInfo info)
{
CheckDisposed();
@@ -591,7 +660,7 @@ namespace Emby.Server.Implementations.Session
var session = GetSession(info.SessionId);
- var libraryItem = info.ItemId.Equals(Guid.Empty)
+ var libraryItem = info.ItemId == Guid.Empty
? null
: GetNowPlayingItem(session, info.ItemId);
@@ -614,9 +683,7 @@ namespace Emby.Server.Implementations.Session
}
}
- // Nothing to save here
- // Fire events to inform plugins
- EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
+ var eventArgs = new PlaybackStartEventArgs
{
Item = libraryItem,
Users = users,
@@ -626,8 +693,17 @@ namespace Emby.Server.Implementations.Session
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
+ };
- }, _logger);
+ await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false);
+
+ // Nothing to save here
+ // Fire events to inform plugins
+ EventHelper.QueueEventIfNotNull(
+ PlaybackStart,
+ this,
+ eventArgs,
+ _logger);
StartIdleCheckTimer();
}
@@ -644,12 +720,9 @@ namespace Emby.Server.Implementations.Session
data.PlayCount++;
data.LastPlayedDate = DateTime.UtcNow;
- if (item.SupportsPlayedStatus)
+ if (item.SupportsPlayedStatus && !item.SupportsPositionTicksResume)
{
- if (!(item is Video))
- {
- data.Played = true;
- }
+ data.Played = true;
}
else
{
@@ -659,14 +732,18 @@ namespace Emby.Server.Implementations.Session
_userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None);
}
+ /// <inheritdoc />
public Task OnPlaybackProgress(PlaybackProgressInfo info)
{
return OnPlaybackProgress(info, false);
}
/// <summary>
- /// Used to report playback progress for an item
+ /// Used to report playback progress for an item.
/// </summary>
+ /// <param name="info">The playback progress info.</param>
+ /// <param name="isAutomated">Whether this is an automated update.</param>
+ /// <returns>Task.</returns>
public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated)
{
CheckDisposed();
@@ -695,7 +772,7 @@ namespace Emby.Server.Implementations.Session
}
}
- PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
+ var eventArgs = new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
@@ -709,7 +786,11 @@ namespace Emby.Server.Implementations.Session
PlaySessionId = info.PlaySessionId,
IsAutomated = isAutomated,
Session = session
- });
+ };
+
+ await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false);
+
+ PlaybackProgress?.Invoke(this, eventArgs);
if (!isAutomated)
{
@@ -743,14 +824,13 @@ namespace Emby.Server.Implementations.Session
{
_userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None);
}
-
}
private static bool UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data)
{
var changed = false;
- if (user.Configuration.RememberAudioSelections)
+ if (user.RememberAudioSelections)
{
if (data.AudioStreamIndex != info.AudioStreamIndex)
{
@@ -767,7 +847,7 @@ namespace Emby.Server.Implementations.Session
}
}
- if (user.Configuration.RememberSubtitleSelections)
+ if (user.RememberSubtitleSelections)
{
if (data.SubtitleStreamIndex != info.SubtitleStreamIndex)
{
@@ -788,12 +868,12 @@ namespace Emby.Server.Implementations.Session
}
/// <summary>
- /// Used to report that playback has ended for an item
+ /// Used to report that playback has ended for an item.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">info</exception>
- /// <exception cref="ArgumentOutOfRangeException">positionTicks</exception>
+ /// <exception cref="ArgumentNullException"><c>info</c> is <c>null</c>.</exception>
+ /// <exception cref="ArgumentOutOfRangeException"><c>info.PositionTicks</c> is <c>null</c> or negative.</exception>
public async Task OnPlaybackStopped(PlaybackStopInfo info)
{
CheckDisposed();
@@ -819,7 +899,7 @@ namespace Emby.Server.Implementations.Session
// Normalize
if (string.IsNullOrEmpty(info.MediaSourceId))
{
- info.MediaSourceId = info.ItemId.ToString("N");
+ info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture);
}
if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
@@ -830,8 +910,7 @@ namespace Emby.Server.Implementations.Session
{
MediaSourceInfo mediaSource = null;
- var hasMediaSources = libraryItem as IHasMediaSources;
- if (hasMediaSources != null)
+ if (libraryItem is IHasMediaSources)
{
mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
}
@@ -848,7 +927,8 @@ namespace Emby.Server.Implementations.Session
{
var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
- _logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
+ _logger.LogInformation(
+ "Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
session.Client,
session.ApplicationVersion,
info.Item.Name,
@@ -887,7 +967,7 @@ namespace Emby.Server.Implementations.Session
}
}
- EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
+ var eventArgs = new PlaybackStopEventArgs
{
Item = libraryItem,
Users = users,
@@ -899,8 +979,11 @@ namespace Emby.Server.Implementations.Session
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
+ };
+
+ await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false);
- }, _logger);
+ EventHelper.QueueEventIfNotNull(PlaybackStopped, this, eventArgs, _logger);
}
private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed)
@@ -936,14 +1019,17 @@ namespace Emby.Server.Implementations.Session
/// <param name="sessionId">The session identifier.</param>
/// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
/// <returns>SessionInfo.</returns>
- /// <exception cref="ResourceNotFoundException"></exception>
+ /// <exception cref="ResourceNotFoundException">
+ /// No session with an Id equal to <c>sessionId</c> was found
+ /// and <c>throwOnMissing</c> is <c>true</c>.
+ /// </exception>
private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
{
- var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
-
+ var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
if (session == null && throwOnMissing)
{
- throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
+ throw new ResourceNotFoundException(
+ string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId));
}
return session;
@@ -952,23 +1038,25 @@ namespace Emby.Server.Implementations.Session
private SessionInfo GetSessionToRemoteControl(string sessionId)
{
// Accept either device id or session id
- var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
+ var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
if (session == null)
{
- throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
+ throw new ResourceNotFoundException(
+ string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId));
}
return session;
}
+ /// <inheritdoc />
public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
{
CheckDisposed();
var generalCommand = new GeneralCommand
{
- Name = GeneralCommandType.DisplayMessage.ToString()
+ Name = GeneralCommandType.DisplayMessage
};
generalCommand.Arguments["Header"] = command.Header;
@@ -982,6 +1070,7 @@ namespace Emby.Server.Implementations.Session
return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
}
+ /// <inheritdoc />
public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
{
CheckDisposed();
@@ -994,27 +1083,46 @@ namespace Emby.Server.Implementations.Session
AssertCanControl(session, controllingSession);
}
- return SendMessageToSession(session, "GeneralCommand", command, cancellationToken);
+ return SendMessageToSession(session, SessionMessageType.GeneralCommand, command, cancellationToken);
}
- private static async Task SendMessageToSession<T>(SessionInfo session, string name, T data, CancellationToken cancellationToken)
+ private static async Task SendMessageToSession<T>(SessionInfo session, SessionMessageType name, T data, CancellationToken cancellationToken)
{
- var controllers = session.SessionControllers.ToArray();
- var messageId = Guid.NewGuid().ToString("N");
+ var controllers = session.SessionControllers;
+ var messageId = Guid.NewGuid();
foreach (var controller in controllers)
{
- await controller.SendMessage(name, messageId, data, controllers, cancellationToken).ConfigureAwait(false);
+ await controller.SendMessage(name, messageId, data, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private static Task SendMessageToSessions<T>(IEnumerable<SessionInfo> sessions, SessionMessageType name, T data, CancellationToken cancellationToken)
+ {
+ IEnumerable<Task> GetTasks()
+ {
+ var messageId = Guid.NewGuid();
+ foreach (var session in sessions)
+ {
+ var controllers = session.SessionControllers;
+ foreach (var controller in controllers)
+ {
+ yield return controller.SendMessage(name, messageId, data, cancellationToken);
+ }
+ }
}
+
+ return Task.WhenAll(GetTasks());
}
+ /// <inheritdoc />
public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
{
CheckDisposed();
var session = GetSessionToRemoteControl(sessionId);
- var user = !session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(session.UserId) : null;
+ var user = session.UserId == Guid.Empty ? null : _userManager.GetUserById(session.UserId);
List<BaseItem> items;
@@ -1039,7 +1147,7 @@ namespace Emby.Server.Implementations.Session
if (command.PlayCommand == PlayCommand.PlayShuffle)
{
- items = items.OrderBy(i => Guid.NewGuid()).ToList();
+ items.Shuffle();
command.PlayCommand = PlayCommand.PlayNow;
}
@@ -1049,30 +1157,32 @@ namespace Emby.Server.Implementations.Session
{
if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
{
- throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
+ throw new ArgumentException(
+ string.Format(CultureInfo.InvariantCulture, "{0} is not allowed to play media.", user.Username));
}
}
- if (user != null && command.ItemIds.Length == 1 && user.Configuration.EnableNextEpisodeAutoPlay)
+ if (user != null
+ && command.ItemIds.Length == 1
+ && user.EnableNextEpisodeAutoPlay
+ && _libraryManager.GetItemById(command.ItemIds[0]) is Episode episode)
{
- var episode = _libraryManager.GetItemById(command.ItemIds[0]) as Episode;
- if (episode != null)
+ var series = episode.Series;
+ if (series != null)
{
- var series = episode.Series;
- if (series != null)
+ var episodes = series.GetEpisodes(
+ user,
+ new DtoOptions(false)
+ {
+ EnableImages = false
+ })
+ .Where(i => !i.IsVirtualItem)
+ .SkipWhile(i => i.Id != episode.Id)
+ .ToList();
+
+ if (episodes.Count > 0)
{
- var episodes = series.GetEpisodes(user, new DtoOptions(false)
- {
- EnableImages = false
- })
- .Where(i => !i.IsVirtualItem)
- .SkipWhile(i => i.Id != episode.Id)
- .ToList();
-
- if (episodes.Count > 0)
- {
- command.ItemIds = episodes.Select(i => i.Id).ToArray();
- }
+ command.ItemIds = episodes.Select(i => i.Id).ToArray();
}
}
}
@@ -1087,22 +1197,36 @@ namespace Emby.Server.Implementations.Session
}
}
- await SendMessageToSession(session, "Play", command, cancellationToken).ConfigureAwait(false);
+ await SendMessageToSession(session, SessionMessageType.Play, command, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+ var session = GetSession(sessionId);
+ await SendMessageToSession(session, SessionMessageType.SyncPlayCommand, command, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+ var session = GetSession(sessionId);
+ await SendMessageToSession(session, SessionMessageType.SyncPlayGroupUpdate, command, cancellationToken).ConfigureAwait(false);
}
- private IList<BaseItem> TranslateItemForPlayback(Guid id, User user)
+ private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user)
{
var item = _libraryManager.GetItemById(id);
if (item == null)
{
_logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
- return new List<BaseItem>();
+ return Array.Empty<BaseItem>();
}
- var byName = item as IItemByName;
-
- if (byName != null)
+ if (item is IItemByName byName)
{
return byName.GetTaggedItems(new InternalItemsQuery(user)
{
@@ -1111,13 +1235,13 @@ namespace Emby.Server.Implementations.Session
DtoOptions = new DtoOptions(false)
{
EnableImages = false,
- Fields = new ItemFields[]
+ Fields = new[]
{
ItemFields.SortName
}
},
IsVirtualItem = false,
- OrderBy = new ValueTuple<string, SortOrder>[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) }
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
});
}
@@ -1138,12 +1262,11 @@ namespace Emby.Server.Implementations.Session
}
},
IsVirtualItem = false,
- OrderBy = new ValueTuple<string, SortOrder>[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) }
-
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
});
}
- return new List<BaseItem> { item };
+ return new[] { item };
}
private IEnumerable<BaseItem> TranslateItemForInstantMix(Guid id, User user)
@@ -1152,27 +1275,31 @@ namespace Emby.Server.Implementations.Session
if (item == null)
{
- _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
+ _logger.LogError("A non-existent item Id {0} was passed into TranslateItemForInstantMix", id);
return new List<BaseItem>();
}
return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false });
}
+ /// <inheritdoc />
public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
{
var generalCommand = new GeneralCommand
{
- Name = GeneralCommandType.DisplayContent.ToString()
+ Name = GeneralCommandType.DisplayContent,
+ Arguments =
+ {
+ ["ItemId"] = command.ItemId,
+ ["ItemName"] = command.ItemName,
+ ["ItemType"] = command.ItemType
+ }
};
- generalCommand.Arguments["ItemId"] = command.ItemId;
- generalCommand.Arguments["ItemName"] = command.ItemName;
- generalCommand.Arguments["ItemType"] = command.ItemType;
-
return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
}
+ /// <inheritdoc />
public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
{
CheckDisposed();
@@ -1185,19 +1312,20 @@ namespace Emby.Server.Implementations.Session
AssertCanControl(session, controllingSession);
if (!controllingSession.UserId.Equals(Guid.Empty))
{
- command.ControllingUserId = controllingSession.UserId.ToString("N");
+ command.ControllingUserId = controllingSession.UserId.ToString("N", CultureInfo.InvariantCulture);
}
}
- return SendMessageToSession(session, "Playstate", command, cancellationToken);
+ return SendMessageToSession(session, SessionMessageType.Playstate, command, cancellationToken);
}
- private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
+ private static void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
{
if (session == null)
{
throw new ArgumentNullException(nameof(session));
}
+
if (controllingSession == null)
{
throw new ArgumentNullException(nameof(controllingSession));
@@ -1209,26 +1337,11 @@ namespace Emby.Server.Implementations.Session
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
+ public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
{
CheckDisposed();
- var sessions = Sessions.ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, "RestartRequired", string.Empty, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error in SendRestartRequiredNotification.", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- await Task.WhenAll(tasks).ConfigureAwait(false);
+ return SendMessageToSessions(Sessions, SessionMessageType.RestartRequired, string.Empty, cancellationToken);
}
/// <summary>
@@ -1240,22 +1353,7 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
- var sessions = Sessions.ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, "ServerShuttingDown", string.Empty, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error in SendServerShutdownNotification.", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
+ return SendMessageToSessions(Sessions, SessionMessageType.ServerShuttingDown, string.Empty, cancellationToken);
}
/// <summary>
@@ -1269,22 +1367,7 @@ namespace Emby.Server.Implementations.Session
_logger.LogDebug("Beginning SendServerRestartNotification");
- var sessions = Sessions.ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, "ServerRestarting", string.Empty, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error in SendServerRestartNotification.", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
+ return SendMessageToSessions(Sessions, SessionMessageType.ServerRestarting, string.Empty, cancellationToken);
}
/// <summary>
@@ -1300,12 +1383,12 @@ namespace Emby.Server.Implementations.Session
var session = GetSession(sessionId);
- if (session.UserId.Equals(userId))
+ if (session.UserId == userId)
{
throw new ArgumentException("The requested user is already the primary user of the session.");
}
- if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId)))
+ if (session.AdditionalUsers.All(i => i.UserId != userId))
{
var user = _userManager.GetUserById(userId);
@@ -1314,7 +1397,7 @@ namespace Emby.Server.Implementations.Session
list.Add(new SessionUserInfo
{
UserId = userId,
- UserName = user.Name
+ UserName = user.Username
});
session.AdditionalUsers = list.ToArray();
@@ -1353,14 +1436,19 @@ namespace Emby.Server.Implementations.Session
/// <summary>
/// Authenticates the new session.
/// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{SessionInfo}.</returns>
+ /// <param name="request">The authenticationrequest.</param>
+ /// <returns>The authentication result.</returns>
public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
{
return AuthenticateNewSessionInternal(request, true);
}
- public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
+ /// <summary>
+ /// Directly authenticates the session without enforcing password.
+ /// </summary>
+ /// <param name="request">The authentication request.</param>
+ /// <returns>The authentication result.</returns>
+ public Task<AuthenticationResult> AuthenticateDirect(AuthenticationRequest request)
{
return AuthenticateNewSessionInternal(request, false);
}
@@ -1370,52 +1458,52 @@ namespace Emby.Server.Implementations.Session
CheckDisposed();
User user = null;
- if (!request.UserId.Equals(Guid.Empty))
+ if (request.UserId != Guid.Empty)
{
- user = _userManager.Users
- .FirstOrDefault(i => i.Id == request.UserId);
+ user = _userManager.GetUserById(request.UserId);
}
- if (user == null)
+ user ??= _userManager.GetUserByName(request.Username);
+
+ if (enforcePassword)
{
- user = _userManager.Users
- .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
+ user = await _userManager.AuthenticateUser(
+ request.Username,
+ request.Password,
+ null,
+ request.RemoteEndPoint,
+ true).ConfigureAwait(false);
}
- if (user != null)
+ if (user == null)
{
- // TODO: Move this to userManager?
- if (!string.IsNullOrEmpty(request.DeviceId))
- {
- if (!_deviceManager.CanAccessDevice(user, request.DeviceId))
- {
- throw new SecurityException("User is not allowed access from this device.");
- }
- }
+ AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
+ throw new AuthenticationException("Invalid username or password entered.");
}
- if (enforcePassword)
+ if (!string.IsNullOrEmpty(request.DeviceId)
+ && !_deviceManager.CanAccessDevice(user, request.DeviceId))
{
- var result = await _userManager.AuthenticateUser(request.Username, request.Password, request.PasswordSha1, request.RemoteEndPoint, true).ConfigureAwait(false);
-
- if (result == null)
- {
- AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
-
- throw new SecurityException("Invalid user or password entered.");
- }
+ throw new SecurityException("User is not allowed access from this device.");
+ }
- user = result;
+ int sessionsCount = Sessions.Count(i => i.UserId.Equals(user.Id));
+ int maxActiveSessions = user.MaxActiveSessions;
+ _logger.LogInformation("Current/Max sessions for user {User}: {Sessions}/{Max}", user.Username, sessionsCount, maxActiveSessions);
+ if (maxActiveSessions >= 1 && sessionsCount >= maxActiveSessions)
+ {
+ throw new SecurityException("User is at their maximum number of sessions.");
}
- var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName);
+ var token = await GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
- var session = LogSessionActivity(request.App,
+ var session = await LogSessionActivity(
+ request.App,
request.AppVersion,
request.DeviceId,
request.DeviceName,
request.RemoteEndPoint,
- user);
+ user).ConfigureAwait(false);
var returnResult = new AuthenticationResult
{
@@ -1430,21 +1518,21 @@ namespace Emby.Server.Implementations.Session
return returnResult;
}
- private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName)
+ private async Task<string> GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName)
{
- var existing = _authRepo.Get(new AuthenticationInfoQuery
- {
- DeviceId = deviceId,
- UserId = user.Id,
- Limit = 1
-
- }).Items.FirstOrDefault();
-
- var allExistingForDevice = _authRepo.Get(new AuthenticationInfoQuery
- {
- DeviceId = deviceId
+ var existing = (await _deviceManager.GetDevices(
+ new DeviceQuery
+ {
+ DeviceId = deviceId,
+ UserId = user.Id,
+ Limit = 1
+ }).ConfigureAwait(false)).Items.FirstOrDefault();
- }).Items;
+ var allExistingForDevice = (await _deviceManager.GetDevices(
+ new DeviceQuery
+ {
+ DeviceId = deviceId
+ }).ConfigureAwait(false)).Items;
foreach (var auth in allExistingForDevice)
{
@@ -1452,43 +1540,29 @@ namespace Emby.Server.Implementations.Session
{
try
{
- Logout(auth);
+ await Logout(auth).ConfigureAwait(false);
}
- catch
+ catch (Exception ex)
{
-
+ _logger.LogError(ex, "Error while logging out.");
}
}
}
if (existing != null)
{
- _logger.LogInformation("Reissuing access token: " + existing.AccessToken);
+ _logger.LogInformation("Reissuing access token: {Token}", existing.AccessToken);
return existing.AccessToken;
}
- var now = DateTime.UtcNow;
-
- var newToken = new AuthenticationInfo
- {
- AppName = app,
- AppVersion = appVersion,
- DateCreated = now,
- DateLastActivity = now,
- DeviceId = deviceId,
- DeviceName = deviceName,
- UserId = user.Id,
- AccessToken = Guid.NewGuid().ToString("N"),
- UserName = user.Name
- };
-
_logger.LogInformation("Creating new access token for user {0}", user.Id);
- _authRepo.Create(newToken);
+ var device = await _deviceManager.CreateDevice(new Device(user.Id, app, appVersion, deviceName, deviceId)).ConfigureAwait(false);
- return newToken.AccessToken;
+ return device.AccessToken;
}
- public void Logout(string accessToken)
+ /// <inheritdoc />
+ public async Task Logout(string accessToken)
{
CheckDisposed();
@@ -1497,29 +1571,30 @@ namespace Emby.Server.Implementations.Session
throw new ArgumentNullException(nameof(accessToken));
}
- var existing = _authRepo.Get(new AuthenticationInfoQuery
- {
- Limit = 1,
- AccessToken = accessToken
-
- }).Items.FirstOrDefault();
+ var existing = (await _deviceManager.GetDevices(
+ new DeviceQuery
+ {
+ Limit = 1,
+ AccessToken = accessToken
+ }).ConfigureAwait(false)).Items;
- if (existing != null)
+ if (existing.Count > 0)
{
- Logout(existing);
+ await Logout(existing[0]).ConfigureAwait(false);
}
}
- public void Logout(AuthenticationInfo existing)
+ /// <inheritdoc />
+ public async Task Logout(Device device)
{
CheckDisposed();
- _logger.LogInformation("Logging out access token {0}", existing.AccessToken);
+ _logger.LogInformation("Logging out access token {0}", device.AccessToken);
- _authRepo.Delete(existing);
+ await _deviceManager.DeleteDevice(device).ConfigureAwait(false);
var sessions = Sessions
- .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
+ .Where(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var session in sessions)
@@ -1530,34 +1605,30 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.LogError("Error reporting session ended", ex);
+ _logger.LogError(ex, "Error reporting session ended");
}
}
}
- public void RevokeUserTokens(Guid userId, string currentAccessToken)
+ /// <inheritdoc />
+ public async Task RevokeUserTokens(Guid userId, string currentAccessToken)
{
CheckDisposed();
- var existing = _authRepo.Get(new AuthenticationInfoQuery
+ var existing = await _deviceManager.GetDevices(new DeviceQuery
{
UserId = userId
- });
+ }).ConfigureAwait(false);
foreach (var info in existing.Items)
{
if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
{
- Logout(info);
+ await Logout(info).ConfigureAwait(false);
}
}
}
- public void RevokeToken(string token)
- {
- Logout(token);
- }
-
/// <summary>
/// Reports the capabilities.
/// </summary>
@@ -1572,7 +1643,8 @@ namespace Emby.Server.Implementations.Session
ReportCapabilities(session, capabilities, true);
}
- private void ReportCapabilities(SessionInfo session,
+ private void ReportCapabilities(
+ SessionInfo session,
ClientCapabilities capabilities,
bool saveCapabilities)
{
@@ -1580,36 +1652,19 @@ namespace Emby.Server.Implementations.Session
if (saveCapabilities)
{
- CapabilitiesChanged?.Invoke(this, new SessionEventArgs
- {
- SessionInfo = session
- });
+ CapabilitiesChanged?.Invoke(
+ this,
+ new SessionEventArgs
+ {
+ SessionInfo = session
+ });
- try
- {
- SaveCapabilities(session.DeviceId, capabilities);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error saving device capabilities", ex);
- }
+ _deviceManager.SaveCapabilities(session.DeviceId, capabilities);
}
}
- private ClientCapabilities GetSavedCapabilities(string deviceId)
- {
- return _deviceManager.GetCapabilities(deviceId);
- }
-
- private void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
- {
- _deviceManager.SaveCapabilities(deviceId, capabilities);
- }
-
- private DtoOptions _itemInfoDtoOptions;
-
/// <summary>
- /// Converts a BaseItem to a BaseItemInfo
+ /// Converts a BaseItem to a BaseItemInfo.
/// </summary>
private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
{
@@ -1671,19 +1726,20 @@ namespace Emby.Server.Implementations.Session
return info;
}
- private string GetImageCacheTag(BaseItem item, ImageType type)
+ private string GetImageCacheTag(User user)
{
try
{
- return _imageProcessor.GetImageCacheTag(item, type);
+ return _imageProcessor.GetImageCacheTag(user);
}
- catch (Exception ex)
+ catch (Exception e)
{
- _logger.LogError("Error getting {0} image info", ex, type);
+ _logger.LogError(e, "Error getting image information for profile image");
return null;
}
}
+ /// <inheritdoc />
public void ReportNowViewingItem(string sessionId, string itemId)
{
if (string.IsNullOrEmpty(itemId))
@@ -1691,23 +1747,17 @@ namespace Emby.Server.Implementations.Session
throw new ArgumentNullException(nameof(itemId));
}
- //var item = _libraryManager.GetItemById(new Guid(itemId));
-
- //var info = GetItemInfo(item, null, null);
-
- //ReportNowViewingItem(sessionId, info);
- }
-
- public void ReportNowViewingItem(string sessionId, BaseItemDto item)
- {
- //var session = GetSession(sessionId);
+ var item = _libraryManager.GetItemById(new Guid(itemId));
+ var session = GetSession(sessionId);
- //session.NowViewingItem = item;
+ session.NowViewingItem = GetItemInfo(item, null);
}
+ /// <inheritdoc />
public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
{
- var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
+ var session = Sessions.FirstOrDefault(i =>
+ string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
if (session != null)
{
@@ -1715,25 +1765,29 @@ namespace Emby.Server.Implementations.Session
}
}
+ /// <inheritdoc />
public void ClearTranscodingInfo(string deviceId)
{
ReportTranscodingInfo(deviceId, null);
}
+ /// <inheritdoc />
public SessionInfo GetSession(string deviceId, string client, string version)
{
- return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
- string.Equals(i.Client, client));
+ return Sessions.FirstOrDefault(i =>
+ string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)
+ && string.Equals(i.Client, client, StringComparison.OrdinalIgnoreCase));
}
- public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
+ /// <inheritdoc />
+ public Task<SessionInfo> GetSessionByAuthenticationToken(Device info, string deviceId, string remoteEndpoint, string appVersion)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
- var user = info.UserId.Equals(Guid.Empty)
+ var user = info.UserId == Guid.Empty
? null
: _userManager.GetUserById(info.UserId);
@@ -1758,33 +1812,38 @@ namespace Emby.Server.Implementations.Session
return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
}
- public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
+ /// <inheritdoc />
+ public async Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
{
- var result = _authRepo.Get(new AuthenticationInfoQuery
+ var items = (await _deviceManager.GetDevices(new DeviceQuery
{
- AccessToken = token
- });
-
- var info = result.Items.FirstOrDefault();
+ AccessToken = token,
+ Limit = 1
+ }).ConfigureAwait(false)).Items;
- if (info == null)
+ if (items.Count == 0)
{
return null;
}
- return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
+ return await GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null).ConfigureAwait(false);
}
- public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendMessageToAdminSessions<T>(SessionMessageType name, T data, CancellationToken cancellationToken)
{
CheckDisposed();
- var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToList();
+ var adminUserIds = _userManager.Users
+ .Where(i => i.HasPermission(PermissionKind.IsAdministrator))
+ .Select(i => i.Id)
+ .ToList();
return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
}
- public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, Func<T> dataFn, CancellationToken cancellationToken)
{
CheckDisposed();
@@ -1795,97 +1854,26 @@ namespace Emby.Server.Implementations.Session
return Task.CompletedTask;
}
- var data = dataFn();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error sending message", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
+ return SendMessageToSessions(sessions, name, dataFn(), cancellationToken);
}
- public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, T data, CancellationToken cancellationToken)
{
CheckDisposed();
- var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error sending message", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
+ var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser));
+ return SendMessageToSessions(sessions, name, data, cancellationToken);
}
- public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendMessageToUserDeviceSessions<T>(string deviceId, SessionMessageType name, T data, CancellationToken cancellationToken)
{
CheckDisposed();
- var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error sending message", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
- }
-
- public Task SendMessageToUserDeviceAndAdminSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
- {
- CheckDisposed();
-
- var sessions = Sessions
- .Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) || IsAdminSession(i))
- .ToList();
-
- var tasks = sessions.Select(session => Task.Run(async () =>
- {
- try
- {
- await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError("Error sending message", ex);
- }
-
- }, cancellationToken)).ToArray();
-
- return Task.WhenAll(tasks);
- }
-
- private bool IsAdminSession(SessionInfo s)
- {
- var user = _userManager.GetUserById(s.UserId);
+ var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
- return user != null && user.Policy.IsAdministrator;
+ return SendMessageToSessions(sessions, name, data, cancellationToken);
}
}
}
diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
index 24903f5e8..2a14a8c7b 100644
--- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
+++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
@@ -1,72 +1,121 @@
+#nullable disable
+
using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.WebSockets;
+using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
{
/// <summary>
- /// Class SessionWebSocketListener
+ /// Class SessionWebSocketListener.
/// </summary>
- public class SessionWebSocketListener : IWebSocketListener, IDisposable
+ public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
{
/// <summary>
- /// The _session manager
+ /// The timeout in seconds after which a WebSocket is considered to be lost.
/// </summary>
- private readonly ISessionManager _sessionManager;
+ private const int WebSocketLostTimeout = 60;
+
+ /// <summary>
+ /// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets.
+ /// </summary>
+ private const float IntervalFactor = 0.2f;
+
+ /// <summary>
+ /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
+ /// </summary>
+ private const float ForceKeepAliveFactor = 0.75f;
+
+ /// <summary>
+ /// Lock used for accesing the KeepAlive cancellation token.
+ /// </summary>
+ private readonly object _keepAliveLock = new object();
+
+ /// <summary>
+ /// The WebSocket watchlist.
+ /// </summary>
+ private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>();
/// <summary>
- /// The _logger
+ /// Lock used for accessing the WebSockets watchlist.
/// </summary>
- private readonly ILogger _logger;
+ private readonly object _webSocketsLock = new object();
/// <summary>
- /// The _dto service
+ /// The _session manager.
/// </summary>
- private readonly IJsonSerializer _json;
+ private readonly ISessionManager _sessionManager;
- private readonly IHttpServer _httpServer;
+ /// <summary>
+ /// The _logger.
+ /// </summary>
+ private readonly ILogger<SessionWebSocketListener> _logger;
+ private readonly ILoggerFactory _loggerFactory;
+ /// <summary>
+ /// The KeepAlive cancellation token.
+ /// </summary>
+ private CancellationTokenSource _keepAliveCancellationToken;
/// <summary>
/// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
/// </summary>
+ /// <param name="logger">The logger.</param>
/// <param name="sessionManager">The session manager.</param>
/// <param name="loggerFactory">The logger factory.</param>
- /// <param name="json">The json.</param>
- /// <param name="httpServer">The HTTP server.</param>
- public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer)
+ public SessionWebSocketListener(
+ ILogger<SessionWebSocketListener> logger,
+ ISessionManager sessionManager,
+ ILoggerFactory loggerFactory)
{
+ _logger = logger;
_sessionManager = sessionManager;
- _logger = loggerFactory.CreateLogger(GetType().Name);
- _json = json;
- _httpServer = httpServer;
- httpServer.WebSocketConnected += _serverManager_WebSocketConnected;
+ _loggerFactory = loggerFactory;
}
- void _serverManager_WebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
+ /// <inheritdoc />
+ public void Dispose()
{
- var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint);
+ StopKeepAlive();
+ }
+ /// <summary>
+ /// Processes the message.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>Task.</returns>
+ public Task ProcessMessageAsync(WebSocketMessageInfo message)
+ => Task.CompletedTask;
+
+ /// <inheritdoc />
+ public async Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection)
+ {
+ var session = await GetSession(connection.QueryString, connection.RemoteEndPoint.ToString()).ConfigureAwait(false);
if (session != null)
{
- EnsureController(session, e.Argument);
+ EnsureController(session, connection);
+ await KeepAliveWebSocket(connection).ConfigureAwait(false);
}
else
{
- _logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url);
+ _logger.LogWarning("Unable to determine session based on query string: {0}", connection.QueryString);
}
}
- private SessionInfo GetSession(QueryParamCollection queryString, string remoteEndpoint)
+ private Task<SessionInfo> GetSession(IQueryCollection queryString, string remoteEndpoint)
{
if (queryString == null)
{
- throw new ArgumentNullException(nameof(queryString));
+ return null;
}
var token = queryString["api_key"];
@@ -74,31 +123,224 @@ namespace Emby.Server.Implementations.Session
{
return null;
}
+
var deviceId = queryString["deviceId"];
return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint);
}
- public void Dispose()
+ private void EnsureController(SessionInfo session, IWebSocketConnection connection)
{
- _httpServer.WebSocketConnected -= _serverManager_WebSocketConnected;
+ var controllerInfo = session.EnsureController<WebSocketController>(
+ s => new WebSocketController(_loggerFactory.CreateLogger<WebSocketController>(), s, _sessionManager));
+
+ var controller = (WebSocketController)controllerInfo.Item1;
+ controller.AddWebSocket(connection);
+
+ _sessionManager.OnSessionControllerConnected(session);
}
/// <summary>
- /// Processes the message.
+ /// Called when a WebSocket is closed.
/// </summary>
- /// <param name="message">The message.</param>
+ /// <param name="sender">The WebSocket.</param>
+ /// <param name="e">The event arguments.</param>
+ private void OnWebSocketClosed(object sender, EventArgs e)
+ {
+ var webSocket = (IWebSocketConnection)sender;
+ _logger.LogDebug("WebSocket {0} is closed.", webSocket);
+ RemoveWebSocket(webSocket);
+ }
+
+ /// <summary>
+ /// Adds a WebSocket to the KeepAlive watchlist.
+ /// </summary>
+ /// <param name="webSocket">The WebSocket to monitor.</param>
+ private async Task KeepAliveWebSocket(IWebSocketConnection webSocket)
+ {
+ lock (_webSocketsLock)
+ {
+ if (!_webSockets.Add(webSocket))
+ {
+ _logger.LogWarning("Multiple attempts to keep alive single WebSocket {0}", webSocket);
+ return;
+ }
+
+ webSocket.Closed += OnWebSocketClosed;
+ webSocket.LastKeepAliveDate = DateTime.UtcNow;
+
+ StartKeepAlive();
+ }
+
+ // Notify WebSocket about timeout
+ try
+ {
+ await SendForceKeepAlive(webSocket).ConfigureAwait(false);
+ }
+ catch (WebSocketException exception)
+ {
+ _logger.LogWarning(exception, "Cannot send ForceKeepAlive message to WebSocket {0}.", webSocket);
+ }
+ }
+
+ /// <summary>
+ /// Removes a WebSocket from the KeepAlive watchlist.
+ /// </summary>
+ /// <param name="webSocket">The WebSocket to remove.</param>
+ private void RemoveWebSocket(IWebSocketConnection webSocket)
+ {
+ lock (_webSocketsLock)
+ {
+ if (!_webSockets.Remove(webSocket))
+ {
+ _logger.LogWarning("WebSocket {0} not on watchlist.", webSocket);
+ }
+ else
+ {
+ webSocket.Closed -= OnWebSocketClosed;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Starts the KeepAlive watcher.
+ /// </summary>
+ private void StartKeepAlive()
+ {
+ lock (_keepAliveLock)
+ {
+ if (_keepAliveCancellationToken == null)
+ {
+ _keepAliveCancellationToken = new CancellationTokenSource();
+ // Start KeepAlive watcher
+ _ = RepeatAsyncCallbackEvery(
+ KeepAliveSockets,
+ TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor),
+ _keepAliveCancellationToken.Token);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Stops the KeepAlive watcher.
+ /// </summary>
+ private void StopKeepAlive()
+ {
+ lock (_keepAliveLock)
+ {
+ if (_keepAliveCancellationToken != null)
+ {
+ _keepAliveCancellationToken.Cancel();
+ _keepAliveCancellationToken.Dispose();
+ _keepAliveCancellationToken = null;
+ }
+ }
+
+ lock (_webSocketsLock)
+ {
+ foreach (var webSocket in _webSockets)
+ {
+ webSocket.Closed -= OnWebSocketClosed;
+ }
+
+ _webSockets.Clear();
+ }
+ }
+
+ /// <summary>
+ /// Checks status of KeepAlive of WebSockets.
+ /// </summary>
+ private async Task KeepAliveSockets()
+ {
+ List<IWebSocketConnection> inactive;
+ List<IWebSocketConnection> lost;
+
+ lock (_webSocketsLock)
+ {
+ _logger.LogDebug("Watching {0} WebSockets.", _webSockets.Count);
+
+ inactive = _webSockets.Where(i =>
+ {
+ var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds;
+ return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout);
+ }).ToList();
+ lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout).ToList();
+ }
+
+ if (inactive.Count > 0)
+ {
+ _logger.LogInformation("Sending ForceKeepAlive message to {0} inactive WebSockets.", inactive.Count);
+ }
+
+ foreach (var webSocket in inactive)
+ {
+ try
+ {
+ await SendForceKeepAlive(webSocket).ConfigureAwait(false);
+ }
+ catch (WebSocketException exception)
+ {
+ _logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket.");
+ lost.Add(webSocket);
+ }
+ }
+
+ lock (_webSocketsLock)
+ {
+ if (lost.Count > 0)
+ {
+ _logger.LogInformation("Lost {0} WebSockets.", lost.Count);
+ foreach (var webSocket in lost)
+ {
+ // TODO: handle session relative to the lost webSocket
+ RemoveWebSocket(webSocket);
+ }
+ }
+
+ if (_webSockets.Count == 0)
+ {
+ StopKeepAlive();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Sends a ForceKeepAlive message to a WebSocket.
+ /// </summary>
+ /// <param name="webSocket">The WebSocket.</param>
/// <returns>Task.</returns>
- public Task ProcessMessage(WebSocketMessageInfo message)
+ private Task SendForceKeepAlive(IWebSocketConnection webSocket)
{
- return Task.CompletedTask;
+ return webSocket.SendAsync(
+ new WebSocketMessage<int>
+ {
+ MessageType = SessionMessageType.ForceKeepAlive,
+ Data = WebSocketLostTimeout
+ },
+ CancellationToken.None);
}
- private void EnsureController(SessionInfo session, IWebSocketConnection connection)
+ /// <summary>
+ /// Runs a given async callback once every specified interval time, until cancelled.
+ /// </summary>
+ /// <param name="callback">The async callback.</param>
+ /// <param name="interval">The interval time.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ private async Task RepeatAsyncCallbackEvery(Func<Task> callback, TimeSpan interval, CancellationToken cancellationToken)
{
- var controllerInfo = session.EnsureController<WebSocketController>(s => new WebSocketController(s, _logger, _sessionManager));
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ await callback().ConfigureAwait(false);
- var controller = (WebSocketController)controllerInfo.Item1;
- controller.AddWebSocket(connection);
+ try
+ {
+ await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
+ }
+ catch (TaskCanceledException)
+ {
+ return;
+ }
+ }
}
}
}
diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs
index 0d483c55f..9fa92a53a 100644
--- a/Emby.Server.Implementations/Session/WebSocketController.cs
+++ b/Emby.Server.Implementations/Session/WebSocketController.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,64 +9,68 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
{
- public class WebSocketController : ISessionController, IDisposable
+ public sealed class WebSocketController : ISessionController, IDisposable
{
- public SessionInfo Session { get; private set; }
- public IReadOnlyList<IWebSocketConnection> Sockets { get; private set; }
-
- private readonly ILogger _logger;
-
+ private readonly ILogger<WebSocketController> _logger;
private readonly ISessionManager _sessionManager;
+ private readonly SessionInfo _session;
- public WebSocketController(SessionInfo session, ILogger logger, ISessionManager sessionManager)
+ private readonly List<IWebSocketConnection> _sockets;
+ private bool _disposed = false;
+
+ public WebSocketController(
+ ILogger<WebSocketController> logger,
+ SessionInfo session,
+ ISessionManager sessionManager)
{
- Session = session;
_logger = logger;
+ _session = session;
_sessionManager = sessionManager;
- Sockets = new List<IWebSocketConnection>();
+ _sockets = new List<IWebSocketConnection>();
}
private bool HasOpenSockets => GetActiveSockets().Any();
+ /// <inheritdoc />
public bool SupportsMediaControl => HasOpenSockets;
+ /// <inheritdoc />
public bool IsSessionActive => HasOpenSockets;
private IEnumerable<IWebSocketConnection> GetActiveSockets()
- {
- return Sockets
- .OrderByDescending(i => i.LastActivityDate)
- .Where(i => i.State == WebSocketState.Open);
- }
+ => _sockets.Where(i => i.State == WebSocketState.Open);
public void AddWebSocket(IWebSocketConnection connection)
{
- var sockets = Sockets.ToList();
- sockets.Add(connection);
+ _logger.LogDebug("Adding websocket to session {Session}", _session.Id);
+ _sockets.Add(connection);
- Sockets = sockets;
-
- connection.Closed += connection_Closed;
+ connection.Closed += OnConnectionClosed;
}
- void connection_Closed(object sender, EventArgs e)
+ private void OnConnectionClosed(object? sender, EventArgs e)
{
- var connection = (IWebSocketConnection)sender;
- var sockets = Sockets.ToList();
- sockets.Remove(connection);
-
- Sockets = sockets;
-
- _sessionManager.CloseIfNeeded(Session);
+ var connection = sender as IWebSocketConnection ?? throw new ArgumentException($"{nameof(sender)} is not of type {nameof(IWebSocketConnection)}", nameof(sender));
+ _logger.LogDebug("Removing websocket from session {Session}", _session.Id);
+ _sockets.Remove(connection);
+ connection.Closed -= OnConnectionClosed;
+ _sessionManager.CloseIfNeeded(_session);
}
- public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task SendMessage<T>(
+ SessionMessageType name,
+ Guid messageId,
+ T data,
+ CancellationToken cancellationToken)
{
var socket = GetActiveSockets()
+ .OrderByDescending(i => i.LastActivityDate)
.FirstOrDefault();
if (socket == null)
@@ -72,21 +78,30 @@ namespace Emby.Server.Implementations.Session
return Task.CompletedTask;
}
- return socket.SendAsync(new WebSocketMessage<T>
- {
- Data = data,
- MessageType = name,
- MessageId = messageId
-
- }, cancellationToken);
+ return socket.SendAsync(
+ new WebSocketMessage<T>
+ {
+ Data = data,
+ MessageType = name,
+ MessageId = messageId
+ },
+ cancellationToken);
}
+ /// <inheritdoc />
public void Dispose()
{
- foreach (var socket in Sockets.ToList())
+ if (_disposed)
{
- socket.Closed -= connection_Closed;
+ return;
}
+
+ foreach (var socket in _sockets)
+ {
+ socket.Closed -= OnConnectionClosed;
+ }
+
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs
index 16507466f..db8b68949 100644
--- a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs
+++ b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
@@ -9,12 +11,18 @@ namespace Emby.Server.Implementations.Sorting
public class AiredEpisodeOrderComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.AiredEpisodeOrder;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
if (x == null)
{
@@ -26,16 +34,6 @@ namespace Emby.Server.Implementations.Sorting
throw new ArgumentNullException(nameof(y));
}
- if (x.PremiereDate.HasValue && y.PremiereDate.HasValue)
- {
- var val = DateTime.Compare(x.PremiereDate.Value, y.PremiereDate.Value);
-
- if (val != 0)
- {
- //return val;
- }
- }
-
var episode1 = x as Episode;
var episode2 = y as Episode;
@@ -129,11 +127,11 @@ namespace Emby.Server.Implementations.Sorting
return GetSpecialCompareValue(x).CompareTo(GetSpecialCompareValue(y));
}
- private static int GetSpecialCompareValue(Episode item)
+ private static long GetSpecialCompareValue(Episode item)
{
// First sort by season number
// Since there are three sort orders, pad with 9 digits (3 for each, figure 1000 episode buffer should be enough)
- var val = (item.AirsAfterSeasonNumber ?? item.AirsBeforeSeasonNumber ?? 0) * 1000000000;
+ var val = (item.AirsAfterSeasonNumber ?? item.AirsBeforeSeasonNumber ?? 0) * 1000000000L;
// Second sort order is if it airs after the season
if (item.AirsAfterSeasonNumber.HasValue)
@@ -152,16 +150,16 @@ namespace Emby.Server.Implementations.Sorting
private static int CompareEpisodes(Episode x, Episode y)
{
- var xValue = (x.ParentIndexNumber ?? -1) * 1000 + (x.IndexNumber ?? -1);
- var yValue = (y.ParentIndexNumber ?? -1) * 1000 + (y.IndexNumber ?? -1);
+ var xValue = ((x.ParentIndexNumber ?? -1) * 1000) + (x.IndexNumber ?? -1);
+ var yValue = ((y.ParentIndexNumber ?? -1) * 1000) + (y.IndexNumber ?? -1);
+ var comparisonResult = xValue.CompareTo(yValue);
+ // If equal, compare premiere dates
+ if (comparisonResult == 0 && x.PremiereDate.HasValue && y.PremiereDate.HasValue)
+ {
+ comparisonResult = DateTime.Compare(x.PremiereDate.Value, y.PremiereDate.Value);
+ }
- return xValue.CompareTo(yValue);
+ return comparisonResult;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.AiredEpisodeOrder;
}
}
diff --git a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs
index 535f123f9..bd1966623 100644
--- a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs
+++ b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs
@@ -8,17 +8,23 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class AlbumArtistComparer
+ /// Class AlbumArtistComparer.
/// </summary>
public class AlbumArtistComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.AlbumArtist;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);
}
@@ -28,17 +34,11 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>System.String.</returns>
- private static string GetValue(BaseItem x)
+ private static string? GetValue(BaseItem? x)
{
var audio = x as IHasAlbumArtist;
- return audio != null ? audio.AlbumArtists.FirstOrDefault() : null;
+ return audio?.AlbumArtists.FirstOrDefault();
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.AlbumArtist;
}
}
diff --git a/Emby.Server.Implementations/Sorting/AlbumComparer.cs b/Emby.Server.Implementations/Sorting/AlbumComparer.cs
index 3831a0d2d..fe7dc84cb 100644
--- a/Emby.Server.Implementations/Sorting/AlbumComparer.cs
+++ b/Emby.Server.Implementations/Sorting/AlbumComparer.cs
@@ -7,17 +7,23 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class AlbumComparer
+ /// Class AlbumComparer.
/// </summary>
public class AlbumComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.Album;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);
}
@@ -27,17 +33,11 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>System.String.</returns>
- private static string GetValue(BaseItem x)
+ private static string? GetValue(BaseItem? x)
{
var audio = x as Audio;
return audio == null ? string.Empty : audio.Album;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Album;
}
}
diff --git a/Emby.Server.Implementations/Sorting/AlphanumComparator.cs b/Emby.Server.Implementations/Sorting/AlphanumComparator.cs
deleted file mode 100644
index 2e00c24d7..000000000
--- a/Emby.Server.Implementations/Sorting/AlphanumComparator.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System.Collections.Generic;
-using System.Text;
-using MediaBrowser.Controller.Sorting;
-
-namespace Emby.Server.Implementations.Sorting
-{
- public class AlphanumComparator : IComparer<string>
- {
- public static int CompareValues(string s1, string s2)
- {
- if (s1 == null || s2 == null)
- {
- return 0;
- }
-
- int thisMarker = 0, thisNumericChunk = 0;
- int thatMarker = 0, thatNumericChunk = 0;
-
- while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
- {
- if (thisMarker >= s1.Length)
- {
- return -1;
- }
- else if (thatMarker >= s2.Length)
- {
- return 1;
- }
- char thisCh = s1[thisMarker];
- char thatCh = s2[thatMarker];
-
- var thisChunk = new StringBuilder();
- var thatChunk = new StringBuilder();
-
- while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
- {
- thisChunk.Append(thisCh);
- thisMarker++;
-
- if (thisMarker < s1.Length)
- {
- thisCh = s1[thisMarker];
- }
- }
-
- while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || SortHelper.InChunk(thatCh, thatChunk[0])))
- {
- thatChunk.Append(thatCh);
- thatMarker++;
-
- if (thatMarker < s2.Length)
- {
- thatCh = s2[thatMarker];
- }
- }
-
- int result = 0;
- // If both chunks contain numeric characters, sort them numerically
- if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
- {
- if (!int.TryParse(thisChunk.ToString(), out thisNumericChunk))
- {
- return 0;
- }
- if (!int.TryParse(thatChunk.ToString(), out thatNumericChunk))
- {
- return 0;
- }
-
- if (thisNumericChunk < thatNumericChunk)
- {
- result = -1;
- }
-
- if (thisNumericChunk > thatNumericChunk)
- {
- result = 1;
- }
- }
- else
- {
- result = thisChunk.ToString().CompareTo(thatChunk.ToString());
- }
-
- if (result != 0)
- {
- return result;
- }
- }
-
- return 0;
- }
-
- public int Compare(string x, string y)
- {
- return CompareValues(x, y);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Sorting/ArtistComparer.cs b/Emby.Server.Implementations/Sorting/ArtistComparer.cs
index 9d5befc9a..7b7ba5753 100644
--- a/Emby.Server.Implementations/Sorting/ArtistComparer.cs
+++ b/Emby.Server.Implementations/Sorting/ArtistComparer.cs
@@ -7,17 +7,15 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class ArtistComparer
+ /// Class ArtistComparer.
/// </summary>
public class ArtistComparer : IBaseItemComparer
{
- /// <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)
+ /// <inheritdoc />
+ public string Name => ItemSortBy.Artist;
+
+ /// <inheritdoc />
+ public int Compare(BaseItem? x, BaseItem? y)
{
return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);
}
@@ -27,22 +25,14 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>System.String.</returns>
- private static string GetValue(BaseItem x)
+ private static string? GetValue(BaseItem? x)
{
- var audio = x as Audio;
-
- if (audio == null)
+ if (x is not Audio audio)
{
return string.Empty;
}
- return audio.Artists.Length == 0 ? null : audio.Artists[0];
+ return audio.Artists.Count == 0 ? null : audio.Artists[0];
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Artist;
}
}
diff --git a/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs b/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs
index 87d3ae2d6..5f142fa4b 100644
--- a/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs
+++ b/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@@ -8,26 +10,30 @@ namespace Emby.Server.Implementations.Sorting
public class CommunityRatingComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.CommunityRating;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
+ }
return (x.CommunityRating ?? 0).CompareTo(y.CommunityRating ?? 0);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.CommunityRating;
}
}
diff --git a/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs b/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs
index adb78dec5..ba1835e4f 100644
--- a/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs
+++ b/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs
@@ -5,30 +5,30 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class CriticRatingComparer
+ /// Class CriticRatingComparer.
/// </summary>
public class CriticRatingComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.CriticRating;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return GetValue(x).CompareTo(GetValue(y));
}
- private static float GetValue(BaseItem x)
+ private static float GetValue(BaseItem? x)
{
- return x.CriticRating ?? 0;
+ return x?.CriticRating ?? 0;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.CriticRating;
}
}
diff --git a/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs b/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs
index 8501bd9ee..8b460166c 100644
--- a/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs
@@ -6,31 +6,35 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class DateCreatedComparer
+ /// Class DateCreatedComparer.
/// </summary>
public class DateCreatedComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.DateCreated;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
+ }
return DateTime.Compare(x.DateCreated, y.DateCreated);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.DateCreated;
}
}
diff --git a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
index 623675157..b1cb123ce 100644
--- a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
@@ -1,4 +1,8 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -27,6 +31,12 @@ namespace Emby.Server.Implementations.Sorting
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.DateLastContentAdded;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -44,9 +54,7 @@ namespace Emby.Server.Implementations.Sorting
/// <returns>DateTime.</returns>
private static DateTime GetDate(BaseItem x)
{
- var folder = x as Folder;
-
- if (folder != null)
+ if (x is Folder folder)
{
if (folder.DateLastMediaAdded.HasValue)
{
@@ -56,11 +64,5 @@ namespace Emby.Server.Implementations.Sorting
return DateTime.MinValue;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.DateLastContentAdded;
}
}
diff --git a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
index 73f59f8cd..ec818253b 100644
--- a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
@@ -1,4 +1,7 @@
+#nullable disable
+
using System;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -7,7 +10,7 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class DatePlayedComparer
+ /// Class DatePlayedComparer.
/// </summary>
public class DatePlayedComparer : IUserBaseItemComparer
{
@@ -30,6 +33,12 @@ namespace Emby.Server.Implementations.Sorting
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.DatePlayed;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -56,11 +65,5 @@ namespace Emby.Server.Implementations.Sorting
return DateTime.MinValue;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.DatePlayed;
}
}
diff --git a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
index 66de05a6a..73e628cf7 100644
--- a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
@@ -1,3 +1,7 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -14,6 +18,24 @@ namespace Emby.Server.Implementations.Sorting
public User User { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.IsFavoriteOrLiked;
+
+ /// <summary>
+ /// Gets or sets the user data repository.
+ /// </summary>
+ /// <value>The user data repository.</value>
+ public IUserDataManager UserDataRepository { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user manager.
+ /// </summary>
+ /// <value>The user manager.</value>
+ public IUserManager UserManager { get; set; }
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -33,23 +55,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsFavoriteOrLiked(User) ? 0 : 1;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.IsFavoriteOrLiked;
-
- /// <summary>
- /// Gets or sets the user data repository.
- /// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
-
- /// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- public IUserManager UserManager { get; set; }
}
}
diff --git a/Emby.Server.Implementations/Sorting/IsFolderComparer.cs b/Emby.Server.Implementations/Sorting/IsFolderComparer.cs
index dfaa144cd..3c5ddeefa 100644
--- a/Emby.Server.Implementations/Sorting/IsFolderComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsFolderComparer.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Querying;
@@ -7,12 +9,18 @@ namespace Emby.Server.Implementations.Sorting
public class IsFolderComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.IsFolder;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return GetValue(x).CompareTo(GetValue(y));
}
@@ -22,15 +30,9 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>System.String.</returns>
- private static int GetValue(BaseItem x)
+ private static int GetValue(BaseItem? x)
{
- return x.IsFolder ? 0 : 1;
+ return x?.IsFolder ?? true ? 0 : 1;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.IsFolder;
}
}
diff --git a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
index da3f3dd25..7d77a8bc5 100644
--- a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
@@ -1,3 +1,8 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -14,6 +19,24 @@ namespace Emby.Server.Implementations.Sorting
public User User { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.IsUnplayed;
+
+ /// <summary>
+ /// Gets or sets the user data repository.
+ /// </summary>
+ /// <value>The user data repository.</value>
+ public IUserDataManager UserDataRepository { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user manager.
+ /// </summary>
+ /// <value>The user manager.</value>
+ public IUserManager UserManager { get; set; }
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -33,23 +56,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsPlayed(User) ? 0 : 1;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.IsUnplayed;
-
- /// <summary>
- /// Gets or sets the user data repository.
- /// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
-
- /// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- public IUserManager UserManager { get; set; }
}
}
diff --git a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
index d99d0eff2..926835f90 100644
--- a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
@@ -1,3 +1,8 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -14,6 +19,24 @@ namespace Emby.Server.Implementations.Sorting
public User User { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.IsUnplayed;
+
+ /// <summary>
+ /// Gets or sets the user data repository.
+ /// </summary>
+ /// <value>The user data repository.</value>
+ public IUserDataManager UserDataRepository { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user manager.
+ /// </summary>
+ /// <value>The user manager.</value>
+ public IUserManager UserManager { get; set; }
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -33,23 +56,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsUnplayed(User) ? 0 : 1;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.IsUnplayed;
-
- /// <summary>
- /// Gets or sets the user data repository.
- /// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
-
- /// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- public IUserManager UserManager { get; set; }
}
}
diff --git a/Emby.Server.Implementations/Sorting/NameComparer.cs b/Emby.Server.Implementations/Sorting/NameComparer.cs
index 10fa4359a..8f87717f4 100644
--- a/Emby.Server.Implementations/Sorting/NameComparer.cs
+++ b/Emby.Server.Implementations/Sorting/NameComparer.cs
@@ -6,31 +6,35 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class NameComparer
+ /// Class NameComparer.
/// </summary>
public class NameComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.Name;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
+ }
return string.Compare(x.Name, y.Name, StringComparison.CurrentCultureIgnoreCase);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Name;
}
}
diff --git a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
index e8fa8edc8..a81f78ebf 100644
--- a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
+++ b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@@ -16,29 +18,33 @@ namespace Emby.Server.Implementations.Sorting
}
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => 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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(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);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.OfficialRating;
}
}
diff --git a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
index eb74ce1bd..45c9044c5 100644
--- a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
+++ b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
@@ -1,3 +1,6 @@
+#nullable disable
+
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@@ -6,7 +9,7 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class PlayCountComparer
+ /// Class PlayCountComparer.
/// </summary>
public class PlayCountComparer : IUserBaseItemComparer
{
@@ -17,6 +20,24 @@ namespace Emby.Server.Implementations.Sorting
public User User { get; set; }
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.PlayCount;
+
+ /// <summary>
+ /// Gets or sets the user data repository.
+ /// </summary>
+ /// <value>The user data repository.</value>
+ public IUserDataManager UserDataRepository { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user manager.
+ /// </summary>
+ /// <value>The user manager.</value>
+ public IUserManager UserManager { get; set; }
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -38,23 +59,5 @@ namespace Emby.Server.Implementations.Sorting
return userdata == null ? 0 : userdata.PlayCount;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.PlayCount;
-
- /// <summary>
- /// Gets or sets the user data repository.
- /// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
-
- /// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- public IUserManager UserManager { get; set; }
}
}
diff --git a/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs b/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs
index 0c944a7a0..b217556ef 100644
--- a/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs
+++ b/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs
@@ -6,17 +6,23 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class PremiereDateComparer
+ /// Class PremiereDateComparer.
/// </summary>
public class PremiereDateComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.PremiereDate;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return GetDate(x).CompareTo(GetDate(y));
}
@@ -26,8 +32,13 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>DateTime.</returns>
- private static DateTime GetDate(BaseItem x)
+ private static DateTime GetDate(BaseItem? x)
{
+ if (x == null)
+ {
+ return DateTime.MinValue;
+ }
+
if (x.PremiereDate.HasValue)
{
return x.PremiereDate.Value;
@@ -44,13 +55,8 @@ namespace Emby.Server.Implementations.Sorting
// Don't blow up if the item has a bad ProductionYear, just return MinValue
}
}
+
return DateTime.MinValue;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.PremiereDate;
}
}
diff --git a/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs b/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs
index 472a07eb3..d2022df7a 100644
--- a/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs
+++ b/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs
@@ -5,17 +5,23 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class ProductionYearComparer
+ /// Class ProductionYearComparer.
/// </summary>
public class ProductionYearComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.ProductionYear;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return GetValue(x).CompareTo(GetValue(y));
}
@@ -25,8 +31,13 @@ namespace Emby.Server.Implementations.Sorting
/// </summary>
/// <param name="x">The x.</param>
/// <returns>DateTime.</returns>
- private static int GetValue(BaseItem x)
+ private static int GetValue(BaseItem? x)
{
+ if (x == null)
+ {
+ return 0;
+ }
+
if (x.ProductionYear.HasValue)
{
return x.ProductionYear.Value;
@@ -39,11 +50,5 @@ namespace Emby.Server.Implementations.Sorting
return 0;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.ProductionYear;
}
}
diff --git a/Emby.Server.Implementations/Sorting/RandomComparer.cs b/Emby.Server.Implementations/Sorting/RandomComparer.cs
index bde8b4534..bf0168222 100644
--- a/Emby.Server.Implementations/Sorting/RandomComparer.cs
+++ b/Emby.Server.Implementations/Sorting/RandomComparer.cs
@@ -6,25 +6,25 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class RandomComparer
+ /// Class RandomComparer.
/// </summary>
public class RandomComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.Random;
+
+ /// <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)
+ public int Compare(BaseItem? x, BaseItem? y)
{
return Guid.NewGuid().CompareTo(Guid.NewGuid());
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Random;
}
}
diff --git a/Emby.Server.Implementations/Sorting/RuntimeComparer.cs b/Emby.Server.Implementations/Sorting/RuntimeComparer.cs
index 1d2bdde26..e32e5552e 100644
--- a/Emby.Server.Implementations/Sorting/RuntimeComparer.cs
+++ b/Emby.Server.Implementations/Sorting/RuntimeComparer.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@@ -6,11 +8,17 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class RuntimeComparer
+ /// Class RuntimeComparer.
/// </summary>
public class RuntimeComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.Runtime;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -19,18 +27,16 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
+ }
return (x.RunTimeTicks ?? 0).CompareTo(y.RunTimeTicks ?? 0);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Runtime;
}
}
diff --git a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs
index 46e0dd918..4123a59f8 100644
--- a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs
+++ b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@@ -8,6 +12,12 @@ namespace Emby.Server.Implementations.Sorting
public class SeriesSortNameComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.SeriesSortName;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -22,13 +32,7 @@ namespace Emby.Server.Implementations.Sorting
{
var hasSeries = item as IHasSeries;
- return hasSeries != null ? hasSeries.FindSeriesSortName() : null;
+ return hasSeries?.FindSeriesSortName();
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.SeriesSortName;
}
}
diff --git a/Emby.Server.Implementations/Sorting/SortNameComparer.cs b/Emby.Server.Implementations/Sorting/SortNameComparer.cs
index cc0571c78..fb97a0349 100644
--- a/Emby.Server.Implementations/Sorting/SortNameComparer.cs
+++ b/Emby.Server.Implementations/Sorting/SortNameComparer.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@@ -6,11 +8,17 @@ using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Sorting
{
/// <summary>
- /// Class SortNameComparer
+ /// Class SortNameComparer.
/// </summary>
public class SortNameComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.SortName;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -19,18 +27,16 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
+ }
return string.Compare(x.SortName, y.SortName, StringComparison.CurrentCultureIgnoreCase);
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.SortName;
}
}
diff --git a/Emby.Server.Implementations/Sorting/StartDateComparer.cs b/Emby.Server.Implementations/Sorting/StartDateComparer.cs
index aa040fa15..c3df7c47e 100644
--- a/Emby.Server.Implementations/Sorting/StartDateComparer.cs
+++ b/Emby.Server.Implementations/Sorting/StartDateComparer.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.LiveTv;
@@ -9,6 +13,12 @@ namespace Emby.Server.Implementations.Sorting
public class StartDateComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.StartDate;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -26,19 +36,12 @@ namespace Emby.Server.Implementations.Sorting
/// <returns>DateTime.</returns>
private static DateTime GetDate(BaseItem x)
{
- var hasStartDate = x as LiveTvProgram;
-
- if (hasStartDate != null)
+ if (x is LiveTvProgram hasStartDate)
{
return hasStartDate.StartDate;
}
+
return DateTime.MinValue;
}
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.StartDate;
}
}
diff --git a/Emby.Server.Implementations/Sorting/StudioComparer.cs b/Emby.Server.Implementations/Sorting/StudioComparer.cs
index 617ed55d5..4d89cfa8b 100644
--- a/Emby.Server.Implementations/Sorting/StudioComparer.cs
+++ b/Emby.Server.Implementations/Sorting/StudioComparer.cs
@@ -1,5 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Linq;
+using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Querying;
@@ -9,6 +14,12 @@ namespace Emby.Server.Implementations.Sorting
public class StudioComparer : IBaseItemComparer
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name => ItemSortBy.Studio;
+
+ /// <summary>
/// Compares the specified x.
/// </summary>
/// <param name="x">The x.</param>
@@ -17,17 +28,16 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y)
{
if (x == null)
+ {
throw new ArgumentNullException(nameof(x));
+ }
if (y == null)
+ {
throw new ArgumentNullException(nameof(y));
- return AlphanumComparator.CompareValues(x.Studios.FirstOrDefault() ?? string.Empty, y.Studios.FirstOrDefault() ?? string.Empty);
- }
+ }
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name => ItemSortBy.Studio;
+ return AlphanumericComparator.CompareValues(x.Studios.FirstOrDefault(), y.Studios.FirstOrDefault());
+ }
}
}
diff --git a/Emby.Server.Implementations/SyncPlay/Group.cs b/Emby.Server.Implementations/SyncPlay/Group.cs
new file mode 100644
index 000000000..75cf890e5
--- /dev/null
+++ b/Emby.Server.Implementations/SyncPlay/Group.cs
@@ -0,0 +1,688 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay;
+using MediaBrowser.Controller.SyncPlay.GroupStates;
+using MediaBrowser.Controller.SyncPlay.Queue;
+using MediaBrowser.Controller.SyncPlay.Requests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.SyncPlay
+{
+ /// <summary>
+ /// Class Group.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public class Group : IGroupStateContext
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<Group> _logger;
+
+ /// <summary>
+ /// The logger factory.
+ /// </summary>
+ private readonly ILoggerFactory _loggerFactory;
+
+ /// <summary>
+ /// The user manager.
+ /// </summary>
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// The session manager.
+ /// </summary>
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// The library manager.
+ /// </summary>
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// The participants, or members of the group.
+ /// </summary>
+ private readonly Dictionary<string, GroupMember> _participants =
+ new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase);
+
+ /// <summary>
+ /// The internal group state.
+ /// </summary>
+ private IGroupState _state;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Group" /> class.
+ /// </summary>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="sessionManager">The session manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ public Group(
+ ILoggerFactory loggerFactory,
+ IUserManager userManager,
+ ISessionManager sessionManager,
+ ILibraryManager libraryManager)
+ {
+ _loggerFactory = loggerFactory;
+ _userManager = userManager;
+ _sessionManager = sessionManager;
+ _libraryManager = libraryManager;
+ _logger = loggerFactory.CreateLogger<Group>();
+
+ _state = new IdleGroupState(loggerFactory);
+ }
+
+ /// <summary>
+ /// Gets the default ping value used for sessions.
+ /// </summary>
+ /// <value>The default ping.</value>
+ public long DefaultPing { get; } = 500;
+
+ /// <summary>
+ /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds.
+ /// </summary>
+ /// <value>The maximum time offset error.</value>
+ public long TimeSyncOffset { get; } = 2000;
+
+ /// <summary>
+ /// Gets the maximum offset error accepted for position reported by clients, in milliseconds.
+ /// </summary>
+ /// <value>The maximum offset error.</value>
+ public long MaxPlaybackOffset { get; } = 500;
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ public Guid GroupId { get; } = Guid.NewGuid();
+
+ /// <summary>
+ /// Gets the group name.
+ /// </summary>
+ /// <value>The group name.</value>
+ public string GroupName { get; private set; }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ public PlayQueueManager PlayQueue { get; } = new PlayQueueManager();
+
+ /// <summary>
+ /// Gets the runtime ticks of current playing item.
+ /// </summary>
+ /// <value>The runtime ticks of current playing item.</value>
+ public long RunTimeTicks { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the last activity.
+ /// </summary>
+ /// <value>The last activity.</value>
+ public DateTime LastActivity { get; set; }
+
+ /// <summary>
+ /// Adds the session to the group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ private void AddSession(SessionInfo session)
+ {
+ _participants.TryAdd(
+ session.Id,
+ new GroupMember(session)
+ {
+ Ping = DefaultPing,
+ IsBuffering = false
+ });
+ }
+
+ /// <summary>
+ /// Removes the session from the group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ private void RemoveSession(SessionInfo session)
+ {
+ _participants.Remove(session.Id);
+ }
+
+ /// <summary>
+ /// Filters sessions of this group.
+ /// </summary>
+ /// <param name="fromId">The current session identifier.</param>
+ /// <param name="type">The filtering type.</param>
+ /// <returns>The list of sessions matching the filter.</returns>
+ private IEnumerable<string> FilterSessions(string fromId, SyncPlayBroadcastType type)
+ {
+ return type switch
+ {
+ SyncPlayBroadcastType.CurrentSession => new string[] { fromId },
+ SyncPlayBroadcastType.AllGroup => _participants
+ .Values
+ .Select(member => member.SessionId),
+ SyncPlayBroadcastType.AllExceptCurrentSession => _participants
+ .Values
+ .Select(member => member.SessionId)
+ .Where(sessionId => !sessionId.Equals(fromId, StringComparison.OrdinalIgnoreCase)),
+ SyncPlayBroadcastType.AllReady => _participants
+ .Values
+ .Where(member => !member.IsBuffering)
+ .Select(member => member.SessionId),
+ _ => Enumerable.Empty<string>()
+ };
+ }
+
+ /// <summary>
+ /// Checks if a given user can access all items of a given queue, that is,
+ /// the user has the required minimum parental access and has access to all required folders.
+ /// </summary>
+ /// <param name="user">The user.</param>
+ /// <param name="queue">The queue.</param>
+ /// <returns><c>true</c> if the user can access all the items in the queue, <c>false</c> otherwise.</returns>
+ private bool HasAccessToQueue(User user, IReadOnlyList<Guid> queue)
+ {
+ // Check if queue is empty.
+ if (queue == null || queue.Count == 0)
+ {
+ return true;
+ }
+
+ foreach (var itemId in queue)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (!item.IsVisibleStandalone(user))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private bool AllUsersHaveAccessToQueue(IReadOnlyList<Guid> queue)
+ {
+ // Check if queue is empty.
+ if (queue == null || queue.Count == 0)
+ {
+ return true;
+ }
+
+ // Get list of users.
+ var users = _participants
+ .Values
+ .Select(participant => _userManager.GetUserById(participant.UserId));
+
+ // Find problematic users.
+ var usersWithNoAccess = users.Where(user => !HasAccessToQueue(user, queue));
+
+ // All users must be able to access the queue.
+ return !usersWithNoAccess.Any();
+ }
+
+ /// <summary>
+ /// Checks if the group is empty.
+ /// </summary>
+ /// <returns><c>true</c> if the group is empty, <c>false</c> otherwise.</returns>
+ public bool IsGroupEmpty() => _participants.Count == 0;
+
+ /// <summary>
+ /// Initializes the group with the session's info.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
+ {
+ GroupName = request.GroupName;
+ AddSession(session);
+
+ var sessionIsPlayingAnItem = session.FullNowPlayingItem != null;
+
+ RestartCurrentItem();
+
+ if (sessionIsPlayingAnItem)
+ {
+ var playlist = session.NowPlayingQueue.Select(item => item.Id).ToList();
+ PlayQueue.Reset();
+ PlayQueue.SetPlaylist(playlist);
+ PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id);
+ RunTimeTicks = session.FullNowPlayingItem.RunTimeTicks ?? 0;
+ PositionTicks = session.PlayState.PositionTicks ?? 0;
+
+ // Maintain playstate.
+ var waitingState = new WaitingGroupState(_loggerFactory)
+ {
+ ResumePlaying = !session.PlayState.IsPaused
+ };
+ SetState(waitingState);
+ }
+
+ var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
+ SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
+
+ _state.SessionJoined(this, _state.Type, session, cancellationToken);
+
+ _logger.LogInformation("Session {SessionId} created group {GroupId}.", session.Id, GroupId.ToString());
+ }
+
+ /// <summary>
+ /// Adds the session to the group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
+ {
+ AddSession(session);
+
+ var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
+ SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
+
+ var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
+ SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
+
+ _state.SessionJoined(this, _state.Type, session, cancellationToken);
+
+ _logger.LogInformation("Session {SessionId} joined group {GroupId}.", session.Id, GroupId.ToString());
+ }
+
+ /// <summary>
+ /// Removes the session from the group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ public void SessionLeave(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken)
+ {
+ _state.SessionLeaving(this, _state.Type, session, cancellationToken);
+
+ RemoveSession(session);
+
+ var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, GroupId.ToString());
+ SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
+
+ var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
+ SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
+
+ _logger.LogInformation("Session {SessionId} left group {GroupId}.", session.Id, GroupId.ToString());
+ }
+
+ /// <summary>
+ /// Handles the requested action by the session.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The requested action.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
+ {
+ // The server's job is to maintain a consistent state for clients to reference
+ // and notify clients of state changes. The actual syncing of media playback
+ // happens client side. Clients are aware of the server's time and use it to sync.
+ _logger.LogInformation("Session {SessionId} requested {RequestType} in group {GroupId} that is {StateType}.", session.Id, request.Action, GroupId.ToString(), _state.Type);
+
+ // Apply requested changes to this group given its current state.
+ // Every request has a slightly different outcome depending on the group's state.
+ // There are currently four different group states that accomplish different goals:
+ // - Idle: in this state no media is playing and clients should be idle (playback is stopped).
+ // - Waiting: in this state the group is waiting for all the clients to be ready to start the playback,
+ // that is, they've either finished loading the media for the first time or they've finished buffering.
+ // Once all clients report to be ready the group's state can change to Playing or Paused.
+ // - Playing: clients have some media loaded and playback is unpaused.
+ // - Paused: clients have some media loaded but playback is currently paused.
+ request.Apply(this, _state, session, cancellationToken);
+ }
+
+ /// <summary>
+ /// Gets the info about the group for the clients.
+ /// </summary>
+ /// <returns>The group info for the clients.</returns>
+ public GroupInfoDto GetInfo()
+ {
+ var participants = _participants.Values.Select(session => session.UserName).Distinct().ToList();
+ return new GroupInfoDto(GroupId, GroupName, _state.Type, participants, DateTime.UtcNow);
+ }
+
+ /// <summary>
+ /// Checks if a user has access to all content in the play queue.
+ /// </summary>
+ /// <param name="user">The user.</param>
+ /// <returns><c>true</c> if the user can access the play queue; <c>false</c> otherwise.</returns>
+ public bool HasAccessToPlayQueue(User user)
+ {
+ var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToList();
+ return HasAccessToQueue(user, items);
+ }
+
+ /// <inheritdoc />
+ public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait)
+ {
+ if (_participants.TryGetValue(session.Id, out GroupMember value))
+ {
+ value.IgnoreGroupWait = ignoreGroupWait;
+ }
+ }
+
+ /// <inheritdoc />
+ public void SetState(IGroupState state)
+ {
+ _logger.LogInformation("Group {GroupId} switching from {FromStateType} to {ToStateType}.", GroupId.ToString(), _state.Type, state.Type);
+ this._state = state;
+ }
+
+ /// <inheritdoc />
+ public Task SendGroupUpdate<T>(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken)
+ {
+ IEnumerable<Task> GetTasks()
+ {
+ foreach (var sessionId in FilterSessions(from.Id, type))
+ {
+ yield return _sessionManager.SendSyncPlayGroupUpdate(sessionId, message, cancellationToken);
+ }
+ }
+
+ return Task.WhenAll(GetTasks());
+ }
+
+ /// <inheritdoc />
+ public Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken)
+ {
+ IEnumerable<Task> GetTasks()
+ {
+ foreach (var sessionId in FilterSessions(from.Id, type))
+ {
+ yield return _sessionManager.SendSyncPlayCommand(sessionId, message, cancellationToken);
+ }
+ }
+
+ return Task.WhenAll(GetTasks());
+ }
+
+ /// <inheritdoc />
+ public SendCommand NewSyncPlayCommand(SendCommandType type)
+ {
+ return new SendCommand(
+ GroupId,
+ PlayQueue.GetPlayingItemPlaylistId(),
+ LastActivity,
+ type,
+ PositionTicks,
+ DateTime.UtcNow);
+ }
+
+ /// <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;
+ return Math.Clamp(ticks, 0, RunTimeTicks);
+ }
+
+ /// <inheritdoc />
+ public void UpdatePing(SessionInfo session, long ping)
+ {
+ if (_participants.TryGetValue(session.Id, out GroupMember value))
+ {
+ value.Ping = ping;
+ }
+ }
+
+ /// <inheritdoc />
+ public long GetHighestPing()
+ {
+ long max = long.MinValue;
+ foreach (var session in _participants.Values)
+ {
+ max = Math.Max(max, session.Ping);
+ }
+
+ return max;
+ }
+
+ /// <inheritdoc />
+ public void SetBuffering(SessionInfo session, bool isBuffering)
+ {
+ if (_participants.TryGetValue(session.Id, out GroupMember value))
+ {
+ value.IsBuffering = isBuffering;
+ }
+ }
+
+ /// <inheritdoc />
+ public void SetAllBuffering(bool isBuffering)
+ {
+ foreach (var session in _participants.Values)
+ {
+ session.IsBuffering = isBuffering;
+ }
+ }
+
+ /// <inheritdoc />
+ public bool IsBuffering()
+ {
+ foreach (var session in _participants.Values)
+ {
+ if (session.IsBuffering && !session.IgnoreGroupWait)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc />
+ public bool SetPlayQueue(IReadOnlyList<Guid> playQueue, int playingItemPosition, long startPositionTicks)
+ {
+ // Ignore on empty queue or invalid item position.
+ if (playQueue.Count == 0 || playingItemPosition >= playQueue.Count || playingItemPosition < 0)
+ {
+ return false;
+ }
+
+ // Check if participants can access the new playing queue.
+ if (!AllUsersHaveAccessToQueue(playQueue))
+ {
+ return false;
+ }
+
+ PlayQueue.Reset();
+ PlayQueue.SetPlaylist(playQueue);
+ PlayQueue.SetPlayingItemByIndex(playingItemPosition);
+ var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
+ RunTimeTicks = item.RunTimeTicks ?? 0;
+ PositionTicks = startPositionTicks;
+ LastActivity = DateTime.UtcNow;
+
+ return true;
+ }
+
+ /// <inheritdoc />
+ public bool SetPlayingItem(Guid playlistItemId)
+ {
+ var itemFound = PlayQueue.SetPlayingItemByPlaylistId(playlistItemId);
+
+ if (itemFound)
+ {
+ var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
+ RunTimeTicks = item.RunTimeTicks ?? 0;
+ }
+ else
+ {
+ RunTimeTicks = 0;
+ }
+
+ RestartCurrentItem();
+
+ return itemFound;
+ }
+
+ /// <inheritdoc />
+ public void ClearPlayQueue(bool clearPlayingItem)
+ {
+ PlayQueue.ClearPlaylist(clearPlayingItem);
+ if (clearPlayingItem)
+ {
+ RestartCurrentItem();
+ }
+ }
+
+ /// <inheritdoc />
+ public bool RemoveFromPlayQueue(IReadOnlyList<Guid> playlistItemIds)
+ {
+ var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds);
+ if (playingItemRemoved)
+ {
+ var itemId = PlayQueue.GetPlayingItemId();
+ if (!itemId.Equals(Guid.Empty))
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ RunTimeTicks = item.RunTimeTicks ?? 0;
+ }
+ else
+ {
+ RunTimeTicks = 0;
+ }
+
+ RestartCurrentItem();
+ }
+
+ return playingItemRemoved;
+ }
+
+ /// <inheritdoc />
+ public bool MoveItemInPlayQueue(Guid playlistItemId, int newIndex)
+ {
+ return PlayQueue.MovePlaylistItem(playlistItemId, newIndex);
+ }
+
+ /// <inheritdoc />
+ public bool AddToPlayQueue(IReadOnlyList<Guid> newItems, GroupQueueMode mode)
+ {
+ // Ignore on empty list.
+ if (newItems.Count == 0)
+ {
+ return false;
+ }
+
+ // Check if participants can access the new playing queue.
+ if (!AllUsersHaveAccessToQueue(newItems))
+ {
+ return false;
+ }
+
+ if (mode.Equals(GroupQueueMode.QueueNext))
+ {
+ PlayQueue.QueueNext(newItems);
+ }
+ else
+ {
+ PlayQueue.Queue(newItems);
+ }
+
+ return true;
+ }
+
+ /// <inheritdoc />
+ public void RestartCurrentItem()
+ {
+ PositionTicks = 0;
+ LastActivity = DateTime.UtcNow;
+ }
+
+ /// <inheritdoc />
+ public bool NextItemInQueue()
+ {
+ var update = PlayQueue.Next();
+ if (update)
+ {
+ var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
+ RunTimeTicks = item.RunTimeTicks ?? 0;
+ RestartCurrentItem();
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <inheritdoc />
+ public bool PreviousItemInQueue()
+ {
+ var update = PlayQueue.Previous();
+ if (update)
+ {
+ var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
+ RunTimeTicks = item.RunTimeTicks ?? 0;
+ RestartCurrentItem();
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <inheritdoc />
+ public void SetRepeatMode(GroupRepeatMode mode)
+ {
+ PlayQueue.SetRepeatMode(mode);
+ }
+
+ /// <inheritdoc />
+ public void SetShuffleMode(GroupShuffleMode mode)
+ {
+ PlayQueue.SetShuffleMode(mode);
+ }
+
+ /// <inheritdoc />
+ public PlayQueueUpdate GetPlayQueueUpdate(PlayQueueUpdateReason reason)
+ {
+ var startPositionTicks = PositionTicks;
+ var isPlaying = _state.Type.Equals(GroupStateType.Playing);
+
+ if (isPlaying)
+ {
+ var currentTime = DateTime.UtcNow;
+ var elapsedTime = currentTime - LastActivity;
+ // Elapsed time is negative if event happens
+ // during the delay added to account for latency.
+ // In this phase clients haven't started the playback yet.
+ // In other words, LastActivity is in the future,
+ // when playback unpause is supposed to happen.
+ // Adjust ticks only if playback actually started.
+ startPositionTicks += Math.Max(elapsedTime.Ticks, 0);
+ }
+
+ return new PlayQueueUpdate(
+ reason,
+ PlayQueue.LastChange,
+ PlayQueue.GetPlaylist(),
+ PlayQueue.PlayingItemIndex,
+ startPositionTicks,
+ isPlaying,
+ PlayQueue.ShuffleMode,
+ PlayQueue.RepeatMode);
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
new file mode 100644
index 000000000..2ebeea717
--- /dev/null
+++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
@@ -0,0 +1,396 @@
+#nullable disable
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Threading;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay;
+using MediaBrowser.Controller.SyncPlay.Requests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.SyncPlay
+{
+ /// <summary>
+ /// Class SyncPlayManager.
+ /// </summary>
+ public class SyncPlayManager : ISyncPlayManager, IDisposable
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<SyncPlayManager> _logger;
+
+ /// <summary>
+ /// The logger factory.
+ /// </summary>
+ private readonly ILoggerFactory _loggerFactory;
+
+ /// <summary>
+ /// The user manager.
+ /// </summary>
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// The session manager.
+ /// </summary>
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// The library manager.
+ /// </summary>
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// The map between users and counter of active sessions.
+ /// </summary>
+ private readonly ConcurrentDictionary<Guid, int> _activeUsers =
+ new ConcurrentDictionary<Guid, int>();
+
+ /// <summary>
+ /// The map between sessions and groups.
+ /// </summary>
+ private readonly ConcurrentDictionary<string, Group> _sessionToGroupMap =
+ new ConcurrentDictionary<string, Group>(StringComparer.OrdinalIgnoreCase);
+
+ /// <summary>
+ /// The groups.
+ /// </summary>
+ private readonly ConcurrentDictionary<Guid, Group> _groups =
+ new ConcurrentDictionary<Guid, Group>();
+
+ /// <summary>
+ /// Lock used for accessing multiple groups at once.
+ /// </summary>
+ /// <remarks>
+ /// This lock has priority on locks made on <see cref="Group"/>.
+ /// </remarks>
+ private readonly object _groupsLock = new object();
+
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayManager" /> class.
+ /// </summary>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="sessionManager">The session manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ public SyncPlayManager(
+ ILoggerFactory loggerFactory,
+ IUserManager userManager,
+ ISessionManager sessionManager,
+ ILibraryManager libraryManager)
+ {
+ _loggerFactory = loggerFactory;
+ _userManager = userManager;
+ _sessionManager = sessionManager;
+ _libraryManager = libraryManager;
+ _logger = loggerFactory.CreateLogger<SyncPlayManager>();
+ _sessionManager.SessionEnded += OnSessionEnded;
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <inheritdoc />
+ public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
+ {
+ if (session == null)
+ {
+ throw new InvalidOperationException("Session is null!");
+ }
+
+ if (request == null)
+ {
+ throw new InvalidOperationException("Request is null!");
+ }
+
+ // Locking required to access list of groups.
+ lock (_groupsLock)
+ {
+ // Make sure that session has not joined another group.
+ if (_sessionToGroupMap.ContainsKey(session.Id))
+ {
+ var leaveGroupRequest = new LeaveGroupRequest();
+ LeaveGroup(session, leaveGroupRequest, cancellationToken);
+ }
+
+ var group = new Group(_loggerFactory, _userManager, _sessionManager, _libraryManager);
+ _groups[group.GroupId] = group;
+
+ if (!_sessionToGroupMap.TryAdd(session.Id, group))
+ {
+ throw new InvalidOperationException("Could not add session to group!");
+ }
+
+ UpdateSessionsCounter(session.UserId, 1);
+ group.CreateGroup(session, request, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
+ {
+ if (session == null)
+ {
+ throw new InvalidOperationException("Session is null!");
+ }
+
+ if (request == null)
+ {
+ throw new InvalidOperationException("Request is null!");
+ }
+
+ var user = _userManager.GetUserById(session.UserId);
+
+ // Locking required to access list of groups.
+ lock (_groupsLock)
+ {
+ _groups.TryGetValue(request.GroupId, out Group group);
+
+ if (group == null)
+ {
+ _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);
+ _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
+ return;
+ }
+
+ // Group lock required to let other requests end first.
+ lock (group)
+ {
+ if (!group.HasAccessToPlayQueue(user))
+ {
+ _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);
+ _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
+ return;
+ }
+
+ if (_sessionToGroupMap.TryGetValue(session.Id, out var existingGroup))
+ {
+ if (existingGroup.GroupId.Equals(request.GroupId))
+ {
+ // Restore session.
+ UpdateSessionsCounter(session.UserId, 1);
+ group.SessionJoin(session, request, cancellationToken);
+ return;
+ }
+
+ var leaveGroupRequest = new LeaveGroupRequest();
+ LeaveGroup(session, leaveGroupRequest, cancellationToken);
+ }
+
+ if (!_sessionToGroupMap.TryAdd(session.Id, group))
+ {
+ throw new InvalidOperationException("Could not add session to group!");
+ }
+
+ UpdateSessionsCounter(session.UserId, 1);
+ group.SessionJoin(session, request, cancellationToken);
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken)
+ {
+ if (session == null)
+ {
+ throw new InvalidOperationException("Session is null!");
+ }
+
+ if (request == null)
+ {
+ throw new InvalidOperationException("Request is null!");
+ }
+
+ // Locking required to access list of groups.
+ lock (_groupsLock)
+ {
+ if (_sessionToGroupMap.TryGetValue(session.Id, out var group))
+ {
+ // Group lock required to let other requests end first.
+ lock (group)
+ {
+ if (_sessionToGroupMap.TryRemove(session.Id, out var tempGroup))
+ {
+ if (!tempGroup.GroupId.Equals(group.GroupId))
+ {
+ throw new InvalidOperationException("Session was in wrong group!");
+ }
+ }
+ else
+ {
+ throw new InvalidOperationException("Could not remove session from group!");
+ }
+
+ UpdateSessionsCounter(session.UserId, -1);
+ group.SessionLeave(session, request, cancellationToken);
+
+ if (group.IsGroupEmpty())
+ {
+ _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId);
+ _groups.Remove(group.GroupId, out _);
+ }
+ }
+ }
+ else
+ {
+ _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
+
+ var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
+ _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
+ return;
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request)
+ {
+ if (session == null)
+ {
+ throw new InvalidOperationException("Session is null!");
+ }
+
+ if (request == null)
+ {
+ throw new InvalidOperationException("Request is null!");
+ }
+
+ var user = _userManager.GetUserById(session.UserId);
+ List<GroupInfoDto> list = new List<GroupInfoDto>();
+
+ lock (_groupsLock)
+ {
+ foreach (var (_, group) in _groups)
+ {
+ // Locking required as group is not thread-safe.
+ lock (group)
+ {
+ if (group.HasAccessToPlayQueue(user))
+ {
+ list.Add(group.GetInfo());
+ }
+ }
+ }
+ }
+
+ return list;
+ }
+
+ /// <inheritdoc />
+ public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
+ {
+ if (session == null)
+ {
+ throw new InvalidOperationException("Session is null!");
+ }
+
+ if (request == null)
+ {
+ throw new InvalidOperationException("Request is null!");
+ }
+
+ if (_sessionToGroupMap.TryGetValue(session.Id, out var group))
+ {
+ // Group lock required as Group is not thread-safe.
+ lock (group)
+ {
+ // Make sure that session still belongs to this group.
+ if (_sessionToGroupMap.TryGetValue(session.Id, out var checkGroup) && !checkGroup.GroupId.Equals(group.GroupId))
+ {
+ // Drop request.
+ return;
+ }
+
+ // Drop request if group is empty.
+ if (group.IsGroupEmpty())
+ {
+ return;
+ }
+
+ // Apply requested changes to group.
+ group.HandleRequest(session, request, cancellationToken);
+ }
+ }
+ else
+ {
+ _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
+
+ var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
+ _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
+ }
+ }
+
+ /// <inheritdoc />
+ public bool IsUserActive(Guid userId)
+ {
+ if (_activeUsers.TryGetValue(userId, out var sessionsCounter))
+ {
+ return sessionsCounter > 0;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _sessionManager.SessionEnded -= OnSessionEnded;
+ _disposed = true;
+ }
+
+ private void OnSessionEnded(object sender, SessionEventArgs e)
+ {
+ var session = e.SessionInfo;
+
+ if (_sessionToGroupMap.TryGetValue(session.Id, out var group))
+ {
+ var leaveGroupRequest = new LeaveGroupRequest();
+ LeaveGroup(session, leaveGroupRequest, CancellationToken.None);
+ }
+ }
+
+ private void UpdateSessionsCounter(Guid userId, int toAdd)
+ {
+ // Update sessions counter.
+ var newSessionsCounter = _activeUsers.AddOrUpdate(
+ userId,
+ 1,
+ (key, sessionsCounter) => sessionsCounter + toAdd);
+
+ // Should never happen.
+ if (newSessionsCounter < 0)
+ {
+ throw new InvalidOperationException("Sessions counter is negative!");
+ }
+
+ // Clean record if user has no more active sessions.
+ if (newSessionsCounter == 0)
+ {
+ _activeUsers.TryRemove(new KeyValuePair<Guid, int>(userId, newSessionsCounter));
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs
index 630ef4893..4d990c871 100644
--- a/Emby.Server.Implementations/TV/TVSeriesManager.cs
+++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs
@@ -1,14 +1,20 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.TV;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Server.Implementations.TV
{
@@ -17,19 +23,19 @@ namespace Emby.Server.Implementations.TV
private readonly IUserManager _userManager;
private readonly IUserDataManager _userDataManager;
private readonly ILibraryManager _libraryManager;
- private readonly IServerConfigurationManager _config;
+ private readonly IServerConfigurationManager _configurationManager;
- public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IServerConfigurationManager config)
+ public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager)
{
_userManager = userManager;
_userDataManager = userDataManager;
_libraryManager = libraryManager;
- _config = config;
+ _configurationManager = configurationManager;
}
- public QueryResult<BaseItem> GetNextUp(NextUpQuery request, DtoOptions dtoOptions)
+ public QueryResult<BaseItem> GetNextUp(NextUpQuery query, DtoOptions options)
{
- var user = _userManager.GetUserById(request.UserId);
+ var user = _userManager.GetUserById(query.UserId);
if (user == null)
{
@@ -37,11 +43,9 @@ namespace Emby.Server.Implementations.TV
}
string presentationUniqueKey = null;
- if (!string.IsNullOrEmpty(request.SeriesId))
+ if (!string.IsNullOrEmpty(query.SeriesId))
{
- var series = _libraryManager.GetItemById(request.SeriesId) as Series;
-
- if (series != null)
+ if (_libraryManager.GetItemById(query.SeriesId) is Series series)
{
presentationUniqueKey = GetUniqueSeriesKey(series);
}
@@ -49,16 +53,14 @@ namespace Emby.Server.Implementations.TV
if (!string.IsNullOrEmpty(presentationUniqueKey))
{
- return GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, dtoOptions), request);
+ return GetResult(GetNextUpEpisodes(query, user, new[] { presentationUniqueKey }, options), query);
}
- var parentIdGuid = string.IsNullOrEmpty(request.ParentId) ? (Guid?)null : new Guid(request.ParentId);
-
BaseItem[] parents;
- if (parentIdGuid.HasValue)
+ if (query.ParentId.HasValue)
{
- var parent = _libraryManager.GetItemById(parentIdGuid.Value);
+ var parent = _libraryManager.GetItemById(query.ParentId.Value);
if (parent != null)
{
@@ -73,14 +75,14 @@ namespace Emby.Server.Implementations.TV
{
parents = _libraryManager.GetUserRootFolder().GetChildren(user, true)
.Where(i => i is Folder)
- .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N")))
+ .Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes).Contains(i.Id))
.ToArray();
}
- return GetNextUp(request, parents, dtoOptions);
+ return GetNextUp(query, parents, options);
}
- public QueryResult<BaseItem> GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions dtoOptions)
+ public QueryResult<BaseItem> GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions options)
{
var user = _userManager.GetUserById(request.UserId);
@@ -93,9 +95,7 @@ namespace Emby.Server.Implementations.TV
int? limit = null;
if (!string.IsNullOrEmpty(request.SeriesId))
{
- var series = _libraryManager.GetItemById(request.SeriesId) as Series;
-
- if (series != null)
+ if (_libraryManager.GetItemById(request.SeriesId) is Series series)
{
presentationUniqueKey = GetUniqueSeriesKey(series);
limit = 1;
@@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.TV
if (!string.IsNullOrEmpty(presentationUniqueKey))
{
- return GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, dtoOptions), request);
+ return GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, options), request);
}
if (limit.HasValue)
@@ -112,26 +112,23 @@ namespace Emby.Server.Implementations.TV
limit = limit.Value + 10;
}
- var items = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- IncludeItemTypes = new[] { typeof(Episode).Name },
- OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DatePlayed, SortOrder.Descending) },
- SeriesPresentationUniqueKey = presentationUniqueKey,
- Limit = limit,
- DtoOptions = new DtoOptions
- {
- Fields = new ItemFields[]
+ var items = _libraryManager
+ .GetItemList(
+ new InternalItemsQuery(user)
{
- ItemFields.SeriesPresentationUniqueKey
- },
- EnableImages = false
- },
- GroupBySeriesPresentationUniqueKey = true
-
- }, parentsFolders.ToList()).Cast<Episode>().Select(GetUniqueSeriesKey);
+ IncludeItemTypes = new[] { nameof(Episode) },
+ OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DatePlayed, SortOrder.Descending) },
+ SeriesPresentationUniqueKey = presentationUniqueKey,
+ Limit = limit,
+ DtoOptions = new DtoOptions { Fields = new[] { ItemFields.SeriesPresentationUniqueKey }, EnableImages = false },
+ GroupBySeriesPresentationUniqueKey = true
+ }, parentsFolders.ToList())
+ .Cast<Episode>()
+ .Where(episode => !string.IsNullOrEmpty(episode.SeriesPresentationUniqueKey))
+ .Select(GetUniqueSeriesKey);
// Avoid implicitly captured closure
- var episodes = GetNextUpEpisodes(request, user, items, dtoOptions);
+ var episodes = GetNextUpEpisodes(request, user, items, options);
return GetResult(episodes, request);
}
@@ -144,8 +141,6 @@ namespace Emby.Server.Implementations.TV
var allNextUp = seriesKeys
.Select(i => GetNextUp(i, currentUser, dtoOptions));
- //allNextUp = allNextUp.OrderByDescending(i => i.Item1);
-
// If viewing all next up for all series, remove first episodes
// But if that returns empty, keep those first episodes (avoid completely empty view)
var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId);
@@ -154,7 +149,12 @@ namespace Emby.Server.Implementations.TV
return allNextUp
.Where(i =>
{
- if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue)
+ if (request.DisableFirstEpisode)
+ {
+ return i.Item1 != DateTime.MinValue;
+ }
+
+ if (alwaysEnableFirstEpisode || (i.Item1 != DateTime.MinValue && i.Item1.Date >= request.NextUpDateCutoff))
{
anyFound = true;
return true;
@@ -191,38 +191,82 @@ namespace Emby.Server.Implementations.TV
{
AncestorWithPresentationUniqueKey = null,
SeriesPresentationUniqueKey = seriesKey,
- IncludeItemTypes = new[] { typeof(Episode).Name },
+ IncludeItemTypes = new[] { nameof(Episode) },
OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Descending) },
IsPlayed = true,
Limit = 1,
ParentIndexNumberNotEquals = 0,
DtoOptions = new DtoOptions
{
- Fields = new ItemFields[]
- {
- ItemFields.SortName
- },
+ Fields = new[] { ItemFields.SortName },
EnableImages = false
}
-
- }).FirstOrDefault();
+ }).Cast<Episode>().FirstOrDefault();
Func<Episode> getEpisode = () =>
{
- return _libraryManager.GetItemList(new InternalItemsQuery(user)
+ var nextEpisode = _libraryManager.GetItemList(new InternalItemsQuery(user)
{
AncestorWithPresentationUniqueKey = null,
SeriesPresentationUniqueKey = seriesKey,
- IncludeItemTypes = new[] { typeof(Episode).Name },
+ IncludeItemTypes = new[] { nameof(Episode) },
OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) },
Limit = 1,
IsPlayed = false,
IsVirtualItem = false,
ParentIndexNumberNotEquals = 0,
- MinSortName = lastWatchedEpisode == null ? null : lastWatchedEpisode.SortName,
+ MinSortName = lastWatchedEpisode?.SortName,
DtoOptions = dtoOptions
-
}).Cast<Episode>().FirstOrDefault();
+
+ if (_configurationManager.Configuration.DisplaySpecialsWithinSeasons)
+ {
+ var consideredEpisodes = _libraryManager.GetItemList(new InternalItemsQuery(user)
+ {
+ AncestorWithPresentationUniqueKey = null,
+ SeriesPresentationUniqueKey = seriesKey,
+ ParentIndexNumber = 0,
+ IncludeItemTypes = new[] { nameof(Episode) },
+ IsPlayed = false,
+ IsVirtualItem = false,
+ DtoOptions = dtoOptions
+ })
+ .Cast<Episode>()
+ .Where(episode => episode.AirsBeforeSeasonNumber != null || episode.AirsAfterSeasonNumber != null)
+ .ToList();
+
+ if (lastWatchedEpisode != null)
+ {
+ // Last watched episode is added, because there could be specials that aired before the last watched episode
+ consideredEpisodes.Add(lastWatchedEpisode);
+ }
+
+ if (nextEpisode != null)
+ {
+ consideredEpisodes.Add(nextEpisode);
+ }
+
+ var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) })
+ .Cast<Episode>();
+ if (lastWatchedEpisode != null)
+ {
+ sortedConsideredEpisodes = sortedConsideredEpisodes.SkipWhile(episode => episode.Id != lastWatchedEpisode.Id).Skip(1);
+ }
+
+ nextEpisode = sortedConsideredEpisodes.FirstOrDefault();
+ }
+
+ if (nextEpisode != null)
+ {
+ var userData = _userDataManager.GetUserData(user, nextEpisode);
+
+ if (userData.PlaybackPositionTicks > 0)
+ {
+ return null;
+ }
+ }
+
+ return nextEpisode;
};
if (lastWatchedEpisode != null)
@@ -253,6 +297,7 @@ namespace Emby.Server.Implementations.TV
{
items = items.Skip(query.StartIndex.Value);
}
+
if (query.Limit.HasValue)
{
items = items.Take(query.Limit.Value);
diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs
index bd86c6cdc..bf51c3968 100644
--- a/Emby.Server.Implementations/Udp/UdpServer.cs
+++ b/Emby.Server.Implementations/Udp/UdpServer.cs
@@ -1,293 +1,145 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Net;
+using System.Net.Sockets;
using System.Text;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Model.ApiClient;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Udp
{
/// <summary>
- /// Provides a Udp Server
+ /// Provides a Udp Server.
/// </summary>
- public class UdpServer : IDisposable
+ public sealed class UdpServer : IDisposable
{
/// <summary>
- /// The _logger
+ /// Address Override Configuration Key.
/// </summary>
- private readonly ILogger _logger;
+ public const string AddressOverrideConfigKey = "PublishedServerUrl";
- private bool _isDisposed;
+ /// <summary>
+ /// The _logger.
+ /// </summary>
+ private readonly ILogger _logger;
+ private readonly IServerApplicationHost _appHost;
+ private readonly IConfiguration _config;
- private readonly List<Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>> _responders = new List<Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>>();
+ private readonly byte[] _receiveBuffer = new byte[8192];
- private readonly IServerApplicationHost _appHost;
- private readonly IJsonSerializer _json;
+ private Socket _udpSocket;
+ private IPEndPoint _endpoint;
+ private bool _disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="UdpServer" /> class.
/// </summary>
- public UdpServer(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory)
+ /// <param name="logger">The logger.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="configuration">The configuration manager.</param>
+ /// <param name="port">The port.</param>
+ public UdpServer(
+ ILogger logger,
+ IServerApplicationHost appHost,
+ IConfiguration configuration,
+ int port)
{
_logger = logger;
_appHost = appHost;
- _json = json;
- _socketFactory = socketFactory;
+ _config = configuration;
- AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message);
- AddMessageResponder("who is EmbyServer?", true, RespondToV2Message);
- AddMessageResponder("who is MediaBrowserServer_v2?", false, RespondToV2Message);
- }
+ _endpoint = new IPEndPoint(IPAddress.Any, port);
- private void AddMessageResponder(string message, bool isSubstring, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task> responder)
- {
- _responders.Add(new Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>(message, isSubstring, responder));
+ _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
- /// <summary>
- /// Raises the <see cref="E:MessageReceived" /> event.
- /// </summary>
- private async void OnMessageReceived(GenericEventArgs<SocketReceiveResult> e)
+ private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
{
- var message = e.Argument;
-
- var encoding = Encoding.UTF8;
- var responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
-
- if (responder == null)
- {
- encoding = Encoding.Unicode;
- responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
- }
-
- if (responder != null)
+ string? localUrl = _config[AddressOverrideConfigKey];
+ if (string.IsNullOrEmpty(localUrl))
{
- var cancellationToken = CancellationToken.None;
-
- try
- {
- await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
-
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in OnMessageReceived");
- }
+ localUrl = _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
}
- }
-
- private Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding)
- {
- var text = encoding.GetString(buffer, 0, bytesReceived);
- var responder = _responders.FirstOrDefault(i =>
- {
- if (i.Item2)
- {
- return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1;
- }
- return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase);
- });
- if (responder == null)
+ if (string.IsNullOrEmpty(localUrl))
{
- return null;
+ _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
+ return;
}
- return new Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>>(text, responder);
- }
- private async Task RespondToV2Message(string messageText, IpEndPointInfo endpoint, Encoding encoding, CancellationToken cancellationToken)
- {
- var parts = messageText.Split('|');
-
- var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
+ var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName);
- if (!string.IsNullOrEmpty(localUrl))
+ try
{
- var response = new ServerDiscoveryInfo
- {
- Address = localUrl,
- Id = _appHost.SystemId,
- Name = _appHost.FriendlyName
- };
-
- await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint, cancellationToken).ConfigureAwait(false);
-
- if (parts.Length > 1)
- {
- _appHost.EnableLoopback(parts[1]);
- }
+ await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
}
- else
+ catch (SocketException ex)
{
- _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
+ _logger.LogError(ex, "Error sending response message");
}
}
/// <summary>
- /// The _udp client
- /// </summary>
- private ISocket _udpClient;
- private readonly ISocketFactory _socketFactory;
-
- /// <summary>
/// Starts the specified port.
/// </summary>
- /// <param name="port">The port.</param>
- public void Start(int port)
+ /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
+ public void Start(CancellationToken cancellationToken)
{
- _udpClient = _socketFactory.CreateUdpSocket(port);
+ _udpSocket.Bind(_endpoint);
- Task.Run(() => BeginReceive());
+ _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
- private readonly byte[] _receiveBuffer = new byte[8192];
-
- private void BeginReceive()
+ private async Task BeginReceiveAsync(CancellationToken cancellationToken)
{
- if (_isDisposed)
- {
- return;
- }
-
- try
+ var infiniteTask = Task.Delay(-1, cancellationToken);
+ while (!cancellationToken.IsCancellationRequested)
{
- var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult);
-
- if (result.CompletedSynchronously)
+ try
{
- OnReceiveResult(result);
- }
- }
- catch (ObjectDisposedException)
- {
- //TODO Investigate and properly fix.
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error receiving udp message");
- }
- }
-
- private void OnReceiveResult(IAsyncResult result)
- {
- if (_isDisposed)
- {
- return;
- }
-
- try
- {
- var socketResult = _udpClient.EndReceive(result);
-
- OnMessageReceived(socketResult);
- }
- catch (ObjectDisposedException)
- {
- //TODO Investigate and properly fix.
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error receiving udp message");
- }
-
- BeginReceive();
- }
+ var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
+ await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
- /// <summary>
- /// Called when [message received].
- /// </summary>
- /// <param name="message">The message.</param>
- private void OnMessageReceived(SocketReceiveResult message)
- {
- if (_isDisposed)
- {
- return;
- }
+ if (!task.IsCompleted)
+ {
+ return;
+ }
- if (message.RemoteEndPoint.Port == 0)
- {
- return;
- }
+ var result = task.Result;
- try
- {
- OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
+ var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
+ if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
+ {
+ await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (SocketException ex)
{
- Argument = message
- });
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error handling UDP message");
- }
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- }
-
- /// <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)
- {
- _isDisposed = true;
-
- if (_udpClient != null)
+ _logger.LogError(ex, "Failed to receive data from socket");
+ }
+ catch (OperationCanceledException)
{
- _udpClient.Dispose();
+ // Don't throw
}
}
}
- public async Task SendAsync(byte[] bytes, IpEndPointInfo remoteEndPoint, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public void Dispose()
{
- if (_isDisposed)
+ if (_disposed)
{
- throw new ObjectDisposedException(GetType().Name);
- }
-
- if (bytes == null)
- {
- throw new ArgumentNullException(nameof(bytes));
- }
-
- if (remoteEndPoint == null)
- {
- throw new ArgumentNullException(nameof(remoteEndPoint));
+ return;
}
- try
- {
- await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false);
-
- _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint);
- }
- catch (OperationCanceledException)
- {
+ _udpSocket?.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint);
- }
+ GC.SuppressFinalize(this);
}
}
-
}
diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs
index 301802b8a..4a022c5db 100644
--- a/Emby.Server.Implementations/Updates/InstallationManager.cs
+++ b/Emby.Server.Implementations/Updates/InstallationManager.cs
@@ -3,465 +3,347 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common;
+using Jellyfin.Data.Events;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.Events;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
+using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Updates;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Updates
{
/// <summary>
- /// Manages all install, uninstall and update operations (both plugins and system)
+ /// Manages all install, uninstall, and update operations for the system and individual plugins.
/// </summary>
public class InstallationManager : IInstallationManager
{
- public event EventHandler<InstallationEventArgs> PackageInstalling;
- public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
- public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
- public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
-
/// <summary>
- /// The current installations
+ /// The logger.
/// </summary>
- public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
+ private readonly ILogger<InstallationManager> _logger;
+ private readonly IApplicationPaths _appPaths;
+ private readonly IEventManager _eventManager;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly IServerConfigurationManager _config;
+ private readonly JsonSerializerOptions _jsonSerializerOptions;
+ private readonly IPluginManager _pluginManager;
/// <summary>
- /// The completed installations
+ /// Gets the application host.
/// </summary>
- private ConcurrentBag<InstallationInfo> CompletedInstallationsInternal { get; set; }
-
- public IEnumerable<InstallationInfo> CompletedInstallations => CompletedInstallationsInternal;
+ /// <value>The application host.</value>
+ private readonly IServerApplicationHost _applicationHost;
+ private readonly IZipClient _zipClient;
+ private readonly object _currentInstallationsLock = new object();
- #region PluginUninstalled Event
/// <summary>
- /// Occurs when [plugin uninstalled].
+ /// The current installations.
/// </summary>
- public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
+ private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
/// <summary>
- /// Called when [plugin uninstalled].
+ /// The completed installations.
/// </summary>
- /// <param name="plugin">The plugin.</param>
- private void OnPluginUninstalled(IPlugin plugin)
- {
- PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
- }
- #endregion
+ private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
- #region PluginUpdated Event
- /// <summary>
- /// Occurs when [plugin updated].
- /// </summary>
- public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
/// <summary>
- /// Called when [plugin updated].
+ /// Initializes a new instance of the <see cref="InstallationManager"/> class.
/// </summary>
- /// <param name="plugin">The plugin.</param>
- /// <param name="newVersion">The new version.</param>
- private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
- {
- _logger.LogInformation("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification);
-
- PluginUpdated?.Invoke(this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) });
-
- _applicationHost.NotifyPendingRestart();
- }
- #endregion
-
- #region PluginInstalled Event
- /// <summary>
- /// Occurs when [plugin updated].
- /// </summary>
- public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
- /// <summary>
- /// Called when [plugin installed].
- /// </summary>
- /// <param name="package">The package.</param>
- private void OnPluginInstalled(PackageVersionInfo package)
- {
- _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
-
- PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo> { Argument = package });
-
- _applicationHost.NotifyPendingRestart();
- }
- #endregion
-
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
- private readonly IApplicationPaths _appPaths;
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IServerConfigurationManager _config;
- private readonly IFileSystem _fileSystem;
-
- /// <summary>
- /// Gets the application host.
- /// </summary>
- /// <value>The application host.</value>
- private readonly IApplicationHost _applicationHost;
-
- private readonly ICryptoProvider _cryptographyProvider;
- private readonly IZipClient _zipClient;
-
- // netframework or netcore
- private readonly string _packageRuntime;
-
+ /// <param name="logger">The <see cref="ILogger{InstallationManager}"/>.</param>
+ /// <param name="appHost">The <see cref="IServerApplicationHost"/>.</param>
+ /// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param>
+ /// <param name="eventManager">The <see cref="IEventManager"/>.</param>
+ /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
+ /// <param name="config">The <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="zipClient">The <see cref="IZipClient"/>.</param>
+ /// <param name="pluginManager">The <see cref="IPluginManager"/>.</param>
public InstallationManager(
- ILoggerFactory loggerFactory,
- IApplicationHost appHost,
+ ILogger<InstallationManager> logger,
+ IServerApplicationHost appHost,
IApplicationPaths appPaths,
- IHttpClient httpClient,
- IJsonSerializer jsonSerializer,
+ IEventManager eventManager,
+ IHttpClientFactory httpClientFactory,
IServerConfigurationManager config,
- IFileSystem fileSystem,
- ICryptoProvider cryptographyProvider,
IZipClient zipClient,
- string packageRuntime)
+ IPluginManager pluginManager)
{
- if (loggerFactory == null)
- {
- throw new ArgumentNullException(nameof(loggerFactory));
- }
-
- CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
- CompletedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
+ _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
+ _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
+ _logger = logger;
_applicationHost = appHost;
_appPaths = appPaths;
- _httpClient = httpClient;
- _jsonSerializer = jsonSerializer;
+ _eventManager = eventManager;
+ _httpClientFactory = httpClientFactory;
_config = config;
- _fileSystem = fileSystem;
- _cryptographyProvider = cryptographyProvider;
_zipClient = zipClient;
- _packageRuntime = packageRuntime;
- _logger = loggerFactory.CreateLogger(nameof(InstallationManager));
- }
-
- private static Version GetPackageVersion(PackageVersionInfo version)
- {
- return new Version(ValueOrDefault(version.versionStr, "0.0.0.1"));
+ _jsonSerializerOptions = JsonDefaults.Options;
+ _pluginManager = pluginManager;
}
- private static string ValueOrDefault(string str, string def)
- {
- return string.IsNullOrEmpty(str) ? def : str;
- }
+ /// <inheritdoc />
+ public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
- /// <summary>
- /// Gets all available packages.
- /// </summary>
- /// <returns>Task{List{PackageInfo}}.</returns>
- public async Task<List<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
- bool withRegistration = true,
- string packageType = null,
- Version applicationVersion = null)
+ /// <inheritdoc />
+ public async Task<PackageInfo[]> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default)
{
- var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
- return FilterPackages(packages, packageType, applicationVersion);
- }
-
- /// <summary>
- /// Gets all available packages.
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{List{PackageInfo}}.</returns>
- public async Task<List<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken)
- {
- using (var response = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = "https://repo.jellyfin.org/releases/plugin/manifest.json",
- CancellationToken = cancellationToken,
- Progress = new SimpleProgress<double>(),
- CacheLength = GetCacheLength()
- }, "GET").ConfigureAwait(false))
+ try
{
- using (var stream = response.Content)
+ PackageInfo[]? packages = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetFromJsonAsync<PackageInfo[]>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false);
+
+ if (packages == null)
{
- return FilterPackages(await _jsonSerializer.DeserializeFromStreamAsync<PackageInfo[]>(stream).ConfigureAwait(false));
+ return Array.Empty<PackageInfo>();
}
- }
- }
- private PackageVersionClass GetSystemUpdateLevel()
- {
- return _applicationHost.SystemUpdateLevel;
- }
-
- private static TimeSpan GetCacheLength()
- {
- return TimeSpan.FromMinutes(3);
- }
-
- protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages)
- {
- var list = new List<PackageInfo>();
-
- foreach (var package in packages)
- {
- var versions = new List<PackageVersionInfo>();
- foreach (var version in package.versions)
+ var minimumVersion = new Version(0, 0, 0, 1);
+ // Store the repository and repository url with each version, as they may be spread apart.
+ foreach (var entry in packages)
{
- if (string.IsNullOrEmpty(version.sourceUrl))
- {
- continue;
- }
-
- if (string.IsNullOrEmpty(version.runtimes) || version.runtimes.IndexOf(_packageRuntime, StringComparison.OrdinalIgnoreCase) == -1)
+ for (int a = entry.Versions.Count - 1; a >= 0; a--)
{
- continue;
+ var ver = entry.Versions[a];
+ ver.RepositoryName = manifestName;
+ ver.RepositoryUrl = manifest;
+
+ if (!filterIncompatible)
+ {
+ continue;
+ }
+
+ if (!Version.TryParse(ver.TargetAbi, out var targetAbi))
+ {
+ targetAbi = minimumVersion;
+ }
+
+ // Only show plugins that are greater than or equal to targetAbi.
+ if (_applicationHost.ApplicationVersion >= targetAbi)
+ {
+ continue;
+ }
+
+ // Not compatible with this version so remove it.
+ entry.Versions.Remove(ver);
}
-
- versions.Add(version);
}
- package.versions = versions
- .OrderByDescending(GetPackageVersion)
- .ToArray();
-
- if (package.versions.Length == 0)
- {
- continue;
- }
-
- list.Add(package);
+ return packages;
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Cannot locate the plugin manifest {Manifest}", manifest);
+ return Array.Empty<PackageInfo>();
+ }
+ catch (JsonException ex)
+ {
+ _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
+ return Array.Empty<PackageInfo>();
+ }
+ catch (UriFormatException ex)
+ {
+ _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
+ return Array.Empty<PackageInfo>();
+ }
+ catch (HttpRequestException ex)
+ {
+ _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
+ return Array.Empty<PackageInfo>();
}
-
- // Remove packages with no versions
- return list;
}
- protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages, string packageType, Version applicationVersion)
+ /// <inheritdoc />
+ public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
{
- var packagesList = FilterPackages(packages);
-
- var returnList = new List<PackageInfo>();
-
- var filterOnPackageType = !string.IsNullOrEmpty(packageType);
-
- foreach (var p in packagesList)
+ var result = new List<PackageInfo>();
+ foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
{
- if (filterOnPackageType && !string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase))
+ if (repository.Enabled && repository.Url != null)
{
- continue;
- }
-
- // If an app version was supplied, filter the versions for each package to only include supported versions
- if (applicationVersion != null)
- {
- p.versions = p.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToArray();
- }
-
- if (p.versions.Length == 0)
- {
- continue;
+ // Where repositories have the same content, the details from the first is taken.
+ foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true))
+ {
+ var existing = FilterPackages(result, package.Name, package.Id).FirstOrDefault();
+
+ // Remove invalid versions from the valid package.
+ for (var i = package.Versions.Count - 1; i >= 0; i--)
+ {
+ var version = package.Versions[i];
+
+ var plugin = _pluginManager.GetPlugin(package.Id, version.VersionNumber);
+ if (plugin != null)
+ {
+ await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
+ }
+
+ // Remove versions with a target ABI greater then the current application version.
+ if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi)
+ {
+ package.Versions.RemoveAt(i);
+ }
+ }
+
+ // Don't add a package that doesn't have any compatible versions.
+ if (package.Versions.Count == 0)
+ {
+ continue;
+ }
+
+ if (existing != null)
+ {
+ // Assumption is both lists are ordered, so slot these into the correct place.
+ MergeSortedList(existing.Versions, package.Versions);
+ }
+ else
+ {
+ result.Add(package);
+ }
+ }
}
-
- returnList.Add(p);
}
- return returnList;
+ return result;
}
- /// <summary>
- /// Determines whether [is package version up to date] [the specified package version info].
- /// </summary>
- /// <param name="packageVersionInfo">The package version info.</param>
- /// <param name="currentServerVersion">The current server version.</param>
- /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
- private static bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
+ /// <inheritdoc />
+ public IEnumerable<PackageInfo> FilterPackages(
+ IEnumerable<PackageInfo> availablePackages,
+ string? name = null,
+ Guid id = default,
+ Version? specificVersion = null)
{
- if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
+ if (name != null)
{
- return true;
+ availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}
- return Version.TryParse(packageVersionInfo.requiredVersionStr, out var requiredVersion) && currentServerVersion >= requiredVersion;
- }
-
- /// <summary>
- /// Gets the package.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="guid">The assembly guid</param>
- /// <param name="classification">The classification.</param>
- /// <param name="version">The version.</param>
- /// <returns>Task{PackageVersionInfo}.</returns>
- public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
- {
- var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
-
- var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
- ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ if (id != default)
+ {
+ availablePackages = availablePackages.Where(x => x.Id == id);
+ }
- if (package == null)
+ if (specificVersion != null)
{
- return null;
+ availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion)));
}
- return package.versions.FirstOrDefault(v => GetPackageVersion(v).Equals(version) && v.classification == classification);
+ return availablePackages;
}
- /// <summary>
- /// Gets the latest compatible version.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="guid">The assembly guid if this is a plug-in</param>
- /// <param name="currentServerVersion">The current server version.</param>
- /// <param name="classification">The classification.</param>
- /// <returns>Task{PackageVersionInfo}.</returns>
- public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
+ /// <inheritdoc />
+ public IEnumerable<InstallationInfo> GetCompatibleVersions(
+ IEnumerable<PackageInfo> availablePackages,
+ string? name = null,
+ Guid id = default,
+ Version? minVersion = null,
+ Version? specificVersion = null)
{
- var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
-
- return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
- }
-
- /// <summary>
- /// Gets the latest compatible version.
- /// </summary>
- /// <param name="availablePackages">The available packages.</param>
- /// <param name="name">The name.</param>
- /// <param name="currentServerVersion">The current server version.</param>
- /// <param name="classification">The classification.</param>
- /// <returns>PackageVersionInfo.</returns>
- public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
- {
- var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
- ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ var package = FilterPackages(availablePackages, name, id, specificVersion).FirstOrDefault();
+ // Package not found in repository
if (package == null)
{
- return null;
+ yield break;
}
- return package.versions
- .OrderByDescending(GetPackageVersion)
- .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
- }
-
- /// <summary>
- /// Gets the available plugin updates.
- /// </summary>
- /// <param name="applicationVersion">The current server version.</param>
- /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
- public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
- {
- var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
-
- var systemUpdateLevel = GetSystemUpdateLevel();
+ var appVer = _applicationHost.ApplicationVersion;
+ var availableVersions = package.Versions
+ .Where(x => string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer);
- // Figure out what needs to be installed
- return _applicationHost.Plugins.Select(p =>
+ if (specificVersion != null)
+ {
+ availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
+ }
+ else if (minVersion != null)
{
- var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel);
+ availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
+ }
- return latestPluginInfo != null && GetPackageVersion(latestPluginInfo) > p.Version ? latestPluginInfo : null;
+ foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
+ {
+ yield return new InstallationInfo
+ {
+ Changelog = v.Changelog,
+ Id = package.Id,
+ Name = package.Name,
+ Version = v.VersionNumber,
+ SourceUrl = v.SourceUrl,
+ Checksum = v.Checksum,
+ PackageInfo = package
+ };
+ }
+ }
- }).Where(i => i != null)
- .Where(p => !string.IsNullOrEmpty(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
+ /// <inheritdoc />
+ public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
+ {
+ var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
+ return GetAvailablePluginUpdates(catalog);
}
- /// <summary>
- /// Installs the package.
- /// </summary>
- /// <param name="package">The package.</param>
- /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">package</exception>
- public async Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
- if (progress == null)
- {
- throw new ArgumentNullException(nameof(progress));
- }
-
- var installationInfo = new InstallationInfo
- {
- Id = Guid.NewGuid(),
- Name = package.name,
- AssemblyGuid = package.guid,
- UpdateClass = package.classification,
- Version = package.versionStr
- };
-
var innerCancellationTokenSource = new CancellationTokenSource();
- var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
+ var tuple = (package, innerCancellationTokenSource);
// Add it to the in-progress list
- lock (CurrentInstallations)
+ lock (_currentInstallationsLock)
{
- CurrentInstallations.Add(tuple);
+ _currentInstallations.Add(tuple);
}
- var innerProgress = new ActionableProgress<double>();
-
- // Whenever the progress updates, update the outer progress object and InstallationInfo
- innerProgress.RegisterAction(percent =>
- {
- progress.Report(percent);
+ using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
+ var linkedToken = linkedTokenSource.Token;
- installationInfo.PercentComplete = percent;
- });
-
- var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
-
- var installationEventArgs = new InstallationEventArgs
- {
- InstallationInfo = installationInfo,
- PackageVersionInfo = package
- };
-
- PackageInstalling?.Invoke(this, installationEventArgs);
+ await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
try
{
- await InstallPackageInternal(package, isPlugin, innerProgress, linkedToken).ConfigureAwait(false);
+ var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
- lock (CurrentInstallations)
+ lock (_currentInstallationsLock)
{
- CurrentInstallations.Remove(tuple);
+ _currentInstallations.Remove(tuple);
}
- CompletedInstallationsInternal.Add(installationInfo);
+ _completedInstallationsInternal.Add(package);
+ await _eventManager.PublishAsync(isUpdate
+ ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
+ : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
- PackageInstallationCompleted?.Invoke(this, installationEventArgs);
+ _applicationHost.NotifyPendingRestart();
}
catch (OperationCanceledException)
{
- lock (CurrentInstallations)
+ lock (_currentInstallationsLock)
{
- CurrentInstallations.Remove(tuple);
+ _currentInstallations.Remove(tuple);
}
- _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
+ _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
- PackageInstallationCancelled?.Invoke(this, installationEventArgs);
+ await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
throw;
}
@@ -469,181 +351,229 @@ namespace Emby.Server.Implementations.Updates
{
_logger.LogError(ex, "Package installation failed");
- lock (CurrentInstallations)
+ lock (_currentInstallationsLock)
{
- CurrentInstallations.Remove(tuple);
+ _currentInstallations.Remove(tuple);
}
- PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
+ await _eventManager.PublishAsync(new InstallationFailedEventArgs
{
- InstallationInfo = installationInfo,
+ InstallationInfo = package,
Exception = ex
- });
+ }).ConfigureAwait(false);
throw;
}
finally
{
// Dispose the progress object and remove the installation from the in-progress list
- tuple.Item2.Dispose();
+ tuple.innerCancellationTokenSource.Dispose();
}
}
/// <summary>
- /// Installs the package internal.
+ /// Uninstalls a plugin.
/// </summary>
- /// <param name="package">The package.</param>
- /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken)
+ /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param>
+ public void UninstallPlugin(LocalPlugin plugin)
{
- IPlugin plugin = null;
+ if (plugin == null)
+ {
+ return;
+ }
- if (isPlugin)
+ if (plugin.Instance?.CanUninstall == false)
{
- // Set last update time if we were installed before
- plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
- ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
+ _logger.LogWarning("Attempt to delete non removable plugin {PluginName}, ignoring request", plugin.Name);
+ return;
}
- string targetPath = plugin == null ? null : plugin.AssemblyFilePath;
+ plugin.Instance?.OnUninstalling();
+
+ // Remove it the quick way for now
+ _pluginManager.RemovePlugin(plugin);
+
+ _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo()));
- // Do the install
- await PerformPackageInstallation(progress, targetPath, package, cancellationToken).ConfigureAwait(false);
+ _applicationHost.NotifyPendingRestart();
+ }
- // Do plugin-specific processing
- if (isPlugin)
+ /// <inheritdoc/>
+ public bool CancelInstallation(Guid id)
+ {
+ lock (_currentInstallationsLock)
{
- if (plugin == null)
+ var install = _currentInstallations.Find(x => x.info.Id == id);
+ if (install == default((InstallationInfo, CancellationTokenSource)))
{
- OnPluginInstalled(package);
- }
- else
- {
- OnPluginUpdated(plugin, package);
+ return false;
}
+
+ install.token.Cancel();
+ _currentInstallations.Remove(install);
+ return true;
}
}
- private async Task PerformPackageInstallation(IProgress<double> progress, string target, PackageVersionInfo package, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public void Dispose()
{
- var extension = Path.GetExtension(package.targetFilename);
- var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase);
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- if (!isArchive)
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ if (dispose)
{
- _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
- return;
- }
+ lock (_currentInstallationsLock)
+ {
+ foreach (var (info, token) in _currentInstallations)
+ {
+ token.Dispose();
+ }
- if (target == null)
- {
- target = Path.Combine(_appPaths.PluginsPath, Path.GetFileNameWithoutExtension(package.targetFilename));
+ _currentInstallations.Clear();
+ }
}
+ }
- // Download to temporary file so that, if interrupted, it won't destroy the existing installation
- var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
- {
- Url = package.sourceUrl,
- CancellationToken = cancellationToken,
- Progress = progress
+ /// <summary>
+ /// Merges two sorted lists.
+ /// </summary>
+ /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param>
+ /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param>
+ private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest)
+ {
+ int sLength = source.Count - 1;
+ int dLength = dest.Count;
+ int s = 0, d = 0;
+ var sourceVersion = source[0].VersionNumber;
+ var destVersion = dest[0].VersionNumber;
- }).ConfigureAwait(false);
+ while (d < dLength)
+ {
+ if (sourceVersion.CompareTo(destVersion) >= 0)
+ {
+ if (s < sLength)
+ {
+ sourceVersion = source[++s].VersionNumber;
+ }
+ else
+ {
+ // Append all of destination to the end of source.
+ while (d < dLength)
+ {
+ source.Add(dest[d++]);
+ }
- cancellationToken.ThrowIfCancellationRequested();
+ break;
+ }
+ }
+ else
+ {
+ source.Insert(s++, dest[d++]);
+ if (d >= dLength)
+ {
+ break;
+ }
- // TODO: Validate with a checksum, *properly*
+ sLength++;
+ destVersion = dest[d].VersionNumber;
+ }
+ }
+ }
- // Success - move it to the real target
- try
+ private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
+ {
+ var plugins = _pluginManager.Plugins;
+ foreach (var plugin in plugins)
{
- using (var stream = File.OpenRead(tempFile))
+ // Don't auto update when plugin marked not to, or when it's disabled.
+ if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == PluginStatus.Disabled)
{
- _zipClient.ExtractAllFromZip(stream, target, true);
+ continue;
}
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error attempting to extract {TempFile} to {TargetFile}", tempFile, target);
- throw;
- }
- try
- {
- _fileSystem.DeleteFile(tempFile);
- }
- catch (IOException ex)
- {
- // Don't fail because of this
- _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile);
+ var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
+ var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
+
+ if (version != null && CompletedInstallations.All(x => x.Id != version.Id))
+ {
+ yield return version;
+ }
}
}
- /// <summary>
- /// Uninstalls a plugin
- /// </summary>
- /// <param name="plugin">The plugin.</param>
- /// <exception cref="ArgumentException"></exception>
- public void UninstallPlugin(IPlugin plugin)
+ private async Task PerformPackageInstallation(InstallationInfo package, PluginStatus status, CancellationToken cancellationToken)
{
- plugin.OnUninstalling();
+ var extension = Path.GetExtension(package.SourceUrl);
+ if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
+ {
+ _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
+ return;
+ }
- // Remove it the quick way for now
- _applicationHost.RemovePlugin(plugin);
+ // Always override the passed-in target (which is a file) and figure it out again
+ string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
- var path = plugin.AssemblyFilePath;
- _logger.LogInformation("Deleting plugin file {0}", path);
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- // Make this case-insensitive to account for possible incorrect assembly naming
- var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
- .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
+ // CA5351: Do Not Use Broken Cryptographic Algorithms
+#pragma warning disable CA5351
+ using var md5 = MD5.Create();
+ cancellationToken.ThrowIfCancellationRequested();
- if (!string.IsNullOrWhiteSpace(file))
+ var hash = Convert.ToHexString(md5.ComputeHash(stream));
+ if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
{
- path = file;
+ _logger.LogError(
+ "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
+ package.Name,
+ package.Checksum,
+ hash);
+ throw new InvalidDataException("The checksum of the received data doesn't match.");
}
- _fileSystem.DeleteFile(path);
+ // Version folder as they cannot be overwritten in Windows.
+ targetDir += "_" + package.Version;
- var list = _config.Configuration.UninstalledPlugins.ToList();
- var filename = Path.GetFileName(path);
- if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
+ if (Directory.Exists(targetDir))
{
- list.Add(filename);
- _config.Configuration.UninstalledPlugins = list.ToArray();
- _config.SaveConfiguration();
+ try
+ {
+ Directory.Delete(targetDir, true);
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ // Ignore any exceptions.
+ }
}
- OnPluginUninstalled(plugin);
-
- _applicationHost.NotifyPendingRestart();
+ stream.Position = 0;
+ _zipClient.ExtractAllFromZip(stream, targetDir, true);
+ await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false);
+ _pluginManager.ImportPluginFrom(targetDir);
}
- /// <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)
+ private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
{
- if (dispose)
- {
- lock (CurrentInstallations)
- {
- foreach (var tuple in CurrentInstallations)
- {
- tuple.Item2.Dispose();
- }
+ LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version))
+ ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version));
- CurrentInstallations.Clear();
- }
- }
- }
+ await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false);
+ _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version);
- public void Dispose()
- {
- Dispose(true);
+ return plugin != null;
}
}
}
diff --git a/Emby.Server.Implementations/UserViews/FolderImageProvider.cs b/Emby.Server.Implementations/UserViews/FolderImageProvider.cs
deleted file mode 100644
index c810004ab..000000000
--- a/Emby.Server.Implementations/UserViews/FolderImageProvider.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using System.Collections.Generic;
-using Emby.Server.Implementations.Images;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-
-namespace Emby.Server.Implementations.UserViews
-{
- public abstract class BaseFolderImageProvider<T> : BaseDynamicImageProvider<T>
- where T : Folder, new()
- {
- protected ILibraryManager _libraryManager;
-
- public BaseFolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
- : base(fileSystem, providerManager, applicationPaths, imageProcessor)
- {
- _libraryManager = libraryManager;
- }
-
- protected override List<BaseItem> GetItemsWithImages(BaseItem item)
- {
- return _libraryManager.GetItemList(new InternalItemsQuery
- {
- Parent = item,
- DtoOptions = new DtoOptions(true),
- ImageTypes = new ImageType[] { ImageType.Primary },
- OrderBy = new System.ValueTuple<string, SortOrder>[]
- {
- new System.ValueTuple<string, SortOrder>(ItemSortBy.IsFolder, SortOrder.Ascending),
- new System.ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending)
- },
- Limit = 1
- });
- }
-
- protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
- {
- return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
- }
-
- protected override bool Supports(BaseItem item)
- {
- return item is T;
- }
-
- protected override bool HasChangedByDate(BaseItem item, ItemImageInfo image)
- {
- if (item is MusicAlbum)
- {
- return false;
- }
-
- return base.HasChangedByDate(item, image);
- }
- }
-
- public class FolderImageProvider : BaseFolderImageProvider<Folder>
- {
- public FolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
- : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
- {
- }
-
- protected override bool Supports(BaseItem item)
- {
- if (item is PhotoAlbum || item is MusicAlbum)
- {
- return false;
- }
-
- var folder = item as Folder;
- if (folder != null)
- {
- if (folder.IsTopParent)
- {
- return false;
- }
- }
- return true;
- //return item.SourceType == SourceType.Library;
- }
- }
-
- public class MusicAlbumImageProvider : BaseFolderImageProvider<MusicAlbum>
- {
- public MusicAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
- : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
- {
- }
- }
-
- public class PhotoAlbumImageProvider : BaseFolderImageProvider<PhotoAlbum>
- {
- public PhotoAlbumImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
- : base(fileSystem, providerManager, applicationPaths, imageProcessor, libraryManager)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/Xml/XmlReaderSettingsFactory.cs b/Emby.Server.Implementations/Xml/XmlReaderSettingsFactory.cs
deleted file mode 100644
index 308922e6d..000000000
--- a/Emby.Server.Implementations/Xml/XmlReaderSettingsFactory.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.Xml;
-using MediaBrowser.Model.Xml;
-
-namespace Emby.Server.Implementations.Xml
-{
- public class XmlReaderSettingsFactory : IXmlReaderSettingsFactory
- {
- public XmlReaderSettings Create(bool enableValidation)
- {
- var settings = new XmlReaderSettings();
-
- if (!enableValidation)
- {
- settings.ValidationType = ValidationType.None;
- }
-
- return settings;
- }
- }
-}
diff --git a/Emby.XmlTv/.gitattributes b/Emby.XmlTv/.gitattributes
deleted file mode 100644
index 1ff0c4230..000000000
--- a/Emby.XmlTv/.gitattributes
+++ /dev/null
@@ -1,63 +0,0 @@
-###############################################################################
-# Set default behavior to automatically normalize line endings.
-###############################################################################
-* text=auto
-
-###############################################################################
-# Set default behavior for command prompt diff.
-#
-# This is need for earlier builds of msysgit that does not have it on by
-# default for csharp files.
-# Note: This is only used by command line
-###############################################################################
-#*.cs diff=csharp
-
-###############################################################################
-# Set the merge driver for project and solution files
-#
-# Merging from the command prompt will add diff markers to the files if there
-# are conflicts (Merging from VS is not affected by the settings below, in VS
-# the diff markers are never inserted). Diff markers may cause the following
-# file extensions to fail to load in VS. An alternative would be to treat
-# these files as binary and thus will always conflict and require user
-# intervention with every merge. To do so, just uncomment the entries below
-###############################################################################
-#*.sln merge=binary
-#*.csproj merge=binary
-#*.vbproj merge=binary
-#*.vcxproj merge=binary
-#*.vcproj merge=binary
-#*.dbproj merge=binary
-#*.fsproj merge=binary
-#*.lsproj merge=binary
-#*.wixproj merge=binary
-#*.modelproj merge=binary
-#*.sqlproj merge=binary
-#*.wwaproj merge=binary
-
-###############################################################################
-# behavior for image files
-#
-# image files are treated as binary by default.
-###############################################################################
-#*.jpg binary
-#*.png binary
-#*.gif binary
-
-###############################################################################
-# diff behavior for common document formats
-#
-# Convert binary document formats to text before diffing them. This feature
-# is only available from the command line. Turn it on by uncommenting the
-# entries below.
-###############################################################################
-#*.doc diff=astextplain
-#*.DOC diff=astextplain
-#*.docx diff=astextplain
-#*.DOCX diff=astextplain
-#*.dot diff=astextplain
-#*.DOT diff=astextplain
-#*.pdf diff=astextplain
-#*.PDF diff=astextplain
-#*.rtf diff=astextplain
-#*.RTF diff=astextplain
diff --git a/Emby.XmlTv/.gitignore b/Emby.XmlTv/.gitignore
deleted file mode 100644
index b06e864a3..000000000
--- a/Emby.XmlTv/.gitignore
+++ /dev/null
@@ -1,212 +0,0 @@
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-
-# User-specific files
-*.suo
-*.user
-*.userosscache
-*.sln.docstates
-
-# User-specific files (MonoDevelop/Xamarin Studio)
-*.userprefs
-
-# Build results
-[Dd]ebug/
-[Dd]ebugPublic/
-[Rr]elease/
-[Rr]eleases/
-x64/
-x86/
-build/
-bld/
-[Bb]in/
-[Oo]bj/
-
-# Visual Studio 2015 cache/options directory
-.vs/
-
-# MSTest test Results
-[Tt]est[Rr]esult*/
-[Bb]uild[Ll]og.*
-
-# NUNIT
-*.VisualState.xml
-TestResult.xml
-
-# Build Results of an ATL Project
-[Dd]ebugPS/
-[Rr]eleasePS/
-dlldata.c
-
-# DNX
-project.lock.json
-artifacts/
-
-*_i.c
-*_p.c
-*_i.h
-*.ilk
-*.meta
-*.obj
-*.pch
-*.pdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.tmp_proj
-*.log
-*.vspscc
-*.vssscc
-.builds
-*.pidb
-*.svclog
-*.scc
-
-# Chutzpah Test files
-_Chutzpah*
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opensdf
-*.sdf
-*.cachefile
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-
-# TFS 2012 Local Workspace
-$tf/
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*/
-*.[Rr]e[Ss]harper
-*.DotSettings.user
-
-# JustCode is a .NET coding add-in
-.JustCode
-
-# TeamCity is a build add-in
-_TeamCity*
-
-# DotCover is a Code Coverage Tool
-*.dotCover
-
-# NCrunch
-_NCrunch_*
-.*crunch*.local.xml
-
-# MightyMoose
-*.mm.*
-AutoTest.Net/
-
-# Web workbench (sass)
-.sass-cache/
-
-# Installshield output folder
-[Ee]xpress/
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish/
-
-# Publish Web Output
-*.[Pp]ublish.xml
-*.azurePubxml
-## TODO: Comment the next line if you want to checkin your
-## web deploy settings but do note that will include unencrypted
-## passwords
-#*.pubxml
-
-*.publishproj
-
-# NuGet Packages
-*.nupkg
-# The packages folder can be ignored because of Package Restore
-**/packages/*
-# except build/, which is used as an MSBuild target.
-!**/packages/build/
-# Uncomment if necessary however generally it will be regenerated when needed
-#!**/packages/repositories.config
-
-# Windows Azure Build Output
-csx/
-*.build.csdef
-
-# Windows Store app package directory
-AppPackages/
-
-# Visual Studio cache files
-# files ending in .cache can be ignored
-*.[Cc]ache
-# but keep track of directories ending in .cache
-!*.[Cc]ache/
-
-# Others
-ClientBin/
-[Ss]tyle[Cc]op.*
-~$*
-*~
-*.dbmdl
-*.dbproj.schemaview
-*.pfx
-*.publishsettings
-node_modules/
-orleans.codegen.cs
-
-# RIA/Silverlight projects
-Generated_Code/
-
-# Backup & report files from converting an old project file
-# to a newer Visual Studio version. Backup files are not needed,
-# because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-UpgradeLog*.htm
-
-# SQL Server files
-*.mdf
-*.ldf
-
-# Business Intelligence projects
-*.rdl.data
-*.bim.layout
-*.bim_*.settings
-
-# Microsoft Fakes
-FakesAssemblies/
-
-# Node.js Tools for Visual Studio
-.ntvs_analysis.dat
-
-# Visual Studio 6 build log
-*.plg
-
-# Visual Studio 6 workspace options file
-*.opt
-
-# LightSwitch generated files
-GeneratedArtifacts/
-_Pvt_Extensions/
-ModelManifest.xml
diff --git a/Emby.XmlTv/Emby.XmlTv.Console/App.config b/Emby.XmlTv/Emby.XmlTv.Console/App.config
deleted file mode 100644
index 2d2a12d81..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Console/App.config
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
- </startup>
-</configuration>
diff --git a/Emby.XmlTv/Emby.XmlTv.Console/Classes/EntityExtensions.cs b/Emby.XmlTv/Emby.XmlTv.Console/Classes/EntityExtensions.cs
deleted file mode 100644
index 96e508f12..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Console/Classes/EntityExtensions.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-using System;
-using System.Linq;
-using System.Text;
-
-using Emby.XmlTv.Entities;
-
-namespace Emby.XmlTv.Console.Classes
-{
- public static class EntityExtensions
- {
- public static string GetHeader(this string text)
- {
- var channelHeaderString = " " + text;
-
- var builder = new StringBuilder();
- builder.AppendLine("".PadRight(5 + channelHeaderString.Length + 5, Char.Parse("*")));
- builder.AppendLine("".PadRight(5, Char.Parse("*")) + channelHeaderString + "".PadRight(5, Char.Parse("*")));
- builder.AppendLine("".PadRight(5 + channelHeaderString.Length + 5, Char.Parse("*")));
-
- return builder.ToString();
- }
-
- public static string GetChannelDetail(this XmlTvChannel channel)
- {
- var builder = new StringBuilder();
- builder.AppendFormat("Id: {0}\r\n", channel.Id);
- builder.AppendFormat("Display-Name: {0}\r\n", channel.DisplayName);
- builder.AppendFormat("Url: {0}\r\n", channel.Url);
- builder.AppendFormat("Icon: {0}\r\n", channel.Icon != null ? channel.Icon.ToString() : string.Empty);
- builder.AppendLine("-------------------------------------------------------");
-
- return builder.ToString();
- }
-
- public static string GetProgrammeDetail(this XmlTvProgram programme, XmlTvChannel channel)
- {
- var builder = new StringBuilder();
- builder.AppendFormat("Channel: {0} - {1}\r\n", channel.Id, channel.DisplayName);
- builder.AppendFormat("Start Date: {0:G}\r\n", programme.StartDate);
- builder.AppendFormat("End Date: {0:G}\r\n", programme.EndDate);
- builder.AppendFormat("Name: {0}\r\n", programme.Title);
- builder.AppendFormat("Episode Detail: {0}\r\n", programme.Episode);
- builder.AppendFormat("Episode Title: {0}\r\n", programme.Episode.Title);
- builder.AppendFormat("Description: {0}\r\n", programme.Description);
- builder.AppendFormat("Categories: {0}\r\n", string.Join(", ", programme.Categories));
- builder.AppendFormat("Countries: {0}\r\n", string.Join(", ", programme.Countries));
- builder.AppendFormat("Credits: {0}\r\n", string.Join(", ", programme.Credits));
- builder.AppendFormat("Rating: {0}\r\n", programme.Rating);
- builder.AppendFormat("Star Rating: {0}\r\n", programme.StarRating.HasValue ? programme.StarRating.Value.ToString() : string.Empty);
- builder.AppendFormat("Previously Shown: {0:G}\r\n", programme.PreviouslyShown);
- builder.AppendFormat("Copyright Date: {0:G}\r\n", programme.CopyrightDate);
- builder.AppendFormat("Is Repeat: {0}\r\n", programme.IsPreviouslyShown);
- builder.AppendFormat("Icon: {0}\r\n", programme.Icon != null ? programme.Icon.ToString() : string.Empty);
- builder.AppendLine("-------------------------------------------------------");
- return builder.ToString();
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv.Console/Emby.XmlTv.Console.csproj b/Emby.XmlTv/Emby.XmlTv.Console/Emby.XmlTv.Console.csproj
deleted file mode 100644
index c10b28e82..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Console/Emby.XmlTv.Console.csproj
+++ /dev/null
@@ -1,22 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
- <ItemGroup>
- <Reference Include="System" />
- <Reference Include="System.Core" />
- <Reference Include="System.Xml.Linq" />
- <Reference Include="Microsoft.CSharp" />
- <Reference Include="System.Data" />
- <Reference Include="System.Net.Http" />
- <Reference Include="System.Xml" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv.csproj">
- <Project>{0d023565-5942-4d79-9098-a1b4b6665a40}</Project>
- <Name>Emby.XmlTv</Name>
- </ProjectReference>
- </ItemGroup>
- <PropertyGroup>
- <TargetFramework>netcoreapp2.1</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/Emby.XmlTv/Emby.XmlTv.Console/Program.cs b/Emby.XmlTv/Emby.XmlTv.Console/Program.cs
deleted file mode 100644
index 3e0c7d125..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Console/Program.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-
-using Emby.XmlTv.Classes;
-using Emby.XmlTv.Console.Classes;
-using Emby.XmlTv.Entities;
-
-namespace Emby.XmlTv.Console
-{
- public class Program
- {
- static void Main(string[] args)
- {
- var filename = @"C:\Temp\QLD.GoldCoast.xml";
-
- if (args.Length == 1 && File.Exists(args[0]))
- {
- filename = args[0];
- }
-
- var timer = Stopwatch.StartNew();
- System.Console.WriteLine("Running XMLTv Parsing");
-
- var resultsFile = String.Format("C:\\Temp\\{0}_Results_{1:HHmmss}.txt",
- Path.GetFileNameWithoutExtension(filename),
- DateTimeOffset.UtcNow);
-
- System.Console.Write("Enter the language required: ");
- var lang = System.Console.ReadLine();
-
- ReadSourceXmlTvFile(filename, resultsFile, lang).Wait();
-
- System.Console.WriteLine("Completed in {0:g} - press any key to open the file...", timer.Elapsed);
- System.Console.ReadKey();
-
- Process.Start(resultsFile);
- }
-
- public static async Task ReadSourceXmlTvFile(string filename, string resultsFile, string lang)
- {
- System.Console.WriteLine("Writing to file: {0}", resultsFile);
-
- using (var resultsFileStream = new StreamWriter(resultsFile) { AutoFlush = true })
- {
- var reader = new XmlTvReader(filename, lang);
- await ReadOutChannels(reader, resultsFileStream);
-
- resultsFileStream.Close();
- }
- }
-
- public static async Task ReadOutChannels(XmlTvReader reader, StreamWriter resultsFileStream)
- {
- var channels = reader.GetChannels().Distinct().ToList();
-
- resultsFileStream.Write(EntityExtensions.GetHeader("Channels"));
-
- foreach (var channel in channels)
- {
- System.Console.WriteLine("Retrieved Channel: {0} - {1}", channel.Id, channel.DisplayName);
- resultsFileStream.Write(channel.GetChannelDetail());
- }
-
- var totalProgrammeCount = 0;
-
- resultsFileStream.Write("\r\n");
- foreach (var channel in channels)
- {
- System.Console.WriteLine("Processing Channel: {0}", channel.DisplayName);
-
- resultsFileStream.Write(EntityExtensions.GetHeader("Programs for " + channel.DisplayName));
- var channelProgrammeCount = await ReadOutChannelProgrammes(reader, channel, resultsFileStream);
-
- totalProgrammeCount += channelProgrammeCount;
- await resultsFileStream.WriteLineAsync(String.Format("Total Programmes for {1}: {0}", channelProgrammeCount, channel.DisplayName));
- }
-
- await resultsFileStream.WriteLineAsync(String.Format("Total Programmes: {0}", totalProgrammeCount));
- }
-
- private static async Task<int> ReadOutChannelProgrammes(XmlTvReader reader, XmlTvChannel channel, StreamWriter resultsFileStream)
- {
- //var startDate = new DateTime(2015, 11, 28);
- //var endDate = new DateTime(2015, 11, 29);
- var startDate = DateTimeOffset.MinValue;
- var endDate = DateTimeOffset.MaxValue;
-
- var count = 0;
-
- foreach (var programme in reader.GetProgrammes(channel.Id, startDate, endDate, new CancellationToken()).Distinct())
- {
- count++;
- await resultsFileStream.WriteLineAsync(programme.GetProgrammeDetail(channel));
- }
-
- return count;
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv.Console/Properties/AssemblyInfo.cs b/Emby.XmlTv/Emby.XmlTv.Console/Properties/AssemblyInfo.cs
deleted file mode 100644
index ff59f890f..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Console/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Emby.XmlTv.Console")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Emby.XmlTv.Console")]
-[assembly: AssemblyCopyright("Copyright © 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("add1d993-6d74-480a-b1fc-7fd9fd05a769")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Emby.XmlTv/Emby.XmlTv.Test/Emby.XmlTv.Test.csproj b/Emby.XmlTv/Emby.XmlTv.Test/Emby.XmlTv.Test.csproj
deleted file mode 100644
index d7c4ad0b7..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Test/Emby.XmlTv.Test.csproj
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" DefaultTargets="Build"
- xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProjectGuid>{C8298223-2468-466C-9B06-FBF61926CECB}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>Emby.XmlTv.Test</RootNamespace>
- <AssemblyName>Emby.XmlTv.Test</AssemblyName>
- <FileAlignment>512</FileAlignment>
- <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
- <IsCodedUITest>False</IsCodedUITest>
- <TestProjectType>UnitTest</TestProjectType>
- <TargetFrameworkProfile />
- <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
- <RestorePackages>true</RestorePackages>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
- <OutputPath>bin\Debug\</OutputPath>
- <DefineConstants>DEBUG;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
- <OutputPath>bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="System" />
- <Reference Include="System.Xml" />
- </ItemGroup>
- <Choose>
- <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
- </ItemGroup>
- </When>
- <Otherwise>
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework">
- <Private>False</Private>
- </Reference>
- </ItemGroup>
- </Otherwise>
- </Choose>
- <ItemGroup>
- <Compile Include="XmlTvReaderDateTimeTests.cs" />
- <Compile Include="XmlTvReaderLanguageTests.cs" />
- <Compile Include="XmlTvReaderTests.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- </ItemGroup>
- <ItemGroup>
- <Content Include="Xml Files\epg.xml" />
- <Content Include="Xml Files\ES_MultiLanguageData.xml">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="Xml Files\honeybee.xml">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="Xml Files\MultilanguageData.xml">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="Xml Files\UK_Data.xml">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- <SubType>Designer</SubType>
- </Content>
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv.csproj">
- <Project>{0D023565-5942-4D79-9098-A1B4B6665A40}</Project>
- <Name>Emby.XmlTv</Name>
- </ProjectReference>
- </ItemGroup>
- <Choose>
- <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- </ItemGroup>
- </When>
- </Choose>
- <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
- <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
- <PropertyGroup>
- <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
- </PropertyGroup>
- <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
- </Target>
- <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
- Other similar extension points exist, see Microsoft.Common.targets.
- <Target Name="BeforeBuild">
- </Target>
- <Target Name="AfterBuild">
- </Target>
- -->
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-</Project>
diff --git a/Emby.XmlTv/Emby.XmlTv.Test/Properties/AssemblyInfo.cs b/Emby.XmlTv/Emby.XmlTv.Test/Properties/AssemblyInfo.cs
deleted file mode 100644
index 902860363..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Test/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Emby.XmlTv.Test")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Emby.XmlTv.Test")]
-[assembly: AssemblyCopyright("Copyright © 2016")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("c8298223-2468-466c-9b06-fbf61926cecb")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderDateTimeTests.cs b/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderDateTimeTests.cs
deleted file mode 100644
index 857cc339c..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderDateTimeTests.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-using System;
-using System.IO;
-
-using Emby.XmlTv.Classes;
-
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace Emby.XmlTv.Test
-{
- [TestClass]
- public class XmlTvReaderDateTimeTests
- {
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_HandlePartDates()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
-
- Assert.AreEqual(Parse("01 Jan 2016 00:00:00"), reader.ParseDate("2016"));
- Assert.AreEqual(Parse("01 Jan 2016 00:00:00"), reader.ParseDate("201601"));
- Assert.AreEqual(Parse("01 Jan 2016 00:00:00"), reader.ParseDate("20160101"));
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("2016010112"));
- Assert.AreEqual(Parse("01 Jan 2016 12:34:00"), reader.ParseDate("201601011234"));
- Assert.AreEqual(Parse("01 Jan 2016 12:34:56"), reader.ParseDate("20160101123456"));
- }
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_HandleDateWithOffset()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
-
- // parse variations on 1:00AM
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("20160101120000 +0000"));
- Assert.AreEqual(Parse("01 Jan 2016 02:00:00"), reader.ParseDate("20160101120000 +1000"));
- Assert.AreEqual(Parse("01 Jan 2016 11:00:00"), reader.ParseDate("20160101120000 +0100"));
- Assert.AreEqual(Parse("01 Jan 2016 11:50:00"), reader.ParseDate("20160101120000 +0010"));
- Assert.AreEqual(Parse("01 Jan 2016 11:59:00"), reader.ParseDate("20160101120000 +0001"));
-
- Assert.AreEqual(Parse("01 Jan 2016 22:00:00"), reader.ParseDate("20160101120000 -1000"));
- Assert.AreEqual(Parse("01 Jan 2016 13:00:00"), reader.ParseDate("20160101120000 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 12:10:00"), reader.ParseDate("20160101120000 -0010"));
- Assert.AreEqual(Parse("01 Jan 2016 12:01:00"), reader.ParseDate("20160101120000 -0001"));
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_HandlePartDatesWithOffset()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
-
- Assert.AreEqual(Parse("01 Jan 2016 01:00:00"), reader.ParseDate("2016 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 01:00:00"), reader.ParseDate("201601 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 01:00:00"), reader.ParseDate("20160101 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 13:00:00"), reader.ParseDate("2016010112 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 13:00:00"), reader.ParseDate("201601011200 -0100"));
- Assert.AreEqual(Parse("01 Jan 2016 13:00:00"), reader.ParseDate("20160101120000 -0100"));
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_HandleSpaces()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
-
- // parse variations on 1:00AM
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("20160101120000 +000"));
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("20160101120000 +00"));
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("20160101120000 +0"));
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_HandleSpaces2()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
-
- // parse variations on 1:00AM
- Assert.AreEqual(Parse("01 Jan 2016 12:00:00"), reader.ParseDate("20160101120000 0"));
- }
-
- private DateTimeOffset Parse(string value)
- {
- return new DateTimeOffset(DateTimeOffset.Parse(value).Ticks, TimeSpan.Zero);
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderLanguageTests.cs b/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderLanguageTests.cs
deleted file mode 100644
index 32a0431d2..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderLanguageTests.cs
+++ /dev/null
@@ -1,181 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading;
-
-using Emby.XmlTv.Classes;
-
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace Emby.XmlTv.Test
-{
- [TestClass]
- public class XmlTvReaderLanguageTests
- {
- /* <title lang="es">Homes Under the Hammer - Spanish</title>
- * <title lang="es">Homes Under the Hammer - Spanish 2</title>
- * <title lang="en">Homes Under the Hammer - English</title>
- * <title lang="en">Homes Under the Hammer - English 2</title>
- * <title lang="">Homes Under the Hammer - Empty Language</title>
- * <title lang="">Homes Under the Hammer - Empty Language 2</title>
- * <title>Homes Under the Hammer - No Language</title>
- * <title>Homes Under the Hammer - No Language 2</title>
- */
-
- /* Expected Behaviour:
- * - Language = Null Homes Under the Hammer - No Language
- * - Language = "" Homes Under the Hammer - No Language
- * - Language = es Homes Under the Hammer - Spanish
- * - Language = en Homes Under the Hammer - English
- */
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_Matching_Language_ES()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es");
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - Spanish", programme.Title);
- Assert.AreEqual(1, programme.Categories.Count);
- Assert.AreEqual("Property - Spanish", programme.Categories[0]);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_Matching_Language_EN()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "en");
-
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - English", programme.Title);
- Assert.AreEqual(1, programme.Categories.Count);
- Assert.AreEqual("Property - English", programme.Categories[0]);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_Matching_With_No_Language()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, null);
-
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - No Language", programme.Title);
- Assert.AreEqual(1, programme.Categories.Count);
- Assert.AreEqual("Property - No Language", programme.Categories[0]);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_Matching_With_Empty_Language()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, String.Empty);
-
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - Empty Language", programme.Title);
- Assert.AreEqual(1, programme.Categories.Count);
- Assert.AreEqual("Property - Empty Language", programme.Categories[0]);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_When_NoMatchFound()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, "es"); // There are no titles or categories for spanish
-
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).Skip(1).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - English", programme.Title);
-
- // Should return all categories
- Assert.AreEqual(2, programme.Categories.Count);
- Assert.IsTrue(programme.Categories.Contains("Property - English"));
- Assert.IsTrue(programme.Categories.Contains("Property - Empty Language"));
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_The_First_When_NoLanguage()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile, null);
-
- var channel = reader.GetChannels().FirstOrDefault();
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programme = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).Skip(1).FirstOrDefault();
-
- Assert.IsNotNull(programme);
- Assert.AreEqual("Homes Under the Hammer - English", programme.Title); // Should return the first in the list
-
- // Should return all categories
- Assert.AreEqual(2, programme.Categories.Count);
- Assert.IsTrue(programme.Categories.Contains("Property - English"));
- Assert.IsTrue(programme.Categories.Contains("Property - Empty Language"));
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\MultilanguageData.xml")]
- public void Should_Return_All_Languages()
- {
- var testFile = Path.GetFullPath(@"MultilanguageData.xml");
- var reader = new XmlTvReader(testFile);
- var cancellationToken = new CancellationToken();
-
- var results = reader.GetLanguages(cancellationToken);
- Assert.IsNotNull(results);
-
- foreach (var result in results)
- {
- Console.WriteLine("{0} - {1}", result.Name, result.Relevance);
- }
-
- Assert.AreEqual(2, results.Count);
- Assert.AreEqual("en", results[0].Name);
- Assert.AreEqual(11, results[0].Relevance);
- Assert.AreEqual("es", results[1].Name);
- Assert.AreEqual(3, results[1].Relevance);
- }
-
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderTests.cs b/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderTests.cs
deleted file mode 100644
index b1dffc59c..000000000
--- a/Emby.XmlTv/Emby.XmlTv.Test/XmlTvReaderTests.cs
+++ /dev/null
@@ -1,219 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading;
-
-using Emby.XmlTv.Classes;
-
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace Emby.XmlTv.Test
-{
- [TestClass]
- public class XmlTvReaderTests
- {
- [TestMethod]
- [DeploymentItem("Xml Files\\UK_Data.xml")]
- public void UK_DataTest_ChannelsTest()
- {
- var testFile = Path.GetFullPath(@"UK_Data.xml");
- var reader = new XmlTvReader(testFile);
-
- var channels = reader.GetChannels().ToList();
- Assert.AreEqual(5, channels.Count);
-
- // Check each channel
- var channel = channels.SingleOrDefault(c => c.Id == "UK_RT_2667");
- Assert.IsNotNull(channel);
- Assert.AreEqual("BBC1 HD", channel.DisplayName);
- Assert.AreEqual("7.1", channel.Number);
- Assert.IsNotNull(channel.Icon);
- Assert.AreEqual("Logo_UK_RT_2667", channel.Icon.Source);
- Assert.AreEqual(100, channel.Icon.Width);
- Assert.AreEqual(200, channel.Icon.Height);
-
- channel = channels.SingleOrDefault(c => c.Id == "UK_RT_105");
- Assert.IsNotNull(channel);
- Assert.AreEqual("BBC2", channel.DisplayName);
- Assert.IsNotNull(channel.Icon);
- Assert.AreEqual("Logo_UK_RT_105", channel.Icon.Source);
- Assert.IsFalse(channel.Icon.Width.HasValue);
- Assert.IsFalse(channel.Icon.Height.HasValue);
-
- channel = channels.SingleOrDefault(c => c.Id == "UK_RT_2118");
- Assert.IsNotNull(channel);
- Assert.AreEqual("ITV1 HD", channel.DisplayName);
- Assert.IsNotNull(channel.Icon);
- Assert.AreEqual("Logo_UK_RT_2118", channel.Icon.Source);
- Assert.AreEqual(100, channel.Icon.Width);
- Assert.IsFalse(channel.Icon.Height.HasValue);
-
- channel = channels.SingleOrDefault(c => c.Id == "UK_RT_2056");
- Assert.IsNotNull(channel);
- Assert.AreEqual("Channel 4 HD", channel.DisplayName);
- Assert.IsNotNull(channel.Icon);
- Assert.AreEqual("Logo_UK_RT_2056", channel.Icon.Source);
- Assert.IsFalse(channel.Icon.Width.HasValue);
- Assert.AreEqual(200, channel.Icon.Height);
-
- channel = channels.SingleOrDefault(c => c.Id == "UK_RT_134");
- Assert.IsNotNull(channel);
- Assert.AreEqual("Channel 5", channel.DisplayName);
- Assert.IsNull(channel.Icon);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\UK_Data.xml")]
- public void UK_DataTest_GeneralTest()
- {
- var testFile = Path.GetFullPath(@"UK_Data.xml");
- var reader = new XmlTvReader(testFile, null);
-
- var channels = reader.GetChannels().ToList();
- Assert.AreEqual(5, channels.Count);
-
- // Pick a channel to check the data for
- var channel = channels.SingleOrDefault(c => c.Id == "UK_RT_2056");
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programmes = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).ToList();
-
- Assert.AreEqual(27, programmes.Count);
- var programme = programmes.SingleOrDefault(p => p.Title == "The Secret Life of");
-
- Assert.IsNotNull(programme);
- Assert.AreEqual(new DateTime(2015, 11, 26, 20, 0, 0), programme.StartDate);
- Assert.AreEqual(new DateTime(2015, 11, 26, 21, 0, 0), programme.EndDate);
- Assert.AreEqual("Cameras follow the youngsters' development after two weeks apart and time has made the heart grow fonder for Alfie and Emily, who are clearly happy to be back together. And although Alfie struggled to empathise with the rest of his peers before, a painting competition proves to be a turning point for him. George takes the children's rejection of his family recipe to heart, but goes on to triumph elsewhere, and romance is in the air when newcomer Sienna captures Arthur's heart.", programme.Description);
- Assert.AreEqual("Documentary", programme.Categories.Single());
- Assert.IsNotNull(programme.Episode);
- Assert.AreEqual("The Secret Life of 5 Year Olds", programme.Episode.Title);
- Assert.AreEqual(1, programme.Episode.Series);
- Assert.IsNull(programme.Episode.SeriesCount);
- Assert.AreEqual(4, programme.Episode.Episode);
- Assert.AreEqual(6, programme.Episode.EpisodeCount);
- Assert.IsNotNull(programme.Premiere);
- //Assert.AreEqual("First showing on national terrestrial TV", programme.Premiere.Details);
- Assert.IsTrue(programme.IsNew);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\UK_Data.xml")]
- public void UK_DataTest_MultipleTitles_SameLanguage_Should_ReturnFirstValue()
- {
- var testFile = Path.GetFullPath(@"UK_Data.xml");
- var reader = new XmlTvReader(testFile, null);
-
- /*
- <title lang="en">Homes Under the Hammer - Title 1</title>
- <title lang="en">Homes Under the Hammer - Title 2</title>
- <title lang="en">Homes Under the Hammer - Title 3</title>
- */
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programmes = reader.GetProgrammes("UK_RT_2667", startDate, startDate.AddDays(1), cancellationToken).ToList();
- var programme = programmes.SingleOrDefault(p => p.Title == "Homes Under the Hammer - Title 1");
-
- Assert.IsNotNull(programme);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\UK_Data.xml")]
- public void UK_DataTest_MultipleTitles_NoLanguage_Should_ReturnFirstValue()
- {
- var testFile = Path.GetFullPath(@"UK_Data.xml");
- var reader = new XmlTvReader(testFile, null);
-
- /*
- <title>Oxford Street Revealed - Title 1</title>
- <title>Oxford Street Revealed - Title 2</title>
- <title>Oxford Street Revealed - Title 3</title>
- */
-
- var startDate = new DateTime(2015, 11, 26);
- var cancellationToken = new CancellationToken();
- var programmes = reader.GetProgrammes("UK_RT_2667", startDate, startDate.AddDays(1), cancellationToken).ToList();
- var programme = programmes.SingleOrDefault(p => p.Title == "Oxford Street Revealed - Title 1");
-
- Assert.IsNotNull(programme);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\ES_MultiLanguageData.xml")]
- public void ES_MultiLanguageDataTest()
- {
- var testFile = Path.GetFullPath(@"ES_MultiLanguageData.xml");
- var reader = new XmlTvReader(testFile, "es"); // Specify the spanish language explicitly
-
- var channels = reader.GetChannels().ToList();
- Assert.AreEqual(141, channels.Count);
-
- // Pick a channel to check the data for
- var channel = channels.SingleOrDefault(c => c.Id == "Canal + HD" && c.DisplayName == "Canal + HD");
- Assert.IsNotNull(channel);
-
- var startDate = new DateTime(2016, 02, 18);
- var cancellationToken = new CancellationToken();
- var programmes = reader.GetProgrammes(channel.Id, startDate, startDate.AddDays(1), cancellationToken).ToList();
-
- Assert.AreEqual(22, programmes.Count);
- var programme = programmes.SingleOrDefault(p => p.Title == "This is Comedy. Judd Apatow & Co.");
-
- /*
- <programme start="20160218055100 +0100" stop="20160218065400 +0100" channel="Canal + HD">
- <title lang="es">This is Comedy. Judd Apatow &amp; Co.</title>
- <title lang="en">This is Comedy</title>
- <desc lang="es">El resurgir creativo de la comedia estadounidense en los últimos 15 años ha tenido un nombre indiscutible, Judd Apatow, y unos colaboradores indispensables, sus amigos (actores, cómicos, escritores) Jonah Hill, Steve Carrell, Paul Rudd, Seth Rogen, Lena Dunham... A través de extractos de sus filmes y de entrevistas a algunos los miembros de su 'banda' (Adam Sandler, Lena Dunham o Jason Segel), este documental muestra la carrera de un productor y director excepcional que ha sido capaz de llevar la risa a su máxima expresión</desc>
- <credits>
- <director>Jacky Goldberg</director>
- </credits>
- <date>2014</date>
- <category lang="es">Documentales</category>
- <category lang="es">Sociedad</category>
- <icon src="http://www.plus.es/recorte/n/caratula4/F3027798" />
- <country>Francia</country>
- <rating system="MPAA">
- <value>TV-G</value>
- </rating>
- <star-rating>
- <value>3/5</value>
- </star-rating>
- </programme>
- */
-
- Assert.IsNotNull(programme);
- Assert.AreEqual(new DateTime(2016, 02, 18, 4, 51, 0), programme.StartDate);
- Assert.AreEqual(new DateTime(2016, 02, 18, 5, 54, 0), programme.EndDate);
- Assert.AreEqual("El resurgir creativo de la comedia estadounidense en los últimos 15 años ha tenido un nombre indiscutible, Judd Apatow, y unos colaboradores indispensables, sus amigos (actores, cómicos, escritores) Jonah Hill, Steve Carrell, Paul Rudd, Seth Rogen, Lena Dunham... A través de extractos de sus filmes y de entrevistas a algunos los miembros de su 'banda' (Adam Sandler, Lena Dunham o Jason Segel), este documental muestra la carrera de un productor y director excepcional que ha sido capaz de llevar la risa a su máxima expresión", programme.Description);
- Assert.AreEqual(2, programme.Categories.Count);
- Assert.AreEqual("Documentales", programme.Categories[0]);
- Assert.AreEqual("Sociedad", programme.Categories[1]);
- Assert.IsNotNull(programme.Episode);
- Assert.IsNull(programme.Episode.Episode);
- Assert.IsNull(programme.Episode.EpisodeCount);
- Assert.IsNull(programme.Episode.Part);
- Assert.IsNull(programme.Episode.PartCount);
- Assert.IsNull(programme.Episode.Series);
- Assert.IsNull(programme.Episode.SeriesCount);
- Assert.IsNull(programme.Episode.Title);
- }
-
- [TestMethod]
- [DeploymentItem("Xml Files\\honeybee.xml")]
- public void HoneybeeTest()
- {
- var testFile = Path.GetFullPath(@"honeybee.xml");
- var reader = new XmlTvReader(testFile, null);
-
- var channels = reader.GetChannels().ToList();
- Assert.AreEqual(16, channels.Count);
-
- var programs = reader.GetProgrammes("2013.honeybee.it", DateTime.UtcNow.AddYears(-1),
- DateTime.UtcNow.AddYears(1), CancellationToken.None).ToList();
- Assert.AreEqual(297, programs.Count);
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv.sln b/Emby.XmlTv/Emby.XmlTv.sln
deleted file mode 100644
index 8243d4b72..000000000
--- a/Emby.XmlTv/Emby.XmlTv.sln
+++ /dev/null
@@ -1,44 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.24720.0
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.XmlTv.Console", "Emby.XmlTv.Console\Emby.XmlTv.Console.csproj", "{ADD1D993-6D74-480A-B1FC-7FD9FD05A769}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv.csproj", "{0D023565-5942-4D79-9098-A1B4B6665A40}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{BB0FD191-A9D0-4CC9-A79E-ECBCF1275268}"
- ProjectSection(SolutionItems) = preProject
- .nuget\NuGet.Config = .nuget\NuGet.Config
- .nuget\NuGet.exe = .nuget\NuGet.exe
- .nuget\NuGet.targets = .nuget\NuGet.targets
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Files", "Solution Files", "{E9F625D5-979E-48E8-9987-F4BCADD79A41}"
- ProjectSection(SolutionItems) = preProject
- Nuget\Emby.XmlTv.nuspec = Nuget\Emby.XmlTv.nuspec
- EndProjectSection
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {ADD1D993-6D74-480A-B1FC-7FD9FD05A769}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {ADD1D993-6D74-480A-B1FC-7FD9FD05A769}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {ADD1D993-6D74-480A-B1FC-7FD9FD05A769}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {ADD1D993-6D74-480A-B1FC-7FD9FD05A769}.Release|Any CPU.Build.0 = Release|Any CPU
- {0D023565-5942-4D79-9098-A1B4B6665A40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {0D023565-5942-4D79-9098-A1B4B6665A40}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {0D023565-5942-4D79-9098-A1B4B6665A40}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0D023565-5942-4D79-9098-A1B4B6665A40}.Release|Any CPU.Build.0 = Release|Any CPU
- {C8298223-2468-466C-9B06-FBF61926CECB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {C8298223-2468-466C-9B06-FBF61926CECB}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {C8298223-2468-466C-9B06-FBF61926CECB}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {C8298223-2468-466C-9B06-FBF61926CECB}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs
deleted file mode 100644
index 52ec7a135..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs
+++ /dev/null
@@ -1,1086 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Xml;
-using Emby.XmlTv.Entities;
-
-namespace Emby.XmlTv.Classes
-{
- // Reads an XmlTv file
- public class XmlTvReader
- {
- private readonly string _fileName;
- private readonly string _language;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="XmlTvReader" /> class.
- /// </summary>
- /// <param name="fileName">Name of the file.</param>
- /// <param name="language">The specific language to return.</param>
- public XmlTvReader(string fileName, string language = null)
- {
- _fileName = fileName;
-
- // Normalize null/string.empty
- if (string.IsNullOrWhiteSpace(language))
- {
- language = null;
- }
- _language = language;
- }
-
- private static XmlReader CreateXmlTextReader(string path)
- {
- var settings = new XmlReaderSettings();
-
- // https://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver(v=vs.110).aspx
- // Looks like we don't need this anyway?
- // Starting with the .NET Framework 4.5.2, this setting has a default value of null.
- //settings.XmlResolver = null;
-
- settings.DtdProcessing = DtdProcessing.Ignore;
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
- //settings.ValidationType = ValidationType.None;
-
- return XmlReader.Create(path, settings);
- }
-
- /// <summary>
- /// Gets the list of channels present in the XML
- /// </summary>
- /// <returns></returns>
- public IEnumerable<XmlTvChannel> GetChannels()
- {
- var list = new List<XmlTvChannel>();
-
- using (var reader = CreateXmlTextReader(_fileName))
- {
- if (reader.ReadToDescendant("tv"))
- {
- if (reader.ReadToDescendant("channel"))
- {
- do
- {
- var channel = GetChannel(reader);
- if (channel != null)
- {
- list.Add(channel);
- }
- }
- while (reader.ReadToFollowing("channel"));
- }
- }
- }
-
- return list;
- }
-
- private XmlTvChannel GetChannel(XmlReader reader)
- {
- var id = reader.GetAttribute("id");
-
- if (string.IsNullOrEmpty(id))
- {
- // LogError("No id found for channel row");
- // Log.Error(" channel#{0} doesnt contain an id", iChannel);
- return null;
- }
-
- var result = new XmlTvChannel() { Id = id };
-
- using (var xmlChannel = reader.ReadSubtree())
- {
- xmlChannel.MoveToContent();
- xmlChannel.Read();
-
- // Read out the data for each node and process individually
- while (!xmlChannel.EOF && xmlChannel.ReadState == ReadState.Interactive)
- {
- if (xmlChannel.NodeType == XmlNodeType.Element)
- {
- switch (xmlChannel.Name)
- {
- case "display-name":
- ProcessNode(xmlChannel, s => result.DisplayName = s, _language, s => SetChannelNumber(result, s));
- break;
- case "url":
- result.Url = xmlChannel.ReadElementContentAsString();
- break;
- case "icon":
- result.Icon = ProcessIconNode(xmlChannel);
- xmlChannel.Skip();
- break;
- default:
- xmlChannel.Skip(); // unknown, skip entire node
- break;
- }
- }
- else
- {
- xmlChannel.Read();
- }
- }
- }
-
- if (string.IsNullOrEmpty(result.DisplayName))
- {
- // LogError("No display-name found for channel {0}", id);
- return null;
- }
-
- return result;
- }
-
- private void SetChannelNumber(XmlTvChannel channel, string value)
- {
- value = value.Replace("-", ".");
- if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var number))
- {
- channel.Number = value;
- }
- }
-
- /// <summary>
- /// Gets the programmes for a specified channel
- /// </summary>
- /// <param name="channelId">The channel id.</param>
- /// <param name="startDateUtc">The UTC start date.</param>
- /// <param name="endDateUtc">The UTC end date.</param>
- /// <param name="cancellationToken">A cancellation token.</param>
- /// <returns></returns>
- public IEnumerable<XmlTvProgram> GetProgrammes(
- string channelId,
- DateTimeOffset startDateUtc,
- DateTimeOffset endDateUtc,
- CancellationToken cancellationToken)
- {
- var list = new List<XmlTvProgram>();
-
- using (var reader = CreateXmlTextReader(_fileName))
- {
- if (reader.ReadToDescendant("tv"))
- {
- if (reader.ReadToDescendant("programme"))
- {
- do
- {
- if (cancellationToken.IsCancellationRequested)
- {
- continue; // Break out
- }
-
- var programme = GetProgramme(reader, channelId, startDateUtc, endDateUtc);
- if (programme != null)
- {
- list.Add(programme);
- }
- }
- while (reader.ReadToFollowing("programme"));
- }
- }
- }
-
- return list;
- }
-
- public XmlTvProgram GetProgramme(XmlReader reader, string channelId, DateTimeOffset startDateUtc, DateTimeOffset endDateUtc)
- {
- var result = new XmlTvProgram();
-
- PopulateHeader(reader, result);
-
- using (var xmlProg = reader.ReadSubtree())
- {
- // First up, validate that this is the correct channel, and programme is within the time we are expecting
- if (!string.Equals(result.ChannelId, channelId, StringComparison.OrdinalIgnoreCase))
- {
- return null;
- }
-
- if (result.EndDate < startDateUtc || result.StartDate >= endDateUtc)
- {
- return null;
- }
-
- xmlProg.MoveToContent();
- xmlProg.Read();
-
- // Loop through each element
- while (!xmlProg.EOF && xmlProg.ReadState == ReadState.Interactive)
- {
- if (xmlProg.NodeType == XmlNodeType.Element)
- {
- switch (xmlProg.Name)
- {
- case "title":
- ProcessTitleNode(xmlProg, result);
- break;
- case "category":
- ProcessCategory(xmlProg, result);
- break;
- case "country":
- ProcessCountry(xmlProg, result);
- break;
- case "desc":
- ProcessDescription(xmlProg, result);
- break;
- case "sub-title":
- ProcessSubTitle(xmlProg, result);
- break;
- case "new":
- ProcessNew(xmlProg, result);
- break;
- case "previously-shown":
- ProcessPreviouslyShown(xmlProg, result);
- break;
- case "quality":
- ProcessQuality(xmlProg, result);
- break;
- case "episode-num":
- ProcessEpisodeNum(xmlProg, result);
- break;
- case "date": // Copyright date
- ProcessCopyrightDate(xmlProg, result);
- break;
- case "star-rating": // Community Rating
- ProcessStarRating(xmlProg, result);
- break;
- case "rating": // Certification Rating
- ProcessRating(xmlProg, result);
- break;
- case "credits":
- if (xmlProg.IsEmptyElement)
- {
- xmlProg.Skip();
- }
- else
- {
- using (var subtree = xmlProg.ReadSubtree())
- {
- ProcessCredits(subtree, result);
- }
- }
- break;
- case "icon":
- result.Icon = ProcessIconNode(xmlProg);
- xmlProg.Skip();
- break;
- case "premiere":
- result.Premiere = new XmlTvPremiere();
- // This was causing data after the premiere node to not be read. Reactivate this and debug if the premiere details are ever needed.
- //ProcessPremiereNode(xmlProg, result);
- xmlProg.Skip();
- break;
- default:
- // unknown, skip entire node
- xmlProg.Skip();
- break;
- }
- }
- else
- {
- xmlProg.Read();
- }
- }
- }
- return result;
- }
-
- /// <summary>
- /// Gets the list of supported languages in the XML
- /// </summary>
- /// <returns></returns>
- public List<XmlTvLanguage> GetLanguages(CancellationToken cancellationToken)
- {
- var results = new Dictionary<string, int>();
-
- //Loop through and parse out all elements and then lang= attributes
- //logger.LogInformation("Loading file {0}", _fileName);
- using (var reader = CreateXmlTextReader(_fileName))
- {
- while (reader.Read())
- {
- if (cancellationToken.IsCancellationRequested)
- {
- continue; // Break out
- }
-
- if (reader.NodeType == XmlNodeType.Element)
- {
- var language = reader.GetAttribute("lang");
- if (!string.IsNullOrEmpty(language))
- {
- if (!results.ContainsKey(language))
- {
- results[language] = 0;
- }
- results[language]++;
- }
- }
- }
- }
-
- return
- results.Keys.Select(k => new XmlTvLanguage() { Name = k, Relevance = results[k] })
- .OrderByDescending(l => l.Relevance)
- .ToList();
- }
-
- private void ProcessCopyrightDate(XmlReader xmlProg, XmlTvProgram result)
- {
- var startValue = xmlProg.ReadElementContentAsString();
- if (string.IsNullOrEmpty(startValue))
- {
- // Log.Error(" programme#{0} doesnt contain a start date", iChannel);
- result.CopyrightDate = null;
- }
- else
- {
- var copyrightDate = ParseDate(startValue);
- if (copyrightDate != null)
- {
- result.CopyrightDate = copyrightDate;
- }
- }
- }
-
- public void ProcessCredits(XmlReader creditsXml, XmlTvProgram result)
- {
- creditsXml.MoveToContent();
- creditsXml.Read();
-
- // Loop through each element
- while (!creditsXml.EOF && creditsXml.ReadState == ReadState.Interactive)
- {
- if (creditsXml.NodeType == XmlNodeType.Element)
- {
- XmlTvCredit credit = null;
- switch (creditsXml.Name)
- {
- case "director":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Director };
- break;
- case "actor":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Actor };
- break;
- case "writer":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Writer };
- break;
- case "adapter":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Adapter };
- break;
- case "producer":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Producer };
- break;
- case "composer":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Composer };
- break;
- case "editor":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Editor };
- break;
- case "presenter":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Presenter };
- break;
- case "commentator":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Commentator };
- break;
- case "guest":
- credit = new XmlTvCredit() { Type = XmlTvCreditType.Guest };
- break;
- }
-
- if (credit != null)
- {
- credit.Name = creditsXml.ReadElementContentAsString();
- result.Credits.Add(credit);
- }
- else
- {
- creditsXml.Skip();
- }
- }
- else
- creditsXml.Read();
- }
- }
-
- public void ProcessStarRating(XmlReader reader, XmlTvProgram result)
- {
- /*
- <star-rating>
- <value>3/3</value>
- </star-rating>
- */
-
- reader.ReadToDescendant("value");
- if (reader.Name == "value")
- {
- var textValue = reader.ReadElementContentAsString();
- if (textValue.Contains("/"))
- {
- var components = textValue.Split('/');
- if (float.TryParse(components[0], out var value))
- {
- result.StarRating = value;
- }
- }
- }
- else
- {
- reader.Skip();
- }
- }
-
- public void ProcessRating(XmlReader reader, XmlTvProgram result)
- {
- /*
- <rating system="MPAA">
- <value>TV-G</value>
- </rating>
- */
-
- var system = reader.GetAttribute("system");
-
- reader.ReadToDescendant("value");
- if (reader.Name == "value")
- {
- result.Rating = new XmlTvRating()
- {
- System = system,
- Value = reader.ReadElementContentAsString()
- };
- }
- else
- {
- reader.Skip();
- }
- }
-
- public void ProcessEpisodeNum(XmlReader reader, XmlTvProgram result)
- {
- /*
- <episode-num system="dd_progid">EP00003026.0666</episode-num>
- <episode-num system="onscreen">2706</episode-num>
- <episode-num system="xmltv_ns">.26/0.</episode-num>
- */
-
- var episodeSystem = reader.GetAttribute("system");
- switch (episodeSystem)
- {
- case "dd_progid":
- ParseEpisodeDataForProgramId(reader, result);
- break;
- case "icetv":
- result.ProviderIds["icetv"] = reader.ReadElementContentAsString();
- break;
- case "xmltv_ns":
- ParseEpisodeDataForXmlTvNs(reader, result);
- break;
- case "onscreen":
- ParseEpisodeDataForOnScreen(reader, result);
- break;
- case "thetvdb.com":
- ParseTvdbSystem(reader, result);
- break;
- case "imdb.com":
- ParseImdbSystem(reader, result);
- break;
- case "themoviedb.org":
- ParseMovieDbSystem(reader, result);
- break;
- case "SxxExx":
- // TODO
- // <episode-num system="SxxExx">S03E12</episode-num>
- reader.Skip();
- break;
- default: // Handles empty string and nulls
- reader.Skip();
- break;
- }
- }
-
- public void ParseMovieDbSystem(XmlReader reader, XmlTvProgram result)
- {
- // <episode-num system="thetvdb.com">series/248841</episode-num>
- // <episode-num system="thetvdb.com">episode/4749206</episode-num>
-
- var value = reader.ReadElementContentAsString();
- var parts = value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
-
- if (string.Equals(parts[0], "series", StringComparison.OrdinalIgnoreCase))
- {
- result.SeriesProviderIds["tmdb"] = parts[1];
- }
-
- else if (parts.Length == 1 || string.Equals(parts[0], "episode", StringComparison.OrdinalIgnoreCase))
- {
- result.ProviderIds["tmdb"] = parts.Last();
- }
- }
-
- public void ParseImdbSystem(XmlReader reader, XmlTvProgram result)
- {
- // <episode-num system="imdb.com">series/tt1837576</episode-num>
- // <episode-num system="imdb.com">episode/tt3288596</episode-num>
-
- var value = reader.ReadElementContentAsString();
- if (string.IsNullOrWhiteSpace(value))
- {
- return;
- }
- var parts = value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
-
- if (parts.Length != 2)
- {
- return;
- }
-
- if (string.Equals(parts[0], "series", StringComparison.OrdinalIgnoreCase))
- {
- result.SeriesProviderIds["imdb"] = parts[1];
- }
-
- else if (string.Equals(parts[0], "episode", StringComparison.OrdinalIgnoreCase))
- {
- result.ProviderIds["imdb"] = parts[1];
- }
- }
-
- public void ParseTvdbSystem(XmlReader reader, XmlTvProgram result)
- {
- // <episode-num system="thetvdb.com">series/248841</episode-num>
- // <episode-num system="thetvdb.com">episode/4749206</episode-num>
-
- var value = reader.ReadElementContentAsString();
- var parts = value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
-
- if (parts.Length != 2)
- {
- return;
- }
-
- if (string.Equals(parts[0], "series", StringComparison.OrdinalIgnoreCase))
- {
- result.SeriesProviderIds["tvdb"] = parts[1];
- }
-
- else if (string.Equals(parts[0], "episode", StringComparison.OrdinalIgnoreCase))
- {
- result.ProviderIds["tvdb"] = parts[1];
- }
- }
-
- public void ParseEpisodeDataForOnScreen(XmlReader reader, XmlTvProgram result)
- {
- //// example: 'Episode #FFEE'
- //serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum);
- //int num1 = serEpNum.IndexOf("#", 0);
- //if (num1 < 0) num1 = 0;
- //episodeNum = CorrectEpisodeNum(serEpNum.Substring(num1, serEpNum.Length - num1), 0);
-
- var value = reader.ReadElementContentAsString();
- // value = HttpUtility.HtmlDecode(value);
- value = value.Replace(" ", "");
-
- var hashIndex = value.IndexOf("#", StringComparison.Ordinal);
- if (hashIndex > -1)
- {
- // Take everything from the hash to the end.
- //TODO: This could be textual - how do we populate an Int32
- // result.EpisodeNumber
- }
- }
-
- public void ParseEpisodeDataForProgramId(XmlReader reader, XmlTvProgram result)
- {
- var value = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(value))
- {
- result.ProgramId = value;
- }
- }
-
- public void ParseEpisodeDataForXmlTvNs(XmlReader reader, XmlTvProgram result)
- {
- var value = reader.ReadElementContentAsString();
-
- value = value.Replace(" ", "");
-
- // Episode details
- var components = value.Split(new[] { "." }, StringSplitOptions.None);
-
- int parsedInt;
-
- if (!string.IsNullOrEmpty(components[0]))
- {
- // Handle either "5/12" or "5"
- var seriesComponents = components[0].Split(new[] { "/" }, StringSplitOptions.None);
-
- // handle the zero basing!
- if (int.TryParse(seriesComponents[0], out parsedInt))
- {
- result.Episode.Series = parsedInt + 1;
- if (seriesComponents.Length == 2)
- {
- if (int.TryParse(seriesComponents[1], out parsedInt))
- {
- result.Episode.SeriesCount = parsedInt;
- }
- }
- }
- }
-
- if (components.Length >= 2)
- {
- if (!string.IsNullOrEmpty(components[1]))
- {
- // Handle either "5/12" or "5"
- var episodeComponents = components[1].Split(new[] { "/" }, StringSplitOptions.None);
-
- // handle the zero basing!
- if (int.TryParse(episodeComponents[0], out parsedInt))
- {
- result.Episode.Episode = parsedInt + 1;
- if (episodeComponents.Count() == 2)
- {
- if (int.TryParse(episodeComponents[1], out parsedInt))
- {
- result.Episode.EpisodeCount = parsedInt;
- }
- }
- }
- }
- }
-
- if (components.Length >= 3)
- {
- if (!string.IsNullOrEmpty(components[2]))
- {
- // Handle either "5/12" or "5"
- var partComponents = components[2].Split(new[] { "/" }, StringSplitOptions.None);
-
- // handle the zero basing!
- if (int.TryParse(partComponents[0], out parsedInt))
- {
- result.Episode.Part = parsedInt + 1;
- if (partComponents.Count() == 2)
- {
- if (int.TryParse(partComponents[1], out parsedInt))
- {
- result.Episode.PartCount = parsedInt;
- }
- }
- }
- }
- }
- }
-
- public void ProcessQuality(XmlReader reader, XmlTvProgram result)
- {
- result.Quality = reader.ReadElementContentAsString();
- }
-
- public void ProcessPreviouslyShown(XmlReader reader, XmlTvProgram result)
- {
- // <previously-shown start="20070708000000" />
- var value = reader.GetAttribute("start");
- if (!string.IsNullOrEmpty(value))
- {
- // TODO: this may not be correct = validate it
- result.PreviouslyShown = ParseDate(value);
- if (result.PreviouslyShown != result.StartDate)
- {
- result.IsPreviouslyShown = true;
- }
- }
- else
- {
- result.IsPreviouslyShown = true;
- }
-
- reader.Skip(); // Move on
- }
-
- public void ProcessNew(XmlReader reader, XmlTvProgram result)
- {
- result.IsNew = true;
- reader.Skip(); // Move on
- }
-
- public void ProcessCategory(XmlReader reader, XmlTvProgram result)
- {
- /*
- <category lang="en">News</category>
- */
-
- result.Categories = result.Categories ?? new List<string>();
- ProcessMultipleNodes(reader, s => result.Categories.Add(s), _language);
-
- //result.Categories.Add(reader.ReadElementContentAsString());
- }
- public void ProcessCountry(XmlReader reader, XmlTvProgram result)
- {
- /*
- <country>Canadá</country>
- <country>EE.UU</country>
- */
-
- result.Countries = result.Countries ?? new List<string>();
- ProcessNode(reader, s => result.Countries.Add(s), _language);
- }
-
- public void ProcessSubTitle(XmlReader reader, XmlTvProgram result)
- {
- /*
- <sub-title lang="en">Gino&apos;s Italian Escape - Islands in the Sun: Southern Sardinia Celebrate the Sea</sub-title>
- <sub-title lang="en">8782</sub-title>
- */
- ProcessNode(reader, s => result.Episode.Title = s, _language);
- }
-
- public void ProcessDescription(XmlReader reader, XmlTvProgram result)
- {
- ProcessNode(reader, s => result.Description = s, _language);
- }
-
- public void ProcessTitleNode(XmlReader reader, XmlTvProgram result)
- {
- // <title lang="en">Gino&apos;s Italian Escape</title>
- ProcessNode(reader, s => result.Title = s, _language);
- }
-
- public void ProcessPremiereNode(XmlReader reader, XmlTvProgram result)
- {
- // <title lang="en">Gino&apos;s Italian Escape</title>
- ProcessNode(reader,
- s =>
- {
- if (result.Premiere == null)
- {
- result.Premiere = new XmlTvPremiere() { Details = s };
- }
- else
- {
- result.Premiere.Details = s;
- }
- }, _language);
- }
-
- public XmlTvIcon ProcessIconNode(XmlReader reader)
- {
- var result = new XmlTvIcon();
- var isPopulated = false;
-
- var source = reader.GetAttribute("src");
- if (!string.IsNullOrEmpty(source))
- {
- result.Source = source;
- isPopulated = true;
- }
-
- var widthString = reader.GetAttribute("width");
- var width = 0;
- if (!string.IsNullOrEmpty(widthString) && int.TryParse(widthString, out width))
- {
- result.Width = width;
- isPopulated = true;
- }
-
- var heightString = reader.GetAttribute("height");
- var height = 0;
- if (!string.IsNullOrEmpty(heightString) && int.TryParse(heightString, out height))
- {
- result.Height = height;
- isPopulated = true;
- }
-
- return isPopulated ? result : null;
- }
-
-
- //public void ProcessNodeWithLanguage(XmlReader reader, Action<string> setter)
- //{
- // var currentElementName = reader.Name;
- // var result = string.Empty;
- // var resultCandidate = reader.ReadElementContentAsString();
- // var exactMatchFound = false;
-
- // while (reader.Name == currentElementName)
- // {
- // var language = reader.GetAttribute("lang");
- // resultCandidate = reader.ReadElementContentAsString();
-
- // if (language == _language && !exactMatchFound)
- // {
- // result = resultCandidate;
- // }
-
- // reader.Skip();
- // }
-
- // result = String.IsNullOrEmpty(result) ? resultCandidate : result;
- // setter(result);
- //}
-
- public void ProcessNode(XmlReader reader, Action<string> setter, string languageRequired = null, Action<string> allOccurrencesSetter = null)
- {
- /* <title lang="es">Homes Under the Hammer - Spanish</title>
- * <title lang="es">Homes Under the Hammer - Spanish 2</title>
- * <title lang="en">Homes Under the Hammer - English</title>
- * <title lang="en">Homes Under the Hammer - English 2</title>
- * <title lang="">Homes Under the Hammer - Empty Language</title>
- * <title lang="">Homes Under the Hammer - Empty Language 2</title>
- * <title>Homes Under the Hammer - No Language</title>
- * <title>Homes Under the Hammer - No Language 2</title>
- */
-
- /* Expected Behaviour:
- * - Language = Null Homes Under the Hammer - No Language
- * - Language = "" Homes Under the Hammer - No Language
- * - Language = es Homes Under the Hammer - Spanish
- * - Language = en Homes Under the Hammer - English
- */
-
- var results = new List<Tuple<string, string>>();
-
- // We will always use the first value - so that if there are no matches we can return something
- var currentElementName = reader.Name;
-
- var lang = reader.HasAttributes ? reader.GetAttribute("lang") : null;
- var currentValue = reader.ReadElementContentAsString();
- results.Add(new Tuple<string, string>(currentValue, lang));
-
- if (allOccurrencesSetter != null)
- {
- allOccurrencesSetter(currentValue);
- }
-
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- if (reader.Name == currentElementName)
- {
- lang = reader.HasAttributes ? reader.GetAttribute("lang") : null;
- currentValue = reader.ReadElementContentAsString();
-
- if (allOccurrencesSetter != null)
- {
- allOccurrencesSetter(currentValue);
- }
-
- results.Add(new Tuple<string, string>(currentValue, lang));
- }
- else
- {
- break;
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- if (languageRequired != null)
- {
- foreach (var result in results)
- {
- if (string.Equals(languageRequired, result.Item2, StringComparison.OrdinalIgnoreCase))
- {
- setter(result.Item1);
- return;
- }
- }
- }
-
- foreach (var result in results)
- {
- if (string.IsNullOrWhiteSpace(result.Item2))
- {
- setter(result.Item1);
- return;
- }
- }
-
- foreach (var result in results)
- {
- setter(result.Item1);
- return;
- }
- }
-
- public void ProcessMultipleNodes(XmlReader reader, Action<string> setter, string languageRequired = null)
- {
- /* <category lang="en">Property - English</category>
- * <category lang="en">Property - English 2</category>
- * <category lang="es">Property - Spanish</category>
- * <category lang="es">Property - Spanish 2</category>
- * <category lang="">Property - Empty Language</category>
- * <category lang="">Property - Empty Language 2</category>
- * <category>Property - No Language</category>
- * <category>Property - No Language 2</category>
- */
-
- /* Expected Behaviour:
- * - Language = Null Property - No Language / Property - No Language 2
- * - Language = "" Property - Empty Language / Property - Empty Language 2
- * - Language = es Property - Spanish / Property - Spanish 2
- * - Language = en Property - English / Property - English 2
- */
-
- var currentElementName = reader.Name;
- var values = new[] { new { Language = reader.GetAttribute("lang"), Value = reader.ReadElementContentAsString() } }.ToList();
-
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element && reader.Name != currentElementName)
- {
- break;
- }
-
- if (reader.NodeType == XmlNodeType.Element && reader.Name == currentElementName)
- {
- values.Add(new { Language = reader.GetAttribute("lang"), Value = reader.ReadElementContentAsString() });
- }
- }
-
- if (values.Count(v => v.Language == languageRequired) > 0)
- {
- values.RemoveAll(v => v.Language != languageRequired);
- }
-
- // ENumerate and return all the matches
- foreach (var result in values)
- {
- setter(result.Value);
- }
- }
-
- public void ProcessMultipleNodesWithLanguage(XmlReader reader, Action<string> setter)
- {
- var currentElementName = reader.Name;
- while (reader.Name == currentElementName)
- {
- var language = reader.GetAttribute("lang");
- if (string.IsNullOrEmpty(_language) || string.IsNullOrEmpty(language) || language == _language)
- {
- setter(reader.ReadElementContentAsString());
- }
- reader.Skip();
- }
- }
-
- private void PopulateHeader(XmlReader reader, XmlTvProgram result)
- {
- result.ChannelId = reader.GetAttribute("channel");
-
- var startValue = reader.GetAttribute("start");
- if (string.IsNullOrEmpty(startValue))
- {
- // Log.Error(" programme#{0} doesnt contain a start date", iChannel);
- result.StartDate = DateTimeOffset.MinValue;
- }
- else
- {
- result.StartDate = ParseDate(startValue).GetValueOrDefault();
- }
-
-
- var endValue = reader.GetAttribute("stop");
- if (string.IsNullOrEmpty(endValue))
- {
- // Log.Error(" programme#{0} doesnt contain an end date", iChannel);
- result.EndDate = DateTimeOffset.MinValue;
- }
- else
- {
- result.EndDate = ParseDate(endValue).GetValueOrDefault();
- }
- }
-
- public const string _regDateWithOffset = @"^(?<dateDigits>[0-9]{4,14})(\s(?<dateOffset>[+-]*[0-9]{1,4}))?$";
-
- public DateTimeOffset? ParseDate(string dateValue)
- {
- /*
- All dates and times in this DTD follow the same format, loosely based
- on ISO 8601. They can be 'YYYYMMDDhhmmss' or some initial
- substring, for example if you only know the year and month you can
- have 'YYYYMM'. You can also append a timezone to the end; if no
- explicit timezone is given, UTC is assumed. Examples:
- '200007281733 BST', '200209', '19880523083000 +0300'. (BST == +0100.)
- */
-
- if (string.IsNullOrEmpty(dateValue))
- {
- return null;
- }
-
- var completeDate = "20000101000000";
- var dateComponent = string.Empty;
- var dateOffset = "+00:00";
- var match = Regex.Match(dateValue, _regDateWithOffset);
- if (match.Success)
- {
- dateComponent = match.Groups["dateDigits"].Value;
- if (!string.IsNullOrEmpty(match.Groups["dateOffset"].Value))
- {
- dateOffset = match.Groups["dateOffset"].Value; // Add in the colon to ease parsing later
- if (dateOffset.Length == 5)
- {
- dateOffset = dateOffset.Insert(3, ":"); // Add in the colon to ease parsing later
- }
- else
- {
- dateOffset = "+00:00";
- }
- }
- }
-
- // Pad out the date component part to 14 characaters so 2016061509 becomes 20160615090000
- if (dateComponent.Length < 14)
- {
- dateComponent = dateComponent + completeDate.Substring(dateComponent.Length, completeDate.Length - dateComponent.Length);
- }
-
- var standardDate = string.Format("{0} {1}", dateComponent, dateOffset);
- if (DateTimeOffset.TryParseExact(standardDate, "yyyyMMddHHmmss zzz", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTimeOffset parsedDateTime))
- {
- return parsedDateTime.ToUniversalTime();
- }
-
- // Logger.LogWarning("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate);
-
- return null;
- }
-
- public string StandardiseDate(string value)
- {
- var completeDate = "20000101000000";
- var dateComponent = string.Empty;
- var dateOffset = "+0000";
-
- var match = Regex.Match(value, _regDateWithOffset);
- if (match.Success)
- {
- dateComponent = match.Groups["dateDigits"].Value;
- dateOffset = match.Groups["dateOffset"].Value;
- }
-
- // Pad out the date component part to 14 characaters so 2016061509 becomes 20160615090000
- if (dateComponent.Length < 14)
- {
- dateComponent = dateComponent + completeDate.Substring(dateComponent.Length, completeDate.Length - dateComponent.Length);
- }
-
- return string.Format("{0} {1}", dateComponent, dateOffset);
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Emby.XmlTv.csproj b/Emby.XmlTv/Emby.XmlTv/Emby.XmlTv.csproj
deleted file mode 100644
index 0225be2c2..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Emby.XmlTv.csproj
+++ /dev/null
@@ -1,12 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
- <ItemGroup>
- <Compile Include="..\..\SharedVersion.cs" />
- </ItemGroup>
-
-</Project>
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvChannel.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvChannel.cs
deleted file mode 100644
index 2673d711c..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvChannel.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System;
-using System.Text;
-
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvChannel : IEquatable<XmlTvChannel>
- {
- public string Id { get; set; }
- public string DisplayName { get; set; }
- public string Number { get; set; }
- public string Url { get; set; }
- public XmlTvIcon Icon { get; set; }
-
- public bool Equals(XmlTvChannel other)
- {
- // If both are null, or both are same instance, return true.
- if (ReferenceEquals(this, other))
- {
- return true;
- }
-
- // If the other is null then return false
- if (other == null)
- {
- return false;
- }
-
- // Return true if the fields match:
- return Id == other.Id;
- }
-
- public override int GetHashCode()
- {
- return (Id.GetHashCode() * 17);
- }
-
- public override string ToString()
- {
- var builder = new StringBuilder();
- builder.AppendFormat("{0} - {1} ", Id, DisplayName);
-
- if (!string.IsNullOrEmpty(Url))
- {
- builder.AppendFormat(" ({0})", Url);
- }
-
- return builder.ToString();
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCredit.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCredit.cs
deleted file mode 100644
index d959ce76f..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCredit.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvCredit
- {
- public XmlTvCreditType Type { get; set; }
- public string Name { get; set; }
-
- public override string ToString()
- {
- return string.Format("{0} - ({1})", Name, Type);
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCreditType.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCreditType.cs
deleted file mode 100644
index 31c7f5e44..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvCreditType.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace Emby.XmlTv.Entities
-{
- public enum XmlTvCreditType
- {
- NotSpecified = 0,
- Director,
- Actor,
- Writer,
- Adapter,
- Producer,
- Composer,
- Editor,
- Presenter,
- Commentator,
- Guest
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvEpisode.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvEpisode.cs
deleted file mode 100644
index 47525b57c..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvEpisode.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using System.Text;
-
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvEpisode
- {
- public int? Series { get; set; }
- public int? SeriesCount { get; set; }
- public int? Episode { get; set; }
- public int? EpisodeCount { get; set; }
- public string Title { get; set; }
- public int? Part { get; set; }
- public int? PartCount { get; set; }
-
- public override string ToString()
- {
- var builder = new StringBuilder();
- if (Series.HasValue || SeriesCount.HasValue)
- {
- builder.AppendFormat("Series {0}", Series.HasValue ? Series.Value.ToString() : "?");
- if (SeriesCount.HasValue)
- {
- builder.AppendFormat(" of {0}", SeriesCount);
- }
- }
-
- if (Episode.HasValue || EpisodeCount.HasValue)
- {
- builder.Append(builder.Length > 0 ? ", " : string.Empty);
- builder.AppendFormat("Episode {0}", Episode.HasValue ? Episode.Value.ToString() : "?");
- if (EpisodeCount.HasValue)
- {
- builder.AppendFormat(" of {0}", EpisodeCount);
- }
- }
-
- if (Part.HasValue || PartCount.HasValue)
- {
- builder.Append(builder.Length > 0 ? ", " : string.Empty);
- builder.AppendFormat("Part {0}", Part.HasValue ? Part.Value.ToString() : "?");
- if (PartCount.HasValue)
- {
- builder.AppendFormat(" of {0}", PartCount);
- }
- }
-
- return builder.ToString();
- }
- }
-
-
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvIcon.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvIcon.cs
deleted file mode 100644
index 77ef8d5fd..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvIcon.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System.Text;
-
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvIcon
- {
- public string Source { get; set; }
- public int? Width { get; set; }
- public int? Height { get; set; }
-
- public override string ToString()
- {
- var builder = new StringBuilder();
- builder.AppendFormat("Source: {0}", Source);
- if (Width.HasValue)
- {
- builder.AppendFormat(", Width: {0}", Width);
- }
- if (Height.HasValue)
- {
- builder.AppendFormat(", Height: {0}", Height);
- }
-
- return builder.ToString();
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvLanguage.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvLanguage.cs
deleted file mode 100644
index 0fd5573cd..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvLanguage.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvLanguage
- {
- /// <summary>
- /// The name.
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// The relevance (number of occurances) of the language, can be used to order (desc)
- /// </summary>
- public int Relevance { get; set; }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvPremiere.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvPremiere.cs
deleted file mode 100644
index a1920bc77..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvPremiere.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvPremiere
- {
- /*
- <premiere lang="en">
- First showing on national terrestrial TV
- </premiere>
- */
-
- public string Details { get; set; }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvProgram.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvProgram.cs
deleted file mode 100644
index 1725e17d7..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvProgram.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Emby.XmlTv.Entities
-{
- public class XmlTvProgram : IEquatable<XmlTvProgram>
- {
- public string ChannelId { get; set; }
-
- public DateTimeOffset StartDate { get; set; }
-
- public DateTimeOffset EndDate { get; set; }
-
- public string Title { get; set; }
-
- public string Description { get; set; }
- public string ProgramId { get; set; }
- public string Quality { get; set; }
-
- public List<string> Categories { get; set; }
-
- public List<string> Countries { get; set; }
-
- public DateTimeOffset? PreviouslyShown { get; set; }
-
- public bool IsPreviouslyShown { get; set; }
- public bool IsNew { get; set; }
-
- public DateTimeOffset? CopyrightDate { get; set; }
-
- public XmlTvEpisode Episode { get; set; }
-
- public List<XmlTvCredit> Credits { get; set; }
-
- public XmlTvRating Rating { get; set; }
-
- public float? StarRating { get; set; }
-
- public XmlTvIcon Icon { get; set; }
-
- public XmlTvPremiere Premiere { get; set; }
-
- public Dictionary<string, string> ProviderIds { get; set; }
- public Dictionary<string, string> SeriesProviderIds { get; set; }
-
- public XmlTvProgram()
- {
- Credits = new List<XmlTvCredit>();
- Categories = new List<string>();
- Countries = new List<string>();
- Episode = new XmlTvEpisode();
-
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- public bool Equals(XmlTvProgram other)
- {
- // If both are null, or both are same instance, return true.
- if (ReferenceEquals(this, other))
- {
- return true;
- }
-
- // If the other is null then return false
- if (other == null)
- {
- return false;
- }
-
- // Return true if the fields match:
- return ChannelId == other.ChannelId &&
- StartDate == other.StartDate &&
- EndDate == other.EndDate;
- }
-
- public override int GetHashCode()
- {
- return (ChannelId.GetHashCode() * 17) + (StartDate.GetHashCode() * 17) + (EndDate.GetHashCode() * 17);
- }
-
- public override string ToString()
- {
- var builder = new StringBuilder();
- builder.AppendFormat("ChannelId: \t\t{0}\r\n", ChannelId);
- builder.AppendFormat("Title: \t\t{0}\r\n", Title);
- builder.AppendFormat("StartDate: \t\t{0}\r\n", StartDate);
- builder.AppendFormat("EndDate: \t\t{0}\r\n", EndDate);
- return builder.ToString();
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvRating.cs b/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvRating.cs
deleted file mode 100644
index e37113d7a..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Entities/XmlTvRating.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using System.Text;
-
-namespace Emby.XmlTv.Entities
-{
- /// <summary>
- /// Describes the rating (certification) applied to a program
- /// </summary>
- /// <remarks>Example XML:
- /// </remarks>
- public class XmlTvRating
- {
- /// <summary>
- /// The literal name of the rating system
- /// </summary>
- /// <example>MPAA</example>
- public string System { get; set; }
-
- /// <summary>
- /// Describes the rating using the system specificed
- /// </summary>
- /// <example>TV-14</example>
- public string Value { get; set; }
-
- public override string ToString()
- {
- var builder = new StringBuilder();
- if (!string.IsNullOrEmpty(Value))
- {
- builder.Append(Value);
- }
-
- if (!string.IsNullOrEmpty(System))
- {
- builder.AppendFormat(" ({0})", System);
- }
-
- return builder.ToString();
- }
- }
-}
diff --git a/Emby.XmlTv/Emby.XmlTv/Properties/AssemblyInfo.cs b/Emby.XmlTv/Emby.XmlTv/Properties/AssemblyInfo.cs
deleted file mode 100644
index ff2efb078..000000000
--- a/Emby.XmlTv/Emby.XmlTv/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("XmlTv")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/Emby.XmlTv/Emby.XmlTv/XmlTvSchema.dtd b/Emby.XmlTv/Emby.XmlTv/XmlTvSchema.dtd
deleted file mode 100644
index 889939224..000000000
--- a/Emby.XmlTv/Emby.XmlTv/XmlTvSchema.dtd
+++ /dev/null
@@ -1,575 +0,0 @@
-<!-- DTD for TV listings
-
-This is a DTD to represent a TV listing. It doesn't explicitly group
-programmes by day or by channel, instead broadcast time and channel
-are attributes of the 'programme' element. Optionally, data about the
-TV channels used can be stored in 'channel' elements.
-
-Data about a TV programme are stored in the subelements of element
-'programme', but metadata such as when it will be broadcast are stored
-as attributes.
-
-Many of the details have a 'lang' attribute so that you can
-store them in multiple languages or have mixed languages in a single
-listing. This 'lang' should be the two-letter code such as 'en' or
-'fr_FR'. Or you can just leave it out and let your reader take a
-guess.
-
-Unless otherwise specified, an element containing CDATA must have some
-text if it is written.
-
-An example XML file for this DTD might look like this:
-
-<tv generator-info-name="my listings generator">
- <channel id="3sat.de">
- <display-name lang="de">3SAT</display-name>
- </channel>
- <channel id="das-erste.de">
- <display-name lang="de">ARD</display-name>
- <display-name lang="de">Das Erste</display-name>
- </channel>
-
- <programme start="200006031633" channel="3sat.de">
- <title lang="de">blah</title>
- <title lang="en">blah</title>
- <desc lang="de">
- Blah Blah Blah.
- </desc>
- <credits>
- <director>blah</director>
- <actor>a</actor>
- <actor>b</actor>
- </credits>
- <date>19901011</date>
- <country>ES</country>
- <episode-num system="xmltv_ns">2 . 9 . 0/1</episode-num>
- <video>
- <aspect>16:9</aspect>
- </video>
- <rating system="MPAA">
- <value>PG</value>
- <icon src="pg_symbol.png" />
- </rating>
- <star-rating>
- <value>3/3</value>
- </star-rating>
- </programme>
- <programme> ... </programme>
- ...
-</tv>
-
-This describes two channels and then a programme broadcast on one of
-the channels, then some more programmes. Almost everything in the DTD
-is optional, so you can write files which are much simpler than this
-example.
-
-All dates and times in this DTD follow the same format, loosely based
-on ISO 8601. They can be 'YYYYMMDDhhmmss' or some initial
-substring, for example if you only know the year and month you can
-have 'YYYYMM'. You can also append a timezone to the end; if no
-explicit timezone is given, UTC is assumed. Examples:
-'200007281733 BST', '200209', '19880523083000 +0300'. (BST == +0100.)
-
-Unless specified otherwise, textual element content may not contain
-newlines - this is to make it easy to convert into line-oriented
-formats, and to avoid the question of what exactly a newline would
-mean in the middle of someone's name or whatever. Leading and
-trailing whitespace in element content is not significant.
-
-At present versions of this DTD correspond to releases of the 'xmltv'
-package, which is a set of programs to generate and manipulate files
-conforming to this DTD. Written by Ed Avis (ed@membled.com) and
-Gottfried Szing, thanks to others for suggestions.
-
-$Id: xmltv.dtd,v 1.47 2014/05/02 07:27:51 bilbo_uk Exp $
-
--->
-
-<!-- The root element, tv.
-
-Date should be the date when the listings were originally produced in
-whatever format; if you're converting data from another source, then
-use the date given by that source. The date when the conversion
-itself was done is not important.
-
-To indicate the source of the listings, there are three attributes you
-can define:
-
-'source-info-url' is a URL describing the data source in
-some human-readable form. So if you are getting your listings from
-SAT.1, you might set this to the URL of a page explaining how to
-subscribe to their feed. If you are getting them from a website, the
-URL might be the index of the site or at least of the TV listings
-section.
-
-'source-info-name' is the link text for that URL; it should
-generally be the human-readable name of your listings supplier.
-Sometimes the link text might be printed without the link itself, in
-hardcopy listings for example.
-
-'source-data-url' is where the actual data is grabbed from. This
-should link directly to the machine-readable data files if possible,
-but it's not rigorously defined what 'actual data' means. If you are
-parsing the data from human-readable pages, then it's more appropriate
-to link to them with the source-info stuff and omit this attribute.
-
-To publicize your wonderful program which generated this file, you can
-use 'generator-info-name' (preferably in the form 'progname/version')
-and 'generator-info-url' (a link to more info about the program).
--->
-<!ELEMENT tv (channel*, programme*)>
-<!ATTLIST tv date CDATA #IMPLIED
- source-info-url CDATA #IMPLIED
- source-info-name CDATA #IMPLIED
- source-data-url CDATA #IMPLIED
- generator-info-name CDATA #IMPLIED
- generator-info-url CDATA #IMPLIED >
-
-<!-- channel - details of a channel
-
-Each 'programme' element (see below) should have an attribute
-'channel' giving the channel on which it is broadcast. If you want to
-provide more detail about channels, you can give some 'channel'
-elements before listing the programmes. The 'id' attribute of the
-channel should match what is given in the 'channel' attribute of the
-programme.
-
-Typically, all the channels used in a particular TV listing will be
-included and then the programmes using those channels. But it's
-entirely optional to include channel details - you can just leave out
-channel elements or provide only some of them. It is also okay to
-give just channels and no programmes, if you just want to describe
-what TV channels are available in a certain area.
-
-Each channel has one id attribute, which must be unique and should
-preferably be in the form suggested by RFC2838 (the 'broadcast'
-element of the grammar in that RFC, in other words, a DNS-like name
-but without any URI scheme). Then one or more display names which are
-shown to the user. You might want a different display name for
-different languages, but also you can have more than one name for the
-same language. Names listed earlier are considered 'more canonical'.
-
-Since the display name is just there as a way for humans to refer to
-the channel, it's acceptable to just put the channel number if it's
-fairly universal among viewers of the channel. But remember that this
-isn't an official statement of what channel number has been
-allocated, and the same number might be used for a different channel
-somewhere else.
-
-The ordering of channel elements makes no difference to the meaning of
-the file, since they are looked up by id and not by their position.
-However it makes things like diffing easier if you write the channel
-elements sorted by ASCII order of their ids.
--->
-<!ELEMENT channel (display-name+, icon*, url*) >
-<!ATTLIST channel id CDATA #REQUIRED >
-
-<!-- A user-friendly name for the channel - maybe even a channel
-number. List the most canonical / common ones first and the most
-obscure names last. The lang attribute follows RFC 1766.
--->
-<!ELEMENT display-name (#PCDATA)>
-<!ATTLIST display-name lang CDATA #IMPLIED>
-
-<!-- A URL where you can find out more about the element that contains
-it (programme or channel). This might be the official site, or a fan
-page, whatever you like really.
-
-If multiple url elements are given, the most authoritative or official
-(which might conflict...) sites should be listed first.
--->
-<!ELEMENT url (#PCDATA)>
-
-<!-- programme - details of a single programme transmission
-
-A show will be exactly the same whether it is broadcast at 18:00 or
-19:00, and on whichever channel. Technical details like broadcast
-time don't affect the content of the programme itself, so they are
-included as attributes of this element. Start time and channel are
-the two that you must include.
-
-Sometimes VCR programming systems like PDC or VPS have their own
-notion of 'start time' which is different from the actual start time,
-so there are attributes for that. In practice, stop time will usually
-be the start time of the next programme, but if you can get it more
-accurate, good for you. Similarly, you can specify a code for
-Gemstar's Showview or VideoPlus programming systems.
-
-TV listings sometimes have the problem of listing two or more
-programmes in the same timeslot, such as 'News; Weather'. We call
-this a 'clump' of programmes, and the 'clumpidx' attribute
-differentiates between two programmes sharing the same timeslot and
-channel. In this case News would have clumpidx="0/2" and Weather
-would have clumpidx="1/2". If you don't have this problem, be
-thankful!
-
-It's intended that start time and stop time, when both are present,
-make a half-closed interval: a programme is considered to be
-broadcasting _at_ its start time but to stop just before its stop
-time. In this way a programme from 11:00 to 12:00 does not overlap
-with another programme from 12:00 to 13:00, not even for a moment.
-Nor is there any gap between the two.
-
-To do: Some means of indicating breaks between programmes on the same
-channel. The 'channel' attribute references the 'id' of a channel
-element, but the DTD doesn't give a way to specify this constraint.
-Perhaps there is some better XML syntax we could use for that.
--->
-<!ELEMENT programme (title+, sub-title*, desc*, credits?, date?,
- category*, keyword*, language?, orig-language?,
- length?, icon*, url*, country*, episode-num*,
- video?, audio?, previously-shown?, premiere?,
- last-chance?, new?, subtitles*, rating*,
- star-rating*, review* )>
-<!ATTLIST programme start CDATA #REQUIRED
- stop CDATA #IMPLIED
- pdc-start CDATA #IMPLIED
- vps-start CDATA #IMPLIED
- showview CDATA #IMPLIED
- videoplus CDATA #IMPLIED
- channel CDATA #REQUIRED
- clumpidx CDATA "0/1" >
-
-<!-- Programme title, eg 'The Simpsons'. -->
-<!ELEMENT title (#PCDATA)>
-<!ATTLIST title lang CDATA #IMPLIED>
-
-<!-- Sub-title or episode title, eg 'Datalore'. Should probably be
-called 'secondary title' to avoid confusion with captioning!
--->
-<!ELEMENT sub-title (#PCDATA)>
-<!ATTLIST sub-title lang CDATA #IMPLIED>
-
-<!-- Description of the programme or episode.
-
-Unlike other elements, long bits of whitespace here are treated as
-equivalent to a single space and newlines are permitted, so you can
-break lines and write a pretty-looking paragraph if you wish.
--->
-<!ELEMENT desc (#PCDATA)>
-<!ATTLIST desc lang CDATA #IMPLIED>
-
-<!-- Credits for the programme.
-
-People are listed in decreasing order of importance; so for example
-the starring actors appear first followed by the smaller parts. As
-with other parts of this file format, not mentioning a particular
-actor (for example) does not imply that he _didn't_ star in the film -
-so normally you'd list only the few most important people.
-
-Adapter can be either somebody who adapted a work for television, or
-somebody who did the translation from another language. Maybe these
-should be separate, but if so how would 'translator' fit in with the
-'language' element?
--->
-<!ELEMENT credits (director*, actor*, writer*, adapter*, producer*,
- composer*, editor*, presenter*, commentator*,
- guest* )>
-<!ELEMENT director (#PCDATA)>
-<!ELEMENT actor (#PCDATA)>
-<!ATTLIST actor role CDATA #IMPLIED>
-<!ELEMENT writer (#PCDATA)>
-<!ELEMENT adapter (#PCDATA)>
-<!ELEMENT producer (#PCDATA)>
-<!ELEMENT composer (#PCDATA)>
-<!ELEMENT editor (#PCDATA)>
-<!ELEMENT presenter (#PCDATA)>
-<!ELEMENT commentator (#PCDATA)>
-<!ELEMENT guest (#PCDATA)>
-
-
-<!-- The date the programme or film was finished. This will probably
-be the same as the copyright date.
--->
-<!ELEMENT date (#PCDATA)>
-
-<!-- Type of programme, eg 'soap', 'comedy' or whatever the
-equivalents are in your language. There's no predefined set of
-categories and it's okay for a programme to belong to several.
--->
-<!ELEMENT category (#PCDATA)>
-<!ATTLIST category lang CDATA #IMPLIED>
-
-<!-- Keywords for the programme, eg 'prison-drama', 'based-on-novel',
-'super-hero'. There's no predefined set of keywords and it's likely
-for a programme to have several. It is recommended that keywords
-containing multiple words are hyphenated.
--->
-<!ELEMENT keyword (#PCDATA)>
-<!ATTLIST keyword lang CDATA #IMPLIED>
-
-<!-- The language the programme will be broadcast in. This does not
-include the language of any subtitles, but it is affected by dubbing
-into a different language. For example, if a French film is dubbed
-into English, language=en and orig-language=fr.
-
-There are two ways to specify the language. You can use the
-two-letter codes such as en or fr, or you can give a name such as
-'English' or 'Deutsch'. In the latter case you might want to use the
-'lang' attribute, for example
-
-<language lang="fr">Allemand</language>
--->
-<!ELEMENT language (#PCDATA)>
-<!ATTLIST language lang CDATA #IMPLIED>
-
-<!-- The original language, before dubbing. The same remarks as for
-'language' apply.
--->
-<!ELEMENT orig-language (#PCDATA)>
-<!ATTLIST orig-language lang CDATA #IMPLIED>
-
-<!-- The true length of the programme, not counting advertisements or
-trailers. But this does take account of any bits which were cut out
-of the broadcast version - eg if a two hour film is cut to 110 minutes
-and then padded with 20 minutes of advertising, length will be 110
-minutes even though end time minus start time is 130 minutes.
--->
-<!ELEMENT length (#PCDATA)>
-<!ATTLIST length units (seconds | minutes | hours) #REQUIRED>
-
-<!-- An icon associated with the element that contains it.
-src: uri of image
-width, height: (optional) dimensions of image
-
-These dimensions are pixel dimensions for the time being, eventually
-this will change to be more like HTML's 'img'.
--->
-<!ELEMENT icon EMPTY>
-<!ATTLIST icon src CDATA #REQUIRED
- width CDATA #IMPLIED
- height CDATA #IMPLIED>
-
-<!-- The value of the element that contains it. This is for elements
-that can have both a textual 'value' and an icon. At present there is
-no 'lang' attribute here because things like 'PG' are not translatable
-(although a document explaining what 'PG' actually means would be).
-It happens that 'value' is used only for this sort of thing.
--->
-<!ELEMENT value (#PCDATA)>
-
-<!-- A country where the programme was made or one of the countries in
-a joint production. You can give the name of a country, in which case
-you might want to specify the language in which this name is written,
-or you can give a two-letter uppercase country code, in which case the
-lang attribute should not be given. For example,
-
-<country lang="en">Italy</country>
-<country>GB</country>
--->
-<!ELEMENT country (#PCDATA)>
-<!ATTLIST country lang CDATA #IMPLIED>
-
-<!-- Episode number
-
-Not the title of the episode, its number or ID. There are several
-ways of numbering episodes, so the 'system' attribute lets you specify
-which you mean.
-
-There are two predefined numbering systems, 'xmltv_ns' and
-'onscreen'.
-
-xmltv_ns: This is intended to be a general way to number episodes and
-parts of multi-part episodes. It is three numbers separated by dots,
-the first is the series or season, the second the episode number
-within that series, and the third the part number, if the programme is
-part of a two-parter. All these numbers are indexed from zero, and
-they can be given in the form 'X/Y' to show series X out of Y series
-made, or episode X out of Y episodes in this series, or part X of a
-Y-part episode. If any of these aren't known they can be omitted.
-You can put spaces whereever you like to make things easier to read.
-
-(NB 'part number' is not used when a whole programme is split in two
-for purely scheduling reasons; it's intended for cases where there
-really is a 'Part One' and 'Part Two'. The format doesn't currently
-have a way to represent a whole programme that happens to be split
-across two or more timeslots.)
-
-Some examples will make things clearer. The first episode of the
-second series is '1.0.0/1' . If it were a two-part episode, then the
-first half would be '1.0.0/2' and the second half '1.0.1/2'. If you
-know that an episode is from the first season, but you don't know
-which episode it is or whether it is part of a multiparter, you could
-give the episode-num as '0..'. Here the second and third numbers have
-been omitted. If you know that this is the first part of a three-part
-episode, which is the last episode of the first series of thirteen,
-its number would be '0 . 12/13 . 0/3'. The series number is just '0'
-because you don't know how many series there are in total - perhaps
-the show is still being made!
-
-The other predefined system, onscreen, is to simply copy what the
-programme makers write in the credits - 'Episode #FFEE' would
-translate to '#FFEE'.
-
-You are encouraged to use one of these two if possible; if xmltv_ns is
-not general enough for your needs, let me know. But if you want, you
-can use your own system and give the 'system' attribute as a URL
-describing the system you use.
-
-Systems proposed in 2013 to refer to common metadatabases in a
-common way:
-'themoviedb.org' with the content 'movie/1234' to refer to a movie,
-'thetvdb.com' with the content 'series/123456' to refer to a series,
-'thetvdb.com' with the content 'episode/123456' to refer to one episode
-of a series and 'imdb.com' with the content 'title/tt123455' to refer to
-a movie, series or episode.
-
--->
-<!ELEMENT episode-num (#PCDATA)>
-<!ATTLIST episode-num system CDATA "onscreen">
-
-<!-- Video details: the subelements describe the picture quality as
-follows:
-
-present: whether this programme has a picture (no, in the
-case of radio stations broadcast on TV or 'Blue'), legal values are
-'yes' or 'no'. Obviously if the value is 'no', the other elements are
-meaningless.
-
-colour: 'yes' for colour, 'no' for black-and-white.
-
-aspect: The horizontal:vertical aspect ratio, eg '4:3' or '16:9'.
-
-quality: information on the quality, eg 'HDTV', '800x600'.
-
--->
-<!ELEMENT video (present?, colour?, aspect?, quality?)>
-<!ELEMENT present (#PCDATA)>
-<!ELEMENT colour (#PCDATA)>
-<!ELEMENT aspect (#PCDATA)>
-<!ELEMENT quality (#PCDATA)>
-
-<!-- Audio details, similar to video details above.
-
-present: whether this programme has any sound at all, 'yes' or 'no'.
-
-stereo: Description of the stereo-ness of the sound. Legal values
-are currently 'mono','stereo','dolby','dolby digital','bilingual'
-and 'surround'. 'bilingual' in this case refers to a single audio
-stream where the left and right channels contain monophonic audio
-in different languages. Other values may be added later.
-
--->
-<!ELEMENT audio (present?, stereo?)>
-<!ELEMENT stereo (#PCDATA)>
-
-<!-- When and where the programme was last shown, if known. Normally
-in TV listings 'repeat' means 'previously shown on this channel', but
-if you don't know what channel the old screening was on (but do know
-that it happened) then you can omit the 'channel' attribute.
-Similarly you can omit the 'start' attribute if you don't know when
-the previous transmission was (though you can of course give just the
-year, etc.).
-
-The absence of this element does not say for certain that the
-programme is brand new and has never been screened anywhere before.
--->
-<!ELEMENT previously-shown EMPTY>
-<!ATTLIST previously-shown start CDATA #IMPLIED
- channel CDATA #IMPLIED >
-
-<!-- 'Premiere'. Different channels have different meanings for this
-word - sometimes it means a film has never before been seen on TV in
-that country, but other channels use it to mean 'the first showing of
-this film on our channel in the current run'. It might have been
-shown before, but now they have paid for another set of showings,
-which makes the first in that set count as a premiere!
-
-So this element doesn't have a clear meaning, just use it to represent
-where 'premiere' would appear in a printed TV listing. You can use
-the content of the element to explain exactly what is meant, for
-example:
-
-<premiere lang="en">
- First showing on national terrestrial TV
-</premiere>
-
-The textual content is a 'paragraph' as for <desc>. If you don't want
-to give an explanation, just write empty content:
-
-<premiere />
--->
-<!ELEMENT premiere (#PCDATA)>
-<!ATTLIST premiere lang CDATA #IMPLIED>
-
-<!-- Last-chance. In a way this is the opposite of premiere. Some
-channels buy the rights to show a movie a certain number of times, and
-the first may be flagged 'premiere', the last as 'last showing'.
-
-For symmetry with premiere, you may use the element content to give a
-'paragraph' describing exactly what is meant - it's unlikely to be the
-last showing ever! Otherwise, explicitly put empty content:
-
-<last-chance />
--->
-<!ELEMENT last-chance (#PCDATA)>
-<!ATTLIST last-chance lang CDATA #IMPLIED>
-
-<!-- New. This is the first screened programme from a new show that
-has never been shown on television before - if not worldwide then at
-least never before in this country. After the first episode or
-programme has been shown, subsequent ones are no longer 'new'.
-Similarly the second series of an established programme is not 'new'.
-
-Note that this does not mean 'new season' or 'new episode' of an
-existing show. You can express part of that using the episode-num
-stuff.
--->
-<!ELEMENT new EMPTY>
-
-<!-- Subtitles. These can be either 'teletext' (sent digitally, and
-displayed at the viewer's request), 'onscreen' (superimposed on the
-picture and impossible to get rid of), or 'deaf-signed' (in-vision
-signing for users of sign language). You can have multiple subtitle
-streams to handle different languages. Language for subtitles is
-specified in the same way as for programmes.
--->
-<!ELEMENT subtitles (language?)>
-<!ATTLIST subtitles type (teletext | onscreen | deaf-signed) #IMPLIED>
-
-<!-- Rating. Various bodies decide on classifications for films -
-usually a minimum age you must be to see it. In principle the same
-could be done for ordinary TV programmes. Because there are many
-systems for doing this, you can also specify the rating system used
-(which in practice is the same as the body which made the rating).
--->
-<!ELEMENT rating (value, icon*)>
-<!ATTLIST rating system CDATA #IMPLIED>
-
-<!-- 'Star rating' - many listings guides award a programme a score as
-a quick guide to how good it is. The value of this element should be
-'N / M', for example one star out of a possible five stars would be
-'1 / 5'. Zero stars is also a possible score (and not the same as
-'unrated'). You should try to map whatever wacky system your listings
-source uses to a number of stars: so for example if they have thumbs
-up, thumbs sideways and thumbs down, you could map that to two, one or
-zero stars out of two. If a programme is marked as recommended in a
-listings guide you could map this to '1 / 1'. Because there could be many
-ways to provide star-ratings or recommendations for a programme, you can
-specify multiple star-ratings. You can specify the star-rating system
-used, or the provider of the recommendation, with the system attribute.
-Whitespace between the numbers and slash is ignored.
--->
-
-<!ELEMENT star-rating (value, icon*)>
-<!ATTLIST star-rating system CDATA #IMPLIED>
-
-<!-- Review. Listings guides may provide reviews of programmes in
-addition to, or in place of, standard programme descriptions. They are
-usually written by in-house reviewers, but reviews can also be made
-available by third-party organisations/individuals. The value of this
-element must be either the text of the review, or a URL that links to it.
-Optional attributes giving the review source and the individual reviewer
-can also be specified.
--->
-<!ELEMENT review (#PCDATA)>
-<!ATTLIST review type (text | url) #REQUIRED
- source CDATA #IMPLIED
- reviewer CDATA #IMPLIED
- lang CDATA #IMPLIED>
-
-<!-- (Why are things like 'stereo', which must be one of a small
-number of values, stored as the contents of elements rather than as
-attributes? Because they are data rather than metadata. Attributes
-are used for things like the language or encoding of element contents,
-or for programme transmission details.) --> \ No newline at end of file
diff --git a/Emby.XmlTv/License.txt b/Emby.XmlTv/License.txt
deleted file mode 100644
index 3c4f73ddb..000000000
--- a/Emby.XmlTv/License.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 Alex Stevens
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/Emby.XmlTv/Nuget/Emby.XmlTv.nuspec b/Emby.XmlTv/Nuget/Emby.XmlTv.nuspec
deleted file mode 100644
index 087ce1e6e..000000000
--- a/Emby.XmlTv/Nuget/Emby.XmlTv.nuspec
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
- <metadata>
- <id>Emby.XmlTv</id>
- <version>1.0.19</version>
- <title>Emby.XmlTv</title>
- <authors>Emby Team</authors>
- <owners>ebr,Luke,scottisafool</owners>
- <projectUrl>https://github.com/MediaBrowser/Emby.XmlTv</projectUrl>
- <iconUrl>http://www.mb3admin.com/images/mb3icons1-1.png</iconUrl>
- <requireLicenseAcceptance>false</requireLicenseAcceptance>
- <description>An XmlTv parsing library.</description>
- <copyright>Copyright © Emby 2013</copyright>
- <dependencies>
- </dependencies>
- </metadata>
- <files>
- <file src="dlls\Emby.XmlTv.dll" target="lib\portable-net45+netstandard2.0+win8\Emby.XmlTv.dll" />
- </files>
-</package> \ No newline at end of file
diff --git a/Emby.XmlTv/README.md b/Emby.XmlTv/README.md
deleted file mode 100644
index 86e777bb2..000000000
--- a/Emby.XmlTv/README.md
+++ /dev/null
@@ -1 +0,0 @@
-# Emby.XmlTv
diff --git a/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs
new file mode 100644
index 000000000..49b6689cd
--- /dev/null
+++ b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Internal produces image attribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method)]
+ public class AcceptsFileAttribute : Attribute
+ {
+ private readonly string[] _contentTypes;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AcceptsFileAttribute"/> class.
+ /// </summary>
+ /// <param name="contentTypes">Content types this endpoint produces.</param>
+ public AcceptsFileAttribute(params string[] contentTypes)
+ {
+ _contentTypes = contentTypes;
+ }
+
+ /// <summary>
+ /// Gets the configured content types.
+ /// </summary>
+ /// <returns>the configured content types.</returns>
+ public string[] GetContentTypes() => _contentTypes;
+ }
+}
diff --git a/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs
new file mode 100644
index 000000000..001f27409
--- /dev/null
+++ b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Produces file attribute of "image/*".
+ /// </summary>
+ public class AcceptsImageFileAttribute : AcceptsFileAttribute
+ {
+ private const string ContentType = "image/*";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AcceptsImageFileAttribute"/> class.
+ /// </summary>
+ public AcceptsImageFileAttribute()
+ : base(ContentType)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs b/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs
new file mode 100644
index 000000000..2fdd1e489
--- /dev/null
+++ b/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.AspNetCore.Mvc.Routing;
+
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Identifies an action that supports the HTTP GET method.
+ /// </summary>
+ public class HttpSubscribeAttribute : HttpMethodAttribute
+ {
+ private static readonly IEnumerable<string> _supportedMethods = new[] { "SUBSCRIBE" };
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpSubscribeAttribute"/> class.
+ /// </summary>
+ public HttpSubscribeAttribute()
+ : base(_supportedMethods)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpSubscribeAttribute"/> class.
+ /// </summary>
+ /// <param name="template">The route template. May not be null.</param>
+ public HttpSubscribeAttribute(string template)
+ : base(_supportedMethods, template)
+ {
+ if (template == null)
+ {
+ throw new ArgumentNullException(nameof(template));
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs b/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs
new file mode 100644
index 000000000..d6d7e4563
--- /dev/null
+++ b/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.AspNetCore.Mvc.Routing;
+
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Identifies an action that supports the HTTP GET method.
+ /// </summary>
+ public class HttpUnsubscribeAttribute : HttpMethodAttribute
+ {
+ private static readonly IEnumerable<string> _supportedMethods = new[] { "UNSUBSCRIBE" };
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpUnsubscribeAttribute"/> class.
+ /// </summary>
+ public HttpUnsubscribeAttribute()
+ : base(_supportedMethods)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpUnsubscribeAttribute"/> class.
+ /// </summary>
+ /// <param name="template">The route template. May not be null.</param>
+ public HttpUnsubscribeAttribute(string template)
+ : base(_supportedMethods, template)
+ {
+ if (template == null)
+ {
+ throw new ArgumentNullException(nameof(template));
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs
new file mode 100644
index 000000000..56c9772b6
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs
@@ -0,0 +1,12 @@
+using System;
+
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Attribute to mark a parameter as obsolete.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Parameter)]
+ public class ParameterObsoleteAttribute : Attribute
+ {
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs
new file mode 100644
index 000000000..3adb700eb
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Produces file attribute of "image/*".
+ /// </summary>
+ public class ProducesAudioFileAttribute : ProducesFileAttribute
+ {
+ private const string ContentType = "audio/*";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProducesAudioFileAttribute"/> class.
+ /// </summary>
+ public ProducesAudioFileAttribute()
+ : base(ContentType)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ProducesFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesFileAttribute.cs
new file mode 100644
index 000000000..62a576ede
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ProducesFileAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Internal produces image attribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method)]
+ public class ProducesFileAttribute : Attribute
+ {
+ private readonly string[] _contentTypes;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProducesFileAttribute"/> class.
+ /// </summary>
+ /// <param name="contentTypes">Content types this endpoint produces.</param>
+ public ProducesFileAttribute(params string[] contentTypes)
+ {
+ _contentTypes = contentTypes;
+ }
+
+ /// <summary>
+ /// Gets the configured content types.
+ /// </summary>
+ /// <returns>the configured content types.</returns>
+ public string[] GetContentTypes() => _contentTypes;
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs
new file mode 100644
index 000000000..e15813676
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Produces file attribute of "image/*".
+ /// </summary>
+ public class ProducesImageFileAttribute : ProducesFileAttribute
+ {
+ private const string ContentType = "image/*";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProducesImageFileAttribute"/> class.
+ /// </summary>
+ public ProducesImageFileAttribute()
+ : base(ContentType)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs
new file mode 100644
index 000000000..5d928ab91
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Produces file attribute of "image/*".
+ /// </summary>
+ public class ProducesPlaylistFileAttribute : ProducesFileAttribute
+ {
+ private const string ContentType = "application/x-mpegURL";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProducesPlaylistFileAttribute"/> class.
+ /// </summary>
+ public ProducesPlaylistFileAttribute()
+ : base(ContentType)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs
new file mode 100644
index 000000000..d8b2856dc
--- /dev/null
+++ b/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Attributes
+{
+ /// <summary>
+ /// Produces file attribute of "video/*".
+ /// </summary>
+ public class ProducesVideoFileAttribute : ProducesFileAttribute
+ {
+ private const string ContentType = "video/*";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProducesVideoFileAttribute"/> class.
+ /// </summary>
+ public ProducesVideoFileAttribute()
+ : base(ContentType)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs
new file mode 100644
index 000000000..88af08dd3
--- /dev/null
+++ b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs
@@ -0,0 +1,47 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
+{
+ /// <summary>
+ /// LAN access handler. Allows anonymous users.
+ /// </summary>
+ public class AnonymousLanAccessHandler : AuthorizationHandler<AnonymousLanAccessRequirement>
+ {
+ private readonly INetworkManager _networkManager;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AnonymousLanAccessHandler"/> class.
+ /// </summary>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public AnonymousLanAccessHandler(
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ {
+ _networkManager = networkManager;
+ _httpContextAccessor = httpContextAccessor;
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement)
+ {
+ var ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress;
+
+ // Loopback will be on LAN, so we can accept null.
+ if (ip == null || _networkManager.IsInLocalNetwork(ip))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessRequirement.cs b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessRequirement.cs
new file mode 100644
index 000000000..49af24ff3
--- /dev/null
+++ b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
+{
+ /// <summary>
+ /// The local network authorization requirement. Allows anonymous users.
+ /// </summary>
+ public class AnonymousLanAccessRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs
new file mode 100644
index 000000000..13d3257df
--- /dev/null
+++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs
@@ -0,0 +1,112 @@
+using System.Security.Claims;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth
+{
+ /// <summary>
+ /// Base authorization handler.
+ /// </summary>
+ /// <typeparam name="T">Type of Authorization Requirement.</typeparam>
+ public abstract class BaseAuthorizationHandler<T> : AuthorizationHandler<T>
+ where T : IAuthorizationRequirement
+ {
+ private readonly IUserManager _userManager;
+ private readonly INetworkManager _networkManager;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseAuthorizationHandler{T}"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ protected BaseAuthorizationHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ {
+ _userManager = userManager;
+ _networkManager = networkManager;
+ _httpContextAccessor = httpContextAccessor;
+ }
+
+ /// <summary>
+ /// Validate authenticated claims.
+ /// </summary>
+ /// <param name="claimsPrincipal">Request claims.</param>
+ /// <param name="ignoreSchedule">Whether to ignore parental control.</param>
+ /// <param name="localAccessOnly">Whether access is to be allowed locally only.</param>
+ /// <param name="requiredDownloadPermission">Whether validation requires download permission.</param>
+ /// <returns>Validated claim status.</returns>
+ protected bool ValidateClaims(
+ ClaimsPrincipal claimsPrincipal,
+ bool ignoreSchedule = false,
+ bool localAccessOnly = false,
+ bool requiredDownloadPermission = false)
+ {
+ // ApiKey is currently global admin, always allow.
+ var isApiKey = ClaimHelpers.GetIsApiKey(claimsPrincipal);
+ if (isApiKey)
+ {
+ return true;
+ }
+
+ // Ensure claim has userId.
+ var userId = ClaimHelpers.GetUserId(claimsPrincipal);
+ if (!userId.HasValue)
+ {
+ return false;
+ }
+
+ // Ensure userId links to a valid user.
+ var user = _userManager.GetUserById(userId.Value);
+ if (user == null)
+ {
+ return false;
+ }
+
+ // Ensure user is not disabled.
+ if (user.HasPermission(PermissionKind.IsDisabled))
+ {
+ return false;
+ }
+
+ var isInLocalNetwork = _httpContextAccessor.HttpContext != null
+ && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp());
+
+ // User cannot access remotely and user is remote
+ if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !isInLocalNetwork)
+ {
+ return false;
+ }
+
+ if (localAccessOnly && !isInLocalNetwork)
+ {
+ return false;
+ }
+
+ // User attempting to access out of parental control hours.
+ if (!ignoreSchedule
+ && !user.HasPermission(PermissionKind.IsAdministrator)
+ && !user.IsParentalScheduleAllowed())
+ {
+ return false;
+ }
+
+ // User attempting to download without permission.
+ if (requiredDownloadPermission
+ && !user.HasPermission(PermissionKind.EnableContentDownloading))
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs
new file mode 100644
index 000000000..369e846ae
--- /dev/null
+++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs
@@ -0,0 +1,84 @@
+using System.Globalization;
+using System.Security.Claims;
+using System.Text.Encodings.Web;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace Jellyfin.Api.Auth
+{
+ /// <summary>
+ /// Custom authentication handler wrapping the legacy authentication.
+ /// </summary>
+ public class CustomAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
+ {
+ private readonly IAuthService _authService;
+ private readonly ILogger<CustomAuthenticationHandler> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CustomAuthenticationHandler" /> class.
+ /// </summary>
+ /// <param name="authService">The jellyfin authentication service.</param>
+ /// <param name="options">Options monitor.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="encoder">The url encoder.</param>
+ /// <param name="clock">The system clock.</param>
+ public CustomAuthenticationHandler(
+ IAuthService authService,
+ IOptionsMonitor<AuthenticationSchemeOptions> options,
+ ILoggerFactory logger,
+ UrlEncoder encoder,
+ ISystemClock clock) : base(options, logger, encoder, clock)
+ {
+ _authService = authService;
+ _logger = logger.CreateLogger<CustomAuthenticationHandler>();
+ }
+
+ /// <inheritdoc />
+ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
+ {
+ try
+ {
+ var authorizationInfo = await _authService.Authenticate(Request).ConfigureAwait(false);
+ var role = UserRoles.User;
+ if (authorizationInfo.IsApiKey || authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator))
+ {
+ role = UserRoles.Administrator;
+ }
+
+ var claims = new[]
+ {
+ new Claim(ClaimTypes.Name, authorizationInfo.User?.Username ?? string.Empty),
+ new Claim(ClaimTypes.Role, role),
+ new Claim(InternalClaimTypes.UserId, authorizationInfo.UserId.ToString("N", CultureInfo.InvariantCulture)),
+ new Claim(InternalClaimTypes.DeviceId, authorizationInfo.DeviceId),
+ new Claim(InternalClaimTypes.Device, authorizationInfo.Device),
+ new Claim(InternalClaimTypes.Client, authorizationInfo.Client),
+ new Claim(InternalClaimTypes.Version, authorizationInfo.Version),
+ new Claim(InternalClaimTypes.Token, authorizationInfo.Token),
+ new Claim(InternalClaimTypes.IsApiKey, authorizationInfo.IsApiKey.ToString(CultureInfo.InvariantCulture))
+ };
+
+ var identity = new ClaimsIdentity(claims, Scheme.Name);
+ var principal = new ClaimsPrincipal(identity);
+ var ticket = new AuthenticationTicket(principal, Scheme.Name);
+
+ return AuthenticateResult.Success(ticket);
+ }
+ catch (AuthenticationException ex)
+ {
+ _logger.LogDebug(ex, "Error authenticating with {Handler}", nameof(CustomAuthenticationHandler));
+ return AuthenticateResult.NoResult();
+ }
+ catch (SecurityException ex)
+ {
+ return AuthenticateResult.Fail(ex);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs
new file mode 100644
index 000000000..be77b7a4e
--- /dev/null
+++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs
@@ -0,0 +1,44 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy
+{
+ /// <summary>
+ /// Default authorization handler.
+ /// </summary>
+ public class DefaultAuthorizationHandler : BaseAuthorizationHandler<DefaultAuthorizationRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DefaultAuthorizationHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public DefaultAuthorizationHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DefaultAuthorizationRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationRequirement.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationRequirement.cs
new file mode 100644
index 000000000..7cea00b69
--- /dev/null
+++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy
+{
+ /// <summary>
+ /// The default authorization requirement.
+ /// </summary>
+ public class DefaultAuthorizationRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs
new file mode 100644
index 000000000..b61680ab1
--- /dev/null
+++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs
@@ -0,0 +1,44 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.DownloadPolicy
+{
+ /// <summary>
+ /// Download authorization handler.
+ /// </summary>
+ public class DownloadHandler : BaseAuthorizationHandler<DownloadRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DownloadHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public DownloadHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DownloadRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadRequirement.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadRequirement.cs
new file mode 100644
index 000000000..b0a72a9de
--- /dev/null
+++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.DownloadPolicy
+{
+ /// <summary>
+ /// The download permission requirement.
+ /// </summary>
+ public class DownloadRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs
new file mode 100644
index 000000000..31482a930
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs
@@ -0,0 +1,56 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy
+{
+ /// <summary>
+ /// Ignore parental control schedule and allow before startup wizard has been completed.
+ /// </summary>
+ public class FirstTimeOrIgnoreParentalControlSetupHandler : BaseAuthorizationHandler<FirstTimeOrIgnoreParentalControlSetupRequirement>
+ {
+ private readonly IConfigurationManager _configurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FirstTimeOrIgnoreParentalControlSetupHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ public FirstTimeOrIgnoreParentalControlSetupHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor,
+ IConfigurationManager configurationManager)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ _configurationManager = configurationManager;
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FirstTimeOrIgnoreParentalControlSetupRequirement requirement)
+ {
+ if (!_configurationManager.CommonConfiguration.IsStartupWizardCompleted)
+ {
+ context.Succeed(requirement);
+ return Task.CompletedTask;
+ }
+
+ var validated = ValidateClaims(context.User, ignoreSchedule: true);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupRequirement.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupRequirement.cs
new file mode 100644
index 000000000..00aaec334
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy
+{
+ /// <summary>
+ /// First time setup or ignore parental controls requirement.
+ /// </summary>
+ public class FirstTimeOrIgnoreParentalControlSetupRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs
new file mode 100644
index 000000000..dd0bd4ec2
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs
@@ -0,0 +1,56 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy
+{
+ /// <summary>
+ /// Authorization handler for requiring first time setup or default privileges.
+ /// </summary>
+ public class FirstTimeSetupOrDefaultHandler : BaseAuthorizationHandler<FirstTimeSetupOrDefaultRequirement>
+ {
+ private readonly IConfigurationManager _configurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FirstTimeSetupOrDefaultHandler" /> class.
+ /// </summary>
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public FirstTimeSetupOrDefaultHandler(
+ IConfigurationManager configurationManager,
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ _configurationManager = configurationManager;
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FirstTimeSetupOrDefaultRequirement requirement)
+ {
+ if (!_configurationManager.CommonConfiguration.IsStartupWizardCompleted)
+ {
+ context.Succeed(requirement);
+ return Task.CompletedTask;
+ }
+
+ var validated = ValidateClaims(context.User);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultRequirement.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultRequirement.cs
new file mode 100644
index 000000000..f7366bd7a
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy
+{
+ /// <summary>
+ /// The authorization requirement, requiring incomplete first time setup or default privileges, for the authorization handler.
+ /// </summary>
+ public class FirstTimeSetupOrDefaultRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs
new file mode 100644
index 000000000..90b76ee99
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs
@@ -0,0 +1,57 @@
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy
+{
+ /// <summary>
+ /// Authorization handler for requiring first time setup or elevated privileges.
+ /// </summary>
+ public class FirstTimeSetupOrElevatedHandler : BaseAuthorizationHandler<FirstTimeSetupOrElevatedRequirement>
+ {
+ private readonly IConfigurationManager _configurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FirstTimeSetupOrElevatedHandler" /> class.
+ /// </summary>
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public FirstTimeSetupOrElevatedHandler(
+ IConfigurationManager configurationManager,
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ _configurationManager = configurationManager;
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FirstTimeSetupOrElevatedRequirement requirement)
+ {
+ if (!_configurationManager.CommonConfiguration.IsStartupWizardCompleted)
+ {
+ context.Succeed(requirement);
+ return Task.CompletedTask;
+ }
+
+ var validated = ValidateClaims(context.User);
+ if (validated && context.User.IsInRole(UserRoles.Administrator))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs
new file mode 100644
index 000000000..51ba637b6
--- /dev/null
+++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy
+{
+ /// <summary>
+ /// The authorization requirement, requiring incomplete first time setup or elevated privileges, for the authorization handler.
+ /// </summary>
+ public class FirstTimeSetupOrElevatedRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs
new file mode 100644
index 000000000..a7623556a
--- /dev/null
+++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs
@@ -0,0 +1,44 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.IgnoreParentalControlPolicy
+{
+ /// <summary>
+ /// Escape schedule controls handler.
+ /// </summary>
+ public class IgnoreParentalControlHandler : BaseAuthorizationHandler<IgnoreParentalControlRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IgnoreParentalControlHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public IgnoreParentalControlHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IgnoreParentalControlRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User, ignoreSchedule: true);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlRequirement.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlRequirement.cs
new file mode 100644
index 000000000..cdad74270
--- /dev/null
+++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.IgnoreParentalControlPolicy
+{
+ /// <summary>
+ /// Escape schedule controls requirement.
+ /// </summary>
+ public class IgnoreParentalControlRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs
new file mode 100644
index 000000000..14722aa57
--- /dev/null
+++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs
@@ -0,0 +1,45 @@
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy
+{
+ /// <summary>
+ /// Local access or require elevated privileges handler.
+ /// </summary>
+ public class LocalAccessOrRequiresElevationHandler : BaseAuthorizationHandler<LocalAccessOrRequiresElevationRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LocalAccessOrRequiresElevationHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public LocalAccessOrRequiresElevationHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessOrRequiresElevationRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User, localAccessOnly: true);
+ if (validated || context.User.IsInRole(UserRoles.Administrator))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationRequirement.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationRequirement.cs
new file mode 100644
index 000000000..d9c64d01c
--- /dev/null
+++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy
+{
+ /// <summary>
+ /// The local access or elevated privileges authorization requirement.
+ /// </summary>
+ public class LocalAccessOrRequiresElevationRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs
new file mode 100644
index 000000000..d772ec554
--- /dev/null
+++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs
@@ -0,0 +1,44 @@
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.LocalAccessPolicy
+{
+ /// <summary>
+ /// Local access handler.
+ /// </summary>
+ public class LocalAccessHandler : BaseAuthorizationHandler<LocalAccessRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LocalAccessHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public LocalAccessHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User, localAccessOnly: true);
+ if (validated)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessRequirement.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessRequirement.cs
new file mode 100644
index 000000000..761127fa4
--- /dev/null
+++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.LocalAccessPolicy
+{
+ /// <summary>
+ /// The local access authorization requirement.
+ /// </summary>
+ public class LocalAccessRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs
new file mode 100644
index 000000000..b235c4b63
--- /dev/null
+++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs
@@ -0,0 +1,45 @@
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.RequiresElevationPolicy
+{
+ /// <summary>
+ /// Authorization handler for requiring elevated privileges.
+ /// </summary>
+ public class RequiresElevationHandler : BaseAuthorizationHandler<RequiresElevationRequirement>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RequiresElevationHandler"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public RequiresElevationHandler(
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RequiresElevationRequirement requirement)
+ {
+ var validated = ValidateClaims(context.User);
+ if (validated && context.User.IsInRole(UserRoles.Administrator))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs
new file mode 100644
index 000000000..cfff1cc0c
--- /dev/null
+++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs
@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.RequiresElevationPolicy
+{
+ /// <summary>
+ /// The authorization requirement for requiring elevated privileges in the authorization handler.
+ /// </summary>
+ public class RequiresElevationRequirement : IAuthorizationRequirement
+ {
+ }
+}
diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs
new file mode 100644
index 000000000..e6c04eb08
--- /dev/null
+++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs
@@ -0,0 +1,105 @@
+using System.Threading.Tasks;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.SyncPlay;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy
+{
+ /// <summary>
+ /// Default authorization handler.
+ /// </summary>
+ public class SyncPlayAccessHandler : BaseAuthorizationHandler<SyncPlayAccessRequirement>
+ {
+ private readonly ISyncPlayManager _syncPlayManager;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayAccessHandler"/> class.
+ /// </summary>
+ /// <param name="syncPlayManager">Instance of the <see cref="ISyncPlayManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ public SyncPlayAccessHandler(
+ ISyncPlayManager syncPlayManager,
+ IUserManager userManager,
+ INetworkManager networkManager,
+ IHttpContextAccessor httpContextAccessor)
+ : base(userManager, networkManager, httpContextAccessor)
+ {
+ _syncPlayManager = syncPlayManager;
+ _userManager = userManager;
+ }
+
+ /// <inheritdoc />
+ protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SyncPlayAccessRequirement requirement)
+ {
+ if (!ValidateClaims(context.User))
+ {
+ context.Fail();
+ return Task.CompletedTask;
+ }
+
+ var userId = ClaimHelpers.GetUserId(context.User);
+ var user = _userManager.GetUserById(userId!.Value);
+
+ if (requirement.RequiredAccess == SyncPlayAccessRequirementType.HasAccess)
+ {
+ if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups
+ || user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups
+ || _syncPlayManager.IsUserActive(userId.Value))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+ }
+ else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.CreateGroup)
+ {
+ if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+ }
+ else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.JoinGroup)
+ {
+ if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups
+ || user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups)
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+ }
+ else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.IsInGroup)
+ {
+ if (_syncPlayManager.IsUserActive(userId.Value))
+ {
+ context.Succeed(requirement);
+ }
+ else
+ {
+ context.Fail();
+ }
+ }
+ else
+ {
+ context.Fail();
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs
new file mode 100644
index 000000000..6fab4c0ad
--- /dev/null
+++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs
@@ -0,0 +1,25 @@
+using Jellyfin.Data.Enums;
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy
+{
+ /// <summary>
+ /// The default authorization requirement.
+ /// </summary>
+ public class SyncPlayAccessRequirement : IAuthorizationRequirement
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayAccessRequirement"/> class.
+ /// </summary>
+ /// <param name="requiredAccess">A value of <see cref="SyncPlayAccessRequirementType"/>.</param>
+ public SyncPlayAccessRequirement(SyncPlayAccessRequirementType requiredAccess)
+ {
+ RequiredAccess = requiredAccess;
+ }
+
+ /// <summary>
+ /// Gets the required SyncPlay access.
+ /// </summary>
+ public SyncPlayAccessRequirementType RequiredAccess { get; }
+ }
+}
diff --git a/Jellyfin.Api/BaseJellyfinApiController.cs b/Jellyfin.Api/BaseJellyfinApiController.cs
new file mode 100644
index 000000000..59d6b7513
--- /dev/null
+++ b/Jellyfin.Api/BaseJellyfinApiController.cs
@@ -0,0 +1,19 @@
+using System.Net.Mime;
+using Jellyfin.Extensions.Json;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api
+{
+ /// <summary>
+ /// Base api controller for the API setting a default route.
+ /// </summary>
+ [ApiController]
+ [Route("[controller]")]
+ [Produces(
+ MediaTypeNames.Application.Json,
+ JsonDefaults.CamelCaseMediaType,
+ JsonDefaults.PascalCaseMediaType)]
+ public class BaseJellyfinApiController : ControllerBase
+ {
+ }
+}
diff --git a/Jellyfin.Api/Constants/AuthenticationSchemes.cs b/Jellyfin.Api/Constants/AuthenticationSchemes.cs
new file mode 100644
index 000000000..bac3379e7
--- /dev/null
+++ b/Jellyfin.Api/Constants/AuthenticationSchemes.cs
@@ -0,0 +1,13 @@
+namespace Jellyfin.Api.Constants
+{
+ /// <summary>
+ /// Authentication schemes for user authentication in the API.
+ /// </summary>
+ public static class AuthenticationSchemes
+ {
+ /// <summary>
+ /// Scheme name for the custom legacy authentication.
+ /// </summary>
+ public const string CustomAuthentication = "CustomAuthentication";
+ }
+}
diff --git a/Jellyfin.Api/Constants/InternalClaimTypes.cs b/Jellyfin.Api/Constants/InternalClaimTypes.cs
new file mode 100644
index 000000000..8323312e5
--- /dev/null
+++ b/Jellyfin.Api/Constants/InternalClaimTypes.cs
@@ -0,0 +1,43 @@
+namespace Jellyfin.Api.Constants
+{
+ /// <summary>
+ /// Internal claim types for authorization.
+ /// </summary>
+ public static class InternalClaimTypes
+ {
+ /// <summary>
+ /// User Id.
+ /// </summary>
+ public const string UserId = "Jellyfin-UserId";
+
+ /// <summary>
+ /// Device Id.
+ /// </summary>
+ public const string DeviceId = "Jellyfin-DeviceId";
+
+ /// <summary>
+ /// Device.
+ /// </summary>
+ public const string Device = "Jellyfin-Device";
+
+ /// <summary>
+ /// Client.
+ /// </summary>
+ public const string Client = "Jellyfin-Client";
+
+ /// <summary>
+ /// Version.
+ /// </summary>
+ public const string Version = "Jellyfin-Version";
+
+ /// <summary>
+ /// Token.
+ /// </summary>
+ public const string Token = "Jellyfin-Token";
+
+ /// <summary>
+ /// Is Api Key.
+ /// </summary>
+ public const string IsApiKey = "Jellyfin-IsApiKey";
+ }
+}
diff --git a/Jellyfin.Api/Constants/Policies.cs b/Jellyfin.Api/Constants/Policies.cs
new file mode 100644
index 000000000..a72eeea28
--- /dev/null
+++ b/Jellyfin.Api/Constants/Policies.cs
@@ -0,0 +1,78 @@
+namespace Jellyfin.Api.Constants
+{
+ /// <summary>
+ /// Policies for the API authorization.
+ /// </summary>
+ public static class Policies
+ {
+ /// <summary>
+ /// Policy name for default authorization.
+ /// </summary>
+ public const string DefaultAuthorization = "DefaultAuthorization";
+
+ /// <summary>
+ /// Policy name for requiring first time setup or elevated privileges.
+ /// </summary>
+ public const string FirstTimeSetupOrElevated = "FirstTimeSetupOrElevated";
+
+ /// <summary>
+ /// Policy name for requiring elevated privileges.
+ /// </summary>
+ public const string RequiresElevation = "RequiresElevation";
+
+ /// <summary>
+ /// Policy name for allowing local access only.
+ /// </summary>
+ public const string LocalAccessOnly = "LocalAccessOnly";
+
+ /// <summary>
+ /// Policy name for escaping schedule controls.
+ /// </summary>
+ public const string IgnoreParentalControl = "IgnoreParentalControl";
+
+ /// <summary>
+ /// Policy name for requiring download permission.
+ /// </summary>
+ public const string Download = "Download";
+
+ /// <summary>
+ /// Policy name for requiring first time setup or default permissions.
+ /// </summary>
+ public const string FirstTimeSetupOrDefault = "FirstTimeSetupOrDefault";
+
+ /// <summary>
+ /// Policy name for requiring local access or elevated privileges.
+ /// </summary>
+ public const string LocalAccessOrRequiresElevation = "LocalAccessOrRequiresElevation";
+
+ /// <summary>
+ /// Policy name for requiring (anonymous) LAN access.
+ /// </summary>
+ public const string AnonymousLanAccessPolicy = "AnonymousLanAccessPolicy";
+
+ /// <summary>
+ /// Policy name for escaping schedule controls or requiring first time setup.
+ /// </summary>
+ public const string FirstTimeSetupOrIgnoreParentalControl = "FirstTimeSetupOrIgnoreParentalControl";
+
+ /// <summary>
+ /// Policy name for accessing SyncPlay.
+ /// </summary>
+ public const string SyncPlayHasAccess = "SyncPlayHasAccess";
+
+ /// <summary>
+ /// Policy name for creating a SyncPlay group.
+ /// </summary>
+ public const string SyncPlayCreateGroup = "SyncPlayCreateGroup";
+
+ /// <summary>
+ /// Policy name for joining a SyncPlay group.
+ /// </summary>
+ public const string SyncPlayJoinGroup = "SyncPlayJoinGroup";
+
+ /// <summary>
+ /// Policy name for accessing a SyncPlay group.
+ /// </summary>
+ public const string SyncPlayIsInGroup = "SyncPlayIsInGroup";
+ }
+}
diff --git a/Jellyfin.Api/Constants/UserRoles.cs b/Jellyfin.Api/Constants/UserRoles.cs
new file mode 100644
index 000000000..d9a536e7d
--- /dev/null
+++ b/Jellyfin.Api/Constants/UserRoles.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Api.Constants
+{
+ /// <summary>
+ /// Constants for user roles used in the authentication and authorization for the API.
+ /// </summary>
+ public static class UserRoles
+ {
+ /// <summary>
+ /// Guest user.
+ /// </summary>
+ public const string Guest = "Guest";
+
+ /// <summary>
+ /// Regular user with no special privileges.
+ /// </summary>
+ public const string User = "User";
+
+ /// <summary>
+ /// Administrator user with elevated privileges.
+ /// </summary>
+ public const string Administrator = "Administrator";
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ActivityLogController.cs b/Jellyfin.Api/Controllers/ActivityLogController.cs
new file mode 100644
index 000000000..ae45f647f
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ActivityLogController.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Activity log controller.
+ /// </summary>
+ [Route("System/ActivityLog")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public class ActivityLogController : BaseJellyfinApiController
+ {
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ActivityLogController"/> class.
+ /// </summary>
+ /// <param name="activityManager">Instance of <see cref="IActivityManager"/> interface.</param>
+ public ActivityLogController(IActivityManager activityManager)
+ {
+ _activityManager = activityManager;
+ }
+
+ /// <summary>
+ /// Gets activity log entries.
+ /// </summary>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="minDate">Optional. The minimum date. Format = ISO.</param>
+ /// <param name="hasUserId">Optional. Filter log entries if it has user id, or not.</param>
+ /// <response code="200">Activity log returned.</response>
+ /// <returns>A <see cref="QueryResult{ActivityLogEntry}"/> containing the log entries.</returns>
+ [HttpGet("Entries")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<ActivityLogEntry>>> GetLogEntries(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] DateTime? minDate,
+ [FromQuery] bool? hasUserId)
+ {
+ return await _activityManager.GetPagedResultAsync(new ActivityLogQuery
+ {
+ Skip = startIndex,
+ Limit = limit,
+ MinDate = minDate,
+ HasUserId = hasUserId
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ApiKeyController.cs b/Jellyfin.Api/Controllers/ApiKeyController.cs
new file mode 100644
index 000000000..8e0332d3e
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ApiKeyController.cs
@@ -0,0 +1,80 @@
+using System.ComponentModel.DataAnnotations;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller.Security;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Authentication controller.
+ /// </summary>
+ [Route("Auth")]
+ public class ApiKeyController : BaseJellyfinApiController
+ {
+ private readonly IAuthenticationManager _authenticationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ApiKeyController"/> class.
+ /// </summary>
+ /// <param name="authenticationManager">Instance of <see cref="IAuthenticationManager"/> interface.</param>
+ public ApiKeyController(IAuthenticationManager authenticationManager)
+ {
+ _authenticationManager = authenticationManager;
+ }
+
+ /// <summary>
+ /// Get all keys.
+ /// </summary>
+ /// <response code="200">Api keys retrieved.</response>
+ /// <returns>A <see cref="QueryResult{AuthenticationInfo}"/> with all keys.</returns>
+ [HttpGet("Keys")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<AuthenticationInfo>>> GetKeys()
+ {
+ var keys = await _authenticationManager.GetApiKeys();
+
+ return new QueryResult<AuthenticationInfo>
+ {
+ Items = keys,
+ TotalRecordCount = keys.Count
+ };
+ }
+
+ /// <summary>
+ /// Create a new api key.
+ /// </summary>
+ /// <param name="app">Name of the app using the authentication key.</param>
+ /// <response code="204">Api key created.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Keys")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CreateKey([FromQuery, Required] string app)
+ {
+ await _authenticationManager.CreateApiKey(app).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Remove an api key.
+ /// </summary>
+ /// <param name="key">The access token to delete.</param>
+ /// <response code="204">Api key deleted.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Keys/{key}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> RevokeKey([FromRoute, Required] string key)
+ {
+ await _authenticationManager.DeleteApiKey(key).ConfigureAwait(false);
+
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs
new file mode 100644
index 000000000..154a56702
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ArtistsController.cs
@@ -0,0 +1,482 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The artists controller.
+ /// </summary>
+ [Route("Artists")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ArtistsController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistsController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ public ArtistsController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ }
+
+ /// <summary>
+ /// Gets all artists from a given item, folder, or the entire library.
+ /// </summary>
+ /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">Optional. Search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
+ /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
+ /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
+ /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
+ /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
+ /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person ids.</param>
+ /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
+ /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="enableTotalRecordCount">Total record count.</param>
+ /// <response code="200">Artists returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the artists.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetArtists(
+ [FromQuery] double? minCommunityRating,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? person,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ User? user = null;
+ BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ user = _userManager.GetUserById(userId.Value);
+ }
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ MediaTypes = mediaTypes,
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ Tags = tags,
+ OfficialRatings = officialRatings,
+ Genres = genres,
+ GenreIds = genreIds,
+ StudioIds = studioIds,
+ Person = person,
+ PersonIds = personIds,
+ PersonTypes = personTypes,
+ Years = years,
+ MinCommunityRating = minCommunityRating,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
+ };
+
+ if (parentId.HasValue)
+ {
+ if (parentItem is Folder)
+ {
+ query.AncestorIds = new[] { parentId.Value };
+ }
+ else
+ {
+ query.ItemIds = new[] { parentId.Value };
+ }
+ }
+
+ // Studios
+ if (studios.Length != 0)
+ {
+ query.StudioIds = studios.Select(i =>
+ {
+ try
+ {
+ return _libraryManager.GetStudio(i);
+ }
+ catch
+ {
+ return null;
+ }
+ }).Where(i => i != null).Select(i => i!.Id).ToArray();
+ }
+
+ foreach (var filter in filters)
+ {
+ switch (filter)
+ {
+ case ItemFilter.Dislikes:
+ query.IsLiked = false;
+ break;
+ case ItemFilter.IsFavorite:
+ query.IsFavorite = true;
+ break;
+ case ItemFilter.IsFavoriteOrLikes:
+ query.IsFavoriteOrLiked = true;
+ break;
+ case ItemFilter.IsFolder:
+ query.IsFolder = true;
+ break;
+ case ItemFilter.IsNotFolder:
+ query.IsFolder = false;
+ break;
+ case ItemFilter.IsPlayed:
+ query.IsPlayed = true;
+ break;
+ case ItemFilter.IsResumable:
+ query.IsResumable = true;
+ break;
+ case ItemFilter.IsUnplayed:
+ query.IsPlayed = false;
+ break;
+ case ItemFilter.Likes:
+ query.IsLiked = true;
+ break;
+ }
+ }
+
+ var result = _libraryManager.GetArtists(query);
+
+ var dtos = result.Items.Select(i =>
+ {
+ var (baseItem, itemCounts) = i;
+ var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
+
+ if (includeItemTypes.Length != 0)
+ {
+ dto.ChildCount = itemCounts.ItemCount;
+ dto.ProgramCount = itemCounts.ProgramCount;
+ dto.SeriesCount = itemCounts.SeriesCount;
+ dto.EpisodeCount = itemCounts.EpisodeCount;
+ dto.MovieCount = itemCounts.MovieCount;
+ dto.TrailerCount = itemCounts.TrailerCount;
+ dto.AlbumCount = itemCounts.AlbumCount;
+ dto.SongCount = itemCounts.SongCount;
+ dto.ArtistCount = itemCounts.ArtistCount;
+ }
+
+ return dto;
+ });
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = dtos.ToArray(),
+ TotalRecordCount = result.TotalRecordCount
+ };
+ }
+
+ /// <summary>
+ /// Gets all album artists from a given item, folder, or the entire library.
+ /// </summary>
+ /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">Optional. Search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
+ /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
+ /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
+ /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
+ /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
+ /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person ids.</param>
+ /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
+ /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="enableTotalRecordCount">Total record count.</param>
+ /// <response code="200">Album artists returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the album artists.</returns>
+ [HttpGet("AlbumArtists")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetAlbumArtists(
+ [FromQuery] double? minCommunityRating,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? person,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ User? user = null;
+ BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ user = _userManager.GetUserById(userId.Value);
+ }
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ MediaTypes = mediaTypes,
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ Tags = tags,
+ OfficialRatings = officialRatings,
+ Genres = genres,
+ GenreIds = genreIds,
+ StudioIds = studioIds,
+ Person = person,
+ PersonIds = personIds,
+ PersonTypes = personTypes,
+ Years = years,
+ MinCommunityRating = minCommunityRating,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
+ };
+
+ if (parentId.HasValue)
+ {
+ if (parentItem is Folder)
+ {
+ query.AncestorIds = new[] { parentId.Value };
+ }
+ else
+ {
+ query.ItemIds = new[] { parentId.Value };
+ }
+ }
+
+ // Studios
+ if (studios.Length != 0)
+ {
+ query.StudioIds = studios.Select(i =>
+ {
+ try
+ {
+ return _libraryManager.GetStudio(i);
+ }
+ catch
+ {
+ return null;
+ }
+ }).Where(i => i != null).Select(i => i!.Id).ToArray();
+ }
+
+ foreach (var filter in filters)
+ {
+ switch (filter)
+ {
+ case ItemFilter.Dislikes:
+ query.IsLiked = false;
+ break;
+ case ItemFilter.IsFavorite:
+ query.IsFavorite = true;
+ break;
+ case ItemFilter.IsFavoriteOrLikes:
+ query.IsFavoriteOrLiked = true;
+ break;
+ case ItemFilter.IsFolder:
+ query.IsFolder = true;
+ break;
+ case ItemFilter.IsNotFolder:
+ query.IsFolder = false;
+ break;
+ case ItemFilter.IsPlayed:
+ query.IsPlayed = true;
+ break;
+ case ItemFilter.IsResumable:
+ query.IsResumable = true;
+ break;
+ case ItemFilter.IsUnplayed:
+ query.IsPlayed = false;
+ break;
+ case ItemFilter.Likes:
+ query.IsLiked = true;
+ break;
+ }
+ }
+
+ var result = _libraryManager.GetAlbumArtists(query);
+
+ var dtos = result.Items.Select(i =>
+ {
+ var (baseItem, itemCounts) = i;
+ var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
+
+ if (includeItemTypes.Length != 0)
+ {
+ dto.ChildCount = itemCounts.ItemCount;
+ dto.ProgramCount = itemCounts.ProgramCount;
+ dto.SeriesCount = itemCounts.SeriesCount;
+ dto.EpisodeCount = itemCounts.EpisodeCount;
+ dto.MovieCount = itemCounts.MovieCount;
+ dto.TrailerCount = itemCounts.TrailerCount;
+ dto.AlbumCount = itemCounts.AlbumCount;
+ dto.SongCount = itemCounts.SongCount;
+ dto.ArtistCount = itemCounts.ArtistCount;
+ }
+
+ return dto;
+ });
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = dtos.ToArray(),
+ TotalRecordCount = result.TotalRecordCount
+ };
+ }
+
+ /// <summary>
+ /// Gets an artist by name.
+ /// </summary>
+ /// <param name="name">Studio name.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Artist returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the artist.</returns>
+ [HttpGet("{name}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BaseItemDto> GetArtistByName([FromRoute, Required] string name, [FromQuery] Guid? userId)
+ {
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ var item = _libraryManager.GetArtist(name, dtoOptions);
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs
new file mode 100644
index 000000000..54ac06276
--- /dev/null
+++ b/Jellyfin.Api/Controllers/AudioController.cs
@@ -0,0 +1,364 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Dlna;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The audio controller.
+ /// </summary>
+ // TODO: In order to authenticate this in the future, Dlna playback will require updating
+ public class AudioController : BaseJellyfinApiController
+ {
+ private readonly AudioHelper _audioHelper;
+
+ private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Progressive;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioController"/> class.
+ /// </summary>
+ /// <param name="audioHelper">Instance of <see cref="AudioHelper"/>.</param>
+ public AudioController(AudioHelper audioHelper)
+ {
+ _audioHelper = audioHelper;
+ }
+
+ /// <summary>
+ /// Gets an audio stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">The audio container.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Audio stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("{itemId}/stream", Name = "GetAudioStream")]
+ [HttpHead("{itemId}/stream", Name = "HeadAudioStream")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesAudioFile]
+ public async Task<ActionResult> GetAudioStream(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string>? streamOptions)
+ {
+ StreamingRequestDto streamingRequest = new StreamingRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Static,
+ StreamOptions = streamOptions
+ };
+
+ return await _audioHelper.GetAudioStream(_transcodingJobType, streamingRequest).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets an audio stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">The audio container.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment lenght.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Audio stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("{itemId}/stream.{container}", Name = "GetAudioStreamByContainer")]
+ [HttpHead("{itemId}/stream.{container}", Name = "HeadAudioStreamByContainer")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesAudioFile]
+ public async Task<ActionResult> GetAudioStreamByContainer(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string>? streamOptions)
+ {
+ StreamingRequestDto streamingRequest = new StreamingRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Static,
+ StreamOptions = streamOptions
+ };
+
+ return await _audioHelper.GetAudioStream(_transcodingJobType, streamingRequest).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/BrandingController.cs b/Jellyfin.Api/Controllers/BrandingController.cs
new file mode 100644
index 000000000..d3ea41201
--- /dev/null
+++ b/Jellyfin.Api/Controllers/BrandingController.cs
@@ -0,0 +1,57 @@
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Branding;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Branding controller.
+ /// </summary>
+ public class BrandingController : BaseJellyfinApiController
+ {
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BrandingController"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public BrandingController(IServerConfigurationManager serverConfigurationManager)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <summary>
+ /// Gets branding configuration.
+ /// </summary>
+ /// <response code="200">Branding configuration returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the branding configuration.</returns>
+ [HttpGet("Configuration")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BrandingOptions> GetBrandingOptions()
+ {
+ return _serverConfigurationManager.GetConfiguration<BrandingOptions>("branding");
+ }
+
+ /// <summary>
+ /// Gets branding css.
+ /// </summary>
+ /// <response code="200">Branding css returned.</response>
+ /// <response code="204">No branding css configured.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the branding css if exist,
+ /// or a <see cref="NoContentResult"/> if the css is not configured.
+ /// </returns>
+ [HttpGet("Css")]
+ [HttpGet("Css.css", Name = "GetBrandingCss_2")]
+ [Produces("text/css")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult<string> GetBrandingCss()
+ {
+ var options = _serverConfigurationManager.GetConfiguration<BrandingOptions>("branding");
+ return options.CustomCss ?? string.Empty;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs
new file mode 100644
index 000000000..54bd80095
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ChannelsController.cs
@@ -0,0 +1,251 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Channels;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Channels;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Channels Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ChannelsController : BaseJellyfinApiController
+ {
+ private readonly IChannelManager _channelManager;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelsController"/> class.
+ /// </summary>
+ /// <param name="channelManager">Instance of the <see cref="IChannelManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ public ChannelsController(IChannelManager channelManager, IUserManager userManager)
+ {
+ _channelManager = channelManager;
+ _userManager = userManager;
+ }
+
+ /// <summary>
+ /// Gets available channels.
+ /// </summary>
+ /// <param name="userId">User Id to filter by. Use <see cref="Guid.Empty"/> to not filter by user.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="supportsLatestItems">Optional. Filter by channels that support getting latest items.</param>
+ /// <param name="supportsMediaDeletion">Optional. Filter by channels that support media deletion.</param>
+ /// <param name="isFavorite">Optional. Filter by channels that are favorite.</param>
+ /// <response code="200">Channels returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the channels.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetChannels(
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool? supportsLatestItems,
+ [FromQuery] bool? supportsMediaDeletion,
+ [FromQuery] bool? isFavorite)
+ {
+ return _channelManager.GetChannels(new ChannelQuery
+ {
+ Limit = limit,
+ StartIndex = startIndex,
+ UserId = userId ?? Guid.Empty,
+ SupportsLatestItems = supportsLatestItems,
+ SupportsMediaDeletion = supportsMediaDeletion,
+ IsFavorite = isFavorite
+ });
+ }
+
+ /// <summary>
+ /// Get all channel features.
+ /// </summary>
+ /// <response code="200">All channel features returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the channel features.</returns>
+ [HttpGet("Features")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<ChannelFeatures>> GetAllChannelFeatures()
+ {
+ return _channelManager.GetAllChannelFeatures();
+ }
+
+ /// <summary>
+ /// Get channel features.
+ /// </summary>
+ /// <param name="channelId">Channel id.</param>
+ /// <response code="200">Channel features returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the channel features.</returns>
+ [HttpGet("{channelId}/Features")]
+ public ActionResult<ChannelFeatures> GetChannelFeatures([FromRoute, Required] Guid channelId)
+ {
+ return _channelManager.GetChannelFeatures(channelId);
+ }
+
+ /// <summary>
+ /// Get channel items.
+ /// </summary>
+ /// <param name="channelId">Channel Id.</param>
+ /// <param name="folderId">Optional. Folder Id.</param>
+ /// <param name="userId">Optional. User Id.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="sortOrder">Optional. Sort Order - Ascending,Descending.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <response code="200">Channel items returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> representing the request to get the channel items.
+ /// The task result contains an <see cref="OkResult"/> containing the channel items.
+ /// </returns>
+ [HttpGet("{channelId}/Items")]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetChannelItems(
+ [FromRoute, Required] Guid channelId,
+ [FromQuery] Guid? folderId,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var query = new InternalItemsQuery(user)
+ {
+ Limit = limit,
+ StartIndex = startIndex,
+ ChannelIds = new[] { channelId },
+ ParentId = folderId ?? Guid.Empty,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
+ DtoOptions = new DtoOptions { Fields = fields }
+ };
+
+ foreach (var filter in filters)
+ {
+ switch (filter)
+ {
+ case ItemFilter.IsFolder:
+ query.IsFolder = true;
+ break;
+ case ItemFilter.IsNotFolder:
+ query.IsFolder = false;
+ break;
+ case ItemFilter.IsUnplayed:
+ query.IsPlayed = false;
+ break;
+ case ItemFilter.IsPlayed:
+ query.IsPlayed = true;
+ break;
+ case ItemFilter.IsFavorite:
+ query.IsFavorite = true;
+ break;
+ case ItemFilter.IsResumable:
+ query.IsResumable = true;
+ break;
+ case ItemFilter.Likes:
+ query.IsLiked = true;
+ break;
+ case ItemFilter.Dislikes:
+ query.IsLiked = false;
+ break;
+ case ItemFilter.IsFavoriteOrLikes:
+ query.IsFavoriteOrLiked = true;
+ break;
+ }
+ }
+
+ return await _channelManager.GetChannelItems(query, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets latest channel items.
+ /// </summary>
+ /// <param name="userId">Optional. User Id.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="channelIds">Optional. Specify one or more channel id's, comma delimited.</param>
+ /// <response code="200">Latest channel items returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> representing the request to get the latest channel items.
+ /// The task result contains an <see cref="OkResult"/> containing the latest channel items.
+ /// </returns>
+ [HttpGet("Items/Latest")]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetLatestChannelItems(
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] channelIds)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var query = new InternalItemsQuery(user)
+ {
+ Limit = limit,
+ StartIndex = startIndex,
+ ChannelIds = channelIds,
+ DtoOptions = new DtoOptions { Fields = fields }
+ };
+
+ foreach (var filter in filters)
+ {
+ switch (filter)
+ {
+ case ItemFilter.IsFolder:
+ query.IsFolder = true;
+ break;
+ case ItemFilter.IsNotFolder:
+ query.IsFolder = false;
+ break;
+ case ItemFilter.IsUnplayed:
+ query.IsPlayed = false;
+ break;
+ case ItemFilter.IsPlayed:
+ query.IsPlayed = true;
+ break;
+ case ItemFilter.IsFavorite:
+ query.IsFavorite = true;
+ break;
+ case ItemFilter.IsResumable:
+ query.IsResumable = true;
+ break;
+ case ItemFilter.Likes:
+ query.IsLiked = true;
+ break;
+ case ItemFilter.Dislikes:
+ query.IsLiked = false;
+ break;
+ case ItemFilter.IsFavoriteOrLikes:
+ query.IsFavoriteOrLiked = true;
+ break;
+ }
+ }
+
+ return await _channelManager.GetLatestChannelItems(query, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/CollectionController.cs b/Jellyfin.Api/Controllers/CollectionController.cs
new file mode 100644
index 000000000..8a98d856c
--- /dev/null
+++ b/Jellyfin.Api/Controllers/CollectionController.cs
@@ -0,0 +1,116 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using MediaBrowser.Controller.Collections;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Collections;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The collection controller.
+ /// </summary>
+ [Route("Collections")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class CollectionController : BaseJellyfinApiController
+ {
+ private readonly ICollectionManager _collectionManager;
+ private readonly IDtoService _dtoService;
+ private readonly IAuthorizationContext _authContext;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionController"/> class.
+ /// </summary>
+ /// <param name="collectionManager">Instance of <see cref="ICollectionManager"/> interface.</param>
+ /// <param name="dtoService">Instance of <see cref="IDtoService"/> interface.</param>
+ /// <param name="authContext">Instance of <see cref="IAuthorizationContext"/> interface.</param>
+ public CollectionController(
+ ICollectionManager collectionManager,
+ IDtoService dtoService,
+ IAuthorizationContext authContext)
+ {
+ _collectionManager = collectionManager;
+ _dtoService = dtoService;
+ _authContext = authContext;
+ }
+
+ /// <summary>
+ /// Creates a new collection.
+ /// </summary>
+ /// <param name="name">The name of the collection.</param>
+ /// <param name="ids">Item Ids to add to the collection.</param>
+ /// <param name="parentId">Optional. Create the collection within a specific folder.</param>
+ /// <param name="isLocked">Whether or not to lock the new collection.</param>
+ /// <response code="200">Collection created.</response>
+ /// <returns>A <see cref="CollectionCreationOptions"/> with information about the new collection.</returns>
+ [HttpPost]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<CollectionCreationResult>> CreateCollection(
+ [FromQuery] string? name,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] ids,
+ [FromQuery] Guid? parentId,
+ [FromQuery] bool isLocked = false)
+ {
+ var userId = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).UserId;
+
+ var item = await _collectionManager.CreateCollectionAsync(new CollectionCreationOptions
+ {
+ IsLocked = isLocked,
+ Name = name,
+ ParentId = parentId,
+ ItemIdList = ids,
+ UserIds = new[] { userId }
+ }).ConfigureAwait(false);
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ var dto = _dtoService.GetBaseItemDto(item, dtoOptions);
+
+ return new CollectionCreationResult
+ {
+ Id = dto.Id
+ };
+ }
+
+ /// <summary>
+ /// Adds items to a collection.
+ /// </summary>
+ /// <param name="collectionId">The collection id.</param>
+ /// <param name="ids">Item ids, comma delimited.</param>
+ /// <response code="204">Items added to collection.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("{collectionId}/Items")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> AddToCollection(
+ [FromRoute, Required] Guid collectionId,
+ [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
+ {
+ await _collectionManager.AddToCollectionAsync(collectionId, ids).ConfigureAwait(true);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Removes items from a collection.
+ /// </summary>
+ /// <param name="collectionId">The collection id.</param>
+ /// <param name="ids">Item ids, comma delimited.</param>
+ /// <response code="204">Items removed from collection.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpDelete("{collectionId}/Items")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> RemoveFromCollection(
+ [FromRoute, Required] Guid collectionId,
+ [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
+ {
+ await _collectionManager.RemoveFromCollectionAsync(collectionId, ids).ConfigureAwait(false);
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs
new file mode 100644
index 000000000..60529e990
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ConfigurationController.cs
@@ -0,0 +1,135 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Net.Mime;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.ConfigurationDtos;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Configuration;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Configuration Controller.
+ /// </summary>
+ [Route("System")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ConfigurationController : BaseJellyfinApiController
+ {
+ private readonly IServerConfigurationManager _configurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+
+ private readonly JsonSerializerOptions _serializerOptions = JsonDefaults.Options;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConfigurationController"/> class.
+ /// </summary>
+ /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ public ConfigurationController(
+ IServerConfigurationManager configurationManager,
+ IMediaEncoder mediaEncoder)
+ {
+ _configurationManager = configurationManager;
+ _mediaEncoder = mediaEncoder;
+ }
+
+ /// <summary>
+ /// Gets application configuration.
+ /// </summary>
+ /// <response code="200">Application configuration returned.</response>
+ /// <returns>Application configuration.</returns>
+ [HttpGet("Configuration")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<ServerConfiguration> GetConfiguration()
+ {
+ return _configurationManager.Configuration;
+ }
+
+ /// <summary>
+ /// Updates application configuration.
+ /// </summary>
+ /// <param name="configuration">Configuration.</param>
+ /// <response code="204">Configuration updated.</response>
+ /// <returns>Update status.</returns>
+ [HttpPost("Configuration")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateConfiguration([FromBody, Required] ServerConfiguration configuration)
+ {
+ _configurationManager.ReplaceConfiguration(configuration);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a named configuration.
+ /// </summary>
+ /// <param name="key">Configuration key.</param>
+ /// <response code="200">Configuration returned.</response>
+ /// <returns>Configuration.</returns>
+ [HttpGet("Configuration/{key}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile(MediaTypeNames.Application.Json)]
+ public ActionResult<object> GetNamedConfiguration([FromRoute, Required] string key)
+ {
+ return _configurationManager.GetConfiguration(key);
+ }
+
+ /// <summary>
+ /// Updates named configuration.
+ /// </summary>
+ /// <param name="key">Configuration key.</param>
+ /// <response code="204">Named configuration updated.</response>
+ /// <returns>Update status.</returns>
+ [HttpPost("Configuration/{key}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> UpdateNamedConfiguration([FromRoute, Required] string key)
+ {
+ var configurationType = _configurationManager.GetConfigurationType(key);
+ var configuration = await JsonSerializer.DeserializeAsync(Request.Body, configurationType, _serializerOptions).ConfigureAwait(false);
+ if (configuration == null)
+ {
+ throw new ArgumentException("Body doesn't contain a valid configuration");
+ }
+
+ _configurationManager.SaveConfiguration(key, configuration);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a default MetadataOptions object.
+ /// </summary>
+ /// <response code="200">Metadata options returned.</response>
+ /// <returns>Default MetadataOptions.</returns>
+ [HttpGet("Configuration/MetadataOptions/Default")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<MetadataOptions> GetDefaultMetadataOptions()
+ {
+ return new MetadataOptions();
+ }
+
+ /// <summary>
+ /// Updates the path to the media encoder.
+ /// </summary>
+ /// <param name="mediaEncoderPath">Media encoder path form body.</param>
+ /// <response code="204">Media encoder path updated.</response>
+ /// <returns>Status.</returns>
+ [HttpPost("MediaEncoder/Path")]
+ [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateMediaEncoderPath([FromBody, Required] MediaEncoderPathDto mediaEncoderPath)
+ {
+ _mediaEncoder.UpdateEncoderPath(mediaEncoderPath.Path, mediaEncoderPath.PathType);
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs
new file mode 100644
index 000000000..87cb418d9
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DashboardController.cs
@@ -0,0 +1,113 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Mime;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Models;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Plugins;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The dashboard controller.
+ /// </summary>
+ [Route("")]
+ public class DashboardController : BaseJellyfinApiController
+ {
+ private readonly ILogger<DashboardController> _logger;
+ private readonly IPluginManager _pluginManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DashboardController"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of <see cref="ILogger{DashboardController}"/> interface.</param>
+ /// <param name="pluginManager">Instance of <see cref="IPluginManager"/> interface.</param>
+ public DashboardController(
+ ILogger<DashboardController> logger,
+ IPluginManager pluginManager)
+ {
+ _logger = logger;
+ _pluginManager = pluginManager;
+ }
+
+ /// <summary>
+ /// Gets the configuration pages.
+ /// </summary>
+ /// <param name="enableInMainMenu">Whether to enable in the main menu.</param>
+ /// <response code="200">ConfigurationPages returned.</response>
+ /// <response code="404">Server still loading.</response>
+ /// <returns>An <see cref="IEnumerable{ConfigurationPageInfo}"/> with infos about the plugins.</returns>
+ [HttpGet("web/ConfigurationPages")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<IEnumerable<ConfigurationPageInfo>> GetConfigurationPages(
+ [FromQuery] bool? enableInMainMenu)
+ {
+ var configPages = _pluginManager.Plugins.SelectMany(GetConfigPages).ToList();
+
+ if (enableInMainMenu.HasValue)
+ {
+ configPages = configPages.Where(p => p.EnableInMainMenu == enableInMainMenu.Value).ToList();
+ }
+
+ return configPages;
+ }
+
+ /// <summary>
+ /// Gets a dashboard configuration page.
+ /// </summary>
+ /// <param name="name">The name of the page.</param>
+ /// <response code="200">ConfigurationPage returned.</response>
+ /// <response code="404">Plugin configuration page not found.</response>
+ /// <returns>The configuration page.</returns>
+ [HttpGet("web/ConfigurationPage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesFile(MediaTypeNames.Text.Html, "application/x-javascript")]
+ public ActionResult GetDashboardConfigurationPage([FromQuery] string? name)
+ {
+ var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, name, StringComparison.OrdinalIgnoreCase));
+ if (altPage == null)
+ {
+ return NotFound();
+ }
+
+ IPlugin plugin = altPage.Item2;
+ string resourcePath = altPage.Item1.EmbeddedResourcePath;
+ Stream? stream = plugin.GetType().Assembly.GetManifestResourceStream(resourcePath);
+ if (stream == null)
+ {
+ _logger.LogError("Failed to get resource {Resource} from plugin {Plugin}", resourcePath, plugin.Name);
+ return NotFound();
+ }
+
+ return File(stream, MimeTypes.GetMimeType(resourcePath));
+ }
+
+ private IEnumerable<ConfigurationPageInfo> GetConfigPages(LocalPlugin plugin)
+ {
+ return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin.Instance, i.Item1));
+ }
+
+ private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(LocalPlugin plugin)
+ {
+ if (plugin.Instance is not IHasWebPages hasWebPages)
+ {
+ return Enumerable.Empty<Tuple<PluginPageInfo, IPlugin>>();
+ }
+
+ return hasWebPages.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin.Instance));
+ }
+
+ private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
+ {
+ return _pluginManager.Plugins.SelectMany(GetPluginPages);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DevicesController.cs b/Jellyfin.Api/Controllers/DevicesController.cs
new file mode 100644
index 000000000..8292cf83b
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DevicesController.cs
@@ -0,0 +1,141 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Dtos;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Devices;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Devices Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public class DevicesController : BaseJellyfinApiController
+ {
+ private readonly IDeviceManager _deviceManager;
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DevicesController"/> class.
+ /// </summary>
+ /// <param name="deviceManager">Instance of <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="sessionManager">Instance of <see cref="ISessionManager"/> interface.</param>
+ public DevicesController(
+ IDeviceManager deviceManager,
+ ISessionManager sessionManager)
+ {
+ _deviceManager = deviceManager;
+ _sessionManager = sessionManager;
+ }
+
+ /// <summary>
+ /// Get Devices.
+ /// </summary>
+ /// <param name="supportsSync">Gets or sets a value indicating whether [supports synchronize].</param>
+ /// <param name="userId">Gets or sets the user identifier.</param>
+ /// <response code="200">Devices retrieved.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of devices.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<DeviceInfo>>> GetDevices([FromQuery] bool? supportsSync, [FromQuery] Guid? userId)
+ {
+ return await _deviceManager.GetDevicesForUser(userId, supportsSync).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get info for a device.
+ /// </summary>
+ /// <param name="id">Device Id.</param>
+ /// <response code="200">Device info retrieved.</response>
+ /// <response code="404">Device not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the device info on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
+ [HttpGet("Info")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<DeviceInfo>> GetDeviceInfo([FromQuery, Required] string id)
+ {
+ var deviceInfo = await _deviceManager.GetDevice(id).ConfigureAwait(false);
+ if (deviceInfo == null)
+ {
+ return NotFound();
+ }
+
+ return deviceInfo;
+ }
+
+ /// <summary>
+ /// Get options for a device.
+ /// </summary>
+ /// <param name="id">Device Id.</param>
+ /// <response code="200">Device options retrieved.</response>
+ /// <response code="404">Device not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the device info on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
+ [HttpGet("Options")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<DeviceOptions>> GetDeviceOptions([FromQuery, Required] string id)
+ {
+ var deviceInfo = await _deviceManager.GetDeviceOptions(id).ConfigureAwait(false);
+ if (deviceInfo == null)
+ {
+ return NotFound();
+ }
+
+ return deviceInfo;
+ }
+
+ /// <summary>
+ /// Update device options.
+ /// </summary>
+ /// <param name="id">Device Id.</param>
+ /// <param name="deviceOptions">Device Options.</param>
+ /// <response code="204">Device options updated.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Options")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> UpdateDeviceOptions(
+ [FromQuery, Required] string id,
+ [FromBody, Required] DeviceOptionsDto deviceOptions)
+ {
+ await _deviceManager.UpdateDeviceOptions(id, deviceOptions.CustomName).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Deletes a device.
+ /// </summary>
+ /// <param name="id">Device Id.</param>
+ /// <response code="204">Device deleted.</response>
+ /// <response code="404">Device not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
+ [HttpDelete]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteDevice([FromQuery, Required] string id)
+ {
+ var existingDevice = await _deviceManager.GetDevice(id).ConfigureAwait(false);
+ if (existingDevice == null)
+ {
+ return NotFound();
+ }
+
+ var sessions = await _deviceManager.GetDevices(new DeviceQuery { DeviceId = id }).ConfigureAwait(false);
+
+ foreach (var session in sessions.Items)
+ {
+ await _sessionManager.Logout(session).ConfigureAwait(false);
+ }
+
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
new file mode 100644
index 000000000..2079476d0
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
@@ -0,0 +1,212 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller;
+using MediaBrowser.Model.Entities;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Display Preferences Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class DisplayPreferencesController : BaseJellyfinApiController
+ {
+ private readonly IDisplayPreferencesManager _displayPreferencesManager;
+ private readonly ILogger<DisplayPreferencesController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DisplayPreferencesController"/> class.
+ /// </summary>
+ /// <param name="displayPreferencesManager">Instance of <see cref="IDisplayPreferencesManager"/> interface.</param>
+ /// <param name="logger">Instance of <see cref="ILogger{DisplayPreferencesController}"/> interface.</param>
+ public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager, ILogger<DisplayPreferencesController> logger)
+ {
+ _displayPreferencesManager = displayPreferencesManager;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Get Display Preferences.
+ /// </summary>
+ /// <param name="displayPreferencesId">Display preferences id.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="client">Client.</param>
+ /// <response code="200">Display preferences retrieved.</response>
+ /// <returns>An <see cref="OkResult"/> containing the display preferences on success, or a <see cref="NotFoundResult"/> if the display preferences could not be found.</returns>
+ [HttpGet("{displayPreferencesId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
+ public ActionResult<DisplayPreferencesDto> GetDisplayPreferences(
+ [FromRoute, Required] string displayPreferencesId,
+ [FromQuery, Required] Guid userId,
+ [FromQuery, Required] string client)
+ {
+ if (!Guid.TryParse(displayPreferencesId, out var itemId))
+ {
+ itemId = displayPreferencesId.GetMD5();
+ }
+
+ var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client);
+ var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
+ itemPreferences.ItemId = itemId;
+
+ var dto = new DisplayPreferencesDto
+ {
+ Client = displayPreferences.Client,
+ Id = displayPreferences.ItemId.ToString(),
+ SortBy = itemPreferences.SortBy,
+ SortOrder = itemPreferences.SortOrder,
+ IndexBy = displayPreferences.IndexBy?.ToString(),
+ RememberIndexing = itemPreferences.RememberIndexing,
+ RememberSorting = itemPreferences.RememberSorting,
+ ScrollDirection = displayPreferences.ScrollDirection,
+ ShowBackdrop = displayPreferences.ShowBackdrop,
+ ShowSidebar = displayPreferences.ShowSidebar
+ };
+
+ foreach (var homeSection in displayPreferences.HomeSections)
+ {
+ dto.CustomPrefs["homesection" + homeSection.Order] = homeSection.Type.ToString().ToLowerInvariant();
+ }
+
+ dto.CustomPrefs["chromecastVersion"] = displayPreferences.ChromecastVersion.ToString().ToLowerInvariant();
+ dto.CustomPrefs["skipForwardLength"] = displayPreferences.SkipForwardLength.ToString(CultureInfo.InvariantCulture);
+ dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture);
+ dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture);
+ dto.CustomPrefs["tvhome"] = displayPreferences.TvHome;
+ dto.CustomPrefs["dashboardTheme"] = displayPreferences.DashboardTheme;
+
+ // Load all custom display preferences
+ var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
+ if (customDisplayPreferences != null)
+ {
+ foreach (var (key, value) in customDisplayPreferences)
+ {
+ dto.CustomPrefs.TryAdd(key, value);
+ }
+ }
+
+ // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
+ _displayPreferencesManager.SaveChanges();
+
+ return dto;
+ }
+
+ /// <summary>
+ /// Update Display Preferences.
+ /// </summary>
+ /// <param name="displayPreferencesId">Display preferences id.</param>
+ /// <param name="userId">User Id.</param>
+ /// <param name="client">Client.</param>
+ /// <param name="displayPreferences">New Display Preferences object.</param>
+ /// <response code="204">Display preferences updated.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success.</returns>
+ [HttpPost("{displayPreferencesId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
+ public ActionResult UpdateDisplayPreferences(
+ [FromRoute, Required] string displayPreferencesId,
+ [FromQuery, Required] Guid userId,
+ [FromQuery, Required] string client,
+ [FromBody, Required] DisplayPreferencesDto displayPreferences)
+ {
+ HomeSectionType[] defaults =
+ {
+ HomeSectionType.SmallLibraryTiles,
+ HomeSectionType.Resume,
+ HomeSectionType.ResumeAudio,
+ HomeSectionType.LiveTv,
+ HomeSectionType.NextUp,
+ HomeSectionType.LatestMedia, HomeSectionType.None,
+ };
+
+ if (!Guid.TryParse(displayPreferencesId, out var itemId))
+ {
+ itemId = displayPreferencesId.GetMD5();
+ }
+
+ var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client);
+ existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : null;
+ existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
+ existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
+
+ existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
+ existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion)
+ ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
+ : ChromecastVersion.Stable;
+ displayPreferences.CustomPrefs.Remove("chromecastVersion");
+
+ existingDisplayPreferences.EnableNextVideoInfoOverlay = displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay)
+ ? bool.Parse(enableNextVideoInfoOverlay)
+ : true;
+ displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
+
+ existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength)
+ ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
+ : 10000;
+ displayPreferences.CustomPrefs.Remove("skipBackLength");
+
+ existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength)
+ ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
+ : 30000;
+ displayPreferences.CustomPrefs.Remove("skipForwardLength");
+
+ existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var theme)
+ ? theme
+ : string.Empty;
+ displayPreferences.CustomPrefs.Remove("dashboardTheme");
+
+ existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
+ ? home
+ : string.Empty;
+ displayPreferences.CustomPrefs.Remove("tvhome");
+
+ existingDisplayPreferences.HomeSections.Clear();
+
+ foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringComparison.OrdinalIgnoreCase)))
+ {
+ var order = int.Parse(key.AsSpan().Slice("homesection".Length));
+ if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
+ {
+ type = order < 7 ? defaults[order] : HomeSectionType.None;
+ }
+
+ displayPreferences.CustomPrefs.Remove(key);
+ existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
+ }
+
+ foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase)))
+ {
+ if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out var type))
+ {
+ _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
+ displayPreferences.CustomPrefs.Remove(key);
+ }
+ }
+
+ var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client);
+ itemPrefs.SortBy = displayPreferences.SortBy;
+ itemPrefs.SortOrder = displayPreferences.SortOrder;
+ itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
+ itemPrefs.RememberSorting = displayPreferences.RememberSorting;
+ itemPrefs.ItemId = itemId;
+
+ // Set all remaining custom preferences.
+ _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs);
+ _displayPreferencesManager.SaveChanges();
+
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DlnaController.cs b/Jellyfin.Api/Controllers/DlnaController.cs
new file mode 100644
index 000000000..35c3a3d92
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DlnaController.cs
@@ -0,0 +1,133 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Model.Dlna;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Dlna Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public class DlnaController : BaseJellyfinApiController
+ {
+ private readonly IDlnaManager _dlnaManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DlnaController"/> class.
+ /// </summary>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ public DlnaController(IDlnaManager dlnaManager)
+ {
+ _dlnaManager = dlnaManager;
+ }
+
+ /// <summary>
+ /// Get profile infos.
+ /// </summary>
+ /// <response code="200">Device profile infos returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the device profile infos.</returns>
+ [HttpGet("ProfileInfos")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<DeviceProfileInfo>> GetProfileInfos()
+ {
+ return Ok(_dlnaManager.GetProfileInfos());
+ }
+
+ /// <summary>
+ /// Gets the default profile.
+ /// </summary>
+ /// <response code="200">Default device profile returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the default profile.</returns>
+ [HttpGet("Profiles/Default")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<DeviceProfile> GetDefaultProfile()
+ {
+ return _dlnaManager.GetDefaultProfile();
+ }
+
+ /// <summary>
+ /// Gets a single profile.
+ /// </summary>
+ /// <param name="profileId">Profile Id.</param>
+ /// <response code="200">Device profile returned.</response>
+ /// <response code="404">Device profile not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the profile on success, or a <see cref="NotFoundResult"/> if device profile not found.</returns>
+ [HttpGet("Profiles/{profileId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<DeviceProfile> GetProfile([FromRoute, Required] string profileId)
+ {
+ var profile = _dlnaManager.GetProfile(profileId);
+ if (profile == null)
+ {
+ return NotFound();
+ }
+
+ return profile;
+ }
+
+ /// <summary>
+ /// Deletes a profile.
+ /// </summary>
+ /// <param name="profileId">Profile id.</param>
+ /// <response code="204">Device profile deleted.</response>
+ /// <response code="404">Device profile not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if profile not found.</returns>
+ [HttpDelete("Profiles/{profileId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult DeleteProfile([FromRoute, Required] string profileId)
+ {
+ var existingDeviceProfile = _dlnaManager.GetProfile(profileId);
+ if (existingDeviceProfile == null)
+ {
+ return NotFound();
+ }
+
+ _dlnaManager.DeleteProfile(profileId);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Creates a profile.
+ /// </summary>
+ /// <param name="deviceProfile">Device profile.</param>
+ /// <response code="204">Device profile created.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Profiles")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult CreateProfile([FromBody] DeviceProfile deviceProfile)
+ {
+ _dlnaManager.CreateProfile(deviceProfile);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a profile.
+ /// </summary>
+ /// <param name="profileId">Profile id.</param>
+ /// <param name="deviceProfile">Device profile.</param>
+ /// <response code="204">Device profile updated.</response>
+ /// <response code="404">Device profile not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if profile not found.</returns>
+ [HttpPost("Profiles/{profileId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult UpdateProfile([FromRoute, Required] string profileId, [FromBody] DeviceProfile deviceProfile)
+ {
+ var existingDeviceProfile = _dlnaManager.GetProfile(profileId);
+ if (existingDeviceProfile == null)
+ {
+ return NotFound();
+ }
+
+ _dlnaManager.UpdateProfile(profileId, deviceProfile);
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs
new file mode 100644
index 000000000..4e8c01577
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DlnaServerController.cs
@@ -0,0 +1,386 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using Emby.Dlna;
+using Emby.Dlna.Main;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller.Dlna;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Dlna Server Controller.
+ /// </summary>
+ [Route("Dlna")]
+ [Authorize(Policy = Policies.AnonymousLanAccessPolicy)]
+ public class DlnaServerController : BaseJellyfinApiController
+ {
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IContentDirectory _contentDirectory;
+ private readonly IConnectionManager _connectionManager;
+ private readonly IMediaReceiverRegistrar _mediaReceiverRegistrar;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DlnaServerController"/> class.
+ /// </summary>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ public DlnaServerController(IDlnaManager dlnaManager)
+ {
+ _dlnaManager = dlnaManager;
+ _contentDirectory = DlnaEntryPoint.Current.ContentDirectory;
+ _connectionManager = DlnaEntryPoint.Current.ConnectionManager;
+ _mediaReceiverRegistrar = DlnaEntryPoint.Current.MediaReceiverRegistrar;
+ }
+
+ /// <summary>
+ /// Get Description Xml.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Description xml returned.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>An <see cref="OkResult"/> containing the description xml.</returns>
+ [HttpGet("{serverId}/description")]
+ [HttpGet("{serverId}/description.xml", Name = "GetDescriptionXml_2")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public ActionResult GetDescriptionXml([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ var url = GetAbsoluteUri();
+ var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase));
+ var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers, serverId, serverAddress);
+ return Ok(xml);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Gets Dlna content directory xml.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Dlna content directory returned.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>An <see cref="OkResult"/> containing the dlna content directory xml.</returns>
+ [HttpGet("{serverId}/ContentDirectory")]
+ [HttpGet("{serverId}/ContentDirectory/ContentDirectory", Name = "GetContentDirectory_2")]
+ [HttpGet("{serverId}/ContentDirectory/ContentDirectory.xml", Name = "GetContentDirectory_3")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ public ActionResult GetContentDirectory([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return Ok(_contentDirectory.GetServiceXml());
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Gets Dlna media receiver registrar xml.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Dlna media receiver registrar xml returned.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Dlna media receiver registrar xml.</returns>
+ [HttpGet("{serverId}/MediaReceiverRegistrar")]
+ [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")]
+ [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar.xml", Name = "GetMediaReceiverRegistrar_3")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ public ActionResult GetMediaReceiverRegistrar([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return Ok(_mediaReceiverRegistrar.GetServiceXml());
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Gets Dlna media receiver registrar xml.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Dlna media receiver registrar xml returned.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Dlna media receiver registrar xml.</returns>
+ [HttpGet("{serverId}/ConnectionManager")]
+ [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")]
+ [HttpGet("{serverId}/ConnectionManager/ConnectionManager.xml", Name = "GetConnectionManager_3")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ public ActionResult GetConnectionManager([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return Ok(_connectionManager.GetServiceXml());
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Process a content directory control request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Control response.</returns>
+ [HttpPost("{serverId}/ContentDirectory/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public async Task<ActionResult<ControlResponse>> ProcessContentDirectoryControlRequest([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Process a connection manager control request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Control response.</returns>
+ [HttpPost("{serverId}/ConnectionManager/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public async Task<ActionResult<ControlResponse>> ProcessConnectionManagerControlRequest([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Process a media receiver registrar control request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Control response.</returns>
+ [HttpPost("{serverId}/MediaReceiverRegistrar/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public async Task<ActionResult<ControlResponse>> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Processes an event subscription request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Event subscription response.</returns>
+ [HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")]
+ [HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")]
+ [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public ActionResult<EventSubscriptionResponse> ProcessMediaReceiverRegistrarEventRequest(string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return ProcessEventRequest(_mediaReceiverRegistrar);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Processes an event subscription request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Event subscription response.</returns>
+ [HttpSubscribe("{serverId}/ContentDirectory/Events")]
+ [HttpUnsubscribe("{serverId}/ContentDirectory/Events")]
+ [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public ActionResult<EventSubscriptionResponse> ProcessContentDirectoryEventRequest(string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return ProcessEventRequest(_contentDirectory);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Processes an event subscription request.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Event subscription response.</returns>
+ [HttpSubscribe("{serverId}/ConnectionManager/Events")]
+ [HttpUnsubscribe("{serverId}/ConnectionManager/Events")]
+ [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
+ public ActionResult<EventSubscriptionResponse> ProcessConnectionManagerEventRequest(string serverId)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return ProcessEventRequest(_connectionManager);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Gets a server icon.
+ /// </summary>
+ /// <param name="serverId">Server UUID.</param>
+ /// <param name="fileName">The icon filename.</param>
+ /// <response code="200">Request processed.</response>
+ /// <response code="404">Not Found.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ /// <returns>Icon stream.</returns>
+ [HttpGet("{serverId}/icons/{fileName}")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [ProducesImageFile]
+ public ActionResult GetIconId([FromRoute, Required] string serverId, [FromRoute, Required] string fileName)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return GetIconInternal(fileName);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ /// <summary>
+ /// Gets a server icon.
+ /// </summary>
+ /// <param name="fileName">The icon filename.</param>
+ /// <returns>Icon stream.</returns>
+ /// <response code="200">Request processed.</response>
+ /// <response code="404">Not Found.</response>
+ /// <response code="503">DLNA is disabled.</response>
+ [HttpGet("icons/{fileName}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
+ [ProducesImageFile]
+ public ActionResult GetIcon([FromRoute, Required] string fileName)
+ {
+ if (DlnaEntryPoint.Enabled)
+ {
+ return GetIconInternal(fileName);
+ }
+
+ return StatusCode(StatusCodes.Status503ServiceUnavailable);
+ }
+
+ private ActionResult GetIconInternal(string fileName)
+ {
+ var icon = _dlnaManager.GetIcon(fileName);
+ if (icon == null)
+ {
+ return NotFound();
+ }
+
+ var contentType = "image/" + Path.GetExtension(fileName)
+ .TrimStart('.')
+ .ToLowerInvariant();
+
+ return File(icon.Stream, contentType);
+ }
+
+ private string GetAbsoluteUri()
+ {
+ return $"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}";
+ }
+
+ private Task<ControlResponse> ProcessControlRequestInternalAsync(string id, Stream requestStream, IUpnpService service)
+ {
+ return service.ProcessControlRequestAsync(new ControlRequest(Request.Headers)
+ {
+ InputXml = requestStream,
+ TargetServerUuId = id,
+ RequestedUrl = GetAbsoluteUri()
+ });
+ }
+
+ private EventSubscriptionResponse ProcessEventRequest(IDlnaEventManager dlnaEventManager)
+ {
+ var subscriptionId = Request.Headers["SID"];
+ if (string.Equals(Request.Method, "subscribe", StringComparison.OrdinalIgnoreCase))
+ {
+ var notificationType = Request.Headers["NT"];
+ var callback = Request.Headers["CALLBACK"];
+ var timeoutString = Request.Headers["TIMEOUT"];
+
+ if (string.IsNullOrEmpty(notificationType))
+ {
+ return dlnaEventManager.RenewEventSubscription(
+ subscriptionId,
+ notificationType,
+ timeoutString,
+ callback);
+ }
+
+ return dlnaEventManager.CreateEventSubscription(notificationType, timeoutString, callback);
+ }
+
+ return dlnaEventManager.CancelEventSubscription(subscriptionId);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs
new file mode 100644
index 000000000..42e82dd5b
--- /dev/null
+++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs
@@ -0,0 +1,1841 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.PlaybackDtos;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Dynamic hls controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class DynamicHlsController : BaseJellyfinApiController
+ {
+ private const string DefaultEncoderPreset = "veryfast";
+ private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
+
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IFileSystem _fileSystem;
+ private readonly IDeviceManager _deviceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly ILogger<DynamicHlsController> _logger;
+ private readonly EncodingHelper _encodingHelper;
+ private readonly DynamicHlsHelper _dynamicHlsHelper;
+ private readonly EncodingOptions _encodingOptions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DynamicHlsController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Instance of the <see cref="TranscodingJobHelper"/> class.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsController}"/> interface.</param>
+ /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ public DynamicHlsController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDlnaManager dlnaManager,
+ IAuthorizationContext authContext,
+ IMediaSourceManager mediaSourceManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IMediaEncoder mediaEncoder,
+ IFileSystem fileSystem,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ ILogger<DynamicHlsController> logger,
+ DynamicHlsHelper dynamicHlsHelper,
+ EncodingHelper encodingHelper)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dlnaManager = dlnaManager;
+ _authContext = authContext;
+ _mediaSourceManager = mediaSourceManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ _mediaEncoder = mediaEncoder;
+ _fileSystem = fileSystem;
+ _deviceManager = deviceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ _logger = logger;
+ _dynamicHlsHelper = dynamicHlsHelper;
+ _encodingHelper = encodingHelper;
+
+ _encodingOptions = serverConfigurationManager.GetEncodingOptions();
+ }
+
+ /// <summary>
+ /// Gets a video hls playlist stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
+ [HttpGet("Videos/{itemId}/master.m3u8")]
+ [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ public async Task<ActionResult> GetMasterHlsVideoPlaylist(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery, Required] string mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions,
+ [FromQuery] bool enableAdaptiveBitrateStreaming = true)
+ {
+ var streamingRequest = new HlsVideoRequestDto
+ {
+ Id = itemId,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions,
+ EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming
+ };
+
+ return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets an audio hls playlist stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
+ /// <response code="200">Audio stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
+ [HttpGet("Audio/{itemId}/master.m3u8")]
+ [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ public async Task<ActionResult> GetMasterHlsAudioPlaylist(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery, Required] string mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions,
+ [FromQuery] bool enableAdaptiveBitrateStreaming = true)
+ {
+ var streamingRequest = new HlsAudioRequestDto
+ {
+ Id = itemId,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions,
+ EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming
+ };
+
+ return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets a video stream using HTTP live streaming.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("Videos/{itemId}/main.m3u8")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ public async Task<ActionResult> GetVariantHlsVideoPlaylist(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var streamingRequest = new VideoRequestDto
+ {
+ Id = itemId,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions
+ };
+
+ return await GetVariantPlaylistInternal(streamingRequest, "main", cancellationTokenSource)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets an audio stream using HTTP live streaming.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Audio stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("Audio/{itemId}/main.m3u8")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ public async Task<ActionResult> GetVariantHlsAudioPlaylist(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var streamingRequest = new StreamingRequestDto
+ {
+ Id = itemId,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions
+ };
+
+ return await GetVariantPlaylistInternal(streamingRequest, "main", cancellationTokenSource)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets a video stream using HTTP live streaming.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="segmentId">The segment id.</param>
+ /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment lenght.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesVideoFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> GetHlsVideoSegment(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string playlistId,
+ [FromRoute, Required] int segmentId,
+ [FromRoute, Required] string container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ var streamingRequest = new VideoRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions
+ };
+
+ return await GetDynamicSegment(streamingRequest, segmentId)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets a video stream using HTTP live streaming.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="segmentId">The segment id.</param>
+ /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesAudioFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> GetHlsAudioSegment(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string playlistId,
+ [FromRoute, Required] int segmentId,
+ [FromRoute, Required] string container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ var streamingRequest = new StreamingRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions
+ };
+
+ return await GetDynamicSegment(streamingRequest, segmentId)
+ .ConfigureAwait(false);
+ }
+
+ private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, string name, CancellationTokenSource cancellationTokenSource)
+ {
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ TranscodingJobType,
+ cancellationTokenSource.Token)
+ .ConfigureAwait(false);
+
+ Response.Headers.Add(HeaderNames.Expires, "0");
+
+ var segmentLengths = GetSegmentLengths(state);
+
+ var segmentContainer = state.Request.SegmentContainer ?? "ts";
+
+ // http://ffmpeg.org/ffmpeg-all.html#toc-hls-2
+ var isHlsInFmp4 = string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase);
+ var hlsVersion = isHlsInFmp4 ? "7" : "3";
+
+ var builder = new StringBuilder(128);
+
+ builder.AppendLine("#EXTM3U")
+ .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD")
+ .Append("#EXT-X-VERSION:")
+ .Append(hlsVersion)
+ .AppendLine()
+ .Append("#EXT-X-TARGETDURATION:")
+ .Append(Math.Ceiling(segmentLengths.Length > 0 ? segmentLengths.Max() : state.SegmentLength))
+ .AppendLine()
+ .AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
+
+ var index = 0;
+ var segmentExtension = GetSegmentFileExtension(streamingRequest.SegmentContainer);
+ var queryString = Request.QueryString;
+
+ if (isHlsInFmp4)
+ {
+ builder.Append("#EXT-X-MAP:URI=\"")
+ .Append("hls1/")
+ .Append(name)
+ .Append("/-1")
+ .Append(segmentExtension)
+ .Append(queryString)
+ .Append('"')
+ .AppendLine();
+ }
+
+ foreach (var length in segmentLengths)
+ {
+ builder.Append("#EXTINF:")
+ .Append(length.ToString("0.0000", CultureInfo.InvariantCulture))
+ .AppendLine(", nodesc")
+ .Append("hls1/")
+ .Append(name)
+ .Append('/')
+ .Append(index++)
+ .Append(segmentExtension)
+ .Append(queryString)
+ .AppendLine();
+ }
+
+ builder.AppendLine("#EXT-X-ENDLIST");
+ return new FileContentResult(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
+ }
+
+ private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
+ {
+ if ((streamingRequest.StartTimeTicks ?? 0) > 0)
+ {
+ throw new ArgumentException("StartTimeTicks is not allowed.");
+ }
+
+ // CTS lifecycle is managed internally.
+ var cancellationTokenSource = new CancellationTokenSource();
+ var cancellationToken = cancellationTokenSource.Token;
+
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ TranscodingJobType,
+ cancellationToken)
+ .ConfigureAwait(false);
+
+ var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
+
+ var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
+
+ var segmentExtension = GetSegmentFileExtension(state.Request.SegmentContainer);
+
+ TranscodingJobDto? job;
+
+ if (System.IO.File.Exists(segmentPath))
+ {
+ job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath);
+ return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
+ }
+
+ var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlistPath);
+ await transcodingLock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ var released = false;
+ var startTranscoding = false;
+
+ try
+ {
+ if (System.IO.File.Exists(segmentPath))
+ {
+ job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ transcodingLock.Release();
+ released = true;
+ _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
+ return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
+ var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
+
+ if (segmentId == -1)
+ {
+ _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
+ startTranscoding = true;
+ segmentId = 0;
+ }
+ else if (currentTranscodingIndex == null)
+ {
+ _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
+ startTranscoding = true;
+ }
+ else if (segmentId < currentTranscodingIndex.Value)
+ {
+ _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
+ startTranscoding = true;
+ }
+ else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
+ {
+ _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
+ startTranscoding = true;
+ }
+
+ if (startTranscoding)
+ {
+ // If the playlist doesn't already exist, startup ffmpeg
+ try
+ {
+ await _transcodingJobHelper.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
+ .ConfigureAwait(false);
+
+ if (currentTranscodingIndex.HasValue)
+ {
+ DeleteLastFile(playlistPath, segmentExtension, 0);
+ }
+
+ streamingRequest.StartTimeTicks = GetStartPositionTicks(state, segmentId);
+
+ state.WaitForPath = segmentPath;
+ job = await _transcodingJobHelper.StartFfMpeg(
+ state,
+ playlistPath,
+ GetCommandLineArguments(playlistPath, state, true, segmentId),
+ Request,
+ TranscodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
+ }
+ catch
+ {
+ state.Dispose();
+ throw;
+ }
+
+ // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
+ }
+ else
+ {
+ job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ if (job?.TranscodingThrottler != null)
+ {
+ await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
+ }
+ }
+ }
+ }
+ finally
+ {
+ if (!released)
+ {
+ transcodingLock.Release();
+ }
+ }
+
+ _logger.LogDebug("returning {0} [general case]", segmentPath);
+ job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static double[] GetSegmentLengths(StreamState state)
+ => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
+
+ internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
+ {
+ var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
+ var wholeSegments = runtimeTicks / segmentLengthTicks;
+ var remainingTicks = runtimeTicks % segmentLengthTicks;
+
+ var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
+ var segments = new double[segmentsLen];
+ for (int i = 0; i < wholeSegments; i++)
+ {
+ segments[i] = segmentlength;
+ }
+
+ if (remainingTicks != 0)
+ {
+ segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
+ }
+
+ return segments;
+ }
+
+ private string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding, int startNumber)
+ {
+ var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
+ var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
+
+ if (state.BaseRequest.BreakOnNonKeyFrames)
+ {
+ // FIXME: this is actually a workaround, as ideally it really should be the client which decides whether non-keyframe
+ // breakpoints are supported; but current implementation always uses "ffmpeg input seeking" which is liable
+ // to produce a missing part of video stream before first keyframe is encountered, which may lead to
+ // awkward cases like a few starting HLS segments having no video whatsoever, which breaks hls.js
+ _logger.LogInformation("Current HLS implementation doesn't support non-keyframe breaks but one is requested, ignoring that request");
+ state.BaseRequest.BreakOnNonKeyFrames = false;
+ }
+
+ // If isEncoding is true we're actually starting ffmpeg
+ var startNumberParam = isEncoding ? startNumber.ToString(CultureInfo.InvariantCulture) : "0";
+ var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions);
+ var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
+
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
+ var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
+ var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer);
+ var outputTsArg = outputPrefix + "%d" + outputExtension;
+
+ var segmentFormat = outputExtension.TrimStart('.');
+ if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
+ {
+ segmentFormat = "mpegts";
+ }
+ else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase))
+ {
+ var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
+ {
+ // on Windows, the path of fmp4 header file needs to be configured
+ true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
+ // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
+ false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
+ };
+
+ segmentFormat = "fmp4" + outputFmp4HeaderArg;
+ }
+ else
+ {
+ _logger.LogError("Invalid HLS segment container: " + segmentFormat);
+ }
+
+ var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
+ ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
+ : "128";
+
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"",
+ inputModifier,
+ _encodingHelper.GetInputArgument(state, _encodingOptions),
+ threads,
+ mapArgs,
+ GetVideoArguments(state, startNumber),
+ GetAudioArguments(state),
+ maxMuxingQueueSize,
+ state.SegmentLength.ToString(CultureInfo.InvariantCulture),
+ segmentFormat,
+ startNumberParam,
+ outputTsArg,
+ outputPath).Trim();
+ }
+
+ /// <summary>
+ /// Gets the audio arguments for transcoding.
+ /// </summary>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <returns>The command line arguments for audio transcoding.</returns>
+ private string GetAudioArguments(StreamState state)
+ {
+ if (state.AudioStream == null)
+ {
+ return string.Empty;
+ }
+
+ var audioCodec = _encodingHelper.GetAudioEncoder(state);
+
+ if (!state.IsOutputVideo)
+ {
+ if (EncodingHelper.IsCopyCodec(audioCodec))
+ {
+ var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
+
+ return "-acodec copy -strict -2" + bitStreamArgs;
+ }
+
+ var audioTranscodeParams = string.Empty;
+
+ audioTranscodeParams += "-acodec " + audioCodec;
+
+ if (state.OutputAudioBitrate.HasValue)
+ {
+ audioTranscodeParams += " -ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioChannels.HasValue)
+ {
+ audioTranscodeParams += " -ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioSampleRate.HasValue)
+ {
+ audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ audioTranscodeParams += " -vn";
+ return audioTranscodeParams;
+ }
+
+ if (EncodingHelper.IsCopyCodec(audioCodec))
+ {
+ var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
+ var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
+
+ if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec))
+ {
+ return "-codec:a:0 copy -strict -2 -copypriorss:a:0 0" + bitStreamArgs;
+ }
+
+ return "-codec:a:0 copy -strict -2" + bitStreamArgs;
+ }
+
+ var args = "-codec:a:0 " + audioCodec;
+
+ var channels = state.OutputAudioChannels;
+
+ if (channels.HasValue)
+ {
+ args += " -ac " + channels.Value;
+ }
+
+ var bitrate = state.OutputAudioBitrate;
+
+ if (bitrate.HasValue)
+ {
+ args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioSampleRate.HasValue)
+ {
+ args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
+
+ return args;
+ }
+
+ /// <summary>
+ /// Gets the video arguments for transcoding.
+ /// </summary>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <param name="startNumber">The first number in the hls sequence.</param>
+ /// <returns>The command line arguments for video transcoding.</returns>
+ private string GetVideoArguments(StreamState state, int startNumber)
+ {
+ if (state.VideoStream == null)
+ {
+ return string.Empty;
+ }
+
+ if (!state.IsOutputVideo)
+ {
+ return string.Empty;
+ }
+
+ var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
+
+ var args = "-codec:v:0 " + codec;
+
+ // Prefer hvc1 to hev1.
+ if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ args += " -tag:v:0 hvc1";
+ }
+
+ // if (state.EnableMpegtsM2TsMode)
+ // {
+ // args += " -mpegts_m2ts_mode 1";
+ // }
+
+ // See if we can save come cpu cycles by avoiding encoding.
+ if (EncodingHelper.IsCopyCodec(codec))
+ {
+ if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
+ {
+ string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream);
+ if (!string.IsNullOrEmpty(bitStreamArgs))
+ {
+ args += " " + bitStreamArgs;
+ }
+ }
+
+ args += " -start_at_zero";
+
+ // args += " -flags -global_header";
+ }
+ else
+ {
+ args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset);
+
+ // Set the key frame params for video encoding to match the hls segment time.
+ args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, false, startNumber);
+
+ // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
+ if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase))
+ {
+ args += " -bf 0";
+ }
+
+ // args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";
+
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+
+ if (hasGraphicalSubs)
+ {
+ // Graphical subs overlay and resolution params.
+ args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec);
+ }
+ else
+ {
+ // Resolution params.
+ args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec);
+ }
+
+ // -start_at_zero is necessary to use with -ss when seeking,
+ // otherwise the target position cannot be determined.
+ if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
+ {
+ args += " -start_at_zero";
+ }
+
+ // args += " -flags -global_header";
+ }
+
+ if (!string.IsNullOrEmpty(state.OutputVideoSync))
+ {
+ args += " -vsync " + state.OutputVideoSync;
+ }
+
+ args += _encodingHelper.GetOutputFFlags(state);
+
+ return args;
+ }
+
+ private string GetSegmentFileExtension(string? segmentContainer)
+ {
+ if (!string.IsNullOrWhiteSpace(segmentContainer))
+ {
+ return "." + segmentContainer;
+ }
+
+ return ".ts";
+ }
+
+ private string GetSegmentPath(StreamState state, string playlist, int index)
+ {
+ var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not valid.", nameof(playlist));
+ var filename = Path.GetFileNameWithoutExtension(playlist);
+
+ return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer));
+ }
+
+ private async Task<ActionResult> GetSegmentResult(
+ StreamState state,
+ string playlistPath,
+ string segmentPath,
+ string segmentExtension,
+ int segmentIndex,
+ TranscodingJobDto? transcodingJob,
+ CancellationToken cancellationToken)
+ {
+ var segmentExists = System.IO.File.Exists(segmentPath);
+ if (segmentExists)
+ {
+ if (transcodingJob != null && transcodingJob.HasExited)
+ {
+ // Transcoding job is over, so assume all existing files are ready
+ _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
+ return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
+ }
+
+ var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
+
+ // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's ready
+ if (segmentIndex < currentTranscodingIndex)
+ {
+ _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, currentTranscodingIndex, segmentIndex);
+ return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
+ }
+ }
+
+ var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
+ if (transcodingJob != null)
+ {
+ while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
+ {
+ // To be considered ready, the segment file has to exist AND
+ // either the transcoding job should be done or next segment should also exist
+ if (segmentExists)
+ {
+ if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
+ {
+ _logger.LogDebug("serving up {0} as it deemed ready", segmentPath);
+ return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
+ }
+ }
+ else
+ {
+ segmentExists = System.IO.File.Exists(segmentPath);
+ if (segmentExists)
+ {
+ continue; // avoid unnecessary waiting if segment just became available
+ }
+ }
+
+ await Task.Delay(100, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (!System.IO.File.Exists(segmentPath))
+ {
+ _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
+ }
+ else
+ {
+ _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+ else
+ {
+ _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
+ }
+
+ return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
+ }
+
+ private ActionResult GetSegmentResult(StreamState state, string segmentPath, int index, TranscodingJobDto? transcodingJob)
+ {
+ var segmentEndingPositionTicks = GetEndPositionTicks(state, index);
+
+ Response.OnCompleted(() =>
+ {
+ _logger.LogDebug("finished serving {0}", segmentPath);
+ if (transcodingJob != null)
+ {
+ transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
+ _transcodingJobHelper.OnTranscodeEndRequest(transcodingJob);
+ }
+
+ return Task.CompletedTask;
+ });
+
+ return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath), false, HttpContext);
+ }
+
+ private long GetEndPositionTicks(StreamState state, int requestedIndex)
+ {
+ double startSeconds = 0;
+ var lengths = GetSegmentLengths(state);
+
+ if (requestedIndex >= lengths.Length)
+ {
+ var msg = string.Format(
+ CultureInfo.InvariantCulture,
+ "Invalid segment index requested: {0} - Segment count: {1}",
+ requestedIndex,
+ lengths.Length);
+ throw new ArgumentException(msg);
+ }
+
+ for (var i = 0; i <= requestedIndex; i++)
+ {
+ startSeconds += lengths[i];
+ }
+
+ return TimeSpan.FromSeconds(startSeconds).Ticks;
+ }
+
+ private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
+ {
+ var job = _transcodingJobHelper.GetTranscodingJob(playlist, TranscodingJobType);
+
+ if (job == null || job.HasExited)
+ {
+ return null;
+ }
+
+ var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
+
+ if (file == null)
+ {
+ return null;
+ }
+
+ var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
+
+ var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
+
+ return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
+ }
+
+ private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
+ {
+ var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", nameof(playlist));
+
+ var filePrefix = Path.GetFileNameWithoutExtension(playlist);
+
+ try
+ {
+ return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
+ .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
+ .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
+ .FirstOrDefault();
+ }
+ catch (IOException)
+ {
+ return null;
+ }
+ }
+
+ private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
+ {
+ var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
+
+ if (file != null)
+ {
+ DeleteFile(file.FullName, retryCount);
+ }
+ }
+
+ private void DeleteFile(string path, int retryCount)
+ {
+ if (retryCount >= 5)
+ {
+ return;
+ }
+
+ _logger.LogDebug("Deleting partial HLS file {path}", path);
+
+ try
+ {
+ _fileSystem.DeleteFile(path);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
+
+ var task = Task.Delay(100);
+ Task.WaitAll(task);
+ DeleteFile(path, retryCount + 1);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
+ }
+ }
+
+ private long GetStartPositionTicks(StreamState state, int requestedIndex)
+ {
+ double startSeconds = 0;
+ var lengths = GetSegmentLengths(state);
+
+ if (requestedIndex >= lengths.Length)
+ {
+ var msg = string.Format(
+ CultureInfo.InvariantCulture,
+ "Invalid segment index requested: {0} - Segment count: {1}",
+ requestedIndex,
+ lengths.Length);
+ throw new ArgumentException(msg);
+ }
+
+ for (var i = 0; i < requestedIndex; i++)
+ {
+ startSeconds += lengths[i];
+ }
+
+ var position = TimeSpan.FromSeconds(startSeconds).Ticks;
+ return position;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/EnvironmentController.cs b/Jellyfin.Api/Controllers/EnvironmentController.cs
new file mode 100644
index 000000000..b0b4b5af5
--- /dev/null
+++ b/Jellyfin.Api/Controllers/EnvironmentController.cs
@@ -0,0 +1,197 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.IO;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.EnvironmentDtos;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Model.IO;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Environment Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
+ public class EnvironmentController : BaseJellyfinApiController
+ {
+ private const char UncSeparator = '\\';
+ private const string UncStartPrefix = @"\\";
+
+ private readonly IFileSystem _fileSystem;
+ private readonly ILogger<EnvironmentController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EnvironmentController"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{EnvironmentController}"/> interface.</param>
+ public EnvironmentController(IFileSystem fileSystem, ILogger<EnvironmentController> logger)
+ {
+ _fileSystem = fileSystem;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Gets the contents of a given directory in the file system.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="includeFiles">An optional filter to include or exclude files from the results. true/false.</param>
+ /// <param name="includeDirectories">An optional filter to include or exclude folders from the results. true/false.</param>
+ /// <response code="200">Directory contents returned.</response>
+ /// <returns>Directory contents.</returns>
+ [HttpGet("DirectoryContents")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<FileSystemEntryInfo> GetDirectoryContents(
+ [FromQuery, Required] string path,
+ [FromQuery] bool includeFiles = false,
+ [FromQuery] bool includeDirectories = false)
+ {
+ if (path.StartsWith(UncStartPrefix, StringComparison.OrdinalIgnoreCase)
+ && path.LastIndexOf(UncSeparator) == 1)
+ {
+ return Array.Empty<FileSystemEntryInfo>();
+ }
+
+ var entries =
+ _fileSystem.GetFileSystemEntries(path)
+ .Where(i => (i.IsDirectory && includeDirectories) || (!i.IsDirectory && includeFiles))
+ .OrderBy(i => i.FullName);
+
+ return entries.Select(f => new FileSystemEntryInfo(f.Name, f.FullName, f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File));
+ }
+
+ /// <summary>
+ /// Validates path.
+ /// </summary>
+ /// <param name="validatePathDto">Validate request object.</param>
+ /// <response code="204">Path validated.</response>
+ /// <response code="404">Path not found.</response>
+ /// <returns>Validation status.</returns>
+ [HttpPost("ValidatePath")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult ValidatePath([FromBody, Required] ValidatePathDto validatePathDto)
+ {
+ if (validatePathDto.IsFile.HasValue)
+ {
+ if (validatePathDto.IsFile.Value)
+ {
+ if (!System.IO.File.Exists(validatePathDto.Path))
+ {
+ return NotFound();
+ }
+ }
+ else
+ {
+ if (!Directory.Exists(validatePathDto.Path))
+ {
+ return NotFound();
+ }
+ }
+ }
+ else
+ {
+ if (!System.IO.File.Exists(validatePathDto.Path) && !Directory.Exists(validatePathDto.Path))
+ {
+ return NotFound();
+ }
+
+ if (validatePathDto.ValidateWritable)
+ {
+ if (validatePathDto.Path == null)
+ {
+ throw new ResourceNotFoundException(nameof(validatePathDto.Path));
+ }
+
+ var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString());
+ try
+ {
+ System.IO.File.WriteAllText(file, string.Empty);
+ }
+ finally
+ {
+ if (System.IO.File.Exists(file))
+ {
+ System.IO.File.Delete(file);
+ }
+ }
+ }
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets network paths.
+ /// </summary>
+ /// <response code="200">Empty array returned.</response>
+ /// <returns>List of entries.</returns>
+ [Obsolete("This endpoint is obsolete.")]
+ [HttpGet("NetworkShares")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<FileSystemEntryInfo>> GetNetworkShares()
+ {
+ _logger.LogWarning("Obsolete endpoint accessed: /Environment/NetworkShares");
+ return Array.Empty<FileSystemEntryInfo>();
+ }
+
+ /// <summary>
+ /// Gets available drives from the server's file system.
+ /// </summary>
+ /// <response code="200">List of entries returned.</response>
+ /// <returns>List of entries.</returns>
+ [HttpGet("Drives")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<FileSystemEntryInfo> GetDrives()
+ {
+ return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo(d.Name, d.FullName, FileSystemEntryType.Directory));
+ }
+
+ /// <summary>
+ /// Gets the parent path of a given path.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <returns>Parent path.</returns>
+ [HttpGet("ParentPath")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<string?> GetParentPath([FromQuery, Required] string path)
+ {
+ string? parent = Path.GetDirectoryName(path);
+ if (string.IsNullOrEmpty(parent))
+ {
+ // Check if unc share
+ var index = path.LastIndexOf(UncSeparator);
+
+ if (index != -1 && path.IndexOf(UncSeparator, StringComparison.OrdinalIgnoreCase) == 0)
+ {
+ parent = path.Substring(0, index);
+
+ if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
+ {
+ parent = null;
+ }
+ }
+ }
+
+ return parent;
+ }
+
+ /// <summary>
+ /// Get Default directory browser.
+ /// </summary>
+ /// <response code="200">Default directory browser returned.</response>
+ /// <returns>Default directory browser.</returns>
+ [HttpGet("DefaultDirectoryBrowser")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<DefaultDirectoryBrowserInfoDto> GetDefaultDirectoryBrowser()
+ {
+ return new DefaultDirectoryBrowserInfoDto();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs
new file mode 100644
index 000000000..223b2a2b6
--- /dev/null
+++ b/Jellyfin.Api/Controllers/FilterController.cs
@@ -0,0 +1,217 @@
+using System;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Filters controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class FilterController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FilterController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ public FilterController(ILibraryManager libraryManager, IUserManager userManager)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ }
+
+ /// <summary>
+ /// Gets legacy query filters.
+ /// </summary>
+ /// <param name="userId">Optional. User id.</param>
+ /// <param name="parentId">Optional. Parent id.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <response code="200">Legacy filters retrieved.</response>
+ /// <returns>Legacy query filters.</returns>
+ [HttpGet("Items/Filters")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryFiltersLegacy> GetQueryFiltersLegacy(
+ [FromQuery] Guid? userId,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ BaseItem? item = null;
+ if (includeItemTypes.Length != 1
+ || !(includeItemTypes[0] == BaseItemKind.BoxSet
+ || includeItemTypes[0] == BaseItemKind.Playlist
+ || includeItemTypes[0] == BaseItemKind.Trailer
+ || includeItemTypes[0] == BaseItemKind.Program))
+ {
+ item = _libraryManager.GetParentItem(parentId, user?.Id);
+ }
+
+ var query = new InternalItemsQuery
+ {
+ User = user,
+ MediaTypes = mediaTypes,
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ Recursive = true,
+ EnableTotalRecordCount = false,
+ DtoOptions = new DtoOptions
+ {
+ Fields = new[] { ItemFields.Genres, ItemFields.Tags },
+ EnableImages = false,
+ EnableUserData = false
+ }
+ };
+
+ if (item is not Folder folder)
+ {
+ return new QueryFiltersLegacy();
+ }
+
+ var itemList = folder.GetItemList(query);
+ return new QueryFiltersLegacy
+ {
+ Years = itemList.Select(i => i.ProductionYear ?? -1)
+ .Where(i => i > 0)
+ .Distinct()
+ .OrderBy(i => i)
+ .ToArray(),
+
+ Genres = itemList.SelectMany(i => i.Genres)
+ .DistinctNames()
+ .OrderBy(i => i)
+ .ToArray(),
+
+ Tags = itemList
+ .SelectMany(i => i.Tags)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .OrderBy(i => i)
+ .ToArray(),
+
+ OfficialRatings = itemList
+ .Select(i => i.OfficialRating)
+ .Where(i => !string.IsNullOrWhiteSpace(i))
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .OrderBy(i => i)
+ .ToArray()
+ };
+ }
+
+ /// <summary>
+ /// Gets query filters.
+ /// </summary>
+ /// <param name="userId">Optional. User id.</param>
+ /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isAiring">Optional. Is item airing.</param>
+ /// <param name="isMovie">Optional. Is item movie.</param>
+ /// <param name="isSports">Optional. Is item sports.</param>
+ /// <param name="isKids">Optional. Is item kids.</param>
+ /// <param name="isNews">Optional. Is item news.</param>
+ /// <param name="isSeries">Optional. Is item series.</param>
+ /// <param name="recursive">Optional. Search recursive.</param>
+ /// <response code="200">Filters retrieved.</response>
+ /// <returns>Query filters.</returns>
+ [HttpGet("Items/Filters2")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryFilters> GetQueryFilters(
+ [FromQuery] Guid? userId,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isAiring,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isSports,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? recursive)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ BaseItem? parentItem = null;
+ if (includeItemTypes.Length == 1
+ && (includeItemTypes[0] == BaseItemKind.BoxSet
+ || includeItemTypes[0] == BaseItemKind.Playlist
+ || includeItemTypes[0] == BaseItemKind.Trailer
+ || includeItemTypes[0] == BaseItemKind.Program))
+ {
+ parentItem = null;
+ }
+ else if (parentId.HasValue)
+ {
+ parentItem = _libraryManager.GetItemById(parentId.Value);
+ }
+
+ var filters = new QueryFilters();
+ var genreQuery = new InternalItemsQuery(user)
+ {
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ DtoOptions = new DtoOptions
+ {
+ Fields = Array.Empty<ItemFields>(),
+ EnableImages = false,
+ EnableUserData = false
+ },
+ IsAiring = isAiring,
+ IsMovie = isMovie,
+ IsSports = isSports,
+ IsKids = isKids,
+ IsNews = isNews,
+ IsSeries = isSeries
+ };
+
+ if ((recursive ?? true) || parentItem is UserView || parentItem is ICollectionFolder)
+ {
+ genreQuery.AncestorIds = parentItem == null ? Array.Empty<Guid>() : new[] { parentItem.Id };
+ }
+ else
+ {
+ genreQuery.Parent = parentItem;
+ }
+
+ if (includeItemTypes.Length == 1
+ && (includeItemTypes[0] == BaseItemKind.MusicAlbum
+ || includeItemTypes[0] == BaseItemKind.MusicVideo
+ || includeItemTypes[0] == BaseItemKind.MusicArtist
+ || includeItemTypes[0] == BaseItemKind.Audio))
+ {
+ filters.Genres = _libraryManager.GetMusicGenres(genreQuery).Items.Select(i => new NameGuidPair
+ {
+ Name = i.Item1.Name,
+ Id = i.Item1.Id
+ }).ToArray();
+ }
+ else
+ {
+ filters.Genres = _libraryManager.GetGenres(genreQuery).Items.Select(i => new NameGuidPair
+ {
+ Name = i.Item1.Name,
+ Id = i.Item1.Id
+ }).ToArray();
+ }
+
+ return filters;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs
new file mode 100644
index 000000000..5aa457153
--- /dev/null
+++ b/Jellyfin.Api/Controllers/GenresController.cs
@@ -0,0 +1,212 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The genres controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class GenresController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GenresController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ public GenresController(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IDtoService dtoService)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ }
+
+ /// <summary>
+ /// Gets all genres from a given item, folder, or the entire library.
+ /// </summary>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">The search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="enableTotalRecordCount">Optional. Include total record count.</param>
+ /// <response code="200">Genres returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the queryresult of genres.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetGenres(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isFavorite,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
+
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
+
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
+ };
+
+ if (parentId.HasValue)
+ {
+ if (parentItem is Folder)
+ {
+ query.AncestorIds = new[] { parentId.Value };
+ }
+ else
+ {
+ query.ItemIds = new[] { parentId.Value };
+ }
+ }
+
+ QueryResult<(BaseItem, ItemCounts)> result;
+ if (parentItem is ICollectionFolder parentCollectionFolder
+ && (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music, StringComparison.Ordinal)
+ || string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos, StringComparison.Ordinal)))
+ {
+ result = _libraryManager.GetMusicGenres(query);
+ }
+ else
+ {
+ result = _libraryManager.GetGenres(query);
+ }
+
+ var shouldIncludeItemTypes = includeItemTypes.Length != 0;
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
+ }
+
+ /// <summary>
+ /// Gets a genre, by name.
+ /// </summary>
+ /// <param name="genreName">The genre name.</param>
+ /// <param name="userId">The user id.</param>
+ /// <response code="200">Genres returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the genre.</returns>
+ [HttpGet("{genreName}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BaseItemDto> GetGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
+ {
+ var dtoOptions = new DtoOptions()
+ .AddClientFields(Request);
+
+ Genre item = new Genre();
+ if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ var result = GetItemFromSlugName<Genre>(_libraryManager, genreName, dtoOptions);
+
+ if (result != null)
+ {
+ item = result;
+ }
+ }
+ else
+ {
+ item = _libraryManager.GetGenre(genreName);
+ }
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+
+ private T? GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
+ where T : BaseItem, new()
+ {
+ var result = libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '&'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ result ??= libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '/'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ result ??= libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '?'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs
new file mode 100644
index 000000000..71caa0fe0
--- /dev/null
+++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs
@@ -0,0 +1,192 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The hls segment controller.
+ /// </summary>
+ [Route("")]
+ public class HlsSegmentController : BaseJellyfinApiController
+ {
+ private readonly IFileSystem _fileSystem;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HlsSegmentController"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Initialized instance of the <see cref="TranscodingJobHelper"/>.</param>
+ public HlsSegmentController(
+ IFileSystem fileSystem,
+ IServerConfigurationManager serverConfigurationManager,
+ TranscodingJobHelper transcodingJobHelper)
+ {
+ _fileSystem = fileSystem;
+ _serverConfigurationManager = serverConfigurationManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ }
+
+ /// <summary>
+ /// Gets the specified audio segment for an audio item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="segmentId">The segment id.</param>
+ /// <response code="200">Hls audio segment returned.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the audio stream.</returns>
+ // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
+ // [Authenticated]
+ [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.mp3", Name = "GetHlsAudioSegmentLegacyMp3")]
+ [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.aac", Name = "GetHlsAudioSegmentLegacyAac")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesAudioFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
+ public ActionResult GetHlsAudioSegmentLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string segmentId)
+ {
+ // TODO: Deprecate with new iOS app
+ var file = segmentId + Path.GetExtension(Request.Path);
+ var transcodePath = _serverConfigurationManager.GetTranscodePath();
+ file = Path.GetFullPath(Path.Combine(transcodePath, file));
+ var fileDir = Path.GetDirectoryName(file);
+ if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath))
+ {
+ return BadRequest("Invalid segment.");
+ }
+
+ return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file), false, HttpContext);
+ }
+
+ /// <summary>
+ /// Gets a hls video playlist.
+ /// </summary>
+ /// <param name="itemId">The video id.</param>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <response code="200">Hls video playlist returned.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the playlist.</returns>
+ [HttpGet("Videos/{itemId}/hls/{playlistId}/stream.m3u8")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
+ public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId)
+ {
+ var file = playlistId + Path.GetExtension(Request.Path);
+ var transcodePath = _serverConfigurationManager.GetTranscodePath();
+ file = Path.GetFullPath(Path.Combine(transcodePath, file));
+ var fileDir = Path.GetDirectoryName(file);
+ if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath) || Path.GetExtension(file) != ".m3u8")
+ {
+ return BadRequest("Invalid segment.");
+ }
+
+ return GetFileResult(file, file);
+ }
+
+ /// <summary>
+ /// Stops an active encoding.
+ /// </summary>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <response code="204">Encoding stopped successfully.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpDelete("Videos/ActiveEncodings")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult StopEncodingProcess(
+ [FromQuery, Required] string deviceId,
+ [FromQuery, Required] string playSessionId)
+ {
+ _transcodingJobHelper.KillTranscodingJobs(deviceId, playSessionId, path => true);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a hls video segment.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="segmentId">The segment id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <response code="200">Hls video segment returned.</response>
+ /// <response code="404">Hls segment not found.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the video segment.</returns>
+ // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
+ // [Authenticated]
+ [HttpGet("Videos/{itemId}/hls/{playlistId}/{segmentId}.{segmentContainer}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesVideoFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
+ public ActionResult GetHlsVideoSegmentLegacy(
+ [FromRoute, Required] string itemId,
+ [FromRoute, Required] string playlistId,
+ [FromRoute, Required] string segmentId,
+ [FromRoute, Required] string segmentContainer)
+ {
+ var file = segmentId + Path.GetExtension(Request.Path);
+ var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath();
+
+ file = Path.GetFullPath(Path.Combine(transcodeFolderPath, file));
+ var fileDir = Path.GetDirectoryName(file);
+ if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath))
+ {
+ return BadRequest("Invalid segment.");
+ }
+
+ var normalizedPlaylistId = playlistId;
+
+ var filePaths = _fileSystem.GetFilePaths(transcodeFolderPath);
+ // Add . to start of segment container for future use.
+ segmentContainer = segmentContainer.Insert(0, ".");
+ string? playlistPath = null;
+ foreach (var path in filePaths)
+ {
+ var pathExtension = Path.GetExtension(path);
+ if ((string.Equals(pathExtension, segmentContainer, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(pathExtension, ".m3u8", StringComparison.OrdinalIgnoreCase))
+ && path.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ playlistPath = path;
+ break;
+ }
+ }
+
+ return playlistPath == null
+ ? NotFound("Hls segment not found.")
+ : GetFileResult(file, playlistPath);
+ }
+
+ private ActionResult GetFileResult(string path, string playlistPath)
+ {
+ var transcodingJob = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
+
+ Response.OnCompleted(() =>
+ {
+ if (transcodingJob != null)
+ {
+ _transcodingJobHelper.OnTranscodeEndRequest(transcodingJob);
+ }
+
+ return Task.CompletedTask;
+ });
+
+ return FileStreamResponseHelpers.GetStaticFileResult(path, MimeTypes.GetMimeType(path), false, HttpContext);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ImageByNameController.cs b/Jellyfin.Api/Controllers/ImageByNameController.cs
new file mode 100644
index 000000000..99ab7f232
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ImageByNameController.cs
@@ -0,0 +1,252 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.IO;
+using System.Linq;
+using System.Net.Mime;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Images By Name Controller.
+ /// </summary>
+ [Route("Images")]
+ public class ImageByNameController : BaseJellyfinApiController
+ {
+ private readonly IServerApplicationPaths _applicationPaths;
+ private readonly IFileSystem _fileSystem;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ImageByNameController" /> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager" /> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem" /> interface.</param>
+ public ImageByNameController(
+ IServerConfigurationManager serverConfigurationManager,
+ IFileSystem fileSystem)
+ {
+ _applicationPaths = serverConfigurationManager.ApplicationPaths;
+ _fileSystem = fileSystem;
+ }
+
+ /// <summary>
+ /// Get all general images.
+ /// </summary>
+ /// <response code="200">Retrieved list of images.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
+ [HttpGet("General")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<ImageByNameInfo>> GetGeneralImages()
+ {
+ return GetImageList(_applicationPaths.GeneralPath, false);
+ }
+
+ /// <summary>
+ /// Get General Image.
+ /// </summary>
+ /// <param name="name">The name of the image.</param>
+ /// <param name="type">Image Type (primary, backdrop, logo, etc).</param>
+ /// <response code="200">Image stream retrieved.</response>
+ /// <response code="404">Image not found.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
+ [HttpGet("General/{name}/{type}")]
+ [AllowAnonymous]
+ [Produces(MediaTypeNames.Application.Octet)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public ActionResult GetGeneralImage([FromRoute, Required] string name, [FromRoute, Required] string type)
+ {
+ var filename = string.Equals(type, "primary", StringComparison.OrdinalIgnoreCase)
+ ? "folder"
+ : type;
+
+ var path = BaseItem.SupportedImageExtensions
+ .Select(i => Path.GetFullPath(Path.Combine(_applicationPaths.GeneralPath, name, filename + i)))
+ .FirstOrDefault(System.IO.File.Exists);
+
+ if (path == null)
+ {
+ return NotFound();
+ }
+
+ if (!path.StartsWith(_applicationPaths.GeneralPath))
+ {
+ return BadRequest("Invalid image path.");
+ }
+
+ var contentType = MimeTypes.GetMimeType(path);
+ return File(AsyncFile.OpenRead(path), contentType);
+ }
+
+ /// <summary>
+ /// Get all general images.
+ /// </summary>
+ /// <response code="200">Retrieved list of images.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
+ [HttpGet("Ratings")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<ImageByNameInfo>> GetRatingImages()
+ {
+ return GetImageList(_applicationPaths.RatingsPath, false);
+ }
+
+ /// <summary>
+ /// Get rating image.
+ /// </summary>
+ /// <param name="theme">The theme to get the image from.</param>
+ /// <param name="name">The name of the image.</param>
+ /// <response code="200">Image stream retrieved.</response>
+ /// <response code="404">Image not found.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
+ [HttpGet("Ratings/{theme}/{name}")]
+ [AllowAnonymous]
+ [Produces(MediaTypeNames.Application.Octet)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public ActionResult GetRatingImage(
+ [FromRoute, Required] string theme,
+ [FromRoute, Required] string name)
+ {
+ return GetImageFile(_applicationPaths.RatingsPath, theme, name);
+ }
+
+ /// <summary>
+ /// Get all media info images.
+ /// </summary>
+ /// <response code="200">Image list retrieved.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
+ [HttpGet("MediaInfo")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<ImageByNameInfo>> GetMediaInfoImages()
+ {
+ return GetImageList(_applicationPaths.MediaInfoImagesPath, false);
+ }
+
+ /// <summary>
+ /// Get media info image.
+ /// </summary>
+ /// <param name="theme">The theme to get the image from.</param>
+ /// <param name="name">The name of the image.</param>
+ /// <response code="200">Image stream retrieved.</response>
+ /// <response code="404">Image not found.</response>
+ /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
+ [HttpGet("MediaInfo/{theme}/{name}")]
+ [AllowAnonymous]
+ [Produces(MediaTypeNames.Application.Octet)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public ActionResult GetMediaInfoImage(
+ [FromRoute, Required] string theme,
+ [FromRoute, Required] string name)
+ {
+ return GetImageFile(_applicationPaths.MediaInfoImagesPath, theme, name);
+ }
+
+ /// <summary>
+ /// Internal FileHelper.
+ /// </summary>
+ /// <param name="basePath">Path to begin search.</param>
+ /// <param name="theme">Theme to search.</param>
+ /// <param name="name">File name to search for.</param>
+ /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
+ private ActionResult GetImageFile(string basePath, string theme, string? name)
+ {
+ var themeFolder = Path.GetFullPath(Path.Combine(basePath, theme));
+
+ if (Directory.Exists(themeFolder))
+ {
+ var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, name + i))
+ .FirstOrDefault(System.IO.File.Exists);
+
+ if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
+ {
+ if (!path.StartsWith(basePath))
+ {
+ return BadRequest("Invalid image path.");
+ }
+
+ var contentType = MimeTypes.GetMimeType(path);
+
+ return PhysicalFile(path, contentType);
+ }
+ }
+
+ var allFolder = Path.GetFullPath(Path.Combine(basePath, "all"));
+ if (Directory.Exists(allFolder))
+ {
+ var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, name + i))
+ .FirstOrDefault(System.IO.File.Exists);
+
+ if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
+ {
+ if (!path.StartsWith(basePath))
+ {
+ return BadRequest("Invalid image path.");
+ }
+
+ var contentType = MimeTypes.GetMimeType(path);
+ return PhysicalFile(path, contentType);
+ }
+ }
+
+ return NotFound();
+ }
+
+ private List<ImageByNameInfo> GetImageList(string path, bool supportsThemes)
+ {
+ try
+ {
+ return _fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, true)
+ .Select(i => new ImageByNameInfo
+ {
+ Name = _fileSystem.GetFileNameWithoutExtension(i),
+ FileLength = i.Length,
+
+ // For themeable images, use the Theme property
+ // For general images, the same object structure is fine,
+ // but it's not owned by a theme, so call it Context
+ Theme = supportsThemes ? GetThemeName(i.FullName, path) : null,
+ Context = supportsThemes ? null : GetThemeName(i.FullName, path),
+ Format = i.Extension.ToLowerInvariant().TrimStart('.')
+ })
+ .OrderBy(i => i.Name)
+ .ToList();
+ }
+ catch (IOException)
+ {
+ return new List<ImageByNameInfo>();
+ }
+ }
+
+ private string? GetThemeName(string path, string rootImagePath)
+ {
+ var parentName = Path.GetDirectoryName(path);
+
+ if (string.Equals(parentName, rootImagePath, StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
+ parentName = Path.GetFileName(parentName);
+
+ return string.Equals(parentName, "all", StringComparison.OrdinalIgnoreCase) ? null : parentName;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs
new file mode 100644
index 000000000..86933074d
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ImageController.cs
@@ -0,0 +1,2032 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net.Mime;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Image controller.
+ /// </summary>
+ [Route("")]
+ public class ImageController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IProviderManager _providerManager;
+ private readonly IImageProcessor _imageProcessor;
+ private readonly IFileSystem _fileSystem;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILogger<ImageController> _logger;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ImageController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="imageProcessor">Instance of the <see cref="IImageProcessor"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{ImageController}"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public ImageController(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IProviderManager providerManager,
+ IImageProcessor imageProcessor,
+ IFileSystem fileSystem,
+ IAuthorizationContext authContext,
+ ILogger<ImageController> logger,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _providerManager = providerManager;
+ _imageProcessor = imageProcessor;
+ _fileSystem = fileSystem;
+ _authContext = authContext;
+ _logger = logger;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <summary>
+ /// Sets the user image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
+ /// <param name="index">(Unused) Image index.</param>
+ /// <response code="204">Image updated.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/Images/{imageType}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [AcceptsImageFile]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> PostUserImage(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] int? index = null)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+ await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false);
+
+ // Handle image/png; charset=utf-8
+ var mimeType = Request.ContentType?.Split(';').FirstOrDefault();
+ var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username);
+ if (user.ProfileImage != null)
+ {
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
+ }
+
+ user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType ?? string.Empty)));
+
+ await _providerManager
+ .SaveImage(memoryStream, mimeType, user.ProfileImage.Path)
+ .ConfigureAwait(false);
+ await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Sets the user image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
+ /// <param name="index">(Unused) Image index.</param>
+ /// <response code="204">Image updated.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/Images/{imageType}/{index}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [AcceptsImageFile]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> PostUserImageByIndex(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute] int index)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+ await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false);
+
+ // Handle image/png; charset=utf-8
+ var mimeType = Request.ContentType?.Split(';').FirstOrDefault();
+ var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username);
+ if (user.ProfileImage != null)
+ {
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
+ }
+
+ user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType ?? string.Empty)));
+
+ await _providerManager
+ .SaveImage(memoryStream, mimeType, user.ProfileImage.Path)
+ .ConfigureAwait(false);
+ await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Delete the user's image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
+ /// <param name="index">(Unused) Image index.</param>
+ /// <response code="204">Image deleted.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Users/{userId}/Images/{imageType}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult> DeleteUserImage(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] int? index = null)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+ if (user?.ProfileImage == null)
+ {
+ return NoContent();
+ }
+
+ try
+ {
+ System.IO.File.Delete(user.ProfileImage.Path);
+ }
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error deleting user profile image:");
+ }
+
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Delete the user's image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
+ /// <param name="index">(Unused) Image index.</param>
+ /// <response code="204">Image deleted.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Users/{userId}/Images/{imageType}/{index}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult> DeleteUserImageByIndex(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute] int index)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+ if (user?.ProfileImage == null)
+ {
+ return NoContent();
+ }
+
+ try
+ {
+ System.IO.File.Delete(user.ProfileImage.Path);
+ }
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error deleting user profile image:");
+ }
+
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Delete an item's image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">The image index.</param>
+ /// <response code="204">Image deleted.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpDelete("Items/{itemId}/Images/{imageType}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteItemImage(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await item.DeleteImageAsync(imageType, imageIndex ?? 0).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Delete an item's image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">The image index.</param>
+ /// <response code="204">Image deleted.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpDelete("Items/{itemId}/Images/{imageType}/{imageIndex}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteItemImageByIndex(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute] int imageIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await item.DeleteImageAsync(imageType, imageIndex).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Set item image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <response code="204">Image saved.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpPost("Items/{itemId}/Images/{imageType}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [AcceptsImageFile]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> SetItemImage(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false);
+
+ // Handle image/png; charset=utf-8
+ var mimeType = Request.ContentType?.Split(';').FirstOrDefault();
+ await _providerManager.SaveImage(item, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Set item image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">(Unused) Image index.</param>
+ /// <response code="204">Image saved.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpPost("Items/{itemId}/Images/{imageType}/{imageIndex}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [AcceptsImageFile]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> SetItemImageByIndex(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute] int imageIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false);
+
+ // Handle image/png; charset=utf-8
+ var mimeType = Request.ContentType?.Split(';').FirstOrDefault();
+ await _providerManager.SaveImage(item, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates the index for an item image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Old image index.</param>
+ /// <param name="newIndex">New image index.</param>
+ /// <response code="204">Image index updated.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpPost("Items/{itemId}/Images/{imageType}/{imageIndex}/Index")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> UpdateItemImageIndex(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery, Required] int newIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await item.SwapImagesAsync(imageType, imageIndex, newIndex).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Get item image infos.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item images returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>The list of image infos on success, or <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpGet("Items/{itemId}/Images")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<IEnumerable<ImageInfo>>> GetItemImageInfos([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var list = new List<ImageInfo>();
+ var itemImages = item.ImageInfos;
+
+ if (itemImages.Length == 0)
+ {
+ // short-circuit
+ return list;
+ }
+
+ await _libraryManager.UpdateImagesAsync(item).ConfigureAwait(false); // this makes sure dimensions and hashes are correct
+
+ foreach (var image in itemImages)
+ {
+ if (!item.AllowsMultipleImages(image.Type))
+ {
+ var info = GetImageInfo(item, image, null);
+
+ if (info != null)
+ {
+ list.Add(info);
+ }
+ }
+ }
+
+ foreach (var imageType in itemImages.Select(i => i.Type).Distinct().Where(item.AllowsMultipleImages))
+ {
+ var index = 0;
+
+ // Prevent implicitly captured closure
+ var currentImageType = imageType;
+
+ foreach (var image in itemImages.Where(i => i.Type == currentImageType))
+ {
+ var info = GetImageInfo(item, image, index);
+
+ if (info != null)
+ {
+ list.Add(info);
+ }
+
+ index++;
+ }
+ }
+
+ return list;
+ }
+
+ /// <summary>
+ /// Gets the item's image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="format">Optional. The <see cref="ImageFormat"/> of the returned image.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Items/{itemId}/Images/{imageType}")]
+ [HttpHead("Items/{itemId}/Images/{imageType}", Name = "HeadItemImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetItemImage(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery] string? tag,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ itemId,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets the item's image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="format">Optional. The <see cref="ImageFormat"/> of the returned image.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Items/{itemId}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Items/{itemId}/Images/{imageType}/{imageIndex}", Name = "HeadItemImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetItemImageByIndex(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute] int imageIndex,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery] string? tag,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ itemId,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets the item's image.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Items/{itemId}/Images/{imageType}/{imageIndex}/{tag}/{format}/{maxWidth}/{maxHeight}/{percentPlayed}/{unplayedCount}")]
+ [HttpHead("Items/{itemId}/Images/{imageType}/{imageIndex}/{tag}/{format}/{maxWidth}/{maxHeight}/{percentPlayed}/{unplayedCount}", Name = "HeadItemImage2")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetItemImage2(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int maxWidth,
+ [FromRoute, Required] int maxHeight,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromRoute, Required] string tag,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromRoute, Required] ImageFormat format,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromRoute, Required] double percentPlayed,
+ [FromRoute, Required] int unplayedCount,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromRoute, Required] int imageIndex)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ itemId,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get artist image by name.
+ /// </summary>
+ /// <param name="name">Artist name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Artists/{name}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Artists/{name}/Images/{imageType}/{imageIndex}", Name = "HeadArtistImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetArtistImage(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromRoute, Required] int imageIndex)
+ {
+ var item = _libraryManager.GetArtist(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get genre image by name.
+ /// </summary>
+ /// <param name="name">Genre name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Genres/{name}/Images/{imageType}")]
+ [HttpHead("Genres/{name}/Images/{imageType}", Name = "HeadGenreImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetGenreImage(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetGenre(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get genre image by name.
+ /// </summary>
+ /// <param name="name">Genre name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Genres/{name}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Genres/{name}/Images/{imageType}/{imageIndex}", Name = "HeadGenreImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetGenreImageByIndex(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var item = _libraryManager.GetGenre(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get music genre image by name.
+ /// </summary>
+ /// <param name="name">Music genre name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("MusicGenres/{name}/Images/{imageType}")]
+ [HttpHead("MusicGenres/{name}/Images/{imageType}", Name = "HeadMusicGenreImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetMusicGenreImage(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetMusicGenre(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get music genre image by name.
+ /// </summary>
+ /// <param name="name">Music genre name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("MusicGenres/{name}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("MusicGenres/{name}/Images/{imageType}/{imageIndex}", Name = "HeadMusicGenreImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetMusicGenreImageByIndex(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var item = _libraryManager.GetMusicGenre(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get person image by name.
+ /// </summary>
+ /// <param name="name">Person name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Persons/{name}/Images/{imageType}")]
+ [HttpHead("Persons/{name}/Images/{imageType}", Name = "HeadPersonImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetPersonImage(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetPerson(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get person image by name.
+ /// </summary>
+ /// <param name="name">Person name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Persons/{name}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Persons/{name}/Images/{imageType}/{imageIndex}", Name = "HeadPersonImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetPersonImageByIndex(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var item = _libraryManager.GetPerson(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get studio image by name.
+ /// </summary>
+ /// <param name="name">Studio name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Studios/{name}/Images/{imageType}")]
+ [HttpHead("Studios/{name}/Images/{imageType}", Name = "HeadStudioImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetStudioImage(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var item = _libraryManager.GetStudio(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get studio image by name.
+ /// </summary>
+ /// <param name="name">Studio name.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Studios/{name}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Studios/{name}/Images/{imageType}/{imageIndex}", Name = "HeadStudioImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetStudioImageByIndex(
+ [FromRoute, Required] string name,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var item = _libraryManager.GetStudio(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return await GetImageInternal(
+ item.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ item,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get user profile image.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Users/{userId}/Images/{imageType}")]
+ [HttpHead("Users/{userId}/Images/{imageType}", Name = "HeadUserImage")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetUserImage(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ {
+ var user = _userManager.GetUserById(userId);
+ if (user?.ProfileImage == null)
+ {
+ return NotFound();
+ }
+
+ var info = new ItemImageInfo
+ {
+ Path = user.ProfileImage.Path,
+ Type = ImageType.Profile,
+ DateModified = user.ProfileImage.LastModified
+ };
+
+ if (width.HasValue)
+ {
+ info.Width = width.Value;
+ }
+
+ if (height.HasValue)
+ {
+ info.Height = height.Value;
+ }
+
+ return await GetImageInternal(
+ user.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ null,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase),
+ info)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get user profile image.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="imageType">Image type.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
+ /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Users/{userId}/Images/{imageType}/{imageIndex}")]
+ [HttpHead("Users/{userId}/Images/{imageType}/{imageIndex}", Name = "HeadUserImageByIndex")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public async Task<ActionResult> GetUserImageByIndex(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromRoute, Required] int imageIndex,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery, ParameterObsolete] bool? cropWhitespace,
+ [FromQuery] bool? addPlayedIndicator,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer)
+ {
+ var user = _userManager.GetUserById(userId);
+ if (user?.ProfileImage == null)
+ {
+ return NotFound();
+ }
+
+ var info = new ItemImageInfo
+ {
+ Path = user.ProfileImage.Path,
+ Type = ImageType.Profile,
+ DateModified = user.ProfileImage.LastModified
+ };
+
+ if (width.HasValue)
+ {
+ info.Width = width.Value;
+ }
+
+ if (height.HasValue)
+ {
+ info.Height = height.Value;
+ }
+
+ return await GetImageInternal(
+ user.Id,
+ imageType,
+ imageIndex,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ addPlayedIndicator,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ null,
+ Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase),
+ info)
+ .ConfigureAwait(false);
+ }
+
+ private static async Task<MemoryStream> GetMemoryStream(Stream inputStream)
+ {
+ using var reader = new StreamReader(inputStream);
+ var text = await reader.ReadToEndAsync().ConfigureAwait(false);
+
+ var bytes = Convert.FromBase64String(text);
+ return new MemoryStream(bytes, 0, bytes.Length, false, true);
+ }
+
+ private ImageInfo? GetImageInfo(BaseItem item, ItemImageInfo info, int? imageIndex)
+ {
+ int? width = null;
+ int? height = null;
+ string? blurhash = null;
+ long length = 0;
+
+ try
+ {
+ if (info.IsLocalFile)
+ {
+ var fileInfo = _fileSystem.GetFileInfo(info.Path);
+ length = fileInfo.Length;
+
+ blurhash = info.BlurHash;
+ width = info.Width;
+ height = info.Height;
+
+ if (width <= 0 || height <= 0)
+ {
+ width = null;
+ height = null;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting image information for {Item}", item.Name);
+ }
+
+ try
+ {
+ return new ImageInfo
+ {
+ Path = info.Path,
+ ImageIndex = imageIndex,
+ ImageType = info.Type,
+ ImageTag = _imageProcessor.GetImageCacheTag(item, info),
+ Size = length,
+ BlurHash = blurhash,
+ Width = width,
+ Height = height
+ };
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting image information for {Path}", info.Path);
+ return null;
+ }
+ }
+
+ private async Task<ActionResult> GetImageInternal(
+ Guid itemId,
+ ImageType imageType,
+ int? imageIndex,
+ string? tag,
+ ImageFormat? format,
+ int? maxWidth,
+ int? maxHeight,
+ double? percentPlayed,
+ int? unplayedCount,
+ int? width,
+ int? height,
+ int? quality,
+ int? fillWidth,
+ int? fillHeight,
+ bool? addPlayedIndicator,
+ int? blur,
+ string? backgroundColor,
+ string? foregroundLayer,
+ BaseItem? item,
+ bool isHeadRequest,
+ ItemImageInfo? imageInfo = null)
+ {
+ if (percentPlayed.HasValue)
+ {
+ if (percentPlayed.Value <= 0)
+ {
+ percentPlayed = null;
+ }
+ else if (percentPlayed.Value >= 100)
+ {
+ percentPlayed = null;
+ addPlayedIndicator = true;
+ }
+ }
+
+ if (percentPlayed.HasValue)
+ {
+ unplayedCount = null;
+ }
+
+ if (unplayedCount.HasValue
+ && unplayedCount.Value <= 0)
+ {
+ unplayedCount = null;
+ }
+
+ if (imageInfo == null)
+ {
+ imageInfo = item?.GetImageInfo(imageType, imageIndex ?? 0);
+ if (imageInfo == null)
+ {
+ return NotFound(string.Format(NumberFormatInfo.InvariantInfo, "{0} does not have an image of type {1}", item?.Name, imageType));
+ }
+ }
+
+ var outputFormats = GetOutputFormats(format);
+
+ TimeSpan? cacheDuration = null;
+
+ if (!string.IsNullOrEmpty(tag))
+ {
+ cacheDuration = TimeSpan.FromDays(365);
+ }
+
+ var responseHeaders = new Dictionary<string, string>
+ {
+ { "transferMode.dlna.org", "Interactive" },
+ { "realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*" }
+ };
+
+ return await GetImageResult(
+ item,
+ itemId,
+ imageIndex,
+ width,
+ height,
+ maxWidth,
+ maxHeight,
+ fillWidth,
+ fillHeight,
+ quality,
+ addPlayedIndicator,
+ percentPlayed,
+ unplayedCount,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ imageInfo,
+ outputFormats,
+ cacheDuration,
+ responseHeaders,
+ isHeadRequest).ConfigureAwait(false);
+ }
+
+ private ImageFormat[] GetOutputFormats(ImageFormat? format)
+ {
+ if (format.HasValue)
+ {
+ return new[] { format.Value };
+ }
+
+ return GetClientSupportedFormats();
+ }
+
+ private ImageFormat[] GetClientSupportedFormats()
+ {
+ var supportedFormats = Request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
+ for (var i = 0; i < supportedFormats.Length; i++)
+ {
+ // Remove charsets etc. (anything after semi-colon)
+ var type = supportedFormats[i];
+ int index = type.IndexOf(';', StringComparison.Ordinal);
+ if (index != -1)
+ {
+ supportedFormats[i] = type.Substring(0, index);
+ }
+ }
+
+ var acceptParam = Request.Query[HeaderNames.Accept];
+
+ var supportsWebP = SupportsFormat(supportedFormats, acceptParam, ImageFormat.Webp, false);
+
+ if (!supportsWebP)
+ {
+ var userAgent = Request.Headers[HeaderNames.UserAgent].ToString();
+ if (userAgent.IndexOf("crosswalk", StringComparison.OrdinalIgnoreCase) != -1 &&
+ userAgent.IndexOf("android", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ supportsWebP = true;
+ }
+ }
+
+ var formats = new List<ImageFormat>(4);
+
+ if (supportsWebP)
+ {
+ formats.Add(ImageFormat.Webp);
+ }
+
+ formats.Add(ImageFormat.Jpg);
+ formats.Add(ImageFormat.Png);
+
+ if (SupportsFormat(supportedFormats, acceptParam, ImageFormat.Gif, true))
+ {
+ formats.Add(ImageFormat.Gif);
+ }
+
+ return formats.ToArray();
+ }
+
+ private bool SupportsFormat(IReadOnlyCollection<string> requestAcceptTypes, string acceptParam, ImageFormat format, bool acceptAll)
+ {
+ var normalized = format.ToString().ToLowerInvariant();
+ var mimeType = "image/" + normalized;
+
+ if (requestAcceptTypes.Contains(mimeType))
+ {
+ return true;
+ }
+
+ if (acceptAll && requestAcceptTypes.Contains("*/*"))
+ {
+ return true;
+ }
+
+ return string.Equals(acceptParam, normalized, StringComparison.OrdinalIgnoreCase);
+ }
+
+ private async Task<ActionResult> GetImageResult(
+ BaseItem? item,
+ Guid itemId,
+ int? index,
+ int? width,
+ int? height,
+ int? maxWidth,
+ int? maxHeight,
+ int? fillWidth,
+ int? fillHeight,
+ int? quality,
+ bool? addPlayedIndicator,
+ double? percentPlayed,
+ int? unplayedCount,
+ int? blur,
+ string? backgroundColor,
+ string? foregroundLayer,
+ ItemImageInfo imageInfo,
+ IReadOnlyCollection<ImageFormat> supportedFormats,
+ TimeSpan? cacheDuration,
+ IDictionary<string, string> headers,
+ bool isHeadRequest)
+ {
+ if (!imageInfo.IsLocalFile && item != null)
+ {
+ imageInfo = await _libraryManager.ConvertImageToLocal(item, imageInfo, index ?? 0).ConfigureAwait(false);
+ }
+
+ var options = new ImageProcessingOptions
+ {
+ Height = height,
+ ImageIndex = index ?? 0,
+ Image = imageInfo,
+ Item = item,
+ ItemId = itemId,
+ MaxHeight = maxHeight,
+ MaxWidth = maxWidth,
+ FillHeight = fillHeight,
+ FillWidth = fillWidth,
+ Quality = quality ?? 100,
+ Width = width,
+ AddPlayedIndicator = addPlayedIndicator ?? false,
+ PercentPlayed = percentPlayed ?? 0,
+ UnplayedCount = unplayedCount,
+ Blur = blur,
+ BackgroundColor = backgroundColor,
+ ForegroundLayer = foregroundLayer,
+ SupportedOutputFormats = supportedFormats
+ };
+
+ var (imagePath, imageContentType, dateImageModified) = await _imageProcessor.ProcessImage(options).ConfigureAwait(false);
+
+ var disableCaching = Request.Headers[HeaderNames.CacheControl].Contains("no-cache");
+ var parsingSuccessful = DateTime.TryParse(Request.Headers[HeaderNames.IfModifiedSince], out var ifModifiedSinceHeader);
+
+ // if the parsing of the IfModifiedSince header was not successful, disable caching
+ if (!parsingSuccessful)
+ {
+ // disableCaching = true;
+ }
+
+ foreach (var (key, value) in headers)
+ {
+ Response.Headers.Add(key, value);
+ }
+
+ Response.ContentType = imageContentType ?? MediaTypeNames.Text.Plain;
+ Response.Headers.Add(HeaderNames.Age, Convert.ToInt64((DateTime.UtcNow - dateImageModified).TotalSeconds).ToString(CultureInfo.InvariantCulture));
+ Response.Headers.Add(HeaderNames.Vary, HeaderNames.Accept);
+
+ if (disableCaching)
+ {
+ Response.Headers.Add(HeaderNames.CacheControl, "no-cache, no-store, must-revalidate");
+ Response.Headers.Add(HeaderNames.Pragma, "no-cache, no-store, must-revalidate");
+ }
+ else
+ {
+ if (cacheDuration.HasValue)
+ {
+ Response.Headers.Add(HeaderNames.CacheControl, "public, max-age=" + cacheDuration.Value.TotalSeconds);
+ }
+ else
+ {
+ Response.Headers.Add(HeaderNames.CacheControl, "public");
+ }
+
+ Response.Headers.Add(HeaderNames.LastModified, dateImageModified.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss \"GMT\"", CultureInfo.InvariantCulture));
+
+ // if the image was not modified since "ifModifiedSinceHeader"-header, return a HTTP status code 304 not modified
+ if (!(dateImageModified > ifModifiedSinceHeader) && cacheDuration.HasValue)
+ {
+ if (ifModifiedSinceHeader.Add(cacheDuration.Value) < DateTime.UtcNow)
+ {
+ Response.StatusCode = StatusCodes.Status304NotModified;
+ return new ContentResult();
+ }
+ }
+ }
+
+ // if the request is a head request, return a NoContent result with the same headers as it would with a GET request
+ if (isHeadRequest)
+ {
+ return NoContent();
+ }
+
+ return PhysicalFile(imagePath, imageContentType ?? MediaTypeNames.Text.Plain);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs
new file mode 100644
index 000000000..a6c2e07c9
--- /dev/null
+++ b/Jellyfin.Api/Controllers/InstantMixController.cs
@@ -0,0 +1,361 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Playlists;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The instant mix controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class InstantMixController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IMusicManager _musicManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InstantMixController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="musicManager">Instance of the <see cref="IMusicManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public InstantMixController(
+ IUserManager userManager,
+ IDtoService dtoService,
+ IMusicManager musicManager,
+ ILibraryManager libraryManager)
+ {
+ _userManager = userManager;
+ _dtoService = dtoService;
+ _musicManager = musicManager;
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given song.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Songs/{id}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromSong(
+ [FromRoute, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var item = _libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given album.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Albums/{id}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromAlbum(
+ [FromRoute, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var album = _libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(album, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given playlist.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Playlists/{id}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromPlaylist(
+ [FromRoute, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var playlist = (Playlist)_libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(playlist, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given genre.
+ /// </summary>
+ /// <param name="name">The genre name.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("MusicGenres/{name}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromMusicGenreByName(
+ [FromRoute, Required] string name,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromGenres(new[] { name }, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given artist.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Artists/{id}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromArtists(
+ [FromRoute, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var item = _libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given item.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Items/{id}/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromItem(
+ [FromRoute, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var item = _libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given artist.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("Artists/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Use GetInstantMixFromArtists")]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromArtists2(
+ [FromQuery, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ return GetInstantMixFromArtists(
+ id,
+ userId,
+ limit,
+ fields,
+ enableImages,
+ enableUserData,
+ imageTypeLimit,
+ enableImageTypes);
+ }
+
+ /// <summary>
+ /// Creates an instant playlist based on a given genre.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Instant playlist returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns>
+ [HttpGet("MusicGenres/InstantMix")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromMusicGenreById(
+ [FromQuery, Required] Guid id,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var item = _libraryManager.GetItemById(id);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
+ return GetResult(items, user, limit, dtoOptions);
+ }
+
+ private QueryResult<BaseItemDto> GetResult(List<BaseItem> items, User? user, int? limit, DtoOptions dtoOptions)
+ {
+ var list = items;
+
+ var result = new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = list.Count
+ };
+
+ if (limit.HasValue && limit < list.Count)
+ {
+ list = list.GetRange(0, limit.Value);
+ }
+
+ var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user);
+
+ result.Items = returnList;
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs
new file mode 100644
index 000000000..448510c06
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ItemLookupController.cs
@@ -0,0 +1,278 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Providers;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Item lookup controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ItemLookupController : BaseJellyfinApiController
+ {
+ private readonly IProviderManager _providerManager;
+ private readonly IServerApplicationPaths _appPaths;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<ItemLookupController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemLookupController"/> class.
+ /// </summary>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> 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="logger">Instance of the <see cref="ILogger{ItemLookupController}"/> interface.</param>
+ public ItemLookupController(
+ IProviderManager providerManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ ILogger<ItemLookupController> logger)
+ {
+ _providerManager = providerManager;
+ _appPaths = serverConfigurationManager.ApplicationPaths;
+ _fileSystem = fileSystem;
+ _libraryManager = libraryManager;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Get the item's external id info.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">External id info retrieved.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>List of external id info.</returns>
+ [HttpGet("Items/{itemId}/ExternalIdInfos")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<IEnumerable<ExternalIdInfo>> GetExternalIdInfos([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return Ok(_providerManager.GetExternalIdInfos(item));
+ }
+
+ /// <summary>
+ /// Get movie remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Movie remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Movie")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMovieRemoteSearchResults([FromBody, Required] RemoteSearchQuery<MovieInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<Movie, MovieInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get trailer remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Trailer remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Trailer")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetTrailerRemoteSearchResults([FromBody, Required] RemoteSearchQuery<TrailerInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<Trailer, TrailerInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get music video remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Music video remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/MusicVideo")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicVideoRemoteSearchResults([FromBody, Required] RemoteSearchQuery<MusicVideoInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<MusicVideo, MusicVideoInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get series remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Series remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Series")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetSeriesRemoteSearchResults([FromBody, Required] RemoteSearchQuery<SeriesInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get box set remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Box set remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/BoxSet")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBoxSetRemoteSearchResults([FromBody, Required] RemoteSearchQuery<BoxSetInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<BoxSet, BoxSetInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get music artist remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Music artist remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/MusicArtist")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicArtistRemoteSearchResults([FromBody, Required] RemoteSearchQuery<ArtistInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<MusicArtist, ArtistInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get music album remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Music album remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/MusicAlbum")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicAlbumRemoteSearchResults([FromBody, Required] RemoteSearchQuery<AlbumInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<MusicAlbum, AlbumInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get person remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Person remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Person")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetPersonRemoteSearchResults([FromBody, Required] RemoteSearchQuery<PersonLookupInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<Person, PersonLookupInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Get book remote search.
+ /// </summary>
+ /// <param name="query">Remote search query.</param>
+ /// <response code="200">Book remote search executed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Book")]
+ public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBookRemoteSearchResults([FromBody, Required] RemoteSearchQuery<BookInfo> query)
+ {
+ var results = await _providerManager.GetRemoteSearchResults<Book, BookInfo>(query, CancellationToken.None)
+ .ConfigureAwait(false);
+ return Ok(results);
+ }
+
+ /// <summary>
+ /// Applies search criteria to an item and refreshes metadata.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="searchResult">The remote search result.</param>
+ /// <param name="replaceAllImages">Optional. Whether or not to replace all images. Default: True.</param>
+ /// <response code="204">Item metadata refreshed.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
+ /// The task result contains an <see cref="NoContentResult"/>.
+ /// </returns>
+ [HttpPost("Items/RemoteSearch/Apply/{itemId}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ApplySearchCriteria(
+ [FromRoute, Required] Guid itemId,
+ [FromBody, Required] RemoteSearchResult searchResult,
+ [FromQuery] bool replaceAllImages = true)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ _logger.LogInformation(
+ "Setting provider id's to item {0}-{1}: {2}",
+ item.Id,
+ item.Name,
+ JsonSerializer.Serialize(searchResult.ProviderIds));
+
+ // Since the refresh process won't erase provider Ids, we need to set this explicitly now.
+ item.ProviderIds = searchResult.ProviderIds;
+ await _providerManager.RefreshFullItem(
+ item,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
+ ImageRefreshMode = MetadataRefreshMode.FullRefresh,
+ ReplaceAllMetadata = true,
+ ReplaceAllImages = replaceAllImages,
+ SearchResult = searchResult
+ }, CancellationToken.None).ConfigureAwait(false);
+
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ItemRefreshController.cs b/Jellyfin.Api/Controllers/ItemRefreshController.cs
new file mode 100644
index 000000000..49865eb5e
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ItemRefreshController.cs
@@ -0,0 +1,86 @@
+using System;
+using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Item Refresh Controller.
+ /// </summary>
+ [Route("Items")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ItemRefreshController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IProviderManager _providerManager;
+ private readonly IFileSystem _fileSystem;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemRefreshController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="providerManager">Instance of <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
+ public ItemRefreshController(
+ ILibraryManager libraryManager,
+ IProviderManager providerManager,
+ IFileSystem fileSystem)
+ {
+ _libraryManager = libraryManager;
+ _providerManager = providerManager;
+ _fileSystem = fileSystem;
+ }
+
+ /// <summary>
+ /// Refreshes metadata for an item.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="metadataRefreshMode">(Optional) Specifies the metadata refresh mode.</param>
+ /// <param name="imageRefreshMode">(Optional) Specifies the image refresh mode.</param>
+ /// <param name="replaceAllMetadata">(Optional) Determines if metadata should be replaced. Only applicable if mode is FullRefresh.</param>
+ /// <param name="replaceAllImages">(Optional) Determines if images should be replaced. Only applicable if mode is FullRefresh.</param>
+ /// <response code="204">Item metadata refresh queued.</response>
+ /// <response code="404">Item to refresh not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
+ [HttpPost("{itemId}/Refresh")]
+ [Description("Refreshes metadata for an item.")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult Post(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] MetadataRefreshMode metadataRefreshMode = MetadataRefreshMode.None,
+ [FromQuery] MetadataRefreshMode imageRefreshMode = MetadataRefreshMode.None,
+ [FromQuery] bool replaceAllMetadata = false,
+ [FromQuery] bool replaceAllImages = false)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var refreshOptions = new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ MetadataRefreshMode = metadataRefreshMode,
+ ImageRefreshMode = imageRefreshMode,
+ ReplaceAllImages = replaceAllImages,
+ ReplaceAllMetadata = replaceAllMetadata,
+ ForceSave = metadataRefreshMode == MetadataRefreshMode.FullRefresh
+ || imageRefreshMode == MetadataRefreshMode.FullRefresh
+ || replaceAllImages
+ || replaceAllMetadata,
+ IsAutomated = false
+ };
+
+ _providerManager.QueueRefresh(item.Id, refreshOptions, RefreshPriority.High);
+ return NoContent();
+ }
+ }
+}
diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/Jellyfin.Api/Controllers/ItemUpdateController.cs
index 825732888..fd137f98f 100644
--- a/MediaBrowser.Api/ItemUpdateService.cs
+++ b/Jellyfin.Api/Controllers/ItemUpdateController.cs
@@ -1,243 +1,227 @@
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 MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
-namespace MediaBrowser.Api
+namespace Jellyfin.Api.Controllers
{
- [Route("/Items/{ItemId}", "POST", Summary = "Updates an item")]
- public class UpdateItem : BaseItemDto, IReturnVoid
- {
- [ApiMember(Name = "ItemId", Description = "The id of the item", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string ItemId { get; set; }
- }
-
- [Route("/Items/{ItemId}/MetadataEditor", "GET", Summary = "Gets metadata editor info for an item")]
- public class GetMetadataEditorInfo : IReturn<MetadataEditorInfo>
- {
- [ApiMember(Name = "ItemId", Description = "The id of the item", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string ItemId { get; set; }
- }
-
- [Route("/Items/{ItemId}/ContentType", "POST", Summary = "Updates an item's content type")]
- public class UpdateItemContentType : IReturnVoid
- {
- [ApiMember(Name = "ItemId", Description = "The id of the item", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid ItemId { get; set; }
-
- [ApiMember(Name = "ContentType", Description = "The content type of the item", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ContentType { get; set; }
- }
-
- [Authenticated(Roles = "admin")]
- public class ItemUpdateService : BaseApiService
+ /// <summary>
+ /// Item update controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public class ItemUpdateController : BaseJellyfinApiController
{
private readonly ILibraryManager _libraryManager;
private readonly IProviderManager _providerManager;
private readonly ILocalizationManager _localizationManager;
- private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
-
- public ItemUpdateService(IFileSystem fileSystem, ILibraryManager libraryManager, IProviderManager providerManager, ILocalizationManager localizationManager, IServerConfigurationManager config)
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemUpdateController"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public ItemUpdateController(
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IProviderManager providerManager,
+ ILocalizationManager localizationManager,
+ IServerConfigurationManager serverConfigurationManager)
{
_libraryManager = libraryManager;
_providerManager = providerManager;
_localizationManager = localizationManager;
- _config = config;
_fileSystem = fileSystem;
+ _serverConfigurationManager = serverConfigurationManager;
}
- public async Task<object> Get(GetMetadataEditorInfo request)
+ /// <summary>
+ /// Updates an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="request">The new item properties.</param>
+ /// <response code="204">Item updated.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
+ [HttpPost("Items/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> UpdateItem([FromRoute, Required] Guid itemId, [FromBody, Required] BaseItemDto request)
{
- var item = _libraryManager.GetItemById(request.ItemId);
-
- var info = new MetadataEditorInfo
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
{
- ParentalRatingOptions = _localizationManager.GetParentalRatings().ToArray(),
- ExternalIdInfos = _providerManager.GetExternalIdInfos(item).ToArray(),
- Countries = await _localizationManager.GetCountries(),
- Cultures = _localizationManager.GetCultures()
- };
+ return NotFound();
+ }
- if (!item.IsVirtualItem && !(item is ICollectionFolder) && !(item is UserView) && !(item is AggregateFolder) && !(item is LiveTvChannel) && !(item is IItemByName) &&
- item.SourceType == SourceType.Library)
- {
- var inheritedContentType = _libraryManager.GetInheritedContentType(item);
- var configuredContentType = _libraryManager.GetConfiguredContentType(item);
+ var newLockData = request.LockData ?? false;
+ var isLockedChanged = item.IsLocked != newLockData;
- if (string.IsNullOrWhiteSpace(inheritedContentType) || !string.IsNullOrWhiteSpace(configuredContentType))
- {
- info.ContentTypeOptions = GetContentTypeOptions(true).ToArray();
- info.ContentType = configuredContentType;
+ var series = item as Series;
+ var displayOrderChanged = series != null && !string.Equals(
+ series.DisplayOrder ?? string.Empty,
+ request.DisplayOrder ?? string.Empty,
+ StringComparison.OrdinalIgnoreCase);
- if (string.IsNullOrWhiteSpace(inheritedContentType) || string.Equals(inheritedContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
+ // Do this first so that metadata savers can pull the updates from the database.
+ if (request.People != null)
+ {
+ _libraryManager.UpdatePeople(
+ item,
+ request.People.Select(x => new PersonInfo
{
- info.ContentTypeOptions = info.ContentTypeOptions
- .Where(i => string.IsNullOrWhiteSpace(i.Value) || string.Equals(i.Value, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
- .ToArray();
- }
- }
+ Name = x.Name,
+ Role = x.Role,
+ Type = x.Type
+ }).ToList());
}
- return ToOptimizedResult(info);
- }
+ UpdateItem(request, item);
- public void Post(UpdateItemContentType request)
- {
- var item = _libraryManager.GetItemById(request.ItemId);
- var path = item.ContainingFolderPath;
+ item.OnMetadataChanged();
- var types = _config.Configuration.ContentTypes
- .Where(i => !string.IsNullOrWhiteSpace(i.Name))
- .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
- .ToList();
+ await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
- if (!string.IsNullOrWhiteSpace(request.ContentType))
+ if (isLockedChanged && item.IsFolder)
{
- types.Add(new NameValuePair
+ var folder = (Folder)item;
+
+ foreach (var child in folder.GetRecursiveChildren())
{
- Name = path,
- Value = request.ContentType
- });
+ child.IsLocked = newLockData;
+ await child.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ }
}
- _config.Configuration.ContentTypes = types.ToArray();
- _config.SaveConfiguration();
- }
-
- private List<NameValuePair> GetContentTypeOptions(bool isForItem)
- {
- var list = new List<NameValuePair>();
-
- if (isForItem)
+ if (displayOrderChanged)
{
- list.Add(new NameValuePair
- {
- Name = "Inherit",
- Value = ""
- });
+ _providerManager.QueueRefresh(
+ series!.Id,
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
+ ImageRefreshMode = MetadataRefreshMode.FullRefresh,
+ ReplaceAllMetadata = true
+ },
+ RefreshPriority.High);
}
- list.Add(new NameValuePair
- {
- Name = "Movies",
- Value = "movies"
- });
- list.Add(new NameValuePair
- {
- Name = "Music",
- Value = "music"
- });
- list.Add(new NameValuePair
- {
- Name = "Shows",
- Value = "tvshows"
- });
+ return NoContent();
+ }
- if (!isForItem)
- {
- list.Add(new NameValuePair
- {
- Name = "Books",
- Value = "books"
- });
- }
+ /// <summary>
+ /// Gets metadata editor info for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="200">Item metadata editor returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>An <see cref="OkResult"/> on success containing the metadata editor, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
+ [HttpGet("Items/{itemId}/MetadataEditor")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<MetadataEditorInfo> GetMetadataEditorInfo([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
- list.Add(new NameValuePair
- {
- Name = "HomeVideos",
- Value = "homevideos"
- });
- list.Add(new NameValuePair
- {
- Name = "MusicVideos",
- Value = "musicvideos"
- });
- list.Add(new NameValuePair
+ var info = new MetadataEditorInfo
{
- Name = "Photos",
- Value = "photos"
- });
+ ParentalRatingOptions = _localizationManager.GetParentalRatings().ToArray(),
+ ExternalIdInfos = _providerManager.GetExternalIdInfos(item).ToArray(),
+ Countries = _localizationManager.GetCountries().ToArray(),
+ Cultures = _localizationManager.GetCultures().ToArray()
+ };
- if (!isForItem)
+ if (!item.IsVirtualItem
+ && item is not ICollectionFolder
+ && item is not UserView
+ && item is not AggregateFolder
+ && item is not LiveTvChannel
+ && item is not IItemByName
+ && item.SourceType == SourceType.Library)
{
- list.Add(new NameValuePair
+ var inheritedContentType = _libraryManager.GetInheritedContentType(item);
+ var configuredContentType = _libraryManager.GetConfiguredContentType(item);
+
+ if (string.IsNullOrWhiteSpace(inheritedContentType) ||
+ !string.IsNullOrWhiteSpace(configuredContentType))
{
- Name = "MixedContent",
- Value = ""
- });
- }
+ info.ContentTypeOptions = GetContentTypeOptions(true).ToArray();
+ info.ContentType = configuredContentType;
- foreach (var val in list)
- {
- val.Name = _localizationManager.GetLocalizedString(val.Name);
+ if (string.IsNullOrWhiteSpace(inheritedContentType)
+ || string.Equals(inheritedContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
+ {
+ info.ContentTypeOptions = info.ContentTypeOptions
+ .Where(i => string.IsNullOrWhiteSpace(i.Value)
+ || string.Equals(i.Value, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+ }
+ }
}
- return list;
+ return info;
}
- public void Post(UpdateItem request)
+ /// <summary>
+ /// Updates an item's content type.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="contentType">The content type of the item.</param>
+ /// <response code="204">Item content type updated.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
+ [HttpPost("Items/{itemId}/ContentType")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string? contentType)
{
- var item = _libraryManager.GetItemById(request.ItemId);
-
- var newLockData = request.LockData ?? false;
- var isLockedChanged = item.IsLocked != newLockData;
-
- var series = item as Series;
- var displayOrderChanged = series != null && !string.Equals(series.DisplayOrder ?? string.Empty, request.DisplayOrder ?? string.Empty, StringComparison.OrdinalIgnoreCase);
-
- // Do this first so that metadata savers can pull the updates from the database.
- if (request.People != null)
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
{
- _libraryManager.UpdatePeople(item, request.People.Select(x => new PersonInfo { Name = x.Name, Role = x.Role, Type = x.Type }).ToList());
+ return NotFound();
}
- UpdateItem(request, item);
-
- item.OnMetadataChanged();
-
- item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
-
- if (isLockedChanged && item.IsFolder)
- {
- var folder = (Folder)item;
+ var path = item.ContainingFolderPath;
- foreach (var child in folder.GetRecursiveChildren())
- {
- child.IsLocked = newLockData;
- child.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- }
- }
+ var types = _serverConfigurationManager.Configuration.ContentTypes
+ .Where(i => !string.IsNullOrWhiteSpace(i.Name))
+ .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
+ .ToList();
- if (displayOrderChanged)
+ if (!string.IsNullOrWhiteSpace(contentType))
{
- _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
+ types.Add(new NameValuePair
{
- MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
- ImageRefreshMode = MetadataRefreshMode.FullRefresh,
- ReplaceAllMetadata = true
-
- }, RefreshPriority.High);
+ Name = path,
+ Value = contentType
+ });
}
- }
- private DateTime NormalizeDateTime(DateTime val)
- {
- return DateTime.SpecifyKind(val, DateTimeKind.Utc);
+ _serverConfigurationManager.Configuration.ContentTypes = types.ToArray();
+ _serverConfigurationManager.SaveConfiguration();
+ return NoContent();
}
private void UpdateItem(BaseItemDto request, BaseItem item)
@@ -255,8 +239,7 @@ namespace MediaBrowser.Api
item.Overview = request.Overview;
item.Genres = request.Genres;
- var episode = item as Episode;
- if (episode != null)
+ if (item is Episode episode)
{
episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber;
episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
@@ -280,8 +263,8 @@ namespace MediaBrowser.Api
item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
}
- item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : (DateTime?)null;
- item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : (DateTime?)null;
+ item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : null;
+ item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : null;
item.ProductionYear = request.ProductionYear;
item.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
item.CustomRating = request.CustomRating;
@@ -294,14 +277,12 @@ namespace MediaBrowser.Api
item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
item.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null)
+ if (item is IHasDisplayOrder hasDisplayOrder)
{
hasDisplayOrder.DisplayOrder = request.DisplayOrder;
}
- var hasAspectRatio = item as IHasAspectRatio;
- if (hasAspectRatio != null)
+ if (item is IHasAspectRatio hasAspectRatio)
{
hasAspectRatio.AspectRatio = request.AspectRatio;
}
@@ -329,16 +310,14 @@ namespace MediaBrowser.Api
item.ProviderIds = request.ProviderIds;
- var video = item as Video;
- if (video != null)
+ if (item is Video video)
{
video.Video3DFormat = request.Video3DFormat;
}
if (request.AlbumArtists != null)
{
- var hasAlbumArtists = item as IHasAlbumArtist;
- if (hasAlbumArtists != null)
+ if (item is IHasAlbumArtist hasAlbumArtists)
{
hasAlbumArtists.AlbumArtists = request
.AlbumArtists
@@ -349,8 +328,7 @@ namespace MediaBrowser.Api
if (request.ArtistItems != null)
{
- var hasArtists = item as IHasArtist;
- if (hasArtists != null)
+ if (item is IHasArtist hasArtists)
{
hasArtists.Artists = request
.ArtistItems
@@ -359,27 +337,25 @@ namespace MediaBrowser.Api
}
}
- var song = item as Audio;
- if (song != null)
+ switch (item)
{
- song.Album = request.Album;
- }
-
- var musicVideo = item as MusicVideo;
- if (musicVideo != null)
- {
- musicVideo.Album = request.Album;
- }
+ case Audio song:
+ song.Album = request.Album;
+ break;
+ case MusicVideo musicVideo:
+ musicVideo.Album = request.Album;
+ break;
+ case Series series:
+ {
+ series.Status = GetSeriesStatus(request);
- var series = item as Series;
- if (series != null)
- {
- series.Status = GetSeriesStatus(request);
+ if (request.AirDays != null)
+ {
+ series.AirDays = request.AirDays;
+ series.AirTime = request.AirTime;
+ }
- if (request.AirDays != null)
- {
- series.AirDays = request.AirDays;
- series.AirTime = request.AirTime;
+ break;
}
}
}
@@ -392,7 +368,82 @@ namespace MediaBrowser.Api
}
return (SeriesStatus)Enum.Parse(typeof(SeriesStatus), item.Status, true);
+ }
+
+ private DateTime NormalizeDateTime(DateTime val)
+ {
+ return DateTime.SpecifyKind(val, DateTimeKind.Utc);
+ }
+ private List<NameValuePair> GetContentTypeOptions(bool isForItem)
+ {
+ var list = new List<NameValuePair>();
+
+ if (isForItem)
+ {
+ list.Add(new NameValuePair
+ {
+ Name = "Inherit",
+ Value = string.Empty
+ });
+ }
+
+ list.Add(new NameValuePair
+ {
+ Name = "Movies",
+ Value = "movies"
+ });
+ list.Add(new NameValuePair
+ {
+ Name = "Music",
+ Value = "music"
+ });
+ list.Add(new NameValuePair
+ {
+ Name = "Shows",
+ Value = "tvshows"
+ });
+
+ if (!isForItem)
+ {
+ list.Add(new NameValuePair
+ {
+ Name = "Books",
+ Value = "books"
+ });
+ }
+
+ list.Add(new NameValuePair
+ {
+ Name = "HomeVideos",
+ Value = "homevideos"
+ });
+ list.Add(new NameValuePair
+ {
+ Name = "MusicVideos",
+ Value = "musicvideos"
+ });
+ list.Add(new NameValuePair
+ {
+ Name = "Photos",
+ Value = "photos"
+ });
+
+ if (!isForItem)
+ {
+ list.Add(new NameValuePair
+ {
+ Name = "MixedContent",
+ Value = string.Empty
+ });
+ }
+
+ foreach (var val in list)
+ {
+ val.Name = _localizationManager.GetLocalizedString(val.Name);
+ }
+
+ return list;
}
}
}
diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs
new file mode 100644
index 000000000..f0d44e5cc
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ItemsController.cs
@@ -0,0 +1,833 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The items controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ItemsController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILocalizationManager _localization;
+ private readonly IDtoService _dtoService;
+ private readonly ILogger<ItemsController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemsController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ public ItemsController(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ ILocalizationManager localization,
+ IDtoService dtoService,
+ ILogger<ItemsController> logger)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _localization = localization;
+ _dtoService = dtoService;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Gets items based on a query.
+ /// </summary>
+ /// <param name="userId">The user id supplied as query parameter.</param>
+ /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
+ /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
+ /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
+ /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
+ /// <param name="hasTrailer">Optional filter by items with trailers.</param>
+ /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
+ /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
+ /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
+ /// <param name="isHd">Optional filter by items that are HD or not.</param>
+ /// <param name="is4K">Optional filter by items that are 4K or not.</param>
+ /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
+ /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
+ /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
+ /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
+ /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
+ /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
+ /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
+ /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
+ /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
+ /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
+ /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
+ /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
+ /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
+ /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
+ /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
+ /// <param name="searchTerm">Optional. Filter based on a search term.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
+ /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
+ /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
+ /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
+ /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
+ /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
+ /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
+ /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
+ /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
+ /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
+ /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
+ /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
+ /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
+ /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
+ /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
+ /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
+ /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="isLocked">Optional filter by items that are locked.</param>
+ /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
+ /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
+ /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
+ /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
+ /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
+ /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
+ /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
+ /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
+ /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
+ /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
+ /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
+ [HttpGet("Items")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetItems(
+ [FromQuery] Guid userId,
+ [FromQuery] string? maxOfficialRating,
+ [FromQuery] bool? hasThemeSong,
+ [FromQuery] bool? hasThemeVideo,
+ [FromQuery] bool? hasSubtitles,
+ [FromQuery] bool? hasSpecialFeature,
+ [FromQuery] bool? hasTrailer,
+ [FromQuery] string? adjacentTo,
+ [FromQuery] int? parentIndexNumber,
+ [FromQuery] bool? hasParentalRating,
+ [FromQuery] bool? isHd,
+ [FromQuery] bool? is4K,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
+ [FromQuery] bool? isMissing,
+ [FromQuery] bool? isUnaired,
+ [FromQuery] double? minCommunityRating,
+ [FromQuery] double? minCriticRating,
+ [FromQuery] DateTime? minPremiereDate,
+ [FromQuery] DateTime? minDateLastSaved,
+ [FromQuery] DateTime? minDateLastSavedForUser,
+ [FromQuery] DateTime? maxPremiereDate,
+ [FromQuery] bool? hasOverview,
+ [FromQuery] bool? hasImdbId,
+ [FromQuery] bool? hasTmdbId,
+ [FromQuery] bool? hasTvdbId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool? recursive,
+ [FromQuery] string? searchTerm,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery] bool? isPlayed,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? person,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
+ [FromQuery] string? minOfficialRating,
+ [FromQuery] bool? isLocked,
+ [FromQuery] bool? isPlaceHolder,
+ [FromQuery] bool? hasOfficialRating,
+ [FromQuery] bool? collapseBoxSetItems,
+ [FromQuery] int? minWidth,
+ [FromQuery] int? minHeight,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] bool? is3D,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool? enableImages = true)
+ {
+ var user = !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ if (includeItemTypes.Length == 1
+ && (includeItemTypes[0] == BaseItemKind.Playlist
+ || includeItemTypes[0] == BaseItemKind.BoxSet))
+ {
+ parentId = null;
+ }
+
+ var item = _libraryManager.GetParentItem(parentId, userId);
+ QueryResult<BaseItem> result;
+
+ if (item is not Folder folder)
+ {
+ folder = _libraryManager.GetUserRootFolder();
+ }
+
+ string? collectionType = null;
+ if (folder is IHasCollectionType hasCollectionType)
+ {
+ collectionType = hasCollectionType.CollectionType;
+ }
+
+ if (string.Equals(collectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
+ {
+ recursive = true;
+ includeItemTypes = new[] { BaseItemKind.Playlist };
+ }
+
+ var enabledChannels = user!.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels);
+
+ bool isInEnabledFolder = Array.IndexOf(user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders), item.Id) != -1
+ // Assume all folders inside an EnabledChannel are enabled
+ || Array.IndexOf(enabledChannels, item.Id) != -1
+ // Assume all items inside an EnabledChannel are enabled
+ || Array.IndexOf(enabledChannels, item.ChannelId) != -1;
+
+ var collectionFolders = _libraryManager.GetCollectionFolders(item);
+ foreach (var collectionFolder in collectionFolders)
+ {
+ if (user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(collectionFolder.Id))
+ {
+ isInEnabledFolder = true;
+ }
+ }
+
+ if (item is not UserRootFolder
+ && !isInEnabledFolder
+ && !user.HasPermission(PermissionKind.EnableAllFolders)
+ && !user.HasPermission(PermissionKind.EnableAllChannels)
+ && !string.Equals(collectionType, CollectionType.Folders, StringComparison.OrdinalIgnoreCase))
+ {
+ _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}.", user.Username, item.Name);
+ return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}.");
+ }
+
+ if ((recursive.HasValue && recursive.Value) || ids.Length != 0 || item is not UserRootFolder)
+ {
+ var query = new InternalItemsQuery(user)
+ {
+ IsPlayed = isPlayed,
+ MediaTypes = mediaTypes,
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ Recursive = recursive ?? false,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
+ IsFavorite = isFavorite,
+ Limit = limit,
+ StartIndex = startIndex,
+ IsMissing = isMissing,
+ IsUnaired = isUnaired,
+ CollapseBoxSetItems = collapseBoxSetItems,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ HasImdbId = hasImdbId,
+ IsPlaceHolder = isPlaceHolder,
+ IsLocked = isLocked,
+ MinWidth = minWidth,
+ MinHeight = minHeight,
+ MaxWidth = maxWidth,
+ MaxHeight = maxHeight,
+ Is3D = is3D,
+ HasTvdbId = hasTvdbId,
+ HasTmdbId = hasTmdbId,
+ HasOverview = hasOverview,
+ HasOfficialRating = hasOfficialRating,
+ HasParentalRating = hasParentalRating,
+ HasSpecialFeature = hasSpecialFeature,
+ HasSubtitles = hasSubtitles,
+ HasThemeSong = hasThemeSong,
+ HasThemeVideo = hasThemeVideo,
+ HasTrailer = hasTrailer,
+ IsHD = isHd,
+ Is4K = is4K,
+ Tags = tags,
+ OfficialRatings = officialRatings,
+ Genres = genres,
+ ArtistIds = artistIds,
+ AlbumArtistIds = albumArtistIds,
+ ContributingArtistIds = contributingArtistIds,
+ GenreIds = genreIds,
+ StudioIds = studioIds,
+ Person = person,
+ PersonIds = personIds,
+ PersonTypes = personTypes,
+ Years = years,
+ ImageTypes = imageTypes,
+ VideoTypes = videoTypes,
+ AdjacentTo = adjacentTo,
+ ItemIds = ids,
+ MinCommunityRating = minCommunityRating,
+ MinCriticRating = minCriticRating,
+ ParentId = parentId ?? Guid.Empty,
+ ParentIndexNumber = parentIndexNumber,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ ExcludeItemIds = excludeItemIds,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ MinDateLastSaved = minDateLastSaved?.ToUniversalTime(),
+ MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
+ MinPremiereDate = minPremiereDate?.ToUniversalTime(),
+ MaxPremiereDate = maxPremiereDate?.ToUniversalTime(),
+ };
+
+ if (ids.Length != 0 || !string.IsNullOrWhiteSpace(searchTerm))
+ {
+ query.CollapseBoxSetItems = false;
+ }
+
+ foreach (var filter in filters)
+ {
+ switch (filter)
+ {
+ case ItemFilter.Dislikes:
+ query.IsLiked = false;
+ break;
+ case ItemFilter.IsFavorite:
+ query.IsFavorite = true;
+ break;
+ case ItemFilter.IsFavoriteOrLikes:
+ query.IsFavoriteOrLiked = true;
+ break;
+ case ItemFilter.IsFolder:
+ query.IsFolder = true;
+ break;
+ case ItemFilter.IsNotFolder:
+ query.IsFolder = false;
+ break;
+ case ItemFilter.IsPlayed:
+ query.IsPlayed = true;
+ break;
+ case ItemFilter.IsResumable:
+ query.IsResumable = true;
+ break;
+ case ItemFilter.IsUnplayed:
+ query.IsPlayed = false;
+ break;
+ case ItemFilter.Likes:
+ query.IsLiked = true;
+ break;
+ }
+ }
+
+ // Filter by Series Status
+ if (seriesStatus.Length != 0)
+ {
+ query.SeriesStatuses = seriesStatus;
+ }
+
+ // ExcludeLocationTypes
+ if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
+ {
+ query.IsVirtualItem = false;
+ }
+
+ if (locationTypes.Length > 0 && locationTypes.Length < 4)
+ {
+ query.IsVirtualItem = locationTypes.Contains(LocationType.Virtual);
+ }
+
+ // Min official rating
+ if (!string.IsNullOrWhiteSpace(minOfficialRating))
+ {
+ query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
+ }
+
+ // Max official rating
+ if (!string.IsNullOrWhiteSpace(maxOfficialRating))
+ {
+ query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
+ }
+
+ // Artists
+ if (artists.Length != 0)
+ {
+ query.ArtistIds = artists.Select(i =>
+ {
+ try
+ {
+ return _libraryManager.GetArtist(i, new DtoOptions(false));
+ }
+ catch
+ {
+ return null;
+ }
+ }).Where(i => i != null).Select(i => i!.Id).ToArray();
+ }
+
+ // ExcludeArtistIds
+ if (excludeArtistIds.Length != 0)
+ {
+ query.ExcludeArtistIds = excludeArtistIds;
+ }
+
+ if (albumIds.Length != 0)
+ {
+ query.AlbumIds = albumIds;
+ }
+
+ // Albums
+ if (albums.Length != 0)
+ {
+ query.AlbumIds = albums.SelectMany(i =>
+ {
+ return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = i, Limit = 1 });
+ }).ToArray();
+ }
+
+ // Studios
+ if (studios.Length != 0)
+ {
+ query.StudioIds = studios.Select(i =>
+ {
+ try
+ {
+ return _libraryManager.GetStudio(i);
+ }
+ catch
+ {
+ return null;
+ }
+ }).Where(i => i != null).Select(i => i!.Id).ToArray();
+ }
+
+ // Apply default sorting if none requested
+ if (query.OrderBy.Count == 0)
+ {
+ // Albums by artist
+ if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase))
+ {
+ query.OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending), new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) };
+ }
+ }
+
+ result = folder.GetItems(query);
+ }
+ else
+ {
+ var itemsArray = folder.GetChildren(user, true);
+ result = new QueryResult<BaseItem> { Items = itemsArray, TotalRecordCount = itemsArray.Count, StartIndex = 0 };
+ }
+
+ return new QueryResult<BaseItemDto> { StartIndex = startIndex.GetValueOrDefault(), TotalRecordCount = result.TotalRecordCount, Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user) };
+ }
+
+ /// <summary>
+ /// Gets items based on a query.
+ /// </summary>
+ /// <param name="userId">The user id supplied as query parameter.</param>
+ /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
+ /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
+ /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
+ /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
+ /// <param name="hasTrailer">Optional filter by items with trailers.</param>
+ /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
+ /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
+ /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
+ /// <param name="isHd">Optional filter by items that are HD or not.</param>
+ /// <param name="is4K">Optional filter by items that are 4K or not.</param>
+ /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.</param>
+ /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimeted.</param>
+ /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
+ /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
+ /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
+ /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
+ /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
+ /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
+ /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
+ /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
+ /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
+ /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
+ /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
+ /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
+ /// <param name="excludeItemIds">Optional. If specified, results will be filtered by exxcluding item ids. This allows multiple, comma delimeted.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
+ /// <param name="searchTerm">Optional. Filter based on a search term.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
+ /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimeted.</param>
+ /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.</param>
+ /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.</param>
+ /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
+ /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
+ /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.</param>
+ /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimeted.</param>
+ /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimeted.</param>
+ /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
+ /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
+ /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
+ /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimeted.</param>
+ /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimeted.</param>
+ /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
+ /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.</param>
+ /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="isLocked">Optional filter by items that are locked.</param>
+ /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
+ /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
+ /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
+ /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
+ /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
+ /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
+ /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
+ /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
+ /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimeted.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimeted.</param>
+ /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimeted.</param>
+ /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
+ [HttpGet("Users/{userId}/Items")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetItemsByUserId(
+ [FromRoute] Guid userId,
+ [FromQuery] string? maxOfficialRating,
+ [FromQuery] bool? hasThemeSong,
+ [FromQuery] bool? hasThemeVideo,
+ [FromQuery] bool? hasSubtitles,
+ [FromQuery] bool? hasSpecialFeature,
+ [FromQuery] bool? hasTrailer,
+ [FromQuery] string? adjacentTo,
+ [FromQuery] int? parentIndexNumber,
+ [FromQuery] bool? hasParentalRating,
+ [FromQuery] bool? isHd,
+ [FromQuery] bool? is4K,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
+ [FromQuery] bool? isMissing,
+ [FromQuery] bool? isUnaired,
+ [FromQuery] double? minCommunityRating,
+ [FromQuery] double? minCriticRating,
+ [FromQuery] DateTime? minPremiereDate,
+ [FromQuery] DateTime? minDateLastSaved,
+ [FromQuery] DateTime? minDateLastSavedForUser,
+ [FromQuery] DateTime? maxPremiereDate,
+ [FromQuery] bool? hasOverview,
+ [FromQuery] bool? hasImdbId,
+ [FromQuery] bool? hasTmdbId,
+ [FromQuery] bool? hasTvdbId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool? recursive,
+ [FromQuery] string? searchTerm,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery] bool? isPlayed,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? person,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
+ [FromQuery] string? minOfficialRating,
+ [FromQuery] bool? isLocked,
+ [FromQuery] bool? isPlaceHolder,
+ [FromQuery] bool? hasOfficialRating,
+ [FromQuery] bool? collapseBoxSetItems,
+ [FromQuery] int? minWidth,
+ [FromQuery] int? minHeight,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] bool? is3D,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool? enableImages = true)
+ {
+ return GetItems(
+ userId,
+ maxOfficialRating,
+ hasThemeSong,
+ hasThemeVideo,
+ hasSubtitles,
+ hasSpecialFeature,
+ hasTrailer,
+ adjacentTo,
+ parentIndexNumber,
+ hasParentalRating,
+ isHd,
+ is4K,
+ locationTypes,
+ excludeLocationTypes,
+ isMissing,
+ isUnaired,
+ minCommunityRating,
+ minCriticRating,
+ minPremiereDate,
+ minDateLastSaved,
+ minDateLastSavedForUser,
+ maxPremiereDate,
+ hasOverview,
+ hasImdbId,
+ hasTmdbId,
+ hasTvdbId,
+ excludeItemIds,
+ startIndex,
+ limit,
+ recursive,
+ searchTerm,
+ sortOrder,
+ parentId,
+ fields,
+ excludeItemTypes,
+ includeItemTypes,
+ filters,
+ isFavorite,
+ mediaTypes,
+ imageTypes,
+ sortBy,
+ isPlayed,
+ genres,
+ officialRatings,
+ tags,
+ years,
+ enableUserData,
+ imageTypeLimit,
+ enableImageTypes,
+ person,
+ personIds,
+ personTypes,
+ studios,
+ artists,
+ excludeArtistIds,
+ artistIds,
+ albumArtistIds,
+ contributingArtistIds,
+ albums,
+ albumIds,
+ ids,
+ videoTypes,
+ minOfficialRating,
+ isLocked,
+ isPlaceHolder,
+ hasOfficialRating,
+ collapseBoxSetItems,
+ minWidth,
+ minHeight,
+ maxWidth,
+ maxHeight,
+ is3D,
+ seriesStatus,
+ nameStartsWithOrGreater,
+ nameStartsWith,
+ nameLessThan,
+ studioIds,
+ genreIds,
+ enableTotalRecordCount,
+ enableImages);
+ }
+
+ /// <summary>
+ /// Gets items based on a query.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The item limit.</param>
+ /// <param name="searchTerm">The search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
+ /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
+ /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <response code="200">Items returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
+ [HttpGet("Users/{userId}/Items/Resume")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool? enableImages = true)
+ {
+ var user = _userManager.GetUserById(userId);
+ var parentIdGuid = parentId ?? Guid.Empty;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var ancestorIds = Array.Empty<Guid>();
+
+ var excludeFolderIds = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes);
+ if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0)
+ {
+ ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
+ .Where(i => i is Folder)
+ .Where(i => !excludeFolderIds.Contains(i.Id))
+ .Select(i => i.Id)
+ .ToArray();
+ }
+
+ var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
+ {
+ OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
+ IsResumable = true,
+ StartIndex = startIndex,
+ Limit = limit,
+ ParentId = parentIdGuid,
+ Recursive = true,
+ DtoOptions = dtoOptions,
+ MediaTypes = mediaTypes,
+ IsVirtualItem = false,
+ CollapseBoxSetItems = false,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ AncestorIds = ancestorIds,
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ SearchTerm = searchTerm
+ });
+
+ var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ StartIndex = startIndex.GetValueOrDefault(),
+ TotalRecordCount = itemsResult.TotalRecordCount,
+ Items = returnItems
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs
new file mode 100644
index 000000000..0be853ca4
--- /dev/null
+++ b/Jellyfin.Api/Controllers/LibraryController.cs
@@ -0,0 +1,1003 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.LibraryDtos;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Progress;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Book = MediaBrowser.Controller.Entities.Book;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Library Controller.
+ /// </summary>
+ [Route("")]
+ public class LibraryController : BaseJellyfinApiController
+ {
+ private readonly IProviderManager _providerManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IActivityManager _activityManager;
+ private readonly ILocalizationManager _localization;
+ private readonly ILibraryMonitor _libraryMonitor;
+ private readonly ILogger<LibraryController> _logger;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LibraryController"/> class.
+ /// </summary>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="libraryMonitor">Instance of the <see cref="ILibraryMonitor"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{LibraryController}"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public LibraryController(
+ IProviderManager providerManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService,
+ IAuthorizationContext authContext,
+ IActivityManager activityManager,
+ ILocalizationManager localization,
+ ILibraryMonitor libraryMonitor,
+ ILogger<LibraryController> logger,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ _providerManager = providerManager;
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ _authContext = authContext;
+ _activityManager = activityManager;
+ _localization = localization;
+ _libraryMonitor = libraryMonitor;
+ _logger = logger;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <summary>
+ /// Get the original file of an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="200">File stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="FileStreamResult"/> with the original file.</returns>
+ [HttpGet("Items/{itemId}/File")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesFile("video/*", "audio/*")]
+ public ActionResult GetFile([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return PhysicalFile(item.Path, MimeTypes.GetMimeType(item.Path), true);
+ }
+
+ /// <summary>
+ /// Gets critic review for an item.
+ /// </summary>
+ /// <response code="200">Critic reviews returned.</response>
+ /// <returns>The list of critic reviews.</returns>
+ [HttpGet("Items/{itemId}/CriticReviews")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [Obsolete("This endpoint is obsolete.")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetCriticReviews()
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ /// <summary>
+ /// Get theme songs for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+ /// <response code="200">Theme songs returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>The item theme songs.</returns>
+ [HttpGet("Items/{itemId}/ThemeSongs")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<ThemeMediaResult> GetThemeSongs(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] Guid? userId,
+ [FromQuery] bool inheritFromParent = false)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var item = itemId.Equals(Guid.Empty)
+ ? (!userId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.RootFolder)
+ : _libraryManager.GetItemById(itemId);
+
+ if (item == null)
+ {
+ return NotFound("Item not found.");
+ }
+
+ IEnumerable<BaseItem> themeItems;
+
+ while (true)
+ {
+ themeItems = item.GetThemeSongs();
+
+ if (themeItems.Any() || !inheritFromParent)
+ {
+ break;
+ }
+
+ var parent = item.GetParent();
+ if (parent == null)
+ {
+ break;
+ }
+
+ item = parent;
+ }
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var items = themeItems
+ .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
+ .ToArray();
+
+ return new ThemeMediaResult
+ {
+ Items = items,
+ TotalRecordCount = items.Length,
+ OwnerId = item.Id
+ };
+ }
+
+ /// <summary>
+ /// Get theme videos for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+ /// <response code="200">Theme videos returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>The item theme videos.</returns>
+ [HttpGet("Items/{itemId}/ThemeVideos")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<ThemeMediaResult> GetThemeVideos(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] Guid? userId,
+ [FromQuery] bool inheritFromParent = false)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var item = itemId.Equals(Guid.Empty)
+ ? (!userId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.RootFolder)
+ : _libraryManager.GetItemById(itemId);
+
+ if (item == null)
+ {
+ return NotFound("Item not found.");
+ }
+
+ IEnumerable<BaseItem> themeItems;
+
+ while (true)
+ {
+ themeItems = item.GetThemeVideos();
+
+ if (themeItems.Any() || !inheritFromParent)
+ {
+ break;
+ }
+
+ var parent = item.GetParent();
+ if (parent == null)
+ {
+ break;
+ }
+
+ item = parent;
+ }
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var items = themeItems
+ .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
+ .ToArray();
+
+ return new ThemeMediaResult
+ {
+ Items = items,
+ TotalRecordCount = items.Length,
+ OwnerId = item.Id
+ };
+ }
+
+ /// <summary>
+ /// Get theme songs and videos for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+ /// <response code="200">Theme songs and videos returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>The item theme videos.</returns>
+ [HttpGet("Items/{itemId}/ThemeMedia")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<AllThemeMediaResult> GetThemeMedia(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] Guid? userId,
+ [FromQuery] bool inheritFromParent = false)
+ {
+ var themeSongs = GetThemeSongs(
+ itemId,
+ userId,
+ inheritFromParent);
+
+ var themeVideos = GetThemeVideos(
+ itemId,
+ userId,
+ inheritFromParent);
+
+ return new AllThemeMediaResult
+ {
+ ThemeSongsResult = themeSongs?.Value,
+ ThemeVideosResult = themeVideos?.Value,
+ SoundtrackSongsResult = new ThemeMediaResult()
+ };
+ }
+
+ /// <summary>
+ /// Starts a library scan.
+ /// </summary>
+ /// <response code="204">Library scan started.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Library/Refresh")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> RefreshLibrary()
+ {
+ try
+ {
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error refreshing library");
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Deletes an item from the library and filesystem.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="204">Item deleted.</response>
+ /// <response code="401">Unauthorized access.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Items/{itemId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ public async Task<ActionResult> DeleteItem(Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+ var user = auth.User;
+
+ if (!item.CanDelete(user))
+ {
+ return Unauthorized("Unauthorized access");
+ }
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions { DeleteFileLocation = true },
+ true);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Deletes items from the library and filesystem.
+ /// </summary>
+ /// <param name="ids">The item ids.</param>
+ /// <response code="204">Items deleted.</response>
+ /// <response code="401">Unauthorized access.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Items")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ public async Task<ActionResult> DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
+ {
+ if (ids.Length == 0)
+ {
+ return NoContent();
+ }
+
+ foreach (var i in ids)
+ {
+ var item = _libraryManager.GetItemById(i);
+ var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+ var user = auth.User;
+
+ if (!item.CanDelete(user))
+ {
+ if (ids.Length > 1)
+ {
+ return Unauthorized("Unauthorized access");
+ }
+
+ continue;
+ }
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions { DeleteFileLocation = true },
+ true);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Get item counts.
+ /// </summary>
+ /// <param name="userId">Optional. Get counts from a specific user's library.</param>
+ /// <param name="isFavorite">Optional. Get counts of favorite items.</param>
+ /// <response code="200">Item counts returned.</response>
+ /// <returns>Item counts.</returns>
+ [HttpGet("Items/Counts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<ItemCounts> GetItemCounts(
+ [FromQuery] Guid? userId,
+ [FromQuery] bool? isFavorite)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var counts = new ItemCounts
+ {
+ AlbumCount = GetCount(typeof(MusicAlbum), user, isFavorite),
+ EpisodeCount = GetCount(typeof(Episode), user, isFavorite),
+ MovieCount = GetCount(typeof(Movie), user, isFavorite),
+ SeriesCount = GetCount(typeof(Series), user, isFavorite),
+ SongCount = GetCount(typeof(Audio), user, isFavorite),
+ MusicVideoCount = GetCount(typeof(MusicVideo), user, isFavorite),
+ BoxSetCount = GetCount(typeof(BoxSet), user, isFavorite),
+ BookCount = GetCount(typeof(Book), user, isFavorite)
+ };
+
+ return counts;
+ }
+
+ /// <summary>
+ /// Gets all parents of an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Item parents returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>Item parents.</returns>
+ [HttpGet("Items/{itemId}/Ancestors")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetAncestors([FromRoute, Required] Guid itemId, [FromQuery] Guid? userId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+
+ if (item == null)
+ {
+ return NotFound("Item not found");
+ }
+
+ var baseItemDtos = new List<BaseItemDto>();
+
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ BaseItem? parent = item.GetParent();
+
+ while (parent != null)
+ {
+ if (user != null)
+ {
+ parent = TranslateParentItem(parent, user);
+ }
+
+ baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
+
+ parent = parent?.GetParent();
+ }
+
+ return baseItemDtos;
+ }
+
+ /// <summary>
+ /// Gets a list of physical paths from virtual folders.
+ /// </summary>
+ /// <response code="200">Physical paths returned.</response>
+ /// <returns>List of physical paths.</returns>
+ [HttpGet("Library/PhysicalPaths")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<string>> GetPhysicalPaths()
+ {
+ return Ok(_libraryManager.RootFolder.Children
+ .SelectMany(c => c.PhysicalLocations));
+ }
+
+ /// <summary>
+ /// Gets all user media folders.
+ /// </summary>
+ /// <param name="isHidden">Optional. Filter by folders that are marked hidden, or not.</param>
+ /// <response code="200">Media folders returned.</response>
+ /// <returns>List of user media folders.</returns>
+ [HttpGet("Library/MediaFolders")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetMediaFolders([FromQuery] bool? isHidden)
+ {
+ var items = _libraryManager.GetUserRootFolder().Children.Concat(_libraryManager.RootFolder.VirtualChildren).OrderBy(i => i.SortName).ToList();
+
+ if (isHidden.HasValue)
+ {
+ var val = isHidden.Value;
+
+ items = items.Where(i => i.IsHidden == val).ToList();
+ }
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var result = new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = items.Count,
+ Items = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions)).ToArray()
+ };
+
+ return result;
+ }
+
+ /// <summary>
+ /// Reports that new episodes of a series have been added by an external source.
+ /// </summary>
+ /// <param name="tvdbId">The tvdbId.</param>
+ /// <response code="204">Report success.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Library/Series/Added", Name = "PostAddedSeries")]
+ [HttpPost("Library/Series/Updated")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult PostUpdatedSeries([FromQuery] string? tvdbId)
+ {
+ var series = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = new[] { nameof(Series) },
+ DtoOptions = new DtoOptions(false)
+ {
+ EnableImages = false
+ }
+ }).Where(i => string.Equals(tvdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tvdb), StringComparison.OrdinalIgnoreCase)).ToArray();
+
+ foreach (var item in series)
+ {
+ _libraryMonitor.ReportFileSystemChanged(item.Path);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that new movies have been added by an external source.
+ /// </summary>
+ /// <param name="tmdbId">The tmdbId.</param>
+ /// <param name="imdbId">The imdbId.</param>
+ /// <response code="204">Report success.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Library/Movies/Added", Name = "PostAddedMovies")]
+ [HttpPost("Library/Movies/Updated")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult PostUpdatedMovies([FromQuery] string? tmdbId, [FromQuery] string? imdbId)
+ {
+ var movies = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = new[] { nameof(Movie) },
+ DtoOptions = new DtoOptions(false)
+ {
+ EnableImages = false
+ }
+ });
+
+ if (!string.IsNullOrWhiteSpace(imdbId))
+ {
+ movies = movies.Where(i => string.Equals(imdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Imdb), StringComparison.OrdinalIgnoreCase)).ToList();
+ }
+ else if (!string.IsNullOrWhiteSpace(tmdbId))
+ {
+ movies = movies.Where(i => string.Equals(tmdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tmdb), StringComparison.OrdinalIgnoreCase)).ToList();
+ }
+ else
+ {
+ movies = new List<BaseItem>();
+ }
+
+ foreach (var item in movies)
+ {
+ _libraryMonitor.ReportFileSystemChanged(item.Path);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that new movies have been added by an external source.
+ /// </summary>
+ /// <param name="dto">The update paths.</param>
+ /// <response code="204">Report success.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Library/Media/Updated")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult PostUpdatedMedia([FromBody, Required] MediaUpdateInfoDto dto)
+ {
+ foreach (var item in dto.Updates)
+ {
+ _libraryMonitor.ReportFileSystemChanged(item.Path ?? throw new ArgumentException("Item path can't be null."));
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Downloads item media.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="200">Media downloaded.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="FileResult"/> containing the media stream.</returns>
+ /// <exception cref="ArgumentException">User can't download or item can't be downloaded.</exception>
+ [HttpGet("Items/{itemId}/Download")]
+ [Authorize(Policy = Policies.Download)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesFile("video/*", "audio/*")]
+ public async Task<ActionResult> GetDownload([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+
+ var user = auth.User;
+
+ if (user != null)
+ {
+ if (!item.CanDownload(user))
+ {
+ throw new ArgumentException("Item does not support downloading");
+ }
+ }
+ else
+ {
+ if (!item.CanDownload())
+ {
+ throw new ArgumentException("Item does not support downloading");
+ }
+ }
+
+ if (user != null)
+ {
+ await LogDownloadAsync(item, user, auth).ConfigureAwait(false);
+ }
+
+ var path = item.Path;
+
+ // Quotes are valid in linux. They'll possibly cause issues here
+ var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty, StringComparison.Ordinal);
+ if (!string.IsNullOrWhiteSpace(filename))
+ {
+ // Kestrel doesn't support non-ASCII characters in headers
+ if (Regex.IsMatch(filename, @"[^\p{IsBasicLatin}]"))
+ {
+ // Manually encoding non-ASCII characters, following https://tools.ietf.org/html/rfc5987#section-3.2.2
+ filename = WebUtility.UrlEncode(filename);
+ }
+ }
+
+ // TODO determine non-ASCII validity.
+ return PhysicalFile(path, MimeTypes.GetMimeType(path), filename, true);
+ }
+
+ /// <summary>
+ /// Gets similar items.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="excludeArtistIds">Exclude artist ids.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param>
+ /// <response code="200">Similar items returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns>
+ [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists")]
+ [HttpGet("Items/{itemId}/Similar")]
+ [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums")]
+ [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows")]
+ [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies")]
+ [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
+ {
+ var item = itemId.Equals(Guid.Empty)
+ ? (!userId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.RootFolder)
+ : _libraryManager.GetItemById(itemId);
+
+ if (item is Episode || (item is IItemByName && item is not MusicArtist))
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request);
+
+ var program = item as IHasProgramAttributes;
+ bool? isMovie = item is Movie || (program != null && program.IsMovie) || item is Trailer;
+ bool? isSeries = item is Series || (program != null && program.IsSeries);
+
+ var includeItemTypes = new List<string>();
+ if (isMovie.Value)
+ {
+ includeItemTypes.Add(nameof(Movie));
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ includeItemTypes.Add(nameof(Trailer));
+ includeItemTypes.Add(nameof(LiveTvProgram));
+ }
+ }
+ else if (isSeries.Value)
+ {
+ includeItemTypes.Add(nameof(Series));
+ }
+ else
+ {
+ // For non series and movie types these columns are typically null
+ isSeries = null;
+ isMovie = null;
+ includeItemTypes.Add(item.GetType().Name);
+ }
+
+ var query = new InternalItemsQuery(user)
+ {
+ Limit = limit,
+ IncludeItemTypes = includeItemTypes.ToArray(),
+ SimilarTo = item,
+ DtoOptions = dtoOptions,
+ EnableTotalRecordCount = !isMovie ?? true,
+ EnableGroupByMetadataKey = isMovie ?? false,
+ MinSimilarityScore = 2 // A remnant from album/artist scoring
+ };
+
+ // ExcludeArtistIds
+ if (excludeArtistIds.Length != 0)
+ {
+ query.ExcludeArtistIds = excludeArtistIds;
+ }
+
+ List<BaseItem> itemsResult = _libraryManager.GetItemList(query);
+
+ var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = returnList,
+ TotalRecordCount = itemsResult.Count
+ };
+ }
+
+ /// <summary>
+ /// Gets the library options info.
+ /// </summary>
+ /// <param name="libraryContentType">Library content type.</param>
+ /// <param name="isNewLibrary">Whether this is a new library.</param>
+ /// <response code="200">Library options info returned.</response>
+ /// <returns>Library options info.</returns>
+ [HttpGet("Libraries/AvailableOptions")]
+ [Authorize(Policy = Policies.FirstTimeSetupOrDefault)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<LibraryOptionsResultDto> GetLibraryOptionsInfo(
+ [FromQuery] string? libraryContentType,
+ [FromQuery] bool isNewLibrary = false)
+ {
+ var result = new LibraryOptionsResultDto();
+
+ var types = GetRepresentativeItemTypes(libraryContentType);
+ var typesList = types.ToList();
+
+ var plugins = _providerManager.GetAllMetadataPlugins()
+ .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
+ .OrderBy(i => typesList.IndexOf(i.ItemType))
+ .ToList();
+
+ result.MetadataSavers = plugins
+ .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
+ .Select(i => new LibraryOptionInfoDto
+ {
+ Name = i.Name,
+ DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
+ })
+ .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First())
+ .ToArray();
+
+ result.MetadataReaders = plugins
+ .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
+ .Select(i => new LibraryOptionInfoDto
+ {
+ Name = i.Name,
+ DefaultEnabled = true
+ })
+ .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First())
+ .ToArray();
+
+ result.SubtitleFetchers = plugins
+ .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
+ .Select(i => new LibraryOptionInfoDto
+ {
+ Name = i.Name,
+ DefaultEnabled = true
+ })
+ .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First())
+ .ToArray();
+
+ var typeOptions = new List<LibraryTypeOptionsDto>();
+
+ foreach (var type in types)
+ {
+ TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions);
+
+ typeOptions.Add(new LibraryTypeOptionsDto
+ {
+ Type = type,
+
+ MetadataFetchers = plugins
+ .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+ .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
+ .Select(i => new LibraryOptionInfoDto
+ {
+ Name = i.Name,
+ DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
+ })
+ .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First())
+ .ToArray(),
+
+ ImageFetchers = plugins
+ .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+ .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
+ .Select(i => new LibraryOptionInfoDto
+ {
+ Name = i.Name,
+ DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
+ })
+ .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First())
+ .ToArray(),
+
+ SupportedImageTypes = plugins
+ .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+ .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
+ .Distinct()
+ .ToArray(),
+
+ DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
+ });
+ }
+
+ result.TypeOptions = typeOptions.ToArray();
+
+ return result;
+ }
+
+ private int GetCount(Type type, User? user, bool? isFavorite)
+ {
+ var query = new InternalItemsQuery(user)
+ {
+ IncludeItemTypes = new[] { type.Name },
+ Limit = 0,
+ Recursive = true,
+ IsVirtualItem = false,
+ IsFavorite = isFavorite,
+ DtoOptions = new DtoOptions(false)
+ {
+ EnableImages = false
+ }
+ };
+
+ return _libraryManager.GetItemsResult(query).TotalRecordCount;
+ }
+
+ private BaseItem? TranslateParentItem(BaseItem item, User user)
+ {
+ return item.GetParent() is AggregateFolder
+ ? _libraryManager.GetUserRootFolder().GetChildren(user, true)
+ .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
+ : item;
+ }
+
+ private async Task LogDownloadAsync(BaseItem item, User user, AuthorizationInfo auth)
+ {
+ try
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Username, item.Name),
+ "UserDownloadingContent",
+ auth.UserId)
+ {
+ ShortOverview = string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
+ }).ConfigureAwait(false);
+ }
+ catch
+ {
+ // Logged at lower levels
+ }
+ }
+
+ private static string[] GetRepresentativeItemTypes(string? contentType)
+ {
+ return contentType switch
+ {
+ CollectionType.BoxSets => new[] { "BoxSet" },
+ CollectionType.Playlists => new[] { "Playlist" },
+ CollectionType.Movies => new[] { "Movie" },
+ CollectionType.TvShows => new[] { "Series", "Season", "Episode" },
+ CollectionType.Books => new[] { "Book" },
+ CollectionType.Music => new[] { "MusicArtist", "MusicAlbum", "Audio", "MusicVideo" },
+ CollectionType.HomeVideos => new[] { "Video", "Photo" },
+ CollectionType.Photos => new[] { "Video", "Photo" },
+ CollectionType.MusicVideos => new[] { "MusicVideo" },
+ _ => new[] { "Series", "Season", "Episode", "Movie" }
+ };
+ }
+
+ private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
+ {
+ if (isNewLibrary)
+ {
+ return false;
+ }
+
+ var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+ .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ .ToArray();
+
+ return metadataOptions.Length == 0 || metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
+ }
+
+ private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
+ {
+ if (isNewLibrary)
+ {
+ if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
+ {
+ return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase));
+ }
+
+ return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase);
+ }
+
+ var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+ .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+
+ return metadataOptions.Length == 0
+ || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
+ }
+
+ private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
+ {
+ if (isNewLibrary)
+ {
+ if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
+ {
+ return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase);
+ }
+
+ return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase);
+ }
+
+ var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+ .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+
+ if (metadataOptions.Length == 0)
+ {
+ return true;
+ }
+
+ return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs
new file mode 100644
index 000000000..ec1170411
--- /dev/null
+++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs
@@ -0,0 +1,327 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.LibraryStructureDto;
+using MediaBrowser.Common.Progress;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The library structure controller.
+ /// </summary>
+ [Route("Library/VirtualFolders")]
+ [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
+ public class LibraryStructureController : BaseJellyfinApiController
+ {
+ private readonly IServerApplicationPaths _appPaths;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILibraryMonitor _libraryMonitor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LibraryStructureController"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="libraryMonitor">Instance of <see cref="ILibraryMonitor"/> interface.</param>
+ public LibraryStructureController(
+ IServerConfigurationManager serverConfigurationManager,
+ ILibraryManager libraryManager,
+ ILibraryMonitor libraryMonitor)
+ {
+ _appPaths = serverConfigurationManager.ApplicationPaths;
+ _libraryManager = libraryManager;
+ _libraryMonitor = libraryMonitor;
+ }
+
+ /// <summary>
+ /// Gets all virtual folders.
+ /// </summary>
+ /// <response code="200">Virtual folders retrieved.</response>
+ /// <returns>An <see cref="IEnumerable{VirtualFolderInfo}"/> with the virtual folders.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<VirtualFolderInfo>> GetVirtualFolders()
+ {
+ return _libraryManager.GetVirtualFolders(true);
+ }
+
+ /// <summary>
+ /// Adds a virtual folder.
+ /// </summary>
+ /// <param name="name">The name of the virtual folder.</param>
+ /// <param name="collectionType">The type of the collection.</param>
+ /// <param name="paths">The paths of the virtual folder.</param>
+ /// <param name="libraryOptionsDto">The library options.</param>
+ /// <param name="refreshLibrary">Whether to refresh the library.</param>
+ /// <response code="204">Folder added.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> AddVirtualFolder(
+ [FromQuery] string? name,
+ [FromQuery] CollectionTypeOptions? collectionType,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths,
+ [FromBody] AddVirtualFolderDto? libraryOptionsDto,
+ [FromQuery] bool refreshLibrary = false)
+ {
+ var libraryOptions = libraryOptionsDto?.LibraryOptions ?? new LibraryOptions();
+
+ if (paths != null && paths.Length > 0)
+ {
+ libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo(i)).ToArray();
+ }
+
+ await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Removes a virtual folder.
+ /// </summary>
+ /// <param name="name">The name of the folder.</param>
+ /// <param name="refreshLibrary">Whether to refresh the library.</param>
+ /// <response code="204">Folder removed.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> RemoveVirtualFolder(
+ [FromQuery] string? name,
+ [FromQuery] bool refreshLibrary = false)
+ {
+ await _libraryManager.RemoveVirtualFolder(name, refreshLibrary).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Renames a virtual folder.
+ /// </summary>
+ /// <param name="name">The name of the virtual folder.</param>
+ /// <param name="newName">The new name.</param>
+ /// <param name="refreshLibrary">Whether to refresh the library.</param>
+ /// <response code="204">Folder renamed.</response>
+ /// <response code="404">Library doesn't exist.</response>
+ /// <response code="409">Library already exists.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, a <see cref="NotFoundResult"/> if the library doesn't exist, a <see cref="ConflictResult"/> if the new name is already taken.</returns>
+ /// <exception cref="ArgumentNullException">The new name may not be null.</exception>
+ [HttpPost("Name")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public ActionResult RenameVirtualFolder(
+ [FromQuery] string? name,
+ [FromQuery] string? newName,
+ [FromQuery] bool refreshLibrary = false)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ if (string.IsNullOrWhiteSpace(newName))
+ {
+ throw new ArgumentNullException(nameof(newName));
+ }
+
+ var rootFolderPath = _appPaths.DefaultUserViewsPath;
+
+ var currentPath = Path.Combine(rootFolderPath, name);
+ var newPath = Path.Combine(rootFolderPath, newName);
+
+ if (!Directory.Exists(currentPath))
+ {
+ return NotFound("The media collection does not exist.");
+ }
+
+ if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
+ {
+ return Conflict($"The media library already exists at {newPath}.");
+ }
+
+ _libraryMonitor.Stop();
+
+ try
+ {
+ // Changing capitalization. Handle windows case insensitivity
+ if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
+ {
+ var tempPath = Path.Combine(
+ rootFolderPath,
+ Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
+ Directory.Move(currentPath, tempPath);
+ currentPath = tempPath;
+ }
+
+ Directory.Move(currentPath, newPath);
+ }
+ finally
+ {
+ CollectionFolder.OnCollectionFolderChange();
+
+ Task.Run(async () =>
+ {
+ // No need to start if scanning the library because it will handle it
+ if (refreshLibrary)
+ {
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ }
+ else
+ {
+ // Need to add a delay here or directory watchers may still pick up the changes
+ // Have to block here to allow exceptions to bubble
+ await Task.Delay(1000).ConfigureAwait(false);
+ _libraryMonitor.Start();
+ }
+ });
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Add a media path to a library.
+ /// </summary>
+ /// <param name="mediaPathDto">The media path dto.</param>
+ /// <param name="refreshLibrary">Whether to refresh the library.</param>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ /// <response code="204">Media path added.</response>
+ /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
+ [HttpPost("Paths")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult AddMediaPath(
+ [FromBody, Required] MediaPathDto mediaPathDto,
+ [FromQuery] bool refreshLibrary = false)
+ {
+ _libraryMonitor.Stop();
+
+ try
+ {
+ var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));
+
+ _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
+ }
+ finally
+ {
+ Task.Run(async () =>
+ {
+ // No need to start if scanning the library because it will handle it
+ if (refreshLibrary)
+ {
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ }
+ else
+ {
+ // Need to add a delay here or directory watchers may still pick up the changes
+ // Have to block here to allow exceptions to bubble
+ await Task.Delay(1000).ConfigureAwait(false);
+ _libraryMonitor.Start();
+ }
+ });
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a media path.
+ /// </summary>
+ /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ /// <response code="204">Media path updated.</response>
+ /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
+ [HttpPost("Paths/Update")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
+ {
+ if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
+ {
+ throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
+ }
+
+ _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Remove a media path.
+ /// </summary>
+ /// <param name="name">The name of the library.</param>
+ /// <param name="path">The path to remove.</param>
+ /// <param name="refreshLibrary">Whether to refresh the library.</param>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ /// <response code="204">Media path removed.</response>
+ /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
+ [HttpDelete("Paths")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult RemoveMediaPath(
+ [FromQuery] string? name,
+ [FromQuery] string? path,
+ [FromQuery] bool refreshLibrary = false)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ _libraryMonitor.Stop();
+
+ try
+ {
+ _libraryManager.RemoveMediaPath(name, path);
+ }
+ finally
+ {
+ Task.Run(async () =>
+ {
+ // No need to start if scanning the library because it will handle it
+ if (refreshLibrary)
+ {
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ }
+ else
+ {
+ // Need to add a delay here or directory watchers may still pick up the changes
+ // Have to block here to allow exceptions to bubble
+ await Task.Delay(1000).ConfigureAwait(false);
+ _libraryMonitor.Start();
+ }
+ });
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Update library options.
+ /// </summary>
+ /// <param name="request">The library name and options.</param>
+ /// <response code="204">Library updated.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("LibraryOptions")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateLibraryOptions(
+ [FromBody] UpdateLibraryOptionsDto request)
+ {
+ var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(request.Id);
+
+ collectionFolder.UpdateLibraryOptions(request.LibraryOptions);
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs
new file mode 100644
index 000000000..b131530c9
--- /dev/null
+++ b/Jellyfin.Api/Controllers/LiveTvController.cs
@@ -0,0 +1,1229 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net.Http;
+using System.Net.Mime;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.LiveTvDtos;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.LiveTv;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Live tv controller.
+ /// </summary>
+ public class LiveTvController : BaseJellyfinApiController
+ {
+ private readonly ILiveTvManager _liveTvManager;
+ private readonly IUserManager _userManager;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly ISessionContext _sessionContext;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IConfigurationManager _configurationManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LiveTvController"/> class.
+ /// </summary>
+ /// <param name="liveTvManager">Instance of the <see cref="ILiveTvManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="sessionContext">Instance of the <see cref="ISessionContext"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Instance of the <see cref="TranscodingJobHelper"/> class.</param>
+ public LiveTvController(
+ ILiveTvManager liveTvManager,
+ IUserManager userManager,
+ IHttpClientFactory httpClientFactory,
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ ISessionContext sessionContext,
+ IMediaSourceManager mediaSourceManager,
+ IConfigurationManager configurationManager,
+ TranscodingJobHelper transcodingJobHelper)
+ {
+ _liveTvManager = liveTvManager;
+ _userManager = userManager;
+ _httpClientFactory = httpClientFactory;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _sessionContext = sessionContext;
+ _mediaSourceManager = mediaSourceManager;
+ _configurationManager = configurationManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ }
+
+ /// <summary>
+ /// Gets available live tv services.
+ /// </summary>
+ /// <response code="200">Available live tv services returned.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the available live tv services.
+ /// </returns>
+ [HttpGet("Info")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<LiveTvInfo> GetLiveTvInfo()
+ {
+ return _liveTvManager.GetLiveTvInfo(CancellationToken.None);
+ }
+
+ /// <summary>
+ /// Gets available live tv channels.
+ /// </summary>
+ /// <param name="type">Optional. Filter by channel type.</param>
+ /// <param name="userId">Optional. Filter by user and attach user data.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="isMovie">Optional. Filter for movies.</param>
+ /// <param name="isSeries">Optional. Filter for series.</param>
+ /// <param name="isNews">Optional. Filter for news.</param>
+ /// <param name="isKids">Optional. Filter for kids.</param>
+ /// <param name="isSports">Optional. Filter for sports.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="isFavorite">Optional. Filter by channels that are favorites, or not.</param>
+ /// <param name="isLiked">Optional. Filter by channels that are liked, or not.</param>
+ /// <param name="isDisliked">Optional. Filter by channels that are disliked, or not.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">"Optional. The image types to include in the output.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="sortBy">Optional. Key to sort by.</param>
+ /// <param name="sortOrder">Optional. Sort order.</param>
+ /// <param name="enableFavoriteSorting">Optional. Incorporate favorite and like status into channel sorting.</param>
+ /// <param name="addCurrentProgram">Optional. Adds current program info to each channel.</param>
+ /// <response code="200">Available live tv channels returned.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the resulting available live tv channels.
+ /// </returns>
+ [HttpGet("Channels")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<QueryResult<BaseItemDto>> GetLiveTvChannels(
+ [FromQuery] ChannelType? type,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isSports,
+ [FromQuery] int? limit,
+ [FromQuery] bool? isFavorite,
+ [FromQuery] bool? isLiked,
+ [FromQuery] bool? isDisliked,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableUserData,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery] SortOrder? sortOrder,
+ [FromQuery] bool enableFavoriteSorting = false,
+ [FromQuery] bool addCurrentProgram = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var channelResult = _liveTvManager.GetInternalChannels(
+ new LiveTvChannelQuery
+ {
+ ChannelType = type,
+ UserId = userId ?? Guid.Empty,
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ IsLiked = isLiked,
+ IsDisliked = isDisliked,
+ EnableFavoriteSorting = enableFavoriteSorting,
+ IsMovie = isMovie,
+ IsSeries = isSeries,
+ IsNews = isNews,
+ IsKids = isKids,
+ IsSports = isSports,
+ SortBy = sortBy,
+ SortOrder = sortOrder ?? SortOrder.Ascending,
+ AddCurrentProgram = addCurrentProgram
+ },
+ dtoOptions,
+ CancellationToken.None);
+
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var fieldsList = dtoOptions.Fields.ToList();
+ fieldsList.Remove(ItemFields.CanDelete);
+ fieldsList.Remove(ItemFields.CanDownload);
+ fieldsList.Remove(ItemFields.DisplayPreferencesId);
+ fieldsList.Remove(ItemFields.Etag);
+ dtoOptions.Fields = fieldsList.ToArray();
+ dtoOptions.AddCurrentProgram = addCurrentProgram;
+
+ var returnArray = _dtoService.GetBaseItemDtos(channelResult.Items, dtoOptions, user);
+ return new QueryResult<BaseItemDto>
+ {
+ Items = returnArray,
+ TotalRecordCount = channelResult.TotalRecordCount
+ };
+ }
+
+ /// <summary>
+ /// Gets a live tv channel.
+ /// </summary>
+ /// <param name="channelId">Channel id.</param>
+ /// <param name="userId">Optional. Attach user data.</param>
+ /// <response code="200">Live tv channel returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the live tv channel.</returns>
+ [HttpGet("Channels/{channelId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<BaseItemDto> GetChannel([FromRoute, Required] Guid channelId, [FromQuery] Guid? userId)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var item = channelId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.GetItemById(channelId);
+
+ var dtoOptions = new DtoOptions()
+ .AddClientFields(Request);
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ /// <summary>
+ /// Gets live tv recordings.
+ /// </summary>
+ /// <param name="channelId">Optional. Filter by channel id.</param>
+ /// <param name="userId">Optional. Filter by user and attach user data.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="status">Optional. Filter by recording status.</param>
+ /// <param name="isInProgress">Optional. Filter by recordings that are in progress, or not.</param>
+ /// <param name="seriesTimerId">Optional. Filter by recordings belonging to a series timer.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="isMovie">Optional. Filter for movies.</param>
+ /// <param name="isSeries">Optional. Filter for series.</param>
+ /// <param name="isKids">Optional. Filter for kids.</param>
+ /// <param name="isSports">Optional. Filter for sports.</param>
+ /// <param name="isNews">Optional. Filter for news.</param>
+ /// <param name="isLibraryItem">Optional. Filter for is library item.</param>
+ /// <param name="enableTotalRecordCount">Optional. Return total record count.</param>
+ /// <response code="200">Live tv recordings returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the live tv recordings.</returns>
+ [HttpGet("Recordings")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<QueryResult<BaseItemDto>> GetRecordings(
+ [FromQuery] string? channelId,
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] RecordingStatus? status,
+ [FromQuery] bool? isInProgress,
+ [FromQuery] string? seriesTimerId,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isSports,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isLibraryItem,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ return _liveTvManager.GetRecordings(
+ new RecordingQuery
+ {
+ ChannelId = channelId,
+ UserId = userId ?? Guid.Empty,
+ StartIndex = startIndex,
+ Limit = limit,
+ Status = status,
+ SeriesTimerId = seriesTimerId,
+ IsInProgress = isInProgress,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ IsMovie = isMovie,
+ IsNews = isNews,
+ IsSeries = isSeries,
+ IsKids = isKids,
+ IsSports = isSports,
+ IsLibraryItem = isLibraryItem,
+ Fields = fields,
+ ImageTypeLimit = imageTypeLimit,
+ EnableImages = enableImages
+ }, dtoOptions);
+ }
+
+ /// <summary>
+ /// Gets live tv recording series.
+ /// </summary>
+ /// <param name="channelId">Optional. Filter by channel id.</param>
+ /// <param name="userId">Optional. Filter by user and attach user data.</param>
+ /// <param name="groupId">Optional. Filter by recording group.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="status">Optional. Filter by recording status.</param>
+ /// <param name="isInProgress">Optional. Filter by recordings that are in progress, or not.</param>
+ /// <param name="seriesTimerId">Optional. Filter by recordings belonging to a series timer.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="enableTotalRecordCount">Optional. Return total record count.</param>
+ /// <response code="200">Live tv recordings returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the live tv recordings.</returns>
+ [HttpGet("Recordings/Series")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [Obsolete("This endpoint is obsolete.")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "channelId", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "groupId", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "startIndex", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "limit", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "status", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isInProgress", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "seriesTimerId", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImages", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageTypeLimit", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImageTypes", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "fields", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableUserData", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableTotalRecordCount", Justification = "Imported from ServiceStack")]
+ public ActionResult<QueryResult<BaseItemDto>> GetRecordingsSeries(
+ [FromQuery] string? channelId,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? groupId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] RecordingStatus? status,
+ [FromQuery] bool? isInProgress,
+ [FromQuery] string? seriesTimerId,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ /// <summary>
+ /// Gets live tv recording groups.
+ /// </summary>
+ /// <param name="userId">Optional. Filter by user and attach user data.</param>
+ /// <response code="200">Recording groups returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the recording groups.</returns>
+ [HttpGet("Recordings/Groups")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [Obsolete("This endpoint is obsolete.")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Imported from ServiceStack")]
+ public ActionResult<QueryResult<BaseItemDto>> GetRecordingGroups([FromQuery] Guid? userId)
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ /// <summary>
+ /// Gets recording folders.
+ /// </summary>
+ /// <param name="userId">Optional. Filter by user and attach user data.</param>
+ /// <response code="200">Recording folders returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the recording folders.</returns>
+ [HttpGet("Recordings/Folders")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<QueryResult<BaseItemDto>> GetRecordingFolders([FromQuery] Guid? userId)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var folders = _liveTvManager.GetRecordingFolders(user);
+
+ var returnArray = _dtoService.GetBaseItemDtos(folders, new DtoOptions(), user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = returnArray,
+ TotalRecordCount = returnArray.Count
+ };
+ }
+
+ /// <summary>
+ /// Gets a live tv recording.
+ /// </summary>
+ /// <param name="recordingId">Recording id.</param>
+ /// <param name="userId">Optional. Attach user data.</param>
+ /// <response code="200">Recording returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the live tv recording.</returns>
+ [HttpGet("Recordings/{recordingId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public ActionResult<BaseItemDto> GetRecording([FromRoute, Required] Guid recordingId, [FromQuery] Guid? userId)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var item = recordingId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(recordingId);
+
+ var dtoOptions = new DtoOptions()
+ .AddClientFields(Request);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ /// <summary>
+ /// Resets a tv tuner.
+ /// </summary>
+ /// <param name="tunerId">Tuner id.</param>
+ /// <response code="204">Tuner reset.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Tuners/{tunerId}/Reset")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult> ResetTuner([FromRoute, Required] string tunerId)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.ResetTuner(tunerId, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <response code="200">Timer returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> containing an <see cref="OkResult"/> which contains the timer.
+ /// </returns>
+ [HttpGet("Timers/{timerId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult<TimerInfoDto>> GetTimer([FromRoute, Required] string timerId)
+ {
+ return await _liveTvManager.GetTimer(timerId, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets the default values for a new timer.
+ /// </summary>
+ /// <param name="programId">Optional. To attach default values based on a program.</param>
+ /// <response code="200">Default values returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> containing an <see cref="OkResult"/> which contains the default values for a timer.
+ /// </returns>
+ [HttpGet("Timers/Defaults")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult<SeriesTimerInfoDto>> GetDefaultTimer([FromQuery] string? programId)
+ {
+ return string.IsNullOrEmpty(programId)
+ ? await _liveTvManager.GetNewTimerDefaults(CancellationToken.None).ConfigureAwait(false)
+ : await _liveTvManager.GetNewTimerDefaults(programId, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets the live tv timers.
+ /// </summary>
+ /// <param name="channelId">Optional. Filter by channel id.</param>
+ /// <param name="seriesTimerId">Optional. Filter by timers belonging to a series timer.</param>
+ /// <param name="isActive">Optional. Filter by timers that are active.</param>
+ /// <param name="isScheduled">Optional. Filter by timers that are scheduled.</param>
+ /// <returns>
+ /// A <see cref="Task"/> containing an <see cref="OkResult"/> which contains the live tv timers.
+ /// </returns>
+ [HttpGet("Timers")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult<QueryResult<TimerInfoDto>>> GetTimers(
+ [FromQuery] string? channelId,
+ [FromQuery] string? seriesTimerId,
+ [FromQuery] bool? isActive,
+ [FromQuery] bool? isScheduled)
+ {
+ return await _liveTvManager.GetTimers(
+ new TimerQuery
+ {
+ ChannelId = channelId,
+ SeriesTimerId = seriesTimerId,
+ IsActive = isActive,
+ IsScheduled = isScheduled
+ }, CancellationToken.None)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets available live tv epgs.
+ /// </summary>
+ /// <param name="channelIds">The channels to return guide information for.</param>
+ /// <param name="userId">Optional. Filter by user id.</param>
+ /// <param name="minStartDate">Optional. The minimum premiere start date.</param>
+ /// <param name="hasAired">Optional. Filter by programs that have completed airing, or not.</param>
+ /// <param name="isAiring">Optional. Filter by programs that are currently airing, or not.</param>
+ /// <param name="maxStartDate">Optional. The maximum premiere start date.</param>
+ /// <param name="minEndDate">Optional. The minimum premiere end date.</param>
+ /// <param name="maxEndDate">Optional. The maximum premiere end date.</param>
+ /// <param name="isMovie">Optional. Filter for movies.</param>
+ /// <param name="isSeries">Optional. Filter for series.</param>
+ /// <param name="isNews">Optional. Filter for news.</param>
+ /// <param name="isKids">Optional. Filter for kids.</param>
+ /// <param name="isSports">Optional. Filter for sports.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Name, StartDate.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="genres">The genres to return guide information for.</param>
+ /// <param name="genreIds">The genre ids to return guide information for.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="seriesTimerId">Optional. Filter by series timer id.</param>
+ /// <param name="librarySeriesId">Optional. Filter by library series id.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableTotalRecordCount">Retrieve total record count.</param>
+ /// <response code="200">Live tv epgs returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> containing a <see cref="OkResult"/> which contains the live tv epgs.
+ /// </returns>
+ [HttpGet("Programs")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetLiveTvPrograms(
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] channelIds,
+ [FromQuery] Guid? userId,
+ [FromQuery] DateTime? minStartDate,
+ [FromQuery] bool? hasAired,
+ [FromQuery] bool? isAiring,
+ [FromQuery] DateTime? maxStartDate,
+ [FromQuery] DateTime? minEndDate,
+ [FromQuery] DateTime? maxEndDate,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isSports,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] string? seriesTimerId,
+ [FromQuery] Guid? librarySeriesId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var query = new InternalItemsQuery(user)
+ {
+ ChannelIds = channelIds,
+ HasAired = hasAired,
+ IsAiring = isAiring,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ MinStartDate = minStartDate,
+ MinEndDate = minEndDate,
+ MaxStartDate = maxStartDate,
+ MaxEndDate = maxEndDate,
+ StartIndex = startIndex,
+ Limit = limit,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
+ IsNews = isNews,
+ IsMovie = isMovie,
+ IsSeries = isSeries,
+ IsKids = isKids,
+ IsSports = isSports,
+ SeriesTimerId = seriesTimerId,
+ Genres = genres,
+ GenreIds = genreIds
+ };
+
+ if (librarySeriesId != null && !librarySeriesId.Equals(Guid.Empty))
+ {
+ query.IsSeries = true;
+
+ if (_libraryManager.GetItemById(librarySeriesId.Value) is Series series)
+ {
+ query.Name = series.Name;
+ }
+ }
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets available live tv epgs.
+ /// </summary>
+ /// <param name="body">Request body.</param>
+ /// <response code="200">Live tv epgs returned.</response>
+ /// <returns>
+ /// A <see cref="Task"/> containing a <see cref="OkResult"/> which contains the live tv epgs.
+ /// </returns>
+ [HttpPost("Programs")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetPrograms([FromBody] GetProgramsDto body)
+ {
+ var user = body.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(body.UserId);
+
+ var query = new InternalItemsQuery(user)
+ {
+ ChannelIds = body.ChannelIds,
+ HasAired = body.HasAired,
+ IsAiring = body.IsAiring,
+ EnableTotalRecordCount = body.EnableTotalRecordCount,
+ MinStartDate = body.MinStartDate,
+ MinEndDate = body.MinEndDate,
+ MaxStartDate = body.MaxStartDate,
+ MaxEndDate = body.MaxEndDate,
+ StartIndex = body.StartIndex,
+ Limit = body.Limit,
+ OrderBy = RequestHelpers.GetOrderBy(body.SortBy, body.SortOrder),
+ IsNews = body.IsNews,
+ IsMovie = body.IsMovie,
+ IsSeries = body.IsSeries,
+ IsKids = body.IsKids,
+ IsSports = body.IsSports,
+ SeriesTimerId = body.SeriesTimerId,
+ Genres = body.Genres,
+ GenreIds = body.GenreIds
+ };
+
+ if (!body.LibrarySeriesId.Equals(Guid.Empty))
+ {
+ query.IsSeries = true;
+
+ if (_libraryManager.GetItemById(body.LibrarySeriesId) is Series series)
+ {
+ query.Name = series.Name;
+ }
+ }
+
+ var dtoOptions = new DtoOptions { Fields = body.Fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes);
+ return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets recommended live tv epgs.
+ /// </summary>
+ /// <param name="userId">Optional. filter by user id.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="isAiring">Optional. Filter by programs that are currently airing, or not.</param>
+ /// <param name="hasAired">Optional. Filter by programs that have completed airing, or not.</param>
+ /// <param name="isSeries">Optional. Filter for series.</param>
+ /// <param name="isMovie">Optional. Filter for movies.</param>
+ /// <param name="isNews">Optional. Filter for news.</param>
+ /// <param name="isKids">Optional. Filter for kids.</param>
+ /// <param name="isSports">Optional. Filter for sports.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="genreIds">The genres to return guide information for.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableUserData">Optional. include user data.</param>
+ /// <param name="enableTotalRecordCount">Retrieve total record count.</param>
+ /// <response code="200">Recommended epgs returned.</response>
+ /// <returns>A <see cref="OkResult"/> containing the queryresult of recommended epgs.</returns>
+ [HttpGet("Programs/Recommended")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetRecommendedPrograms(
+ [FromQuery] Guid? userId,
+ [FromQuery] int? limit,
+ [FromQuery] bool? isAiring,
+ [FromQuery] bool? hasAired,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isSports,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var query = new InternalItemsQuery(user)
+ {
+ IsAiring = isAiring,
+ Limit = limit,
+ HasAired = hasAired,
+ IsSeries = isSeries,
+ IsMovie = isMovie,
+ IsKids = isKids,
+ IsNews = isNews,
+ IsSports = isSports,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ GenreIds = genreIds
+ };
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ return _liveTvManager.GetRecommendedPrograms(query, dtoOptions, CancellationToken.None);
+ }
+
+ /// <summary>
+ /// Gets a live tv program.
+ /// </summary>
+ /// <param name="programId">Program id.</param>
+ /// <param name="userId">Optional. Attach user data.</param>
+ /// <response code="200">Program returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the livetv program.</returns>
+ [HttpGet("Programs/{programId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<BaseItemDto>> GetProgram(
+ [FromRoute, Required] string programId,
+ [FromQuery] Guid? userId)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ return await _liveTvManager.GetProgram(programId, CancellationToken.None, user).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Deletes a live tv recording.
+ /// </summary>
+ /// <param name="recordingId">Recording id.</param>
+ /// <response code="204">Recording deleted.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns>
+ [HttpDelete("Recordings/{recordingId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteRecording([FromRoute, Required] Guid recordingId)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+
+ var item = _libraryManager.GetItemById(recordingId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ _libraryManager.DeleteItem(item, new DeleteOptions
+ {
+ DeleteFileLocation = false
+ });
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Cancels a live tv timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <response code="204">Timer deleted.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Timers/{timerId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CancelTimer([FromRoute, Required] string timerId)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.CancelTimer(timerId).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a live tv timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <param name="timerInfo">New timer info.</param>
+ /// <response code="204">Timer updated.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Timers/{timerId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "timerId", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> UpdateTimer([FromRoute, Required] string timerId, [FromBody] TimerInfoDto timerInfo)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.UpdateTimer(timerInfo, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Creates a live tv timer.
+ /// </summary>
+ /// <param name="timerInfo">New timer info.</param>
+ /// <response code="204">Timer created.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Timers")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CreateTimer([FromBody] TimerInfoDto timerInfo)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.CreateTimer(timerInfo, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a live tv series timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <response code="200">Series timer returned.</response>
+ /// <response code="404">Series timer not found.</response>
+ /// <returns>A <see cref="OkResult"/> on success, or a <see cref="NotFoundResult"/> if timer not found.</returns>
+ [HttpGet("SeriesTimers/{timerId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<SeriesTimerInfoDto>> GetSeriesTimer([FromRoute, Required] string timerId)
+ {
+ var timer = await _liveTvManager.GetSeriesTimer(timerId, CancellationToken.None).ConfigureAwait(false);
+ if (timer == null)
+ {
+ return NotFound();
+ }
+
+ return timer;
+ }
+
+ /// <summary>
+ /// Gets live tv series timers.
+ /// </summary>
+ /// <param name="sortBy">Optional. Sort by SortName or Priority.</param>
+ /// <param name="sortOrder">Optional. Sort in Ascending or Descending order.</param>
+ /// <response code="200">Timers returned.</response>
+ /// <returns>An <see cref="OkResult"/> of live tv series timers.</returns>
+ [HttpGet("SeriesTimers")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<SeriesTimerInfoDto>>> GetSeriesTimers([FromQuery] string? sortBy, [FromQuery] SortOrder? sortOrder)
+ {
+ return await _liveTvManager.GetSeriesTimers(
+ new SeriesTimerQuery
+ {
+ SortOrder = sortOrder ?? SortOrder.Ascending,
+ SortBy = sortBy
+ }, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Cancels a live tv series timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <response code="204">Timer cancelled.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("SeriesTimers/{timerId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CancelSeriesTimer([FromRoute, Required] string timerId)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.CancelSeriesTimer(timerId).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a live tv series timer.
+ /// </summary>
+ /// <param name="timerId">Timer id.</param>
+ /// <param name="seriesTimerInfo">New series timer info.</param>
+ /// <response code="204">Series timer updated.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("SeriesTimers/{timerId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "timerId", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> UpdateSeriesTimer([FromRoute, Required] string timerId, [FromBody] SeriesTimerInfoDto seriesTimerInfo)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.UpdateSeriesTimer(seriesTimerInfo, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Creates a live tv series timer.
+ /// </summary>
+ /// <param name="seriesTimerInfo">New series timer info.</param>
+ /// <response code="204">Series timer info created.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("SeriesTimers")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CreateSeriesTimer([FromBody] SeriesTimerInfoDto seriesTimerInfo)
+ {
+ await AssertUserCanManageLiveTv().ConfigureAwait(false);
+ await _liveTvManager.CreateSeriesTimer(seriesTimerInfo, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Get recording group.
+ /// </summary>
+ /// <param name="groupId">Group id.</param>
+ /// <returns>A <see cref="NotFoundResult"/>.</returns>
+ [HttpGet("Recordings/Groups/{groupId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("This endpoint is obsolete.")]
+ public ActionResult<BaseItemDto> GetRecordingGroup([FromRoute, Required] Guid groupId)
+ {
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Get guid info.
+ /// </summary>
+ /// <response code="200">Guid info returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the guide info.</returns>
+ [HttpGet("GuideInfo")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<GuideInfo> GetGuideInfo()
+ {
+ return _liveTvManager.GetGuideInfo();
+ }
+
+ /// <summary>
+ /// Adds a tuner host.
+ /// </summary>
+ /// <param name="tunerHostInfo">New tuner host.</param>
+ /// <response code="200">Created tuner host returned.</response>
+ /// <returns>A <see cref="OkResult"/> containing the created tuner host.</returns>
+ [HttpPost("TunerHosts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<TunerHostInfo>> AddTunerHost([FromBody] TunerHostInfo tunerHostInfo)
+ {
+ return await _liveTvManager.SaveTunerHost(tunerHostInfo).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Deletes a tuner host.
+ /// </summary>
+ /// <param name="id">Tuner host id.</param>
+ /// <response code="204">Tuner host deleted.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("TunerHosts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult DeleteTunerHost([FromQuery] string? id)
+ {
+ var config = _configurationManager.GetConfiguration<LiveTvOptions>("livetv");
+ config.TunerHosts = config.TunerHosts.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
+ _configurationManager.SaveConfiguration("livetv", config);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets default listings provider info.
+ /// </summary>
+ /// <response code="200">Default listings provider info returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the default listings provider info.</returns>
+ [HttpGet("ListingProviders/Default")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<ListingsProviderInfo> GetDefaultListingProvider()
+ {
+ return new ListingsProviderInfo();
+ }
+
+ /// <summary>
+ /// Adds a listings provider.
+ /// </summary>
+ /// <param name="pw">Password.</param>
+ /// <param name="listingsProviderInfo">New listings info.</param>
+ /// <param name="validateListings">Validate listings.</param>
+ /// <param name="validateLogin">Validate login.</param>
+ /// <response code="200">Created listings provider returned.</response>
+ /// <returns>A <see cref="OkResult"/> containing the created listings provider.</returns>
+ [HttpPost("ListingProviders")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [SuppressMessage("Microsoft.Performance", "CA5350:RemoveSha1", MessageId = "AddListingProvider", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult<ListingsProviderInfo>> AddListingProvider(
+ [FromQuery] string? pw,
+ [FromBody] ListingsProviderInfo listingsProviderInfo,
+ [FromQuery] bool validateListings = false,
+ [FromQuery] bool validateLogin = false)
+ {
+ if (!string.IsNullOrEmpty(pw))
+ {
+ using var sha = SHA1.Create();
+ // TODO: remove ToLower when Convert.ToHexString supports lowercase
+ // Schedules Direct requires the hex to be lowercase
+ listingsProviderInfo.Password = Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))).ToLowerInvariant();
+ }
+
+ return await _liveTvManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Delete listing provider.
+ /// </summary>
+ /// <param name="id">Listing provider id.</param>
+ /// <response code="204">Listing provider deleted.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("ListingProviders")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult DeleteListingProvider([FromQuery] string? id)
+ {
+ _liveTvManager.DeleteListingsProvider(id);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets available lineups.
+ /// </summary>
+ /// <param name="id">Provider id.</param>
+ /// <param name="type">Provider type.</param>
+ /// <param name="location">Location.</param>
+ /// <param name="country">Country.</param>
+ /// <response code="200">Available lineups returned.</response>
+ /// <returns>A <see cref="OkResult"/> containing the available lineups.</returns>
+ [HttpGet("ListingProviders/Lineups")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<IEnumerable<NameIdPair>>> GetLineups(
+ [FromQuery] string? id,
+ [FromQuery] string? type,
+ [FromQuery] string? location,
+ [FromQuery] string? country)
+ {
+ return await _liveTvManager.GetLineups(type, id, country, location).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets available countries.
+ /// </summary>
+ /// <response code="200">Available countries returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the available countries.</returns>
+ [HttpGet("ListingProviders/SchedulesDirect/Countries")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile(MediaTypeNames.Application.Json)]
+ public async Task<ActionResult> GetSchedulesDirectCountries()
+ {
+ var client = _httpClientFactory.CreateClient(NamedClient.Default);
+ // https://json.schedulesdirect.org/20141201/available/countries
+ // Can't dispose the response as it's required up the call chain.
+ var response = await client.GetAsync(new Uri("https://json.schedulesdirect.org/20141201/available/countries"))
+ .ConfigureAwait(false);
+
+ return File(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), MediaTypeNames.Application.Json);
+ }
+
+ /// <summary>
+ /// Get channel mapping options.
+ /// </summary>
+ /// <param name="providerId">Provider id.</param>
+ /// <response code="200">Channel mapping options returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the channel mapping options.</returns>
+ [HttpGet("ChannelMappingOptions")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<ChannelMappingOptionsDto>> GetChannelMappingOptions([FromQuery] string? providerId)
+ {
+ var config = _configurationManager.GetConfiguration<LiveTvOptions>("livetv");
+
+ var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
+
+ var listingsProviderName = _liveTvManager.ListingProviders.First(i => string.Equals(i.Type, listingsProviderInfo.Type, StringComparison.OrdinalIgnoreCase)).Name;
+
+ var tunerChannels = await _liveTvManager.GetChannelsForListingsProvider(providerId, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var providerChannels = await _liveTvManager.GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var mappings = listingsProviderInfo.ChannelMappings;
+
+ return new ChannelMappingOptionsDto
+ {
+ TunerChannels = tunerChannels.Select(i => _liveTvManager.GetTunerChannelMapping(i, mappings, providerChannels)).ToList(),
+ ProviderChannels = providerChannels.Select(i => new NameIdPair
+ {
+ Name = i.Name,
+ Id = i.Id
+ }).ToList(),
+ Mappings = mappings,
+ ProviderName = listingsProviderName
+ };
+ }
+
+ /// <summary>
+ /// Set channel mappings.
+ /// </summary>
+ /// <param name="setChannelMappingDto">The set channel mapping dto.</param>
+ /// <response code="200">Created channel mapping returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the created channel mapping.</returns>
+ [HttpPost("ChannelMappings")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<TunerChannelMapping>> SetChannelMapping([FromBody, Required] SetChannelMappingDto setChannelMappingDto)
+ {
+ return await _liveTvManager.SetChannelMapping(setChannelMappingDto.ProviderId, setChannelMappingDto.TunerChannelId, setChannelMappingDto.ProviderChannelId).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Get tuner host types.
+ /// </summary>
+ /// <response code="200">Tuner host types returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the tuner host types.</returns>
+ [HttpGet("TunerHosts/Types")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<NameIdPair>> GetTunerHostTypes()
+ {
+ return _liveTvManager.GetTunerHostTypes();
+ }
+
+ /// <summary>
+ /// Discover tuners.
+ /// </summary>
+ /// <param name="newDevicesOnly">Only discover new tuners.</param>
+ /// <response code="200">Tuners returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the tuners.</returns>
+ [HttpGet("Tuners/Discvover", Name = "DiscvoverTuners")]
+ [HttpGet("Tuners/Discover")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<IEnumerable<TunerHostInfo>>> DiscoverTuners([FromQuery] bool newDevicesOnly = false)
+ {
+ return await _liveTvManager.DiscoverTuners(newDevicesOnly, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets a live tv recording stream.
+ /// </summary>
+ /// <param name="recordingId">Recording id.</param>
+ /// <response code="200">Recording stream returned.</response>
+ /// <response code="404">Recording not found.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the recording stream on success,
+ /// or a <see cref="NotFoundResult"/> if recording not found.
+ /// </returns>
+ [HttpGet("LiveRecordings/{recordingId}/stream")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesVideoFile]
+ public ActionResult GetLiveRecordingFile([FromRoute, Required] string recordingId)
+ {
+ var path = _liveTvManager.GetEmbyTvActiveRecordingPath(recordingId);
+
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ return NotFound();
+ }
+
+ var stream = new ProgressiveFileStream(path, null, _transcodingJobHelper);
+ return new FileStreamResult(stream, MimeTypes.GetMimeType(path));
+ }
+
+ /// <summary>
+ /// Gets a live tv channel stream.
+ /// </summary>
+ /// <param name="streamId">Stream id.</param>
+ /// <param name="container">Container type.</param>
+ /// <response code="200">Stream returned.</response>
+ /// <response code="404">Stream not found.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the channel stream on success,
+ /// or a <see cref="NotFoundResult"/> if stream not found.
+ /// </returns>
+ [HttpGet("LiveStreamFiles/{streamId}/stream.{container}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesVideoFile]
+ public ActionResult GetLiveStreamFile([FromRoute, Required] string streamId, [FromRoute, Required] string container)
+ {
+ var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfoByUniqueId(streamId);
+ if (liveStreamInfo == null)
+ {
+ return NotFound();
+ }
+
+ var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream());
+ return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file." + container));
+ }
+
+ private async Task AssertUserCanManageLiveTv()
+ {
+ var user = await _sessionContext.GetUser(Request).ConfigureAwait(false);
+
+ if (user == null)
+ {
+ throw new SecurityException("Anonymous live tv management is not allowed.");
+ }
+
+ if (!user.HasPermission(PermissionKind.EnableLiveTvManagement))
+ {
+ throw new SecurityException("The current user does not have permission to manage live tv.");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/LocalizationController.cs b/Jellyfin.Api/Controllers/LocalizationController.cs
new file mode 100644
index 000000000..3d8b9e0ca
--- /dev/null
+++ b/Jellyfin.Api/Controllers/LocalizationController.cs
@@ -0,0 +1,76 @@
+using System.Collections.Generic;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Localization controller.
+ /// </summary>
+ [Authorize(Policy = Policies.FirstTimeSetupOrDefault)]
+ public class LocalizationController : BaseJellyfinApiController
+ {
+ private readonly ILocalizationManager _localization;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LocalizationController"/> class.
+ /// </summary>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public LocalizationController(ILocalizationManager localization)
+ {
+ _localization = localization;
+ }
+
+ /// <summary>
+ /// Gets known cultures.
+ /// </summary>
+ /// <response code="200">Known cultures returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of cultures.</returns>
+ [HttpGet("Cultures")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<CultureDto>> GetCultures()
+ {
+ return Ok(_localization.GetCultures());
+ }
+
+ /// <summary>
+ /// Gets known countries.
+ /// </summary>
+ /// <response code="200">Known countries returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of countries.</returns>
+ [HttpGet("Countries")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<CountryInfo>> GetCountries()
+ {
+ return Ok(_localization.GetCountries());
+ }
+
+ /// <summary>
+ /// Gets known parental ratings.
+ /// </summary>
+ /// <response code="200">Known parental ratings returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of parental ratings.</returns>
+ [HttpGet("ParentalRatings")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<ParentalRating>> GetParentalRatings()
+ {
+ return Ok(_localization.GetParentalRatings());
+ }
+
+ /// <summary>
+ /// Gets localization options.
+ /// </summary>
+ /// <response code="200">Localization options returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of localization options.</returns>
+ [HttpGet("Options")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<LocalizationOption>> GetLocalizationOptions()
+ {
+ return Ok(_localization.GetLocalizationOptions());
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs
new file mode 100644
index 000000000..b422eb78c
--- /dev/null
+++ b/Jellyfin.Api/Controllers/MediaInfoController.cs
@@ -0,0 +1,328 @@
+using System;
+using System.Buffers;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.MediaInfoDtos;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The media info controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class MediaInfoController : BaseJellyfinApiController
+ {
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IDeviceManager _deviceManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILogger<MediaInfoController> _logger;
+ private readonly MediaInfoHelper _mediaInfoHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MediaInfoController"/> class.
+ /// </summary>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{MediaInfoController}"/> interface.</param>
+ /// <param name="mediaInfoHelper">Instance of the <see cref="MediaInfoHelper"/>.</param>
+ public MediaInfoController(
+ IMediaSourceManager mediaSourceManager,
+ IDeviceManager deviceManager,
+ ILibraryManager libraryManager,
+ IAuthorizationContext authContext,
+ ILogger<MediaInfoController> logger,
+ MediaInfoHelper mediaInfoHelper)
+ {
+ _mediaSourceManager = mediaSourceManager;
+ _deviceManager = deviceManager;
+ _libraryManager = libraryManager;
+ _authContext = authContext;
+ _logger = logger;
+ _mediaInfoHelper = mediaInfoHelper;
+ }
+
+ /// <summary>
+ /// Gets live playback media info for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <response code="200">Playback info returned.</response>
+ /// <returns>A <see cref="Task"/> containing a <see cref="PlaybackInfoResponse"/> with the playback information.</returns>
+ [HttpGet("Items/{itemId}/PlaybackInfo")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<PlaybackInfoResponse>> GetPlaybackInfo([FromRoute, Required] Guid itemId, [FromQuery, Required] Guid userId)
+ {
+ return await _mediaInfoHelper.GetPlaybackInfo(
+ itemId,
+ userId)
+ .ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets live playback media info for an item.
+ /// </summary>
+ /// <remarks>
+ /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
+ /// Query parameters are obsolete.
+ /// </remarks>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="maxStreamingBitrate">The maximum streaming bitrate.</param>
+ /// <param name="startTimeTicks">The start time in ticks.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="maxAudioChannels">The maximum number of audio channels.</param>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="liveStreamId">The livestream id.</param>
+ /// <param name="autoOpenLiveStream">Whether to auto open the livestream.</param>
+ /// <param name="enableDirectPlay">Whether to enable direct play. Default: true.</param>
+ /// <param name="enableDirectStream">Whether to enable direct stream. Default: true.</param>
+ /// <param name="enableTranscoding">Whether to enable transcoding. Default: true.</param>
+ /// <param name="allowVideoStreamCopy">Whether to allow to copy the video stream. Default: true.</param>
+ /// <param name="allowAudioStreamCopy">Whether to allow to copy the audio stream. Default: true.</param>
+ /// <param name="playbackInfoDto">The playback info.</param>
+ /// <response code="200">Playback info returned.</response>
+ /// <returns>A <see cref="Task"/> containing a <see cref="PlaybackInfoResponse"/> with the playback info.</returns>
+ [HttpPost("Items/{itemId}/PlaybackInfo")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<PlaybackInfoResponse>> GetPostedPlaybackInfo(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, ParameterObsolete] Guid? userId,
+ [FromQuery, ParameterObsolete] int? maxStreamingBitrate,
+ [FromQuery, ParameterObsolete] long? startTimeTicks,
+ [FromQuery, ParameterObsolete] int? audioStreamIndex,
+ [FromQuery, ParameterObsolete] int? subtitleStreamIndex,
+ [FromQuery, ParameterObsolete] int? maxAudioChannels,
+ [FromQuery, ParameterObsolete] string? mediaSourceId,
+ [FromQuery, ParameterObsolete] string? liveStreamId,
+ [FromQuery, ParameterObsolete] bool? autoOpenLiveStream,
+ [FromQuery, ParameterObsolete] bool? enableDirectPlay,
+ [FromQuery, ParameterObsolete] bool? enableDirectStream,
+ [FromQuery, ParameterObsolete] bool? enableTranscoding,
+ [FromQuery, ParameterObsolete] bool? allowVideoStreamCopy,
+ [FromQuery, ParameterObsolete] bool? allowAudioStreamCopy,
+ [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] PlaybackInfoDto? playbackInfoDto)
+ {
+ var authInfo = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+
+ var profile = playbackInfoDto?.DeviceProfile;
+ _logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", profile);
+
+ if (profile == null)
+ {
+ var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
+ if (caps != null)
+ {
+ profile = caps.DeviceProfile;
+ }
+ }
+
+ // Copy params from posted body
+ // TODO clean up when breaking API compatibility.
+ userId ??= playbackInfoDto?.UserId;
+ maxStreamingBitrate ??= playbackInfoDto?.MaxStreamingBitrate;
+ startTimeTicks ??= playbackInfoDto?.StartTimeTicks;
+ audioStreamIndex ??= playbackInfoDto?.AudioStreamIndex;
+ subtitleStreamIndex ??= playbackInfoDto?.SubtitleStreamIndex;
+ maxAudioChannels ??= playbackInfoDto?.MaxAudioChannels;
+ mediaSourceId ??= playbackInfoDto?.MediaSourceId;
+ liveStreamId ??= playbackInfoDto?.LiveStreamId;
+ autoOpenLiveStream ??= playbackInfoDto?.AutoOpenLiveStream ?? false;
+ enableDirectPlay ??= playbackInfoDto?.EnableDirectPlay ?? true;
+ enableDirectStream ??= playbackInfoDto?.EnableDirectStream ?? true;
+ enableTranscoding ??= playbackInfoDto?.EnableTranscoding ?? true;
+ allowVideoStreamCopy ??= playbackInfoDto?.AllowVideoStreamCopy ?? true;
+ allowAudioStreamCopy ??= playbackInfoDto?.AllowAudioStreamCopy ?? true;
+
+ var info = await _mediaInfoHelper.GetPlaybackInfo(
+ itemId,
+ userId,
+ mediaSourceId,
+ liveStreamId)
+ .ConfigureAwait(false);
+
+ if (info.ErrorCode != null)
+ {
+ return info;
+ }
+
+ if (profile != null)
+ {
+ // set device specific data
+ var item = _libraryManager.GetItemById(itemId);
+
+ foreach (var mediaSource in info.MediaSources)
+ {
+ _mediaInfoHelper.SetDeviceSpecificData(
+ item,
+ mediaSource,
+ profile,
+ authInfo,
+ maxStreamingBitrate ?? profile.MaxStreamingBitrate,
+ startTimeTicks ?? 0,
+ mediaSourceId ?? string.Empty,
+ audioStreamIndex,
+ subtitleStreamIndex,
+ maxAudioChannels,
+ info.PlaySessionId!,
+ userId ?? Guid.Empty,
+ enableDirectPlay.Value,
+ enableDirectStream.Value,
+ enableTranscoding.Value,
+ allowVideoStreamCopy.Value,
+ allowAudioStreamCopy.Value,
+ Request.HttpContext.GetNormalizedRemoteIp());
+ }
+
+ _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);
+ }
+
+ if (autoOpenLiveStream.Value)
+ {
+ var mediaSource = string.IsNullOrWhiteSpace(mediaSourceId) ? info.MediaSources[0] : info.MediaSources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.Ordinal));
+
+ if (mediaSource != null && mediaSource.RequiresOpening && string.IsNullOrWhiteSpace(mediaSource.LiveStreamId))
+ {
+ var openStreamResult = await _mediaInfoHelper.OpenMediaSource(
+ Request,
+ new LiveStreamRequest
+ {
+ AudioStreamIndex = audioStreamIndex,
+ DeviceProfile = playbackInfoDto?.DeviceProfile,
+ EnableDirectPlay = enableDirectPlay.Value,
+ EnableDirectStream = enableDirectStream.Value,
+ ItemId = itemId,
+ MaxAudioChannels = maxAudioChannels,
+ MaxStreamingBitrate = maxStreamingBitrate,
+ PlaySessionId = info.PlaySessionId,
+ StartTimeTicks = startTimeTicks,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ UserId = userId ?? Guid.Empty,
+ OpenToken = mediaSource.OpenToken
+ }).ConfigureAwait(false);
+
+ info.MediaSources = new[] { openStreamResult.MediaSource };
+ }
+ }
+
+ if (info.MediaSources != null)
+ {
+ foreach (var mediaSource in info.MediaSources)
+ {
+ _mediaInfoHelper.NormalizeMediaSourceContainer(mediaSource, profile!, DlnaProfileType.Video);
+ }
+ }
+
+ return info;
+ }
+
+ /// <summary>
+ /// Opens a media source.
+ /// </summary>
+ /// <param name="openToken">The open token.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="maxStreamingBitrate">The maximum streaming bitrate.</param>
+ /// <param name="startTimeTicks">The start time in ticks.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="maxAudioChannels">The maximum number of audio channels.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="openLiveStreamDto">The open live stream dto.</param>
+ /// <param name="enableDirectPlay">Whether to enable direct play. Default: true.</param>
+ /// <param name="enableDirectStream">Whether to enable direct stream. Default: true.</param>
+ /// <response code="200">Media source opened.</response>
+ /// <returns>A <see cref="Task"/> containing a <see cref="LiveStreamResponse"/>.</returns>
+ [HttpPost("LiveStreams/Open")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<LiveStreamResponse>> OpenLiveStream(
+ [FromQuery] string? openToken,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] Guid? itemId,
+ [FromBody] OpenLiveStreamDto? openLiveStreamDto,
+ [FromQuery] bool? enableDirectPlay,
+ [FromQuery] bool? enableDirectStream)
+ {
+ var request = new LiveStreamRequest
+ {
+ OpenToken = openToken ?? openLiveStreamDto?.OpenToken,
+ UserId = userId ?? openLiveStreamDto?.UserId ?? Guid.Empty,
+ PlaySessionId = playSessionId ?? openLiveStreamDto?.PlaySessionId,
+ MaxStreamingBitrate = maxStreamingBitrate ?? openLiveStreamDto?.MaxStreamingBitrate,
+ StartTimeTicks = startTimeTicks ?? openLiveStreamDto?.StartTimeTicks,
+ AudioStreamIndex = audioStreamIndex ?? openLiveStreamDto?.AudioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex ?? openLiveStreamDto?.SubtitleStreamIndex,
+ MaxAudioChannels = maxAudioChannels ?? openLiveStreamDto?.MaxAudioChannels,
+ ItemId = itemId ?? openLiveStreamDto?.ItemId ?? Guid.Empty,
+ DeviceProfile = openLiveStreamDto?.DeviceProfile,
+ EnableDirectPlay = enableDirectPlay ?? openLiveStreamDto?.EnableDirectPlay ?? true,
+ EnableDirectStream = enableDirectStream ?? openLiveStreamDto?.EnableDirectStream ?? true,
+ DirectPlayProtocols = openLiveStreamDto?.DirectPlayProtocols ?? new[] { MediaProtocol.Http }
+ };
+ return await _mediaInfoHelper.OpenMediaSource(Request, request).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Closes a media source.
+ /// </summary>
+ /// <param name="liveStreamId">The livestream id.</param>
+ /// <response code="204">Livestream closed.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("LiveStreams/Close")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> CloseLiveStream([FromQuery, Required] string liveStreamId)
+ {
+ await _mediaSourceManager.CloseLiveStream(liveStreamId).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Tests the network with a request with the size of the bitrate.
+ /// </summary>
+ /// <param name="size">The bitrate. Defaults to 102400.</param>
+ /// <response code="200">Test buffer returned.</response>
+ /// <returns>A <see cref="FileResult"/> with specified bitrate.</returns>
+ [HttpGet("Playback/BitrateTest")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile(MediaTypeNames.Application.Octet)]
+ public ActionResult GetBitrateTestBytes([FromQuery][Range(1, 100_000_000, ErrorMessage = "The requested size must be greater than or equal to {1} and less than or equal to {2}")] int size = 102400)
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(size);
+ try
+ {
+ Random.Shared.NextBytes(buffer);
+ return File(buffer, MediaTypeNames.Application.Octet);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs
new file mode 100644
index 000000000..99c90d19e
--- /dev/null
+++ b/Jellyfin.Api/Controllers/MoviesController.cs
@@ -0,0 +1,330 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Movies controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class MoviesController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MoviesController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public MoviesController(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <summary>
+ /// Gets movie recommendations.
+ /// </summary>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. The fields to return.</param>
+ /// <param name="categoryLimit">The max number of categories to return.</param>
+ /// <param name="itemLimit">The max number of items to return per category.</param>
+ /// <response code="200">Movie recommendations returned.</response>
+ /// <returns>The list of movie recommendations.</returns>
+ [HttpGet("Recommendations")]
+ public ActionResult<IEnumerable<RecommendationDto>> GetMovieRecommendations(
+ [FromQuery] Guid? userId,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] int categoryLimit = 5,
+ [FromQuery] int itemLimit = 8)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request);
+
+ var categories = new List<RecommendationDto>();
+
+ var parentIdGuid = parentId ?? Guid.Empty;
+
+ var query = new InternalItemsQuery(user)
+ {
+ IncludeItemTypes = new[]
+ {
+ nameof(Movie),
+ // nameof(Trailer),
+ // nameof(LiveTvProgram)
+ },
+ // IsMovie = true
+ OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.Random, SortOrder.Descending) },
+ Limit = 7,
+ ParentId = parentIdGuid,
+ Recursive = true,
+ IsPlayed = true,
+ DtoOptions = dtoOptions
+ };
+
+ var recentlyPlayedMovies = _libraryManager.GetItemList(query);
+
+ var itemTypes = new List<string> { nameof(Movie) };
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ itemTypes.Add(nameof(Trailer));
+ itemTypes.Add(nameof(LiveTvProgram));
+ }
+
+ var likedMovies = _libraryManager.GetItemList(new InternalItemsQuery(user)
+ {
+ IncludeItemTypes = itemTypes.ToArray(),
+ IsMovie = true,
+ OrderBy = new[] { (ItemSortBy.Random, SortOrder.Descending) },
+ Limit = 10,
+ IsFavoriteOrLiked = true,
+ ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(),
+ EnableGroupByMetadataKey = true,
+ ParentId = parentIdGuid,
+ Recursive = true,
+ DtoOptions = dtoOptions
+ });
+
+ var mostRecentMovies = recentlyPlayedMovies.GetRange(0, Math.Min(recentlyPlayedMovies.Count, 6));
+ // Get recently played directors
+ var recentDirectors = GetDirectors(mostRecentMovies)
+ .ToList();
+
+ // Get recently played actors
+ var recentActors = GetActors(mostRecentMovies)
+ .ToList();
+
+ var similarToRecentlyPlayed = GetSimilarTo(user, recentlyPlayedMovies, itemLimit, dtoOptions, RecommendationType.SimilarToRecentlyPlayed).GetEnumerator();
+ var similarToLiked = GetSimilarTo(user, likedMovies, itemLimit, dtoOptions, RecommendationType.SimilarToLikedItem).GetEnumerator();
+
+ var hasDirectorFromRecentlyPlayed = GetWithDirector(user, recentDirectors, itemLimit, dtoOptions, RecommendationType.HasDirectorFromRecentlyPlayed).GetEnumerator();
+ var hasActorFromRecentlyPlayed = GetWithActor(user, recentActors, itemLimit, dtoOptions, RecommendationType.HasActorFromRecentlyPlayed).GetEnumerator();
+
+ var categoryTypes = new List<IEnumerator<RecommendationDto>>
+ {
+ // Give this extra weight
+ similarToRecentlyPlayed,
+ similarToRecentlyPlayed,
+
+ // Give this extra weight
+ similarToLiked,
+ similarToLiked,
+ hasDirectorFromRecentlyPlayed,
+ hasActorFromRecentlyPlayed
+ };
+
+ while (categories.Count < categoryLimit)
+ {
+ var allEmpty = true;
+
+ foreach (var category in categoryTypes)
+ {
+ if (category.MoveNext())
+ {
+ categories.Add(category.Current);
+ allEmpty = false;
+
+ if (categories.Count >= categoryLimit)
+ {
+ break;
+ }
+ }
+ }
+
+ if (allEmpty)
+ {
+ break;
+ }
+ }
+
+ return Ok(categories.OrderBy(i => i.RecommendationType));
+ }
+
+ private IEnumerable<RecommendationDto> GetWithDirector(
+ User? user,
+ IEnumerable<string> names,
+ int itemLimit,
+ DtoOptions dtoOptions,
+ RecommendationType type)
+ {
+ var itemTypes = new List<string> { nameof(Movie) };
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ itemTypes.Add(nameof(Trailer));
+ itemTypes.Add(nameof(LiveTvProgram));
+ }
+
+ foreach (var name in names)
+ {
+ var items = _libraryManager.GetItemList(
+ new InternalItemsQuery(user)
+ {
+ Person = name,
+ // Account for duplicates by imdb id, since the database doesn't support this yet
+ Limit = itemLimit + 2,
+ PersonTypes = new[] { PersonType.Director },
+ IncludeItemTypes = itemTypes.ToArray(),
+ IsMovie = true,
+ EnableGroupByMetadataKey = true,
+ DtoOptions = dtoOptions
+ }).GroupBy(i => i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Imdb) ?? Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture))
+ .Select(x => x.First())
+ .Take(itemLimit)
+ .ToList();
+
+ if (items.Count > 0)
+ {
+ var returnItems = _dtoService.GetBaseItemDtos(items, dtoOptions, user);
+
+ yield return new RecommendationDto
+ {
+ BaselineItemName = name,
+ CategoryId = name.GetMD5(),
+ RecommendationType = type,
+ Items = returnItems
+ };
+ }
+ }
+ }
+
+ private IEnumerable<RecommendationDto> GetWithActor(User? user, IEnumerable<string> names, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
+ {
+ var itemTypes = new List<string> { nameof(Movie) };
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ itemTypes.Add(nameof(Trailer));
+ itemTypes.Add(nameof(LiveTvProgram));
+ }
+
+ foreach (var name in names)
+ {
+ var items = _libraryManager.GetItemList(new InternalItemsQuery(user)
+ {
+ Person = name,
+ // Account for duplicates by imdb id, since the database doesn't support this yet
+ Limit = itemLimit + 2,
+ IncludeItemTypes = itemTypes.ToArray(),
+ IsMovie = true,
+ EnableGroupByMetadataKey = true,
+ DtoOptions = dtoOptions
+ }).GroupBy(i => i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Imdb) ?? Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture))
+ .Select(x => x.First())
+ .Take(itemLimit)
+ .ToList();
+
+ if (items.Count > 0)
+ {
+ var returnItems = _dtoService.GetBaseItemDtos(items, dtoOptions, user);
+
+ yield return new RecommendationDto
+ {
+ BaselineItemName = name,
+ CategoryId = name.GetMD5(),
+ RecommendationType = type,
+ Items = returnItems
+ };
+ }
+ }
+ }
+
+ private IEnumerable<RecommendationDto> GetSimilarTo(User? user, IEnumerable<BaseItem> baselineItems, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
+ {
+ var itemTypes = new List<string> { nameof(Movie) };
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ itemTypes.Add(nameof(Trailer));
+ itemTypes.Add(nameof(LiveTvProgram));
+ }
+
+ foreach (var item in baselineItems)
+ {
+ var similar = _libraryManager.GetItemList(new InternalItemsQuery(user)
+ {
+ Limit = itemLimit,
+ IncludeItemTypes = itemTypes.ToArray(),
+ IsMovie = true,
+ SimilarTo = item,
+ EnableGroupByMetadataKey = true,
+ DtoOptions = dtoOptions
+ });
+
+ if (similar.Count > 0)
+ {
+ var returnItems = _dtoService.GetBaseItemDtos(similar, dtoOptions, user);
+
+ yield return new RecommendationDto
+ {
+ BaselineItemName = item.Name,
+ CategoryId = item.Id,
+ RecommendationType = type,
+ Items = returnItems
+ };
+ }
+ }
+ }
+
+ private IEnumerable<string> GetActors(IEnumerable<BaseItem> items)
+ {
+ var people = _libraryManager.GetPeople(new InternalPeopleQuery(Array.Empty<string>(), new[] { PersonType.Director })
+ {
+ MaxListOrder = 3
+ });
+
+ var itemIds = items.Select(i => i.Id).ToList();
+
+ return people
+ .Where(i => itemIds.Contains(i.ItemId))
+ .Select(i => i.Name)
+ .DistinctNames();
+ }
+
+ private IEnumerable<string> GetDirectors(IEnumerable<BaseItem> items)
+ {
+ var people = _libraryManager.GetPeople(new InternalPeopleQuery(
+ new[] { PersonType.Director },
+ Array.Empty<string>()));
+
+ var itemIds = items.Select(i => i.Id).ToList();
+
+ return people
+ .Where(i => itemIds.Contains(i.ItemId))
+ .Select(i => i.Name)
+ .DistinctNames();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs
new file mode 100644
index 000000000..27eec2b9a
--- /dev/null
+++ b/Jellyfin.Api/Controllers/MusicGenresController.cs
@@ -0,0 +1,196 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The music genres controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class MusicGenresController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicGenresController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of <see cref="IDtoService"/> interface.</param>
+ public MusicGenresController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ }
+
+ /// <summary>
+ /// Gets all music genres from a given item, folder, or the entire library.
+ /// </summary>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">The search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="enableTotalRecordCount">Optional. Include total record count.</param>
+ /// <response code="200">Music genres returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the queryresult of music genres.</returns>
+ [HttpGet]
+ [Obsolete("Use GetGenres instead")]
+ public ActionResult<QueryResult<BaseItemDto>> GetMusicGenres(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isFavorite,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
+
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
+
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
+ };
+
+ if (parentId.HasValue)
+ {
+ if (parentItem is Folder)
+ {
+ query.AncestorIds = new[] { parentId.Value };
+ }
+ else
+ {
+ query.ItemIds = new[] { parentId.Value };
+ }
+ }
+
+ var result = _libraryManager.GetMusicGenres(query);
+
+ var shouldIncludeItemTypes = includeItemTypes.Length != 0;
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
+ }
+
+ /// <summary>
+ /// Gets a music genre, by name.
+ /// </summary>
+ /// <param name="genreName">The genre name.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <returns>An <see cref="OkResult"/> containing a <see cref="BaseItemDto"/> with the music genre.</returns>
+ [HttpGet("{genreName}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BaseItemDto> GetMusicGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
+ {
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ MusicGenre? item;
+
+ if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ item = GetItemFromSlugName<MusicGenre>(_libraryManager, genreName, dtoOptions);
+ }
+ else
+ {
+ item = _libraryManager.GetMusicGenre(genreName);
+ }
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+
+ private T? GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
+ where T : BaseItem, new()
+ {
+ var result = libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '&'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ result ??= libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '/'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ result ??= libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Name = name.Replace(BaseItem.SlugChar, '?'),
+ IncludeItemTypes = new[] { typeof(T).Name },
+ DtoOptions = dtoOptions
+ }).OfType<T>().FirstOrDefault();
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs
new file mode 100644
index 000000000..420630cdf
--- /dev/null
+++ b/Jellyfin.Api/Controllers/NotificationsController.cs
@@ -0,0 +1,138 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.NotificationDtos;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Notifications;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Notifications;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The notification controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class NotificationsController : BaseJellyfinApiController
+ {
+ private readonly INotificationManager _notificationManager;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NotificationsController" /> class.
+ /// </summary>
+ /// <param name="notificationManager">The notification manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ public NotificationsController(INotificationManager notificationManager, IUserManager userManager)
+ {
+ _notificationManager = notificationManager;
+ _userManager = userManager;
+ }
+
+ /// <summary>
+ /// Gets a user's notifications.
+ /// </summary>
+ /// <response code="200">Notifications returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing a list of notifications.</returns>
+ [HttpGet("{userId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<NotificationResultDto> GetNotifications()
+ {
+ return new NotificationResultDto();
+ }
+
+ /// <summary>
+ /// Gets a user's notification summary.
+ /// </summary>
+ /// <response code="200">Summary of user's notifications returned.</response>
+ /// <returns>An <cref see="OkResult"/> containing a summary of the users notifications.</returns>
+ [HttpGet("{userId}/Summary")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<NotificationsSummaryDto> GetNotificationsSummary()
+ {
+ return new NotificationsSummaryDto();
+ }
+
+ /// <summary>
+ /// Gets notification types.
+ /// </summary>
+ /// <response code="200">All notification types returned.</response>
+ /// <returns>An <cref see="OkResult"/> containing a list of all notification types.</returns>
+ [HttpGet("Types")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<NotificationTypeInfo> GetNotificationTypes()
+ {
+ return _notificationManager.GetNotificationTypes();
+ }
+
+ /// <summary>
+ /// Gets notification services.
+ /// </summary>
+ /// <response code="200">All notification services returned.</response>
+ /// <returns>An <cref see="OkResult"/> containing a list of all notification services.</returns>
+ [HttpGet("Services")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<NameIdPair> GetNotificationServices()
+ {
+ return _notificationManager.GetNotificationServices();
+ }
+
+ /// <summary>
+ /// Sends a notification to all admins.
+ /// </summary>
+ /// <param name="notificationDto">The notification request.</param>
+ /// <response code="204">Notification sent.</response>
+ /// <returns>A <cref see="NoContentResult"/>.</returns>
+ [HttpPost("Admin")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult CreateAdminNotification([FromBody, Required] AdminNotificationDto notificationDto)
+ {
+ var notification = new NotificationRequest
+ {
+ Name = notificationDto.Name,
+ Description = notificationDto.Description,
+ Url = notificationDto.Url,
+ Level = notificationDto.NotificationLevel ?? NotificationLevel.Normal,
+ UserIds = _userManager.Users
+ .Where(user => user.HasPermission(PermissionKind.IsAdministrator))
+ .Select(user => user.Id)
+ .ToArray(),
+ Date = DateTime.UtcNow,
+ };
+
+ _notificationManager.SendNotification(notification, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Sets notifications as read.
+ /// </summary>
+ /// <response code="204">Notifications set as read.</response>
+ /// <returns>A <cref see="NoContentResult"/>.</returns>
+ [HttpPost("{userId}/Read")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult SetRead()
+ {
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Sets notifications as unread.
+ /// </summary>
+ /// <response code="204">Notifications set as unread.</response>
+ /// <returns>A <cref see="NoContentResult"/>.</returns>
+ [HttpPost("{userId}/Unread")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult SetUnread()
+ {
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs
new file mode 100644
index 000000000..5dd49ef2f
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PackageController.cs
@@ -0,0 +1,167 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Updates;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Package Controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PackageController : BaseJellyfinApiController
+ {
+ private readonly IInstallationManager _installationManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PackageController"/> class.
+ /// </summary>
+ /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public PackageController(IInstallationManager installationManager, IServerConfigurationManager serverConfigurationManager)
+ {
+ _installationManager = installationManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <summary>
+ /// Gets a package by name or assembly GUID.
+ /// </summary>
+ /// <param name="name">The name of the package.</param>
+ /// <param name="assemblyGuid">The GUID of the associated assembly.</param>
+ /// <response code="200">Package retrieved.</response>
+ /// <returns>A <see cref="PackageInfo"/> containing package information.</returns>
+ [HttpGet("Packages/{name}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<PackageInfo>> GetPackageInfo(
+ [FromRoute, Required] string name,
+ [FromQuery] Guid? assemblyGuid)
+ {
+ var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false);
+ var result = _installationManager.FilterPackages(
+ packages,
+ name,
+ assemblyGuid ?? default)
+ .FirstOrDefault();
+
+ if (result == null)
+ {
+ return NotFound();
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets available packages.
+ /// </summary>
+ /// <response code="200">Available packages returned.</response>
+ /// <returns>An <see cref="PackageInfo"/> containing available packages information.</returns>
+ [HttpGet("Packages")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<IEnumerable<PackageInfo>> GetPackages()
+ {
+ IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false);
+
+ return packages;
+ }
+
+ /// <summary>
+ /// Installs a package.
+ /// </summary>
+ /// <param name="name">Package name.</param>
+ /// <param name="assemblyGuid">GUID of the associated assembly.</param>
+ /// <param name="version">Optional version. Defaults to latest version.</param>
+ /// <param name="repositoryUrl">Optional. Specify the repository to install from.</param>
+ /// <response code="204">Package found.</response>
+ /// <response code="404">Package not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the package could not be found.</returns>
+ [HttpPost("Packages/Installed/{name}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public async Task<ActionResult> InstallPackage(
+ [FromRoute, Required] string name,
+ [FromQuery] Guid? assemblyGuid,
+ [FromQuery] string? version,
+ [FromQuery] string? repositoryUrl)
+ {
+ var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false);
+ if (!string.IsNullOrEmpty(repositoryUrl))
+ {
+ packages = packages.Where(p => p.Versions.Any(q => q.RepositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase)))
+ .ToList();
+ }
+
+ var package = _installationManager.GetCompatibleVersions(
+ packages,
+ name,
+ assemblyGuid ?? Guid.Empty,
+ specificVersion: string.IsNullOrEmpty(version) ? null : Version.Parse(version))
+ .FirstOrDefault();
+
+ if (package == null)
+ {
+ return NotFound();
+ }
+
+ await _installationManager.InstallPackage(package).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Cancels a package installation.
+ /// </summary>
+ /// <param name="packageId">Installation Id.</param>
+ /// <response code="204">Installation cancelled.</response>
+ /// <returns>A <see cref="NoContentResult"/> on successfully cancelling a package installation.</returns>
+ [HttpDelete("Packages/Installing/{packageId}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult CancelPackageInstallation(
+ [FromRoute, Required] Guid packageId)
+ {
+ _installationManager.CancelInstallation(packageId);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets all package repositories.
+ /// </summary>
+ /// <response code="200">Package repositories returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the list of package repositories.</returns>
+ [HttpGet("Repositories")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<RepositoryInfo>> GetRepositories()
+ {
+ return _serverConfigurationManager.Configuration.PluginRepositories;
+ }
+
+ /// <summary>
+ /// Sets the enabled and existing package repositories.
+ /// </summary>
+ /// <param name="repositoryInfos">The list of package repositories.</param>
+ /// <response code="204">Package repositories saved.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Repositories")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult SetRepositories([FromBody, Required] List<RepositoryInfo> repositoryInfos)
+ {
+ _serverConfigurationManager.Configuration.PluginRepositories = repositoryInfos;
+ _serverConfigurationManager.SaveConfiguration();
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs
new file mode 100644
index 000000000..b98307f87
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PersonsController.cs
@@ -0,0 +1,147 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Persons controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PersonsController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PersonsController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ public PersonsController(
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ IUserManager userManager,
+ IUserDataManager userDataManager)
+ {
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ }
+
+ /// <summary>
+ /// Gets all persons.
+ /// </summary>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">The search term.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not. userId is required.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="excludePersonTypes">Optional. If specified results will be filtered to exclude those containing the specified PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="personTypes">Optional. If specified results will be filtered to include only those containing the specified PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="appearsInItemId">Optional. If specified, person results will be filtered on items related to said persons.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <response code="200">Persons returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the queryresult of persons.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetPersons(
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludePersonTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery] Guid? appearsInItemId,
+ [FromQuery] Guid? userId,
+ [FromQuery] bool? enableImages = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ User? user = null;
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ user = _userManager.GetUserById(userId.Value);
+ }
+
+ var isFavoriteInFilters = filters.Any(f => f == ItemFilter.IsFavorite);
+ var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery(
+ personTypes,
+ excludePersonTypes)
+ {
+ NameContains = searchTerm,
+ User = user,
+ IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite,
+ AppearsInItemId = appearsInItemId ?? Guid.Empty,
+ Limit = limit ?? 0
+ });
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = peopleItems.Select(person => _dtoService.GetItemByNameDto(person, dtoOptions, null, user)).ToArray(),
+ TotalRecordCount = peopleItems.Count
+ };
+ }
+
+ /// <summary>
+ /// Get person by name.
+ /// </summary>
+ /// <param name="name">Person name.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Person returned.</response>
+ /// <response code="404">Person not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the person on success,
+ /// or a <see cref="NotFoundResult"/> if person not found.</returns>
+ [HttpGet("{name}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<BaseItemDto> GetPerson([FromRoute, Required] string name, [FromQuery] Guid? userId)
+ {
+ var dtoOptions = new DtoOptions()
+ .AddClientFields(Request);
+
+ var item = _libraryManager.GetPerson(name);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs
new file mode 100644
index 000000000..1667d6ede
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PlaylistsController.cs
@@ -0,0 +1,220 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.PlaylistDtos;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Playlists;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Playlists;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Playlists controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PlaylistsController : BaseJellyfinApiController
+ {
+ private readonly IPlaylistManager _playlistManager;
+ private readonly IDtoService _dtoService;
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaylistsController"/> class.
+ /// </summary>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public PlaylistsController(
+ IDtoService dtoService,
+ IPlaylistManager playlistManager,
+ IUserManager userManager,
+ ILibraryManager libraryManager)
+ {
+ _dtoService = dtoService;
+ _playlistManager = playlistManager;
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Creates a new playlist.
+ /// </summary>
+ /// <remarks>
+ /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
+ /// Query parameters are obsolete.
+ /// </remarks>
+ /// <param name="name">The playlist name.</param>
+ /// <param name="ids">The item ids.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="mediaType">The media type.</param>
+ /// <param name="createPlaylistRequest">The create playlist payload.</param>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist.
+ /// The task result contains an <see cref="OkResult"/> indicating success.
+ /// </returns>
+ [HttpPost]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist(
+ [FromQuery, ParameterObsolete] string? name,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder)), ParameterObsolete] IReadOnlyList<Guid> ids,
+ [FromQuery, ParameterObsolete] Guid? userId,
+ [FromQuery, ParameterObsolete] string? mediaType,
+ [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest)
+ {
+ if (ids.Count == 0)
+ {
+ ids = createPlaylistRequest?.Ids ?? Array.Empty<Guid>();
+ }
+
+ var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest
+ {
+ Name = name ?? createPlaylistRequest?.Name,
+ ItemIdList = ids,
+ UserId = userId ?? createPlaylistRequest?.UserId ?? default,
+ MediaType = mediaType ?? createPlaylistRequest?.MediaType
+ }).ConfigureAwait(false);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Adds items to a playlist.
+ /// </summary>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="ids">Item id, comma delimited.</param>
+ /// <param name="userId">The userId.</param>
+ /// <response code="204">Items added to playlist.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success.</returns>
+ [HttpPost("{playlistId}/Items")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> AddToPlaylist(
+ [FromRoute, Required] Guid playlistId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
+ [FromQuery] Guid? userId)
+ {
+ await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId ?? Guid.Empty).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Moves a playlist item.
+ /// </summary>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="newIndex">The new index.</param>
+ /// <response code="204">Item moved to new index.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success.</returns>
+ [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> MoveItem(
+ [FromRoute, Required] string playlistId,
+ [FromRoute, Required] string itemId,
+ [FromRoute, Required] int newIndex)
+ {
+ await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Removes items from a playlist.
+ /// </summary>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="entryIds">The item ids, comma delimited.</param>
+ /// <response code="204">Items removed.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success.</returns>
+ [HttpDelete("{playlistId}/Items")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> RemoveFromPlaylist(
+ [FromRoute, Required] string playlistId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
+ {
+ await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets the original items of a playlist.
+ /// </summary>
+ /// <param name="playlistId">The playlist id.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <response code="200">Original playlist returned.</response>
+ /// <response code="404">Playlist not found.</response>
+ /// <returns>The original playlist items.</returns>
+ [HttpGet("{playlistId}/Items")]
+ public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
+ [FromRoute, Required] Guid playlistId,
+ [FromQuery, Required] Guid userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? enableImages,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
+ {
+ var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
+ if (playlist == null)
+ {
+ return NotFound();
+ }
+
+ var user = !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId) : null;
+
+ var items = playlist.GetManageableItems().ToArray();
+
+ var count = items.Length;
+
+ if (startIndex.HasValue)
+ {
+ items = items.Skip(startIndex.Value).ToArray();
+ }
+
+ if (limit.HasValue)
+ {
+ items = items.Take(limit.Value).ToArray();
+ }
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
+
+ for (int index = 0; index < dtos.Count; index++)
+ {
+ dtos[index].PlaylistItemId = items[index].Item1.Id;
+ }
+
+ var result = new QueryResult<BaseItemDto>
+ {
+ Items = dtos,
+ TotalRecordCount = count
+ };
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs
new file mode 100644
index 000000000..6dee1c219
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PlaystateController.cs
@@ -0,0 +1,371 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Playstate controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PlaystateController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataRepository;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ISessionManager _sessionManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILogger<PlaystateController> _logger;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaystateController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataRepository">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ /// <param name="transcodingJobHelper">Th <see cref="TranscodingJobHelper"/> singleton.</param>
+ public PlaystateController(
+ IUserManager userManager,
+ IUserDataManager userDataRepository,
+ ILibraryManager libraryManager,
+ ISessionManager sessionManager,
+ IAuthorizationContext authContext,
+ ILoggerFactory loggerFactory,
+ TranscodingJobHelper transcodingJobHelper)
+ {
+ _userManager = userManager;
+ _userDataRepository = userDataRepository;
+ _libraryManager = libraryManager;
+ _sessionManager = sessionManager;
+ _authContext = authContext;
+ _logger = loggerFactory.CreateLogger<PlaystateController>();
+
+ _transcodingJobHelper = transcodingJobHelper;
+ }
+
+ /// <summary>
+ /// Marks an item as played for user.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="datePlayed">Optional. The date the item was played.</param>
+ /// <response code="200">Item marked as played.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/PlayedItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<UserItemDataDto>> MarkPlayedItem(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed)
+ {
+ var user = _userManager.GetUserById(userId);
+ var session = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ var dto = UpdatePlayedStatus(user, itemId, true, datePlayed);
+ foreach (var additionalUserInfo in session.AdditionalUsers)
+ {
+ var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
+ UpdatePlayedStatus(additionalUser, itemId, true, datePlayed);
+ }
+
+ return dto;
+ }
+
+ /// <summary>
+ /// Marks an item as unplayed for user.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item marked as unplayed.</response>
+ /// <returns>A <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<UserItemDataDto>> MarkUnplayedItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+ var session = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ var dto = UpdatePlayedStatus(user, itemId, false, null);
+ foreach (var additionalUserInfo in session.AdditionalUsers)
+ {
+ var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
+ UpdatePlayedStatus(additionalUser, itemId, false, null);
+ }
+
+ return dto;
+ }
+
+ /// <summary>
+ /// Reports playback has started within a session.
+ /// </summary>
+ /// <param name="playbackStartInfo">The playback start info.</param>
+ /// <response code="204">Playback start recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Playing")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ReportPlaybackStart([FromBody] PlaybackStartInfo playbackStartInfo)
+ {
+ playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
+ playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports playback progress within a session.
+ /// </summary>
+ /// <param name="playbackProgressInfo">The playback progress info.</param>
+ /// <response code="204">Playback progress recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Playing/Progress")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ReportPlaybackProgress([FromBody] PlaybackProgressInfo playbackProgressInfo)
+ {
+ playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
+ playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Pings a playback session.
+ /// </summary>
+ /// <param name="playSessionId">Playback session id.</param>
+ /// <response code="204">Playback session pinged.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Playing/Ping")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult PingPlaybackSession([FromQuery, Required] string playSessionId)
+ {
+ _transcodingJobHelper.PingTranscodingJob(playSessionId, null);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports playback has stopped within a session.
+ /// </summary>
+ /// <param name="playbackStopInfo">The playback stop info.</param>
+ /// <response code="204">Playback stop recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Playing/Stopped")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ReportPlaybackStopped([FromBody] PlaybackStopInfo playbackStopInfo)
+ {
+ _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
+ if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
+ {
+ var authInfo = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+ await _transcodingJobHelper.KillTranscodingJobs(authInfo.DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
+ }
+
+ playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that a user has begun playing an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="playMethod">The play method.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="canSeek">Indicates if the client can seek.</param>
+ /// <response code="204">Play start recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task<ActionResult> OnPlaybackStart(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] PlayMethod? playMethod,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] bool canSeek = false)
+ {
+ var playbackStartInfo = new PlaybackStartInfo
+ {
+ CanSeek = canSeek,
+ ItemId = itemId,
+ MediaSourceId = mediaSourceId,
+ AudioStreamIndex = audioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ PlayMethod = playMethod ?? PlayMethod.Transcode,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId
+ };
+
+ playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
+ playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports a user's playback progress.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="positionTicks">Optional. The current position, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="volumeLevel">Scale of 0-100.</param>
+ /// <param name="playMethod">The play method.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="repeatMode">The repeat mode.</param>
+ /// <param name="isPaused">Indicates if the player is paused.</param>
+ /// <param name="isMuted">Indicates if the player is muted.</param>
+ /// <response code="204">Play progress recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task<ActionResult> OnPlaybackProgress(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] long? positionTicks,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] int? volumeLevel,
+ [FromQuery] PlayMethod? playMethod,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] RepeatMode? repeatMode,
+ [FromQuery] bool isPaused = false,
+ [FromQuery] bool isMuted = false)
+ {
+ var playbackProgressInfo = new PlaybackProgressInfo
+ {
+ ItemId = itemId,
+ PositionTicks = positionTicks,
+ IsMuted = isMuted,
+ IsPaused = isPaused,
+ MediaSourceId = mediaSourceId,
+ AudioStreamIndex = audioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ VolumeLevel = volumeLevel,
+ PlayMethod = playMethod ?? PlayMethod.Transcode,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId,
+ RepeatMode = repeatMode ?? RepeatMode.RepeatNone
+ };
+
+ playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
+ playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that a user has stopped playing an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="nextMediaType">The next media type that will play.</param>
+ /// <param name="positionTicks">Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <response code="204">Playback stop recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task<ActionResult> OnPlaybackStopped(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? nextMediaType,
+ [FromQuery] long? positionTicks,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId)
+ {
+ var playbackStopInfo = new PlaybackStopInfo
+ {
+ ItemId = itemId,
+ PositionTicks = positionTicks,
+ MediaSourceId = mediaSourceId,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId,
+ NextMediaType = nextMediaType
+ };
+
+ _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
+ if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
+ {
+ var authInfo = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+ await _transcodingJobHelper.KillTranscodingJobs(authInfo.DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
+ }
+
+ playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates the played status.
+ /// </summary>
+ /// <param name="user">The user.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
+ /// <param name="datePlayed">The date played.</param>
+ /// <returns>Task.</returns>
+ private UserItemDataDto UpdatePlayedStatus(User user, Guid itemId, bool wasPlayed, DateTime? datePlayed)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+
+ if (wasPlayed)
+ {
+ item.MarkPlayed(user, datePlayed, true);
+ }
+ else
+ {
+ item.MarkUnplayed(user);
+ }
+
+ return _userDataRepository.GetUserDataDto(item, user);
+ }
+
+ private PlayMethod ValidatePlayMethod(PlayMethod method, string? playSessionId)
+ {
+ if (method == PlayMethod.Transcode)
+ {
+ var job = string.IsNullOrWhiteSpace(playSessionId) ? null : _transcodingJobHelper.GetTranscodingJob(playSessionId);
+ if (job == null)
+ {
+ return PlayMethod.DirectPlay;
+ }
+ }
+
+ return method;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs
new file mode 100644
index 000000000..0ae6109bc
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PluginsController.cs
@@ -0,0 +1,341 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.PluginDtos;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Plugins;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Plugins controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PluginsController : BaseJellyfinApiController
+ {
+ private readonly IInstallationManager _installationManager;
+ private readonly IPluginManager _pluginManager;
+ private readonly IConfigurationManager _config;
+ private readonly JsonSerializerOptions _serializerOptions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginsController"/> class.
+ /// </summary>
+ /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param>
+ /// <param name="pluginManager">Instance of the <see cref="IPluginManager"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ public PluginsController(
+ IInstallationManager installationManager,
+ IPluginManager pluginManager,
+ IConfigurationManager config)
+ {
+ _installationManager = installationManager;
+ _pluginManager = pluginManager;
+ _serializerOptions = JsonDefaults.Options;
+ _config = config;
+ }
+
+ /// <summary>
+ /// Get plugin security info.
+ /// </summary>
+ /// <response code="200">Plugin security info returned.</response>
+ /// <returns>Plugin security info.</returns>
+ [Obsolete("This endpoint should not be used.")]
+ [HttpGet("SecurityInfo")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public static ActionResult<PluginSecurityInfo> GetPluginSecurityInfo()
+ {
+ return new PluginSecurityInfo
+ {
+ IsMbSupporter = true,
+ SupporterKey = "IAmTotallyLegit"
+ };
+ }
+
+ /// <summary>
+ /// Gets registration status for a feature.
+ /// </summary>
+ /// <param name="name">Feature name.</param>
+ /// <response code="200">Registration status returned.</response>
+ /// <returns>Mb registration record.</returns>
+ [Obsolete("This endpoint should not be used.")]
+ [HttpPost("RegistrationRecords/{name}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public static ActionResult<MBRegistrationRecord> GetRegistrationStatus([FromRoute, Required] string name)
+ {
+ return new MBRegistrationRecord
+ {
+ IsRegistered = true,
+ RegChecked = true,
+ TrialVersion = false,
+ IsValid = true,
+ RegError = false
+ };
+ }
+
+ /// <summary>
+ /// Gets registration status for a feature.
+ /// </summary>
+ /// <param name="name">Feature name.</param>
+ /// <response code="501">Not implemented.</response>
+ /// <returns>Not Implemented.</returns>
+ /// <exception cref="NotImplementedException">This endpoint is not implemented.</exception>
+ [Obsolete("Paid plugins are not supported")]
+ [HttpGet("Registrations/{name}")]
+ [ProducesResponseType(StatusCodes.Status501NotImplemented)]
+ public static ActionResult GetRegistration([FromRoute, Required] string name)
+ {
+ // TODO Once we have proper apps and plugins and decide to break compatibility with paid plugins,
+ // delete all these registration endpoints. They are only kept for compatibility.
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets a list of currently installed plugins.
+ /// </summary>
+ /// <response code="200">Installed plugins returned.</response>
+ /// <returns>List of currently installed plugins.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<PluginInfo>> GetPlugins()
+ {
+ return Ok(_pluginManager.Plugins
+ .OrderBy(p => p.Name)
+ .Select(p => p.GetPluginInfo()));
+ }
+
+ /// <summary>
+ /// Enables a disabled plugin.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <param name="version">Plugin version.</param>
+ /// <response code="204">Plugin enabled.</response>
+ /// <response code="404">Plugin not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpPost("{pluginId}/{version}/Enable")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult EnablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId, version);
+ if (plugin == null)
+ {
+ return NotFound();
+ }
+
+ _pluginManager.EnablePlugin(plugin);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Disable a plugin.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <param name="version">Plugin version.</param>
+ /// <response code="204">Plugin disabled.</response>
+ /// <response code="404">Plugin not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpPost("{pluginId}/{version}/Disable")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult DisablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId, version);
+ if (plugin == null)
+ {
+ return NotFound();
+ }
+
+ _pluginManager.DisablePlugin(plugin);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Uninstalls a plugin by version.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <param name="version">Plugin version.</param>
+ /// <response code="204">Plugin uninstalled.</response>
+ /// <response code="404">Plugin not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpDelete("{pluginId}/{version}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult UninstallPluginByVersion([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId, version);
+ if (plugin == null)
+ {
+ return NotFound();
+ }
+
+ _installationManager.UninstallPlugin(plugin);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Uninstalls a plugin.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <response code="204">Plugin uninstalled.</response>
+ /// <response code="404">Plugin not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpDelete("{pluginId}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Please use the UninstallPluginByVersion API.")]
+ public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId)
+ {
+ // If no version is given, return the current instance.
+ var plugins = _pluginManager.Plugins.Where(p => p.Id.Equals(pluginId));
+
+ // Select the un-instanced one first.
+ var plugin = plugins.FirstOrDefault(p => p.Instance == null) ?? plugins.OrderBy(p => p.Manifest.Status).FirstOrDefault();
+
+ if (plugin != null)
+ {
+ _installationManager.UninstallPlugin(plugin);
+ return NoContent();
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Gets plugin configuration.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <response code="200">Plugin configuration returned.</response>
+ /// <response code="404">Plugin not found or plugin configuration not found.</response>
+ /// <returns>Plugin configuration.</returns>
+ [HttpGet("{pluginId}/Configuration")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId);
+ if (plugin?.Instance is IHasPluginConfiguration configPlugin)
+ {
+ return configPlugin.Configuration;
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Updates plugin configuration.
+ /// </summary>
+ /// <remarks>
+ /// Accepts plugin configuration as JSON body.
+ /// </remarks>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <response code="204">Plugin configuration updated.</response>
+ /// <response code="404">Plugin not found or plugin does not have configuration.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpPost("{pluginId}/Configuration")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId);
+ if (plugin?.Instance is not IHasPluginConfiguration configPlugin)
+ {
+ return NotFound();
+ }
+
+ var configuration = (BasePluginConfiguration?)await JsonSerializer.DeserializeAsync(Request.Body, configPlugin.ConfigurationType, _serializerOptions)
+ .ConfigureAwait(false);
+
+ if (configuration != null)
+ {
+ configPlugin.UpdateConfiguration(configuration);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a plugin's image.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <param name="version">Plugin version.</param>
+ /// <response code="200">Plugin image returned.</response>
+ /// <returns>Plugin's image.</returns>
+ [HttpGet("{pluginId}/{version}/Image")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ [AllowAnonymous]
+ public ActionResult GetPluginImage([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId, version);
+ if (plugin == null)
+ {
+ return NotFound();
+ }
+
+ var imagePath = Path.Combine(plugin.Path, plugin.Manifest.ImagePath ?? string.Empty);
+ if (plugin.Manifest.ImagePath == null || !System.IO.File.Exists(imagePath))
+ {
+ return NotFound();
+ }
+
+ imagePath = Path.Combine(plugin.Path, plugin.Manifest.ImagePath);
+ return PhysicalFile(imagePath, MimeTypes.GetMimeType(imagePath));
+ }
+
+ /// <summary>
+ /// Gets a plugin's manifest.
+ /// </summary>
+ /// <param name="pluginId">Plugin id.</param>
+ /// <response code="204">Plugin manifest returned.</response>
+ /// <response code="404">Plugin not found.</response>
+ /// <returns>A <see cref="PluginManifest"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns>
+ [HttpPost("{pluginId}/Manifest")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId)
+ {
+ var plugin = _pluginManager.GetPlugin(pluginId);
+
+ if (plugin != null)
+ {
+ return plugin.Manifest;
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Updates plugin security info.
+ /// </summary>
+ /// <param name="pluginSecurityInfo">Plugin security info.</param>
+ /// <response code="204">Plugin security info updated.</response>
+ /// <returns>An <see cref="NoContentResult"/>.</returns>
+ [Obsolete("This endpoint should not be used.")]
+ [HttpPost("SecurityInfo")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdatePluginSecurityInfo([FromBody, Required] PluginSecurityInfo pluginSecurityInfo)
+ {
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/QuickConnectController.cs b/Jellyfin.Api/Controllers/QuickConnectController.cs
new file mode 100644
index 000000000..87b78fe93
--- /dev/null
+++ b/Jellyfin.Api/Controllers/QuickConnectController.cs
@@ -0,0 +1,123 @@
+using System.ComponentModel.DataAnnotations;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.QuickConnect;
+using MediaBrowser.Model.QuickConnect;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Quick connect controller.
+ /// </summary>
+ public class QuickConnectController : BaseJellyfinApiController
+ {
+ private readonly IQuickConnect _quickConnect;
+ private readonly IAuthorizationContext _authContext;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QuickConnectController"/> class.
+ /// </summary>
+ /// <param name="quickConnect">Instance of the <see cref="IQuickConnect"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ public QuickConnectController(IQuickConnect quickConnect, IAuthorizationContext authContext)
+ {
+ _quickConnect = quickConnect;
+ _authContext = authContext;
+ }
+
+ /// <summary>
+ /// Gets the current quick connect state.
+ /// </summary>
+ /// <response code="200">Quick connect state returned.</response>
+ /// <returns>Whether Quick Connect is enabled on the server or not.</returns>
+ [HttpGet("Enabled")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<bool> GetEnabled()
+ {
+ return _quickConnect.IsEnabled;
+ }
+
+ /// <summary>
+ /// Initiate a new quick connect request.
+ /// </summary>
+ /// <response code="200">Quick connect request successfully created.</response>
+ /// <response code="401">Quick connect is not active on this server.</response>
+ /// <returns>A <see cref="QuickConnectResult"/> with a secret and code for future use or an error message.</returns>
+ [HttpGet("Initiate")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QuickConnectResult>> Initiate()
+ {
+ try
+ {
+ var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+ return _quickConnect.TryConnect(auth);
+ }
+ catch (AuthenticationException)
+ {
+ return Unauthorized("Quick connect is disabled");
+ }
+ }
+
+ /// <summary>
+ /// Attempts to retrieve authentication information.
+ /// </summary>
+ /// <param name="secret">Secret previously returned from the Initiate endpoint.</param>
+ /// <response code="200">Quick connect result returned.</response>
+ /// <response code="404">Unknown quick connect secret.</response>
+ /// <returns>An updated <see cref="QuickConnectResult"/>.</returns>
+ [HttpGet("Connect")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<QuickConnectResult> Connect([FromQuery, Required] string secret)
+ {
+ try
+ {
+ return _quickConnect.CheckRequestStatus(secret);
+ }
+ catch (ResourceNotFoundException)
+ {
+ return NotFound("Unknown secret");
+ }
+ catch (AuthenticationException)
+ {
+ return Unauthorized("Quick connect is disabled");
+ }
+ }
+
+ /// <summary>
+ /// Authorizes a pending quick connect request.
+ /// </summary>
+ /// <param name="code">Quick connect code to authorize.</param>
+ /// <response code="200">Quick connect result authorized successfully.</response>
+ /// <response code="403">Unknown user id.</response>
+ /// <returns>Boolean indicating if the authorization was successful.</returns>
+ [HttpPost("Authorize")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult<bool>> Authorize([FromQuery, Required] string code)
+ {
+ var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);
+ if (!userId.HasValue)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "Unknown user id");
+ }
+
+ try
+ {
+ return await _quickConnect.AuthorizeRequest(userId.Value, code).ConfigureAwait(false);
+ }
+ catch (AuthenticationException)
+ {
+ return Unauthorized("Quick connect is disabled");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs
new file mode 100644
index 000000000..35921ede8
--- /dev/null
+++ b/Jellyfin.Api/Controllers/RemoteImageController.cs
@@ -0,0 +1,187 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Extensions;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Providers;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Remote Images Controller.
+ /// </summary>
+ [Route("")]
+ public class RemoteImageController : BaseJellyfinApiController
+ {
+ private readonly IProviderManager _providerManager;
+ private readonly IServerApplicationPaths _applicationPaths;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RemoteImageController"/> class.
+ /// </summary>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
+ /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public RemoteImageController(
+ IProviderManager providerManager,
+ IServerApplicationPaths applicationPaths,
+ IHttpClientFactory httpClientFactory,
+ ILibraryManager libraryManager)
+ {
+ _providerManager = providerManager;
+ _applicationPaths = applicationPaths;
+ _httpClientFactory = httpClientFactory;
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Gets available remote images for an item.
+ /// </summary>
+ /// <param name="itemId">Item Id.</param>
+ /// <param name="type">The image type.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="providerName">Optional. The image provider to use.</param>
+ /// <param name="includeAllLanguages">Optional. Include all languages.</param>
+ /// <response code="200">Remote Images returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>Remote Image Result.</returns>
+ [HttpGet("Items/{itemId}/RemoteImages")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<RemoteImageResult>> GetRemoteImages(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] ImageType? type,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? providerName,
+ [FromQuery] bool includeAllLanguages = false)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var images = await _providerManager.GetAvailableRemoteImages(
+ item,
+ new RemoteImageQuery(providerName ?? string.Empty)
+ {
+ IncludeAllLanguages = includeAllLanguages,
+ IncludeDisabledProviders = true,
+ ImageType = type
+ }, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var imageArray = images.ToArray();
+ var allProviders = _providerManager.GetRemoteImageProviderInfo(item);
+ if (type.HasValue)
+ {
+ allProviders = allProviders.Where(o => o.SupportedImages.Contains(type.Value));
+ }
+
+ var result = new RemoteImageResult
+ {
+ TotalRecordCount = imageArray.Length,
+ Providers = allProviders.Select(o => o.Name)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToArray()
+ };
+
+ if (startIndex.HasValue)
+ {
+ imageArray = imageArray.Skip(startIndex.Value).ToArray();
+ }
+
+ if (limit.HasValue)
+ {
+ imageArray = imageArray.Take(limit.Value).ToArray();
+ }
+
+ result.Images = imageArray;
+ return result;
+ }
+
+ /// <summary>
+ /// Gets available remote image providers for an item.
+ /// </summary>
+ /// <param name="itemId">Item Id.</param>
+ /// <response code="200">Returned remote image providers.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>List of remote image providers.</returns>
+ [HttpGet("Items/{itemId}/RemoteImages/Providers")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<IEnumerable<ImageProviderInfo>> GetRemoteImageProviders([FromRoute, Required] Guid itemId)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ return Ok(_providerManager.GetRemoteImageProviderInfo(item));
+ }
+
+ /// <summary>
+ /// Downloads a remote image for an item.
+ /// </summary>
+ /// <param name="itemId">Item Id.</param>
+ /// <param name="type">The image type.</param>
+ /// <param name="imageUrl">The image url.</param>
+ /// <response code="204">Remote image downloaded.</response>
+ /// <response code="404">Remote image not found.</response>
+ /// <returns>Download status.</returns>
+ [HttpPost("Items/{itemId}/RemoteImages/Download")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DownloadRemoteImage(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, Required] ImageType type,
+ [FromQuery] string? imageUrl)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets the full cache path.
+ /// </summary>
+ /// <param name="filename">The filename.</param>
+ /// <returns>System.String.</returns>
+ private string GetFullCachePath(string filename)
+ {
+ return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/ScheduledTasksController.cs b/Jellyfin.Api/Controllers/ScheduledTasksController.cs
new file mode 100644
index 000000000..68e4f0586
--- /dev/null
+++ b/Jellyfin.Api/Controllers/ScheduledTasksController.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Model.Tasks;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Scheduled Tasks Controller.
+ /// </summary>
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public class ScheduledTasksController : BaseJellyfinApiController
+ {
+ private readonly ITaskManager _taskManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScheduledTasksController"/> class.
+ /// </summary>
+ /// <param name="taskManager">Instance of the <see cref="ITaskManager"/> interface.</param>
+ public ScheduledTasksController(ITaskManager taskManager)
+ {
+ _taskManager = taskManager;
+ }
+
+ /// <summary>
+ /// Get tasks.
+ /// </summary>
+ /// <param name="isHidden">Optional filter tasks that are hidden, or not.</param>
+ /// <param name="isEnabled">Optional filter tasks that are enabled, or not.</param>
+ /// <response code="200">Scheduled tasks retrieved.</response>
+ /// <returns>The list of scheduled tasks.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<TaskInfo> GetTasks(
+ [FromQuery] bool? isHidden,
+ [FromQuery] bool? isEnabled)
+ {
+ IEnumerable<IScheduledTaskWorker> tasks = _taskManager.ScheduledTasks.OrderBy(o => o.Name);
+
+ foreach (var task in tasks)
+ {
+ if (task.ScheduledTask is IConfigurableScheduledTask scheduledTask)
+ {
+ if (isHidden.HasValue && isHidden.Value != scheduledTask.IsHidden)
+ {
+ continue;
+ }
+
+ if (isEnabled.HasValue && isEnabled.Value != scheduledTask.IsEnabled)
+ {
+ continue;
+ }
+ }
+
+ yield return ScheduledTaskHelpers.GetTaskInfo(task);
+ }
+ }
+
+ /// <summary>
+ /// Get task by id.
+ /// </summary>
+ /// <param name="taskId">Task Id.</param>
+ /// <response code="200">Task retrieved.</response>
+ /// <response code="404">Task not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the task on success, or a <see cref="NotFoundResult"/> if the task could not be found.</returns>
+ [HttpGet("{taskId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<TaskInfo> GetTask([FromRoute, Required] string taskId)
+ {
+ var task = _taskManager.ScheduledTasks.FirstOrDefault(i =>
+ string.Equals(i.Id, taskId, StringComparison.OrdinalIgnoreCase));
+
+ if (task == null)
+ {
+ return NotFound();
+ }
+
+ return ScheduledTaskHelpers.GetTaskInfo(task);
+ }
+
+ /// <summary>
+ /// Start specified task.
+ /// </summary>
+ /// <param name="taskId">Task Id.</param>
+ /// <response code="204">Task started.</response>
+ /// <response code="404">Task not found.</response>
+ /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns>
+ [HttpPost("Running/{taskId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult StartTask([FromRoute, Required] string taskId)
+ {
+ var task = _taskManager.ScheduledTasks.FirstOrDefault(o =>
+ o.Id.Equals(taskId, StringComparison.OrdinalIgnoreCase));
+
+ if (task == null)
+ {
+ return NotFound();
+ }
+
+ _taskManager.Execute(task, new TaskOptions());
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Stop specified task.
+ /// </summary>
+ /// <param name="taskId">Task Id.</param>
+ /// <response code="204">Task stopped.</response>
+ /// <response code="404">Task not found.</response>
+ /// <returns>An <see cref="OkResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns>
+ [HttpDelete("Running/{taskId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult StopTask([FromRoute, Required] string taskId)
+ {
+ var task = _taskManager.ScheduledTasks.FirstOrDefault(o =>
+ o.Id.Equals(taskId, StringComparison.OrdinalIgnoreCase));
+
+ if (task == null)
+ {
+ return NotFound();
+ }
+
+ _taskManager.Cancel(task);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Update specified task triggers.
+ /// </summary>
+ /// <param name="taskId">Task Id.</param>
+ /// <param name="triggerInfos">Triggers.</param>
+ /// <response code="204">Task triggers updated.</response>
+ /// <response code="404">Task not found.</response>
+ /// <returns>An <see cref="OkResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns>
+ [HttpPost("{taskId}/Triggers")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult UpdateTask(
+ [FromRoute, Required] string taskId,
+ [FromBody, Required] TaskTriggerInfo[] triggerInfos)
+ {
+ var task = _taskManager.ScheduledTasks.FirstOrDefault(o =>
+ o.Id.Equals(taskId, StringComparison.OrdinalIgnoreCase));
+ if (task == null)
+ {
+ return NotFound();
+ }
+
+ task.Triggers = triggerInfos;
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs
new file mode 100644
index 000000000..73bdf9018
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SearchController.cs
@@ -0,0 +1,268 @@
+using System;
+using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Search;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Search controller.
+ /// </summary>
+ [Route("Search/Hints")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class SearchController : BaseJellyfinApiController
+ {
+ private readonly ISearchEngine _searchEngine;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly IImageProcessor _imageProcessor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SearchController"/> class.
+ /// </summary>
+ /// <param name="searchEngine">Instance of <see cref="ISearchEngine"/> interface.</param>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of <see cref="IDtoService"/> interface.</param>
+ /// <param name="imageProcessor">Instance of <see cref="IImageProcessor"/> interface.</param>
+ public SearchController(
+ ISearchEngine searchEngine,
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ IImageProcessor imageProcessor)
+ {
+ _searchEngine = searchEngine;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _imageProcessor = imageProcessor;
+ }
+
+ /// <summary>
+ /// Gets the search hint result.
+ /// </summary>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="userId">Optional. Supply a user id to search within a user's library or omit to search all.</param>
+ /// <param name="searchTerm">The search term to filter on.</param>
+ /// <param name="includeItemTypes">If specified, only results with the specified item types are returned. This allows multiple, comma delimeted.</param>
+ /// <param name="excludeItemTypes">If specified, results with these item types are filtered out. This allows multiple, comma delimeted.</param>
+ /// <param name="mediaTypes">If specified, only results with the specified media types are returned. This allows multiple, comma delimeted.</param>
+ /// <param name="parentId">If specified, only children of the parent are returned.</param>
+ /// <param name="isMovie">Optional filter for movies.</param>
+ /// <param name="isSeries">Optional filter for series.</param>
+ /// <param name="isNews">Optional filter for news.</param>
+ /// <param name="isKids">Optional filter for kids.</param>
+ /// <param name="isSports">Optional filter for sports.</param>
+ /// <param name="includePeople">Optional filter whether to include people.</param>
+ /// <param name="includeMedia">Optional filter whether to include media.</param>
+ /// <param name="includeGenres">Optional filter whether to include genres.</param>
+ /// <param name="includeStudios">Optional filter whether to include studios.</param>
+ /// <param name="includeArtists">Optional filter whether to include artists.</param>
+ /// <response code="200">Search hint returned.</response>
+ /// <returns>An <see cref="SearchHintResult"/> with the results of the search.</returns>
+ [HttpGet]
+ [Description("Gets search hints based on a search term")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<SearchHintResult> Get(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] Guid? userId,
+ [FromQuery, Required] string searchTerm,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery] Guid? parentId,
+ [FromQuery] bool? isMovie,
+ [FromQuery] bool? isSeries,
+ [FromQuery] bool? isNews,
+ [FromQuery] bool? isKids,
+ [FromQuery] bool? isSports,
+ [FromQuery] bool includePeople = true,
+ [FromQuery] bool includeMedia = true,
+ [FromQuery] bool includeGenres = true,
+ [FromQuery] bool includeStudios = true,
+ [FromQuery] bool includeArtists = true)
+ {
+ var result = _searchEngine.GetSearchHints(new SearchQuery
+ {
+ Limit = limit,
+ SearchTerm = searchTerm,
+ IncludeArtists = includeArtists,
+ IncludeGenres = includeGenres,
+ IncludeMedia = includeMedia,
+ IncludePeople = includePeople,
+ IncludeStudios = includeStudios,
+ StartIndex = startIndex,
+ UserId = userId ?? Guid.Empty,
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ MediaTypes = mediaTypes,
+ ParentId = parentId,
+
+ IsKids = isKids,
+ IsMovie = isMovie,
+ IsNews = isNews,
+ IsSeries = isSeries,
+ IsSports = isSports
+ });
+
+ return new SearchHintResult
+ {
+ TotalRecordCount = result.TotalRecordCount,
+ SearchHints = result.Items.Select(GetSearchHintResult).ToArray()
+ };
+ }
+
+ /// <summary>
+ /// Gets the search hint result.
+ /// </summary>
+ /// <param name="hintInfo">The hint info.</param>
+ /// <returns>SearchHintResult.</returns>
+ private SearchHint GetSearchHintResult(SearchHintInfo hintInfo)
+ {
+ var item = hintInfo.Item;
+
+ var result = new SearchHint
+ {
+ Name = item.Name,
+ IndexNumber = item.IndexNumber,
+ ParentIndexNumber = item.ParentIndexNumber,
+ Id = item.Id,
+ Type = item.GetClientTypeName(),
+ MediaType = item.MediaType,
+ MatchedTerm = hintInfo.MatchedTerm,
+ RunTimeTicks = item.RunTimeTicks,
+ ProductionYear = item.ProductionYear,
+ ChannelId = item.ChannelId,
+ EndDate = item.EndDate
+ };
+
+ // legacy
+ result.ItemId = result.Id;
+
+ if (item.IsFolder)
+ {
+ result.IsFolder = true;
+ }
+
+ var primaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary);
+
+ if (primaryImageTag != null)
+ {
+ result.PrimaryImageTag = primaryImageTag;
+ result.PrimaryImageAspectRatio = _dtoService.GetPrimaryImageAspectRatio(item);
+ }
+
+ SetThumbImageInfo(result, item);
+ SetBackdropImageInfo(result, item);
+
+ switch (item)
+ {
+ case IHasSeries hasSeries:
+ result.Series = hasSeries.SeriesName;
+ break;
+ case LiveTvProgram program:
+ result.StartDate = program.StartDate;
+ break;
+ case Series series:
+ if (series.Status.HasValue)
+ {
+ result.Status = series.Status.Value.ToString();
+ }
+
+ break;
+ case MusicAlbum album:
+ result.Artists = album.Artists;
+ result.AlbumArtist = album.AlbumArtist;
+ break;
+ case Audio song:
+ result.AlbumArtist = song.AlbumArtists?[0];
+ result.Artists = song.Artists;
+
+ MusicAlbum musicAlbum = song.AlbumEntity;
+
+ if (musicAlbum != null)
+ {
+ result.Album = musicAlbum.Name;
+ result.AlbumId = musicAlbum.Id;
+ }
+ else
+ {
+ result.Album = song.Album;
+ }
+
+ break;
+ }
+
+ if (!item.ChannelId.Equals(Guid.Empty))
+ {
+ var channel = _libraryManager.GetItemById(item.ChannelId);
+ result.ChannelName = channel?.Name;
+ }
+
+ return result;
+ }
+
+ private void SetThumbImageInfo(SearchHint hint, BaseItem item)
+ {
+ var itemWithImage = item.HasImage(ImageType.Thumb) ? item : null;
+
+ if (itemWithImage == null && item is Episode)
+ {
+ itemWithImage = GetParentWithImage<Series>(item, ImageType.Thumb);
+ }
+
+ itemWithImage ??= GetParentWithImage<BaseItem>(item, ImageType.Thumb);
+
+ if (itemWithImage != null)
+ {
+ var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Thumb);
+
+ if (tag != null)
+ {
+ hint.ThumbImageTag = tag;
+ hint.ThumbImageItemId = itemWithImage.Id.ToString("N", CultureInfo.InvariantCulture);
+ }
+ }
+ }
+
+ private void SetBackdropImageInfo(SearchHint hint, BaseItem item)
+ {
+ var itemWithImage = (item.HasImage(ImageType.Backdrop) ? item : null)
+ ?? GetParentWithImage<BaseItem>(item, ImageType.Backdrop);
+
+ if (itemWithImage != null)
+ {
+ var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Backdrop);
+
+ if (tag != null)
+ {
+ hint.BackdropImageTag = tag;
+ hint.BackdropImageItemId = itemWithImage.Id.ToString("N", CultureInfo.InvariantCulture);
+ }
+ }
+ }
+
+ private T? GetParentWithImage<T>(BaseItem item, ImageType type)
+ where T : BaseItem
+ {
+ return item.GetParents().OfType<T>().FirstOrDefault(i => i.HasImage(type));
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs
new file mode 100644
index 000000000..3a04cb3a4
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SessionController.cs
@@ -0,0 +1,508 @@
+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.ModelBinders;
+using Jellyfin.Api.Models.SessionDtos;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The session controller.
+ /// </summary>
+ [Route("")]
+ public class SessionController : BaseJellyfinApiController
+ {
+ private readonly ISessionManager _sessionManager;
+ private readonly IUserManager _userManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IDeviceManager _deviceManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionController"/> class.
+ /// </summary>
+ /// <param name="sessionManager">Instance of <see cref="ISessionManager"/> interface.</param>
+ /// <param name="userManager">Instance of <see cref="IUserManager"/> interface.</param>
+ /// <param name="authContext">Instance of <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="deviceManager">Instance of <see cref="IDeviceManager"/> interface.</param>
+ public SessionController(
+ ISessionManager sessionManager,
+ IUserManager userManager,
+ IAuthorizationContext authContext,
+ IDeviceManager deviceManager)
+ {
+ _sessionManager = sessionManager;
+ _userManager = userManager;
+ _authContext = authContext;
+ _deviceManager = deviceManager;
+ }
+
+ /// <summary>
+ /// Gets a list of sessions.
+ /// </summary>
+ /// <param name="controllableByUserId">Filter by sessions that a given user is allowed to remote control.</param>
+ /// <param name="deviceId">Filter by device Id.</param>
+ /// <param name="activeWithinSeconds">Optional. Filter by sessions that were active in the last n seconds.</param>
+ /// <response code="200">List of sessions returned.</response>
+ /// <returns>An <see cref="IEnumerable{SessionInfo}"/> with the available sessions.</returns>
+ [HttpGet("Sessions")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<SessionInfo>> GetSessions(
+ [FromQuery] Guid? controllableByUserId,
+ [FromQuery] string? deviceId,
+ [FromQuery] int? activeWithinSeconds)
+ {
+ var result = _sessionManager.Sessions;
+
+ if (!string.IsNullOrEmpty(deviceId))
+ {
+ result = result.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
+ }
+
+ if (controllableByUserId.HasValue && !controllableByUserId.Equals(Guid.Empty))
+ {
+ result = result.Where(i => i.SupportsRemoteControl);
+
+ var user = _userManager.GetUserById(controllableByUserId.Value);
+
+ if (!user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers))
+ {
+ result = result.Where(i => i.UserId.Equals(Guid.Empty) || i.ContainsUser(controllableByUserId.Value));
+ }
+
+ if (!user.HasPermission(PermissionKind.EnableSharedDeviceControl))
+ {
+ result = result.Where(i => !i.UserId.Equals(Guid.Empty));
+ }
+
+ if (activeWithinSeconds.HasValue && activeWithinSeconds.Value > 0)
+ {
+ var minActiveDate = DateTime.UtcNow.AddSeconds(0 - activeWithinSeconds.Value);
+ result = result.Where(i => i.LastActivityDate >= minActiveDate);
+ }
+
+ result = result.Where(i =>
+ {
+ if (!string.IsNullOrWhiteSpace(i.DeviceId))
+ {
+ if (!_deviceManager.CanAccessDevice(user, i.DeviceId))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ });
+ }
+
+ return Ok(result);
+ }
+
+ /// <summary>
+ /// Instructs a session to browse to an item or view.
+ /// </summary>
+ /// <param name="sessionId">The session Id.</param>
+ /// <param name="itemType">The type of item to browse to.</param>
+ /// <param name="itemId">The Id of the item.</param>
+ /// <param name="itemName">The name of the item.</param>
+ /// <response code="204">Instruction sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Viewing")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> DisplayContent(
+ [FromRoute, Required] string sessionId,
+ [FromQuery, Required] string itemType,
+ [FromQuery, Required] string itemId,
+ [FromQuery, Required] string itemName)
+ {
+ var command = new BrowseRequest
+ {
+ ItemId = itemId,
+ ItemName = itemName,
+ ItemType = itemType
+ };
+
+ await _sessionManager.SendBrowseCommand(
+ await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
+ sessionId,
+ command,
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Instructs a session to play an item.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="playCommand">The type of play command to issue (PlayNow, PlayNext, PlayLast). Clients who have not yet implemented play next and play last may play now.</param>
+ /// <param name="itemIds">The ids of the items to play, comma delimited.</param>
+ /// <param name="startPositionTicks">The starting position of the first item.</param>
+ /// <param name="mediaSourceId">Optional. The media source id.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to play.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to play.</param>
+ /// <param name="startIndex">Optional. The start index.</param>
+ /// <response code="204">Instruction sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Playing")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> Play(
+ [FromRoute, Required] string sessionId,
+ [FromQuery, Required] PlayCommand playCommand,
+ [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds,
+ [FromQuery] long? startPositionTicks,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] int? startIndex)
+ {
+ var playRequest = new PlayRequest
+ {
+ ItemIds = itemIds,
+ StartPositionTicks = startPositionTicks,
+ PlayCommand = playCommand,
+ MediaSourceId = mediaSourceId,
+ AudioStreamIndex = audioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ StartIndex = startIndex
+ };
+
+ await _sessionManager.SendPlayCommand(
+ await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
+ sessionId,
+ playRequest,
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Issues a playstate command to a client.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="command">The <see cref="PlaystateCommand"/>.</param>
+ /// <param name="seekPositionTicks">The optional position ticks.</param>
+ /// <param name="controllingUserId">The optional controlling user id.</param>
+ /// <response code="204">Playstate command sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Playing/{command}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SendPlaystateCommand(
+ [FromRoute, Required] string sessionId,
+ [FromRoute, Required] PlaystateCommand command,
+ [FromQuery] long? seekPositionTicks,
+ [FromQuery] string? controllingUserId)
+ {
+ await _sessionManager.SendPlaystateCommand(
+ await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
+ sessionId,
+ new PlaystateRequest()
+ {
+ Command = command,
+ ControllingUserId = controllingUserId,
+ SeekPositionTicks = seekPositionTicks,
+ },
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Issues a system command to a client.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="command">The command to send.</param>
+ /// <response code="204">System command sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/System/{command}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SendSystemCommand(
+ [FromRoute, Required] string sessionId,
+ [FromRoute, Required] GeneralCommandType command)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ var generalCommand = new GeneralCommand
+ {
+ Name = command,
+ ControllingUserId = currentSession.UserId
+ };
+
+ await _sessionManager.SendGeneralCommand(currentSession.Id, sessionId, generalCommand, CancellationToken.None);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Issues a general command to a client.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="command">The command to send.</param>
+ /// <response code="204">General command sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Command/{command}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SendGeneralCommand(
+ [FromRoute, Required] string sessionId,
+ [FromRoute, Required] GeneralCommandType command)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
+
+ var generalCommand = new GeneralCommand
+ {
+ Name = command,
+ ControllingUserId = currentSession.UserId
+ };
+
+ await _sessionManager.SendGeneralCommand(currentSession.Id, sessionId, generalCommand, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Issues a full general command to a client.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="command">The <see cref="GeneralCommand"/>.</param>
+ /// <response code="204">Full general command sent to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Command")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SendFullGeneralCommand(
+ [FromRoute, Required] string sessionId,
+ [FromBody, Required] GeneralCommand command)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authContext, Request)
+ .ConfigureAwait(false);
+
+ if (command == null)
+ {
+ throw new ArgumentException("Request body may not be null");
+ }
+
+ command.ControllingUserId = currentSession.UserId;
+
+ await _sessionManager.SendGeneralCommand(
+ currentSession.Id,
+ sessionId,
+ command,
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Issues a command to a client to display a message to the user.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="command">The <see cref="MessageCommand" /> object containing Header, Message Text, and TimeoutMs.</param>
+ /// <response code="204">Message sent.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/Message")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SendMessageCommand(
+ [FromRoute, Required] string sessionId,
+ [FromBody, Required] MessageCommand command)
+ {
+ if (string.IsNullOrWhiteSpace(command.Header))
+ {
+ command.Header = "Message from Server";
+ }
+
+ await _sessionManager.SendMessageCommand(
+ await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false),
+ sessionId,
+ command,
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Adds an additional user to a session.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <response code="204">User added to session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/{sessionId}/User/{userId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult AddUserToSession(
+ [FromRoute, Required] string sessionId,
+ [FromRoute, Required] Guid userId)
+ {
+ _sessionManager.AddAdditionalUser(sessionId, userId);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Removes an additional user from a session.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <response code="204">User removed from session.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Sessions/{sessionId}/User/{userId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult RemoveUserFromSession(
+ [FromRoute, Required] string sessionId,
+ [FromRoute, Required] Guid userId)
+ {
+ _sessionManager.RemoveAdditionalUser(sessionId, userId);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates capabilities for a device.
+ /// </summary>
+ /// <param name="id">The session id.</param>
+ /// <param name="playableMediaTypes">A list of playable media types, comma delimited. Audio, Video, Book, Photo.</param>
+ /// <param name="supportedCommands">A list of supported remote control commands, comma delimited.</param>
+ /// <param name="supportsMediaControl">Determines whether media can be played remotely..</param>
+ /// <param name="supportsSync">Determines whether sync is supported.</param>
+ /// <param name="supportsPersistentIdentifier">Determines whether the device supports a unique identifier.</param>
+ /// <response code="204">Capabilities posted.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Capabilities")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> PostCapabilities(
+ [FromQuery] string? id,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] playableMediaTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands,
+ [FromQuery] bool supportsMediaControl = false,
+ [FromQuery] bool supportsSync = false,
+ [FromQuery] bool supportsPersistentIdentifier = true)
+ {
+ if (string.IsNullOrWhiteSpace(id))
+ {
+ id = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ }
+
+ _sessionManager.ReportCapabilities(id, new ClientCapabilities
+ {
+ PlayableMediaTypes = playableMediaTypes,
+ SupportedCommands = supportedCommands,
+ SupportsMediaControl = supportsMediaControl,
+ SupportsSync = supportsSync,
+ SupportsPersistentIdentifier = supportsPersistentIdentifier
+ });
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates capabilities for a device.
+ /// </summary>
+ /// <param name="id">The session id.</param>
+ /// <param name="capabilities">The <see cref="ClientCapabilities"/>.</param>
+ /// <response code="204">Capabilities updated.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Capabilities/Full")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> PostFullCapabilities(
+ [FromQuery] string? id,
+ [FromBody, Required] ClientCapabilitiesDto capabilities)
+ {
+ if (string.IsNullOrWhiteSpace(id))
+ {
+ id = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+ }
+
+ _sessionManager.ReportCapabilities(id, capabilities.ToClientCapabilities());
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that a session is viewing an item.
+ /// </summary>
+ /// <param name="sessionId">The session id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="204">Session reported to server.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Viewing")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ReportViewing(
+ [FromQuery] string? sessionId,
+ [FromQuery, Required] string? itemId)
+ {
+ string session = sessionId ?? await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
+
+ _sessionManager.ReportNowViewingItem(session, itemId);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Reports that a session has ended.
+ /// </summary>
+ /// <response code="204">Session end reported to server.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Sessions/Logout")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> ReportSessionEnded()
+ {
+ AuthorizationInfo auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+
+ await _sessionManager.Logout(auth.Token).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Get all auth providers.
+ /// </summary>
+ /// <response code="200">Auth providers retrieved.</response>
+ /// <returns>An <see cref="IEnumerable{NameIdPair}"/> with the auth providers.</returns>
+ [HttpGet("Auth/Providers")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<NameIdPair>> GetAuthProviders()
+ {
+ return _userManager.GetAuthenticationProviders();
+ }
+
+ /// <summary>
+ /// Get all password reset providers.
+ /// </summary>
+ /// <response code="200">Password reset providers retrieved.</response>
+ /// <returns>An <see cref="IEnumerable{NameIdPair}"/> with the password reset providers.</returns>
+ [HttpGet("Auth/PasswordResetProviders")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ public ActionResult<IEnumerable<NameIdPair>> GetPasswordResetProviders()
+ {
+ return _userManager.GetPasswordResetProviders();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs
new file mode 100644
index 000000000..a01a617fc
--- /dev/null
+++ b/Jellyfin.Api/Controllers/StartupController.cs
@@ -0,0 +1,150 @@
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.StartupDtos;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The startup wizard controller.
+ /// </summary>
+ [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
+ public class StartupController : BaseJellyfinApiController
+ {
+ private readonly IServerConfigurationManager _config;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StartupController" /> class.
+ /// </summary>
+ /// <param name="config">The server configuration manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ public StartupController(IServerConfigurationManager config, IUserManager userManager)
+ {
+ _config = config;
+ _userManager = userManager;
+ }
+
+ /// <summary>
+ /// Completes the startup wizard.
+ /// </summary>
+ /// <response code="204">Startup wizard completed.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Complete")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult CompleteWizard()
+ {
+ _config.Configuration.IsStartupWizardCompleted = true;
+ _config.SaveConfiguration();
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets the initial startup wizard configuration.
+ /// </summary>
+ /// <response code="200">Initial startup wizard configuration retrieved.</response>
+ /// <returns>An <see cref="OkResult"/> containing the initial startup wizard configuration.</returns>
+ [HttpGet("Configuration")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<StartupConfigurationDto> GetStartupConfiguration()
+ {
+ return new StartupConfigurationDto
+ {
+ UICulture = _config.Configuration.UICulture,
+ MetadataCountryCode = _config.Configuration.MetadataCountryCode,
+ PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage
+ };
+ }
+
+ /// <summary>
+ /// Sets the initial startup wizard configuration.
+ /// </summary>
+ /// <param name="startupConfiguration">The updated startup configuration.</param>
+ /// <response code="204">Configuration saved.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Configuration")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateInitialConfiguration([FromBody, Required] StartupConfigurationDto startupConfiguration)
+ {
+ _config.Configuration.UICulture = startupConfiguration.UICulture ?? string.Empty;
+ _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode ?? string.Empty;
+ _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage ?? string.Empty;
+ _config.SaveConfiguration();
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Sets remote access and UPnP.
+ /// </summary>
+ /// <param name="startupRemoteAccessDto">The startup remote access dto.</param>
+ /// <response code="204">Configuration saved.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("RemoteAccess")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult SetRemoteAccess([FromBody, Required] StartupRemoteAccessDto startupRemoteAccessDto)
+ {
+ NetworkConfiguration settings = _config.GetNetworkConfiguration();
+ settings.EnableRemoteAccess = startupRemoteAccessDto.EnableRemoteAccess;
+ settings.EnableUPnP = startupRemoteAccessDto.EnableAutomaticPortMapping;
+ _config.SaveConfiguration("network", settings);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets the first user.
+ /// </summary>
+ /// <response code="200">Initial user retrieved.</response>
+ /// <returns>The first user.</returns>
+ [HttpGet("User")]
+ [HttpGet("FirstUser", Name = "GetFirstUser_2")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<StartupUserDto> GetFirstUser()
+ {
+ // TODO: Remove this method when startup wizard no longer requires an existing user.
+ await _userManager.InitializeAsync().ConfigureAwait(false);
+ var user = _userManager.Users.First();
+ return new StartupUserDto
+ {
+ Name = user.Username,
+ Password = user.Password
+ };
+ }
+
+ /// <summary>
+ /// Sets the user name and password.
+ /// </summary>
+ /// <param name="startupUserDto">The DTO containing username and password.</param>
+ /// <response code="204">Updated user name and password.</response>
+ /// <returns>
+ /// A <see cref="Task" /> that represents the asynchronous update operation.
+ /// The task result contains a <see cref="NoContentResult"/> indicating success.
+ /// </returns>
+ [HttpPost("User")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> UpdateStartupUser([FromBody] StartupUserDto startupUserDto)
+ {
+ var user = _userManager.Users.First();
+
+ if (startupUserDto.Name != null)
+ {
+ user.Username = startupUserDto.Name;
+ }
+
+ await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
+
+ if (!string.IsNullOrEmpty(startupUserDto.Password))
+ {
+ await _userManager.ChangePassword(user, startupUserDto.Password).ConfigureAwait(false);
+ }
+
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs
new file mode 100644
index 000000000..da8f8b199
--- /dev/null
+++ b/Jellyfin.Api/Controllers/StudiosController.cs
@@ -0,0 +1,154 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Studios controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class StudiosController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StudiosController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ public StudiosController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ }
+
+ /// <summary>
+ /// Gets all studios from a given item, folder, or the entire library.
+ /// </summary>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="searchTerm">Optional. Search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="enableTotalRecordCount">Total record count.</param>
+ /// <response code="200">Studios returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the studios.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetStudios(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isFavorite,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool enableTotalRecordCount = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
+
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ StartIndex = startIndex,
+ Limit = limit,
+ IsFavorite = isFavorite,
+ NameLessThan = nameLessThan,
+ NameStartsWith = nameStartsWith,
+ NameStartsWithOrGreater = nameStartsWithOrGreater,
+ DtoOptions = dtoOptions,
+ SearchTerm = searchTerm,
+ EnableTotalRecordCount = enableTotalRecordCount
+ };
+
+ if (parentId.HasValue)
+ {
+ if (parentItem is Folder)
+ {
+ query.AncestorIds = new[] { parentId.Value };
+ }
+ else
+ {
+ query.ItemIds = new[] { parentId.Value };
+ }
+ }
+
+ var result = _libraryManager.GetStudios(query);
+ var shouldIncludeItemTypes = includeItemTypes.Length != 0;
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
+ }
+
+ /// <summary>
+ /// Gets a studio by name.
+ /// </summary>
+ /// <param name="name">Studio name.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Studio returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the studio.</returns>
+ [HttpGet("{name}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BaseItemDto> GetStudio([FromRoute, Required] string name, [FromQuery] Guid? userId)
+ {
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ var item = _libraryManager.GetStudio(name);
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs
new file mode 100644
index 000000000..db8307f28
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SubtitleController.cs
@@ -0,0 +1,549 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net.Mime;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.SubtitleDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Controller.Subtitles;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Model.Subtitles;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Subtitle controller.
+ /// </summary>
+ [Route("")]
+ public class SubtitleController : BaseJellyfinApiController
+ {
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ISubtitleManager _subtitleManager;
+ private readonly ISubtitleEncoder _subtitleEncoder;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IProviderManager _providerManager;
+ private readonly IFileSystem _fileSystem;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILogger<SubtitleController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubtitleController"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="subtitleManager">Instance of <see cref="ISubtitleManager"/> interface.</param>
+ /// <param name="subtitleEncoder">Instance of <see cref="ISubtitleEncoder"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="providerManager">Instance of <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
+ /// <param name="authContext">Instance of <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="logger">Instance of <see cref="ILogger{SubtitleController}"/> interface.</param>
+ public SubtitleController(
+ IServerConfigurationManager serverConfigurationManager,
+ ILibraryManager libraryManager,
+ ISubtitleManager subtitleManager,
+ ISubtitleEncoder subtitleEncoder,
+ IMediaSourceManager mediaSourceManager,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ IAuthorizationContext authContext,
+ ILogger<SubtitleController> logger)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ _libraryManager = libraryManager;
+ _subtitleManager = subtitleManager;
+ _subtitleEncoder = subtitleEncoder;
+ _mediaSourceManager = mediaSourceManager;
+ _providerManager = providerManager;
+ _fileSystem = fileSystem;
+ _authContext = authContext;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Deletes an external subtitle file.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="index">The index of the subtitle file.</param>
+ /// <response code="204">Subtitle deleted.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Videos/{itemId}/Subtitles/{index}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<Task> DeleteSubtitle(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] int index)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ _subtitleManager.DeleteSubtitles(item, index);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Search remote subtitles.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="language">The language of the subtitles.</param>
+ /// <param name="isPerfectMatch">Optional. Only show subtitles which are a perfect match.</param>
+ /// <response code="200">Subtitles retrieved.</response>
+ /// <returns>An array of <see cref="RemoteSubtitleInfo"/>.</returns>
+ [HttpGet("Items/{itemId}/RemoteSearch/Subtitles/{language}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<IEnumerable<RemoteSubtitleInfo>>> SearchRemoteSubtitles(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string language,
+ [FromQuery] bool? isPerfectMatch)
+ {
+ var video = (Video)_libraryManager.GetItemById(itemId);
+
+ return await _subtitleManager.SearchSubtitles(video, language, isPerfectMatch, false, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Downloads a remote subtitle.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="subtitleId">The subtitle id.</param>
+ /// <response code="204">Subtitle downloaded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Items/{itemId}/RemoteSearch/Subtitles/{subtitleId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> DownloadRemoteSubtitles(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string subtitleId)
+ {
+ var video = (Video)_libraryManager.GetItemById(itemId);
+
+ try
+ {
+ await _subtitleManager.DownloadSubtitles(video, subtitleId, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error downloading subtitles");
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets the remote subtitles.
+ /// </summary>
+ /// <param name="id">The item id.</param>
+ /// <response code="200">File returned.</response>
+ /// <returns>A <see cref="FileStreamResult"/> with the subtitle file.</returns>
+ [HttpGet("Providers/Subtitles/Subtitles/{id}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Application.Octet)]
+ [ProducesFile("text/*")]
+ public async Task<ActionResult> GetRemoteSubtitles([FromRoute, Required] string id)
+ {
+ var result = await _subtitleManager.GetRemoteSubtitles(id, CancellationToken.None).ConfigureAwait(false);
+
+ return File(result.Stream, MimeTypes.GetMimeType("file." + result.Format));
+ }
+
+ /// <summary>
+ /// Gets subtitles in a specified format.
+ /// </summary>
+ /// <param name="routeItemId">The (route) item id.</param>
+ /// <param name="routeMediaSourceId">The (route) media source id.</param>
+ /// <param name="routeIndex">The (route) subtitle stream index.</param>
+ /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="index">The subtitle stream index.</param>
+ /// <param name="format">The format of the returned subtitle.</param>
+ /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
+ /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
+ /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
+ /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
+ /// <response code="200">File returned.</response>
+ /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
+ [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/Stream.{routeFormat}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile("text/*")]
+ public async Task<ActionResult> GetSubtitle(
+ [FromRoute, Required] Guid routeItemId,
+ [FromRoute, Required] string routeMediaSourceId,
+ [FromRoute, Required] int routeIndex,
+ [FromRoute, Required] string routeFormat,
+ [FromQuery, ParameterObsolete] Guid? itemId,
+ [FromQuery, ParameterObsolete] string? mediaSourceId,
+ [FromQuery, ParameterObsolete] int? index,
+ [FromQuery, ParameterObsolete] string? format,
+ [FromQuery] long? endPositionTicks,
+ [FromQuery] bool copyTimestamps = false,
+ [FromQuery] bool addVttTimeMap = false,
+ [FromQuery] long startPositionTicks = 0)
+ {
+ // Set parameters to route value if not provided via query.
+ itemId ??= routeItemId;
+ mediaSourceId ??= routeMediaSourceId;
+ index ??= routeIndex;
+ format ??= routeFormat;
+
+ if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase))
+ {
+ format = "json";
+ }
+
+ if (string.IsNullOrEmpty(format))
+ {
+ var item = (Video)_libraryManager.GetItemById(itemId.Value);
+
+ var idString = itemId.Value.ToString("N", CultureInfo.InvariantCulture);
+ var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false)
+ .First(i => string.Equals(i.Id, mediaSourceId ?? idString, StringComparison.Ordinal));
+
+ var subtitleStream = mediaSource.MediaStreams
+ .First(i => i.Type == MediaStreamType.Subtitle && i.Index == index);
+
+ return PhysicalFile(subtitleStream.Path, MimeTypes.GetMimeType(subtitleStream.Path));
+ }
+
+ if (string.Equals(format, "vtt", StringComparison.OrdinalIgnoreCase) && addVttTimeMap)
+ {
+ await using Stream stream = await EncodeSubtitles(itemId.Value, mediaSourceId, index.Value, format, startPositionTicks, endPositionTicks, copyTimestamps).ConfigureAwait(false);
+ using var reader = new StreamReader(stream);
+
+ var text = await reader.ReadToEndAsync().ConfigureAwait(false);
+
+ text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000", StringComparison.Ordinal);
+
+ return File(Encoding.UTF8.GetBytes(text), MimeTypes.GetMimeType("file." + format));
+ }
+
+ return File(
+ await EncodeSubtitles(
+ itemId.Value,
+ mediaSourceId,
+ index.Value,
+ format,
+ startPositionTicks,
+ endPositionTicks,
+ copyTimestamps).ConfigureAwait(false),
+ MimeTypes.GetMimeType("file." + format));
+ }
+
+ /// <summary>
+ /// Gets subtitles in a specified format.
+ /// </summary>
+ /// <param name="routeItemId">The (route) item id.</param>
+ /// <param name="routeMediaSourceId">The (route) media source id.</param>
+ /// <param name="routeIndex">The (route) subtitle stream index.</param>
+ /// <param name="routeStartPositionTicks">The (route) start position of the subtitle in ticks.</param>
+ /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="index">The subtitle stream index.</param>
+ /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
+ /// <param name="format">The format of the returned subtitle.</param>
+ /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
+ /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
+ /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
+ /// <response code="200">File returned.</response>
+ /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
+ [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/{routeStartPositionTicks}/Stream.{routeFormat}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile("text/*")]
+ public Task<ActionResult> GetSubtitleWithTicks(
+ [FromRoute, Required] Guid routeItemId,
+ [FromRoute, Required] string routeMediaSourceId,
+ [FromRoute, Required] int routeIndex,
+ [FromRoute, Required] long routeStartPositionTicks,
+ [FromRoute, Required] string routeFormat,
+ [FromQuery, ParameterObsolete] Guid? itemId,
+ [FromQuery, ParameterObsolete] string? mediaSourceId,
+ [FromQuery, ParameterObsolete] int? index,
+ [FromQuery, ParameterObsolete] long? startPositionTicks,
+ [FromQuery, ParameterObsolete] string? format,
+ [FromQuery] long? endPositionTicks,
+ [FromQuery] bool copyTimestamps = false,
+ [FromQuery] bool addVttTimeMap = false)
+ {
+ return GetSubtitle(
+ routeItemId,
+ routeMediaSourceId,
+ routeIndex,
+ routeFormat,
+ itemId,
+ mediaSourceId,
+ index,
+ format,
+ endPositionTicks,
+ copyTimestamps,
+ addVttTimeMap,
+ startPositionTicks ?? routeStartPositionTicks);
+ }
+
+ /// <summary>
+ /// Gets an HLS subtitle playlist.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="index">The subtitle stream index.</param>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="segmentLength">The subtitle segment length.</param>
+ /// <response code="200">Subtitle playlist retrieved.</response>
+ /// <returns>A <see cref="FileContentResult"/> with the HLS subtitle playlist.</returns>
+ [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/subtitles.m3u8")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ public async Task<ActionResult> GetSubtitlePlaylist(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] int index,
+ [FromRoute, Required] string mediaSourceId,
+ [FromQuery, Required] int segmentLength)
+ {
+ var item = (Video)_libraryManager.GetItemById(itemId);
+
+ var mediaSource = await _mediaSourceManager.GetMediaSource(item, mediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
+
+ var runtime = mediaSource.RunTimeTicks ?? -1;
+
+ if (runtime <= 0)
+ {
+ throw new ArgumentException("HLS Subtitles are not supported for this media.");
+ }
+
+ var segmentLengthTicks = TimeSpan.FromSeconds(segmentLength).Ticks;
+ if (segmentLengthTicks <= 0)
+ {
+ throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
+ }
+
+ var builder = new StringBuilder();
+ builder.AppendLine("#EXTM3U")
+ .Append("#EXT-X-TARGETDURATION:")
+ .Append(segmentLength)
+ .AppendLine()
+ .AppendLine("#EXT-X-VERSION:3")
+ .AppendLine("#EXT-X-MEDIA-SEQUENCE:0")
+ .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
+
+ long positionTicks = 0;
+
+ var accessToken = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).Token;
+
+ while (positionTicks < runtime)
+ {
+ var remaining = runtime - positionTicks;
+ var lengthTicks = Math.Min(remaining, segmentLengthTicks);
+
+ builder.Append("#EXTINF:")
+ .Append(TimeSpan.FromTicks(lengthTicks).TotalSeconds)
+ .Append(',')
+ .AppendLine();
+
+ var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
+
+ var url = string.Format(
+ CultureInfo.InvariantCulture,
+ "stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
+ positionTicks.ToString(CultureInfo.InvariantCulture),
+ endPositionTicks.ToString(CultureInfo.InvariantCulture),
+ accessToken);
+
+ builder.AppendLine(url);
+
+ positionTicks += segmentLengthTicks;
+ }
+
+ builder.AppendLine("#EXT-X-ENDLIST");
+ return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
+ }
+
+ /// <summary>
+ /// Upload an external subtitle file.
+ /// </summary>
+ /// <param name="itemId">The item the subtitle belongs to.</param>
+ /// <param name="body">The request body.</param>
+ /// <response code="204">Subtitle uploaded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Videos/{itemId}/Subtitles")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> UploadSubtitle(
+ [FromRoute, Required] Guid itemId,
+ [FromBody, Required] UploadSubtitleDto body)
+ {
+ var video = (Video)_libraryManager.GetItemById(itemId);
+ var data = Convert.FromBase64String(body.Data);
+ await using var memoryStream = new MemoryStream(data);
+ await _subtitleManager.UploadSubtitle(
+ video,
+ new SubtitleResponse
+ {
+ Format = body.Format,
+ Language = body.Language,
+ IsForced = body.IsForced,
+ Stream = memoryStream
+ }).ConfigureAwait(false);
+ _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Encodes a subtitle in the specified format.
+ /// </summary>
+ /// <param name="id">The media id.</param>
+ /// <param name="mediaSourceId">The source media id.</param>
+ /// <param name="index">The subtitle index.</param>
+ /// <param name="format">The format to convert to.</param>
+ /// <param name="startPositionTicks">The start position in ticks.</param>
+ /// <param name="endPositionTicks">The end position in ticks.</param>
+ /// <param name="copyTimestamps">Whether to copy the timestamps.</param>
+ /// <returns>A <see cref="Task{Stream}"/> with the new subtitle file.</returns>
+ private Task<Stream> EncodeSubtitles(
+ Guid id,
+ string? mediaSourceId,
+ int index,
+ string format,
+ long startPositionTicks,
+ long? endPositionTicks,
+ bool copyTimestamps)
+ {
+ var item = _libraryManager.GetItemById(id);
+
+ return _subtitleEncoder.GetSubtitles(
+ item,
+ mediaSourceId,
+ index,
+ format,
+ startPositionTicks,
+ endPositionTicks ?? 0,
+ copyTimestamps,
+ CancellationToken.None);
+ }
+
+ /// <summary>
+ /// Gets a list of available fallback font files.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>An array of <see cref="FontFile"/> with the available font files.</returns>
+ [HttpGet("FallbackFont/Fonts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable<FontFile> GetFallbackFontList()
+ {
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var fallbackFontPath = encodingOptions.FallbackFontPath;
+
+ if (!string.IsNullOrEmpty(fallbackFontPath))
+ {
+ var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false);
+ var fontFiles = files
+ .Select(i => new FontFile
+ {
+ Name = i.Name,
+ Size = i.Length,
+ DateCreated = _fileSystem.GetCreationTimeUtc(i),
+ DateModified = _fileSystem.GetLastWriteTimeUtc(i)
+ })
+ .OrderBy(i => i.Size)
+ .ThenBy(i => i.Name)
+ .ThenByDescending(i => i.DateModified)
+ .ThenByDescending(i => i.DateCreated);
+ // max total size 20M
+ const int MaxSize = 20971520;
+ var sizeCounter = 0L;
+ foreach (var fontFile in fontFiles)
+ {
+ sizeCounter += fontFile.Size;
+ if (sizeCounter >= MaxSize)
+ {
+ _logger.LogWarning("Some fonts will not be sent due to size limitations");
+ yield break;
+ }
+
+ yield return fontFile;
+ }
+ }
+ else
+ {
+ _logger.LogWarning("The path of fallback font folder has not been set");
+ encodingOptions.EnableFallbackFont = false;
+ }
+ }
+
+ /// <summary>
+ /// Gets a fallback font file.
+ /// </summary>
+ /// <param name="name">The name of the fallback font file to get.</param>
+ /// <response code="200">Fallback font file retrieved.</response>
+ /// <returns>The fallback font file.</returns>
+ [HttpGet("FallbackFont/Fonts/{name}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile("font/*")]
+ public ActionResult GetFallbackFont([FromRoute, Required] string name)
+ {
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var fallbackFontPath = encodingOptions.FallbackFontPath;
+
+ if (!string.IsNullOrEmpty(fallbackFontPath))
+ {
+ var fontFile = _fileSystem.GetFiles(fallbackFontPath)
+ .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
+ var fileSize = fontFile?.Length;
+
+ if (fontFile != null && fileSize != null && fileSize > 0)
+ {
+ _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize);
+ return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName));
+ }
+ else
+ {
+ _logger.LogWarning("The selected font is null or empty");
+ }
+ }
+ else
+ {
+ _logger.LogWarning("The path of fallback font folder has not been set");
+ encodingOptions.EnableFallbackFont = false;
+ }
+
+ // returning HTTP 204 will break the SubtitlesOctopus
+ return Ok();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs
new file mode 100644
index 000000000..97eec4bd2
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SuggestionsController.cs
@@ -0,0 +1,91 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The suggestions controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class SuggestionsController : BaseJellyfinApiController
+ {
+ private readonly IDtoService _dtoService;
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SuggestionsController"/> class.
+ /// </summary>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public SuggestionsController(
+ IDtoService dtoService,
+ IUserManager userManager,
+ ILibraryManager libraryManager)
+ {
+ _dtoService = dtoService;
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Gets suggestions.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="mediaType">The media types.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="startIndex">Optional. The start index.</param>
+ /// <param name="limit">Optional. The limit.</param>
+ /// <param name="enableTotalRecordCount">Whether to enable the total record count.</param>
+ /// <response code="200">Suggestions returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the suggestions.</returns>
+ [HttpGet("Users/{userId}/Suggestions")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetSuggestions(
+ [FromRoute, Required] Guid userId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaType,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] type,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool enableTotalRecordCount = false)
+ {
+ var user = !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId) : null;
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
+ {
+ OrderBy = new[] { (ItemSortBy.Random, SortOrder.Descending) },
+ MediaTypes = mediaType,
+ IncludeItemTypes = type,
+ IsVirtualItem = false,
+ StartIndex = startIndex,
+ Limit = limit,
+ DtoOptions = dtoOptions,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ Recursive = true
+ });
+
+ var dtoList = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = result.TotalRecordCount,
+ Items = dtoList
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs
new file mode 100644
index 000000000..c6b70f3d2
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SyncPlayController.cs
@@ -0,0 +1,423 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.SyncPlayDtos;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Controller.SyncPlay.Requests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The sync play controller.
+ /// </summary>
+ [Authorize(Policy = Policies.SyncPlayHasAccess)]
+ public class SyncPlayController : BaseJellyfinApiController
+ {
+ private readonly ISessionManager _sessionManager;
+ private readonly IAuthorizationContext _authorizationContext;
+ private readonly ISyncPlayManager _syncPlayManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayController"/> class.
+ /// </summary>
+ /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
+ /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="syncPlayManager">Instance of the <see cref="ISyncPlayManager"/> interface.</param>
+ public SyncPlayController(
+ ISessionManager sessionManager,
+ IAuthorizationContext authorizationContext,
+ ISyncPlayManager syncPlayManager)
+ {
+ _sessionManager = sessionManager;
+ _authorizationContext = authorizationContext;
+ _syncPlayManager = syncPlayManager;
+ }
+
+ /// <summary>
+ /// Create a new SyncPlay group.
+ /// </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>
+ [HttpPost("New")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayCreateGroup)]
+ public async Task<ActionResult> SyncPlayCreateGroup(
+ [FromBody, Required] NewGroupRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new NewGroupRequest(requestData.GroupName);
+ _syncPlayManager.NewGroup(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Join an existing SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The group to join.</param>
+ /// <response code="204">Group join successful.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Join")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayJoinGroup)]
+ public async Task<ActionResult> SyncPlayJoinGroup(
+ [FromBody, Required] JoinGroupRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new JoinGroupRequest(requestData.GroupId);
+ _syncPlayManager.JoinGroup(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Leave the joined SyncPlay group.
+ /// </summary>
+ /// <response code="204">Group leave successful.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Leave")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayLeaveGroup()
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new LeaveGroupRequest();
+ _syncPlayManager.LeaveGroup(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets all SyncPlay groups.
+ /// </summary>
+ /// <response code="200">Groups returned.</response>
+ /// <returns>An <see cref="IEnumerable{GroupInfoView}"/> containing the available SyncPlay groups.</returns>
+ [HttpGet("List")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Authorize(Policy = Policies.SyncPlayJoinGroup)]
+ public async Task<ActionResult<IEnumerable<GroupInfoDto>>> SyncPlayGetGroups()
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new ListGroupsRequest();
+ return Ok(_syncPlayManager.ListGroups(currentSession, syncPlayRequest));
+ }
+
+ /// <summary>
+ /// Request to set new playlist in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new playlist to play in the group.</param>
+ /// <response code="204">Queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("SetNewQueue")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySetNewQueue(
+ [FromBody, Required] PlayRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new PlayGroupRequest(
+ requestData.PlayingQueue,
+ requestData.PlayingItemPosition,
+ requestData.StartPositionTicks);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to change playlist item in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new item to play.</param>
+ /// <response code="204">Queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("SetPlaylistItem")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySetPlaylistItem(
+ [FromBody, Required] SetPlaylistItemRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new SetPlaylistItemGroupRequest(requestData.PlaylistItemId);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to remove items from the playlist in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The items to remove.</param>
+ /// <response code="204">Queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("RemoveFromPlaylist")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayRemoveFromPlaylist(
+ [FromBody, Required] RemoveFromPlaylistRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new RemoveFromPlaylistGroupRequest(requestData.PlaylistItemIds, requestData.ClearPlaylist, requestData.ClearPlayingItem);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to move an item in the playlist in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new position for the item.</param>
+ /// <response code="204">Queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("MovePlaylistItem")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayMovePlaylistItem(
+ [FromBody, Required] MovePlaylistItemRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new MovePlaylistItemGroupRequest(requestData.PlaylistItemId, requestData.NewIndex);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to queue items to the playlist of a SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The items to add.</param>
+ /// <response code="204">Queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Queue")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayQueue(
+ [FromBody, Required] QueueRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new QueueGroupRequest(requestData.ItemIds, requestData.Mode);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request unpause in SyncPlay group.
+ /// </summary>
+ /// <response code="204">Unpause update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Unpause")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayUnpause()
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new UnpauseGroupRequest();
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request pause in SyncPlay group.
+ /// </summary>
+ /// <response code="204">Pause update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Pause")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayPause()
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new PauseGroupRequest();
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request stop in SyncPlay group.
+ /// </summary>
+ /// <response code="204">Stop update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Stop")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayStop()
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new StopGroupRequest();
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request seek in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new playback position.</param>
+ /// <response code="204">Seek update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Seek")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySeek(
+ [FromBody, Required] SeekRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new SeekGroupRequest(requestData.PositionTicks);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Notify SyncPlay group that member is buffering.
+ /// </summary>
+ /// <param name="requestData">The player status.</param>
+ /// <response code="204">Group state update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Buffering")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayBuffering(
+ [FromBody, Required] BufferRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new BufferGroupRequest(
+ requestData.When,
+ requestData.PositionTicks,
+ requestData.IsPlaying,
+ requestData.PlaylistItemId);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Notify SyncPlay group that member is ready for playback.
+ /// </summary>
+ /// <param name="requestData">The player status.</param>
+ /// <response code="204">Group state update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Ready")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayReady(
+ [FromBody, Required] ReadyRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new ReadyGroupRequest(
+ requestData.When,
+ requestData.PositionTicks,
+ requestData.IsPlaying,
+ requestData.PlaylistItemId);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request SyncPlay group to ignore member during group-wait.
+ /// </summary>
+ /// <param name="requestData">The settings to set.</param>
+ /// <response code="204">Member state updated.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("SetIgnoreWait")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySetIgnoreWait(
+ [FromBody, Required] IgnoreWaitRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new IgnoreWaitGroupRequest(requestData.IgnoreWait);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request next item in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The current item information.</param>
+ /// <response code="204">Next item update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("NextItem")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayNextItem(
+ [FromBody, Required] NextItemRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new NextItemGroupRequest(requestData.PlaylistItemId);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request previous item in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The current item information.</param>
+ /// <response code="204">Previous item update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("PreviousItem")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlayPreviousItem(
+ [FromBody, Required] PreviousItemRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new PreviousItemGroupRequest(requestData.PlaylistItemId);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to set repeat mode in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new repeat mode.</param>
+ /// <response code="204">Play queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("SetRepeatMode")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySetRepeatMode(
+ [FromBody, Required] SetRepeatModeRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new SetRepeatModeGroupRequest(requestData.Mode);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Request to set shuffle mode in SyncPlay group.
+ /// </summary>
+ /// <param name="requestData">The new shuffle mode.</param>
+ /// <response code="204">Play queue update sent to all group members.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("SetShuffleMode")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Authorize(Policy = Policies.SyncPlayIsInGroup)]
+ public async Task<ActionResult> SyncPlaySetShuffleMode(
+ [FromBody, Required] SetShuffleModeRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new SetShuffleModeGroupRequest(requestData.Mode);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Update session ping.
+ /// </summary>
+ /// <param name="requestData">The new ping.</param>
+ /// <response code="204">Ping updated.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("Ping")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task<ActionResult> SyncPlayPing(
+ [FromBody, Required] PingRequestDto requestData)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request).ConfigureAwait(false);
+ var syncPlayRequest = new PingGroupRequest(requestData.Ping);
+ _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None);
+ return NoContent();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs
new file mode 100644
index 000000000..904738bb4
--- /dev/null
+++ b/Jellyfin.Api/Controllers/SystemController.cs
@@ -0,0 +1,222 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.System;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The system controller.
+ /// </summary>
+ public class SystemController : BaseJellyfinApiController
+ {
+ private readonly IServerApplicationHost _appHost;
+ private readonly IApplicationPaths _appPaths;
+ private readonly IFileSystem _fileSystem;
+ private readonly INetworkManager _network;
+ private readonly ILogger<SystemController> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SystemController"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="appHost">Instance of <see cref="IServerApplicationHost"/> interface.</param>
+ /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
+ /// <param name="network">Instance of <see cref="INetworkManager"/> interface.</param>
+ /// <param name="logger">Instance of <see cref="ILogger{SystemController}"/> interface.</param>
+ public SystemController(
+ IServerConfigurationManager serverConfigurationManager,
+ IServerApplicationHost appHost,
+ IFileSystem fileSystem,
+ INetworkManager network,
+ ILogger<SystemController> logger)
+ {
+ _appPaths = serverConfigurationManager.ApplicationPaths;
+ _appHost = appHost;
+ _fileSystem = fileSystem;
+ _network = network;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Gets information about the server.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>A <see cref="SystemInfo"/> with info about the system.</returns>
+ [HttpGet("Info")]
+ [Authorize(Policy = Policies.FirstTimeSetupOrIgnoreParentalControl)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<SystemInfo> GetSystemInfo()
+ {
+ return _appHost.GetSystemInfo(Request);
+ }
+
+ /// <summary>
+ /// Gets public information about the server.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>A <see cref="PublicSystemInfo"/> with public info about the system.</returns>
+ [HttpGet("Info/Public")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<PublicSystemInfo> GetPublicSystemInfo()
+ {
+ return _appHost.GetPublicSystemInfo(Request);
+ }
+
+ /// <summary>
+ /// Pings the system.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>The server name.</returns>
+ [HttpGet("Ping", Name = "GetPingSystem")]
+ [HttpPost("Ping", Name = "PostPingSystem")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<string> PingSystem()
+ {
+ return _appHost.Name;
+ }
+
+ /// <summary>
+ /// Restarts the application.
+ /// </summary>
+ /// <response code="204">Server restarted.</response>
+ /// <returns>No content. Server restarted.</returns>
+ [HttpPost("Restart")]
+ [Authorize(Policy = Policies.LocalAccessOrRequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult RestartApplication()
+ {
+ Task.Run(async () =>
+ {
+ await Task.Delay(100).ConfigureAwait(false);
+ _appHost.Restart();
+ });
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Shuts down the application.
+ /// </summary>
+ /// <response code="204">Server shut down.</response>
+ /// <returns>No content. Server shut down.</returns>
+ [HttpPost("Shutdown")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult ShutdownApplication()
+ {
+ Task.Run(async () =>
+ {
+ await Task.Delay(100).ConfigureAwait(false);
+ await _appHost.Shutdown().ConfigureAwait(false);
+ });
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a list of available server log files.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>An array of <see cref="LogFile"/> with the available log files.</returns>
+ [HttpGet("Logs")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<LogFile[]> GetServerLogs()
+ {
+ IEnumerable<FileSystemMetadata> files;
+
+ try
+ {
+ files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt", ".log" }, true, false);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error getting logs");
+ files = Enumerable.Empty<FileSystemMetadata>();
+ }
+
+ var result = files.Select(i => new LogFile
+ {
+ DateCreated = _fileSystem.GetCreationTimeUtc(i),
+ DateModified = _fileSystem.GetLastWriteTimeUtc(i),
+ Name = i.Name,
+ Size = i.Length
+ })
+ .OrderByDescending(i => i.DateModified)
+ .ThenByDescending(i => i.DateCreated)
+ .ThenBy(i => i.Name)
+ .ToArray();
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets information about the request endpoint.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns><see cref="EndPointInfo"/> with information about the endpoint.</returns>
+ [HttpGet("Endpoint")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<EndPointInfo> GetEndpointInfo()
+ {
+ return new EndPointInfo
+ {
+ IsLocal = HttpContext.IsLocal(),
+ IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())
+ };
+ }
+
+ /// <summary>
+ /// Gets a log file.
+ /// </summary>
+ /// <param name="name">The name of the log file to get.</param>
+ /// <response code="200">Log file retrieved.</response>
+ /// <returns>The log file.</returns>
+ [HttpGet("Logs/Log")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesFile(MediaTypeNames.Text.Plain)]
+ public ActionResult GetLogFile([FromQuery, Required] string name)
+ {
+ var file = _fileSystem.GetFiles(_appPaths.LogDirectoryPath)
+ .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
+
+ // For older files, assume fully static
+ var fileShare = file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite;
+ FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, fileShare, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ return File(stream, "text/plain; charset=utf-8");
+ }
+
+ /// <summary>
+ /// Gets wake on lan information.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <returns>An <see cref="IEnumerable{WakeOnLanInfo}"/> with the WakeOnLan infos.</returns>
+ [HttpGet("WakeOnLanInfo")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<WakeOnLanInfo>> GetWakeOnLanInfo()
+ {
+ var result = _appHost.GetWakeOnLanInfo();
+ return Ok(result);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/TimeSyncController.cs b/Jellyfin.Api/Controllers/TimeSyncController.cs
new file mode 100644
index 000000000..e7c5a7125
--- /dev/null
+++ b/Jellyfin.Api/Controllers/TimeSyncController.cs
@@ -0,0 +1,34 @@
+using System;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The time sync controller.
+ /// </summary>
+ [Route("")]
+ public class TimeSyncController : BaseJellyfinApiController
+ {
+ /// <summary>
+ /// Gets the current UTC time.
+ /// </summary>
+ /// <response code="200">Time returned.</response>
+ /// <returns>An <see cref="UtcTimeResponse"/> to sync the client and server time.</returns>
+ [HttpGet("GetUtcTime")]
+ [ProducesResponseType(statusCode: StatusCodes.Status200OK)]
+ public ActionResult<UtcTimeResponse> GetUtcTime()
+ {
+ // Important to keep the following line at the beginning
+ var requestReceptionTime = DateTime.UtcNow;
+
+ // Important to keep the following line at the end
+ var responseTransmissionTime = DateTime.UtcNow;
+
+ // Implementing NTP on such a high level results in this useless
+ // information being sent. On the other hand it enables future additions.
+ return new UtcTimeResponse(requestReceptionTime, responseTransmissionTime);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs
new file mode 100644
index 000000000..5cb7468b2
--- /dev/null
+++ b/Jellyfin.Api/Controllers/TrailersController.cs
@@ -0,0 +1,283 @@
+using System;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The trailers controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class TrailersController : BaseJellyfinApiController
+ {
+ private readonly ItemsController _itemsController;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TrailersController"/> class.
+ /// </summary>
+ /// <param name="itemsController">Instance of <see cref="ItemsController"/>.</param>
+ public TrailersController(ItemsController itemsController)
+ {
+ _itemsController = itemsController;
+ }
+
+ /// <summary>
+ /// Finds movies and trailers similar to a given trailer.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
+ /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
+ /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
+ /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
+ /// <param name="hasTrailer">Optional filter by items with trailers.</param>
+ /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
+ /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
+ /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
+ /// <param name="isHd">Optional filter by items that are HD or not.</param>
+ /// <param name="is4K">Optional filter by items that are 4K or not.</param>
+ /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
+ /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
+ /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
+ /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
+ /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
+ /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
+ /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
+ /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
+ /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
+ /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
+ /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
+ /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
+ /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
+ /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
+ /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
+ /// <param name="searchTerm">Optional. Filter based on a search term.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
+ /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
+ /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
+ /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
+ /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
+ /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
+ /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional, include user data.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
+ /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
+ /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
+ /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
+ /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
+ /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
+ /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
+ /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
+ /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
+ /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
+ /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
+ /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
+ /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
+ /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
+ /// <param name="isLocked">Optional filter by items that are locked.</param>
+ /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
+ /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
+ /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
+ /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
+ /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
+ /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
+ /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
+ /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
+ /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
+ /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
+ /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
+ /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
+ /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
+ /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
+ /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the trailers.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetTrailers(
+ [FromQuery] Guid userId,
+ [FromQuery] string? maxOfficialRating,
+ [FromQuery] bool? hasThemeSong,
+ [FromQuery] bool? hasThemeVideo,
+ [FromQuery] bool? hasSubtitles,
+ [FromQuery] bool? hasSpecialFeature,
+ [FromQuery] bool? hasTrailer,
+ [FromQuery] string? adjacentTo,
+ [FromQuery] int? parentIndexNumber,
+ [FromQuery] bool? hasParentalRating,
+ [FromQuery] bool? isHd,
+ [FromQuery] bool? is4K,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
+ [FromQuery] bool? isMissing,
+ [FromQuery] bool? isUnaired,
+ [FromQuery] double? minCommunityRating,
+ [FromQuery] double? minCriticRating,
+ [FromQuery] DateTime? minPremiereDate,
+ [FromQuery] DateTime? minDateLastSaved,
+ [FromQuery] DateTime? minDateLastSavedForUser,
+ [FromQuery] DateTime? maxPremiereDate,
+ [FromQuery] bool? hasOverview,
+ [FromQuery] bool? hasImdbId,
+ [FromQuery] bool? hasTmdbId,
+ [FromQuery] bool? hasTvdbId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool? recursive,
+ [FromQuery] string? searchTerm,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
+ [FromQuery] bool? isFavorite,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery] bool? isPlayed,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
+ [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? person,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] studios,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] artists,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] albums,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
+ [FromQuery] string? minOfficialRating,
+ [FromQuery] bool? isLocked,
+ [FromQuery] bool? isPlaceHolder,
+ [FromQuery] bool? hasOfficialRating,
+ [FromQuery] bool? collapseBoxSetItems,
+ [FromQuery] int? minWidth,
+ [FromQuery] int? minHeight,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] bool? is3D,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
+ [FromQuery] string? nameStartsWithOrGreater,
+ [FromQuery] string? nameStartsWith,
+ [FromQuery] string? nameLessThan,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool? enableImages = true)
+ {
+ var includeItemTypes = new[] { BaseItemKind.Trailer };
+
+ return _itemsController
+ .GetItems(
+ userId,
+ maxOfficialRating,
+ hasThemeSong,
+ hasThemeVideo,
+ hasSubtitles,
+ hasSpecialFeature,
+ hasTrailer,
+ adjacentTo,
+ parentIndexNumber,
+ hasParentalRating,
+ isHd,
+ is4K,
+ locationTypes,
+ excludeLocationTypes,
+ isMissing,
+ isUnaired,
+ minCommunityRating,
+ minCriticRating,
+ minPremiereDate,
+ minDateLastSaved,
+ minDateLastSavedForUser,
+ maxPremiereDate,
+ hasOverview,
+ hasImdbId,
+ hasTmdbId,
+ hasTvdbId,
+ excludeItemIds,
+ startIndex,
+ limit,
+ recursive,
+ searchTerm,
+ sortOrder,
+ parentId,
+ fields,
+ excludeItemTypes,
+ includeItemTypes,
+ filters,
+ isFavorite,
+ mediaTypes,
+ imageTypes,
+ sortBy,
+ isPlayed,
+ genres,
+ officialRatings,
+ tags,
+ years,
+ enableUserData,
+ imageTypeLimit,
+ enableImageTypes,
+ person,
+ personIds,
+ personTypes,
+ studios,
+ artists,
+ excludeArtistIds,
+ artistIds,
+ albumArtistIds,
+ contributingArtistIds,
+ albums,
+ albumIds,
+ ids,
+ videoTypes,
+ minOfficialRating,
+ isLocked,
+ isPlaceHolder,
+ hasOfficialRating,
+ collapseBoxSetItems,
+ minWidth,
+ minHeight,
+ maxWidth,
+ maxHeight,
+ is3D,
+ seriesStatus,
+ nameStartsWithOrGreater,
+ nameStartsWith,
+ nameLessThan,
+ studioIds,
+ genreIds,
+ enableTotalRecordCount,
+ enableImages);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs
new file mode 100644
index 000000000..5dd773331
--- /dev/null
+++ b/Jellyfin.Api/Controllers/TvShowsController.cs
@@ -0,0 +1,388 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.TV;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The tv shows controller.
+ /// </summary>
+ [Route("Shows")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class TvShowsController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly ITVSeriesManager _tvSeriesManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TvShowsController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="tvSeriesManager">Instance of the <see cref="ITVSeriesManager"/> interface.</param>
+ public TvShowsController(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ ITVSeriesManager tvSeriesManager)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _tvSeriesManager = tvSeriesManager;
+ }
+
+ /// <summary>
+ /// Gets a list of next up episodes.
+ /// </summary>
+ /// <param name="userId">The user id of the user to get the next up episodes for.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="seriesId">Optional. Filter by series id.</param>
+ /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="enableImges">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="nextUpDateCutoff">Optional. Starting date of shows to show in Next Up section.</param>
+ /// <param name="enableTotalRecordCount">Whether to enable the total records count. Defaults to true.</param>
+ /// <param name="disableFirstEpisode">Whether to disable sending the first episode in a series as next up.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the next up episodes.</returns>
+ [HttpGet("NextUp")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetNextUp(
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] string? seriesId,
+ [FromQuery] Guid? parentId,
+ [FromQuery] bool? enableImges,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] DateTime? nextUpDateCutoff,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool disableFirstEpisode = false)
+ {
+ var options = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var result = _tvSeriesManager.GetNextUp(
+ new NextUpQuery
+ {
+ Limit = limit,
+ ParentId = parentId,
+ SeriesId = seriesId,
+ StartIndex = startIndex,
+ UserId = userId ?? Guid.Empty,
+ EnableTotalRecordCount = enableTotalRecordCount,
+ DisableFirstEpisode = disableFirstEpisode,
+ NextUpDateCutoff = nextUpDateCutoff ?? DateTime.MinValue
+ },
+ options);
+
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var returnItems = _dtoService.GetBaseItemDtos(result.Items, options, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = result.TotalRecordCount,
+ Items = returnItems
+ };
+ }
+
+ /// <summary>
+ /// Gets a list of upcoming episodes.
+ /// </summary>
+ /// <param name="userId">The user id of the user to get the upcoming episodes for.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="enableImges">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the next up episodes.</returns>
+ [HttpGet("Upcoming")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetUpcomingEpisodes(
+ [FromQuery] Guid? userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] Guid? parentId,
+ [FromQuery] bool? enableImges,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var minPremiereDate = DateTime.UtcNow.Date.AddDays(-1);
+
+ var parentIdGuid = parentId ?? Guid.Empty;
+
+ var options = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user)
+ {
+ IncludeItemTypes = new[] { nameof(Episode) },
+ OrderBy = new[] { (ItemSortBy.PremiereDate, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) },
+ MinPremiereDate = minPremiereDate,
+ StartIndex = startIndex,
+ Limit = limit,
+ ParentId = parentIdGuid,
+ Recursive = true,
+ DtoOptions = options
+ });
+
+ var returnItems = _dtoService.GetBaseItemDtos(itemsResult, options, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = itemsResult.Count,
+ Items = returnItems
+ };
+ }
+
+ /// <summary>
+ /// Gets episodes for a tv season.
+ /// </summary>
+ /// <param name="seriesId">The series id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param>
+ /// <param name="season">Optional filter by season number.</param>
+ /// <param name="seasonId">Optional. Filter by season id.</param>
+ /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
+ /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
+ /// <param name="startItemId">Optional. Skip through the list until a given item is found.</param>
+ /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="enableImages">Optional, include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the episodes on success or a <see cref="NotFoundResult"/> if the series was not found.</returns>
+ [HttpGet("{seriesId}/Episodes")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<QueryResult<BaseItemDto>> GetEpisodes(
+ [FromRoute, Required] Guid seriesId,
+ [FromQuery] Guid? userId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] int? season,
+ [FromQuery] Guid? seasonId,
+ [FromQuery] bool? isMissing,
+ [FromQuery] string? adjacentTo,
+ [FromQuery] Guid? startItemId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] string? sortBy)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ List<BaseItem> episodes;
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ if (seasonId.HasValue) // Season id was supplied. Get episodes by season id.
+ {
+ var item = _libraryManager.GetItemById(seasonId.Value);
+ if (item is not Season seasonItem)
+ {
+ return NotFound("No season exists with Id " + seasonId);
+ }
+
+ episodes = seasonItem.GetEpisodes(user, dtoOptions);
+ }
+ else if (season.HasValue) // Season number was supplied. Get episodes by season number
+ {
+ if (_libraryManager.GetItemById(seriesId) is not Series series)
+ {
+ return NotFound("Series not found");
+ }
+
+ var seasonItem = series
+ .GetSeasons(user, dtoOptions)
+ .FirstOrDefault(i => i.IndexNumber == season.Value);
+
+ episodes = seasonItem == null ?
+ new List<BaseItem>()
+ : ((Season)seasonItem).GetEpisodes(user, dtoOptions);
+ }
+ else // No season number or season id was supplied. Returning all episodes.
+ {
+ if (_libraryManager.GetItemById(seriesId) is not Series series)
+ {
+ return NotFound("Series not found");
+ }
+
+ episodes = series.GetEpisodes(user, dtoOptions).ToList();
+ }
+
+ // Filter after the fact in case the ui doesn't want them
+ if (isMissing.HasValue)
+ {
+ var val = isMissing.Value;
+ episodes = episodes
+ .Where(i => ((Episode)i).IsMissingEpisode == val)
+ .ToList();
+ }
+
+ if (startItemId.HasValue)
+ {
+ episodes = episodes
+ .SkipWhile(i => !startItemId.Value.Equals(i.Id))
+ .ToList();
+ }
+
+ // This must be the last filter
+ if (!string.IsNullOrEmpty(adjacentTo))
+ {
+ episodes = UserViewBuilder.FilterForAdjacency(episodes, adjacentTo).ToList();
+ }
+
+ if (string.Equals(sortBy, ItemSortBy.Random, StringComparison.OrdinalIgnoreCase))
+ {
+ episodes.Shuffle();
+ }
+
+ var returnItems = episodes;
+
+ if (startIndex.HasValue || limit.HasValue)
+ {
+ returnItems = ApplyPaging(episodes, startIndex, limit).ToList();
+ }
+
+ var dtos = _dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = episodes.Count,
+ Items = dtos
+ };
+ }
+
+ /// <summary>
+ /// Gets seasons for a tv series.
+ /// </summary>
+ /// <param name="seriesId">The series id.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param>
+ /// <param name="isSpecialSeason">Optional. Filter by special season.</param>
+ /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
+ /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> on success or a <see cref="NotFoundResult"/> if the series was not found.</returns>
+ [HttpGet("{seriesId}/Seasons")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<QueryResult<BaseItemDto>> GetSeasons(
+ [FromRoute, Required] Guid seriesId,
+ [FromQuery] Guid? userId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery] bool? isSpecialSeason,
+ [FromQuery] bool? isMissing,
+ [FromQuery] string? adjacentTo,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ if (_libraryManager.GetItemById(seriesId) is not Series series)
+ {
+ return NotFound("Series not found");
+ }
+
+ var seasons = series.GetItemList(new InternalItemsQuery(user)
+ {
+ IsMissing = isMissing,
+ IsSpecialSeason = isSpecialSeason,
+ AdjacentTo = adjacentTo
+ });
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var returnItems = _dtoService.GetBaseItemDtos(seasons, dtoOptions, user);
+
+ return new QueryResult<BaseItemDto>
+ {
+ TotalRecordCount = returnItems.Count,
+ Items = returnItems
+ };
+ }
+
+ /// <summary>
+ /// Applies the paging.
+ /// </summary>
+ /// <param name="items">The items.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The limit.</param>
+ /// <returns>IEnumerable{BaseItem}.</returns>
+ private IEnumerable<BaseItem> ApplyPaging(IEnumerable<BaseItem> items, int? startIndex, int? limit)
+ {
+ // Start at
+ if (startIndex.HasValue)
+ {
+ items = items.Skip(startIndex.Value);
+ }
+
+ // Return limit
+ if (limit.HasValue)
+ {
+ items = items.Take(limit.Value);
+ }
+
+ return items;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs
new file mode 100644
index 000000000..bc9527a0b
--- /dev/null
+++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs
@@ -0,0 +1,368 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The universal audio controller.
+ /// </summary>
+ [Route("")]
+ public class UniversalAudioController : BaseJellyfinApiController
+ {
+ private readonly IAuthorizationContext _authorizationContext;
+ private readonly IDeviceManager _deviceManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<UniversalAudioController> _logger;
+ private readonly MediaInfoHelper _mediaInfoHelper;
+ private readonly AudioHelper _audioHelper;
+ private readonly DynamicHlsHelper _dynamicHlsHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UniversalAudioController"/> class.
+ /// </summary>
+ /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{UniversalAudioController}"/> interface.</param>
+ /// <param name="mediaInfoHelper">Instance of <see cref="MediaInfoHelper"/>.</param>
+ /// <param name="audioHelper">Instance of <see cref="AudioHelper"/>.</param>
+ /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
+ public UniversalAudioController(
+ IAuthorizationContext authorizationContext,
+ IDeviceManager deviceManager,
+ ILibraryManager libraryManager,
+ ILogger<UniversalAudioController> logger,
+ MediaInfoHelper mediaInfoHelper,
+ AudioHelper audioHelper,
+ DynamicHlsHelper dynamicHlsHelper)
+ {
+ _authorizationContext = authorizationContext;
+ _deviceManager = deviceManager;
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _mediaInfoHelper = mediaInfoHelper;
+ _audioHelper = audioHelper;
+ _dynamicHlsHelper = dynamicHlsHelper;
+ }
+
+ /// <summary>
+ /// Gets an audio stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">Optional. The audio container.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="userId">Optional. The user id.</param>
+ /// <param name="audioCodec">Optional. The audio codec to transcode to.</param>
+ /// <param name="maxAudioChannels">Optional. The maximum number of audio channels.</param>
+ /// <param name="transcodingAudioChannels">Optional. The number of how many audio channels to transcode to.</param>
+ /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="transcodingContainer">Optional. The container to transcode to.</param>
+ /// <param name="transcodingProtocol">Optional. The transcoding protocol.</param>
+ /// <param name="maxAudioSampleRate">Optional. The maximum audio sample rate.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="enableRemoteMedia">Optional. Whether to enable remote media.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="enableRedirection">Whether to enable redirection. Defaults to true.</param>
+ /// <response code="200">Audio stream returned.</response>
+ /// <response code="302">Redirected to remote audio stream.</response>
+ /// <returns>A <see cref="Task"/> containing the audio file.</returns>
+ [HttpGet("Audio/{itemId}/universal")]
+ [HttpHead("Audio/{itemId}/universal", Name = "HeadUniversalAudioStream")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status302Found)]
+ [ProducesAudioFile]
+ public async Task<ActionResult> GetUniversalAudioStream(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] container,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] Guid? userId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] int? transcodingAudioChannels,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] string? transcodingContainer,
+ [FromQuery] string? transcodingProtocol,
+ [FromQuery] int? maxAudioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] bool? enableRemoteMedia,
+ [FromQuery] bool breakOnNonKeyFrames = false,
+ [FromQuery] bool enableRedirection = true)
+ {
+ var deviceProfile = GetDeviceProfile(container, transcodingContainer, audioCodec, transcodingProtocol, breakOnNonKeyFrames, transcodingAudioChannels, maxAudioSampleRate, maxAudioBitDepth, maxAudioChannels);
+ (await _authorizationContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).DeviceId = deviceId;
+
+ var authInfo = await _authorizationContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+
+ _logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", deviceProfile);
+
+ if (deviceProfile == null)
+ {
+ var clientCapabilities = _deviceManager.GetCapabilities(authInfo.DeviceId);
+ if (clientCapabilities != null)
+ {
+ deviceProfile = clientCapabilities.DeviceProfile;
+ }
+ }
+
+ var info = await _mediaInfoHelper.GetPlaybackInfo(
+ itemId,
+ userId,
+ mediaSourceId)
+ .ConfigureAwait(false);
+
+ if (deviceProfile != null)
+ {
+ // set device specific data
+ var item = _libraryManager.GetItemById(itemId);
+
+ foreach (var sourceInfo in info.MediaSources)
+ {
+ _mediaInfoHelper.SetDeviceSpecificData(
+ item,
+ sourceInfo,
+ deviceProfile,
+ authInfo,
+ maxStreamingBitrate ?? deviceProfile.MaxStreamingBitrate,
+ startTimeTicks ?? 0,
+ mediaSourceId ?? string.Empty,
+ null,
+ null,
+ maxAudioChannels,
+ info.PlaySessionId!,
+ userId ?? Guid.Empty,
+ true,
+ true,
+ true,
+ true,
+ true,
+ Request.HttpContext.GetNormalizedRemoteIp());
+ }
+
+ _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);
+ }
+
+ if (info.MediaSources != null)
+ {
+ foreach (var source in info.MediaSources)
+ {
+ _mediaInfoHelper.NormalizeMediaSourceContainer(source, deviceProfile!, DlnaProfileType.Video);
+ }
+ }
+
+ var mediaSource = info.MediaSources![0];
+ if (mediaSource.SupportsDirectPlay && mediaSource.Protocol == MediaProtocol.Http)
+ {
+ if (enableRedirection)
+ {
+ if (mediaSource.IsRemote && enableRemoteMedia.HasValue && enableRemoteMedia.Value)
+ {
+ return Redirect(mediaSource.Path);
+ }
+ }
+ }
+
+ var isStatic = mediaSource.SupportsDirectStream;
+ if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ {
+ // hls segment container can only be mpegts or fmp4 per ffmpeg documentation
+ // ffmpeg option -> file extension
+ // mpegts -> ts
+ // fmp4 -> mp4
+ // TODO: remove this when we switch back to the segment muxer
+ var supportedHlsContainers = new[] { "ts", "mp4" };
+
+ var dynamicHlsRequestDto = new HlsAudioRequestDto
+ {
+ Id = itemId,
+ Container = ".m3u8",
+ Static = isStatic,
+ PlaySessionId = info.PlaySessionId,
+ // fallback to mpegts if device reports some weird value unsupported by hls
+ SegmentContainer = Array.Exists(supportedHlsContainers, element => element == transcodingContainer) ? transcodingContainer : "ts",
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = true,
+ AllowAudioStreamCopy = true,
+ AllowVideoStreamCopy = true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames,
+ AudioSampleRate = maxAudioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
+ StartTimeTicks = startTimeTicks,
+ SubtitleMethod = SubtitleDeliveryMethod.Hls,
+ RequireAvc = false,
+ DeInterlace = false,
+ RequireNonAnamorphic = false,
+ EnableMpegtsM2TsMode = false,
+ TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(',', mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()),
+ Context = EncodingContext.Static,
+ StreamOptions = new Dictionary<string, string>(),
+ EnableAdaptiveBitrateStreaming = true
+ };
+
+ return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType.Hls, dynamicHlsRequestDto, true)
+ .ConfigureAwait(false);
+ }
+
+ var audioStreamingDto = new StreamingRequestDto
+ {
+ Id = itemId,
+ Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
+ Static = isStatic,
+ PlaySessionId = info.PlaySessionId,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = true,
+ AllowAudioStreamCopy = true,
+ AllowVideoStreamCopy = true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames,
+ AudioSampleRate = maxAudioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = isStatic ? (int?)null : (audioBitRate ?? maxStreamingBitrate),
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = maxAudioChannels,
+ CopyTimestamps = true,
+ StartTimeTicks = startTimeTicks,
+ SubtitleMethod = SubtitleDeliveryMethod.Embed,
+ TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(',', mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()),
+ Context = EncodingContext.Static
+ };
+
+ return await _audioHelper.GetAudioStream(TranscodingJobType.Progressive, audioStreamingDto).ConfigureAwait(false);
+ }
+
+ private DeviceProfile GetDeviceProfile(
+ string[] containers,
+ string? transcodingContainer,
+ string? audioCodec,
+ string? transcodingProtocol,
+ bool? breakOnNonKeyFrames,
+ int? transcodingAudioChannels,
+ int? maxAudioSampleRate,
+ int? maxAudioBitDepth,
+ int? maxAudioChannels)
+ {
+ var deviceProfile = new DeviceProfile();
+
+ int len = containers.Length;
+ var directPlayProfiles = new DirectPlayProfile[len];
+ for (int i = 0; i < len; i++)
+ {
+ var parts = containers[i].Split('|', StringSplitOptions.RemoveEmptyEntries);
+
+ var audioCodecs = parts.Length == 1 ? null : string.Join(',', parts.Skip(1));
+
+ directPlayProfiles[i] = new DirectPlayProfile
+ {
+ Type = DlnaProfileType.Audio,
+ Container = parts[0],
+ AudioCodec = audioCodecs
+ };
+ }
+
+ deviceProfile.DirectPlayProfiles = directPlayProfiles;
+
+ deviceProfile.TranscodingProfiles = new[]
+ {
+ new TranscodingProfile
+ {
+ Type = DlnaProfileType.Audio,
+ Context = EncodingContext.Streaming,
+ Container = transcodingContainer ?? "mp3",
+ AudioCodec = audioCodec ?? "mp3",
+ Protocol = transcodingProtocol ?? "http",
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ MaxAudioChannels = transcodingAudioChannels?.ToString(CultureInfo.InvariantCulture)
+ }
+ };
+
+ var codecProfiles = new List<CodecProfile>();
+ var conditions = new List<ProfileCondition>();
+
+ if (maxAudioSampleRate.HasValue)
+ {
+ // codec profile
+ conditions.Add(
+ new ProfileCondition
+ {
+ Condition = ProfileConditionType.LessThanEqual,
+ IsRequired = false,
+ Property = ProfileConditionValue.AudioSampleRate,
+ Value = maxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)
+ });
+ }
+
+ if (maxAudioBitDepth.HasValue)
+ {
+ // codec profile
+ conditions.Add(
+ new ProfileCondition
+ {
+ Condition = ProfileConditionType.LessThanEqual,
+ IsRequired = false,
+ Property = ProfileConditionValue.AudioBitDepth,
+ Value = maxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture)
+ });
+ }
+
+ if (maxAudioChannels.HasValue)
+ {
+ // codec profile
+ conditions.Add(
+ new ProfileCondition
+ {
+ Condition = ProfileConditionType.LessThanEqual,
+ IsRequired = false,
+ Property = ProfileConditionValue.AudioChannels,
+ Value = maxAudioChannels.Value.ToString(CultureInfo.InvariantCulture)
+ });
+ }
+
+ if (conditions.Count > 0)
+ {
+ // codec profile
+ codecProfiles.Add(
+ new CodecProfile
+ {
+ Type = CodecType.Audio,
+ Container = string.Join(',', containers),
+ Conditions = conditions.ToArray()
+ });
+ }
+
+ deviceProfile.CodecProfiles = codecProfiles.ToArray();
+
+ return deviceProfile;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs
new file mode 100644
index 000000000..4263d4fe5
--- /dev/null
+++ b/Jellyfin.Api/Controllers/UserController.cs
@@ -0,0 +1,590 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.UserDtos;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.QuickConnect;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Users;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// User controller.
+ /// </summary>
+ [Route("Users")]
+ public class UserController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly ISessionManager _sessionManager;
+ private readonly INetworkManager _networkManager;
+ private readonly IDeviceManager _deviceManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IServerConfigurationManager _config;
+ private readonly ILogger _logger;
+ private readonly IQuickConnect _quickConnectManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="quickConnectManager">Instance of the <see cref="IQuickConnect"/> interface.</param>
+ public UserController(
+ IUserManager userManager,
+ ISessionManager sessionManager,
+ INetworkManager networkManager,
+ IDeviceManager deviceManager,
+ IAuthorizationContext authContext,
+ IServerConfigurationManager config,
+ ILogger<UserController> logger,
+ IQuickConnect quickConnectManager)
+ {
+ _userManager = userManager;
+ _sessionManager = sessionManager;
+ _networkManager = networkManager;
+ _deviceManager = deviceManager;
+ _authContext = authContext;
+ _config = config;
+ _logger = logger;
+ _quickConnectManager = quickConnectManager;
+ }
+
+ /// <summary>
+ /// Gets a list of users.
+ /// </summary>
+ /// <param name="isHidden">Optional filter by IsHidden=true or false.</param>
+ /// <param name="isDisabled">Optional filter by IsDisabled=true or false.</param>
+ /// <response code="200">Users returned.</response>
+ /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the users.</returns>
+ [HttpGet]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers(
+ [FromQuery] bool? isHidden,
+ [FromQuery] bool? isDisabled)
+ {
+ var users = await Get(isHidden, isDisabled, false, false).ConfigureAwait(false);
+ return Ok(users);
+ }
+
+ /// <summary>
+ /// Gets a list of publicly visible users for display on a login screen.
+ /// </summary>
+ /// <response code="200">Public users returned.</response>
+ /// <returns>An <see cref="IEnumerable{UserDto}"/> containing the public users.</returns>
+ [HttpGet("Public")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<IEnumerable<UserDto>>> GetPublicUsers()
+ {
+ // If the startup wizard hasn't been completed then just return all users
+ if (!_config.Configuration.IsStartupWizardCompleted)
+ {
+ return Ok(await Get(false, false, false, false).ConfigureAwait(false));
+ }
+
+ return Ok(await Get(false, false, true, true).ConfigureAwait(false));
+ }
+
+ /// <summary>
+ /// Gets a user by Id.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <response code="200">User returned.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>An <see cref="UserDto"/> with information about the user or a <see cref="NotFoundResult"/> if the user was not found.</returns>
+ [HttpGet("{userId}")]
+ [Authorize(Policy = Policies.IgnoreParentalControl)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<UserDto> GetUserById([FromRoute, Required] Guid userId)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ if (user == null)
+ {
+ return NotFound("User not found");
+ }
+
+ var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString());
+ return result;
+ }
+
+ /// <summary>
+ /// Deletes a user.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <response code="204">User deleted.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="NotFoundResult"/> if the user was not found.</returns>
+ [HttpDelete("{userId}")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteUser([FromRoute, Required] Guid userId)
+ {
+ var user = _userManager.GetUserById(userId);
+ await _sessionManager.RevokeUserTokens(user.Id, null).ConfigureAwait(false);
+ await _userManager.DeleteUserAsync(userId).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Authenticates a user.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="pw">The password as plain text.</param>
+ /// <param name="password">The password sha1-hash.</param>
+ /// <response code="200">User authenticated.</response>
+ /// <response code="403">Sha1-hashed password only is not allowed.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationResult"/>.</returns>
+ [HttpPost("{userId}/Authenticate")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult<AuthenticationResult>> AuthenticateUser(
+ [FromRoute, Required] Guid userId,
+ [FromQuery, Required] string pw,
+ [FromQuery] string? password)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ if (user == null)
+ {
+ return NotFound("User not found");
+ }
+
+ if (!string.IsNullOrEmpty(password) && string.IsNullOrEmpty(pw))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "Only sha1 password is not allowed.");
+ }
+
+ AuthenticateUserByName request = new AuthenticateUserByName
+ {
+ Username = user.Username,
+ Pw = pw
+ };
+ return await AuthenticateUserByName(request).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Authenticates a user by name.
+ /// </summary>
+ /// <param name="request">The <see cref="AuthenticateUserByName"/> request.</param>
+ /// <response code="200">User authenticated.</response>
+ /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
+ [HttpPost("AuthenticateByName")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<AuthenticationResult>> AuthenticateUserByName([FromBody, Required] AuthenticateUserByName request)
+ {
+ var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
+
+ try
+ {
+ var result = await _sessionManager.AuthenticateNewSession(new AuthenticationRequest
+ {
+ App = auth.Client,
+ AppVersion = auth.Version,
+ DeviceId = auth.DeviceId,
+ DeviceName = auth.Device,
+ Password = request.Pw,
+ RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(),
+ Username = request.Username
+ }).ConfigureAwait(false);
+
+ return result;
+ }
+ catch (SecurityException e)
+ {
+ // rethrow adding IP address to message
+ throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
+ }
+ }
+
+ /// <summary>
+ /// Authenticates a user with quick connect.
+ /// </summary>
+ /// <param name="request">The <see cref="QuickConnectDto"/> request.</param>
+ /// <response code="200">User authenticated.</response>
+ /// <response code="400">Missing token.</response>
+ /// <returns>A <see cref="Task"/> containing an <see cref="AuthenticationRequest"/> with information about the new session.</returns>
+ [HttpPost("AuthenticateWithQuickConnect")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<AuthenticationResult> AuthenticateWithQuickConnect([FromBody, Required] QuickConnectDto request)
+ {
+ try
+ {
+ return _quickConnectManager.GetAuthorizedRequest(request.Secret);
+ }
+ catch (SecurityException e)
+ {
+ // rethrow adding IP address to message
+ throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
+ }
+ }
+
+ /// <summary>
+ /// Updates a user's password.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="request">The <see cref="UpdateUserPassword"/> request.</param>
+ /// <response code="204">Password successfully reset.</response>
+ /// <response code="403">User is not allowed to update the password.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
+ [HttpPost("{userId}/Password")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> UpdateUserPassword(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UpdateUserPassword request)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+
+ if (user == null)
+ {
+ return NotFound("User not found");
+ }
+
+ if (request.ResetPassword)
+ {
+ await _userManager.ResetPassword(user).ConfigureAwait(false);
+ }
+ else
+ {
+ var success = await _userManager.AuthenticateUser(
+ user.Username,
+ request.CurrentPw,
+ request.CurrentPw,
+ HttpContext.GetNormalizedRemoteIp().ToString(),
+ false).ConfigureAwait(false);
+
+ if (success == null)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered.");
+ }
+
+ await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false);
+
+ var currentToken = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).Token;
+
+ await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a user's easy password.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="request">The <see cref="UpdateUserEasyPassword"/> request.</param>
+ /// <response code="204">Password successfully reset.</response>
+ /// <response code="403">User is not allowed to update the password.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
+ [HttpPost("{userId}/EasyPassword")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> UpdateUserEasyPassword(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UpdateUserEasyPassword request)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the easy password.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+
+ if (user == null)
+ {
+ return NotFound("User not found");
+ }
+
+ if (request.ResetPassword)
+ {
+ await _userManager.ResetEasyPassword(user).ConfigureAwait(false);
+ }
+ else
+ {
+ await _userManager.ChangeEasyPassword(user, request.NewPw, request.NewPassword).ConfigureAwait(false);
+ }
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a user.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="updateUser">The updated user model.</param>
+ /// <response code="204">User updated.</response>
+ /// <response code="400">User information was not supplied.</response>
+ /// <response code="403">User update forbidden.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
+ [HttpPost("{userId}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult> UpdateUser(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UserDto updateUser)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed.");
+ }
+
+ var user = _userManager.GetUserById(userId);
+
+ if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
+ {
+ await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
+ }
+
+ await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a user policy.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="newPolicy">The new user policy.</param>
+ /// <response code="204">User policy updated.</response>
+ /// <response code="400">User policy was not supplied.</response>
+ /// <response code="403">User policy update forbidden.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure..</returns>
+ [HttpPost("{userId}/Policy")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult> UpdateUserPolicy(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UserPolicy newPolicy)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ // If removing admin access
+ if (!newPolicy.IsAdministrator && user.HasPermission(PermissionKind.IsAdministrator))
+ {
+ if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one user in the system with administrative access.");
+ }
+ }
+
+ // If disabling
+ if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "Administrators cannot be disabled.");
+ }
+
+ // If disabling
+ if (newPolicy.IsDisabled && !user.HasPermission(PermissionKind.IsDisabled))
+ {
+ if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one enabled user in the system.");
+ }
+
+ var currentToken = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).Token;
+ await _sessionManager.RevokeUserTokens(user.Id, currentToken).ConfigureAwait(false);
+ }
+
+ await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Updates a user configuration.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="userConfig">The new user configuration.</param>
+ /// <response code="204">User configuration updated.</response>
+ /// <response code="403">User configuration update forbidden.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("{userId}/Configuration")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult> UpdateUserConfiguration(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UserConfiguration userConfig)
+ {
+ if (!await RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false).ConfigureAwait(false))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
+ }
+
+ await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Creates a user.
+ /// </summary>
+ /// <param name="request">The create user by name request body.</param>
+ /// <response code="200">User created.</response>
+ /// <returns>An <see cref="UserDto"/> of the new user.</returns>
+ [HttpPost("New")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request)
+ {
+ var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false);
+
+ // no need to authenticate password for new user
+ if (request.Password != null)
+ {
+ await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
+ }
+
+ var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString());
+
+ return result;
+ }
+
+ /// <summary>
+ /// Initiates the forgot password process for a local user.
+ /// </summary>
+ /// <param name="forgotPasswordRequest">The forgot password request containing the entered username.</param>
+ /// <response code="200">Password reset process started.</response>
+ /// <returns>A <see cref="Task"/> containing a <see cref="ForgotPasswordResult"/>.</returns>
+ [HttpPost("ForgotPassword")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
+ {
+ var ip = HttpContext.GetNormalizedRemoteIp();
+ var isLocal = HttpContext.IsLocal()
+ || _networkManager.IsInLocalNetwork(ip);
+
+ if (isLocal)
+ {
+ _logger.LogWarning("Password reset proccess initiated from outside the local network with IP: {IP}", ip);
+ }
+
+ var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Redeems a forgot password pin.
+ /// </summary>
+ /// <param name="forgotPasswordPinRequest">The forgot password pin request containing the entered pin.</param>
+ /// <response code="200">Pin reset process started.</response>
+ /// <returns>A <see cref="Task"/> containing a <see cref="PinRedeemResult"/>.</returns>
+ [HttpPost("ForgotPassword/Pin")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<PinRedeemResult>> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest)
+ {
+ var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false);
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the user based on auth token.
+ /// </summary>
+ /// <response code="200">User returned.</response>
+ /// <response code="400">Token is not owned by a user.</response>
+ /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns>
+ [HttpGet("Me")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public ActionResult<UserDto> GetCurrentUser()
+ {
+ var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);
+ if (userId == null)
+ {
+ return BadRequest();
+ }
+
+ var user = _userManager.GetUserById(userId.Value);
+ if (user == null)
+ {
+ return BadRequest();
+ }
+
+ return _userManager.GetUserDto(user);
+ }
+
+ private async Task<IEnumerable<UserDto>> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
+ {
+ var users = _userManager.Users;
+
+ if (isDisabled.HasValue)
+ {
+ users = users.Where(i => i.HasPermission(PermissionKind.IsDisabled) == isDisabled.Value);
+ }
+
+ if (isHidden.HasValue)
+ {
+ users = users.Where(i => i.HasPermission(PermissionKind.IsHidden) == isHidden.Value);
+ }
+
+ if (filterByDevice)
+ {
+ var deviceId = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).DeviceId;
+
+ if (!string.IsNullOrWhiteSpace(deviceId))
+ {
+ users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
+ }
+ }
+
+ if (filterByNetwork)
+ {
+ if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()))
+ {
+ users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
+ }
+ }
+
+ var result = users
+ .OrderBy(u => u.Username)
+ .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString()));
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs
new file mode 100644
index 000000000..a33a0826c
--- /dev/null
+++ b/Jellyfin.Api/Controllers/UserLibraryController.cs
@@ -0,0 +1,394 @@
+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.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// User library controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class UserLibraryController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataRepository;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IDtoService _dtoService;
+ private readonly IUserViewManager _userViewManager;
+ private readonly IFileSystem _fileSystem;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserLibraryController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataRepository">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="userViewManager">Instance of the <see cref="IUserViewManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ public UserLibraryController(
+ IUserManager userManager,
+ IUserDataManager userDataRepository,
+ ILibraryManager libraryManager,
+ IDtoService dtoService,
+ IUserViewManager userViewManager,
+ IFileSystem fileSystem)
+ {
+ _userManager = userManager;
+ _userDataRepository = userDataRepository;
+ _libraryManager = libraryManager;
+ _dtoService = dtoService;
+ _userViewManager = userViewManager;
+ _fileSystem = fileSystem;
+ }
+
+ /// <summary>
+ /// Gets an item from a user's library.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the d item.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<BaseItemDto>> GetItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.GetItemById(itemId);
+
+ await RefreshItemOnDemandIfNeeded(item).ConfigureAwait(false);
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ /// <summary>
+ /// Gets the root folder from a user's library.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <response code="200">Root folder returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the user's root folder.</returns>
+ [HttpGet("Users/{userId}/Items/Root")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<BaseItemDto> GetRootFolder([FromRoute, Required] Guid userId)
+ {
+ var user = _userManager.GetUserById(userId);
+ var item = _libraryManager.GetUserRootFolder();
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ /// <summary>
+ /// Gets intros to play before the main media item plays.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Intros returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the intros to play.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/Intros")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetIntros([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.GetItemById(itemId);
+
+ var items = await _libraryManager.GetIntros(item, user).ConfigureAwait(false);
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var dtos = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user)).ToArray();
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = dtos,
+ TotalRecordCount = dtos.Length
+ };
+ }
+
+ /// <summary>
+ /// Marks an item as a favorite.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item marked as favorite.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/FavoriteItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<UserItemDataDto> MarkFavoriteItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ return MarkFavorite(userId, itemId, true);
+ }
+
+ /// <summary>
+ /// Unmarks item as a favorite.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item unmarked as favorite.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpDelete("Users/{userId}/FavoriteItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<UserItemDataDto> UnmarkFavoriteItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ return MarkFavorite(userId, itemId, false);
+ }
+
+ /// <summary>
+ /// Deletes a user's saved personal rating for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Personal rating removed.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpDelete("Users/{userId}/Items/{itemId}/Rating")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<UserItemDataDto> DeleteUserItemRating([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ return UpdateUserItemRatingInternal(userId, itemId, null);
+ }
+
+ /// <summary>
+ /// Updates a user's rating for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="likes">Whether this <see cref="UpdateUserItemRating" /> is likes.</param>
+ /// <response code="200">Item rating updated.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/Items/{itemId}/Rating")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<UserItemDataDto> UpdateUserItemRating([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery] bool? likes)
+ {
+ return UpdateUserItemRatingInternal(userId, itemId, likes);
+ }
+
+ /// <summary>
+ /// Gets local trailers for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">An <see cref="OkResult"/> containing the item's local trailers.</response>
+ /// <returns>The items local trailers.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/LocalTrailers")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetLocalTrailers([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.GetItemById(itemId);
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var dtosExtras = item.GetExtras(new[] { ExtraType.Trailer })
+ .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
+ .ToArray();
+
+ if (item is IHasTrailers hasTrailers)
+ {
+ var trailers = hasTrailers.GetTrailers();
+ var dtosTrailers = _dtoService.GetBaseItemDtos(trailers, dtoOptions, user, item);
+ var allTrailers = new BaseItemDto[dtosExtras.Length + dtosTrailers.Count];
+ dtosExtras.CopyTo(allTrailers, 0);
+ dtosTrailers.CopyTo(allTrailers, dtosExtras.Length);
+ return allTrailers;
+ }
+
+ return dtosExtras;
+ }
+
+ /// <summary>
+ /// Gets special features for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Special features returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the special features.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/SpecialFeatures")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetSpecialFeatures([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.GetItemById(itemId);
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+
+ return Ok(item
+ .GetExtras(BaseItem.DisplayExtraTypes)
+ .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)));
+ }
+
+ /// <summary>
+ /// Gets latest media.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isPlayed">Filter by items that are played, or not.</param>
+ /// <param name="enableImages">Optional. include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. include user data.</param>
+ /// <param name="limit">Return item limit.</param>
+ /// <param name="groupItems">Whether or not to group items into a parent container.</param>
+ /// <response code="200">Latest media returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the latest media.</returns>
+ [HttpGet("Users/{userId}/Items/Latest")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetLatestMedia(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isPlayed,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int limit = 20,
+ [FromQuery] bool groupItems = true)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ if (!isPlayed.HasValue)
+ {
+ if (user.HidePlayedInLatest)
+ {
+ isPlayed = false;
+ }
+ }
+
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ var list = _userViewManager.GetLatestItems(
+ new LatestItemsQuery
+ {
+ GroupItems = groupItems,
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ IsPlayed = isPlayed,
+ Limit = limit,
+ ParentId = parentId ?? Guid.Empty,
+ UserId = userId,
+ }, dtoOptions);
+
+ var dtos = list.Select(i =>
+ {
+ var item = i.Item2[0];
+ var childCount = 0;
+
+ if (i.Item1 != null && (i.Item2.Count > 1 || i.Item1 is MusicAlbum))
+ {
+ item = i.Item1;
+ childCount = i.Item2.Count;
+ }
+
+ var dto = _dtoService.GetBaseItemDto(item, dtoOptions, user);
+
+ dto.ChildCount = childCount;
+
+ return dto;
+ });
+
+ return Ok(dtos);
+ }
+
+ private async Task RefreshItemOnDemandIfNeeded(BaseItem item)
+ {
+ if (item is Person)
+ {
+ var hasMetdata = !string.IsNullOrWhiteSpace(item.Overview) && item.HasImage(ImageType.Primary);
+ var performFullRefresh = !hasMetdata && (DateTime.UtcNow - item.DateLastRefreshed).TotalDays >= 3;
+
+ if (!hasMetdata)
+ {
+ var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
+ ImageRefreshMode = MetadataRefreshMode.FullRefresh,
+ ForceSave = performFullRefresh
+ };
+
+ await item.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Marks the favorite.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="isFavorite">if set to <c>true</c> [is favorite].</param>
+ private UserItemDataDto MarkFavorite(Guid userId, Guid itemId, bool isFavorite)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(itemId);
+
+ // Get the user data for this item
+ var data = _userDataRepository.GetUserData(user, item);
+
+ // Set favorite status
+ data.IsFavorite = isFavorite;
+
+ _userDataRepository.SaveUserData(user, item, data, UserDataSaveReason.UpdateUserRating, CancellationToken.None);
+
+ return _userDataRepository.GetUserDataDto(item, user);
+ }
+
+ /// <summary>
+ /// Updates the user item rating.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="likes">if set to <c>true</c> [likes].</param>
+ private UserItemDataDto UpdateUserItemRatingInternal(Guid userId, Guid itemId, bool? likes)
+ {
+ var user = _userManager.GetUserById(userId);
+
+ var item = itemId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(itemId);
+
+ // Get the user data for this item
+ var data = _userDataRepository.GetUserData(user, item);
+
+ data.Likes = likes;
+
+ _userDataRepository.SaveUserData(user, item, data, UserDataSaveReason.UpdateUserRating, CancellationToken.None);
+
+ return _userDataRepository.GetUserDataDto(item, user);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/UserViewsController.cs b/Jellyfin.Api/Controllers/UserViewsController.cs
new file mode 100644
index 000000000..3d27371f6
--- /dev/null
+++ b/Jellyfin.Api/Controllers/UserViewsController.cs
@@ -0,0 +1,151 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.UserViewDtos;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Library;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// User views controller.
+ /// </summary>
+ [Route("")]
+ public class UserViewsController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly IUserViewManager _userViewManager;
+ private readonly IDtoService _dtoService;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserViewsController"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userViewManager">Instance of the <see cref="IUserViewManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public UserViewsController(
+ IUserManager userManager,
+ IUserViewManager userViewManager,
+ IDtoService dtoService,
+ IAuthorizationContext authContext,
+ ILibraryManager libraryManager)
+ {
+ _userManager = userManager;
+ _userViewManager = userViewManager;
+ _dtoService = dtoService;
+ _authContext = authContext;
+ _libraryManager = libraryManager;
+ }
+
+ /// <summary>
+ /// Get user views.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="includeExternalContent">Whether or not to include external views such as channels or live tv.</param>
+ /// <param name="presetViews">Preset views.</param>
+ /// <param name="includeHidden">Whether or not to include hidden content.</param>
+ /// <response code="200">User views returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the user views.</returns>
+ [HttpGet("Users/{userId}/Views")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetUserViews(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] bool? includeExternalContent,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] presetViews,
+ [FromQuery] bool includeHidden = false)
+ {
+ var query = new UserViewQuery
+ {
+ UserId = userId,
+ IncludeHidden = includeHidden
+ };
+
+ if (includeExternalContent.HasValue)
+ {
+ query.IncludeExternalContent = includeExternalContent.Value;
+ }
+
+ if (presetViews.Length != 0)
+ {
+ query.PresetViews = presetViews;
+ }
+
+ var app = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).Client ?? string.Empty;
+ if (app.IndexOf("emby rt", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ query.PresetViews = new[] { CollectionType.Movies, CollectionType.TvShows };
+ }
+
+ var folders = _userViewManager.GetUserViews(query);
+
+ var dtoOptions = new DtoOptions().AddClientFields(Request);
+ var fields = dtoOptions.Fields.ToList();
+
+ fields.Add(ItemFields.PrimaryImageAspectRatio);
+ fields.Add(ItemFields.DisplayPreferencesId);
+ fields.Remove(ItemFields.BasicSyncInfo);
+ dtoOptions.Fields = fields.ToArray();
+
+ var user = _userManager.GetUserById(userId);
+
+ var dtos = folders.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user))
+ .ToArray();
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = dtos,
+ TotalRecordCount = dtos.Length
+ };
+ }
+
+ /// <summary>
+ /// Get user view grouping options.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <response code="200">User view grouping options returned.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the user view grouping options
+ /// or a <see cref="NotFoundResult"/> if user not found.
+ /// </returns>
+ [HttpGet("Users/{userId}/GroupingOptions")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<IEnumerable<SpecialViewOptionDto>> GetGroupingOptions([FromRoute, Required] Guid userId)
+ {
+ var user = _userManager.GetUserById(userId);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ return Ok(_libraryManager.GetUserRootFolder()
+ .GetChildren(user, true)
+ .OfType<Folder>()
+ .Where(UserView.IsEligibleForGrouping)
+ .Select(i => new SpecialViewOptionDto
+ {
+ Name = i.Name,
+ Id = i.Id.ToString("N", CultureInfo.InvariantCulture)
+ })
+ .OrderBy(i => i.Name));
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs
new file mode 100644
index 000000000..c2bb0dfff
--- /dev/null
+++ b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs
@@ -0,0 +1,82 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Net.Mime;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Attachments controller.
+ /// </summary>
+ [Route("Videos")]
+ public class VideoAttachmentsController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IAttachmentExtractor _attachmentExtractor;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideoAttachmentsController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="attachmentExtractor">Instance of the <see cref="IAttachmentExtractor"/> interface.</param>
+ public VideoAttachmentsController(
+ ILibraryManager libraryManager,
+ IAttachmentExtractor attachmentExtractor)
+ {
+ _libraryManager = libraryManager;
+ _attachmentExtractor = attachmentExtractor;
+ }
+
+ /// <summary>
+ /// Get video attachment.
+ /// </summary>
+ /// <param name="videoId">Video ID.</param>
+ /// <param name="mediaSourceId">Media Source ID.</param>
+ /// <param name="index">Attachment Index.</param>
+ /// <response code="200">Attachment retrieved.</response>
+ /// <response code="404">Video or attachment not found.</response>
+ /// <returns>An <see cref="FileStreamResult"/> containing the attachment stream on success, or a <see cref="NotFoundResult"/> if the attachment could not be found.</returns>
+ [HttpGet("{videoId}/{mediaSourceId}/Attachments/{index}")]
+ [ProducesFile(MediaTypeNames.Application.Octet)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> GetAttachment(
+ [FromRoute, Required] Guid videoId,
+ [FromRoute, Required] string mediaSourceId,
+ [FromRoute, Required] int index)
+ {
+ try
+ {
+ var item = _libraryManager.GetItemById(videoId);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var (attachment, stream) = await _attachmentExtractor.GetAttachment(
+ item,
+ mediaSourceId,
+ index,
+ CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var contentType = string.IsNullOrWhiteSpace(attachment.MimeType)
+ ? MediaTypeNames.Application.Octet
+ : attachment.MimeType;
+
+ return new FileStreamResult(stream, contentType);
+ }
+ catch (ResourceNotFoundException e)
+ {
+ return NotFound(e.Message);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs
new file mode 100644
index 000000000..ef25db8c9
--- /dev/null
+++ b/Jellyfin.Api/Controllers/VideoHlsController.cs
@@ -0,0 +1,586 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.PlaybackDtos;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The video hls controller.
+ /// </summary>
+ [Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class VideoHlsController : BaseJellyfinApiController
+ {
+ private const string DefaultEncoderPreset = "superfast";
+ private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
+
+ private readonly EncodingHelper _encodingHelper;
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IDeviceManager _deviceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly ILogger<VideoHlsController> _logger;
+ private readonly EncodingOptions _encodingOptions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideoHlsController"/> class.
+ /// </summary>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="userManger">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{VideoHlsController}"/>.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ public VideoHlsController(
+ IMediaEncoder mediaEncoder,
+ IDlnaManager dlnaManager,
+ IUserManager userManger,
+ IAuthorizationContext authorizationContext,
+ ILibraryManager libraryManager,
+ IMediaSourceManager mediaSourceManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ ILogger<VideoHlsController> logger,
+ EncodingHelper encodingHelper)
+ {
+ _dlnaManager = dlnaManager;
+ _authContext = authorizationContext;
+ _userManager = userManger;
+ _libraryManager = libraryManager;
+ _mediaSourceManager = mediaSourceManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ _mediaEncoder = mediaEncoder;
+ _deviceManager = deviceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ _logger = logger;
+ _encodingHelper = encodingHelper;
+
+ _encodingOptions = serverConfigurationManager.GetEncodingOptions();
+ }
+
+ /// <summary>
+ /// Gets a hls live stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">The audio container.</param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment lenght.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <param name="maxWidth">Optional. The max width.</param>
+ /// <param name="maxHeight">Optional. The max height.</param>
+ /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
+ /// <response code="200">Hls live stream retrieved.</response>
+ /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
+ [HttpGet("Videos/{itemId}/live.m3u8")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesPlaylistFile]
+ public async Task<ActionResult> GetLiveHlsStream(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] bool? enableSubtitlesInManifest)
+ {
+ VideoRequestDto streamingRequest = new VideoRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions,
+ MaxHeight = maxHeight,
+ MaxWidth = maxWidth,
+ EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true
+ };
+
+ // CTS lifecycle is managed internally.
+ var cancellationTokenSource = new CancellationTokenSource();
+ // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" the token
+ // since it gets disposed when ffmpeg exits
+ var cancellationToken = cancellationTokenSource.Token;
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ TranscodingJobType,
+ cancellationToken)
+ .ConfigureAwait(false);
+
+ TranscodingJobDto? job = null;
+ var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
+
+ if (!System.IO.File.Exists(playlistPath))
+ {
+ var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlistPath);
+ await transcodingLock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ if (!System.IO.File.Exists(playlistPath))
+ {
+ // If the playlist doesn't already exist, startup ffmpeg
+ try
+ {
+ job = await _transcodingJobHelper.StartFfMpeg(
+ state,
+ playlistPath,
+ GetCommandLineArguments(playlistPath, state),
+ Request,
+ TranscodingJobType,
+ cancellationTokenSource)
+ .ConfigureAwait(false);
+ job.IsLiveOutput = true;
+ }
+ catch
+ {
+ state.Dispose();
+ throw;
+ }
+
+ minSegments = state.MinSegments;
+ if (minSegments > 0)
+ {
+ await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+ finally
+ {
+ transcodingLock.Release();
+ }
+ }
+
+ job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+
+ if (job != null)
+ {
+ _transcodingJobHelper.OnTranscodeEndRequest(job);
+ }
+
+ var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
+
+ return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
+ }
+
+ /// <summary>
+ /// Gets the command line arguments for ffmpeg.
+ /// </summary>
+ /// <param name="outputPath">The output path of the file.</param>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <returns>The command line arguments as a string.</returns>
+ private string GetCommandLineArguments(string outputPath, StreamState state)
+ {
+ var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
+ var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); // GetNumberOfThreads is static.
+ var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions);
+ var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
+
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
+ var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
+ var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
+ var outputTsArg = outputPrefix + "%d" + outputExtension;
+
+ var segmentFormat = outputExtension.TrimStart('.');
+ if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
+ {
+ segmentFormat = "mpegts";
+ }
+ else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase))
+ {
+ var outputFmp4HeaderArg = string.Empty;
+ if (OperatingSystem.IsWindows())
+ {
+ // on Windows, the path of fmp4 header file needs to be configured
+ outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"";
+ }
+ else
+ {
+ // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
+ outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\"";
+ }
+
+ segmentFormat = "fmp4" + outputFmp4HeaderArg;
+ }
+ else
+ {
+ _logger.LogError("Invalid HLS segment container: {SegmentFormat}", segmentFormat);
+ }
+
+ var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
+ ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
+ : "128";
+
+ var baseUrlParam = string.Format(
+ CultureInfo.InvariantCulture,
+ "\"hls/{0}/\"",
+ Path.GetFileNameWithoutExtension(outputPath));
+
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -hls_segment_type {8} -start_number 0 -hls_base_url {9} -hls_playlist_type event -hls_segment_filename \"{10}\" -y \"{11}\"",
+ inputModifier,
+ _encodingHelper.GetInputArgument(state, _encodingOptions),
+ threads,
+ mapArgs,
+ GetVideoArguments(state),
+ GetAudioArguments(state),
+ maxMuxingQueueSize,
+ state.SegmentLength.ToString(CultureInfo.InvariantCulture),
+ segmentFormat,
+ baseUrlParam,
+ outputTsArg,
+ outputPath).Trim();
+ }
+
+ /// <summary>
+ /// Gets the audio arguments for transcoding.
+ /// </summary>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <returns>The command line arguments for audio transcoding.</returns>
+ private string GetAudioArguments(StreamState state)
+ {
+ if (state.AudioStream == null)
+ {
+ return string.Empty;
+ }
+
+ var audioCodec = _encodingHelper.GetAudioEncoder(state);
+
+ if (!state.IsOutputVideo)
+ {
+ if (EncodingHelper.IsCopyCodec(audioCodec))
+ {
+ var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
+
+ return "-acodec copy -strict -2" + bitStreamArgs;
+ }
+
+ var audioTranscodeParams = string.Empty;
+
+ audioTranscodeParams += "-acodec " + audioCodec;
+
+ if (state.OutputAudioBitrate.HasValue)
+ {
+ audioTranscodeParams += " -ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioChannels.HasValue)
+ {
+ audioTranscodeParams += " -ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioSampleRate.HasValue)
+ {
+ audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ audioTranscodeParams += " -vn";
+ return audioTranscodeParams;
+ }
+
+ if (EncodingHelper.IsCopyCodec(audioCodec))
+ {
+ var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
+
+ return "-acodec copy -strict -2" + bitStreamArgs;
+ }
+
+ var args = "-codec:a:0 " + audioCodec;
+
+ var channels = state.OutputAudioChannels;
+
+ if (channels.HasValue)
+ {
+ args += " -ac " + channels.Value;
+ }
+
+ var bitrate = state.OutputAudioBitrate;
+
+ if (bitrate.HasValue)
+ {
+ args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ if (state.OutputAudioSampleRate.HasValue)
+ {
+ args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
+
+ return args;
+ }
+
+ /// <summary>
+ /// Gets the video arguments for transcoding.
+ /// </summary>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <returns>The command line arguments for video transcoding.</returns>
+ private string GetVideoArguments(StreamState state)
+ {
+ if (state.VideoStream == null)
+ {
+ return string.Empty;
+ }
+
+ if (!state.IsOutputVideo)
+ {
+ return string.Empty;
+ }
+
+ var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
+
+ var args = "-codec:v:0 " + codec;
+
+ // Prefer hvc1 to hev1.
+ if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ args += " -tag:v:0 hvc1";
+ }
+
+ // if (state.EnableMpegtsM2TsMode)
+ // {
+ // args += " -mpegts_m2ts_mode 1";
+ // }
+
+ // See if we can save come cpu cycles by avoiding encoding.
+ if (EncodingHelper.IsCopyCodec(codec))
+ {
+ // If h264_mp4toannexb is ever added, do not use it for live tv.
+ if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
+ {
+ string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream);
+ if (!string.IsNullOrEmpty(bitStreamArgs))
+ {
+ args += " " + bitStreamArgs;
+ }
+ }
+
+ args += " -start_at_zero";
+ }
+ else
+ {
+ args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset);
+
+ // Set the key frame params for video encoding to match the hls segment time.
+ args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, true, null);
+
+ // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
+ if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase))
+ {
+ args += " -bf 0";
+ }
+
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+
+ if (hasGraphicalSubs)
+ {
+ // Graphical subs overlay and resolution params.
+ args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec);
+ }
+ else
+ {
+ // Resolution params.
+ args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec);
+ }
+
+ if (state.SubtitleStream == null || !state.SubtitleStream.IsExternal || state.SubtitleStream.IsTextSubtitleStream)
+ {
+ args += " -start_at_zero";
+ }
+ }
+
+ args += " -flags -global_header";
+
+ if (!string.IsNullOrEmpty(state.OutputVideoSync))
+ {
+ args += " -vsync " + state.OutputVideoSync;
+ }
+
+ args += _encodingHelper.GetOutputFFlags(state);
+
+ return args;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs
new file mode 100644
index 000000000..e1cbc6f33
--- /dev/null
+++ b/Jellyfin.Api/Controllers/VideosController.cs
@@ -0,0 +1,687 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Attributes;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// The videos controller.
+ /// </summary>
+ public class VideosController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IDeviceManager _deviceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly EncodingHelper _encodingHelper;
+
+ private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Progressive;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideosController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Instance of the <see cref="TranscodingJobHelper"/> class.</param>
+ /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ public VideosController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService,
+ IDlnaManager dlnaManager,
+ IAuthorizationContext authContext,
+ IMediaSourceManager mediaSourceManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IMediaEncoder mediaEncoder,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ IHttpClientFactory httpClientFactory,
+ EncodingHelper encodingHelper)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ _dlnaManager = dlnaManager;
+ _authContext = authContext;
+ _mediaSourceManager = mediaSourceManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ _mediaEncoder = mediaEncoder;
+ _deviceManager = deviceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ _httpClientFactory = httpClientFactory;
+ _encodingHelper = encodingHelper;
+ }
+
+ /// <summary>
+ /// Gets additional parts for a video.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Additional parts returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the parts.</returns>
+ [HttpGet("{itemId}/AdditionalParts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetAdditionalPart([FromRoute, Required] Guid itemId, [FromQuery] Guid? userId)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+
+ var item = itemId.Equals(Guid.Empty)
+ ? (!userId.Equals(Guid.Empty)
+ ? _libraryManager.GetUserRootFolder()
+ : _libraryManager.RootFolder)
+ : _libraryManager.GetItemById(itemId);
+
+ var dtoOptions = new DtoOptions();
+ dtoOptions = dtoOptions.AddClientFields(Request);
+
+ BaseItemDto[] items;
+ if (item is Video video)
+ {
+ items = video.GetAdditionalParts()
+ .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, video))
+ .ToArray();
+ }
+ else
+ {
+ items = Array.Empty<BaseItemDto>();
+ }
+
+ var result = new QueryResult<BaseItemDto>
+ {
+ Items = items,
+ TotalRecordCount = items.Length
+ };
+
+ return result;
+ }
+
+ /// <summary>
+ /// Removes alternate video sources.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="204">Alternate sources deleted.</response>
+ /// <response code="404">Video not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="NotFoundResult"/> if the video doesn't exist.</returns>
+ [HttpDelete("{itemId}/AlternateSources")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task<ActionResult> DeleteAlternateSources([FromRoute, Required] Guid itemId)
+ {
+ var video = (Video)_libraryManager.GetItemById(itemId);
+
+ if (video == null)
+ {
+ return NotFound("The video either does not exist or the id does not belong to a video.");
+ }
+
+ if (video.LinkedAlternateVersions.Length == 0)
+ {
+ video = (Video)_libraryManager.GetItemById(video.PrimaryVersionId);
+ }
+
+ foreach (var link in video.GetLinkedAlternateVersions())
+ {
+ link.SetPrimaryVersionId(null);
+ link.LinkedAlternateVersions = Array.Empty<LinkedChild>();
+
+ await link.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ video.LinkedAlternateVersions = Array.Empty<LinkedChild>();
+ video.SetPrimaryVersionId(null);
+ await video.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Merges videos into a single record.
+ /// </summary>
+ /// <param name="ids">Item id list. This allows multiple, comma delimited.</param>
+ /// <response code="204">Videos merged.</response>
+ /// <response code="400">Supply at least 2 video ids.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="BadRequestResult"/> if less than two ids were supplied.</returns>
+ [HttpPost("MergeVersions")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public async Task<ActionResult> MergeVersions([FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
+ {
+ var items = ids
+ .Select(i => _libraryManager.GetItemById(i))
+ .OfType<Video>()
+ .OrderBy(i => i.Id)
+ .ToList();
+
+ if (items.Count < 2)
+ {
+ return BadRequest("Please supply at least two videos to merge.");
+ }
+
+ var primaryVersion = items.FirstOrDefault(i => i.MediaSourceCount > 1 && string.IsNullOrEmpty(i.PrimaryVersionId));
+ if (primaryVersion == null)
+ {
+ primaryVersion = items
+ .OrderBy(i =>
+ {
+ if (i.Video3DFormat.HasValue || i.VideoType != VideoType.VideoFile)
+ {
+ return 1;
+ }
+
+ return 0;
+ })
+ .ThenByDescending(i => i.GetDefaultVideoStream()?.Width ?? 0)
+ .First();
+ }
+
+ var alternateVersionsOfPrimary = primaryVersion.LinkedAlternateVersions.ToList();
+
+ foreach (var item in items.Where(i => i.Id != primaryVersion.Id))
+ {
+ item.SetPrimaryVersionId(primaryVersion.Id.ToString("N", CultureInfo.InvariantCulture));
+
+ await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+
+ if (!alternateVersionsOfPrimary.Any(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase)))
+ {
+ alternateVersionsOfPrimary.Add(new LinkedChild
+ {
+ Path = item.Path,
+ ItemId = item.Id
+ });
+ }
+
+ foreach (var linkedItem in item.LinkedAlternateVersions)
+ {
+ if (!alternateVersionsOfPrimary.Any(i => string.Equals(i.Path, linkedItem.Path, StringComparison.OrdinalIgnoreCase)))
+ {
+ alternateVersionsOfPrimary.Add(linkedItem);
+ }
+ }
+
+ if (item.LinkedAlternateVersions.Length > 0)
+ {
+ item.LinkedAlternateVersions = Array.Empty<LinkedChild>();
+ await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+
+ primaryVersion.LinkedAlternateVersions = alternateVersionsOfPrimary.ToArray();
+ await primaryVersion.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a video stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
+ /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("{itemId}/stream")]
+ [HttpHead("{itemId}/stream", Name = "HeadVideoStream")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesVideoFile]
+ public async Task<ActionResult> GetVideoStream(
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ var isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head;
+ // CTS lifecycle is managed internally.
+ var cancellationTokenSource = new CancellationTokenSource();
+ var streamingRequest = new VideoRequestDto
+ {
+ Id = itemId,
+ Container = container,
+ Static = @static ?? false,
+ Params = @params,
+ Tag = tag,
+ DeviceProfileId = deviceProfileId,
+ PlaySessionId = playSessionId,
+ SegmentContainer = segmentContainer,
+ SegmentLength = segmentLength,
+ MinSegments = minSegments,
+ MediaSourceId = mediaSourceId,
+ DeviceId = deviceId,
+ AudioCodec = audioCodec,
+ EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
+ AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
+ AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
+ BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
+ AudioSampleRate = audioSampleRate,
+ MaxAudioChannels = maxAudioChannels,
+ AudioBitRate = audioBitRate,
+ MaxAudioBitDepth = maxAudioBitDepth,
+ AudioChannels = audioChannels,
+ Profile = profile,
+ Level = level,
+ Framerate = framerate,
+ MaxFramerate = maxFramerate,
+ CopyTimestamps = copyTimestamps ?? false,
+ StartTimeTicks = startTimeTicks,
+ Width = width,
+ Height = height,
+ MaxWidth = maxWidth,
+ MaxHeight = maxHeight,
+ VideoBitRate = videoBitRate,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
+ MaxRefFrames = maxRefFrames,
+ MaxVideoBitDepth = maxVideoBitDepth,
+ RequireAvc = requireAvc ?? false,
+ DeInterlace = deInterlace ?? false,
+ RequireNonAnamorphic = requireNonAnamorphic ?? false,
+ TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
+ CpuCoreLimit = cpuCoreLimit,
+ LiveStreamId = liveStreamId,
+ EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
+ VideoCodec = videoCodec,
+ SubtitleCodec = subtitleCodec,
+ TranscodeReasons = transcodeReasons,
+ AudioStreamIndex = audioStreamIndex,
+ VideoStreamIndex = videoStreamIndex,
+ Context = context ?? EncodingContext.Streaming,
+ StreamOptions = streamOptions
+ };
+
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ _transcodingJobType,
+ cancellationTokenSource.Token)
+ .ConfigureAwait(false);
+
+ if (@static.HasValue && @static.Value && state.DirectStreamProvider != null)
+ {
+ StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager);
+
+ var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId);
+ if (liveStreamInfo == null)
+ {
+ return NotFound();
+ }
+
+ var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream());
+ // TODO (moved from MediaBrowser.Api): Don't hardcode contentType
+ return File(liveStream, MimeTypes.GetMimeType("file.ts"));
+ }
+
+ // Static remote stream
+ if (@static.HasValue && @static.Value && state.InputProtocol == MediaProtocol.Http)
+ {
+ StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager);
+
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ return await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, HttpContext).ConfigureAwait(false);
+ }
+
+ if (@static.HasValue && @static.Value && state.InputProtocol != MediaProtocol.File)
+ {
+ return BadRequest($"Input protocol {state.InputProtocol} cannot be streamed statically");
+ }
+
+ var outputPath = state.OutputFilePath;
+ var outputPathExists = System.IO.File.Exists(outputPath);
+
+ var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
+ var isTranscodeCached = outputPathExists && transcodingJob != null;
+
+ StreamingHelpers.AddDlnaHeaders(state, Response.Headers, (@static.HasValue && @static.Value) || isTranscodeCached, startTimeTicks, Request, _dlnaManager);
+
+ // Static stream
+ if (@static.HasValue && @static.Value)
+ {
+ var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
+
+ if (state.MediaSource.IsInfiniteStream)
+ {
+ var liveStream = new ProgressiveFileStream(state.MediaPath, null, _transcodingJobHelper);
+ return File(liveStream, contentType);
+ }
+
+ return FileStreamResponseHelpers.GetStaticFileResult(
+ state.MediaPath,
+ contentType,
+ isHeadRequest,
+ HttpContext);
+ }
+
+ // Need to start ffmpeg (because media can't be returned directly)
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast");
+ return await FileStreamResponseHelpers.GetTranscodedFile(
+ state,
+ isHeadRequest,
+ HttpContext,
+ _transcodingJobHelper,
+ ffmpegCommandLineArguments,
+ _transcodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Gets a video stream.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
+ /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
+ /// <param name="params">The streaming parameters.</param>
+ /// <param name="tag">The tag.</param>
+ /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="segmentContainer">The segment container.</param>
+ /// <param name="segmentLength">The segment length.</param>
+ /// <param name="minSegments">The minimum number of segments.</param>
+ /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
+ /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
+ /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
+ /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
+ /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
+ /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
+ /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
+ /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
+ /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
+ /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
+ /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
+ /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
+ /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
+ /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
+ /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
+ /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
+ /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
+ /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
+ /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
+ /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
+ /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
+ /// <param name="maxRefFrames">Optional.</param>
+ /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
+ /// <param name="requireAvc">Optional. Whether to require avc.</param>
+ /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
+ /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
+ /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
+ /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
+ /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vp8, vp9, vpx (deprecated), wmv.</param>
+ /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
+ /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
+ /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
+ /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
+ /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
+ /// <param name="streamOptions">Optional. The streaming options.</param>
+ /// <response code="200">Video stream returned.</response>
+ /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
+ [HttpGet("{itemId}/stream.{container}")]
+ [HttpHead("{itemId}/stream.{container}", Name = "HeadVideoStreamByContainer")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesVideoFile]
+ public Task<ActionResult> GetVideoStreamByContainer(
+ [FromRoute, Required] Guid itemId,
+ [FromRoute, Required] string container,
+ [FromQuery] bool? @static,
+ [FromQuery] string? @params,
+ [FromQuery] string? tag,
+ [FromQuery] string? deviceProfileId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] string? segmentContainer,
+ [FromQuery] int? segmentLength,
+ [FromQuery] int? minSegments,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? deviceId,
+ [FromQuery] string? audioCodec,
+ [FromQuery] bool? enableAutoStreamCopy,
+ [FromQuery] bool? allowVideoStreamCopy,
+ [FromQuery] bool? allowAudioStreamCopy,
+ [FromQuery] bool? breakOnNonKeyFrames,
+ [FromQuery] int? audioSampleRate,
+ [FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? audioBitRate,
+ [FromQuery] int? audioChannels,
+ [FromQuery] int? maxAudioChannels,
+ [FromQuery] string? profile,
+ [FromQuery] string? level,
+ [FromQuery] float? framerate,
+ [FromQuery] float? maxFramerate,
+ [FromQuery] bool? copyTimestamps,
+ [FromQuery] long? startTimeTicks,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] int? videoBitRate,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
+ [FromQuery] int? maxRefFrames,
+ [FromQuery] int? maxVideoBitDepth,
+ [FromQuery] bool? requireAvc,
+ [FromQuery] bool? deInterlace,
+ [FromQuery] bool? requireNonAnamorphic,
+ [FromQuery] int? transcodingMaxAudioChannels,
+ [FromQuery] int? cpuCoreLimit,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] bool? enableMpegtsM2TsMode,
+ [FromQuery] string? videoCodec,
+ [FromQuery] string? subtitleCodec,
+ [FromQuery] string? transcodeReasons,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? videoStreamIndex,
+ [FromQuery] EncodingContext? context,
+ [FromQuery] Dictionary<string, string> streamOptions)
+ {
+ return GetVideoStream(
+ itemId,
+ container,
+ @static,
+ @params,
+ tag,
+ deviceProfileId,
+ playSessionId,
+ segmentContainer,
+ segmentLength,
+ minSegments,
+ mediaSourceId,
+ deviceId,
+ audioCodec,
+ enableAutoStreamCopy,
+ allowVideoStreamCopy,
+ allowAudioStreamCopy,
+ breakOnNonKeyFrames,
+ audioSampleRate,
+ maxAudioBitDepth,
+ audioBitRate,
+ audioChannels,
+ maxAudioChannels,
+ profile,
+ level,
+ framerate,
+ maxFramerate,
+ copyTimestamps,
+ startTimeTicks,
+ width,
+ height,
+ maxWidth,
+ maxHeight,
+ videoBitRate,
+ subtitleStreamIndex,
+ subtitleMethod,
+ maxRefFrames,
+ maxVideoBitDepth,
+ requireAvc,
+ deInterlace,
+ requireNonAnamorphic,
+ transcodingMaxAudioChannels,
+ cpuCoreLimit,
+ liveStreamId,
+ enableMpegtsM2TsMode,
+ videoCodec,
+ subtitleCodec,
+ transcodeReasons,
+ audioStreamIndex,
+ videoStreamIndex,
+ context,
+ streamOptions);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs
new file mode 100644
index 000000000..d6dc6650c
--- /dev/null
+++ b/Jellyfin.Api/Controllers/YearsController.cs
@@ -0,0 +1,229 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Controllers
+{
+ /// <summary>
+ /// Years controller.
+ /// </summary>
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class YearsController : BaseJellyfinApiController
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDtoService _dtoService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="YearsController"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+ public YearsController(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDtoService dtoService)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dtoService = dtoService;
+ }
+
+ /// <summary>
+ /// Get years.
+ /// </summary>
+ /// <param name="startIndex">Skips over a given number of items within the results. Use for paging.</param>
+ /// <param name="limit">Optional. The maximum number of records to return.</param>
+ /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be excluded based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be included based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="userId">User Id.</param>
+ /// <param name="recursive">Search recursively.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <response code="200">Year query returned.</response>
+ /// <returns> A <see cref="QueryResult{BaseItemDto}"/> containing the year result.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetYears(
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] Guid? userId,
+ [FromQuery] bool recursive = true,
+ [FromQuery] bool? enableImages = true)
+ {
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request)
+ .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+
+ User? user = null;
+ BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId);
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ user = _userManager.GetUserById(userId.Value);
+ }
+
+ IList<BaseItem> items;
+
+ var query = new InternalItemsQuery(user)
+ {
+ ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes),
+ IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes),
+ MediaTypes = mediaTypes,
+ DtoOptions = dtoOptions
+ };
+
+ bool Filter(BaseItem i) => FilterItem(i, excludeItemTypes, includeItemTypes, mediaTypes);
+
+ if (parentItem.IsFolder)
+ {
+ var folder = (Folder)parentItem;
+
+ if (!userId.Equals(Guid.Empty))
+ {
+ items = recursive ? folder.GetRecursiveChildren(user, query).ToList() : folder.GetChildren(user, true).Where(Filter).ToList();
+ }
+ else
+ {
+ items = recursive ? folder.GetRecursiveChildren(Filter) : folder.Children.Where(Filter).ToList();
+ }
+ }
+ else
+ {
+ items = new[] { parentItem }.Where(Filter).ToList();
+ }
+
+ var extractedItems = GetAllItems(items);
+
+ var filteredItems = _libraryManager.Sort(extractedItems, user, RequestHelpers.GetOrderBy(sortBy, sortOrder));
+
+ var ibnItemsArray = filteredItems.ToList();
+
+ IEnumerable<BaseItem> ibnItems = ibnItemsArray;
+
+ var result = new QueryResult<BaseItemDto> { TotalRecordCount = ibnItemsArray.Count };
+
+ if (startIndex.HasValue || limit.HasValue)
+ {
+ if (startIndex.HasValue)
+ {
+ ibnItems = ibnItems.Skip(startIndex.Value);
+ }
+
+ if (limit.HasValue)
+ {
+ ibnItems = ibnItems.Take(limit.Value);
+ }
+ }
+
+ var tuples = ibnItems.Select(i => new Tuple<BaseItem, List<BaseItem>>(i, new List<BaseItem>()));
+
+ var dtos = tuples.Select(i => _dtoService.GetItemByNameDto(i.Item1, dtoOptions, i.Item2, user));
+
+ result.Items = dtos.Where(i => i != null).ToArray();
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets a year.
+ /// </summary>
+ /// <param name="year">The year.</param>
+ /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+ /// <response code="200">Year returned.</response>
+ /// <response code="404">Year not found.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the year,
+ /// or a <see cref="NotFoundResult"/> if year not found.
+ /// </returns>
+ [HttpGet("{year}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public ActionResult<BaseItemDto> GetYear([FromRoute, Required] int year, [FromQuery] Guid? userId)
+ {
+ var item = _libraryManager.GetYear(year);
+ if (item == null)
+ {
+ return NotFound();
+ }
+
+ var dtoOptions = new DtoOptions()
+ .AddClientFields(Request);
+
+ if (userId.HasValue && !userId.Equals(Guid.Empty))
+ {
+ var user = _userManager.GetUserById(userId.Value);
+ return _dtoService.GetBaseItemDto(item, dtoOptions, user);
+ }
+
+ return _dtoService.GetBaseItemDto(item, dtoOptions);
+ }
+
+ private bool FilterItem(BaseItem f, IReadOnlyCollection<BaseItemKind> excludeItemTypes, IReadOnlyCollection<BaseItemKind> includeItemTypes, IReadOnlyCollection<string> mediaTypes)
+ {
+ var baseItemKind = f.GetBaseItemKind();
+ // Exclude item types
+ if (excludeItemTypes.Count > 0 && excludeItemTypes.Contains(baseItemKind))
+ {
+ return false;
+ }
+
+ // Include item types
+ if (includeItemTypes.Count > 0 && !includeItemTypes.Contains(baseItemKind))
+ {
+ return false;
+ }
+
+ // Include MediaTypes
+ if (mediaTypes.Count > 0 && !mediaTypes.Contains(f.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private IEnumerable<BaseItem> GetAllItems(IEnumerable<BaseItem> items)
+ {
+ return items
+ .Select(i => i.ProductionYear ?? 0)
+ .Where(i => i > 0)
+ .Distinct()
+ .Select(year => _libraryManager.GetYear(year));
+ }
+ }
+}
diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs
new file mode 100644
index 000000000..5e338b67d
--- /dev/null
+++ b/Jellyfin.Api/Extensions/DtoExtensions.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Generic;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Extensions
+{
+ /// <summary>
+ /// Dto Extensions.
+ /// </summary>
+ public static class DtoExtensions
+ {
+ /// <summary>
+ /// Add additional fields depending on client.
+ /// </summary>
+ /// <remarks>
+ /// Use in place of GetDtoOptions.
+ /// Legacy order: 2.
+ /// </remarks>
+ /// <param name="dtoOptions">DtoOptions object.</param>
+ /// <param name="request">Current request.</param>
+ /// <returns>Modified DtoOptions object.</returns>
+ internal static DtoOptions AddClientFields(
+ this DtoOptions dtoOptions, HttpRequest request)
+ {
+ dtoOptions.Fields ??= Array.Empty<ItemFields>();
+
+ string? client = ClaimHelpers.GetClient(request.HttpContext.User);
+
+ // No client in claim
+ if (string.IsNullOrEmpty(client))
+ {
+ return dtoOptions;
+ }
+
+ if (!dtoOptions.ContainsField(ItemFields.RecursiveItemCount))
+ {
+ if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ int oldLen = dtoOptions.Fields.Count;
+ var arr = new ItemFields[oldLen + 1];
+ dtoOptions.Fields.CopyTo(arr, 0);
+ arr[oldLen] = ItemFields.RecursiveItemCount;
+ dtoOptions.Fields = arr;
+ }
+ }
+
+ if (!dtoOptions.ContainsField(ItemFields.ChildCount))
+ {
+ if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("roku", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("samsung", StringComparison.OrdinalIgnoreCase) != -1 ||
+ client.IndexOf("androidtv", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ int oldLen = dtoOptions.Fields.Count;
+ var arr = new ItemFields[oldLen + 1];
+ dtoOptions.Fields.CopyTo(arr, 0);
+ arr[oldLen] = ItemFields.ChildCount;
+ dtoOptions.Fields = arr;
+ }
+ }
+
+ return dtoOptions;
+ }
+
+ /// <summary>
+ /// Add additional DtoOptions.
+ /// </summary>
+ /// <remarks>
+ /// Converted from IHasDtoOptions.
+ /// Legacy order: 3.
+ /// </remarks>
+ /// <param name="dtoOptions">DtoOptions object.</param>
+ /// <param name="enableImages">Enable images.</param>
+ /// <param name="enableUserData">Enable user data.</param>
+ /// <param name="imageTypeLimit">Image type limit.</param>
+ /// <param name="enableImageTypes">Enable image types.</param>
+ /// <returns>Modified DtoOptions object.</returns>
+ internal static DtoOptions AddAdditionalDtoOptions(
+ this DtoOptions dtoOptions,
+ bool? enableImages,
+ bool? enableUserData,
+ int? imageTypeLimit,
+ IReadOnlyList<ImageType> enableImageTypes)
+ {
+ dtoOptions.EnableImages = enableImages ?? true;
+
+ if (imageTypeLimit.HasValue)
+ {
+ dtoOptions.ImageTypeLimit = imageTypeLimit.Value;
+ }
+
+ if (enableUserData.HasValue)
+ {
+ dtoOptions.EnableUserData = enableUserData.Value;
+ }
+
+ if (enableImageTypes.Count != 0)
+ {
+ dtoOptions.ImageTypes = enableImageTypes;
+ }
+
+ return dtoOptions;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs
new file mode 100644
index 000000000..bec961dad
--- /dev/null
+++ b/Jellyfin.Api/Helpers/AudioHelper.cs
@@ -0,0 +1,188 @@
+using System.IO;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Audio helper.
+ /// </summary>
+ public class AudioHelper
+ {
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IDeviceManager _deviceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly EncodingHelper _encodingHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioHelper"/> class.
+ /// </summary>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Instance of <see cref="TranscodingJobHelper"/>.</param>
+ /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ public AudioHelper(
+ IDlnaManager dlnaManager,
+ IAuthorizationContext authContext,
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IMediaSourceManager mediaSourceManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IMediaEncoder mediaEncoder,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ IHttpClientFactory httpClientFactory,
+ IHttpContextAccessor httpContextAccessor,
+ EncodingHelper encodingHelper)
+ {
+ _dlnaManager = dlnaManager;
+ _authContext = authContext;
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _mediaSourceManager = mediaSourceManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ _mediaEncoder = mediaEncoder;
+ _deviceManager = deviceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ _httpClientFactory = httpClientFactory;
+ _httpContextAccessor = httpContextAccessor;
+ _encodingHelper = encodingHelper;
+ }
+
+ /// <summary>
+ /// Get audio stream.
+ /// </summary>
+ /// <param name="transcodingJobType">Transcoding job type.</param>
+ /// <param name="streamingRequest">Streaming controller.Request dto.</param>
+ /// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns>
+ public async Task<ActionResult> GetAudioStream(
+ TranscodingJobType transcodingJobType,
+ StreamingRequestDto streamingRequest)
+ {
+ if (_httpContextAccessor.HttpContext == null)
+ {
+ throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext));
+ }
+
+ bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head;
+
+ // CTS lifecycle is managed internally.
+ var cancellationTokenSource = new CancellationTokenSource();
+
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ _httpContextAccessor.HttpContext.Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ transcodingJobType,
+ cancellationTokenSource.Token)
+ .ConfigureAwait(false);
+
+ if (streamingRequest.Static && state.DirectStreamProvider != null)
+ {
+ StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, true, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager);
+
+ var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId);
+ if (liveStreamInfo == null)
+ {
+ throw new FileNotFoundException();
+ }
+
+ var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream());
+ // TODO (moved from MediaBrowser.Api): Don't hardcode contentType
+ return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file.ts"));
+ }
+
+ // Static remote stream
+ if (streamingRequest.Static && state.InputProtocol == MediaProtocol.Http)
+ {
+ StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, true, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager);
+
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ return await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, _httpContextAccessor.HttpContext).ConfigureAwait(false);
+ }
+
+ if (streamingRequest.Static && state.InputProtocol != MediaProtocol.File)
+ {
+ return new BadRequestObjectResult($"Input protocol {state.InputProtocol} cannot be streamed statically");
+ }
+
+ var outputPath = state.OutputFilePath;
+ var outputPathExists = File.Exists(outputPath);
+
+ var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
+ var isTranscodeCached = outputPathExists && transcodingJob != null;
+
+ StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, streamingRequest.Static || isTranscodeCached, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager);
+
+ // Static stream
+ if (streamingRequest.Static)
+ {
+ var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
+
+ if (state.MediaSource.IsInfiniteStream)
+ {
+ var stream = new ProgressiveFileStream(state.MediaPath, null, _transcodingJobHelper);
+ return new FileStreamResult(stream, contentType);
+ }
+
+ return FileStreamResponseHelpers.GetStaticFileResult(
+ state.MediaPath,
+ contentType,
+ isHeadRequest,
+ _httpContextAccessor.HttpContext);
+ }
+
+ // Need to start ffmpeg (because media can't be returned directly)
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath);
+ return await FileStreamResponseHelpers.GetTranscodedFile(
+ state,
+ isHeadRequest,
+ _httpContextAccessor.HttpContext,
+ _transcodingJobHelper,
+ ffmpegCommandLineArguments,
+ transcodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/ClaimHelpers.cs b/Jellyfin.Api/Helpers/ClaimHelpers.cs
new file mode 100644
index 000000000..c1c2f93b4
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ClaimHelpers.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Linq;
+using System.Security.Claims;
+using Jellyfin.Api.Constants;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Claim Helpers.
+ /// </summary>
+ public static class ClaimHelpers
+ {
+ /// <summary>
+ /// Get user id from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>User id.</returns>
+ public static Guid? GetUserId(in ClaimsPrincipal user)
+ {
+ var value = GetClaimValue(user, InternalClaimTypes.UserId);
+ return string.IsNullOrEmpty(value)
+ ? null
+ : Guid.Parse(value);
+ }
+
+ /// <summary>
+ /// Get device id from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>Device id.</returns>
+ public static string? GetDeviceId(in ClaimsPrincipal user)
+ => GetClaimValue(user, InternalClaimTypes.DeviceId);
+
+ /// <summary>
+ /// Get device from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>Device.</returns>
+ public static string? GetDevice(in ClaimsPrincipal user)
+ => GetClaimValue(user, InternalClaimTypes.Device);
+
+ /// <summary>
+ /// Get client from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>Client.</returns>
+ public static string? GetClient(in ClaimsPrincipal user)
+ => GetClaimValue(user, InternalClaimTypes.Client);
+
+ /// <summary>
+ /// Get version from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>Version.</returns>
+ public static string? GetVersion(in ClaimsPrincipal user)
+ => GetClaimValue(user, InternalClaimTypes.Version);
+
+ /// <summary>
+ /// Get token from claims.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>Token.</returns>
+ public static string? GetToken(in ClaimsPrincipal user)
+ => GetClaimValue(user, InternalClaimTypes.Token);
+
+ /// <summary>
+ /// Gets a flag specifying whether the request is using an api key.
+ /// </summary>
+ /// <param name="user">Current claims principal.</param>
+ /// <returns>The flag specifying whether the request is using an api key.</returns>
+ public static bool GetIsApiKey(in ClaimsPrincipal user)
+ {
+ var claimValue = GetClaimValue(user, InternalClaimTypes.IsApiKey);
+ return !string.IsNullOrEmpty(claimValue)
+ && bool.TryParse(claimValue, out var parsedClaimValue)
+ && parsedClaimValue;
+ }
+
+ private static string? GetClaimValue(in ClaimsPrincipal user, string name)
+ {
+ return user?.Identities
+ .SelectMany(c => c.Claims)
+ .Where(claim => claim.Type.Equals(name, StringComparison.OrdinalIgnoreCase))
+ .Select(claim => claim.Value)
+ .FirstOrDefault();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs
new file mode 100644
index 000000000..a911a3324
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Reflection;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// A static class for copying matching properties from one object to another.
+ /// TODO: remove at the point when a fixed migration path has been decided upon.
+ /// </summary>
+ public static class ClassMigrationHelper
+ {
+ /// <summary>
+ /// Extension for 'Object' that copies the properties to a destination object.
+ /// </summary>
+ /// <param name="source">The source.</param>
+ /// <param name="destination">The destination.</param>
+ public static void CopyProperties(this object source, object destination)
+ {
+ // If any this null throw an exception.
+ if (source == null || destination == null)
+ {
+ throw new Exception("Source or/and Destination Objects are null");
+ }
+
+ // Getting the Types of the objects.
+ Type typeDest = destination.GetType();
+ Type typeSrc = source.GetType();
+
+ // Iterate the Properties of the source instance and populate them from their destination counterparts.
+ PropertyInfo[] srcProps = typeSrc.GetProperties();
+ foreach (PropertyInfo srcProp in srcProps)
+ {
+ if (!srcProp.CanRead)
+ {
+ continue;
+ }
+
+ var targetProperty = typeDest.GetProperty(srcProp.Name);
+ if (targetProperty == null)
+ {
+ continue;
+ }
+
+ if (!targetProperty.CanWrite)
+ {
+ continue;
+ }
+
+ var obj = targetProperty.GetSetMethod(true);
+ if (obj != null && obj.IsPrivate)
+ {
+ continue;
+ }
+
+ var target = targetProperty.GetSetMethod();
+ if (target != null && (target.Attributes & MethodAttributes.Static) != 0)
+ {
+ continue;
+ }
+
+ if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
+ {
+ continue;
+ }
+
+ // Passed all tests, lets set the value.
+ targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
new file mode 100644
index 000000000..4abe4c5d5
--- /dev/null
+++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
@@ -0,0 +1,707 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Security.Claims;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Dynamic hls helper.
+ /// </summary>
+ public class DynamicHlsHelper
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly IUserManager _userManager;
+ private readonly IDlnaManager _dlnaManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IDeviceManager _deviceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly INetworkManager _networkManager;
+ private readonly ILogger<DynamicHlsHelper> _logger;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly EncodingHelper _encodingHelper;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DynamicHlsHelper"/> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Instance of <see cref="TranscodingJobHelper"/>.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsHelper}"/> interface.</param>
+ /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ public DynamicHlsHelper(
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IDlnaManager dlnaManager,
+ IAuthorizationContext authContext,
+ IMediaSourceManager mediaSourceManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IMediaEncoder mediaEncoder,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ INetworkManager networkManager,
+ ILogger<DynamicHlsHelper> logger,
+ IHttpContextAccessor httpContextAccessor,
+ EncodingHelper encodingHelper)
+ {
+ _libraryManager = libraryManager;
+ _userManager = userManager;
+ _dlnaManager = dlnaManager;
+ _authContext = authContext;
+ _mediaSourceManager = mediaSourceManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ _mediaEncoder = mediaEncoder;
+ _deviceManager = deviceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ _networkManager = networkManager;
+ _logger = logger;
+ _httpContextAccessor = httpContextAccessor;
+ _encodingHelper = encodingHelper;
+ }
+
+ /// <summary>
+ /// Get master hls playlist.
+ /// </summary>
+ /// <param name="transcodingJobType">Transcoding job type.</param>
+ /// <param name="streamingRequest">Streaming request dto.</param>
+ /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
+ /// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns>
+ public async Task<ActionResult> GetMasterHlsPlaylist(
+ TranscodingJobType transcodingJobType,
+ StreamingRequestDto streamingRequest,
+ bool enableAdaptiveBitrateStreaming)
+ {
+ var isHeadRequest = _httpContextAccessor.HttpContext?.Request.Method == WebRequestMethods.Http.Head;
+ // CTS lifecycle is managed internally.
+ var cancellationTokenSource = new CancellationTokenSource();
+ return await GetMasterPlaylistInternal(
+ streamingRequest,
+ isHeadRequest,
+ enableAdaptiveBitrateStreaming,
+ transcodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
+ }
+
+ private async Task<ActionResult> GetMasterPlaylistInternal(
+ StreamingRequestDto streamingRequest,
+ bool isHeadRequest,
+ bool enableAdaptiveBitrateStreaming,
+ TranscodingJobType transcodingJobType,
+ CancellationTokenSource cancellationTokenSource)
+ {
+ if (_httpContextAccessor.HttpContext == null)
+ {
+ throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext));
+ }
+
+ using var state = await StreamingHelpers.GetStreamingState(
+ streamingRequest,
+ _httpContextAccessor.HttpContext.Request,
+ _authContext,
+ _mediaSourceManager,
+ _userManager,
+ _libraryManager,
+ _serverConfigurationManager,
+ _mediaEncoder,
+ _encodingHelper,
+ _dlnaManager,
+ _deviceManager,
+ _transcodingJobHelper,
+ transcodingJobType,
+ cancellationTokenSource.Token)
+ .ConfigureAwait(false);
+
+ _httpContextAccessor.HttpContext.Response.Headers.Add(HeaderNames.Expires, "0");
+ if (isHeadRequest)
+ {
+ return new FileContentResult(Array.Empty<byte>(), MimeTypes.GetMimeType("playlist.m3u8"));
+ }
+
+ var totalBitrate = (state.OutputAudioBitrate ?? 0) + (state.OutputVideoBitrate ?? 0);
+
+ var builder = new StringBuilder();
+
+ builder.AppendLine("#EXTM3U");
+
+ var isLiveStream = state.IsSegmentedLiveStream;
+
+ var queryString = _httpContextAccessor.HttpContext.Request.QueryString.ToString();
+
+ // from universal audio service
+ if (!string.IsNullOrWhiteSpace(state.Request.SegmentContainer)
+ && !queryString.Contains("SegmentContainer", StringComparison.OrdinalIgnoreCase))
+ {
+ queryString += "&SegmentContainer=" + state.Request.SegmentContainer;
+ }
+
+ // from universal audio service
+ if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons)
+ && !queryString.Contains("TranscodeReasons=", StringComparison.OrdinalIgnoreCase))
+ {
+ queryString += "&TranscodeReasons=" + state.Request.TranscodeReasons;
+ }
+
+ // Main stream
+ var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
+
+ playlistUrl += queryString;
+
+ var subtitleStreams = state.MediaSource
+ .MediaStreams
+ .Where(i => i.IsTextSubtitleStream)
+ .ToList();
+
+ var subtitleGroup = subtitleStreams.Count > 0 && (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Hls || state.VideoRequest!.EnableSubtitlesInManifest)
+ ? "subs"
+ : null;
+
+ // If we're burning in subtitles then don't add additional subs to the manifest
+ if (state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
+ {
+ subtitleGroup = null;
+ }
+
+ if (!string.IsNullOrWhiteSpace(subtitleGroup))
+ {
+ AddSubtitles(state, subtitleStreams, builder, _httpContextAccessor.HttpContext.User);
+ }
+
+ var basicPlaylist = AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup);
+
+ if (state.VideoStream != null && state.VideoRequest != null)
+ {
+ // Provide SDR HEVC entrance for backward compatibility.
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
+ && !string.IsNullOrEmpty(state.VideoStream.VideoRange)
+ && string.Equals(state.VideoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ var requestedVideoProfiles = state.GetRequestedProfiles("hevc");
+ if (requestedVideoProfiles != null && requestedVideoProfiles.Length > 0)
+ {
+ // Force HEVC Main Profile and disable video stream copy.
+ state.OutputVideoCodec = "hevc";
+ var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(',', requestedVideoProfiles), "main");
+ sdrVideoUrl += "&AllowVideoStreamCopy=false";
+
+ var sdrOutputVideoBitrate = _encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec) ?? 0;
+ var sdrOutputAudioBitrate = _encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream) ?? 0;
+ var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate;
+
+ AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup);
+
+ // Restore the video codec
+ state.OutputVideoCodec = "copy";
+ }
+ }
+
+ // Provide Level 5.0 entrance for backward compatibility.
+ // e.g. Apple A10 chips refuse the master playlist containing SDR HEVC Main Level 5.1 video,
+ // but in fact it is capable of playing videos up to Level 6.1.
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
+ && state.VideoStream.Level.HasValue
+ && state.VideoStream.Level > 150
+ && !string.IsNullOrEmpty(state.VideoStream.VideoRange)
+ && string.Equals(state.VideoStream.VideoRange, "SDR", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ var playlistCodecsField = new StringBuilder();
+ AppendPlaylistCodecsField(playlistCodecsField, state);
+
+ // Force the video level to 5.0.
+ var originalLevel = state.VideoStream.Level;
+ state.VideoStream.Level = 150;
+ var newPlaylistCodecsField = new StringBuilder();
+ AppendPlaylistCodecsField(newPlaylistCodecsField, state);
+
+ // Restore the video level.
+ state.VideoStream.Level = originalLevel;
+ var newPlaylist = ReplacePlaylistCodecsField(basicPlaylist, playlistCodecsField, newPlaylistCodecsField);
+ builder.Append(newPlaylist);
+ }
+ }
+
+ if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp()))
+ {
+ var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
+
+ // By default, vary by just 200k
+ var variation = GetBitrateVariation(totalBitrate);
+
+ var newBitrate = totalBitrate - variation;
+ var variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
+ AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
+
+ variation *= 2;
+ newBitrate = totalBitrate - variation;
+ variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
+ AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
+ }
+
+ return new FileContentResult(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
+ }
+
+ private StringBuilder AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string? subtitleGroup)
+ {
+ var playlistBuilder = new StringBuilder();
+ playlistBuilder.Append("#EXT-X-STREAM-INF:BANDWIDTH=")
+ .Append(bitrate.ToString(CultureInfo.InvariantCulture))
+ .Append(",AVERAGE-BANDWIDTH=")
+ .Append(bitrate.ToString(CultureInfo.InvariantCulture));
+
+ AppendPlaylistVideoRangeField(playlistBuilder, state);
+
+ AppendPlaylistCodecsField(playlistBuilder, state);
+
+ AppendPlaylistResolutionField(playlistBuilder, state);
+
+ AppendPlaylistFramerateField(playlistBuilder, state);
+
+ if (!string.IsNullOrWhiteSpace(subtitleGroup))
+ {
+ playlistBuilder.Append(",SUBTITLES=\"")
+ .Append(subtitleGroup)
+ .Append('"');
+ }
+
+ playlistBuilder.Append(Environment.NewLine);
+ playlistBuilder.AppendLine(url);
+ builder.Append(playlistBuilder);
+
+ return playlistBuilder;
+ }
+
+ /// <summary>
+ /// Appends a VIDEO-RANGE field containing the range of the output video stream.
+ /// </summary>
+ /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
+ /// <param name="builder">StringBuilder to append the field to.</param>
+ /// <param name="state">StreamState of the current stream.</param>
+ private void AppendPlaylistVideoRangeField(StringBuilder builder, StreamState state)
+ {
+ if (state.VideoStream != null && !string.IsNullOrEmpty(state.VideoStream.VideoRange))
+ {
+ var videoRange = state.VideoStream.VideoRange;
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
+ {
+ if (string.Equals(videoRange, "SDR", StringComparison.OrdinalIgnoreCase))
+ {
+ builder.Append(",VIDEO-RANGE=SDR");
+ }
+
+ if (string.Equals(videoRange, "HDR", StringComparison.OrdinalIgnoreCase))
+ {
+ builder.Append(",VIDEO-RANGE=PQ");
+ }
+ }
+ else
+ {
+ // Currently we only encode to SDR.
+ builder.Append(",VIDEO-RANGE=SDR");
+ }
+ }
+ }
+
+ /// <summary>
+ /// Appends a CODECS field containing formatted strings of
+ /// the active streams output video and audio codecs.
+ /// </summary>
+ /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
+ /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
+ /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
+ /// <param name="builder">StringBuilder to append the field to.</param>
+ /// <param name="state">StreamState of the current stream.</param>
+ private void AppendPlaylistCodecsField(StringBuilder builder, StreamState state)
+ {
+ // Video
+ string videoCodecs = string.Empty;
+ int? videoCodecLevel = GetOutputVideoCodecLevel(state);
+ if (!string.IsNullOrEmpty(state.ActualOutputVideoCodec) && videoCodecLevel.HasValue)
+ {
+ videoCodecs = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
+ }
+
+ // Audio
+ string audioCodecs = string.Empty;
+ if (!string.IsNullOrEmpty(state.ActualOutputAudioCodec))
+ {
+ audioCodecs = GetPlaylistAudioCodecs(state);
+ }
+
+ StringBuilder codecs = new StringBuilder();
+
+ codecs.Append(videoCodecs);
+
+ if (!string.IsNullOrEmpty(videoCodecs) && !string.IsNullOrEmpty(audioCodecs))
+ {
+ codecs.Append(',');
+ }
+
+ codecs.Append(audioCodecs);
+
+ if (codecs.Length > 1)
+ {
+ builder.Append(",CODECS=\"")
+ .Append(codecs)
+ .Append('"');
+ }
+ }
+
+ /// <summary>
+ /// Appends a RESOLUTION field containing the resolution of the output stream.
+ /// </summary>
+ /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
+ /// <param name="builder">StringBuilder to append the field to.</param>
+ /// <param name="state">StreamState of the current stream.</param>
+ private void AppendPlaylistResolutionField(StringBuilder builder, StreamState state)
+ {
+ if (state.OutputWidth.HasValue && state.OutputHeight.HasValue)
+ {
+ builder.Append(",RESOLUTION=")
+ .Append(state.OutputWidth.GetValueOrDefault())
+ .Append('x')
+ .Append(state.OutputHeight.GetValueOrDefault());
+ }
+ }
+
+ /// <summary>
+ /// Appends a FRAME-RATE field containing the framerate of the output stream.
+ /// </summary>
+ /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
+ /// <param name="builder">StringBuilder to append the field to.</param>
+ /// <param name="state">StreamState of the current stream.</param>
+ private void AppendPlaylistFramerateField(StringBuilder builder, StreamState state)
+ {
+ double? framerate = null;
+ if (state.TargetFramerate.HasValue)
+ {
+ framerate = Math.Round(state.TargetFramerate.GetValueOrDefault(), 3);
+ }
+ else if (state.VideoStream?.RealFrameRate != null)
+ {
+ framerate = Math.Round(state.VideoStream.RealFrameRate.GetValueOrDefault(), 3);
+ }
+
+ if (framerate.HasValue)
+ {
+ builder.Append(",FRAME-RATE=")
+ .Append(framerate.Value.ToString(CultureInfo.InvariantCulture));
+ }
+ }
+
+ private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress)
+ {
+ // Within the local network this will likely do more harm than good.
+ if (_networkManager.IsInLocalNetwork(ipAddress))
+ {
+ return false;
+ }
+
+ if (!enableAdaptiveBitrateStreaming)
+ {
+ return false;
+ }
+
+ if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
+ {
+ // Opening live streams is so slow it's not even worth it
+ return false;
+ }
+
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
+ {
+ return false;
+ }
+
+ if (EncodingHelper.IsCopyCodec(state.OutputAudioCodec))
+ {
+ return false;
+ }
+
+ if (!state.IsOutputVideo)
+ {
+ return false;
+ }
+
+ // Having problems in android
+ return false;
+ // return state.VideoRequest.VideoBitRate.HasValue;
+ }
+
+ private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder, ClaimsPrincipal user)
+ {
+ var selectedIndex = state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Hls ? (int?)null : state.SubtitleStream.Index;
+ const string Format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},AUTOSELECT=YES,URI=\"{3}\",LANGUAGE=\"{4}\"";
+
+ foreach (var stream in subtitles)
+ {
+ var name = stream.DisplayTitle;
+
+ var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
+ var isForced = stream.IsForced;
+
+ var url = string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}&api_key={3}",
+ state.Request.MediaSourceId,
+ stream.Index.ToString(CultureInfo.InvariantCulture),
+ 30.ToString(CultureInfo.InvariantCulture),
+ ClaimHelpers.GetToken(user));
+
+ var line = string.Format(
+ CultureInfo.InvariantCulture,
+ Format,
+ name,
+ isDefault ? "YES" : "NO",
+ isForced ? "YES" : "NO",
+ url,
+ stream.Language ?? "Unknown");
+
+ builder.AppendLine(line);
+ }
+ }
+
+ /// <summary>
+ /// Get the H.26X level of the output video stream.
+ /// </summary>
+ /// <param name="state">StreamState of the current stream.</param>
+ /// <returns>H.26X level of the output video stream.</returns>
+ private int? GetOutputVideoCodecLevel(StreamState state)
+ {
+ string levelString = string.Empty;
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
+ && state.VideoStream != null
+ && state.VideoStream.Level.HasValue)
+ {
+ levelString = state.VideoStream.Level.ToString() ?? string.Empty;
+ }
+ else
+ {
+ if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec) ?? "41";
+ levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
+ }
+
+ if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ levelString = state.GetRequestedLevel("h265") ?? state.GetRequestedLevel("hevc") ?? "120";
+ levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
+ }
+ }
+
+ if (int.TryParse(levelString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLevel))
+ {
+ return parsedLevel;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Get the H.26X profile of the output video stream.
+ /// </summary>
+ /// <param name="state">StreamState of the current stream.</param>
+ /// <param name="codec">Video codec.</param>
+ /// <returns>H.26X profile of the output video stream.</returns>
+ private string GetOutputVideoCodecProfile(StreamState state, string codec)
+ {
+ string profileString = string.Empty;
+ if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
+ && !string.IsNullOrEmpty(state.VideoStream.Profile))
+ {
+ profileString = state.VideoStream.Profile;
+ }
+ else if (!string.IsNullOrEmpty(codec))
+ {
+ profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty;
+ if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ profileString ??= "high";
+ }
+
+ if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ profileString ??= "main";
+ }
+ }
+
+ return profileString;
+ }
+
+ /// <summary>
+ /// Gets a formatted string of the output audio codec, for use in the CODECS field.
+ /// </summary>
+ /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
+ /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
+ /// <param name="state">StreamState of the current stream.</param>
+ /// <returns>Formatted audio codec string.</returns>
+ private string GetPlaylistAudioCodecs(StreamState state)
+ {
+ if (string.Equals(state.ActualOutputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
+ string? profile = state.GetRequestedProfiles("aac").FirstOrDefault();
+ return HlsCodecStringHelpers.GetAACString(profile);
+ }
+
+ if (string.Equals(state.ActualOutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
+ {
+ return HlsCodecStringHelpers.GetMP3String();
+ }
+
+ if (string.Equals(state.ActualOutputAudioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
+ {
+ return HlsCodecStringHelpers.GetAC3String();
+ }
+
+ if (string.Equals(state.ActualOutputAudioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
+ {
+ return HlsCodecStringHelpers.GetEAC3String();
+ }
+
+ if (string.Equals(state.ActualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase))
+ {
+ return HlsCodecStringHelpers.GetFLACString();
+ }
+
+ if (string.Equals(state.ActualOutputAudioCodec, "alac", StringComparison.OrdinalIgnoreCase))
+ {
+ return HlsCodecStringHelpers.GetALACString();
+ }
+
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Gets a formatted string of the output video codec, for use in the CODECS field.
+ /// </summary>
+ /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
+ /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
+ /// <param name="state">StreamState of the current stream.</param>
+ /// <param name="codec">Video codec.</param>
+ /// <param name="level">Video level.</param>
+ /// <returns>Formatted video codec string.</returns>
+ private string GetPlaylistVideoCodecs(StreamState state, string codec, int level)
+ {
+ if (level == 0)
+ {
+ // This is 0 when there's no requested H.26X level in the device profile
+ // and the source is not encoded in H.26X
+ _logger.LogError("Got invalid H.26X level when building CODECS field for HLS master playlist");
+ return string.Empty;
+ }
+
+ if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ string profile = GetOutputVideoCodecProfile(state, "h264");
+ return HlsCodecStringHelpers.GetH264String(profile, level);
+ }
+
+ if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ string profile = GetOutputVideoCodecProfile(state, "hevc");
+ return HlsCodecStringHelpers.GetH265String(profile, level);
+ }
+
+ return string.Empty;
+ }
+
+ private int GetBitrateVariation(int bitrate)
+ {
+ // By default, vary by just 50k
+ var variation = 50000;
+
+ if (bitrate >= 10000000)
+ {
+ variation = 2000000;
+ }
+ else if (bitrate >= 5000000)
+ {
+ variation = 1500000;
+ }
+ else if (bitrate >= 3000000)
+ {
+ variation = 1000000;
+ }
+ else if (bitrate >= 2000000)
+ {
+ variation = 500000;
+ }
+ else if (bitrate >= 1000000)
+ {
+ variation = 300000;
+ }
+ else if (bitrate >= 600000)
+ {
+ variation = 200000;
+ }
+ else if (bitrate >= 400000)
+ {
+ variation = 100000;
+ }
+
+ return variation;
+ }
+
+ private string ReplaceVideoBitrate(string url, int oldValue, int newValue)
+ {
+ return url.Replace(
+ "videobitrate=" + oldValue.ToString(CultureInfo.InvariantCulture),
+ "videobitrate=" + newValue.ToString(CultureInfo.InvariantCulture),
+ StringComparison.OrdinalIgnoreCase);
+ }
+
+ private string ReplaceProfile(string url, string codec, string oldValue, string newValue)
+ {
+ string profileStr = codec + "-profile=";
+ return url.Replace(
+ profileStr + oldValue,
+ profileStr + newValue,
+ StringComparison.OrdinalIgnoreCase);
+ }
+
+ private string ReplacePlaylistCodecsField(StringBuilder playlist, StringBuilder oldValue, StringBuilder newValue)
+ {
+ var oldPlaylist = playlist.ToString();
+ return oldPlaylist.Replace(
+ oldValue.ToString(),
+ newValue.ToString(),
+ StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
new file mode 100644
index 000000000..6385b62c9
--- /dev/null
+++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
@@ -0,0 +1,140 @@
+using System;
+using System.IO;
+using System.Net.Http;
+using System.Net.Mime;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.PlaybackDtos;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Controller.MediaEncoding;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// The stream response helpers.
+ /// </summary>
+ public static class FileStreamResponseHelpers
+ {
+ /// <summary>
+ /// Returns a static file from a remote source.
+ /// </summary>
+ /// <param name="state">The current <see cref="StreamState"/>.</param>
+ /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
+ /// <param name="httpClient">The <see cref="HttpClient"/> making the remote request.</param>
+ /// <param name="httpContext">The current http context.</param>
+ /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
+ /// <returns>A <see cref="Task{ActionResult}"/> containing the API response.</returns>
+ public static async Task<ActionResult> GetStaticRemoteStreamResult(
+ StreamState state,
+ bool isHeadRequest,
+ HttpClient httpClient,
+ HttpContext httpContext,
+ CancellationToken cancellationToken = default)
+ {
+ if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent))
+ {
+ httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, useragent);
+ }
+
+ // Can't dispose the response as it's required up the call chain.
+ var response = await httpClient.GetAsync(new Uri(state.MediaPath), cancellationToken).ConfigureAwait(false);
+ var contentType = response.Content.Headers.ContentType?.ToString() ?? MediaTypeNames.Text.Plain;
+
+ httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
+
+ if (isHeadRequest)
+ {
+ httpContext.Response.Headers[HeaderNames.ContentType] = contentType;
+ return new OkResult();
+ }
+
+ return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), contentType);
+ }
+
+ /// <summary>
+ /// Returns a static file from the server.
+ /// </summary>
+ /// <param name="path">The path to the file.</param>
+ /// <param name="contentType">The content type of the file.</param>
+ /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
+ /// <param name="httpContext">The current http context.</param>
+ /// <returns>An <see cref="ActionResult"/> the file.</returns>
+ public static ActionResult GetStaticFileResult(
+ string path,
+ string contentType,
+ bool isHeadRequest,
+ HttpContext httpContext)
+ {
+ httpContext.Response.ContentType = contentType;
+
+ // if the request is a head request, return an OkResult (200) with the same headers as it would with a GET request
+ if (isHeadRequest)
+ {
+ return new OkResult();
+ }
+
+ return new PhysicalFileResult(path, contentType) { EnableRangeProcessing = true };
+ }
+
+ /// <summary>
+ /// Returns a transcoded file from the server.
+ /// </summary>
+ /// <param name="state">The current <see cref="StreamState"/>.</param>
+ /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
+ /// <param name="httpContext">The current http context.</param>
+ /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
+ /// <param name="ffmpegCommandLineArguments">The command line arguments to start ffmpeg.</param>
+ /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
+ /// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param>
+ /// <returns>A <see cref="Task{ActionResult}"/> containing the transcoded file.</returns>
+ public static async Task<ActionResult> GetTranscodedFile(
+ StreamState state,
+ bool isHeadRequest,
+ HttpContext httpContext,
+ TranscodingJobHelper transcodingJobHelper,
+ string ffmpegCommandLineArguments,
+ TranscodingJobType transcodingJobType,
+ CancellationTokenSource cancellationTokenSource)
+ {
+ // Use the command line args with a dummy playlist path
+ var outputPath = state.OutputFilePath;
+
+ httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
+
+ var contentType = state.GetMimeType(outputPath);
+
+ // Headers only
+ if (isHeadRequest)
+ {
+ httpContext.Response.Headers[HeaderNames.ContentType] = contentType;
+ return new OkResult();
+ }
+
+ var transcodingLock = transcodingJobHelper.GetTranscodingLock(outputPath);
+ await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
+ try
+ {
+ TranscodingJobDto? job;
+ if (!File.Exists(outputPath))
+ {
+ job = await transcodingJobHelper.StartFfMpeg(state, outputPath, ffmpegCommandLineArguments, httpContext.Request, transcodingJobType, cancellationTokenSource).ConfigureAwait(false);
+ }
+ else
+ {
+ job = transcodingJobHelper.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
+ state.Dispose();
+ }
+
+ var stream = new ProgressiveFileStream(outputPath, job, transcodingJobHelper);
+ return new FileStreamResult(stream, contentType);
+ }
+ finally
+ {
+ transcodingLock.Release();
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs
new file mode 100644
index 000000000..a5369c441
--- /dev/null
+++ b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs
@@ -0,0 +1,169 @@
+using System;
+using System.Globalization;
+using System.Text;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Hls Codec string helpers.
+ /// </summary>
+ public static class HlsCodecStringHelpers
+ {
+ /// <summary>
+ /// Codec name for MP3.
+ /// </summary>
+ public const string MP3 = "mp4a.40.34";
+
+ /// <summary>
+ /// Codec name for AC-3.
+ /// </summary>
+ public const string AC3 = "mp4a.a5";
+
+ /// <summary>
+ /// Codec name for E-AC-3.
+ /// </summary>
+ public const string EAC3 = "mp4a.a6";
+
+ /// <summary>
+ /// Codec name for FLAC.
+ /// </summary>
+ public const string FLAC = "fLaC";
+
+ /// <summary>
+ /// Codec name for ALAC.
+ /// </summary>
+ public const string ALAC = "alac";
+
+ /// <summary>
+ /// Gets a MP3 codec string.
+ /// </summary>
+ /// <returns>MP3 codec string.</returns>
+ public static string GetMP3String()
+ {
+ return MP3;
+ }
+
+ /// <summary>
+ /// Gets an AAC codec string.
+ /// </summary>
+ /// <param name="profile">AAC profile.</param>
+ /// <returns>AAC codec string.</returns>
+ public static string GetAACString(string? profile)
+ {
+ StringBuilder result = new StringBuilder("mp4a", 9);
+
+ if (string.Equals(profile, "HE", StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(".40.5");
+ }
+ else
+ {
+ // Default to LC if profile is invalid
+ result.Append(".40.2");
+ }
+
+ return result.ToString();
+ }
+
+ /// <summary>
+ /// Gets an AC-3 codec string.
+ /// </summary>
+ /// <returns>AC-3 codec string.</returns>
+ public static string GetAC3String()
+ {
+ return AC3;
+ }
+
+ /// <summary>
+ /// Gets an E-AC-3 codec string.
+ /// </summary>
+ /// <returns>E-AC-3 codec string.</returns>
+ public static string GetEAC3String()
+ {
+ return EAC3;
+ }
+
+ /// <summary>
+ /// Gets an FLAC codec string.
+ /// </summary>
+ /// <returns>FLAC codec string.</returns>
+ public static string GetFLACString()
+ {
+ return FLAC;
+ }
+
+ /// <summary>
+ /// Gets an ALAC codec string.
+ /// </summary>
+ /// <returns>ALAC codec string.</returns>
+ public static string GetALACString()
+ {
+ return ALAC;
+ }
+
+ /// <summary>
+ /// Gets a H.264 codec string.
+ /// </summary>
+ /// <param name="profile">H.264 profile.</param>
+ /// <param name="level">H.264 level.</param>
+ /// <returns>H.264 string.</returns>
+ public static string GetH264String(string? profile, int level)
+ {
+ StringBuilder result = new StringBuilder("avc1", 11);
+
+ if (string.Equals(profile, "high", StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(".6400");
+ }
+ else if (string.Equals(profile, "main", StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(".4D40");
+ }
+ else if (string.Equals(profile, "baseline", StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(".42E0");
+ }
+ else
+ {
+ // Default to constrained baseline if profile is invalid
+ result.Append(".4240");
+ }
+
+ string levelHex = level.ToString("X2", CultureInfo.InvariantCulture);
+ result.Append(levelHex);
+
+ return result.ToString();
+ }
+
+ /// <summary>
+ /// Gets a H.265 codec string.
+ /// </summary>
+ /// <param name="profile">H.265 profile.</param>
+ /// <param name="level">H.265 level.</param>
+ /// <returns>H.265 string.</returns>
+ public static string GetH265String(string? profile, int level)
+ {
+ // The h265 syntax is a bit of a mystery at the time this comment was written.
+ // This is what I've found through various sources:
+ // FORMAT: [codecTag].[profile].[constraint?].L[level * 30].[UNKNOWN]
+ StringBuilder result = new StringBuilder("hvc1", 16);
+
+ if (string.Equals(profile, "main10", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(profile, "main 10", StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(".2.4");
+ }
+ else
+ {
+ // Default to main if profile is invalid
+ result.Append(".1.4");
+ }
+
+ result.Append(".L")
+ .Append(level)
+ .Append(".B0");
+
+ return result.ToString();
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs
new file mode 100644
index 000000000..456762147
--- /dev/null
+++ b/Jellyfin.Api/Helpers/HlsHelpers.cs
@@ -0,0 +1,138 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StreamingDtos;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// The hls helpers.
+ /// </summary>
+ public static class HlsHelpers
+ {
+ /// <summary>
+ /// Waits for a minimum number of segments to be available.
+ /// </summary>
+ /// <param name="playlist">The playlist string.</param>
+ /// <param name="segmentCount">The segment count.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
+ /// <returns>A <see cref="Task"/> indicating the waiting process.</returns>
+ public static async Task WaitForMinimumSegmentCount(string playlist, int? segmentCount, ILogger logger, CancellationToken cancellationToken)
+ {
+ logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist);
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
+ var fileStream = new FileStream(
+ playlist,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.ReadWrite,
+ IODefaults.FileStreamBufferSize,
+ FileOptions.Asynchronous | FileOptions.SequentialScan);
+ await using (fileStream.ConfigureAwait(false))
+ {
+ using var reader = new StreamReader(fileStream);
+ var count = 0;
+
+ while (!reader.EndOfStream)
+ {
+ var line = await reader.ReadLineAsync().ConfigureAwait(false);
+ if (line == null)
+ {
+ // Nothing currently in buffer.
+ break;
+ }
+
+ if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ count++;
+ if (count >= segmentCount)
+ {
+ logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
+ return;
+ }
+ }
+ }
+ }
+
+ await Task.Delay(100, cancellationToken).ConfigureAwait(false);
+ }
+ catch (IOException)
+ {
+ // May get an error if the file is locked
+ }
+
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ /// <summary>
+ /// Gets the #EXT-X-MAP string.
+ /// </summary>
+ /// <param name="outputPath">The output path of the file.</param>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <param name="isOsDepends">Get a normal string or depends on OS.</param>
+ /// <returns>The string text of #EXT-X-MAP.</returns>
+ public static string GetFmp4InitFileName(string outputPath, StreamState state, bool isOsDepends)
+ {
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
+ var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
+ var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
+
+ // on Linux/Unix
+ // #EXT-X-MAP:URI="prefix-1.mp4"
+ var fmp4InitFileName = outputFileNameWithoutExtension + "-1" + outputExtension;
+ if (!isOsDepends)
+ {
+ return fmp4InitFileName;
+ }
+
+ if (OperatingSystem.IsWindows())
+ {
+ // on Windows
+ // #EXT-X-MAP:URI="X:\transcodes\prefix-1.mp4"
+ fmp4InitFileName = outputPrefix + "-1" + outputExtension;
+ }
+
+ return fmp4InitFileName;
+ }
+
+ /// <summary>
+ /// Gets the hls playlist text.
+ /// </summary>
+ /// <param name="path">The path to the playlist file.</param>
+ /// <param name="state">The <see cref="StreamState"/>.</param>
+ /// <returns>The playlist text as a string.</returns>
+ public static string GetLivePlaylistText(string path, StreamState state)
+ {
+ var text = File.ReadAllText(path);
+
+ var segmentFormat = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.');
+ if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase))
+ {
+ var fmp4InitFileName = GetFmp4InitFileName(path, state, true);
+ var baseUrlParam = string.Format(
+ CultureInfo.InvariantCulture,
+ "hls/{0}/",
+ Path.GetFileNameWithoutExtension(path));
+ var newFmp4InitFileName = baseUrlParam + GetFmp4InitFileName(path, state, false);
+
+ // Replace fMP4 init file URI.
+ text = text.Replace(fmp4InitFileName, newFmp4InitFileName, StringComparison.InvariantCulture);
+ }
+
+ return text;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
new file mode 100644
index 000000000..3b8dc7e31
--- /dev/null
+++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
@@ -0,0 +1,583 @@
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Media info helper.
+ /// </summary>
+ public class MediaInfoHelper
+ {
+ private readonly IUserManager _userManager;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly ILogger<MediaInfoHelper> _logger;
+ private readonly INetworkManager _networkManager;
+ private readonly IDeviceManager _deviceManager;
+ private readonly IAuthorizationContext _authContext;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MediaInfoHelper"/> class.
+ /// </summary>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> 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="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{MediaInfoHelper}"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ public MediaInfoHelper(
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IMediaSourceManager mediaSourceManager,
+ IMediaEncoder mediaEncoder,
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MediaInfoHelper> logger,
+ INetworkManager networkManager,
+ IDeviceManager deviceManager,
+ IAuthorizationContext authContext)
+ {
+ _userManager = userManager;
+ _libraryManager = libraryManager;
+ _mediaSourceManager = mediaSourceManager;
+ _mediaEncoder = mediaEncoder;
+ _serverConfigurationManager = serverConfigurationManager;
+ _logger = logger;
+ _networkManager = networkManager;
+ _deviceManager = deviceManager;
+ _authContext = authContext;
+ }
+
+ /// <summary>
+ /// Get playback info.
+ /// </summary>
+ /// <param name="id">Item id.</param>
+ /// <param name="userId">User Id.</param>
+ /// <param name="mediaSourceId">Media source id.</param>
+ /// <param name="liveStreamId">Live stream id.</param>
+ /// <returns>A <see cref="Task"/> containing the <see cref="PlaybackInfoResponse"/>.</returns>
+ public async Task<PlaybackInfoResponse> GetPlaybackInfo(
+ Guid id,
+ Guid? userId,
+ string? mediaSourceId = null,
+ string? liveStreamId = null)
+ {
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var item = _libraryManager.GetItemById(id);
+ var result = new PlaybackInfoResponse();
+
+ MediaSourceInfo[] mediaSources;
+ if (string.IsNullOrWhiteSpace(liveStreamId))
+ {
+ // TODO (moved from MediaBrowser.Api) handle supportedLiveMediaTypes?
+ var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, true, CancellationToken.None).ConfigureAwait(false);
+
+ if (string.IsNullOrWhiteSpace(mediaSourceId))
+ {
+ mediaSources = mediaSourcesList.ToArray();
+ }
+ else
+ {
+ mediaSources = mediaSourcesList
+ .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+ }
+ }
+ else
+ {
+ var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
+
+ mediaSources = new[] { mediaSource };
+ }
+
+ if (mediaSources.Length == 0)
+ {
+ result.MediaSources = Array.Empty<MediaSourceInfo>();
+
+ result.ErrorCode ??= PlaybackErrorCode.NoCompatibleStream;
+ }
+ else
+ {
+ // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it
+ // Should we move this directly into MediaSourceManager?
+ var mediaSourcesClone = JsonSerializer.Deserialize<MediaSourceInfo[]>(JsonSerializer.SerializeToUtf8Bytes(mediaSources));
+ if (mediaSourcesClone != null)
+ {
+ result.MediaSources = mediaSourcesClone;
+ }
+
+ result.PlaySessionId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// SetDeviceSpecificData.
+ /// </summary>
+ /// <param name="item">Item to set data for.</param>
+ /// <param name="mediaSource">Media source info.</param>
+ /// <param name="profile">Device profile.</param>
+ /// <param name="auth">Authorization info.</param>
+ /// <param name="maxBitrate">Max bitrate.</param>
+ /// <param name="startTimeTicks">Start time ticks.</param>
+ /// <param name="mediaSourceId">Media source id.</param>
+ /// <param name="audioStreamIndex">Audio stream index.</param>
+ /// <param name="subtitleStreamIndex">Subtitle stream index.</param>
+ /// <param name="maxAudioChannels">Max audio channels.</param>
+ /// <param name="playSessionId">Play session id.</param>
+ /// <param name="userId">User id.</param>
+ /// <param name="enableDirectPlay">Enable direct play.</param>
+ /// <param name="enableDirectStream">Enable direct stream.</param>
+ /// <param name="enableTranscoding">Enable transcoding.</param>
+ /// <param name="allowVideoStreamCopy">Allow video stream copy.</param>
+ /// <param name="allowAudioStreamCopy">Allow audio stream copy.</param>
+ /// <param name="ipAddress">Requesting IP address.</param>
+ public void SetDeviceSpecificData(
+ BaseItem item,
+ MediaSourceInfo mediaSource,
+ DeviceProfile profile,
+ AuthorizationInfo auth,
+ int? maxBitrate,
+ long startTimeTicks,
+ string mediaSourceId,
+ int? audioStreamIndex,
+ int? subtitleStreamIndex,
+ int? maxAudioChannels,
+ string playSessionId,
+ Guid userId,
+ bool enableDirectPlay,
+ bool enableDirectStream,
+ bool enableTranscoding,
+ bool allowVideoStreamCopy,
+ bool allowAudioStreamCopy,
+ IPAddress ipAddress)
+ {
+ var streamBuilder = new StreamBuilder(_mediaEncoder, _logger);
+
+ var options = new VideoOptions
+ {
+ MediaSources = new[] { mediaSource },
+ Context = EncodingContext.Streaming,
+ DeviceId = auth.DeviceId,
+ ItemId = item.Id,
+ Profile = profile,
+ MaxAudioChannels = maxAudioChannels
+ };
+
+ if (string.Equals(mediaSourceId, mediaSource.Id, StringComparison.OrdinalIgnoreCase))
+ {
+ options.MediaSourceId = mediaSourceId;
+ options.AudioStreamIndex = audioStreamIndex;
+ options.SubtitleStreamIndex = subtitleStreamIndex;
+ }
+
+ var user = _userManager.GetUserById(userId);
+
+ if (!enableDirectPlay)
+ {
+ mediaSource.SupportsDirectPlay = false;
+ }
+
+ if (!enableDirectStream)
+ {
+ mediaSource.SupportsDirectStream = false;
+ }
+
+ if (!enableTranscoding)
+ {
+ mediaSource.SupportsTranscoding = false;
+ }
+
+ if (item is Audio)
+ {
+ _logger.LogInformation(
+ "User policy for {0}. EnableAudioPlaybackTranscoding: {1}",
+ user.Username,
+ user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding));
+ }
+ else
+ {
+ _logger.LogInformation(
+ "User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}",
+ user.Username,
+ user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
+ user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
+ user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding));
+ }
+
+ // Beginning of Playback Determination: Attempt DirectPlay first
+ if (mediaSource.SupportsDirectPlay)
+ {
+ if (mediaSource.IsRemote && user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding))
+ {
+ mediaSource.SupportsDirectPlay = false;
+ }
+ else
+ {
+ var supportsDirectStream = mediaSource.SupportsDirectStream;
+
+ // Dummy this up to fool StreamBuilder
+ mediaSource.SupportsDirectStream = true;
+ options.MaxBitrate = maxBitrate;
+
+ if (item is Audio)
+ {
+ if (!user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
+ {
+ options.ForceDirectPlay = true;
+ }
+ }
+ else if (item is Video)
+ {
+ if (!user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding)
+ && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding)
+ && !user.HasPermission(PermissionKind.EnablePlaybackRemuxing))
+ {
+ options.ForceDirectPlay = true;
+ }
+ }
+
+ // The MediaSource supports direct stream, now test to see if the client supports it
+ var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)
+ ? streamBuilder.BuildAudioItem(options)
+ : streamBuilder.BuildVideoItem(options);
+
+ if (streamInfo == null || !streamInfo.IsDirectStream)
+ {
+ mediaSource.SupportsDirectPlay = false;
+ }
+
+ // Set this back to what it was
+ mediaSource.SupportsDirectStream = supportsDirectStream;
+
+ if (streamInfo != null)
+ {
+ SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
+ mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex;
+ }
+ }
+ }
+
+ if (mediaSource.SupportsDirectStream)
+ {
+ if (mediaSource.IsRemote && user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding))
+ {
+ mediaSource.SupportsDirectStream = false;
+ }
+ else
+ {
+ options.MaxBitrate = GetMaxBitrate(maxBitrate, user, ipAddress);
+
+ if (item is Audio)
+ {
+ if (!user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
+ {
+ options.ForceDirectStream = true;
+ }
+ }
+ else if (item is Video)
+ {
+ if (!user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding)
+ && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding)
+ && user.HasPermission(PermissionKind.EnablePlaybackRemuxing))
+ {
+ options.ForceDirectStream = true;
+ }
+ }
+
+ // The MediaSource supports direct stream, now test to see if the client supports it
+ var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)
+ ? streamBuilder.BuildAudioItem(options)
+ : streamBuilder.BuildVideoItem(options);
+
+ if (streamInfo == null || !streamInfo.IsDirectStream)
+ {
+ mediaSource.SupportsDirectStream = false;
+ }
+
+ if (streamInfo != null)
+ {
+ SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
+ mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex;
+ }
+ }
+ }
+
+ if (mediaSource.SupportsTranscoding)
+ {
+ options.MaxBitrate = GetMaxBitrate(maxBitrate, user, ipAddress);
+
+ // The MediaSource supports direct stream, now test to see if the client supports it
+ var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)
+ ? streamBuilder.BuildAudioItem(options)
+ : streamBuilder.BuildVideoItem(options);
+
+ if (mediaSource.IsRemote && user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding))
+ {
+ if (streamInfo != null)
+ {
+ streamInfo.PlaySessionId = playSessionId;
+ streamInfo.StartPositionTicks = startTimeTicks;
+ mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-');
+ mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false";
+ mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false";
+ mediaSource.TranscodingContainer = streamInfo.Container;
+ mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
+
+ // Do this after the above so that StartPositionTicks is set
+ SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
+ mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex;
+ }
+ }
+ else
+ {
+ if (streamInfo != null)
+ {
+ streamInfo.PlaySessionId = playSessionId;
+
+ if (streamInfo.PlayMethod == PlayMethod.Transcode)
+ {
+ streamInfo.StartPositionTicks = startTimeTicks;
+ mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-');
+
+ if (!allowVideoStreamCopy)
+ {
+ mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false";
+ }
+
+ if (!allowAudioStreamCopy)
+ {
+ mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false";
+ }
+
+ mediaSource.TranscodingContainer = streamInfo.Container;
+ mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
+ }
+
+ if (!allowAudioStreamCopy)
+ {
+ mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false";
+ }
+
+ mediaSource.TranscodingContainer = streamInfo.Container;
+ mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
+
+ // Do this after the above so that StartPositionTicks is set
+ SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
+ mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex;
+ }
+ }
+ }
+
+ foreach (var attachment in mediaSource.MediaAttachments)
+ {
+ attachment.DeliveryUrl = string.Format(
+ CultureInfo.InvariantCulture,
+ "/Videos/{0}/{1}/Attachments/{2}",
+ item.Id,
+ mediaSource.Id,
+ attachment.Index);
+ }
+ }
+
+ /// <summary>
+ /// Sort media source.
+ /// </summary>
+ /// <param name="result">Playback info response.</param>
+ /// <param name="maxBitrate">Max bitrate.</param>
+ public void SortMediaSources(PlaybackInfoResponse result, long? maxBitrate)
+ {
+ var originalList = result.MediaSources.ToList();
+
+ result.MediaSources = result.MediaSources.OrderBy(i =>
+ {
+ // Nothing beats direct playing a file
+ if (i.SupportsDirectPlay && i.Protocol == MediaProtocol.File)
+ {
+ return 0;
+ }
+
+ return 1;
+ })
+ .ThenBy(i =>
+ {
+ // Let's assume direct streaming a file is just as desirable as direct playing a remote url
+ if (i.SupportsDirectPlay || i.SupportsDirectStream)
+ {
+ return 0;
+ }
+
+ return 1;
+ })
+ .ThenBy(i =>
+ {
+ return i.Protocol switch
+ {
+ MediaProtocol.File => 0,
+ _ => 1,
+ };
+ })
+ .ThenBy(i =>
+ {
+ if (maxBitrate.HasValue && i.Bitrate.HasValue)
+ {
+ return i.Bitrate.Value <= maxBitrate.Value ? 0 : 2;
+ }
+
+ return 1;
+ })
+ .ThenBy(originalList.IndexOf)
+ .ToArray();
+ }
+
+ /// <summary>
+ /// Open media source.
+ /// </summary>
+ /// <param name="httpRequest">Http Request.</param>
+ /// <param name="request">Live stream request.</param>
+ /// <returns>A <see cref="Task"/> containing the <see cref="LiveStreamResponse"/>.</returns>
+ public async Task<LiveStreamResponse> OpenMediaSource(HttpRequest httpRequest, LiveStreamRequest request)
+ {
+ var authInfo = await _authContext.GetAuthorizationInfo(httpRequest).ConfigureAwait(false);
+
+ var result = await _mediaSourceManager.OpenLiveStream(request, CancellationToken.None).ConfigureAwait(false);
+
+ var profile = request.DeviceProfile;
+ if (profile == null)
+ {
+ var clientCapabilities = _deviceManager.GetCapabilities(authInfo.DeviceId);
+ if (clientCapabilities != null)
+ {
+ profile = clientCapabilities.DeviceProfile;
+ }
+ }
+
+ if (profile != null)
+ {
+ var item = _libraryManager.GetItemById(request.ItemId);
+
+ SetDeviceSpecificData(
+ item,
+ result.MediaSource,
+ profile,
+ authInfo,
+ request.MaxStreamingBitrate,
+ request.StartTimeTicks ?? 0,
+ result.MediaSource.Id,
+ request.AudioStreamIndex,
+ request.SubtitleStreamIndex,
+ request.MaxAudioChannels,
+ request.PlaySessionId,
+ request.UserId,
+ request.EnableDirectPlay,
+ request.EnableDirectStream,
+ true,
+ true,
+ true,
+ httpRequest.HttpContext.GetNormalizedRemoteIp());
+ }
+ else
+ {
+ if (!string.IsNullOrWhiteSpace(result.MediaSource.TranscodingUrl))
+ {
+ result.MediaSource.TranscodingUrl += "&LiveStreamId=" + result.MediaSource.LiveStreamId;
+ }
+ }
+
+ // here was a check if (result.MediaSource != null) but Rider said it will never be null
+ NormalizeMediaSourceContainer(result.MediaSource, profile!, DlnaProfileType.Video);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Normalize media source container.
+ /// </summary>
+ /// <param name="mediaSource">Media source.</param>
+ /// <param name="profile">Device profile.</param>
+ /// <param name="type">Dlna profile type.</param>
+ public void NormalizeMediaSourceContainer(MediaSourceInfo mediaSource, DeviceProfile profile, DlnaProfileType type)
+ {
+ mediaSource.Container = StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(mediaSource.Container, profile, type);
+ }
+
+ private void SetDeviceSpecificSubtitleInfo(StreamInfo info, MediaSourceInfo mediaSource, string accessToken)
+ {
+ var profiles = info.GetSubtitleProfiles(_mediaEncoder, false, "-", accessToken);
+ mediaSource.DefaultSubtitleStreamIndex = info.SubtitleStreamIndex;
+
+ mediaSource.TranscodeReasons = info.TranscodeReasons;
+
+ foreach (var profile in profiles)
+ {
+ foreach (var stream in mediaSource.MediaStreams)
+ {
+ if (stream.Type == MediaStreamType.Subtitle && stream.Index == profile.Index)
+ {
+ stream.DeliveryMethod = profile.DeliveryMethod;
+
+ if (profile.DeliveryMethod == SubtitleDeliveryMethod.External)
+ {
+ stream.DeliveryUrl = profile.Url.TrimStart('-');
+ stream.IsExternalUrl = profile.IsExternalUrl;
+ }
+ }
+ }
+ }
+ }
+
+ private int? GetMaxBitrate(int? clientMaxBitrate, User user, IPAddress ipAddress)
+ {
+ var maxBitrate = clientMaxBitrate;
+ var remoteClientMaxBitrate = user.RemoteClientBitrateLimit ?? 0;
+
+ if (remoteClientMaxBitrate <= 0)
+ {
+ remoteClientMaxBitrate = _serverConfigurationManager.Configuration.RemoteClientBitrateLimit;
+ }
+
+ if (remoteClientMaxBitrate > 0)
+ {
+ var isInLocalNetwork = _networkManager.IsInLocalNetwork(ipAddress);
+
+ _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork);
+ if (!isInLocalNetwork)
+ {
+ maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
+ }
+ }
+
+ return maxBitrate;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs
new file mode 100644
index 000000000..61e18220a
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs
@@ -0,0 +1,163 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.PlaybackDtos;
+using MediaBrowser.Model.IO;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// A progressive file stream for transferring transcoded files as they are written to.
+ /// </summary>
+ public class ProgressiveFileStream : Stream
+ {
+ private readonly Stream _stream;
+ private readonly TranscodingJobDto? _job;
+ private readonly TranscodingJobHelper? _transcodingJobHelper;
+ private readonly int _timeoutMs;
+ private int _bytesWritten;
+ private bool _disposed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
+ /// </summary>
+ /// <param name="filePath">The path to the transcoded file.</param>
+ /// <param name="job">The transcoding job information.</param>
+ /// <param name="transcodingJobHelper">The transcoding job helper.</param>
+ /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
+ public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper, int timeoutMs = 30000)
+ {
+ _job = job;
+ _transcodingJobHelper = transcodingJobHelper;
+ _timeoutMs = timeoutMs;
+
+ _stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
+ /// </summary>
+ /// <param name="stream">The stream to progressively copy.</param>
+ /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
+ public ProgressiveFileStream(Stream stream, int timeoutMs = 30000)
+ {
+ _job = null;
+ _transcodingJobHelper = null;
+ _timeoutMs = timeoutMs;
+ _stream = stream;
+ }
+
+ /// <inheritdoc />
+ public override bool CanRead => _stream.CanRead;
+
+ /// <inheritdoc />
+ public override bool CanSeek => false;
+
+ /// <inheritdoc />
+ public override bool CanWrite => false;
+
+ /// <inheritdoc />
+ public override long Length => throw new NotSupportedException();
+
+ /// <inheritdoc />
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ /// <inheritdoc />
+ public override void Flush()
+ {
+ _stream.Flush();
+ }
+
+ /// <inheritdoc />
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ return _stream.Read(buffer, offset, count);
+ }
+
+ /// <inheritdoc />
+ public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ int totalBytesRead = 0;
+ int remainingBytesToRead = count;
+ var stopwatch = Stopwatch.StartNew();
+
+ int newOffset = offset;
+ while (remainingBytesToRead > 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ int bytesRead = await _stream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
+
+ remainingBytesToRead -= bytesRead;
+ newOffset += bytesRead;
+
+ if (bytesRead > 0)
+ {
+ _bytesWritten += bytesRead;
+ totalBytesRead += bytesRead;
+
+ if (_job != null)
+ {
+ _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
+ }
+ }
+ else
+ {
+ // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely
+ if (_job?.HasExited ?? stopwatch.ElapsedMilliseconds > _timeoutMs)
+ {
+ break;
+ }
+
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ return totalBytesRead;
+ }
+
+ /// <inheritdoc />
+ public override long Seek(long offset, SeekOrigin origin)
+ => throw new NotSupportedException();
+
+ /// <inheritdoc />
+ public override void SetLength(long value)
+ => throw new NotSupportedException();
+
+ /// <inheritdoc />
+ public override void Write(byte[] buffer, int offset, int count)
+ => throw new NotSupportedException();
+
+ /// <inheritdoc />
+ protected override void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ try
+ {
+ if (disposing)
+ {
+ _stream.Dispose();
+
+ if (_job != null)
+ {
+ _transcodingJobHelper?.OnTranscodeEndRequest(_job);
+ }
+ }
+ }
+ finally
+ {
+ _disposed = true;
+ base.Dispose(disposing);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs
new file mode 100644
index 000000000..0efd3443b
--- /dev/null
+++ b/Jellyfin.Api/Helpers/RequestHelpers.cs
@@ -0,0 +1,157 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Request Extensions.
+ /// </summary>
+ public static class RequestHelpers
+ {
+ /// <summary>
+ /// Get Order By.
+ /// </summary>
+ /// <param name="sortBy">Sort By. Comma delimited string.</param>
+ /// <param name="requestedSortOrder">Sort Order. Comma delimited string.</param>
+ /// <returns>Order By.</returns>
+ public static (string, SortOrder)[] GetOrderBy(IReadOnlyList<string> sortBy, IReadOnlyList<SortOrder> requestedSortOrder)
+ {
+ if (sortBy.Count == 0)
+ {
+ return Array.Empty<ValueTuple<string, SortOrder>>();
+ }
+
+ var result = new (string, SortOrder)[sortBy.Count];
+ var i = 0;
+ // Add elements which have a SortOrder specified
+ for (; i < requestedSortOrder.Count; i++)
+ {
+ result[i] = (sortBy[i], requestedSortOrder[i]);
+ }
+
+ // Add remaining elements with the first specified SortOrder
+ // or the default one if no SortOrders are specified
+ var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending;
+ for (; i < sortBy.Count; i++)
+ {
+ result[i] = (sortBy[i], order);
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Checks if the user can update an entry.
+ /// </summary>
+ /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="requestContext">The <see cref="HttpRequest"/>.</param>
+ /// <param name="userId">The user id.</param>
+ /// <param name="restrictUserPreferences">Whether to restrict the user preferences.</param>
+ /// <returns>A <see cref="bool"/> whether the user can update the entry.</returns>
+ internal static async Task<bool> AssertCanUpdateUser(IAuthorizationContext authContext, HttpRequest requestContext, Guid userId, bool restrictUserPreferences)
+ {
+ var auth = await authContext.GetAuthorizationInfo(requestContext).ConfigureAwait(false);
+
+ var authenticatedUser = auth.User;
+
+ // If they're going to update the record of another user, they must be an administrator
+ if ((!userId.Equals(auth.UserId) && !authenticatedUser.HasPermission(PermissionKind.IsAdministrator))
+ || (restrictUserPreferences && !authenticatedUser.EnableUserPreferenceAccess))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ internal static async Task<SessionInfo> GetSession(ISessionManager sessionManager, IAuthorizationContext authContext, HttpRequest request)
+ {
+ var authorization = await authContext.GetAuthorizationInfo(request).ConfigureAwait(false);
+ var user = authorization.User;
+ var session = await sessionManager.LogSessionActivity(
+ authorization.Client,
+ authorization.Version,
+ authorization.DeviceId,
+ authorization.Device,
+ request.HttpContext.GetNormalizedRemoteIp().ToString(),
+ user).ConfigureAwait(false);
+
+ if (session == null)
+ {
+ throw new ArgumentException("Session not found.");
+ }
+
+ return session;
+ }
+
+ internal static async Task<string> GetSessionId(ISessionManager sessionManager, IAuthorizationContext authContext, HttpRequest request)
+ {
+ var session = await GetSession(sessionManager, authContext, request).ConfigureAwait(false);
+
+ return session.Id;
+ }
+
+ internal static QueryResult<BaseItemDto> CreateQueryResult(
+ QueryResult<(BaseItem, ItemCounts)> result,
+ DtoOptions dtoOptions,
+ IDtoService dtoService,
+ bool includeItemTypes,
+ User? user)
+ {
+ var dtos = result.Items.Select(i =>
+ {
+ var (baseItem, counts) = i;
+ var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
+
+ if (includeItemTypes)
+ {
+ dto.ChildCount = counts.ItemCount;
+ dto.ProgramCount = counts.ProgramCount;
+ dto.SeriesCount = counts.SeriesCount;
+ dto.EpisodeCount = counts.EpisodeCount;
+ dto.MovieCount = counts.MovieCount;
+ dto.TrailerCount = counts.TrailerCount;
+ dto.AlbumCount = counts.AlbumCount;
+ dto.SongCount = counts.SongCount;
+ dto.ArtistCount = counts.ArtistCount;
+ }
+
+ return dto;
+ });
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = dtos.ToArray(),
+ TotalRecordCount = result.TotalRecordCount
+ };
+ }
+
+ internal static string[] GetItemTypeStrings(IReadOnlyList<BaseItemKind> itemKinds)
+ {
+ if (itemKinds.Count == 0)
+ {
+ return Array.Empty<string>();
+ }
+
+ var itemTypes = new string[itemKinds.Count];
+ for (var i = 0; i < itemKinds.Count; i++)
+ {
+ itemTypes[i] = itemKinds[i].ToString();
+ }
+
+ return itemTypes;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs
new file mode 100644
index 000000000..4fc791665
--- /dev/null
+++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs
@@ -0,0 +1,774 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StreamingDtos;
+using Jellyfin.Extensions;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Primitives;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// The streaming helpers.
+ /// </summary>
+ public static class StreamingHelpers
+ {
+ /// <summary>
+ /// Gets the current streaming state.
+ /// </summary>
+ /// <param name="streamingRequest">The <see cref="StreamingRequestDto"/>.</param>
+ /// <param name="httpRequest">The <see cref="HttpRequest"/>.</param>
+ /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
+ /// <param name="transcodingJobHelper">Initialized <see cref="TranscodingJobHelper"/>.</param>
+ /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
+ /// <returns>A <see cref="Task"/> containing the current <see cref="StreamState"/>.</returns>
+ public static async Task<StreamState> GetStreamingState(
+ StreamingRequestDto streamingRequest,
+ HttpRequest httpRequest,
+ IAuthorizationContext authorizationContext,
+ IMediaSourceManager mediaSourceManager,
+ IUserManager userManager,
+ ILibraryManager libraryManager,
+ IServerConfigurationManager serverConfigurationManager,
+ IMediaEncoder mediaEncoder,
+ EncodingHelper encodingHelper,
+ IDlnaManager dlnaManager,
+ IDeviceManager deviceManager,
+ TranscodingJobHelper transcodingJobHelper,
+ TranscodingJobType transcodingJobType,
+ CancellationToken cancellationToken)
+ {
+ // Parse the DLNA time seek header
+ if (!streamingRequest.StartTimeTicks.HasValue)
+ {
+ var timeSeek = httpRequest.Headers["TimeSeekRange.dlna.org"];
+
+ streamingRequest.StartTimeTicks = ParseTimeSeekHeader(timeSeek.ToString());
+ }
+
+ if (!string.IsNullOrWhiteSpace(streamingRequest.Params))
+ {
+ ParseParams(streamingRequest);
+ }
+
+ streamingRequest.StreamOptions = ParseStreamOptions(httpRequest.Query);
+ if (httpRequest.Path.Value == null)
+ {
+ throw new ResourceNotFoundException(nameof(httpRequest.Path));
+ }
+
+ var url = httpRequest.Path.Value.AsSpan().RightPart('.').ToString();
+
+ if (string.IsNullOrEmpty(streamingRequest.AudioCodec))
+ {
+ streamingRequest.AudioCodec = encodingHelper.InferAudioCodec(url);
+ }
+
+ var enableDlnaHeaders = !string.IsNullOrWhiteSpace(streamingRequest.Params) ||
+ string.Equals(httpRequest.Headers["GetContentFeatures.DLNA.ORG"], "1", StringComparison.OrdinalIgnoreCase);
+
+ var state = new StreamState(mediaSourceManager, transcodingJobType, transcodingJobHelper)
+ {
+ Request = streamingRequest,
+ RequestedUrl = url,
+ UserAgent = httpRequest.Headers[HeaderNames.UserAgent],
+ EnableDlnaHeaders = enableDlnaHeaders
+ };
+
+ var auth = await authorizationContext.GetAuthorizationInfo(httpRequest).ConfigureAwait(false);
+ if (!auth.UserId.Equals(Guid.Empty))
+ {
+ state.User = userManager.GetUserById(auth.UserId);
+ }
+
+ if (state.IsVideoRequest && !string.IsNullOrWhiteSpace(state.Request.VideoCodec))
+ {
+ state.SupportedVideoCodecs = state.Request.VideoCodec.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ state.Request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
+ }
+
+ if (!string.IsNullOrWhiteSpace(streamingRequest.AudioCodec))
+ {
+ state.SupportedAudioCodecs = streamingRequest.AudioCodec.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(mediaEncoder.CanEncodeToAudioCodec)
+ ?? state.SupportedAudioCodecs.FirstOrDefault();
+ }
+
+ if (!string.IsNullOrWhiteSpace(streamingRequest.SubtitleCodec))
+ {
+ state.SupportedSubtitleCodecs = streamingRequest.SubtitleCodec.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(mediaEncoder.CanEncodeToSubtitleCodec)
+ ?? state.SupportedSubtitleCodecs.FirstOrDefault();
+ }
+
+ var item = libraryManager.GetItemById(streamingRequest.Id);
+
+ state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
+
+ MediaSourceInfo? mediaSource = null;
+ if (string.IsNullOrWhiteSpace(streamingRequest.LiveStreamId))
+ {
+ var currentJob = !string.IsNullOrWhiteSpace(streamingRequest.PlaySessionId)
+ ? transcodingJobHelper.GetTranscodingJob(streamingRequest.PlaySessionId)
+ : null;
+
+ if (currentJob != null)
+ {
+ mediaSource = currentJob.MediaSource;
+ }
+
+ if (mediaSource == null)
+ {
+ var mediaSources = await mediaSourceManager.GetPlaybackMediaSources(libraryManager.GetItemById(streamingRequest.Id), null, false, false, cancellationToken).ConfigureAwait(false);
+
+ mediaSource = string.IsNullOrEmpty(streamingRequest.MediaSourceId)
+ ? mediaSources[0]
+ : mediaSources.Find(i => string.Equals(i.Id, streamingRequest.MediaSourceId, StringComparison.InvariantCulture));
+
+ if (mediaSource == null && Guid.Parse(streamingRequest.MediaSourceId) == streamingRequest.Id)
+ {
+ mediaSource = mediaSources[0];
+ }
+ }
+ }
+ else
+ {
+ var liveStreamInfo = await mediaSourceManager.GetLiveStreamWithDirectStreamProvider(streamingRequest.LiveStreamId, cancellationToken).ConfigureAwait(false);
+ mediaSource = liveStreamInfo.Item1;
+ state.DirectStreamProvider = liveStreamInfo.Item2;
+ }
+
+ var encodingOptions = serverConfigurationManager.GetEncodingOptions();
+
+ encodingHelper.AttachMediaSourceInfo(state, encodingOptions, mediaSource, url);
+
+ string? containerInternal = Path.GetExtension(state.RequestedUrl);
+
+ if (!string.IsNullOrEmpty(streamingRequest.Container))
+ {
+ containerInternal = streamingRequest.Container;
+ }
+
+ if (string.IsNullOrEmpty(containerInternal))
+ {
+ containerInternal = streamingRequest.Static ?
+ StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, null, DlnaProfileType.Audio)
+ : GetOutputFileExtension(state);
+ }
+
+ state.OutputContainer = (containerInternal ?? string.Empty).TrimStart('.');
+
+ state.OutputAudioBitrate = encodingHelper.GetAudioBitrateParam(streamingRequest.AudioBitRate, streamingRequest.AudioCodec, state.AudioStream);
+
+ state.OutputAudioCodec = streamingRequest.AudioCodec;
+
+ state.OutputAudioChannels = encodingHelper.GetNumAudioChannelsParam(state, state.AudioStream, state.OutputAudioCodec);
+
+ if (state.VideoRequest != null)
+ {
+ state.OutputVideoCodec = state.Request.VideoCodec;
+ state.OutputVideoBitrate = encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
+
+ encodingHelper.TryStreamCopy(state);
+
+ if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec) && state.OutputVideoBitrate.HasValue)
+ {
+ var isVideoResolutionNotRequested = !state.VideoRequest.Width.HasValue
+ && !state.VideoRequest.Height.HasValue
+ && !state.VideoRequest.MaxWidth.HasValue
+ && !state.VideoRequest.MaxHeight.HasValue;
+
+ if (isVideoResolutionNotRequested
+ && state.VideoStream != null
+ && state.VideoRequest.VideoBitRate.HasValue
+ && state.VideoStream.BitRate.HasValue
+ && state.VideoRequest.VideoBitRate.Value >= state.VideoStream.BitRate.Value)
+ {
+ // Don't downscale the resolution if the width/height/MaxWidth/MaxHeight is not requested,
+ // and the requested video bitrate is higher than source video bitrate.
+ if (state.VideoStream.Width.HasValue || state.VideoStream.Height.HasValue)
+ {
+ state.VideoRequest.MaxWidth = state.VideoStream?.Width;
+ state.VideoRequest.MaxHeight = state.VideoStream?.Height;
+ }
+ }
+ else
+ {
+ var resolution = ResolutionNormalizer.Normalize(
+ state.VideoStream?.BitRate,
+ state.OutputVideoBitrate.Value,
+ state.VideoRequest.MaxWidth,
+ state.VideoRequest.MaxHeight);
+
+ state.VideoRequest.MaxWidth = resolution.MaxWidth;
+ state.VideoRequest.MaxHeight = resolution.MaxHeight;
+ }
+ }
+ }
+
+ ApplyDeviceProfileSettings(state, dlnaManager, deviceManager, httpRequest, streamingRequest.DeviceProfileId, streamingRequest.Static);
+
+ var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
+ ? GetOutputFileExtension(state)
+ : ("." + state.OutputContainer);
+
+ state.OutputFilePath = GetOutputFilePath(state, ext!, serverConfigurationManager, streamingRequest.DeviceId, streamingRequest.PlaySessionId);
+
+ return state;
+ }
+
+ /// <summary>
+ /// Adds the dlna headers.
+ /// </summary>
+ /// <param name="state">The state.</param>
+ /// <param name="responseHeaders">The response headers.</param>
+ /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
+ /// <param name="startTimeTicks">The start time in ticks.</param>
+ /// <param name="request">The <see cref="HttpRequest"/>.</param>
+ /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
+ public static void AddDlnaHeaders(
+ StreamState state,
+ IHeaderDictionary responseHeaders,
+ bool isStaticallyStreamed,
+ long? startTimeTicks,
+ HttpRequest request,
+ IDlnaManager dlnaManager)
+ {
+ if (!state.EnableDlnaHeaders)
+ {
+ return;
+ }
+
+ var profile = state.DeviceProfile;
+
+ StringValues transferMode = request.Headers["transferMode.dlna.org"];
+ responseHeaders.Add("transferMode.dlna.org", string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode.ToString());
+ responseHeaders.Add("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*");
+
+ if (state.RunTimeTicks.HasValue)
+ {
+ if (string.Equals(request.Headers["getMediaInfo.sec"], "1", StringComparison.OrdinalIgnoreCase))
+ {
+ var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
+ responseHeaders.Add("MediaInfo.sec", string.Format(
+ CultureInfo.InvariantCulture,
+ "SEC_Duration={0};",
+ Convert.ToInt32(ms)));
+ }
+
+ if (!isStaticallyStreamed && profile != null)
+ {
+ AddTimeSeekResponseHeaders(state, responseHeaders, startTimeTicks);
+ }
+ }
+
+ profile ??= dlnaManager.GetDefaultProfile();
+
+ var audioCodec = state.ActualOutputAudioCodec;
+
+ if (!state.IsVideoRequest)
+ {
+ responseHeaders.Add("contentFeatures.dlna.org", ContentFeatureBuilder.BuildAudioHeader(
+ profile,
+ state.OutputContainer,
+ audioCodec,
+ state.OutputAudioBitrate,
+ state.OutputAudioSampleRate,
+ state.OutputAudioChannels,
+ state.OutputAudioBitDepth,
+ isStaticallyStreamed,
+ state.RunTimeTicks,
+ state.TranscodeSeekInfo));
+ }
+ else
+ {
+ var videoCodec = state.ActualOutputVideoCodec;
+
+ responseHeaders.Add(
+ "contentFeatures.dlna.org",
+ ContentFeatureBuilder.BuildVideoHeader(profile, state.OutputContainer, videoCodec, audioCodec, state.OutputWidth, state.OutputHeight, state.TargetVideoBitDepth, state.OutputVideoBitrate, state.TargetTimestamp, isStaticallyStreamed, state.RunTimeTicks, state.TargetVideoProfile, state.TargetVideoLevel, state.TargetFramerate, state.TargetPacketLength, state.TranscodeSeekInfo, state.IsTargetAnamorphic, state.IsTargetInterlaced, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, state.TargetVideoCodecTag, state.IsTargetAVC).FirstOrDefault() ?? string.Empty);
+ }
+ }
+
+ /// <summary>
+ /// Parses the time seek header.
+ /// </summary>
+ /// <param name="value">The time seek header string.</param>
+ /// <returns>A nullable <see cref="long"/> representing the seek time in ticks.</returns>
+ private static long? ParseTimeSeekHeader(ReadOnlySpan<char> value)
+ {
+ if (value.IsEmpty)
+ {
+ return null;
+ }
+
+ const string npt = "npt=";
+ if (!value.StartsWith(npt, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new ArgumentException("Invalid timeseek header");
+ }
+
+ var index = value.IndexOf('-');
+ value = index == -1
+ ? value.Slice(npt.Length)
+ : value.Slice(npt.Length, index - npt.Length);
+ if (value.IndexOf(':') == -1)
+ {
+ // Parses npt times in the format of '417.33'
+ if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
+ {
+ return TimeSpan.FromSeconds(seconds).Ticks;
+ }
+
+ throw new ArgumentException("Invalid timeseek header");
+ }
+
+ try
+ {
+ // Parses npt times in the format of '10:19:25.7'
+ return TimeSpan.Parse(value).Ticks;
+ }
+ catch
+ {
+ throw new ArgumentException("Invalid timeseek header");
+ }
+ }
+
+ /// <summary>
+ /// Parses query parameters as StreamOptions.
+ /// </summary>
+ /// <param name="queryString">The query string.</param>
+ /// <returns>A <see cref="Dictionary{String,String}"/> containing the stream options.</returns>
+ private static Dictionary<string, string> ParseStreamOptions(IQueryCollection queryString)
+ {
+ Dictionary<string, string> streamOptions = new Dictionary<string, string>();
+ foreach (var param in queryString)
+ {
+ if (char.IsLower(param.Key[0]))
+ {
+ // This was probably not parsed initially and should be a StreamOptions
+ // or the generated URL should correctly serialize it
+ // TODO: This should be incorporated either in the lower framework for parsing requests
+ streamOptions[param.Key] = param.Value;
+ }
+ }
+
+ return streamOptions;
+ }
+
+ /// <summary>
+ /// Adds the dlna time seek headers to the response.
+ /// </summary>
+ /// <param name="state">The current <see cref="StreamState"/>.</param>
+ /// <param name="responseHeaders">The <see cref="IHeaderDictionary"/> of the response.</param>
+ /// <param name="startTimeTicks">The start time in ticks.</param>
+ private static void AddTimeSeekResponseHeaders(StreamState state, IHeaderDictionary responseHeaders, long? startTimeTicks)
+ {
+ var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks!.Value).TotalSeconds.ToString(CultureInfo.InvariantCulture);
+ var startSeconds = TimeSpan.FromTicks(startTimeTicks ?? 0).TotalSeconds.ToString(CultureInfo.InvariantCulture);
+
+ responseHeaders.Add("TimeSeekRange.dlna.org", string.Format(
+ CultureInfo.InvariantCulture,
+ "npt={0}-{1}/{1}",
+ startSeconds,
+ runtimeSeconds));
+ responseHeaders.Add("X-AvailableSeekRange", string.Format(
+ CultureInfo.InvariantCulture,
+ "1 npt={0}-{1}",
+ startSeconds,
+ runtimeSeconds));
+ }
+
+ /// <summary>
+ /// Gets the output file extension.
+ /// </summary>
+ /// <param name="state">The state.</param>
+ /// <returns>System.String.</returns>
+ private static string? GetOutputFileExtension(StreamState state)
+ {
+ var ext = Path.GetExtension(state.RequestedUrl);
+
+ if (!string.IsNullOrEmpty(ext))
+ {
+ return ext;
+ }
+
+ // Try to infer based on the desired video codec
+ if (state.IsVideoRequest)
+ {
+ var videoCodec = state.Request.VideoCodec;
+
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(videoCodec, "h265", StringComparison.OrdinalIgnoreCase))
+ {
+ return ".ts";
+ }
+
+ if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
+ {
+ return ".ogv";
+ }
+
+ if (string.Equals(videoCodec, "vp8", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "vp9", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
+ {
+ return ".webm";
+ }
+
+ if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
+ {
+ return ".asf";
+ }
+ }
+
+ // Try to infer based on the desired audio codec
+ if (!state.IsVideoRequest)
+ {
+ var audioCodec = state.Request.AudioCodec;
+
+ if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
+ {
+ return ".aac";
+ }
+
+ if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
+ {
+ return ".mp3";
+ }
+
+ if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
+ {
+ return ".ogg";
+ }
+
+ if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
+ {
+ return ".wma";
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets the output file path for transcoding.
+ /// </summary>
+ /// <param name="state">The current <see cref="StreamState"/>.</param>
+ /// <param name="outputFileExtension">The file extension of the output file.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="deviceId">The device id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <returns>The complete file path, including the folder, for the transcoding file.</returns>
+ private static string GetOutputFilePath(StreamState state, string outputFileExtension, IServerConfigurationManager serverConfigurationManager, string? deviceId, string? playSessionId)
+ {
+ var data = $"{state.MediaPath}-{state.UserAgent}-{deviceId!}-{playSessionId!}";
+
+ var filename = data.GetMD5().ToString("N", CultureInfo.InvariantCulture);
+ var ext = outputFileExtension?.ToLowerInvariant();
+ var folder = serverConfigurationManager.GetTranscodePath();
+
+ return Path.Combine(folder, filename + ext);
+ }
+
+ private static void ApplyDeviceProfileSettings(StreamState state, IDlnaManager dlnaManager, IDeviceManager deviceManager, HttpRequest request, string? deviceProfileId, bool? @static)
+ {
+ if (!string.IsNullOrWhiteSpace(deviceProfileId))
+ {
+ state.DeviceProfile = dlnaManager.GetProfile(deviceProfileId);
+
+ if (state.DeviceProfile == null)
+ {
+ var caps = deviceManager.GetCapabilities(deviceProfileId);
+ state.DeviceProfile = caps == null ? dlnaManager.GetProfile(request.Headers) : caps.DeviceProfile;
+ }
+ }
+
+ var profile = state.DeviceProfile;
+
+ if (profile == null)
+ {
+ // Don't use settings from the default profile.
+ // Only use a specific profile if it was requested.
+ return;
+ }
+
+ var audioCodec = state.ActualOutputAudioCodec;
+ var videoCodec = state.ActualOutputVideoCodec;
+
+ var mediaProfile = !state.IsVideoRequest
+ ? profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate, state.OutputAudioSampleRate, state.OutputAudioBitDepth)
+ : profile.GetVideoMediaProfile(
+ state.OutputContainer,
+ audioCodec,
+ videoCodec,
+ state.OutputWidth,
+ state.OutputHeight,
+ state.TargetVideoBitDepth,
+ state.OutputVideoBitrate,
+ state.TargetVideoProfile,
+ state.TargetVideoLevel,
+ state.TargetFramerate,
+ state.TargetPacketLength,
+ state.TargetTimestamp,
+ state.IsTargetAnamorphic,
+ state.IsTargetInterlaced,
+ state.TargetRefFrames,
+ state.TargetVideoStreamCount,
+ state.TargetAudioStreamCount,
+ state.TargetVideoCodecTag,
+ state.IsTargetAVC);
+
+ if (mediaProfile != null)
+ {
+ state.MimeType = mediaProfile.MimeType;
+ }
+
+ if (!(@static.HasValue && @static.Value))
+ {
+ var transcodingProfile = !state.IsVideoRequest ? profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) : profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
+
+ if (transcodingProfile != null)
+ {
+ state.EstimateContentLength = transcodingProfile.EstimateContentLength;
+ // state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
+ state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
+
+ if (state.VideoRequest != null)
+ {
+ state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
+ state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Parses the parameters.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ private static void ParseParams(StreamingRequestDto request)
+ {
+ if (string.IsNullOrEmpty(request.Params))
+ {
+ return;
+ }
+
+ var vals = request.Params.Split(';');
+
+ var videoRequest = request as VideoRequestDto;
+
+ for (var i = 0; i < vals.Length; i++)
+ {
+ var val = vals[i];
+
+ if (string.IsNullOrWhiteSpace(val))
+ {
+ continue;
+ }
+
+ switch (i)
+ {
+ case 0:
+ request.DeviceProfileId = val;
+ break;
+ case 1:
+ request.DeviceId = val;
+ break;
+ case 2:
+ request.MediaSourceId = val;
+ break;
+ case 3:
+ request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ break;
+ case 4:
+ if (videoRequest != null)
+ {
+ videoRequest.VideoCodec = val;
+ }
+
+ break;
+ case 5:
+ request.AudioCodec = val;
+ break;
+ case 6:
+ if (videoRequest != null)
+ {
+ videoRequest.AudioStreamIndex = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 7:
+ if (videoRequest != null)
+ {
+ videoRequest.SubtitleStreamIndex = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 8:
+ if (videoRequest != null)
+ {
+ videoRequest.VideoBitRate = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 9:
+ request.AudioBitRate = int.Parse(val, CultureInfo.InvariantCulture);
+ break;
+ case 10:
+ request.MaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture);
+ break;
+ case 11:
+ if (videoRequest != null)
+ {
+ videoRequest.MaxFramerate = float.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 12:
+ if (videoRequest != null)
+ {
+ videoRequest.MaxWidth = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 13:
+ if (videoRequest != null)
+ {
+ videoRequest.MaxHeight = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 14:
+ request.StartTimeTicks = long.Parse(val, CultureInfo.InvariantCulture);
+ break;
+ case 15:
+ if (videoRequest != null)
+ {
+ videoRequest.Level = val;
+ }
+
+ break;
+ case 16:
+ if (videoRequest != null)
+ {
+ videoRequest.MaxRefFrames = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 17:
+ if (videoRequest != null)
+ {
+ videoRequest.MaxVideoBitDepth = int.Parse(val, CultureInfo.InvariantCulture);
+ }
+
+ break;
+ case 18:
+ if (videoRequest != null)
+ {
+ videoRequest.Profile = val;
+ }
+
+ break;
+ case 19:
+ // cabac no longer used
+ break;
+ case 20:
+ request.PlaySessionId = val;
+ break;
+ case 21:
+ // api_key
+ break;
+ case 22:
+ request.LiveStreamId = val;
+ break;
+ case 23:
+ // Duplicating ItemId because of MediaMonkey
+ break;
+ case 24:
+ if (videoRequest != null)
+ {
+ videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ }
+
+ break;
+ case 25:
+ if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
+ {
+ if (Enum.TryParse(val, out SubtitleDeliveryMethod method))
+ {
+ videoRequest.SubtitleMethod = method;
+ }
+ }
+
+ break;
+ case 26:
+ request.TranscodingMaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture);
+ break;
+ case 27:
+ if (videoRequest != null)
+ {
+ videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ }
+
+ break;
+ case 28:
+ request.Tag = val;
+ break;
+ case 29:
+ if (videoRequest != null)
+ {
+ videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ }
+
+ break;
+ case 30:
+ request.SubtitleCodec = val;
+ break;
+ case 31:
+ if (videoRequest != null)
+ {
+ videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ }
+
+ break;
+ case 32:
+ if (videoRequest != null)
+ {
+ videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
+ }
+
+ break;
+ case 33:
+ request.TranscodeReasons = val;
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
new file mode 100644
index 000000000..07d0b5543
--- /dev/null
+++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
@@ -0,0 +1,892 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.PlaybackDtos;
+using Jellyfin.Api.Models.StreamingDtos;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Helpers
+{
+ /// <summary>
+ /// Transcoding job helpers.
+ /// </summary>
+ public class TranscodingJobHelper : IDisposable
+ {
+ /// <summary>
+ /// The active transcoding jobs.
+ /// </summary>
+ private static readonly List<TranscodingJobDto> _activeTranscodingJobs = new List<TranscodingJobDto>();
+
+ /// <summary>
+ /// The transcoding locks.
+ /// </summary>
+ private static readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = new Dictionary<string, SemaphoreSlim>();
+
+ private readonly IAuthorizationContext _authorizationContext;
+ private readonly EncodingHelper _encodingHelper;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILogger<TranscodingJobHelper> _logger;
+ private readonly IMediaEncoder _mediaEncoder;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly ISessionManager _sessionManager;
+ private readonly ILoggerFactory _loggerFactory;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TranscodingJobHelper"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobHelpers}"/> interface.</param>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
+ /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+ /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public TranscodingJobHelper(
+ ILogger<TranscodingJobHelper> logger,
+ IMediaSourceManager mediaSourceManager,
+ IFileSystem fileSystem,
+ IMediaEncoder mediaEncoder,
+ IServerConfigurationManager serverConfigurationManager,
+ ISessionManager sessionManager,
+ IAuthorizationContext authorizationContext,
+ EncodingHelper encodingHelper,
+ ILoggerFactory loggerFactory)
+ {
+ _logger = logger;
+ _mediaSourceManager = mediaSourceManager;
+ _fileSystem = fileSystem;
+ _mediaEncoder = mediaEncoder;
+ _serverConfigurationManager = serverConfigurationManager;
+ _sessionManager = sessionManager;
+ _authorizationContext = authorizationContext;
+ _encodingHelper = encodingHelper;
+ _loggerFactory = loggerFactory;
+
+ DeleteEncodedMediaCache();
+
+ sessionManager.PlaybackProgress += OnPlaybackProgress;
+ sessionManager.PlaybackStart += OnPlaybackProgress;
+ }
+
+ /// <summary>
+ /// Get transcoding job.
+ /// </summary>
+ /// <param name="playSessionId">Playback session id.</param>
+ /// <returns>The transcoding job.</returns>
+ public TranscodingJobDto? GetTranscodingJob(string playSessionId)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ /// <summary>
+ /// Get transcoding job.
+ /// </summary>
+ /// <param name="path">Path to the transcoding file.</param>
+ /// <param name="type">The <see cref="TranscodingJobType"/>.</param>
+ /// <returns>The transcoding job.</returns>
+ public TranscodingJobDto? GetTranscodingJob(string path, TranscodingJobType type)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ /// <summary>
+ /// Ping transcoding job.
+ /// </summary>
+ /// <param name="playSessionId">Play session id.</param>
+ /// <param name="isUserPaused">Is user paused.</param>
+ /// <exception cref="ArgumentNullException">Play session id is null.</exception>
+ public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
+ {
+ if (string.IsNullOrEmpty(playSessionId))
+ {
+ throw new ArgumentNullException(nameof(playSessionId));
+ }
+
+ _logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
+
+ List<TranscodingJobDto> jobs;
+
+ lock (_activeTranscodingJobs)
+ {
+ // This is really only needed for HLS.
+ // Progressive streams can stop on their own reliably.
+ jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
+ }
+
+ foreach (var job in jobs)
+ {
+ if (isUserPaused.HasValue)
+ {
+ _logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
+ job.IsUserPaused = isUserPaused.Value;
+ }
+
+ PingTimer(job, true);
+ }
+ }
+
+ private void PingTimer(TranscodingJobDto job, bool isProgressCheckIn)
+ {
+ if (job.HasExited)
+ {
+ job.StopKillTimer();
+ return;
+ }
+
+ var timerDuration = 10000;
+
+ if (job.Type != TranscodingJobType.Progressive)
+ {
+ timerDuration = 60000;
+ }
+
+ job.PingTimeout = timerDuration;
+ job.LastPingDate = DateTime.UtcNow;
+
+ // Don't start the timer for playback checkins with progressive streaming
+ if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
+ {
+ job.StartKillTimer(OnTranscodeKillTimerStopped);
+ }
+ else
+ {
+ job.ChangeKillTimerIfStarted();
+ }
+ }
+
+ /// <summary>
+ /// Called when [transcode kill timer stopped].
+ /// </summary>
+ /// <param name="state">The state.</param>
+ private async void OnTranscodeKillTimerStopped(object? state)
+ {
+ var job = state as TranscodingJobDto ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJobDto)}", nameof(state));
+ if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
+ {
+ var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
+
+ if (timeSinceLastPing < job.PingTimeout)
+ {
+ job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
+ return;
+ }
+ }
+
+ _logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
+ await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Kills the single transcoding job.
+ /// </summary>
+ /// <param name="deviceId">The device id.</param>
+ /// <param name="playSessionId">The play session identifier.</param>
+ /// <param name="deleteFiles">The delete files.</param>
+ /// <returns>Task.</returns>
+ public Task KillTranscodingJobs(string deviceId, string? playSessionId, Func<string, bool> deleteFiles)
+ {
+ return KillTranscodingJobs(
+ j => string.IsNullOrWhiteSpace(playSessionId)
+ ? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase)
+ : string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase), deleteFiles);
+ }
+
+ /// <summary>
+ /// Kills the transcoding jobs.
+ /// </summary>
+ /// <param name="killJob">The kill job.</param>
+ /// <param name="deleteFiles">The delete files.</param>
+ /// <returns>Task.</returns>
+ private Task KillTranscodingJobs(Func<TranscodingJobDto, bool> killJob, Func<string, bool> deleteFiles)
+ {
+ var jobs = new List<TranscodingJobDto>();
+
+ lock (_activeTranscodingJobs)
+ {
+ // This is really only needed for HLS.
+ // Progressive streams can stop on their own reliably.
+ jobs.AddRange(_activeTranscodingJobs.Where(killJob));
+ }
+
+ if (jobs.Count == 0)
+ {
+ return Task.CompletedTask;
+ }
+
+ IEnumerable<Task> GetKillJobs()
+ {
+ foreach (var job in jobs)
+ {
+ yield return KillTranscodingJob(job, false, deleteFiles);
+ }
+ }
+
+ return Task.WhenAll(GetKillJobs());
+ }
+
+ /// <summary>
+ /// Kills the transcoding job.
+ /// </summary>
+ /// <param name="job">The job.</param>
+ /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
+ /// <param name="delete">The delete.</param>
+ private async Task KillTranscodingJob(TranscodingJobDto job, bool closeLiveStream, Func<string, bool> delete)
+ {
+ job.DisposeKillTimer();
+
+ _logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
+ lock (_activeTranscodingJobs)
+ {
+ _activeTranscodingJobs.Remove(job);
+
+ if (job.CancellationTokenSource?.IsCancellationRequested == false)
+ {
+ job.CancellationTokenSource.Cancel();
+ }
+ }
+
+ lock (_transcodingLocks)
+ {
+ _transcodingLocks.Remove(job.Path!);
+ }
+
+ lock (job.ProcessLock!)
+ {
+ job.TranscodingThrottler?.Stop().GetAwaiter().GetResult();
+
+ var process = job.Process;
+
+ var hasExited = job.HasExited;
+
+ if (!hasExited)
+ {
+ try
+ {
+ _logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
+
+ process!.StandardInput.WriteLine("q");
+
+ // Need to wait because killing is asynchronous.
+ if (!process.WaitForExit(5000))
+ {
+ _logger.LogInformation("Killing FFmpeg process for {Path}", job.Path);
+ process.Kill();
+ }
+ }
+ catch (InvalidOperationException)
+ {
+ }
+ }
+ }
+
+ if (delete(job.Path!))
+ {
+ await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
+ }
+
+ if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
+ {
+ try
+ {
+ await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
+ }
+ }
+ }
+
+ private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
+ {
+ if (retryCount >= 10)
+ {
+ return;
+ }
+
+ _logger.LogInformation("Deleting partial stream file(s) {Path}", path);
+
+ await Task.Delay(delayMs).ConfigureAwait(false);
+
+ try
+ {
+ if (jobType == TranscodingJobType.Progressive)
+ {
+ DeleteProgressivePartialStreamFiles(path);
+ }
+ else
+ {
+ DeleteHlsPartialStreamFiles(path);
+ }
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
+
+ await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
+ }
+ }
+
+ /// <summary>
+ /// Deletes the progressive partial stream files.
+ /// </summary>
+ /// <param name="outputFilePath">The output file path.</param>
+ private void DeleteProgressivePartialStreamFiles(string outputFilePath)
+ {
+ if (File.Exists(outputFilePath))
+ {
+ _fileSystem.DeleteFile(outputFilePath);
+ }
+ }
+
+ /// <summary>
+ /// Deletes the HLS partial stream files.
+ /// </summary>
+ /// <param name="outputFilePath">The output file path.</param>
+ private void DeleteHlsPartialStreamFiles(string outputFilePath)
+ {
+ var directory = Path.GetDirectoryName(outputFilePath)
+ ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputFilePath));
+
+ var name = Path.GetFileNameWithoutExtension(outputFilePath);
+
+ var filesToDelete = _fileSystem.GetFilePaths(directory)
+ .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
+
+ List<Exception>? exs = null;
+ foreach (var file in filesToDelete)
+ {
+ try
+ {
+ _logger.LogDebug("Deleting HLS file {0}", file);
+ _fileSystem.DeleteFile(file);
+ }
+ catch (IOException ex)
+ {
+ (exs ??= new List<Exception>(4)).Add(ex);
+ _logger.LogError(ex, "Error deleting HLS file {Path}", file);
+ }
+ }
+
+ if (exs != null)
+ {
+ throw new AggregateException("Error deleting HLS files", exs);
+ }
+ }
+
+ /// <summary>
+ /// Report the transcoding progress to the session manager.
+ /// </summary>
+ /// <param name="job">The <see cref="TranscodingJobDto"/> of which the progress will be reported.</param>
+ /// <param name="state">The <see cref="StreamState"/> of the current transcoding job.</param>
+ /// <param name="transcodingPosition">The current transcoding position.</param>
+ /// <param name="framerate">The framerate of the transcoding job.</param>
+ /// <param name="percentComplete">The completion percentage of the transcode.</param>
+ /// <param name="bytesTranscoded">The number of bytes transcoded.</param>
+ /// <param name="bitRate">The bitrate of the transcoding job.</param>
+ public void ReportTranscodingProgress(
+ TranscodingJobDto job,
+ StreamState state,
+ TimeSpan? transcodingPosition,
+ float? framerate,
+ double? percentComplete,
+ long? bytesTranscoded,
+ int? bitRate)
+ {
+ var ticks = transcodingPosition?.Ticks;
+
+ if (job != null)
+ {
+ job.Framerate = framerate;
+ job.CompletionPercentage = percentComplete;
+ job.TranscodingPositionTicks = ticks;
+ job.BytesTranscoded = bytesTranscoded;
+ job.BitRate = bitRate;
+ }
+
+ var deviceId = state.Request.DeviceId;
+
+ if (!string.IsNullOrWhiteSpace(deviceId))
+ {
+ var audioCodec = state.ActualOutputAudioCodec;
+ var videoCodec = state.ActualOutputVideoCodec;
+ var hardwareAccelerationTypeString = _serverConfigurationManager.GetEncodingOptions().HardwareAccelerationType;
+ HardwareEncodingType? hardwareAccelerationType = string.IsNullOrEmpty(hardwareAccelerationTypeString)
+ ? null
+ : (HardwareEncodingType)Enum.Parse(typeof(HardwareEncodingType), hardwareAccelerationTypeString, true);
+
+ _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
+ {
+ Bitrate = bitRate ?? state.TotalOutputBitrate,
+ AudioCodec = audioCodec,
+ VideoCodec = videoCodec,
+ Container = state.OutputContainer,
+ Framerate = framerate,
+ CompletionPercentage = percentComplete,
+ Width = state.OutputWidth,
+ Height = state.OutputHeight,
+ AudioChannels = state.OutputAudioChannels,
+ IsAudioDirect = EncodingHelper.IsCopyCodec(state.OutputAudioCodec),
+ IsVideoDirect = EncodingHelper.IsCopyCodec(state.OutputVideoCodec),
+ HardwareAccelerationType = hardwareAccelerationType,
+ TranscodeReasons = state.TranscodeReasons
+ });
+ }
+ }
+
+ /// <summary>
+ /// Starts FFmpeg.
+ /// </summary>
+ /// <param name="state">The state.</param>
+ /// <param name="outputPath">The output path.</param>
+ /// <param name="commandLineArguments">The command line arguments for FFmpeg.</param>
+ /// <param name="request">The <see cref="HttpRequest"/>.</param>
+ /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
+ /// <param name="cancellationTokenSource">The cancellation token source.</param>
+ /// <param name="workingDirectory">The working directory.</param>
+ /// <returns>Task.</returns>
+ public async Task<TranscodingJobDto> StartFfMpeg(
+ StreamState state,
+ string outputPath,
+ string commandLineArguments,
+ HttpRequest request,
+ TranscodingJobType transcodingJobType,
+ CancellationTokenSource cancellationTokenSource,
+ string? workingDirectory = null)
+ {
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(directory);
+
+ await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
+
+ if (state.VideoRequest != null && !EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
+ {
+ var auth = await _authorizationContext.GetAuthorizationInfo(request).ConfigureAwait(false);
+ if (auth.User != null && !auth.User.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
+ {
+ this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
+
+ throw new ArgumentException("User does not have access to video transcoding.");
+ }
+ }
+
+ if (string.IsNullOrEmpty(_mediaEncoder.EncoderPath))
+ {
+ throw new ArgumentException("FFmpeg path not set.");
+ }
+
+ var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ WindowStyle = ProcessWindowStyle.Hidden,
+ CreateNoWindow = true,
+ UseShellExecute = false,
+
+ // Must consume both stdout and stderr or deadlocks may occur
+ // RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ RedirectStandardInput = true,
+ FileName = _mediaEncoder.EncoderPath,
+ Arguments = commandLineArguments,
+ WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? string.Empty : workingDirectory,
+ ErrorDialog = false
+ },
+ EnableRaisingEvents = true
+ };
+
+ var transcodingJob = this.OnTranscodeBeginning(
+ outputPath,
+ state.Request.PlaySessionId,
+ state.MediaSource.LiveStreamId,
+ Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
+ transcodingJobType,
+ process,
+ state.Request.DeviceId,
+ state,
+ cancellationTokenSource);
+
+ var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
+ _logger.LogInformation(commandLineLogMessage);
+
+ var logFilePrefix = "FFmpeg.Transcode-";
+ if (state.VideoRequest != null
+ && EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
+ {
+ logFilePrefix = EncodingHelper.IsCopyCodec(state.OutputAudioCodec)
+ ? "FFmpeg.Remux-"
+ : "FFmpeg.DirectStream-";
+ }
+
+ var logFilePath = Path.Combine(
+ _serverConfigurationManager.ApplicationPaths.LogDirectoryPath,
+ $"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log");
+
+ // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
+ Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+
+ var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
+ await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
+
+ process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
+
+ try
+ {
+ process.Start();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error starting FFmpeg");
+
+ this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
+
+ throw;
+ }
+
+ _logger.LogDebug("Launched FFmpeg process");
+ state.TranscodingJob = transcodingJob;
+
+ // Important - don't await the log task or we won't be able to kill FFmpeg when the user stops playback
+ _ = new JobLogger(_logger).StartStreamingLog(state, process.StandardError.BaseStream, logStream);
+
+ // Wait for the file to exist before proceeding
+ var ffmpegTargetFile = state.WaitForPath ?? outputPath;
+ _logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile);
+ while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited)
+ {
+ await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
+ }
+
+ _logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile);
+
+ if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
+ {
+ await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
+
+ if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
+ {
+ await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
+ }
+ }
+
+ if (!transcodingJob.HasExited)
+ {
+ StartThrottler(state, transcodingJob);
+ }
+ else if (transcodingJob.ExitCode != 0)
+ {
+ throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "FFmpeg exited with code {0}", transcodingJob.ExitCode));
+ }
+
+ _logger.LogDebug("StartFfMpeg() finished successfully");
+
+ return transcodingJob;
+ }
+
+ private void StartThrottler(StreamState state, TranscodingJobDto transcodingJob)
+ {
+ if (EnableThrottling(state))
+ {
+ transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, new Logger<TranscodingThrottler>(new LoggerFactory()), _serverConfigurationManager, _fileSystem);
+ state.TranscodingThrottler.Start();
+ }
+ }
+
+ private bool EnableThrottling(StreamState state)
+ {
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+
+ // enable throttling when NOT using hardware acceleration
+ if (string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
+ {
+ return state.InputProtocol == MediaProtocol.File &&
+ state.RunTimeTicks.HasValue &&
+ state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
+ state.IsInputVideo &&
+ state.VideoType == VideoType.VideoFile &&
+ !EncodingHelper.IsCopyCodec(state.OutputVideoCodec);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Called when [transcode beginning].
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="playSessionId">The play session identifier.</param>
+ /// <param name="liveStreamId">The live stream identifier.</param>
+ /// <param name="transcodingJobId">The transcoding job identifier.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="process">The process.</param>
+ /// <param name="deviceId">The device id.</param>
+ /// <param name="state">The state.</param>
+ /// <param name="cancellationTokenSource">The cancellation token source.</param>
+ /// <returns>TranscodingJob.</returns>
+ public TranscodingJobDto OnTranscodeBeginning(
+ string path,
+ string? playSessionId,
+ string? liveStreamId,
+ string transcodingJobId,
+ TranscodingJobType type,
+ Process process,
+ string? deviceId,
+ StreamState state,
+ CancellationTokenSource cancellationTokenSource)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ var job = new TranscodingJobDto(_loggerFactory.CreateLogger<TranscodingJobDto>())
+ {
+ Type = type,
+ Path = path,
+ Process = process,
+ ActiveRequestCount = 1,
+ DeviceId = deviceId,
+ CancellationTokenSource = cancellationTokenSource,
+ Id = transcodingJobId,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId,
+ MediaSource = state.MediaSource
+ };
+
+ _activeTranscodingJobs.Add(job);
+
+ ReportTranscodingProgress(job, state, null, null, null, null, null);
+
+ return job;
+ }
+ }
+
+ /// <summary>
+ /// Called when [transcode end].
+ /// </summary>
+ /// <param name="job">The transcode job.</param>
+ public void OnTranscodeEndRequest(TranscodingJobDto job)
+ {
+ job.ActiveRequestCount--;
+ _logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={ActiveRequestCount}", job.ActiveRequestCount);
+ if (job.ActiveRequestCount <= 0)
+ {
+ PingTimer(job, false);
+ }
+ }
+
+ /// <summary>
+ /// <summary>
+ /// The progressive
+ /// </summary>
+ /// Called when [transcode failed to start].
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="state">The state.</param>
+ public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
+
+ if (job != null)
+ {
+ _activeTranscodingJobs.Remove(job);
+ }
+ }
+
+ lock (_transcodingLocks)
+ {
+ _transcodingLocks.Remove(path);
+ }
+
+ if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
+ {
+ _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
+ }
+ }
+
+ /// <summary>
+ /// Processes the exited.
+ /// </summary>
+ /// <param name="process">The process.</param>
+ /// <param name="job">The job.</param>
+ /// <param name="state">The state.</param>
+ private void OnFfMpegProcessExited(Process process, TranscodingJobDto job, StreamState state)
+ {
+ job.HasExited = true;
+ job.ExitCode = process.ExitCode;
+
+ _logger.LogDebug("Disposing stream resources");
+ state.Dispose();
+
+ if (process.ExitCode == 0)
+ {
+ _logger.LogInformation("FFmpeg exited with code 0");
+ }
+ else
+ {
+ _logger.LogError("FFmpeg exited with code {0}", process.ExitCode);
+ }
+
+ job.Dispose();
+ }
+
+ private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
+ {
+ if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
+ {
+ var liveStreamResponse = await _mediaSourceManager.OpenLiveStream(
+ new LiveStreamRequest { OpenToken = state.MediaSource.OpenToken },
+ cancellationTokenSource.Token)
+ .ConfigureAwait(false);
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+
+ _encodingHelper.AttachMediaSourceInfo(state, encodingOptions, liveStreamResponse.MediaSource, state.RequestedUrl);
+
+ if (state.VideoRequest != null)
+ {
+ _encodingHelper.TryStreamCopy(state);
+ }
+ }
+
+ if (state.MediaSource.BufferMs.HasValue)
+ {
+ await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
+ }
+ }
+
+ /// <summary>
+ /// Called when [transcode begin request].
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="type">The type.</param>
+ /// <returns>The <see cref="TranscodingJobDto"/>.</returns>
+ public TranscodingJobDto? OnTranscodeBeginRequest(string path, TranscodingJobType type)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
+
+ if (job == null)
+ {
+ return null;
+ }
+
+ OnTranscodeBeginRequest(job);
+
+ return job;
+ }
+ }
+
+ private void OnTranscodeBeginRequest(TranscodingJobDto job)
+ {
+ job.ActiveRequestCount++;
+
+ if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
+ {
+ job.StopKillTimer();
+ }
+ }
+
+ /// <summary>
+ /// Gets the transcoding lock.
+ /// </summary>
+ /// <param name="outputPath">The output path of the transcoded file.</param>
+ /// <returns>A <see cref="SemaphoreSlim"/>.</returns>
+ public SemaphoreSlim GetTranscodingLock(string outputPath)
+ {
+ lock (_transcodingLocks)
+ {
+ if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result))
+ {
+ result = new SemaphoreSlim(1, 1);
+ _transcodingLocks[outputPath] = result;
+ }
+
+ return result;
+ }
+ }
+
+ private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
+ {
+ if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
+ {
+ PingTranscodingJob(e.PlaySessionId, e.IsPaused);
+ }
+ }
+
+ /// <summary>
+ /// Deletes the encoded media cache.
+ /// </summary>
+ private void DeleteEncodedMediaCache()
+ {
+ var path = _serverConfigurationManager.GetTranscodePath();
+ if (!Directory.Exists(path))
+ {
+ return;
+ }
+
+ foreach (var file in _fileSystem.GetFilePaths(path, true))
+ {
+ _fileSystem.DeleteFile(file);
+ }
+ }
+
+ /// <summary>
+ /// Dispose transcoding job helper.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Dispose throttler.
+ /// </summary>
+ /// <param name="disposing">Disposing.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _loggerFactory.Dispose();
+ _sessionManager.PlaybackProgress -= OnPlaybackProgress;
+ _sessionManager.PlaybackStart -= OnPlaybackProgress;
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj
new file mode 100644
index 000000000..57480b2f3
--- /dev/null
+++ b/Jellyfin.Api/Jellyfin.Api.csproj
@@ -0,0 +1,40 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{DFBEFB4C-DA19-4143-98B7-27320C7F7163}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <!-- https://github.com/microsoft/ApplicationInsights-dotnet/issues/2047 -->
+ <NoWarn>AD0001</NoWarn>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
+ <PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="6.2.3" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
+ <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
+ <_Parameter1>Jellyfin.Api.Tests</_Parameter1>
+ </AssemblyAttribute>
+ </ItemGroup>
+
+</Project>
diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
new file mode 100644
index 000000000..c04f3c721
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ /// <summary>
+ /// Comma delimited array model binder.
+ /// Returns an empty array of specified type if there is no query parameter.
+ /// </summary>
+ public class CommaDelimitedArrayModelBinder : IModelBinder
+ {
+ private readonly ILogger<CommaDelimitedArrayModelBinder> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CommaDelimitedArrayModelBinder"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{CommaDelimitedArrayModelBinder}"/> interface.</param>
+ public CommaDelimitedArrayModelBinder(ILogger<CommaDelimitedArrayModelBinder> logger)
+ {
+ _logger = logger;
+ }
+
+ /// <inheritdoc/>
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
+ var converter = TypeDescriptor.GetConverter(elementType);
+
+ if (valueProviderResult.Length > 1)
+ {
+ var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var value = valueProviderResult.FirstValue;
+
+ if (value != null)
+ {
+ var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ var typedValues = GetParsedResult(splitValues, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var emptyResult = Array.CreateInstance(elementType, 0);
+ bindingContext.Result = ModelBindingResult.Success(emptyResult);
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+
+ private Array GetParsedResult(IReadOnlyList<string> values, Type elementType, TypeConverter converter)
+ {
+ var parsedValues = new object?[values.Count];
+ var convertedCount = 0;
+ for (var i = 0; i < values.Count; i++)
+ {
+ try
+ {
+ parsedValues[i] = converter.ConvertFromString(values[i].Trim());
+ convertedCount++;
+ }
+ catch (FormatException e)
+ {
+ _logger.LogDebug(e, "Error converting value.");
+ }
+ }
+
+ var typedValues = Array.CreateInstance(elementType, convertedCount);
+ var typedValueIndex = 0;
+ for (var i = 0; i < parsedValues.Length; i++)
+ {
+ if (parsedValues[i] != null)
+ {
+ typedValues.SetValue(parsedValues[i], typedValueIndex);
+ typedValueIndex++;
+ }
+ }
+
+ return typedValues;
+ }
+ }
+}
diff --git a/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs b/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs
new file mode 100644
index 000000000..e1cb725f3
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs
@@ -0,0 +1,49 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ /// <summary>
+ /// DateTime model binder.
+ /// </summary>
+ public class LegacyDateTimeModelBinder : IModelBinder
+ {
+ // Borrowed from the DateTimeModelBinderProvider
+ private const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces;
+ private readonly DateTimeModelBinder _defaultModelBinder;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LegacyDateTimeModelBinder"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public LegacyDateTimeModelBinder(ILoggerFactory loggerFactory)
+ {
+ _defaultModelBinder = new DateTimeModelBinder(SupportedStyles, loggerFactory);
+ }
+
+ /// <inheritdoc />
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ if (valueProviderResult.Values.Count == 1)
+ {
+ var dateTimeString = valueProviderResult.FirstValue;
+ // Mark Played Item.
+ if (DateTime.TryParseExact(dateTimeString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime))
+ {
+ bindingContext.Result = ModelBindingResult.Success(dateTime);
+ }
+ else
+ {
+ return _defaultModelBinder.BindModelAsync(bindingContext);
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs
new file mode 100644
index 000000000..d2e78ac88
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs
@@ -0,0 +1,48 @@
+using System;
+using System.ComponentModel;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ /// <summary>
+ /// Nullable enum model binder.
+ /// </summary>
+ public class NullableEnumModelBinder : IModelBinder
+ {
+ private readonly ILogger<NullableEnumModelBinder> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NullableEnumModelBinder"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{NullableEnumModelBinder}"/> interface.</param>
+ public NullableEnumModelBinder(ILogger<NullableEnumModelBinder> logger)
+ {
+ _logger = logger;
+ }
+
+ /// <inheritdoc />
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
+ var converter = TypeDescriptor.GetConverter(elementType);
+ if (valueProviderResult.Length != 0)
+ {
+ try
+ {
+ // REVIEW: This shouldn't be null here
+ var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue!);
+ bindingContext.Result = ModelBindingResult.Success(convertedValue);
+ }
+ catch (FormatException e)
+ {
+ _logger.LogDebug(e, "Error converting value.");
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs b/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs
new file mode 100644
index 000000000..bc12ad05d
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs
@@ -0,0 +1,27 @@
+using System;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ /// <summary>
+ /// Nullable enum model binder provider.
+ /// </summary>
+ public class NullableEnumModelBinderProvider : IModelBinderProvider
+ {
+ /// <inheritdoc />
+ public IModelBinder? GetBinder(ModelBinderProviderContext context)
+ {
+ var nullableType = Nullable.GetUnderlyingType(context.Metadata.ModelType);
+ if (nullableType == null || !nullableType.IsEnum)
+ {
+ // Type isn't nullable or isn't an enum.
+ return null;
+ }
+
+ var logger = context.Services.GetRequiredService<ILogger<NullableEnumModelBinder>>();
+ return new NullableEnumModelBinder(logger);
+ }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs
new file mode 100644
index 000000000..639ab0793
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ /// <summary>
+ /// Comma delimited array model binder.
+ /// Returns an empty array of specified type if there is no query parameter.
+ /// </summary>
+ public class PipeDelimitedArrayModelBinder : IModelBinder
+ {
+ private readonly ILogger<PipeDelimitedArrayModelBinder> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PipeDelimitedArrayModelBinder"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{PipeDelimitedArrayModelBinder}"/> interface.</param>
+ public PipeDelimitedArrayModelBinder(ILogger<PipeDelimitedArrayModelBinder> logger)
+ {
+ _logger = logger;
+ }
+
+ /// <inheritdoc/>
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
+ var converter = TypeDescriptor.GetConverter(elementType);
+
+ if (valueProviderResult.Length > 1)
+ {
+ var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var value = valueProviderResult.FirstValue;
+
+ if (value != null)
+ {
+ var splitValues = value.Split('|', StringSplitOptions.RemoveEmptyEntries);
+ var typedValues = GetParsedResult(splitValues, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var emptyResult = Array.CreateInstance(elementType, 0);
+ bindingContext.Result = ModelBindingResult.Success(emptyResult);
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+
+ private Array GetParsedResult(IReadOnlyList<string> values, Type elementType, TypeConverter converter)
+ {
+ var parsedValues = new object?[values.Count];
+ var convertedCount = 0;
+ for (var i = 0; i < values.Count; i++)
+ {
+ try
+ {
+ parsedValues[i] = converter.ConvertFromString(values[i].Trim());
+ convertedCount++;
+ }
+ catch (FormatException e)
+ {
+ _logger.LogDebug(e, "Error converting value.");
+ }
+ }
+
+ var typedValues = Array.CreateInstance(elementType, convertedCount);
+ var typedValueIndex = 0;
+ for (var i = 0; i < parsedValues.Length; i++)
+ {
+ if (parsedValues[i] != null)
+ {
+ typedValues.SetValue(parsedValues[i], typedValueIndex);
+ typedValueIndex++;
+ }
+ }
+
+ return typedValues;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Models/ConfigurationDtos/MediaEncoderPathDto.cs b/Jellyfin.Api/Models/ConfigurationDtos/MediaEncoderPathDto.cs
new file mode 100644
index 000000000..3b827ec12
--- /dev/null
+++ b/Jellyfin.Api/Models/ConfigurationDtos/MediaEncoderPathDto.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.ConfigurationDtos
+{
+ /// <summary>
+ /// Media Encoder Path Dto.
+ /// </summary>
+ public class MediaEncoderPathDto
+ {
+ /// <summary>
+ /// Gets or sets media encoder path.
+ /// </summary>
+ public string Path { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets media encoder path type.
+ /// </summary>
+ public string PathType { get; set; } = null!;
+ }
+}
diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs
new file mode 100644
index 000000000..ec4a0d1a1
--- /dev/null
+++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs
@@ -0,0 +1,67 @@
+using System;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+
+namespace Jellyfin.Api.Models
+{
+ /// <summary>
+ /// The configuration page info.
+ /// </summary>
+ public class ConfigurationPageInfo
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConfigurationPageInfo"/> class.
+ /// </summary>
+ /// <param name="plugin">Instance of <see cref="IPlugin"/> interface.</param>
+ /// <param name="page">Instance of <see cref="PluginPageInfo"/> interface.</param>
+ public ConfigurationPageInfo(IPlugin? plugin, PluginPageInfo page)
+ {
+ Name = page.Name;
+ EnableInMainMenu = page.EnableInMainMenu;
+ MenuSection = page.MenuSection;
+ MenuIcon = page.MenuIcon;
+ DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin?.Name : page.DisplayName;
+ PluginId = plugin?.Id;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConfigurationPageInfo"/> class.
+ /// </summary>
+ public ConfigurationPageInfo()
+ {
+ Name = string.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the configurations page is enabled in the main menu.
+ /// </summary>
+ public bool EnableInMainMenu { get; set; }
+
+ /// <summary>
+ /// Gets or sets the menu section.
+ /// </summary>
+ public string? MenuSection { get; set; }
+
+ /// <summary>
+ /// Gets or sets the menu icon.
+ /// </summary>
+ public string? MenuIcon { get; set; }
+
+ /// <summary>
+ /// Gets or sets the display name.
+ /// </summary>
+ public string? DisplayName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plugin id.
+ /// </summary>
+ /// <value>The plugin id.</value>
+ public Guid? PluginId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs b/Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs
new file mode 100644
index 000000000..249d828d3
--- /dev/null
+++ b/Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs
@@ -0,0 +1,106 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Api.Models.DisplayPreferencesDtos
+{
+ /// <summary>
+ /// Defines the display preferences for any item that supports them (usually Folders).
+ /// </summary>
+ public class DisplayPreferencesDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DisplayPreferencesDto" /> class.
+ /// </summary>
+ public DisplayPreferencesDto()
+ {
+ RememberIndexing = false;
+ PrimaryImageHeight = 250;
+ PrimaryImageWidth = 250;
+ ShowBackdrop = true;
+ CustomPrefs = new Dictionary<string, string>();
+ }
+
+ /// <summary>
+ /// Gets or sets the user id.
+ /// </summary>
+ /// <value>The user id.</value>
+ public string? Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the view.
+ /// </summary>
+ /// <value>The type of the view.</value>
+ public string? ViewType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sort by.
+ /// </summary>
+ /// <value>The sort by.</value>
+ public string? SortBy { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index by.
+ /// </summary>
+ /// <value>The index by.</value>
+ public string? IndexBy { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether [remember indexing].
+ /// </summary>
+ /// <value><c>true</c> if [remember indexing]; otherwise, <c>false</c>.</value>
+ public bool RememberIndexing { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height of the primary image.
+ /// </summary>
+ /// <value>The height of the primary image.</value>
+ public int PrimaryImageHeight { get; set; }
+
+ /// <summary>
+ /// Gets or sets the width of the primary image.
+ /// </summary>
+ /// <value>The width of the primary image.</value>
+ public int PrimaryImageWidth { get; set; }
+
+ /// <summary>
+ /// Gets the custom prefs.
+ /// </summary>
+ /// <value>The custom prefs.</value>
+ public Dictionary<string, string> CustomPrefs { get; }
+
+ /// <summary>
+ /// Gets or sets the scroll direction.
+ /// </summary>
+ /// <value>The scroll direction.</value>
+ public ScrollDirection ScrollDirection { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to show backdrops on this item.
+ /// </summary>
+ /// <value><c>true</c> if showing backdrops; otherwise, <c>false</c>.</value>
+ public bool ShowBackdrop { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether [remember sorting].
+ /// </summary>
+ /// <value><c>true</c> if [remember sorting]; otherwise, <c>false</c>.</value>
+ public bool RememberSorting { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sort order.
+ /// </summary>
+ /// <value>The sort order.</value>
+ public SortOrder SortOrder { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether [show sidebar].
+ /// </summary>
+ /// <value><c>true</c> if [show sidebar]; otherwise, <c>false</c>.</value>
+ public bool ShowSidebar { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client.
+ /// </summary>
+ public string? Client { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/EnvironmentDtos/DefaultDirectoryBrowserInfoDto.cs b/Jellyfin.Api/Models/EnvironmentDtos/DefaultDirectoryBrowserInfoDto.cs
new file mode 100644
index 000000000..92be15b8a
--- /dev/null
+++ b/Jellyfin.Api/Models/EnvironmentDtos/DefaultDirectoryBrowserInfoDto.cs
@@ -0,0 +1,13 @@
+namespace Jellyfin.Api.Models.EnvironmentDtos
+{
+ /// <summary>
+ /// Default directory browser info.
+ /// </summary>
+ public class DefaultDirectoryBrowserInfoDto
+ {
+ /// <summary>
+ /// Gets or sets the path.
+ /// </summary>
+ public string? Path { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/EnvironmentDtos/ValidatePathDto.cs b/Jellyfin.Api/Models/EnvironmentDtos/ValidatePathDto.cs
new file mode 100644
index 000000000..418c11c2d
--- /dev/null
+++ b/Jellyfin.Api/Models/EnvironmentDtos/ValidatePathDto.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Api.Models.EnvironmentDtos
+{
+ /// <summary>
+ /// Validate path object.
+ /// </summary>
+ public class ValidatePathDto
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether validate if path is writable.
+ /// </summary>
+ public bool ValidateWritable { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path.
+ /// </summary>
+ public string? Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets is path file.
+ /// </summary>
+ public bool? IsFile { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionInfoDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionInfoDto.cs
new file mode 100644
index 000000000..358434434
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionInfoDto.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+ /// <summary>
+ /// Library option info dto.
+ /// </summary>
+ public class LibraryOptionInfoDto
+ {
+ /// <summary>
+ /// Gets or sets name.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether default enabled.
+ /// </summary>
+ public bool DefaultEnabled { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs
new file mode 100644
index 000000000..7de44aa65
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs
@@ -0,0 +1,31 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+ /// <summary>
+ /// Library options result dto.
+ /// </summary>
+ public class LibraryOptionsResultDto
+ {
+ /// <summary>
+ /// Gets or sets the metadata savers.
+ /// </summary>
+ public IReadOnlyList<LibraryOptionInfoDto> MetadataSavers { get; set; } = Array.Empty<LibraryOptionInfoDto>();
+
+ /// <summary>
+ /// Gets or sets the metadata readers.
+ /// </summary>
+ public IReadOnlyList<LibraryOptionInfoDto> MetadataReaders { get; set; } = Array.Empty<LibraryOptionInfoDto>();
+
+ /// <summary>
+ /// Gets or sets the subtitle fetchers.
+ /// </summary>
+ public IReadOnlyList<LibraryOptionInfoDto> SubtitleFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>();
+
+ /// <summary>
+ /// Gets or sets the type options.
+ /// </summary>
+ public IReadOnlyList<LibraryTypeOptionsDto> TypeOptions { get; set; } = Array.Empty<LibraryTypeOptionsDto>();
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs
new file mode 100644
index 000000000..20f45196d
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+ /// <summary>
+ /// Library type options dto.
+ /// </summary>
+ public class LibraryTypeOptionsDto
+ {
+ /// <summary>
+ /// Gets or sets the type.
+ /// </summary>
+ public string? Type { get; set; }
+
+ /// <summary>
+ /// Gets or sets the metadata fetchers.
+ /// </summary>
+ public IReadOnlyList<LibraryOptionInfoDto> MetadataFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>();
+
+ /// <summary>
+ /// Gets or sets the image fetchers.
+ /// </summary>
+ public IReadOnlyList<LibraryOptionInfoDto> ImageFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>();
+
+ /// <summary>
+ /// Gets or sets the supported image types.
+ /// </summary>
+ public IReadOnlyList<ImageType> SupportedImageTypes { get; set; } = Array.Empty<ImageType>();
+
+ /// <summary>
+ /// Gets or sets the default image options.
+ /// </summary>
+ public IReadOnlyList<ImageOption> DefaultImageOptions { get; set; } = Array.Empty<ImageOption>();
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs
new file mode 100644
index 000000000..f93638898
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs
@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+ /// <summary>
+ /// Media Update Info Dto.
+ /// </summary>
+ public class MediaUpdateInfoDto
+ {
+ /// <summary>
+ /// Gets or sets the list of updates.
+ /// </summary>
+ public IReadOnlyList<MediaUpdateInfoPathDto> Updates { get; set; } = Array.Empty<MediaUpdateInfoPathDto>();
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs
new file mode 100644
index 000000000..852315b92
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs
@@ -0,0 +1,19 @@
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+ /// <summary>
+ /// The media update info path.
+ /// </summary>
+ public class MediaUpdateInfoPathDto
+ {
+ /// <summary>
+ /// Gets or sets media path.
+ /// </summary>
+ public string? Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets media update type.
+ /// Created, Modified, Deleted.
+ /// </summary>
+ public string? UpdateType { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryStructureDto/AddVirtualFolderDto.cs b/Jellyfin.Api/Models/LibraryStructureDto/AddVirtualFolderDto.cs
new file mode 100644
index 000000000..ab68d5223
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryStructureDto/AddVirtualFolderDto.cs
@@ -0,0 +1,15 @@
+using MediaBrowser.Model.Configuration;
+
+namespace Jellyfin.Api.Models.LibraryStructureDto
+{
+ /// <summary>
+ /// Add virtual folder dto.
+ /// </summary>
+ public class AddVirtualFolderDto
+ {
+ /// <summary>
+ /// Gets or sets library options.
+ /// </summary>
+ public LibraryOptions? LibraryOptions { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryStructureDto/MediaPathDto.cs b/Jellyfin.Api/Models/LibraryStructureDto/MediaPathDto.cs
new file mode 100644
index 000000000..f65988259
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryStructureDto/MediaPathDto.cs
@@ -0,0 +1,27 @@
+using System.ComponentModel.DataAnnotations;
+using MediaBrowser.Model.Configuration;
+
+namespace Jellyfin.Api.Models.LibraryStructureDto
+{
+ /// <summary>
+ /// Media Path dto.
+ /// </summary>
+ public class MediaPathDto
+ {
+ /// <summary>
+ /// Gets or sets the name of the library.
+ /// </summary>
+ [Required]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path to add.
+ /// </summary>
+ public string? Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path info.
+ /// </summary>
+ public MediaPathInfo? PathInfo { get; set; }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Api/Models/LibraryStructureDto/UpdateLibraryOptionsDto.cs b/Jellyfin.Api/Models/LibraryStructureDto/UpdateLibraryOptionsDto.cs
new file mode 100644
index 000000000..c78ed51f7
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryStructureDto/UpdateLibraryOptionsDto.cs
@@ -0,0 +1,21 @@
+using System;
+using MediaBrowser.Model.Configuration;
+
+namespace Jellyfin.Api.Models.LibraryStructureDto
+{
+ /// <summary>
+ /// Update library options dto.
+ /// </summary>
+ public class UpdateLibraryOptionsDto
+ {
+ /// <summary>
+ /// Gets or sets the library item id.
+ /// </summary>
+ public Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets library options.
+ /// </summary>
+ public LibraryOptions? LibraryOptions { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs b/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs
new file mode 100644
index 000000000..fbd4985f9
--- /dev/null
+++ b/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs
@@ -0,0 +1,23 @@
+using System.ComponentModel.DataAnnotations;
+using MediaBrowser.Model.Configuration;
+
+namespace Jellyfin.Api.Models.LibraryStructureDto
+{
+ /// <summary>
+ /// Update library options dto.
+ /// </summary>
+ public class UpdateMediaPathRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the library name.
+ /// </summary>
+ [Required]
+ public string Name { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets library folder path information.
+ /// </summary>
+ [Required]
+ public MediaPathInfo PathInfo { get; set; } = null!;
+ }
+}
diff --git a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
new file mode 100644
index 000000000..f43822da7
--- /dev/null
+++ b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Dto;
+
+namespace Jellyfin.Api.Models.LiveTvDtos
+{
+ /// <summary>
+ /// Channel mapping options dto.
+ /// </summary>
+ public class ChannelMappingOptionsDto
+ {
+ /// <summary>
+ /// Gets or sets list of tuner channels.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA2227:ReadOnlyRemoveSetter", MessageId = "TunerChannels", Justification = "Imported from ServiceStack")]
+ public List<TunerChannelMapping> TunerChannels { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets list of provider channels.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA2227:ReadOnlyRemoveSetter", MessageId = "ProviderChannels", Justification = "Imported from ServiceStack")]
+ public List<NameIdPair> ProviderChannels { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets list of mappings.
+ /// </summary>
+ public IReadOnlyList<NameValuePair> Mappings { get; set; } = Array.Empty<NameValuePair>();
+
+ /// <summary>
+ /// Gets or sets provider name.
+ /// </summary>
+ public string? ProviderName { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs
new file mode 100644
index 000000000..411e4c550
--- /dev/null
+++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs
@@ -0,0 +1,179 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json.Converters;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
+
+namespace Jellyfin.Api.Models.LiveTvDtos
+{
+ /// <summary>
+ /// Get programs dto.
+ /// </summary>
+ public class GetProgramsDto
+ {
+ /// <summary>
+ /// Gets or sets the channels to return guide information for.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<Guid> ChannelIds { get; set; } = Array.Empty<Guid>();
+
+ /// <summary>
+ /// Gets or sets optional. Filter by user id.
+ /// </summary>
+ public Guid UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum premiere start date.
+ /// Optional.
+ /// </summary>
+ public DateTime? MinStartDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter by programs that have completed airing, or not.
+ /// Optional.
+ /// </summary>
+ public bool? HasAired { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter by programs that are currently airing, or not.
+ /// Optional.
+ /// </summary>
+ public bool? IsAiring { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum premiere start date.
+ /// Optional.
+ /// </summary>
+ public DateTime? MaxStartDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum premiere end date.
+ /// Optional.
+ /// </summary>
+ public DateTime? MinEndDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum premiere end date.
+ /// Optional.
+ /// </summary>
+ public DateTime? MaxEndDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter for movies.
+ /// Optional.
+ /// </summary>
+ public bool? IsMovie { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter for series.
+ /// Optional.
+ /// </summary>
+ public bool? IsSeries { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter for news.
+ /// Optional.
+ /// </summary>
+ public bool? IsNews { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter for kids.
+ /// Optional.
+ /// </summary>
+ public bool? IsKids { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter for sports.
+ /// Optional.
+ /// </summary>
+ public bool? IsSports { get; set; }
+
+ /// <summary>
+ /// Gets or sets the record index to start at. All items with a lower index will be dropped from the results.
+ /// Optional.
+ /// </summary>
+ public int? StartIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum number of records to return.
+ /// Optional.
+ /// </summary>
+ public int? Limit { get; set; }
+
+ /// <summary>
+ /// Gets or sets specify one or more sort orders, comma delimited. Options: Name, StartDate.
+ /// Optional.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<string> SortBy { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets sort Order - Ascending,Descending.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<SortOrder> SortOrder { get; set; } = Array.Empty<SortOrder>();
+
+ /// <summary>
+ /// Gets or sets the genres to return guide information for.
+ /// </summary>
+ [JsonConverter(typeof(JsonPipeDelimitedArrayConverterFactory))]
+ public IReadOnlyList<string> Genres { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the genre ids to return guide information for.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<Guid> GenreIds { get; set; } = Array.Empty<Guid>();
+
+ /// <summary>
+ /// Gets or sets include image information in output.
+ /// Optional.
+ /// </summary>
+ public bool? EnableImages { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether retrieve total record count.
+ /// </summary>
+ public bool EnableTotalRecordCount { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the max number of images to return, per image type.
+ /// Optional.
+ /// </summary>
+ public int? ImageTypeLimit { get; set; }
+
+ /// <summary>
+ /// Gets or sets the image types to include in the output.
+ /// Optional.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<ImageType> EnableImageTypes { get; set; } = Array.Empty<ImageType>();
+
+ /// <summary>
+ /// Gets or sets include user data.
+ /// Optional.
+ /// </summary>
+ public bool? EnableUserData { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter by series timer id.
+ /// Optional.
+ /// </summary>
+ public string? SeriesTimerId { get; set; }
+
+ /// <summary>
+ /// Gets or sets filter by library series id.
+ /// Optional.
+ /// </summary>
+ public Guid LibrarySeriesId { get; set; }
+
+ /// <summary>
+ /// Gets or sets specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.
+ /// Optional.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<ItemFields> Fields { get; set; } = Array.Empty<ItemFields>();
+ }
+}
diff --git a/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs b/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs
new file mode 100644
index 000000000..2ddaa89e8
--- /dev/null
+++ b/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs
@@ -0,0 +1,28 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.LiveTvDtos
+{
+ /// <summary>
+ /// Set channel mapping dto.
+ /// </summary>
+ public class SetChannelMappingDto
+ {
+ /// <summary>
+ /// Gets or sets the provider id.
+ /// </summary>
+ [Required]
+ public string ProviderId { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the tuner channel id.
+ /// </summary>
+ [Required]
+ public string TunerChannelId { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the provider channel id.
+ /// </summary>
+ [Required]
+ public string ProviderChannelId { get; set; } = string.Empty;
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs
new file mode 100644
index 000000000..704542326
--- /dev/null
+++ b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.MediaInfo;
+
+namespace Jellyfin.Api.Models.MediaInfoDtos
+{
+ /// <summary>
+ /// Open live stream dto.
+ /// </summary>
+ public class OpenLiveStreamDto
+ {
+ /// <summary>
+ /// Gets or sets the open token.
+ /// </summary>
+ public string? OpenToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user id.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the play session id.
+ /// </summary>
+ public string? PlaySessionId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the max streaming bitrate.
+ /// </summary>
+ public int? MaxStreamingBitrate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start time in ticks.
+ /// </summary>
+ public long? StartTimeTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio stream index.
+ /// </summary>
+ public int? AudioStreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subtitle stream index.
+ /// </summary>
+ public int? SubtitleStreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the max audio channels.
+ /// </summary>
+ public int? MaxAudioChannels { get; set; }
+
+ /// <summary>
+ /// Gets or sets the item id.
+ /// </summary>
+ public Guid? ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable direct play.
+ /// </summary>
+ public bool? EnableDirectPlay { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enale direct stream.
+ /// </summary>
+ public bool? EnableDirectStream { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device profile.
+ /// </summary>
+ public DeviceProfile? DeviceProfile { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device play protocols.
+ /// </summary>
+ public IReadOnlyList<MediaProtocol> DirectPlayProtocols { get; set; } = Array.Empty<MediaProtocol>();
+ }
+}
diff --git a/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs
new file mode 100644
index 000000000..2cfdba507
--- /dev/null
+++ b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs
@@ -0,0 +1,86 @@
+using System;
+using MediaBrowser.Model.Dlna;
+
+namespace Jellyfin.Api.Models.MediaInfoDtos
+{
+ /// <summary>
+ /// Plabyback info dto.
+ /// </summary>
+ public class PlaybackInfoDto
+ {
+ /// <summary>
+ /// Gets or sets the playback userId.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the max streaming bitrate.
+ /// </summary>
+ public int? MaxStreamingBitrate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start time in ticks.
+ /// </summary>
+ public long? StartTimeTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio stream index.
+ /// </summary>
+ public int? AudioStreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subtitle stream index.
+ /// </summary>
+ public int? SubtitleStreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the max audio channels.
+ /// </summary>
+ public int? MaxAudioChannels { get; set; }
+
+ /// <summary>
+ /// Gets or sets the media source id.
+ /// </summary>
+ public string? MediaSourceId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the live stream id.
+ /// </summary>
+ public string? LiveStreamId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device profile.
+ /// </summary>
+ public DeviceProfile? DeviceProfile { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable direct play.
+ /// </summary>
+ public bool? EnableDirectPlay { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable direct stream.
+ /// </summary>
+ public bool? EnableDirectStream { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable transcoding.
+ /// </summary>
+ public bool? EnableTranscoding { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable video stream copy.
+ /// </summary>
+ public bool? AllowVideoStreamCopy { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to allow audio stream copy.
+ /// </summary>
+ public bool? AllowAudioStreamCopy { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to auto open the live stream.
+ /// </summary>
+ public bool? AutoOpenLiveStream { get; set; }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs
new file mode 100644
index 000000000..2c3a6282f
--- /dev/null
+++ b/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs
@@ -0,0 +1,30 @@
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Api.Models.NotificationDtos
+{
+ /// <summary>
+ /// The admin notification dto.
+ /// </summary>
+ public class AdminNotificationDto
+ {
+ /// <summary>
+ /// Gets or sets the notification name.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the notification description.
+ /// </summary>
+ public string? Description { get; set; }
+
+ /// <summary>
+ /// Gets or sets the notification level.
+ /// </summary>
+ public NotificationLevel? NotificationLevel { get; set; }
+
+ /// <summary>
+ /// Gets or sets the notification url.
+ /// </summary>
+ public string? Url { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs
new file mode 100644
index 000000000..af5239ec2
--- /dev/null
+++ b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs
@@ -0,0 +1,51 @@
+using System;
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Api.Models.NotificationDtos
+{
+ /// <summary>
+ /// The notification DTO.
+ /// </summary>
+ public class NotificationDto
+ {
+ /// <summary>
+ /// Gets or sets the notification ID. Defaults to an empty string.
+ /// </summary>
+ public string Id { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the notification's user ID. Defaults to an empty string.
+ /// </summary>
+ public string UserId { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the notification date.
+ /// </summary>
+ public DateTime Date { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the notification has been read. Defaults to false.
+ /// </summary>
+ public bool IsRead { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets the notification's name. Defaults to an empty string.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the notification's description. Defaults to an empty string.
+ /// </summary>
+ public string Description { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the notification's URL. Defaults to an empty string.
+ /// </summary>
+ public string Url { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the notification level.
+ /// </summary>
+ public NotificationLevel Level { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs
new file mode 100644
index 000000000..64e92bd83
--- /dev/null
+++ b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Api.Models.NotificationDtos
+{
+ /// <summary>
+ /// A list of notifications with the total record count for pagination.
+ /// </summary>
+ public class NotificationResultDto
+ {
+ /// <summary>
+ /// Gets or sets the current page of notifications.
+ /// </summary>
+ public IReadOnlyList<NotificationDto> Notifications { get; set; } = Array.Empty<NotificationDto>();
+
+ /// <summary>
+ /// Gets or sets the total number of notifications.
+ /// </summary>
+ public int TotalRecordCount { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs
new file mode 100644
index 000000000..0568dea66
--- /dev/null
+++ b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs
@@ -0,0 +1,20 @@
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Api.Models.NotificationDtos
+{
+ /// <summary>
+ /// The notification summary DTO.
+ /// </summary>
+ public class NotificationsSummaryDto
+ {
+ /// <summary>
+ /// Gets or sets the number of unread notifications.
+ /// </summary>
+ public int UnreadCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum unread notification level.
+ /// </summary>
+ public NotificationLevel? MaxUnreadNotificationLevel { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
new file mode 100644
index 000000000..fed837b85
--- /dev/null
+++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
@@ -0,0 +1,284 @@
+using System;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Dto;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Models.PlaybackDtos
+{
+ /// <summary>
+ /// Class TranscodingJob.
+ /// </summary>
+ public class TranscodingJobDto : IDisposable
+ {
+ /// <summary>
+ /// The process lock.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA1051:NoVisibleInstanceFields", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "SA1401:PrivateField", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
+ public readonly object ProcessLock = new object();
+
+ /// <summary>
+ /// Timer lock.
+ /// </summary>
+ private readonly object _timerLock = new object();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TranscodingJobDto"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobDto}"/> interface.</param>
+ public TranscodingJobDto(ILogger<TranscodingJobDto> logger)
+ {
+ Logger = logger;
+ }
+
+ /// <summary>
+ /// Gets or sets the play session identifier.
+ /// </summary>
+ /// <value>The play session identifier.</value>
+ public string? PlaySessionId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the live stream identifier.
+ /// </summary>
+ /// <value>The live stream identifier.</value>
+ public string? LiveStreamId { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether is live output.
+ /// </summary>
+ public bool IsLiveOutput { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path.
+ /// </summary>
+ /// <value>The path.</value>
+ public MediaSourceInfo? MediaSource { get; set; }
+
+ /// <summary>
+ /// Gets or sets path.
+ /// </summary>
+ public string? Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type.
+ /// </summary>
+ /// <value>The type.</value>
+ public TranscodingJobType Type { get; set; }
+
+ /// <summary>
+ /// Gets or sets the process.
+ /// </summary>
+ /// <value>The process.</value>
+ public Process? Process { get; set; }
+
+ /// <summary>
+ /// Gets logger.
+ /// </summary>
+ public ILogger<TranscodingJobDto> Logger { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the active request count.
+ /// </summary>
+ /// <value>The active request count.</value>
+ public int ActiveRequestCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the kill timer.
+ /// </summary>
+ /// <value>The kill timer.</value>
+ private Timer? KillTimer { get; set; }
+
+ /// <summary>
+ /// Gets or sets device id.
+ /// </summary>
+ public string? DeviceId { get; set; }
+
+ /// <summary>
+ /// Gets or sets cancellation token source.
+ /// </summary>
+ public CancellationTokenSource? CancellationTokenSource { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether has exited.
+ /// </summary>
+ public bool HasExited { get; set; }
+
+ /// <summary>
+ /// Gets or sets exit code.
+ /// </summary>
+ public int ExitCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether is user paused.
+ /// </summary>
+ public bool IsUserPaused { get; set; }
+
+ /// <summary>
+ /// Gets or sets id.
+ /// </summary>
+ public string? Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets framerate.
+ /// </summary>
+ public float? Framerate { get; set; }
+
+ /// <summary>
+ /// Gets or sets completion percentage.
+ /// </summary>
+ public double? CompletionPercentage { get; set; }
+
+ /// <summary>
+ /// Gets or sets bytes downloaded.
+ /// </summary>
+ public long? BytesDownloaded { get; set; }
+
+ /// <summary>
+ /// Gets or sets bytes transcoded.
+ /// </summary>
+ public long? BytesTranscoded { get; set; }
+
+ /// <summary>
+ /// Gets or sets bit rate.
+ /// </summary>
+ public int? BitRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets transcoding position ticks.
+ /// </summary>
+ public long? TranscodingPositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets download position ticks.
+ /// </summary>
+ public long? DownloadPositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets transcoding throttler.
+ /// </summary>
+ public TranscodingThrottler? TranscodingThrottler { get; set; }
+
+ /// <summary>
+ /// Gets or sets last ping date.
+ /// </summary>
+ public DateTime LastPingDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets ping timeout.
+ /// </summary>
+ public int PingTimeout { get; set; }
+
+ /// <summary>
+ /// Stop kill timer.
+ /// </summary>
+ public void StopKillTimer()
+ {
+ lock (_timerLock)
+ {
+ KillTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+ }
+ }
+
+ /// <summary>
+ /// Dispose kill timer.
+ /// </summary>
+ public void DisposeKillTimer()
+ {
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ KillTimer.Dispose();
+ KillTimer = null;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Start kill timer.
+ /// </summary>
+ /// <param name="callback">Callback action.</param>
+ public void StartKillTimer(Action<object?> callback)
+ {
+ StartKillTimer(callback, PingTimeout);
+ }
+
+ /// <summary>
+ /// Start kill timer.
+ /// </summary>
+ /// <param name="callback">Callback action.</param>
+ /// <param name="intervalMs">Callback interval.</param>
+ public void StartKillTimer(Action<object?> callback, int intervalMs)
+ {
+ if (HasExited)
+ {
+ return;
+ }
+
+ lock (_timerLock)
+ {
+ if (KillTimer == null)
+ {
+ Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer = new Timer(new TimerCallback(callback), this, intervalMs, Timeout.Infinite);
+ }
+ else
+ {
+ Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer.Change(intervalMs, Timeout.Infinite);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Change kill timer if started.
+ /// </summary>
+ public void ChangeKillTimerIfStarted()
+ {
+ if (HasExited)
+ {
+ return;
+ }
+
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ var intervalMs = PingTimeout;
+
+ Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer.Change(intervalMs, Timeout.Infinite);
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Dispose all resources.
+ /// </summary>
+ /// <param name="disposing">Whether to dispose all resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ Process?.Dispose();
+ Process = null;
+ KillTimer?.Dispose();
+ KillTimer = null;
+ CancellationTokenSource?.Dispose();
+ CancellationTokenSource = null;
+ TranscodingThrottler?.Dispose();
+ TranscodingThrottler = null;
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Api/Playback/TranscodingThrottler.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs
index 0e73d77ef..7b32d76ba 100644
--- a/MediaBrowser.Api/Playback/TranscodingThrottler.cs
+++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
@@ -6,18 +6,28 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Api.Playback
+namespace Jellyfin.Api.Models.PlaybackDtos
{
+ /// <summary>
+ /// Transcoding throttler.
+ /// </summary>
public class TranscodingThrottler : IDisposable
{
- private readonly TranscodingJob _job;
- private readonly ILogger _logger;
- private Timer _timer;
- private bool _isPaused;
+ private readonly TranscodingJobDto _job;
+ private readonly ILogger<TranscodingThrottler> _logger;
private readonly IConfigurationManager _config;
private readonly IFileSystem _fileSystem;
+ private Timer? _timer;
+ private bool _isPaused;
- public TranscodingThrottler(TranscodingJob job, ILogger logger, IConfigurationManager config, IFileSystem fileSystem)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TranscodingThrottler"/> class.
+ /// </summary>
+ /// <param name="job">Transcoding job dto.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{TranscodingThrottler}"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ public TranscodingThrottler(TranscodingJobDto job, ILogger<TranscodingThrottler> logger, IConfigurationManager config, IFileSystem fileSystem)
{
_job = job;
_logger = logger;
@@ -25,17 +35,73 @@ namespace MediaBrowser.Api.Playback
_fileSystem = fileSystem;
}
- private EncodingOptions GetOptions()
+ /// <summary>
+ /// Start timer.
+ /// </summary>
+ public void Start()
{
- return _config.GetConfiguration<EncodingOptions>("encoding");
+ _timer = new Timer(TimerCallback, null, 5000, 5000);
}
- public void Start()
+ /// <summary>
+ /// Unpause transcoding.
+ /// </summary>
+ /// <returns>A <see cref="Task"/>.</returns>
+ public async Task UnpauseTranscoding()
{
- _timer = new Timer(TimerCallback, null, 5000, 5000);
+ if (_isPaused)
+ {
+ _logger.LogDebug("Sending resume command to ffmpeg");
+
+ try
+ {
+ await _job.Process!.StandardInput.WriteLineAsync().ConfigureAwait(false);
+ _isPaused = false;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error resuming transcoding");
+ }
+ }
+ }
+
+ /// <summary>
+ /// Stop throttler.
+ /// </summary>
+ /// <returns>A <see cref="Task"/>.</returns>
+ public async Task Stop()
+ {
+ DisposeTimer();
+ await UnpauseTranscoding().ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Dispose throttler.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Dispose throttler.
+ /// </summary>
+ /// <param name="disposing">Disposing.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ DisposeTimer();
+ }
}
- private async void TimerCallback(object state)
+ private EncodingOptions GetOptions()
+ {
+ return _config.GetEncodingOptions();
+ }
+
+ private async void TimerCallback(object? state)
{
if (_job.HasExited)
{
@@ -47,11 +113,11 @@ namespace MediaBrowser.Api.Playback
if (options.EnableThrottling && IsThrottleAllowed(_job, options.ThrottleDelaySeconds))
{
- await PauseTranscoding();
+ await PauseTranscoding().ConfigureAwait(false);
}
else
{
- await UnpauseTranscoding();
+ await UnpauseTranscoding().ConfigureAwait(false);
}
}
@@ -63,7 +129,7 @@ namespace MediaBrowser.Api.Playback
try
{
- await _job.Process.StandardInput.WriteAsync("c");
+ await _job.Process!.StandardInput.WriteAsync("c").ConfigureAwait(false);
_isPaused = true;
}
catch (Exception ex)
@@ -73,31 +139,14 @@ namespace MediaBrowser.Api.Playback
}
}
- public async Task UnpauseTranscoding()
- {
- if (_isPaused)
- {
- _logger.LogDebug("Sending resume command to ffmpeg");
-
- try
- {
- await _job.Process.StandardInput.WriteLineAsync();
- _isPaused = false;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error resuming transcoding");
- }
- }
- }
-
- private bool IsThrottleAllowed(TranscodingJob job, int thresholdSeconds)
+ private bool IsThrottleAllowed(TranscodingJobDto job, int thresholdSeconds)
{
var bytesDownloaded = job.BytesDownloaded ?? 0;
var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
var downloadPositionTicks = job.DownloadPositionTicks ?? 0;
- var path = job.Path;
+ var path = job.Path ?? throw new ArgumentException("Path can't be null.");
+
var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks;
if (downloadPositionTicks > 0 && transcodingPositionTicks > 0)
@@ -152,17 +201,6 @@ namespace MediaBrowser.Api.Playback
return false;
}
- public async Task Stop()
- {
- DisposeTimer();
- await UnpauseTranscoding();
- }
-
- public void Dispose()
- {
- DisposeTimer();
- }
-
private void DisposeTimer()
{
if (_timer != null)
diff --git a/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs
new file mode 100644
index 000000000..0761b2085
--- /dev/null
+++ b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+
+namespace Jellyfin.Api.Models.PlaylistDtos
+{
+ /// <summary>
+ /// Create new playlist dto.
+ /// </summary>
+ public class CreatePlaylistDto
+ {
+ /// <summary>
+ /// Gets or sets the name of the new playlist.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets item ids to add to the playlist.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<Guid> Ids { get; set; } = Array.Empty<Guid>();
+
+ /// <summary>
+ /// Gets or sets the user id.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the media type.
+ /// </summary>
+ public string? MediaType { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/PluginDtos/MBRegistrationRecord.cs b/Jellyfin.Api/Models/PluginDtos/MBRegistrationRecord.cs
new file mode 100644
index 000000000..7f1255f4b
--- /dev/null
+++ b/Jellyfin.Api/Models/PluginDtos/MBRegistrationRecord.cs
@@ -0,0 +1,40 @@
+using System;
+
+namespace Jellyfin.Api.Models.PluginDtos
+{
+ /// <summary>
+ /// MB Registration Record.
+ /// </summary>
+ public class MBRegistrationRecord
+ {
+ /// <summary>
+ /// Gets or sets expiration date.
+ /// </summary>
+ public DateTime ExpirationDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether is registered.
+ /// </summary>
+ public bool IsRegistered { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether reg checked.
+ /// </summary>
+ public bool RegChecked { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether reg error.
+ /// </summary>
+ public bool RegError { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether trial version.
+ /// </summary>
+ public bool TrialVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether is valid.
+ /// </summary>
+ public bool IsValid { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/PluginDtos/PluginSecurityInfo.cs b/Jellyfin.Api/Models/PluginDtos/PluginSecurityInfo.cs
new file mode 100644
index 000000000..a90398425
--- /dev/null
+++ b/Jellyfin.Api/Models/PluginDtos/PluginSecurityInfo.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.PluginDtos
+{
+ /// <summary>
+ /// Plugin security info.
+ /// </summary>
+ public class PluginSecurityInfo
+ {
+ /// <summary>
+ /// Gets or sets the supporter key.
+ /// </summary>
+ public string? SupporterKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether is mb supporter.
+ /// </summary>
+ public bool IsMbSupporter { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs
new file mode 100644
index 000000000..fa62472e1
--- /dev/null
+++ b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Api.Models.SessionDtos
+{
+ /// <summary>
+ /// Client capabilities dto.
+ /// </summary>
+ public class ClientCapabilitiesDto
+ {
+ /// <summary>
+ /// Gets or sets the list of playable media types.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<string> PlayableMediaTypes { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the list of supported commands.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<GeneralCommandType> SupportedCommands { get; set; } = Array.Empty<GeneralCommandType>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether session supports media control.
+ /// </summary>
+ public bool SupportsMediaControl { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether session supports content uploading.
+ /// </summary>
+ public bool SupportsContentUploading { get; set; }
+
+ /// <summary>
+ /// Gets or sets the message callback url.
+ /// </summary>
+ public string? MessageCallbackUrl { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether session supports a persistent identifier.
+ /// </summary>
+ public bool SupportsPersistentIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether session supports sync.
+ /// </summary>
+ public bool SupportsSync { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device profile.
+ /// </summary>
+ public DeviceProfile? DeviceProfile { get; set; }
+
+ /// <summary>
+ /// Gets or sets the app store url.
+ /// </summary>
+ public string? AppStoreUrl { get; set; }
+
+ /// <summary>
+ /// Gets or sets the icon url.
+ /// </summary>
+ public string? IconUrl { get; set; }
+
+ /// <summary>
+ /// Convert the dto to the full <see cref="ClientCapabilities"/> model.
+ /// </summary>
+ /// <returns>The converted <see cref="ClientCapabilities"/> model.</returns>
+ public ClientCapabilities ToClientCapabilities()
+ {
+ return new ClientCapabilities
+ {
+ PlayableMediaTypes = PlayableMediaTypes,
+ SupportedCommands = SupportedCommands,
+ SupportsMediaControl = SupportsMediaControl,
+ SupportsContentUploading = SupportsContentUploading,
+ MessageCallbackUrl = MessageCallbackUrl,
+ SupportsPersistentIdentifier = SupportsPersistentIdentifier,
+ SupportsSync = SupportsSync,
+ DeviceProfile = DeviceProfile,
+ AppStoreUrl = AppStoreUrl,
+ IconUrl = IconUrl
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs
new file mode 100644
index 000000000..a5f012245
--- /dev/null
+++ b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Api.Models.StartupDtos
+{
+ /// <summary>
+ /// The startup configuration DTO.
+ /// </summary>
+ public class StartupConfigurationDto
+ {
+ /// <summary>
+ /// Gets or sets UI language culture.
+ /// </summary>
+ public string? UICulture { get; set; }
+
+ /// <summary>
+ /// Gets or sets the metadata country code.
+ /// </summary>
+ public string? MetadataCountryCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the preferred language for the metadata.
+ /// </summary>
+ public string? PreferredMetadataLanguage { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StartupDtos/StartupRemoteAccessDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupRemoteAccessDto.cs
new file mode 100644
index 000000000..4027ba41a
--- /dev/null
+++ b/Jellyfin.Api/Models/StartupDtos/StartupRemoteAccessDto.cs
@@ -0,0 +1,22 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.StartupDtos
+{
+ /// <summary>
+ /// Startup remote access dto.
+ /// </summary>
+ public class StartupRemoteAccessDto
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether enable remote access.
+ /// </summary>
+ [Required]
+ public bool EnableRemoteAccess { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether enable automatic port mapping.
+ /// </summary>
+ [Required]
+ public bool EnableAutomaticPortMapping { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs
new file mode 100644
index 000000000..e4c973548
--- /dev/null
+++ b/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.StartupDtos
+{
+ /// <summary>
+ /// The startup user DTO.
+ /// </summary>
+ public class StartupUserDto
+ {
+ /// <summary>
+ /// Gets or sets the username.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ public string? Password { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StreamingDtos/HlsAudioRequestDto.cs b/Jellyfin.Api/Models/StreamingDtos/HlsAudioRequestDto.cs
new file mode 100644
index 000000000..3791fadbe
--- /dev/null
+++ b/Jellyfin.Api/Models/StreamingDtos/HlsAudioRequestDto.cs
@@ -0,0 +1,13 @@
+namespace Jellyfin.Api.Models.StreamingDtos
+{
+ /// <summary>
+ /// The hls video request dto.
+ /// </summary>
+ public class HlsAudioRequestDto : StreamingRequestDto
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether enable adaptive bitrate streaming.
+ /// </summary>
+ public bool EnableAdaptiveBitrateStreaming { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StreamingDtos/HlsVideoRequestDto.cs b/Jellyfin.Api/Models/StreamingDtos/HlsVideoRequestDto.cs
new file mode 100644
index 000000000..7a4be091b
--- /dev/null
+++ b/Jellyfin.Api/Models/StreamingDtos/HlsVideoRequestDto.cs
@@ -0,0 +1,13 @@
+namespace Jellyfin.Api.Models.StreamingDtos
+{
+ /// <summary>
+ /// The hls video request dto.
+ /// </summary>
+ public class HlsVideoRequestDto : VideoRequestDto
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether enable adaptive bitrate streaming.
+ /// </summary>
+ public bool EnableAdaptiveBitrateStreaming { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StreamingDtos/StreamState.cs b/Jellyfin.Api/Models/StreamingDtos/StreamState.cs
new file mode 100644
index 000000000..cbabf087b
--- /dev/null
+++ b/Jellyfin.Api/Models/StreamingDtos/StreamState.cs
@@ -0,0 +1,204 @@
+using System;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.PlaybackDtos;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Dlna;
+
+namespace Jellyfin.Api.Models.StreamingDtos
+{
+ /// <summary>
+ /// The stream state dto.
+ /// </summary>
+ public class StreamState : EncodingJobInfo, IDisposable
+ {
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private bool _disposed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StreamState" /> class.
+ /// </summary>
+ /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager" /> interface.</param>
+ /// <param name="transcodingType">The <see cref="TranscodingJobType" />.</param>
+ /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper" /> singleton.</param>
+ public StreamState(IMediaSourceManager mediaSourceManager, TranscodingJobType transcodingType, TranscodingJobHelper transcodingJobHelper)
+ : base(transcodingType)
+ {
+ _mediaSourceManager = mediaSourceManager;
+ _transcodingJobHelper = transcodingJobHelper;
+ }
+
+ /// <summary>
+ /// Gets or sets the requested url.
+ /// </summary>
+ public string? RequestedUrl { get; set; }
+
+ /// <summary>
+ /// Gets or sets the request.
+ /// </summary>
+ public StreamingRequestDto Request
+ {
+ get => (StreamingRequestDto)BaseRequest;
+ set
+ {
+ BaseRequest = value;
+ IsVideoRequest = VideoRequest != null;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the transcoding throttler.
+ /// </summary>
+ public TranscodingThrottler? TranscodingThrottler { get; set; }
+
+ /// <summary>
+ /// Gets the video request.
+ /// </summary>
+ public VideoRequestDto? VideoRequest => Request as VideoRequestDto;
+
+ /// <summary>
+ /// Gets or sets the direct stream provicer.
+ /// </summary>
+ /// <remarks>
+ /// Deprecated.
+ /// </remarks>
+ public IDirectStreamProvider? DirectStreamProvider { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path to wait for.
+ /// </summary>
+ public string? WaitForPath { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the request outputs video.
+ /// </summary>
+ public bool IsOutputVideo => Request is VideoRequestDto;
+
+ /// <summary>
+ /// Gets the segment length.
+ /// </summary>
+ public int SegmentLength
+ {
+ get
+ {
+ if (Request.SegmentLength.HasValue)
+ {
+ return Request.SegmentLength.Value;
+ }
+
+ if (EncodingHelper.IsCopyCodec(OutputVideoCodec))
+ {
+ var userAgent = UserAgent ?? string.Empty;
+
+ if (userAgent.IndexOf("AppleTV", StringComparison.OrdinalIgnoreCase) != -1
+ || userAgent.IndexOf("cfnetwork", StringComparison.OrdinalIgnoreCase) != -1
+ || userAgent.IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1
+ || userAgent.IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1
+ || userAgent.IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ return 6;
+ }
+
+ if (IsSegmentedLiveStream)
+ {
+ return 3;
+ }
+
+ return 6;
+ }
+
+ return 3;
+ }
+ }
+
+ /// <summary>
+ /// Gets the minimum number of segments.
+ /// </summary>
+ public int MinSegments
+ {
+ get
+ {
+ if (Request.MinSegments.HasValue)
+ {
+ return Request.MinSegments.Value;
+ }
+
+ return SegmentLength >= 10 ? 2 : 3;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the user agent.
+ /// </summary>
+ public string? UserAgent { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to estimate the content length.
+ /// </summary>
+ public bool EstimateContentLength { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transcode seek info.
+ /// </summary>
+ public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable dlna headers.
+ /// </summary>
+ public bool EnableDlnaHeaders { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device profile.
+ /// </summary>
+ public DeviceProfile? DeviceProfile { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transcoding job.
+ /// </summary>
+ public TranscodingJobDto? TranscodingJob { get; set; }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <inheritdoc />
+ public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
+ {
+ _transcodingJobHelper.ReportTranscodingProgress(TranscodingJob!, this, transcodingPosition, framerate, percentComplete, bytesTranscoded, bitRate);
+ }
+
+ /// <summary>
+ /// Disposes the stream state.
+ /// </summary>
+ /// <param name="disposing">Whether the object is currently beeing disposed.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
+ {
+ // REVIEW: Is this the right place for this?
+ if (MediaSource.RequiresClosing
+ && string.IsNullOrWhiteSpace(Request.LiveStreamId)
+ && !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
+ {
+ _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).GetAwaiter().GetResult();
+ }
+
+ TranscodingThrottler?.Dispose();
+ }
+
+ TranscodingThrottler = null;
+ TranscodingJob = null;
+
+ _disposed = true;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Models/StreamingDtos/StreamingRequestDto.cs b/Jellyfin.Api/Models/StreamingDtos/StreamingRequestDto.cs
new file mode 100644
index 000000000..1791b0370
--- /dev/null
+++ b/Jellyfin.Api/Models/StreamingDtos/StreamingRequestDto.cs
@@ -0,0 +1,45 @@
+using MediaBrowser.Controller.MediaEncoding;
+
+namespace Jellyfin.Api.Models.StreamingDtos
+{
+ /// <summary>
+ /// The audio streaming request dto.
+ /// </summary>
+ public class StreamingRequestDto : BaseEncodingJobOptions
+ {
+ /// <summary>
+ /// Gets or sets the device profile.
+ /// </summary>
+ public string? DeviceProfileId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the params.
+ /// </summary>
+ public string? Params { get; set; }
+
+ /// <summary>
+ /// Gets or sets the play session id.
+ /// </summary>
+ public string? PlaySessionId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tag.
+ /// </summary>
+ public string? Tag { get; set; }
+
+ /// <summary>
+ /// Gets or sets the segment container.
+ /// </summary>
+ public string? SegmentContainer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the segment length.
+ /// </summary>
+ public int? SegmentLength { get; set; }
+
+ /// <summary>
+ /// Gets or sets the min segments.
+ /// </summary>
+ public int? MinSegments { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/StreamingDtos/VideoRequestDto.cs b/Jellyfin.Api/Models/StreamingDtos/VideoRequestDto.cs
new file mode 100644
index 000000000..cce2a89d4
--- /dev/null
+++ b/Jellyfin.Api/Models/StreamingDtos/VideoRequestDto.cs
@@ -0,0 +1,19 @@
+namespace Jellyfin.Api.Models.StreamingDtos
+{
+ /// <summary>
+ /// The video request dto.
+ /// </summary>
+ public class VideoRequestDto : StreamingRequestDto
+ {
+ /// <summary>
+ /// Gets a value indicating whether this instance has fixed resolution.
+ /// </summary>
+ /// <value><c>true</c> if this instance has fixed resolution; otherwise, <c>false</c>.</value>
+ public bool HasFixedResolution => Width.HasValue || Height.HasValue;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable subtitles in the manifest.
+ /// </summary>
+ public bool EnableSubtitlesInManifest { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs b/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs
new file mode 100644
index 000000000..30473255e
--- /dev/null
+++ b/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs
@@ -0,0 +1,34 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.SubtitleDtos
+{
+ /// <summary>
+ /// Upload subtitles dto.
+ /// </summary>
+ public class UploadSubtitleDto
+ {
+ /// <summary>
+ /// Gets or sets the subtitle language.
+ /// </summary>
+ [Required]
+ public string Language { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the subtitle format.
+ /// </summary>
+ [Required]
+ public string Format { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the subtitle is forced.
+ /// </summary>
+ [Required]
+ public bool IsForced { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subtitle data.
+ /// </summary>
+ [Required]
+ public string Data { get; set; } = string.Empty;
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs
new file mode 100644
index 000000000..479c44084
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs
@@ -0,0 +1,42 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class BufferRequestDto.
+ /// </summary>
+ public class BufferRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BufferRequestDto"/> class.
+ /// </summary>
+ public BufferRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets when the request has been made by the client.
+ /// </summary>
+ /// <value>The date of the request.</value>
+ public DateTime When { get; set; }
+
+ /// <summary>
+ /// Gets or sets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the client playback is unpaused.
+ /// </summary>
+ /// <value>The client playback status.</value>
+ public bool IsPlaying { get; set; }
+
+ /// <summary>
+ /// Gets or sets the playlist item identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist item identifier.</value>
+ public Guid PlaylistItemId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs
new file mode 100644
index 000000000..4c30b7be4
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs
@@ -0,0 +1,14 @@
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class IgnoreWaitRequestDto.
+ /// </summary>
+ public class IgnoreWaitRequestDto
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether the client should be ignored.
+ /// </summary>
+ /// <value>The client group-wait status.</value>
+ public bool IgnoreWait { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs
new file mode 100644
index 000000000..ed97b8d6a
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs
@@ -0,0 +1,16 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class JoinGroupRequestDto.
+ /// </summary>
+ public class JoinGroupRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the group identifier.
+ /// </summary>
+ /// <value>The identifier of the group to join.</value>
+ public Guid GroupId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs
new file mode 100644
index 000000000..3af25f3e3
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs
@@ -0,0 +1,30 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class MovePlaylistItemRequestDto.
+ /// </summary>
+ public class MovePlaylistItemRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovePlaylistItemRequestDto"/> class.
+ /// </summary>
+ public MovePlaylistItemRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the playlist identifier of the item.
+ /// </summary>
+ /// <value>The playlist identifier of the item.</value>
+ public Guid PlaylistItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the new position.
+ /// </summary>
+ /// <value>The new position.</value>
+ public int NewIndex { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs
new file mode 100644
index 000000000..441d7be36
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs
@@ -0,0 +1,22 @@
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class NewGroupRequestDto.
+ /// </summary>
+ public class NewGroupRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NewGroupRequestDto"/> class.
+ /// </summary>
+ public NewGroupRequestDto()
+ {
+ GroupName = string.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the group name.
+ /// </summary>
+ /// <value>The name of the new group.</value>
+ public string GroupName { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs
new file mode 100644
index 000000000..f59a93f13
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class NextItemRequestDto.
+ /// </summary>
+ public class NextItemRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NextItemRequestDto"/> class.
+ /// </summary>
+ public NextItemRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the playing item identifier.
+ /// </summary>
+ /// <value>The playing item identifier.</value>
+ public Guid PlaylistItemId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs
new file mode 100644
index 000000000..c4ac06856
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs
@@ -0,0 +1,14 @@
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class PingRequestDto.
+ /// </summary>
+ public class PingRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the ping time.
+ /// </summary>
+ /// <value>The ping time.</value>
+ public long Ping { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs
new file mode 100644
index 000000000..844388cd9
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class PlayRequestDto.
+ /// </summary>
+ public class PlayRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlayRequestDto"/> class.
+ /// </summary>
+ public PlayRequestDto()
+ {
+ PlayingQueue = Array.Empty<Guid>();
+ }
+
+ /// <summary>
+ /// Gets or sets the playing queue.
+ /// </summary>
+ /// <value>The playing queue.</value>
+ public IReadOnlyList<Guid> PlayingQueue { get; set; }
+
+ /// <summary>
+ /// Gets or sets the position of the playing item in the queue.
+ /// </summary>
+ /// <value>The playing item position.</value>
+ public int PlayingItemPosition { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start position ticks.
+ /// </summary>
+ /// <value>The start position ticks.</value>
+ public long StartPositionTicks { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs
new file mode 100644
index 000000000..7fd4a49be
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class PreviousItemRequestDto.
+ /// </summary>
+ public class PreviousItemRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PreviousItemRequestDto"/> class.
+ /// </summary>
+ public PreviousItemRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the playing item identifier.
+ /// </summary>
+ /// <value>The playing item identifier.</value>
+ public Guid PlaylistItemId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs
new file mode 100644
index 000000000..2b187f443
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.SyncPlay;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class QueueRequestDto.
+ /// </summary>
+ public class QueueRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QueueRequestDto"/> class.
+ /// </summary>
+ public QueueRequestDto()
+ {
+ ItemIds = Array.Empty<Guid>();
+ }
+
+ /// <summary>
+ /// Gets or sets the items to enqueue.
+ /// </summary>
+ /// <value>The items to enqueue.</value>
+ public IReadOnlyList<Guid> ItemIds { get; set; }
+
+ /// <summary>
+ /// Gets or sets the mode in which to add the new items.
+ /// </summary>
+ /// <value>The enqueue mode.</value>
+ public GroupQueueMode Mode { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs
new file mode 100644
index 000000000..d9c193016
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs
@@ -0,0 +1,42 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class ReadyRequest.
+ /// </summary>
+ public class ReadyRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReadyRequestDto"/> class.
+ /// </summary>
+ public ReadyRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets when the request has been made by the client.
+ /// </summary>
+ /// <value>The date of the request.</value>
+ public DateTime When { get; set; }
+
+ /// <summary>
+ /// Gets or sets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the client playback is unpaused.
+ /// </summary>
+ /// <value>The client playback status.</value>
+ public bool IsPlaying { get; set; }
+
+ /// <summary>
+ /// Gets or sets the playlist item identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist item identifier.</value>
+ public Guid PlaylistItemId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs
new file mode 100644
index 000000000..02ce5a048
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class RemoveFromPlaylistRequestDto.
+ /// </summary>
+ public class RemoveFromPlaylistRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RemoveFromPlaylistRequestDto"/> class.
+ /// </summary>
+ public RemoveFromPlaylistRequestDto()
+ {
+ PlaylistItemIds = Array.Empty<Guid>();
+ }
+
+ /// <summary>
+ /// Gets or sets the playlist identifiers ot the items. Ignored when clearing the playlist.
+ /// </summary>
+ /// <value>The playlist identifiers ot the items.</value>
+ public IReadOnlyList<Guid> PlaylistItemIds { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the entire playlist should be cleared.
+ /// </summary>
+ /// <value>Whether the entire playlist should be cleared.</value>
+ public bool ClearPlaylist { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the playing item should be removed as well. Used only when clearing the playlist.
+ /// </summary>
+ /// <value>Whether the playing item should be removed as well.</value>
+ public bool ClearPlayingItem { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs
new file mode 100644
index 000000000..b9af0be7f
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs
@@ -0,0 +1,14 @@
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class SeekRequestDto.
+ /// </summary>
+ public class SeekRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs
new file mode 100644
index 000000000..b937679fc
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class SetPlaylistItemRequestDto.
+ /// </summary>
+ public class SetPlaylistItemRequestDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetPlaylistItemRequestDto"/> class.
+ /// </summary>
+ public SetPlaylistItemRequestDto()
+ {
+ PlaylistItemId = Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the playlist identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist identifier of the playing item.</value>
+ public Guid PlaylistItemId { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs
new file mode 100644
index 000000000..e748fc3e0
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs
@@ -0,0 +1,16 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class SetRepeatModeRequestDto.
+ /// </summary>
+ public class SetRepeatModeRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the repeat mode.
+ /// </summary>
+ /// <value>The repeat mode.</value>
+ public GroupRepeatMode Mode { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs
new file mode 100644
index 000000000..0e427f4a4
--- /dev/null
+++ b/Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs
@@ -0,0 +1,16 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace Jellyfin.Api.Models.SyncPlayDtos
+{
+ /// <summary>
+ /// Class SetShuffleModeRequestDto.
+ /// </summary>
+ public class SetShuffleModeRequestDto
+ {
+ /// <summary>
+ /// Gets or sets the shuffle mode.
+ /// </summary>
+ /// <value>The shuffle mode.</value>
+ public GroupShuffleMode Mode { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs b/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs
new file mode 100644
index 000000000..41f7b169e
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs
@@ -0,0 +1,26 @@
+using System;
+
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// The authenticate user by name request body.
+ /// </summary>
+ public class AuthenticateUserByName
+ {
+ /// <summary>
+ /// Gets or sets the username.
+ /// </summary>
+ public string? Username { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plain text password.
+ /// </summary>
+ public string? Pw { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sha1-hashed password.
+ /// </summary>
+ [Obsolete("Send password using pw field")]
+ public string? Password { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/CreateUserByName.cs b/Jellyfin.Api/Models/UserDtos/CreateUserByName.cs
new file mode 100644
index 000000000..1c88d3628
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/CreateUserByName.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// The create user by name request body.
+ /// </summary>
+ public class CreateUserByName
+ {
+ /// <summary>
+ /// Gets or sets the username.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the password.
+ /// </summary>
+ public string? Password { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/ForgotPasswordDto.cs b/Jellyfin.Api/Models/UserDtos/ForgotPasswordDto.cs
new file mode 100644
index 000000000..b31c6539c
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/ForgotPasswordDto.cs
@@ -0,0 +1,16 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// Forgot Password request body DTO.
+ /// </summary>
+ public class ForgotPasswordDto
+ {
+ /// <summary>
+ /// Gets or sets the entered username to have its password reset.
+ /// </summary>
+ [Required]
+ public string? EnteredUsername { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs b/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs
new file mode 100644
index 000000000..62780e23c
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs
@@ -0,0 +1,16 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// Forgot Password Pin enter request body DTO.
+ /// </summary>
+ public class ForgotPasswordPinDto
+ {
+ /// <summary>
+ /// Gets or sets the entered pin to have the password reset.
+ /// </summary>
+ [Required]
+ public string? Pin { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/QuickConnectDto.cs b/Jellyfin.Api/Models/UserDtos/QuickConnectDto.cs
new file mode 100644
index 000000000..9493c08c2
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/QuickConnectDto.cs
@@ -0,0 +1,16 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// The quick connect request body.
+ /// </summary>
+ public class QuickConnectDto
+ {
+ /// <summary>
+ /// Gets or sets the quick connect secret.
+ /// </summary>
+ [Required]
+ public string Secret { get; set; } = null!;
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/UpdateUserEasyPassword.cs b/Jellyfin.Api/Models/UserDtos/UpdateUserEasyPassword.cs
new file mode 100644
index 000000000..0a173ea1a
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/UpdateUserEasyPassword.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// The update user easy password request body.
+ /// </summary>
+ public class UpdateUserEasyPassword
+ {
+ /// <summary>
+ /// Gets or sets the new sha1-hashed password.
+ /// </summary>
+ public string? NewPassword { get; set; }
+
+ /// <summary>
+ /// Gets or sets the new password.
+ /// </summary>
+ public string? NewPw { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to reset the password.
+ /// </summary>
+ public bool ResetPassword { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserDtos/UpdateUserPassword.cs b/Jellyfin.Api/Models/UserDtos/UpdateUserPassword.cs
new file mode 100644
index 000000000..8288dbbc4
--- /dev/null
+++ b/Jellyfin.Api/Models/UserDtos/UpdateUserPassword.cs
@@ -0,0 +1,28 @@
+namespace Jellyfin.Api.Models.UserDtos
+{
+ /// <summary>
+ /// The update user password request body.
+ /// </summary>
+ public class UpdateUserPassword
+ {
+ /// <summary>
+ /// Gets or sets the current sha1-hashed password.
+ /// </summary>
+ public string? CurrentPassword { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current plain text password.
+ /// </summary>
+ public string? CurrentPw { get; set; }
+
+ /// <summary>
+ /// Gets or sets the new plain text password.
+ /// </summary>
+ public string? NewPw { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to reset the password.
+ /// </summary>
+ public bool ResetPassword { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/Models/UserViewDtos/SpecialViewOptionDto.cs b/Jellyfin.Api/Models/UserViewDtos/SpecialViewOptionDto.cs
new file mode 100644
index 000000000..84b6b0958
--- /dev/null
+++ b/Jellyfin.Api/Models/UserViewDtos/SpecialViewOptionDto.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.UserViewDtos
+{
+ /// <summary>
+ /// Special view option dto.
+ /// </summary>
+ public class SpecialViewOptionDto
+ {
+ /// <summary>
+ /// Gets or sets view option name.
+ /// </summary>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets view option id.
+ /// </summary>
+ public string? Id { get; set; }
+ }
+}
diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs
new file mode 100644
index 000000000..288e03fcf
--- /dev/null
+++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs
@@ -0,0 +1,64 @@
+using System;
+using System.Threading.Tasks;
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.WebSocketListeners
+{
+ /// <summary>
+ /// Class SessionInfoWebSocketListener.
+ /// </summary>
+ public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState>
+ {
+ /// <summary>
+ /// The _kernel.
+ /// </summary>
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ActivityLogWebSocketListener"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{ActivityLogWebSocketListener}"/> interface.</param>
+ /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
+ public ActivityLogWebSocketListener(ILogger<ActivityLogWebSocketListener> logger, IActivityManager activityManager)
+ : base(logger)
+ {
+ _activityManager = activityManager;
+ _activityManager.EntryCreated += OnEntryCreated;
+ }
+
+ /// <inheritdoc />
+ protected override SessionMessageType Type => SessionMessageType.ActivityLogEntry;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StartType => SessionMessageType.ActivityLogEntryStart;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StopType => SessionMessageType.ActivityLogEntryStop;
+
+ /// <summary>
+ /// Gets the data to send.
+ /// </summary>
+ /// <returns>Task{SystemInfo}.</returns>
+ protected override Task<ActivityLogEntry[]> GetDataToSend()
+ {
+ return Task.FromResult(Array.Empty<ActivityLogEntry>());
+ }
+
+ /// <inheritdoc />
+ protected override void Dispose(bool dispose)
+ {
+ _activityManager.EntryCreated -= OnEntryCreated;
+
+ base.Dispose(dispose);
+ }
+
+ private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e)
+ {
+ SendData(true).GetAwaiter().GetResult();
+ }
+ }
+}
diff --git a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs
new file mode 100644
index 000000000..94df23e56
--- /dev/null
+++ b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs
@@ -0,0 +1,84 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Session;
+using MediaBrowser.Model.Tasks;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.WebSocketListeners
+{
+ /// <summary>
+ /// Class ScheduledTasksWebSocketListener.
+ /// </summary>
+ public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState>
+ {
+ /// <summary>
+ /// Gets or sets the task manager.
+ /// </summary>
+ /// <value>The task manager.</value>
+ private readonly ITaskManager _taskManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScheduledTasksWebSocketListener"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{ScheduledTasksWebSocketListener}"/> interface.</param>
+ /// <param name="taskManager">Instance of the <see cref="ITaskManager"/> interface.</param>
+ public ScheduledTasksWebSocketListener(ILogger<ScheduledTasksWebSocketListener> logger, ITaskManager taskManager)
+ : base(logger)
+ {
+ _taskManager = taskManager;
+
+ _taskManager.TaskExecuting += OnTaskExecuting;
+ _taskManager.TaskCompleted += OnTaskCompleted;
+ }
+
+ /// <inheritdoc />
+ protected override SessionMessageType Type => SessionMessageType.ScheduledTasksInfo;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StartType => SessionMessageType.ScheduledTasksInfoStart;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StopType => SessionMessageType.ScheduledTasksInfoStop;
+
+ /// <summary>
+ /// Gets the data to send.
+ /// </summary>
+ /// <returns>Task{IEnumerable{TaskInfo}}.</returns>
+ protected override Task<IEnumerable<TaskInfo>> GetDataToSend()
+ {
+ return Task.FromResult(_taskManager.ScheduledTasks
+ .OrderBy(i => i.Name)
+ .Select(ScheduledTaskHelpers.GetTaskInfo)
+ .Where(i => !i.IsHidden));
+ }
+
+ /// <inheritdoc />
+ protected override void Dispose(bool dispose)
+ {
+ _taskManager.TaskExecuting -= OnTaskExecuting;
+ _taskManager.TaskCompleted -= OnTaskCompleted;
+
+ base.Dispose(dispose);
+ }
+
+ private void OnTaskCompleted(object? sender, TaskCompletionEventArgs e)
+ {
+ SendData(true);
+ e.Task.TaskProgress -= OnTaskProgress;
+ }
+
+ private void OnTaskExecuting(object? sender, GenericEventArgs<IScheduledTaskWorker> e)
+ {
+ SendData(true);
+ e.Argument.TaskProgress += OnTaskProgress;
+ }
+
+ private void OnTaskProgress(object? sender, GenericEventArgs<double> e)
+ {
+ SendData(false);
+ }
+ }
+}
diff --git a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs
new file mode 100644
index 000000000..d996ac69f
--- /dev/null
+++ b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs
@@ -0,0 +1,104 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.WebSocketListeners
+{
+ /// <summary>
+ /// Class SessionInfoWebSocketListener.
+ /// </summary>
+ public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionInfoWebSocketListener"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{SessionInfoWebSocketListener}"/> interface.</param>
+ /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
+ public SessionInfoWebSocketListener(ILogger<SessionInfoWebSocketListener> logger, ISessionManager sessionManager)
+ : base(logger)
+ {
+ _sessionManager = sessionManager;
+
+ _sessionManager.SessionStarted += OnSessionManagerSessionStarted;
+ _sessionManager.SessionEnded += OnSessionManagerSessionEnded;
+ _sessionManager.PlaybackStart += OnSessionManagerPlaybackStart;
+ _sessionManager.PlaybackStopped += OnSessionManagerPlaybackStopped;
+ _sessionManager.PlaybackProgress += OnSessionManagerPlaybackProgress;
+ _sessionManager.CapabilitiesChanged += OnSessionManagerCapabilitiesChanged;
+ _sessionManager.SessionActivity += OnSessionManagerSessionActivity;
+ }
+
+ /// <inheritdoc />
+ protected override SessionMessageType Type => SessionMessageType.Sessions;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StartType => SessionMessageType.SessionsStart;
+
+ /// <inheritdoc />
+ protected override SessionMessageType StopType => SessionMessageType.SessionsStop;
+
+ /// <summary>
+ /// Gets the data to send.
+ /// </summary>
+ /// <returns>Task{SystemInfo}.</returns>
+ protected override Task<IEnumerable<SessionInfo>> GetDataToSend()
+ {
+ return Task.FromResult(_sessionManager.Sessions);
+ }
+
+ /// <inheritdoc />
+ protected override void Dispose(bool dispose)
+ {
+ _sessionManager.SessionStarted -= OnSessionManagerSessionStarted;
+ _sessionManager.SessionEnded -= OnSessionManagerSessionEnded;
+ _sessionManager.PlaybackStart -= OnSessionManagerPlaybackStart;
+ _sessionManager.PlaybackStopped -= OnSessionManagerPlaybackStopped;
+ _sessionManager.PlaybackProgress -= OnSessionManagerPlaybackProgress;
+ _sessionManager.CapabilitiesChanged -= OnSessionManagerCapabilitiesChanged;
+ _sessionManager.SessionActivity -= OnSessionManagerSessionActivity;
+
+ base.Dispose(dispose);
+ }
+
+ private async void OnSessionManagerSessionActivity(object? sender, SessionEventArgs e)
+ {
+ await SendData(false).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerCapabilitiesChanged(object? sender, SessionEventArgs e)
+ {
+ await SendData(true).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
+ {
+ await SendData(!e.IsAutomated).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerPlaybackStopped(object? sender, PlaybackStopEventArgs e)
+ {
+ await SendData(true).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerPlaybackStart(object? sender, PlaybackProgressEventArgs e)
+ {
+ await SendData(true).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerSessionEnded(object? sender, SessionEventArgs e)
+ {
+ await SendData(true).ConfigureAwait(false);
+ }
+
+ private async void OnSessionManagerSessionStarted(object? sender, SessionEventArgs e)
+ {
+ await SendData(true).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Data/DayOfWeekHelper.cs b/Jellyfin.Data/DayOfWeekHelper.cs
new file mode 100644
index 000000000..b7ba30180
--- /dev/null
+++ b/Jellyfin.Data/DayOfWeekHelper.cs
@@ -0,0 +1,21 @@
+#pragma warning disable CS1591
+
+using System;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data
+{
+ public static class DayOfWeekHelper
+ {
+ public static DayOfWeek[] GetDaysOfWeek(DynamicDayOfWeek day)
+ {
+ return day switch
+ {
+ DynamicDayOfWeek.Everyday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday },
+ DynamicDayOfWeek.Weekday => new[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday },
+ DynamicDayOfWeek.Weekend => new[] { DayOfWeek.Sunday, DayOfWeek.Saturday },
+ _ => new[] { (DayOfWeek)day }
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Data/Dtos/DeviceOptionsDto.cs b/Jellyfin.Data/Dtos/DeviceOptionsDto.cs
new file mode 100644
index 000000000..392ef5ff4
--- /dev/null
+++ b/Jellyfin.Data/Dtos/DeviceOptionsDto.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Data.Dtos
+{
+ /// <summary>
+ /// A dto representing custom options for a device.
+ /// </summary>
+ public class DeviceOptionsDto
+ {
+ /// <summary>
+ /// Gets or sets the id.
+ /// </summary>
+ public int Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device id.
+ /// </summary>
+ public string? DeviceId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the custom name.
+ /// </summary>
+ public string? CustomName { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/AccessSchedule.cs b/Jellyfin.Data/Entities/AccessSchedule.cs
new file mode 100644
index 000000000..befc4ca02
--- /dev/null
+++ b/Jellyfin.Data/Entities/AccessSchedule.cs
@@ -0,0 +1,62 @@
+using System;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Xml.Serialization;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a user's access schedule.
+ /// </summary>
+ public class AccessSchedule
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessSchedule"/> class.
+ /// </summary>
+ /// <param name="dayOfWeek">The day of the week.</param>
+ /// <param name="startHour">The start hour.</param>
+ /// <param name="endHour">The end hour.</param>
+ /// <param name="userId">The associated user's id.</param>
+ public AccessSchedule(DynamicDayOfWeek dayOfWeek, double startHour, double endHour, Guid userId)
+ {
+ UserId = userId;
+ DayOfWeek = dayOfWeek;
+ StartHour = startHour;
+ EndHour = endHour;
+ }
+
+ /// <summary>
+ /// Gets the id of this instance.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [XmlIgnore]
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets the id of the associated user.
+ /// </summary>
+ [XmlIgnore]
+ public Guid UserId { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the day of week.
+ /// </summary>
+ /// <value>The day of week.</value>
+ public DynamicDayOfWeek DayOfWeek { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start hour.
+ /// </summary>
+ /// <value>The start hour.</value>
+ public double StartHour { get; set; }
+
+ /// <summary>
+ /// Gets or sets the end hour.
+ /// </summary>
+ /// <value>The end hour.</value>
+ public double EndHour { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/ActivityLog.cs b/Jellyfin.Data/Entities/ActivityLog.cs
new file mode 100644
index 000000000..1d1b86552
--- /dev/null
+++ b/Jellyfin.Data/Entities/ActivityLog.cs
@@ -0,0 +1,130 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity referencing an activity log entry.
+ /// </summary>
+ public class ActivityLog : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ActivityLog"/> class.
+ /// Public constructor with required data.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="userId">The user id.</param>
+ public ActivityLog(string name, string type, Guid userId)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ if (string.IsNullOrEmpty(type))
+ {
+ throw new ArgumentNullException(nameof(type));
+ }
+
+ Name = name;
+ Type = type;
+ UserId = userId;
+ DateCreated = DateTime.UtcNow;
+ LogSeverity = LogLevel.Information;
+ }
+
+ /// <summary>
+ /// Gets the identity of this instance.
+ /// </summary>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 512.
+ /// </remarks>
+ [MaxLength(512)]
+ [StringLength(512)]
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the overview.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 512.
+ /// </remarks>
+ [MaxLength(512)]
+ [StringLength(512)]
+ public string? Overview { get; set; }
+
+ /// <summary>
+ /// Gets or sets the short overview.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 512.
+ /// </remarks>
+ [MaxLength(512)]
+ [StringLength(512)]
+ public string? ShortOverview { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 256.
+ /// </remarks>
+ [MaxLength(256)]
+ [StringLength(256)]
+ public string Type { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the item id.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 256.
+ /// </remarks>
+ [MaxLength(256)]
+ [StringLength(256)]
+ public string? ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date created. This should be in UTC.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime DateCreated { get; set; }
+
+ /// <summary>
+ /// Gets or sets the log severity. Default is <see cref="LogLevel.Trace"/>.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public LogLevel LogSeverity { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs
new file mode 100644
index 000000000..b07b7c731
--- /dev/null
+++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs
@@ -0,0 +1,80 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity that represents a user's custom display preferences for a specific item.
+ /// </summary>
+ public class CustomItemDisplayPreferences
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CustomItemDisplayPreferences"/> class.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client.</param>
+ /// <param name="key">The preference key.</param>
+ /// <param name="value">The preference value.</param>
+ public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string key, string? value)
+ {
+ UserId = userId;
+ ItemId = itemId;
+ Client = client;
+ Key = key;
+ Value = value;
+ }
+
+ /// <summary>
+ /// Gets the Id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the user Id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the id of the associated item.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client string.
+ /// </summary>
+ /// <remarks>
+ /// Required. Max Length = 32.
+ /// </remarks>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string Client { get; set; }
+
+ /// <summary>
+ /// Gets or sets the preference key.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public string Key { get; set; }
+
+ /// <summary>
+ /// Gets or sets the preference value.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public string? Value { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/DisplayPreferences.cs b/Jellyfin.Data/Entities/DisplayPreferences.cs
new file mode 100644
index 000000000..646961238
--- /dev/null
+++ b/Jellyfin.Data/Entities/DisplayPreferences.cs
@@ -0,0 +1,150 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a user's display preferences.
+ /// </summary>
+ public class DisplayPreferences
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DisplayPreferences"/> class.
+ /// </summary>
+ /// <param name="userId">The user's id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client string.</param>
+ public DisplayPreferences(Guid userId, Guid itemId, string client)
+ {
+ UserId = userId;
+ ItemId = itemId;
+ Client = client;
+ ShowSidebar = false;
+ ShowBackdrop = true;
+ SkipForwardLength = 30000;
+ SkipBackwardLength = 10000;
+ ScrollDirection = ScrollDirection.Horizontal;
+ ChromecastVersion = ChromecastVersion.Stable;
+
+ HomeSections = new HashSet<HomeSection>();
+ }
+
+ /// <summary>
+ /// Gets the Id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the user Id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the id of the associated item.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client string.
+ /// </summary>
+ /// <remarks>
+ /// Required. Max Length = 32.
+ /// </remarks>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string Client { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to show the sidebar.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool ShowSidebar { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to show the backdrop.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool ShowBackdrop { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scroll direction.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public ScrollDirection ScrollDirection { get; set; }
+
+ /// <summary>
+ /// Gets or sets what the view should be indexed by.
+ /// </summary>
+ public IndexingKind? IndexBy { get; set; }
+
+ /// <summary>
+ /// Gets or sets the length of time to skip forwards, in milliseconds.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int SkipForwardLength { get; set; }
+
+ /// <summary>
+ /// Gets or sets the length of time to skip backwards, in milliseconds.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int SkipBackwardLength { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Chromecast Version.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public ChromecastVersion ChromecastVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the next video info overlay should be shown.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool EnableNextVideoInfoOverlay { get; set; }
+
+ /// <summary>
+ /// Gets or sets the dashboard theme.
+ /// </summary>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string? DashboardTheme { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tv home screen.
+ /// </summary>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string? TvHome { get; set; }
+
+ /// <summary>
+ /// Gets the home sections.
+ /// </summary>
+ public virtual ICollection<HomeSection> HomeSections { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Group.cs b/Jellyfin.Data/Entities/Group.cs
new file mode 100644
index 000000000..14da0bb15
--- /dev/null
+++ b/Jellyfin.Data/Entities/Group.cs
@@ -0,0 +1,83 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a group.
+ /// </summary>
+ public class Group : IHasPermissions, IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Group"/> class.
+ /// </summary>
+ /// <param name="name">The name of the group.</param>
+ public Group(string name)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ Name = name;
+ Id = Guid.NewGuid();
+
+ Permissions = new HashSet<Permission>();
+ Preferences = new HashSet<Preference>();
+ }
+
+ /// <summary>
+ /// Gets the id of this group.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ public Guid Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the group's name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string Name { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the group's permissions.
+ /// </summary>
+ public virtual ICollection<Permission> Permissions { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the group's preferences.
+ /// </summary>
+ public virtual ICollection<Preference> Preferences { get; private set; }
+
+ /// <inheritdoc/>
+ public bool HasPermission(PermissionKind kind)
+ {
+ return Permissions.First(p => p.Kind == kind).Value;
+ }
+
+ /// <inheritdoc/>
+ public void SetPermission(PermissionKind kind, bool value)
+ {
+ Permissions.First(p => p.Kind == kind).Value = value;
+ }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/HomeSection.cs b/Jellyfin.Data/Entities/HomeSection.cs
new file mode 100644
index 000000000..e194aa537
--- /dev/null
+++ b/Jellyfin.Data/Entities/HomeSection.cs
@@ -0,0 +1,44 @@
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a section on the user's home page.
+ /// </summary>
+ public class HomeSection
+ {
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity. Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the Id of the associated display preferences.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int DisplayPreferencesId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the order.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int Order { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public HomeSectionType Type { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/ImageInfo.cs b/Jellyfin.Data/Entities/ImageInfo.cs
new file mode 100644
index 000000000..b5c7a1c12
--- /dev/null
+++ b/Jellyfin.Data/Entities/ImageInfo.cs
@@ -0,0 +1,54 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing an image.
+ /// </summary>
+ public class ImageInfo
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ImageInfo"/> class.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ public ImageInfo(string path)
+ {
+ Path = path;
+ LastModified = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets the user id.
+ /// </summary>
+ public Guid? UserId { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the path of the image.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ [MaxLength(512)]
+ [StringLength(512)]
+ public string Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date last modified.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime LastModified { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs
new file mode 100644
index 000000000..948126d0a
--- /dev/null
+++ b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs
@@ -0,0 +1,113 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity that represents a user's display preferences for a specific item.
+ /// </summary>
+ public class ItemDisplayPreferences
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemDisplayPreferences"/> class.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client.</param>
+ public ItemDisplayPreferences(Guid userId, Guid itemId, string client)
+ {
+ UserId = userId;
+ ItemId = itemId;
+ Client = client;
+
+ SortBy = "SortName";
+ SortOrder = SortOrder.Ascending;
+ RememberSorting = false;
+ RememberIndexing = false;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the user Id.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the id of the associated item.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public Guid ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client string.
+ /// </summary>
+ /// <remarks>
+ /// Required. Max Length = 32.
+ /// </remarks>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string Client { get; set; }
+
+ /// <summary>
+ /// Gets or sets the view type.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public ViewType ViewType { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the indexing should be remembered.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool RememberIndexing { get; set; }
+
+ /// <summary>
+ /// Gets or sets what the view should be indexed by.
+ /// </summary>
+ public IndexingKind? IndexBy { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the sorting type should be remembered.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool RememberSorting { get; set; }
+
+ /// <summary>
+ /// Gets or sets what the view should be sorted by.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ [MaxLength(64)]
+ [StringLength(64)]
+ public string SortBy { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sort order.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public SortOrder SortOrder { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Artwork.cs b/Jellyfin.Data/Entities/Libraries/Artwork.cs
new file mode 100644
index 000000000..923525fc5
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Artwork.cs
@@ -0,0 +1,67 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing artwork.
+ /// </summary>
+ public class Artwork : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Artwork"/> class.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="kind">The kind of art.</param>
+ public Artwork(string path, ArtKind kind)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ Path = path;
+ Kind = kind;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the path.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the kind of artwork.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public ArtKind Kind { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Book.cs b/Jellyfin.Data/Entities/Libraries/Book.cs
new file mode 100644
index 000000000..a838686d0
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Book.cs
@@ -0,0 +1,29 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a book.
+ /// </summary>
+ public class Book : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Book"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Book(Library library) : base(library)
+ {
+ BookMetadata = new HashSet<BookMetadata>();
+ Releases = new HashSet<Release>();
+ }
+
+ /// <summary>
+ /// Gets a collection containing the metadata for this book.
+ /// </summary>
+ public virtual ICollection<BookMetadata> BookMetadata { get; private set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs
new file mode 100644
index 000000000..4a350d200
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs
@@ -0,0 +1,34 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity containing metadata for a book.
+ /// </summary>
+ public class BookMetadata : ItemMetadata, IHasCompanies
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BookMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public BookMetadata(string title, string language) : base(title, language)
+ {
+ Publishers = new HashSet<Company>();
+ }
+
+ /// <summary>
+ /// Gets or sets the ISBN.
+ /// </summary>
+ public long? Isbn { get; set; }
+
+ /// <summary>
+ /// Gets a collection of the publishers for this book.
+ /// </summary>
+ public virtual ICollection<Company> Publishers { get; private set; }
+
+ /// <inheritdoc />
+ public ICollection<Company> Companies => Publishers;
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Chapter.cs b/Jellyfin.Data/Entities/Libraries/Chapter.cs
new file mode 100644
index 000000000..3d81f713d
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Chapter.cs
@@ -0,0 +1,83 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a chapter.
+ /// </summary>
+ public class Chapter : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Chapter"/> class.
+ /// </summary>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ /// <param name="startTime">The start time for this chapter.</param>
+ public Chapter(string language, long startTime)
+ {
+ if (string.IsNullOrEmpty(language))
+ {
+ throw new ArgumentNullException(nameof(language));
+ }
+
+ Language = language;
+ StartTime = startTime;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the language.
+ /// </summary>
+ /// <remarks>
+ /// Required, Min length = 3, Max length = 3
+ /// ISO-639-3 3-character language codes.
+ /// </remarks>
+ [MinLength(3)]
+ [MaxLength(3)]
+ [StringLength(3)]
+ public string Language { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start time.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public long StartTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the end time.
+ /// </summary>
+ public long? EndTime { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Collection.cs b/Jellyfin.Data/Entities/Libraries/Collection.cs
new file mode 100644
index 000000000..7de601969
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Collection.cs
@@ -0,0 +1,57 @@
+#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
+
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a collection.
+ /// </summary>
+ public class Collection : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Collection"/> class.
+ /// </summary>
+ public Collection()
+ {
+ Items = new HashSet<CollectionItem>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Name { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing this collection's items.
+ /// </summary>
+ public virtual ICollection<CollectionItem> Items { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs
new file mode 100644
index 000000000..0cb4716db
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs
@@ -0,0 +1,64 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a collection item.
+ /// </summary>
+ public class CollectionItem : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionItem"/> class.
+ /// </summary>
+ /// <param name="libraryItem">The library item.</param>
+ public CollectionItem(LibraryItem libraryItem)
+ {
+ LibraryItem = libraryItem;
+ }
+
+ /// <summary>
+ /// Gets or sets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the library item.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public virtual LibraryItem LibraryItem { get; set; }
+
+ /// <summary>
+ /// Gets or sets the next item in the collection.
+ /// </summary>
+ /// <remarks>
+ /// TODO check if this properly updated Dependant and has the proper principal relationship.
+ /// </remarks>
+ public virtual CollectionItem? Next { get; set; }
+
+ /// <summary>
+ /// Gets or sets the previous item in the collection.
+ /// </summary>
+ /// <remarks>
+ /// TODO check if this properly updated Dependant and has the proper principal relationship.
+ /// </remarks>
+ public virtual CollectionItem? Previous { get; set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Company.cs b/Jellyfin.Data/Entities/Libraries/Company.cs
new file mode 100644
index 000000000..1abbee445
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Company.cs
@@ -0,0 +1,54 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a company.
+ /// </summary>
+ public class Company : IHasCompanies, IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Company"/> class.
+ /// </summary>
+ public Company()
+ {
+ CompanyMetadata = new HashSet<CompanyMetadata>();
+ ChildCompanies = new HashSet<Company>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the metadata.
+ /// </summary>
+ public virtual ICollection<CompanyMetadata> CompanyMetadata { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing this company's child companies.
+ /// </summary>
+ public virtual ICollection<Company> ChildCompanies { get; private set; }
+
+ /// <inheritdoc />
+ public ICollection<Company> Companies => ChildCompanies;
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs
new file mode 100644
index 000000000..a29f08c7f
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs
@@ -0,0 +1,59 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity holding metadata for a <see cref="Company"/>.
+ /// </summary>
+ public class CompanyMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CompanyMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public CompanyMetadata(string title, string language) : base(title, language)
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the description.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? Description { get; set; }
+
+ /// <summary>
+ /// Gets or sets the headquarters.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string? Headquarters { get; set; }
+
+ /// <summary>
+ /// Gets or sets the country code.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 2.
+ /// </remarks>
+ [MaxLength(2)]
+ [StringLength(2)]
+ public string? Country { get; set; }
+
+ /// <summary>
+ /// Gets or sets the homepage.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Homepage { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/CustomItem.cs b/Jellyfin.Data/Entities/Libraries/CustomItem.cs
new file mode 100644
index 000000000..e27d01d86
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/CustomItem.cs
@@ -0,0 +1,29 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a custom item.
+ /// </summary>
+ public class CustomItem : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CustomItem"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public CustomItem(Library library) : base(library)
+ {
+ CustomItemMetadata = new HashSet<CustomItemMetadata>();
+ Releases = new HashSet<Release>();
+ }
+
+ /// <summary>
+ /// Gets a collection containing the metadata for this item.
+ /// </summary>
+ public virtual ICollection<CustomItemMetadata> CustomItemMetadata { get; private set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs
new file mode 100644
index 000000000..af2393870
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs
@@ -0,0 +1,17 @@
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity containing metadata for a custom item.
+ /// </summary>
+ public class CustomItemMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CustomItemMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public CustomItemMetadata(string title, string language) : base(title, language)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Episode.cs b/Jellyfin.Data/Entities/Libraries/Episode.cs
new file mode 100644
index 000000000..ce2f0c617
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Episode.cs
@@ -0,0 +1,34 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing an episode.
+ /// </summary>
+ public class Episode : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Episode"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Episode(Library library) : base(library)
+ {
+ Releases = new HashSet<Release>();
+ EpisodeMetadata = new HashSet<EpisodeMetadata>();
+ }
+
+ /// <summary>
+ /// Gets or sets the episode number.
+ /// </summary>
+ public int? EpisodeNumber { get; set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the metadata for this episode.
+ /// </summary>
+ public virtual ICollection<EpisodeMetadata> EpisodeMetadata { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs
new file mode 100644
index 000000000..b0ef11e0f
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs
@@ -0,0 +1,49 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity containing metadata for an <see cref="Episode"/>.
+ /// </summary>
+ public class EpisodeMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public EpisodeMetadata(string title, string language) : base(title, language)
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the outline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Outline { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plot.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? Plot { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tagline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Tagline { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Genre.cs b/Jellyfin.Data/Entities/Libraries/Genre.cs
new file mode 100644
index 000000000..3b822ee82
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Genre.cs
@@ -0,0 +1,50 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a genre.
+ /// </summary>
+ public class Genre : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Genre"/> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ public Genre(string name)
+ {
+ Name = name;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Indexed, Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string Name { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs
new file mode 100644
index 000000000..d429a90c6
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs
@@ -0,0 +1,148 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An abstract class that holds metadata.
+ /// </summary>
+ public abstract class ItemMetadata : IHasArtwork, IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ protected ItemMetadata(string title, string language)
+ {
+ if (string.IsNullOrEmpty(title))
+ {
+ throw new ArgumentNullException(nameof(title));
+ }
+
+ if (string.IsNullOrEmpty(language))
+ {
+ throw new ArgumentNullException(nameof(language));
+ }
+
+ Title = title;
+ Language = language;
+ DateAdded = DateTime.UtcNow;
+ DateModified = DateAdded;
+
+ PersonRoles = new HashSet<PersonRole>();
+ Genres = new HashSet<Genre>();
+ Artwork = new HashSet<Artwork>();
+ Ratings = new HashSet<Rating>();
+ Sources = new HashSet<MetadataProviderId>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the title.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string Title { get; set; }
+
+ /// <summary>
+ /// Gets or sets the original title.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? OriginalTitle { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sort title.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? SortTitle { get; set; }
+
+ /// <summary>
+ /// Gets or sets the language.
+ /// </summary>
+ /// <remarks>
+ /// Required, Min length = 3, Max length = 3.
+ /// ISO-639-3 3-character language codes.
+ /// </remarks>
+ [MinLength(3)]
+ [MaxLength(3)]
+ [StringLength(3)]
+ public string Language { get; set; }
+
+ /// <summary>
+ /// Gets or sets the release date.
+ /// </summary>
+ public DateTimeOffset? ReleaseDate { get; set; }
+
+ /// <summary>
+ /// Gets the date added.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime DateAdded { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the date modified.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime DateModified { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the person roles for this item.
+ /// </summary>
+ public virtual ICollection<PersonRole> PersonRoles { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the genres for this item.
+ /// </summary>
+ public virtual ICollection<Genre> Genres { get; private set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Artwork> Artwork { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the ratings for this item.
+ /// </summary>
+ public virtual ICollection<Rating> Ratings { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the metadata sources for this item.
+ /// </summary>
+ public virtual ICollection<MetadataProviderId> Sources { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Library.cs b/Jellyfin.Data/Entities/Libraries/Library.cs
new file mode 100644
index 000000000..0db42a1c7
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Library.cs
@@ -0,0 +1,60 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a library.
+ /// </summary>
+ public class Library : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Library"/> class.
+ /// </summary>
+ /// <param name="name">The name of the library.</param>
+ /// <param name="path">The path of the library.</param>
+ public Library(string name, string path)
+ {
+ Name = name;
+ Path = path;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 128.
+ /// </remarks>
+ [MaxLength(128)]
+ [StringLength(128)]
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the root path of the library.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public string Path { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs
new file mode 100644
index 000000000..d889b871e
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs
@@ -0,0 +1,55 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a library item.
+ /// </summary>
+ public abstract class LibraryItem : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LibraryItem"/> class.
+ /// </summary>
+ /// <param name="library">The library of this item.</param>
+ protected LibraryItem(Library library)
+ {
+ DateAdded = DateTime.UtcNow;
+ Library = library;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets the date this library item was added.
+ /// </summary>
+ public DateTime DateAdded { get; private set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the library of this item.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public virtual Library Library { get; set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MediaFile.cs b/Jellyfin.Data/Entities/Libraries/MediaFile.cs
new file mode 100644
index 000000000..36e1e4777
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MediaFile.cs
@@ -0,0 +1,75 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a file on disk.
+ /// </summary>
+ public class MediaFile : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MediaFile"/> class.
+ /// </summary>
+ /// <param name="path">The path relative to the LibraryRoot.</param>
+ /// <param name="kind">The file kind.</param>
+ public MediaFile(string path, MediaFileKind kind)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ Path = path;
+ Kind = kind;
+
+ MediaFileStreams = new HashSet<MediaFileStream>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the path relative to the library root.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the kind of media file.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public MediaFileKind Kind { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the streams in this file.
+ /// </summary>
+ public virtual ICollection<MediaFileStream> MediaFileStreams { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs
new file mode 100644
index 000000000..e24e73ecb
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs
@@ -0,0 +1,50 @@
+#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
+
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a stream in a media file.
+ /// </summary>
+ public class MediaFileStream : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MediaFileStream"/> class.
+ /// </summary>
+ /// <param name="streamNumber">The number of this stream.</param>
+ public MediaFileStream(int streamNumber)
+ {
+ StreamNumber = streamNumber;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the stream number.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int StreamNumber { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs
new file mode 100644
index 000000000..b27196078
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs
@@ -0,0 +1,56 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a metadata provider.
+ /// </summary>
+ public class MetadataProvider : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MetadataProvider"/> class.
+ /// </summary>
+ /// <param name="name">The name of the metadata provider.</param>
+ public MetadataProvider(string name)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ Name = name;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string Name { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs
new file mode 100644
index 000000000..44c198518
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs
@@ -0,0 +1,66 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a unique identifier for a metadata provider.
+ /// </summary>
+ public class MetadataProviderId : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MetadataProviderId"/> class.
+ /// </summary>
+ /// <param name="providerId">The provider id.</param>
+ /// <param name="metadataProvider">The metadata provider.</param>
+ public MetadataProviderId(string providerId, MetadataProvider metadataProvider)
+ {
+ if (string.IsNullOrEmpty(providerId))
+ {
+ throw new ArgumentNullException(nameof(providerId));
+ }
+
+ ProviderId = providerId;
+ MetadataProvider = metadataProvider;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the provider id.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string ProviderId { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the metadata provider.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public virtual MetadataProvider MetadataProvider { get; set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Movie.cs b/Jellyfin.Data/Entities/Libraries/Movie.cs
new file mode 100644
index 000000000..499fafd0e
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Movie.cs
@@ -0,0 +1,29 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a movie.
+ /// </summary>
+ public class Movie : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Movie"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Movie(Library library) : base(library)
+ {
+ Releases = new HashSet<Release>();
+ MovieMetadata = new HashSet<MovieMetadata>();
+ }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the metadata for this movie.
+ /// </summary>
+ public virtual ICollection<MovieMetadata> MovieMetadata { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs
new file mode 100644
index 000000000..44b5f34d7
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs
@@ -0,0 +1,70 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity holding the metadata for a movie.
+ /// </summary>
+ public class MovieMetadata : ItemMetadata, IHasCompanies
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovieMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the movie.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public MovieMetadata(string title, string language) : base(title, language)
+ {
+ Studios = new HashSet<Company>();
+ }
+
+ /// <summary>
+ /// Gets or sets the outline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Outline { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tagline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Tagline { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plot.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? Plot { get; set; }
+
+ /// <summary>
+ /// Gets or sets the country code.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 2.
+ /// </remarks>
+ [MaxLength(2)]
+ [StringLength(2)]
+ public string? Country { get; set; }
+
+ /// <summary>
+ /// Gets the studios that produced this movie.
+ /// </summary>
+ public virtual ICollection<Company> Studios { get; private set; }
+
+ /// <inheritdoc />
+ public ICollection<Company> Companies => Studios;
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs
new file mode 100644
index 000000000..d6231bbf0
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs
@@ -0,0 +1,30 @@
+using System.Collections.Generic;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a music album.
+ /// </summary>
+ public class MusicAlbum : LibraryItem
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicAlbum"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public MusicAlbum(Library library) : base(library)
+ {
+ MusicAlbumMetadata = new HashSet<MusicAlbumMetadata>();
+ Tracks = new HashSet<Track>();
+ }
+
+ /// <summary>
+ /// Gets a collection containing the album metadata.
+ /// </summary>
+ public virtual ICollection<MusicAlbumMetadata> MusicAlbumMetadata { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the tracks.
+ /// </summary>
+ public virtual ICollection<Track> Tracks { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs
new file mode 100644
index 000000000..691f3504f
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs
@@ -0,0 +1,56 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity holding the metadata for a music album.
+ /// </summary>
+ public class MusicAlbumMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicAlbumMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the album.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public MusicAlbumMetadata(string title, string language) : base(title, language)
+ {
+ Labels = new HashSet<Company>();
+ }
+
+ /// <summary>
+ /// Gets or sets the barcode.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string? Barcode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the label number.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string? LabelNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the country code.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 2.
+ /// </remarks>
+ [MaxLength(2)]
+ [StringLength(2)]
+ public string? Country { get; set; }
+
+ /// <summary>
+ /// Gets a collection containing the labels.
+ /// </summary>
+ public virtual ICollection<Company> Labels { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Person.cs b/Jellyfin.Data/Entities/Libraries/Person.cs
new file mode 100644
index 000000000..8b67d920d
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Person.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a person.
+ /// </summary>
+ public class Person : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Person"/> class.
+ /// </summary>
+ /// <param name="name">The name of the person.</param>
+ public Person(string name)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ Name = name;
+ DateAdded = DateTime.UtcNow;
+ DateModified = DateAdded;
+
+ Sources = new HashSet<MetadataProviderId>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the source id.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(256)]
+ [StringLength(256)]
+ public string? SourceId { get; set; }
+
+ /// <summary>
+ /// Gets the date added.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime DateAdded { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the date modified.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public DateTime DateModified { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a list of metadata sources for this person.
+ /// </summary>
+ public virtual ICollection<MetadataProviderId> Sources { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/PersonRole.cs b/Jellyfin.Data/Entities/Libraries/PersonRole.cs
new file mode 100644
index 000000000..7d40bdf44
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/PersonRole.cs
@@ -0,0 +1,80 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a person's role in media.
+ /// </summary>
+ public class PersonRole : IHasArtwork, IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PersonRole"/> class.
+ /// </summary>
+ /// <param name="type">The role type.</param>
+ /// <param name="person">The person.</param>
+ public PersonRole(PersonRoleType type, Person person)
+ {
+ Type = type;
+ Person = person;
+ Artwork = new HashSet<Artwork>();
+ Sources = new HashSet<MetadataProviderId>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name of the person's role.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Role { get; set; }
+
+ /// <summary>
+ /// Gets or sets the person's role type.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public PersonRoleType Type { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the person.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public virtual Person Person { get; set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Artwork> Artwork { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the metadata sources for this person role.
+ /// </summary>
+ public virtual ICollection<MetadataProviderId> Sources { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Photo.cs b/Jellyfin.Data/Entities/Libraries/Photo.cs
new file mode 100644
index 000000000..4b459432b
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Photo.cs
@@ -0,0 +1,29 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a photo.
+ /// </summary>
+ public class Photo : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Photo"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Photo(Library library) : base(library)
+ {
+ PhotoMetadata = new HashSet<PhotoMetadata>();
+ Releases = new HashSet<Release>();
+ }
+
+ /// <summary>
+ /// Gets a collection containing the photo metadata.
+ /// </summary>
+ public virtual ICollection<PhotoMetadata> PhotoMetadata { get; private set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs b/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs
new file mode 100644
index 000000000..6c284307d
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs
@@ -0,0 +1,17 @@
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity that holds metadata for a photo.
+ /// </summary>
+ public class PhotoMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PhotoMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the photo.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public PhotoMetadata(string title, string language) : base(title, language)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Rating.cs b/Jellyfin.Data/Entities/Libraries/Rating.cs
new file mode 100644
index 000000000..58c8fa49e
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Rating.cs
@@ -0,0 +1,59 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a rating for an entity.
+ /// </summary>
+ public class Rating : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Rating"/> class.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ public Rating(double value)
+ {
+ Value = value;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the value.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public double Value { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of votes.
+ /// </summary>
+ public int? Votes { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the rating type.
+ /// If this is <c>null</c> it's the internal user rating.
+ /// </summary>
+ public virtual RatingSource? RatingType { get; set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/RatingSource.cs b/Jellyfin.Data/Entities/Libraries/RatingSource.cs
new file mode 100644
index 000000000..0f3a07324
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/RatingSource.cs
@@ -0,0 +1,73 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// This is the entity to store review ratings, not age ratings.
+ /// </summary>
+ public class RatingSource : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RatingSource"/> class.
+ /// </summary>
+ /// <param name="minimumValue">The minimum value.</param>
+ /// <param name="maximumValue">The maximum value.</param>
+ public RatingSource(double minimumValue, double maximumValue)
+ {
+ MinimumValue = minimumValue;
+ MaximumValue = maximumValue;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum value.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public double MinimumValue { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum value.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public double MaximumValue { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the metadata source.
+ /// </summary>
+ public virtual MetadataProviderId? Source { get; set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Release.cs b/Jellyfin.Data/Entities/Libraries/Release.cs
new file mode 100644
index 000000000..d3d52bf5c
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Release.cs
@@ -0,0 +1,70 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a release for a library item, eg. Director's cut vs. standard.
+ /// </summary>
+ public class Release : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Release"/> class.
+ /// </summary>
+ /// <param name="name">The name of this release.</param>
+ public Release(string name)
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ throw new ArgumentNullException(nameof(name));
+ }
+
+ Name = name;
+
+ MediaFiles = new HashSet<MediaFile>();
+ Chapters = new HashSet<Chapter>();
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string Name { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the media files for this release.
+ /// </summary>
+ public virtual ICollection<MediaFile> MediaFiles { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the chapters for this release.
+ /// </summary>
+ public virtual ICollection<Chapter> Chapters { get; private set; }
+
+ /// <inheritdoc />
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Season.cs b/Jellyfin.Data/Entities/Libraries/Season.cs
new file mode 100644
index 000000000..fc110b49d
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Season.cs
@@ -0,0 +1,35 @@
+using System.Collections.Generic;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a season.
+ /// </summary>
+ public class Season : LibraryItem
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Season"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Season(Library library) : base(library)
+ {
+ Episodes = new HashSet<Episode>();
+ SeasonMetadata = new HashSet<SeasonMetadata>();
+ }
+
+ /// <summary>
+ /// Gets or sets the season number.
+ /// </summary>
+ public int? SeasonNumber { get; set; }
+
+ /// <summary>
+ /// Gets the season metadata.
+ /// </summary>
+ public virtual ICollection<SeasonMetadata> SeasonMetadata { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the number of episodes.
+ /// </summary>
+ public virtual ICollection<Episode> Episodes { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs
new file mode 100644
index 000000000..da40a075f
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs
@@ -0,0 +1,29 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity that holds metadata for seasons.
+ /// </summary>
+ public class SeasonMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeasonMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public SeasonMetadata(string title, string language) : base(title, language)
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the outline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Outline { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Series.cs b/Jellyfin.Data/Entities/Libraries/Series.cs
new file mode 100644
index 000000000..0354433e0
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Series.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a a series.
+ /// </summary>
+ public class Series : LibraryItem
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Series"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Series(Library library) : base(library)
+ {
+ Seasons = new HashSet<Season>();
+ SeriesMetadata = new HashSet<SeriesMetadata>();
+ }
+
+ /// <summary>
+ /// Gets or sets the days of week.
+ /// </summary>
+ public DayOfWeek? AirsDayOfWeek { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time the show airs, ignore the date portion.
+ /// </summary>
+ public DateTimeOffset? AirsTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date the series first aired.
+ /// </summary>
+ public DateTime? FirstAired { get; set; }
+
+ /// <summary>
+ /// Gets a collection containing the series metadata.
+ /// </summary>
+ public virtual ICollection<SeriesMetadata> SeriesMetadata { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the seasons.
+ /// </summary>
+ public virtual ICollection<Season> Seasons { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs
new file mode 100644
index 000000000..42115802c
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs
@@ -0,0 +1,70 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing series metadata.
+ /// </summary>
+ public class SeriesMetadata : ItemMetadata, IHasCompanies
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeriesMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public SeriesMetadata(string title, string language) : base(title, language)
+ {
+ Networks = new HashSet<Company>();
+ }
+
+ /// <summary>
+ /// Gets or sets the outline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Outline { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plot.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? Plot { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tagline.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 1024.
+ /// </remarks>
+ [MaxLength(1024)]
+ [StringLength(1024)]
+ public string? Tagline { get; set; }
+
+ /// <summary>
+ /// Gets or sets the country code.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 2.
+ /// </remarks>
+ [MaxLength(2)]
+ [StringLength(2)]
+ public string? Country { get; set; }
+
+ /// <summary>
+ /// Gets a collection containing the networks.
+ /// </summary>
+ public virtual ICollection<Company> Networks { get; private set; }
+
+ /// <inheritdoc />
+ public ICollection<Company> Companies => Networks;
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/Track.cs b/Jellyfin.Data/Entities/Libraries/Track.cs
new file mode 100644
index 000000000..d35400033
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/Track.cs
@@ -0,0 +1,34 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity representing a track.
+ /// </summary>
+ public class Track : LibraryItem, IHasReleases
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Track"/> class.
+ /// </summary>
+ /// <param name="library">The library.</param>
+ public Track(Library library) : base(library)
+ {
+ Releases = new HashSet<Release>();
+ TrackMetadata = new HashSet<TrackMetadata>();
+ }
+
+ /// <summary>
+ /// Gets or sets the track number.
+ /// </summary>
+ public int? TrackNumber { get; set; }
+
+ /// <inheritdoc />
+ public virtual ICollection<Release> Releases { get; private set; }
+
+ /// <summary>
+ /// Gets a collection containing the track metadata.
+ /// </summary>
+ public virtual ICollection<TrackMetadata> TrackMetadata { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs b/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs
new file mode 100644
index 000000000..042d2b90d
--- /dev/null
+++ b/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs
@@ -0,0 +1,17 @@
+namespace Jellyfin.Data.Entities.Libraries
+{
+ /// <summary>
+ /// An entity holding metadata for a track.
+ /// </summary>
+ public class TrackMetadata : ItemMetadata
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TrackMetadata"/> class.
+ /// </summary>
+ /// <param name="title">The title or name of the object.</param>
+ /// <param name="language">ISO-639-3 3-character language codes.</param>
+ public TrackMetadata(string title, string language) : base(title, language)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs
new file mode 100644
index 000000000..6d2e68077
--- /dev/null
+++ b/Jellyfin.Data/Entities/Permission.cs
@@ -0,0 +1,68 @@
+#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing whether the associated user has a specific permission.
+ /// </summary>
+ public class Permission : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Permission"/> class.
+ /// Public constructor with required data.
+ /// </summary>
+ /// <param name="kind">The permission kind.</param>
+ /// <param name="value">The value of this permission.</param>
+ public Permission(PermissionKind kind, bool value)
+ {
+ Kind = kind;
+ Value = value;
+ }
+
+ /// <summary>
+ /// Gets the id of this permission.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the id of the associated user.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets the type of this permission.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public PermissionKind Kind { get; private set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the associated user has this permission.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool Value { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc/>
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs
new file mode 100644
index 000000000..a6ab275d3
--- /dev/null
+++ b/Jellyfin.Data/Entities/Preference.cs
@@ -0,0 +1,68 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a preference attached to a user or group.
+ /// </summary>
+ public class Preference : IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Preference"/> class.
+ /// Public constructor with required data.
+ /// </summary>
+ /// <param name="kind">The preference kind.</param>
+ /// <param name="value">The value.</param>
+ public Preference(PreferenceKind kind, string value)
+ {
+ Kind = kind;
+ Value = value ?? throw new ArgumentNullException(nameof(value));
+ }
+
+ /// <summary>
+ /// Gets the id of this preference.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the id of the associated user.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets the type of this preference.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public PreferenceKind Kind { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the value of this preference.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string Value { get; set; }
+
+ /// <inheritdoc/>
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <inheritdoc/>
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Security/ApiKey.cs b/Jellyfin.Data/Entities/Security/ApiKey.cs
new file mode 100644
index 000000000..31d865d01
--- /dev/null
+++ b/Jellyfin.Data/Entities/Security/ApiKey.cs
@@ -0,0 +1,56 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Globalization;
+
+namespace Jellyfin.Data.Entities.Security
+{
+ /// <summary>
+ /// An entity representing an API key.
+ /// </summary>
+ public class ApiKey
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ApiKey"/> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ public ApiKey(string name)
+ {
+ Name = name;
+
+ AccessToken = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ DateCreated = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the date created.
+ /// </summary>
+ public DateTime DateCreated { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date of last activity.
+ /// </summary>
+ public DateTime DateLastActivity { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ [MaxLength(64)]
+ [StringLength(64)]
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ public string AccessToken { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Security/Device.cs b/Jellyfin.Data/Entities/Security/Device.cs
new file mode 100644
index 000000000..67d7f78ed
--- /dev/null
+++ b/Jellyfin.Data/Entities/Security/Device.cs
@@ -0,0 +1,107 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Globalization;
+
+namespace Jellyfin.Data.Entities.Security
+{
+ /// <summary>
+ /// An entity representing a device.
+ /// </summary>
+ public class Device
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Device"/> class.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="appName">The app name.</param>
+ /// <param name="appVersion">The app version.</param>
+ /// <param name="deviceName">The device name.</param>
+ /// <param name="deviceId">The device id.</param>
+ public Device(Guid userId, string appName, string appVersion, string deviceName, string deviceId)
+ {
+ UserId = userId;
+ AppName = appName;
+ AppVersion = appVersion;
+ DeviceName = deviceName;
+ DeviceId = deviceId;
+
+ AccessToken = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ DateCreated = DateTime.UtcNow;
+ DateModified = DateCreated;
+ DateLastActivity = DateCreated;
+
+ // Non-nullable for EF Core, as this is a required relationship.
+ User = null!;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets the user id.
+ /// </summary>
+ public Guid UserId { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ public string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the app name.
+ /// </summary>
+ [MaxLength(64)]
+ [StringLength(64)]
+ public string AppName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the app version.
+ /// </summary>
+ [MaxLength(32)]
+ [StringLength(32)]
+ public string AppVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device name.
+ /// </summary>
+ [MaxLength(64)]
+ [StringLength(64)]
+ public string DeviceName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device id.
+ /// </summary>
+ [MaxLength(256)]
+ [StringLength(256)]
+ public string DeviceId { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this device is active.
+ /// </summary>
+ public bool IsActive { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date created.
+ /// </summary>
+ public DateTime DateCreated { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date modified.
+ /// </summary>
+ public DateTime DateModified { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date of last activity.
+ /// </summary>
+ public DateTime DateLastActivity { get; set; }
+
+ /// <summary>
+ /// Gets the user.
+ /// </summary>
+ public User User { get; private set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/Security/DeviceOptions.cs b/Jellyfin.Data/Entities/Security/DeviceOptions.cs
new file mode 100644
index 000000000..531f66c62
--- /dev/null
+++ b/Jellyfin.Data/Entities/Security/DeviceOptions.cs
@@ -0,0 +1,35 @@
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Jellyfin.Data.Entities.Security
+{
+ /// <summary>
+ /// An entity representing custom options for a device.
+ /// </summary>
+ public class DeviceOptions
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceOptions"/> class.
+ /// </summary>
+ /// <param name="deviceId">The device id.</param>
+ public DeviceOptions(string deviceId)
+ {
+ DeviceId = deviceId;
+ }
+
+ /// <summary>
+ /// Gets the id.
+ /// </summary>
+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public int Id { get; private set; }
+
+ /// <summary>
+ /// Gets the device id.
+ /// </summary>
+ public string DeviceId { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the custom name.
+ /// </summary>
+ public string? CustomName { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs
new file mode 100644
index 000000000..e309e54de
--- /dev/null
+++ b/Jellyfin.Data/Entities/User.cs
@@ -0,0 +1,521 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Interfaces;
+
+namespace Jellyfin.Data.Entities
+{
+ /// <summary>
+ /// An entity representing a user.
+ /// </summary>
+ public class User : IHasPermissions, IHasConcurrencyToken
+ {
+ /// <summary>
+ /// The values being delimited here are Guids, so commas work as they do not appear in Guids.
+ /// </summary>
+ private const char Delimiter = ',';
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="User"/> class.
+ /// Public constructor with required data.
+ /// </summary>
+ /// <param name="username">The username for the new user.</param>
+ /// <param name="authenticationProviderId">The Id of the user's authentication provider.</param>
+ /// <param name="passwordResetProviderId">The Id of the user's password reset provider.</param>
+ public User(string username, string authenticationProviderId, string passwordResetProviderId)
+ {
+ if (string.IsNullOrEmpty(username))
+ {
+ throw new ArgumentNullException(nameof(username));
+ }
+
+ if (string.IsNullOrEmpty(authenticationProviderId))
+ {
+ throw new ArgumentNullException(nameof(authenticationProviderId));
+ }
+
+ if (string.IsNullOrEmpty(passwordResetProviderId))
+ {
+ throw new ArgumentNullException(nameof(passwordResetProviderId));
+ }
+
+ Username = username;
+ AuthenticationProviderId = authenticationProviderId;
+ PasswordResetProviderId = passwordResetProviderId;
+
+ AccessSchedules = new HashSet<AccessSchedule>();
+ DisplayPreferences = new HashSet<DisplayPreferences>();
+ ItemDisplayPreferences = new HashSet<ItemDisplayPreferences>();
+ // Groups = new HashSet<Group>();
+ Permissions = new HashSet<Permission>();
+ Preferences = new HashSet<Preference>();
+ // ProviderMappings = new HashSet<ProviderMapping>();
+
+ // Set default values
+ Id = Guid.NewGuid();
+ InvalidLoginAttemptCount = 0;
+ EnableUserPreferenceAccess = true;
+ MustUpdatePassword = false;
+ DisplayMissingEpisodes = false;
+ DisplayCollectionsView = false;
+ HidePlayedInLatest = true;
+ RememberAudioSelections = true;
+ RememberSubtitleSelections = true;
+ EnableNextEpisodeAutoPlay = true;
+ EnableAutoLogin = false;
+ PlayDefaultAudioTrack = true;
+ SubtitleMode = SubtitlePlaybackMode.Default;
+ SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups;
+ }
+
+ /// <summary>
+ /// Gets or sets the Id of the user.
+ /// </summary>
+ /// <remarks>
+ /// Identity, Indexed, Required.
+ /// </remarks>
+ [JsonIgnore]
+ public Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's name.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string Username { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password, or <c>null</c> if none is set.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? Password { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's easy password, or <c>null</c> if none is set.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 65535.
+ /// </remarks>
+ [MaxLength(65535)]
+ [StringLength(65535)]
+ public string? EasyPassword { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user must update their password.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool MustUpdatePassword { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio language preference.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string? AudioLanguagePreference { get; set; }
+
+ /// <summary>
+ /// Gets or sets the authentication provider id.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string AuthenticationProviderId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the password reset provider id.
+ /// </summary>
+ /// <remarks>
+ /// Required, Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string PasswordResetProviderId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the invalid login attempt count.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public int InvalidLoginAttemptCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the last activity date.
+ /// </summary>
+ public DateTime? LastActivityDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the last login date.
+ /// </summary>
+ public DateTime? LastLoginDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of login attempts the user can make before they are locked out.
+ /// </summary>
+ public int? LoginAttemptsBeforeLockout { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum number of active sessions the user can have at once.
+ /// </summary>
+ public int MaxActiveSessions { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subtitle mode.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public SubtitlePlaybackMode SubtitleMode { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the default audio track should be played.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool PlayDefaultAudioTrack { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subtitle language preference.
+ /// </summary>
+ /// <remarks>
+ /// Max length = 255.
+ /// </remarks>
+ [MaxLength(255)]
+ [StringLength(255)]
+ public string? SubtitleLanguagePreference { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether missing episodes should be displayed.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool DisplayMissingEpisodes { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to display the collections view.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool DisplayCollectionsView { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user has a local password.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool EnableLocalPassword { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the server should hide played content in "Latest".
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool HidePlayedInLatest { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to remember audio selections on played content.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool RememberAudioSelections { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to remember subtitle selections on played content.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool RememberSubtitleSelections { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable auto-play for the next episode.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool EnableNextEpisodeAutoPlay { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user should auto-login.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool EnableAutoLogin { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user can change their preferences.
+ /// </summary>
+ /// <remarks>
+ /// Required.
+ /// </remarks>
+ public bool EnableUserPreferenceAccess { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum parental age rating.
+ /// </summary>
+ public int? MaxParentalAgeRating { get; set; }
+
+ /// <summary>
+ /// Gets or sets the remote client bitrate limit.
+ /// </summary>
+ public int? RemoteClientBitrateLimit { get; set; }
+
+ /// <summary>
+ /// Gets or sets the internal id.
+ /// This is a temporary stopgap for until the library db is migrated.
+ /// This corresponds to the value of the index of this user in the library db.
+ /// </summary>
+ public long InternalId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's profile image. Can be <c>null</c>.
+ /// </summary>
+ // [ForeignKey("UserId")]
+ public virtual ImageInfo? ProfileImage { get; set; }
+
+ /// <summary>
+ /// Gets the user's display preferences.
+ /// </summary>
+ public virtual ICollection<DisplayPreferences> DisplayPreferences { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the level of sync play permissions this user has.
+ /// </summary>
+ public SyncPlayUserAccessType SyncPlayAccess { get; set; }
+
+ /// <inheritdoc />
+ [ConcurrencyCheck]
+ public uint RowVersion { get; private set; }
+
+ /// <summary>
+ /// Gets the list of access schedules this user has.
+ /// </summary>
+ public virtual ICollection<AccessSchedule> AccessSchedules { get; private set; }
+
+ /// <summary>
+ /// Gets the list of item display preferences.
+ /// </summary>
+ public virtual ICollection<ItemDisplayPreferences> ItemDisplayPreferences { get; private set; }
+
+ /*
+ /// <summary>
+ /// Gets the list of groups this user is a member of.
+ /// </summary>
+ public virtual ICollection<Group> Groups { get; private set; }
+ */
+
+ /// <summary>
+ /// Gets the list of permissions this user has.
+ /// </summary>
+ [ForeignKey("Permission_Permissions_Guid")]
+ public virtual ICollection<Permission> Permissions { get; private set; }
+
+ /*
+ /// <summary>
+ /// Gets the list of provider mappings this user has.
+ /// </summary>
+ public virtual ICollection<ProviderMapping> ProviderMappings { get; private set; }
+ */
+
+ /// <summary>
+ /// Gets the list of preferences this user has.
+ /// </summary>
+ [ForeignKey("Preference_Preferences_Guid")]
+ public virtual ICollection<Preference> Preferences { get; private set; }
+
+ /// <inheritdoc/>
+ public void OnSavingChanges()
+ {
+ RowVersion++;
+ }
+
+ /// <summary>
+ /// Checks whether the user has the specified permission.
+ /// </summary>
+ /// <param name="kind">The permission kind.</param>
+ /// <returns><c>True</c> if the user has the specified permission.</returns>
+ public bool HasPermission(PermissionKind kind)
+ {
+ return Permissions.First(p => p.Kind == kind).Value;
+ }
+
+ /// <summary>
+ /// Sets the given permission kind to the provided value.
+ /// </summary>
+ /// <param name="kind">The permission kind.</param>
+ /// <param name="value">The value to set.</param>
+ public void SetPermission(PermissionKind kind, bool value)
+ {
+ Permissions.First(p => p.Kind == kind).Value = value;
+ }
+
+ /// <summary>
+ /// Gets the user's preferences for the given preference kind.
+ /// </summary>
+ /// <param name="preference">The preference kind.</param>
+ /// <returns>A string array containing the user's preferences.</returns>
+ public string[] GetPreference(PreferenceKind preference)
+ {
+ var val = Preferences.First(p => p.Kind == preference).Value;
+
+ return Equals(val, string.Empty) ? Array.Empty<string>() : val.Split(Delimiter);
+ }
+
+ /// <summary>
+ /// Gets the user's preferences for the given preference kind.
+ /// </summary>
+ /// <param name="preference">The preference kind.</param>
+ /// <typeparam name="T">Type of preference.</typeparam>
+ /// <returns>A {T} array containing the user's preference.</returns>
+ public T[] GetPreferenceValues<T>(PreferenceKind preference)
+ {
+ var val = Preferences.First(p => p.Kind == preference).Value;
+ if (string.IsNullOrEmpty(val))
+ {
+ return Array.Empty<T>();
+ }
+
+ // Convert array of {string} to array of {T}
+ var converter = TypeDescriptor.GetConverter(typeof(T));
+ var stringValues = val.Split(Delimiter);
+ var convertedCount = 0;
+ var parsedValues = new T[stringValues.Length];
+ for (var i = 0; i < stringValues.Length; i++)
+ {
+ try
+ {
+ var parsedValue = converter.ConvertFromString(stringValues[i].Trim());
+ if (parsedValue != null)
+ {
+ parsedValues[convertedCount++] = (T)parsedValue;
+ }
+ }
+ catch (FormatException)
+ {
+ // Unable to convert value
+ }
+ }
+
+ return parsedValues[..convertedCount];
+ }
+
+ /// <summary>
+ /// Sets the specified preference to the given value.
+ /// </summary>
+ /// <param name="preference">The preference kind.</param>
+ /// <param name="values">The values.</param>
+ public void SetPreference(PreferenceKind preference, string[] values)
+ {
+ Preferences.First(p => p.Kind == preference).Value
+ = string.Join(Delimiter, values);
+ }
+
+ /// <summary>
+ /// Sets the specified preference to the given value.
+ /// </summary>
+ /// <param name="preference">The preference kind.</param>
+ /// <param name="values">The values.</param>
+ /// <typeparam name="T">The type of value.</typeparam>
+ public void SetPreference<T>(PreferenceKind preference, T[] values)
+ {
+ Preferences.First(p => p.Kind == preference).Value
+ = string.Join(Delimiter, values);
+ }
+
+ /// <summary>
+ /// Checks whether this user is currently allowed to use the server.
+ /// </summary>
+ /// <returns><c>True</c> if the current time is within an access schedule, or there are no access schedules.</returns>
+ public bool IsParentalScheduleAllowed()
+ {
+ return AccessSchedules.Count == 0
+ || AccessSchedules.Any(i => IsParentalScheduleAllowed(i, DateTime.UtcNow));
+ }
+
+ /// <summary>
+ /// Checks whether the provided folder is in this user's grouped folders.
+ /// </summary>
+ /// <param name="id">The Guid of the folder.</param>
+ /// <returns><c>True</c> if the folder is in the user's grouped folders.</returns>
+ public bool IsFolderGrouped(Guid id)
+ {
+ return Array.IndexOf(GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders), id) != -1;
+ }
+
+ /// <summary>
+ /// Initializes the default permissions for a user. Should only be called on user creation.
+ /// </summary>
+ // TODO: make these user configurable?
+ public void AddDefaultPermissions()
+ {
+ Permissions.Add(new Permission(PermissionKind.IsAdministrator, false));
+ Permissions.Add(new Permission(PermissionKind.IsDisabled, false));
+ Permissions.Add(new Permission(PermissionKind.IsHidden, true));
+ Permissions.Add(new Permission(PermissionKind.EnableAllChannels, true));
+ Permissions.Add(new Permission(PermissionKind.EnableAllDevices, true));
+ Permissions.Add(new Permission(PermissionKind.EnableAllFolders, true));
+ Permissions.Add(new Permission(PermissionKind.EnableContentDeletion, false));
+ Permissions.Add(new Permission(PermissionKind.EnableContentDownloading, true));
+ Permissions.Add(new Permission(PermissionKind.EnableMediaConversion, true));
+ Permissions.Add(new Permission(PermissionKind.EnableMediaPlayback, true));
+ Permissions.Add(new Permission(PermissionKind.EnablePlaybackRemuxing, true));
+ Permissions.Add(new Permission(PermissionKind.EnablePublicSharing, true));
+ Permissions.Add(new Permission(PermissionKind.EnableRemoteAccess, true));
+ Permissions.Add(new Permission(PermissionKind.EnableSyncTranscoding, true));
+ Permissions.Add(new Permission(PermissionKind.EnableAudioPlaybackTranscoding, true));
+ Permissions.Add(new Permission(PermissionKind.EnableLiveTvAccess, true));
+ Permissions.Add(new Permission(PermissionKind.EnableLiveTvManagement, true));
+ Permissions.Add(new Permission(PermissionKind.EnableSharedDeviceControl, true));
+ Permissions.Add(new Permission(PermissionKind.EnableVideoPlaybackTranscoding, true));
+ Permissions.Add(new Permission(PermissionKind.ForceRemoteSourceTranscoding, false));
+ Permissions.Add(new Permission(PermissionKind.EnableRemoteControlOfOtherUsers, false));
+ }
+
+ /// <summary>
+ /// Initializes the default preferences. Should only be called on user creation.
+ /// </summary>
+ public void AddDefaultPreferences()
+ {
+ foreach (var val in Enum.GetValues(typeof(PreferenceKind)).Cast<PreferenceKind>())
+ {
+ Preferences.Add(new Preference(val, string.Empty));
+ }
+ }
+
+ private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date)
+ {
+ var localTime = date.ToLocalTime();
+ var hour = localTime.TimeOfDay.TotalHours;
+
+ return DayOfWeekHelper.GetDaysOfWeek(schedule.DayOfWeek).Contains(localTime.DayOfWeek)
+ && hour >= schedule.StartHour
+ && hour <= schedule.EndHour;
+ }
+ }
+}
diff --git a/Jellyfin.Data/Enums/ArtKind.cs b/Jellyfin.Data/Enums/ArtKind.cs
new file mode 100644
index 000000000..f7a73848c
--- /dev/null
+++ b/Jellyfin.Data/Enums/ArtKind.cs
@@ -0,0 +1,33 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing types of art.
+ /// </summary>
+ public enum ArtKind
+ {
+ /// <summary>
+ /// Another type of art, not covered by the other members.
+ /// </summary>
+ Other = 0,
+
+ /// <summary>
+ /// A poster.
+ /// </summary>
+ Poster = 1,
+
+ /// <summary>
+ /// A banner.
+ /// </summary>
+ Banner = 2,
+
+ /// <summary>
+ /// A thumbnail.
+ /// </summary>
+ Thumbnail = 3,
+
+ /// <summary>
+ /// A logo.
+ /// </summary>
+ Logo = 4
+ }
+}
diff --git a/Jellyfin.Data/Enums/BaseItemKind.cs b/Jellyfin.Data/Enums/BaseItemKind.cs
new file mode 100644
index 000000000..875781746
--- /dev/null
+++ b/Jellyfin.Data/Enums/BaseItemKind.cs
@@ -0,0 +1,205 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// The base item kind.
+ /// </summary>
+ /// <remarks>
+ /// This enum is generated from all classes that inherit from <c>BaseItem</c>.
+ /// </remarks>
+ public enum BaseItemKind
+ {
+ /// <summary>
+ /// Item is aggregate folder.
+ /// </summary>
+ AggregateFolder,
+
+ /// <summary>
+ /// Item is audio.
+ /// </summary>
+ Audio,
+
+ /// <summary>
+ /// Item is audio book.
+ /// </summary>
+ AudioBook,
+
+ /// <summary>
+ /// Item is base plugin folder.
+ /// </summary>
+ BasePluginFolder,
+
+ /// <summary>
+ /// Item is book.
+ /// </summary>
+ Book,
+
+ /// <summary>
+ /// Item is box set.
+ /// </summary>
+ BoxSet,
+
+ /// <summary>
+ /// Item is channel.
+ /// </summary>
+ Channel,
+
+ /// <summary>
+ /// Item is channel folder item.
+ /// </summary>
+ ChannelFolderItem,
+
+ /// <summary>
+ /// Item is collection folder.
+ /// </summary>
+ CollectionFolder,
+
+ /// <summary>
+ /// Item is episode.
+ /// </summary>
+ Episode,
+
+ /// <summary>
+ /// Item is folder.
+ /// </summary>
+ Folder,
+
+ /// <summary>
+ /// Item is genre.
+ /// </summary>
+ Genre,
+
+ /// <summary>
+ /// Item is manual playlists folder.
+ /// </summary>
+ ManualPlaylistsFolder,
+
+ /// <summary>
+ /// Item is movie.
+ /// </summary>
+ Movie,
+
+ /// <summary>
+ /// Item is a live tv channel.
+ /// </summary>
+ LiveTvChannel,
+
+ /// <summary>
+ /// Item is a live tv program.
+ /// </summary>
+ LiveTvProgram,
+
+ /// <summary>
+ /// Item is music album.
+ /// </summary>
+ MusicAlbum,
+
+ /// <summary>
+ /// Item is music artist.
+ /// </summary>
+ MusicArtist,
+
+ /// <summary>
+ /// Item is music genre.
+ /// </summary>
+ MusicGenre,
+
+ /// <summary>
+ /// Item is music video.
+ /// </summary>
+ MusicVideo,
+
+ /// <summary>
+ /// Item is person.
+ /// </summary>
+ Person,
+
+ /// <summary>
+ /// Item is photo.
+ /// </summary>
+ Photo,
+
+ /// <summary>
+ /// Item is photo album.
+ /// </summary>
+ PhotoAlbum,
+
+ /// <summary>
+ /// Item is playlist.
+ /// </summary>
+ Playlist,
+
+ /// <summary>
+ /// Item is playlist folder.
+ /// </summary>
+ PlaylistsFolder,
+
+ /// <summary>
+ /// Item is program
+ /// </summary>
+ Program,
+
+ /// <summary>
+ /// Item is recording.
+ /// </summary>
+ /// <remarks>
+ /// Manually added.
+ /// </remarks>
+ Recording,
+
+ /// <summary>
+ /// Item is season.
+ /// </summary>
+ Season,
+
+ /// <summary>
+ /// Item is series.
+ /// </summary>
+ Series,
+
+ /// <summary>
+ /// Item is studio.
+ /// </summary>
+ Studio,
+
+ /// <summary>
+ /// Item is trailer.
+ /// </summary>
+ Trailer,
+
+ /// <summary>
+ /// Item is live tv channel.
+ /// </summary>
+ /// <remarks>
+ /// Type is overridden.
+ /// </remarks>
+ TvChannel,
+
+ /// <summary>
+ /// Item is live tv program.
+ /// </summary>
+ /// <remarks>
+ /// Type is overridden.
+ /// </remarks>
+ TvProgram,
+
+ /// <summary>
+ /// Item is user root folder.
+ /// </summary>
+ UserRootFolder,
+
+ /// <summary>
+ /// Item is user view.
+ /// </summary>
+ UserView,
+
+ /// <summary>
+ /// Item is video.
+ /// </summary>
+ Video,
+
+ /// <summary>
+ /// Item is year.
+ /// </summary>
+ Year
+ }
+}
diff --git a/Jellyfin.Data/Enums/ChromecastVersion.cs b/Jellyfin.Data/Enums/ChromecastVersion.cs
new file mode 100644
index 000000000..2622e08ef
--- /dev/null
+++ b/Jellyfin.Data/Enums/ChromecastVersion.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the version of Chromecast to be used by clients.
+ /// </summary>
+ public enum ChromecastVersion
+ {
+ /// <summary>
+ /// Stable Chromecast version.
+ /// </summary>
+ Stable = 0,
+
+ /// <summary>
+ /// Unstable Chromecast version.
+ /// </summary>
+ Unstable = 1
+ }
+}
diff --git a/Jellyfin.Data/Enums/DynamicDayOfWeek.cs b/Jellyfin.Data/Enums/DynamicDayOfWeek.cs
new file mode 100644
index 000000000..d3d8dd822
--- /dev/null
+++ b/Jellyfin.Data/Enums/DynamicDayOfWeek.cs
@@ -0,0 +1,58 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum that represents a day of the week, weekdays, weekends, or all days.
+ /// </summary>
+ public enum DynamicDayOfWeek
+ {
+ /// <summary>
+ /// Sunday.
+ /// </summary>
+ Sunday = 0,
+
+ /// <summary>
+ /// Monday.
+ /// </summary>
+ Monday = 1,
+
+ /// <summary>
+ /// Tuesday.
+ /// </summary>
+ Tuesday = 2,
+
+ /// <summary>
+ /// Wednesday.
+ /// </summary>
+ Wednesday = 3,
+
+ /// <summary>
+ /// Thursday.
+ /// </summary>
+ Thursday = 4,
+
+ /// <summary>
+ /// Friday.
+ /// </summary>
+ Friday = 5,
+
+ /// <summary>
+ /// Saturday.
+ /// </summary>
+ Saturday = 6,
+
+ /// <summary>
+ /// All days of the week.
+ /// </summary>
+ Everyday = 7,
+
+ /// <summary>
+ /// A week day, or Monday-Friday.
+ /// </summary>
+ Weekday = 8,
+
+ /// <summary>
+ /// Saturday and Sunday.
+ /// </summary>
+ Weekend = 9
+ }
+}
diff --git a/Jellyfin.Data/Enums/HomeSectionType.cs b/Jellyfin.Data/Enums/HomeSectionType.cs
new file mode 100644
index 000000000..9bcd097dc
--- /dev/null
+++ b/Jellyfin.Data/Enums/HomeSectionType.cs
@@ -0,0 +1,58 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the different options for the home screen sections.
+ /// </summary>
+ public enum HomeSectionType
+ {
+ /// <summary>
+ /// None.
+ /// </summary>
+ None = 0,
+
+ /// <summary>
+ /// My Media.
+ /// </summary>
+ SmallLibraryTiles = 1,
+
+ /// <summary>
+ /// My Media Small.
+ /// </summary>
+ LibraryButtons = 2,
+
+ /// <summary>
+ /// Active Recordings.
+ /// </summary>
+ ActiveRecordings = 3,
+
+ /// <summary>
+ /// Continue Watching.
+ /// </summary>
+ Resume = 4,
+
+ /// <summary>
+ /// Continue Listening.
+ /// </summary>
+ ResumeAudio = 5,
+
+ /// <summary>
+ /// Latest Media.
+ /// </summary>
+ LatestMedia = 6,
+
+ /// <summary>
+ /// Next Up.
+ /// </summary>
+ NextUp = 7,
+
+ /// <summary>
+ /// Live TV.
+ /// </summary>
+ LiveTv = 8,
+
+ /// <summary>
+ /// Continue Reading.
+ /// </summary>
+ ResumeBook = 9
+ }
+}
diff --git a/Jellyfin.Data/Enums/IndexingKind.cs b/Jellyfin.Data/Enums/IndexingKind.cs
new file mode 100644
index 000000000..c0df07714
--- /dev/null
+++ b/Jellyfin.Data/Enums/IndexingKind.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing a type of indexing in a user's display preferences.
+ /// </summary>
+ public enum IndexingKind
+ {
+ /// <summary>
+ /// Index by the premiere date.
+ /// </summary>
+ PremiereDate = 0,
+
+ /// <summary>
+ /// Index by the production year.
+ /// </summary>
+ ProductionYear = 1,
+
+ /// <summary>
+ /// Index by the community rating.
+ /// </summary>
+ CommunityRating = 2
+ }
+}
diff --git a/Jellyfin.Data/Enums/MediaFileKind.cs b/Jellyfin.Data/Enums/MediaFileKind.cs
new file mode 100644
index 000000000..797c26ec2
--- /dev/null
+++ b/Jellyfin.Data/Enums/MediaFileKind.cs
@@ -0,0 +1,33 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the type of media file.
+ /// </summary>
+ public enum MediaFileKind
+ {
+ /// <summary>
+ /// The main file.
+ /// </summary>
+ Main = 0,
+
+ /// <summary>
+ /// A sidecar file.
+ /// </summary>
+ Sidecar = 1,
+
+ /// <summary>
+ /// An additional part to the main file.
+ /// </summary>
+ AdditionalPart = 2,
+
+ /// <summary>
+ /// An alternative format to the main file.
+ /// </summary>
+ AlternativeFormat = 3,
+
+ /// <summary>
+ /// An additional stream for the main file.
+ /// </summary>
+ AdditionalStream = 4
+ }
+}
diff --git a/Jellyfin.Data/Enums/PermissionKind.cs b/Jellyfin.Data/Enums/PermissionKind.cs
new file mode 100644
index 000000000..7d5200874
--- /dev/null
+++ b/Jellyfin.Data/Enums/PermissionKind.cs
@@ -0,0 +1,113 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// The types of user permissions.
+ /// </summary>
+ public enum PermissionKind
+ {
+ /// <summary>
+ /// Whether the user is an administrator.
+ /// </summary>
+ IsAdministrator = 0,
+
+ /// <summary>
+ /// Whether the user is hidden.
+ /// </summary>
+ IsHidden = 1,
+
+ /// <summary>
+ /// Whether the user is disabled.
+ /// </summary>
+ IsDisabled = 2,
+
+ /// <summary>
+ /// Whether the user can control shared devices.
+ /// </summary>
+ EnableSharedDeviceControl = 3,
+
+ /// <summary>
+ /// Whether the user can access the server remotely.
+ /// </summary>
+ EnableRemoteAccess = 4,
+
+ /// <summary>
+ /// Whether the user can manage live tv.
+ /// </summary>
+ EnableLiveTvManagement = 5,
+
+ /// <summary>
+ /// Whether the user can access live tv.
+ /// </summary>
+ EnableLiveTvAccess = 6,
+
+ /// <summary>
+ /// Whether the user can play media.
+ /// </summary>
+ EnableMediaPlayback = 7,
+
+ /// <summary>
+ /// Whether the server should transcode audio for the user if requested.
+ /// </summary>
+ EnableAudioPlaybackTranscoding = 8,
+
+ /// <summary>
+ /// Whether the server should transcode video for the user if requested.
+ /// </summary>
+ EnableVideoPlaybackTranscoding = 9,
+
+ /// <summary>
+ /// Whether the user can delete content.
+ /// </summary>
+ EnableContentDeletion = 10,
+
+ /// <summary>
+ /// Whether the user can download content.
+ /// </summary>
+ EnableContentDownloading = 11,
+
+ /// <summary>
+ /// Whether to enable sync transcoding for the user.
+ /// </summary>
+ EnableSyncTranscoding = 12,
+
+ /// <summary>
+ /// Whether the user can do media conversion.
+ /// </summary>
+ EnableMediaConversion = 13,
+
+ /// <summary>
+ /// Whether the user has access to all devices.
+ /// </summary>
+ EnableAllDevices = 14,
+
+ /// <summary>
+ /// Whether the user has access to all channels.
+ /// </summary>
+ EnableAllChannels = 15,
+
+ /// <summary>
+ /// Whether the user has access to all folders.
+ /// </summary>
+ EnableAllFolders = 16,
+
+ /// <summary>
+ /// Whether to enable public sharing for the user.
+ /// </summary>
+ EnablePublicSharing = 17,
+
+ /// <summary>
+ /// Whether the user can remotely control other users.
+ /// </summary>
+ EnableRemoteControlOfOtherUsers = 18,
+
+ /// <summary>
+ /// Whether the user is permitted to do playback remuxing.
+ /// </summary>
+ EnablePlaybackRemuxing = 19,
+
+ /// <summary>
+ /// Whether the server should force transcoding on remote connections for the user.
+ /// </summary>
+ ForceRemoteSourceTranscoding = 20
+ }
+}
diff --git a/Jellyfin.Data/Enums/PersonRoleType.cs b/Jellyfin.Data/Enums/PersonRoleType.cs
new file mode 100644
index 000000000..1e619f5ee
--- /dev/null
+++ b/Jellyfin.Data/Enums/PersonRoleType.cs
@@ -0,0 +1,68 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing a person's role in a specific media item.
+ /// </summary>
+ public enum PersonRoleType
+ {
+ /// <summary>
+ /// Another role, not covered by the other types.
+ /// </summary>
+ Other = 0,
+
+ /// <summary>
+ /// The director of the media.
+ /// </summary>
+ Director = 1,
+
+ /// <summary>
+ /// An artist.
+ /// </summary>
+ Artist = 2,
+
+ /// <summary>
+ /// The original artist.
+ /// </summary>
+ OriginalArtist = 3,
+
+ /// <summary>
+ /// An actor.
+ /// </summary>
+ Actor = 4,
+
+ /// <summary>
+ /// A voice actor.
+ /// </summary>
+ VoiceActor = 5,
+
+ /// <summary>
+ /// A producer.
+ /// </summary>
+ Producer = 6,
+
+ /// <summary>
+ /// A remixer.
+ /// </summary>
+ Remixer = 7,
+
+ /// <summary>
+ /// A conductor.
+ /// </summary>
+ Conductor = 8,
+
+ /// <summary>
+ /// A composer.
+ /// </summary>
+ Composer = 9,
+
+ /// <summary>
+ /// An author.
+ /// </summary>
+ Author = 10,
+
+ /// <summary>
+ /// An editor.
+ /// </summary>
+ Editor = 11
+ }
+}
diff --git a/Jellyfin.Data/Enums/PreferenceKind.cs b/Jellyfin.Data/Enums/PreferenceKind.cs
new file mode 100644
index 000000000..a54d789af
--- /dev/null
+++ b/Jellyfin.Data/Enums/PreferenceKind.cs
@@ -0,0 +1,68 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// The types of user preferences.
+ /// </summary>
+ public enum PreferenceKind
+ {
+ /// <summary>
+ /// A list of blocked tags.
+ /// </summary>
+ BlockedTags = 0,
+
+ /// <summary>
+ /// A list of blocked channels.
+ /// </summary>
+ BlockedChannels = 1,
+
+ /// <summary>
+ /// A list of blocked media folders.
+ /// </summary>
+ BlockedMediaFolders = 2,
+
+ /// <summary>
+ /// A list of enabled devices.
+ /// </summary>
+ EnabledDevices = 3,
+
+ /// <summary>
+ /// A list of enabled channels.
+ /// </summary>
+ EnabledChannels = 4,
+
+ /// <summary>
+ /// A list of enabled folders.
+ /// </summary>
+ EnabledFolders = 5,
+
+ /// <summary>
+ /// A list of folders to allow content deletion from.
+ /// </summary>
+ EnableContentDeletionFromFolders = 6,
+
+ /// <summary>
+ /// A list of latest items to exclude.
+ /// </summary>
+ LatestItemExcludes = 7,
+
+ /// <summary>
+ /// A list of media to exclude.
+ /// </summary>
+ MyMediaExcludes = 8,
+
+ /// <summary>
+ /// A list of grouped folders.
+ /// </summary>
+ GroupedFolders = 9,
+
+ /// <summary>
+ /// A list of unrated items to block.
+ /// </summary>
+ BlockUnratedItems = 10,
+
+ /// <summary>
+ /// A list of ordered views.
+ /// </summary>
+ OrderedViews = 11
+ }
+}
diff --git a/Jellyfin.Data/Enums/ScrollDirection.cs b/Jellyfin.Data/Enums/ScrollDirection.cs
new file mode 100644
index 000000000..9595eb490
--- /dev/null
+++ b/Jellyfin.Data/Enums/ScrollDirection.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the axis that should be scrolled.
+ /// </summary>
+ public enum ScrollDirection
+ {
+ /// <summary>
+ /// Horizontal scrolling direction.
+ /// </summary>
+ Horizontal = 0,
+
+ /// <summary>
+ /// Vertical scrolling direction.
+ /// </summary>
+ Vertical = 1
+ }
+}
diff --git a/Jellyfin.Data/Enums/SortOrder.cs b/Jellyfin.Data/Enums/SortOrder.cs
new file mode 100644
index 000000000..760a857f5
--- /dev/null
+++ b/Jellyfin.Data/Enums/SortOrder.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the sorting order.
+ /// </summary>
+ public enum SortOrder
+ {
+ /// <summary>
+ /// Sort in increasing order.
+ /// </summary>
+ Ascending = 0,
+
+ /// <summary>
+ /// Sort in decreasing order.
+ /// </summary>
+ Descending = 1
+ }
+}
diff --git a/Jellyfin.Data/Enums/SubtitlePlaybackMode.cs b/Jellyfin.Data/Enums/SubtitlePlaybackMode.cs
new file mode 100644
index 000000000..ca41300ed
--- /dev/null
+++ b/Jellyfin.Data/Enums/SubtitlePlaybackMode.cs
@@ -0,0 +1,33 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing a subtitle playback mode.
+ /// </summary>
+ public enum SubtitlePlaybackMode
+ {
+ /// <summary>
+ /// The default subtitle playback mode.
+ /// </summary>
+ Default = 0,
+
+ /// <summary>
+ /// Always show subtitles.
+ /// </summary>
+ Always = 1,
+
+ /// <summary>
+ /// Only show forced subtitles.
+ /// </summary>
+ OnlyForced = 2,
+
+ /// <summary>
+ /// Don't show subtitles.
+ /// </summary>
+ None = 3,
+
+ /// <summary>
+ /// Only show subtitles when the current audio stream is in a different language.
+ /// </summary>
+ Smart = 4
+ }
+}
diff --git a/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs b/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs
new file mode 100644
index 000000000..8c3e6cb17
--- /dev/null
+++ b/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs
@@ -0,0 +1,28 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// Enum SyncPlayAccessRequirementType.
+ /// </summary>
+ public enum SyncPlayAccessRequirementType
+ {
+ /// <summary>
+ /// User must have access to SyncPlay, in some form.
+ /// </summary>
+ HasAccess = 0,
+
+ /// <summary>
+ /// User must be able to create groups.
+ /// </summary>
+ CreateGroup = 1,
+
+ /// <summary>
+ /// User must be able to join groups.
+ /// </summary>
+ JoinGroup = 2,
+
+ /// <summary>
+ /// User must be in a group.
+ /// </summary>
+ IsInGroup = 3
+ }
+}
diff --git a/Jellyfin.Data/Enums/SyncPlayUserAccessType.cs b/Jellyfin.Data/Enums/SyncPlayUserAccessType.cs
new file mode 100644
index 000000000..030d16fb9
--- /dev/null
+++ b/Jellyfin.Data/Enums/SyncPlayUserAccessType.cs
@@ -0,0 +1,23 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// Enum SyncPlayUserAccessType.
+ /// </summary>
+ public enum SyncPlayUserAccessType
+ {
+ /// <summary>
+ /// User can create groups and join them.
+ /// </summary>
+ CreateAndJoinGroups = 0,
+
+ /// <summary>
+ /// User can only join already existing groups.
+ /// </summary>
+ JoinGroups = 1,
+
+ /// <summary>
+ /// SyncPlay is disabled for the user.
+ /// </summary>
+ None = 2
+ }
+}
diff --git a/Jellyfin.Data/Enums/UnratedItem.cs b/Jellyfin.Data/Enums/UnratedItem.cs
new file mode 100644
index 000000000..871794086
--- /dev/null
+++ b/Jellyfin.Data/Enums/UnratedItem.cs
@@ -0,0 +1,53 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing an unrated item.
+ /// </summary>
+ public enum UnratedItem
+ {
+ /// <summary>
+ /// A movie.
+ /// </summary>
+ Movie = 0,
+
+ /// <summary>
+ /// A trailer.
+ /// </summary>
+ Trailer = 1,
+
+ /// <summary>
+ /// A series.
+ /// </summary>
+ Series = 2,
+
+ /// <summary>
+ /// Music.
+ /// </summary>
+ Music = 3,
+
+ /// <summary>
+ /// A book.
+ /// </summary>
+ Book = 4,
+
+ /// <summary>
+ /// A live TV channel
+ /// </summary>
+ LiveTvChannel = 5,
+
+ /// <summary>
+ /// A live TV program.
+ /// </summary>
+ LiveTvProgram = 6,
+
+ /// <summary>
+ /// Channel content.
+ /// </summary>
+ ChannelContent = 7,
+
+ /// <summary>
+ /// Another type, not covered by the other fields.
+ /// </summary>
+ Other = 8
+ }
+}
diff --git a/Jellyfin.Data/Enums/ViewType.cs b/Jellyfin.Data/Enums/ViewType.cs
new file mode 100644
index 000000000..c0fd7d448
--- /dev/null
+++ b/Jellyfin.Data/Enums/ViewType.cs
@@ -0,0 +1,113 @@
+namespace Jellyfin.Data.Enums
+{
+ /// <summary>
+ /// An enum representing the type of view for a library or collection.
+ /// </summary>
+ public enum ViewType
+ {
+ /// <summary>
+ /// Shows albums.
+ /// </summary>
+ Albums = 0,
+
+ /// <summary>
+ /// Shows album artists.
+ /// </summary>
+ AlbumArtists = 1,
+
+ /// <summary>
+ /// Shows artists.
+ /// </summary>
+ Artists = 2,
+
+ /// <summary>
+ /// Shows channels.
+ /// </summary>
+ Channels = 3,
+
+ /// <summary>
+ /// Shows collections.
+ /// </summary>
+ Collections = 4,
+
+ /// <summary>
+ /// Shows episodes.
+ /// </summary>
+ Episodes = 5,
+
+ /// <summary>
+ /// Shows favorites.
+ /// </summary>
+ Favorites = 6,
+
+ /// <summary>
+ /// Shows genres.
+ /// </summary>
+ Genres = 7,
+
+ /// <summary>
+ /// Shows guide.
+ /// </summary>
+ Guide = 8,
+
+ /// <summary>
+ /// Shows movies.
+ /// </summary>
+ Movies = 9,
+
+ /// <summary>
+ /// Shows networks.
+ /// </summary>
+ Networks = 10,
+
+ /// <summary>
+ /// Shows playlists.
+ /// </summary>
+ Playlists = 11,
+
+ /// <summary>
+ /// Shows programs.
+ /// </summary>
+ Programs = 12,
+
+ /// <summary>
+ /// Shows recordings.
+ /// </summary>
+ Recordings = 13,
+
+ /// <summary>
+ /// Shows schedule.
+ /// </summary>
+ Schedule = 14,
+
+ /// <summary>
+ /// Shows series.
+ /// </summary>
+ Series = 15,
+
+ /// <summary>
+ /// Shows shows.
+ /// </summary>
+ Shows = 16,
+
+ /// <summary>
+ /// Shows songs.
+ /// </summary>
+ Songs = 17,
+
+ /// <summary>
+ /// Shows songs.
+ /// </summary>
+ Suggestions = 18,
+
+ /// <summary>
+ /// Shows trailers.
+ /// </summary>
+ Trailers = 19,
+
+ /// <summary>
+ /// Shows upcoming.
+ /// </summary>
+ Upcoming = 20
+ }
+}
diff --git a/MediaBrowser.Model/Events/GenericEventArgs.cs b/Jellyfin.Data/Events/GenericEventArgs.cs
index fc8bc620f..7b9a5111e 100644
--- a/MediaBrowser.Model/Events/GenericEventArgs.cs
+++ b/Jellyfin.Data/Events/GenericEventArgs.cs
@@ -1,20 +1,14 @@
using System;
-namespace MediaBrowser.Model.Events
+namespace Jellyfin.Data.Events
{
/// <summary>
- /// Provides a generic EventArgs subclass that can hold any kind of object
+ /// Provides a generic EventArgs subclass that can hold any kind of object.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of this event.</typeparam>
public class GenericEventArgs<T> : EventArgs
{
/// <summary>
- /// Gets or sets the argument.
- /// </summary>
- /// <value>The argument.</value>
- public T Argument { get; set; }
-
- /// <summary>
/// Initializes a new instance of the <see cref="GenericEventArgs{T}"/> class.
/// </summary>
/// <param name="arg">The argument.</param>
@@ -24,10 +18,9 @@ namespace MediaBrowser.Model.Events
}
/// <summary>
- /// Initializes a new instance of the <see cref="GenericEventArgs{T}"/> class.
+ /// Gets the argument.
/// </summary>
- public GenericEventArgs()
- {
- }
+ /// <value>The argument.</value>
+ public T Argument { get; }
}
}
diff --git a/Jellyfin.Data/Events/System/PendingRestartEventArgs.cs b/Jellyfin.Data/Events/System/PendingRestartEventArgs.cs
new file mode 100644
index 000000000..2aa40a946
--- /dev/null
+++ b/Jellyfin.Data/Events/System/PendingRestartEventArgs.cs
@@ -0,0 +1,11 @@
+using System;
+
+namespace Jellyfin.Data.Events.System
+{
+ /// <summary>
+ /// An event that occurs when there is a pending restart.
+ /// </summary>
+ public class PendingRestartEventArgs : EventArgs
+ {
+ }
+}
diff --git a/Jellyfin.Data/Events/Users/UserCreatedEventArgs.cs b/Jellyfin.Data/Events/Users/UserCreatedEventArgs.cs
new file mode 100644
index 000000000..66f7c8d4f
--- /dev/null
+++ b/Jellyfin.Data/Events/Users/UserCreatedEventArgs.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Data.Entities;
+
+namespace Jellyfin.Data.Events.Users
+{
+ /// <summary>
+ /// An event that occurs when a user is created.
+ /// </summary>
+ public class UserCreatedEventArgs : GenericEventArgs<User>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserCreatedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The user.</param>
+ public UserCreatedEventArgs(User arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Events/Users/UserDeletedEventArgs.cs b/Jellyfin.Data/Events/Users/UserDeletedEventArgs.cs
new file mode 100644
index 000000000..0b9493375
--- /dev/null
+++ b/Jellyfin.Data/Events/Users/UserDeletedEventArgs.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Data.Entities;
+
+namespace Jellyfin.Data.Events.Users
+{
+ /// <summary>
+ /// An event that occurs when a user is deleted.
+ /// </summary>
+ public class UserDeletedEventArgs : GenericEventArgs<User>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserDeletedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The user.</param>
+ public UserDeletedEventArgs(User arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Events/Users/UserLockedOutEventArgs.cs b/Jellyfin.Data/Events/Users/UserLockedOutEventArgs.cs
new file mode 100644
index 000000000..cca3726dc
--- /dev/null
+++ b/Jellyfin.Data/Events/Users/UserLockedOutEventArgs.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Data.Entities;
+
+namespace Jellyfin.Data.Events.Users
+{
+ /// <summary>
+ /// An event that occurs when a user is locked out.
+ /// </summary>
+ public class UserLockedOutEventArgs : GenericEventArgs<User>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserLockedOutEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The user.</param>
+ public UserLockedOutEventArgs(User arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Events/Users/UserPasswordChangedEventArgs.cs b/Jellyfin.Data/Events/Users/UserPasswordChangedEventArgs.cs
new file mode 100644
index 000000000..087ec9ab6
--- /dev/null
+++ b/Jellyfin.Data/Events/Users/UserPasswordChangedEventArgs.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Data.Entities;
+
+namespace Jellyfin.Data.Events.Users
+{
+ /// <summary>
+ /// An event that occurs when a user's password has changed.
+ /// </summary>
+ public class UserPasswordChangedEventArgs : GenericEventArgs<User>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserPasswordChangedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The user.</param>
+ public UserPasswordChangedEventArgs(User arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Events/Users/UserUpdatedEventArgs.cs b/Jellyfin.Data/Events/Users/UserUpdatedEventArgs.cs
new file mode 100644
index 000000000..2b4e49cdf
--- /dev/null
+++ b/Jellyfin.Data/Events/Users/UserUpdatedEventArgs.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Data.Entities;
+
+namespace Jellyfin.Data.Events.Users
+{
+ /// <summary>
+ /// An event that occurs when a user is updated.
+ /// </summary>
+ public class UserUpdatedEventArgs : GenericEventArgs<User>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserUpdatedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The user.</param>
+ public UserUpdatedEventArgs(User arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Data/Interfaces/IHasArtwork.cs b/Jellyfin.Data/Interfaces/IHasArtwork.cs
new file mode 100644
index 000000000..a4d9c54af
--- /dev/null
+++ b/Jellyfin.Data/Interfaces/IHasArtwork.cs
@@ -0,0 +1,16 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Entities.Libraries;
+
+namespace Jellyfin.Data.Interfaces
+{
+ /// <summary>
+ /// An interface abstracting an entity that has artwork.
+ /// </summary>
+ public interface IHasArtwork
+ {
+ /// <summary>
+ /// Gets a collection containing this entity's artwork.
+ /// </summary>
+ ICollection<Artwork> Artwork { get; }
+ }
+}
diff --git a/Jellyfin.Data/Interfaces/IHasCompanies.cs b/Jellyfin.Data/Interfaces/IHasCompanies.cs
new file mode 100644
index 000000000..8f19ce04f
--- /dev/null
+++ b/Jellyfin.Data/Interfaces/IHasCompanies.cs
@@ -0,0 +1,16 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Entities.Libraries;
+
+namespace Jellyfin.Data.Interfaces
+{
+ /// <summary>
+ /// An abstraction representing an entity that has companies.
+ /// </summary>
+ public interface IHasCompanies
+ {
+ /// <summary>
+ /// Gets a collection containing this entity's companies.
+ /// </summary>
+ ICollection<Company> Companies { get; }
+ }
+}
diff --git a/Jellyfin.Data/Interfaces/IHasConcurrencyToken.cs b/Jellyfin.Data/Interfaces/IHasConcurrencyToken.cs
new file mode 100644
index 000000000..2c4091493
--- /dev/null
+++ b/Jellyfin.Data/Interfaces/IHasConcurrencyToken.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Data.Interfaces
+{
+ /// <summary>
+ /// An interface abstracting an entity that has a concurrency token.
+ /// </summary>
+ public interface IHasConcurrencyToken
+ {
+ /// <summary>
+ /// Gets the version of this row. Acts as a concurrency token.
+ /// </summary>
+ uint RowVersion { get; }
+
+ /// <summary>
+ /// Called when saving changes to this entity.
+ /// </summary>
+ void OnSavingChanges();
+ }
+}
diff --git a/Jellyfin.Data/Interfaces/IHasPermissions.cs b/Jellyfin.Data/Interfaces/IHasPermissions.cs
new file mode 100644
index 000000000..85ee12ad7
--- /dev/null
+++ b/Jellyfin.Data/Interfaces/IHasPermissions.cs
@@ -0,0 +1,31 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+
+namespace Jellyfin.Data.Interfaces
+{
+ /// <summary>
+ /// An abstraction representing an entity that has permissions.
+ /// </summary>
+ public interface IHasPermissions
+ {
+ /// <summary>
+ /// Gets a collection containing this entity's permissions.
+ /// </summary>
+ ICollection<Permission> Permissions { get; }
+
+ /// <summary>
+ /// Checks whether this entity has the specified permission kind.
+ /// </summary>
+ /// <param name="kind">The kind of permission.</param>
+ /// <returns><c>true</c> if this entity has the specified permission, <c>false</c> otherwise.</returns>
+ bool HasPermission(PermissionKind kind);
+
+ /// <summary>
+ /// Sets the specified permission to the provided value.
+ /// </summary>
+ /// <param name="kind">The kind of permission.</param>
+ /// <param name="value">The value to set.</param>
+ void SetPermission(PermissionKind kind, bool value);
+ }
+}
diff --git a/Jellyfin.Data/Interfaces/IHasReleases.cs b/Jellyfin.Data/Interfaces/IHasReleases.cs
new file mode 100644
index 000000000..3b615893e
--- /dev/null
+++ b/Jellyfin.Data/Interfaces/IHasReleases.cs
@@ -0,0 +1,16 @@
+using System.Collections.Generic;
+using Jellyfin.Data.Entities.Libraries;
+
+namespace Jellyfin.Data.Interfaces
+{
+ /// <summary>
+ /// An abstraction representing an entity that has releases.
+ /// </summary>
+ public interface IHasReleases
+ {
+ /// <summary>
+ /// Gets a collection containing this entity's releases.
+ /// </summary>
+ ICollection<Release> Releases { get; }
+ }
+}
diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj
new file mode 100644
index 000000000..2de53e7c8
--- /dev/null
+++ b/Jellyfin.Data/Jellyfin.Data.csproj
@@ -0,0 +1,45 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </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>
+
+ <PropertyGroup>
+ <Authors>Jellyfin Contributors</Authors>
+ <PackageId>Jellyfin.Data</PackageId>
+ <VersionPrefix>10.8.0</VersionPrefix>
+ <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
+ </ItemGroup>
+
+ <!-- Code analysers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0-rc.2*" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
+ </ItemGroup>
+
+</Project>
diff --git a/Jellyfin.Data/Queries/ActivityLogQuery.cs b/Jellyfin.Data/Queries/ActivityLogQuery.cs
new file mode 100644
index 000000000..f1af099d3
--- /dev/null
+++ b/Jellyfin.Data/Queries/ActivityLogQuery.cs
@@ -0,0 +1,20 @@
+using System;
+
+namespace Jellyfin.Data.Queries
+{
+ /// <summary>
+ /// A class representing a query to the activity logs.
+ /// </summary>
+ public class ActivityLogQuery : PaginatedQuery
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether to take entries with a user id.
+ /// </summary>
+ public bool? HasUserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum date to query for.
+ /// </summary>
+ public DateTime? MinDate { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Queries/DeviceQuery.cs b/Jellyfin.Data/Queries/DeviceQuery.cs
new file mode 100644
index 000000000..083e00548
--- /dev/null
+++ b/Jellyfin.Data/Queries/DeviceQuery.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Jellyfin.Data.Queries
+{
+ /// <summary>
+ /// A query to retrieve devices.
+ /// </summary>
+ public class DeviceQuery : PaginatedQuery
+ {
+ /// <summary>
+ /// Gets or sets the user id of the device.
+ /// </summary>
+ public Guid? UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the device id.
+ /// </summary>
+ public string? DeviceId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ public string? AccessToken { get; set; }
+ }
+}
diff --git a/Jellyfin.Data/Queries/PaginatedQuery.cs b/Jellyfin.Data/Queries/PaginatedQuery.cs
new file mode 100644
index 000000000..58267ebe7
--- /dev/null
+++ b/Jellyfin.Data/Queries/PaginatedQuery.cs
@@ -0,0 +1,18 @@
+namespace Jellyfin.Data.Queries
+{
+ /// <summary>
+ /// An abstract class for paginated queries.
+ /// </summary>
+ public abstract class PaginatedQuery
+ {
+ /// <summary>
+ /// Gets or sets the index to start at.
+ /// </summary>
+ public int? Skip { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum number of items to include.
+ /// </summary>
+ public int? Limit { get; set; }
+ }
+}
diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
index f023bc55d..5fa386eca 100644
--- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
+++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
@@ -1,8 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <ProjectGuid>{154872D9-6C12-4007-96E3-8F70A58386CE}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -10,9 +16,10 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="SkiaSharp" Version="1.68.0" />
- <PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="1.68.0" />
- <PackageReference Include="Jellyfin.SkiaSharp.NativeAssets.LinuxArm" Version="1.68.0" />
+ <PackageReference Include="BlurHashSharp" Version="1.2.0" />
+ <PackageReference Include="BlurHashSharp.SkiaSharp" Version="1.2.0" />
+ <PackageReference Include="SkiaSharp" Version="2.80.3" />
+ <PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.80.3" />
</ItemGroup>
<ItemGroup>
@@ -21,4 +28,11 @@
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
+ <!-- Code analysers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/Jellyfin.Drawing.Skia/PercentPlayedDrawer.cs b/Jellyfin.Drawing.Skia/PercentPlayedDrawer.cs
index 0d5a1d3c0..6136a2ff9 100644
--- a/Jellyfin.Drawing.Skia/PercentPlayedDrawer.cs
+++ b/Jellyfin.Drawing.Skia/PercentPlayedDrawer.cs
@@ -4,28 +4,33 @@ using SkiaSharp;
namespace Jellyfin.Drawing.Skia
{
+ /// <summary>
+ /// Static helper class used to draw percentage-played indicators on images.
+ /// </summary>
public static class PercentPlayedDrawer
{
private const int IndicatorHeight = 8;
+ /// <summary>
+ /// Draw a percentage played indicator on a canvas.
+ /// </summary>
+ /// <param name="canvas">The canvas to draw the indicator on.</param>
+ /// <param name="imageSize">The size of the image being drawn on.</param>
+ /// <param name="percent">The percentage played to display with the indicator.</param>
public static void Process(SKCanvas canvas, ImageDimensions imageSize, double percent)
{
- using (var paint = new SKPaint())
- {
- var endX = imageSize.Width - 1;
- var endY = imageSize.Height - 1;
+ using var paint = new SKPaint();
+ var endX = imageSize.Width - 1;
+ var endY = imageSize.Height - 1;
- paint.Color = SKColor.Parse("#99000000");
- paint.Style = SKPaintStyle.Fill;
- canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, (float)endX, (float)endY), paint);
+ paint.Color = SKColor.Parse("#99000000");
+ paint.Style = SKPaintStyle.Fill;
+ canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, endX, endY), paint);
- double foregroundWidth = endX;
- foregroundWidth *= percent;
- foregroundWidth /= 100;
+ double foregroundWidth = (endX * percent) / 100;
- paint.Color = SKColor.Parse("#FF52B54B");
- canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, Convert.ToInt32(foregroundWidth), (float)endY), paint);
- }
+ paint.Color = SKColor.Parse("#FF00A4DC");
+ canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, Convert.ToInt32(foregroundWidth), endY), paint);
}
}
}
diff --git a/Jellyfin.Drawing.Skia/PlayedIndicatorDrawer.cs b/Jellyfin.Drawing.Skia/PlayedIndicatorDrawer.cs
index 62497da27..db4f78398 100644
--- a/Jellyfin.Drawing.Skia/PlayedIndicatorDrawer.cs
+++ b/Jellyfin.Drawing.Skia/PlayedIndicatorDrawer.cs
@@ -3,42 +3,46 @@ using SkiaSharp;
namespace Jellyfin.Drawing.Skia
{
+ /// <summary>
+ /// Static helper class for drawing 'played' indicators.
+ /// </summary>
public static class PlayedIndicatorDrawer
{
private const int OffsetFromTopRightCorner = 38;
+ /// <summary>
+ /// Draw a 'played' indicator in the top right corner of a canvas.
+ /// </summary>
+ /// <param name="canvas">The canvas to draw the indicator on.</param>
+ /// <param name="imageSize">
+ /// The dimensions of the image to draw the indicator on. The width is used to determine the x-position of the
+ /// indicator.
+ /// </param>
public static void DrawPlayedIndicator(SKCanvas canvas, ImageDimensions imageSize)
{
var x = imageSize.Width - OffsetFromTopRightCorner;
- using (var paint = new SKPaint())
+ using var paint = new SKPaint
{
- paint.Color = SKColor.Parse("#CC52B54B");
- paint.Style = SKPaintStyle.Fill;
- canvas.DrawCircle((float)x, OffsetFromTopRightCorner, 20, paint);
- }
+ Color = SKColor.Parse("#CC00A4DC"),
+ Style = SKPaintStyle.Fill
+ };
- using (var paint = new SKPaint())
- {
- paint.Color = new SKColor(255, 255, 255, 255);
- paint.Style = SKPaintStyle.Fill;
-
- paint.TextSize = 30;
- paint.IsAntialias = true;
+ canvas.DrawCircle(x, OffsetFromTopRightCorner, 20, paint);
- var text = "✔️";
- var emojiChar = StringUtilities.GetUnicodeCharacterCode(text, SKTextEncoding.Utf32);
- // or:
- //var emojiChar = 0x1F680;
+ paint.Color = new SKColor(255, 255, 255, 255);
+ paint.TextSize = 30;
+ paint.IsAntialias = true;
- // ask the font manager for a font with that character
- var fontManager = SKFontManager.Default;
- var emojiTypeface = fontManager.MatchCharacter(emojiChar);
+ // or:
+ // var emojiChar = 0x1F680;
+ const string Text = "✔️";
+ var emojiChar = StringUtilities.GetUnicodeCharacterCode(Text, SKTextEncoding.Utf32);
- paint.Typeface = emojiTypeface;
+ // ask the font manager for a font with that character
+ paint.Typeface = SKFontManager.Default.MatchCharacter(emojiChar);
- canvas.DrawText(text, (float)x - 20, OffsetFromTopRightCorner + 12, paint);
- }
+ canvas.DrawText(Text, (float)x - 20, OffsetFromTopRightCorner + 12, paint);
}
}
}
diff --git a/Jellyfin.Drawing.Skia/Properties/AssemblyInfo.cs b/Jellyfin.Drawing.Skia/Properties/AssemblyInfo.cs
index ea1c457f6..e7db09449 100644
--- a/Jellyfin.Drawing.Skia/Properties/AssemblyInfo.cs
+++ b/Jellyfin.Drawing.Skia/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/Jellyfin.Drawing.Skia/SkiaCodecException.cs b/Jellyfin.Drawing.Skia/SkiaCodecException.cs
new file mode 100644
index 000000000..9a50a4d62
--- /dev/null
+++ b/Jellyfin.Drawing.Skia/SkiaCodecException.cs
@@ -0,0 +1,45 @@
+using System.Globalization;
+using SkiaSharp;
+
+namespace Jellyfin.Drawing.Skia
+{
+ /// <summary>
+ /// Represents errors that occur during interaction with Skia codecs.
+ /// </summary>
+ public class SkiaCodecException : SkiaException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaCodecException" /> class.
+ /// </summary>
+ /// <param name="result">The non-successful codec result returned by Skia.</param>
+ public SkiaCodecException(SKCodecResult result)
+ {
+ CodecResult = result;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaCodecException" /> class
+ /// with a specified error message.
+ /// </summary>
+ /// <param name="result">The non-successful codec result returned by Skia.</param>
+ /// <param name="message">The message that describes the error.</param>
+ public SkiaCodecException(SKCodecResult result, string message)
+ : base(message)
+ {
+ CodecResult = result;
+ }
+
+ /// <summary>
+ /// Gets the non-successful codec result returned by Skia.
+ /// </summary>
+ public SKCodecResult CodecResult { get; }
+
+ /// <inheritdoc />
+ public override string ToString()
+ => string.Format(
+ CultureInfo.InvariantCulture,
+ "Non-success codec result: {0}\n{1}",
+ CodecResult,
+ base.ToString());
+ }
+}
diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs
index 5060476ba..6d0a5ac2b 100644
--- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs
+++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs
@@ -2,49 +2,57 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
-using System.Linq;
-using System.Reflection;
+using BlurHashSharp.SkiaSharp;
+using Diacritics.Extensions;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Extensions;
using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
using SkiaSharp;
+using static Jellyfin.Drawing.Skia.SkiaHelper;
namespace Jellyfin.Drawing.Skia
{
+ /// <summary>
+ /// Image encoder that uses <see cref="SkiaSharp"/> to manipulate images.
+ /// </summary>
public class SkiaEncoder : IImageEncoder
{
- private readonly ILogger _logger;
- private static IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
- private static ILocalizationManager _localizationManager;
-
- public SkiaEncoder(
- ILoggerFactory loggerFactory,
- IApplicationPaths appPaths,
- IFileSystem fileSystem,
- ILocalizationManager localizationManager)
+ private static readonly HashSet<string> _transparentImageTypes
+ = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" };
+
+ private readonly ILogger<SkiaEncoder> _logger;
+ private readonly IApplicationPaths _appPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaEncoder"/> class.
+ /// </summary>
+ /// <param name="logger">The application logger.</param>
+ /// <param name="appPaths">The application paths.</param>
+ public SkiaEncoder(ILogger<SkiaEncoder> logger, IApplicationPaths appPaths)
{
- _logger = loggerFactory.CreateLogger("ImageEncoder");
+ _logger = logger;
_appPaths = appPaths;
- _fileSystem = fileSystem;
- _localizationManager = localizationManager;
-
- LogVersion();
}
+ /// <inheritdoc/>
+ public string Name => "Skia";
+
+ /// <inheritdoc/>
+ public bool SupportsImageCollageCreation => true;
+
+ /// <inheritdoc/>
+ public bool SupportsImageEncoding => true;
+
+ /// <inheritdoc/>
public IReadOnlyCollection<string> SupportedInputFormats =>
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"jpeg",
"jpg",
"png",
-
"dng",
-
"webp",
"gif",
"bmp",
@@ -53,175 +61,110 @@ namespace Jellyfin.Drawing.Skia
"ktx",
"pkm",
"wbmp",
-
- // TODO
- // Are all of these supported? https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
-
+ // TODO: check if these are supported on multiple platforms
+ // https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
// working on windows at least
"cr2",
"nef",
"arw"
};
+ /// <inheritdoc/>
public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
=> new HashSet<ImageFormat>() { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
- private void LogVersion()
+ /// <summary>
+ /// Check if the native lib is available.
+ /// </summary>
+ /// <returns>True if the native lib is available, otherwise false.</returns>
+ public static bool IsNativeLibAvailable()
{
- // test an operation that requires the native library
- SKPMColor.PreMultiply(SKColors.Black);
-
- _logger.LogInformation("SkiaSharp version: " + GetVersion());
- }
-
- public static Version GetVersion()
- => typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version;
-
- private static bool IsTransparent(SKColor color)
- => (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
-
- public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
- {
- switch (selectedFormat)
- {
- case ImageFormat.Bmp:
- return SKEncodedImageFormat.Bmp;
- case ImageFormat.Jpg:
- return SKEncodedImageFormat.Jpeg;
- case ImageFormat.Gif:
- return SKEncodedImageFormat.Gif;
- case ImageFormat.Webp:
- return SKEncodedImageFormat.Webp;
- default:
- return SKEncodedImageFormat.Png;
+ try
+ {
+ // test an operation that requires the native library
+ SKPMColor.PreMultiply(SKColors.Black);
+ return true;
}
- }
-
- private static bool IsTransparentRow(SKBitmap bmp, int row)
- {
- for (var i = 0; i < bmp.Width; ++i)
+ catch (Exception)
{
- if (!IsTransparent(bmp.GetPixel(i, row)))
- {
- return false;
- }
+ return false;
}
- return true;
}
- private static bool IsTransparentColumn(SKBitmap bmp, int col)
+ /// <summary>
+ /// Convert a <see cref="ImageFormat"/> to a <see cref="SKEncodedImageFormat"/>.
+ /// </summary>
+ /// <param name="selectedFormat">The format to convert.</param>
+ /// <returns>The converted format.</returns>
+ public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
{
- for (var i = 0; i < bmp.Height; ++i)
+ return selectedFormat switch
{
- if (!IsTransparent(bmp.GetPixel(col, i)))
- {
- return false;
- }
- }
- return true;
+ ImageFormat.Bmp => SKEncodedImageFormat.Bmp,
+ ImageFormat.Jpg => SKEncodedImageFormat.Jpeg,
+ ImageFormat.Gif => SKEncodedImageFormat.Gif,
+ ImageFormat.Webp => SKEncodedImageFormat.Webp,
+ _ => SKEncodedImageFormat.Png
+ };
}
- private SKBitmap CropWhiteSpace(SKBitmap bitmap)
+ /// <inheritdoc />
+ /// <exception cref="ArgumentNullException">The path is null.</exception>
+ /// <exception cref="FileNotFoundException">The path is not valid.</exception>
+ /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
+ public ImageDimensions GetImageSize(string path)
{
- var topmost = 0;
- for (int row = 0; row < bitmap.Height; ++row)
- {
- if (IsTransparentRow(bitmap, row))
- {
- topmost = row + 1;
- }
- else
- {
- break;
- }
- }
-
- int bottommost = bitmap.Height;
- for (int row = bitmap.Height - 1; row >= 0; --row)
- {
- if (IsTransparentRow(bitmap, row))
- {
- bottommost = row;
- }
- else
- {
- break;
- }
- }
-
- int leftmost = 0, rightmost = bitmap.Width;
- for (int col = 0; col < bitmap.Width; ++col)
+ if (!File.Exists(path))
{
- if (IsTransparentColumn(bitmap, col))
- {
- leftmost = col + 1;
- }
- else
- {
- break;
- }
+ throw new FileNotFoundException("File not found", path);
}
- for (int col = bitmap.Width - 1; col >= 0; --col)
- {
- if (IsTransparentColumn(bitmap, col))
- {
- rightmost = col;
- }
- else
- {
- break;
- }
- }
+ using var codec = SKCodec.Create(path, out SKCodecResult result);
+ EnsureSuccess(result);
- var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
+ var info = codec.Info;
- using (var image = SKImage.FromBitmap(bitmap))
- using (var subset = image.Subset(newRect))
- {
- return SKBitmap.FromImage(subset);
- }
+ return new ImageDimensions(info.Width, info.Height);
}
- public ImageDimensions GetImageSize(string path)
+ /// <inheritdoc />
+ /// <exception cref="ArgumentNullException">The path is null.</exception>
+ /// <exception cref="FileNotFoundException">The path is not valid.</exception>
+ /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
+ public string GetImageBlurHash(int xComp, int yComp, string path)
{
- using (var s = new SKFileStream(path))
- using (var codec = SKCodec.Create(s))
+ if (path == null)
{
- var info = codec.Info;
-
- return new ImageDimensions(info.Width, info.Height);
+ throw new ArgumentNullException(nameof(path));
}
- }
- private static bool HasDiacritics(string text)
- => !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
+ // Any larger than 128x128 is too slow and there's no visually discernible difference
+ return BlurHashEncoder.Encode(xComp, yComp, path, 128, 128);
+ }
- private static bool RequiresSpecialCharacterHack(string path)
+ private bool RequiresSpecialCharacterHack(string path)
{
- if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter))
- {
- return true;
- }
-
- if (HasDiacritics(path))
+ for (int i = 0; i < path.Length; i++)
{
- return true;
+ if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter)
+ {
+ return true;
+ }
}
- return false;
+ return path.HasDiacritics();
}
- private static string NormalizePath(string path, IFileSystem fileSystem)
+ private string NormalizePath(string path)
{
if (!RequiresSpecialCharacterHack(path))
{
return path;
}
- var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
-
- Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
+ var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
+ var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException($"Provided path ({tempPath}) is not valid.");
+ Directory.CreateDirectory(directory);
File.Copy(path, tempPath, true);
return tempPath;
@@ -234,67 +177,61 @@ namespace Jellyfin.Drawing.Skia
return SKEncodedOrigin.TopLeft;
}
- switch (orientation.Value)
- {
- case ImageOrientation.TopRight:
- return SKEncodedOrigin.TopRight;
- case ImageOrientation.RightTop:
- return SKEncodedOrigin.RightTop;
- case ImageOrientation.RightBottom:
- return SKEncodedOrigin.RightBottom;
- case ImageOrientation.LeftTop:
- return SKEncodedOrigin.LeftTop;
- case ImageOrientation.LeftBottom:
- return SKEncodedOrigin.LeftBottom;
- case ImageOrientation.BottomRight:
- return SKEncodedOrigin.BottomRight;
- case ImageOrientation.BottomLeft:
- return SKEncodedOrigin.BottomLeft;
- default:
- return SKEncodedOrigin.TopLeft;
- }
+ return orientation.Value switch
+ {
+ ImageOrientation.TopRight => SKEncodedOrigin.TopRight,
+ ImageOrientation.RightTop => SKEncodedOrigin.RightTop,
+ ImageOrientation.RightBottom => SKEncodedOrigin.RightBottom,
+ ImageOrientation.LeftTop => SKEncodedOrigin.LeftTop,
+ ImageOrientation.LeftBottom => SKEncodedOrigin.LeftBottom,
+ ImageOrientation.BottomRight => SKEncodedOrigin.BottomRight,
+ ImageOrientation.BottomLeft => SKEncodedOrigin.BottomLeft,
+ _ => SKEncodedOrigin.TopLeft
+ };
}
- private static readonly HashSet<string> TransparentImageTypes
- = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" };
-
- internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKEncodedOrigin origin)
+ /// <summary>
+ /// Decode an image.
+ /// </summary>
+ /// <param name="path">The filepath of the image to decode.</param>
+ /// <param name="forceCleanBitmap">Whether to force clean the bitmap.</param>
+ /// <param name="orientation">The orientation of the image.</param>
+ /// <param name="origin">The detected origin of the image.</param>
+ /// <returns>The resulting bitmap of the image.</returns>
+ internal SKBitmap? Decode(string path, bool forceCleanBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("File not found", path);
}
- var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path));
+ var requiresTransparencyHack = _transparentImageTypes.Contains(Path.GetExtension(path));
if (requiresTransparencyHack || forceCleanBitmap)
{
- using (var stream = new SKFileStream(NormalizePath(path, fileSystem)))
- using (var codec = SKCodec.Create(stream))
+ using SKCodec codec = SKCodec.Create(NormalizePath(path), out SKCodecResult res);
+ if (res != SKCodecResult.Success)
{
- if (codec == null)
- {
- origin = GetSKEncodedOrigin(orientation);
- return null;
- }
+ origin = GetSKEncodedOrigin(orientation);
+ return null;
+ }
- // create the bitmap
- var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
+ // create the bitmap
+ var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
- // decode
- _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
+ // decode
+ _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
- origin = codec.EncodedOrigin;
+ origin = codec.EncodedOrigin;
- return bitmap;
- }
+ return bitmap;
}
- var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));
+ var resultBitmap = SKBitmap.Decode(NormalizePath(path));
if (resultBitmap == null)
{
- return Decode(path, true, fileSystem, orientation, out origin);
+ return Decode(path, true, orientation, out origin);
}
// If we have to resize these they often end up distorted
@@ -302,7 +239,7 @@ namespace Jellyfin.Drawing.Skia
{
using (resultBitmap)
{
- return Decode(path, true, fileSystem, orientation, out origin);
+ return Decode(path, true, orientation, out origin);
}
}
@@ -310,26 +247,11 @@ namespace Jellyfin.Drawing.Skia
return resultBitmap;
}
- private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
+ private SKBitmap? GetBitmap(string path, bool autoOrient, ImageOrientation? orientation)
{
- if (cropWhitespace)
- {
- using (var bitmap = Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin))
- {
- return CropWhiteSpace(bitmap);
- }
- }
-
- return Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin);
- }
-
- private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
- {
- SKEncodedOrigin origin;
-
if (autoOrient)
{
- var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
+ var bitmap = Decode(path, true, orientation, out var origin);
if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
{
@@ -342,281 +264,231 @@ namespace Jellyfin.Drawing.Skia
return bitmap;
}
- return GetBitmap(path, cropWhitespace, false, orientation, out origin);
+ return Decode(path, false, orientation, out _);
}
private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
{
- //var transformations = {
- // 2: { rotate: 0, flip: true},
- // 3: { rotate: 180, flip: false},
- // 4: { rotate: 180, flip: true},
- // 5: { rotate: 90, flip: true},
- // 6: { rotate: 90, flip: false},
- // 7: { rotate: 270, flip: true},
- // 8: { rotate: 270, flip: false},
- //}
+ var needsFlip = origin == SKEncodedOrigin.LeftBottom
+ || origin == SKEncodedOrigin.LeftTop
+ || origin == SKEncodedOrigin.RightBottom
+ || origin == SKEncodedOrigin.RightTop;
+ var rotated = needsFlip
+ ? new SKBitmap(bitmap.Height, bitmap.Width)
+ : new SKBitmap(bitmap.Width, bitmap.Height);
+ using var surface = new SKCanvas(rotated);
+ var midX = (float)rotated.Width / 2;
+ var midY = (float)rotated.Height / 2;
switch (origin)
{
case SKEncodedOrigin.TopRight:
- {
- var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
- using (var surface = new SKCanvas(rotated))
- {
- surface.Translate(rotated.Width, 0);
- surface.Scale(-1, 1);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- return rotated;
- }
-
+ surface.Scale(-1, 1, midX, midY);
+ break;
case SKEncodedOrigin.BottomRight:
- {
- var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
- using (var surface = new SKCanvas(rotated))
- {
- float px = (float)bitmap.Width / 2;
- float py = (float)bitmap.Height / 2;
-
- surface.RotateDegrees(180, px, py);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- return rotated;
- }
-
+ surface.RotateDegrees(180, midX, midY);
+ break;
case SKEncodedOrigin.BottomLeft:
- {
- var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
- using (var surface = new SKCanvas(rotated))
- {
- float px = (float)bitmap.Width / 2;
-
- float py = (float)bitmap.Height / 2;
-
- surface.Translate(rotated.Width, 0);
- surface.Scale(-1, 1);
-
- surface.RotateDegrees(180, px, py);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- return rotated;
- }
-
+ surface.Scale(1, -1, midX, midY);
+ break;
case SKEncodedOrigin.LeftTop:
- {
- // TODO: Remove dual canvases, had trouble with flipping
- using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
- {
- using (var surface = new SKCanvas(rotated))
- {
- surface.Translate(rotated.Width, 0);
-
- surface.RotateDegrees(90);
-
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
- using (var flippedCanvas = new SKCanvas(flippedBitmap))
- {
- flippedCanvas.Translate(flippedBitmap.Width, 0);
- flippedCanvas.Scale(-1, 1);
- flippedCanvas.DrawBitmap(rotated, 0, 0);
- }
-
- return flippedBitmap;
- }
- }
-
+ surface.Translate(0, -rotated.Height);
+ surface.Scale(1, -1, midX, midY);
+ surface.RotateDegrees(-90);
+ break;
case SKEncodedOrigin.RightTop:
- {
- var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
- using (var surface = new SKCanvas(rotated))
- {
- surface.Translate(rotated.Width, 0);
- surface.RotateDegrees(90);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- return rotated;
- }
-
+ surface.Translate(rotated.Width, 0);
+ surface.RotateDegrees(90);
+ break;
case SKEncodedOrigin.RightBottom:
- {
- // TODO: Remove dual canvases, had trouble with flipping
- using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
- {
- using (var surface = new SKCanvas(rotated))
- {
- surface.Translate(0, rotated.Height);
- surface.RotateDegrees(270);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
- using (var flippedCanvas = new SKCanvas(flippedBitmap))
- {
- flippedCanvas.Translate(flippedBitmap.Width, 0);
- flippedCanvas.Scale(-1, 1);
- flippedCanvas.DrawBitmap(rotated, 0, 0);
- }
-
- return flippedBitmap;
- }
- }
-
+ surface.Translate(rotated.Width, 0);
+ surface.Scale(1, -1, midX, midY);
+ surface.RotateDegrees(90);
+ break;
case SKEncodedOrigin.LeftBottom:
- {
- var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
- using (var surface = new SKCanvas(rotated))
- {
- surface.Translate(0, rotated.Height);
- surface.RotateDegrees(270);
- surface.DrawBitmap(bitmap, 0, 0);
- }
-
- return rotated;
- }
-
- default: return bitmap;
+ surface.Translate(0, rotated.Height);
+ surface.RotateDegrees(-90);
+ break;
}
+
+ surface.DrawBitmap(bitmap, 0, 0);
+ return rotated;
+ }
+
+ /// <summary>
+ /// Resizes an image on the CPU, by utilizing a surface and canvas.
+ ///
+ /// The convolutional matrix kernel used in this resize function gives a (light) sharpening effect.
+ /// This technique is similar to effect that can be created using for example the [Convolution matrix filter in GIMP](https://docs.gimp.org/2.10/en/gimp-filter-convolution-matrix.html).
+ /// </summary>
+ /// <param name="source">The source bitmap.</param>
+ /// <param name="targetInfo">This specifies the target size and other information required to create the surface.</param>
+ /// <param name="isAntialias">This enables anti-aliasing on the SKPaint instance.</param>
+ /// <param name="isDither">This enables dithering on the SKPaint instance.</param>
+ /// <returns>The resized image.</returns>
+ internal static SKImage ResizeImage(SKBitmap source, SKImageInfo targetInfo, bool isAntialias = false, bool isDither = false)
+ {
+ using var surface = SKSurface.Create(targetInfo);
+ using var canvas = surface.Canvas;
+ using var paint = new SKPaint
+ {
+ FilterQuality = SKFilterQuality.High,
+ IsAntialias = isAntialias,
+ IsDither = isDither
+ };
+
+ var kernel = new float[9]
+ {
+ 0, -.1f, 0,
+ -.1f, 1.4f, -.1f,
+ 0, -.1f, 0,
+ };
+
+ var kernelSize = new SKSizeI(3, 3);
+ var kernelOffset = new SKPointI(1, 1);
+
+ paint.ImageFilter = SKImageFilter.CreateMatrixConvolution(
+ kernelSize,
+ kernel,
+ 1f,
+ 0f,
+ kernelOffset,
+ SKShaderTileMode.Clamp,
+ true);
+
+ canvas.DrawBitmap(
+ source,
+ SKRect.Create(0, 0, source.Width, source.Height),
+ SKRect.Create(0, 0, targetInfo.Width, targetInfo.Height),
+ paint);
+
+ return surface.Snapshot();
}
- public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
+ /// <inheritdoc/>
+ public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat)
{
- if (string.IsNullOrWhiteSpace(inputPath))
+ if (inputPath.Length == 0)
{
- throw new ArgumentNullException(nameof(inputPath));
+ throw new ArgumentException("String can't be empty.", nameof(inputPath));
}
- if (string.IsNullOrWhiteSpace(inputPath))
+ if (outputPath.Length == 0)
{
- throw new ArgumentNullException(nameof(outputPath));
+ throw new ArgumentException("String can't be empty.", nameof(outputPath));
}
- var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
+ var skiaOutputFormat = GetImageFormat(outputFormat);
var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
var blur = options.Blur ?? 0;
var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
- using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
+ using var bitmap = GetBitmap(inputPath, autoOrient, orientation);
+ if (bitmap == null)
{
- if (bitmap == null)
- {
- throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
- }
+ throw new InvalidDataException($"Skia unable to read image {inputPath}");
+ }
- var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
+ var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
- if (!options.CropWhiteSpace
- && options.HasDefaultOptions(inputPath, originalImageSize)
- && !autoOrient)
- {
- // Just spit out the original file if all the options are default
- return inputPath;
- }
+ if (options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
+ {
+ // Just spit out the original file if all the options are default
+ return inputPath;
+ }
+
+ var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
+
+ var width = newImageSize.Width;
+ var height = newImageSize.Height;
- var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
+ // scale image (the FromImage creates a copy)
+ var imageInfo = new SKImageInfo(width, height, bitmap.ColorType, bitmap.AlphaType, bitmap.ColorSpace);
+ using var resizedBitmap = SKBitmap.FromImage(ResizeImage(bitmap, imageInfo));
- var width = newImageSize.Width;
- var height = newImageSize.Height;
+ // If all we're doing is resizing then we can stop now
+ if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
+ {
+ var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(outputDirectory);
+ using var outputStream = new SKFileWStream(outputPath);
+ using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
+ resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
+ return outputPath;
+ }
- using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
+ // create bitmap to use for canvas drawing used to draw into bitmap
+ using var saveBitmap = new SKBitmap(width, height);
+ using var canvas = new SKCanvas(saveBitmap);
+ // set background color if present
+ if (hasBackgroundColor)
+ {
+ canvas.Clear(SKColor.Parse(options.BackgroundColor));
+ }
+
+ // 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));
+ }
+
+ // If foreground layer present then draw
+ if (hasForegroundColor)
+ {
+ if (!double.TryParse(options.ForegroundLayer, out double opacity))
{
- // scale image
- bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
+ opacity = .4;
+ }
- // If all we're doing is resizing then we can stop now
- if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
- {
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
- using (var outputStream = new SKFileWStream(outputPath))
- using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
- {
- pixmap.Encode(outputStream, skiaOutputFormat, quality);
- return outputPath;
- }
- }
+ canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
+ }
- // create bitmap to use for canvas drawing used to draw into bitmap
- using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
- using (var canvas = new SKCanvas(saveBitmap))
- {
- // set background color if present
- if (hasBackgroundColor)
- {
- canvas.Clear(SKColor.Parse(options.BackgroundColor));
- }
-
- // 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));
- }
-
- // If foreground layer present then draw
- if (hasForegroundColor)
- {
- if (!double.TryParse(options.ForegroundLayer, out double opacity))
- {
- opacity = .4;
- }
-
- canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
- }
-
- if (hasIndicator)
- {
- DrawIndicator(canvas, width, height, options);
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
- using (var outputStream = new SKFileWStream(outputPath))
- {
- using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
- {
- pixmap.Encode(outputStream, skiaOutputFormat, quality);
- }
- }
- }
+ if (hasIndicator)
+ {
+ DrawIndicator(canvas, width, height, options);
+ }
+
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(directory);
+ using (var outputStream = new SKFileWStream(outputPath))
+ {
+ using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
+ {
+ pixmap.Encode(outputStream, skiaOutputFormat, quality);
}
}
+
return outputPath;
}
- public void CreateImageCollage(ImageCollageOptions options)
+ /// <inheritdoc/>
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
double ratio = (double)options.Width / options.Height;
if (ratio >= 1.4)
{
- new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
+ new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, libraryName);
}
else if (ratio >= .9)
{
- new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
+ new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
}
else
{
// TODO: Create Poster collage capability
- new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
+ new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
}
}
@@ -645,11 +517,5 @@ namespace Jellyfin.Drawing.Skia
_logger.LogError(ex, "Error drawing indicator overlay");
}
}
-
- public string Name => "Skia";
-
- public bool SupportsImageCollageCreation => true;
-
- public bool SupportsImageEncoding => true;
}
}
diff --git a/Jellyfin.Drawing.Skia/SkiaException.cs b/Jellyfin.Drawing.Skia/SkiaException.cs
new file mode 100644
index 000000000..5b272eac5
--- /dev/null
+++ b/Jellyfin.Drawing.Skia/SkiaException.cs
@@ -0,0 +1,39 @@
+using System;
+
+namespace Jellyfin.Drawing.Skia
+{
+ /// <summary>
+ /// Represents errors that occur during interaction with Skia.
+ /// </summary>
+ public class SkiaException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaException"/> class.
+ /// </summary>
+ public SkiaException()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public SkiaException(string message) : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkiaException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The error message that explains the reason for the exception.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if
+ /// no inner exception is specified.
+ /// </param>
+ public SkiaException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Drawing.Skia/SkiaHelper.cs b/Jellyfin.Drawing.Skia/SkiaHelper.cs
new file mode 100644
index 000000000..f9c79c855
--- /dev/null
+++ b/Jellyfin.Drawing.Skia/SkiaHelper.cs
@@ -0,0 +1,23 @@
+using SkiaSharp;
+
+namespace Jellyfin.Drawing.Skia
+{
+ /// <summary>
+ /// Class containing helper methods for working with SkiaSharp.
+ /// </summary>
+ public static class SkiaHelper
+ {
+ /// <summary>
+ /// Ensures the result is a success
+ /// by throwing an exception when that's not the case.
+ /// </summary>
+ /// <param name="result">The result returned by Skia.</param>
+ public static void EnsureSuccess(SKCodecResult result)
+ {
+ if (result != SKCodecResult.Success)
+ {
+ throw new SkiaCodecException(result);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
index dfdf39871..d1cc2255d 100644
--- a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
+++ b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
@@ -1,23 +1,32 @@
using System;
using System.Collections.Generic;
using System.IO;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.IO;
+using System.Text.RegularExpressions;
using SkiaSharp;
namespace Jellyfin.Drawing.Skia
{
+ /// <summary>
+ /// Used to build collages of multiple images arranged in vertical strips.
+ /// </summary>
public class StripCollageBuilder
{
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
+ private readonly SkiaEncoder _skiaEncoder;
- public StripCollageBuilder(IApplicationPaths appPaths, IFileSystem fileSystem)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StripCollageBuilder"/> class.
+ /// </summary>
+ /// <param name="skiaEncoder">The encoder to use for building collages.</param>
+ public StripCollageBuilder(SkiaEncoder skiaEncoder)
{
- _appPaths = appPaths;
- _fileSystem = fileSystem;
+ _skiaEncoder = skiaEncoder;
}
+ /// <summary>
+ /// Check which format an image has been encoded with using its filename extension.
+ /// </summary>
+ /// <param name="outputPath">The path to the image to get the format for.</param>
+ /// <returns>The image format.</returns>
public static SKEncodedImageFormat GetEncodedFormat(string outputPath)
{
if (outputPath == null)
@@ -25,149 +34,137 @@ namespace Jellyfin.Drawing.Skia
throw new ArgumentNullException(nameof(outputPath));
}
- var ext = Path.GetExtension(outputPath).ToLowerInvariant();
+ var ext = Path.GetExtension(outputPath);
- if (ext == ".jpg" || ext == ".jpeg")
+ if (string.Equals(ext, ".jpg", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(ext, ".jpeg", StringComparison.OrdinalIgnoreCase))
+ {
return SKEncodedImageFormat.Jpeg;
+ }
- if (ext == ".webp")
+ if (string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase))
+ {
return SKEncodedImageFormat.Webp;
+ }
- if (ext == ".gif")
+ if (string.Equals(ext, ".gif", StringComparison.OrdinalIgnoreCase))
+ {
return SKEncodedImageFormat.Gif;
+ }
- if (ext == ".bmp")
+ if (string.Equals(ext, ".bmp", StringComparison.OrdinalIgnoreCase))
+ {
return SKEncodedImageFormat.Bmp;
+ }
// default to png
return SKEncodedImageFormat.Png;
}
- public void BuildSquareCollage(string[] paths, string outputPath, int width, int height)
+ /// <summary>
+ /// Create a square collage.
+ /// </summary>
+ /// <param name="paths">The paths of the images to use in the collage.</param>
+ /// <param name="outputPath">The path at which to place the resulting collage image.</param>
+ /// <param name="width">The desired width of the collage.</param>
+ /// <param name="height">The desired height of the collage.</param>
+ public void BuildSquareCollage(IReadOnlyList<string> paths, string outputPath, int width, int height)
{
- using (var bitmap = BuildSquareCollageBitmap(paths, width, height))
- using (var outputStream = new SKFileWStream(outputPath))
- {
- using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
- {
- pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
- }
- }
+ using var bitmap = BuildSquareCollageBitmap(paths, width, height);
+ using var outputStream = new SKFileWStream(outputPath);
+ using var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels());
+ pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
- public void BuildThumbCollage(string[] paths, string outputPath, int width, int height)
+ /// <summary>
+ /// Create a thumb collage.
+ /// </summary>
+ /// <param name="paths">The paths of the images to use in the collage.</param>
+ /// <param name="outputPath">The path at which to place the resulting image.</param>
+ /// <param name="width">The desired width of the collage.</param>
+ /// <param name="height">The desired height of the collage.</param>
+ /// <param name="libraryName">The name of the library to draw on the collage.</param>
+ public void BuildThumbCollage(IReadOnlyList<string> paths, string outputPath, int width, int height, string? libraryName)
{
- using (var bitmap = BuildThumbCollageBitmap(paths, width, height))
- {
- using (var outputStream = new SKFileWStream(outputPath))
- {
- using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
- {
- pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
- }
- }
- }
+ using var bitmap = BuildThumbCollageBitmap(paths, width, height, libraryName);
+ using var outputStream = new SKFileWStream(outputPath);
+ using var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels());
+ pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
- private SKBitmap BuildThumbCollageBitmap(string[] paths, int width, int height)
+ private SKBitmap BuildThumbCollageBitmap(IReadOnlyList<string> paths, int width, int height, string? libraryName)
{
var bitmap = new SKBitmap(width, height);
- using (var canvas = new SKCanvas(bitmap))
+ using var canvas = new SKCanvas(bitmap);
+ canvas.Clear(SKColors.Black);
+
+ using var backdrop = GetNextValidImage(paths, 0, out _);
+ if (backdrop == null)
{
- canvas.Clear(SKColors.Black);
+ return bitmap;
+ }
- // determine sizes for each image that will composited into the final image
- var iSlice = Convert.ToInt32(width * 0.23475);
- int iTrans = Convert.ToInt32(height * .25);
- int iHeight = Convert.ToInt32(height * .70);
- var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
- var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
- int imageIndex = 0;
+ // 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));
+ // draw the backdrop
+ canvas.DrawImage(residedBackdrop, 0, 0);
- for (int i = 0; i < 4; i++)
- {
+ // draw shadow rectangle
+ using var paintColor = new SKPaint
+ {
+ Color = SKColors.Black.WithAlpha(0x78),
+ Style = SKPaintStyle.Fill
+ };
+ canvas.DrawRect(0, 0, width, height, paintColor);
- using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
- {
- imageIndex = newIndex;
-
- if (currentBitmap == null)
- {
- continue;
- }
-
- // resize to the same aspect as the original
- int iWidth = (int)Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height);
- using (var resizeBitmap = new SKBitmap(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
- {
- currentBitmap.ScalePixels(resizeBitmap, SKFilterQuality.High);
- // crop image
- int ix = (int)Math.Abs((iWidth - iSlice) / 2);
- using (var image = SKImage.FromBitmap(resizeBitmap))
- using (var subset = image.Subset(SKRectI.Create(ix, 0, iSlice, iHeight)))
- {
- // draw image onto canvas
- canvas.DrawImage(subset ?? image, (horizontalImagePadding * (i + 1)) + (iSlice * i), verticalSpacing);
-
- if (subset == null)
- {
- continue;
- }
- // create reflection of image below the drawn image
- using (var croppedBitmap = SKBitmap.FromImage(subset))
- using (var reflectionBitmap = new SKBitmap(croppedBitmap.Width, croppedBitmap.Height / 2, croppedBitmap.ColorType, croppedBitmap.AlphaType))
- {
- // resize to half height
- currentBitmap.ScalePixels(reflectionBitmap, SKFilterQuality.High);
-
- using (var flippedBitmap = new SKBitmap(reflectionBitmap.Width, reflectionBitmap.Height, reflectionBitmap.ColorType, reflectionBitmap.AlphaType))
- using (var flippedCanvas = new SKCanvas(flippedBitmap))
- {
- // flip image vertically
- var matrix = SKMatrix.MakeScale(1, -1);
- matrix.SetScaleTranslate(1, -1, 0, flippedBitmap.Height);
- flippedCanvas.SetMatrix(matrix);
- flippedCanvas.DrawBitmap(reflectionBitmap, 0, 0);
- flippedCanvas.ResetMatrix();
-
- // create gradient to make image appear as a reflection
- var remainingHeight = height - (iHeight + (2 * verticalSpacing));
- flippedCanvas.ClipRect(SKRect.Create(reflectionBitmap.Width, remainingHeight));
- using (var gradient = new SKPaint())
- {
- gradient.IsAntialias = true;
- gradient.BlendMode = SKBlendMode.SrcOver;
- gradient.Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, remainingHeight), new[] { new SKColor(0, 0, 0, 128), new SKColor(0, 0, 0, 208), new SKColor(0, 0, 0, 240), new SKColor(0, 0, 0, 255) }, null, SKShaderTileMode.Clamp);
- flippedCanvas.DrawPaint(gradient);
- }
-
- // finally draw reflection onto canvas
- canvas.DrawBitmap(flippedBitmap, (horizontalImagePadding * (i + 1)) + (iSlice * i), iHeight + (2 * verticalSpacing));
- }
- }
- }
- }
- }
- }
+ var typeFace = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright);
+
+ // use the system fallback to find a typeface for the given CJK character
+ var nonCjkPattern = @"[^\p{IsCJKUnifiedIdeographs}\p{IsCJKUnifiedIdeographsExtensionA}\p{IsKatakana}\p{IsHiragana}\p{IsHangulSyllables}\p{IsHangulJamo}]";
+ var filteredName = Regex.Replace(libraryName ?? string.Empty, nonCjkPattern, string.Empty);
+ if (!string.IsNullOrEmpty(filteredName))
+ {
+ typeFace = SKFontManager.Default.MatchCharacter(null, SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright, null, filteredName[0]);
}
+ // draw library name
+ using var textPaint = new SKPaint
+ {
+ Color = SKColors.White,
+ Style = SKPaintStyle.Fill,
+ TextSize = 112,
+ TextAlign = SKTextAlign.Center,
+ Typeface = typeFace,
+ IsAntialias = true
+ };
+
+ // scale down text to 90% of the width if text is larger than 95% of the width
+ var textWidth = textPaint.MeasureText(libraryName);
+ if (textWidth > width * 0.95)
+ {
+ textPaint.TextSize = 0.9f * width * textPaint.TextSize / textWidth;
+ }
+
+ canvas.DrawText(libraryName, width / 2f, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), textPaint);
+
return bitmap;
}
- private SKBitmap GetNextValidImage(string[] paths, int currentIndex, out int newIndex)
+ private SKBitmap? GetNextValidImage(IReadOnlyList<string> paths, int currentIndex, out int newIndex)
{
var imagesTested = new Dictionary<int, int>();
- SKBitmap bitmap = null;
+ SKBitmap? bitmap = null;
- while (imagesTested.Count < paths.Length)
+ while (imagesTested.Count < paths.Count)
{
- if (currentIndex >= paths.Length)
+ if (currentIndex >= paths.Count)
{
currentIndex = 0;
}
- bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out var origin);
+ bitmap = _skiaEncoder.Decode(paths[currentIndex], false, null, out _);
imagesTested[currentIndex] = 0;
@@ -183,41 +180,34 @@ namespace Jellyfin.Drawing.Skia
return bitmap;
}
- private SKBitmap BuildSquareCollageBitmap(string[] paths, int width, int height)
+ private SKBitmap BuildSquareCollageBitmap(IReadOnlyList<string> paths, int width, int height)
{
var bitmap = new SKBitmap(width, height);
var imageIndex = 0;
var cellWidth = width / 2;
var cellHeight = height / 2;
- using (var canvas = new SKCanvas(bitmap))
+ using var canvas = new SKCanvas(bitmap);
+ for (var x = 0; x < 2; x++)
{
- for (var x = 0; x < 2; x++)
+ for (var y = 0; y < 2; y++)
{
- for (var y = 0; y < 2; y++)
- {
+ using var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex);
+ imageIndex = newIndex;
- using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
- {
- imageIndex = newIndex;
-
- if (currentBitmap == null)
- {
- continue;
- }
-
- using (var resizedBitmap = new SKBitmap(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
- {
- // scale image
- currentBitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
-
- // draw this image into the strip at the next position
- var xPos = x * cellWidth;
- var yPos = y * cellHeight;
- canvas.DrawBitmap(resizedBitmap, xPos, yPos);
- }
- }
+ if (currentBitmap == null)
+ {
+ continue;
}
+
+ // Scale image. The FromBitmap creates a copy
+ var imageInfo = new SKImageInfo(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType, currentBitmap.ColorSpace);
+ using var resizedBitmap = SKBitmap.FromImage(SkiaEncoder.ResizeImage(currentBitmap, imageInfo));
+
+ // draw this image into the strip at the next position
+ var xPos = x * cellWidth;
+ var yPos = y * cellHeight;
+ canvas.DrawBitmap(resizedBitmap, xPos, yPos);
}
}
diff --git a/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs b/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
index ba712bff7..58f887c96 100644
--- a/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
+++ b/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
@@ -4,48 +4,61 @@ using SkiaSharp;
namespace Jellyfin.Drawing.Skia
{
+ /// <summary>
+ /// Static helper class for drawing unplayed count indicators.
+ /// </summary>
public static class UnplayedCountIndicator
{
+ /// <summary>
+ /// The x-offset used when drawing an unplayed count indicator.
+ /// </summary>
private const int OffsetFromTopRightCorner = 38;
+ /// <summary>
+ /// Draw an unplayed count indicator in the top right corner of a canvas.
+ /// </summary>
+ /// <param name="canvas">The canvas to draw the indicator on.</param>
+ /// <param name="imageSize">
+ /// The dimensions of the image to draw the indicator on. The width is used to determine the x-position of the
+ /// indicator.
+ /// </param>
+ /// <param name="count">The number to draw in the indicator.</param>
public static void DrawUnplayedCountIndicator(SKCanvas canvas, ImageDimensions imageSize, int count)
{
var x = imageSize.Width - OffsetFromTopRightCorner;
var text = count.ToString(CultureInfo.InvariantCulture);
- using (var paint = new SKPaint())
+ using var paint = new SKPaint
{
- paint.Color = SKColor.Parse("#CC52B54B");
- paint.Style = SKPaintStyle.Fill;
- canvas.DrawCircle((float)x, OffsetFromTopRightCorner, 20, paint);
+ Color = SKColor.Parse("#CC00A4DC"),
+ Style = SKPaintStyle.Fill
+ };
+
+ canvas.DrawCircle(x, OffsetFromTopRightCorner, 20, paint);
+
+ paint.Color = new SKColor(255, 255, 255, 255);
+ paint.TextSize = 24;
+ paint.IsAntialias = true;
+
+ var y = OffsetFromTopRightCorner + 9;
+
+ if (text.Length == 1)
+ {
+ x -= 7;
}
- using (var paint = new SKPaint())
+
+ if (text.Length == 2)
+ {
+ x -= 13;
+ }
+ else if (text.Length >= 3)
{
- paint.Color = new SKColor(255, 255, 255, 255);
- paint.Style = SKPaintStyle.Fill;
-
- paint.TextSize = 24;
- paint.IsAntialias = true;
-
- var y = OffsetFromTopRightCorner + 9;
-
- if (text.Length == 1)
- {
- x -= 7;
- }
- if (text.Length == 2)
- {
- x -= 13;
- }
- else if (text.Length >= 3)
- {
- x -= 15;
- y -= 2;
- paint.TextSize = 18;
- }
-
- canvas.DrawText(text, (float)x, y, paint);
+ x -= 15;
+ y -= 2;
+ paint.TextSize = 18;
}
+
+ canvas.DrawText(text, x, y, paint);
}
}
}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
new file mode 100644
index 000000000..61db223d9
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
@@ -0,0 +1,235 @@
+#pragma warning disable CA1819 // Properties should not return arrays
+
+using System;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfiguration" />.
+ /// </summary>
+ public class NetworkConfiguration
+ {
+ /// <summary>
+ /// The default value for <see cref="HttpServerPortNumber"/>.
+ /// </summary>
+ public const int DefaultHttpPort = 8096;
+
+ /// <summary>
+ /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>.
+ /// </summary>
+ public const int DefaultHttpsPort = 8920;
+
+ private string _baseUrl = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the server should force connections over HTTPS.
+ /// </summary>
+ public bool RequireHttps { get; set; }
+
+ /// <summary>
+ /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
+ /// </summary>
+ public string CertificatePath { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
+ /// </summary>
+ public string CertificatePassword { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
+ /// </summary>
+ public string BaseUrl
+ {
+ get => _baseUrl;
+ set
+ {
+ // Normalize the start of the string
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ // If baseUrl is empty, set an empty prefix string
+ _baseUrl = string.Empty;
+ return;
+ }
+
+ if (value[0] != '/')
+ {
+ // If baseUrl was not configured with a leading slash, append one for consistency
+ value = "/" + value;
+ }
+
+ // Normalize the end of the string
+ if (value[^1] == '/')
+ {
+ // If baseUrl was configured with a trailing slash, remove it for consistency
+ value = value.Remove(value.Length - 1);
+ }
+
+ _baseUrl = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the public HTTPS port.
+ /// </summary>
+ /// <value>The public HTTPS port.</value>
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
+
+ /// <summary>
+ /// Gets or sets the HTTP server port number.
+ /// </summary>
+ /// <value>The HTTP server port number.</value>
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets the HTTPS server port number.
+ /// </summary>
+ /// <value>The HTTPS server port number.</value>
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to use HTTPS.
+ /// </summary>
+ /// <remarks>
+ /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be
+ /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>.
+ /// </remarks>
+ public bool EnableHttps { get; set; }
+
+ /// <summary>
+ /// Gets or sets the public mapped port.
+ /// </summary>
+ /// <value>The public mapped port.</value>
+ public int PublicPort { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
+ /// </summary>
+ public bool UPnPCreateHttpPortMap { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UDPPortRange.
+ /// </summary>
+ public string UDPPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets IPV6 capability.
+ /// </summary>
+ public bool EnableIPV6 { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets IPV4 capability.
+ /// </summary>
+ public bool EnableIPV4 { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log.
+ /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect.
+ /// </summary>
+ public bool EnableSSDPTracing { get; set; }
+
+ /// <summary>
+ /// Gets or sets the SSDPTracingFilter
+ /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
+ /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public string SSDPTracingFilter { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the number of times SSDP UDP messages are sent.
+ /// </summary>
+ public int UDPSendCount { get; set; } = 2;
+
+ /// <summary>
+ /// Gets or sets the delay between each groups of SSDP messages (in ms).
+ /// </summary>
+ public int UDPSendDelay { get; set; } = 100;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
+ /// </summary>
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
+ /// </summary>
+ public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+
+ /// <summary>
+ /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
+ /// </summary>
+ public int GatewayMonitorPeriod { get; set; } = 60;
+
+ /// <summary>
+ /// Gets a value indicating whether multi-socket binding is available.
+ /// </summary>
+ public bool EnableMultiSocketBinding { get; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
+ /// Depending on the address range implemented ULA ranges might not be used.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ports that HDHomerun uses.
+ /// </summary>
+ public string HDHomerunPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the PublishedServerUriBySubnet
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ /// </summary>
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
+ /// </summary>
+ public bool AutoDiscoveryTracing { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery is enabled.
+ /// </summary>
+ public bool AutoDiscovery { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
+ /// </summary>
+ public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
+ /// </summary>
+ public bool IsRemoteIPFilterBlacklist { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable automatic port forwarding.
+ /// </summary>
+ public bool EnableUPnP { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// </summary>
+ public bool EnableRemoteAccess { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the subnets that are deemed to make up the LAN.
+ /// </summary>
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
+ /// </summary>
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks.
+ /// </summary>
+ public string[] KnownProxies { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests.
+ /// </summary>
+ public bool EnablePublishedServerUriByRequest { get; set; } = false;
+ }
+}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
new file mode 100644
index 000000000..8cbe398b0
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
@@ -0,0 +1,20 @@
+using MediaBrowser.Common.Configuration;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfigurationExtensions" />.
+ /// </summary>
+ public static class NetworkConfigurationExtensions
+ {
+ /// <summary>
+ /// Retrieves the network configuration.
+ /// </summary>
+ /// <param name="config">The <see cref="IConfigurationManager"/>.</param>
+ /// <returns>The <see cref="NetworkConfiguration"/>.</returns>
+ public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config)
+ {
+ return config.GetConfiguration<NetworkConfiguration>("network");
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs
new file mode 100644
index 000000000..ac0485d87
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs
@@ -0,0 +1,27 @@
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfigurationFactory" />.
+ /// </summary>
+ public class NetworkConfigurationFactory : IConfigurationFactory
+ {
+ /// <summary>
+ /// The GetConfigurations.
+ /// </summary>
+ /// <returns>The <see cref="IEnumerable{ConfigurationStore}"/>.</returns>
+ public IEnumerable<ConfigurationStore> GetConfigurations()
+ {
+ return new[]
+ {
+ new ConfigurationStore
+ {
+ Key = "network",
+ ConfigurationType = typeof(NetworkConfiguration)
+ }
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj
new file mode 100644
index 000000000..0cd9a5915
--- /dev/null
+++ b/Jellyfin.Networking/Jellyfin.Networking.csproj
@@ -0,0 +1,23 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
+ <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs
new file mode 100644
index 000000000..4078fd126
--- /dev/null
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -0,0 +1,1380 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Networking.Manager
+{
+ /// <summary>
+ /// Class to take care of network interface management.
+ /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
+ /// </summary>
+ public class NetworkManager : INetworkManager, IDisposable
+ {
+ /// <summary>
+ /// Contains the description of the interface along with its index.
+ /// </summary>
+ private readonly Dictionary<string, int> _interfaceNames;
+
+ /// <summary>
+ /// Threading lock for network properties.
+ /// </summary>
+ private readonly object _intLock = new object();
+
+ /// <summary>
+ /// List of all interface addresses and masks.
+ /// </summary>
+ private readonly Collection<IPObject> _interfaceAddresses;
+
+ /// <summary>
+ /// List of all interface MAC addresses.
+ /// </summary>
+ private readonly List<PhysicalAddress> _macAddresses;
+
+ private readonly ILogger<NetworkManager> _logger;
+
+ private readonly IConfigurationManager _configurationManager;
+
+ private readonly object _eventFireLock;
+
+ /// <summary>
+ /// Holds the bind address overrides.
+ /// </summary>
+ private readonly Dictionary<IPNetAddress, string> _publishedServerUrls;
+
+ /// <summary>
+ /// Used to stop "event-racing conditions".
+ /// </summary>
+ private bool _eventfire;
+
+ /// <summary>
+ /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
+ /// or internal interface network subnets if undefined by user.
+ /// </summary>
+ private Collection<IPObject> _lanSubnets;
+
+ /// <summary>
+ /// User defined list of subnets to excluded from the LAN.
+ /// </summary>
+ private Collection<IPObject> _excludedSubnets;
+
+ /// <summary>
+ /// List of interface addresses to bind the WS.
+ /// </summary>
+ private Collection<IPObject> _bindAddresses;
+
+ /// <summary>
+ /// List of interface addresses to exclude from bind.
+ /// </summary>
+ private Collection<IPObject> _bindExclusions;
+
+ /// <summary>
+ /// Caches list of all internal filtered interface addresses and masks.
+ /// </summary>
+ private Collection<IPObject> _internalInterfaces;
+
+ /// <summary>
+ /// Flag set when no custom LAN has been defined in the configuration.
+ /// </summary>
+ private bool _usingPrivateAddresses;
+
+ /// <summary>
+ /// True if this object is disposed.
+ /// </summary>
+ private bool _disposed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NetworkManager"/> class.
+ /// </summary>
+ /// <param name="configurationManager">IServerConfigurationManager instance.</param>
+ /// <param name="logger">Logger to use for messages.</param>
+#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
+ public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
+ {
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
+
+ _interfaceAddresses = new Collection<IPObject>();
+ _macAddresses = new List<PhysicalAddress>();
+ _interfaceNames = new Dictionary<string, int>();
+ _publishedServerUrls = new Dictionary<IPNetAddress, string>();
+ _eventFireLock = new object();
+
+ UpdateSettings(_configurationManager.GetNetworkConfiguration());
+
+ NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
+ NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
+
+ _configurationManager.NamedConfigurationUpdated += ConfigurationUpdated;
+ }
+#pragma warning restore CS8618 // Non-nullable field is uninitialized.
+
+ /// <summary>
+ /// Event triggered on network changes.
+ /// </summary>
+ public event EventHandler? NetworkChanged;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether testing is taking place.
+ /// </summary>
+ public static string MockNetworkSettings { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IP6 is enabled.
+ /// </summary>
+ public bool IsIP6Enabled { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IP4 is enabled.
+ /// </summary>
+ public bool IsIP4Enabled { get; set; }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> RemoteAddressFilter { get; private set; }
+
+ /// <summary>
+ /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; internal set; }
+
+ /// <summary>
+ /// Gets the Published server override list.
+ /// </summary>
+ public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls;
+
+ /// <summary>
+ /// Creates a new network collection.
+ /// </summary>
+ /// <param name="source">Items to assign the collection, or null.</param>
+ /// <returns>The collection created.</returns>
+ public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null)
+ {
+ var result = new Collection<IPObject>();
+ if (source != null)
+ {
+ foreach (var item in source)
+ {
+ result.AddItem(item, false);
+ }
+ }
+
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <inheritdoc/>
+ public IReadOnlyCollection<PhysicalAddress> GetMacAddresses()
+ {
+ // Populated in construction - so always has values.
+ return _macAddresses;
+ }
+
+ /// <inheritdoc/>
+ public bool IsGatewayInterface(IPObject? addressObj)
+ {
+ var address = addressObj?.Address ?? IPAddress.None;
+ return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
+ }
+
+ /// <inheritdoc/>
+ public bool IsGatewayInterface(IPAddress? addressObj)
+ {
+ return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetLoopbacks()
+ {
+ Collection<IPObject> nc = new Collection<IPObject>();
+ if (IsIP4Enabled)
+ {
+ nc.AddItem(IPAddress.Loopback);
+ }
+
+ if (IsIP6Enabled)
+ {
+ nc.AddItem(IPAddress.IPv6Loopback);
+ }
+
+ return nc;
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcluded(IPAddress ip)
+ {
+ return _excludedSubnets.ContainsAddress(ip);
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcluded(EndPoint ip)
+ {
+ return ip != null && IsExcluded(((IPEndPoint)ip).Address);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> CreateIPCollection(string[] values, bool negated = false)
+ {
+ Collection<IPObject> col = new Collection<IPObject>();
+ if (values == null)
+ {
+ return col;
+ }
+
+ for (int a = 0; a < values.Length; a++)
+ {
+ string v = values[a].Trim();
+
+ try
+ {
+ if (v.StartsWith('!'))
+ {
+ if (negated)
+ {
+ AddToCollection(col, v[1..]);
+ }
+ }
+ else if (!negated)
+ {
+ AddToCollection(col, v);
+ }
+ }
+ catch (ArgumentException e)
+ {
+ _logger.LogWarning(e, "Ignoring LAN value {Value}.", v);
+ }
+ }
+
+ return col;
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false)
+ {
+ int count = _bindAddresses.Count;
+
+ if (count == 0)
+ {
+ if (_bindExclusions.Count > 0)
+ {
+ // Return all the interfaces except the ones specifically excluded.
+ return _interfaceAddresses.Exclude(_bindExclusions, false);
+ }
+
+ if (individualInterfaces)
+ {
+ return new Collection<IPObject>(_interfaceAddresses);
+ }
+
+ // No bind address and no exclusions, so listen on all interfaces.
+ Collection<IPObject> result = new Collection<IPObject>();
+
+ if (IsIP6Enabled && IsIP4Enabled)
+ {
+ // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any
+ result.AddItem(IPAddress.IPv6Any);
+ }
+ else if (IsIP4Enabled)
+ {
+ result.AddItem(IPAddress.Any);
+ }
+ else if (IsIP6Enabled)
+ {
+ // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses.
+ foreach (var iface in _interfaceAddresses)
+ {
+ if (iface.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result.AddItem(iface.Address);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ // Remove any excluded bind interfaces.
+ return _bindAddresses.Exclude(_bindExclusions, false);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(string source, out int? port)
+ {
+ if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
+ {
+ return GetBindInterface(host, out port);
+ }
+
+ return GetBindInterface(IPHost.None, out port);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(IPAddress source, out int? port)
+ {
+ return GetBindInterface(new IPNetAddress(source), out port);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(HttpRequest source, out int? port)
+ {
+ string result;
+
+ if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host))
+ {
+ result = GetBindInterface(host, out port);
+ port ??= source.Host.Port;
+ }
+ else
+ {
+ result = GetBindInterface(IPNetAddress.None, out port);
+ port ??= source?.Host.Port;
+ }
+
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(IPObject source, out int? port)
+ {
+ port = null;
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ // Do we have a source?
+ bool haveSource = !source.Address.Equals(IPAddress.None);
+ bool isExternal = false;
+
+ if (haveSource)
+ {
+ if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ }
+
+ if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
+ {
+ _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ }
+
+ isExternal = !IsInLocalNetwork(source);
+
+ if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
+ {
+ _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
+ return res;
+ }
+ }
+
+ _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal);
+
+ // No preference given, so move on to bind addresses.
+ if (MatchesBindInterface(source, isExternal, out string result))
+ {
+ return result;
+ }
+
+ if (isExternal && MatchesExternalInterface(source, out result))
+ {
+ return result;
+ }
+
+ // Get the first LAN interface address that isn't a loopback.
+ var interfaces = CreateCollection(
+ _interfaceAddresses
+ .Exclude(_bindExclusions, false)
+ .Where(IsInLocalNetwork)
+ .OrderBy(p => p.Tag));
+
+ if (interfaces.Count > 0)
+ {
+ if (haveSource)
+ {
+ foreach (var intf in interfaces)
+ {
+ if (intf.Address.Equals(source.Address))
+ {
+ result = FormatIP6String(intf.Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result);
+ return result;
+ }
+ }
+
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in interfaces)
+ {
+ if (intf.Contains(source))
+ {
+ result = FormatIP6String(intf.Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result);
+ return result;
+ }
+ }
+ }
+
+ result = FormatIP6String(interfaces.First().Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result);
+ return result;
+ }
+
+ // There isn't any others, so we'll use the loopback.
+ result = IsIP6Enabled ? "::1" : "127.0.0.1";
+ _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetInternalBindAddresses()
+ {
+ int count = _bindAddresses.Count;
+
+ if (count == 0)
+ {
+ if (_bindExclusions.Count > 0)
+ {
+ // Return all the internal interfaces except the ones excluded.
+ return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)));
+ }
+
+ // No bind address, so return all internal interfaces.
+ return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()));
+ }
+
+ return new Collection<IPObject>(_bindAddresses);
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPObject address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.Equals(IPAddress.None))
+ {
+ return false;
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(string address)
+ {
+ if (IPHost.TryParse(address, out IPHost ep))
+ {
+ return _lanSubnets.ContainsAddress(ep) && !_excludedSubnets.ContainsAddress(ep);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool IsPrivateAddressRange(IPObject address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+ else
+ {
+ return address.IsPrivateAddressRange();
+ }
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcludedInterface(IPAddress address)
+ {
+ return _bindExclusions.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null)
+ {
+ if (filter == null)
+ {
+ return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks();
+ }
+
+ return _lanSubnets.Exclude(filter, true);
+ }
+
+ /// <inheritdoc/>
+ public bool IsValidInterfaceAddress(IPAddress address)
+ {
+ return _interfaceAddresses.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool TryParseInterface(string token, out Collection<IPObject>? result)
+ {
+ result = null;
+ if (string.IsNullOrEmpty(token))
+ {
+ return false;
+ }
+
+ if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
+ {
+ result = new Collection<IPObject>();
+
+ _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
+
+ // Replace interface tags with the interface IP's.
+ foreach (IPNetAddress iface in _interfaceAddresses)
+ {
+ if (Math.Abs(iface.Tag) == index
+ && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
+ || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ {
+ result.AddItem(iface, false);
+ }
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public bool HasRemoteAccess(IPAddress remoteIp)
+ {
+ var config = _configurationManager.GetNetworkConfiguration();
+ if (config.EnableRemoteAccess)
+ {
+ // 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.Count > 0 && !IsInLocalNetwork(remoteIp))
+ {
+ // remoteAddressFilter is a whitelist or blacklist.
+ return RemoteAddressFilter.ContainsAddress(remoteIp) == !config.IsRemoteIPFilterBlacklist;
+ }
+ }
+ else if (!IsInLocalNetwork(remoteIp))
+ {
+ // Remote not enabled. So everyone should be LAN.
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Reloads all settings and re-initialises the instance.
+ /// </summary>
+ /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
+ public void UpdateSettings(object configuration)
+ {
+ NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
+
+ IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
+ IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
+
+ if (!IsIP6Enabled && !IsIP4Enabled)
+ {
+ _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
+ IsIP4Enabled = true;
+ }
+
+ TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
+ // UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding;
+
+ if (string.IsNullOrEmpty(MockNetworkSettings))
+ {
+ InitialiseInterfaces();
+ }
+ else // Used in testing only.
+ {
+ // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway.
+ var interfaceList = MockNetworkSettings.Split('|');
+ foreach (var details in interfaceList)
+ {
+ var parts = details.Split(',');
+ var address = IPNetAddress.Parse(parts[0]);
+ var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
+ address.Tag = index;
+ _interfaceAddresses.AddItem(address, false);
+ _interfaceNames[parts[2]] = Math.Abs(index);
+ }
+
+ if (IsIP4Enabled)
+ {
+ _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
+ }
+
+ if (IsIP6Enabled)
+ {
+ _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
+ }
+ }
+
+ InitialiseLAN(config);
+ InitialiseBind(config);
+ InitialiseRemote(config);
+ InitialiseOverrides(config);
+ }
+
+ /// <summary>
+ /// Protected implementation of Dispose pattern.
+ /// </summary>
+ /// <param name="disposing"><c>True</c> to dispose the managed state.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!_disposed)
+ {
+ if (disposing)
+ {
+ _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated;
+ NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
+ NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;
+ }
+
+ _disposed = true;
+ }
+ }
+
+ /// <summary>
+ /// Tries to identify the string and return an object of that class.
+ /// </summary>
+ /// <param name="addr">String to parse.</param>
+ /// <param name="result">IPObject to return.</param>
+ /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns>
+ private static bool TryParse(string addr, out IPObject result)
+ {
+ if (!string.IsNullOrEmpty(addr))
+ {
+ // Is it an IP address
+ if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
+ {
+ result = nw;
+ return true;
+ }
+
+ if (IPHost.TryParse(addr, out IPHost h))
+ {
+ result = h;
+ return true;
+ }
+ }
+
+ result = IPNetAddress.None;
+ return false;
+ }
+
+ /// <summary>
+ /// Converts an IPAddress into a string.
+ /// Ipv6 addresses are returned in [ ], with their scope removed.
+ /// </summary>
+ /// <param name="address">Address to convert.</param>
+ /// <returns>URI safe conversion of the address.</returns>
+ private static string FormatIP6String(IPAddress address)
+ {
+ var str = address.ToString();
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
+ if (i != -1)
+ {
+ str = str.Substring(0, i);
+ }
+
+ return $"[{str}]";
+ }
+
+ return str;
+ }
+
+ private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
+ {
+ if (evt.Key.Equals("network", StringComparison.Ordinal))
+ {
+ UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
+ }
+ }
+
+ /// <summary>
+ /// Checks the string to see if it matches any interface names.
+ /// </summary>
+ /// <param name="token">String to check.</param>
+ /// <param name="index">Interface index numbers that match.</param>
+ /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns>
+ private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List<int>? index)
+ {
+ index = null;
+
+ // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
+ // Null check required here for automated testing.
+ if (_interfaceNames != null && token.Length > 1)
+ {
+ bool partial = token[^1] == '*';
+ if (partial)
+ {
+ token = token[0..^1];
+ }
+
+ foreach ((string interfc, int interfcIndex) in _interfaceNames)
+ {
+ if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
+ || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
+ {
+ index ??= new List<int>();
+ index.Add(interfcIndex);
+ }
+ }
+ }
+
+ return index != null;
+ }
+
+ /// <summary>
+ /// Parses a string and adds it into the collection, replacing any interface references.
+ /// </summary>
+ /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param>
+ /// <param name="token">String value to parse.</param>
+ private void AddToCollection(Collection<IPObject> col, string token)
+ {
+ // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
+ // Null check required here for automated testing.
+ if (TryGetInterfaces(token, out var indices))
+ {
+ _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
+
+ // Replace all the interface tags with the interface IP's.
+ foreach (IPNetAddress iface in _interfaceAddresses)
+ {
+ if (indices.Contains(Math.Abs(iface.Tag))
+ && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
+ || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ {
+ col.AddItem(iface);
+ }
+ }
+ }
+ else if (TryParse(token, out IPObject obj))
+ {
+ // Expand if the ip address is "any".
+ if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled)
+ || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled))
+ {
+ foreach (IPNetAddress iface in _interfaceAddresses)
+ {
+ if (obj.AddressFamily == iface.AddressFamily)
+ {
+ col.AddItem(iface);
+ }
+ }
+ }
+ else if (!IsIP6Enabled)
+ {
+ // Remove IP6 addresses from multi-homed IPHosts.
+ obj.Remove(AddressFamily.InterNetworkV6);
+ if (!obj.IsIP6())
+ {
+ col.AddItem(obj);
+ }
+ }
+ else if (!IsIP4Enabled)
+ {
+ // Remove IP4 addresses from multi-homed IPHosts.
+ obj.Remove(AddressFamily.InterNetwork);
+ if (obj.IsIP6())
+ {
+ col.AddItem(obj);
+ }
+ }
+ else
+ {
+ col.AddItem(obj);
+ }
+ }
+ else
+ {
+ _logger.LogDebug("Invalid or unknown object {Token}.", token);
+ }
+ }
+
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
+ private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
+ {
+ _logger.LogDebug("Network availability changed.");
+ OnNetworkChanged();
+ }
+
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">An <see cref="EventArgs"/>.</param>
+ private void OnNetworkAddressChanged(object? sender, EventArgs e)
+ {
+ _logger.LogDebug("Network address change detected.");
+ OnNetworkChanged();
+ }
+
+ /// <summary>
+ /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
+ /// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ private async Task OnNetworkChangeAsync()
+ {
+ try
+ {
+ await Task.Delay(2000).ConfigureAwait(false);
+ InitialiseInterfaces();
+ // Recalculate LAN caches.
+ InitialiseLAN(_configurationManager.GetNetworkConfiguration());
+
+ NetworkChanged?.Invoke(this, EventArgs.Empty);
+ }
+ finally
+ {
+ _eventfire = false;
+ }
+ }
+
+ /// <summary>
+ /// Triggers our event, and re-loads interface information.
+ /// </summary>
+ private void OnNetworkChanged()
+ {
+ lock (_eventFireLock)
+ {
+ if (!_eventfire)
+ {
+ _logger.LogDebug("Network Address Change Event.");
+ // As network events tend to fire one after the other only fire once every second.
+ _eventfire = true;
+ OnNetworkChangeAsync().GetAwaiter().GetResult();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Parses the user defined overrides into the dictionary object.
+ /// Overrides are the equivalent of localised publishedServerUrl, enabling
+ /// different addresses to be advertised over different subnets.
+ /// format is subnet=ipaddress|host|uri
+ /// when subnet = 0.0.0.0, any external address matches.
+ /// </summary>
+ private void InitialiseOverrides(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ _publishedServerUrls.Clear();
+ string[] overrides = config.PublishedServerUriBySubnet;
+ if (overrides == null)
+ {
+ return;
+ }
+
+ foreach (var entry in overrides)
+ {
+ var parts = entry.Split('=');
+ if (parts.Length != 2)
+ {
+ _logger.LogError("Unable to parse bind override: {Entry}", entry);
+ }
+ else
+ {
+ var replacement = parts[1].Trim();
+ if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
+ }
+ else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
+ }
+ else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null)
+ {
+ foreach (IPNetAddress na in addresses)
+ {
+ _publishedServerUrls[na] = replacement;
+ }
+ }
+ else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
+ {
+ _publishedServerUrls[result] = replacement;
+ }
+ else
+ {
+ _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]);
+ }
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Initialises the network bind addresses.
+ /// </summary>
+ private void InitialiseBind(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ string[] lanAddresses = config.LocalNetworkAddresses;
+
+ // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
+ if (config.IgnoreVirtualInterfaces)
+ {
+ // each virtual interface name must be pre-pended with the exclusion symbol !
+ var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray();
+ if (lanAddresses.Length > 0)
+ {
+ var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length];
+ Array.Copy(lanAddresses, newList, lanAddresses.Length);
+ Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length);
+ lanAddresses = newList;
+ }
+ else
+ {
+ lanAddresses = virtualInterfaceNames;
+ }
+ }
+
+ // Read and parse bind addresses and exclusions, removing ones that don't exist.
+ _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses);
+ _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses);
+ _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
+ _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
+ }
+ }
+
+ /// <summary>
+ /// Initialises the remote address values.
+ /// </summary>
+ private void InitialiseRemote(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
+ }
+ }
+
+ /// <summary>
+ /// Initialises internal LAN cache settings.
+ /// </summary>
+ private void InitialiseLAN(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ _logger.LogDebug("Refreshing LAN information.");
+
+ // Get configuration options.
+ string[] subnets = config.LocalNetworkSubnets;
+
+ // Create lists from user settings.
+
+ _lanSubnets = CreateIPCollection(subnets);
+ _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks();
+
+ // If no LAN addresses are specified - all private subnets are deemed to be the LAN
+ _usingPrivateAddresses = _lanSubnets.Count == 0;
+
+ // NOTE: The order of the commands generating the collection in this statement matters.
+ // Altering the order will cause the collections to be created incorrectly.
+ if (_usingPrivateAddresses)
+ {
+ _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
+ // Internal interfaces must be private and not excluded.
+ _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
+
+ // Subnets are the same as the calculated internal interface.
+ _lanSubnets = new Collection<IPObject>();
+
+ // We must listen on loopback for LiveTV to function regardless of the settings.
+ if (IsIP6Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP6Loopback);
+ _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
+ _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
+ }
+
+ if (IsIP4Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP4Loopback);
+ _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8"));
+ _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12"));
+ _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16"));
+ }
+ }
+ else
+ {
+ // We must listen on loopback for LiveTV to function regardless of the settings.
+ if (IsIP6Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP6Loopback);
+ }
+
+ if (IsIP4Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP4Loopback);
+ }
+
+ // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
+ _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork));
+ }
+
+ _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString());
+ _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString());
+ _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString());
+ }
+ }
+
+ /// <summary>
+ /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
+ /// Generate a list of all active mac addresses that aren't loopback addresses.
+ /// </summary>
+ private void InitialiseInterfaces()
+ {
+ lock (_intLock)
+ {
+ _logger.LogDebug("Refreshing interfaces.");
+
+ _interfaceNames.Clear();
+ _interfaceAddresses.Clear();
+ _macAddresses.Clear();
+
+ try
+ {
+ IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
+ .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
+
+ foreach (NetworkInterface adapter in nics)
+ {
+ try
+ {
+ IPInterfaceProperties ipProperties = adapter.GetIPProperties();
+ PhysicalAddress mac = adapter.GetPhysicalAddress();
+
+ // populate mac list
+ if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
+ {
+ _macAddresses.Add(mac);
+ }
+
+ // populate interface address list
+ foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
+ {
+ if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
+ {
+ // Keep the number of gateways on this interface, along with its index.
+ Tag = ipProperties.GetIPv4Properties().Index
+ };
+
+ int tag = nw.Tag;
+ if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
+ {
+ // -ve Tags signify the interface has a gateway.
+ nw.Tag *= -1;
+ }
+
+ _interfaceAddresses.AddItem(nw, false);
+
+ // Store interface name so we can use the name in Collections.
+ _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
+ _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
+ }
+ else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
+ {
+ // Keep the number of gateways on this interface, along with its index.
+ Tag = ipProperties.GetIPv6Properties().Index
+ };
+
+ int tag = nw.Tag;
+ if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
+ {
+ // -ve Tags signify the interface has a gateway.
+ nw.Tag *= -1;
+ }
+
+ _interfaceAddresses.AddItem(nw, false);
+
+ // Store interface name so we can use the name in Collections.
+ _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
+ _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
+ }
+ }
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+ {
+ // Ignore error, and attempt to continue.
+ _logger.LogError(ex, "Error encountered parsing interfaces.");
+ }
+#pragma warning restore CA1031 // Do not catch general exception types
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error in InitialiseInterfaces.");
+ }
+
+ // If for some reason we don't have an interface info, resolve our DNS name.
+ if (_interfaceAddresses.Count == 0)
+ {
+ _logger.LogError("No interfaces information available. Resolving DNS name.");
+ IPHost host = new IPHost(Dns.GetHostName());
+ foreach (var a in host.GetAddresses())
+ {
+ _interfaceAddresses.AddItem(a);
+ }
+
+ if (_interfaceAddresses.Count == 0)
+ {
+ _logger.LogWarning("No interfaces information available. Using loopback.");
+ }
+ }
+
+ if (IsIP4Enabled)
+ {
+ _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
+ }
+
+ if (IsIP6Enabled)
+ {
+ _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
+ }
+
+ _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
+ _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString());
+ }
+ }
+
+ /// <summary>
+ /// Attempts to match the source against a user defined bind interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
+ /// <param name="bindPreference">The published server url that matches the source address.</param>
+ /// <param name="port">The resultant port, if one exists.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port)
+ {
+ bindPreference = string.Empty;
+ port = null;
+
+ // Check for user override.
+ foreach (var addr in _publishedServerUrls)
+ {
+ // Remaining. Match anything.
+ if (addr.Key.Address.Equals(IPAddress.Broadcast))
+ {
+ bindPreference = addr.Value;
+ break;
+ }
+ else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet)
+ {
+ // External.
+ bindPreference = addr.Value;
+ break;
+ }
+ else if (addr.Key.Contains(source))
+ {
+ // Match ip address.
+ bindPreference = addr.Value;
+ break;
+ }
+ }
+
+ if (string.IsNullOrEmpty(bindPreference))
+ {
+ return false;
+ }
+
+ // Has it got a port defined?
+ var parts = bindPreference.Split(':');
+ if (parts.Length > 1)
+ {
+ if (int.TryParse(parts[1], out int p))
+ {
+ bindPreference = parts[0];
+ port = p;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Attempts to match the source against a user defined bind interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
+ /// <param name="result">The result, if a match is found.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result)
+ {
+ result = string.Empty;
+ var addresses = _bindAddresses.Exclude(_bindExclusions, false);
+
+ int count = addresses.Count;
+ if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
+ {
+ // Ignore IPAny addresses.
+ count = 0;
+ }
+
+ if (count != 0)
+ {
+ // Check to see if any of the bind interfaces are in the same subnet.
+
+ IPAddress? defaultGateway = null;
+ IPAddress? bindAddress = null;
+
+ if (isInExternalSubnet)
+ {
+ // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
+ foreach (var addr in addresses.OrderBy(p => p.Tag))
+ {
+ if (defaultGateway == null && !IsInLocalNetwork(addr))
+ {
+ defaultGateway = addr.Address;
+ }
+
+ if (bindAddress == null && addr.Contains(source))
+ {
+ bindAddress = addr.Address;
+ }
+
+ if (defaultGateway != null && bindAddress != null)
+ {
+ break;
+ }
+ }
+ }
+ else
+ {
+ // Look for the best internal address.
+ bindAddress = addresses
+ .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
+ .OrderBy(p => p.Tag)
+ .FirstOrDefault()?.Address;
+ }
+
+ if (bindAddress != null)
+ {
+ result = FormatIP6String(bindAddress);
+ _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result);
+ return true;
+ }
+
+ if (isInExternalSubnet && defaultGateway != null)
+ {
+ result = FormatIP6String(defaultGateway);
+ _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result);
+ return true;
+ }
+
+ result = FormatIP6String(addresses[0].Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result);
+
+ if (isInExternalSubnet)
+ {
+ _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to match the source against an external interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="result">The result, if a match is found.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesExternalInterface(IPObject source, out string result)
+ {
+ result = string.Empty;
+ // Get the first WAN interface address that isn't a loopback.
+ var extResult = _interfaceAddresses
+ .Exclude(_bindExclusions, false)
+ .Where(p => !IsInLocalNetwork(p))
+ .OrderBy(p => p.Tag);
+
+ if (extResult.Any())
+ {
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in extResult)
+ {
+ if (!IsInLocalNetwork(intf) && intf.Contains(source))
+ {
+ result = FormatIP6String(intf.Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result);
+ return true;
+ }
+ }
+
+ result = FormatIP6String(extResult.First().Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result);
+ return true;
+ }
+
+ _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source);
+ return false;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs
new file mode 100644
index 000000000..ba2c8b54f
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs
@@ -0,0 +1,100 @@
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Querying;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations.Activity
+{
+ /// <summary>
+ /// Manages the storage and retrieval of <see cref="ActivityLog"/> instances.
+ /// </summary>
+ public class ActivityManager : IActivityManager
+ {
+ private readonly JellyfinDbProvider _provider;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ActivityManager"/> class.
+ /// </summary>
+ /// <param name="provider">The Jellyfin database provider.</param>
+ public ActivityManager(JellyfinDbProvider provider)
+ {
+ _provider = provider;
+ }
+
+ /// <inheritdoc/>
+ public event EventHandler<GenericEventArgs<ActivityLogEntry>>? EntryCreated;
+
+ /// <inheritdoc/>
+ public async Task CreateAsync(ActivityLog entry)
+ {
+ await using var dbContext = _provider.CreateContext();
+
+ dbContext.ActivityLogs.Add(entry);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+
+ EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(ConvertToOldModel(entry)));
+ }
+
+ /// <inheritdoc/>
+ public async Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query)
+ {
+ await using var dbContext = _provider.CreateContext();
+
+ IQueryable<ActivityLog> entries = dbContext.ActivityLogs
+ .AsQueryable()
+ .OrderByDescending(entry => entry.DateCreated);
+
+ if (query.MinDate.HasValue)
+ {
+ entries = entries.Where(entry => entry.DateCreated >= query.MinDate);
+ }
+
+ if (query.HasUserId.HasValue)
+ {
+ entries = entries.Where(entry => entry.UserId != Guid.Empty == query.HasUserId.Value );
+ }
+
+ return new QueryResult<ActivityLogEntry>
+ {
+ Items = await entries
+ .Skip(query.Skip ?? 0)
+ .Take(query.Limit ?? 100)
+ .AsAsyncEnumerable()
+ .Select(ConvertToOldModel)
+ .ToListAsync()
+ .ConfigureAwait(false),
+ TotalRecordCount = await entries.CountAsync().ConfigureAwait(false)
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task CleanAsync(DateTime startDate)
+ {
+ await using var dbContext = _provider.CreateContext();
+ var entries = dbContext.ActivityLogs
+ .AsQueryable()
+ .Where(entry => entry.DateCreated <= startDate);
+
+ dbContext.RemoveRange(entries);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ private static ActivityLogEntry ConvertToOldModel(ActivityLog entry)
+ {
+ return new ActivityLogEntry(entry.Name, entry.Type, entry.UserId)
+ {
+ Id = entry.Id,
+ Overview = entry.Overview,
+ ShortOverview = entry.ShortOverview,
+ ItemId = entry.ItemId,
+ Date = entry.DateCreated,
+ Severity = entry.LogSeverity
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Devices/DeviceManager.cs b/Jellyfin.Server.Implementations/Devices/DeviceManager.cs
new file mode 100644
index 000000000..0655c9813
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Devices/DeviceManager.cs
@@ -0,0 +1,243 @@
+using System;
+using System.Collections.Concurrent;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Devices;
+using MediaBrowser.Model.Querying;
+using MediaBrowser.Model.Session;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations.Devices
+{
+ /// <summary>
+ /// Manages the creation, updating, and retrieval of devices.
+ /// </summary>
+ public class DeviceManager : IDeviceManager
+ {
+ private readonly JellyfinDbProvider _dbProvider;
+ private readonly IUserManager _userManager;
+ private readonly ConcurrentDictionary<string, ClientCapabilities> _capabilitiesMap = new ();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceManager"/> class.
+ /// </summary>
+ /// <param name="dbProvider">The database provider.</param>
+ /// <param name="userManager">The user manager.</param>
+ public DeviceManager(JellyfinDbProvider dbProvider, IUserManager userManager)
+ {
+ _dbProvider = dbProvider;
+ _userManager = userManager;
+ }
+
+ /// <inheritdoc />
+ public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>>? DeviceOptionsUpdated;
+
+ /// <inheritdoc />
+ public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
+ {
+ _capabilitiesMap[deviceId] = capabilities;
+ }
+
+ /// <inheritdoc />
+ public async Task UpdateDeviceOptions(string deviceId, string deviceName)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var deviceOptions = await dbContext.DeviceOptions.AsQueryable().FirstOrDefaultAsync(dev => dev.DeviceId == deviceId).ConfigureAwait(false);
+ if (deviceOptions == null)
+ {
+ deviceOptions = new DeviceOptions(deviceId);
+ dbContext.DeviceOptions.Add(deviceOptions);
+ }
+
+ deviceOptions.CustomName = deviceName;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+
+ DeviceOptionsUpdated?.Invoke(this, new GenericEventArgs<Tuple<string, DeviceOptions>>(new Tuple<string, DeviceOptions>(deviceId, deviceOptions)));
+ }
+
+ /// <inheritdoc />
+ public async Task<Device> CreateDevice(Device device)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+
+ dbContext.Devices.Add(device);
+
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ return device;
+ }
+
+ /// <inheritdoc />
+ public async Task<DeviceOptions> GetDeviceOptions(string deviceId)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var deviceOptions = await dbContext.DeviceOptions
+ .AsQueryable()
+ .FirstOrDefaultAsync(d => d.DeviceId == deviceId)
+ .ConfigureAwait(false);
+
+ return deviceOptions ?? new DeviceOptions(deviceId);
+ }
+
+ /// <inheritdoc />
+ public ClientCapabilities GetCapabilities(string deviceId)
+ {
+ return _capabilitiesMap.TryGetValue(deviceId, out ClientCapabilities? result)
+ ? result
+ : new ClientCapabilities();
+ }
+
+ /// <inheritdoc />
+ public async Task<DeviceInfo?> GetDevice(string id)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var device = await dbContext.Devices
+ .AsQueryable()
+ .Where(d => d.DeviceId == id)
+ .OrderByDescending(d => d.DateLastActivity)
+ .Include(d => d.User)
+ .FirstOrDefaultAsync()
+ .ConfigureAwait(false);
+
+ var deviceInfo = device == null ? null : ToDeviceInfo(device);
+
+ return deviceInfo;
+ }
+
+ /// <inheritdoc />
+ public async Task<QueryResult<Device>> GetDevices(DeviceQuery query)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+
+ var devices = dbContext.Devices.AsQueryable();
+
+ if (query.UserId.HasValue)
+ {
+ devices = devices.Where(device => device.UserId == query.UserId.Value);
+ }
+
+ if (query.DeviceId != null)
+ {
+ devices = devices.Where(device => device.DeviceId == query.DeviceId);
+ }
+
+ if (query.AccessToken != null)
+ {
+ devices = devices.Where(device => device.AccessToken == query.AccessToken);
+ }
+
+ var count = await devices.CountAsync().ConfigureAwait(false);
+
+ if (query.Skip.HasValue)
+ {
+ devices = devices.Skip(query.Skip.Value);
+ }
+
+ if (query.Limit.HasValue)
+ {
+ devices = devices.Take(query.Limit.Value);
+ }
+
+ return new QueryResult<Device>
+ {
+ Items = await devices.ToListAsync().ConfigureAwait(false),
+ StartIndex = query.Skip ?? 0,
+ TotalRecordCount = count
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task<QueryResult<DeviceInfo>> GetDeviceInfos(DeviceQuery query)
+ {
+ var devices = await GetDevices(query).ConfigureAwait(false);
+
+ return new QueryResult<DeviceInfo>
+ {
+ Items = devices.Items.Select(device => ToDeviceInfo(device)).ToList(),
+ StartIndex = devices.StartIndex,
+ TotalRecordCount = devices.TotalRecordCount
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task<QueryResult<DeviceInfo>> GetDevicesForUser(Guid? userId, bool? supportsSync)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var sessions = dbContext.Devices
+ .Include(d => d.User)
+ .AsQueryable()
+ .OrderBy(d => d.DeviceId)
+ .ThenByDescending(d => d.DateLastActivity)
+ .AsAsyncEnumerable();
+
+ if (supportsSync.HasValue)
+ {
+ sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == supportsSync.Value);
+ }
+
+ if (userId.HasValue)
+ {
+ var user = _userManager.GetUserById(userId.Value);
+
+ sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
+ }
+
+ var array = await sessions.Select(device => ToDeviceInfo(device)).ToArrayAsync().ConfigureAwait(false);
+
+ return new QueryResult<DeviceInfo>(array);
+ }
+
+ /// <inheritdoc />
+ public async Task DeleteDevice(Device device)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ dbContext.Devices.Remove(device);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public bool CanAccessDevice(User user, string deviceId)
+ {
+ if (user == null)
+ {
+ throw new ArgumentNullException(nameof(user));
+ }
+
+ if (string.IsNullOrEmpty(deviceId))
+ {
+ throw new ArgumentNullException(nameof(deviceId));
+ }
+
+ if (user.HasPermission(PermissionKind.EnableAllDevices) || user.HasPermission(PermissionKind.IsAdministrator))
+ {
+ return true;
+ }
+
+ return user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparer.OrdinalIgnoreCase)
+ || !GetCapabilities(deviceId).SupportsPersistentIdentifier;
+ }
+
+ private DeviceInfo ToDeviceInfo(Device authInfo)
+ {
+ var caps = GetCapabilities(authInfo.DeviceId);
+
+ return new DeviceInfo
+ {
+ AppName = authInfo.AppName,
+ AppVersion = authInfo.AppVersion,
+ Id = authInfo.DeviceId,
+ LastUserId = authInfo.UserId,
+ LastUserName = authInfo.User.Username,
+ Name = authInfo.DeviceName,
+ DateLastActivity = authInfo.DateLastActivity,
+ IconUrl = caps.IconUrl
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Library/SubtitleDownloadFailureLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Library/SubtitleDownloadFailureLogger.cs
new file mode 100644
index 000000000..449f27be2
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Library/SubtitleDownloadFailureLogger.cs
@@ -0,0 +1,102 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Subtitles;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Library
+{
+ /// <summary>
+ /// Creates an entry in the activity log whenever a subtitle download fails.
+ /// </summary>
+ public class SubtitleDownloadFailureLogger : IEventConsumer<SubtitleDownloadFailureEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubtitleDownloadFailureLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public SubtitleDownloadFailureLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(SubtitleDownloadFailureEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("SubtitleDownloadFailureFromForItem"),
+ eventArgs.Provider,
+ GetItemName(eventArgs.Item)),
+ "SubtitleDownloadFailure",
+ Guid.Empty)
+ {
+ ItemId = eventArgs.Item.Id.ToString("N", CultureInfo.InvariantCulture),
+ ShortOverview = eventArgs.Exception.Message
+ }).ConfigureAwait(false);
+ }
+
+ private static string GetItemName(BaseItem item)
+ {
+ var name = item.Name;
+ if (item is Episode episode)
+ {
+ if (episode.IndexNumber.HasValue)
+ {
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "Ep{0} - {1}",
+ episode.IndexNumber.Value,
+ name);
+ }
+
+ if (episode.ParentIndexNumber.HasValue)
+ {
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "S{0}, {1}",
+ episode.ParentIndexNumber.Value,
+ name);
+ }
+ }
+
+ if (item is IHasSeries hasSeries)
+ {
+ name = hasSeries.SeriesName + " - " + name;
+ }
+
+ if (item is IHasAlbumArtist hasAlbumArtist)
+ {
+ var artists = hasAlbumArtist.AlbumArtists;
+
+ if (artists.Count > 0)
+ {
+ name = artists[0] + " - " + name;
+ }
+ }
+ else if (item is IHasArtist hasArtist)
+ {
+ var artists = hasArtist.Artists;
+
+ if (artists.Count > 0)
+ {
+ name = artists[0] + " - " + name;
+ }
+ }
+
+ return name;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationFailedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationFailedLogger.cs
new file mode 100644
index 000000000..f899b4497
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationFailedLogger.cs
@@ -0,0 +1,52 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Security
+{
+ /// <summary>
+ /// Creates an entry in the activity log when there is a failed login attempt.
+ /// </summary>
+ public class AuthenticationFailedLogger : IEventConsumer<GenericEventArgs<AuthenticationRequest>>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationFailedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public AuthenticationFailedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(GenericEventArgs<AuthenticationRequest> eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("FailedLoginAttemptWithUserName"),
+ eventArgs.Argument.Username),
+ "AuthenticationFailed",
+ Guid.Empty)
+ {
+ LogSeverity = LogLevel.Error,
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("LabelIpAddressValue"),
+ eventArgs.Argument.RemoteEndPoint),
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs
new file mode 100644
index 000000000..8b0bd84c6
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs
@@ -0,0 +1,49 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Security
+{
+ /// <summary>
+ /// Creates an entry in the activity log when there is a successful login attempt.
+ /// </summary>
+ public class AuthenticationSucceededLogger : IEventConsumer<GenericEventArgs<AuthenticationResult>>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationSucceededLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public AuthenticationSucceededLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(GenericEventArgs<AuthenticationResult> eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("AuthenticationSucceededWithUserName"),
+ eventArgs.Argument.User.Name),
+ "AuthenticationSucceeded",
+ eventArgs.Argument.User.Id)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("LabelIpAddressValue"),
+ eventArgs.Argument.SessionInfo.RemoteEndPoint),
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs
new file mode 100644
index 000000000..aa6015caa
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs
@@ -0,0 +1,104 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Session
+{
+ /// <summary>
+ /// Creates an entry in the activity log whenever a user starts playback.
+ /// </summary>
+ public class PlaybackStartLogger : IEventConsumer<PlaybackStartEventArgs>
+ {
+ private readonly ILogger<PlaybackStartLogger> _logger;
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaybackStartLogger"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PlaybackStartLogger(ILogger<PlaybackStartLogger> logger, ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _logger = logger;
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PlaybackStartEventArgs eventArgs)
+ {
+ if (eventArgs.MediaInfo == null)
+ {
+ _logger.LogWarning("PlaybackStart reported with null media info.");
+ return;
+ }
+
+ if (eventArgs.Item != null && eventArgs.Item.IsThemeMedia)
+ {
+ // Don't report theme song or local trailer playback
+ return;
+ }
+
+ if (eventArgs.Users.Count == 0)
+ {
+ return;
+ }
+
+ var user = eventArgs.Users[0];
+
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserStartedPlayingItemWithValues"),
+ user.Username,
+ GetItemName(eventArgs.MediaInfo),
+ eventArgs.DeviceName),
+ GetPlaybackNotificationType(eventArgs.MediaInfo.MediaType),
+ user.Id))
+ .ConfigureAwait(false);
+ }
+
+ private static string GetItemName(BaseItemDto item)
+ {
+ var name = item.Name;
+
+ if (!string.IsNullOrEmpty(item.SeriesName))
+ {
+ name = item.SeriesName + " - " + name;
+ }
+
+ if (item.Artists != null && item.Artists.Count > 0)
+ {
+ name = item.Artists[0] + " - " + name;
+ }
+
+ return name;
+ }
+
+ private static string GetPlaybackNotificationType(string mediaType)
+ {
+ if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
+ {
+ return NotificationType.AudioPlayback.ToString();
+ }
+
+ if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
+ {
+ return NotificationType.VideoPlayback.ToString();
+ }
+
+ return "Playback";
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs
new file mode 100644
index 000000000..1648b1b47
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs
@@ -0,0 +1,112 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Session
+{
+ /// <summary>
+ /// Creates an activity log entry whenever a user stops playback.
+ /// </summary>
+ public class PlaybackStopLogger : IEventConsumer<PlaybackStopEventArgs>
+ {
+ private readonly ILogger<PlaybackStopLogger> _logger;
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaybackStopLogger"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PlaybackStopLogger(ILogger<PlaybackStopLogger> logger, ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _logger = logger;
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PlaybackStopEventArgs eventArgs)
+ {
+ var item = eventArgs.MediaInfo;
+
+ if (item == null)
+ {
+ _logger.LogWarning("PlaybackStopped reported with null media info.");
+ return;
+ }
+
+ if (eventArgs.Item != null && eventArgs.Item.IsThemeMedia)
+ {
+ // Don't report theme song or local trailer playback
+ return;
+ }
+
+ if (eventArgs.Users.Count == 0)
+ {
+ return;
+ }
+
+ var user = eventArgs.Users[0];
+
+ var notificationType = GetPlaybackStoppedNotificationType(item.MediaType);
+ if (notificationType == null)
+ {
+ return;
+ }
+
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserStoppedPlayingItemWithValues"),
+ user.Username,
+ GetItemName(item),
+ eventArgs.DeviceName),
+ notificationType,
+ user.Id))
+ .ConfigureAwait(false);
+ }
+
+ private static string GetItemName(BaseItemDto item)
+ {
+ var name = item.Name;
+
+ if (!string.IsNullOrEmpty(item.SeriesName))
+ {
+ name = item.SeriesName + " - " + name;
+ }
+
+ if (item.Artists != null && item.Artists.Count > 0)
+ {
+ name = item.Artists[0] + " - " + name;
+ }
+
+ return name;
+ }
+
+ private static string? GetPlaybackStoppedNotificationType(string mediaType)
+ {
+ if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
+ {
+ return NotificationType.AudioPlaybackStopped.ToString();
+ }
+
+ if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
+ {
+ return NotificationType.VideoPlaybackStopped.ToString();
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionEndedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionEndedLogger.cs
new file mode 100644
index 000000000..cf20946ec
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionEndedLogger.cs
@@ -0,0 +1,54 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Session;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Session
+{
+ /// <summary>
+ /// Creates an entry in the activity log whenever a session ends.
+ /// </summary>
+ public class SessionEndedLogger : IEventConsumer<SessionEndedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionEndedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public SessionEndedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(SessionEndedEventArgs eventArgs)
+ {
+ if (string.IsNullOrEmpty(eventArgs.Argument.UserName))
+ {
+ return;
+ }
+
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserOfflineFromDevice"),
+ eventArgs.Argument.UserName,
+ eventArgs.Argument.DeviceName),
+ "SessionEnded",
+ eventArgs.Argument.UserId)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("LabelIpAddressValue"),
+ eventArgs.Argument.RemoteEndPoint),
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionStartedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionStartedLogger.cs
new file mode 100644
index 000000000..6a0f29b09
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/SessionStartedLogger.cs
@@ -0,0 +1,54 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Session;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Session
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a session is started.
+ /// </summary>
+ public class SessionStartedLogger : IEventConsumer<SessionStartedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionStartedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public SessionStartedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(SessionStartedEventArgs eventArgs)
+ {
+ if (string.IsNullOrEmpty(eventArgs.Argument.UserName))
+ {
+ return;
+ }
+
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserOnlineFromDevice"),
+ eventArgs.Argument.UserName,
+ eventArgs.Argument.DeviceName),
+ "SessionStarted",
+ eventArgs.Argument.UserId)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("LabelIpAddressValue"),
+ eventArgs.Argument.RemoteEndPoint)
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/System/PendingRestartNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/System/PendingRestartNotifier.cs
new file mode 100644
index 000000000..2fa38dd71
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/System/PendingRestartNotifier.cs
@@ -0,0 +1,31 @@
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Events.System;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.System
+{
+ /// <summary>
+ /// Notifies users when there is a pending restart.
+ /// </summary>
+ public class PendingRestartNotifier : IEventConsumer<PendingRestartEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PendingRestartNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PendingRestartNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PendingRestartEventArgs eventArgs)
+ {
+ await _sessionManager.SendRestartRequiredNotification(CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs
new file mode 100644
index 000000000..cbc9f3017
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs
@@ -0,0 +1,158 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+using MediaBrowser.Model.Tasks;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.System
+{
+ /// <summary>
+ /// Creates an activity log entry whenever a task is completed.
+ /// </summary>
+ public class TaskCompletedLogger : IEventConsumer<TaskCompletionEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TaskCompletedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public TaskCompletedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(TaskCompletionEventArgs eventArgs)
+ {
+ var result = eventArgs.Result;
+ var task = eventArgs.Task;
+
+ if (task.ScheduledTask is IConfigurableScheduledTask activityTask
+ && !activityTask.IsLogged)
+ {
+ return;
+ }
+
+ var time = result.EndTimeUtc - result.StartTimeUtc;
+ var runningTime = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("LabelRunningTimeValue"),
+ ToUserFriendlyString(time));
+
+ if (result.Status == TaskCompletionStatus.Failed)
+ {
+ var vals = new List<string>();
+
+ if (!string.IsNullOrEmpty(eventArgs.Result.ErrorMessage))
+ {
+ vals.Add(eventArgs.Result.ErrorMessage);
+ }
+
+ if (!string.IsNullOrEmpty(eventArgs.Result.LongErrorMessage))
+ {
+ vals.Add(eventArgs.Result.LongErrorMessage);
+ }
+
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
+ NotificationType.TaskFailed.ToString(),
+ Guid.Empty)
+ {
+ LogSeverity = LogLevel.Error,
+ Overview = string.Join(Environment.NewLine, vals),
+ ShortOverview = runningTime
+ }).ConfigureAwait(false);
+ }
+ }
+
+ private static string ToUserFriendlyString(TimeSpan span)
+ {
+ const int DaysInYear = 365;
+ const int DaysInMonth = 30;
+
+ // Get each non-zero value from TimeSpan component
+ var values = new List<string>();
+
+ // Number of years
+ int days = span.Days;
+ if (days >= DaysInYear)
+ {
+ int years = days / DaysInYear;
+ values.Add(CreateValueString(years, "year"));
+ days %= DaysInYear;
+ }
+
+ // Number of months
+ if (days >= DaysInMonth)
+ {
+ int months = days / DaysInMonth;
+ values.Add(CreateValueString(months, "month"));
+ days = days % DaysInMonth;
+ }
+
+ // Number of days
+ if (days >= 1)
+ {
+ values.Add(CreateValueString(days, "day"));
+ }
+
+ // Number of hours
+ if (span.Hours >= 1)
+ {
+ values.Add(CreateValueString(span.Hours, "hour"));
+ }
+
+ // Number of minutes
+ if (span.Minutes >= 1)
+ {
+ values.Add(CreateValueString(span.Minutes, "minute"));
+ }
+
+ // Number of seconds (include when 0 if no other components included)
+ if (span.Seconds >= 1 || values.Count == 0)
+ {
+ values.Add(CreateValueString(span.Seconds, "second"));
+ }
+
+ // Combine values into string
+ var builder = new StringBuilder();
+ for (int i = 0; i < values.Count; i++)
+ {
+ if (builder.Length > 0)
+ {
+ builder.Append(i == values.Count - 1 ? " and " : ", ");
+ }
+
+ builder.Append(values[i]);
+ }
+
+ // Return result
+ return builder.ToString();
+ }
+
+ /// <summary>
+ /// Constructs a string description of a time-span value.
+ /// </summary>
+ /// <param name="value">The value of this item.</param>
+ /// <param name="description">The name of this item (singular form).</param>
+ private static string CreateValueString(int value, string description)
+ {
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0:#,##0} {1}",
+ value,
+ value == 1 ? description : string.Format(CultureInfo.InvariantCulture, "{0}s", description));
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs
new file mode 100644
index 000000000..0993c6df7
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+using MediaBrowser.Model.Tasks;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.System
+{
+ /// <summary>
+ /// Notifies admin users when a task is completed.
+ /// </summary>
+ public class TaskCompletedNotifier : IEventConsumer<TaskCompletionEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TaskCompletedNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public TaskCompletedNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(TaskCompletionEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.ScheduledTaskEnded, eventArgs.Result, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs
new file mode 100644
index 000000000..1d790da6b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Notifies admin users when a plugin installation is cancelled.
+ /// </summary>
+ public class PluginInstallationCancelledNotifier : IEventConsumer<PluginInstallationCancelledEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallationCancelledNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PluginInstallationCancelledNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginInstallationCancelledEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationCancelled, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedLogger.cs
new file mode 100644
index 000000000..d71c298c5
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedLogger.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a package installation fails.
+ /// </summary>
+ public class PluginInstallationFailedLogger : IEventConsumer<InstallationFailedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallationFailedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PluginInstallationFailedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(InstallationFailedEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("NameInstallFailed"),
+ eventArgs.InstallationInfo.Name),
+ NotificationType.InstallationFailed.ToString(),
+ Guid.Empty)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("VersionNumber"),
+ eventArgs.InstallationInfo.Version),
+ Overview = eventArgs.Exception.Message
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs
new file mode 100644
index 000000000..a1faf18fc
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Notifies admin users when a plugin installation fails.
+ /// </summary>
+ public class PluginInstallationFailedNotifier : IEventConsumer<InstallationFailedEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallationFailedNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PluginInstallationFailedNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(InstallationFailedEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationFailed, eventArgs.InstallationInfo, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledLogger.cs
new file mode 100644
index 000000000..8837172db
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledLogger.cs
@@ -0,0 +1,50 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a plugin is installed.
+ /// </summary>
+ public class PluginInstalledLogger : IEventConsumer<PluginInstalledEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstalledLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PluginInstalledLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginInstalledEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("PluginInstalledWithName"),
+ eventArgs.Argument.Name),
+ NotificationType.PluginInstalled.ToString(),
+ Guid.Empty)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("VersionNumber"),
+ eventArgs.Argument.Version)
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs
new file mode 100644
index 000000000..bd1a71404
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Notifies admin users when a plugin is installed.
+ /// </summary>
+ public class PluginInstalledNotifier : IEventConsumer<PluginInstalledEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstalledNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PluginInstalledNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginInstalledEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationCompleted, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs
new file mode 100644
index 000000000..b513ac64a
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Notifies admin users when a plugin is being installed.
+ /// </summary>
+ public class PluginInstallingNotifier : IEventConsumer<PluginInstallingEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallingNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PluginInstallingNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginInstallingEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstalling, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs
new file mode 100644
index 000000000..eb7572ac6
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs
@@ -0,0 +1,45 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a plugin is uninstalled.
+ /// </summary>
+ public class PluginUninstalledLogger : IEventConsumer<PluginUninstalledEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginUninstalledLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PluginUninstalledLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginUninstalledEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("PluginUninstalledWithName"),
+ eventArgs.Argument.Name),
+ NotificationType.PluginUninstalled.ToString(),
+ Guid.Empty))
+ .ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs
new file mode 100644
index 000000000..1fd7b9adf
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs
@@ -0,0 +1,32 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Notifies admin users when a plugin is uninstalled.
+ /// </summary>
+ public class PluginUninstalledNotifier : IEventConsumer<PluginUninstalledEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginUninstalledNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public PluginUninstalledNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginUninstalledEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageUninstalled, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUpdatedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUpdatedLogger.cs
new file mode 100644
index 000000000..9ce16f774
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUpdatedLogger.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a plugin is updated.
+ /// </summary>
+ public class PluginUpdatedLogger : IEventConsumer<PluginUpdatedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginUpdatedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public PluginUpdatedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(PluginUpdatedEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("PluginUpdatedWithName"),
+ eventArgs.Argument.Name),
+ NotificationType.PluginUpdateInstalled.ToString(),
+ Guid.Empty)
+ {
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("VersionNumber"),
+ eventArgs.Argument.Version),
+ Overview = eventArgs.Argument.Changelog
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserCreatedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserCreatedLogger.cs
new file mode 100644
index 000000000..dc855cc36
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserCreatedLogger.cs
@@ -0,0 +1,43 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a user is created.
+ /// </summary>
+ public class UserCreatedLogger : IEventConsumer<UserCreatedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserCreatedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public UserCreatedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserCreatedEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserCreatedWithName"),
+ eventArgs.Argument.Username),
+ "UserCreated",
+ eventArgs.Argument.Id))
+ .ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedLogger.cs
new file mode 100644
index 000000000..c68a62c81
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedLogger.cs
@@ -0,0 +1,44 @@
+using System;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Adds an entry to the activity log when a user is deleted.
+ /// </summary>
+ public class UserDeletedLogger : IEventConsumer<UserDeletedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserDeletedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public UserDeletedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserDeletedEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserDeletedWithName"),
+ eventArgs.Argument.Username),
+ "UserDeleted",
+ Guid.Empty))
+ .ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs
new file mode 100644
index 000000000..303e88621
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Notifies the user's sessions when a user is deleted.
+ /// </summary>
+ public class UserDeletedNotifier : IEventConsumer<UserDeletedEventArgs>
+ {
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserDeletedNotifier"/> class.
+ /// </summary>
+ /// <param name="sessionManager">The session manager.</param>
+ public UserDeletedNotifier(ISessionManager sessionManager)
+ {
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserDeletedEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToUserSessions(
+ new List<Guid> { eventArgs.Argument.Id },
+ SessionMessageType.UserDeleted,
+ eventArgs.Argument.Id.ToString("N", CultureInfo.InvariantCulture),
+ CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserLockedOutLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserLockedOutLogger.cs
new file mode 100644
index 000000000..a31f222ee
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserLockedOutLogger.cs
@@ -0,0 +1,47 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Notifications;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a user is locked out.
+ /// </summary>
+ public class UserLockedOutLogger : IEventConsumer<UserLockedOutEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserLockedOutLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public UserLockedOutLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserLockedOutEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserLockedOutWithName"),
+ eventArgs.Argument.Username),
+ NotificationType.UserLockedOut.ToString(),
+ eventArgs.Argument.Id)
+ {
+ LogSeverity = LogLevel.Error
+ }).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserPasswordChangedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserPasswordChangedLogger.cs
new file mode 100644
index 000000000..dc8ecbf48
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserPasswordChangedLogger.cs
@@ -0,0 +1,43 @@
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Globalization;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Creates an entry in the activity log when a user's password is changed.
+ /// </summary>
+ public class UserPasswordChangedLogger : IEventConsumer<UserPasswordChangedEventArgs>
+ {
+ private readonly ILocalizationManager _localizationManager;
+ private readonly IActivityManager _activityManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserPasswordChangedLogger"/> class.
+ /// </summary>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <param name="activityManager">The activity manager.</param>
+ public UserPasswordChangedLogger(ILocalizationManager localizationManager, IActivityManager activityManager)
+ {
+ _localizationManager = localizationManager;
+ _activityManager = activityManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserPasswordChangedEventArgs eventArgs)
+ {
+ await _activityManager.CreateAsync(new ActivityLog(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localizationManager.GetLocalizedString("UserPasswordChangedWithName"),
+ eventArgs.Argument.Username),
+ "UserPasswordChanged",
+ eventArgs.Argument.Id))
+ .ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs
new file mode 100644
index 000000000..9beb6f2f2
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs
@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
+
+namespace Jellyfin.Server.Implementations.Events.Consumers.Users
+{
+ /// <summary>
+ /// Notifies a user when their account has been updated.
+ /// </summary>
+ public class UserUpdatedNotifier : IEventConsumer<UserUpdatedEventArgs>
+ {
+ private readonly IUserManager _userManager;
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserUpdatedNotifier"/> class.
+ /// </summary>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="sessionManager">The session manager.</param>
+ public UserUpdatedNotifier(IUserManager userManager, ISessionManager sessionManager)
+ {
+ _userManager = userManager;
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public async Task OnEvent(UserUpdatedEventArgs eventArgs)
+ {
+ await _sessionManager.SendMessageToUserSessions(
+ new List<Guid> { eventArgs.Argument.Id },
+ SessionMessageType.UserUpdated,
+ _userManager.GetUserDto(eventArgs.Argument),
+ CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/EventManager.cs b/Jellyfin.Server.Implementations/Events/EventManager.cs
new file mode 100644
index 000000000..8c5d8f2ce
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/EventManager.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Threading.Tasks;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Events;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Events
+{
+ /// <summary>
+ /// Handles the firing of events.
+ /// </summary>
+ public class EventManager : IEventManager
+ {
+ private readonly ILogger<EventManager> _logger;
+ private readonly IServerApplicationHost _appHost;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EventManager"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="appHost">The application host.</param>
+ public EventManager(ILogger<EventManager> logger, IServerApplicationHost appHost)
+ {
+ _logger = logger;
+ _appHost = appHost;
+ }
+
+ /// <inheritdoc />
+ public void Publish<T>(T eventArgs)
+ where T : EventArgs
+ {
+ PublishInternal(eventArgs).GetAwaiter().GetResult();
+ }
+
+ /// <inheritdoc />
+ public async Task PublishAsync<T>(T eventArgs)
+ where T : EventArgs
+ {
+ await PublishInternal(eventArgs).ConfigureAwait(false);
+ }
+
+ private async Task PublishInternal<T>(T eventArgs)
+ where T : EventArgs
+ {
+ using var scope = _appHost.ServiceProvider?.CreateScope();
+ if (scope == null)
+ {
+ return;
+ }
+
+ foreach (var service in scope.ServiceProvider.GetServices<IEventConsumer<T>>())
+ {
+ try
+ {
+ await service.OnEvent(eventArgs).ConfigureAwait(false);
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Uncaught exception in EventConsumer {type}: ", service.GetType());
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Events/EventingServiceCollectionExtensions.cs b/Jellyfin.Server.Implementations/Events/EventingServiceCollectionExtensions.cs
new file mode 100644
index 000000000..5d558189b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Events/EventingServiceCollectionExtensions.cs
@@ -0,0 +1,72 @@
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Events.System;
+using Jellyfin.Data.Events.Users;
+using Jellyfin.Server.Implementations.Events.Consumers.Library;
+using Jellyfin.Server.Implementations.Events.Consumers.Security;
+using Jellyfin.Server.Implementations.Events.Consumers.Session;
+using Jellyfin.Server.Implementations.Events.Consumers.System;
+using Jellyfin.Server.Implementations.Events.Consumers.Updates;
+using Jellyfin.Server.Implementations.Events.Consumers.Users;
+using MediaBrowser.Common.Updates;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Events.Session;
+using MediaBrowser.Controller.Events.Updates;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.Subtitles;
+using MediaBrowser.Model.Tasks;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Jellyfin.Server.Implementations.Events
+{
+ /// <summary>
+ /// A class containing extensions to <see cref="IServiceCollection"/> for eventing.
+ /// </summary>
+ public static class EventingServiceCollectionExtensions
+ {
+ /// <summary>
+ /// Adds the event services to the service collection.
+ /// </summary>
+ /// <param name="collection">The service collection.</param>
+ public static void AddEventServices(this IServiceCollection collection)
+ {
+ // Library consumers
+ collection.AddScoped<IEventConsumer<SubtitleDownloadFailureEventArgs>, SubtitleDownloadFailureLogger>();
+
+ // Security consumers
+ collection.AddScoped<IEventConsumer<GenericEventArgs<AuthenticationRequest>>, AuthenticationFailedLogger>();
+ collection.AddScoped<IEventConsumer<GenericEventArgs<AuthenticationResult>>, AuthenticationSucceededLogger>();
+
+ // Session consumers
+ collection.AddScoped<IEventConsumer<PlaybackStartEventArgs>, PlaybackStartLogger>();
+ collection.AddScoped<IEventConsumer<PlaybackStopEventArgs>, PlaybackStopLogger>();
+ collection.AddScoped<IEventConsumer<SessionEndedEventArgs>, SessionEndedLogger>();
+ collection.AddScoped<IEventConsumer<SessionStartedEventArgs>, SessionStartedLogger>();
+
+ // System consumers
+ collection.AddScoped<IEventConsumer<PendingRestartEventArgs>, PendingRestartNotifier>();
+ collection.AddScoped<IEventConsumer<TaskCompletionEventArgs>, TaskCompletedLogger>();
+ collection.AddScoped<IEventConsumer<TaskCompletionEventArgs>, TaskCompletedNotifier>();
+
+ // Update consumers
+ collection.AddScoped<IEventConsumer<PluginInstallationCancelledEventArgs>, PluginInstallationCancelledNotifier>();
+ collection.AddScoped<IEventConsumer<InstallationFailedEventArgs>, PluginInstallationFailedLogger>();
+ collection.AddScoped<IEventConsumer<InstallationFailedEventArgs>, PluginInstallationFailedNotifier>();
+ collection.AddScoped<IEventConsumer<PluginInstalledEventArgs>, PluginInstalledLogger>();
+ collection.AddScoped<IEventConsumer<PluginInstalledEventArgs>, PluginInstalledNotifier>();
+ collection.AddScoped<IEventConsumer<PluginInstallingEventArgs>, PluginInstallingNotifier>();
+ collection.AddScoped<IEventConsumer<PluginUninstalledEventArgs>, PluginUninstalledLogger>();
+ collection.AddScoped<IEventConsumer<PluginUninstalledEventArgs>, PluginUninstalledNotifier>();
+ collection.AddScoped<IEventConsumer<PluginUpdatedEventArgs>, PluginUpdatedLogger>();
+
+ // User consumers
+ collection.AddScoped<IEventConsumer<UserCreatedEventArgs>, UserCreatedLogger>();
+ collection.AddScoped<IEventConsumer<UserDeletedEventArgs>, UserDeletedLogger>();
+ collection.AddScoped<IEventConsumer<UserDeletedEventArgs>, UserDeletedNotifier>();
+ collection.AddScoped<IEventConsumer<UserLockedOutEventArgs>, UserLockedOutLogger>();
+ collection.AddScoped<IEventConsumer<UserPasswordChangedEventArgs>, UserPasswordChangedLogger>();
+ collection.AddScoped<IEventConsumer<UserUpdatedEventArgs>, UserUpdatedNotifier>();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
new file mode 100644
index 000000000..e26cf093b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
@@ -0,0 +1,40 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ </PropertyGroup>
+
+ <!-- Code analysers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="System.Linq.Async" Version="5.0.0" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0-rc.2*">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0-rc.2*">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Jellyfin.Data\Jellyfin.Data.csproj" />
+ <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
+ <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs
new file mode 100644
index 000000000..dc4f53913
--- /dev/null
+++ b/Jellyfin.Server.Implementations/JellyfinDb.cs
@@ -0,0 +1,162 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Interfaces;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations
+{
+ /// <inheritdoc/>
+ public class JellyfinDb : DbContext
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JellyfinDb"/> class.
+ /// </summary>
+ /// <param name="options">The database context options.</param>
+ public JellyfinDb(DbContextOptions<JellyfinDb> options) : base(options)
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the default connection string.
+ /// </summary>
+ public static string ConnectionString { get; set; } = @"Data Source=jellyfin.db";
+
+ public virtual DbSet<AccessSchedule> AccessSchedules { get; set; }
+
+ public virtual DbSet<ActivityLog> ActivityLogs { get; set; }
+
+ public virtual DbSet<ApiKey> ApiKeys { get; set; }
+
+ public virtual DbSet<Device> Devices { get; set; }
+
+ public virtual DbSet<DeviceOptions> DeviceOptions { get; set; }
+
+ public virtual DbSet<DisplayPreferences> DisplayPreferences { get; set; }
+
+ public virtual DbSet<ImageInfo> ImageInfos { get; set; }
+
+ public virtual DbSet<ItemDisplayPreferences> ItemDisplayPreferences { get; set; }
+
+ public virtual DbSet<CustomItemDisplayPreferences> CustomItemDisplayPreferences { get; set; }
+
+ public virtual DbSet<Permission> Permissions { get; set; }
+
+ public virtual DbSet<Preference> Preferences { get; set; }
+
+ public virtual DbSet<User> Users { get; set; }
+
+ /*public virtual DbSet<Artwork> Artwork { get; set; }
+
+ public virtual DbSet<Book> Books { get; set; }
+
+ public virtual DbSet<BookMetadata> BookMetadata { get; set; }
+
+ public virtual DbSet<Chapter> Chapters { get; set; }
+
+ public virtual DbSet<Collection> Collections { get; set; }
+
+ public virtual DbSet<CollectionItem> CollectionItems { get; set; }
+
+ public virtual DbSet<Company> Companies { get; set; }
+
+ public virtual DbSet<CompanyMetadata> CompanyMetadata { get; set; }
+
+ public virtual DbSet<CustomItem> CustomItems { get; set; }
+
+ public virtual DbSet<CustomItemMetadata> CustomItemMetadata { get; set; }
+
+ public virtual DbSet<Episode> Episodes { get; set; }
+
+ public virtual DbSet<EpisodeMetadata> EpisodeMetadata { get; set; }
+
+ public virtual DbSet<Genre> Genres { get; set; }
+
+ public virtual DbSet<Group> Groups { get; set; }
+
+ public virtual DbSet<Library> Libraries { get; set; }
+
+ public virtual DbSet<LibraryItem> LibraryItems { get; set; }
+
+ public virtual DbSet<LibraryRoot> LibraryRoot { get; set; }
+
+ public virtual DbSet<MediaFile> MediaFiles { get; set; }
+
+ public virtual DbSet<MediaFileStream> MediaFileStream { get; set; }
+
+ public virtual DbSet<Metadata> Metadata { get; set; }
+
+ public virtual DbSet<MetadataProvider> MetadataProviders { get; set; }
+
+ public virtual DbSet<MetadataProviderId> MetadataProviderIds { get; set; }
+
+ public virtual DbSet<Movie> Movies { get; set; }
+
+ public virtual DbSet<MovieMetadata> MovieMetadata { get; set; }
+
+ public virtual DbSet<MusicAlbum> MusicAlbums { get; set; }
+
+ public virtual DbSet<MusicAlbumMetadata> MusicAlbumMetadata { get; set; }
+
+ public virtual DbSet<Person> People { get; set; }
+
+ public virtual DbSet<PersonRole> PersonRoles { get; set; }
+
+ public virtual DbSet<Photo> Photo { get; set; }
+
+ public virtual DbSet<PhotoMetadata> PhotoMetadata { get; set; }
+
+ public virtual DbSet<ProviderMapping> ProviderMappings { get; set; }
+
+ public virtual DbSet<Rating> Ratings { get; set; }
+
+ /// <summary>
+ /// Repository for global::Jellyfin.Data.Entities.RatingSource - This is the entity to
+ /// store review ratings, not age ratings.
+ /// </summary>
+ public virtual DbSet<RatingSource> RatingSources { get; set; }
+
+ public virtual DbSet<Release> Releases { get; set; }
+
+ public virtual DbSet<Season> Seasons { get; set; }
+
+ public virtual DbSet<SeasonMetadata> SeasonMetadata { get; set; }
+
+ public virtual DbSet<Series> Series { get; set; }
+
+ public virtual DbSet<SeriesMetadata> SeriesMetadata { get; set; }
+
+ public virtual DbSet<Track> Tracks { get; set; }
+
+ public virtual DbSet<TrackMetadata> TrackMetadata { get; set; }*/
+
+ /// <inheritdoc/>
+ public override int SaveChanges()
+ {
+ foreach (var saveEntity in ChangeTracker.Entries()
+ .Where(e => e.State == EntityState.Modified)
+ .Select(entry => entry.Entity)
+ .OfType<IHasConcurrencyToken>())
+ {
+ saveEntity.OnSavingChanges();
+ }
+
+ return base.SaveChanges();
+ }
+
+ /// <inheritdoc />
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ modelBuilder.SetDefaultDateTimeKind(DateTimeKind.Utc);
+ base.OnModelCreating(modelBuilder);
+ modelBuilder.HasDefaultSchema("jellyfin");
+
+ // Configuration for each entity is in it's own class inside 'ModelConfiguration'.
+ modelBuilder.ApplyConfigurationsFromAssembly(typeof(JellyfinDb).Assembly);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/JellyfinDbProvider.cs b/Jellyfin.Server.Implementations/JellyfinDbProvider.cs
new file mode 100644
index 000000000..c2c5198d1
--- /dev/null
+++ b/Jellyfin.Server.Implementations/JellyfinDbProvider.cs
@@ -0,0 +1,51 @@
+using System;
+using System.IO;
+using System.Linq;
+using MediaBrowser.Common.Configuration;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations
+{
+ /// <summary>
+ /// Factory class for generating new <see cref="JellyfinDb"/> instances.
+ /// </summary>
+ public class JellyfinDbProvider
+ {
+ private readonly IServiceProvider _serviceProvider;
+ private readonly IApplicationPaths _appPaths;
+ private readonly ILogger<JellyfinDbProvider> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JellyfinDbProvider"/> class.
+ /// </summary>
+ /// <param name="serviceProvider">The application's service provider.</param>
+ /// <param name="appPaths">The application paths.</param>
+ /// <param name="logger">The logger.</param>
+ public JellyfinDbProvider(IServiceProvider serviceProvider, IApplicationPaths appPaths, ILogger<JellyfinDbProvider> logger)
+ {
+ _serviceProvider = serviceProvider;
+ _appPaths = appPaths;
+ _logger = logger;
+
+ using var jellyfinDb = CreateContext();
+ if (jellyfinDb.Database.GetPendingMigrations().Any())
+ {
+ _logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
+ jellyfinDb.Database.Migrate();
+ _logger.LogInformation("EFCore migrations applied successfully");
+ }
+ }
+
+ /// <summary>
+ /// Creates a new <see cref="JellyfinDb"/> context.
+ /// </summary>
+ /// <returns>The newly created context.</returns>
+ public JellyfinDb CreateContext()
+ {
+ var contextOptions = new DbContextOptionsBuilder<JellyfinDb>().UseSqlite($"Filename={Path.Combine(_appPaths.DataPath, "jellyfin.db")}");
+ return ActivatorUtilities.CreateInstance<JellyfinDb>(_serviceProvider, contextOptions.Options);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.Designer.cs
new file mode 100644
index 000000000..98a83b745
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.Designer.cs
@@ -0,0 +1,72 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20200514181226_AddActivityLog")]
+ partial class AddActivityLog
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.3");
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<int>("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.cs b/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.cs
new file mode 100644
index 000000000..5e0b454d8
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200514181226_AddActivityLog.cs
@@ -0,0 +1,46 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddActivityLog : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.EnsureSchema(
+ name: "jellyfin");
+
+ migrationBuilder.CreateTable(
+ name: "ActivityLogs",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Name = table.Column<string>(maxLength: 512, nullable: false),
+ Overview = table.Column<string>(maxLength: 512, nullable: true),
+ ShortOverview = table.Column<string>(maxLength: 512, nullable: true),
+ Type = table.Column<string>(maxLength: 256, nullable: false),
+ UserId = table.Column<Guid>(nullable: false),
+ ItemId = table.Column<string>(maxLength: 256, nullable: true),
+ DateCreated = table.Column<DateTime>(nullable: false),
+ LogSeverity = table.Column<int>(nullable: false),
+ RowVersion = table.Column<uint>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ActivityLogs", x => x.Id);
+ });
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "ActivityLogs",
+ schema: "jellyfin");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.Designer.cs
new file mode 100644
index 000000000..6342ce9cf
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.Designer.cs
@@ -0,0 +1,312 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20200613202153_AddUsers")]
+ partial class AddUsers
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.4");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<int>("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<Guid?>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("ImageInfos");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AudioLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<string>("AuthenticationProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ 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?>("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Password")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property<string>("PasswordResetProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<int>("SubtitleMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SyncPlayAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.HasKey("Id");
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.cs b/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.cs
new file mode 100644
index 000000000..7e5a76850
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200613202153_AddUsers.cs
@@ -0,0 +1,197 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddUsers : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "Users",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<Guid>(nullable: false),
+ Username = table.Column<string>(maxLength: 255, nullable: false),
+ Password = table.Column<string>(maxLength: 65535, nullable: true),
+ EasyPassword = table.Column<string>(maxLength: 65535, nullable: true),
+ MustUpdatePassword = table.Column<bool>(nullable: false),
+ AudioLanguagePreference = table.Column<string>(maxLength: 255, nullable: true),
+ AuthenticationProviderId = table.Column<string>(maxLength: 255, nullable: false),
+ PasswordResetProviderId = table.Column<string>(maxLength: 255, nullable: false),
+ InvalidLoginAttemptCount = table.Column<int>(nullable: false),
+ LastActivityDate = table.Column<DateTime>(nullable: true),
+ LastLoginDate = table.Column<DateTime>(nullable: true),
+ LoginAttemptsBeforeLockout = table.Column<int>(nullable: true),
+ SubtitleMode = table.Column<int>(nullable: false),
+ PlayDefaultAudioTrack = table.Column<bool>(nullable: false),
+ SubtitleLanguagePreference = table.Column<string>(maxLength: 255, nullable: true),
+ DisplayMissingEpisodes = table.Column<bool>(nullable: false),
+ DisplayCollectionsView = table.Column<bool>(nullable: false),
+ EnableLocalPassword = table.Column<bool>(nullable: false),
+ HidePlayedInLatest = table.Column<bool>(nullable: false),
+ RememberAudioSelections = table.Column<bool>(nullable: false),
+ RememberSubtitleSelections = table.Column<bool>(nullable: false),
+ EnableNextEpisodeAutoPlay = table.Column<bool>(nullable: false),
+ EnableAutoLogin = table.Column<bool>(nullable: false),
+ EnableUserPreferenceAccess = table.Column<bool>(nullable: false),
+ MaxParentalAgeRating = table.Column<int>(nullable: true),
+ RemoteClientBitrateLimit = table.Column<int>(nullable: true),
+ InternalId = table.Column<long>(nullable: false),
+ SyncPlayAccess = table.Column<int>(nullable: false),
+ RowVersion = table.Column<uint>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Users", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "AccessSchedules",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(nullable: false),
+ DayOfWeek = table.Column<int>(nullable: false),
+ StartHour = table.Column<double>(nullable: false),
+ EndHour = table.Column<double>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_AccessSchedules", x => x.Id);
+ table.ForeignKey(
+ name: "FK_AccessSchedules_Users_UserId",
+ column: x => x.UserId,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "ImageInfos",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(nullable: true),
+ Path = table.Column<string>(maxLength: 512, nullable: false),
+ LastModified = table.Column<DateTime>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ImageInfos", x => x.Id);
+ table.ForeignKey(
+ name: "FK_ImageInfos_Users_UserId",
+ column: x => x.UserId,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Permissions",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Kind = table.Column<int>(nullable: false),
+ Value = table.Column<bool>(nullable: false),
+ RowVersion = table.Column<uint>(nullable: false),
+ Permission_Permissions_Guid = table.Column<Guid>(nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Permissions", x => x.Id);
+ table.ForeignKey(
+ name: "FK_Permissions_Users_Permission_Permissions_Guid",
+ column: x => x.Permission_Permissions_Guid,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Preferences",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Kind = table.Column<int>(nullable: false),
+ Value = table.Column<string>(maxLength: 65535, nullable: false),
+ RowVersion = table.Column<uint>(nullable: false),
+ Preference_Preferences_Guid = table.Column<Guid>(nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Preferences", x => x.Id);
+ table.ForeignKey(
+ name: "FK_Preferences_Users_Preference_Preferences_Guid",
+ column: x => x.Preference_Preferences_Guid,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccessSchedules_UserId",
+ schema: "jellyfin",
+ table: "AccessSchedules",
+ column: "UserId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ImageInfos_UserId",
+ schema: "jellyfin",
+ table: "ImageInfos",
+ column: "UserId",
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Permissions_Permission_Permissions_Guid",
+ schema: "jellyfin",
+ table: "Permissions",
+ column: "Permission_Permissions_Guid");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Preferences_Preference_Preferences_Guid",
+ schema: "jellyfin",
+ table: "Preferences",
+ column: "Preference_Preferences_Guid");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "AccessSchedules",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "ImageInfos",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "Permissions",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "Preferences",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "Users",
+ schema: "jellyfin");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.Designer.cs
new file mode 100644
index 000000000..d44707d06
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.Designer.cs
@@ -0,0 +1,459 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20200728005145_AddDisplayPreferences")]
+ partial class AddDisplayPreferences
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.6");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<int>("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChromecastVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<string>("DashboardTheme")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<bool>("EnableNextVideoInfoOverlay")
+ .HasColumnType("INTEGER");
+
+ b.Property<int?>("IndexBy")
+ .HasColumnType("INTEGER");
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<Guid?>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("ImageInfos");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ 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()
+ .HasColumnType("TEXT")
+ .HasMaxLength(64);
+
+ 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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AudioLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<string>("AuthenticationProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ 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?>("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Password")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property<string>("PasswordResetProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<int>("SubtitleMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SyncPlayAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.HasKey("Id");
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("DisplayPreferences")
+ .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.cs b/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.cs
new file mode 100644
index 000000000..3009f0b61
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200728005145_AddDisplayPreferences.cs
@@ -0,0 +1,132 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddDisplayPreferences : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "DisplayPreferences",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(nullable: false),
+ Client = table.Column<string>(maxLength: 32, nullable: false),
+ ShowSidebar = table.Column<bool>(nullable: false),
+ ShowBackdrop = table.Column<bool>(nullable: false),
+ ScrollDirection = table.Column<int>(nullable: false),
+ IndexBy = table.Column<int>(nullable: true),
+ SkipForwardLength = table.Column<int>(nullable: false),
+ SkipBackwardLength = table.Column<int>(nullable: false),
+ ChromecastVersion = table.Column<int>(nullable: false),
+ EnableNextVideoInfoOverlay = table.Column<bool>(nullable: false),
+ DashboardTheme = table.Column<string>(maxLength: 32, nullable: true),
+ TvHome = table.Column<string>(maxLength: 32, nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_DisplayPreferences", x => x.Id);
+ table.ForeignKey(
+ name: "FK_DisplayPreferences_Users_UserId",
+ column: x => x.UserId,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "ItemDisplayPreferences",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(nullable: false),
+ ItemId = table.Column<Guid>(nullable: false),
+ Client = table.Column<string>(maxLength: 32, nullable: false),
+ ViewType = table.Column<int>(nullable: false),
+ RememberIndexing = table.Column<bool>(nullable: false),
+ IndexBy = table.Column<int>(nullable: true),
+ RememberSorting = table.Column<bool>(nullable: false),
+ SortBy = table.Column<string>(maxLength: 64, nullable: false),
+ SortOrder = table.Column<int>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ItemDisplayPreferences", x => x.Id);
+ table.ForeignKey(
+ name: "FK_ItemDisplayPreferences_Users_UserId",
+ column: x => x.UserId,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "HomeSection",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ DisplayPreferencesId = table.Column<int>(nullable: false),
+ Order = table.Column<int>(nullable: false),
+ Type = table.Column<int>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_HomeSection", x => x.Id);
+ table.ForeignKey(
+ name: "FK_HomeSection_DisplayPreferences_DisplayPreferencesId",
+ column: x => x.DisplayPreferencesId,
+ principalSchema: "jellyfin",
+ principalTable: "DisplayPreferences",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ column: "UserId",
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_HomeSection_DisplayPreferencesId",
+ schema: "jellyfin",
+ table: "HomeSection",
+ column: "DisplayPreferencesId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ItemDisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "ItemDisplayPreferences",
+ column: "UserId");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "HomeSection",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "ItemDisplayPreferences",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "DisplayPreferences",
+ schema: "jellyfin");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.Designer.cs
new file mode 100644
index 000000000..2234f9d5f
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.Designer.cs
@@ -0,0 +1,461 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20200905220533_FixDisplayPreferencesIndex")]
+ partial class FixDisplayPreferencesIndex
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.7");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<int>("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChromecastVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<string>("DashboardTheme")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<bool>("EnableNextVideoInfoOverlay")
+ .HasColumnType("INTEGER");
+
+ b.Property<int?>("IndexBy")
+ .HasColumnType("INTEGER");
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("UserId", "Client")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<Guid?>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("ImageInfos");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ 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()
+ .HasColumnType("TEXT")
+ .HasMaxLength(64);
+
+ 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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AudioLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<string>("AuthenticationProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ 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?>("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Password")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property<string>("PasswordResetProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<int>("SubtitleMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SyncPlayAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.HasKey("Id");
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("DisplayPreferences")
+ .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.cs b/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.cs
new file mode 100644
index 000000000..33c5bb4ca
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20200905220533_FixDisplayPreferencesIndex.cs
@@ -0,0 +1,51 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class FixDisplayPreferencesIndex : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ column: "UserId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ columns: new[] { "UserId", "Client" },
+ unique: true);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ column: "UserId",
+ unique: true);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs
new file mode 100644
index 000000000..e5c326a32
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs
@@ -0,0 +1,464 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20201004171403_AddMaxActiveSessions")]
+ partial class AddMaxActiveSessions
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.8");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<int>("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChromecastVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<string>("DashboardTheme")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<bool>("EnableNextVideoInfoOverlay")
+ .HasColumnType("INTEGER");
+
+ b.Property<int?>("IndexBy")
+ .HasColumnType("INTEGER");
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property<Guid>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("UserId", "Client")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property<Guid?>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("ImageInfos");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ 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()
+ .HasColumnType("TEXT")
+ .HasMaxLength(64);
+
+ 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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AudioLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<string>("AuthenticationProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property<string>("PasswordResetProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ 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")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property<int>("SubtitleMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SyncPlayAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.HasKey("Id");
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("DisplayPreferences")
+ .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs
new file mode 100644
index 000000000..10acb4def
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddMaxActiveSessions : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<int>(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users",
+ nullable: false,
+ defaultValue: 0);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs
new file mode 100644
index 000000000..10663d065
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs
@@ -0,0 +1,522 @@
+#pragma warning disable CS1591
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20201204223655_AddCustomDisplayPreferences")]
+ partial class AddCustomDisplayPreferences
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "5.0.0");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("UserId", "ItemId", "Client", "Key")
+ .IsUnique();
+
+ b.ToTable("CustomItemDisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+
+ b.HasIndex("UserId", "ItemId", "Client")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ 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.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("DisplayPreferences")
+ .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Navigation("HomeSections");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Navigation("AccessSchedules");
+
+ b.Navigation("DisplayPreferences")
+ .IsRequired();
+
+ b.Navigation("ItemDisplayPreferences");
+
+ b.Navigation("Permissions");
+
+ b.Navigation("Preferences");
+
+ b.Navigation("ProfileImage");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs
new file mode 100644
index 000000000..fbc0bffa9
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs
@@ -0,0 +1,108 @@
+#pragma warning disable CS1591
+// <auto-generated />
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddCustomDisplayPreferences : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.AlterColumn<int>(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users",
+ type: "INTEGER",
+ nullable: false,
+ defaultValue: 0,
+ oldClrType: typeof(int),
+ oldType: "INTEGER",
+ oldNullable: true);
+
+ migrationBuilder.AddColumn<Guid>(
+ name: "ItemId",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ type: "TEXT",
+ nullable: false,
+ defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
+
+ migrationBuilder.CreateTable(
+ name: "CustomItemDisplayPreferences",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(type: "TEXT", nullable: false),
+ ItemId = table.Column<Guid>(type: "TEXT", nullable: false),
+ Client = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
+ Key = table.Column<string>(type: "TEXT", nullable: false),
+ Value = table.Column<string>(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_CustomItemDisplayPreferences", x => x.Id);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId_ItemId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ columns: new[] { "UserId", "ItemId", "Client" },
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_CustomItemDisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences",
+ column: "UserId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_CustomItemDisplayPreferences_UserId_ItemId_Client_Key",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences",
+ columns: new[] { "UserId", "ItemId", "Client", "Key" },
+ unique: true);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "CustomItemDisplayPreferences",
+ schema: "jellyfin");
+
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId_ItemId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.DropColumn(
+ name: "ItemId",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.AlterColumn<int>(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users",
+ type: "INTEGER",
+ nullable: true,
+ oldClrType: typeof(int),
+ oldType: "INTEGER");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId_Client",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ columns: new[] { "UserId", "Client" },
+ unique: true);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs
new file mode 100644
index 000000000..869676824
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs
@@ -0,0 +1,535 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20210320181425_AddIndexesAndCollations")]
+ partial class AddIndexesAndCollations
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "5.0.3");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId", "ItemId", "Client", "Key")
+ .IsUnique();
+
+ b.ToTable("CustomItemDisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ 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")
+ .UseCollation("NOCASE");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("DisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Navigation("HomeSections");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs
new file mode 100644
index 000000000..506e4ae66
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs
@@ -0,0 +1,240 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddIndexesAndCollations : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_ImageInfos_Users_UserId",
+ schema: "jellyfin",
+ table: "ImageInfos");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_Permissions_Users_Permission_Permissions_Guid",
+ schema: "jellyfin",
+ table: "Permissions");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_Preferences_Users_Preference_Preferences_Guid",
+ schema: "jellyfin",
+ table: "Preferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_Preferences_Preference_Preferences_Guid",
+ schema: "jellyfin",
+ table: "Preferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_Permissions_Permission_Permissions_Guid",
+ schema: "jellyfin",
+ table: "Permissions");
+
+ migrationBuilder.DropIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_CustomItemDisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences");
+
+ migrationBuilder.AlterColumn<string>(
+ name: "Username",
+ schema: "jellyfin",
+ table: "Users",
+ type: "TEXT",
+ maxLength: 255,
+ nullable: false,
+ collation: "NOCASE",
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldMaxLength: 255);
+
+ migrationBuilder.AddColumn<Guid>(
+ name: "UserId",
+ schema: "jellyfin",
+ table: "Preferences",
+ type: "TEXT",
+ nullable: true);
+
+ migrationBuilder.AddColumn<Guid>(
+ name: "UserId",
+ schema: "jellyfin",
+ table: "Permissions",
+ type: "TEXT",
+ nullable: true);
+
+ migrationBuilder.Sql("UPDATE Preferences SET UserId = Preference_Preferences_Guid");
+ migrationBuilder.Sql("UPDATE Permissions SET UserId = Permission_Permissions_Guid");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Users_Username",
+ schema: "jellyfin",
+ table: "Users",
+ column: "Username",
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Preferences_UserId_Kind",
+ schema: "jellyfin",
+ table: "Preferences",
+ columns: new[] { "UserId", "Kind" },
+ unique: true,
+ filter: "[UserId] IS NOT NULL");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Permissions_UserId_Kind",
+ schema: "jellyfin",
+ table: "Permissions",
+ columns: new[] { "UserId", "Kind" },
+ unique: true,
+ filter: "[UserId] IS NOT NULL");
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ImageInfos_Users_UserId",
+ schema: "jellyfin",
+ table: "ImageInfos",
+ column: "UserId",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_Permissions_Users_UserId",
+ schema: "jellyfin",
+ table: "Permissions",
+ column: "UserId",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_Preferences_Users_UserId",
+ schema: "jellyfin",
+ table: "Preferences",
+ column: "UserId",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_ImageInfos_Users_UserId",
+ schema: "jellyfin",
+ table: "ImageInfos");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_Permissions_Users_UserId",
+ schema: "jellyfin",
+ table: "Permissions");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_Preferences_Users_UserId",
+ schema: "jellyfin",
+ table: "Preferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_Users_Username",
+ schema: "jellyfin",
+ table: "Users");
+
+ migrationBuilder.DropIndex(
+ name: "IX_Preferences_UserId_Kind",
+ schema: "jellyfin",
+ table: "Preferences");
+
+ migrationBuilder.DropIndex(
+ name: "IX_Permissions_UserId_Kind",
+ schema: "jellyfin",
+ table: "Permissions");
+
+ migrationBuilder.DropColumn(
+ name: "UserId",
+ schema: "jellyfin",
+ table: "Preferences");
+
+ migrationBuilder.DropColumn(
+ name: "UserId",
+ schema: "jellyfin",
+ table: "Permissions");
+
+ migrationBuilder.AlterColumn<string>(
+ name: "Username",
+ schema: "jellyfin",
+ table: "Users",
+ type: "TEXT",
+ maxLength: 255,
+ nullable: false,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldMaxLength: 255,
+ oldCollation: "NOCASE");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Preferences_Preference_Preferences_Guid",
+ schema: "jellyfin",
+ table: "Preferences",
+ column: "Preference_Preferences_Guid");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Permissions_Permission_Permissions_Guid",
+ schema: "jellyfin",
+ table: "Permissions",
+ column: "Permission_Permissions_Guid");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "DisplayPreferences",
+ column: "UserId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_CustomItemDisplayPreferences_UserId",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences",
+ column: "UserId");
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ImageInfos_Users_UserId",
+ schema: "jellyfin",
+ table: "ImageInfos",
+ column: "UserId",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_Permissions_Users_Permission_Permissions_Guid",
+ schema: "jellyfin",
+ table: "Permissions",
+ column: "Permission_Permissions_Guid",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_Preferences_Users_Preference_Preferences_Guid",
+ schema: "jellyfin",
+ table: "Preferences",
+ column: "Preference_Preferences_Guid",
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs
new file mode 100644
index 000000000..d332d19f2
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs
@@ -0,0 +1,520 @@
+#pragma warning disable CS1591
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20210407110544_NullableCustomPrefValue")]
+ partial class NullableCustomPrefValue
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "5.0.3");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+
+ b.HasIndex("UserId", "ItemId", "Client", "Key")
+ .IsUnique();
+
+ b.ToTable("CustomItemDisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+
+ b.HasIndex("UserId", "ItemId", "Client")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<string>("Value")
+ .IsRequired()
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ 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.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("DisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Navigation("HomeSections");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs
new file mode 100644
index 000000000..ade68612c
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs
@@ -0,0 +1,35 @@
+#pragma warning disable CS1591
+// <auto-generated />
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class NullableCustomPrefValue : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AlterColumn<string>(
+ name: "Value",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AlterColumn<string>(
+ name: "Value",
+ schema: "jellyfin",
+ table: "CustomItemDisplayPreferences",
+ type: "TEXT",
+ nullable: false,
+ defaultValue: "",
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.Designer.cs
new file mode 100644
index 000000000..7e9566e2e
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.Designer.cs
@@ -0,0 +1,653 @@
+#pragma warning disable CS1591
+
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20210814002109_AddDevices")]
+ partial class AddDevices
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "5.0.7");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ 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")
+ .UseCollation("NOCASE");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("DisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Security.Device", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Navigation("HomeSections");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.cs b/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.cs
new file mode 100644
index 000000000..ac062317a
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20210814002109_AddDevices.cs
@@ -0,0 +1,128 @@
+#pragma warning disable CS1591, SA1601
+
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddDevices : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "ApiKeys",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ DateCreated = table.Column<DateTime>(type: "TEXT", nullable: false),
+ DateLastActivity = table.Column<DateTime>(type: "TEXT", nullable: false),
+ Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
+ AccessToken = table.Column<string>(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ApiKeys", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "DeviceOptions",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ DeviceId = table.Column<string>(type: "TEXT", nullable: false),
+ CustomName = table.Column<string>(type: "TEXT", nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_DeviceOptions", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Devices",
+ schema: "jellyfin",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ UserId = table.Column<Guid>(type: "TEXT", nullable: false),
+ AccessToken = table.Column<string>(type: "TEXT", nullable: false),
+ AppName = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
+ AppVersion = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
+ DeviceName = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
+ DeviceId = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
+ IsActive = table.Column<bool>(type: "INTEGER", nullable: false),
+ DateCreated = table.Column<DateTime>(type: "TEXT", nullable: false),
+ DateModified = table.Column<DateTime>(type: "TEXT", nullable: false),
+ DateLastActivity = table.Column<DateTime>(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Devices", x => x.Id);
+ table.ForeignKey(
+ name: "FK_Devices_Users_UserId",
+ column: x => x.UserId,
+ principalSchema: "jellyfin",
+ principalTable: "Users",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ApiKeys_AccessToken",
+ schema: "jellyfin",
+ table: "ApiKeys",
+ column: "AccessToken",
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_DeviceOptions_DeviceId",
+ schema: "jellyfin",
+ table: "DeviceOptions",
+ column: "DeviceId",
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Devices_AccessToken_DateLastActivity",
+ schema: "jellyfin",
+ table: "Devices",
+ columns: new[] { "AccessToken", "DateLastActivity" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Devices_DeviceId",
+ schema: "jellyfin",
+ table: "Devices",
+ column: "DeviceId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Devices_DeviceId_DateLastActivity",
+ schema: "jellyfin",
+ table: "Devices",
+ columns: new[] { "DeviceId", "DateLastActivity" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Devices_UserId_DeviceId",
+ schema: "jellyfin",
+ table: "Devices",
+ columns: new[] { "UserId", "DeviceId" });
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "ApiKeys",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "DeviceOptions",
+ schema: "jellyfin");
+
+ migrationBuilder.DropTable(
+ name: "Devices",
+ schema: "jellyfin");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/DesignTimeJellyfinDbFactory.cs b/Jellyfin.Server.Implementations/Migrations/DesignTimeJellyfinDbFactory.cs
new file mode 100644
index 000000000..72a4a8c3b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/DesignTimeJellyfinDbFactory.cs
@@ -0,0 +1,20 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Design;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <summary>
+ /// The design time factory for <see cref="JellyfinDb"/>.
+ /// This is only used for the creation of migrations and not during runtime.
+ /// </summary>
+ internal class DesignTimeJellyfinDbFactory : IDesignTimeDbContextFactory<JellyfinDb>
+ {
+ public JellyfinDb CreateDbContext(string[] args)
+ {
+ var optionsBuilder = new DbContextOptionsBuilder<JellyfinDb>();
+ optionsBuilder.UseSqlite("Data Source=jellyfin.db");
+
+ return new JellyfinDb(optionsBuilder.Options);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs
new file mode 100644
index 000000000..fcc360e26
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs
@@ -0,0 +1,649 @@
+// <auto-generated />
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ partial class JellyfinDbModelSnapshot : ModelSnapshot
+ {
+ protected override void BuildModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "5.0.7");
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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<bool>("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EasyPassword")
+ .HasMaxLength(65535)
+ .HasColumnType("TEXT");
+
+ 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")
+ .UseCollation("NOCASE");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("DisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Security.Device", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Navigation("HomeSections");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.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/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs b/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs
new file mode 100644
index 000000000..80ad65a42
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs
@@ -0,0 +1,48 @@
+using System;
+using Jellyfin.Server.Implementations.ValueConverters;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations
+{
+ /// <summary>
+ /// Model builder extensions.
+ /// </summary>
+ public static class ModelBuilderExtensions
+ {
+ /// <summary>
+ /// Specify value converter for the object type.
+ /// </summary>
+ /// <param name="modelBuilder">The model builder.</param>
+ /// <param name="converter">The <see cref="ValueConverter{TModel,TProvider}"/>.</param>
+ /// <typeparam name="T">The type to convert.</typeparam>
+ /// <returns>The modified <see cref="ModelBuilder"/>.</returns>
+ public static ModelBuilder UseValueConverterForType<T>(this ModelBuilder modelBuilder, ValueConverter converter)
+ {
+ var type = typeof(T);
+ foreach (var entityType in modelBuilder.Model.GetEntityTypes())
+ {
+ foreach (var property in entityType.GetProperties())
+ {
+ if (property.ClrType == type)
+ {
+ property.SetValueConverter(converter);
+ }
+ }
+ }
+
+ return modelBuilder;
+ }
+
+ /// <summary>
+ /// Specify the default <see cref="DateTimeKind"/>.
+ /// </summary>
+ /// <param name="modelBuilder">The model builder to extend.</param>
+ /// <param name="kind">The <see cref="DateTimeKind"/> to specify.</param>
+ public static void SetDefaultDateTimeKind(this ModelBuilder modelBuilder, DateTimeKind kind)
+ {
+ modelBuilder.UseValueConverterForType<DateTime>(new DateTimeKindValueConverter(kind));
+ modelBuilder.UseValueConverterForType<DateTime?>(new DateTimeKindValueConverter(kind));
+ }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/ApiKeyConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/ApiKeyConfiguration.cs
new file mode 100644
index 000000000..3f19b6986
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/ApiKeyConfiguration.cs
@@ -0,0 +1,20 @@
+using Jellyfin.Data.Entities.Security;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the ApiKey entity.
+ /// </summary>
+ public class ApiKeyConfiguration : IEntityTypeConfiguration<ApiKey>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<ApiKey> builder)
+ {
+ builder
+ .HasIndex(entity => entity.AccessToken)
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/CustomItemDisplayPreferencesConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/CustomItemDisplayPreferencesConfiguration.cs
new file mode 100644
index 000000000..779aec986
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/CustomItemDisplayPreferencesConfiguration.cs
@@ -0,0 +1,20 @@
+using Jellyfin.Data.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the CustomItemDisplayPreferences entity.
+ /// </summary>
+ public class CustomItemDisplayPreferencesConfiguration : IEntityTypeConfiguration<CustomItemDisplayPreferences>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<CustomItemDisplayPreferences> builder)
+ {
+ builder
+ .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client, entity.Key })
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/DeviceConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/DeviceConfiguration.cs
new file mode 100644
index 000000000..a750b65c0
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/DeviceConfiguration.cs
@@ -0,0 +1,28 @@
+using Jellyfin.Data.Entities.Security;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the Device entity.
+ /// </summary>
+ public class DeviceConfiguration : IEntityTypeConfiguration<Device>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<Device> builder)
+ {
+ builder
+ .HasIndex(entity => new { entity.DeviceId, entity.DateLastActivity });
+
+ builder
+ .HasIndex(entity => new { entity.AccessToken, entity.DateLastActivity });
+
+ builder
+ .HasIndex(entity => new { entity.UserId, entity.DeviceId });
+
+ builder
+ .HasIndex(entity => entity.DeviceId);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/DeviceOptionsConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/DeviceOptionsConfiguration.cs
new file mode 100644
index 000000000..038afd752
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/DeviceOptionsConfiguration.cs
@@ -0,0 +1,20 @@
+using Jellyfin.Data.Entities.Security;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the DeviceOptions entity.
+ /// </summary>
+ public class DeviceOptionsConfiguration : IEntityTypeConfiguration<DeviceOptions>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<DeviceOptions> builder)
+ {
+ builder
+ .HasIndex(entity => entity.DeviceId)
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/DisplayPreferencesConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/DisplayPreferencesConfiguration.cs
new file mode 100644
index 000000000..9b437861b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/DisplayPreferencesConfiguration.cs
@@ -0,0 +1,25 @@
+using Jellyfin.Data.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the DisplayPreferencesConfiguration entity.
+ /// </summary>
+ public class DisplayPreferencesConfiguration : IEntityTypeConfiguration<DisplayPreferences>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<DisplayPreferences> builder)
+ {
+ builder
+ .HasMany(d => d.HomeSections)
+ .WithOne()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client })
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/PermissionConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/PermissionConfiguration.cs
new file mode 100644
index 000000000..240e284c0
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/PermissionConfiguration.cs
@@ -0,0 +1,24 @@
+using Jellyfin.Data.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the Permission entity.
+ /// </summary>
+ public class PermissionConfiguration : IEntityTypeConfiguration<Permission>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<Permission> builder)
+ {
+ // Used to get a user's permissions or a specific permission for a user.
+ // Also prevents multiple values being created for a user.
+ // Filtered over non-null user ids for when other entities (groups, API keys) get permissions
+ builder
+ .HasIndex(p => new { p.UserId, p.Kind })
+ .HasFilter("[UserId] IS NOT NULL")
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/PreferenceConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/PreferenceConfiguration.cs
new file mode 100644
index 000000000..49c869c6a
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/PreferenceConfiguration.cs
@@ -0,0 +1,21 @@
+using Jellyfin.Data.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the Permission entity.
+ /// </summary>
+ public class PreferenceConfiguration : IEntityTypeConfiguration<Preference>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<Preference> builder)
+ {
+ builder
+ .HasIndex(p => new { p.UserId, p.Kind })
+ .HasFilter("[UserId] IS NOT NULL")
+ .IsUnique();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ModelConfiguration/UserConfiguration.cs b/Jellyfin.Server.Implementations/ModelConfiguration/UserConfiguration.cs
new file mode 100644
index 000000000..a369cf656
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ModelConfiguration/UserConfiguration.cs
@@ -0,0 +1,56 @@
+using Jellyfin.Data.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Server.Implementations.ModelConfiguration
+{
+ /// <summary>
+ /// FluentAPI configuration for the User entity.
+ /// </summary>
+ public class UserConfiguration : IEntityTypeConfiguration<User>
+ {
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<User> builder)
+ {
+ builder
+ .Property(user => user.Username)
+ .UseCollation("NOCASE");
+
+ builder
+ .HasOne(u => u.ProfileImage)
+ .WithOne()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasMany(u => u.Permissions)
+ .WithOne()
+ .HasForeignKey(p => p.UserId)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasMany(u => u.Preferences)
+ .WithOne()
+ .HasForeignKey(p => p.UserId)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasMany(u => u.AccessSchedules)
+ .WithOne()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasMany(u => u.DisplayPreferences)
+ .WithOne()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasMany(u => u.ItemDisplayPreferences)
+ .WithOne()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder
+ .HasIndex(entity => entity.Username)
+ .IsUnique();
+ }
+ }
+}
diff --git a/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs b/Jellyfin.Server.Implementations/Properties/AssemblyInfo.cs
index d60eccc2e..6528d4fdc 100644
--- a/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs
+++ b/Jellyfin.Server.Implementations/Properties/AssemblyInfo.cs
@@ -1,19 +1,21 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
-[assembly: AssemblyTitle("IsoMounter")]
+[assembly: AssemblyTitle("Jellyfin.Server.Implementations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.Server.Implementations.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs b/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs
new file mode 100644
index 000000000..b79e46469
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs
@@ -0,0 +1,73 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities.Security;
+using MediaBrowser.Controller.Security;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations.Security
+{
+ /// <inheritdoc />
+ public class AuthenticationManager : IAuthenticationManager
+ {
+ private readonly JellyfinDbProvider _dbProvider;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationManager"/> class.
+ /// </summary>
+ /// <param name="dbProvider">The database provider.</param>
+ public AuthenticationManager(JellyfinDbProvider dbProvider)
+ {
+ _dbProvider = dbProvider;
+ }
+
+ /// <inheritdoc />
+ public async Task CreateApiKey(string name)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+
+ dbContext.ApiKeys.Add(new ApiKey(name));
+
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+
+ return await dbContext.ApiKeys
+ .AsAsyncEnumerable()
+ .Select(key => new AuthenticationInfo
+ {
+ AppName = key.Name,
+ AccessToken = key.AccessToken,
+ DateCreated = key.DateCreated,
+ DeviceId = string.Empty,
+ DeviceName = string.Empty,
+ AppVersion = string.Empty
+ }).ToListAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task DeleteApiKey(string accessToken)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+
+ var key = await dbContext.ApiKeys
+ .AsQueryable()
+ .Where(apiKey => apiKey.AccessToken == accessToken)
+ .FirstOrDefaultAsync()
+ .ConfigureAwait(false);
+
+ if (key == null)
+ {
+ return;
+ }
+
+ dbContext.Remove(key);
+
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs b/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs
new file mode 100644
index 000000000..3ab043c64
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs
@@ -0,0 +1,308 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Server.Implementations.Security
+{
+ public class AuthorizationContext : IAuthorizationContext
+ {
+ private readonly JellyfinDbProvider _jellyfinDbProvider;
+ private readonly IUserManager _userManager;
+
+ public AuthorizationContext(JellyfinDbProvider jellyfinDb, IUserManager userManager)
+ {
+ _jellyfinDbProvider = jellyfinDb;
+ _userManager = userManager;
+ }
+
+ public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
+ {
+ if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached != null)
+ {
+ return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
+ }
+
+ return GetAuthorization(requestContext);
+ }
+
+ public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
+ {
+ var auth = GetAuthorizationDictionary(requestContext);
+ var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
+ return authInfo;
+ }
+
+ /// <summary>
+ /// Gets the authorization.
+ /// </summary>
+ /// <param name="httpReq">The HTTP req.</param>
+ /// <returns>Dictionary{System.StringSystem.String}.</returns>
+ private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpReq)
+ {
+ var auth = GetAuthorizationDictionary(httpReq);
+ var authInfo = await GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query).ConfigureAwait(false);
+
+ httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
+ return authInfo;
+ }
+
+ private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
+ IReadOnlyDictionary<string, string>? auth,
+ IHeaderDictionary headers,
+ IQueryCollection queryString)
+ {
+ string? deviceId = null;
+ string? deviceName = null;
+ string? client = null;
+ string? version = null;
+ string? token = null;
+
+ if (auth != null)
+ {
+ auth.TryGetValue("DeviceId", out deviceId);
+ auth.TryGetValue("Device", out deviceName);
+ auth.TryGetValue("Client", out client);
+ auth.TryGetValue("Version", out version);
+ auth.TryGetValue("Token", out token);
+ }
+
+#pragma warning disable CA1508 // string.IsNullOrEmpty(token) is always false.
+ if (string.IsNullOrEmpty(token))
+ {
+ token = headers["X-Emby-Token"];
+ }
+
+ if (string.IsNullOrEmpty(token))
+ {
+ token = headers["X-MediaBrowser-Token"];
+ }
+
+ if (string.IsNullOrEmpty(token))
+ {
+ token = queryString["ApiKey"];
+ }
+
+ // TODO deprecate this query parameter.
+ if (string.IsNullOrEmpty(token))
+ {
+ token = queryString["api_key"];
+ }
+
+ var authInfo = new AuthorizationInfo
+ {
+ Client = client,
+ Device = deviceName,
+ DeviceId = deviceId,
+ Version = version,
+ Token = token,
+ IsAuthenticated = false,
+ HasToken = false
+ };
+
+ if (string.IsNullOrWhiteSpace(token))
+ {
+ // Request doesn't contain a token.
+ return authInfo;
+ }
+#pragma warning restore CA1508
+
+ authInfo.HasToken = true;
+ await using var dbContext = _jellyfinDbProvider.CreateContext();
+ var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);
+
+ if (device != null)
+ {
+ authInfo.IsAuthenticated = true;
+ var updateToken = false;
+
+ // TODO: Remove these checks for IsNullOrWhiteSpace
+ if (string.IsNullOrWhiteSpace(authInfo.Client))
+ {
+ authInfo.Client = device.AppName;
+ }
+
+ if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
+ {
+ authInfo.DeviceId = device.DeviceId;
+ }
+
+ // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
+ var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
+
+ if (string.IsNullOrWhiteSpace(authInfo.Device))
+ {
+ authInfo.Device = device.DeviceName;
+ }
+ else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
+ {
+ if (allowTokenInfoUpdate)
+ {
+ updateToken = true;
+ device.DeviceName = authInfo.Device;
+ }
+ }
+
+ if (string.IsNullOrWhiteSpace(authInfo.Version))
+ {
+ authInfo.Version = device.AppVersion;
+ }
+ else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
+ {
+ if (allowTokenInfoUpdate)
+ {
+ updateToken = true;
+ device.AppVersion = authInfo.Version;
+ }
+ }
+
+ if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
+ {
+ device.DateLastActivity = DateTime.UtcNow;
+ updateToken = true;
+ }
+
+ authInfo.User = _userManager.GetUserById(device.UserId);
+
+ if (updateToken)
+ {
+ dbContext.Devices.Update(device);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+ }
+ else
+ {
+ var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
+ if (key != null)
+ {
+ authInfo.IsAuthenticated = true;
+ authInfo.Client = key.Name;
+ authInfo.Token = key.AccessToken;
+ authInfo.DeviceId = string.Empty;
+ authInfo.Device = string.Empty;
+ authInfo.Version = string.Empty;
+ authInfo.IsApiKey = true;
+ }
+ }
+
+ return authInfo;
+ }
+
+ /// <summary>
+ /// Gets the auth.
+ /// </summary>
+ /// <param name="httpReq">The HTTP req.</param>
+ /// <returns>Dictionary{System.StringSystem.String}.</returns>
+ private static Dictionary<string, string>? GetAuthorizationDictionary(HttpContext httpReq)
+ {
+ var auth = httpReq.Request.Headers["X-Emby-Authorization"];
+
+ if (string.IsNullOrEmpty(auth))
+ {
+ auth = httpReq.Request.Headers[HeaderNames.Authorization];
+ }
+
+ return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
+ }
+
+ /// <summary>
+ /// Gets the auth.
+ /// </summary>
+ /// <param name="httpReq">The HTTP req.</param>
+ /// <returns>Dictionary{System.StringSystem.String}.</returns>
+ private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
+ {
+ var auth = httpReq.Headers["X-Emby-Authorization"];
+
+ if (string.IsNullOrEmpty(auth))
+ {
+ auth = httpReq.Headers[HeaderNames.Authorization];
+ }
+
+ return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
+ }
+
+ /// <summary>
+ /// Gets the authorization.
+ /// </summary>
+ /// <param name="authorizationHeader">The authorization header.</param>
+ /// <returns>Dictionary{System.StringSystem.String}.</returns>
+ private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
+ {
+ var firstSpace = authorizationHeader.IndexOf(' ');
+
+ // There should be at least two parts
+ if (firstSpace == -1)
+ {
+ return null;
+ }
+
+ var name = authorizationHeader[..firstSpace];
+
+ if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
+ && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
+ // Remove up until the first space
+ authorizationHeader = authorizationHeader[(firstSpace + 1)..];
+ return GetParts(authorizationHeader);
+ }
+
+ /// <summary>
+ /// Get the authorization header components.
+ /// </summary>
+ /// <param name="authorizationHeader">The authorization header.</param>
+ /// <returns>Dictionary{System.StringSystem.String}.</returns>
+ public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
+ {
+ var result = new Dictionary<string, string>();
+ var escaped = false;
+ int start = 0;
+ string key = string.Empty;
+
+ int i;
+ for (i = 0; i < authorizationHeader.Length; i++)
+ {
+ var token = authorizationHeader[i];
+ if (token == '"' || token == ',')
+ {
+ // Applying a XOR logic to evaluate whether it is opening or closing a value
+ escaped = (!escaped) == (token == '"');
+ if (token == ',' && !escaped)
+ {
+ // Meeting a comma after a closing escape char means the value is complete
+ if (start < i)
+ {
+ result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
+ key = string.Empty;
+ }
+
+ start = i + 1;
+ }
+ }
+ else if (!escaped && token == '=')
+ {
+ key = authorizationHeader[start.. i].Trim().ToString();
+ start = i + 1;
+ }
+ }
+
+ // Add last value
+ if (start < i)
+ {
+ result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs
new file mode 100644
index 000000000..6a78e7ee6
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs
@@ -0,0 +1,118 @@
+using System;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Cryptography;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Model.Cryptography;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ /// <summary>
+ /// The default authentication provider.
+ /// </summary>
+ public class DefaultAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
+ {
+ private readonly ICryptoProvider _cryptographyProvider;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DefaultAuthenticationProvider"/> class.
+ /// </summary>
+ /// <param name="cryptographyProvider">The cryptography provider.</param>
+ public DefaultAuthenticationProvider(ICryptoProvider cryptographyProvider)
+ {
+ _cryptographyProvider = cryptographyProvider;
+ }
+
+ /// <inheritdoc />
+ public string Name => "Default";
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ // This is dumb and an artifact of the backwards way auth providers were designed.
+ // This version of authenticate was never meant to be called, but needs to be here for interface compat
+ // Only the providers that don't provide local user support use this
+ public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
+ {
+ throw new NotImplementedException();
+ }
+
+ /// <inheritdoc />
+ // This is the version that we need to use for local users. Because reasons.
+ public Task<ProviderAuthenticationResult> Authenticate(string username, string password, User resolvedUser)
+ {
+ if (resolvedUser == null)
+ {
+ throw new AuthenticationException("Specified user does not exist.");
+ }
+
+ bool success = false;
+
+ // As long as jellyfin supports password-less users, we need this little block here to accommodate
+ if (!HasPassword(resolvedUser) && string.IsNullOrEmpty(password))
+ {
+ return Task.FromResult(new ProviderAuthenticationResult
+ {
+ Username = username
+ });
+ }
+
+ // Handle the case when the stored password is null, but the user tried to login with a password
+ if (resolvedUser.Password != null)
+ {
+ byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
+
+ PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password);
+ if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id)
+ || _cryptographyProvider.DefaultHashMethod == readyHash.Id)
+ {
+ byte[] calculatedHash = _cryptographyProvider.ComputeHash(
+ readyHash.Id,
+ passwordBytes,
+ readyHash.Salt.ToArray());
+
+ if (readyHash.Hash.SequenceEqual(calculatedHash))
+ {
+ success = true;
+ }
+ }
+ else
+ {
+ throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}");
+ }
+ }
+
+ if (!success)
+ {
+ throw new AuthenticationException("Invalid username or password");
+ }
+
+ return Task.FromResult(new ProviderAuthenticationResult
+ {
+ Username = username
+ });
+ }
+
+ /// <inheritdoc />
+ public bool HasPassword(User user)
+ => !string.IsNullOrEmpty(user?.Password);
+
+ /// <inheritdoc />
+ public Task ChangePassword(User user, string newPassword)
+ {
+ if (string.IsNullOrEmpty(newPassword))
+ {
+ user.Password = null;
+ return Task.CompletedTask;
+ }
+
+ PasswordHash newPasswordHash = _cryptographyProvider.CreatePasswordHash(newPassword);
+ user.Password = newPasswordHash.ToString();
+
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs
new file mode 100644
index 000000000..5e84255f9
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs
@@ -0,0 +1,133 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Users;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ /// <summary>
+ /// The default password reset provider.
+ /// </summary>
+ public class DefaultPasswordResetProvider : IPasswordResetProvider
+ {
+ private const string BaseResetFileName = "passwordreset";
+
+ private readonly IApplicationHost _appHost;
+
+ private readonly string _passwordResetFileBase;
+ private readonly string _passwordResetFileBaseDir;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DefaultPasswordResetProvider"/> class.
+ /// </summary>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <param name="appHost">The application host.</param>
+ public DefaultPasswordResetProvider(IServerConfigurationManager configurationManager, IApplicationHost appHost)
+ {
+ _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
+ _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, BaseResetFileName);
+ _appHost = appHost;
+ // TODO: Remove the circular dependency on UserManager
+ }
+
+ /// <inheritdoc />
+ public string Name => "Default Password Reset Provider";
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
+ {
+ var userManager = _appHost.Resolve<IUserManager>();
+ var usersReset = new List<string>();
+ foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*"))
+ {
+ SerializablePasswordReset spr;
+ await using (var str = AsyncFile.OpenRead(resetFile))
+ {
+ spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false)
+ ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid.");
+ }
+
+ if (spr.ExpirationDate < DateTime.UtcNow)
+ {
+ File.Delete(resetFile);
+ }
+ else if (string.Equals(
+ spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal),
+ pin.Replace("-", string.Empty, StringComparison.Ordinal),
+ StringComparison.OrdinalIgnoreCase))
+ {
+ var resetUser = userManager.GetUserByName(spr.UserName)
+ ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
+
+ await userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
+ usersReset.Add(resetUser.Username);
+ File.Delete(resetFile);
+ }
+ }
+
+ if (usersReset.Count < 1)
+ {
+ throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
+ }
+
+ return new PinRedeemResult
+ {
+ Success = true,
+ UsersReset = usersReset.ToArray()
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork)
+ {
+ byte[] bytes = new byte[4];
+ RandomNumberGenerator.Fill(bytes);
+ string pin = BitConverter.ToString(bytes);
+
+ DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
+ string filePath = _passwordResetFileBase + user.Id + ".json";
+ SerializablePasswordReset spr = new SerializablePasswordReset
+ {
+ ExpirationDate = expireTime,
+ Pin = pin,
+ PinFile = filePath,
+ UserName = user.Username
+ };
+
+ await using (FileStream fileStream = AsyncFile.OpenWrite(filePath))
+ {
+ await JsonSerializer.SerializeAsync(fileStream, spr).ConfigureAwait(false);
+ }
+
+ user.EasyPassword = pin;
+
+ return new ForgotPasswordResult
+ {
+ Action = ForgotPasswordAction.PinCode,
+ PinExpirationDate = expireTime,
+ PinFile = filePath
+ };
+ }
+
+#nullable disable
+ private class SerializablePasswordReset : PasswordPinCreationResult
+ {
+ public string Pin { get; set; }
+
+ public string UserName { get; set; }
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs b/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs
new file mode 100644
index 000000000..a471ea1d5
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs
@@ -0,0 +1,64 @@
+#pragma warning disable CS1591
+
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Plugins;
+using MediaBrowser.Controller.Session;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ public sealed class DeviceAccessEntryPoint : IServerEntryPoint
+ {
+ private readonly IUserManager _userManager;
+ private readonly IDeviceManager _deviceManager;
+ private readonly ISessionManager _sessionManager;
+
+ public DeviceAccessEntryPoint(IUserManager userManager, IDeviceManager deviceManager, ISessionManager sessionManager)
+ {
+ _userManager = userManager;
+ _deviceManager = deviceManager;
+ _sessionManager = sessionManager;
+ }
+
+ public Task RunAsync()
+ {
+ _userManager.OnUserUpdated += OnUserUpdated;
+
+ return Task.CompletedTask;
+ }
+
+ public void Dispose()
+ {
+ }
+
+ private async void OnUserUpdated(object? sender, GenericEventArgs<User> e)
+ {
+ var user = e.Argument;
+ if (!user.HasPermission(PermissionKind.EnableAllDevices))
+ {
+ await UpdateDeviceAccess(user).ConfigureAwait(false);
+ }
+ }
+
+ private async Task UpdateDeviceAccess(User user)
+ {
+ var existing = (await _deviceManager.GetDevices(new DeviceQuery
+ {
+ UserId = user.Id
+ }).ConfigureAwait(false)).Items;
+
+ foreach (var device in existing)
+ {
+ if (!string.IsNullOrEmpty(device.DeviceId) && !_deviceManager.CanAccessDevice(user, device.DeviceId))
+ {
+ await _sessionManager.Logout(device).ConfigureAwait(false);
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs
new file mode 100644
index 000000000..c89e3c74d
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs
@@ -0,0 +1,104 @@
+#pragma warning disable CA1307
+#pragma warning disable CA1309
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ /// <summary>
+ /// Manages the storage and retrieval of display preferences through Entity Framework.
+ /// </summary>
+ public class DisplayPreferencesManager : IDisplayPreferencesManager
+ {
+ private readonly JellyfinDb _dbContext;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DisplayPreferencesManager"/> class.
+ /// </summary>
+ /// <param name="dbContext">The database context.</param>
+ public DisplayPreferencesManager(JellyfinDb dbContext)
+ {
+ _dbContext = dbContext;
+ }
+
+ /// <inheritdoc />
+ public DisplayPreferences GetDisplayPreferences(Guid userId, Guid itemId, string client)
+ {
+ var prefs = _dbContext.DisplayPreferences
+ .Include(pref => pref.HomeSections)
+ .FirstOrDefault(pref =>
+ pref.UserId == userId && string.Equals(pref.Client, client) && pref.ItemId == itemId);
+
+ if (prefs == null)
+ {
+ prefs = new DisplayPreferences(userId, itemId, client);
+ _dbContext.DisplayPreferences.Add(prefs);
+ }
+
+ return prefs;
+ }
+
+ /// <inheritdoc />
+ public ItemDisplayPreferences GetItemDisplayPreferences(Guid userId, Guid itemId, string client)
+ {
+ var prefs = _dbContext.ItemDisplayPreferences
+ .FirstOrDefault(pref => pref.UserId == userId && pref.ItemId == itemId && string.Equals(pref.Client, client));
+
+ if (prefs == null)
+ {
+ prefs = new ItemDisplayPreferences(userId, Guid.Empty, client);
+ _dbContext.ItemDisplayPreferences.Add(prefs);
+ }
+
+ return prefs;
+ }
+
+ /// <inheritdoc />
+ public IList<ItemDisplayPreferences> ListItemDisplayPreferences(Guid userId, string client)
+ {
+ return _dbContext.ItemDisplayPreferences
+ .AsQueryable()
+ .Where(prefs => prefs.UserId == userId && prefs.ItemId != Guid.Empty && string.Equals(prefs.Client, client))
+ .ToList();
+ }
+
+ /// <inheritdoc />
+ public Dictionary<string, string?> ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client)
+ {
+ return _dbContext.CustomItemDisplayPreferences
+ .AsQueryable()
+ .Where(prefs => prefs.UserId == userId
+ && prefs.ItemId == itemId
+ && string.Equals(prefs.Client, client))
+ .ToDictionary(prefs => prefs.Key, prefs => prefs.Value);
+ }
+
+ /// <inheritdoc />
+ public void SetCustomItemDisplayPreferences(Guid userId, Guid itemId, string client, Dictionary<string, string> customPreferences)
+ {
+ var existingPrefs = _dbContext.CustomItemDisplayPreferences
+ .AsQueryable()
+ .Where(prefs => prefs.UserId == userId
+ && prefs.ItemId == itemId
+ && string.Equals(prefs.Client, client));
+ _dbContext.CustomItemDisplayPreferences.RemoveRange(existingPrefs);
+
+ foreach (var (key, value) in customPreferences)
+ {
+ _dbContext.CustomItemDisplayPreferences
+ .Add(new CustomItemDisplayPreferences(userId, itemId, client, key, value));
+ }
+ }
+
+ /// <inheritdoc />
+ public void SaveChanges()
+ {
+ _dbContext.SaveChanges();
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs
new file mode 100644
index 000000000..c4e4c460a
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs
@@ -0,0 +1,36 @@
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Authentication;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ /// <summary>
+ /// An invalid authentication provider.
+ /// </summary>
+ public class InvalidAuthProvider : IAuthenticationProvider
+ {
+ /// <inheritdoc />
+ public string Name => "InvalidOrMissingAuthenticationProvider";
+
+ /// <inheritdoc />
+ public bool IsEnabled => false;
+
+ /// <inheritdoc />
+ public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
+ {
+ throw new AuthenticationException("User Account cannot login with this provider. The Normal provider for this user cannot be found");
+ }
+
+ /// <inheritdoc />
+ public bool HasPassword(User user)
+ {
+ return true;
+ }
+
+ /// <inheritdoc />
+ public Task ChangePassword(User user, string newPassword)
+ {
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs
new file mode 100644
index 000000000..8ca6e8d21
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/UserManager.cs
@@ -0,0 +1,876 @@
+#pragma warning disable CA1307
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Events.Users;
+using MediaBrowser.Common;
+using MediaBrowser.Common.Cryptography;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Cryptography;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Users;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.Users
+{
+ /// <summary>
+ /// Manages the creation and retrieval of <see cref="User"/> instances.
+ /// </summary>
+ public class UserManager : IUserManager
+ {
+ private readonly JellyfinDbProvider _dbProvider;
+ private readonly IEventManager _eventManager;
+ private readonly ICryptoProvider _cryptoProvider;
+ private readonly INetworkManager _networkManager;
+ private readonly IApplicationHost _appHost;
+ private readonly IImageProcessor _imageProcessor;
+ private readonly ILogger<UserManager> _logger;
+ private readonly IReadOnlyCollection<IPasswordResetProvider> _passwordResetProviders;
+ private readonly IReadOnlyCollection<IAuthenticationProvider> _authenticationProviders;
+ private readonly InvalidAuthProvider _invalidAuthProvider;
+ private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider;
+ private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider;
+
+ private readonly IDictionary<Guid, User> _users;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserManager"/> class.
+ /// </summary>
+ /// <param name="dbProvider">The database provider.</param>
+ /// <param name="eventManager">The event manager.</param>
+ /// <param name="cryptoProvider">The cryptography provider.</param>
+ /// <param name="networkManager">The network manager.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="imageProcessor">The image processor.</param>
+ /// <param name="logger">The logger.</param>
+ public UserManager(
+ JellyfinDbProvider dbProvider,
+ IEventManager eventManager,
+ ICryptoProvider cryptoProvider,
+ INetworkManager networkManager,
+ IApplicationHost appHost,
+ IImageProcessor imageProcessor,
+ ILogger<UserManager> logger)
+ {
+ _dbProvider = dbProvider;
+ _eventManager = eventManager;
+ _cryptoProvider = cryptoProvider;
+ _networkManager = networkManager;
+ _appHost = appHost;
+ _imageProcessor = imageProcessor;
+ _logger = logger;
+
+ _passwordResetProviders = appHost.GetExports<IPasswordResetProvider>();
+ _authenticationProviders = appHost.GetExports<IAuthenticationProvider>();
+
+ _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
+ _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
+ _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
+
+ _users = new ConcurrentDictionary<Guid, User>();
+ using var dbContext = _dbProvider.CreateContext();
+ foreach (var user in dbContext.Users
+ .Include(user => user.Permissions)
+ .Include(user => user.Preferences)
+ .Include(user => user.AccessSchedules)
+ .Include(user => user.ProfileImage)
+ .AsEnumerable())
+ {
+ _users.Add(user.Id, user);
+ }
+ }
+
+ /// <inheritdoc/>
+ public event EventHandler<GenericEventArgs<User>>? OnUserUpdated;
+
+ /// <inheritdoc/>
+ public IEnumerable<User> Users => _users.Values;
+
+ /// <inheritdoc/>
+ public IEnumerable<Guid> UsersIds => _users.Keys;
+
+ /// <inheritdoc/>
+ public User? GetUserById(Guid id)
+ {
+ if (id == Guid.Empty)
+ {
+ throw new ArgumentException("Guid can't be empty", nameof(id));
+ }
+
+ _users.TryGetValue(id, out var user);
+ return user;
+ }
+
+ /// <inheritdoc/>
+ public User? GetUserByName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ throw new ArgumentException("Invalid username", nameof(name));
+ }
+
+ return _users.Values.FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// <inheritdoc/>
+ public async Task RenameUser(User user, string newName)
+ {
+ if (user == null)
+ {
+ throw new ArgumentNullException(nameof(user));
+ }
+
+ ThrowIfInvalidUsername(newName);
+
+ if (user.Username.Equals(newName, StringComparison.Ordinal))
+ {
+ throw new ArgumentException("The new and old names must be different.");
+ }
+
+ await using var dbContext = _dbProvider.CreateContext();
+
+ if (await dbContext.Users
+ .AsQueryable()
+ .Where(u => u.Username == newName && u.Id != user.Id)
+ .AnyAsync()
+ .ConfigureAwait(false))
+ {
+ throw new ArgumentException(string.Format(
+ CultureInfo.InvariantCulture,
+ "A user with the name '{0}' already exists.",
+ newName));
+ }
+
+ user.Username = newName;
+ await UpdateUserAsync(user).ConfigureAwait(false);
+ OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
+ }
+
+ /// <inheritdoc/>
+ public async Task UpdateUserAsync(User user)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ dbContext.Users.Update(user);
+ _users[user.Id] = user;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ internal async Task<User> CreateUserInternalAsync(string name, JellyfinDb dbContext)
+ {
+ // TODO: Remove after user item data is migrated.
+ var max = await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)
+ ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
+ : 0;
+
+ var user = new User(
+ name,
+ _defaultAuthenticationProvider.GetType().FullName!,
+ _defaultPasswordResetProvider.GetType().FullName!)
+ {
+ InternalId = max + 1
+ };
+
+ user.AddDefaultPermissions();
+ user.AddDefaultPreferences();
+
+ _users.Add(user.Id, user);
+
+ return user;
+ }
+
+ /// <inheritdoc/>
+ public async Task<User> CreateUserAsync(string name)
+ {
+ ThrowIfInvalidUsername(name);
+
+ if (Users.Any(u => u.Username.Equals(name, StringComparison.OrdinalIgnoreCase)))
+ {
+ throw new ArgumentException(string.Format(
+ CultureInfo.InvariantCulture,
+ "A user with the name '{0}' already exists.",
+ name));
+ }
+
+ await using var dbContext = _dbProvider.CreateContext();
+
+ var newUser = await CreateUserInternalAsync(name, dbContext).ConfigureAwait(false);
+
+ dbContext.Users.Add(newUser);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+
+ await _eventManager.PublishAsync(new UserCreatedEventArgs(newUser)).ConfigureAwait(false);
+
+ return newUser;
+ }
+
+ /// <inheritdoc/>
+ public async Task DeleteUserAsync(Guid userId)
+ {
+ if (!_users.TryGetValue(userId, out var user))
+ {
+ throw new ResourceNotFoundException(nameof(userId));
+ }
+
+ if (_users.Count == 1)
+ {
+ throw new InvalidOperationException(string.Format(
+ CultureInfo.InvariantCulture,
+ "The user '{0}' cannot be deleted because there must be at least one user in the system.",
+ user.Username));
+ }
+
+ if (user.HasPermission(PermissionKind.IsAdministrator)
+ && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
+ {
+ throw new ArgumentException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
+ user.Username),
+ nameof(userId));
+ }
+
+ await using var dbContext = _dbProvider.CreateContext();
+ dbContext.Users.Remove(user);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ _users.Remove(userId);
+
+ await _eventManager.PublishAsync(new UserDeletedEventArgs(user)).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc/>
+ public Task ResetPassword(User user)
+ {
+ return ChangePassword(user, string.Empty);
+ }
+
+ /// <inheritdoc/>
+ public Task ResetEasyPassword(User user)
+ {
+ return ChangeEasyPassword(user, string.Empty, null);
+ }
+
+ /// <inheritdoc/>
+ public async Task ChangePassword(User user, string newPassword)
+ {
+ if (user == null)
+ {
+ throw new ArgumentNullException(nameof(user));
+ }
+
+ await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
+ await UpdateUserAsync(user).ConfigureAwait(false);
+
+ await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc/>
+ public async Task ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
+ {
+ if (newPassword != null)
+ {
+ newPasswordSha1 = _cryptoProvider.CreatePasswordHash(newPassword).ToString();
+ }
+
+ if (string.IsNullOrWhiteSpace(newPasswordSha1))
+ {
+ throw new ArgumentNullException(nameof(newPasswordSha1));
+ }
+
+ user.EasyPassword = newPasswordSha1;
+ await UpdateUserAsync(user).ConfigureAwait(false);
+
+ _eventManager.Publish(new UserPasswordChangedEventArgs(user));
+ }
+
+ /// <inheritdoc/>
+ public UserDto GetUserDto(User user, string? remoteEndPoint = null)
+ {
+ var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
+ return new UserDto
+ {
+ Name = user.Username,
+ Id = user.Id,
+ ServerId = _appHost.SystemId,
+ HasPassword = hasPassword,
+ HasConfiguredPassword = hasPassword,
+ HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
+ EnableAutoLogin = user.EnableAutoLogin,
+ LastLoginDate = user.LastLoginDate,
+ LastActivityDate = user.LastActivityDate,
+ PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
+ Configuration = new UserConfiguration
+ {
+ SubtitleMode = user.SubtitleMode,
+ HidePlayedInLatest = user.HidePlayedInLatest,
+ EnableLocalPassword = user.EnableLocalPassword,
+ PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
+ DisplayCollectionsView = user.DisplayCollectionsView,
+ DisplayMissingEpisodes = user.DisplayMissingEpisodes,
+ AudioLanguagePreference = user.AudioLanguagePreference,
+ RememberAudioSelections = user.RememberAudioSelections,
+ EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
+ RememberSubtitleSelections = user.RememberSubtitleSelections,
+ SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
+ OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
+ GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
+ MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
+ LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
+ },
+ Policy = new UserPolicy
+ {
+ MaxParentalRating = user.MaxParentalAgeRating,
+ EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
+ RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
+ AuthenticationProviderId = user.AuthenticationProviderId,
+ PasswordResetProviderId = user.PasswordResetProviderId,
+ InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
+ LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
+ MaxActiveSessions = user.MaxActiveSessions,
+ IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
+ IsHidden = user.HasPermission(PermissionKind.IsHidden),
+ IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
+ EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
+ EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
+ EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
+ EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
+ EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
+ EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
+ EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
+ EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
+ EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
+ EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
+ EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
+ EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
+ EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
+ EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
+ EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
+ EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
+ ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
+ EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
+ AccessSchedules = user.AccessSchedules.ToArray(),
+ BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
+ EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
+ EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
+ EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
+ EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
+ SyncPlayAccess = user.SyncPlayAccess,
+ BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
+ BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
+ BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
+ }
+ };
+ }
+
+ /// <inheritdoc/>
+ public async Task<User?> AuthenticateUser(
+ string username,
+ string password,
+ string passwordSha1,
+ string remoteEndPoint,
+ bool isUserSession)
+ {
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
+ throw new ArgumentNullException(nameof(username));
+ }
+
+ var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
+ var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
+ .ConfigureAwait(false);
+ var authenticationProvider = authResult.authenticationProvider;
+ var success = authResult.success;
+
+ if (user == null)
+ {
+ string updatedUsername = authResult.username;
+
+ if (success
+ && authenticationProvider != null
+ && authenticationProvider is not DefaultAuthenticationProvider)
+ {
+ // Trust the username returned by the authentication provider
+ username = updatedUsername;
+
+ // Search the database for the user again
+ // the authentication provider might have created it
+ user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
+
+ if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null)
+ {
+ await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
+ }
+ }
+ }
+
+ if (success && user != null && authenticationProvider != null)
+ {
+ var providerId = authenticationProvider.GetType().FullName;
+
+ if (providerId != null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
+ {
+ user.AuthenticationProviderId = providerId;
+ await UpdateUserAsync(user).ConfigureAwait(false);
+ }
+ }
+
+ if (user == null)
+ {
+ _logger.LogInformation(
+ "Authentication request for {UserName} has been denied (IP: {IP}).",
+ username,
+ remoteEndPoint);
+ throw new AuthenticationException("Invalid username or password entered.");
+ }
+
+ if (user.HasPermission(PermissionKind.IsDisabled))
+ {
+ _logger.LogInformation(
+ "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
+ username,
+ remoteEndPoint);
+ throw new SecurityException(
+ $"The {user.Username} account is currently disabled. Please consult with your administrator.");
+ }
+
+ if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
+ !_networkManager.IsInLocalNetwork(remoteEndPoint))
+ {
+ _logger.LogInformation(
+ "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
+ username,
+ remoteEndPoint);
+ throw new SecurityException("Forbidden.");
+ }
+
+ if (!user.IsParentalScheduleAllowed())
+ {
+ _logger.LogInformation(
+ "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
+ username,
+ remoteEndPoint);
+ throw new SecurityException("User is not allowed access at this time.");
+ }
+
+ // Update LastActivityDate and LastLoginDate, then save
+ if (success)
+ {
+ if (isUserSession)
+ {
+ user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
+ }
+
+ user.InvalidLoginAttemptCount = 0;
+ await UpdateUserAsync(user).ConfigureAwait(false);
+ _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
+ }
+ else
+ {
+ await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
+ _logger.LogInformation(
+ "Authentication request for {UserName} has been denied (IP: {IP}).",
+ user.Username,
+ remoteEndPoint);
+ }
+
+ return success ? user : null;
+ }
+
+ /// <inheritdoc/>
+ public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
+ {
+ var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
+
+ if (user != null && isInNetwork)
+ {
+ var passwordResetProvider = GetPasswordResetProvider(user);
+ var result = await passwordResetProvider
+ .StartForgotPasswordProcess(user, isInNetwork)
+ .ConfigureAwait(false);
+
+ await UpdateUserAsync(user).ConfigureAwait(false);
+ return result;
+ }
+
+ return new ForgotPasswordResult
+ {
+ Action = ForgotPasswordAction.InNetworkRequired,
+ PinFile = string.Empty
+ };
+ }
+
+ /// <inheritdoc/>
+ public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
+ {
+ foreach (var provider in _passwordResetProviders)
+ {
+ var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
+
+ if (result.Success)
+ {
+ return result;
+ }
+ }
+
+ return new PinRedeemResult();
+ }
+
+ /// <inheritdoc />
+ public async Task InitializeAsync()
+ {
+ // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
+ if (_users.Any())
+ {
+ return;
+ }
+
+ var defaultName = Environment.UserName;
+ if (string.IsNullOrWhiteSpace(defaultName) || !IsValidUsername(defaultName))
+ {
+ defaultName = "MyJellyfinUser";
+ }
+
+ _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
+
+ await using var dbContext = _dbProvider.CreateContext();
+ var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
+ newUser.SetPermission(PermissionKind.IsAdministrator, true);
+ newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
+ newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
+
+ dbContext.Users.Add(newUser);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc/>
+ public NameIdPair[] GetAuthenticationProviders()
+ {
+ return _authenticationProviders
+ .Where(provider => provider.IsEnabled)
+ .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
+ .ThenBy(i => i.Name)
+ .Select(i => new NameIdPair
+ {
+ Name = i.Name,
+ Id = i.GetType().FullName
+ })
+ .ToArray();
+ }
+
+ /// <inheritdoc/>
+ public NameIdPair[] GetPasswordResetProviders()
+ {
+ return _passwordResetProviders
+ .Where(provider => provider.IsEnabled)
+ .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
+ .ThenBy(i => i.Name)
+ .Select(i => new NameIdPair
+ {
+ Name = i.Name,
+ Id = i.GetType().FullName
+ })
+ .ToArray();
+ }
+
+ /// <inheritdoc/>
+ public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var user = dbContext.Users
+ .Include(u => u.Permissions)
+ .Include(u => u.Preferences)
+ .Include(u => u.AccessSchedules)
+ .Include(u => u.ProfileImage)
+ .FirstOrDefault(u => u.Id == userId)
+ ?? throw new ArgumentException("No user exists with given Id!");
+
+ user.SubtitleMode = config.SubtitleMode;
+ user.HidePlayedInLatest = config.HidePlayedInLatest;
+ user.EnableLocalPassword = config.EnableLocalPassword;
+ user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
+ user.DisplayCollectionsView = config.DisplayCollectionsView;
+ user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
+ user.AudioLanguagePreference = config.AudioLanguagePreference;
+ user.RememberAudioSelections = config.RememberAudioSelections;
+ user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
+ user.RememberSubtitleSelections = config.RememberSubtitleSelections;
+ user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
+
+ 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.Update(user);
+ _users[user.Id] = user;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc/>
+ public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
+ {
+ await using var dbContext = _dbProvider.CreateContext();
+ var user = dbContext.Users
+ .Include(u => u.Permissions)
+ .Include(u => u.Preferences)
+ .Include(u => u.AccessSchedules)
+ .Include(u => u.ProfileImage)
+ .FirstOrDefault(u => u.Id == userId)
+ ?? throw new ArgumentException("No user exists with given Id!");
+
+ // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
+ int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
+ {
+ -1 => null,
+ 0 => 3,
+ _ => policy.LoginAttemptsBeforeLockout
+ };
+
+ user.MaxParentalAgeRating = policy.MaxParentalRating;
+ user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
+ user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
+ user.AuthenticationProviderId = policy.AuthenticationProviderId;
+ user.PasswordResetProviderId = policy.PasswordResetProviderId;
+ user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
+ user.LoginAttemptsBeforeLockout = maxLoginAttempts;
+ user.MaxActiveSessions = policy.MaxActiveSessions;
+ user.SyncPlayAccess = policy.SyncPlayAccess;
+ 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.AccessSchedules.Clear();
+ foreach (var policyAccessSchedule in policy.AccessSchedules)
+ {
+ user.AccessSchedules.Add(policyAccessSchedule);
+ }
+
+ // TODO: fix this at some point
+ user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
+ 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);
+
+ dbContext.Update(user);
+ _users[user.Id] = user;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ }
+
+ /// <inheritdoc/>
+ public async Task ClearProfileImageAsync(User user)
+ {
+ if (user.ProfileImage == null)
+ {
+ return;
+ }
+
+ await using var dbContext = _dbProvider.CreateContext();
+ dbContext.Remove(user.ProfileImage);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ user.ProfileImage = null;
+ _users[user.Id] = user;
+ }
+
+ internal static void ThrowIfInvalidUsername(string name)
+ {
+ if (!string.IsNullOrWhiteSpace(name) && IsValidUsername(name))
+ {
+ return;
+ }
+
+ throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
+ }
+
+ private static bool IsValidUsername(string name)
+ {
+ // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
+ // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
+ // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
+ return Regex.IsMatch(name, @"^[\w\ \-'._@]+$");
+ }
+
+ private IAuthenticationProvider GetAuthenticationProvider(User user)
+ {
+ return GetAuthenticationProviders(user)[0];
+ }
+
+ private IPasswordResetProvider GetPasswordResetProvider(User user)
+ {
+ return GetPasswordResetProviders(user)[0];
+ }
+
+ private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
+ {
+ var authenticationProviderId = user?.AuthenticationProviderId;
+
+ var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
+
+ if (!string.IsNullOrEmpty(authenticationProviderId))
+ {
+ providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
+ }
+
+ if (providers.Count == 0)
+ {
+ // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
+ _logger.LogWarning(
+ "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
+ user?.Username,
+ user?.AuthenticationProviderId);
+ providers = new List<IAuthenticationProvider>
+ {
+ _invalidAuthProvider
+ };
+ }
+
+ return providers;
+ }
+
+ private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
+ {
+ var passwordResetProviderId = user.PasswordResetProviderId;
+ var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
+
+ if (!string.IsNullOrEmpty(passwordResetProviderId))
+ {
+ providers = providers.Where(i =>
+ string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+ }
+
+ if (providers.Length == 0)
+ {
+ providers = new IPasswordResetProvider[]
+ {
+ _defaultPasswordResetProvider
+ };
+ }
+
+ return providers;
+ }
+
+ private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
+ string username,
+ string password,
+ User? user,
+ string remoteEndPoint)
+ {
+ bool success = false;
+ IAuthenticationProvider? authenticationProvider = null;
+
+ foreach (var provider in GetAuthenticationProviders(user))
+ {
+ var providerAuthResult =
+ await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
+ var updatedUsername = providerAuthResult.username;
+ success = providerAuthResult.success;
+
+ if (success)
+ {
+ authenticationProvider = provider;
+ username = updatedUsername;
+ break;
+ }
+ }
+
+ if (!success
+ && _networkManager.IsInLocalNetwork(remoteEndPoint)
+ && user?.EnableLocalPassword == true
+ && !string.IsNullOrEmpty(user.EasyPassword))
+ {
+ // Check easy password
+ var passwordHash = PasswordHash.Parse(user.EasyPassword);
+ var hash = _cryptoProvider.ComputeHash(
+ passwordHash.Id,
+ Encoding.UTF8.GetBytes(password),
+ passwordHash.Salt.ToArray());
+ success = passwordHash.Hash.SequenceEqual(hash);
+ }
+
+ return (authenticationProvider, username, success);
+ }
+
+ private async Task<(string username, bool success)> AuthenticateWithProvider(
+ IAuthenticationProvider provider,
+ string username,
+ string password,
+ User? resolvedUser)
+ {
+ try
+ {
+ var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
+ ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
+ : await provider.Authenticate(username, password).ConfigureAwait(false);
+
+ if (authenticationResult.Username != username)
+ {
+ _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
+ username = authenticationResult.Username;
+ }
+
+ return (username, true);
+ }
+ catch (AuthenticationException ex)
+ {
+ _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
+
+ return (username, false);
+ }
+ }
+
+ private async Task IncrementInvalidLoginAttemptCount(User user)
+ {
+ user.InvalidLoginAttemptCount++;
+ int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
+ if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
+ {
+ user.SetPermission(PermissionKind.IsDisabled, true);
+ await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
+ _logger.LogWarning(
+ "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
+ user.Username,
+ user.InvalidLoginAttemptCount);
+ }
+
+ await UpdateUserAsync(user).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs
new file mode 100644
index 000000000..a9a18c823
--- /dev/null
+++ b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs
@@ -0,0 +1,21 @@
+using System;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.ValueConverters
+{
+ /// <summary>
+ /// ValueConverter to specify kind.
+ /// </summary>
+ public class DateTimeKindValueConverter : ValueConverter<DateTime, DateTime>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DateTimeKindValueConverter"/> class.
+ /// </summary>
+ /// <param name="kind">The kind to specify.</param>
+ /// <param name="mappingHints">The mapping hints.</param>
+ public DateTimeKindValueConverter(DateTimeKind kind, ConverterMappingHints? mappingHints = null)
+ : base(v => v.ToUniversalTime(), v => DateTime.SpecifyKind(v, kind), mappingHints)
+ {
+ }
+ }
+}
diff --git a/Jellyfin.Server/Configuration/CorsPolicyProvider.cs b/Jellyfin.Server/Configuration/CorsPolicyProvider.cs
new file mode 100644
index 000000000..b061be33b
--- /dev/null
+++ b/Jellyfin.Server/Configuration/CorsPolicyProvider.cs
@@ -0,0 +1,49 @@
+using System;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.AspNetCore.Cors.Infrastructure;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Server.Configuration
+{
+ /// <summary>
+ /// Cors policy provider.
+ /// </summary>
+ public class CorsPolicyProvider : ICorsPolicyProvider
+ {
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CorsPolicyProvider"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public CorsPolicyProvider(IServerConfigurationManager serverConfigurationManager)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <inheritdoc />
+ public Task<CorsPolicy?> GetPolicyAsync(HttpContext context, string? policyName)
+ {
+ var corsHosts = _serverConfigurationManager.Configuration.CorsHosts;
+ var builder = new CorsPolicyBuilder()
+ .AllowAnyMethod()
+ .AllowAnyHeader();
+
+ // No hosts configured or only default configured.
+ if (corsHosts.Length == 0
+ || (corsHosts.Length == 1
+ && string.Equals(corsHosts[0], CorsConstants.AnyOrigin, StringComparison.Ordinal)))
+ {
+ builder.AllowAnyOrigin();
+ }
+ else
+ {
+ builder.WithOrigins(corsHosts)
+ .AllowCredentials();
+ }
+
+ return Task.FromResult<CorsPolicy?>(builder.Build());
+ }
+ }
+}
diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs
index 84d78d3fb..21bd9ba01 100644
--- a/Jellyfin.Server/CoreAppHost.cs
+++ b/Jellyfin.Server/CoreAppHost.cs
@@ -1,61 +1,124 @@
+using System;
using System.Collections.Generic;
+using System.IO;
using System.Reflection;
+using Emby.Drawing;
using Emby.Server.Implementations;
-using Emby.Server.Implementations.HttpServer;
-using Jellyfin.Server.SocketSharp;
+using Emby.Server.Implementations.Session;
+using Jellyfin.Api.WebSocketListeners;
+using Jellyfin.Drawing.Skia;
+using Jellyfin.Server.Implementations;
+using Jellyfin.Server.Implementations.Activity;
+using Jellyfin.Server.Implementations.Devices;
+using Jellyfin.Server.Implementations.Events;
+using Jellyfin.Server.Implementations.Security;
+using Jellyfin.Server.Implementations.Users;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.BaseItemManager;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Controller.Events;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Security;
+using MediaBrowser.Model.Activity;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Server
{
+ /// <summary>
+ /// Implementation of the abstract <see cref="ApplicationHost" /> class.
+ /// </summary>
public class CoreAppHost : ApplicationHost
{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CoreAppHost" /> class.
+ /// </summary>
+ /// <param name="applicationPaths">The <see cref="ServerApplicationPaths" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="loggerFactory">The <see cref="ILoggerFactory" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="options">The <see cref="StartupOptions" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="startupConfig">The <see cref="IConfiguration" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="fileSystem">The <see cref="IFileSystem" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="collection">The <see cref="IServiceCollection"/> to be used by the <see cref="CoreAppHost"/>.</param>
public CoreAppHost(
- ServerApplicationPaths applicationPaths,
+ IServerApplicationPaths applicationPaths,
ILoggerFactory loggerFactory,
- StartupOptions options,
+ IStartupOptions options,
+ IConfiguration startupConfig,
IFileSystem fileSystem,
- IEnvironmentInfo environmentInfo,
- MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder,
- MediaBrowser.Common.Net.INetworkManager networkManager,
- IConfiguration configuration)
+ IServiceCollection collection)
: base(
applicationPaths,
loggerFactory,
options,
+ startupConfig,
fileSystem,
- environmentInfo,
- imageEncoder,
- networkManager,
- configuration)
+ collection)
{
}
- public override bool CanSelfRestart => StartupOptions.RestartPath != null;
+ /// <inheritdoc/>
+ protected override void RegisterServices()
+ {
+ // Register an image encoder
+ bool useSkiaEncoder = SkiaEncoder.IsNativeLibAvailable();
+ Type imageEncoderType = useSkiaEncoder
+ ? typeof(SkiaEncoder)
+ : typeof(NullImageEncoder);
+ ServiceCollection.AddSingleton(typeof(IImageEncoder), imageEncoderType);
+
+ // Log a warning if the Skia encoder could not be used
+ if (!useSkiaEncoder)
+ {
+ Logger.LogWarning($"Skia not available. Will fallback to {nameof(NullImageEncoder)}.");
+ }
+
+ ServiceCollection.AddDbContextPool<JellyfinDb>(
+ options => options
+ .UseLoggerFactory(LoggerFactory)
+ .UseSqlite($"Filename={Path.Combine(ApplicationPaths.DataPath, "jellyfin.db")}"));
+
+ ServiceCollection.AddEventServices();
+ ServiceCollection.AddSingleton<IBaseItemManager, BaseItemManager>();
+ ServiceCollection.AddSingleton<IEventManager, EventManager>();
+ ServiceCollection.AddSingleton<JellyfinDbProvider>();
+
+ ServiceCollection.AddSingleton<IActivityManager, ActivityManager>();
+ ServiceCollection.AddSingleton<IUserManager, UserManager>();
+ ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>();
+ ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
+
+ // TODO search the assemblies instead of adding them manually?
+ ServiceCollection.AddSingleton<IWebSocketListener, SessionWebSocketListener>();
+ ServiceCollection.AddSingleton<IWebSocketListener, ActivityLogWebSocketListener>();
+ ServiceCollection.AddSingleton<IWebSocketListener, ScheduledTasksWebSocketListener>();
+ ServiceCollection.AddSingleton<IWebSocketListener, SessionInfoWebSocketListener>();
- protected override bool SupportsDualModeSockets => true;
+ ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
+ ServiceCollection.AddScoped<IAuthenticationManager, AuthenticationManager>();
+
+ base.RegisterServices();
+ }
+
+ /// <inheritdoc />
protected override void RestartInternal() => Program.Restart();
+ /// <inheritdoc />
protected override IEnumerable<Assembly> GetAssembliesWithPartsInternal()
{
+ // Jellyfin.Server
yield return typeof(CoreAppHost).Assembly;
+
+ // Jellyfin.Server.Implementations
+ yield return typeof(JellyfinDb).Assembly;
}
+ /// <inheritdoc />
protected override void ShutdownInternal() => Program.Shutdown();
-
- protected override IHttpListener CreateHttpListener()
- => new WebSocketSharpListener(
- Logger,
- Certificate,
- StreamHelper,
- NetworkManager,
- SocketFactory,
- CryptographyProvider,
- SupportsDualModeSockets,
- FileSystemManager,
- EnvironmentInfo);
}
}
diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
new file mode 100644
index 000000000..e29167747
--- /dev/null
+++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
@@ -0,0 +1,144 @@
+using System.Collections.Generic;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Server.Middleware;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.OpenApi.Models;
+
+namespace Jellyfin.Server.Extensions
+{
+ /// <summary>
+ /// Extensions for adding API specific functionality to the application pipeline.
+ /// </summary>
+ public static class ApiApplicationBuilderExtensions
+ {
+ /// <summary>
+ /// Adds swagger and swagger UI to the application pipeline.
+ /// </summary>
+ /// <param name="applicationBuilder">The application builder.</param>
+ /// <param name="serverConfigurationManager">The server configuration.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseJellyfinApiSwagger(
+ this IApplicationBuilder applicationBuilder,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
+ // specifying the Swagger JSON endpoint.
+
+ var baseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl.Trim('/');
+ var apiDocBaseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl;
+ if (!string.IsNullOrEmpty(baseUrl))
+ {
+ baseUrl += '/';
+ }
+
+ return applicationBuilder
+ .UseSwagger(c =>
+ {
+ // Custom path requires {documentName}, SwaggerDoc documentName is 'api-docs'
+ c.RouteTemplate = "{documentName}/openapi.json";
+ c.PreSerializeFilters.Add((swagger, httpReq) =>
+ {
+ swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{apiDocBaseUrl}" } };
+ });
+ })
+ .UseSwaggerUI(c =>
+ {
+ c.DocumentTitle = "Jellyfin API";
+ c.SwaggerEndpoint($"/{baseUrl}api-docs/openapi.json", "Jellyfin API");
+ c.InjectStylesheet($"/{baseUrl}api-docs/swagger/custom.css");
+ c.RoutePrefix = "api-docs/swagger";
+ })
+ .UseReDoc(c =>
+ {
+ c.DocumentTitle = "Jellyfin API";
+ c.SpecUrl($"/{baseUrl}api-docs/openapi.json");
+ c.InjectStylesheet($"/{baseUrl}api-docs/redoc/custom.css");
+ c.RoutePrefix = "api-docs/redoc";
+ });
+ }
+
+ /// <summary>
+ /// Adds IP based access validation to the application pipeline.
+ /// </summary>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseIpBasedAccessValidation(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<IpBasedAccessValidationMiddleware>();
+ }
+
+ /// <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>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseQueryStringDecoding(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<QueryStringDecodingMiddleware>();
+ }
+
+ /// <summary>
+ /// Adds base url redirection to the application pipeline.
+ /// </summary>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseBaseUrlRedirection(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<BaseUrlRedirectionMiddleware>();
+ }
+
+ /// <summary>
+ /// Adds a custom message during server startup to the application pipeline.
+ /// </summary>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseServerStartupMessage(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<ServerStartupMessageMiddleware>();
+ }
+
+ /// <summary>
+ /// Adds a WebSocket request handler to the application pipeline.
+ /// </summary>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseWebSocketHandler(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<WebSocketHandlerMiddleware>();
+ }
+
+ /// <summary>
+ /// Adds robots.txt redirection to the application pipeline.
+ /// </summary>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UseRobotsRedirection(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<RobotsRedirectionMiddleware>();
+ }
+
+ /// <summary>
+ /// Adds /emby and /mediabrowser route trimming to the application pipeline.
+ /// </summary>
+ /// <remarks>
+ /// This must be injected before any path related middleware.
+ /// </remarks>
+ /// <param name="appBuilder">The application builder.</param>
+ /// <returns>The updated application builder.</returns>
+ public static IApplicationBuilder UsePathTrim(this IApplicationBuilder appBuilder)
+ {
+ return appBuilder.UseMiddleware<LegacyEmbyRouteRewriteMiddleware>();
+ }
+ }
+}
diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
new file mode 100644
index 000000000..e853609d6
--- /dev/null
+++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
@@ -0,0 +1,421 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Reflection;
+using Emby.Server.Implementations;
+using Jellyfin.Api.Auth;
+using Jellyfin.Api.Auth.AnonymousLanAccessPolicy;
+using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
+using Jellyfin.Api.Auth.DownloadPolicy;
+using Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy;
+using Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy;
+using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
+using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
+using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
+using Jellyfin.Api.Auth.LocalAccessPolicy;
+using Jellyfin.Api.Auth.RequiresElevationPolicy;
+using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Controllers;
+using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Server.Configuration;
+using Jellyfin.Server.Filters;
+using Jellyfin.Server.Formatters;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Model.Entities;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Cors.Infrastructure;
+using Microsoft.AspNetCore.HttpOverrides;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.OpenApi.Any;
+using Microsoft.OpenApi.Interfaces;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
+
+namespace Jellyfin.Server.Extensions
+{
+ /// <summary>
+ /// API specific extensions for the service collection.
+ /// </summary>
+ public static class ApiServiceCollectionExtensions
+ {
+ /// <summary>
+ /// Adds jellyfin API authorization policies to the DI container.
+ /// </summary>
+ /// <param name="serviceCollection">The service collection.</param>
+ /// <returns>The updated service collection.</returns>
+ public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, AnonymousLanAccessHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
+ serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
+ return serviceCollection.AddAuthorizationCore(options =>
+ {
+ options.AddPolicy(
+ Policies.DefaultAuthorization,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new DefaultAuthorizationRequirement());
+ });
+ options.AddPolicy(
+ Policies.Download,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new DownloadRequirement());
+ });
+ options.AddPolicy(
+ Policies.FirstTimeSetupOrDefault,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
+ });
+ options.AddPolicy(
+ Policies.FirstTimeSetupOrElevated,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
+ });
+ options.AddPolicy(
+ Policies.IgnoreParentalControl,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new IgnoreParentalControlRequirement());
+ });
+ options.AddPolicy(
+ Policies.FirstTimeSetupOrIgnoreParentalControl,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
+ });
+ options.AddPolicy(
+ Policies.LocalAccessOnly,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new LocalAccessRequirement());
+ });
+ options.AddPolicy(
+ Policies.LocalAccessOrRequiresElevation,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
+ });
+ options.AddPolicy(
+ Policies.RequiresElevation,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new RequiresElevationRequirement());
+ });
+ options.AddPolicy(
+ Policies.SyncPlayHasAccess,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
+ });
+ options.AddPolicy(
+ Policies.SyncPlayCreateGroup,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
+ });
+ options.AddPolicy(
+ Policies.SyncPlayJoinGroup,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
+ });
+ options.AddPolicy(
+ Policies.SyncPlayIsInGroup,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
+ });
+ options.AddPolicy(
+ Policies.AnonymousLanAccessPolicy,
+ policy =>
+ {
+ policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+ policy.AddRequirements(new AnonymousLanAccessRequirement());
+ });
+ });
+ }
+
+ /// <summary>
+ /// Adds custom legacy authentication to the service collection.
+ /// </summary>
+ /// <param name="serviceCollection">The service collection.</param>
+ /// <returns>The updated service collection.</returns>
+ public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
+ {
+ return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
+ .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
+ }
+
+ /// <summary>
+ /// Extension method for adding the jellyfin API to the service collection.
+ /// </summary>
+ /// <param name="serviceCollection">The service collection.</param>
+ /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
+ /// <param name="config">The <see cref="NetworkConfiguration"/>.</param>
+ /// <returns>The MVC builder.</returns>
+ public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config)
+ {
+ IMvcBuilder mvcBuilder = serviceCollection
+ .AddCors()
+ .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
+ .Configure<ForwardedHeadersOptions>(options =>
+ {
+ // 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.KnownNetworks.Clear();
+ options.KnownProxies.Clear();
+ }
+ else
+ {
+ AddProxyAddresses(config, config.KnownProxies, options);
+ }
+
+ // Only set forward limit if we have some known proxies or some known networks.
+ if (options.KnownProxies.Count != 0 || options.KnownNetworks.Count != 0)
+ {
+ options.ForwardLimit = null;
+ }
+ })
+ .AddMvc(opts =>
+ {
+ // Allow requester to change between camelCase and PascalCase
+ opts.RespectBrowserAcceptHeader = true;
+
+ opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
+ opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
+
+ opts.OutputFormatters.Add(new CssOutputFormatter());
+ opts.OutputFormatters.Add(new XmlOutputFormatter());
+
+ opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
+ })
+
+ // Clear app parts to avoid other assemblies being picked up
+ .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
+ .AddApplicationPart(typeof(StartupController).Assembly)
+ .AddJsonOptions(options =>
+ {
+ // Update all properties that are set in JsonDefaults
+ var jsonOptions = JsonDefaults.PascalCaseOptions;
+
+ // From JsonDefaults
+ options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
+ options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
+ options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
+ options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
+
+ options.JsonSerializerOptions.Converters.Clear();
+ foreach (var converter in jsonOptions.Converters)
+ {
+ options.JsonSerializerOptions.Converters.Add(converter);
+ }
+
+ // From JsonDefaults.PascalCase
+ options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
+ });
+
+ foreach (Assembly pluginAssembly in pluginAssemblies)
+ {
+ mvcBuilder.AddApplicationPart(pluginAssembly);
+ }
+
+ return mvcBuilder.AddControllersAsServices();
+ }
+
+ /// <summary>
+ /// Adds Swagger to the service collection.
+ /// </summary>
+ /// <param name="serviceCollection">The service collection.</param>
+ /// <returns>The updated service collection.</returns>
+ public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
+ {
+ return serviceCollection.AddSwaggerGen(c =>
+ {
+ var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(3) ?? "0.0.1";
+ c.SwaggerDoc("api-docs", new OpenApiInfo
+ {
+ Title = "Jellyfin API",
+ Version = version,
+ Extensions = new Dictionary<string, IOpenApiExtension>
+ {
+ {
+ "x-jellyfin-version",
+ new OpenApiString(version)
+ }
+ }
+ });
+
+ c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
+ {
+ Type = SecuritySchemeType.ApiKey,
+ In = ParameterLocation.Header,
+ Name = "Authorization",
+ Description = "API key header parameter"
+ });
+
+ // Add all xml doc files to swagger generator.
+ var xmlFiles = Directory.GetFiles(
+ AppContext.BaseDirectory,
+ "*.xml",
+ SearchOption.TopDirectoryOnly);
+
+ foreach (var xmlFile in xmlFiles)
+ {
+ c.IncludeXmlComments(xmlFile);
+ }
+
+ // Order actions by route path, then by http method.
+ c.OrderActionsBy(description =>
+ $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
+
+ // Use method name as operationId
+ c.CustomOperationIds(
+ description =>
+ {
+ description.TryGetMethodInfo(out MethodInfo methodInfo);
+ // Attribute name, method name, none.
+ return description?.ActionDescriptor.AttributeRouteInfo?.Name
+ ?? methodInfo?.Name
+ ?? null;
+ });
+
+ // Allow parameters to properly be nullable.
+ c.UseAllOfToExtendReferenceSchemas();
+ c.SupportNonNullableReferenceTypes();
+
+ // TODO - remove when all types are supported in System.Text.Json
+ c.AddSwaggerTypeMappings();
+
+ c.OperationFilter<SecurityRequirementsOperationFilter>();
+ c.OperationFilter<FileResponseFilter>();
+ c.OperationFilter<FileRequestFilter>();
+ c.OperationFilter<ParameterObsoleteFilter>();
+ c.DocumentFilter<AdditionalModelFilter>();
+ });
+ }
+
+ /// <summary>
+ /// Sets up the proxy configuration based on the addresses in <paramref name="allowedProxies"/>.
+ /// </summary>
+ /// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
+ /// <param name="allowedProxies">The string array to parse.</param>
+ /// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param>
+ internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options)
+ {
+ for (var i = 0; i < allowedProxies.Length; i++)
+ {
+ if (IPNetAddress.TryParse(allowedProxies[i], out var addr))
+ {
+ AddIpAddress(config, options, addr.Address, addr.PrefixLength);
+ }
+ else if (IPHost.TryParse(allowedProxies[i], out var host))
+ {
+ foreach (var address in host.GetAddresses())
+ {
+ AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
+ }
+ }
+ }
+ }
+
+ private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
+ {
+ if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
+ {
+ return;
+ }
+
+ // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address.
+ if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6)
+ {
+ // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format.
+ // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 .
+ addr = addr.MapToIPv6();
+ }
+
+ if (prefixLength == 32)
+ {
+ options.KnownProxies.Add(addr);
+ }
+ else
+ {
+ options.KnownNetworks.Add(new IPNetwork(addr, prefixLength));
+ }
+ }
+
+ private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
+ {
+ /*
+ * TODO remove when System.Text.Json properly supports non-string keys.
+ * Used in BaseItemDto.ImageBlurHashes
+ */
+ options.MapType<Dictionary<ImageType, string>>(() =>
+ new OpenApiSchema
+ {
+ Type = "object",
+ AdditionalProperties = new OpenApiSchema
+ {
+ Type = "string"
+ }
+ });
+
+ /*
+ * Support BlurHash dictionary
+ */
+ options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
+ new OpenApiSchema
+ {
+ Type = "object",
+ Properties = typeof(ImageType).GetEnumNames().ToDictionary(
+ name => name,
+ _ => new OpenApiSchema
+ {
+ Type = "object",
+ AdditionalProperties = new OpenApiSchema
+ {
+ Type = "string"
+ }
+ })
+ });
+ }
+ }
+}
diff --git a/Jellyfin.Server/Filters/AdditionalModelFilter.cs b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
new file mode 100644
index 000000000..87a59e0b4
--- /dev/null
+++ b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
@@ -0,0 +1,34 @@
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.ApiClient;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Session;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ /// <summary>
+ /// Add models not directly used by the API, but used for discovery and websockets.
+ /// </summary>
+ public class AdditionalModelFilter : IDocumentFilter
+ {
+ /// <inheritdoc />
+ public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
+ {
+ context.SchemaGenerator.GenerateSchema(typeof(LibraryUpdateInfo), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(IPlugin), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(PlayRequest), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(PlaystateRequest), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(TimerEventInfo), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(SendCommand), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(GeneralCommandType), context.SchemaRepository);
+
+ context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate<object>), context.SchemaRepository);
+
+ context.SchemaGenerator.GenerateSchema(typeof(SessionMessageType), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(ServerDiscoveryInfo), context.SchemaRepository);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Filters/FileRequestFilter.cs b/Jellyfin.Server/Filters/FileRequestFilter.cs
new file mode 100644
index 000000000..69e10994f
--- /dev/null
+++ b/Jellyfin.Server/Filters/FileRequestFilter.cs
@@ -0,0 +1,43 @@
+using System.Collections.Generic;
+using Jellyfin.Api.Attributes;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ /// <inheritdoc />
+ public class FileRequestFilter : IOperationFilter
+ {
+ /// <inheritdoc />
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ foreach (var attribute in context.ApiDescription.ActionDescriptor.EndpointMetadata)
+ {
+ if (attribute is AcceptsFileAttribute acceptsFileAttribute)
+ {
+ operation.RequestBody = GetRequestBody(acceptsFileAttribute.GetContentTypes());
+ break;
+ }
+ }
+ }
+
+ private static OpenApiRequestBody GetRequestBody(IEnumerable<string> contentTypes)
+ {
+ var body = new OpenApiRequestBody();
+ var mediaType = new OpenApiMediaType
+ {
+ Schema = new OpenApiSchema
+ {
+ Type = "string",
+ Format = "binary"
+ }
+ };
+ foreach (var contentType in contentTypes)
+ {
+ body.Content.Add(contentType, mediaType);
+ }
+
+ return body;
+ }
+ }
+}
diff --git a/Jellyfin.Server/Filters/FileResponseFilter.cs b/Jellyfin.Server/Filters/FileResponseFilter.cs
new file mode 100644
index 000000000..eae9a8004
--- /dev/null
+++ b/Jellyfin.Server/Filters/FileResponseFilter.cs
@@ -0,0 +1,53 @@
+using System;
+using System.Linq;
+using Jellyfin.Api.Attributes;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ /// <inheritdoc />
+ public class FileResponseFilter : IOperationFilter
+ {
+ private const string SuccessCode = "200";
+ private static readonly OpenApiMediaType _openApiMediaType = new OpenApiMediaType
+ {
+ Schema = new OpenApiSchema
+ {
+ Type = "string",
+ Format = "binary"
+ }
+ };
+
+ /// <inheritdoc />
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ foreach (var attribute in context.ApiDescription.ActionDescriptor.EndpointMetadata)
+ {
+ if (attribute is ProducesFileAttribute producesFileAttribute)
+ {
+ // Get operation response values.
+ var response = operation.Responses
+ .FirstOrDefault(o => o.Key.Equals(SuccessCode, StringComparison.Ordinal));
+
+ // Operation doesn't have a response.
+ if (response.Value == null)
+ {
+ continue;
+ }
+
+ // Clear existing responses.
+ response.Value.Content.Clear();
+
+ // Add all content-types as file.
+ foreach (var contentType in producesFileAttribute.GetContentTypes())
+ {
+ response.Value.Content.Add(contentType, _openApiMediaType);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs
new file mode 100644
index 000000000..b9ce221f5
--- /dev/null
+++ b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Linq;
+using Jellyfin.Api.Attributes;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ /// <summary>
+ /// Mark parameter as deprecated if it has the <see cref="ParameterObsoleteAttribute"/>.
+ /// </summary>
+ public class ParameterObsoleteFilter : IOperationFilter
+ {
+ /// <inheritdoc />
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ foreach (var parameterDescription in context.ApiDescription.ParameterDescriptions)
+ {
+ if (parameterDescription
+ .CustomAttributes()
+ .OfType<ParameterObsoleteAttribute>()
+ .Any())
+ {
+ foreach (var parameter in operation.Parameters)
+ {
+ if (parameter.Name.Equals(parameterDescription.Name, StringComparison.Ordinal))
+ {
+ parameter.Deprecated = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs b/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs
new file mode 100644
index 000000000..802662ce2
--- /dev/null
+++ b/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Jellyfin.Api.Constants;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ /// <summary>
+ /// Security requirement operation filter.
+ /// </summary>
+ public class SecurityRequirementsOperationFilter : IOperationFilter
+ {
+ /// <inheritdoc />
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ var requiredScopes = new List<string>();
+
+ // Add all method scopes.
+ foreach (var attribute in context.MethodInfo.GetCustomAttributes(true))
+ {
+ if (attribute is AuthorizeAttribute authorizeAttribute
+ && authorizeAttribute.Policy != null
+ && !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal))
+ {
+ requiredScopes.Add(authorizeAttribute.Policy);
+ }
+ }
+
+ // Add controller scopes if any.
+ var controllerAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true);
+ if (controllerAttributes != null)
+ {
+ foreach (var attribute in controllerAttributes)
+ {
+ if (attribute is AuthorizeAttribute authorizeAttribute
+ && authorizeAttribute.Policy != null
+ && !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal))
+ {
+ requiredScopes.Add(authorizeAttribute.Policy);
+ }
+ }
+ }
+
+ if (requiredScopes.Count != 0)
+ {
+ if (!operation.Responses.ContainsKey("401"))
+ {
+ operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
+ }
+
+ if (!operation.Responses.ContainsKey("403"))
+ {
+ operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
+ }
+
+ var scheme = new OpenApiSecurityScheme
+ {
+ Reference = new OpenApiReference
+ {
+ Type = ReferenceType.SecurityScheme,
+ Id = AuthenticationSchemes.CustomAuthentication
+ }
+ };
+
+ operation.Security = new List<OpenApiSecurityRequirement>
+ {
+ new OpenApiSecurityRequirement
+ {
+ [scheme] = requiredScopes
+ }
+ };
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs
new file mode 100644
index 000000000..ea8c5ecdb
--- /dev/null
+++ b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs
@@ -0,0 +1,21 @@
+using Jellyfin.Extensions.Json;
+using Microsoft.AspNetCore.Mvc.Formatters;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Server.Formatters
+{
+ /// <summary>
+ /// Camel Case Json Profile Formatter.
+ /// </summary>
+ public class CamelCaseJsonProfileFormatter : SystemTextJsonOutputFormatter
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CamelCaseJsonProfileFormatter"/> class.
+ /// </summary>
+ public CamelCaseJsonProfileFormatter() : base(JsonDefaults.CamelCaseOptions)
+ {
+ SupportedMediaTypes.Clear();
+ SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(JsonDefaults.CamelCaseMediaType));
+ }
+ }
+}
diff --git a/Jellyfin.Server/Formatters/CssOutputFormatter.cs b/Jellyfin.Server/Formatters/CssOutputFormatter.cs
new file mode 100644
index 000000000..cfc9d1ad3
--- /dev/null
+++ b/Jellyfin.Server/Formatters/CssOutputFormatter.cs
@@ -0,0 +1,36 @@
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.Formatters;
+
+namespace Jellyfin.Server.Formatters
+{
+ /// <summary>
+ /// Css output formatter.
+ /// </summary>
+ public class CssOutputFormatter : TextOutputFormatter
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CssOutputFormatter"/> class.
+ /// </summary>
+ public CssOutputFormatter()
+ {
+ SupportedMediaTypes.Add("text/css");
+
+ SupportedEncodings.Add(Encoding.UTF8);
+ SupportedEncodings.Add(Encoding.Unicode);
+ }
+
+ /// <summary>
+ /// Write context object to stream.
+ /// </summary>
+ /// <param name="context">Writer context.</param>
+ /// <param name="selectedEncoding">Unused. Writer encoding.</param>
+ /// <returns>Write stream task.</returns>
+ public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
+ {
+ var stringResponse = context.Object?.ToString();
+ return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs
new file mode 100644
index 000000000..03ca7dda7
--- /dev/null
+++ b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs
@@ -0,0 +1,24 @@
+using System.Net.Mime;
+using Jellyfin.Extensions.Json;
+using Microsoft.AspNetCore.Mvc.Formatters;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Server.Formatters
+{
+ /// <summary>
+ /// Pascal Case Json Profile Formatter.
+ /// </summary>
+ public class PascalCaseJsonProfileFormatter : SystemTextJsonOutputFormatter
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PascalCaseJsonProfileFormatter"/> class.
+ /// </summary>
+ public PascalCaseJsonProfileFormatter() : base(JsonDefaults.PascalCaseOptions)
+ {
+ SupportedMediaTypes.Clear();
+ // Add application/json for default formatter
+ SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json));
+ SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(JsonDefaults.PascalCaseMediaType));
+ }
+ }
+}
diff --git a/Jellyfin.Server/Formatters/XmlOutputFormatter.cs b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs
new file mode 100644
index 000000000..be0baea2d
--- /dev/null
+++ b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs
@@ -0,0 +1,33 @@
+using System.Net.Mime;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.Formatters;
+
+namespace Jellyfin.Server.Formatters
+{
+ /// <summary>
+ /// Xml output formatter.
+ /// </summary>
+ public class XmlOutputFormatter : TextOutputFormatter
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="XmlOutputFormatter"/> class.
+ /// </summary>
+ public XmlOutputFormatter()
+ {
+ SupportedMediaTypes.Clear();
+ SupportedMediaTypes.Add(MediaTypeNames.Text.Xml);
+
+ SupportedEncodings.Add(Encoding.UTF8);
+ SupportedEncodings.Add(Encoding.Unicode);
+ }
+
+ /// <inheritdoc />
+ public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
+ {
+ var stringResponse = context.Object?.ToString();
+ return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Infrastructure/SymlinkFollowingPhysicalFileResultExecutor.cs b/Jellyfin.Server/Infrastructure/SymlinkFollowingPhysicalFileResultExecutor.cs
new file mode 100644
index 000000000..73a619b8d
--- /dev/null
+++ b/Jellyfin.Server/Infrastructure/SymlinkFollowingPhysicalFileResultExecutor.cs
@@ -0,0 +1,144 @@
+// The MIT License (MIT)
+//
+// Copyright (c) .NET Foundation and Contributors
+//
+// All rights reserved.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Extensions;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
+using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
+
+namespace Jellyfin.Server.Infrastructure
+{
+ /// <inheritdoc />
+ public class SymlinkFollowingPhysicalFileResultExecutor : PhysicalFileResultExecutor
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SymlinkFollowingPhysicalFileResultExecutor"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">An instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public SymlinkFollowingPhysicalFileResultExecutor(ILoggerFactory loggerFactory) : base(loggerFactory)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override FileMetadata GetFileInfo(string path)
+ {
+ var fileInfo = new FileInfo(path);
+ var length = fileInfo.Length;
+ // This may or may not be fixed in .NET 6, but looks like it will not https://github.com/dotnet/aspnetcore/issues/34371
+ if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
+ {
+ using var fileHandle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ length = RandomAccess.GetLength(fileHandle);
+ }
+
+ return new FileMetadata
+ {
+ Exists = fileInfo.Exists,
+ Length = length,
+ LastModified = fileInfo.LastWriteTimeUtc
+ };
+ }
+
+ /// <inheritdoc />
+ protected override Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength)
+ {
+ if (context == null)
+ {
+ throw new ArgumentNullException(nameof(context));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ if (range != null && rangeLength == 0)
+ {
+ return Task.CompletedTask;
+ }
+
+ // It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code
+ if (!IsSymLink(result.FileName))
+ {
+ return base.WriteFileAsync(context, result, range, rangeLength);
+ }
+
+ var response = context.HttpContext.Response;
+
+ if (range != null)
+ {
+ return SendFileAsync(
+ result.FileName,
+ response,
+ offset: range.From ?? 0L,
+ count: rangeLength);
+ }
+
+ return SendFileAsync(
+ result.FileName,
+ response,
+ offset: 0,
+ count: null);
+ }
+
+ private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count)
+ {
+ var fileInfo = GetFileInfo(filePath);
+ if (offset < 0 || offset > fileInfo.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
+ }
+
+ if (count.HasValue
+ && (count.Value < 0 || count.Value > fileInfo.Length - offset))
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
+ }
+
+ // Copied from SendFileFallback.SendFileAsync
+ const int BufferSize = 1024 * 16;
+
+ await using var fileStream = new FileStream(
+ filePath,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.ReadWrite,
+ bufferSize: BufferSize,
+ options: FileOptions.Asynchronous | FileOptions.SequentialScan);
+
+ fileStream.Seek(offset, SeekOrigin.Begin);
+ await StreamCopyOperation
+ .CopyToAsync(fileStream, response.Body, count, BufferSize, CancellationToken.None)
+ .ConfigureAwait(true);
+ }
+
+ private static bool IsSymLink(string path) => (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
+ }
+}
diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj
index bd670df52..49d979e11 100644
--- a/Jellyfin.Server/Jellyfin.Server.csproj
+++ b/Jellyfin.Server/Jellyfin.Server.csproj
@@ -1,20 +1,19 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{07E39F42-A2C6-4B32-AF8C-725F957A73FF}</ProjectGuid>
+ </PropertyGroup>
<PropertyGroup>
<AssemblyName>jellyfin</AssemblyName>
<OutputType>Exe</OutputType>
- <TargetFramework>netcoreapp2.1</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
+ <ServerGarbageCollection>false</ServerGarbageCollection>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
- <PropertyGroup>
- <!-- We need C# 7.1 for async main-->
- <LangVersion>latest</LangVersion>
- <!-- Disable documentation warnings (for now) -->
- <NoWarn>SA1600;CS1591</NoWarn>
- </PropertyGroup>
-
<ItemGroup>
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
@@ -23,40 +22,48 @@
<EmbeddedResource Include="Resources/Configuration/*" />
</ItemGroup>
- <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- </PropertyGroup>
-
- <!-- Code analysers-->
+ <!-- Code Analyzers-->
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
- <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.3" />
- <PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />
- <PackageReference Include="SerilogAnalyzer" Version="0.15.0" />
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
</ItemGroup>
- <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
- <CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
- </PropertyGroup>
-
<ItemGroup>
- <PackageReference Include="CommandLineParser" Version="2.4.3" />
- <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" />
- <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
- <PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
- <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
- <PackageReference Include="Serilog.Sinks.Async" Version="1.3.0" />
- <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
- <PackageReference Include="Serilog.Sinks.File" Version="4.0.0" />
- <PackageReference Include="SkiaSharp" Version="1.68.0" />
- <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="1.1.13" />
- <PackageReference Include="SQLitePCLRaw.provider.sqlite3.netstandard11" Version="1.1.13" />
+ <PackageReference Include="CommandLineParser" Version="2.8.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="6.0.0-rc.2*" />
+ <PackageReference Include="prometheus-net" Version="5.0.1" />
+ <PackageReference Include="prometheus-net.AspNetCore" Version="5.0.1" />
+ <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
+ <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
+ <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
+ <PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
+ <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0" />
+ <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
+ <PackageReference Include="Serilog.Sinks.Graylog" Version="2.2.2" />
+ <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.0.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
- <ProjectReference Include="..\Emby.IsoMounting\IsoMounter\IsoMounter.csproj" />
<ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
<ProjectReference Include="..\Jellyfin.Drawing.Skia\Jellyfin.Drawing.Skia.csproj" />
+ <ProjectReference Include="..\Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <None Update="wwwroot\api-docs\redoc\custom.css">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="wwwroot\api-docs\swagger\custom.css">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="wwwroot\api-docs\banner-dark.svg">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
</ItemGroup>
</Project>
diff --git a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs
new file mode 100644
index 000000000..3e5982eed
--- /dev/null
+++ b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs
@@ -0,0 +1,84 @@
+using System;
+using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+using ConfigurationExtensions = MediaBrowser.Controller.Extensions.ConfigurationExtensions;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Redirect requests without baseurl prefix to the baseurl prefixed URL.
+ /// </summary>
+ public class BaseUrlRedirectionMiddleware
+ {
+ private readonly RequestDelegate _next;
+ private readonly ILogger<BaseUrlRedirectionMiddleware> _logger;
+ private readonly IConfiguration _configuration;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseUrlRedirectionMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="configuration">The application configuration.</param>
+ public BaseUrlRedirectionMiddleware(
+ RequestDelegate next,
+ ILogger<BaseUrlRedirectionMiddleware> logger,
+ IConfiguration configuration)
+ {
+ _next = next;
+ _logger = logger;
+ _configuration = configuration;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <param name="serverConfigurationManager">The server configuration manager.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext, IServerConfigurationManager serverConfigurationManager)
+ {
+ var localPath = httpContext.Request.Path.ToString();
+ var baseUrlPrefix = serverConfigurationManager.GetNetworkConfiguration().BaseUrl;
+
+ if (!string.IsNullOrEmpty(baseUrlPrefix))
+ {
+ var startsWithBaseUrl = localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase);
+
+ if (!startsWithBaseUrl
+ && (localPath.Equals("/health", StringComparison.OrdinalIgnoreCase)
+ || localPath.Equals("/health/", StringComparison.OrdinalIgnoreCase)))
+ {
+ _logger.LogDebug("Redirecting /health check");
+ httpContext.Response.Redirect(baseUrlPrefix + "/health");
+ return;
+ }
+
+ if (!startsWithBaseUrl
+ || localPath.Length == baseUrlPrefix.Length
+ // Local path is /baseUrl/
+ || (localPath.Length == baseUrlPrefix.Length + 1 && localPath[^1] == '/'))
+ {
+ // Always redirect back to the default path if the base prefix is invalid, missing, or is the full path.
+ _logger.LogDebug("Normalizing an URL at {LocalPath}", localPath);
+ httpContext.Response.Redirect(baseUrlPrefix + "/" + _configuration[ConfigurationExtensions.DefaultRedirectKey]);
+ return;
+ }
+ }
+ else if (string.IsNullOrEmpty(localPath)
+ || localPath.Equals("/", StringComparison.Ordinal))
+ {
+ // Always redirect back to the default path if root is requested.
+ _logger.LogDebug("Normalizing an URL at {LocalPath}", localPath);
+ httpContext.Response.Redirect("/" + _configuration[ConfigurationExtensions.DefaultRedirectKey]);
+ return;
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs
new file mode 100644
index 000000000..db7877c31
--- /dev/null
+++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs
@@ -0,0 +1,151 @@
+using System;
+using System.IO;
+using System.Net.Mime;
+using System.Net.Sockets;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Exception Middleware.
+ /// </summary>
+ public class ExceptionMiddleware
+ {
+ private readonly RequestDelegate _next;
+ private readonly ILogger<ExceptionMiddleware> _logger;
+ private readonly IServerConfigurationManager _configuration;
+ private readonly IWebHostEnvironment _hostEnvironment;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">Next request delegate.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="hostEnvironment">Instance of the <see cref="IWebHostEnvironment"/> interface.</param>
+ public ExceptionMiddleware(
+ RequestDelegate next,
+ ILogger<ExceptionMiddleware> logger,
+ IServerConfigurationManager serverConfigurationManager,
+ IWebHostEnvironment hostEnvironment)
+ {
+ _next = next;
+ _logger = logger;
+ _configuration = serverConfigurationManager;
+ _hostEnvironment = hostEnvironment;
+ }
+
+ /// <summary>
+ /// Invoke request.
+ /// </summary>
+ /// <param name="context">Request context.</param>
+ /// <returns>Task.</returns>
+ public async Task Invoke(HttpContext context)
+ {
+ try
+ {
+ await _next(context).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ if (context.Response.HasStarted)
+ {
+ _logger.LogWarning("The response has already started, the exception middleware will not be executed.");
+ throw;
+ }
+
+ ex = GetActualException(ex);
+
+ bool ignoreStackTrace =
+ ex is SocketException
+ || ex is IOException
+ || ex is OperationCanceledException
+ || ex is SecurityException
+ || ex is AuthenticationException
+ || ex is FileNotFoundException;
+
+ if (ignoreStackTrace)
+ {
+ _logger.LogError(
+ "Error processing request: {ExceptionMessage}. URL {Method} {Url}.",
+ ex.Message.TrimEnd('.'),
+ context.Request.Method,
+ context.Request.Path);
+ }
+ else
+ {
+ _logger.LogError(
+ ex,
+ "Error processing request. URL {Method} {Url}.",
+ context.Request.Method,
+ context.Request.Path);
+ }
+
+ context.Response.StatusCode = GetStatusCode(ex);
+ context.Response.ContentType = MediaTypeNames.Text.Plain;
+
+ // Don't send exception unless the server is in a Development environment
+ var errorContent = _hostEnvironment.IsDevelopment()
+ ? NormalizeExceptionMessage(ex.Message)
+ : "Error processing request.";
+ await context.Response.WriteAsync(errorContent).ConfigureAwait(false);
+ }
+ }
+
+ private static Exception GetActualException(Exception ex)
+ {
+ if (ex is AggregateException agg)
+ {
+ var inner = agg.InnerException;
+ if (inner != null)
+ {
+ return GetActualException(inner);
+ }
+
+ var inners = agg.InnerExceptions;
+ if (inners.Count > 0)
+ {
+ return GetActualException(inners[0]);
+ }
+ }
+
+ return ex;
+ }
+
+ private static int GetStatusCode(Exception ex)
+ {
+ switch (ex)
+ {
+ case ArgumentException _: return StatusCodes.Status400BadRequest;
+ case AuthenticationException _: return StatusCodes.Status401Unauthorized;
+ case SecurityException _: return StatusCodes.Status403Forbidden;
+ case DirectoryNotFoundException _:
+ case FileNotFoundException _:
+ case ResourceNotFoundException _: return StatusCodes.Status404NotFound;
+ case MethodNotAllowedException _: return StatusCodes.Status405MethodNotAllowed;
+ default: return StatusCodes.Status500InternalServerError;
+ }
+ }
+
+ private string NormalizeExceptionMessage(string msg)
+ {
+ // Strip any information we don't want to reveal
+ return msg.Replace(
+ _configuration.ApplicationPaths.ProgramSystemPath,
+ string.Empty,
+ StringComparison.OrdinalIgnoreCase)
+ .Replace(
+ _configuration.ApplicationPaths.ProgramDataPath,
+ string.Empty,
+ StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs
new file mode 100644
index 000000000..0afcd61a0
--- /dev/null
+++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs
@@ -0,0 +1,50 @@
+using System.Net;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Validates the IP of requests coming from local networks wrt. remote access.
+ /// </summary>
+ public class IpBasedAccessValidationMiddleware
+ {
+ private readonly RequestDelegate _next;
+
+ /// <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)
+ {
+ _next = next;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <param name="networkManager">The network manager.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
+ {
+ if (httpContext.IsLocal())
+ {
+ // Running locally.
+ await _next(httpContext).ConfigureAwait(false);
+ return;
+ }
+
+ var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
+
+ if (!networkManager.HasRemoteAccess(remoteIp))
+ {
+ return;
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs
new file mode 100644
index 000000000..67bf24d2a
--- /dev/null
+++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs
@@ -0,0 +1,45 @@
+using System.Net;
+using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Server.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)
+ {
+ var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
+
+ if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
+ {
+ return;
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs b/Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs
new file mode 100644
index 000000000..fdd8974d2
--- /dev/null
+++ b/Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Removes /emby and /mediabrowser from requested route.
+ /// </summary>
+ public class LegacyEmbyRouteRewriteMiddleware
+ {
+ private const string EmbyPath = "/emby";
+ private const string MediabrowserPath = "/mediabrowser";
+
+ private readonly RequestDelegate _next;
+ private readonly ILogger<LegacyEmbyRouteRewriteMiddleware> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LegacyEmbyRouteRewriteMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ /// <param name="logger">The logger.</param>
+ public LegacyEmbyRouteRewriteMiddleware(
+ RequestDelegate next,
+ ILogger<LegacyEmbyRouteRewriteMiddleware> logger)
+ {
+ _next = next;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext)
+ {
+ var localPath = httpContext.Request.Path.ToString();
+ if (localPath.StartsWith(EmbyPath, StringComparison.OrdinalIgnoreCase))
+ {
+ httpContext.Request.Path = localPath[EmbyPath.Length..];
+ _logger.LogDebug("Removing {EmbyPath} from route.", EmbyPath);
+ }
+ else if (localPath.StartsWith(MediabrowserPath, StringComparison.OrdinalIgnoreCase))
+ {
+ httpContext.Request.Path = localPath[MediabrowserPath.Length..];
+ _logger.LogDebug("Removing {MediabrowserPath} from route.", MediabrowserPath);
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs
new file mode 100644
index 000000000..cdd86e28e
--- /dev/null
+++ b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs
@@ -0,0 +1,39 @@
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// URL decodes the querystring before binding.
+ /// </summary>
+ public class QueryStringDecodingMiddleware
+ {
+ private readonly RequestDelegate _next;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QueryStringDecodingMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ public QueryStringDecodingMiddleware(RequestDelegate next)
+ {
+ _next = next;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext)
+ {
+ var feature = httpContext.Features.Get<IQueryFeature>();
+ if (feature != null)
+ {
+ httpContext.Features.Set<IQueryFeature>(new UrlDecodeQueryFeature(feature));
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs
new file mode 100644
index 000000000..74874da1b
--- /dev/null
+++ b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs
@@ -0,0 +1,79 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Configuration;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Extensions;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Response time middleware.
+ /// </summary>
+ public class ResponseTimeMiddleware
+ {
+ private const string ResponseHeaderResponseTime = "X-Response-Time-ms";
+
+ private readonly RequestDelegate _next;
+ private readonly ILogger<ResponseTimeMiddleware> _logger;
+
+ private readonly bool _enableWarning;
+ private readonly long _warningThreshold;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResponseTimeMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">Next request delegate.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public ResponseTimeMiddleware(
+ RequestDelegate next,
+ ILogger<ResponseTimeMiddleware> logger,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ _next = next;
+ _logger = logger;
+
+ _enableWarning = serverConfigurationManager.Configuration.EnableSlowResponseWarning;
+ _warningThreshold = serverConfigurationManager.Configuration.SlowResponseThresholdMs;
+ }
+
+ /// <summary>
+ /// Invoke request.
+ /// </summary>
+ /// <param name="context">Request context.</param>
+ /// <returns>Task.</returns>
+ public async Task Invoke(HttpContext context)
+ {
+ var watch = new Stopwatch();
+ watch.Start();
+
+ context.Response.OnStarting(() =>
+ {
+ watch.Stop();
+ LogWarning(context, watch);
+ var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
+ context.Response.Headers[ResponseHeaderResponseTime] = responseTimeForCompleteRequest.ToString(CultureInfo.InvariantCulture);
+ return Task.CompletedTask;
+ });
+
+ // Call the next delegate/middleware in the pipeline
+ await this._next(context).ConfigureAwait(false);
+ }
+
+ private void LogWarning(HttpContext context, Stopwatch watch)
+ {
+ if (_enableWarning && watch.ElapsedMilliseconds > _warningThreshold)
+ {
+ _logger.LogWarning(
+ "Slow HTTP Response from {url} to {remoteIp} in {elapsed:g} with Status Code {statusCode}",
+ context.Request.GetDisplayUrl(),
+ context.GetNormalizedRemoteIp(),
+ watch.Elapsed,
+ context.Response.StatusCode);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs
new file mode 100644
index 000000000..9d40d74fe
--- /dev/null
+++ b/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Redirect requests to robots.txt to web/robots.txt.
+ /// </summary>
+ public class RobotsRedirectionMiddleware
+ {
+ private readonly RequestDelegate _next;
+ private readonly ILogger<RobotsRedirectionMiddleware> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RobotsRedirectionMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ /// <param name="logger">The logger.</param>
+ public RobotsRedirectionMiddleware(
+ RequestDelegate next,
+ ILogger<RobotsRedirectionMiddleware> logger)
+ {
+ _next = next;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext)
+ {
+ var localPath = httpContext.Request.Path.ToString();
+ if (string.Equals(localPath, "/robots.txt", StringComparison.OrdinalIgnoreCase))
+ {
+ _logger.LogDebug("Redirecting robots.txt request to web/robots.txt");
+ httpContext.Response.Redirect("web/robots.txt");
+ return;
+ }
+
+ await _next(httpContext).ConfigureAwait(false);
+ }
+ }
+} \ No newline at end of file
diff --git a/Jellyfin.Server/Middleware/ServerStartupMessageMiddleware.cs b/Jellyfin.Server/Middleware/ServerStartupMessageMiddleware.cs
new file mode 100644
index 000000000..2ec063392
--- /dev/null
+++ b/Jellyfin.Server/Middleware/ServerStartupMessageMiddleware.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using MediaBrowser.Controller;
+using MediaBrowser.Model.Globalization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Shows a custom message during server startup.
+ /// </summary>
+ public class ServerStartupMessageMiddleware
+ {
+ private readonly RequestDelegate _next;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ServerStartupMessageMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ public ServerStartupMessageMiddleware(RequestDelegate next)
+ {
+ _next = next;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <param name="serverApplicationHost">The server application host.</param>
+ /// <param name="localizationManager">The localization manager.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(
+ HttpContext httpContext,
+ IServerApplicationHost serverApplicationHost,
+ ILocalizationManager localizationManager)
+ {
+ if (serverApplicationHost.CoreStartupHasCompleted
+ || httpContext.Request.Path.Equals("/system/ping", StringComparison.OrdinalIgnoreCase))
+ {
+ await _next(httpContext).ConfigureAwait(false);
+ return;
+ }
+
+ var message = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
+ httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
+ httpContext.Response.ContentType = MediaTypeNames.Text.Html;
+ await httpContext.Response.WriteAsync(message, httpContext.RequestAborted).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs
new file mode 100644
index 000000000..e4d2937e7
--- /dev/null
+++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs
@@ -0,0 +1,84 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Jellyfin.Extensions;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
+using Microsoft.Extensions.Primitives;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Defines the <see cref="UrlDecodeQueryFeature"/>.
+ /// </summary>
+ public class UrlDecodeQueryFeature : IQueryFeature
+ {
+ private IQueryCollection? _store;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
+ /// </summary>
+ /// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
+ public UrlDecodeQueryFeature(IQueryFeature feature)
+ {
+ Query = feature.Query;
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
+ /// </summary>
+ public IQueryCollection Query
+ {
+ get
+ {
+ return _store ?? QueryCollection.Empty;
+ }
+
+ set
+ {
+ // Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
+ if (value.Count != 1)
+ {
+ _store = value;
+ return;
+ }
+
+ // Encoded querystrings have no value, so don't process anything if a value is present.
+ var (key, stringValues) = value.First();
+ if (!string.IsNullOrEmpty(stringValues))
+ {
+ _store = value;
+ return;
+ }
+
+ if (!key.Contains('='))
+ {
+ _store = value;
+ return;
+ }
+
+ var pairs = new Dictionary<string, StringValues>();
+ foreach (var pair in key.SpanSplit('&'))
+ {
+ var i = pair.IndexOf('=');
+ if (i == -1)
+ {
+ // encoded is an equals.
+ // We use TryAdd so duplicate keys get ignored
+ pairs.TryAdd(pair.ToString(), StringValues.Empty);
+ continue;
+ }
+
+ var k = pair[..i].ToString();
+ var v = pair[(i + 1)..].ToString();
+ if (!pairs.TryAdd(k, new StringValues(v)))
+ {
+ pairs[k] = StringValues.Concat(pairs[k], v);
+ }
+ }
+
+ _store = new QueryCollection(pairs);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs
new file mode 100644
index 000000000..b7a5d2b34
--- /dev/null
+++ b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs
@@ -0,0 +1,40 @@
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Server.Middleware
+{
+ /// <summary>
+ /// Handles WebSocket requests.
+ /// </summary>
+ public class WebSocketHandlerMiddleware
+ {
+ private readonly RequestDelegate _next;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebSocketHandlerMiddleware"/> class.
+ /// </summary>
+ /// <param name="next">The next delegate in the pipeline.</param>
+ public WebSocketHandlerMiddleware(RequestDelegate next)
+ {
+ _next = next;
+ }
+
+ /// <summary>
+ /// Executes the middleware action.
+ /// </summary>
+ /// <param name="httpContext">The current HTTP context.</param>
+ /// <param name="webSocketManager">The WebSocket connection manager.</param>
+ /// <returns>The async task.</returns>
+ public async Task Invoke(HttpContext httpContext, IWebSocketManager webSocketManager)
+ {
+ if (!httpContext.WebSockets.IsWebSocketRequest)
+ {
+ await _next(httpContext).ConfigureAwait(false);
+ return;
+ }
+
+ await webSocketManager.WebSocketRequestHandler(httpContext).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/IMigrationRoutine.cs b/Jellyfin.Server/Migrations/IMigrationRoutine.cs
new file mode 100644
index 000000000..c1000eede
--- /dev/null
+++ b/Jellyfin.Server/Migrations/IMigrationRoutine.cs
@@ -0,0 +1,30 @@
+using System;
+
+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/MigrationOptions.cs b/Jellyfin.Server/Migrations/MigrationOptions.cs
new file mode 100644
index 000000000..c9710f1fd
--- /dev/null
+++ b/Jellyfin.Server/Migrations/MigrationOptions.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Server.Migrations
+{
+ /// <summary>
+ /// Configuration part that holds all migrations that were applied.
+ /// </summary>
+ public class MigrationOptions
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrationOptions"/> class.
+ /// </summary>
+ public MigrationOptions()
+ {
+ Applied = new List<(Guid Id, string Name)>();
+ }
+
+// .Net xml serializer can't handle interfaces
+#pragma warning disable CA1002 // Do not expose generic lists
+ /// <summary>
+ /// Gets the list of applied migration routine names.
+ /// </summary>
+ public List<(Guid Id, string Name)> Applied { get; }
+#pragma warning restore CA1002
+ }
+}
diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs
new file mode 100644
index 000000000..7365c8dbc
--- /dev/null
+++ b/Jellyfin.Server/Migrations/MigrationRunner.cs
@@ -0,0 +1,86 @@
+using System;
+using System.Linq;
+using MediaBrowser.Common.Configuration;
+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 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.AddPeopleQueryIndex),
+ typeof(Routines.MigrateAuthenticationDb)
+ };
+
+ /// <summary>
+ /// Run all needed migrations.
+ /// </summary>
+ /// <param name="host">CoreAppHost that hosts current version.</param>
+ /// <param name="loggerFactory">Factory for making the logger.</param>
+ public static void 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);
+
+ if (!host.ConfigurationManager.Configuration.IsStartupWizardCompleted && migrationOptions.Applied.Count == 0)
+ {
+ // If startup wizard is not finished, this is a fresh install.
+ // Don't run any migrations, just mark all of them as applied.
+ logger.LogInformation("Marking all known migrations as applied because this is a fresh install");
+ migrationOptions.Applied.AddRange(migrations.Where(m => !m.PerformOnNewInstall).Select(m => (m.Id, m.Name)));
+ host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions);
+ }
+
+ var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet();
+
+ for (var i = 0; i < migrations.Length; i++)
+ {
+ var migrationRoutine = migrations[i];
+ if (appliedMigrationIds.Contains(migrationRoutine.Id))
+ {
+ logger.LogDebug("Skipping migration '{Name}' since it is already applied", migrationRoutine.Name);
+ continue;
+ }
+
+ 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));
+ host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions);
+ logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/MigrationsFactory.cs b/Jellyfin.Server/Migrations/MigrationsFactory.cs
new file mode 100644
index 000000000..23c1b1ee6
--- /dev/null
+++ b/Jellyfin.Server/Migrations/MigrationsFactory.cs
@@ -0,0 +1,20 @@
+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
new file mode 100644
index 000000000..7a1ca6671
--- /dev/null
+++ b/Jellyfin.Server/Migrations/MigrationsListStore.cs
@@ -0,0 +1,24 @@
+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/Routines/AddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs
new file mode 100644
index 000000000..f6d8c9cc0
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs
@@ -0,0 +1,45 @@
+using System;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Updates;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// Migration to initialize system configuration with the default plugin repository.
+ /// </summary>
+ public class AddDefaultPluginRepository : IMigrationRoutine
+ {
+ 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="AddDefaultPluginRepository"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public AddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <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.Add(_defaultRepositoryInfo);
+ _serverConfigurationManager.SaveConfiguration();
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs
new file mode 100644
index 000000000..6343c422d
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs
@@ -0,0 +1,49 @@
+using System;
+using System.IO;
+using MediaBrowser.Controller;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// Migration to add table indexes to optimize the Persons query.
+ /// </summary>
+ public class AddPeopleQueryIndex : IMigrationRoutine
+ {
+ private const string DbFilename = "library.db";
+ private readonly ILogger<AddPeopleQueryIndex> _logger;
+ private readonly IServerApplicationPaths _serverApplicationPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AddPeopleQueryIndex"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{AddPeopleQueryIndex}"/> interface.</param>
+ /// <param name="serverApplicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
+ public AddPeopleQueryIndex(ILogger<AddPeopleQueryIndex> logger, IServerApplicationPaths serverApplicationPaths)
+ {
+ _logger = logger;
+ _serverApplicationPaths = serverApplicationPaths;
+ }
+
+ /// <inheritdoc />
+ public Guid Id => new Guid("DE009B59-BAAE-428D-A810-F67762DC05B8");
+
+ /// <inheritdoc />
+ public string Name => "AddPeopleQueryIndex";
+
+ /// <inheritdoc />
+ public bool PerformOnNewInstall => true;
+
+ /// <inheritdoc />
+ public void Perform()
+ {
+ var databasePath = Path.Join(_serverApplicationPaths.DataPath, DbFilename);
+ using var connection = SQLite3.Open(databasePath, ConnectionFlags.ReadWrite, null);
+ _logger.LogInformation("Creating index idx_TypedBaseItemsUserDataKeyType");
+ connection.Execute("CREATE INDEX IF NOT EXISTS idx_TypedBaseItemsUserDataKeyType ON TypedBaseItems(UserDataKey, Type);");
+ _logger.LogInformation("Creating index idx_PeopleNameListOrder");
+ connection.Execute("CREATE INDEX IF NOT EXISTS idx_PeopleNameListOrder ON People(Name, ListOrder);");
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs
new file mode 100644
index 000000000..ee4f8b0ba
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using MediaBrowser.Common.Configuration;
+using Newtonsoft.Json.Linq;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// Migration to initialize the user logging configuration file "logging.user.json".
+ /// 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>
+ internal class CreateUserLoggingConfigFile : IMigrationRoutine
+ {
+ /// <summary>
+ /// File history for logging.json as existed during this migration creation. The contents for each has been minified.
+ /// </summary>
+ private readonly List<string> _defaultConfigHistory = new List<string>
+ {
+ // 9a6c27947353585391e211aa88b925f81e8cd7b9
+ @"{""Serilog"":{""MinimumLevel"":{""Default"":""Information"",""Override"":{""Microsoft"":""Warning"",""System"":""Warning""}},""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""retainedFileCountLimit"":3,""rollOnFileSizeLimit"":true,""fileSizeLimitBytes"":100000000,""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}""}}]}}],""Enrich"":[""FromLogContext"",""WithThreadId""]}}",
+ // 71bdcd730705a714ee208eaad7290b7c68df3885
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""retainedFileCountLimit"":3,""rollOnFileSizeLimit"":true,""fileSizeLimitBytes"":100000000,""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}""}}]}}],""Enrich"":[""FromLogContext"",""WithThreadId""]}}",
+ // a44936f97f8afc2817d3491615a7cfe1e31c251c
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}""}},{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}""}}]}}",
+ // 7af3754a11ad5a4284f107997fb5419a010ce6f3
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}""}}]}}]}}",
+ // 60691349a11f541958e0b2247c9abc13cb40c9fb
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""retainedFileCountLimit"":3,""rollOnFileSizeLimit"":true,""fileSizeLimitBytes"":100000000,""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}""}}]}}]}}",
+ // 65fe243afbcc4b596cf8726708c1965cd34b5f68
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""retainedFileCountLimit"":3,""rollOnFileSizeLimit"":true,""fileSizeLimitBytes"":100000000,""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}""}}]}}],""Enrich"":[""FromLogContext"",""WithThreadId""]}}",
+ // 96c9af590494aa8137d5a061aaf1e68feee60b67
+ @"{""Serilog"":{""MinimumLevel"":""Information"",""WriteTo"":[{""Name"":""Console"",""Args"":{""outputTemplate"":""[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}""}},{""Name"":""Async"",""Args"":{""configure"":[{""Name"":""File"",""Args"":{""path"":""%JELLYFIN_LOG_DIR%//log_.log"",""rollingInterval"":""Day"",""retainedFileCountLimit"":3,""rollOnFileSizeLimit"":true,""fileSizeLimitBytes"":100000000,""outputTemplate"":""[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}""}}]}}],""Enrich"":[""FromLogContext"",""WithThreadId""]}}",
+ };
+
+ private readonly IApplicationPaths _appPaths;
+
+ public CreateUserLoggingConfigFile(IApplicationPaths appPaths)
+ {
+ _appPaths = appPaths;
+ }
+
+ /// <inheritdoc/>
+ public Guid Id => Guid.Parse("{EF103419-8451-40D8-9F34-D1A8E93A1679}");
+
+ /// <inheritdoc/>
+ public string Name => "CreateLoggingConfigHeirarchy";
+
+ /// <inheritdoc/>
+ public bool PerformOnNewInstall => false;
+
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ var logDirectory = _appPaths.ConfigurationDirectoryPath;
+ var existingConfigPath = Path.Combine(logDirectory, "logging.json");
+
+ // If the existing logging.json config file is unmodified, then 'reset' it by moving it to 'logging.old.json'
+ // NOTE: This config file has 'reloadOnChange: true', so this change will take effect immediately even though it has already been loaded
+ if (File.Exists(existingConfigPath) && ExistingConfigUnmodified(existingConfigPath))
+ {
+ File.Move(existingConfigPath, Path.Combine(logDirectory, "logging.old.json"));
+ }
+ }
+
+ /// <summary>
+ /// Check if the existing logging.json file has not been modified by the user by comparing it to all the
+ /// versions in our git history. Until now, the file has never been migrated after first creation so users
+ /// could have any version from the git history.
+ /// </summary>
+ /// <exception cref="IOException"><paramref name="oldConfigPath"/> does not exist or could not be read.</exception>
+ private bool ExistingConfigUnmodified(string oldConfigPath)
+ {
+ var existingConfigJson = JToken.Parse(File.ReadAllText(oldConfigPath));
+ return _defaultConfigHistory
+ .Select(JToken.Parse)
+ .Any(historicalConfigJson => JToken.DeepEquals(existingConfigJson, historicalConfigJson));
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs
new file mode 100644
index 000000000..378e88e25
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs
@@ -0,0 +1,44 @@
+using System;
+using MediaBrowser.Common.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// Disable transcode throttling for all installations since it is currently broken for certain video formats.
+ /// </summary>
+ internal class DisableTranscodingThrottling : IMigrationRoutine
+ {
+ private readonly ILogger<DisableTranscodingThrottling> _logger;
+ private readonly IConfigurationManager _configManager;
+
+ public DisableTranscodingThrottling(ILogger<DisableTranscodingThrottling> logger, IConfigurationManager configManager)
+ {
+ _logger = logger;
+ _configManager = configManager;
+ }
+
+ /// <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
+ var encoding = _configManager.GetEncodingOptions();
+ if (encoding.EnableThrottling)
+ {
+ _logger.LogInformation("Disabling transcoding throttling during migration");
+ encoding.EnableThrottling = false;
+
+ _configManager.SaveConfiguration("encoding", encoding);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
new file mode 100644
index 000000000..9e22978ae
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
@@ -0,0 +1,154 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Emby.Server.Implementations.Data;
+using Jellyfin.Data.Entities;
+using Jellyfin.Server.Implementations;
+using MediaBrowser.Controller;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// The migration routine for migrating the activity log database to EF Core.
+ /// </summary>
+ public class MigrateActivityLogDb : IMigrationRoutine
+ {
+ private const string DbFilename = "activitylog.db";
+
+ private readonly ILogger<MigrateActivityLogDb> _logger;
+ private readonly JellyfinDbProvider _provider;
+ private readonly IServerApplicationPaths _paths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrateActivityLogDb"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="paths">The server application paths.</param>
+ /// <param name="provider">The database provider.</param>
+ public MigrateActivityLogDb(ILogger<MigrateActivityLogDb> logger, IServerApplicationPaths paths, JellyfinDbProvider provider)
+ {
+ _logger = logger;
+ _provider = provider;
+ _paths = paths;
+ }
+
+ /// <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)
+ {
+ { "None", LogLevel.None },
+ { "Trace", LogLevel.Trace },
+ { "Debug", LogLevel.Debug },
+ { "Information", LogLevel.Information },
+ { "Info", LogLevel.Information },
+ { "Warn", LogLevel.Warning },
+ { "Warning", LogLevel.Warning },
+ { "Error", LogLevel.Error },
+ { "Critical", LogLevel.Critical }
+ };
+
+ var dataPath = _paths.DataPath;
+ using (var connection = SQLite3.Open(
+ Path.Combine(dataPath, DbFilename),
+ ConnectionFlags.ReadOnly,
+ null))
+ {
+ using var userDbConnection = SQLite3.Open(Path.Combine(dataPath, "users.db"), ConnectionFlags.ReadOnly, null);
+ _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
+ using var dbContext = _provider.CreateContext();
+
+ var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
+
+ // Make sure that the database is empty in case of failed migration due to power outages, etc.
+ dbContext.ActivityLogs.RemoveRange(dbContext.ActivityLogs);
+ dbContext.SaveChanges();
+ // Reset the autoincrement counter
+ dbContext.Database.ExecuteSqlRaw("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'ActivityLog';");
+ dbContext.SaveChanges();
+
+ var newEntries = new List<ActivityLog>();
+
+ foreach (var entry in queryResult)
+ {
+ if (!logLevelDictionary.TryGetValue(entry[8].ToString(), out var severity))
+ {
+ severity = LogLevel.Trace;
+ }
+
+ var guid = Guid.Empty;
+ if (entry[6].SQLiteType != SQLiteType.Null && !Guid.TryParse(entry[6].ToString(), out guid))
+ {
+ // This is not a valid Guid, see if it is an internal ID from an old Emby schema
+ _logger.LogWarning("Invalid Guid in UserId column: {Guid}", entry[6].ToString());
+
+ using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=@Id");
+ statement.TryBind("@Id", entry[6].ToString());
+
+ foreach (var row in statement.Query())
+ {
+ if (row.Count > 0 && Guid.TryParse(row[0].ToString(), out guid))
+ {
+ // Successfully parsed a Guid from the user table.
+ break;
+ }
+ }
+ }
+
+ var newEntry = new ActivityLog(entry[1].ToString(), entry[4].ToString(), guid)
+ {
+ DateCreated = entry[7].ReadDateTime(),
+ LogSeverity = severity
+ };
+
+ if (entry[2].SQLiteType != SQLiteType.Null)
+ {
+ newEntry.Overview = entry[2].ToString();
+ }
+
+ if (entry[3].SQLiteType != SQLiteType.Null)
+ {
+ newEntry.ShortOverview = entry[3].ToString();
+ }
+
+ if (entry[5].SQLiteType != SQLiteType.Null)
+ {
+ newEntry.ItemId = entry[5].ToString();
+ }
+
+ newEntries.Add(newEntry);
+ }
+
+ dbContext.ActivityLogs.AddRange(newEntries);
+ dbContext.SaveChanges();
+ }
+
+ try
+ {
+ File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
+
+ var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
+ if (File.Exists(journalPath))
+ {
+ File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
+ }
+ }
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error renaming legacy activity log database to 'activitylog.db.old'");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs
new file mode 100644
index 000000000..21f153623
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs
@@ -0,0 +1,129 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Emby.Server.Implementations.Data;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Server.Implementations;
+using MediaBrowser.Controller;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// A migration that moves data from the authentication database into the new schema.
+ /// </summary>
+ public class MigrateAuthenticationDb : IMigrationRoutine
+ {
+ private const string DbFilename = "authentication.db";
+
+ private readonly ILogger<MigrateAuthenticationDb> _logger;
+ private readonly JellyfinDbProvider _dbProvider;
+ private readonly IServerApplicationPaths _appPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrateAuthenticationDb"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="dbProvider">The database provider.</param>
+ /// <param name="appPaths">The server application paths.</param>
+ public MigrateAuthenticationDb(ILogger<MigrateAuthenticationDb> logger, JellyfinDbProvider dbProvider, IServerApplicationPaths appPaths)
+ {
+ _logger = logger;
+ _dbProvider = dbProvider;
+ _appPaths = appPaths;
+ }
+
+ /// <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;
+ using (var connection = SQLite3.Open(
+ Path.Combine(dataPath, DbFilename),
+ ConnectionFlags.ReadOnly,
+ null))
+ {
+ using var dbContext = _dbProvider.CreateContext();
+
+ var authenticatedDevices = connection.Query("SELECT * FROM Tokens");
+
+ foreach (var row in authenticatedDevices)
+ {
+ if (row[6].IsDbNull())
+ {
+ dbContext.ApiKeys.Add(new ApiKey(row[3].ToString())
+ {
+ AccessToken = row[1].ToString(),
+ DateCreated = row[9].ToDateTime(),
+ DateLastActivity = row[10].ToDateTime()
+ });
+ }
+ else
+ {
+ dbContext.Devices.Add(new Device(
+ new Guid(row[6].ToString()),
+ row[3].ToString(),
+ row[4].ToString(),
+ row[5].ToString(),
+ row[2].ToString())
+ {
+ AccessToken = row[1].ToString(),
+ IsActive = row[8].ToBool(),
+ DateCreated = row[9].ToDateTime(),
+ DateLastActivity = row[10].ToDateTime()
+ });
+ }
+ }
+
+ var deviceOptions = connection.Query("SELECT * FROM Devices");
+ var deviceIds = new HashSet<string>();
+ foreach (var row in deviceOptions)
+ {
+ if (row[2].IsDbNull())
+ {
+ continue;
+ }
+
+ var deviceId = row[2].ToString();
+ if (deviceIds.Contains(deviceId))
+ {
+ continue;
+ }
+
+ deviceIds.Add(deviceId);
+
+ dbContext.DeviceOptions.Add(new DeviceOptions(deviceId)
+ {
+ CustomName = row[1].IsDbNull() ? null : row[1].ToString()
+ });
+ }
+
+ dbContext.SaveChanges();
+ }
+
+ try
+ {
+ File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
+
+ var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
+ if (File.Exists(journalPath))
+ {
+ File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
+ }
+ }
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error renaming legacy activity log database to 'authentication.db.old'");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
new file mode 100644
index 000000000..40f871759
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
@@ -0,0 +1,228 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Server.Implementations;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Entities;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// The migration routine for migrating the display preferences database to EF Core.
+ /// </summary>
+ public class MigrateDisplayPreferencesDb : IMigrationRoutine
+ {
+ private const string DbFilename = "displaypreferences.db";
+
+ private readonly ILogger<MigrateDisplayPreferencesDb> _logger;
+ private readonly IServerApplicationPaths _paths;
+ private readonly JellyfinDbProvider _provider;
+ private readonly JsonSerializerOptions _jsonOptions;
+ private readonly IUserManager _userManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrateDisplayPreferencesDb"/> 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="userManager">The user manager.</param>
+ public MigrateDisplayPreferencesDb(
+ ILogger<MigrateDisplayPreferencesDb> logger,
+ IServerApplicationPaths paths,
+ JellyfinDbProvider provider,
+ IUserManager userManager)
+ {
+ _logger = logger;
+ _paths = paths;
+ _provider = provider;
+ _userManager = userManager;
+ _jsonOptions = new JsonSerializerOptions();
+ _jsonOptions.Converters.Add(new JsonStringEnumConverter());
+ }
+
+ /// <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 =
+ {
+ HomeSectionType.SmallLibraryTiles,
+ HomeSectionType.Resume,
+ HomeSectionType.ResumeAudio,
+ HomeSectionType.LiveTv,
+ HomeSectionType.NextUp,
+ HomeSectionType.LatestMedia,
+ HomeSectionType.None,
+ };
+
+ var chromecastDict = new Dictionary<string, ChromecastVersion>(StringComparer.OrdinalIgnoreCase)
+ {
+ { "stable", ChromecastVersion.Stable },
+ { "nightly", ChromecastVersion.Unstable },
+ { "unstable", ChromecastVersion.Unstable }
+ };
+
+ var displayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var customDisplayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var dbFilePath = Path.Combine(_paths.DataPath, DbFilename);
+ using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null))
+ {
+ using var dbContext = _provider.CreateContext();
+
+ var results = connection.Query("SELECT * FROM userdisplaypreferences");
+ foreach (var result in results)
+ {
+ var dto = JsonSerializer.Deserialize<DisplayPreferencesDto>(result[3].ToBlob(), _jsonOptions);
+ if (dto == null)
+ {
+ continue;
+ }
+
+ var itemId = new Guid(result[1].ToBlob());
+ var dtoUserId = new Guid(result[1].ToBlob());
+ var client = result[2].ToString();
+ var displayPreferencesKey = $"{dtoUserId}|{itemId}|{client}";
+ if (displayPrefs.Contains(displayPreferencesKey))
+ {
+ // Duplicate display preference.
+ continue;
+ }
+
+ displayPrefs.Add(displayPreferencesKey);
+ var existingUser = _userManager.GetUserById(dtoUserId);
+ if (existingUser == null)
+ {
+ _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", dtoUserId);
+ continue;
+ }
+
+ var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
+ ? chromecastDict[version]
+ : ChromecastVersion.Stable;
+ dto.CustomPrefs.Remove("chromecastVersion");
+
+ var displayPreferences = new DisplayPreferences(dtoUserId, itemId, client)
+ {
+ IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : null,
+ ShowBackdrop = dto.ShowBackdrop,
+ ShowSidebar = dto.ShowSidebar,
+ ScrollDirection = dto.ScrollDirection,
+ ChromecastVersion = chromecastVersion,
+ SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && int.TryParse(length, out var skipForwardLength)
+ ? skipForwardLength
+ : 30000,
+ SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && !string.IsNullOrEmpty(length) && int.TryParse(length, out var skipBackwardLength)
+ ? skipBackwardLength
+ : 10000,
+ EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled) && !string.IsNullOrEmpty(enabled)
+ ? bool.Parse(enabled)
+ : true,
+ DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.Empty,
+ TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty
+ };
+
+ dto.CustomPrefs.Remove("skipForwardLength");
+ dto.CustomPrefs.Remove("skipBackLength");
+ dto.CustomPrefs.Remove("enableNextVideoInfoOverlay");
+ dto.CustomPrefs.Remove("dashboardtheme");
+ dto.CustomPrefs.Remove("tvhome");
+
+ for (int i = 0; i < 7; i++)
+ {
+ var key = "homesection" + i;
+ dto.CustomPrefs.TryGetValue(key, out var homeSection);
+
+ displayPreferences.HomeSections.Add(new HomeSection
+ {
+ Order = i,
+ Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i]
+ });
+
+ dto.CustomPrefs.Remove(key);
+ }
+
+ var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayPreferences.Client)
+ {
+ SortBy = dto.SortBy ?? "SortName",
+ SortOrder = dto.SortOrder,
+ RememberIndexing = dto.RememberIndexing,
+ RememberSorting = dto.RememberSorting,
+ };
+
+ dbContext.Add(defaultLibraryPrefs);
+
+ foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Ordinal)))
+ {
+ if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var landingItemId))
+ {
+ continue;
+ }
+
+ var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, landingItemId, displayPreferences.Client)
+ {
+ SortBy = dto.SortBy ?? "SortName",
+ SortOrder = dto.SortOrder,
+ RememberIndexing = dto.RememberIndexing,
+ RememberSorting = dto.RememberSorting,
+ };
+
+ if (Enum.TryParse<ViewType>(dto.ViewType, true, out var viewType))
+ {
+ libraryDisplayPreferences.ViewType = viewType;
+ }
+
+ dto.CustomPrefs.Remove(key);
+ dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences);
+ }
+
+ foreach (var (key, value) in dto.CustomPrefs)
+ {
+ // Custom display preferences can have a key collision.
+ var indexKey = $"{displayPreferences.UserId}|{itemId}|{displayPreferences.Client}|{key}";
+ if (!customDisplayPrefs.Contains(indexKey))
+ {
+ dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client, key, value));
+ customDisplayPrefs.Add(indexKey);
+ }
+ }
+
+ dbContext.Add(displayPreferences);
+ }
+
+ dbContext.SaveChanges();
+ }
+
+ try
+ {
+ File.Move(dbFilePath, dbFilePath + ".old");
+
+ var journalPath = dbFilePath + "-journal";
+ if (File.Exists(journalPath))
+ {
+ File.Move(journalPath, dbFilePath + ".old-journal");
+ }
+ }
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error renaming legacy display preferences database to 'displaypreferences.db.old'");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs
new file mode 100644
index 000000000..9b2d603c7
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs
@@ -0,0 +1,219 @@
+using System;
+using System.IO;
+using Emby.Server.Implementations.Data;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json;
+using Jellyfin.Server.Implementations;
+using Jellyfin.Server.Implementations.Users;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Serialization;
+using MediaBrowser.Model.Users;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+using JsonSerializer = System.Text.Json.JsonSerializer;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// The migration routine for migrating the user database to EF Core.
+ /// </summary>
+ public class MigrateUserDb : IMigrationRoutine
+ {
+ private const string DbFilename = "users.db";
+
+ private readonly ILogger<MigrateUserDb> _logger;
+ private readonly IServerApplicationPaths _paths;
+ private readonly JellyfinDbProvider _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,
+ JellyfinDbProvider provider,
+ IXmlSerializer xmlSerializer)
+ {
+ _logger = logger;
+ _paths = paths;
+ _provider = provider;
+ _xmlSerializer = xmlSerializer;
+ }
+
+ /// <inheritdoc/>
+ public Guid Id => Guid.Parse("5C4B82A2-F053-4009-BD05-B6FCAD82F14C");
+
+ /// <inheritdoc/>
+ public string Name => "MigrateUserDatabase";
+
+ /// <inheritdoc/>
+ public bool PerformOnNewInstall => false;
+
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ var dataPath = _paths.DataPath;
+ _logger.LogInformation("Migrating the user database may take a while, do not stop Jellyfin.");
+
+ using (var connection = SQLite3.Open(Path.Combine(dataPath, DbFilename), ConnectionFlags.ReadOnly, null))
+ {
+ var dbContext = _provider.CreateContext();
+
+ var queryResult = connection.Query("SELECT * FROM LocalUsersv2");
+
+ dbContext.RemoveRange(dbContext.Users);
+ dbContext.SaveChanges();
+
+ foreach (var entry in queryResult)
+ {
+ UserMockup? mockup = JsonSerializer.Deserialize<UserMockup>(entry[2].ToBlob(), JsonDefaults.Options);
+ if (mockup == 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
+ };
+
+ var user = new User(mockup.Name, policy.AuthenticationProviderId!, policy.PasswordResetProviderId!)
+ {
+ Id = entry[1].ReadGuidFromBlob(),
+ InternalId = entry[0].ToInt64(),
+ 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,
+ EasyPassword = mockup.EasyPassword,
+ LastLoginDate = mockup.LastLoginDate,
+ LastActivityDate = mockup.LastActivityDate
+ };
+
+ 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);
+
+ 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);
+ }
+
+ dbContext.SaveChanges();
+ }
+
+ try
+ {
+ File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
+
+ var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
+ if (File.Exists(journalPath))
+ {
+ 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; }
+
+ public string EasyPassword { get; set; }
+
+ public DateTime? LastLoginDate { get; set; }
+
+ public DateTime? LastActivityDate { get; set; }
+
+ public string Name { get; set; }
+
+ public ItemImageInfo[] ImageInfos { get; set; }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
new file mode 100644
index 000000000..394f14d63
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
@@ -0,0 +1,49 @@
+using System;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Updates;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ /// <summary>
+ /// Migration to initialize system configuration with the default plugin repository.
+ /// </summary>
+ public class ReaddDefaultPluginRepository : IMigrationRoutine
+ {
+ 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;
+
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ // Only add if repository list is empty
+ if (_serverConfigurationManager.Configuration.PluginRepositories.Count == 0)
+ {
+ _serverConfigurationManager.Configuration.PluginRepositories.Add(_defaultRepositoryInfo);
+ _serverConfigurationManager.SaveConfiguration();
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
new file mode 100644
index 000000000..9137ea234
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
@@ -0,0 +1,52 @@
+using System;
+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}");
+
+ /// <inheritdoc/>
+ public string Name => "RemoveDownloadImagesInAdvance";
+
+ /// <inheritdoc/>
+ public bool PerformOnNewInstall => false;
+
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ 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))
+ {
+ continue;
+ }
+
+ var libraryOptions = virtualFolder.LibraryOptions;
+ var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(folderId);
+ // 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
new file mode 100644
index 000000000..6c26e47e1
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Globalization;
+using System.IO;
+
+using MediaBrowser.Controller;
+using Microsoft.Extensions.Logging;
+using SQLitePCL.pretty;
+
+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>
+ 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)
+ {
+ _logger = logger;
+ _paths = paths;
+ }
+
+ /// <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 = SQLite3.Open(
+ dbPath,
+ ConnectionFlags.ReadWrite,
+ null))
+ {
+ // 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.SelectScalarString());
+
+ // Do nothing if no duplicate extras were detected
+ if (bads.Length == 0)
+ {
+ _logger.LogInformation("No duplicate extras detected, skipping migration.");
+ return;
+ }
+
+ // 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))
+ {
+ 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;
+ }
+ }
+ }
+
+ // 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')");
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs
index 41ee73a56..45699f3af 100644
--- a/Jellyfin.Server/Program.cs
+++ b/Jellyfin.Server/Program.cs
@@ -1,64 +1,79 @@
using System;
+using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
-using System.Net.Security;
using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Text.RegularExpressions;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
-using Emby.Drawing;
using Emby.Server.Implementations;
-using Emby.Server.Implementations.EnvironmentInfo;
using Emby.Server.Implementations.IO;
-using Emby.Server.Implementations.Networking;
-using Jellyfin.Drawing.Skia;
+using Jellyfin.Server.Implementations;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.Globalization;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Extensions;
using MediaBrowser.Model.IO;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
using Serilog;
-using Serilog.AspNetCore;
+using Serilog.Extensions.Logging;
+using SQLitePCL;
+using ConfigurationExtensions = MediaBrowser.Controller.Extensions.ConfigurationExtensions;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace Jellyfin.Server
{
+ /// <summary>
+ /// Class containing the entry point of the application.
+ /// </summary>
public static class Program
{
+ /// <summary>
+ /// The name of logging configuration file containing application defaults.
+ /// </summary>
+ public const string LoggingConfigFileDefault = "logging.default.json";
+
+ /// <summary>
+ /// The name of the logging configuration file containing the system-specific override settings.
+ /// </summary>
+ public const string LoggingConfigFileSystem = "logging.json";
+
private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
- private static ILogger _logger;
+ private static ILogger _logger = NullLogger.Instance;
private static bool _restartOnShutdown;
- private static IConfiguration appConfig;
- public static async Task Main(string[] args)
+ /// <summary>
+ /// The entry point of the application.
+ /// </summary>
+ /// <param name="args">The command line arguments passed.</param>
+ /// <returns><see cref="Task" />.</returns>
+ public static Task Main(string[] args)
{
- // For backwards compatibility.
- // Modify any input arguments now which start with single-hyphen to POSIX standard
- // double-hyphen to allow parsing by CommandLineParser package.
- const string pattern = @"^(-[^-\s]{2})"; // Match -xx, not -x, not --xx, not xx
- const string substitution = @"-$1"; // Prepend with additional single-hyphen
- var regex = new Regex(pattern);
-
- for (var i = 0; i < args.Length; i++)
+ static Task ErrorParsingArguments(IEnumerable<Error> errors)
{
- args[i] = regex.Replace(args[i], substitution);
+ Environment.ExitCode = 1;
+ return Task.CompletedTask;
}
// Parse the command line arguments and either start the app or exit indicating error
- await Parser.Default.ParseArguments<StartupOptions>(args)
- .MapResult(
- options => StartApp(options),
- errs => Task.FromResult(0)).ConfigureAwait(false);
+ return Parser.Default.ParseArguments<StartupOptions>(args)
+ .MapResult(StartApp, ErrorParsingArguments);
}
- public static void Shutdown()
+ /// <summary>
+ /// Shuts down the application.
+ /// </summary>
+ internal static void Shutdown()
{
if (!_tokenSource.IsCancellationRequested)
{
@@ -66,7 +81,10 @@ namespace Jellyfin.Server
}
}
- public static void Restart()
+ /// <summary>
+ /// Restarts the application.
+ /// </summary>
+ internal static void Restart()
{
_restartOnShutdown = true;
@@ -75,22 +93,39 @@ namespace Jellyfin.Server
private static async Task StartApp(StartupOptions options)
{
+ var stopWatch = new Stopwatch();
+ stopWatch.Start();
+
+ // Log all uncaught exceptions to std error
+ static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) =>
+ Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject.ToString());
+ AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole;
+
ServerApplicationPaths appPaths = CreateApplicationPaths(options);
// $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
- appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);
+ // Enable cl-va P010 interop for tonemapping on Intel VAAPI
+ Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
+ Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
+
+ await InitLoggingConfigFile(appPaths).ConfigureAwait(false);
- CreateLogger(appConfig, appPaths);
+ // Create an instance of the application configuration to use for application startup
+ IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
+ // Initialize logging framework
+ InitializeLoggingFramework(startupConfig, appPaths);
_logger = _loggerFactory.CreateLogger("Main");
- AppDomain.CurrentDomain.UnhandledException += (sender, e)
+ // Log uncaught exceptions to the logging instead of std error
+ AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole;
+ AppDomain.CurrentDomain.UnhandledException += (_, e)
=> _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
// Intercept Ctrl+C and Ctrl+Break
- Console.CancelKeyPress += (sender, e) =>
+ Console.CancelKeyPress += (_, e) =>
{
if (_tokenSource.IsCancellationRequested)
{
@@ -104,7 +139,7 @@ namespace Jellyfin.Server
};
// Register a SIGTERM handler
- AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
+ AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
if (_tokenSource.IsCancellationRequested)
{
@@ -116,45 +151,86 @@ namespace Jellyfin.Server
Shutdown();
};
- _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);
-
- EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem());
- ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
-
- SQLitePCL.Batteries_V2.Init();
+ _logger.LogInformation(
+ "Jellyfin version: {Version}",
+ Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
- // Allow all https requests
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; } );
+ ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
- var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, appPaths);
+ PerformStaticInitialization();
+ var serviceCollection = new ServiceCollection();
- using (var appHost = new CoreAppHost(
+ var appHost = new CoreAppHost(
appPaths,
_loggerFactory,
options,
- fileSystem,
- environmentInfo,
- new NullImageEncoder(),
- new NetworkManager(_loggerFactory, environmentInfo),
- appConfig))
+ startupConfig,
+ new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
+ serviceCollection);
+
+ try
{
- await appHost.Init(new ServiceCollection()).ConfigureAwait(false);
+ // If hosting the web client, validate the client content path
+ if (startupConfig.HostWebClient())
+ {
+ string? webContentPath = appHost.ConfigurationManager.ApplicationPaths.WebPath;
+ if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0)
+ {
+ throw new InvalidOperationException(
+ "The server is expected to host the web client, but the provided content directory is either " +
+ $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " +
+ "server, you may set the '--nowebclient' command line flag, or set" +
+ $"'{ConfigurationExtensions.HostWebClientKey}=false' in your config settings.");
+ }
+ }
- appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);
+ appHost.Init();
- await appHost.RunStartupTasks().ConfigureAwait(false);
+ var webHost = new WebHostBuilder().ConfigureWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build();
- // TODO: read input for a stop command
+ // Re-use the web host service provider in the app host since ASP.NET doesn't allow a custom service collection.
+ appHost.ServiceProvider = webHost.Services;
+ await appHost.InitializeServices().ConfigureAwait(false);
+ Migrations.MigrationRunner.Run(appHost, _loggerFactory);
try
{
- // Block main thread until shutdown
- await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
+ await webHost.StartAsync(_tokenSource.Token).ConfigureAwait(false);
}
- catch (TaskCanceledException)
+ catch (Exception ex) when (ex is not TaskCanceledException)
{
- // Don't throw on cancellation
+ _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in network.xml and try again.");
+ throw;
}
+
+ await appHost.RunStartupTasksAsync(_tokenSource.Token).ConfigureAwait(false);
+
+ stopWatch.Stop();
+
+ _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed);
+
+ // Block main thread until shutdown
+ await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
+ }
+ catch (TaskCanceledException)
+ {
+ // Don't throw on cancellation
+ }
+ catch (Exception ex)
+ {
+ _logger.LogCritical(ex, "Error while starting server.");
+ }
+ finally
+ {
+ _logger.LogInformation("Running query planner optimizations in the database... This might take a while");
+ // Run before disposing the application
+ using var context = appHost.Resolve<JellyfinDbProvider>().CreateContext();
+ if (context.Database.IsSqlite())
+ {
+ context.Database.ExecuteSqlRaw("PRAGMA optimize");
+ }
+
+ appHost.Dispose();
}
if (_restartOnShutdown)
@@ -164,36 +240,153 @@ namespace Jellyfin.Server
}
/// <summary>
+ /// Call static initialization methods for the application.
+ /// </summary>
+ public static void PerformStaticInitialization()
+ {
+ // Make sure we have all the code pages we can get
+ // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ // Increase the max http request limit
+ // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
+ ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
+
+ // Disable the "Expect: 100-Continue" header by default
+ // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
+ ServicePointManager.Expect100Continue = false;
+
+ Batteries_V2.Init();
+ if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
+ {
+ _logger.LogWarning("Failed to enable shared cache for SQLite");
+ }
+ }
+
+ /// <summary>
+ /// Configure the web host builder.
+ /// </summary>
+ /// <param name="builder">The builder to configure.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="serviceCollection">The application service collection.</param>
+ /// <param name="commandLineOpts">The command line options passed to the application.</param>
+ /// <param name="startupConfig">The application configuration.</param>
+ /// <param name="appPaths">The application paths.</param>
+ /// <returns>The configured web host builder.</returns>
+ public static IWebHostBuilder ConfigureWebHostBuilder(
+ this IWebHostBuilder builder,
+ ApplicationHost appHost,
+ IServiceCollection serviceCollection,
+ StartupOptions commandLineOpts,
+ IConfiguration startupConfig,
+ IApplicationPaths appPaths)
+ {
+ return builder
+ .UseKestrel((builderContext, options) =>
+ {
+ var addresses = appHost.NetManager.GetAllBindInterfaces();
+
+ bool flagged = false;
+ foreach (IPObject netAdd in addresses)
+ {
+ _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd);
+ options.Listen(netAdd.Address, appHost.HttpPort);
+ if (appHost.ListenWithHttps)
+ {
+ options.Listen(
+ netAdd.Address,
+ appHost.HttpsPort,
+ listenOptions => listenOptions.UseHttps(appHost.Certificate));
+ }
+ else if (builderContext.HostingEnvironment.IsDevelopment())
+ {
+ try
+ {
+ options.Listen(
+ netAdd.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;
+ }
+ }
+ }
+ }
+
+ // Bind to unix socket (only on unix systems)
+ if (startupConfig.UseUnixSocket() && Environment.OSVersion.Platform == PlatformID.Unix)
+ {
+ var socketPath = startupConfig.GetUnixSocketPath();
+ if (string.IsNullOrEmpty(socketPath))
+ {
+ var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
+ if (xdgRuntimeDir == null)
+ {
+ // Fall back to config dir
+ socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, "socket.sock");
+ }
+ else
+ {
+ socketPath = Path.Join(xdgRuntimeDir, "jellyfin-socket");
+ }
+ }
+
+ // 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);
+ }
+ })
+ .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(commandLineOpts, appPaths, startupConfig))
+ .UseSerilog()
+ .ConfigureServices(services =>
+ {
+ // Merge the external ServiceCollection into ASP.NET DI
+ services.Add(serviceCollection);
+ })
+ .UseStartup<Startup>();
+ }
+
+ /// <summary>
/// Create the data, config and log paths from the variety of inputs(command line args,
- /// environment variables) or decide on what default to use. For Windows it's %AppPath%
- /// for everything else the XDG approach is followed:
- /// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+ /// environment variables) or decide on what default to use. For Windows it's %AppPath%
+ /// for everything else the
+ /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
+ /// is followed.
/// </summary>
- /// <param name="options">StartupOptions</param>
- /// <returns>ServerApplicationPaths</returns>
+ /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
+ /// <returns><see cref="ServerApplicationPaths" />.</returns>
private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
{
// dataDir
// IF --datadir
- // ELSE IF $JELLYFIN_DATA_PATH
+ // ELSE IF $JELLYFIN_DATA_DIR
// ELSE IF windows, use <%APPDATA%>/jellyfin
// ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
// ELSE use $HOME/.local/share/jellyfin
var dataDir = options.DataDir;
-
if (string.IsNullOrEmpty(dataDir))
{
- dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
+ dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
if (string.IsNullOrEmpty(dataDir))
{
// LocalApplicationData follows the XDG spec on unix machines
- dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "jellyfin");
+ dataDir = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+ "jellyfin");
}
}
- Directory.CreateDirectory(dataDir);
-
// configDir
// IF --configdir
// ELSE IF $JELLYFIN_CONFIG_DIR
@@ -209,20 +402,26 @@ namespace Jellyfin.Server
if (string.IsNullOrEmpty(configDir))
{
- if (options.DataDir != null || Directory.Exists(Path.Combine(dataDir, "config")) || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ if (options.DataDir != null
+ || Directory.Exists(Path.Combine(dataDir, "config"))
+ || OperatingSystem.IsWindows())
{
// Hang config folder off already set dataDir
configDir = Path.Combine(dataDir, "config");
}
else
{
- // $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored.
+ // $XDG_CONFIG_HOME defines the base directory relative to which
+ // user specific configuration files should be stored.
configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
- // If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME /.config should be used.
+ // If $XDG_CONFIG_HOME is either not set or empty,
+ // a default equal to $HOME /.config should be used.
if (string.IsNullOrEmpty(configDir))
{
- configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
+ configDir = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
+ ".config");
}
configDir = Path.Combine(configDir, "jellyfin");
@@ -237,27 +436,30 @@ namespace Jellyfin.Server
// ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
// ELSE HOME/.cache/jellyfin
var cacheDir = options.CacheDir;
-
if (string.IsNullOrEmpty(cacheDir))
{
cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
if (string.IsNullOrEmpty(cacheDir))
{
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ if (OperatingSystem.IsWindows())
{
// Hang cache folder off already set dataDir
cacheDir = Path.Combine(dataDir, "cache");
}
else
{
- // $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored.
+ // $XDG_CACHE_HOME defines the base directory relative to which
+ // user specific non-essential data files should be stored.
cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
- // If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.
+ // If $XDG_CACHE_HOME is either not set or empty,
+ // a default equal to $HOME/.cache should be used.
if (string.IsNullOrEmpty(cacheDir))
{
- cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache");
+ cacheDir = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
+ ".cache");
}
cacheDir = Path.Combine(cacheDir, "jellyfin");
@@ -265,13 +467,28 @@ namespace Jellyfin.Server
}
}
+ // webDir
+ // IF --webdir
+ // ELSE IF $JELLYFIN_WEB_DIR
+ // ELSE <bindir>/jellyfin-web
+ var webDir = options.WebDir;
+ if (string.IsNullOrEmpty(webDir))
+ {
+ webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
+
+ if (string.IsNullOrEmpty(webDir))
+ {
+ // Use default location under ResourcesPath
+ webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
+ }
+ }
+
// logDir
// IF --logdir
// ELSE IF $JELLYFIN_LOG_DIR
// ELSE IF --datadir, use <datadir>/log (assume portable run)
// ELSE <datadir>/log
var logDir = options.LogDir;
-
if (string.IsNullOrEmpty(logDir))
{
logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
@@ -283,9 +500,17 @@ namespace Jellyfin.Server
}
}
+ // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
+ dataDir = Path.GetFullPath(dataDir);
+ logDir = Path.GetFullPath(logDir);
+ configDir = Path.GetFullPath(configDir);
+ cacheDir = Path.GetFullPath(cacheDir);
+ webDir = Path.GetFullPath(webDir);
+
// Ensure the main folders exist before we continue
try
{
+ Directory.CreateDirectory(dataDir);
Directory.CreateDirectory(logDir);
Directory.CreateDirectory(configDir);
Directory.CreateDirectory(cacheDir);
@@ -297,101 +522,98 @@ namespace Jellyfin.Server
Environment.Exit(1);
}
- return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir);
+ return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
}
- private static async Task<IConfiguration> CreateConfiguration(IApplicationPaths appPaths)
+ /// <summary>
+ /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
+ /// already.
+ /// </summary>
+ /// <param name="appPaths">The application paths.</param>
+ /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
+ public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
{
- string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
-
- if (!File.Exists(configPath))
+ // Do nothing if the config file already exists
+ string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
+ if (File.Exists(configPath))
{
- // For some reason the csproj name is used instead of the assembly name
- using (Stream rscstr = typeof(Program).Assembly
- .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
- using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
- {
- await rscstr.CopyToAsync(fstr).ConfigureAwait(false);
- }
+ return;
}
+ // Get a stream of the resource contents
+ // NOTE: The .csproj name is used instead of the assembly name in the resource path
+ const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
+ await using Stream resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
+ ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
+
+ // Copy the resource contents to the expected file path for the config file
+ await using Stream dst = new FileStream(configPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ await resource.CopyToAsync(dst).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Create the application configuration.
+ /// </summary>
+ /// <param name="commandLineOpts">The command line options passed to the program.</param>
+ /// <param name="appPaths">The application paths.</param>
+ /// <returns>The application configuration.</returns>
+ public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
+ {
return new ConfigurationBuilder()
+ .ConfigureAppConfiguration(commandLineOpts, appPaths)
+ .Build();
+ }
+
+ private static IConfigurationBuilder ConfigureAppConfiguration(
+ this IConfigurationBuilder config,
+ StartupOptions commandLineOpts,
+ IApplicationPaths appPaths,
+ IConfiguration? startupConfig = null)
+ {
+ // Use the swagger API page as the default redirect path if not hosting the web client
+ var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
+ if (startupConfig != null && !startupConfig.HostWebClient())
+ {
+ inMemoryDefaultConfig[ConfigurationExtensions.DefaultRedirectKey] = "api-docs/swagger";
+ }
+
+ return config
.SetBasePath(appPaths.ConfigurationDirectoryPath)
- .AddJsonFile("logging.json")
+ .AddInMemoryCollection(inMemoryDefaultConfig)
+ .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
+ .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
.AddEnvironmentVariables("JELLYFIN_")
- .AddInMemoryCollection(ConfigurationOptions.Configuration)
- .Build();
+ .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
}
- private static void CreateLogger(IConfiguration configuration, IApplicationPaths appPaths)
+ /// <summary>
+ /// Initialize Serilog using configuration and fall back to defaults on failure.
+ /// </summary>
+ private static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
{
try
{
// Serilog.Log is used by SerilogLoggerFactory when no logger is specified
- Serilog.Log.Logger = new LoggerConfiguration()
+ Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
+ .Enrich.WithThreadId()
.CreateLogger();
}
catch (Exception ex)
{
- Serilog.Log.Logger = new LoggerConfiguration()
- .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
+ Log.Logger = new LoggerConfiguration()
+ .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
.WriteTo.Async(x => x.File(
Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
rollingInterval: RollingInterval.Day,
- outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
+ outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}",
+ encoding: Encoding.UTF8))
.Enrich.FromLogContext()
+ .Enrich.WithThreadId()
.CreateLogger();
- Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
- }
- }
-
- private static IImageEncoder GetImageEncoder(
- IFileSystem fileSystem,
- IApplicationPaths appPaths,
- ILocalizationManager localizationManager)
- {
- try
- {
- return new SkiaEncoder(_loggerFactory, appPaths, fileSystem, localizationManager);
- }
- catch (Exception ex)
- {
- _logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
- }
-
- return new NullImageEncoder();
- }
-
- private static MediaBrowser.Model.System.OperatingSystem GetOperatingSystem()
- {
- switch (Environment.OSVersion.Platform)
- {
- case PlatformID.MacOSX:
- return MediaBrowser.Model.System.OperatingSystem.OSX;
- case PlatformID.Win32NT:
- return MediaBrowser.Model.System.OperatingSystem.Windows;
- case PlatformID.Unix:
- default:
- {
- string osDescription = RuntimeInformation.OSDescription;
- if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.Linux;
- }
- else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.OSX;
- }
- else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.BSD;
- }
-
- throw new Exception($"Can't resolve OS with description: '{osDescription}'");
- }
+ Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
}
}
@@ -399,23 +621,22 @@ namespace Jellyfin.Server
{
_logger.LogInformation("Starting new instance");
- string module = options.RestartPath;
+ var module = options.RestartPath;
if (string.IsNullOrWhiteSpace(module))
{
- module = Environment.GetCommandLineArgs().First();
+ module = Environment.GetCommandLineArgs()[0];
}
string commandLineArgsString;
-
if (options.RestartArgs != null)
{
- commandLineArgsString = options.RestartArgs ?? string.Empty;
+ commandLineArgsString = options.RestartArgs;
}
else
{
commandLineArgsString = string.Join(
- " ",
+ ' ',
Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
}
diff --git a/Jellyfin.Server/Properties/AssemblyInfo.cs b/Jellyfin.Server/Properties/AssemblyInfo.cs
index 2959cdf1f..fe2d5c5f9 100644
--- a/Jellyfin.Server/Properties/AssemblyInfo.cs
+++ b/Jellyfin.Server/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -9,8 +10,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
@@ -19,3 +20,5 @@ using System.Runtime.InteropServices;
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
+
+[assembly: InternalsVisibleTo("Jellyfin.Server.Tests")]
diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json
new file mode 100644
index 000000000..20d432afc
--- /dev/null
+++ b/Jellyfin.Server/Properties/launchSettings.json
@@ -0,0 +1,29 @@
+{
+ "profiles": {
+ "Jellyfin.Server": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:8096",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "Jellyfin.Server (nowebclient)": {
+ "commandName": "Project",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ },
+ "commandLineArgs": "--nowebclient"
+ },
+ "Jellyfin.Server (API Docs)": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "launchUrl": "api-docs/swagger",
+ "applicationUrl": "http://localhost:8096",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ },
+ "commandLineArgs": "--nowebclient"
+ }
+ }
+}
diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json
index d16991277..f64a85219 100644
--- a/Jellyfin.Server/Resources/Configuration/logging.json
+++ b/Jellyfin.Server/Resources/Configuration/logging.json
@@ -1,11 +1,17 @@
{
"Serilog": {
- "MinimumLevel": "Information",
+ "MinimumLevel": {
+ "Default": "Information",
+ "Override": {
+ "Microsoft": "Warning",
+ "System": "Warning"
+ }
+ },
"WriteTo": [
{
"Name": "Console",
"Args": {
- "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}"
+ "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
}
},
{
@@ -17,12 +23,16 @@
"Args": {
"path": "%JELLYFIN_LOG_DIR%//log_.log",
"rollingInterval": "Day",
- "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"
+ "retainedFileCountLimit": 3,
+ "rollOnFileSizeLimit": true,
+ "fileSizeLimitBytes": 100000000,
+ "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"
}
}
]
}
}
- ]
+ ],
+ "Enrich": [ "FromLogContext", "WithThreadId" ]
}
}
diff --git a/Jellyfin.Server/SocketSharp/HttpFile.cs b/Jellyfin.Server/SocketSharp/HttpFile.cs
deleted file mode 100644
index 448b666b6..000000000
--- a/Jellyfin.Server/SocketSharp/HttpFile.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System.IO;
-using MediaBrowser.Model.Services;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public class HttpFile : IHttpFile
- {
- public string Name { get; set; }
-
- public string FileName { get; set; }
-
- public long ContentLength { get; set; }
-
- public string ContentType { get; set; }
-
- public Stream InputStream { get; set; }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/HttpPostedFile.cs b/Jellyfin.Server/SocketSharp/HttpPostedFile.cs
deleted file mode 100644
index f38ed848e..000000000
--- a/Jellyfin.Server/SocketSharp/HttpPostedFile.cs
+++ /dev/null
@@ -1,204 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-public sealed class HttpPostedFile : IDisposable
-{
- private string _name;
- private string _contentType;
- private Stream _stream;
- private bool _disposed = false;
-
- internal HttpPostedFile(string name, string content_type, Stream base_stream, long offset, long length)
- {
- _name = name;
- _contentType = content_type;
- _stream = new ReadSubStream(base_stream, offset, length);
- }
-
- public string ContentType => _contentType;
-
- public int ContentLength => (int)_stream.Length;
-
- public string FileName => _name;
-
- public Stream InputStream => _stream;
-
- /// <summary>
- /// Releases the unmanaged resources and disposes of the managed resources used.
- /// </summary>
- public void Dispose()
- {
- if (_disposed)
- {
- return;
- }
-
- _stream.Dispose();
- _stream = null;
-
- _name = null;
- _contentType = null;
-
- _disposed = true;
- }
-
- private class ReadSubStream : Stream
- {
- private Stream _stream;
- private long _offset;
- private long _end;
- private long _position;
-
- public ReadSubStream(Stream s, long offset, long length)
- {
- _stream = s;
- _offset = offset;
- _end = offset + length;
- _position = offset;
- }
-
- public override void Flush()
- {
- }
-
- public override int Read(byte[] buffer, int dest_offset, int count)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
-
- if (dest_offset < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(dest_offset), "< 0");
- }
-
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count), "< 0");
- }
-
- int len = buffer.Length;
- if (dest_offset > len)
- {
- throw new ArgumentException("destination offset is beyond array size", nameof(dest_offset));
- }
-
- // reordered to avoid possible integer overflow
- if (dest_offset > len - count)
- {
- throw new ArgumentException("Reading would overrun buffer", nameof(count));
- }
-
- if (count > _end - _position)
- {
- count = (int)(_end - _position);
- }
-
- if (count <= 0)
- {
- return 0;
- }
-
- _stream.Position = _position;
- int result = _stream.Read(buffer, dest_offset, count);
- if (result > 0)
- {
- _position += result;
- }
- else
- {
- _position = _end;
- }
-
- return result;
- }
-
- public override int ReadByte()
- {
- if (_position >= _end)
- {
- return -1;
- }
-
- _stream.Position = _position;
- int result = _stream.ReadByte();
- if (result < 0)
- {
- _position = _end;
- }
- else
- {
- _position++;
- }
-
- return result;
- }
-
- public override long Seek(long d, SeekOrigin origin)
- {
- long real;
- switch (origin)
- {
- case SeekOrigin.Begin:
- real = _offset + d;
- break;
- case SeekOrigin.End:
- real = _end + d;
- break;
- case SeekOrigin.Current:
- real = _position + d;
- break;
- default:
- throw new ArgumentException("Unknown SeekOrigin value", nameof(origin));
- }
-
- long virt = real - _offset;
- if (virt < 0 || virt > Length)
- {
- throw new ArgumentException("Invalid position", nameof(d));
- }
-
- _position = _stream.Seek(real, SeekOrigin.Begin);
- return _position;
- }
-
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new NotSupportedException();
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => true;
-
- public override bool CanWrite => false;
-
- public override long Length => _end - _offset;
-
- public override long Position
- {
- get => _position - _offset;
- set
- {
- if (value > Length)
- {
- throw new ArgumentOutOfRangeException(nameof(value));
- }
-
- _position = Seek(value, SeekOrigin.Begin);
- }
- }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/RequestMono.cs b/Jellyfin.Server/SocketSharp/RequestMono.cs
deleted file mode 100644
index f2a08c9ae..000000000
--- a/Jellyfin.Server/SocketSharp/RequestMono.cs
+++ /dev/null
@@ -1,680 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public partial class WebSocketSharpRequest : IHttpRequest
- {
- internal static string GetParameter(string header, string attr)
- {
- int ap = header.IndexOf(attr, StringComparison.Ordinal);
- if (ap == -1)
- {
- return null;
- }
-
- ap += attr.Length;
- if (ap >= header.Length)
- {
- return null;
- }
-
- char ending = header[ap];
- if (ending != '"')
- {
- ending = ' ';
- }
-
- int end = header.IndexOf(ending, ap + 1);
- if (end == -1)
- {
- return ending == '"' ? null : header.Substring(ap);
- }
-
- return header.Substring(ap + 1, end - ap - 1);
- }
-
- private async Task LoadMultiPart(WebROCollection form)
- {
- string boundary = GetParameter(ContentType, "; boundary=");
- if (boundary == null)
- {
- return;
- }
-
- using (var requestStream = InputStream)
- {
- // DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
- // Not ending with \r\n?
- var ms = new MemoryStream(32 * 1024);
- await requestStream.CopyToAsync(ms).ConfigureAwait(false);
-
- var input = ms;
- ms.WriteByte((byte)'\r');
- ms.WriteByte((byte)'\n');
-
- input.Position = 0;
-
- // Uncomment to debug
- // var content = new StreamReader(ms).ReadToEnd();
- // Console.WriteLine(boundary + "::" + content);
- // input.Position = 0;
-
- var multi_part = new HttpMultipart(input, boundary, ContentEncoding);
-
- HttpMultipart.Element e;
- while ((e = multi_part.ReadNextElement()) != null)
- {
- if (e.Filename == null)
- {
- byte[] copy = new byte[e.Length];
-
- input.Position = e.Start;
- input.Read(copy, 0, (int)e.Length);
-
- form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
- }
- else
- {
- // We use a substream, as in 2.x we will support large uploads streamed to disk,
- var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
- files[e.Name] = sub;
- }
- }
- }
- }
-
- public async Task<QueryParamCollection> GetFormData()
- {
- var form = new WebROCollection();
- files = new Dictionary<string, HttpPostedFile>();
-
- if (IsContentType("multipart/form-data", true))
- {
- await LoadMultiPart(form).ConfigureAwait(false);
- }
- else if (IsContentType("application/x-www-form-urlencoded", true))
- {
- await LoadWwwForm(form).ConfigureAwait(false);
- }
-
-#if NET_4_0
- if (validateRequestNewMode && !checked_form) {
- // Setting this before calling the validator prevents
- // possible endless recursion
- checked_form = true;
- ValidateNameValueCollection("Form", query_string_nvc, RequestValidationSource.Form);
- } else
-#endif
- if (validate_form && !checked_form)
- {
- checked_form = true;
- ValidateNameValueCollection("Form", form);
- }
-
- return form;
- }
-
- public string Accept => string.IsNullOrEmpty(request.Headers["Accept"]) ? null : request.Headers["Accept"];
-
- public string Authorization => string.IsNullOrEmpty(request.Headers["Authorization"]) ? null : request.Headers["Authorization"];
-
- protected bool validate_cookies { get; set; }
- protected bool validate_query_string { get; set; }
- protected bool validate_form { get; set; }
- protected bool checked_cookies { get; set; }
- protected bool checked_query_string { get; set; }
- protected bool checked_form { get; set; }
-
- private static void ThrowValidationException(string name, string key, string value)
- {
- string v = "\"" + value + "\"";
- if (v.Length > 20)
- {
- v = v.Substring(0, 16) + "...\"";
- }
-
- string msg = string.Format(
- CultureInfo.InvariantCulture,
- "A potentially dangerous Request.{0} value was detected from the client ({1}={2}).",
- name,
- key,
- v);
-
- throw new Exception(msg);
- }
-
- private static void ValidateNameValueCollection(string name, QueryParamCollection coll)
- {
- if (coll == null)
- {
- return;
- }
-
- foreach (var pair in coll)
- {
- var key = pair.Name;
- var val = pair.Value;
- if (val != null && val.Length > 0 && IsInvalidString(val))
- {
- ThrowValidationException(name, key, val);
- }
- }
- }
-
- internal static bool IsInvalidString(string val)
- => IsInvalidString(val, out var validationFailureIndex);
-
- internal static bool IsInvalidString(string val, out int validationFailureIndex)
- {
- validationFailureIndex = 0;
-
- int len = val.Length;
- if (len < 2)
- {
- return false;
- }
-
- char current = val[0];
- for (int idx = 1; idx < len; idx++)
- {
- char next = val[idx];
-
- // See http://secunia.com/advisories/14325
- if (current == '<' || current == '\xff1c')
- {
- if (next == '!' || next < ' '
- || (next >= 'a' && next <= 'z')
- || (next >= 'A' && next <= 'Z'))
- {
- validationFailureIndex = idx - 1;
- return true;
- }
- }
- else if (current == '&' && next == '#')
- {
- validationFailureIndex = idx - 1;
- return true;
- }
-
- current = next;
- }
-
- return false;
- }
-
- public void ValidateInput()
- {
- validate_cookies = true;
- validate_query_string = true;
- validate_form = true;
- }
-
- private bool IsContentType(string ct, bool starts_with)
- {
- if (ct == null || ContentType == null)
- {
- return false;
- }
-
- if (starts_with)
- {
- return ContentType.StartsWith(ct, StringComparison.OrdinalIgnoreCase);
- }
-
- return string.Equals(ContentType, ct, StringComparison.OrdinalIgnoreCase);
- }
-
- private async Task LoadWwwForm(WebROCollection form)
- {
- using (var input = InputStream)
- {
- using (var ms = new MemoryStream())
- {
- await input.CopyToAsync(ms).ConfigureAwait(false);
- ms.Position = 0;
-
- using (var s = new StreamReader(ms, ContentEncoding))
- {
- var key = new StringBuilder();
- var value = new StringBuilder();
- int c;
-
- while ((c = s.Read()) != -1)
- {
- if (c == '=')
- {
- value.Length = 0;
- while ((c = s.Read()) != -1)
- {
- if (c == '&')
- {
- AddRawKeyValue(form, key, value);
- break;
- }
- else
- {
- value.Append((char)c);
- }
- }
-
- if (c == -1)
- {
- AddRawKeyValue(form, key, value);
- return;
- }
- }
- else if (c == '&')
- {
- AddRawKeyValue(form, key, value);
- }
- else
- {
- key.Append((char)c);
- }
- }
-
- if (c == -1)
- {
- AddRawKeyValue(form, key, value);
- }
- }
- }
- }
- }
-
- private static void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
- {
- form.Add(WebUtility.UrlDecode(key.ToString()), WebUtility.UrlDecode(value.ToString()));
-
- key.Length = 0;
- value.Length = 0;
- }
-
- private Dictionary<string, HttpPostedFile> files;
-
- private class WebROCollection : QueryParamCollection
- {
- public override string ToString()
- {
- var result = new StringBuilder();
- foreach (var pair in this)
- {
- if (result.Length > 0)
- {
- result.Append('&');
- }
-
- var key = pair.Name;
- if (key != null && key.Length > 0)
- {
- result.Append(key);
- result.Append('=');
- }
-
- result.Append(pair.Value);
- }
-
- return result.ToString();
- }
- }
- private class HttpMultipart
- {
-
- public class Element
- {
- public string ContentType { get; set; }
-
- public string Name { get; set; }
-
- public string Filename { get; set; }
-
- public Encoding Encoding { get; set; }
-
- public long Start { get; set; }
-
- public long Length { get; set; }
-
- public override string ToString()
- {
- return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
- Start.ToString(CultureInfo.CurrentCulture) + ", Length " + Length.ToString(CultureInfo.CurrentCulture);
- }
- }
-
- private const byte LF = (byte)'\n';
-
- private const byte CR = (byte)'\r';
-
- private Stream data;
-
- private string boundary;
-
- private byte[] boundaryBytes;
-
- private byte[] buffer;
-
- private bool atEof;
-
- private Encoding encoding;
-
- private StringBuilder sb;
-
- // See RFC 2046
- // In the case of multipart entities, in which one or more different
- // sets of data are combined in a single body, a "multipart" media type
- // field must appear in the entity's header. The body must then contain
- // one or more body parts, each preceded by a boundary delimiter line,
- // and the last one followed by a closing boundary delimiter line.
- // After its boundary delimiter line, each body part then consists of a
- // header area, a blank line, and a body area. Thus a body part is
- // similar to an RFC 822 message in syntax, but different in meaning.
-
- public HttpMultipart(Stream data, string b, Encoding encoding)
- {
- this.data = data;
- boundary = b;
- boundaryBytes = encoding.GetBytes(b);
- buffer = new byte[boundaryBytes.Length + 2]; // CRLF or '--'
- this.encoding = encoding;
- sb = new StringBuilder();
- }
-
- public Element ReadNextElement()
- {
- if (atEof || ReadBoundary())
- {
- return null;
- }
-
- var elem = new Element();
- string header;
- while ((header = ReadHeaders()) != null)
- {
- if (header.StartsWith("Content-Disposition:", StringComparison.OrdinalIgnoreCase))
- {
- elem.Name = GetContentDispositionAttribute(header, "name");
- elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
- }
- else if (header.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase))
- {
- elem.ContentType = header.Substring("Content-Type:".Length).Trim();
- elem.Encoding = GetEncoding(elem.ContentType);
- }
- }
-
- long start = data.Position;
- elem.Start = start;
- long pos = MoveToNextBoundary();
- if (pos == -1)
- {
- return null;
- }
-
- elem.Length = pos - start;
- return elem;
- }
-
- private string ReadLine()
- {
- // CRLF or LF are ok as line endings.
- bool got_cr = false;
- int b = 0;
- sb.Length = 0;
- while (true)
- {
- b = data.ReadByte();
- if (b == -1)
- {
- return null;
- }
-
- if (b == LF)
- {
- break;
- }
-
- got_cr = b == CR;
- sb.Append((char)b);
- }
-
- if (got_cr)
- {
- sb.Length--;
- }
-
- return sb.ToString();
- }
-
- private static string GetContentDispositionAttribute(string l, string name)
- {
- int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
- if (idx < 0)
- {
- return null;
- }
-
- int begin = idx + name.Length + "=\"".Length;
- int end = l.IndexOf('"', begin);
- if (end < 0)
- {
- return null;
- }
-
- if (begin == end)
- {
- return string.Empty;
- }
-
- return l.Substring(begin, end - begin);
- }
-
- private string GetContentDispositionAttributeWithEncoding(string l, string name)
- {
- int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
- if (idx < 0)
- {
- return null;
- }
-
- int begin = idx + name.Length + "=\"".Length;
- int end = l.IndexOf('"', begin);
- if (end < 0)
- {
- return null;
- }
-
- if (begin == end)
- {
- return string.Empty;
- }
-
- string temp = l.Substring(begin, end - begin);
- byte[] source = new byte[temp.Length];
- for (int i = temp.Length - 1; i >= 0; i--)
- {
- source[i] = (byte)temp[i];
- }
-
- return encoding.GetString(source, 0, source.Length);
- }
-
- private bool ReadBoundary()
- {
- try
- {
- string line;
- do
- {
- line = ReadLine();
- }
- while (line.Length == 0);
-
- if (line[0] != '-' || line[1] != '-')
- {
- return false;
- }
-
- if (!line.EndsWith(boundary, StringComparison.Ordinal))
- {
- return true;
- }
- }
- catch
- {
-
- }
-
- return false;
- }
-
- private string ReadHeaders()
- {
- string s = ReadLine();
- if (s.Length == 0)
- {
- return null;
- }
-
- return s;
- }
-
- private static bool CompareBytes(byte[] orig, byte[] other)
- {
- for (int i = orig.Length - 1; i >= 0; i--)
- {
- if (orig[i] != other[i])
- {
- return false;
- }
- }
-
- return true;
- }
-
- private long MoveToNextBoundary()
- {
- long retval = 0;
- bool got_cr = false;
-
- int state = 0;
- int c = data.ReadByte();
- while (true)
- {
- if (c == -1)
- {
- return -1;
- }
-
- if (state == 0 && c == LF)
- {
- retval = data.Position - 1;
- if (got_cr)
- {
- retval--;
- }
-
- state = 1;
- c = data.ReadByte();
- }
- else if (state == 0)
- {
- got_cr = c == CR;
- c = data.ReadByte();
- }
- else if (state == 1 && c == '-')
- {
- c = data.ReadByte();
- if (c == -1)
- {
- return -1;
- }
-
- if (c != '-')
- {
- state = 0;
- got_cr = false;
- continue; // no ReadByte() here
- }
-
- int nread = data.Read(buffer, 0, buffer.Length);
- int bl = buffer.Length;
- if (nread != bl)
- {
- return -1;
- }
-
- if (!CompareBytes(boundaryBytes, buffer))
- {
- state = 0;
- data.Position = retval + 2;
- if (got_cr)
- {
- data.Position++;
- got_cr = false;
- }
-
- c = data.ReadByte();
- continue;
- }
-
- if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
- {
- atEof = true;
- }
- else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
- {
- state = 0;
- data.Position = retval + 2;
- if (got_cr)
- {
- data.Position++;
- got_cr = false;
- }
-
- c = data.ReadByte();
- continue;
- }
-
- data.Position = retval + 2;
- if (got_cr)
- {
- data.Position++;
- }
-
- break;
- }
- else
- {
- // state == 1
- state = 0; // no ReadByte() here
- }
- }
-
- return retval;
- }
-
- private static string StripPath(string path)
- {
- if (path == null || path.Length == 0)
- {
- return path;
- }
-
- if (path.IndexOf(":\\", StringComparison.Ordinal) != 1
- && !path.StartsWith("\\\\", StringComparison.Ordinal))
- {
- return path;
- }
-
- return path.Substring(path.LastIndexOf('\\') + 1);
- }
- }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/SharpWebSocket.cs b/Jellyfin.Server/SocketSharp/SharpWebSocket.cs
deleted file mode 100644
index 9b0951857..000000000
--- a/Jellyfin.Server/SocketSharp/SharpWebSocket.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-using System;
-using System.Net.WebSockets;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Net;
-using Microsoft.Extensions.Logging;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public class SharpWebSocket : IWebSocket
- {
- /// <summary>
- /// The logger
- /// </summary>
- private readonly ILogger _logger;
-
- public event EventHandler<EventArgs> Closed;
-
- /// <summary>
- /// Gets or sets the web socket.
- /// </summary>
- /// <value>The web socket.</value>
- private SocketHttpListener.WebSocket WebSocket { get; set; }
-
- private TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
- private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
- private bool _disposed = false;
-
- public SharpWebSocket(SocketHttpListener.WebSocket socket, ILogger logger)
- {
- if (socket == null)
- {
- throw new ArgumentNullException(nameof(socket));
- }
-
- if (logger == null)
- {
- throw new ArgumentNullException(nameof(logger));
- }
-
- _logger = logger;
- WebSocket = socket;
-
- socket.OnMessage += OnSocketMessage;
- socket.OnClose += OnSocketClose;
- socket.OnError += OnSocketError;
- }
-
- public Task ConnectAsServerAsync()
- => WebSocket.ConnectAsServer();
-
- public Task StartReceive()
- {
- return _taskCompletionSource.Task;
- }
-
- private void OnSocketError(object sender, SocketHttpListener.ErrorEventArgs e)
- {
- _logger.LogError("Error in SharpWebSocket: {Message}", e.Message ?? string.Empty);
-
- // Closed?.Invoke(this, EventArgs.Empty);
- }
-
- private void OnSocketClose(object sender, SocketHttpListener.CloseEventArgs e)
- {
- _taskCompletionSource.TrySetResult(true);
-
- Closed?.Invoke(this, EventArgs.Empty);
- }
-
- private void OnSocketMessage(object sender, SocketHttpListener.MessageEventArgs e)
- {
- if (OnReceiveBytes != null)
- {
- OnReceiveBytes(e.RawData);
- }
- }
-
- /// <summary>
- /// Gets or sets the state.
- /// </summary>
- /// <value>The state.</value>
- public WebSocketState State => WebSocket.ReadyState;
-
- /// <summary>
- /// Sends the async.
- /// </summary>
- /// <param name="bytes">The bytes.</param>
- /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
- {
- return WebSocket.SendAsync(bytes);
- }
-
- /// <summary>
- /// Sends the asynchronous.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
- {
- return WebSocket.SendAsync(text);
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- 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 (_disposed)
- {
- return;
- }
-
- if (dispose)
- {
- WebSocket.OnMessage -= OnSocketMessage;
- WebSocket.OnClose -= OnSocketClose;
- WebSocket.OnError -= OnSocketError;
-
- _cancellationTokenSource.Cancel();
-
- WebSocket.CloseAsync().GetAwaiter().GetResult();
- }
-
- _disposed = true;
- }
-
- /// <summary>
- /// Gets or sets the receive action.
- /// </summary>
- /// <value>The receive action.</value>
- public Action<byte[]> OnReceiveBytes { get; set; }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs
deleted file mode 100644
index 736f9feef..000000000
--- a/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs
+++ /dev/null
@@ -1,263 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.HttpServer;
-using Emby.Server.Implementations.Net;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-using SocketHttpListener.Net;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public class WebSocketSharpListener : IHttpListener
- {
- private HttpListener _listener;
-
- private readonly ILogger _logger;
- private readonly X509Certificate _certificate;
- private readonly IStreamHelper _streamHelper;
- private readonly INetworkManager _networkManager;
- private readonly ISocketFactory _socketFactory;
- private readonly ICryptoProvider _cryptoProvider;
- private readonly IFileSystem _fileSystem;
- private readonly bool _enableDualMode;
- private readonly IEnvironmentInfo _environment;
-
- private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
- private CancellationToken _disposeCancellationToken;
-
- public WebSocketSharpListener(
- ILogger logger,
- X509Certificate certificate,
- IStreamHelper streamHelper,
- INetworkManager networkManager,
- ISocketFactory socketFactory,
- ICryptoProvider cryptoProvider,
- bool enableDualMode,
- IFileSystem fileSystem,
- IEnvironmentInfo environment)
- {
- _logger = logger;
- _certificate = certificate;
- _streamHelper = streamHelper;
- _networkManager = networkManager;
- _socketFactory = socketFactory;
- _cryptoProvider = cryptoProvider;
- _enableDualMode = enableDualMode;
- _fileSystem = fileSystem;
- _environment = environment;
-
- _disposeCancellationToken = _disposeCancellationTokenSource.Token;
- }
-
- public Func<Exception, IRequest, bool, bool, Task> ErrorHandler { get; set; }
- public Func<IHttpRequest, string, string, string, CancellationToken, Task> RequestHandler { get; set; }
-
- public Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
-
- public Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
-
- public void Start(IEnumerable<string> urlPrefixes)
- {
- if (_listener == null)
- {
- _listener = new HttpListener(_logger, _cryptoProvider, _socketFactory, _streamHelper, _fileSystem, _environment);
- }
-
- _listener.EnableDualMode = _enableDualMode;
-
- if (_certificate != null)
- {
- _listener.LoadCert(_certificate);
- }
-
- _logger.LogInformation("Adding HttpListener prefixes {Prefixes}", urlPrefixes);
- _listener.Prefixes.AddRange(urlPrefixes);
-
- _listener.OnContext = async c => await InitTask(c, _disposeCancellationToken).ConfigureAwait(false);
-
- _listener.Start();
- }
-
- private static void LogRequest(ILogger logger, HttpListenerRequest request)
- {
- var url = request.Url.ToString();
-
- logger.LogInformation(
- "{0} {1}. UserAgent: {2}",
- request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod,
- url,
- request.UserAgent ?? string.Empty);
- }
-
- private Task InitTask(HttpListenerContext context, CancellationToken cancellationToken)
- {
- IHttpRequest httpReq = null;
- var request = context.Request;
-
- try
- {
- if (request.IsWebSocketRequest)
- {
- LogRequest(_logger, request);
-
- return ProcessWebSocketRequest(context);
- }
-
- httpReq = GetRequest(context);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error processing request");
-
- httpReq = httpReq ?? GetRequest(context);
- return ErrorHandler(ex, httpReq, true, true);
- }
-
- var uri = request.Url;
-
- return RequestHandler(httpReq, uri.OriginalString, uri.Host, uri.LocalPath, cancellationToken);
- }
-
- private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
- {
- try
- {
- var endpoint = ctx.Request.RemoteEndPoint.ToString();
- var url = ctx.Request.RawUrl;
-
- var queryString = ctx.Request.QueryString;
-
- var connectingArgs = new WebSocketConnectingEventArgs
- {
- Url = url,
- QueryString = queryString,
- Endpoint = endpoint
- };
-
- WebSocketConnecting?.Invoke(connectingArgs);
-
- if (connectingArgs.AllowConnection)
- {
- _logger.LogDebug("Web socket connection allowed");
-
- var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
-
- if (WebSocketConnected != null)
- {
- var socket = new SharpWebSocket(webSocketContext.WebSocket, _logger);
- await socket.ConnectAsServerAsync().ConfigureAwait(false);
-
- WebSocketConnected(new WebSocketConnectEventArgs
- {
- Url = url,
- QueryString = queryString,
- WebSocket = socket,
- Endpoint = endpoint
- });
-
- await ReceiveWebSocketAsync(ctx, socket).ConfigureAwait(false);
- }
- }
- else
- {
- _logger.LogWarning("Web socket connection not allowed");
- ctx.Response.StatusCode = 401;
- ctx.Response.Close();
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "AcceptWebSocketAsync error");
- ctx.Response.StatusCode = 500;
- ctx.Response.Close();
- }
- }
-
- private async Task ReceiveWebSocketAsync(HttpListenerContext ctx, SharpWebSocket socket)
- {
- try
- {
- await socket.StartReceive().ConfigureAwait(false);
- }
- finally
- {
- TryClose(ctx, 200);
- }
- }
-
- private void TryClose(HttpListenerContext ctx, int statusCode)
- {
- try
- {
- ctx.Response.StatusCode = statusCode;
- ctx.Response.Close();
- }
- catch (ObjectDisposedException)
- {
- // TODO: Investigate and properly fix.
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error closing web socket response");
- }
- }
-
- private IHttpRequest GetRequest(HttpListenerContext httpContext)
- {
- var urlSegments = httpContext.Request.Url.Segments;
-
- var operationName = urlSegments[urlSegments.Length - 1];
-
- var req = new WebSocketSharpRequest(httpContext, operationName, _logger);
-
- return req;
- }
-
- public Task Stop()
- {
- _disposeCancellationTokenSource.Cancel();
- _listener?.Close();
-
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// Releases the unmanaged resources and disposes of the managed resources used.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- private bool _disposed;
-
- /// <summary>
- /// Releases the unmanaged resources and disposes of the managed resources used.
- /// </summary>
- /// <param name="disposing">Whether or not the managed resources should be disposed</param>
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed)
- {
- return;
- }
-
- if (disposing)
- {
- Stop().GetAwaiter().GetResult();
- }
-
- _disposed = true;
- }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs
deleted file mode 100644
index 6458707d9..000000000
--- a/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs
+++ /dev/null
@@ -1,534 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using SocketHttpListener.Net;
-using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
-using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
-using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
-using IResponse = MediaBrowser.Model.Services.IResponse;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public partial class WebSocketSharpRequest : IHttpRequest
- {
- private readonly HttpListenerRequest request;
- private readonly IHttpResponse response;
-
- public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, ILogger logger)
- {
- this.OperationName = operationName;
- this.request = httpContext.Request;
- this.response = new WebSocketSharpResponse(logger, httpContext.Response, this);
-
- // HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
- }
-
- public HttpListenerRequest HttpRequest => request;
-
- public object OriginalRequest => request;
-
- public IResponse Response => response;
-
- public IHttpResponse HttpResponse => response;
-
- public string OperationName { get; set; }
-
- public object Dto { get; set; }
-
- public string RawUrl => request.RawUrl;
-
- public string AbsoluteUri => request.Url.AbsoluteUri.TrimEnd('/');
-
- public string UserHostAddress => request.UserHostAddress;
-
- public string XForwardedFor
- => string.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"];
-
- public int? XForwardedPort
- => string.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
-
- public string XForwardedProtocol => string.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"];
-
- public string XRealIp => string.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"];
-
- private string remoteIp;
- public string RemoteIp =>
- remoteIp ??
- (remoteIp = CheckBadChars(XForwardedFor) ??
- NormalizeIp(CheckBadChars(XRealIp) ??
- (request.RemoteEndPoint != null ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
-
- private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
-
- // CheckBadChars - throws on invalid chars to be not found in header name/value
- internal static string CheckBadChars(string name)
- {
- if (name == null || name.Length == 0)
- {
- return name;
- }
-
- // VALUE check
- // Trim spaces from both ends
- name = name.Trim(HttpTrimCharacters);
-
- // First, check for correctly formed multi-line value
- // Second, check for absence of CTL characters
- int crlf = 0;
- for (int i = 0; i < name.Length; ++i)
- {
- char c = (char)(0x000000ff & (uint)name[i]);
- switch (crlf)
- {
- case 0:
- {
- if (c == '\r')
- {
- crlf = 1;
- }
- else if (c == '\n')
- {
- // Technically this is bad HTTP. But it would be a breaking change to throw here.
- // Is there an exploit?
- crlf = 2;
- }
- else if (c == 127 || (c < ' ' && c != '\t'))
- {
- throw new ArgumentException("net_WebHeaderInvalidControlChars");
- }
-
- break;
- }
-
- case 1:
- {
- if (c == '\n')
- {
- crlf = 2;
- break;
- }
-
- throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
- }
-
- case 2:
- {
- if (c == ' ' || c == '\t')
- {
- crlf = 0;
- break;
- }
-
- throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
- }
- }
- }
-
- if (crlf != 0)
- {
- throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
- }
-
- return name;
- }
-
- internal static bool ContainsNonAsciiChars(string token)
- {
- for (int i = 0; i < token.Length; ++i)
- {
- if ((token[i] < 0x20) || (token[i] > 0x7e))
- {
- return true;
- }
- }
-
- return false;
- }
-
- private string NormalizeIp(string ip)
- {
- if (!string.IsNullOrWhiteSpace(ip))
- {
- // Handle ipv4 mapped to ipv6
- const string srch = "::ffff:";
- var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
- if (index == 0)
- {
- ip = ip.Substring(srch.Length);
- }
- }
-
- return ip;
- }
-
- public bool IsSecureConnection => request.IsSecureConnection || XForwardedProtocol == "https";
-
- public string[] AcceptTypes => request.AcceptTypes;
-
- private Dictionary<string, object> items;
- public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
-
- private string responseContentType;
- public string ResponseContentType
- {
- get =>
- responseContentType
- ?? (responseContentType = GetResponseContentType(this));
- set => this.responseContentType = value;
- }
-
- public const string FormUrlEncoded = "application/x-www-form-urlencoded";
- public const string MultiPartFormData = "multipart/form-data";
- public static string GetResponseContentType(IRequest httpReq)
- {
- var specifiedContentType = GetQueryStringContentType(httpReq);
- if (!string.IsNullOrEmpty(specifiedContentType))
- {
- return specifiedContentType;
- }
-
- const string serverDefaultContentType = "application/json";
-
- var acceptContentTypes = httpReq.AcceptTypes;
- string defaultContentType = null;
- if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
- {
- defaultContentType = serverDefaultContentType;
- }
-
- var acceptsAnything = false;
- var hasDefaultContentType = defaultContentType != null;
- if (acceptContentTypes != null)
- {
- foreach (var acceptsType in acceptContentTypes)
- {
- // TODO: @bond move to Span when Span.Split lands
- // https://github.com/dotnet/corefx/issues/26528
- var contentType = acceptsType?.Split(';')[0].Trim();
- acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
-
- if (acceptsAnything)
- {
- break;
- }
- }
-
- if (acceptsAnything)
- {
- if (hasDefaultContentType)
- {
- return defaultContentType;
- }
- else
- {
- return serverDefaultContentType;
- }
- }
- }
-
- if (acceptContentTypes == null && httpReq.ContentType == Soap11)
- {
- return Soap11;
- }
-
- // We could also send a '406 Not Acceptable', but this is allowed also
- return serverDefaultContentType;
- }
-
- public const string Soap11 = "text/xml; charset=utf-8";
-
- public static bool HasAnyOfContentTypes(IRequest request, params string[] contentTypes)
- {
- if (contentTypes == null || request.ContentType == null)
- {
- return false;
- }
-
- foreach (var contentType in contentTypes)
- {
- if (IsContentType(request, contentType))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsContentType(IRequest request, string contentType)
- {
- return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
- }
-
- private static string GetQueryStringContentType(IRequest httpReq)
- {
- ReadOnlySpan<char> format = httpReq.QueryString["format"];
- if (format == null)
- {
- const int formatMaxLength = 4;
- ReadOnlySpan<char> pi = httpReq.PathInfo;
- if (pi == null || pi.Length <= formatMaxLength)
- {
- return null;
- }
-
- if (pi[0] == '/')
- {
- pi = pi.Slice(1);
- }
-
- format = LeftPart(pi, '/');
- if (format.Length > formatMaxLength)
- {
- return null;
- }
- }
-
- format = LeftPart(format, '.');
- if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
- {
- return "application/json";
- }
- else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
- {
- return "application/xml";
- }
-
- return null;
- }
-
- public static string LeftPart(string strVal, char needle)
- {
- if (strVal == null)
- {
- return null;
- }
-
- var pos = strVal.IndexOf(needle, StringComparison.Ordinal);
- return pos == -1 ? strVal : strVal.Substring(0, pos);
- }
-
- public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
- {
- if (strVal == null)
- {
- return null;
- }
-
- var pos = strVal.IndexOf(needle);
- return pos == -1 ? strVal : strVal.Slice(0, pos);
- }
-
- public static string HandlerFactoryPath;
-
- private string pathInfo;
- public string PathInfo
- {
- get
- {
- if (this.pathInfo == null)
- {
- var mode = HandlerFactoryPath;
-
- var pos = request.RawUrl.IndexOf('?', StringComparison.Ordinal);
- if (pos != -1)
- {
- var path = request.RawUrl.Substring(0, pos);
- this.pathInfo = GetPathInfo(
- path,
- mode,
- mode ?? string.Empty);
- }
- else
- {
- this.pathInfo = request.RawUrl;
- }
-
- this.pathInfo = System.Net.WebUtility.UrlDecode(pathInfo);
- this.pathInfo = NormalizePathInfo(pathInfo, mode);
- }
-
- return this.pathInfo;
- }
- }
-
- private static string GetPathInfo(string fullPath, string mode, string appPath)
- {
- var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
- if (!string.IsNullOrEmpty(pathInfo))
- {
- return pathInfo;
- }
-
- // Wildcard mode relies on this to work out the handlerPath
- pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
- if (!string.IsNullOrEmpty(pathInfo))
- {
- return pathInfo;
- }
-
- return fullPath;
- }
-
- private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
- {
- if (mappedPathRoot == null)
- {
- return null;
- }
-
- var sbPathInfo = new StringBuilder();
- var fullPathParts = fullPath.Split('/');
- var mappedPathRootParts = mappedPathRoot.Split('/');
- var fullPathIndexOffset = mappedPathRootParts.Length - 1;
- var pathRootFound = false;
-
- for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
- {
- if (pathRootFound)
- {
- sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
- }
- else if (fullPathIndex - fullPathIndexOffset >= 0)
- {
- pathRootFound = true;
- for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
- {
- if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
- {
- pathRootFound = false;
- break;
- }
- }
- }
- }
-
- if (!pathRootFound)
- {
- return null;
- }
-
- var path = sbPathInfo.ToString();
- return path.Length > 1 ? path.TrimEnd('/') : "/";
- }
-
- private Dictionary<string, System.Net.Cookie> cookies;
- public IDictionary<string, System.Net.Cookie> Cookies
- {
- get
- {
- if (cookies == null)
- {
- cookies = new Dictionary<string, System.Net.Cookie>();
- foreach (var cookie in this.request.Cookies)
- {
- var httpCookie = (System.Net.Cookie)cookie;
- cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
- }
- }
-
- return cookies;
- }
- }
-
- public string UserAgent => request.UserAgent;
-
- public QueryParamCollection Headers => request.Headers;
-
- private QueryParamCollection queryString;
- public QueryParamCollection QueryString => queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query));
-
- public bool IsLocal => request.IsLocal;
-
- private string httpMethod;
- public string HttpMethod =>
- httpMethod
- ?? (httpMethod = request.HttpMethod);
-
- public string Verb => HttpMethod;
-
- public string ContentType => request.ContentType;
-
- private Encoding contentEncoding;
- public Encoding ContentEncoding
- {
- get => contentEncoding ?? request.ContentEncoding;
- set => contentEncoding = value;
- }
-
- public Uri UrlReferrer => request.UrlReferrer;
-
- public static Encoding GetEncoding(string contentTypeHeader)
- {
- var param = GetParameter(contentTypeHeader, "charset=");
- if (param == null)
- {
- return null;
- }
-
- try
- {
- return Encoding.GetEncoding(param);
- }
- catch (ArgumentException)
- {
- return null;
- }
- }
-
- public Stream InputStream => request.InputStream;
-
- public long ContentLength => request.ContentLength64;
-
- private IHttpFile[] httpFiles;
- public IHttpFile[] Files
- {
- get
- {
- if (httpFiles == null)
- {
- if (files == null)
- {
- return httpFiles = Array.Empty<IHttpFile>();
- }
-
- httpFiles = new IHttpFile[files.Count];
- var i = 0;
- foreach (var pair in files)
- {
- var reqFile = pair.Value;
- httpFiles[i] = new HttpFile
- {
- ContentType = reqFile.ContentType,
- ContentLength = reqFile.ContentLength,
- FileName = reqFile.FileName,
- InputStream = reqFile.InputStream,
- };
- i++;
- }
- }
-
- return httpFiles;
- }
- }
-
- public static string NormalizePathInfo(string pathInfo, string handlerPath)
- {
- if (handlerPath != null)
- {
- var trimmed = pathInfo.TrimStart('/');
- if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
- {
- return trimmed.Substring(handlerPath.Length);
- }
- }
-
- return pathInfo;
- }
- }
-}
diff --git a/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs
deleted file mode 100644
index cf5aee5d4..000000000
--- a/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs
+++ /dev/null
@@ -1,181 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse;
-using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
-using IRequest = MediaBrowser.Model.Services.IRequest;
-
-namespace Jellyfin.Server.SocketSharp
-{
- public class WebSocketSharpResponse : IHttpResponse
- {
- private readonly ILogger _logger;
-
- private readonly HttpListenerResponse _response;
-
- public WebSocketSharpResponse(ILogger logger, HttpListenerResponse response, IRequest request)
- {
- _logger = logger;
- this._response = response;
- Items = new Dictionary<string, object>();
- Request = request;
- }
-
- public IRequest Request { get; private set; }
-
- public Dictionary<string, object> Items { get; private set; }
-
- public object OriginalResponse => _response;
-
- public int StatusCode
- {
- get => this._response.StatusCode;
- set => this._response.StatusCode = value;
- }
-
- public string StatusDescription
- {
- get => this._response.StatusDescription;
- set => this._response.StatusDescription = value;
- }
-
- public string ContentType
- {
- get => _response.ContentType;
- set => _response.ContentType = value;
- }
-
- public QueryParamCollection Headers => _response.Headers;
-
- private static string AsHeaderValue(Cookie cookie)
- {
- DateTime defaultExpires = DateTime.MinValue;
-
- var path = cookie.Expires == defaultExpires
- ? "/"
- : cookie.Path ?? "/";
-
- var sb = new StringBuilder();
-
- sb.Append($"{cookie.Name}={cookie.Value};path={path}");
-
- if (cookie.Expires != defaultExpires)
- {
- sb.Append($";expires={cookie.Expires:R}");
- }
-
- if (!string.IsNullOrEmpty(cookie.Domain))
- {
- sb.Append($";domain={cookie.Domain}");
- }
-
- if (cookie.Secure)
- {
- sb.Append(";Secure");
- }
-
- if (cookie.HttpOnly)
- {
- sb.Append(";HttpOnly");
- }
-
- return sb.ToString();
- }
-
- public void AddHeader(string name, string value)
- {
- if (string.Equals(name, "Content-Type", StringComparison.OrdinalIgnoreCase))
- {
- ContentType = value;
- return;
- }
-
- _response.AddHeader(name, value);
- }
-
- public string GetHeader(string name)
- {
- return _response.Headers[name];
- }
-
- public void Redirect(string url)
- {
- _response.Redirect(url);
- }
-
- public Stream OutputStream => _response.OutputStream;
-
- public void Close()
- {
- if (!this.IsClosed)
- {
- this.IsClosed = true;
-
- try
- {
- var response = this._response;
-
- var outputStream = response.OutputStream;
-
- // This is needed with compression
- outputStream.Flush();
- outputStream.Dispose();
-
- response.Close();
- }
- catch (SocketException)
- {
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in HttpListenerResponseWrapper");
- }
- }
- }
-
- public bool IsClosed
- {
- get;
- private set;
- }
-
- public void SetContentLength(long contentLength)
- {
- // you can happily set the Content-Length header in Asp.Net
- // but HttpListener will complain if you do - you have to set ContentLength64 on the response.
- // workaround: HttpListener throws "The parameter is incorrect" exceptions when we try to set the Content-Length header
- _response.ContentLength64 = contentLength;
- }
-
- public void SetCookie(Cookie cookie)
- {
- var cookieStr = AsHeaderValue(cookie);
- _response.Headers.Add("Set-Cookie", cookieStr);
- }
-
- public bool SendChunked
- {
- get => _response.SendChunked;
- set => _response.SendChunked = value;
- }
-
- public bool KeepAlive { get; set; }
-
- public void ClearCookies()
- {
- }
-
- public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
- {
- return _response.TransmitFile(path, offset, count, fileShareMode, cancellationToken);
- }
- }
-}
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
new file mode 100644
index 000000000..8085c2630
--- /dev/null
+++ b/Jellyfin.Server/Startup.cs
@@ -0,0 +1,197 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Server.Extensions;
+using Jellyfin.Server.Implementations;
+using Jellyfin.Server.Infrastructure;
+using Jellyfin.Server.Middleware;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Extensions;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
+using Microsoft.AspNetCore.StaticFiles;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.FileProviders;
+using Microsoft.Extensions.Hosting;
+using Prometheus;
+
+namespace Jellyfin.Server
+{
+ /// <summary>
+ /// Startup configuration for the Kestrel webhost.
+ /// </summary>
+ public class Startup
+ {
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+ private readonly IServerApplicationHost _serverApplicationHost;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Startup" /> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">The server configuration manager.</param>
+ /// <param name="serverApplicationHost">The server application host.</param>
+ public Startup(
+ IServerConfigurationManager serverConfigurationManager,
+ IServerApplicationHost serverApplicationHost)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ _serverApplicationHost = serverApplicationHost;
+ }
+
+ /// <summary>
+ /// Configures the service collection for the webhost.
+ /// </summary>
+ /// <param name="services">The service collection.</param>
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddResponseCompression();
+ services.AddHttpContextAccessor();
+ services.AddHttpsRedirection(options =>
+ {
+ options.HttpsPort = _serverApplicationHost.HttpsPort;
+ });
+
+ // TODO remove once this is fixed upstream https://github.com/dotnet/aspnetcore/issues/34371
+ services.AddSingleton<IActionResultExecutor<PhysicalFileResult>, SymlinkFollowingPhysicalFileResultExecutor>();
+ services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration());
+
+ services.AddJellyfinApiSwagger();
+
+ // configure custom legacy authentication
+ services.AddCustomAuthentication();
+
+ services.AddJellyfinApiAuthorization();
+
+ var productHeader = new ProductInfoHeaderValue(
+ _serverApplicationHost.Name.Replace(' ', '-'),
+ _serverApplicationHost.ApplicationVersionString);
+ var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0);
+ var acceptXmlHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Xml, 0.9);
+ var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*", 0.8);
+ Func<IServiceProvider, HttpMessageHandler> defaultHttpClientHandlerDelegate = (_) => new SocketsHttpHandler()
+ {
+ AutomaticDecompression = DecompressionMethods.All,
+ RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8
+ };
+
+ services
+ .AddHttpClient(NamedClient.Default, c =>
+ {
+ c.DefaultRequestHeaders.UserAgent.Add(productHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
+ })
+ .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
+
+ services.AddHttpClient(NamedClient.MusicBrainz, c =>
+ {
+ c.DefaultRequestHeaders.UserAgent.Add(productHeader);
+ c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"({_serverApplicationHost.ApplicationUserAgentAddress})"));
+ c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
+ })
+ .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
+
+ services.AddHealthChecks()
+ .AddDbContextCheck<JellyfinDb>();
+ }
+
+ /// <summary>
+ /// Configures the app builder for the webhost.
+ /// </summary>
+ /// <param name="app">The application builder.</param>
+ /// <param name="env">The webhost environment.</param>
+ /// <param name="appConfig">The application config.</param>
+ public void Configure(
+ IApplicationBuilder app,
+ IWebHostEnvironment env,
+ IConfiguration appConfig)
+ {
+ app.UseBaseUrlRedirection();
+
+ // Wrap rest of configuration so everything only listens on BaseUrl.
+ var config = _serverConfigurationManager.GetNetworkConfiguration();
+ app.Map(config.BaseUrl, mainApp =>
+ {
+ if (env.IsDevelopment())
+ {
+ mainApp.UseDeveloperExceptionPage();
+ }
+
+ mainApp.UseForwardedHeaders();
+ mainApp.UseMiddleware<ExceptionMiddleware>();
+
+ mainApp.UseMiddleware<ResponseTimeMiddleware>();
+
+ mainApp.UseWebSockets();
+
+ mainApp.UseResponseCompression();
+
+ mainApp.UseCors();
+
+ if (config.RequireHttps && _serverApplicationHost.ListenWithHttps)
+ {
+ mainApp.UseHttpsRedirection();
+ }
+
+ // This must be injected before any path related middleware.
+ mainApp.UsePathTrim();
+ mainApp.UseStaticFiles();
+ if (appConfig.HostWebClient())
+ {
+ var extensionProvider = new FileExtensionContentTypeProvider();
+
+ // subtitles octopus requires .data, .mem files.
+ extensionProvider.Mappings.Add(".data", MediaTypeNames.Application.Octet);
+ extensionProvider.Mappings.Add(".mem", MediaTypeNames.Application.Octet);
+ mainApp.UseStaticFiles(new StaticFileOptions
+ {
+ FileProvider = new PhysicalFileProvider(_serverConfigurationManager.ApplicationPaths.WebPath),
+ RequestPath = "/web",
+ ContentTypeProvider = extensionProvider
+ });
+
+ mainApp.UseRobotsRedirection();
+ }
+
+ mainApp.UseAuthentication();
+ mainApp.UseJellyfinApiSwagger(_serverConfigurationManager);
+ mainApp.UseQueryStringDecoding();
+ mainApp.UseRouting();
+ mainApp.UseAuthorization();
+
+ mainApp.UseLanFiltering();
+ mainApp.UseIpBasedAccessValidation();
+ mainApp.UseWebSocketHandler();
+ mainApp.UseServerStartupMessage();
+
+ if (_serverConfigurationManager.Configuration.EnableMetrics)
+ {
+ // Must be registered after any middleware that could change HTTP response codes or the data will be bad
+ mainApp.UseHttpMetrics();
+ }
+
+ mainApp.UseEndpoints(endpoints =>
+ {
+ endpoints.MapControllers();
+ if (_serverConfigurationManager.Configuration.EnableMetrics)
+ {
+ endpoints.MapMetrics("/metrics");
+ }
+
+ endpoints.MapHealthChecks("/health");
+ });
+ });
+ }
+ }
+}
diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs
index 5d3f7b171..a1cecc8c6 100644
--- a/Jellyfin.Server/StartupOptions.cs
+++ b/Jellyfin.Server/StartupOptions.cs
@@ -1,5 +1,8 @@
+using System.Collections.Generic;
using CommandLine;
using Emby.Server.Implementations;
+using Emby.Server.Implementations.Udp;
+using MediaBrowser.Controller.Extensions;
namespace Jellyfin.Server
{
@@ -8,37 +11,95 @@ namespace Jellyfin.Server
/// </summary>
public class StartupOptions : IStartupOptions
{
+ /// <summary>
+ /// Gets or sets the path to the data directory.
+ /// </summary>
+ /// <value>The path to the data directory.</value>
[Option('d', "datadir", Required = false, HelpText = "Path to use for the data folder (database files, etc.).")]
- public string DataDir { get; set; }
+ public string? DataDir { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether the server should not host the web client.
+ /// </summary>
+ [Option("nowebclient", Required = false, HelpText = "Indicates that the web server should not host the web client.")]
+ public bool NoWebClient { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path to the web directory.
+ /// </summary>
+ /// <value>The path to the web directory.</value>
+ [Option('w', "webdir", Required = false, HelpText = "Path to the Jellyfin web UI resources.")]
+ public string? WebDir { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path to the cache directory.
+ /// </summary>
+ /// <value>The path to the cache directory.</value>
[Option('C', "cachedir", Required = false, HelpText = "Path to use for caching.")]
- public string CacheDir { get; set; }
+ public string? CacheDir { get; set; }
+ /// <summary>
+ /// Gets or sets the path to the config directory.
+ /// </summary>
+ /// <value>The path to the config directory.</value>
[Option('c', "configdir", Required = false, HelpText = "Path to use for configuration data (user settings and pictures).")]
- public string ConfigDir { get; set; }
+ public string? ConfigDir { get; set; }
+ /// <summary>
+ /// Gets or sets the path to the log directory.
+ /// </summary>
+ /// <value>The path to the log directory.</value>
[Option('l', "logdir", Required = false, HelpText = "Path to use for writing log files.")]
- public string LogDir { get; set; }
-
- [Option("ffmpeg", Required = false, HelpText = "Path to external FFmpeg executable to use in place of default found in PATH. Must be specified along with --ffprobe.")]
- public string FFmpegPath { get; set; }
+ public string? LogDir { get; set; }
- [Option("ffprobe", Required = false, HelpText = "Path to external FFprobe executable to use in place of default found in PATH. Must be specified along with --ffmpeg.")]
- public string FFprobePath { get; set; }
+ /// <inheritdoc />
+ [Option("ffmpeg", Required = false, HelpText = "Path to external FFmpeg executable to use in place of default found in PATH.")]
+ public string? FFmpegPath { get; set; }
+ /// <inheritdoc />
[Option("service", Required = false, HelpText = "Run as headless service.")]
public bool IsService { get; set; }
- [Option("noautorunwebapp", Required = false, HelpText = "Run headless if startup wizard is complete.")]
- public bool NoAutoRunWebApp { get; set; }
-
+ /// <inheritdoc />
[Option("package-name", Required = false, HelpText = "Used when packaging Jellyfin (example, synology).")]
- public string PackageName { get; set; }
+ public string? PackageName { get; set; }
+ /// <inheritdoc />
[Option("restartpath", Required = false, HelpText = "Path to restart script.")]
- public string RestartPath { get; set; }
+ public string? RestartPath { get; set; }
+ /// <inheritdoc />
[Option("restartargs", Required = false, HelpText = "Arguments for restart script.")]
- public string RestartArgs { get; set; }
+ public string? RestartArgs { get; set; }
+
+ /// <inheritdoc />
+ [Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")]
+ public string? PublishedServerUrl { 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>
+ public Dictionary<string, string> ConvertToConfig()
+ {
+ var config = new Dictionary<string, string>();
+
+ if (NoWebClient)
+ {
+ config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString);
+ }
+
+ if (PublishedServerUrl != null)
+ {
+ config.Add(UdpServer.AddressOverrideConfigKey, PublishedServerUrl);
+ }
+
+ if (FFmpegPath != null)
+ {
+ config.Add(ConfigurationExtensions.FfmpegPathKey, FFmpegPath);
+ }
+
+ return config;
+ }
}
}
diff --git a/Jellyfin.Server/wwwroot/api-docs/banner-dark.svg b/Jellyfin.Server/wwwroot/api-docs/banner-dark.svg
new file mode 100644
index 000000000..b62b7545c
--- /dev/null
+++ b/Jellyfin.Server/wwwroot/api-docs/banner-dark.svg
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- ***** BEGIN LICENSE BLOCK *****
+ - Part of the Jellyfin project (https://jellyfin.media)
+ -
+ - All copyright belongs to the Jellyfin contributors; a full list can
+ - be found in the file CONTRIBUTORS.md
+ -
+ - This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.
+ - To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/.
+- ***** END LICENSE BLOCK ***** -->
+<svg id="banner-dark" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1536 512">
+ <defs>
+ <linearGradient id="linear-gradient" x1="110.25" y1="213.3" x2="496.14" y2="436.09" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="#aa5cc3"/>
+ <stop offset="1" stop-color="#00a4dc"/>
+ </linearGradient>
+ </defs>
+ <title>banner-dark</title>
+ <g id="banner-dark">
+ <g id="banner-dark-icon">
+ <path id="inner-shape" d="M261.42,201.62c-20.44,0-86.24,119.29-76.2,139.43s142.48,19.92,152.4,0S281.86,201.63,261.42,201.62Z" fill="url(#linear-gradient)"/>
+ <path id="outer-shape" d="M261.42,23.3C199.83,23.3,1.57,382.73,31.8,443.43s429.34,60,459.24,0S323,23.3,261.42,23.3ZM411.9,390.76c-19.59,39.33-281.08,39.77-300.9,0S221.1,115.48,261.45,115.48,431.49,351.42,411.9,390.76Z" fill="url(#linear-gradient)"/>
+ </g>
+ <g id="jellyfin-light-outlines" style="isolation:isolate" transform="translate(43.8)">
+ <path d="M556.64,350.75a67,67,0,0,1-22.87-27.47,8.91,8.91,0,0,1-1.49-4.75,7.42,7.42,0,0,1,2.83-5.94,9.25,9.25,0,0,1,6.09-2.38c3.16,0,5.94,1.69,8.31,5.05a48.09,48.09,0,0,0,16.34,20.34,40.59,40.59,0,0,0,24,7.58q20.51,0,33.27-12.62t12.77-33.12V159a8.44,8.44,0,0,1,2.67-6.39,9.56,9.56,0,0,1,6.83-2.52,9,9,0,0,1,6.68,2.52,8.7,8.7,0,0,1,2.53,6.39v138.4a64.7,64.7,0,0,1-8.32,32.67,59,59,0,0,1-23,22.72Q608.62,361,589.9,361A57.21,57.21,0,0,1,556.64,350.75Z" fill="#fff"/>
+ <path d="M831.66,279.47a8.77,8.77,0,0,1-6.24,2.53H713.16q0,17.82,7.27,31.92a54.91,54.91,0,0,0,20.79,22.28q13.51,8.18,31.93,8.17a54,54,0,0,0,25.54-5.94,52.7,52.7,0,0,0,18.12-15.15,10,10,0,0,1,6.24-2.67,8.14,8.14,0,0,1,7.72,7.72,8.81,8.81,0,0,1-3,6.24,74.7,74.7,0,0,1-23.91,19A65.56,65.56,0,0,1,773.45,361q-22.87,0-40.4-9.8a69.51,69.51,0,0,1-27.32-27.48q-9.79-17.66-9.8-40.83,0-24.36,9.65-42.62t25.69-27.92a65.2,65.2,0,0,1,34.16-9.65A70,70,0,0,1,798.84,211a65.78,65.78,0,0,1,25.39,24.36q9.81,16,10.1,38A8.07,8.07,0,0,1,831.66,279.47ZM733.5,231.8Q718.8,243.68,714.64,266H815.92v-2.38A46.91,46.91,0,0,0,807,240.27a48.47,48.47,0,0,0-18.56-15.15,54,54,0,0,0-23-5.2Q748.2,219.92,733.5,231.8Z" fill="#fff"/>
+ <path d="M888.24,355.5a8.92,8.92,0,0,1-15.3-6.38v-202a8.91,8.91,0,1,1,17.82,0v202A8.65,8.65,0,0,1,888.24,355.5Z" fill="#fff"/>
+ <path d="M956.55,355.5a8.92,8.92,0,0,1-15.3-6.38v-202a8.91,8.91,0,1,1,17.82,0v202A8.65,8.65,0,0,1,956.55,355.5Z" fill="#fff"/>
+ <path d="M1122.86,206.11a8.7,8.7,0,0,1,2.53,6.39v131q0,23.44-9.21,40.09a61.58,61.58,0,0,1-25.54,25.25q-16.34,8.61-36.83,8.61a96.73,96.73,0,0,1-23.31-2.68,61.72,61.72,0,0,1-18-7.12q-6.24-3.87-6.24-8.62a17.94,17.94,0,0,1,.6-3,8.06,8.06,0,0,1,3-4.45,7.49,7.49,0,0,1,4.45-1.49,7.91,7.91,0,0,1,3.56.89q19,10.39,36.24,10.4,24.65,0,39.06-15.44t14.4-42.18V333.38a54.37,54.37,0,0,1-21.38,20,62.55,62.55,0,0,1-30.3,7.58q-25.83,0-39.2-15.45t-13.37-41.87V212.5a8.91,8.91,0,1,1,17.82,0V301q0,21.39,9.36,32.38t29.25,11a48,48,0,0,0,23.32-6.09,49.88,49.88,0,0,0,17.82-16,37.44,37.44,0,0,0,6.68-21.24V212.5a9,9,0,0,1,15.29-6.39Z" fill="#fff"/>
+ <path d="M1210.18,161.41q-5.21,6.24-5.2,17.23v30.59h33.27a8.19,8.19,0,0,1,5.79,2.38,8.26,8.26,0,0,1,0,11.88,8.22,8.22,0,0,1-5.79,2.37H1205V349.12a8.91,8.91,0,1,1-17.82,0V225.86h-21.68a7.83,7.83,0,0,1-5.94-2.52,8.21,8.21,0,0,1-2.37-5.79,8,8,0,0,1,2.37-6.09,8.33,8.33,0,0,1,5.94-2.23h21.68V178.64q0-18.7,10.84-29t29-10.24a46.1,46.1,0,0,1,15.45,2.52q7.13,2.53,7.12,8.17a8.07,8.07,0,0,1-2.37,5.94,7.37,7.37,0,0,1-5.35,2.37,18.81,18.81,0,0,1-6.53-1.48,42,42,0,0,0-10.4-1.78Q1215.37,155.18,1210.18,161.41ZM1276,180.87c-2.19-1.88-3.27-4.61-3.27-8.17v-3q0-5.34,3.41-8.17t9.36-2.82q11.88,0,11.88,11v3c0,3.56-1,6.29-3.12,8.17s-5.1,2.82-9.06,2.82S1278.14,182.75,1276,180.87Zm15.59,174.63a8.92,8.92,0,0,1-15.3-6.38V212.5a8.91,8.91,0,1,1,17.82,0V349.12A8.65,8.65,0,0,1,1291.56,355.5Z" fill="#fff"/>
+ <path d="M1452.53,218.88q12.92,16.2,12.92,42.92v87.32a8.4,8.4,0,0,1-2.67,6.38,8.8,8.8,0,0,1-6.24,2.53,8.64,8.64,0,0,1-8.91-8.91V262.69q0-19.31-9.65-31.33t-29.85-12a53.28,53.28,0,0,0-42.77,21.83,36.24,36.24,0,0,0-7.13,21.53v86.43a8.91,8.91,0,1,1-17.82,0V216.06a8.91,8.91,0,1,1,17.82,0V232.4q8-12.77,23-21.24A61.84,61.84,0,0,1,1412,202.7Q1439.61,202.7,1452.53,218.88Z" fill="#fff"/>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/Jellyfin.Server/wwwroot/api-docs/redoc/custom.css b/Jellyfin.Server/wwwroot/api-docs/redoc/custom.css
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Jellyfin.Server/wwwroot/api-docs/redoc/custom.css
diff --git a/Jellyfin.Server/wwwroot/api-docs/swagger/custom.css b/Jellyfin.Server/wwwroot/api-docs/swagger/custom.css
new file mode 100644
index 000000000..acb59888e
--- /dev/null
+++ b/Jellyfin.Server/wwwroot/api-docs/swagger/custom.css
@@ -0,0 +1,15 @@
+/* logo */
+.topbar-wrapper img[alt="Swagger UI"], .topbar-wrapper span {
+ visibility: collapse;
+}
+
+.topbar-wrapper .link:after {
+ content: url(../banner-dark.svg);
+ display: block;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ max-width: 100%;
+ max-height: 100%;
+ width: 150px;
+}
+/* end logo */
diff --git a/Jellyfin.sln b/Jellyfin.sln
new file mode 100644
index 000000000..4626601c3
--- /dev/null
+++ b/Jellyfin.sln
@@ -0,0 +1,288 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30503.244
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Controller", "MediaBrowser.Controller\MediaBrowser.Controller.csproj", "{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Common", "MediaBrowser.Common\MediaBrowser.Common.csproj", "{9142EEFA-7570-41E1-BFCC-468BB571AF2F}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Model", "MediaBrowser.Model\MediaBrowser.Model.csproj", "{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Providers", "MediaBrowser.Providers\MediaBrowser.Providers.csproj", "{442B5058-DCAF-4263-BB6A-F21E31120A1B}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.XbmcMetadata", "MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj", "{23499896-B135-4527-8574-C26E926EA99E}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.LocalMetadata", "MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj", "{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Photos", "Emby.Photos\Emby.Photos.csproj", "{89AB4548-770D-41FD-A891-8DAFF44F452C}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DvdLib", "DvdLib\DvdLib.csproj", "{713F42B5-878E-499D-A878-E4C652B1D5E8}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Server.Implementations", "Emby.Server.Implementations\Emby.Server.Implementations.csproj", "{E383961B-9356-4D5D-8233-9A1079D03055}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RSSDP", "RSSDP\RSSDP.csproj", "{21002819-C39A-4D3E-BE83-2A276A77FB1F}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Dlna", "Emby.Dlna\Emby.Dlna.csproj", "{805844AB-E92F-45E6-9D99-4F6D48D129A5}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Notifications", "Emby.Notifications\Emby.Notifications.csproj", "{2E030C33-6923-4530-9E54-FA29FA6AD1A9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Naming", "Emby.Naming\Emby.Naming.csproj", "{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ jellyfin.ruleset = jellyfin.ruleset
+ SharedVersion.cs = SharedVersion.cs
+ EndProjectSection
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Drawing.Skia", "Jellyfin.Drawing.Skia\Jellyfin.Drawing.Skia.csproj", "{154872D9-6C12-4007-96E3-8F70A58386CE}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Api", "Jellyfin.Api\Jellyfin.Api.csproj", "{DFBEFB4C-DA19-4143-98B7-27320C7F7163}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}"
+ ProjectSection(SolutionItems) = preProject
+ tests\jellyfin-tests.ruleset = tests\jellyfin-tests.ruleset
+ EndProjectSection
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Common.Tests", "tests\Jellyfin.Common.Tests\Jellyfin.Common.Tests.csproj", "{DF194677-DFD3-42AF-9F75-D44D5A416478}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.MediaEncoding.Tests", "tests\Jellyfin.MediaEncoding.Tests\Jellyfin.MediaEncoding.Tests.csproj", "{28464062-0939-4AA7-9F7B-24DDDA61A7C0}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Naming.Tests", "tests\Jellyfin.Naming.Tests\Jellyfin.Naming.Tests.csproj", "{3998657B-1CCC-49DD-A19F-275DC8495F57}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Api.Tests", "tests\Jellyfin.Api.Tests\Jellyfin.Api.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementations.Tests", "tests\Jellyfin.Server.Implementations.Tests\Jellyfin.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Controller.Tests", "tests\Jellyfin.Controller.Tests\Jellyfin.Controller.Tests.csproj", "{462584F7-5023-4019-9EAC-B98CA458C0A0}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Data", "Jellyfin.Data\Jellyfin.Data.csproj", "{F03299F2-469F-40EF-A655-3766F97A5702}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementations", "Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj", "{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Providers.Tests", "tests\Jellyfin.Providers.Tests\Jellyfin.Providers.Tests.csproj", "{A964008C-2136-4716-B6CB-B3426C22320A}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{C9F0AB5D-F4D7-40C8-A353-3305C86D6D4C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Extensions", "src\Jellyfin.Extensions\Jellyfin.Extensions.csproj", "{750B8757-BE3D-4F8C-941A-FBAD94904ADA}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Extensions.Tests", "tests\Jellyfin.Extensions.Tests\Jellyfin.Extensions.Tests.csproj", "{332A5C7A-F907-47CA-910E-BE6F7371B9E0}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU
+ {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.Build.0 = Release|Any CPU
+ {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.Build.0 = Release|Any CPU
+ {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.Build.0 = Release|Any CPU
+ {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU
+ {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {DFBEFB4C-DA19-4143-98B7-27320C7F7163}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DFBEFB4C-DA19-4143-98B7-27320C7F7163}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DFBEFB4C-DA19-4143-98B7-27320C7F7163}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DFBEFB4C-DA19-4143-98B7-27320C7F7163}.Release|Any CPU.Build.0 = Release|Any CPU
+ {DF194677-DFD3-42AF-9F75-D44D5A416478}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DF194677-DFD3-42AF-9F75-D44D5A416478}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DF194677-DFD3-42AF-9F75-D44D5A416478}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DF194677-DFD3-42AF-9F75-D44D5A416478}.Release|Any CPU.Build.0 = Release|Any CPU
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3998657B-1CCC-49DD-A19F-275DC8495F57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3998657B-1CCC-49DD-A19F-275DC8495F57}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3998657B-1CCC-49DD-A19F-275DC8495F57}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3998657B-1CCC-49DD-A19F-275DC8495F57}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {462584F7-5023-4019-9EAC-B98CA458C0A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {462584F7-5023-4019-9EAC-B98CA458C0A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {462584F7-5023-4019-9EAC-B98CA458C0A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {462584F7-5023-4019-9EAC-B98CA458C0A0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F03299F2-469F-40EF-A655-3766F97A5702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F03299F2-469F-40EF-A655-3766F97A5702}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F03299F2-469F-40EF-A655-3766F97A5702}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F03299F2-469F-40EF-A655-3766F97A5702}.Release|Any CPU.Build.0 = Release|Any CPU
+ {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.Build.0 = Release|Any CPU
+ {30922383-D513-4F4D-B890-A940B57FA353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {30922383-D513-4F4D-B890-A940B57FA353}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A964008C-2136-4716-B6CB-B3426C22320A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A964008C-2136-4716-B6CB-B3426C22320A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {750B8757-BE3D-4F8C-941A-FBAD94904ADA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {750B8757-BE3D-4F8C-941A-FBAD94904ADA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {750B8757-BE3D-4F8C-941A-FBAD94904ADA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {750B8757-BE3D-4F8C-941A-FBAD94904ADA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {332A5C7A-F907-47CA-910E-BE6F7371B9E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {332A5C7A-F907-47CA-910E-BE6F7371B9E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {332A5C7A-F907-47CA-910E-BE6F7371B9E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {332A5C7A-F907-47CA-910E-BE6F7371B9E0}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {30922383-D513-4F4D-B890-A940B57FA353} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {A964008C-2136-4716-B6CB-B3426C22320A} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {750B8757-BE3D-4F8C-941A-FBAD94904ADA} = {C9F0AB5D-F4D7-40C8-A353-3305C86D6D4C}
+ {332A5C7A-F907-47CA-910E-BE6F7371B9E0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE}
+ EndGlobalSection
+ GlobalSection(AutomaticVersions) = postSolution
+ UpdateAssemblyVersion = True
+ UpdateAssemblyFileVersion = True
+ UpdateAssemblyInfoVersion = True
+ AssemblyVersionSettings = None.None.None.None
+ AssemblyFileVersionSettings = None.None.None.None
+ AssemblyInfoVersionSettings = None.None.None.None
+ UpdatePackageVersion = False
+ AssemblyInfoVersionType = SettingsVersion
+ InheritWinAppVersionFrom = None
+ EndGlobalSection
+ GlobalSection(MonoDevelopProperties) = preSolution
+ Policies = $0
+ $0.StandardHeader = $1
+ $1.IncludeInNewFiles = False
+ $0.DotNetNamingPolicy = $2
+ $2.DirectoryNamespaceAssociation = PrefixedHierarchical
+ EndGlobalSection
+EndGlobal
diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs
deleted file mode 100644
index ceff6b02e..000000000
--- a/MediaBrowser.Api/ApiEntryPoint.cs
+++ /dev/null
@@ -1,868 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Api.Playback;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Diagnostics;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Session;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class ServerEntryPoint
- /// </summary>
- public class ApiEntryPoint : IServerEntryPoint
- {
- /// <summary>
- /// The instance
- /// </summary>
- public static ApiEntryPoint Instance;
-
- /// <summary>
- /// Gets or sets the logger.
- /// </summary>
- /// <value>The logger.</value>
- internal ILogger Logger { get; private set; }
- internal IHttpResultFactory ResultFactory { get; private set; }
-
- /// <summary>
- /// The application paths
- /// </summary>
- private readonly IServerConfigurationManager _config;
-
- private readonly ISessionManager _sessionManager;
- private readonly IFileSystem _fileSystem;
- private readonly IMediaSourceManager _mediaSourceManager;
- public readonly IProcessFactory ProcessFactory;
-
- /// <summary>
- /// The active transcoding jobs
- /// </summary>
- private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
-
- private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks =
- new Dictionary<string, SemaphoreSlim>();
-
- private bool _disposed = false;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
- /// </summary>
- /// <param name="logger">The logger.</param>
- /// <param name="sessionManager">The session manager.</param>
- /// <param name="config">The configuration.</param>
- /// <param name="fileSystem">The file system.</param>
- /// <param name="mediaSourceManager">The media source manager.</param>
- public ApiEntryPoint(
- ILogger logger,
- ISessionManager sessionManager,
- IServerConfigurationManager config,
- IFileSystem fileSystem,
- IMediaSourceManager mediaSourceManager,
- IProcessFactory processFactory,
- IHttpResultFactory resultFactory)
- {
- Logger = logger;
- _sessionManager = sessionManager;
- _config = config;
- _fileSystem = fileSystem;
- _mediaSourceManager = mediaSourceManager;
- ProcessFactory = processFactory;
- ResultFactory = resultFactory;
-
- _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress;
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
-
- Instance = this;
- }
-
- public static string[] Split(string value, char separator, bool removeEmpty)
- {
- if (string.IsNullOrWhiteSpace(value))
- {
- return Array.Empty<string>();
- }
-
- if (removeEmpty)
- {
- return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- return value.Split(separator);
- }
-
- public SemaphoreSlim GetTranscodingLock(string outputPath)
- {
- lock (_transcodingLocks)
- {
- if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim result))
- {
- result = new SemaphoreSlim(1, 1);
- _transcodingLocks[outputPath] = result;
- }
-
- return result;
- }
- }
-
- private void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
- {
- PingTranscodingJob(e.PlaySessionId, e.IsPaused);
- }
- }
-
- void _sessionManager_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
- {
- if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
- {
- PingTranscodingJob(e.PlaySessionId, e.IsPaused);
- }
- }
-
- /// <summary>
- /// Runs this instance.
- /// </summary>
- public Task RunAsync()
- {
- try
- {
- DeleteEncodedMediaCache();
- }
- catch (FileNotFoundException)
- {
- // Don't clutter the log
- }
- catch (IOException)
- {
- // Don't clutter the log
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error deleting encoded media cache");
- }
-
- return Task.CompletedTask;
- }
-
- public EncodingOptions GetEncodingOptions()
- {
- return ConfigurationManagerExtensions.GetConfiguration<EncodingOptions>(_config, "encoding");
- }
-
- /// <summary>
- /// Deletes the encoded media cache.
- /// </summary>
- private void DeleteEncodedMediaCache()
- {
- var path = _config.ApplicationPaths.GetTranscodingTempPath();
-
- foreach (var file in _fileSystem.GetFilePaths(path, true))
- {
- _fileSystem.DeleteFile(file);
- }
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- 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 (_disposed)
- {
- return;
- }
-
- if (dispose)
- {
- // TODO: dispose
- }
-
- var jobs = _activeTranscodingJobs.ToList();
- var jobCount = jobs.Count;
-
- IEnumerable<Task> GetKillJobs()
- {
- foreach (var job in jobs)
- {
- yield return KillTranscodingJob(job, false, path => true);
- }
- }
-
- // Wait for all processes to be killed
- if (jobCount > 0)
- {
- Task.WaitAll(GetKillJobs().ToArray());
- }
-
- _activeTranscodingJobs.Clear();
- _transcodingLocks.Clear();
-
- _sessionManager.PlaybackProgress -= _sessionManager_PlaybackProgress;
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
-
- _disposed = true;
- }
-
-
- /// <summary>
- /// Called when [transcode beginning].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="playSessionId">The play session identifier.</param>
- /// <param name="liveStreamId">The live stream identifier.</param>
- /// <param name="transcodingJobId">The transcoding job identifier.</param>
- /// <param name="type">The type.</param>
- /// <param name="process">The process.</param>
- /// <param name="deviceId">The device id.</param>
- /// <param name="state">The state.</param>
- /// <param name="cancellationTokenSource">The cancellation token source.</param>
- /// <returns>TranscodingJob.</returns>
- public TranscodingJob OnTranscodeBeginning(
- string path,
- string playSessionId,
- string liveStreamId,
- string transcodingJobId,
- TranscodingJobType type,
- Process process,
- string deviceId,
- StreamState state,
- CancellationTokenSource cancellationTokenSource)
- {
- lock (_activeTranscodingJobs)
- {
- var job = new TranscodingJob(Logger)
- {
- Type = type,
- Path = path,
- Process = process,
- ActiveRequestCount = 1,
- DeviceId = deviceId,
- CancellationTokenSource = cancellationTokenSource,
- Id = transcodingJobId,
- PlaySessionId = playSessionId,
- LiveStreamId = liveStreamId,
- MediaSource = state.MediaSource
- };
-
- _activeTranscodingJobs.Add(job);
-
- ReportTranscodingProgress(job, state, null, null, null, null, null);
-
- return job;
- }
- }
-
- public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
- {
- var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
-
- if (job != null)
- {
- job.Framerate = framerate;
- job.CompletionPercentage = percentComplete;
- job.TranscodingPositionTicks = ticks;
- job.BytesTranscoded = bytesTranscoded;
- job.BitRate = bitRate;
- }
-
- var deviceId = state.Request.DeviceId;
-
- if (!string.IsNullOrWhiteSpace(deviceId))
- {
- var audioCodec = state.ActualOutputAudioCodec;
- var videoCodec = state.ActualOutputVideoCodec;
-
- _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
- {
- Bitrate = bitRate ?? state.TotalOutputBitrate,
- AudioCodec = audioCodec,
- VideoCodec = videoCodec,
- Container = state.OutputContainer,
- Framerate = framerate,
- CompletionPercentage = percentComplete,
- Width = state.OutputWidth,
- Height = state.OutputHeight,
- AudioChannels = state.OutputAudioChannels,
- IsAudioDirect = string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
- IsVideoDirect = string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase),
- TranscodeReasons = state.TranscodeReasons
- });
- }
- }
-
- /// <summary>
- /// <summary>
- /// The progressive
- /// </summary>
- /// Called when [transcode failed to start].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="type">The type.</param>
- /// <param name="state">The state.</param>
- public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
- {
- lock (_activeTranscodingJobs)
- {
- var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
-
- if (job != null)
- {
- _activeTranscodingJobs.Remove(job);
- }
- }
-
- lock (_transcodingLocks)
- {
- _transcodingLocks.Remove(path);
- }
-
- if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
- {
- _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
- }
- }
-
- /// <summary>
- /// Determines whether [has active transcoding job] [the specified path].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="type">The type.</param>
- /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
- public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
- {
- return GetTranscodingJob(path, type) != null;
- }
-
- public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
- {
- lock (_activeTranscodingJobs)
- {
- return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
- }
- }
-
- public TranscodingJob GetTranscodingJob(string playSessionId)
- {
- lock (_activeTranscodingJobs)
- {
- return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
- }
- }
-
- /// <summary>
- /// Called when [transcode begin request].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="type">The type.</param>
- public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
- {
- lock (_activeTranscodingJobs)
- {
- var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
-
- if (job == null)
- {
- return null;
- }
-
- OnTranscodeBeginRequest(job);
-
- return job;
- }
- }
-
- public void OnTranscodeBeginRequest(TranscodingJob job)
- {
- job.ActiveRequestCount++;
-
- if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
- {
- job.StopKillTimer();
- }
- }
-
- public void OnTranscodeEndRequest(TranscodingJob job)
- {
- job.ActiveRequestCount--;
- //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
- if (job.ActiveRequestCount <= 0)
- {
- PingTimer(job, false);
- }
- }
- internal void PingTranscodingJob(string playSessionId, bool? isUserPaused)
- {
- if (string.IsNullOrEmpty(playSessionId))
- {
- throw new ArgumentNullException(nameof(playSessionId));
- }
-
- //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
-
- List<TranscodingJob> jobs;
-
- lock (_activeTranscodingJobs)
- {
- // This is really only needed for HLS.
- // Progressive streams can stop on their own reliably
- jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
- }
-
- foreach (var job in jobs)
- {
- if (isUserPaused.HasValue)
- {
- //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
- job.IsUserPaused = isUserPaused.Value;
- }
- PingTimer(job, true);
- }
- }
-
- private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
- {
- if (job.HasExited)
- {
- job.StopKillTimer();
- return;
- }
-
- var timerDuration = 10000;
-
- if (job.Type != TranscodingJobType.Progressive)
- {
- timerDuration = 60000;
- }
-
- job.PingTimeout = timerDuration;
- job.LastPingDate = DateTime.UtcNow;
-
- // Don't start the timer for playback checkins with progressive streaming
- if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
- {
- job.StartKillTimer(OnTranscodeKillTimerStopped);
- }
- else
- {
- job.ChangeKillTimerIfStarted();
- }
- }
-
- /// <summary>
- /// Called when [transcode kill timer stopped].
- /// </summary>
- /// <param name="state">The state.</param>
- private async void OnTranscodeKillTimerStopped(object state)
- {
- var job = (TranscodingJob)state;
-
- if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
- {
- var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
-
- if (timeSinceLastPing < job.PingTimeout)
- {
- job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
- return;
- }
- }
-
- Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
-
- await KillTranscodingJob(job, true, path => true);
- }
-
- /// <summary>
- /// Kills the single transcoding job.
- /// </summary>
- /// <param name="deviceId">The device id.</param>
- /// <param name="playSessionId">The play session identifier.</param>
- /// <param name="deleteFiles">The delete files.</param>
- /// <returns>Task.</returns>
- internal Task KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
- {
- return KillTranscodingJobs(j =>
- {
- if (!string.IsNullOrWhiteSpace(playSessionId))
- {
- return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
- }
-
- return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase);
-
- }, deleteFiles);
- }
-
- /// <summary>
- /// Kills the transcoding jobs.
- /// </summary>
- /// <param name="killJob">The kill job.</param>
- /// <param name="deleteFiles">The delete files.</param>
- /// <returns>Task.</returns>
- private Task KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
- {
- var jobs = new List<TranscodingJob>();
-
- lock (_activeTranscodingJobs)
- {
- // This is really only needed for HLS.
- // Progressive streams can stop on their own reliably
- jobs.AddRange(_activeTranscodingJobs.Where(killJob));
- }
-
- if (jobs.Count == 0)
- {
- return Task.CompletedTask;
- }
-
- IEnumerable<Task> GetKillJobs()
- {
- foreach (var job in jobs)
- {
- yield return KillTranscodingJob(job, false, deleteFiles);
- }
- }
-
- return Task.WhenAll(GetKillJobs());
- }
-
- /// <summary>
- /// Kills the transcoding job.
- /// </summary>
- /// <param name="job">The job.</param>
- /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
- /// <param name="delete">The delete.</param>
- private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
- {
- job.DisposeKillTimer();
-
- Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
-
- lock (_activeTranscodingJobs)
- {
- _activeTranscodingJobs.Remove(job);
-
- if (!job.CancellationTokenSource.IsCancellationRequested)
- {
- job.CancellationTokenSource.Cancel();
- }
- }
-
- lock (_transcodingLocks)
- {
- _transcodingLocks.Remove(job.Path);
- }
-
- lock (job.ProcessLock)
- {
- if (job.TranscodingThrottler != null)
- {
- job.TranscodingThrottler.Stop().GetAwaiter().GetResult();
- }
-
- var process = job.Process;
-
- var hasExited = job.HasExited;
-
- if (!hasExited)
- {
- try
- {
- Logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
-
- //process.Kill();
- process.StandardInput.WriteLine("q");
-
- // Need to wait because killing is asynchronous
- if (!process.WaitForExit(5000))
- {
- Logger.LogInformation("Killing ffmpeg process for {Path}", job.Path);
- process.Kill();
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error killing transcoding job for {Path}", job.Path);
- }
- }
- }
-
- if (delete(job.Path))
- {
- await DeletePartialStreamFiles(job.Path, job.Type, 0, 1500).ConfigureAwait(false);
- }
-
- if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
- {
- try
- {
- await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
- }
- }
- }
-
- private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
- {
- if (retryCount >= 10)
- {
- return;
- }
-
- Logger.LogInformation("Deleting partial stream file(s) {Path}", path);
-
- await Task.Delay(delayMs).ConfigureAwait(false);
-
- try
- {
- if (jobType == TranscodingJobType.Progressive)
- {
- DeleteProgressivePartialStreamFiles(path);
- }
- else
- {
- DeleteHlsPartialStreamFiles(path);
- }
- }
- catch (FileNotFoundException)
- {
-
- }
- catch (IOException ex)
- {
- Logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
-
- await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
- }
- }
-
- /// <summary>
- /// Deletes the progressive partial stream files.
- /// </summary>
- /// <param name="outputFilePath">The output file path.</param>
- private void DeleteProgressivePartialStreamFiles(string outputFilePath)
- {
- _fileSystem.DeleteFile(outputFilePath);
- }
-
- /// <summary>
- /// Deletes the HLS partial stream files.
- /// </summary>
- /// <param name="outputFilePath">The output file path.</param>
- private void DeleteHlsPartialStreamFiles(string outputFilePath)
- {
- var directory = Path.GetDirectoryName(outputFilePath);
- var name = Path.GetFileNameWithoutExtension(outputFilePath);
-
- var filesToDelete = _fileSystem.GetFilePaths(directory)
- .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
-
- Exception e = null;
-
- foreach (var file in filesToDelete)
- {
- try
- {
- //Logger.LogDebug("Deleting HLS file {0}", file);
- _fileSystem.DeleteFile(file);
- }
- catch (FileNotFoundException)
- {
-
- }
- catch (IOException ex)
- {
- e = ex;
- Logger.LogError(ex, "Error deleting HLS file {Path}", file);
- }
- }
-
- if (e != null)
- {
- throw e;
- }
- }
- }
-
- /// <summary>
- /// Class TranscodingJob
- /// </summary>
- public class TranscodingJob
- {
- /// <summary>
- /// Gets or sets the play session identifier.
- /// </summary>
- /// <value>The play session identifier.</value>
- public string PlaySessionId { get; set; }
- /// <summary>
- /// Gets or sets the live stream identifier.
- /// </summary>
- /// <value>The live stream identifier.</value>
- public string LiveStreamId { get; set; }
-
- public bool IsLiveOutput { get; set; }
-
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- public MediaSourceInfo MediaSource { get; set; }
- public string Path { get; set; }
- /// <summary>
- /// Gets or sets the type.
- /// </summary>
- /// <value>The type.</value>
- public TranscodingJobType Type { get; set; }
- /// <summary>
- /// Gets or sets the process.
- /// </summary>
- /// <value>The process.</value>
- public Process Process { get; set; }
- public ILogger Logger { get; private set; }
- /// <summary>
- /// Gets or sets the active request count.
- /// </summary>
- /// <value>The active request count.</value>
- public int ActiveRequestCount { get; set; }
- /// <summary>
- /// Gets or sets the kill timer.
- /// </summary>
- /// <value>The kill timer.</value>
- private Timer KillTimer { get; set; }
-
- public string DeviceId { get; set; }
-
- public CancellationTokenSource CancellationTokenSource { get; set; }
-
- public object ProcessLock = new object();
-
- public bool HasExited { get; set; }
- public bool IsUserPaused { get; set; }
-
- public string Id { get; set; }
-
- public float? Framerate { get; set; }
- public double? CompletionPercentage { get; set; }
-
- public long? BytesDownloaded { get; set; }
- public long? BytesTranscoded { get; set; }
- public int? BitRate { get; set; }
-
- public long? TranscodingPositionTicks { get; set; }
- public long? DownloadPositionTicks { get; set; }
-
- public TranscodingThrottler TranscodingThrottler { get; set; }
-
- private readonly object _timerLock = new object();
-
- public DateTime LastPingDate { get; set; }
- public int PingTimeout { get; set; }
-
- public TranscodingJob(ILogger logger)
- {
- Logger = logger;
- }
-
- public void StopKillTimer()
- {
- lock (_timerLock)
- {
- if (KillTimer != null)
- {
- KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
- }
- }
- }
-
- public void DisposeKillTimer()
- {
- lock (_timerLock)
- {
- if (KillTimer != null)
- {
- KillTimer.Dispose();
- KillTimer = null;
- }
- }
- }
-
- public void StartKillTimer(Action<object> callback)
- {
- StartKillTimer(callback, PingTimeout);
- }
-
- public void StartKillTimer(Action<object> callback, int intervalMs)
- {
- if (HasExited)
- {
- return;
- }
-
- lock (_timerLock)
- {
- if (KillTimer == null)
- {
- //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
- KillTimer = new Timer(new TimerCallback(callback), this, intervalMs, Timeout.Infinite);
- }
- else
- {
- //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
- KillTimer.Change(intervalMs, Timeout.Infinite);
- }
- }
- }
-
- public void ChangeKillTimerIfStarted()
- {
- if (HasExited)
- {
- return;
- }
-
- lock (_timerLock)
- {
- if (KillTimer != null)
- {
- var intervalMs = PingTimeout;
-
- //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
- KillTimer.Change(intervalMs, Timeout.Infinite);
- }
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs
deleted file mode 100644
index a037357ed..000000000
--- a/MediaBrowser.Api/BaseApiService.cs
+++ /dev/null
@@ -1,373 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Querying;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class BaseApiService
- /// </summary>
- public class BaseApiService : IService, IRequiresRequest
- {
- /// <summary>
- /// Gets or sets the logger.
- /// </summary>
- /// <value>The logger.</value>
- public ILogger Logger => ApiEntryPoint.Instance.Logger;
-
- /// <summary>
- /// Gets or sets the HTTP result factory.
- /// </summary>
- /// <value>The HTTP result factory.</value>
- public IHttpResultFactory ResultFactory => ApiEntryPoint.Instance.ResultFactory;
-
- /// <summary>
- /// Gets or sets the request context.
- /// </summary>
- /// <value>The request context.</value>
- public IRequest Request { get; set; }
-
- public string GetHeader(string name)
- {
- return Request.Headers[name];
- }
-
- public static string[] SplitValue(string value, char delim)
- {
- if (value == null)
- {
- return Array.Empty<string>();
- }
-
- return value.Split(new[] { delim }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public static Guid[] GetGuids(string value)
- {
- if (value == null)
- {
- return Array.Empty<Guid>();
- }
-
- return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(i => new Guid(i))
- .ToArray();
- }
-
- /// <summary>
- /// To the optimized result.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="result">The result.</param>
- /// <returns>System.Object.</returns>
- protected object ToOptimizedResult<T>(T result)
- where T : class
- {
- return ResultFactory.GetResult(Request, result);
- }
-
- protected void AssertCanUpdateUser(IAuthorizationContext authContext, IUserManager userManager, Guid userId, bool restrictUserPreferences)
- {
- var auth = authContext.GetAuthorizationInfo(Request);
-
- var authenticatedUser = auth.User;
-
- // If they're going to update the record of another user, they must be an administrator
- if (!userId.Equals(auth.UserId))
- {
- if (!authenticatedUser.Policy.IsAdministrator)
- {
- throw new SecurityException("Unauthorized access.");
- }
- }
- else if (restrictUserPreferences)
- {
- if (!authenticatedUser.Policy.EnableUserPreferenceAccess)
- {
- throw new SecurityException("Unauthorized access.");
- }
- }
- }
-
- /// <summary>
- /// Gets the session.
- /// </summary>
- /// <returns>SessionInfo.</returns>
- protected SessionInfo GetSession(ISessionContext sessionContext)
- {
- var session = sessionContext.GetSession(Request);
-
- if (session == null)
- {
- throw new ArgumentException("Session not found.");
- }
-
- return session;
- }
-
- protected DtoOptions GetDtoOptions(IAuthorizationContext authContext, object request)
- {
- var options = new DtoOptions();
-
- if (request is IHasItemFields hasFields)
- {
- options.Fields = hasFields.GetItemFields();
- }
-
- if (!options.ContainsField(Model.Querying.ItemFields.RecursiveItemCount)
- || !options.ContainsField(Model.Querying.ItemFields.ChildCount))
- {
- var client = authContext.GetAuthorizationInfo(Request).Client ?? string.Empty;
- if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1)
- {
- int oldLen = options.Fields.Length;
- var arr = new ItemFields[oldLen + 1];
- options.Fields.CopyTo(arr, 0);
- arr[oldLen] = Model.Querying.ItemFields.RecursiveItemCount;
- options.Fields = arr;
- }
-
- if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("roku", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("samsung", StringComparison.OrdinalIgnoreCase) != -1 ||
- client.IndexOf("androidtv", StringComparison.OrdinalIgnoreCase) != -1)
- {
-
- int oldLen = options.Fields.Length;
- var arr = new ItemFields[oldLen + 1];
- options.Fields.CopyTo(arr, 0);
- arr[oldLen] = Model.Querying.ItemFields.ChildCount;
- options.Fields = arr;
- }
- }
-
- if (request is IHasDtoOptions hasDtoOptions)
- {
- options.EnableImages = hasDtoOptions.EnableImages ?? true;
-
- if (hasDtoOptions.ImageTypeLimit.HasValue)
- {
- options.ImageTypeLimit = hasDtoOptions.ImageTypeLimit.Value;
- }
- if (hasDtoOptions.EnableUserData.HasValue)
- {
- options.EnableUserData = hasDtoOptions.EnableUserData.Value;
- }
-
- if (!string.IsNullOrWhiteSpace(hasDtoOptions.EnableImageTypes))
- {
- if (string.IsNullOrEmpty(hasDtoOptions.EnableImageTypes))
- {
- options.ImageTypes = Array.Empty<ImageType>();
- }
- else
- {
- options.ImageTypes = hasDtoOptions.EnableImageTypes.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true))
- .ToArray();
- }
- }
- }
-
- return options;
- }
-
- protected MusicArtist GetArtist(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- if (name.IndexOf(BaseItem.SlugChar) != -1)
- {
- var result = GetItemFromSlugName<MusicArtist>(libraryManager, name, dtoOptions);
-
- if (result != null)
- {
- return result;
- }
- }
-
- return libraryManager.GetArtist(name, dtoOptions);
- }
-
- protected Studio GetStudio(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- if (name.IndexOf(BaseItem.SlugChar) != -1)
- {
- var result = GetItemFromSlugName<Studio>(libraryManager, name, dtoOptions);
-
- if (result != null)
- {
- return result;
- }
- }
-
- return libraryManager.GetStudio(name);
- }
-
- protected Genre GetGenre(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- if (name.IndexOf(BaseItem.SlugChar) != -1)
- {
- var result = GetItemFromSlugName<Genre>(libraryManager, name, dtoOptions);
-
- if (result != null)
- {
- return result;
- }
- }
-
- return libraryManager.GetGenre(name);
- }
-
- protected MusicGenre GetMusicGenre(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- if (name.IndexOf(BaseItem.SlugChar) != -1)
- {
- var result = GetItemFromSlugName<MusicGenre>(libraryManager, name, dtoOptions);
-
- if (result != null)
- {
- return result;
- }
- }
-
- return libraryManager.GetMusicGenre(name);
- }
-
- protected Person GetPerson(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- if (name.IndexOf(BaseItem.SlugChar) != -1)
- {
- var result = GetItemFromSlugName<Person>(libraryManager, name, dtoOptions);
-
- if (result != null)
- {
- return result;
- }
- }
-
- return libraryManager.GetPerson(name);
- }
-
- private T GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
- where T : BaseItem, new()
- {
- var result = libraryManager.GetItemList(new InternalItemsQuery
- {
- Name = name.Replace(BaseItem.SlugChar, '&'),
- IncludeItemTypes = new[] { typeof(T).Name },
- DtoOptions = dtoOptions
-
- }).OfType<T>().FirstOrDefault();
-
- if (result == null)
- {
- result = libraryManager.GetItemList(new InternalItemsQuery
- {
- Name = name.Replace(BaseItem.SlugChar, '/'),
- IncludeItemTypes = new[] { typeof(T).Name },
- DtoOptions = dtoOptions
-
- }).OfType<T>().FirstOrDefault();
- }
-
- if (result == null)
- {
- result = libraryManager.GetItemList(new InternalItemsQuery
- {
- Name = name.Replace(BaseItem.SlugChar, '?'),
- IncludeItemTypes = new[] { typeof(T).Name },
- DtoOptions = dtoOptions
-
- }).OfType<T>().FirstOrDefault();
- }
-
- return result;
- }
-
- protected string GetPathValue(int index)
- {
- var pathInfo = Parse(Request.PathInfo);
- var first = pathInfo[0];
-
- // backwards compatibility
- if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase))
- {
- index++;
- }
-
- return pathInfo[index];
- }
-
- private string[] Parse(string pathUri)
- {
- var actionParts = pathUri.Split(new[] { "://" }, StringSplitOptions.None);
-
- var pathInfo = actionParts[actionParts.Length - 1];
-
- var optionsPos = pathInfo.LastIndexOf('?');
- if (optionsPos != -1)
- {
- pathInfo = pathInfo.Substring(0, optionsPos);
- }
-
- var args = pathInfo.Split('/');
-
- return args.Skip(1).ToArray();
- }
-
- /// <summary>
- /// Gets the name of the item by.
- /// </summary>
- protected BaseItem GetItemByName(string name, string type, ILibraryManager libraryManager, DtoOptions dtoOptions)
- {
- BaseItem item;
-
- if (type.IndexOf("Person", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = GetPerson(name, libraryManager, dtoOptions);
- }
- else if (type.IndexOf("Artist", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = GetArtist(name, libraryManager, dtoOptions);
- }
- else if (type.IndexOf("Genre", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = GetGenre(name, libraryManager, dtoOptions);
- }
- else if (type.IndexOf("MusicGenre", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = GetMusicGenre(name, libraryManager, dtoOptions);
- }
- else if (type.IndexOf("Studio", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = GetStudio(name, libraryManager, dtoOptions);
- }
- else if (type.IndexOf("Year", StringComparison.OrdinalIgnoreCase) == 0)
- {
- item = libraryManager.GetYear(int.Parse(name));
- }
- else
- {
- throw new ArgumentException();
- }
-
- return item;
- }
- }
-}
diff --git a/MediaBrowser.Api/BrandingService.cs b/MediaBrowser.Api/BrandingService.cs
deleted file mode 100644
index f5845f4e0..000000000
--- a/MediaBrowser.Api/BrandingService.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Branding;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Branding/Configuration", "GET", Summary = "Gets branding configuration")]
- public class GetBrandingOptions : IReturn<BrandingOptions>
- {
- }
-
- [Route("/Branding/Css", "GET", Summary = "Gets custom css")]
- [Route("/Branding/Css.css", "GET", Summary = "Gets custom css")]
- public class GetBrandingCss
- {
- }
-
- public class BrandingService : BaseApiService
- {
- private readonly IConfigurationManager _config;
-
- public BrandingService(IConfigurationManager config)
- {
- _config = config;
- }
-
- public object Get(GetBrandingOptions request)
- {
- return _config.GetConfiguration<BrandingOptions>("branding");
- }
-
- public object Get(GetBrandingCss request)
- {
- var result = _config.GetConfiguration<BrandingOptions>("branding");
-
- // When null this throws a 405 error under Mono OSX, so default to empty string
- return ResultFactory.GetResult(Request, result.CustomCss ?? string.Empty, "text/css");
- }
- }
-}
diff --git a/MediaBrowser.Api/ChannelService.cs b/MediaBrowser.Api/ChannelService.cs
deleted file mode 100644
index d28bfaff5..000000000
--- a/MediaBrowser.Api/ChannelService.cs
+++ /dev/null
@@ -1,341 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Api.UserLibrary;
-using MediaBrowser.Controller.Channels;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Channels;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Channels", "GET", Summary = "Gets available channels")]
- public class GetChannels : IReturn<QueryResult<BaseItemDto>>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "SupportsLatestItems", Description = "Optional. Filter by channels that support getting latest items.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? SupportsLatestItems { get; set; }
-
- public bool? SupportsMediaDeletion { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is favorite.
- /// </summary>
- /// <value><c>null</c> if [is favorite] contains no value, <c>true</c> if [is favorite]; otherwise, <c>false</c>.</value>
- public bool? IsFavorite { get; set; }
- }
-
- [Route("/Channels/{Id}/Features", "GET", Summary = "Gets features for a channel")]
- public class GetChannelFeatures : IReturn<ChannelFeatures>
- {
- [ApiMember(Name = "Id", Description = "Channel Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Channels/Features", "GET", Summary = "Gets features for a channel")]
- public class GetAllChannelFeatures : IReturn<ChannelFeatures[]>
- {
- }
-
- [Route("/Channels/{Id}/Items", "GET", Summary = "Gets channel items")]
- public class GetChannelItems : IReturn<QueryResult<BaseItemDto>>, IHasItemFields
- {
- [ApiMember(Name = "Id", Description = "Channel Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "FolderId", Description = "Folder Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string FolderId { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "SortOrder", Description = "Sort Order - Ascending,Descending", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SortOrder { get; set; }
-
- [ApiMember(Name = "Filters", Description = "Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Filters { get; set; }
-
- [ApiMember(Name = "SortBy", Description = "Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string SortBy { get; set; }
-
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- /// <summary>
- /// Gets the filters.
- /// </summary>
- /// <returns>IEnumerable{ItemFilter}.</returns>
- public IEnumerable<ItemFilter> GetFilters()
- {
- var val = Filters;
-
- if (string.IsNullOrEmpty(val))
- {
- return new ItemFilter[] { };
- }
-
- return val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true));
- }
-
- /// <summary>
- /// Gets the order by.
- /// </summary>
- /// <returns>IEnumerable{ItemSortBy}.</returns>
- public ValueTuple<string, SortOrder>[] GetOrderBy()
- {
- return BaseItemsRequest.GetOrderBy(SortBy, SortOrder);
- }
- }
-
- [Route("/Channels/Items/Latest", "GET", Summary = "Gets channel items")]
- public class GetLatestChannelItems : IReturn<QueryResult<BaseItemDto>>, IHasItemFields
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "Filters", Description = "Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Filters { get; set; }
-
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "ChannelIds", Description = "Optional. Specify one or more channel id's, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ChannelIds { get; set; }
-
- /// <summary>
- /// Gets the filters.
- /// </summary>
- /// <returns>IEnumerable{ItemFilter}.</returns>
- public IEnumerable<ItemFilter> GetFilters()
- {
- var val = Filters;
-
- if (string.IsNullOrEmpty(val))
- {
- return new ItemFilter[] { };
- }
-
- return val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true));
- }
- }
-
- [Authenticated]
- public class ChannelService : BaseApiService
- {
- private readonly IChannelManager _channelManager;
- private IUserManager _userManager;
-
- public ChannelService(IChannelManager channelManager, IUserManager userManager)
- {
- _channelManager = channelManager;
- _userManager = userManager;
- }
-
- public object Get(GetAllChannelFeatures request)
- {
- var result = _channelManager.GetAllChannelFeatures();
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetChannelFeatures request)
- {
- var result = _channelManager.GetChannelFeatures(request.Id);
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetChannels request)
- {
- var result = _channelManager.GetChannels(new ChannelQuery
- {
- Limit = request.Limit,
- StartIndex = request.StartIndex,
- UserId = request.UserId,
- SupportsLatestItems = request.SupportsLatestItems,
- SupportsMediaDeletion = request.SupportsMediaDeletion,
- IsFavorite = request.IsFavorite
- });
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetChannelItems request)
- {
- var user = request.UserId.Equals(Guid.Empty)
- ? null
- : _userManager.GetUserById(request.UserId);
-
- var query = new InternalItemsQuery(user)
- {
- Limit = request.Limit,
- StartIndex = request.StartIndex,
- ChannelIds = new Guid[] { new Guid(request.Id) },
- ParentId = string.IsNullOrWhiteSpace(request.FolderId) ? Guid.Empty : new Guid(request.FolderId),
- OrderBy = request.GetOrderBy(),
- DtoOptions = new Controller.Dto.DtoOptions
- {
- Fields = request.GetItemFields()
- }
-
- };
-
- foreach (var filter in request.GetFilters())
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = await _channelManager.GetChannelItems(query, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetLatestChannelItems request)
- {
- var user = request.UserId.Equals(Guid.Empty)
- ? null
- : _userManager.GetUserById(request.UserId);
-
- var query = new InternalItemsQuery(user)
- {
- Limit = request.Limit,
- StartIndex = request.StartIndex,
- ChannelIds = (request.ChannelIds ?? string.Empty).Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => new Guid(i)).ToArray(),
- DtoOptions = new Controller.Dto.DtoOptions
- {
- Fields = request.GetItemFields()
- }
- };
-
- foreach (var filter in request.GetFilters())
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = await _channelManager.GetLatestChannelItems(query, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
- }
-}
diff --git a/MediaBrowser.Api/ConfigurationService.cs b/MediaBrowser.Api/ConfigurationService.cs
deleted file mode 100644
index 718f537bc..000000000
--- a/MediaBrowser.Api/ConfigurationService.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetConfiguration
- /// </summary>
- [Route("/System/Configuration", "GET", Summary = "Gets application configuration")]
- [Authenticated]
- public class GetConfiguration : IReturn<ServerConfiguration>
- {
-
- }
-
- [Route("/System/Configuration/{Key}", "GET", Summary = "Gets a named configuration")]
- [Authenticated(AllowBeforeStartupWizard = true)]
- public class GetNamedConfiguration
- {
- [ApiMember(Name = "Key", Description = "Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Key { get; set; }
- }
-
- /// <summary>
- /// Class UpdateConfiguration
- /// </summary>
- [Route("/System/Configuration", "POST", Summary = "Updates application configuration")]
- [Authenticated(Roles = "Admin")]
- public class UpdateConfiguration : ServerConfiguration, IReturnVoid
- {
- }
-
- [Route("/System/Configuration/{Key}", "POST", Summary = "Updates named configuration")]
- [Authenticated(Roles = "Admin")]
- public class UpdateNamedConfiguration : IReturnVoid, IRequiresRequestStream
- {
- [ApiMember(Name = "Key", Description = "Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Key { get; set; }
-
- public Stream RequestStream { get; set; }
- }
-
- [Route("/System/Configuration/MetadataOptions/Default", "GET", Summary = "Gets a default MetadataOptions object")]
- [Authenticated(Roles = "Admin")]
- public class GetDefaultMetadataOptions : IReturn<MetadataOptions>
- {
-
- }
-
- [Route("/System/MediaEncoder/Path", "POST", Summary = "Updates the path to the media encoder")]
- [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
- public class UpdateMediaEncoderPath : IReturnVoid
- {
- [ApiMember(Name = "Path", Description = "Path", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Path { get; set; }
- [ApiMember(Name = "PathType", Description = "PathType", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string PathType { get; set; }
- }
-
- public class ConfigurationService : BaseApiService
- {
- /// <summary>
- /// The _json serializer
- /// </summary>
- private readonly IJsonSerializer _jsonSerializer;
-
- /// <summary>
- /// The _configuration manager
- /// </summary>
- private readonly IServerConfigurationManager _configurationManager;
-
- private readonly IFileSystem _fileSystem;
- private readonly IProviderManager _providerManager;
- private readonly ILibraryManager _libraryManager;
- private readonly IMediaEncoder _mediaEncoder;
-
- public ConfigurationService(IJsonSerializer jsonSerializer, IServerConfigurationManager configurationManager, IFileSystem fileSystem, IProviderManager providerManager, ILibraryManager libraryManager, IMediaEncoder mediaEncoder)
- {
- _jsonSerializer = jsonSerializer;
- _configurationManager = configurationManager;
- _fileSystem = fileSystem;
- _providerManager = providerManager;
- _libraryManager = libraryManager;
- _mediaEncoder = mediaEncoder;
- }
-
- public void Post(UpdateMediaEncoderPath request)
- {
- _mediaEncoder.UpdateEncoderPath(request.Path, request.PathType);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetConfiguration request)
- {
- return ToOptimizedResult(_configurationManager.Configuration);
- }
-
- public object Get(GetNamedConfiguration request)
- {
- var result = _configurationManager.GetConfiguration(request.Key);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified configuraiton.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(UpdateConfiguration request)
- {
- // Silly, but we need to serialize and deserialize or the XmlSerializer will write the xml with an element name of UpdateConfiguration
- var json = _jsonSerializer.SerializeToString(request);
-
- var config = _jsonSerializer.DeserializeFromString<ServerConfiguration>(json);
-
- _configurationManager.ReplaceConfiguration(config);
- }
-
- public async Task Post(UpdateNamedConfiguration request)
- {
- var key = GetPathValue(2);
-
- var configurationType = _configurationManager.GetConfigurationType(key);
- var configuration = await _jsonSerializer.DeserializeFromStreamAsync(request.RequestStream, configurationType).ConfigureAwait(false);
-
- _configurationManager.SaveConfiguration(key, configuration);
- }
-
- public object Get(GetDefaultMetadataOptions request)
- {
- return ToOptimizedResult(new MetadataOptions());
- }
- }
-}
diff --git a/MediaBrowser.Api/Devices/DeviceService.cs b/MediaBrowser.Api/Devices/DeviceService.cs
deleted file mode 100644
index dc211af6b..000000000
--- a/MediaBrowser.Api/Devices/DeviceService.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Devices;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Devices
-{
- [Route("/Devices", "GET", Summary = "Gets all devices")]
- [Authenticated(Roles = "Admin")]
- public class GetDevices : DeviceQuery, IReturn<QueryResult<DeviceInfo>>
- {
- }
-
- [Route("/Devices/Info", "GET", Summary = "Gets info for a device")]
- [Authenticated(Roles = "Admin")]
- public class GetDeviceInfo : IReturn<DeviceInfo>
- {
- [ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Devices/Options", "GET", Summary = "Gets options for a device")]
- [Authenticated(Roles = "Admin")]
- public class GetDeviceOptions : IReturn<DeviceOptions>
- {
- [ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Devices", "DELETE", Summary = "Deletes a device")]
- public class DeleteDevice
- {
- [ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/Devices/CameraUploads", "GET", Summary = "Gets camera upload history for a device")]
- [Authenticated]
- public class GetCameraUploads : IReturn<ContentUploadHistory>
- {
- [ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string DeviceId { get; set; }
- }
-
- [Route("/Devices/CameraUploads", "POST", Summary = "Uploads content")]
- [Authenticated]
- public class PostCameraUpload : IRequiresRequestStream, IReturnVoid
- {
- [ApiMember(Name = "DeviceId", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string DeviceId { get; set; }
-
- [ApiMember(Name = "Album", Description = "Album", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Album { get; set; }
-
- [ApiMember(Name = "Name", Description = "Name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Name { get; set; }
-
- [ApiMember(Name = "Id", Description = "Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Id { get; set; }
-
- public Stream RequestStream { get; set; }
- }
-
- [Route("/Devices/Options", "POST", Summary = "Updates device options")]
- [Authenticated(Roles = "Admin")]
- public class PostDeviceOptions : DeviceOptions, IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- public class DeviceService : BaseApiService
- {
- private readonly IDeviceManager _deviceManager;
- private readonly IAuthenticationRepository _authRepo;
- private readonly ISessionManager _sessionManager;
-
- public DeviceService(IDeviceManager deviceManager, IAuthenticationRepository authRepo, ISessionManager sessionManager)
- {
- _deviceManager = deviceManager;
- _authRepo = authRepo;
- _sessionManager = sessionManager;
- }
-
- public void Post(PostDeviceOptions request)
- {
- _deviceManager.UpdateDeviceOptions(request.Id, request);
- }
-
- public object Get(GetDevices request)
- {
- return ToOptimizedResult(_deviceManager.GetDevices(request));
- }
-
- public object Get(GetDeviceInfo request)
- {
- return _deviceManager.GetDevice(request.Id);
- }
-
- public object Get(GetDeviceOptions request)
- {
- return _deviceManager.GetDeviceOptions(request.Id);
- }
-
- public object Get(GetCameraUploads request)
- {
- return ToOptimizedResult(_deviceManager.GetCameraUploadHistory(request.DeviceId));
- }
-
- public void Delete(DeleteDevice request)
- {
- var sessions = _authRepo.Get(new AuthenticationInfoQuery
- {
- DeviceId = request.Id
-
- }).Items;
-
- foreach (var session in sessions)
- {
- _sessionManager.Logout(session);
- }
- }
-
- public Task Post(PostCameraUpload request)
- {
- var deviceId = Request.QueryString["DeviceId"];
- var album = Request.QueryString["Album"];
- var id = Request.QueryString["Id"];
- var name = Request.QueryString["Name"];
-
- if (Request.ContentType.IndexOf("multi", StringComparison.OrdinalIgnoreCase) == -1)
- {
- return _deviceManager.AcceptCameraUpload(deviceId, request.RequestStream, new LocalFileInfo
- {
- MimeType = Request.ContentType,
- Album = album,
- Name = name,
- Id = id
- });
- }
- else
- {
- var file = Request.Files.Length == 0 ? null : Request.Files[0];
-
- return _deviceManager.AcceptCameraUpload(deviceId, file.InputStream, new LocalFileInfo
- {
- MimeType = file.ContentType,
- Album = album,
- Name = name,
- Id = id
- });
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/DisplayPreferencesService.cs b/MediaBrowser.Api/DisplayPreferencesService.cs
deleted file mode 100644
index d56023fe2..000000000
--- a/MediaBrowser.Api/DisplayPreferencesService.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System.Threading;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class UpdateDisplayPreferences
- /// </summary>
- [Route("/DisplayPreferences/{DisplayPreferencesId}", "POST", Summary = "Updates a user's display preferences for an item")]
- public class UpdateDisplayPreferences : DisplayPreferences, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "DisplayPreferencesId", Description = "DisplayPreferences Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string DisplayPreferencesId { get; set; }
-
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string UserId { get; set; }
- }
-
- [Route("/DisplayPreferences/{Id}", "GET", Summary = "Gets a user's display preferences for an item")]
- public class GetDisplayPreferences : IReturn<DisplayPreferences>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "Client", Description = "Client", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Client { get; set; }
- }
-
- /// <summary>
- /// Class DisplayPreferencesService
- /// </summary>
- [Authenticated]
- public class DisplayPreferencesService : BaseApiService
- {
- /// <summary>
- /// The _display preferences manager
- /// </summary>
- private readonly IDisplayPreferencesRepository _displayPreferencesManager;
- /// <summary>
- /// The _json serializer
- /// </summary>
- private readonly IJsonSerializer _jsonSerializer;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DisplayPreferencesService" /> class.
- /// </summary>
- /// <param name="jsonSerializer">The json serializer.</param>
- /// <param name="displayPreferencesManager">The display preferences manager.</param>
- public DisplayPreferencesService(IJsonSerializer jsonSerializer, IDisplayPreferencesRepository displayPreferencesManager)
- {
- _jsonSerializer = jsonSerializer;
- _displayPreferencesManager = displayPreferencesManager;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Get(GetDisplayPreferences request)
- {
- var result = _displayPreferencesManager.GetDisplayPreferences(request.Id, request.UserId, request.Client);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(UpdateDisplayPreferences request)
- {
- // Serialize to json and then back so that the core doesn't see the request dto type
- var displayPreferences = _jsonSerializer.DeserializeFromString<DisplayPreferences>(_jsonSerializer.SerializeToString(request));
-
- _displayPreferencesManager.SaveDisplayPreferences(displayPreferences, request.UserId, request.Client, CancellationToken.None);
- }
- }
-}
diff --git a/MediaBrowser.Api/EnvironmentService.cs b/MediaBrowser.Api/EnvironmentService.cs
deleted file mode 100644
index f4813e713..000000000
--- a/MediaBrowser.Api/EnvironmentService.cs
+++ /dev/null
@@ -1,321 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetDirectoryContents
- /// </summary>
- [Route("/Environment/DirectoryContents", "GET", Summary = "Gets the contents of a given directory in the file system")]
- public class GetDirectoryContents : IReturn<List<FileSystemEntryInfo>>
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Path { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [include files].
- /// </summary>
- /// <value><c>true</c> if [include files]; otherwise, <c>false</c>.</value>
- [ApiMember(Name = "IncludeFiles", Description = "An optional filter to include or exclude files from the results. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool IncludeFiles { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [include directories].
- /// </summary>
- /// <value><c>true</c> if [include directories]; otherwise, <c>false</c>.</value>
- [ApiMember(Name = "IncludeDirectories", Description = "An optional filter to include or exclude folders from the results. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool IncludeDirectories { get; set; }
- }
-
- [Route("/Environment/ValidatePath", "POST", Summary = "Gets the contents of a given directory in the file system")]
- public class ValidatePath
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Path { get; set; }
-
- public bool ValidateWriteable { get; set; }
- public bool? IsFile { get; set; }
- }
-
- [Route("/Environment/NetworkShares", "GET", Summary = "Gets shares from a network device")]
- public class GetNetworkShares : IReturn<List<FileSystemEntryInfo>>
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Path { get; set; }
- }
-
- /// <summary>
- /// Class GetDrives
- /// </summary>
- [Route("/Environment/Drives", "GET", Summary = "Gets available drives from the server's file system")]
- public class GetDrives : IReturn<List<FileSystemEntryInfo>>
- {
- }
-
- /// <summary>
- /// Class GetNetworkComputers
- /// </summary>
- [Route("/Environment/NetworkDevices", "GET", Summary = "Gets a list of devices on the network")]
- public class GetNetworkDevices : IReturn<List<FileSystemEntryInfo>>
- {
- }
-
- [Route("/Environment/ParentPath", "GET", Summary = "Gets the parent path of a given path")]
- public class GetParentPath : IReturn<string>
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Path { get; set; }
- }
-
- public class DefaultDirectoryBrowserInfo
- {
- public string Path { get; set; }
- }
-
- [Route("/Environment/DefaultDirectoryBrowser", "GET", Summary = "Gets the parent path of a given path")]
- public class GetDefaultDirectoryBrowser : IReturn<DefaultDirectoryBrowserInfo>
- {
-
- }
-
- /// <summary>
- /// Class EnvironmentService
- /// </summary>
- [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
- public class EnvironmentService : BaseApiService
- {
- const char UncSeparator = '\\';
- const string UncSeparatorString = "\\";
-
- /// <summary>
- /// The _network manager
- /// </summary>
- private readonly INetworkManager _networkManager;
- private readonly IFileSystem _fileSystem;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="EnvironmentService" /> class.
- /// </summary>
- /// <param name="networkManager">The network manager.</param>
- public EnvironmentService(INetworkManager networkManager, IFileSystem fileSystem)
- {
- if (networkManager == null)
- {
- throw new ArgumentNullException(nameof(networkManager));
- }
-
- _networkManager = networkManager;
- _fileSystem = fileSystem;
- }
-
- public void Post(ValidatePath request)
- {
- if (request.IsFile.HasValue)
- {
- if (request.IsFile.Value)
- {
- if (!File.Exists(request.Path))
- {
- throw new FileNotFoundException("File not found", request.Path);
- }
- }
- else
- {
- if (!Directory.Exists(request.Path))
- {
- throw new FileNotFoundException("File not found", request.Path);
- }
- }
- }
-
- else
- {
- if (!File.Exists(request.Path) && !Directory.Exists(request.Path))
- {
- throw new FileNotFoundException("Path not found", request.Path);
- }
-
- if (request.ValidateWriteable)
- {
- EnsureWriteAccess(request.Path);
- }
- }
- }
-
- protected void EnsureWriteAccess(string path)
- {
- var file = Path.Combine(path, Guid.NewGuid().ToString());
-
- File.WriteAllText(file, string.Empty);
- _fileSystem.DeleteFile(file);
- }
-
- public object Get(GetDefaultDirectoryBrowser request) =>
- ToOptimizedResult(new DefaultDirectoryBrowserInfo {Path = null});
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetDirectoryContents request)
- {
- var path = request.Path;
-
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(Path));
- }
-
- var networkPrefix = UncSeparatorString + UncSeparatorString;
-
- if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase) && path.LastIndexOf(UncSeparator) == 1)
- {
- return ToOptimizedResult(GetNetworkShares(path).OrderBy(i => i.Path).ToList());
- }
-
- return ToOptimizedResult(GetFileSystemEntries(request).ToList());
- }
-
- public object Get(GetNetworkShares request)
- {
- var path = request.Path;
-
- var shares = GetNetworkShares(path).OrderBy(i => i.Path).ToList();
-
- return ToOptimizedResult(shares);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetDrives request)
- {
- var result = GetDrives().ToList();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the list that is returned when an empty path is supplied
- /// </summary>
- /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
- private IEnumerable<FileSystemEntryInfo> GetDrives()
- {
- return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo
- {
- Name = d.Name,
- Path = d.FullName,
- Type = FileSystemEntryType.Directory
- });
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetNetworkDevices request)
- {
- var result = _networkManager.GetNetworkDevices().ToList();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the network shares.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
- private IEnumerable<FileSystemEntryInfo> GetNetworkShares(string path)
- {
- return _networkManager.GetNetworkShares(path).Where(s => s.ShareType == NetworkShareType.Disk).Select(c => new FileSystemEntryInfo
- {
- Name = c.Name,
- Path = Path.Combine(path, c.Name),
- Type = FileSystemEntryType.NetworkShare
- });
- }
-
- /// <summary>
- /// Gets the file system entries.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
- private IEnumerable<FileSystemEntryInfo> GetFileSystemEntries(GetDirectoryContents request)
- {
- var entries = _fileSystem.GetFileSystemEntries(request.Path).OrderBy(i => i.FullName).Where(i =>
- {
- var isDirectory = i.IsDirectory;
-
- if (!request.IncludeFiles && !isDirectory)
- {
- return false;
- }
-
- if (!request.IncludeDirectories && isDirectory)
- {
- return false;
- }
-
- return true;
- });
-
- return entries.Select(f => new FileSystemEntryInfo
- {
- Name = f.Name,
- Path = f.FullName,
- Type = f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File
-
- });
- }
-
- public object Get(GetParentPath request)
- {
- var parent = Path.GetDirectoryName(request.Path);
-
- if (string.IsNullOrEmpty(parent))
- {
- // Check if unc share
- var index = request.Path.LastIndexOf(UncSeparator);
-
- if (index != -1 && request.Path.IndexOf(UncSeparator) == 0)
- {
- parent = request.Path.Substring(0, index);
-
- if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
- {
- parent = null;
- }
- }
- }
-
- return parent;
- }
- }
-}
diff --git a/MediaBrowser.Api/FilterService.cs b/MediaBrowser.Api/FilterService.cs
deleted file mode 100644
index 9caf07cea..000000000
--- a/MediaBrowser.Api/FilterService.cs
+++ /dev/null
@@ -1,234 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Items/Filters", "GET", Summary = "Gets branding configuration")]
- public class GetQueryFiltersLegacy : IReturn<QueryFiltersLegacy>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string IncludeItemTypes { get; set; }
-
- [ApiMember(Name = "MediaTypes", Description = "Optional filter by MediaType. Allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string MediaTypes { get; set; }
-
- public string[] GetMediaTypes()
- {
- return (MediaTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetIncludeItemTypes()
- {
- return (IncludeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
- }
-
- [Route("/Items/Filters2", "GET", Summary = "Gets branding configuration")]
- public class GetQueryFilters : IReturn<QueryFilters>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string IncludeItemTypes { get; set; }
-
- [ApiMember(Name = "MediaTypes", Description = "Optional filter by MediaType. Allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string MediaTypes { get; set; }
-
- public string[] GetMediaTypes()
- {
- return (MediaTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetIncludeItemTypes()
- {
- return (IncludeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public bool? IsAiring { get; set; }
- public bool? IsMovie { get; set; }
- public bool? IsSports { get; set; }
- public bool? IsKids { get; set; }
- public bool? IsNews { get; set; }
- public bool? IsSeries { get; set; }
- public bool? Recursive { get; set; }
- }
-
- [Authenticated]
- public class FilterService : BaseApiService
- {
- private readonly ILibraryManager _libraryManager;
- private readonly IUserManager _userManager;
-
- public FilterService(ILibraryManager libraryManager, IUserManager userManager)
- {
- _libraryManager = libraryManager;
- _userManager = userManager;
- }
-
- public object Get(GetQueryFilters request)
- {
- var parentItem = string.IsNullOrEmpty(request.ParentId) ? null : _libraryManager.GetItemById(request.ParentId);
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, typeof(Trailer).Name, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "Program", StringComparison.OrdinalIgnoreCase))
- {
- parentItem = null;
- }
-
- var filters = new QueryFilters();
-
- var genreQuery = new InternalItemsQuery(user)
- {
- IncludeItemTypes = request.GetIncludeItemTypes(),
- DtoOptions = new Controller.Dto.DtoOptions
- {
- Fields = new ItemFields[] { },
- EnableImages = false,
- EnableUserData = false
- },
- IsAiring = request.IsAiring,
- IsMovie = request.IsMovie,
- IsSports = request.IsSports,
- IsKids = request.IsKids,
- IsNews = request.IsNews,
- IsSeries = request.IsSeries
- };
-
- // Non recursive not yet supported for library folders
- if ((request.Recursive ?? true) || parentItem is UserView || parentItem is ICollectionFolder)
- {
- genreQuery.AncestorIds = parentItem == null ? Array.Empty<Guid>() : new Guid[] { parentItem.Id };
- }
- else
- {
- genreQuery.Parent = parentItem;
- }
-
- if (string.Equals(request.IncludeItemTypes, "MusicAlbum", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "MusicVideo", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "MusicArtist", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "Audio", StringComparison.OrdinalIgnoreCase))
- {
- filters.Genres = _libraryManager.GetMusicGenres(genreQuery).Items.Select(i => new NameGuidPair
- {
- Name = i.Item1.Name,
- Id = i.Item1.Id
-
- }).ToArray();
- }
- else
- {
- filters.Genres = _libraryManager.GetGenres(genreQuery).Items.Select(i => new NameGuidPair
- {
- Name = i.Item1.Name,
- Id = i.Item1.Id
-
- }).ToArray();
- }
-
- return ToOptimizedResult(filters);
- }
-
- public object Get(GetQueryFiltersLegacy request)
- {
- var parentItem = string.IsNullOrEmpty(request.ParentId) ? null : _libraryManager.GetItemById(request.ParentId);
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, typeof(Trailer).Name, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(request.IncludeItemTypes, "Program", StringComparison.OrdinalIgnoreCase))
- {
- parentItem = null;
- }
-
- var item = string.IsNullOrEmpty(request.ParentId) ?
- user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder() :
- parentItem;
-
- var result = ((Folder)item).GetItemList(GetItemsQuery(request, user));
-
- var filters = GetFilters(result);
-
- return ToOptimizedResult(filters);
- }
-
- private QueryFiltersLegacy GetFilters(BaseItem[] items)
- {
- var result = new QueryFiltersLegacy();
-
- result.Years = items.Select(i => i.ProductionYear ?? -1)
- .Where(i => i > 0)
- .Distinct()
- .OrderBy(i => i)
- .ToArray();
-
- result.Genres = items.SelectMany(i => i.Genres)
- .DistinctNames()
- .OrderBy(i => i)
- .ToArray();
-
- result.Tags = items
- .SelectMany(i => i.Tags)
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .OrderBy(i => i)
- .ToArray();
-
- result.OfficialRatings = items
- .Select(i => i.OfficialRating)
- .Where(i => !string.IsNullOrWhiteSpace(i))
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .OrderBy(i => i)
- .ToArray();
-
- return result;
- }
-
- private InternalItemsQuery GetItemsQuery(GetQueryFiltersLegacy request, User user)
- {
- var query = new InternalItemsQuery
- {
- User = user,
- MediaTypes = request.GetMediaTypes(),
- IncludeItemTypes = request.GetIncludeItemTypes(),
- Recursive = true,
- EnableTotalRecordCount = false,
- DtoOptions = new Controller.Dto.DtoOptions
- {
- Fields = new ItemFields[] { ItemFields.Genres, ItemFields.Tags },
- EnableImages = false,
- EnableUserData = false
- }
- };
-
- return query;
- }
- }
-}
diff --git a/MediaBrowser.Api/IHasDtoOptions.cs b/MediaBrowser.Api/IHasDtoOptions.cs
deleted file mode 100644
index 03d3b3692..000000000
--- a/MediaBrowser.Api/IHasDtoOptions.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-namespace MediaBrowser.Api
-{
- public interface IHasDtoOptions : IHasItemFields
- {
- bool? EnableImages { get; set; }
- bool? EnableUserData { get; set; }
-
- int? ImageTypeLimit { get; set; }
-
- string EnableImageTypes { get; set; }
- }
-}
diff --git a/MediaBrowser.Api/IHasItemFields.cs b/MediaBrowser.Api/IHasItemFields.cs
deleted file mode 100644
index 8598ea262..000000000
--- a/MediaBrowser.Api/IHasItemFields.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Interface IHasItemFields
- /// </summary>
- public interface IHasItemFields
- {
- /// <summary>
- /// Gets or sets the fields.
- /// </summary>
- /// <value>The fields.</value>
- string Fields { get; set; }
- }
-
- /// <summary>
- /// Class ItemFieldsExtensions.
- /// </summary>
- public static class ItemFieldsExtensions
- {
- /// <summary>
- /// Gets the item fields.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>IEnumerable{ItemFields}.</returns>
- public static ItemFields[] GetItemFields(this IHasItemFields request)
- {
- var val = request.Fields;
-
- if (string.IsNullOrEmpty(val))
- {
- return new ItemFields[] { };
- }
-
- return val.Split(',').Select(v =>
- {
- if (Enum.TryParse(v, true, out ItemFields value))
- {
- return (ItemFields?)value;
- }
- return null;
-
- }).Where(i => i.HasValue).Select(i => i.Value).ToArray();
- }
- }
-}
diff --git a/MediaBrowser.Api/Images/ImageByNameService.cs b/MediaBrowser.Api/Images/ImageByNameService.cs
deleted file mode 100644
index 922bd8ed6..000000000
--- a/MediaBrowser.Api/Images/ImageByNameService.cs
+++ /dev/null
@@ -1,273 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Images
-{
- /// <summary>
- /// Class GetGeneralImage
- /// </summary>
- [Route("/Images/General/{Name}/{Type}", "GET", Summary = "Gets a general image by name")]
- public class GetGeneralImage
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The name of the image", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- [ApiMember(Name = "Type", Description = "Image Type (primary, backdrop, logo, etc).", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Type { get; set; }
- }
-
- /// <summary>
- /// Class GetRatingImage
- /// </summary>
- [Route("/Images/Ratings/{Theme}/{Name}", "GET", Summary = "Gets a rating image by name")]
- public class GetRatingImage
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The name of the image", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the theme.
- /// </summary>
- /// <value>The theme.</value>
- [ApiMember(Name = "Theme", Description = "The theme to get the image from", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Theme { get; set; }
- }
-
- /// <summary>
- /// Class GetMediaInfoImage
- /// </summary>
- [Route("/Images/MediaInfo/{Theme}/{Name}", "GET", Summary = "Gets a media info image by name")]
- public class GetMediaInfoImage
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The name of the image", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the theme.
- /// </summary>
- /// <value>The theme.</value>
- [ApiMember(Name = "Theme", Description = "The theme to get the image from", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Theme { get; set; }
- }
-
- [Route("/Images/MediaInfo", "GET", Summary = "Gets all media info image by name")]
- [Authenticated]
- public class GetMediaInfoImages : IReturn<List<ImageByNameInfo>>
- {
- }
-
- [Route("/Images/Ratings", "GET", Summary = "Gets all rating images by name")]
- [Authenticated]
- public class GetRatingImages : IReturn<List<ImageByNameInfo>>
- {
- }
-
- [Route("/Images/General", "GET", Summary = "Gets all general images by name")]
- [Authenticated]
- public class GetGeneralImages : IReturn<List<ImageByNameInfo>>
- {
- }
-
- /// <summary>
- /// Class ImageByNameService
- /// </summary>
- public class ImageByNameService : BaseApiService
- {
- /// <summary>
- /// The _app paths
- /// </summary>
- private readonly IServerApplicationPaths _appPaths;
-
- private readonly IFileSystem _fileSystem;
- private readonly IHttpResultFactory _resultFactory;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImageByNameService" /> class.
- /// </summary>
- /// <param name="appPaths">The app paths.</param>
- public ImageByNameService(IServerApplicationPaths appPaths, IFileSystem fileSystem, IHttpResultFactory resultFactory)
- {
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- _resultFactory = resultFactory;
- }
-
- public object Get(GetMediaInfoImages request)
- {
- return ToOptimizedResult(GetImageList(_appPaths.MediaInfoImagesPath, true));
- }
-
- public object Get(GetRatingImages request)
- {
- return ToOptimizedResult(GetImageList(_appPaths.RatingsPath, true));
- }
-
- public object Get(GetGeneralImages request)
- {
- return ToOptimizedResult(GetImageList(_appPaths.GeneralPath, false));
- }
-
- private List<ImageByNameInfo> GetImageList(string path, bool supportsThemes)
- {
- try
- {
- return _fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, true)
- .Select(i => new ImageByNameInfo
- {
- Name = _fileSystem.GetFileNameWithoutExtension(i),
- FileLength = i.Length,
-
- // For themeable images, use the Theme property
- // For general images, the same object structure is fine,
- // but it's not owned by a theme, so call it Context
- Theme = supportsThemes ? GetThemeName(i.FullName, path) : null,
- Context = supportsThemes ? null : GetThemeName(i.FullName, path),
-
- Format = i.Extension.ToLowerInvariant().TrimStart('.')
- })
- .OrderBy(i => i.Name)
- .ToList();
- }
- catch (IOException)
- {
- return new List<ImageByNameInfo>();
- }
- }
-
- private string GetThemeName(string path, string rootImagePath)
- {
- var parentName = Path.GetDirectoryName(path);
-
- if (string.Equals(parentName, rootImagePath, StringComparison.OrdinalIgnoreCase))
- {
- return null;
- }
-
- parentName = Path.GetFileName(parentName);
-
- return string.Equals(parentName, "all", StringComparison.OrdinalIgnoreCase) ?
- null :
- parentName;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetGeneralImage request)
- {
- var filename = string.Equals(request.Type, "primary", StringComparison.OrdinalIgnoreCase)
- ? "folder"
- : request.Type;
-
- var paths = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(_appPaths.GeneralPath, request.Name, filename + i)).ToList();
-
- var path = paths.FirstOrDefault(File.Exists) ?? paths.FirstOrDefault();
-
- return _resultFactory.GetStaticFileResult(Request, path);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetRatingImage request)
- {
- var themeFolder = Path.Combine(_appPaths.RatingsPath, request.Theme);
-
- if (Directory.Exists(themeFolder))
- {
- var path = BaseItem.SupportedImageExtensions
- .Select(i => Path.Combine(themeFolder, request.Name + i))
- .FirstOrDefault(File.Exists);
-
- if (!string.IsNullOrEmpty(path))
- {
- return _resultFactory.GetStaticFileResult(Request, path);
- }
- }
-
- var allFolder = Path.Combine(_appPaths.RatingsPath, "all");
-
- if (Directory.Exists(allFolder))
- {
- // Avoid implicitly captured closure
- var currentRequest = request;
-
- var path = BaseItem.SupportedImageExtensions
- .Select(i => Path.Combine(allFolder, currentRequest.Name + i))
- .FirstOrDefault(File.Exists);
-
- if (!string.IsNullOrEmpty(path))
- {
- return _resultFactory.GetStaticFileResult(Request, path);
- }
- }
-
- throw new ResourceNotFoundException("MediaInfo image not found: " + request.Name);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetMediaInfoImage request)
- {
- var themeFolder = Path.Combine(_appPaths.MediaInfoImagesPath, request.Theme);
-
- if (Directory.Exists(themeFolder))
- {
- var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, request.Name + i))
- .FirstOrDefault(File.Exists);
-
- if (!string.IsNullOrEmpty(path))
- {
- return _resultFactory.GetStaticFileResult(Request, path);
- }
- }
-
- var allFolder = Path.Combine(_appPaths.MediaInfoImagesPath, "all");
-
- if (Directory.Exists(allFolder))
- {
- // Avoid implicitly captured closure
- var currentRequest = request;
-
- var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, currentRequest.Name + i))
- .FirstOrDefault(File.Exists);
-
- if (!string.IsNullOrEmpty(path))
- {
- return _resultFactory.GetStaticFileResult(Request, path);
- }
- }
-
- throw new ResourceNotFoundException("MediaInfo image not found: " + request.Name);
- }
- }
-}
diff --git a/MediaBrowser.Api/Images/ImageRequest.cs b/MediaBrowser.Api/Images/ImageRequest.cs
deleted file mode 100644
index 71ff09b63..000000000
--- a/MediaBrowser.Api/Images/ImageRequest.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Images
-{
- /// <summary>
- /// Class ImageRequest
- /// </summary>
- public class ImageRequest : DeleteImageRequest
- {
- /// <summary>
- /// The max width
- /// </summary>
- [ApiMember(Name = "MaxWidth", Description = "The maximum image width to return.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxWidth { get; set; }
-
- /// <summary>
- /// The max height
- /// </summary>
- [ApiMember(Name = "MaxHeight", Description = "The maximum image height to return.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxHeight { get; set; }
-
- /// <summary>
- /// The width
- /// </summary>
- [ApiMember(Name = "Width", Description = "The fixed image width to return.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Width { get; set; }
-
- /// <summary>
- /// The height
- /// </summary>
- [ApiMember(Name = "Height", Description = "The fixed image height to return.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Height { get; set; }
-
- /// <summary>
- /// Gets or sets the quality.
- /// </summary>
- /// <value>The quality.</value>
- [ApiMember(Name = "Quality", Description = "Optional quality setting, from 0-100. Defaults to 90 and should suffice in most cases.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Quality { get; set; }
-
- /// <summary>
- /// Gets or sets the tag.
- /// </summary>
- /// <value>The tag.</value>
- [ApiMember(Name = "Tag", Description = "Optional. Supply the cache tag from the item object to receive strong caching headers.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Tag { get; set; }
-
- [ApiMember(Name = "CropWhitespace", Description = "Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? CropWhitespace { get; set; }
-
- [ApiMember(Name = "EnableImageEnhancers", Description = "Enable or disable image enhancers such as cover art.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool EnableImageEnhancers { get; set; }
-
- [ApiMember(Name = "Format", Description = "Determines the output foramt of the image - original,gif,jpg,png", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public string Format { get; set; }
-
- [ApiMember(Name = "AddPlayedIndicator", Description = "Optional. Add a played indicator", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool AddPlayedIndicator { get; set; }
-
- [ApiMember(Name = "PercentPlayed", Description = "Optional percent to render for the percent played overlay", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public double? PercentPlayed { get; set; }
-
- [ApiMember(Name = "UnplayedCount", Description = "Optional unplayed count overlay to render", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? UnplayedCount { get; set; }
-
- public int? Blur { get; set; }
-
- [ApiMember(Name = "BackgroundColor", Description = "Optional. Apply a background color for transparent images.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string BackgroundColor { get; set; }
-
- [ApiMember(Name = "ForegroundLayer", Description = "Optional. Apply a foreground layer on top of the image.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ForegroundLayer { get; set; }
-
- public ImageRequest()
- {
- EnableImageEnhancers = true;
- }
- }
-
- /// <summary>
- /// Class DeleteImageRequest
- /// </summary>
- public class DeleteImageRequest
- {
- /// <summary>
- /// Gets or sets the type of the image.
- /// </summary>
- /// <value>The type of the image.</value>
- [ApiMember(Name = "Type", Description = "Image Type", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET,POST,DELETE")]
- public ImageType Type { get; set; }
-
- /// <summary>
- /// Gets or sets the index.
- /// </summary>
- /// <value>The index.</value>
- [ApiMember(Name = "Index", Description = "Image Index", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET,POST,DELETE")]
- public int? Index { get; set; }
- }
-}
diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs
deleted file mode 100644
index 61db7b8d4..000000000
--- a/MediaBrowser.Api/Images/ImageService.cs
+++ /dev/null
@@ -1,762 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Images
-{
- /// <summary>
- /// Class GetItemImage
- /// </summary>
- [Route("/Items/{Id}/Images", "GET", Summary = "Gets information about an item's images")]
- [Authenticated]
- public class GetItemImageInfos : IReturn<List<ImageInfo>>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Items/{Id}/Images/{Type}", "GET")]
- [Route("/Items/{Id}/Images/{Type}/{Index}", "GET")]
- [Route("/Items/{Id}/Images/{Type}", "HEAD")]
- [Route("/Items/{Id}/Images/{Type}/{Index}", "HEAD")]
- [Route("/Items/{Id}/Images/{Type}/{Index}/{Tag}/{Format}/{MaxWidth}/{MaxHeight}/{PercentPlayed}/{UnplayedCount}", "GET")]
- [Route("/Items/{Id}/Images/{Type}/{Index}/{Tag}/{Format}/{MaxWidth}/{MaxHeight}/{PercentPlayed}/{UnplayedCount}", "HEAD")]
- public class GetItemImage : ImageRequest
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class UpdateItemImageIndex
- /// </summary>
- [Route("/Items/{Id}/Images/{Type}/{Index}/Index", "POST", Summary = "Updates the index for an item image")]
- [Authenticated(Roles = "admin")]
- public class UpdateItemImageIndex : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the type of the image.
- /// </summary>
- /// <value>The type of the image.</value>
- [ApiMember(Name = "Type", Description = "Image Type", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public ImageType Type { get; set; }
-
- /// <summary>
- /// Gets or sets the index.
- /// </summary>
- /// <value>The index.</value>
- [ApiMember(Name = "Index", Description = "Image Index", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int Index { get; set; }
-
- /// <summary>
- /// Gets or sets the new index.
- /// </summary>
- /// <value>The new index.</value>
- [ApiMember(Name = "NewIndex", Description = "The new image index", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public int NewIndex { get; set; }
- }
-
- /// <summary>
- /// Class GetPersonImage
- /// </summary>
- [Route("/Artists/{Name}/Images/{Type}", "GET")]
- [Route("/Artists/{Name}/Images/{Type}/{Index}", "GET")]
- [Route("/Genres/{Name}/Images/{Type}", "GET")]
- [Route("/Genres/{Name}/Images/{Type}/{Index}", "GET")]
- [Route("/MusicGenres/{Name}/Images/{Type}", "GET")]
- [Route("/MusicGenres/{Name}/Images/{Type}/{Index}", "GET")]
- [Route("/Persons/{Name}/Images/{Type}", "GET")]
- [Route("/Persons/{Name}/Images/{Type}/{Index}", "GET")]
- [Route("/Studios/{Name}/Images/{Type}", "GET")]
- [Route("/Studios/{Name}/Images/{Type}/{Index}", "GET")]
- ////[Route("/Years/{Year}/Images/{Type}", "GET")]
- ////[Route("/Years/{Year}/Images/{Type}/{Index}", "GET")]
- [Route("/Artists/{Name}/Images/{Type}", "HEAD")]
- [Route("/Artists/{Name}/Images/{Type}/{Index}", "HEAD")]
- [Route("/Genres/{Name}/Images/{Type}", "HEAD")]
- [Route("/Genres/{Name}/Images/{Type}/{Index}", "HEAD")]
- [Route("/MusicGenres/{Name}/Images/{Type}", "HEAD")]
- [Route("/MusicGenres/{Name}/Images/{Type}/{Index}", "HEAD")]
- [Route("/Persons/{Name}/Images/{Type}", "HEAD")]
- [Route("/Persons/{Name}/Images/{Type}/{Index}", "HEAD")]
- [Route("/Studios/{Name}/Images/{Type}", "HEAD")]
- [Route("/Studios/{Name}/Images/{Type}/{Index}", "HEAD")]
- ////[Route("/Years/{Year}/Images/{Type}", "HEAD")]
- ////[Route("/Years/{Year}/Images/{Type}/{Index}", "HEAD")]
- public class GetItemByNameImage : ImageRequest
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "Item name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
- }
-
- /// <summary>
- /// Class GetUserImage
- /// </summary>
- [Route("/Users/{Id}/Images/{Type}", "GET")]
- [Route("/Users/{Id}/Images/{Type}/{Index}", "GET")]
- [Route("/Users/{Id}/Images/{Type}", "HEAD")]
- [Route("/Users/{Id}/Images/{Type}/{Index}", "HEAD")]
- public class GetUserImage : ImageRequest
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class DeleteItemImage
- /// </summary>
- [Route("/Items/{Id}/Images/{Type}", "DELETE")]
- [Route("/Items/{Id}/Images/{Type}/{Index}", "DELETE")]
- [Authenticated(Roles = "admin")]
- public class DeleteItemImage : DeleteImageRequest, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class DeleteUserImage
- /// </summary>
- [Route("/Users/{Id}/Images/{Type}", "DELETE")]
- [Route("/Users/{Id}/Images/{Type}/{Index}", "DELETE")]
- [Authenticated]
- public class DeleteUserImage : DeleteImageRequest, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class PostUserImage
- /// </summary>
- [Route("/Users/{Id}/Images/{Type}", "POST")]
- [Route("/Users/{Id}/Images/{Type}/{Index}", "POST")]
- [Authenticated]
- public class PostUserImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// The raw Http Request Input Stream
- /// </summary>
- /// <value>The request stream.</value>
- public Stream RequestStream { get; set; }
- }
-
- /// <summary>
- /// Class PostItemImage
- /// </summary>
- [Route("/Items/{Id}/Images/{Type}", "POST")]
- [Route("/Items/{Id}/Images/{Type}/{Index}", "POST")]
- [Authenticated(Roles = "admin")]
- public class PostItemImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// The raw Http Request Input Stream
- /// </summary>
- /// <value>The request stream.</value>
- public Stream RequestStream { get; set; }
- }
-
- /// <summary>
- /// Class ImageService
- /// </summary>
- public class ImageService : BaseApiService
- {
- private readonly IUserManager _userManager;
-
- private readonly ILibraryManager _libraryManager;
-
- private readonly IProviderManager _providerManager;
-
- private readonly IItemRepository _itemRepo;
- private readonly IImageProcessor _imageProcessor;
- private readonly IFileSystem _fileSystem;
- private readonly IAuthorizationContext _authContext;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImageService" /> class.
- /// </summary>
- public ImageService(IUserManager userManager, ILibraryManager libraryManager, IProviderManager providerManager, IItemRepository itemRepo, IImageProcessor imageProcessor, IFileSystem fileSystem, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _libraryManager = libraryManager;
- _providerManager = providerManager;
- _itemRepo = itemRepo;
- _imageProcessor = imageProcessor;
- _fileSystem = fileSystem;
- _authContext = authContext;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetItemImageInfos request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var result = GetItemImageInfos(item);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item image infos.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>Task{List{ImageInfo}}.</returns>
- public List<ImageInfo> GetItemImageInfos(BaseItem item)
- {
- var list = new List<ImageInfo>();
-
- var itemImages = item.ImageInfos;
-
- foreach (var image in itemImages)
- {
- if (!item.AllowsMultipleImages(image.Type))
- {
- var info = GetImageInfo(item, image, null);
-
- if (info != null)
- {
- list.Add(info);
- }
- }
- }
-
- foreach (var imageType in itemImages.Select(i => i.Type).Distinct().Where(item.AllowsMultipleImages))
- {
- var index = 0;
-
- // Prevent implicitly captured closure
- var currentImageType = imageType;
-
- foreach (var image in itemImages.Where(i => i.Type == currentImageType))
- {
- var info = GetImageInfo(item, image, index);
-
- if (info != null)
- {
- list.Add(info);
- }
-
- index++;
- }
- }
-
- return list;
- }
-
- private ImageInfo GetImageInfo(BaseItem item, ItemImageInfo info, int? imageIndex)
- {
- try
- {
- int? width = null;
- int? height = null;
- long length = 0;
-
- try
- {
- if (info.IsLocalFile)
- {
- var fileInfo = _fileSystem.GetFileInfo(info.Path);
- length = fileInfo.Length;
-
- ImageDimensions size = _imageProcessor.GetImageDimensions(item, info, true);
- width = size.Width;
- height = size.Height;
-
- if (width <= 0 || height <= 0)
- {
- width = null;
- height = null;
- }
-
- }
- }
- catch
- {
-
- }
- return new ImageInfo
- {
- Path = info.Path,
- ImageIndex = imageIndex,
- ImageType = info.Type,
- ImageTag = _imageProcessor.GetImageCacheTag(item, info),
- Size = length,
- Width = width,
- Height = height
- };
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error getting image information for {path}", info.Path);
-
- return null;
- }
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetItemImage request)
- {
- return GetImage(request, request.Id, null, false);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Head(GetItemImage request)
- {
- return GetImage(request, request.Id, null, true);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetUserImage request)
- {
- var item = _userManager.GetUserById(request.Id);
-
- return GetImage(request, Guid.Empty, item, false);
- }
-
- public object Head(GetUserImage request)
- {
- var item = _userManager.GetUserById(request.Id);
-
- return GetImage(request, Guid.Empty, item, true);
- }
-
- public object Get(GetItemByNameImage request)
- {
- var type = GetPathValue(0);
-
- var item = GetItemByName(request.Name, type, _libraryManager, new DtoOptions(false));
-
- return GetImage(request, item.Id, item, false);
- }
-
- public object Head(GetItemByNameImage request)
- {
- var type = GetPathValue(0);
-
- var item = GetItemByName(request.Name, type, _libraryManager, new DtoOptions(false));
-
- return GetImage(request, item.Id, item, true);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(PostUserImage request)
- {
- var userId = GetPathValue(1);
- AssertCanUpdateUser(_authContext, _userManager, new Guid(userId), true);
-
- request.Type = (ImageType)Enum.Parse(typeof(ImageType), GetPathValue(3), true);
-
- var item = _userManager.GetUserById(userId);
-
- return PostImage(item, request.RequestStream, request.Type, Request.ContentType);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(PostItemImage request)
- {
- var id = GetPathValue(1);
-
- request.Type = (ImageType)Enum.Parse(typeof(ImageType), GetPathValue(3), true);
-
- var item = _libraryManager.GetItemById(id);
-
- return PostImage(item, request.RequestStream, request.Type, Request.ContentType);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(DeleteUserImage request)
- {
- var userId = request.Id;
- AssertCanUpdateUser(_authContext, _userManager, userId, true);
-
- var item = _userManager.GetUserById(userId);
-
- item.DeleteImage(request.Type, request.Index ?? 0);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(DeleteItemImage request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- item.DeleteImage(request.Type, request.Index ?? 0);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(UpdateItemImageIndex request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- UpdateItemIndex(item, request.Type, request.Index, request.NewIndex);
- }
-
- /// <summary>
- /// Updates the index of the item.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="type">The type.</param>
- /// <param name="currentIndex">Index of the current.</param>
- /// <param name="newIndex">The new index.</param>
- /// <returns>Task.</returns>
- private void UpdateItemIndex(BaseItem item, ImageType type, int currentIndex, int newIndex)
- {
- item.SwapImages(type, currentIndex, newIndex);
- }
-
- /// <summary>
- /// Gets the image.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="item">The item.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ResourceNotFoundException"></exception>
- public Task<object> GetImage(ImageRequest request, Guid itemId, BaseItem item, bool isHeadRequest)
- {
- if (request.PercentPlayed.HasValue)
- {
- if (request.PercentPlayed.Value <= 0)
- {
- request.PercentPlayed = null;
- }
- else if (request.PercentPlayed.Value >= 100)
- {
- request.PercentPlayed = null;
- request.AddPlayedIndicator = true;
- }
- }
- if (request.PercentPlayed.HasValue)
- {
- request.UnplayedCount = null;
- }
- if (request.UnplayedCount.HasValue)
- {
- if (request.UnplayedCount.Value <= 0)
- {
- request.UnplayedCount = null;
- }
- }
-
- if (item == null)
- {
- item = _libraryManager.GetItemById(itemId);
-
- if (item == null)
- {
- throw new ResourceNotFoundException(string.Format("Item {0} not found.", itemId.ToString("N")));
- }
- }
-
- var imageInfo = GetImageInfo(request, item);
-
- if (imageInfo == null)
- {
- var displayText = item == null ? itemId.ToString() : item.Name;
- throw new ResourceNotFoundException(string.Format("{0} does not have an image of type {1}", displayText, request.Type));
- }
-
- IImageEnhancer[] supportedImageEnhancers;
-
- if (_imageProcessor.ImageEnhancers.Length > 0)
- {
- if (item == null)
- {
- item = _libraryManager.GetItemById(itemId);
- }
-
- supportedImageEnhancers = request.EnableImageEnhancers ? _imageProcessor.GetSupportedEnhancers(item, request.Type) : Array.Empty<IImageEnhancer>();
- }
- else
- {
- supportedImageEnhancers = Array.Empty<IImageEnhancer>();
- }
-
- var cropwhitespace = request.Type == ImageType.Logo ||
- request.Type == ImageType.Art;
-
- if (request.CropWhitespace.HasValue)
- {
- cropwhitespace = request.CropWhitespace.Value;
- }
-
- var outputFormats = GetOutputFormats(request);
-
- TimeSpan? cacheDuration = null;
-
- if (!string.IsNullOrEmpty(request.Tag))
- {
- cacheDuration = TimeSpan.FromDays(365);
- }
-
- var responseHeaders = new Dictionary<string, string>
- {
- {"transferMode.dlna.org", "Interactive"},
- {"realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*"}
- };
-
- return GetImageResult(item,
- itemId,
- request,
- imageInfo,
- cropwhitespace,
- outputFormats,
- supportedImageEnhancers,
- cacheDuration,
- responseHeaders,
- isHeadRequest);
- }
-
- private async Task<object> GetImageResult(BaseItem item,
- Guid itemId,
- ImageRequest request,
- ItemImageInfo image,
- bool cropwhitespace,
- ImageFormat[] supportedFormats,
- IImageEnhancer[] enhancers,
- TimeSpan? cacheDuration,
- IDictionary<string, string> headers,
- bool isHeadRequest)
- {
- var options = new ImageProcessingOptions
- {
- CropWhiteSpace = cropwhitespace,
- Enhancers = enhancers,
- Height = request.Height,
- ImageIndex = request.Index ?? 0,
- Image = image,
- Item = item,
- ItemId = itemId,
- MaxHeight = request.MaxHeight,
- MaxWidth = request.MaxWidth,
- Quality = request.Quality ?? 100,
- Width = request.Width,
- AddPlayedIndicator = request.AddPlayedIndicator,
- PercentPlayed = request.PercentPlayed ?? 0,
- UnplayedCount = request.UnplayedCount,
- Blur = request.Blur,
- BackgroundColor = request.BackgroundColor,
- ForegroundLayer = request.ForegroundLayer,
- SupportedOutputFormats = supportedFormats
- };
-
- var imageResult = await _imageProcessor.ProcessImage(options).ConfigureAwait(false);
-
- headers["Vary"] = "Accept";
-
- return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- {
- CacheDuration = cacheDuration,
- ResponseHeaders = headers,
- ContentType = imageResult.Item2,
- DateLastModified = imageResult.Item3,
- IsHeadRequest = isHeadRequest,
- Path = imageResult.Item1,
-
- FileShare = FileShareMode.Read
-
- }).ConfigureAwait(false);
- }
-
- private ImageFormat[] GetOutputFormats(ImageRequest request)
- {
- if (!string.IsNullOrWhiteSpace(request.Format))
- {
- if (Enum.TryParse(request.Format, true, out ImageFormat format))
- {
- return new ImageFormat[] { format };
- }
- }
-
- return GetClientSupportedFormats();
- }
-
- private ImageFormat[] GetClientSupportedFormats()
- {
- //logger.LogDebug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty<string>()));
- var supportedFormats = (Request.AcceptTypes ?? Array.Empty<string>()).Select(i => i.Split(';')[0]).ToArray();
- var acceptParam = Request.QueryString["accept"];
-
- var supportsWebP = SupportsFormat(supportedFormats, acceptParam, "webp", false);
-
- if (!supportsWebP)
- {
- var userAgent = Request.UserAgent ?? string.Empty;
- if (userAgent.IndexOf("crosswalk", StringComparison.OrdinalIgnoreCase) != -1 &&
- userAgent.IndexOf("android", StringComparison.OrdinalIgnoreCase) != -1)
- {
- supportsWebP = true;
- }
- }
-
- var formats = new List<ImageFormat>(4);
-
- if (supportsWebP)
- {
- formats.Add(ImageFormat.Webp);
- }
-
- formats.Add(ImageFormat.Jpg);
- formats.Add(ImageFormat.Png);
-
- if (SupportsFormat(supportedFormats, acceptParam, "gif", true))
- {
- formats.Add(ImageFormat.Gif);
- }
-
- return formats.ToArray();
- }
-
- private bool SupportsFormat(string[] requestAcceptTypes, string acceptParam, string format, bool acceptAll)
- {
- var mimeType = "image/" + format;
-
- if (requestAcceptTypes.Contains(mimeType))
- {
- return true;
- }
-
- if (acceptAll && requestAcceptTypes.Contains("*/*"))
- {
- return true;
- }
-
- return string.Equals(Request.QueryString["accept"], format, StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Gets the image path.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
- private ItemImageInfo GetImageInfo(ImageRequest request, BaseItem item)
- {
- var index = request.Index ?? 0;
-
- return item.GetImageInfo(request.Type, index);
- }
-
- /// <summary>
- /// Posts the image.
- /// </summary>
- /// <param name="entity">The entity.</param>
- /// <param name="inputStream">The input stream.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="mimeType">Type of the MIME.</param>
- /// <returns>Task.</returns>
- public async Task PostImage(BaseItem entity, Stream inputStream, ImageType imageType, string mimeType)
- {
- using (var reader = new StreamReader(inputStream))
- {
- var text = await reader.ReadToEndAsync().ConfigureAwait(false);
-
- var bytes = Convert.FromBase64String(text);
-
- var memoryStream = new MemoryStream(bytes)
- {
- Position = 0
- };
-
- // Handle image/png; charset=utf-8
- mimeType = mimeType.Split(';').FirstOrDefault();
-
- await _providerManager.SaveImage(entity, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false);
-
- entity.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/Images/RemoteImageService.cs b/MediaBrowser.Api/Images/RemoteImageService.cs
deleted file mode 100644
index 24d4751c5..000000000
--- a/MediaBrowser.Api/Images/RemoteImageService.cs
+++ /dev/null
@@ -1,291 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Images
-{
- public class BaseRemoteImageRequest : IReturn<RemoteImageResult>
- {
- [ApiMember(Name = "Type", Description = "The image type", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public ImageType? Type { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "ProviderName", Description = "Optional. The image provider to use", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ProviderName { get; set; }
-
- [ApiMember(Name = "IncludeAllLanguages", Description = "Optional.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludeAllLanguages { get; set; }
- }
-
- [Route("/Items/{Id}/RemoteImages", "GET", Summary = "Gets available remote images for an item")]
- [Authenticated]
- public class GetRemoteImages : BaseRemoteImageRequest
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Items/{Id}/RemoteImages/Providers", "GET", Summary = "Gets available remote image providers for an item")]
- [Authenticated]
- public class GetRemoteImageProviders : IReturn<List<ImageProviderInfo>>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- public class BaseDownloadRemoteImage : IReturnVoid
- {
- [ApiMember(Name = "Type", Description = "The image type", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public ImageType Type { get; set; }
-
- [ApiMember(Name = "ProviderName", Description = "The image provider", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string ProviderName { get; set; }
-
- [ApiMember(Name = "ImageUrl", Description = "The image url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string ImageUrl { get; set; }
- }
-
- [Route("/Items/{Id}/RemoteImages/Download", "POST", Summary = "Downloads a remote image for an item")]
- [Authenticated(Roles = "Admin")]
- public class DownloadRemoteImage : BaseDownloadRemoteImage
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Images/Remote", "GET", Summary = "Gets a remote image")]
- public class GetRemoteImage
- {
- [ApiMember(Name = "ImageUrl", Description = "The image url", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ImageUrl { get; set; }
- }
-
- public class RemoteImageService : BaseApiService
- {
- private readonly IProviderManager _providerManager;
-
- private readonly IServerApplicationPaths _appPaths;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
-
- private readonly IDtoService _dtoService;
- private readonly ILibraryManager _libraryManager;
-
- public RemoteImageService(IProviderManager providerManager, IDtoService dtoService, IServerApplicationPaths appPaths, IHttpClient httpClient, IFileSystem fileSystem, ILibraryManager libraryManager)
- {
- _providerManager = providerManager;
- _dtoService = dtoService;
- _appPaths = appPaths;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _libraryManager = libraryManager;
- }
-
- public object Get(GetRemoteImageProviders request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var result = GetImageProviders(item);
-
- return ToOptimizedResult(result);
- }
-
- private List<ImageProviderInfo> GetImageProviders(BaseItem item)
- {
- return _providerManager.GetRemoteImageProviderInfo(item).ToList();
- }
-
- public async Task<object> Get(GetRemoteImages request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var images = await _providerManager.GetAvailableRemoteImages(item, new RemoteImageQuery
- {
- ProviderName = request.ProviderName,
- IncludeAllLanguages = request.IncludeAllLanguages,
- IncludeDisabledProviders = true,
- ImageType = request.Type
-
- }, CancellationToken.None).ConfigureAwait(false);
-
- var imagesList = images.ToArray();
-
- var allProviders = _providerManager.GetRemoteImageProviderInfo(item);
-
- if (request.Type.HasValue)
- {
- allProviders = allProviders.Where(i => i.SupportedImages.Contains(request.Type.Value));
- }
-
- var result = new RemoteImageResult
- {
- TotalRecordCount = imagesList.Length,
- Providers = allProviders.Select(i => i.Name)
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .ToArray()
- };
-
- if (request.StartIndex.HasValue)
- {
- imagesList = imagesList.Skip(request.StartIndex.Value)
- .ToArray();
- }
-
- if (request.Limit.HasValue)
- {
- imagesList = imagesList.Take(request.Limit.Value)
- .ToArray();
- }
-
- result.Images = imagesList;
-
- return result;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(DownloadRemoteImage request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- return DownloadRemoteImage(item, request);
- }
-
- /// <summary>
- /// Downloads the remote image.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="request">The request.</param>
- /// <returns>Task.</returns>
- private async Task DownloadRemoteImage(BaseItem item, BaseDownloadRemoteImage request)
- {
- await _providerManager.SaveImage(item, request.ImageUrl, request.Type, null, CancellationToken.None).ConfigureAwait(false);
-
- item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetRemoteImage request)
- {
- var urlHash = request.ImageUrl.GetMD5();
- var pointerCachePath = GetFullCachePath(urlHash.ToString());
-
- string contentPath;
-
- try
- {
- contentPath = File.ReadAllText(pointerCachePath);
-
- if (File.Exists(contentPath))
- {
- return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
- }
- }
- catch (FileNotFoundException)
- {
- // Means the file isn't cached yet
- }
- catch (IOException)
- {
- // Means the file isn't cached yet
- }
-
- await DownloadImage(request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
-
- // Read the pointer file again
- contentPath = File.ReadAllText(pointerCachePath);
-
- return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Downloads the image.
- /// </summary>
- /// <param name="url">The URL.</param>
- /// <param name="urlHash">The URL hash.</param>
- /// <param name="pointerCachePath">The pointer cache path.</param>
- /// <returns>Task.</returns>
- private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
- {
- using (var result = await _httpClient.GetResponse(new HttpRequestOptions
- {
- Url = url,
- BufferContent = false
-
- }).ConfigureAwait(false))
- {
- var ext = result.ContentType.Split('/').Last();
-
- var fullCachePath = GetFullCachePath(urlHash + "." + ext);
-
- Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
- using (var stream = result.Content)
- {
- using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(filestream).ConfigureAwait(false);
- }
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
- File.WriteAllText(pointerCachePath, fullCachePath);
- }
- }
-
- /// <summary>
- /// Gets the full cache path.
- /// </summary>
- /// <param name="filename">The filename.</param>
- /// <returns>System.String.</returns>
- private string GetFullCachePath(string filename)
- {
- return Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
- }
- }
-}
diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs
deleted file mode 100644
index f3ea7907f..000000000
--- a/MediaBrowser.Api/ItemLookupService.cs
+++ /dev/null
@@ -1,319 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api
-{
- [Route("/Items/{Id}/ExternalIdInfos", "GET", Summary = "Gets external id infos for an item")]
- [Authenticated(Roles = "Admin")]
- public class GetExternalIdInfos : IReturn<List<ExternalIdInfo>>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
- }
-
- [Route("/Items/RemoteSearch/Movie", "POST")]
- [Authenticated]
- public class GetMovieRemoteSearchResults : RemoteSearchQuery<MovieInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/Trailer", "POST")]
- [Authenticated]
- public class GetTrailerRemoteSearchResults : RemoteSearchQuery<TrailerInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/MusicVideo", "POST")]
- [Authenticated]
- public class GetMusicVideoRemoteSearchResults : RemoteSearchQuery<MusicVideoInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/Series", "POST")]
- [Authenticated]
- public class GetSeriesRemoteSearchResults : RemoteSearchQuery<SeriesInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/BoxSet", "POST")]
- [Authenticated]
- public class GetBoxSetRemoteSearchResults : RemoteSearchQuery<BoxSetInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/MusicArtist", "POST")]
- [Authenticated]
- public class GetMusicArtistRemoteSearchResults : RemoteSearchQuery<ArtistInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/MusicAlbum", "POST")]
- [Authenticated]
- public class GetMusicAlbumRemoteSearchResults : RemoteSearchQuery<AlbumInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/Person", "POST")]
- [Authenticated(Roles = "Admin")]
- public class GetPersonRemoteSearchResults : RemoteSearchQuery<PersonLookupInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/Book", "POST")]
- [Authenticated]
- public class GetBookRemoteSearchResults : RemoteSearchQuery<BookInfo>, IReturn<List<RemoteSearchResult>>
- {
- }
-
- [Route("/Items/RemoteSearch/Image", "GET", Summary = "Gets a remote image")]
- public class GetRemoteSearchImage
- {
- [ApiMember(Name = "ImageUrl", Description = "The image url", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ImageUrl { get; set; }
-
- [ApiMember(Name = "ProviderName", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ProviderName { get; set; }
- }
-
- [Route("/Items/RemoteSearch/Apply/{Id}", "POST", Summary = "Applies search criteria to an item and refreshes metadata")]
- [Authenticated(Roles = "Admin")]
- public class ApplySearchCriteria : RemoteSearchResult, IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "The item id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "ReplaceAllImages", Description = "Whether or not to replace all images", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool ReplaceAllImages { get; set; }
-
- public ApplySearchCriteria()
- {
- ReplaceAllImages = true;
- }
- }
-
- public class ItemLookupService : BaseApiService
- {
- private readonly IProviderManager _providerManager;
- private readonly IServerApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
- private readonly ILibraryManager _libraryManager;
- private readonly IJsonSerializer _json;
-
- public ItemLookupService(IProviderManager providerManager, IServerApplicationPaths appPaths, IFileSystem fileSystem, ILibraryManager libraryManager, IJsonSerializer json)
- {
- _providerManager = providerManager;
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- _libraryManager = libraryManager;
- _json = json;
- }
-
- public object Get(GetExternalIdInfos request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var infos = _providerManager.GetExternalIdInfos(item).ToList();
-
- return ToOptimizedResult(infos);
- }
-
- public async Task<object> Post(GetTrailerRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<Trailer, TrailerInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetBookRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<Book, BookInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetMovieRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<Movie, MovieInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetSeriesRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetBoxSetRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<BoxSet, BoxSetInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetMusicVideoRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<MusicVideo, MusicVideoInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetPersonRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<Person, PersonLookupInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetMusicAlbumRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<MusicAlbum, AlbumInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(GetMusicArtistRemoteSearchResults request)
- {
- var result = await _providerManager.GetRemoteSearchResults<MusicArtist, ArtistInfo>(request, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public Task<object> Get(GetRemoteSearchImage request)
- {
- return GetRemoteImage(request);
- }
-
- public Task Post(ApplySearchCriteria request)
- {
- var item = _libraryManager.GetItemById(new Guid(request.Id));
-
- //foreach (var key in request.ProviderIds)
- //{
- // var value = key.Value;
-
- // if (!string.IsNullOrWhiteSpace(value))
- // {
- // item.SetProviderId(key.Key, value);
- // }
- //}
- Logger.LogInformation("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds));
-
- // Since the refresh process won't erase provider Ids, we need to set this explicitly now.
- item.ProviderIds = request.ProviderIds;
- //item.ProductionYear = request.ProductionYear;
- //item.Name = request.Name;
-
- return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
- {
- MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
- ImageRefreshMode = MetadataRefreshMode.FullRefresh,
- ReplaceAllMetadata = true,
- ReplaceAllImages = request.ReplaceAllImages,
- SearchResult = request
-
- }, CancellationToken.None);
- }
-
- /// <summary>
- /// Gets the remote image.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{System.Object}.</returns>
- private async Task<object> GetRemoteImage(GetRemoteSearchImage request)
- {
- var urlHash = request.ImageUrl.GetMD5();
- var pointerCachePath = GetFullCachePath(urlHash.ToString());
-
- string contentPath;
-
- try
- {
- contentPath = File.ReadAllText(pointerCachePath);
-
- if (File.Exists(contentPath))
- {
- return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
- }
- }
- catch (FileNotFoundException)
- {
- // Means the file isn't cached yet
- }
- catch (IOException)
- {
- // Means the file isn't cached yet
- }
-
- await DownloadImage(request.ProviderName, request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
-
- // Read the pointer file again
- contentPath = File.ReadAllText(pointerCachePath);
-
- return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Downloads the image.
- /// </summary>
- /// <param name="providerName">Name of the provider.</param>
- /// <param name="url">The URL.</param>
- /// <param name="urlHash">The URL hash.</param>
- /// <param name="pointerCachePath">The pointer cache path.</param>
- /// <returns>Task.</returns>
- private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath)
- {
- var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);
-
- var ext = result.ContentType.Split('/').Last();
-
- var fullCachePath = GetFullCachePath(urlHash + "." + ext);
-
- Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
- using (var stream = result.Content)
- {
- using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(filestream).ConfigureAwait(false);
- }
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
- File.WriteAllText(pointerCachePath, fullCachePath);
- }
-
- /// <summary>
- /// Gets the full cache path.
- /// </summary>
- /// <param name="filename">The filename.</param>
- /// <returns>System.String.</returns>
- private string GetFullCachePath(string filename)
- {
- return Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
- }
-
- }
-}
diff --git a/MediaBrowser.Api/ItemRefreshService.cs b/MediaBrowser.Api/ItemRefreshService.cs
deleted file mode 100644
index 8238ad19c..000000000
--- a/MediaBrowser.Api/ItemRefreshService.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api
-{
- public class BaseRefreshRequest : IReturnVoid
- {
- [ApiMember(Name = "MetadataRefreshMode", Description = "Specifies the metadata refresh mode", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public MetadataRefreshMode MetadataRefreshMode { get; set; }
-
- [ApiMember(Name = "ImageRefreshMode", Description = "Specifies the image refresh mode", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public MetadataRefreshMode ImageRefreshMode { get; set; }
-
- [ApiMember(Name = "ReplaceAllMetadata", Description = "Determines if metadata should be replaced. Only applicable if mode is FullRefresh", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool ReplaceAllMetadata { get; set; }
-
- [ApiMember(Name = "ReplaceAllImages", Description = "Determines if images should be replaced. Only applicable if mode is FullRefresh", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool ReplaceAllImages { get; set; }
- }
-
- [Route("/Items/{Id}/Refresh", "POST", Summary = "Refreshes metadata for an item")]
- public class RefreshItem : BaseRefreshRequest
- {
- [ApiMember(Name = "Recursive", Description = "Indicates if the refresh should occur recursively.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
- public bool Recursive { get; set; }
-
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Authenticated]
- public class ItemRefreshService : BaseApiService
- {
- private readonly ILibraryManager _libraryManager;
- private readonly IProviderManager _providerManager;
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
-
- public ItemRefreshService(ILibraryManager libraryManager, IProviderManager providerManager, IFileSystem fileSystem, ILogger logger)
- {
- _libraryManager = libraryManager;
- _providerManager = providerManager;
- _fileSystem = fileSystem;
- _logger = logger;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(RefreshItem request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var options = GetRefreshOptions(request);
-
- _providerManager.QueueRefresh(item.Id, options, RefreshPriority.High);
- }
-
- private MetadataRefreshOptions GetRefreshOptions(RefreshItem request)
- {
- return new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
- {
- MetadataRefreshMode = request.MetadataRefreshMode,
- ImageRefreshMode = request.ImageRefreshMode,
- ReplaceAllImages = request.ReplaceAllImages,
- ReplaceAllMetadata = request.ReplaceAllMetadata,
- ForceSave = request.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || request.ImageRefreshMode == MetadataRefreshMode.FullRefresh || request.ReplaceAllImages || request.ReplaceAllMetadata,
- IsAutomated = false
- };
- }
- }
-}
diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs
deleted file mode 100644
index d44b07256..000000000
--- a/MediaBrowser.Api/Library/LibraryService.cs
+++ /dev/null
@@ -1,1210 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Api.Movies;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Controller.TV;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Library
-{
- [Route("/Items/{Id}/File", "GET", Summary = "Gets the original file of an item")]
- [Authenticated]
- public class GetFile
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetCriticReviews
- /// </summary>
- [Route("/Items/{Id}/CriticReviews", "GET", Summary = "Gets critic reviews for an item")]
- [Authenticated]
- public class GetCriticReviews : IReturn<QueryResult<BaseItemDto>>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
- }
-
- /// <summary>
- /// Class GetThemeSongs
- /// </summary>
- [Route("/Items/{Id}/ThemeSongs", "GET", Summary = "Gets theme songs for an item")]
- [Authenticated]
- public class GetThemeSongs : IReturn<ThemeMediaResult>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool InheritFromParent { get; set; }
- }
-
- /// <summary>
- /// Class GetThemeVideos
- /// </summary>
- [Route("/Items/{Id}/ThemeVideos", "GET", Summary = "Gets theme videos for an item")]
- [Authenticated]
- public class GetThemeVideos : IReturn<ThemeMediaResult>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool InheritFromParent { get; set; }
- }
-
- /// <summary>
- /// Class GetThemeVideos
- /// </summary>
- [Route("/Items/{Id}/ThemeMedia", "GET", Summary = "Gets theme videos and songs for an item")]
- [Authenticated]
- public class GetThemeMedia : IReturn<AllThemeMediaResult>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool InheritFromParent { get; set; }
- }
-
- [Route("/Library/Refresh", "POST", Summary = "Starts a library scan")]
- [Authenticated(Roles = "Admin")]
- public class RefreshLibrary : IReturnVoid
- {
- }
-
- [Route("/Items/{Id}", "DELETE", Summary = "Deletes an item from the library and file system")]
- [Authenticated]
- public class DeleteItem : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/Items", "DELETE", Summary = "Deletes an item from the library and file system")]
- [Authenticated]
- public class DeleteItems : IReturnVoid
- {
- [ApiMember(Name = "Ids", Description = "Ids", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Ids { get; set; }
- }
-
- [Route("/Items/Counts", "GET")]
- [Authenticated]
- public class GetItemCounts : IReturn<ItemCounts>
- {
- [ApiMember(Name = "UserId", Description = "Optional. Get counts from a specific user's library.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "IsFavorite", Description = "Optional. Get counts of favorite items", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsFavorite { get; set; }
- }
-
- [Route("/Items/{Id}/Ancestors", "GET", Summary = "Gets all parents of an item")]
- [Authenticated]
- public class GetAncestors : IReturn<BaseItemDto[]>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetPhyscialPaths
- /// </summary>
- [Route("/Library/PhysicalPaths", "GET", Summary = "Gets a list of physical paths from virtual folders")]
- [Authenticated(Roles = "Admin")]
- public class GetPhyscialPaths : IReturn<List<string>>
- {
- }
-
- [Route("/Library/MediaFolders", "GET", Summary = "Gets all user media folders.")]
- [Authenticated]
- public class GetMediaFolders : IReturn<QueryResult<BaseItemDto>>
- {
- [ApiMember(Name = "IsHidden", Description = "Optional. Filter by folders that are marked hidden, or not.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? IsHidden { get; set; }
- }
-
- [Route("/Library/Series/Added", "POST", Summary = "Reports that new episodes of a series have been added by an external source")]
- [Route("/Library/Series/Updated", "POST", Summary = "Reports that new episodes of a series have been added by an external source")]
- [Authenticated]
- public class PostUpdatedSeries : IReturnVoid
- {
- [ApiMember(Name = "TvdbId", Description = "Tvdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string TvdbId { get; set; }
- }
-
- [Route("/Library/Movies/Added", "POST", Summary = "Reports that new movies have been added by an external source")]
- [Route("/Library/Movies/Updated", "POST", Summary = "Reports that new movies have been added by an external source")]
- [Authenticated]
- public class PostUpdatedMovies : IReturnVoid
- {
- [ApiMember(Name = "TmdbId", Description = "Tmdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string TmdbId { get; set; }
- [ApiMember(Name = "ImdbId", Description = "Imdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string ImdbId { get; set; }
- }
-
- public class MediaUpdateInfo
- {
- public string Path { get; set; }
-
- // Created, Modified, Deleted
- public string UpdateType { get; set; }
- }
-
- [Route("/Library/Media/Updated", "POST", Summary = "Reports that new movies have been added by an external source")]
- [Authenticated]
- public class PostUpdatedMedia : IReturnVoid
- {
- [ApiMember(Name = "Updates", Description = "A list of updated media paths", IsRequired = false, DataType = "string", ParameterType = "body", Verb = "POST")]
- public List<MediaUpdateInfo> Updates { get; set; }
- }
-
- [Route("/Items/{Id}/Download", "GET", Summary = "Downloads item media")]
- [Authenticated(Roles = "download")]
- public class GetDownload
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Artists/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
- [Route("/Items/{Id}/Similar", "GET", Summary = "Gets similar items")]
- [Route("/Albums/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
- [Route("/Shows/{Id}/Similar", "GET", Summary = "Finds tv shows similar to a given one.")]
- [Route("/Movies/{Id}/Similar", "GET", Summary = "Finds movies and trailers similar to a given movie.")]
- [Route("/Trailers/{Id}/Similar", "GET", Summary = "Finds movies and trailers similar to a given trailer.")]
- [Authenticated]
- public class GetSimilarItems : BaseGetSimilarItemsFromItem
- {
- }
-
- [Route("/Libraries/AvailableOptions", "GET")]
- [Authenticated(AllowBeforeStartupWizard = true)]
- public class GetLibraryOptionsInfo : IReturn<LibraryOptionsResult>
- {
- public string LibraryContentType { get; set; }
- public bool IsNewLibrary { get; set; }
- }
-
- public class LibraryOptionInfo
- {
- public string Name { get; set; }
- public bool DefaultEnabled { get; set; }
- }
-
- public class LibraryOptionsResult
- {
- public LibraryOptionInfo[] MetadataSavers { get; set; }
- public LibraryOptionInfo[] MetadataReaders { get; set; }
- public LibraryOptionInfo[] SubtitleFetchers { get; set; }
- public LibraryTypeOptions[] TypeOptions { get; set; }
- }
-
- public class LibraryTypeOptions
- {
- public string Type { get; set; }
- public LibraryOptionInfo[] MetadataFetchers { get; set; }
- public LibraryOptionInfo[] ImageFetchers { get; set; }
- public ImageType[] SupportedImageTypes { get; set; }
- public ImageOption[] DefaultImageOptions { get; set; }
- }
-
- /// <summary>
- /// Class LibraryService
- /// </summary>
- public class LibraryService : BaseApiService
- {
- /// <summary>
- /// The _item repo
- /// </summary>
- private readonly IItemRepository _itemRepo;
-
- private readonly ILibraryManager _libraryManager;
- private readonly IUserManager _userManager;
- private readonly IUserDataManager _userDataManager;
-
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
- private readonly IActivityManager _activityManager;
- private readonly ILocalizationManager _localization;
- private readonly ILiveTvManager _liveTv;
- private readonly ITVSeriesManager _tvManager;
- private readonly ILibraryMonitor _libraryMonitor;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _config;
- private readonly IProviderManager _providerManager;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LibraryService" /> class.
- /// </summary>
- public LibraryService(IProviderManager providerManager, IItemRepository itemRepo, ILibraryManager libraryManager, IUserManager userManager,
- IDtoService dtoService, IUserDataManager userDataManager, IAuthorizationContext authContext, IActivityManager activityManager, ILocalizationManager localization, ILiveTvManager liveTv, ITVSeriesManager tvManager, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, IServerConfigurationManager config)
- {
- _itemRepo = itemRepo;
- _libraryManager = libraryManager;
- _userManager = userManager;
- _dtoService = dtoService;
- _userDataManager = userDataManager;
- _authContext = authContext;
- _activityManager = activityManager;
- _localization = localization;
- _liveTv = liveTv;
- _tvManager = tvManager;
- _libraryMonitor = libraryMonitor;
- _fileSystem = fileSystem;
- _config = config;
- _providerManager = providerManager;
- }
-
- private string[] GetRepresentativeItemTypes(string contentType)
- {
- switch (contentType)
- {
- case CollectionType.BoxSets:
- return new string[] { "BoxSet" };
- case CollectionType.Playlists:
- return new string[] { "Playlist" };
- case CollectionType.Movies:
- return new string[] { "Movie" };
- case CollectionType.TvShows:
- return new string[] { "Series", "Season", "Episode" };
- case CollectionType.Books:
- return new string[] { "Book" };
- case CollectionType.Music:
- return new string[] { "MusicAlbum", "MusicArtist", "Audio", "MusicVideo" };
- case CollectionType.HomeVideos:
- case CollectionType.Photos:
- return new string[] { "Video", "Photo" };
- case CollectionType.MusicVideos:
- return new string[] { "MusicVideo" };
- default:
- return new string[] { "Series", "Season", "Episode", "Movie" };
- }
- }
-
- private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
- {
- if (isNewLibrary)
- {
- return false;
- }
-
- var metadataOptions = _config.Configuration.MetadataOptions
- .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- .ToArray();
-
- if (metadataOptions.Length == 0)
- {
- return true;
- }
-
- return metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
- }
-
- private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
- {
- if (isNewLibrary)
- {
- if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
- {
- if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- return true;
- }
- else if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "The Open Movie Database", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- else if (string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- return false;
- }
-
- var metadataOptions = _config.Configuration.MetadataOptions
- .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
- .ToArray();
-
- if (metadataOptions.Length == 0)
- {
- return true;
- }
-
- return metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
- }
-
- private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
- {
- if (isNewLibrary)
- {
- if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
- {
- if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- return true;
- }
- else if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "The Open Movie Database", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- else if (string.Equals(name, "FanArt", StringComparison.OrdinalIgnoreCase))
- {
- if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- if (string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- return true;
- }
- else if (string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "Emby Designs", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- else if (string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- return false;
- }
-
- var metadataOptions = _config.Configuration.MetadataOptions
- .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
- .ToArray();
-
- if (metadataOptions.Length == 0)
- {
- return true;
- }
-
- return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
- }
-
- public object Get(GetLibraryOptionsInfo request)
- {
- var result = new LibraryOptionsResult();
-
- var types = GetRepresentativeItemTypes(request.LibraryContentType);
- var isNewLibrary = request.IsNewLibrary;
- var typesList = types.ToList();
-
- var plugins = _providerManager.GetAllMetadataPlugins()
- .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
- .OrderBy(i => typesList.IndexOf(i.ItemType))
- .ToList();
-
- result.MetadataSavers = plugins
- .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
- .Select(i => new LibraryOptionInfo
- {
- Name = i.Name,
- DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
- })
- .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First())
- .ToArray();
-
- result.MetadataReaders = plugins
- .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
- .Select(i => new LibraryOptionInfo
- {
- Name = i.Name,
- DefaultEnabled = true
- })
- .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First())
- .ToArray();
-
- result.SubtitleFetchers = plugins
- .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
- .Select(i => new LibraryOptionInfo
- {
- Name = i.Name,
- DefaultEnabled = true
- })
- .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First())
- .ToArray();
-
- var typeOptions = new List<LibraryTypeOptions>();
-
- foreach (var type in types)
- {
- ImageOption[] defaultImageOptions = null;
- TypeOptions.DefaultImageOptions.TryGetValue(type, out defaultImageOptions);
-
- typeOptions.Add(new LibraryTypeOptions
- {
- Type = type,
-
- MetadataFetchers = plugins
- .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
- .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
- .Select(i => new LibraryOptionInfo
- {
- Name = i.Name,
- DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
- })
- .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First())
- .ToArray(),
-
- ImageFetchers = plugins
- .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
- .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
- .Select(i => new LibraryOptionInfo
- {
- Name = i.Name,
- DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
- })
- .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First())
- .ToArray(),
-
- SupportedImageTypes = plugins
- .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
- .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
- .Distinct()
- .ToArray(),
-
- DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
- });
- }
-
- result.TypeOptions = typeOptions.ToArray();
-
- return result;
- }
-
- public object Get(GetSimilarItems request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id) ?
- (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() :
- _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id);
-
- var program = item as IHasProgramAttributes;
-
- if (item is Movie || (program != null && program.IsMovie) || item is Trailer)
- {
- return new MoviesService(_userManager, _libraryManager, _dtoService, _config, _authContext)
- {
- Request = Request,
-
- }.GetSimilarItemsResult(request);
- }
-
- if (program != null && program.IsSeries)
- {
- return GetSimilarItemsResult(request, new[] { typeof(Series).Name });
- }
-
- if (item is Episode || (item is IItemByName && !(item is MusicArtist)))
- {
- return new QueryResult<BaseItemDto>();
- }
-
- return GetSimilarItemsResult(request, new[] { item.GetType().Name });
- }
-
- private QueryResult<BaseItemDto> GetSimilarItemsResult(BaseGetSimilarItemsFromItem request, string[] includeItemTypes)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id) ?
- (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() :
- _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var query = new InternalItemsQuery(user)
- {
- Limit = request.Limit,
- IncludeItemTypes = includeItemTypes,
- SimilarTo = item,
- DtoOptions = dtoOptions,
- EnableTotalRecordCount = false
- };
-
- // ExcludeArtistIds
- if (!string.IsNullOrEmpty(request.ExcludeArtistIds))
- {
- query.ExcludeArtistIds = BaseApiService.GetGuids(request.ExcludeArtistIds);
- }
-
- List<BaseItem> itemsResult;
-
- if (item is MusicArtist)
- {
- query.IncludeItemTypes = Array.Empty<string>();
-
- itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
- }
- else
- {
- itemsResult = _libraryManager.GetItemList(query);
- }
-
- var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = returnList,
-
- TotalRecordCount = itemsResult.Count
- };
-
- return result;
- }
-
- public object Get(GetMediaFolders request)
- {
- var items = _libraryManager.GetUserRootFolder().Children.Concat(_libraryManager.RootFolder.VirtualChildren).OrderBy(i => i.SortName).ToList();
-
- if (request.IsHidden.HasValue)
- {
- var val = request.IsHidden.Value;
-
- items = items.Where(i => i.IsHidden == val).ToList();
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = new QueryResult<BaseItemDto>
- {
- TotalRecordCount = items.Count,
-
- Items = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions)).ToArray()
- };
-
- return result;
- }
-
- public void Post(PostUpdatedSeries request)
- {
- var series = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(Series).Name },
- DtoOptions = new DtoOptions(false)
- {
- EnableImages = false
- }
-
- }).Where(i => string.Equals(request.TvdbId, i.GetProviderId(MetadataProviders.Tvdb), StringComparison.OrdinalIgnoreCase)).ToArray();
-
- foreach (var item in series)
- {
- _libraryMonitor.ReportFileSystemChanged(item.Path);
- }
- }
-
- public void Post(PostUpdatedMedia request)
- {
- if (request.Updates != null)
- {
- foreach (var item in request.Updates)
- {
- _libraryMonitor.ReportFileSystemChanged(item.Path);
- }
- }
- }
-
- public void Post(PostUpdatedMovies request)
- {
- var movies = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(Movie).Name },
- DtoOptions = new DtoOptions(false)
- {
- EnableImages = false
- }
-
- });
-
- if (!string.IsNullOrWhiteSpace(request.ImdbId))
- {
- movies = movies.Where(i => string.Equals(request.ImdbId, i.GetProviderId(MetadataProviders.Imdb), StringComparison.OrdinalIgnoreCase)).ToList();
- }
- else if (!string.IsNullOrWhiteSpace(request.TmdbId))
- {
- movies = movies.Where(i => string.Equals(request.TmdbId, i.GetProviderId(MetadataProviders.Tmdb), StringComparison.OrdinalIgnoreCase)).ToList();
- }
- else
- {
- movies = new List<BaseItem>();
- }
-
- foreach (var item in movies)
- {
- _libraryMonitor.ReportFileSystemChanged(item.Path);
- }
- }
-
- public Task<object> Get(GetDownload request)
- {
- var item = _libraryManager.GetItemById(request.Id);
- var auth = _authContext.GetAuthorizationInfo(Request);
-
- var user = auth.User;
-
- if (user != null)
- {
- if (!item.CanDownload(user))
- {
- throw new ArgumentException("Item does not support downloading");
- }
- }
- else
- {
- if (!item.CanDownload())
- {
- throw new ArgumentException("Item does not support downloading");
- }
- }
-
- var headers = new Dictionary<string, string>();
-
- if (user != null)
- {
- LogDownload(item, user, auth);
- }
-
- var path = item.Path;
-
- // Quotes are valid in linux. They'll possibly cause issues here
- var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty);
- if (!string.IsNullOrWhiteSpace(filename))
- {
- headers["Content-Disposition"] = "attachment; filename=\"" + filename + "\"";
- }
-
- return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- {
- Path = path,
- ResponseHeaders = headers
- });
- }
-
- private void LogDownload(BaseItem item, User user, AuthorizationInfo auth)
- {
- try
- {
- _activityManager.Create(new ActivityLogEntry
- {
- Name = string.Format(_localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Name, item.Name),
- Type = "UserDownloadingContent",
- ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
- UserId = auth.UserId
-
- });
- }
- catch
- {
- // Logged at lower levels
- }
- }
-
- public Task<object> Get(GetFile request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- return ResultFactory.GetStaticFileResult(Request, item.Path);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPhyscialPaths request)
- {
- var result = _libraryManager.RootFolder.Children
- .SelectMany(c => c.PhysicalLocations)
- .ToList();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetAncestors request)
- {
- var result = GetAncestors(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the ancestors.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto[]}.</returns>
- public List<BaseItemDto> GetAncestors(GetAncestors request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var baseItemDtos = new List<BaseItemDto>();
-
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- BaseItem parent = item.GetParent();
-
- while (parent != null)
- {
- if (user != null)
- {
- parent = TranslateParentItem(parent, user);
- }
-
- baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
-
- parent = parent.GetParent();
- }
-
- return baseItemDtos;
- }
-
- private BaseItem TranslateParentItem(BaseItem item, User user)
- {
- if (item.GetParent() is AggregateFolder)
- {
- return _libraryManager.GetUserRootFolder().GetChildren(user, true).FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path));
- }
-
- return item;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetCriticReviews request)
- {
- return new QueryResult<BaseItemDto>();
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetItemCounts request)
- {
- var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
-
- var counts = new ItemCounts
- {
- AlbumCount = GetCount(typeof(MusicAlbum), user, request),
- EpisodeCount = GetCount(typeof(Episode), user, request),
- MovieCount = GetCount(typeof(Movie), user, request),
- SeriesCount = GetCount(typeof(Series), user, request),
- SongCount = GetCount(typeof(Audio), user, request),
- MusicVideoCount = GetCount(typeof(MusicVideo), user, request),
- BoxSetCount = GetCount(typeof(BoxSet), user, request),
- BookCount = GetCount(typeof(Book), user, request)
- };
-
- return ToOptimizedResult(counts);
- }
-
- private int GetCount(Type type, User user, GetItemCounts request)
- {
- var query = new InternalItemsQuery(user)
- {
- IncludeItemTypes = new[] { type.Name },
- Limit = 0,
- Recursive = true,
- IsVirtualItem = false,
- IsFavorite = request.IsFavorite,
- DtoOptions = new DtoOptions(false)
- {
- EnableImages = false
- }
- };
-
- return _libraryManager.GetItemsResult(query).TotalRecordCount;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(RefreshLibrary request)
- {
- Task.Run(() =>
- {
- try
- {
- _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error refreshing library");
- }
- });
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(DeleteItems request)
- {
- var ids = string.IsNullOrWhiteSpace(request.Ids)
- ? Array.Empty<string>()
- : request.Ids.Split(',');
-
- foreach (var i in ids)
- {
- var item = _libraryManager.GetItemById(i);
- var auth = _authContext.GetAuthorizationInfo(Request);
- var user = auth.User;
-
- if (!item.CanDelete(user))
- {
- if (ids.Length > 1)
- {
- throw new SecurityException("Unauthorized access");
- }
-
- continue;
- }
-
- _libraryManager.DeleteItem(item, new DeleteOptions
- {
- DeleteFileLocation = true
-
- }, true);
- }
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(DeleteItem request)
- {
- Delete(new DeleteItems
- {
- Ids = request.Id
- });
- }
-
- public object Get(GetThemeMedia request)
- {
- var themeSongs = GetThemeSongs(new GetThemeSongs
- {
- InheritFromParent = request.InheritFromParent,
- Id = request.Id,
- UserId = request.UserId
-
- });
-
- var themeVideos = GetThemeVideos(new GetThemeVideos
- {
- InheritFromParent = request.InheritFromParent,
- Id = request.Id,
- UserId = request.UserId
-
- });
-
- return ToOptimizedResult(new AllThemeMediaResult
- {
- ThemeSongsResult = themeSongs,
- ThemeVideosResult = themeVideos,
-
- SoundtrackSongsResult = new ThemeMediaResult()
- });
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetThemeSongs request)
- {
- var result = GetThemeSongs(request);
-
- return ToOptimizedResult(result);
- }
-
- private ThemeMediaResult GetThemeSongs(GetThemeSongs request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id)
- ? (!request.UserId.Equals(Guid.Empty)
- ? _libraryManager.GetUserRootFolder()
- : (Folder)_libraryManager.RootFolder)
- : _libraryManager.GetItemById(request.Id);
-
- if (item == null)
- {
- throw new ResourceNotFoundException("Item not found.");
- }
-
- BaseItem[] themeItems = Array.Empty<BaseItem>();
-
- while (true)
- {
- themeItems = item.GetThemeSongs().ToArray();
-
- if (themeItems.Length > 0)
- {
- break;
- }
-
- if (!request.InheritFromParent)
- {
- break;
- }
-
- var parent = item.GetParent();
- if (parent == null)
- {
- break;
- }
- item = parent;
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = themeItems
- .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item));
-
- var items = dtos.ToArray();
-
- return new ThemeMediaResult
- {
- Items = items,
- TotalRecordCount = items.Length,
- OwnerId = item.Id
- };
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetThemeVideos request)
- {
- var result = GetThemeVideos(request);
-
- return ToOptimizedResult(result);
- }
-
- public ThemeMediaResult GetThemeVideos(GetThemeVideos request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id)
- ? (!request.UserId.Equals(Guid.Empty)
- ? _libraryManager.GetUserRootFolder()
- : (Folder)_libraryManager.RootFolder)
- : _libraryManager.GetItemById(request.Id);
-
- if (item == null)
- {
- throw new ResourceNotFoundException("Item not found.");
- }
-
- BaseItem[] themeItems = Array.Empty<BaseItem>();
-
- while (true)
- {
- themeItems = item.GetThemeVideos().ToArray();
-
- if (themeItems.Length > 0)
- {
- break;
- }
-
- if (!request.InheritFromParent)
- {
- break;
- }
-
- var parent = item.GetParent();
- if (parent == null)
- {
- break;
- }
- item = parent;
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = themeItems
- .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item));
-
- var items = dtos.ToArray();
-
- return new ThemeMediaResult
- {
- Items = items,
- TotalRecordCount = items.Length,
- OwnerId = item.Id
- };
- }
- }
-}
diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs
deleted file mode 100644
index d6bcf7878..000000000
--- a/MediaBrowser.Api/Library/LibraryStructureService.cs
+++ /dev/null
@@ -1,416 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Library
-{
- /// <summary>
- /// Class GetDefaultVirtualFolders
- /// </summary>
- [Route("/Library/VirtualFolders", "GET")]
- public class GetVirtualFolders : IReturn<List<VirtualFolderInfo>>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- public string UserId { get; set; }
- }
-
- [Route("/Library/VirtualFolders", "POST")]
- public class AddVirtualFolder : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the type of the collection.
- /// </summary>
- /// <value>The type of the collection.</value>
- public string CollectionType { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [refresh library].
- /// </summary>
- /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
- public bool RefreshLibrary { get; set; }
-
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- public string[] Paths { get; set; }
-
- public LibraryOptions LibraryOptions { get; set; }
- }
-
- [Route("/Library/VirtualFolders", "DELETE")]
- public class RemoveVirtualFolder : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [refresh library].
- /// </summary>
- /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
- public bool RefreshLibrary { get; set; }
- }
-
- [Route("/Library/VirtualFolders/Name", "POST")]
- public class RenameVirtualFolder : IReturnVoid
- {
- /// <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 NewName { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [refresh library].
- /// </summary>
- /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
- public bool RefreshLibrary { get; set; }
- }
-
- [Route("/Library/VirtualFolders/Paths", "POST")]
- public class AddMediaPath : IReturnVoid
- {
- /// <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 Path { get; set; }
-
- public MediaPathInfo PathInfo { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [refresh library].
- /// </summary>
- /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
- public bool RefreshLibrary { get; set; }
- }
-
- [Route("/Library/VirtualFolders/Paths/Update", "POST")]
- public class UpdateMediaPath : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- public MediaPathInfo PathInfo { get; set; }
- }
-
- [Route("/Library/VirtualFolders/Paths", "DELETE")]
- public class RemoveMediaPath : IReturnVoid
- {
- /// <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 Path { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [refresh library].
- /// </summary>
- /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
- public bool RefreshLibrary { get; set; }
- }
-
- [Route("/Library/VirtualFolders/LibraryOptions", "POST")]
- public class UpdateLibraryOptions : IReturnVoid
- {
- public string Id { get; set; }
-
- public LibraryOptions LibraryOptions { get; set; }
- }
-
- /// <summary>
- /// Class LibraryStructureService
- /// </summary>
- [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
- public class LibraryStructureService : BaseApiService
- {
- /// <summary>
- /// The _app paths
- /// </summary>
- private readonly IServerApplicationPaths _appPaths;
-
- /// <summary>
- /// The _library manager
- /// </summary>
- private readonly ILibraryManager _libraryManager;
-
- private readonly ILibraryMonitor _libraryMonitor;
-
- private readonly IFileSystem _fileSystem;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LibraryStructureService" /> class.
- /// </summary>
- public LibraryStructureService(IServerApplicationPaths appPaths, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IFileSystem fileSystem)
- {
- if (appPaths == null)
- {
- throw new ArgumentNullException(nameof(appPaths));
- }
-
- _appPaths = appPaths;
- _libraryManager = libraryManager;
- _libraryMonitor = libraryMonitor;
- _fileSystem = fileSystem;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetVirtualFolders request)
- {
- var result = _libraryManager.GetVirtualFolders(true);
-
- return ToOptimizedResult(result);
- }
-
- public void Post(UpdateLibraryOptions request)
- {
- var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(request.Id);
-
- collectionFolder.UpdateLibraryOptions(request.LibraryOptions);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(AddVirtualFolder request)
- {
- var libraryOptions = request.LibraryOptions ?? new LibraryOptions();
-
- if (request.Paths != null && request.Paths.Length > 0)
- {
- libraryOptions.PathInfos = request.Paths.Select(i => new MediaPathInfo { Path = i }).ToArray();
- }
-
- return _libraryManager.AddVirtualFolder(request.Name, request.CollectionType, libraryOptions, request.RefreshLibrary);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(RenameVirtualFolder request)
- {
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- if (string.IsNullOrWhiteSpace(request.NewName))
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- var rootFolderPath = _appPaths.DefaultUserViewsPath;
-
- var currentPath = Path.Combine(rootFolderPath, request.Name);
- var newPath = Path.Combine(rootFolderPath, request.NewName);
-
- if (!Directory.Exists(currentPath))
- {
- throw new FileNotFoundException("The media collection does not exist");
- }
-
- if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
- {
- throw new ArgumentException("Media library already exists at " + newPath + ".");
- }
-
- _libraryMonitor.Stop();
-
- try
- {
- // Changing capitalization. Handle windows case insensitivity
- if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
- {
- var tempPath = Path.Combine(rootFolderPath, Guid.NewGuid().ToString("N"));
- Directory.Move(currentPath, tempPath);
- currentPath = tempPath;
- }
-
- Directory.Move(currentPath, newPath);
- }
- finally
- {
- CollectionFolder.OnCollectionFolderChange();
-
- Task.Run(() =>
- {
- // No need to start if scanning the library because it will handle it
- if (request.RefreshLibrary)
- {
- _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
- }
- else
- {
- // Need to add a delay here or directory watchers may still pick up the changes
- var task = Task.Delay(1000);
- // Have to block here to allow exceptions to bubble
- Task.WaitAll(task);
-
- _libraryMonitor.Start();
- }
- });
- }
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Delete(RemoveVirtualFolder request)
- {
- return _libraryManager.RemoveVirtualFolder(request.Name, request.RefreshLibrary);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(AddMediaPath request)
- {
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- _libraryMonitor.Stop();
-
- try
- {
- var mediaPath = request.PathInfo;
-
- if (mediaPath == null)
- {
- mediaPath = new MediaPathInfo
- {
- Path = request.Path
- };
- }
- _libraryManager.AddMediaPath(request.Name, mediaPath);
- }
- finally
- {
- Task.Run(() =>
- {
- // No need to start if scanning the library because it will handle it
- if (request.RefreshLibrary)
- {
- _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
- }
- else
- {
- // Need to add a delay here or directory watchers may still pick up the changes
- var task = Task.Delay(1000);
- // Have to block here to allow exceptions to bubble
- Task.WaitAll(task);
-
- _libraryMonitor.Start();
- }
- });
- }
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(UpdateMediaPath request)
- {
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- _libraryManager.UpdateMediaPath(request.Name, request.PathInfo);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(RemoveMediaPath request)
- {
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- _libraryMonitor.Stop();
-
- try
- {
- _libraryManager.RemoveMediaPath(request.Name, request.Path);
- }
- finally
- {
- Task.Run(() =>
- {
- // No need to start if scanning the library because it will handle it
- if (request.RefreshLibrary)
- {
- _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
- }
- else
- {
- // Need to add a delay here or directory watchers may still pick up the changes
- var task = Task.Delay(1000);
- // Have to block here to allow exceptions to bubble
- Task.WaitAll(task);
-
- _libraryMonitor.Start();
- }
- });
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs
deleted file mode 100644
index 8fdd726b7..000000000
--- a/MediaBrowser.Api/LiveTv/LiveTvService.cs
+++ /dev/null
@@ -1,1268 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Api.UserLibrary;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Api.LiveTv
-{
- /// <summary>
- /// This is insecure right now to avoid windows phone refactoring
- /// </summary>
- [Route("/LiveTv/Info", "GET", Summary = "Gets available live tv services.")]
- [Authenticated]
- public class GetLiveTvInfo : IReturn<LiveTvInfo>
- {
- }
-
- [Route("/LiveTv/Channels", "GET", Summary = "Gets available live tv channels.")]
- [Authenticated]
- public class GetChannels : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "Type", Description = "Optional filter by channel type.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public ChannelType? Type { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsMovie { get; set; }
-
- [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSeries { get; set; }
-
- [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsNews { get; set; }
-
- [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsKids { get; set; }
-
- [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSports { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "IsFavorite", Description = "Filter by channels that are favorites, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsFavorite { get; set; }
-
- [ApiMember(Name = "IsLiked", Description = "Filter by channels that are liked, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsLiked { get; set; }
-
- [ApiMember(Name = "IsDisliked", Description = "Filter by channels that are disliked, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsDisliked { get; set; }
-
- [ApiMember(Name = "EnableFavoriteSorting", Description = "Incorporate favorite and like status into channel sorting.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool EnableFavoriteSorting { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "AddCurrentProgram", Description = "Optional. Adds current program info to each channel", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool AddCurrentProgram { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- public string SortBy { get; set; }
-
- public SortOrder? SortOrder { get; set; }
-
- /// <summary>
- /// Gets the order by.
- /// </summary>
- /// <returns>IEnumerable{ItemSortBy}.</returns>
- public string[] GetOrderBy()
- {
- var val = SortBy;
-
- if (string.IsNullOrEmpty(val))
- {
- return Array.Empty<string>();
- }
-
- return val.Split(',');
- }
-
- public GetChannels()
- {
- AddCurrentProgram = true;
- }
- }
-
- [Route("/LiveTv/Channels/{Id}", "GET", Summary = "Gets a live tv channel")]
- [Authenticated]
- public class GetChannel : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Channel Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- [Route("/LiveTv/Recordings", "GET", Summary = "Gets live tv recordings")]
- [Authenticated]
- public class GetRecordings : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "ChannelId", Description = "Optional filter by channel id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ChannelId { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "Status", Description = "Optional filter by recording status.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public RecordingStatus? Status { get; set; }
-
- [ApiMember(Name = "Status", Description = "Optional filter by recordings that are in progress, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsInProgress { get; set; }
-
- [ApiMember(Name = "SeriesTimerId", Description = "Optional filter by recordings belonging to a series timer", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SeriesTimerId { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- public bool EnableTotalRecordCount { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- public bool? IsMovie { get; set; }
- public bool? IsSeries { get; set; }
- public bool? IsKids { get; set; }
- public bool? IsSports { get; set; }
- public bool? IsNews { get; set; }
- public bool? IsLibraryItem { get; set; }
-
- public GetRecordings()
- {
- EnableTotalRecordCount = true;
- }
- }
-
- [Route("/LiveTv/Recordings/Series", "GET", Summary = "Gets live tv recordings")]
- [Authenticated]
- public class GetRecordingSeries : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "ChannelId", Description = "Optional filter by channel id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ChannelId { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "GroupId", Description = "Optional filter by recording group.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string GroupId { get; set; }
-
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "Status", Description = "Optional filter by recording status.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public RecordingStatus? Status { get; set; }
-
- [ApiMember(Name = "Status", Description = "Optional filter by recordings that are in progress, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsInProgress { get; set; }
-
- [ApiMember(Name = "SeriesTimerId", Description = "Optional filter by recordings belonging to a series timer", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SeriesTimerId { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- public bool EnableTotalRecordCount { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- public GetRecordingSeries()
- {
- EnableTotalRecordCount = true;
- }
- }
-
- [Route("/LiveTv/Recordings/Groups", "GET", Summary = "Gets live tv recording groups")]
- [Authenticated]
- public class GetRecordingGroups : IReturn<QueryResult<BaseItemDto>>
- {
- [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string UserId { get; set; }
- }
-
- [Route("/LiveTv/Recordings/Folders", "GET", Summary = "Gets recording folders")]
- [Authenticated]
- public class GetRecordingFolders : IReturn<BaseItemDto[]>
- {
- [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- [Route("/LiveTv/Recordings/{Id}", "GET", Summary = "Gets a live tv recording")]
- [Authenticated]
- public class GetRecording : IReturn<BaseItemDto>
- {
- [ApiMember(Name = "Id", Description = "Recording Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- [Route("/LiveTv/Tuners/{Id}/Reset", "POST", Summary = "Resets a tv tuner")]
- [Authenticated]
- public class ResetTuner : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Tuner Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/Timers/{Id}", "GET", Summary = "Gets a live tv timer")]
- [Authenticated]
- public class GetTimer : IReturn<TimerInfoDto>
- {
- [ApiMember(Name = "Id", Description = "Timer Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/Timers/Defaults", "GET", Summary = "Gets default values for a new timer")]
- [Authenticated]
- public class GetDefaultTimer : IReturn<SeriesTimerInfoDto>
- {
- [ApiMember(Name = "ProgramId", Description = "Optional, to attach default values based on a program.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ProgramId { get; set; }
- }
-
- [Route("/LiveTv/Timers", "GET", Summary = "Gets live tv timers")]
- [Authenticated]
- public class GetTimers : IReturn<QueryResult<TimerInfoDto>>
- {
- [ApiMember(Name = "ChannelId", Description = "Optional filter by channel id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ChannelId { get; set; }
-
- [ApiMember(Name = "SeriesTimerId", Description = "Optional filter by timers belonging to a series timer", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SeriesTimerId { get; set; }
-
- public bool? IsActive { get; set; }
-
- public bool? IsScheduled { get; set; }
- }
-
- [Route("/LiveTv/Programs", "GET,POST", Summary = "Gets available live tv epgs..")]
- [Authenticated]
- public class GetPrograms : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "ChannelIds", Description = "The channels to return guide information for.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string ChannelIds { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional filter by user id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "MinStartDate", Description = "Optional. The minimum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string MinStartDate { get; set; }
-
- [ApiMember(Name = "HasAired", Description = "Optional. Filter by programs that have completed airing, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasAired { get; set; }
- public bool? IsAiring { get; set; }
-
- [ApiMember(Name = "MaxStartDate", Description = "Optional. The maximum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string MaxStartDate { get; set; }
-
- [ApiMember(Name = "MinEndDate", Description = "Optional. The minimum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string MinEndDate { get; set; }
-
- [ApiMember(Name = "MaxEndDate", Description = "Optional. The maximum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string MaxEndDate { get; set; }
-
- [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsMovie { get; set; }
-
- [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSeries { get; set; }
-
- [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsNews { get; set; }
-
- [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsKids { get; set; }
-
- [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSports { get; set; }
-
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "SortBy", Description = "Optional. Specify one or more sort orders, comma delimeted. Options: Name, StartDate", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string SortBy { get; set; }
-
- [ApiMember(Name = "SortOrder", Description = "Sort Order - Ascending,Descending", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SortOrder { get; set; }
-
- [ApiMember(Name = "Genres", Description = "The genres to return guide information for.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string Genres { get; set; }
-
- [ApiMember(Name = "GenreIds", Description = "The genres to return guide information for.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string GenreIds { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- public bool EnableTotalRecordCount { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- public string SeriesTimerId { get; set; }
- public Guid LibrarySeriesId { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- public GetPrograms()
- {
- EnableTotalRecordCount = true;
- }
- }
-
- [Route("/LiveTv/Programs/Recommended", "GET", Summary = "Gets available live tv epgs..")]
- [Authenticated]
- public class GetRecommendedPrograms : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- public bool EnableTotalRecordCount { get; set; }
-
- public GetRecommendedPrograms()
- {
- EnableTotalRecordCount = true;
- }
-
- [ApiMember(Name = "UserId", Description = "Optional filter by user id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "IsAiring", Description = "Optional. Filter by programs that are currently airing, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsAiring { get; set; }
-
- [ApiMember(Name = "HasAired", Description = "Optional. Filter by programs that have completed airing, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasAired { get; set; }
-
- [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSeries { get; set; }
-
- [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsMovie { get; set; }
-
- [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsNews { get; set; }
-
- [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsKids { get; set; }
-
- [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSports { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "GenreIds", Description = "The genres to return guide information for.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string GenreIds { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
- }
-
- [Route("/LiveTv/Programs/{Id}", "GET", Summary = "Gets a live tv program")]
- [Authenticated]
- public class GetProgram : IReturn<BaseItemDto>
- {
- [ApiMember(Name = "Id", Description = "Program Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "Optional attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
-
- [Route("/LiveTv/Recordings/{Id}", "DELETE", Summary = "Deletes a live tv recording")]
- [Authenticated]
- public class DeleteRecording : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Recording Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
- }
-
- [Route("/LiveTv/Timers/{Id}", "DELETE", Summary = "Cancels a live tv timer")]
- [Authenticated]
- public class CancelTimer : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Timer Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/Timers/{Id}", "POST", Summary = "Updates a live tv timer")]
- [Authenticated]
- public class UpdateTimer : TimerInfoDto, IReturnVoid
- {
- }
-
- [Route("/LiveTv/Timers", "POST", Summary = "Creates a live tv timer")]
- [Authenticated]
- public class CreateTimer : TimerInfoDto, IReturnVoid
- {
- }
-
- [Route("/LiveTv/SeriesTimers/{Id}", "GET", Summary = "Gets a live tv series timer")]
- [Authenticated]
- public class GetSeriesTimer : IReturn<TimerInfoDto>
- {
- [ApiMember(Name = "Id", Description = "Timer Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/SeriesTimers", "GET", Summary = "Gets live tv series timers")]
- [Authenticated]
- public class GetSeriesTimers : IReturn<QueryResult<SeriesTimerInfoDto>>
- {
- [ApiMember(Name = "SortBy", Description = "Optional. Sort by SortName or Priority", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public string SortBy { get; set; }
-
- [ApiMember(Name = "SortOrder", Description = "Optional. Sort in Ascending or Descending order", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")]
- public SortOrder SortOrder { get; set; }
- }
-
- [Route("/LiveTv/SeriesTimers/{Id}", "DELETE", Summary = "Cancels a live tv series timer")]
- [Authenticated]
- public class CancelSeriesTimer : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Timer Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/SeriesTimers/{Id}", "POST", Summary = "Updates a live tv series timer")]
- [Authenticated]
- public class UpdateSeriesTimer : SeriesTimerInfoDto, IReturnVoid
- {
- }
-
- [Route("/LiveTv/SeriesTimers", "POST", Summary = "Creates a live tv series timer")]
- [Authenticated]
- public class CreateSeriesTimer : SeriesTimerInfoDto, IReturnVoid
- {
- }
-
- [Route("/LiveTv/Recordings/Groups/{Id}", "GET", Summary = "Gets a recording group")]
- [Authenticated]
- public class GetRecordingGroup : IReturn<BaseItemDto>
- {
- [ApiMember(Name = "Id", Description = "Recording group Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/GuideInfo", "GET", Summary = "Gets guide info")]
- [Authenticated]
- public class GetGuideInfo : IReturn<GuideInfo>
- {
- }
-
- [Route("/LiveTv/TunerHosts", "POST", Summary = "Adds a tuner host")]
- [Authenticated]
- public class AddTunerHost : TunerHostInfo, IReturn<TunerHostInfo>
- {
- }
-
- [Route("/LiveTv/TunerHosts", "DELETE", Summary = "Deletes a tuner host")]
- [Authenticated]
- public class DeleteTunerHost : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Tuner host id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/ListingProviders/Default", "GET")]
- [Authenticated]
- public class GetDefaultListingProvider : ListingsProviderInfo, IReturn<ListingsProviderInfo>
- {
- }
-
- [Route("/LiveTv/ListingProviders", "POST", Summary = "Adds a listing provider")]
- [Authenticated]
- public class AddListingProvider : ListingsProviderInfo, IReturn<ListingsProviderInfo>
- {
- public bool ValidateLogin { get; set; }
- public bool ValidateListings { get; set; }
- public string Pw { get; set; }
- }
-
- [Route("/LiveTv/ListingProviders", "DELETE", Summary = "Deletes a listing provider")]
- [Authenticated]
- public class DeleteListingProvider : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Provider id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/ListingProviders/Lineups", "GET", Summary = "Gets available lineups")]
- [Authenticated]
- public class GetLineups : IReturn<List<NameIdPair>>
- {
- [ApiMember(Name = "Id", Description = "Provider id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "Type", Description = "Provider Type", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Type { get; set; }
-
- [ApiMember(Name = "Location", Description = "Location", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Location { get; set; }
-
- [ApiMember(Name = "Country", Description = "Country", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Country { get; set; }
- }
-
- [Route("/LiveTv/ListingProviders/SchedulesDirect/Countries", "GET", Summary = "Gets available lineups")]
- [Authenticated]
- public class GetSchedulesDirectCountries
- {
- }
-
- [Route("/LiveTv/ChannelMappingOptions")]
- [Authenticated]
- public class GetChannelMappingOptions
- {
- [ApiMember(Name = "Id", Description = "Provider id", IsRequired = true, DataType = "string", ParameterType = "query")]
- public string ProviderId { get; set; }
- }
-
- [Route("/LiveTv/ChannelMappings")]
- [Authenticated]
- public class SetChannelMapping
- {
- [ApiMember(Name = "Id", Description = "Provider id", IsRequired = true, DataType = "string", ParameterType = "query")]
- public string ProviderId { get; set; }
- public string TunerChannelId { get; set; }
- public string ProviderChannelId { get; set; }
- }
-
- public class ChannelMappingOptions
- {
- public List<TunerChannelMapping> TunerChannels { get; set; }
- public List<NameIdPair> ProviderChannels { get; set; }
- public NameValuePair[] Mappings { get; set; }
- public string ProviderName { get; set; }
- }
-
- [Route("/LiveTv/LiveStreamFiles/{Id}/stream.{Container}", "GET", Summary = "Gets a live tv channel")]
- public class GetLiveStreamFile
- {
- public string Id { get; set; }
- public string Container { get; set; }
- }
-
- [Route("/LiveTv/LiveRecordings/{Id}/stream", "GET", Summary = "Gets a live tv channel")]
- public class GetLiveRecordingFile
- {
- public string Id { get; set; }
- }
-
- [Route("/LiveTv/TunerHosts/Types", "GET")]
- [Authenticated]
- public class GetTunerHostTypes : IReturn<List<NameIdPair>>
- {
-
- }
-
- [Route("/LiveTv/Tuners/Discvover", "GET")]
- [Authenticated]
- public class DiscoverTuners : IReturn<List<TunerHostInfo>>
- {
- public bool NewDevicesOnly { get; set; }
- }
-
- public class LiveTvService : BaseApiService
- {
- private readonly ILiveTvManager _liveTvManager;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly ILibraryManager _libraryManager;
- private readonly IDtoService _dtoService;
- private readonly IFileSystem _fileSystem;
- private readonly IAuthorizationContext _authContext;
- private readonly ISessionContext _sessionContext;
- private readonly IEnvironmentInfo _environment;
- private ICryptoProvider _cryptographyProvider;
- private IStreamHelper _streamHelper;
- private IMediaSourceManager _mediaSourceManager;
-
- public LiveTvService(ICryptoProvider crypto, IMediaSourceManager mediaSourceManager, IStreamHelper streamHelper, ILiveTvManager liveTvManager, IUserManager userManager, IServerConfigurationManager config, IHttpClient httpClient, ILibraryManager libraryManager, IDtoService dtoService, IFileSystem fileSystem, IAuthorizationContext authContext, ISessionContext sessionContext, IEnvironmentInfo environment)
- {
- _liveTvManager = liveTvManager;
- _userManager = userManager;
- _config = config;
- _httpClient = httpClient;
- _libraryManager = libraryManager;
- _dtoService = dtoService;
- _fileSystem = fileSystem;
- _authContext = authContext;
- _sessionContext = sessionContext;
- _environment = environment;
- _cryptographyProvider = crypto;
- _streamHelper = streamHelper;
- _mediaSourceManager = mediaSourceManager;
- }
-
- public object Get(GetTunerHostTypes request)
- {
- var list = _liveTvManager.GetTunerHostTypes();
- return ToOptimizedResult(list);
- }
-
- public object Get(GetRecordingFolders request)
- {
- var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
- var folders = _liveTvManager.GetRecordingFolders(user);
-
- var returnArray = _dtoService.GetBaseItemDtos(folders.ToArray(), new DtoOptions(), user);
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = returnArray,
- TotalRecordCount = returnArray.Length
- };
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetLiveRecordingFile request)
- {
- var path = _liveTvManager.GetEmbyTvActiveRecordingPath(request.Id);
-
- if (string.IsNullOrWhiteSpace(path))
- {
- throw new FileNotFoundException();
- }
-
- var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- outputHeaders["Content-Type"] = Model.Net.MimeTypes.GetMimeType(path);
-
- return new ProgressiveFileCopier(_fileSystem, _streamHelper, path, outputHeaders, Logger, _environment)
- {
- AllowEndOfFile = false
- };
- }
-
- public async Task<object> Get(DiscoverTuners request)
- {
- var result = await _liveTvManager.DiscoverTuners(request.NewDevicesOnly, CancellationToken.None).ConfigureAwait(false);
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetLiveStreamFile request)
- {
- var liveStreamInfo = await _mediaSourceManager.GetDirectStreamProviderByUniqueId(request.Id, CancellationToken.None).ConfigureAwait(false);
-
- var directStreamProvider = liveStreamInfo;
-
- var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- outputHeaders["Content-Type"] = Model.Net.MimeTypes.GetMimeType("file." + request.Container);
-
- return new ProgressiveFileCopier(directStreamProvider, _streamHelper, outputHeaders, Logger, _environment)
- {
- AllowEndOfFile = false
- };
- }
-
- public object Get(GetDefaultListingProvider request)
- {
- return ToOptimizedResult(new ListingsProviderInfo());
- }
-
- public async Task<object> Post(SetChannelMapping request)
- {
- return await _liveTvManager.SetChannelMapping(request.ProviderId, request.TunerChannelId, request.ProviderChannelId).ConfigureAwait(false);
- }
-
- public async Task<object> Get(GetChannelMappingOptions request)
- {
- var config = GetConfiguration();
-
- var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(request.ProviderId, i.Id, StringComparison.OrdinalIgnoreCase));
-
- var listingsProviderName = _liveTvManager.ListingProviders.First(i => string.Equals(i.Type, listingsProviderInfo.Type, StringComparison.OrdinalIgnoreCase)).Name;
-
- var tunerChannels = await _liveTvManager.GetChannelsForListingsProvider(request.ProviderId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var providerChannels = await _liveTvManager.GetChannelsFromListingsProviderData(request.ProviderId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var mappings = listingsProviderInfo.ChannelMappings;
-
- var result = new ChannelMappingOptions
- {
- TunerChannels = tunerChannels.Select(i => _liveTvManager.GetTunerChannelMapping(i, mappings, providerChannels)).ToList(),
-
- ProviderChannels = providerChannels.Select(i => new NameIdPair
- {
- Name = i.Name,
- Id = i.Id
-
- }).ToList(),
-
- Mappings = mappings,
-
- ProviderName = listingsProviderName
- };
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetSchedulesDirectCountries request)
- {
- // https://json.schedulesdirect.org/20141201/available/countries
-
- var response = await _httpClient.Get(new HttpRequestOptions
- {
- Url = "https://json.schedulesdirect.org/20141201/available/countries",
- BufferContent = false
-
- }).ConfigureAwait(false);
-
- return ResultFactory.GetResult(Request, response, "application/json");
- }
-
- private void AssertUserCanManageLiveTv()
- {
- var user = _sessionContext.GetUser(Request);
-
- if (user == null)
- {
- throw new SecurityException("Anonymous live tv management is not allowed.");
- }
-
- if (!user.Policy.EnableLiveTvManagement)
- {
- throw new SecurityException("The current user does not have permission to manage live tv.");
- }
- }
-
- public async Task<object> Post(AddListingProvider request)
- {
- if (request.Pw != null)
- {
- request.Password = GetHashedString(request.Pw);
- }
-
- request.Pw = null;
-
- var result = await _liveTvManager.SaveListingProvider(request, request.ValidateLogin, request.ValidateListings).ConfigureAwait(false);
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the hashed string.
- /// </summary>
- private string GetHashedString(string str)
- {
- // legacy
- return BitConverter.ToString(
- _cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str)))
- .Replace("-", string.Empty).ToLowerInvariant();
- }
-
- public void Delete(DeleteListingProvider request)
- {
- _liveTvManager.DeleteListingsProvider(request.Id);
- }
-
- public async Task<object> Post(AddTunerHost request)
- {
- var result = await _liveTvManager.SaveTunerHost(request).ConfigureAwait(false);
- return ToOptimizedResult(result);
- }
-
- public void Delete(DeleteTunerHost request)
- {
- var config = GetConfiguration();
-
- config.TunerHosts = config.TunerHosts.Where(i => !string.Equals(request.Id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
-
- _config.SaveConfiguration("livetv", config);
- }
-
- private LiveTvOptions GetConfiguration()
- {
- return _config.GetConfiguration<LiveTvOptions>("livetv");
- }
-
- private void UpdateConfiguration(LiveTvOptions options)
- {
- _config.SaveConfiguration("livetv", options);
- }
-
- public async Task<object> Get(GetLineups request)
- {
- var info = await _liveTvManager.GetLineups(request.Type, request.Id, request.Country, request.Location).ConfigureAwait(false);
-
- return ToOptimizedResult(info);
- }
-
- public object Get(GetLiveTvInfo request)
- {
- var info = _liveTvManager.GetLiveTvInfo(CancellationToken.None);
-
- return ToOptimizedResult(info);
- }
-
- public object Get(GetChannels request)
- {
- var options = GetDtoOptions(_authContext, request);
-
- var channelResult = _liveTvManager.GetInternalChannels(new LiveTvChannelQuery
- {
- ChannelType = request.Type,
- UserId = request.UserId,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- IsFavorite = request.IsFavorite,
- IsLiked = request.IsLiked,
- IsDisliked = request.IsDisliked,
- EnableFavoriteSorting = request.EnableFavoriteSorting,
- IsMovie = request.IsMovie,
- IsSeries = request.IsSeries,
- IsNews = request.IsNews,
- IsKids = request.IsKids,
- IsSports = request.IsSports,
- SortBy = request.GetOrderBy(),
- SortOrder = request.SortOrder ?? SortOrder.Ascending,
- AddCurrentProgram = request.AddCurrentProgram
-
- }, options, CancellationToken.None);
-
- var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
-
- RemoveFields(options);
-
- options.AddCurrentProgram = request.AddCurrentProgram;
-
- var returnArray = _dtoService.GetBaseItemDtos(channelResult.Items, options, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = returnArray,
- TotalRecordCount = channelResult.TotalRecordCount
- };
-
- return ToOptimizedResult(result);
- }
-
- private void RemoveFields(DtoOptions options)
- {
- var fields = options.Fields.ToList();
-
- fields.Remove(ItemFields.CanDelete);
- fields.Remove(ItemFields.CanDownload);
- fields.Remove(ItemFields.DisplayPreferencesId);
- fields.Remove(ItemFields.Etag);
- options.Fields = fields.ToArray();
- }
-
- public object Get(GetChannel request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = _dtoService.GetBaseItemDto(item, dtoOptions, user);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetPrograms request)
- {
- var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
-
- var query = new InternalItemsQuery(user)
- {
- ChannelIds = ApiEntryPoint.Split(request.ChannelIds, ',', true).Select(i => new Guid(i)).ToArray(),
- HasAired = request.HasAired,
- IsAiring = request.IsAiring,
- EnableTotalRecordCount = request.EnableTotalRecordCount
- };
-
- if (!string.IsNullOrEmpty(request.MinStartDate))
- {
- query.MinStartDate = DateTime.Parse(request.MinStartDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MinEndDate))
- {
- query.MinEndDate = DateTime.Parse(request.MinEndDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MaxStartDate))
- {
- query.MaxStartDate = DateTime.Parse(request.MaxStartDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MaxEndDate))
- {
- query.MaxEndDate = DateTime.Parse(request.MaxEndDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- query.StartIndex = request.StartIndex;
- query.Limit = request.Limit;
- query.OrderBy = BaseItemsRequest.GetOrderBy(request.SortBy, request.SortOrder);
- query.IsNews = request.IsNews;
- query.IsMovie = request.IsMovie;
- query.IsSeries = request.IsSeries;
- query.IsKids = request.IsKids;
- query.IsSports = request.IsSports;
- query.SeriesTimerId = request.SeriesTimerId;
- query.Genres = (request.Genres ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- query.GenreIds = GetGuids(request.GenreIds);
-
- if (!request.LibrarySeriesId.Equals(Guid.Empty))
- {
- query.IsSeries = true;
-
- var series = _libraryManager.GetItemById(request.LibrarySeriesId) as Series;
- if (series != null)
- {
- query.Name = series.Name;
- }
- }
-
- var result = await _liveTvManager.GetPrograms(query, GetDtoOptions(_authContext, request), CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetRecommendedPrograms request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var query = new InternalItemsQuery(user)
- {
- IsAiring = request.IsAiring,
- Limit = request.Limit,
- HasAired = request.HasAired,
- IsSeries = request.IsSeries,
- IsMovie = request.IsMovie,
- IsKids = request.IsKids,
- IsNews = request.IsNews,
- IsSports = request.IsSports,
- EnableTotalRecordCount = request.EnableTotalRecordCount
- };
-
- query.GenreIds = GetGuids(request.GenreIds);
-
- var result = _liveTvManager.GetRecommendedPrograms(query, GetDtoOptions(_authContext, request), CancellationToken.None);
-
- return ToOptimizedResult(result);
- }
-
- public object Post(GetPrograms request)
- {
- return Get(request);
- }
-
- public object Get(GetRecordings request)
- {
- var options = GetDtoOptions(_authContext, request);
-
- var result = _liveTvManager.GetRecordings(new RecordingQuery
- {
- ChannelId = request.ChannelId,
- UserId = request.UserId,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- Status = request.Status,
- SeriesTimerId = request.SeriesTimerId,
- IsInProgress = request.IsInProgress,
- EnableTotalRecordCount = request.EnableTotalRecordCount,
- IsMovie = request.IsMovie,
- IsNews = request.IsNews,
- IsSeries = request.IsSeries,
- IsKids = request.IsKids,
- IsSports = request.IsSports,
- IsLibraryItem = request.IsLibraryItem,
- Fields = request.GetItemFields(),
- ImageTypeLimit = request.ImageTypeLimit,
- EnableImages = request.EnableImages
-
- }, options);
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetRecordingSeries request)
- {
- return ToOptimizedResult(new QueryResult<BaseItemDto>());
- }
-
- public object Get(GetRecording request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = _dtoService.GetBaseItemDto(item, dtoOptions, user);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetTimer request)
- {
- var result = await _liveTvManager.GetTimer(request.Id, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetTimers request)
- {
- var result = await _liveTvManager.GetTimers(new TimerQuery
- {
- ChannelId = request.ChannelId,
- SeriesTimerId = request.SeriesTimerId,
- IsActive = request.IsActive,
- IsScheduled = request.IsScheduled
-
- }, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public void Delete(DeleteRecording request)
- {
- AssertUserCanManageLiveTv();
-
- _libraryManager.DeleteItem(_libraryManager.GetItemById(request.Id), new DeleteOptions
- {
- DeleteFileLocation = false
- });
- }
-
- public Task Delete(CancelTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.CancelTimer(request.Id);
- }
-
- public Task Post(UpdateTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.UpdateTimer(request, CancellationToken.None);
- }
-
- public async Task<object> Get(GetSeriesTimers request)
- {
- var result = await _liveTvManager.GetSeriesTimers(new SeriesTimerQuery
- {
- SortOrder = request.SortOrder,
- SortBy = request.SortBy
-
- }, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetSeriesTimer request)
- {
- var result = await _liveTvManager.GetSeriesTimer(request.Id, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public Task Delete(CancelSeriesTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.CancelSeriesTimer(request.Id);
- }
-
- public Task Post(UpdateSeriesTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.UpdateSeriesTimer(request, CancellationToken.None);
- }
-
- public async Task<object> Get(GetDefaultTimer request)
- {
- if (string.IsNullOrEmpty(request.ProgramId))
- {
- var result = await _liveTvManager.GetNewTimerDefaults(CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
- else
- {
- var result = await _liveTvManager.GetNewTimerDefaults(request.ProgramId, CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
- }
-
- public async Task<object> Get(GetProgram request)
- {
- var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
-
- var result = await _liveTvManager.GetProgram(request.Id, CancellationToken.None, user).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public Task Post(CreateSeriesTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.CreateSeriesTimer(request, CancellationToken.None);
- }
-
- public Task Post(CreateTimer request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.CreateTimer(request, CancellationToken.None);
- }
-
- public object Get(GetRecordingGroups request)
- {
- return ToOptimizedResult(new QueryResult<BaseItemDto>());
- }
-
- public object Get(GetRecordingGroup request)
- {
- throw new FileNotFoundException();
- }
-
- public object Get(GetGuideInfo request)
- {
- return ToOptimizedResult(_liveTvManager.GetGuideInfo());
- }
-
- public Task Post(ResetTuner request)
- {
- AssertUserCanManageLiveTv();
-
- return _liveTvManager.ResetTuner(request.Id, CancellationToken.None);
- }
- }
-}
diff --git a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs
deleted file mode 100644
index 8412bf66b..000000000
--- a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.LiveTv
-{
- public class ProgressiveFileCopier : IAsyncStreamWriter, IHasHeaders
- {
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
- private readonly string _path;
- private readonly Dictionary<string, string> _outputHeaders;
-
- const int StreamCopyToBufferSize = 81920;
-
- public long StartPosition { get; set; }
- public bool AllowEndOfFile = true;
-
- private readonly IDirectStreamProvider _directStreamProvider;
- private readonly IEnvironmentInfo _environment;
- private IStreamHelper _streamHelper;
-
- public ProgressiveFileCopier(IFileSystem fileSystem, IStreamHelper streamHelper, string path, Dictionary<string, string> outputHeaders, ILogger logger, IEnvironmentInfo environment)
- {
- _fileSystem = fileSystem;
- _path = path;
- _outputHeaders = outputHeaders;
- _logger = logger;
- _environment = environment;
- _streamHelper = streamHelper;
- }
-
- public ProgressiveFileCopier(IDirectStreamProvider directStreamProvider, IStreamHelper streamHelper, Dictionary<string, string> outputHeaders, ILogger logger, IEnvironmentInfo environment)
- {
- _directStreamProvider = directStreamProvider;
- _outputHeaders = outputHeaders;
- _logger = logger;
- _environment = environment;
- _streamHelper = streamHelper;
- }
-
- public IDictionary<string, string> Headers => _outputHeaders;
-
- private Stream GetInputStream(bool allowAsyncFileRead)
- {
- var fileOpenOptions = FileOpenOptions.SequentialScan;
-
- if (allowAsyncFileRead)
- {
- fileOpenOptions |= FileOpenOptions.Asynchronous;
- }
-
- return _fileSystem.GetFileStream(_path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
- }
-
- public async Task WriteToAsync(Stream outputStream, CancellationToken cancellationToken)
- {
- if (_directStreamProvider != null)
- {
- await _directStreamProvider.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
- return;
- }
-
- var eofCount = 0;
-
- // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
- var allowAsyncFileRead = true;
-
- using (var inputStream = GetInputStream(allowAsyncFileRead))
- {
- if (StartPosition > 0)
- {
- inputStream.Position = StartPosition;
- }
-
- var emptyReadLimit = AllowEndOfFile ? 20 : 100;
-
- while (eofCount < emptyReadLimit)
- {
- int bytesRead;
- bytesRead = await _streamHelper.CopyToAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
-
- //var position = fs.Position;
- //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
-
- if (bytesRead == 0)
- {
- eofCount++;
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- eofCount = 0;
- }
- }
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/LocalizationService.cs b/MediaBrowser.Api/LocalizationService.cs
deleted file mode 100644
index eeff67e13..000000000
--- a/MediaBrowser.Api/LocalizationService.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetCultures
- /// </summary>
- [Route("/Localization/Cultures", "GET", Summary = "Gets known cultures")]
- public class GetCultures : IReturn<CultureDto[]>
- {
- }
-
- /// <summary>
- /// Class GetCountries
- /// </summary>
- [Route("/Localization/Countries", "GET", Summary = "Gets known countries")]
- public class GetCountries : IReturn<CountryInfo[]>
- {
- }
-
- /// <summary>
- /// Class ParentalRatings
- /// </summary>
- [Route("/Localization/ParentalRatings", "GET", Summary = "Gets known parental ratings")]
- public class GetParentalRatings : IReturn<ParentalRating[]>
- {
- }
-
- /// <summary>
- /// Class ParentalRatings
- /// </summary>
- [Route("/Localization/Options", "GET", Summary = "Gets localization options")]
- public class GetLocalizationOptions : IReturn<LocalizationOption[]>
- {
- }
-
- /// <summary>
- /// Class CulturesService
- /// </summary>
- [Authenticated(AllowBeforeStartupWizard = true)]
- public class LocalizationService : BaseApiService
- {
- /// <summary>
- /// The _localization
- /// </summary>
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LocalizationService"/> class.
- /// </summary>
- /// <param name="localization">The localization.</param>
- public LocalizationService(ILocalizationManager localization)
- {
- _localization = localization;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetParentalRatings request)
- {
- var result = _localization.GetParentalRatings();
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetLocalizationOptions request)
- {
- var result = _localization.GetLocalizationOptions();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetCountries request)
- {
- var result = await _localization.GetCountries();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetCultures request)
- {
- var result = _localization.GetCultures();
-
- return ToOptimizedResult(result);
- }
- }
-
-}
diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj
deleted file mode 100644
index ba29c656b..000000000
--- a/MediaBrowser.Api/MediaBrowser.Api.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/MediaBrowser.Api/Movies/CollectionService.cs b/MediaBrowser.Api/Movies/CollectionService.cs
deleted file mode 100644
index b52f8a547..000000000
--- a/MediaBrowser.Api/Movies/CollectionService.cs
+++ /dev/null
@@ -1,96 +0,0 @@
-using System;
-using MediaBrowser.Controller.Collections;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Collections;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Movies
-{
- [Route("/Collections", "POST", Summary = "Creates a new collection")]
- public class CreateCollection : IReturn<CollectionCreationResult>
- {
- [ApiMember(Name = "IsLocked", Description = "Whether or not to lock the new collection.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
- public bool IsLocked { get; set; }
-
- [ApiMember(Name = "Name", Description = "The name of the new collection.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Name { get; set; }
-
- [ApiMember(Name = "ParentId", Description = "Optional - create the collection within a specific folder", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "Ids", Description = "Item Ids to add to the collection", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
- public string Ids { get; set; }
- }
-
- [Route("/Collections/{Id}/Items", "POST", Summary = "Adds items to a collection")]
- public class AddToCollection : IReturnVoid
- {
- [ApiMember(Name = "Ids", Description = "Item id, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Ids { get; set; }
-
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Collections/{Id}/Items", "DELETE", Summary = "Removes items from a collection")]
- public class RemoveFromCollection : IReturnVoid
- {
- [ApiMember(Name = "Ids", Description = "Item id, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string Ids { get; set; }
-
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Authenticated]
- public class CollectionService : BaseApiService
- {
- private readonly ICollectionManager _collectionManager;
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
-
- public CollectionService(ICollectionManager collectionManager, IDtoService dtoService, IAuthorizationContext authContext)
- {
- _collectionManager = collectionManager;
- _dtoService = dtoService;
- _authContext = authContext;
- }
-
- public object Post(CreateCollection request)
- {
- var userId = _authContext.GetAuthorizationInfo(Request).UserId;
-
- var parentId = string.IsNullOrWhiteSpace(request.ParentId) ? (Guid?)null : new Guid(request.ParentId);
-
- var item = _collectionManager.CreateCollection(new CollectionCreationOptions
- {
- IsLocked = request.IsLocked,
- Name = request.Name,
- ParentId = parentId,
- ItemIdList = SplitValue(request.Ids, ','),
- UserIds = new[] { userId }
-
- });
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dto = _dtoService.GetBaseItemDto(item, dtoOptions);
-
- return new CollectionCreationResult
- {
- Id = dto.Id
- };
- }
-
- public void Post(AddToCollection request)
- {
- _collectionManager.AddToCollection(new Guid(request.Id), SplitValue(request.Ids, ','));
- }
-
- public void Delete(RemoveFromCollection request)
- {
- _collectionManager.RemoveFromCollection(new Guid(request.Id), SplitValue(request.Ids, ','));
- }
- }
-}
diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs
deleted file mode 100644
index 91766255f..000000000
--- a/MediaBrowser.Api/Movies/MoviesService.cs
+++ /dev/null
@@ -1,406 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Movies
-{
- [Route("/Movies/Recommendations", "GET", Summary = "Gets movie recommendations")]
- public class GetMovieRecommendations : IReturn<RecommendationDto[]>, IHasDtoOptions
- {
- [ApiMember(Name = "CategoryLimit", Description = "The max number of categories to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int CategoryLimit { get; set; }
-
- [ApiMember(Name = "ItemLimit", Description = "The max number of items to return per category", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int ItemLimit { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// </summary>
- /// <value>The parent id.</value>
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- public GetMovieRecommendations()
- {
- CategoryLimit = 5;
- ItemLimit = 8;
- }
-
- public string Fields { get; set; }
- }
-
- /// <summary>
- /// Class MoviesService
- /// </summary>
- [Authenticated]
- public class MoviesService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- private readonly ILibraryManager _libraryManager;
-
- private readonly IDtoService _dtoService;
- private readonly IServerConfigurationManager _config;
- private readonly IAuthorizationContext _authContext;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MoviesService" /> class.
- /// </summary>
- public MoviesService(IUserManager userManager, ILibraryManager libraryManager, IDtoService dtoService, IServerConfigurationManager config, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _libraryManager = libraryManager;
- _dtoService = dtoService;
- _config = config;
- _authContext = authContext;
- }
-
- public object Get(GetMovieRecommendations request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = GetRecommendationCategories(user, request.ParentId, request.CategoryLimit, request.ItemLimit, dtoOptions);
-
- return ToOptimizedResult(result);
- }
-
- public QueryResult<BaseItemDto> GetSimilarItemsResult(BaseGetSimilarItemsFromItem request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id) ?
- (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() :
- _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id);
-
- var itemTypes = new List<string> { typeof(Movie).Name };
- if (_config.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(typeof(Trailer).Name);
- itemTypes.Add(typeof(LiveTvProgram).Name);
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- Limit = request.Limit,
- IncludeItemTypes = itemTypes.ToArray(),
- IsMovie = true,
- SimilarTo = item,
- EnableGroupByMetadataKey = true,
- DtoOptions = dtoOptions
-
- });
-
- var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = returnList,
-
- TotalRecordCount = itemsResult.Count
- };
-
- return result;
- }
-
- private IEnumerable<RecommendationDto> GetRecommendationCategories(User user, string parentId, int categoryLimit, int itemLimit, DtoOptions dtoOptions)
- {
- var categories = new List<RecommendationDto>();
-
- var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId);
-
- var query = new InternalItemsQuery(user)
- {
- IncludeItemTypes = new[]
- {
- typeof(Movie).Name,
- //typeof(Trailer).Name,
- //typeof(LiveTvProgram).Name
- },
- // IsMovie = true
- OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.Random }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(),
- Limit = 7,
- ParentId = parentIdGuid,
- Recursive = true,
- IsPlayed = true,
- DtoOptions = dtoOptions
- };
-
- var recentlyPlayedMovies = _libraryManager.GetItemList(query);
-
- var itemTypes = new List<string> { typeof(Movie).Name };
- if (_config.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(typeof(Trailer).Name);
- itemTypes.Add(typeof(LiveTvProgram).Name);
- }
-
- var likedMovies = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- IncludeItemTypes = itemTypes.ToArray(),
- IsMovie = true,
- OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(),
- Limit = 10,
- IsFavoriteOrLiked = true,
- ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(),
- EnableGroupByMetadataKey = true,
- ParentId = parentIdGuid,
- Recursive = true,
- DtoOptions = dtoOptions
-
- });
-
- var mostRecentMovies = recentlyPlayedMovies.Take(6).ToList();
- // Get recently played directors
- var recentDirectors = GetDirectors(mostRecentMovies)
- .OrderBy(i => Guid.NewGuid())
- .ToList();
-
- // Get recently played actors
- var recentActors = GetActors(mostRecentMovies)
- .OrderBy(i => Guid.NewGuid())
- .ToList();
-
- var similarToRecentlyPlayed = GetSimilarTo(user, recentlyPlayedMovies, itemLimit, dtoOptions, RecommendationType.SimilarToRecentlyPlayed).GetEnumerator();
- var similarToLiked = GetSimilarTo(user, likedMovies, itemLimit, dtoOptions, RecommendationType.SimilarToLikedItem).GetEnumerator();
-
- var hasDirectorFromRecentlyPlayed = GetWithDirector(user, recentDirectors, itemLimit, dtoOptions, RecommendationType.HasDirectorFromRecentlyPlayed).GetEnumerator();
- var hasActorFromRecentlyPlayed = GetWithActor(user, recentActors, itemLimit, dtoOptions, RecommendationType.HasActorFromRecentlyPlayed).GetEnumerator();
-
- var categoryTypes = new List<IEnumerator<RecommendationDto>>
- {
- // Give this extra weight
- similarToRecentlyPlayed,
- similarToRecentlyPlayed,
-
- // Give this extra weight
- similarToLiked,
- similarToLiked,
-
- hasDirectorFromRecentlyPlayed,
- hasActorFromRecentlyPlayed
- };
-
- while (categories.Count < categoryLimit)
- {
- var allEmpty = true;
-
- foreach (var category in categoryTypes)
- {
- if (category.MoveNext())
- {
- categories.Add(category.Current);
- allEmpty = false;
-
- if (categories.Count >= categoryLimit)
- {
- break;
- }
- }
- }
-
- if (allEmpty)
- {
- break;
- }
- }
-
- return categories.OrderBy(i => i.RecommendationType).ThenBy(i => Guid.NewGuid());
- }
-
- private IEnumerable<RecommendationDto> GetWithDirector(User user, IEnumerable<string> names, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
- {
- var itemTypes = new List<string> { typeof(Movie).Name };
- if (_config.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(typeof(Trailer).Name);
- itemTypes.Add(typeof(LiveTvProgram).Name);
- }
-
- foreach (var name in names)
- {
- var items = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- Person = name,
- // Account for duplicates by imdb id, since the database doesn't support this yet
- Limit = itemLimit + 2,
- PersonTypes = new[] { PersonType.Director },
- IncludeItemTypes = itemTypes.ToArray(),
- IsMovie = true,
- EnableGroupByMetadataKey = true,
- DtoOptions = dtoOptions
-
- }).GroupBy(i => i.GetProviderId(MetadataProviders.Imdb) ?? Guid.NewGuid().ToString("N"))
- .Select(x => x.First())
- .Take(itemLimit)
- .ToList();
-
- if (items.Count > 0)
- {
- var returnItems = _dtoService.GetBaseItemDtos(items, dtoOptions, user);
-
- yield return new RecommendationDto
- {
- BaselineItemName = name,
- CategoryId = name.GetMD5(),
- RecommendationType = type,
- Items = returnItems
- };
- }
- }
- }
-
- private IEnumerable<RecommendationDto> GetWithActor(User user, IEnumerable<string> names, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
- {
- var itemTypes = new List<string> { typeof(Movie).Name };
- if (_config.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(typeof(Trailer).Name);
- itemTypes.Add(typeof(LiveTvProgram).Name);
- }
-
- foreach (var name in names)
- {
- var items = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- Person = name,
- // Account for duplicates by imdb id, since the database doesn't support this yet
- Limit = itemLimit + 2,
- IncludeItemTypes = itemTypes.ToArray(),
- IsMovie = true,
- EnableGroupByMetadataKey = true,
- DtoOptions = dtoOptions
-
- }).GroupBy(i => i.GetProviderId(MetadataProviders.Imdb) ?? Guid.NewGuid().ToString("N"))
- .Select(x => x.First())
- .Take(itemLimit)
- .ToList();
-
- if (items.Count > 0)
- {
- var returnItems = _dtoService.GetBaseItemDtos(items, dtoOptions, user);
-
- yield return new RecommendationDto
- {
- BaselineItemName = name,
- CategoryId = name.GetMD5(),
- RecommendationType = type,
- Items = returnItems
- };
- }
- }
- }
-
- private IEnumerable<RecommendationDto> GetSimilarTo(User user, List<BaseItem> baselineItems, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
- {
- var itemTypes = new List<string> { typeof(Movie).Name };
- if (_config.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(typeof(Trailer).Name);
- itemTypes.Add(typeof(LiveTvProgram).Name);
- }
-
- foreach (var item in baselineItems)
- {
- var similar = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- Limit = itemLimit,
- IncludeItemTypes = itemTypes.ToArray(),
- IsMovie = true,
- SimilarTo = item,
- EnableGroupByMetadataKey = true,
- DtoOptions = dtoOptions
-
- });
-
- if (similar.Count > 0)
- {
- var returnItems = _dtoService.GetBaseItemDtos(similar, dtoOptions, user);
-
- yield return new RecommendationDto
- {
- BaselineItemName = item.Name,
- CategoryId = item.Id,
- RecommendationType = type,
- Items = returnItems
- };
- }
- }
- }
-
- private IEnumerable<string> GetActors(List<BaseItem> items)
- {
- var people = _libraryManager.GetPeople(new InternalPeopleQuery
- {
- ExcludePersonTypes = new[]
- {
- PersonType.Director
- },
- MaxListOrder = 3
- });
-
- var itemIds = items.Select(i => i.Id).ToList();
-
- return people
- .Where(i => itemIds.Contains(i.ItemId))
- .Select(i => i.Name)
- .DistinctNames();
- }
-
- private IEnumerable<string> GetDirectors(List<BaseItem> items)
- {
- var people = _libraryManager.GetPeople(new InternalPeopleQuery
- {
- PersonTypes = new string[]
- {
- PersonType.Director
- }
- });
-
- var itemIds = items.Select(i => i.Id).ToList();
-
- return people
- .Where(i => itemIds.Contains(i.ItemId))
- .Select(i => i.Name)
- .DistinctNames();
- }
- }
-}
diff --git a/MediaBrowser.Api/Movies/TrailersService.cs b/MediaBrowser.Api/Movies/TrailersService.cs
deleted file mode 100644
index 6e4443dbe..000000000
--- a/MediaBrowser.Api/Movies/TrailersService.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using MediaBrowser.Api.UserLibrary;
-using MediaBrowser.Controller.Collections;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Movies
-{
- [Route("/Trailers", "GET", Summary = "Finds movies and trailers similar to a given trailer.")]
- public class Getrailers : BaseItemsRequest, IReturn<QueryResult<BaseItemDto>>
- {
- }
-
- /// <summary>
- /// Class TrailersService
- /// </summary>
- [Authenticated]
- public class TrailersService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- /// <summary>
- /// The _user data repository
- /// </summary>
- private readonly IUserDataManager _userDataRepository;
- /// <summary>
- /// The _library manager
- /// </summary>
- private readonly ILibraryManager _libraryManager;
-
- private readonly IDtoService _dtoService;
- private readonly ICollectionManager _collectionManager;
- private readonly ILocalizationManager _localizationManager;
- private readonly IJsonSerializer _json;
- private readonly IAuthorizationContext _authContext;
-
- public TrailersService(IUserManager userManager, IUserDataManager userDataRepository, ILibraryManager libraryManager, IDtoService dtoService, ICollectionManager collectionManager, ILocalizationManager localizationManager, IJsonSerializer json, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _userDataRepository = userDataRepository;
- _libraryManager = libraryManager;
- _dtoService = dtoService;
- _collectionManager = collectionManager;
- _localizationManager = localizationManager;
- _json = json;
- _authContext = authContext;
- }
-
- public object Get(Getrailers request)
- {
- var json = _json.SerializeToString(request);
- var getItems = _json.DeserializeFromString<GetItems>(json);
-
- getItems.IncludeItemTypes = "Trailer";
-
- return new ItemsService(_userManager, _libraryManager, _localizationManager, _dtoService, _authContext)
- {
- Request = Request,
-
- }.Get(getItems);
- }
- }
-}
diff --git a/MediaBrowser.Api/Music/AlbumsService.cs b/MediaBrowser.Api/Music/AlbumsService.cs
deleted file mode 100644
index c48bcde5c..000000000
--- a/MediaBrowser.Api/Music/AlbumsService.cs
+++ /dev/null
@@ -1,119 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Music
-{
- [Route("/Albums/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
- public class GetSimilarAlbums : BaseGetSimilarItemsFromItem
- {
- }
-
- [Route("/Artists/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
- public class GetSimilarArtists : BaseGetSimilarItemsFromItem
- {
- }
-
- [Authenticated]
- public class AlbumsService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- /// <summary>
- /// The _user data repository
- /// </summary>
- private readonly IUserDataManager _userDataRepository;
- /// <summary>
- /// The _library manager
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly IItemRepository _itemRepo;
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
-
- public AlbumsService(IUserManager userManager, IUserDataManager userDataRepository, ILibraryManager libraryManager, IItemRepository itemRepo, IDtoService dtoService, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _userDataRepository = userDataRepository;
- _libraryManager = libraryManager;
- _itemRepo = itemRepo;
- _dtoService = dtoService;
- _authContext = authContext;
- }
-
- public object Get(GetSimilarArtists request)
- {
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = SimilarItemsHelper.GetSimilarItemsResult(dtoOptions, _userManager,
- _itemRepo,
- _libraryManager,
- _userDataRepository,
- _dtoService,
- Logger,
- request, new[] { typeof(MusicArtist) },
- SimilarItemsHelper.GetSimiliarityScore);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetSimilarAlbums request)
- {
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = SimilarItemsHelper.GetSimilarItemsResult(dtoOptions, _userManager,
- _itemRepo,
- _libraryManager,
- _userDataRepository,
- _dtoService,
- Logger,
- request, new[] { typeof(MusicAlbum) },
- GetAlbumSimilarityScore);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the album similarity score.
- /// </summary>
- /// <param name="item1">The item1.</param>
- /// <param name="item1People">The item1 people.</param>
- /// <param name="allPeople">All people.</param>
- /// <param name="item2">The item2.</param>
- /// <returns>System.Int32.</returns>
- private int GetAlbumSimilarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2)
- {
- var points = SimilarItemsHelper.GetSimiliarityScore(item1, item1People, allPeople, item2);
-
- var album1 = (MusicAlbum)item1;
- var album2 = (MusicAlbum)item2;
-
- var artists1 = album1
- .AllArtists
- .DistinctNames()
- .ToList();
-
- var artists2 = album2
- .AllArtists
- .DistinctNames()
- .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
-
- return points + artists1.Where(artists2.ContainsKey).Sum(i => 5);
- }
- }
-}
diff --git a/MediaBrowser.Api/Music/InstantMixService.cs b/MediaBrowser.Api/Music/InstantMixService.cs
deleted file mode 100644
index 875f0a8de..000000000
--- a/MediaBrowser.Api/Music/InstantMixService.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Music
-{
- [Route("/Songs/{Id}/InstantMix", "GET", Summary = "Creates an instant playlist based on a given song")]
- public class GetInstantMixFromSong : BaseGetSimilarItemsFromItem
- {
- }
-
- [Route("/Albums/{Id}/InstantMix", "GET", Summary = "Creates an instant playlist based on a given album")]
- public class GetInstantMixFromAlbum : BaseGetSimilarItemsFromItem
- {
- }
-
- [Route("/Playlists/{Id}/InstantMix", "GET", Summary = "Creates an instant playlist based on a given playlist")]
- public class GetInstantMixFromPlaylist : BaseGetSimilarItemsFromItem
- {
- }
-
- [Route("/MusicGenres/{Name}/InstantMix", "GET", Summary = "Creates an instant playlist based on a music genre")]
- public class GetInstantMixFromMusicGenre : BaseGetSimilarItems
- {
- [ApiMember(Name = "Name", Description = "The genre name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
- }
-
- [Route("/Artists/InstantMix", "GET", Summary = "Creates an instant playlist based on a given artist")]
- public class GetInstantMixFromArtistId : BaseGetSimilarItems
- {
- [ApiMember(Name = "Id", Description = "The artist Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/MusicGenres/InstantMix", "GET", Summary = "Creates an instant playlist based on a music genre")]
- public class GetInstantMixFromMusicGenreId : BaseGetSimilarItems
- {
- [ApiMember(Name = "Id", Description = "The genre Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Items/{Id}/InstantMix", "GET", Summary = "Creates an instant playlist based on a given item")]
- public class GetInstantMixFromItem : BaseGetSimilarItemsFromItem
- {
- }
-
- [Authenticated]
- public class InstantMixService : BaseApiService
- {
- private readonly IUserManager _userManager;
-
- private readonly IDtoService _dtoService;
- private readonly ILibraryManager _libraryManager;
- private readonly IMusicManager _musicManager;
- private readonly IAuthorizationContext _authContext;
-
- public InstantMixService(IUserManager userManager, IDtoService dtoService, IMusicManager musicManager, ILibraryManager libraryManager, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _dtoService = dtoService;
- _musicManager = musicManager;
- _libraryManager = libraryManager;
- _authContext = authContext;
- }
-
- public object Get(GetInstantMixFromItem request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromArtistId request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromMusicGenreId request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromSong request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromAlbum request)
- {
- var album = _libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(album, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromPlaylist request)
- {
- var playlist = (Playlist)_libraryManager.GetItemById(request.Id);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromItem(playlist, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- public object Get(GetInstantMixFromMusicGenre request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var items = _musicManager.GetInstantMixFromGenres(new[] { request.Name }, user, dtoOptions);
-
- return GetResult(items, user, request, dtoOptions);
- }
-
- private object GetResult(List<BaseItem> items, User user, BaseGetSimilarItems request, DtoOptions dtoOptions)
- {
- var list = items;
-
- var result = new QueryResult<BaseItemDto>
- {
- TotalRecordCount = list.Count
- };
-
- if (request.Limit.HasValue)
- {
- list = list.Take(request.Limit.Value).ToList();
- }
-
- var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user);
-
- result.Items = returnList;
-
- return result;
- }
-
- }
-}
diff --git a/MediaBrowser.Api/PackageService.cs b/MediaBrowser.Api/PackageService.cs
deleted file mode 100644
index fbb876dea..000000000
--- a/MediaBrowser.Api/PackageService.cs
+++ /dev/null
@@ -1,218 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Updates;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetPackage
- /// </summary>
- [Route("/Packages/{Name}", "GET", Summary = "Gets a package, by name or assembly guid")]
- [Authenticated]
- public class GetPackage : IReturn<PackageInfo>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The name of the package", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "AssemblyGuid", Description = "The guid of the associated assembly", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string AssemblyGuid { get; set; }
- }
-
- /// <summary>
- /// Class GetPackages
- /// </summary>
- [Route("/Packages", "GET", Summary = "Gets available packages")]
- [Authenticated]
- public class GetPackages : IReturn<PackageInfo[]>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "PackageType", Description = "Optional package type filter (System/UserInstalled)", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string PackageType { get; set; }
-
- [ApiMember(Name = "TargetSystems", Description = "Optional. Filter by target system type. Allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string TargetSystems { get; set; }
-
- [ApiMember(Name = "IsPremium", Description = "Optional. Filter by premium status", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? IsPremium { get; set; }
-
- [ApiMember(Name = "IsAdult", Description = "Optional. Filter by package that contain adult content.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? IsAdult { get; set; }
-
- public bool? IsAppStoreEnabled { get; set; }
- }
-
- /// <summary>
- /// Class InstallPackage
- /// </summary>
- [Route("/Packages/Installed/{Name}", "POST", Summary = "Installs a package")]
- [Authenticated(Roles = "Admin")]
- public class InstallPackage : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "Package name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "AssemblyGuid", Description = "Guid of the associated assembly", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string AssemblyGuid { get; set; }
-
- /// <summary>
- /// Gets or sets the version.
- /// </summary>
- /// <value>The version.</value>
- [ApiMember(Name = "Version", Description = "Optional version. Defaults to latest version.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Version { get; set; }
-
- /// <summary>
- /// Gets or sets the update class.
- /// </summary>
- /// <value>The update class.</value>
- [ApiMember(Name = "UpdateClass", Description = "Optional update class (Dev, Beta, Release). Defaults to Release.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public PackageVersionClass UpdateClass { get; set; }
- }
-
- /// <summary>
- /// Class CancelPackageInstallation
- /// </summary>
- [Route("/Packages/Installing/{Id}", "DELETE", Summary = "Cancels a package installation")]
- [Authenticated(Roles = "Admin")]
- public class CancelPackageInstallation : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Installation Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class PackageService
- /// </summary>
- public class PackageService : BaseApiService
- {
- private readonly IInstallationManager _installationManager;
- private readonly IApplicationHost _appHost;
-
- public PackageService(IInstallationManager installationManager, IApplicationHost appHost)
- {
- _installationManager = installationManager;
- _appHost = appHost;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- ///
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPackage request)
- {
- var packages = _installationManager.GetAvailablePackages(CancellationToken.None, applicationVersion: typeof(PackageService).Assembly.GetName().Version).Result;
-
- var result = packages.FirstOrDefault(p => string.Equals(p.guid, request.AssemblyGuid ?? "none", StringComparison.OrdinalIgnoreCase))
- ?? packages.FirstOrDefault(p => p.name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetPackages request)
- {
- IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages(CancellationToken.None, false, request.PackageType, typeof(PackageService).Assembly.GetName().Version).ConfigureAwait(false);
-
- if (!string.IsNullOrEmpty(request.TargetSystems))
- {
- var apps = request.TargetSystems.Split(',').Select(i => (PackageTargetSystem)Enum.Parse(typeof(PackageTargetSystem), i, true));
-
- packages = packages.Where(p => apps.Contains(p.targetSystem));
- }
-
- if (request.IsPremium.HasValue)
- {
- packages = packages.Where(p => p.isPremium == request.IsPremium.Value);
- }
-
- if (request.IsAdult.HasValue)
- {
- packages = packages.Where(p => p.adult == request.IsAdult.Value);
- }
-
- if (request.IsAppStoreEnabled.HasValue)
- {
- packages = packages.Where(p => p.enableInAppStore == request.IsAppStoreEnabled.Value);
- }
-
- return ToOptimizedResult(packages.ToArray());
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <exception cref="ResourceNotFoundException"></exception>
- public async Task Post(InstallPackage request)
- {
- var package = string.IsNullOrEmpty(request.Version) ?
- await _installationManager.GetLatestCompatibleVersion(request.Name, request.AssemblyGuid, typeof(PackageService).Assembly.GetName().Version, request.UpdateClass).ConfigureAwait(false) :
- await _installationManager.GetPackage(request.Name, request.AssemblyGuid, request.UpdateClass, Version.Parse(request.Version)).ConfigureAwait(false);
-
- if (package == null)
- {
- throw new ResourceNotFoundException(string.Format("Package not found: {0}", request.Name));
- }
-
- await _installationManager.InstallPackage(package, true, new SimpleProgress<double>(), CancellationToken.None);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(CancelPackageInstallation request)
- {
- var info = _installationManager.CurrentInstallations.FirstOrDefault(i => i.Item1.Id.Equals(request.Id));
-
- if (info != null)
- {
- info.Item2.Cancel();
- }
- }
- }
-
-}
diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs
deleted file mode 100644
index a6be071b8..000000000
--- a/MediaBrowser.Api/Playback/BaseStreamingService.cs
+++ /dev/null
@@ -1,1056 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Diagnostics;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback
-{
- /// <summary>
- /// Class BaseStreamingService
- /// </summary>
- public abstract class BaseStreamingService : BaseApiService
- {
- /// <summary>
- /// Gets or sets the application paths.
- /// </summary>
- /// <value>The application paths.</value>
- protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
-
- /// <summary>
- /// Gets or sets the user manager.
- /// </summary>
- /// <value>The user manager.</value>
- protected IUserManager UserManager { get; private set; }
-
- /// <summary>
- /// Gets or sets the library manager.
- /// </summary>
- /// <value>The library manager.</value>
- protected ILibraryManager LibraryManager { get; private set; }
-
- /// <summary>
- /// Gets or sets the iso manager.
- /// </summary>
- /// <value>The iso manager.</value>
- protected IIsoManager IsoManager { get; private set; }
-
- /// <summary>
- /// Gets or sets the media encoder.
- /// </summary>
- /// <value>The media encoder.</value>
- protected IMediaEncoder MediaEncoder { get; private set; }
-
- protected IFileSystem FileSystem { get; private set; }
-
- protected IDlnaManager DlnaManager { get; private set; }
- protected IDeviceManager DeviceManager { get; private set; }
- protected ISubtitleEncoder SubtitleEncoder { get; private set; }
- protected IMediaSourceManager MediaSourceManager { get; private set; }
- protected IJsonSerializer JsonSerializer { get; private set; }
-
- protected IAuthorizationContext AuthorizationContext { get; private set; }
-
- protected EncodingHelper EncodingHelper { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
- /// </summary>
- protected BaseStreamingService(
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext)
- {
- ServerConfigurationManager = serverConfig;
- UserManager = userManager;
- LibraryManager = libraryManager;
- IsoManager = isoManager;
- MediaEncoder = mediaEncoder;
- FileSystem = fileSystem;
- DlnaManager = dlnaManager;
- SubtitleEncoder = subtitleEncoder;
- DeviceManager = deviceManager;
- MediaSourceManager = mediaSourceManager;
- JsonSerializer = jsonSerializer;
- AuthorizationContext = authorizationContext;
-
- EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder);
- }
-
- /// <summary>
- /// Gets the command line arguments.
- /// </summary>
- protected abstract string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding);
-
- /// <summary>
- /// Gets the type of the transcoding job.
- /// </summary>
- /// <value>The type of the transcoding job.</value>
- protected abstract TranscodingJobType TranscodingJobType { get; }
-
- /// <summary>
- /// Gets the output file extension.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>System.String.</returns>
- protected virtual string GetOutputFileExtension(StreamState state)
- {
- return Path.GetExtension(state.RequestedUrl);
- }
-
- /// <summary>
- /// Gets the output file path.
- /// </summary>
- private string GetOutputFilePath(StreamState state, EncodingOptions encodingOptions, string outputFileExtension)
- {
- var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
-
- var data = GetCommandLineArguments("dummy\\dummy", encodingOptions, state, false);
-
- data += "-" + (state.Request.DeviceId ?? string.Empty);
- data += "-" + (state.Request.PlaySessionId ?? string.Empty);
-
- var dataHash = data.GetMD5().ToString("N");
-
- if (EnableOutputInSubFolder)
- {
- return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLowerInvariant());
- }
-
- return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLowerInvariant());
- }
-
- protected virtual bool EnableOutputInSubFolder => false;
-
- protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- protected virtual string GetDefaultH264Preset()
- {
- return "superfast";
- }
-
- private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
- {
- if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
- {
- state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false);
- }
-
- if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
- {
- var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
- {
- OpenToken = state.MediaSource.OpenToken
-
- }, cancellationTokenSource.Token).ConfigureAwait(false);
-
- EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.RequestedUrl);
-
- if (state.VideoRequest != null)
- {
- EncodingHelper.TryStreamCopy(state);
- }
- }
-
- if (state.MediaSource.BufferMs.HasValue)
- {
- await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
- }
- }
-
- /// <summary>
- /// Starts the FFMPEG.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <param name="outputPath">The output path.</param>
- /// <param name="cancellationTokenSource">The cancellation token source.</param>
- /// <param name="workingDirectory">The working directory.</param>
- /// <returns>Task.</returns>
- protected async Task<TranscodingJob> StartFfMpeg(
- StreamState state,
- string outputPath,
- CancellationTokenSource cancellationTokenSource,
- string workingDirectory = null)
- {
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
-
- await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
-
- if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- var auth = AuthorizationContext.GetAuthorizationInfo(Request);
- if (auth.User != null)
- {
- if (!auth.User.Policy.EnableVideoPlaybackTranscoding)
- {
- ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
-
- throw new ArgumentException("User does not have access to video transcoding");
- }
- }
- }
-
- var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
-
- var transcodingId = Guid.NewGuid().ToString("N");
- var commandLineArgs = GetCommandLineArguments(outputPath, encodingOptions, state, true);
-
- var process = new Process()
- {
- StartInfo = new ProcessStartInfo()
- {
- WindowStyle = ProcessWindowStyle.Hidden,
- CreateNoWindow = true,
- UseShellExecute = false,
-
- // Must consume both stdout and stderr or deadlocks may occur
- //RedirectStandardOutput = true,
- RedirectStandardError = true,
- RedirectStandardInput = true,
-
- FileName = MediaEncoder.EncoderPath,
- Arguments = commandLineArgs,
- WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? null : workingDirectory,
-
- ErrorDialog = false
- },
- EnableRaisingEvents = true
- };
-
- var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
- state.Request.PlaySessionId,
- state.MediaSource.LiveStreamId,
- transcodingId,
- TranscodingJobType,
- process,
- state.Request.DeviceId,
- state,
- cancellationTokenSource);
-
- var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
- Logger.LogInformation(commandLineLogMessage);
-
- var logFilePrefix = "ffmpeg-transcode";
- if (state.VideoRequest != null)
- {
- if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
- && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- logFilePrefix = "ffmpeg-directstream";
- }
- else if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- logFilePrefix = "ffmpeg-remux";
- }
- }
-
- var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
- Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
-
- // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
- state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
-
- var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
- await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
-
- process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
-
- try
- {
- process.Start();
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error starting ffmpeg");
-
- ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
-
- throw;
- }
-
- // MUST read both stdout and stderr asynchronously or a deadlock may occurr
- //process.BeginOutputReadLine();
-
- state.TranscodingJob = transcodingJob;
-
- // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
- new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, state.LogFileStream);
-
- // Wait for the file to exist before proceeeding
- while (!File.Exists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
- {
- await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
- }
-
- if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
- {
- await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
-
- if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
- {
- await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
- }
- }
-
- if (!transcodingJob.HasExited)
- {
- StartThrottler(state, transcodingJob);
- }
-
- return transcodingJob;
- }
-
- private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
- {
- if (EnableThrottling(state))
- {
- transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager, FileSystem);
- state.TranscodingThrottler.Start();
- }
- }
-
- private bool EnableThrottling(StreamState state)
- {
- return false;
- //// do not use throttling with hardware encoders
- //return state.InputProtocol == MediaProtocol.File &&
- // state.RunTimeTicks.HasValue &&
- // state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
- // state.IsInputVideo &&
- // state.VideoType == VideoType.VideoFile &&
- // !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) &&
- // string.Equals(GetVideoEncoder(state), "libx264", StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Processes the exited.
- /// </summary>
- /// <param name="process">The process.</param>
- /// <param name="job">The job.</param>
- /// <param name="state">The state.</param>
- private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
- {
- if (job != null)
- {
- job.HasExited = true;
- }
-
- Logger.LogDebug("Disposing stream resources");
- state.Dispose();
-
- try
- {
- Logger.LogInformation("FFMpeg exited with code {0}", process.ExitCode);
- }
- catch
- {
- Logger.LogError("FFMpeg exited with an error.");
- }
-
- // This causes on exited to be called twice:
- //try
- //{
- // // Dispose the process
- // process.Dispose();
- //}
- //catch (Exception ex)
- //{
- // Logger.LogError(ex, "Error disposing ffmpeg.");
- //}
- }
-
- /// <summary>
- /// Parses the parameters.
- /// </summary>
- /// <param name="request">The request.</param>
- private void ParseParams(StreamRequest request)
- {
- var vals = request.Params.Split(';');
-
- var videoRequest = request as VideoStreamRequest;
-
- for (var i = 0; i < vals.Length; i++)
- {
- var val = vals[i];
-
- if (string.IsNullOrWhiteSpace(val))
- {
- continue;
- }
-
- if (i == 0)
- {
- request.DeviceProfileId = val;
- }
- else if (i == 1)
- {
- request.DeviceId = val;
- }
- else if (i == 2)
- {
- request.MediaSourceId = val;
- }
- else if (i == 3)
- {
- request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- else if (i == 4)
- {
- if (videoRequest != null)
- {
- videoRequest.VideoCodec = val;
- }
- }
- else if (i == 5)
- {
- request.AudioCodec = val;
- }
- else if (i == 6)
- {
- if (videoRequest != null)
- {
- videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
- }
- }
- else if (i == 7)
- {
- if (videoRequest != null)
- {
- videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
- }
- }
- else if (i == 8)
- {
- if (videoRequest != null)
- {
- videoRequest.VideoBitRate = int.Parse(val, UsCulture);
- }
- }
- else if (i == 9)
- {
- request.AudioBitRate = int.Parse(val, UsCulture);
- }
- else if (i == 10)
- {
- request.MaxAudioChannels = int.Parse(val, UsCulture);
- }
- else if (i == 11)
- {
- if (videoRequest != null)
- {
- videoRequest.MaxFramerate = float.Parse(val, UsCulture);
- }
- }
- else if (i == 12)
- {
- if (videoRequest != null)
- {
- videoRequest.MaxWidth = int.Parse(val, UsCulture);
- }
- }
- else if (i == 13)
- {
- if (videoRequest != null)
- {
- videoRequest.MaxHeight = int.Parse(val, UsCulture);
- }
- }
- else if (i == 14)
- {
- request.StartTimeTicks = long.Parse(val, UsCulture);
- }
- else if (i == 15)
- {
- if (videoRequest != null)
- {
- videoRequest.Level = val;
- }
- }
- else if (i == 16)
- {
- if (videoRequest != null)
- {
- videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
- }
- }
- else if (i == 17)
- {
- if (videoRequest != null)
- {
- videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
- }
- }
- else if (i == 18)
- {
- if (videoRequest != null)
- {
- videoRequest.Profile = val;
- }
- }
- else if (i == 19)
- {
- // cabac no longer used
- }
- else if (i == 20)
- {
- request.PlaySessionId = val;
- }
- else if (i == 21)
- {
- // api_key
- }
- else if (i == 22)
- {
- request.LiveStreamId = val;
- }
- else if (i == 23)
- {
- // Duplicating ItemId because of MediaMonkey
- }
- else if (i == 24)
- {
- if (videoRequest != null)
- {
- videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- }
- else if (i == 25)
- {
- if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
- {
- if (Enum.TryParse(val, out SubtitleDeliveryMethod method))
- {
- videoRequest.SubtitleMethod = method;
- }
- }
- }
- else if (i == 26)
- {
- request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
- }
- else if (i == 27)
- {
- if (videoRequest != null)
- {
- videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- }
- else if (i == 28)
- {
- request.Tag = val;
- }
- else if (i == 29)
- {
- if (videoRequest != null)
- {
- videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- }
- else if (i == 30)
- {
- request.SubtitleCodec = val;
- }
- else if (i == 31)
- {
- if (videoRequest != null)
- {
- videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- }
- else if (i == 32)
- {
- if (videoRequest != null)
- {
- videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- }
- else if (i == 33)
- {
- request.TranscodeReasons = val;
- }
- }
- }
-
- /// <summary>
- /// Parses query parameters as StreamOptions
- /// <summary>
- /// <param name="request">The stream request.</param>
- private void ParseStreamOptions(StreamRequest request)
- {
- foreach (var param in Request.QueryString)
- {
- if (char.IsLower(param.Name[0]))
- {
- // This was probably not parsed initially and should be a StreamOptions
- // TODO: This should be incorporated either in the lower framework for parsing requests
- // or the generated URL should correctly serialize it
- request.StreamOptions[param.Name] = param.Value;
- }
- }
- }
-
- /// <summary>
- /// Parses the dlna headers.
- /// </summary>
- /// <param name="request">The request.</param>
- private void ParseDlnaHeaders(StreamRequest request)
- {
- if (!request.StartTimeTicks.HasValue)
- {
- var timeSeek = GetHeader("TimeSeekRange.dlna.org");
-
- request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
- }
- }
-
- /// <summary>
- /// Parses the time seek header.
- /// </summary>
- private long? ParseTimeSeekHeader(string value)
- {
- if (string.IsNullOrWhiteSpace(value))
- {
- return null;
- }
-
- if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
- {
- throw new ArgumentException("Invalid timeseek header");
- }
- value = value.Substring(4).Split(new[] { '-' }, 2)[0];
-
- if (value.IndexOf(':') == -1)
- {
- // Parses npt times in the format of '417.33'
- if (double.TryParse(value, NumberStyles.Any, UsCulture, out var seconds))
- {
- return TimeSpan.FromSeconds(seconds).Ticks;
- }
-
- throw new ArgumentException("Invalid timeseek header");
- }
-
- // Parses npt times in the format of '10:19:25.7'
- var tokens = value.Split(new[] { ':' }, 3);
- double secondsSum = 0;
- var timeFactor = 3600;
-
- foreach (var time in tokens)
- {
- if (double.TryParse(time, NumberStyles.Any, UsCulture, out var digit))
- {
- secondsSum += digit * timeFactor;
- }
- else
- {
- throw new ArgumentException("Invalid timeseek header");
- }
- timeFactor /= 60;
- }
- return TimeSpan.FromSeconds(secondsSum).Ticks;
- }
-
- /// <summary>
- /// Gets the state.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>StreamState.</returns>
- protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
- {
- ParseDlnaHeaders(request);
-
- if (!string.IsNullOrWhiteSpace(request.Params))
- {
- ParseParams(request);
- }
-
- ParseStreamOptions(request);
-
- var url = Request.PathInfo;
-
- if (string.IsNullOrEmpty(request.AudioCodec))
- {
- request.AudioCodec = EncodingHelper.InferAudioCodec(url);
- }
-
- var enableDlnaHeaders = !string.IsNullOrWhiteSpace(request.Params) /*||
- string.Equals(Request.Headers.Get("GetContentFeatures.DLNA.ORG"), "1", StringComparison.OrdinalIgnoreCase)*/;
-
- var state = new StreamState(MediaSourceManager, Logger, TranscodingJobType)
- {
- Request = request,
- RequestedUrl = url,
- UserAgent = Request.UserAgent,
- EnableDlnaHeaders = enableDlnaHeaders
- };
-
- var auth = AuthorizationContext.GetAuthorizationInfo(Request);
- if (!auth.UserId.Equals(Guid.Empty))
- {
- state.User = UserManager.GetUserById(auth.UserId);
- }
-
- //if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
- // (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
- // (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
- //{
- // state.SegmentLength = 6;
- //}
-
- if (state.VideoRequest != null)
- {
- if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
- {
- state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
- state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
- }
- }
-
- if (!string.IsNullOrWhiteSpace(request.AudioCodec))
- {
- state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
- state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
- ?? state.SupportedAudioCodecs.FirstOrDefault();
- }
-
- if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
- {
- state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
- state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToSubtitleCodec(i))
- ?? state.SupportedSubtitleCodecs.FirstOrDefault();
- }
-
- var item = LibraryManager.GetItemById(request.Id);
-
- state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
-
- //var primaryImage = item.GetImageInfo(ImageType.Primary, 0) ??
- // item.Parents.Select(i => i.GetImageInfo(ImageType.Primary, 0)).FirstOrDefault(i => i != null);
- //if (primaryImage != null)
- //{
- // state.AlbumCoverPath = primaryImage.Path;
- //}
-
- MediaSourceInfo mediaSource = null;
- if (string.IsNullOrWhiteSpace(request.LiveStreamId))
- {
- var currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
- ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
- : null;
-
- if (currentJob != null)
- {
- mediaSource = currentJob.MediaSource;
- }
-
- if (mediaSource == null)
- {
- var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(LibraryManager.GetItemById(request.Id), null, false, false, cancellationToken).ConfigureAwait(false)).ToList();
-
- mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
- ? mediaSources.First()
- : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
-
- if (mediaSource == null && request.MediaSourceId.Equals(request.Id))
- {
- mediaSource = mediaSources.First();
- }
- }
- }
- else
- {
- var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
- mediaSource = liveStreamInfo.Item1;
- state.DirectStreamProvider = liveStreamInfo.Item2;
- }
-
- var videoRequest = request as VideoStreamRequest;
-
- EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);
-
- var container = Path.GetExtension(state.RequestedUrl);
-
- if (string.IsNullOrEmpty(container))
- {
- container = request.Container;
- }
-
- if (string.IsNullOrEmpty(container))
- {
- container = request.Static ?
- StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, state.MediaPath, null, DlnaProfileType.Audio) :
- GetOutputFileExtension(state);
- }
-
- state.OutputContainer = (container ?? string.Empty).TrimStart('.');
-
- state.OutputAudioBitrate = EncodingHelper.GetAudioBitrateParam(state.Request, state.AudioStream);
-
- state.OutputAudioCodec = state.Request.AudioCodec;
-
- state.OutputAudioChannels = EncodingHelper.GetNumAudioChannelsParam(state, state.AudioStream, state.OutputAudioCodec);
-
- if (videoRequest != null)
- {
- state.OutputVideoCodec = state.VideoRequest.VideoCodec;
- state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
-
- if (videoRequest != null)
- {
- EncodingHelper.TryStreamCopy(state);
- }
-
- if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- var resolution = ResolutionNormalizer.Normalize(
- state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
- state.VideoStream == null ? (int?)null : state.VideoStream.Width,
- state.VideoStream == null ? (int?)null : state.VideoStream.Height,
- state.OutputVideoBitrate.Value,
- state.VideoStream == null ? null : state.VideoStream.Codec,
- state.OutputVideoCodec,
- videoRequest.MaxWidth,
- videoRequest.MaxHeight);
-
- videoRequest.MaxWidth = resolution.MaxWidth;
- videoRequest.MaxHeight = resolution.MaxHeight;
- }
-
- ApplyDeviceProfileSettings(state);
- }
- else
- {
- ApplyDeviceProfileSettings(state);
- }
-
- var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
- ? GetOutputFileExtension(state)
- : ("." + state.OutputContainer);
-
- var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
-
- state.OutputFilePath = GetOutputFilePath(state, encodingOptions, ext);
-
- return state;
- }
-
- private void ApplyDeviceProfileSettings(StreamState state)
- {
- var headers = Request.Headers.ToDictionary();
-
- if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
- {
- state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
- }
- else
- {
- if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
- {
- var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
-
- if (caps != null)
- {
- state.DeviceProfile = caps.DeviceProfile;
- }
- else
- {
- state.DeviceProfile = DlnaManager.GetProfile(headers);
- }
- }
- }
-
- var profile = state.DeviceProfile;
-
- if (profile == null)
- {
- // Don't use settings from the default profile.
- // Only use a specific profile if it was requested.
- return;
- }
-
- var audioCodec = state.ActualOutputAudioCodec;
- var videoCodec = state.ActualOutputVideoCodec;
-
- var mediaProfile = state.VideoRequest == null ?
- profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate, state.OutputAudioSampleRate, state.OutputAudioBitDepth) :
- profile.GetVideoMediaProfile(state.OutputContainer,
- audioCodec,
- videoCodec,
- state.OutputWidth,
- state.OutputHeight,
- state.TargetVideoBitDepth,
- state.OutputVideoBitrate,
- state.TargetVideoProfile,
- state.TargetVideoLevel,
- state.TargetFramerate,
- state.TargetPacketLength,
- state.TargetTimestamp,
- state.IsTargetAnamorphic,
- state.IsTargetInterlaced,
- state.TargetRefFrames,
- state.TargetVideoStreamCount,
- state.TargetAudioStreamCount,
- state.TargetVideoCodecTag,
- state.IsTargetAVC);
-
- if (mediaProfile != null)
- {
- state.MimeType = mediaProfile.MimeType;
- }
-
- if (!state.Request.Static)
- {
- var transcodingProfile = state.VideoRequest == null ?
- profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
- profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
-
- if (transcodingProfile != null)
- {
- state.EstimateContentLength = transcodingProfile.EstimateContentLength;
- //state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
- state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
-
- if (state.VideoRequest != null)
- {
- state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
- state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
- }
- }
- }
- }
-
- /// <summary>
- /// Adds the dlna headers.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
- protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
- {
- if (!state.EnableDlnaHeaders)
- {
- return;
- }
-
- var profile = state.DeviceProfile;
-
- var transferMode = GetHeader("transferMode.dlna.org");
- responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
- responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
-
- if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
- {
- if (state.RunTimeTicks.HasValue)
- {
- var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
- responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
- }
- }
-
- if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
- {
- AddTimeSeekResponseHeaders(state, responseHeaders);
- }
-
- if (profile == null)
- {
- profile = DlnaManager.GetDefaultProfile();
- }
-
- var audioCodec = state.ActualOutputAudioCodec;
-
- if (state.VideoRequest == null)
- {
- responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
- .BuildAudioHeader(
- state.OutputContainer,
- audioCodec,
- state.OutputAudioBitrate,
- state.OutputAudioSampleRate,
- state.OutputAudioChannels,
- state.OutputAudioBitDepth,
- isStaticallyStreamed,
- state.RunTimeTicks,
- state.TranscodeSeekInfo
- );
- }
- else
- {
- var videoCodec = state.ActualOutputVideoCodec;
-
- responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
- .BuildVideoHeader(
- state.OutputContainer,
- videoCodec,
- audioCodec,
- state.OutputWidth,
- state.OutputHeight,
- state.TargetVideoBitDepth,
- state.OutputVideoBitrate,
- state.TargetTimestamp,
- isStaticallyStreamed,
- state.RunTimeTicks,
- state.TargetVideoProfile,
- state.TargetVideoLevel,
- state.TargetFramerate,
- state.TargetPacketLength,
- state.TranscodeSeekInfo,
- state.IsTargetAnamorphic,
- state.IsTargetInterlaced,
- state.TargetRefFrames,
- state.TargetVideoStreamCount,
- state.TargetAudioStreamCount,
- state.TargetVideoCodecTag,
- state.IsTargetAVC
-
- ).FirstOrDefault() ?? string.Empty;
- }
-
- foreach (var item in responseHeaders)
- {
- Request.Response.AddHeader(item.Key, item.Value);
- }
- }
-
- private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
- {
- var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
- var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
-
- responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
- responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
deleted file mode 100644
index 1acc42ea5..000000000
--- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
+++ /dev/null
@@ -1,344 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback.Hls
-{
- /// <summary>
- /// Class BaseHlsService
- /// </summary>
- public abstract class BaseHlsService : BaseStreamingService
- {
- /// <summary>
- /// Gets the audio arguments.
- /// </summary>
- protected abstract string GetAudioArguments(StreamState state, EncodingOptions encodingOptions);
-
- /// <summary>
- /// Gets the video arguments.
- /// </summary>
- protected abstract string GetVideoArguments(StreamState state, EncodingOptions encodingOptions);
-
- /// <summary>
- /// Gets the segment file extension.
- /// </summary>
- protected string GetSegmentFileExtension(StreamRequest request)
- {
- var segmentContainer = request.SegmentContainer;
- if (!string.IsNullOrWhiteSpace(segmentContainer))
- {
- return "." + segmentContainer;
- }
-
- return ".ts";
- }
-
- /// <summary>
- /// Gets the type of the transcoding job.
- /// </summary>
- /// <value>The type of the transcoding job.</value>
- protected override TranscodingJobType TranscodingJobType => TranscodingJobType.Hls;
-
- /// <summary>
- /// Processes the request async.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="isLive">if set to <c>true</c> [is live].</param>
- /// <returns>Task{System.Object}.</returns>
- /// <exception cref="ArgumentException">A video bitrate is required
- /// or
- /// An audio bitrate is required</exception>
- protected async Task<object> ProcessRequestAsync(StreamRequest request, bool isLive)
- {
- var cancellationTokenSource = new CancellationTokenSource();
-
- var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
-
- TranscodingJob job = null;
- var playlist = state.OutputFilePath;
-
- if (!File.Exists(playlist))
- {
- var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlist);
- await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
- try
- {
- if (!File.Exists(playlist))
- {
- // If the playlist doesn't already exist, startup ffmpeg
- try
- {
- job = await StartFfMpeg(state, playlist, cancellationTokenSource).ConfigureAwait(false);
- job.IsLiveOutput = isLive;
- }
- catch
- {
- state.Dispose();
- throw;
- }
-
- var minSegments = state.MinSegments;
- if (minSegments > 0)
- {
- await WaitForMinimumSegmentCount(playlist, minSegments, cancellationTokenSource.Token).ConfigureAwait(false);
- }
- }
- }
- finally
- {
- transcodingLock.Release();
- }
- }
-
- if (isLive)
- {
- job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType);
-
- if (job != null)
- {
- ApiEntryPoint.Instance.OnTranscodeEndRequest(job);
- }
- return ResultFactory.GetResult(GetLivePlaylistText(playlist, state.SegmentLength), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
- }
-
- var audioBitrate = state.OutputAudioBitrate ?? 0;
- var videoBitrate = state.OutputVideoBitrate ?? 0;
-
- var baselineStreamBitrate = 64000;
-
- var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, baselineStreamBitrate);
-
- job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType);
-
- if (job != null)
- {
- ApiEntryPoint.Instance.OnTranscodeEndRequest(job);
- }
-
- return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
- }
-
- private string GetLivePlaylistText(string path, int segmentLength)
- {
- using (var stream = FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite))
- {
- using (var reader = new StreamReader(stream))
- {
- var text = reader.ReadToEnd();
-
- text = text.Replace("#EXTM3U", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT");
-
- var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(UsCulture);
-
- text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength - 1).ToString(UsCulture), newDuration, StringComparison.OrdinalIgnoreCase);
- //text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(UsCulture), newDuration, StringComparison.OrdinalIgnoreCase);
-
- return text;
- }
- }
- }
-
- private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, int baselineStreamBitrate)
- {
- var builder = new StringBuilder();
-
- builder.AppendLine("#EXTM3U");
-
- // Pad a little to satisfy the apple hls validator
- var paddedBitrate = Convert.ToInt32(bitrate * 1.15);
-
- // Main stream
- builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
- var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
- builder.AppendLine(playlistUrl);
-
- return builder.ToString();
- }
-
- protected virtual async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
- {
- Logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist);
-
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- // Need to use FileShareMode.ReadWrite because we're reading the file at the same time it's being written
- using (var fileStream = GetPlaylistFileStream(playlist))
- {
- using (var reader = new StreamReader(fileStream))
- {
- var count = 0;
-
- while (!reader.EndOfStream)
- {
- var line = reader.ReadLine();
-
- if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
- {
- count++;
- if (count >= segmentCount)
- {
- Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
- return;
- }
- }
- }
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
- }
- }
- }
- catch (IOException)
- {
- // May get an error if the file is locked
- }
-
- await Task.Delay(50, cancellationToken).ConfigureAwait(false);
- }
- }
-
- protected Stream GetPlaylistFileStream(string path)
- {
- var tmpPath = path + ".tmp";
- tmpPath = path;
-
- try
- {
- return FileSystem.GetFileStream(tmpPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, FileOpenOptions.SequentialScan);
- }
- catch (IOException)
- {
- return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, FileOpenOptions.SequentialScan);
- }
- }
-
- protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
- {
- var itsOffsetMs = 0;
-
- var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds.ToString(UsCulture));
-
- var videoCodec = EncodingHelper.GetVideoEncoder(state, encodingOptions);
-
- var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec);
-
- var inputModifier = EncodingHelper.GetInputModifier(state, encodingOptions);
-
- // If isEncoding is true we're actually starting ffmpeg
- var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
-
- var baseUrlParam = string.Empty;
-
- if (state.Request is GetLiveHlsStream)
- {
- baseUrlParam = string.Format(" -hls_base_url \"{0}/\"",
- "hls/" + Path.GetFileNameWithoutExtension(outputPath));
- }
-
- var useGenericSegmenter = true;
- if (useGenericSegmenter)
- {
- var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request);
-
- var timeDeltaParam = string.Empty;
-
- var segmentFormat = GetSegmentFileExtension(state.Request).TrimStart('.');
- if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
- {
- segmentFormat = "mpegts";
- }
-
- baseUrlParam = string.Format("\"{0}/\"", "hls/" + Path.GetFileNameWithoutExtension(outputPath));
-
- return string.Format("{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {10} -individual_header_trailer 0 -segment_format {11} -segment_list_entry_prefix {12} -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
- inputModifier,
- EncodingHelper.GetInputArgument(state, encodingOptions),
- threads,
- EncodingHelper.GetMapArgs(state),
- GetVideoArguments(state, encodingOptions),
- GetAudioArguments(state, encodingOptions),
- state.SegmentLength.ToString(UsCulture),
- startNumberParam,
- outputPath,
- outputTsArg,
- timeDeltaParam,
- segmentFormat,
- baseUrlParam
- ).Trim();
- }
-
- // add when stream copying?
- // -avoid_negative_ts make_zero -fflags +genpts
-
- var args = string.Format("{0} {1} {2} -map_metadata -1 -map_chapters -1 -threads {3} {4} {5} -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero {6} -hls_time {7} -individual_header_trailer 0 -start_number {8} -hls_list_size {9}{10} -y \"{11}\"",
- itsOffset,
- inputModifier,
- EncodingHelper.GetInputArgument(state, encodingOptions),
- threads,
- EncodingHelper.GetMapArgs(state),
- GetVideoArguments(state, encodingOptions),
- GetAudioArguments(state, encodingOptions),
- state.SegmentLength.ToString(UsCulture),
- startNumberParam,
- state.HlsListSize.ToString(UsCulture),
- baseUrlParam,
- outputPath
- ).Trim();
-
- return args;
- }
-
- protected override string GetDefaultH264Preset()
- {
- return "veryfast";
- }
-
- protected virtual int GetStartNumber(StreamState state)
- {
- return 0;
- }
-
- public BaseHlsService(
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext)
- : base(serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
deleted file mode 100644
index 45f003cae..000000000
--- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
+++ /dev/null
@@ -1,997 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
-
-namespace MediaBrowser.Api.Playback.Hls
-{
- /// <summary>
- /// Options is needed for chromecast. Threw Head in there since it's related
- /// </summary>
- [Route("/Videos/{Id}/master.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
- [Route("/Videos/{Id}/master.m3u8", "HEAD", Summary = "Gets a video stream using HTTP live streaming.")]
- public class GetMasterHlsVideoPlaylist : VideoStreamRequest, IMasterHlsRequest
- {
- public bool EnableAdaptiveBitrateStreaming { get; set; }
-
- public GetMasterHlsVideoPlaylist()
- {
- EnableAdaptiveBitrateStreaming = true;
- }
- }
-
- [Route("/Audio/{Id}/master.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
- [Route("/Audio/{Id}/master.m3u8", "HEAD", Summary = "Gets an audio stream using HTTP live streaming.")]
- public class GetMasterHlsAudioPlaylist : StreamRequest, IMasterHlsRequest
- {
- public bool EnableAdaptiveBitrateStreaming { get; set; }
-
- public GetMasterHlsAudioPlaylist()
- {
- EnableAdaptiveBitrateStreaming = true;
- }
- }
-
- public interface IMasterHlsRequest
- {
- bool EnableAdaptiveBitrateStreaming { get; set; }
- }
-
- [Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
- public class GetVariantHlsVideoPlaylist : VideoStreamRequest
- {
- }
-
- [Route("/Audio/{Id}/main.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
- public class GetVariantHlsAudioPlaylist : StreamRequest
- {
- }
-
- [Route("/Videos/{Id}/hls1/{PlaylistId}/{SegmentId}.{SegmentContainer}", "GET")]
- public class GetHlsVideoSegment : VideoStreamRequest
- {
- public string PlaylistId { get; set; }
-
- /// <summary>
- /// Gets or sets the segment id.
- /// </summary>
- /// <value>The segment id.</value>
- public string SegmentId { get; set; }
- }
-
- [Route("/Audio/{Id}/hls1/{PlaylistId}/{SegmentId}.{SegmentContainer}", "GET")]
- public class GetHlsAudioSegment : StreamRequest
- {
- public string PlaylistId { get; set; }
-
- /// <summary>
- /// Gets or sets the segment id.
- /// </summary>
- /// <value>The segment id.</value>
- public string SegmentId { get; set; }
- }
-
- [Authenticated]
- public class DynamicHlsService : BaseHlsService
- {
-
- public DynamicHlsService(
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext,
- INetworkManager networkManager)
- : base(serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext)
- {
- NetworkManager = networkManager;
- }
-
- protected INetworkManager NetworkManager { get; private set; }
-
- public Task<object> Get(GetMasterHlsVideoPlaylist request)
- {
- return GetMasterPlaylistInternal(request, "GET");
- }
-
- public Task<object> Head(GetMasterHlsVideoPlaylist request)
- {
- return GetMasterPlaylistInternal(request, "HEAD");
- }
-
- public Task<object> Get(GetMasterHlsAudioPlaylist request)
- {
- return GetMasterPlaylistInternal(request, "GET");
- }
-
- public Task<object> Head(GetMasterHlsAudioPlaylist request)
- {
- return GetMasterPlaylistInternal(request, "HEAD");
- }
-
- public Task<object> Get(GetVariantHlsVideoPlaylist request)
- {
- return GetVariantPlaylistInternal(request, true, "main");
- }
-
- public Task<object> Get(GetVariantHlsAudioPlaylist request)
- {
- return GetVariantPlaylistInternal(request, false, "main");
- }
-
- public Task<object> Get(GetHlsVideoSegment request)
- {
- return GetDynamicSegment(request, request.SegmentId);
- }
-
- public Task<object> Get(GetHlsAudioSegment request)
- {
- return GetDynamicSegment(request, request.SegmentId);
- }
-
- private async Task<object> GetDynamicSegment(StreamRequest request, string segmentId)
- {
- if ((request.StartTimeTicks ?? 0) > 0)
- {
- throw new ArgumentException("StartTimeTicks is not allowed.");
- }
-
- var cancellationTokenSource = new CancellationTokenSource();
- var cancellationToken = cancellationTokenSource.Token;
-
- var requestedIndex = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
-
- var state = await GetState(request, cancellationToken).ConfigureAwait(false);
-
- var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
-
- var segmentPath = GetSegmentPath(state, playlistPath, requestedIndex);
-
- var segmentExtension = GetSegmentFileExtension(state.Request);
-
- TranscodingJob job = null;
-
- if (File.Exists(segmentPath))
- {
- job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false);
- }
-
- var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlistPath);
- await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
- var released = false;
- var startTranscoding = false;
-
- try
- {
- if (File.Exists(segmentPath))
- {
- job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- transcodingLock.Release();
- released = true;
- return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
- var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
-
- if (currentTranscodingIndex == null)
- {
- Logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
- startTranscoding = true;
- }
- else if (requestedIndex < currentTranscodingIndex.Value)
- {
- Logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
- startTranscoding = true;
- }
- else if (requestedIndex - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
- {
- Logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex);
- startTranscoding = true;
- }
- if (startTranscoding)
- {
- // If the playlist doesn't already exist, startup ffmpeg
- try
- {
- await ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false);
-
- if (currentTranscodingIndex.HasValue)
- {
- DeleteLastFile(playlistPath, segmentExtension, 0);
- }
-
- request.StartTimeTicks = GetStartPositionTicks(state, requestedIndex);
-
- job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
- }
- catch
- {
- state.Dispose();
- throw;
- }
-
- //await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
- }
- else
- {
- job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- if (job.TranscodingThrottler != null)
- {
- await job.TranscodingThrottler.UnpauseTranscoding();
- }
- }
- }
- }
- finally
- {
- if (!released)
- {
- transcodingLock.Release();
- }
- }
-
- //Logger.LogInformation("waiting for {0}", segmentPath);
- //while (!File.Exists(segmentPath))
- //{
- // await Task.Delay(50, cancellationToken).ConfigureAwait(false);
- //}
-
- Logger.LogInformation("returning {0}", segmentPath);
- job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false);
- }
-
- private const int BufferSize = 81920;
-
- private long GetStartPositionTicks(StreamState state, int requestedIndex)
- {
- double startSeconds = 0;
- var lengths = GetSegmentLengths(state);
-
- if (requestedIndex >= lengths.Length)
- {
- var msg = string.Format("Invalid segment index requested: {0} - Segment count: {1}", requestedIndex, lengths.Length);
- throw new ArgumentException(msg);
- }
-
- for (var i = 0; i < requestedIndex; i++)
- {
- startSeconds += lengths[i];
- }
-
- var position = TimeSpan.FromSeconds(startSeconds).Ticks;
- return position;
- }
-
- private long GetEndPositionTicks(StreamState state, int requestedIndex)
- {
- double startSeconds = 0;
- var lengths = GetSegmentLengths(state);
-
- if (requestedIndex >= lengths.Length)
- {
- var msg = string.Format("Invalid segment index requested: {0} - Segment count: {1}", requestedIndex, lengths.Length);
- throw new ArgumentException(msg);
- }
-
- for (var i = 0; i <= requestedIndex; i++)
- {
- startSeconds += lengths[i];
- }
-
- var position = TimeSpan.FromSeconds(startSeconds).Ticks;
- return position;
- }
-
- private double[] GetSegmentLengths(StreamState state)
- {
- var result = new List<double>();
-
- var ticks = state.RunTimeTicks ?? 0;
-
- var segmentLengthTicks = TimeSpan.FromSeconds(state.SegmentLength).Ticks;
-
- while (ticks > 0)
- {
- var length = ticks >= segmentLengthTicks ? segmentLengthTicks : ticks;
-
- result.Add(TimeSpan.FromTicks(length).TotalSeconds);
-
- ticks -= length;
- }
-
- return result.ToArray();
- }
-
- public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
- {
- var job = ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType);
-
- if (job == null || job.HasExited)
- {
- return null;
- }
-
- var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
-
- if (file == null)
- {
- return null;
- }
-
- var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
-
- var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
-
- return int.Parse(indexString, NumberStyles.Integer, UsCulture);
- }
-
- private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
- {
- var file = GetLastTranscodingFile(playlistPath, segmentExtension, FileSystem);
-
- if (file != null)
- {
- DeleteFile(file.FullName, retryCount);
- }
- }
-
- private void DeleteFile(string path, int retryCount)
- {
- if (retryCount >= 5)
- {
- return;
- }
-
- Logger.LogDebug("Deleting partial HLS file {path}", path);
-
- try
- {
- FileSystem.DeleteFile(path);
- }
- catch (IOException ex)
- {
- Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
-
- var task = Task.Delay(100);
- Task.WaitAll(task);
- DeleteFile(path, retryCount + 1);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
- }
- }
-
- private static FileSystemMetadata GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
- {
- var folder = Path.GetDirectoryName(playlist);
-
- var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
-
- try
- {
- return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
- .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
- .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
- .FirstOrDefault();
- }
- catch (IOException)
- {
- return null;
- }
- }
-
- protected override int GetStartNumber(StreamState state)
- {
- return GetStartNumber(state.VideoRequest);
- }
-
- private int GetStartNumber(VideoStreamRequest request)
- {
- var segmentId = "0";
-
- var segmentRequest = request as GetHlsVideoSegment;
- if (segmentRequest != null)
- {
- segmentId = segmentRequest.SegmentId;
- }
-
- return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
- }
-
- private string GetSegmentPath(StreamState state, string playlist, int index)
- {
- var folder = Path.GetDirectoryName(playlist);
-
- var filename = Path.GetFileNameWithoutExtension(playlist);
-
- return Path.Combine(folder, filename + index.ToString(UsCulture) + GetSegmentFileExtension(state.Request));
- }
-
- private async Task<object> GetSegmentResult(StreamState state,
- string playlistPath,
- string segmentPath,
- string segmentExtension,
- int segmentIndex,
- TranscodingJob transcodingJob,
- CancellationToken cancellationToken)
- {
- var segmentFileExists = File.Exists(segmentPath);
-
- // If all transcoding has completed, just return immediately
- if (transcodingJob != null && transcodingJob.HasExited && segmentFileExists)
- {
- return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false);
- }
-
- if (segmentFileExists)
- {
- var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
-
- // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's ready
- if (segmentIndex < currentTranscodingIndex)
- {
- return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false);
- }
- }
-
- var segmentFilename = Path.GetFileName(segmentPath);
-
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- var text = File.ReadAllText(playlistPath, Encoding.UTF8);
-
- // If it appears in the playlist, it's done
- if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
- {
- if (!segmentFileExists)
- {
- segmentFileExists = File.Exists(segmentPath);
- }
- if (segmentFileExists)
- {
- return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false);
- }
- //break;
- }
- }
- catch (IOException)
- {
- // May get an error if the file is locked
- }
-
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
- return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false);
- }
-
- private Task<object> GetSegmentResult(StreamState state, string segmentPath, int index, TranscodingJob transcodingJob)
- {
- var segmentEndingPositionTicks = GetEndPositionTicks(state, index);
-
- return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- {
- Path = segmentPath,
- FileShare = FileShareMode.ReadWrite,
- OnComplete = () =>
- {
- if (transcodingJob != null)
- {
- transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
- ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
- }
- }
- });
- }
-
- private async Task<object> GetMasterPlaylistInternal(StreamRequest request, string method)
- {
- var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
-
- if (string.IsNullOrEmpty(request.MediaSourceId))
- {
- throw new ArgumentException("MediaSourceId is required");
- }
-
- var playlistText = string.Empty;
-
- if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
- {
- var audioBitrate = state.OutputAudioBitrate ?? 0;
- var videoBitrate = state.OutputVideoBitrate ?? 0;
-
- playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
- }
-
- return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
- }
-
- private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
- {
- var builder = new StringBuilder();
-
- builder.AppendLine("#EXTM3U");
-
- var isLiveStream = state.IsSegmentedLiveStream;
-
- var queryStringIndex = Request.RawUrl.IndexOf('?');
- var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
-
- // from universal audio service
- if (queryString.IndexOf("SegmentContainer", StringComparison.OrdinalIgnoreCase) == -1 && !string.IsNullOrWhiteSpace(state.Request.SegmentContainer))
- {
- queryString += "&SegmentContainer=" + state.Request.SegmentContainer;
- }
- // from universal audio service
- if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons) && queryString.IndexOf("TranscodeReasons=", StringComparison.OrdinalIgnoreCase) == -1)
- {
- queryString += "&TranscodeReasons=" + state.Request.TranscodeReasons;
- }
-
- // Main stream
- var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
-
- playlistUrl += queryString;
-
- var request = state.Request;
-
- var subtitleStreams = state.MediaSource
- .MediaStreams
- .Where(i => i.IsTextSubtitleStream)
- .ToList();
-
- var subtitleGroup = subtitleStreams.Count > 0 &&
- request is GetMasterHlsVideoPlaylist &&
- (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Hls || state.VideoRequest.EnableSubtitlesInManifest) ?
- "subs" :
- null;
-
- // If we're burning in subtitles then don't add additional subs to the manifest
- if (state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
- {
- subtitleGroup = null;
- }
-
- if (!string.IsNullOrWhiteSpace(subtitleGroup))
- {
- AddSubtitles(state, subtitleStreams, builder);
- }
-
- AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup);
-
- if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
- {
- var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
-
- // By default, vary by just 200k
- var variation = GetBitrateVariation(totalBitrate);
-
- var newBitrate = totalBitrate - variation;
- var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
- AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
-
- variation *= 2;
- newBitrate = totalBitrate - variation;
- variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
- AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
- }
-
- return builder.ToString();
- }
-
- private string ReplaceBitrate(string url, int oldValue, int newValue)
- {
- return url.Replace(
- "videobitrate=" + oldValue.ToString(UsCulture),
- "videobitrate=" + newValue.ToString(UsCulture),
- StringComparison.OrdinalIgnoreCase);
- }
-
- private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
- {
- var selectedIndex = state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Hls ? (int?)null : state.SubtitleStream.Index;
-
- foreach (var stream in subtitles)
- {
- const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},AUTOSELECT=YES,URI=\"{3}\",LANGUAGE=\"{4}\"";
-
- var name = stream.DisplayTitle;
-
- var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
- var isForced = stream.IsForced;
-
- var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}&api_key={3}",
- state.Request.MediaSourceId,
- stream.Index.ToString(UsCulture),
- 30.ToString(UsCulture),
- AuthorizationContext.GetAuthorizationInfo(Request).Token);
-
- var line = string.Format(format,
- name,
- isDefault ? "YES" : "NO",
- isForced ? "YES" : "NO",
- url,
- stream.Language ?? "Unknown");
-
- builder.AppendLine(line);
- }
- }
-
- private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
- {
- // Within the local network this will likely do more harm than good.
- if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
- {
- return false;
- }
-
- var request = state.Request as IMasterHlsRequest;
- if (request != null && !request.EnableAdaptiveBitrateStreaming)
- {
- return false;
- }
-
- if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
- {
- // Opening live streams is so slow it's not even worth it
- return false;
- }
-
- if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
-
- if (!state.IsOutputVideo)
- {
- return false;
- }
-
- // Having problems in android
- return false;
- //return state.VideoRequest.VideoBitRate.HasValue;
- }
-
- private void AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string subtitleGroup)
- {
- var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture) + ",AVERAGE-BANDWIDTH=" + bitrate.ToString(UsCulture);
-
- // tvos wants resolution, codecs, framerate
- //if (state.TargetFramerate.HasValue)
- //{
- // header += string.Format(",FRAME-RATE=\"{0}\"", state.TargetFramerate.Value.ToString(CultureInfo.InvariantCulture));
- //}
-
- if (!string.IsNullOrWhiteSpace(subtitleGroup))
- {
- header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
- }
-
- builder.AppendLine(header);
- builder.AppendLine(url);
- }
-
- private int GetBitrateVariation(int bitrate)
- {
- // By default, vary by just 50k
- var variation = 50000;
-
- if (bitrate >= 10000000)
- {
- variation = 2000000;
- }
- else if (bitrate >= 5000000)
- {
- variation = 1500000;
- }
- else if (bitrate >= 3000000)
- {
- variation = 1000000;
- }
- else if (bitrate >= 2000000)
- {
- variation = 500000;
- }
- else if (bitrate >= 1000000)
- {
- variation = 300000;
- }
- else if (bitrate >= 600000)
- {
- variation = 200000;
- }
- else if (bitrate >= 400000)
- {
- variation = 100000;
- }
-
- return variation;
- }
-
- private async Task<object> GetVariantPlaylistInternal(StreamRequest request, bool isOutputVideo, string name)
- {
- var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
-
- var segmentLengths = GetSegmentLengths(state);
-
- var builder = new StringBuilder();
-
- builder.AppendLine("#EXTM3U");
- builder.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
- builder.AppendLine("#EXT-X-VERSION:3");
- builder.AppendLine("#EXT-X-TARGETDURATION:" + Math.Ceiling(segmentLengths.Length > 0 ? segmentLengths.Max() : state.SegmentLength).ToString(UsCulture));
- builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
-
- var queryStringIndex = Request.RawUrl.IndexOf('?');
- var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
-
- //if ((Request.UserAgent ?? string.Empty).IndexOf("roku", StringComparison.OrdinalIgnoreCase) != -1)
- //{
- // queryString = string.Empty;
- //}
-
- var index = 0;
-
- foreach (var length in segmentLengths)
- {
- builder.AppendLine("#EXTINF:" + length.ToString("0.0000", UsCulture) + ", nodesc");
-
- builder.AppendLine(string.Format("hls1/{0}/{1}{2}{3}",
-
- name,
- index.ToString(UsCulture),
- GetSegmentFileExtension(request),
- queryString));
-
- index++;
- }
-
- builder.AppendLine("#EXT-X-ENDLIST");
-
- var playlistText = builder.ToString();
-
- return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
- }
-
- protected override string GetAudioArguments(StreamState state, EncodingOptions encodingOptions)
- {
- var audioCodec = EncodingHelper.GetAudioEncoder(state);
-
- if (!state.IsOutputVideo)
- {
- if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- return "-acodec copy";
- }
-
- var audioTranscodeParams = new List<string>();
-
- audioTranscodeParams.Add("-acodec " + audioCodec);
-
- if (state.OutputAudioBitrate.HasValue)
- {
- audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(UsCulture));
- }
-
- if (state.OutputAudioChannels.HasValue)
- {
- audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(UsCulture));
- }
-
- if (state.OutputAudioSampleRate.HasValue)
- {
- audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture));
- }
-
- audioTranscodeParams.Add("-vn");
- return string.Join(" ", audioTranscodeParams.ToArray());
- }
-
- if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- var videoCodec = EncodingHelper.GetVideoEncoder(state, encodingOptions);
-
- if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.EnableBreakOnNonKeyFrames(videoCodec))
- {
- return "-codec:a:0 copy -copypriorss:a:0 0";
- }
-
- return "-codec:a:0 copy";
- }
-
- var args = "-codec:a:0 " + audioCodec;
-
- var channels = state.OutputAudioChannels;
-
- if (channels.HasValue)
- {
- args += " -ac " + channels.Value;
- }
-
- var bitrate = state.OutputAudioBitrate;
-
- if (bitrate.HasValue)
- {
- args += " -ab " + bitrate.Value.ToString(UsCulture);
- }
-
- if (state.OutputAudioSampleRate.HasValue)
- {
- args += " -ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture);
- }
-
- args += " " + EncodingHelper.GetAudioFilterParam(state, encodingOptions, true);
-
- return args;
- }
-
- protected override string GetVideoArguments(StreamState state, EncodingOptions encodingOptions)
- {
- if (!state.IsOutputVideo)
- {
- return string.Empty;
- }
-
- var codec = EncodingHelper.GetVideoEncoder(state, encodingOptions);
-
- var args = "-codec:v:0 " + codec;
-
- // if (state.EnableMpegtsM2TsMode)
- // {
- // args += " -mpegts_m2ts_mode 1";
- // }
-
- // See if we can save come cpu cycles by avoiding encoding
- if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- if (state.VideoStream != null && EncodingHelper.IsH264(state.VideoStream) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
- {
- args += " -bsf:v h264_mp4toannexb";
- }
-
- //args += " -flags -global_header";
- }
- else
- {
- var keyFrameArg = string.Format(" -force_key_frames \"expr:gte(t,n_forced*{0})\"",
- state.SegmentLength.ToString(UsCulture));
-
- var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
-
- args += " " + EncodingHelper.GetVideoQualityParam(state, codec, encodingOptions, GetDefaultH264Preset()) + keyFrameArg;
-
- //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";
-
- // Add resolution params, if specified
- if (!hasGraphicalSubs)
- {
- args += EncodingHelper.GetOutputSizeParam(state, encodingOptions, codec, true);
- }
-
- // This is for internal graphical subs
- if (hasGraphicalSubs)
- {
- args += EncodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec);
- }
-
- //args += " -flags -global_header";
- }
-
- if (args.IndexOf("-copyts", StringComparison.OrdinalIgnoreCase) == -1)
- {
- args += " -copyts";
- }
-
- if (!string.IsNullOrEmpty(state.OutputVideoSync))
- {
- args += " -vsync " + state.OutputVideoSync;
- }
-
- args += EncodingHelper.GetOutputFFlags(state);
-
- return args;
- }
-
- protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
- {
- var videoCodec = EncodingHelper.GetVideoEncoder(state, encodingOptions);
-
- var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec);
-
- var inputModifier = EncodingHelper.GetInputModifier(state, encodingOptions);
-
- // If isEncoding is true we're actually starting ffmpeg
- var startNumber = GetStartNumber(state);
- var startNumberParam = isEncoding ? startNumber.ToString(UsCulture) : "0";
-
- var mapArgs = state.IsOutputVideo ? EncodingHelper.GetMapArgs(state) : string.Empty;
-
- var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request);
-
- var timeDeltaParam = string.Empty;
-
- if (isEncoding && startNumber > 0)
- {
- var startTime = state.SegmentLength * startNumber;
- timeDeltaParam = string.Format("-segment_time_delta -{0}", startTime);
- }
-
- var segmentFormat = GetSegmentFileExtension(state.Request).TrimStart('.');
- if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
- {
- segmentFormat = "mpegts";
- }
-
- var breakOnNonKeyFrames = state.EnableBreakOnNonKeyFrames(videoCodec);
-
- var breakOnNonKeyFramesArg = breakOnNonKeyFrames ? " -break_non_keyframes 1" : "";
-
- return string.Format("{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {10} -individual_header_trailer 0{12} -segment_format {11} -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
- inputModifier,
- EncodingHelper.GetInputArgument(state, encodingOptions),
- threads,
- mapArgs,
- GetVideoArguments(state, encodingOptions),
- GetAudioArguments(state, encodingOptions),
- state.SegmentLength.ToString(UsCulture),
- startNumberParam,
- outputPath,
- outputTsArg,
- timeDeltaParam,
- segmentFormat,
- breakOnNonKeyFramesArg
- ).Trim();
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs
deleted file mode 100644
index 6a2c7ae03..000000000
--- a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Playback.Hls
-{
- /// <summary>
- /// Class GetHlsAudioSegment
- /// </summary>
- // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
- //[Authenticated]
- [Route("/Audio/{Id}/hls/{SegmentId}/stream.mp3", "GET")]
- [Route("/Audio/{Id}/hls/{SegmentId}/stream.aac", "GET")]
- public class GetHlsAudioSegmentLegacy
- {
- // TODO: Deprecate with new iOS app
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the segment id.
- /// </summary>
- /// <value>The segment id.</value>
- public string SegmentId { get; set; }
- }
-
- /// <summary>
- /// Class GetHlsVideoSegment
- /// </summary>
- [Route("/Videos/{Id}/hls/{PlaylistId}/stream.m3u8", "GET")]
- [Authenticated]
- public class GetHlsPlaylistLegacy
- {
- // TODO: Deprecate with new iOS app
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public string Id { get; set; }
-
- public string PlaylistId { get; set; }
- }
-
- [Route("/Videos/ActiveEncodings", "DELETE")]
- [Authenticated]
- public class StopEncodingProcess
- {
- [ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string DeviceId { get; set; }
-
- [ApiMember(Name = "PlaySessionId", Description = "The play session id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string PlaySessionId { get; set; }
- }
-
- /// <summary>
- /// Class GetHlsVideoSegment
- /// </summary>
- // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
- //[Authenticated]
- [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.{SegmentContainer}", "GET")]
- public class GetHlsVideoSegmentLegacy : VideoStreamRequest
- {
- public string PlaylistId { get; set; }
-
- /// <summary>
- /// Gets or sets the segment id.
- /// </summary>
- /// <value>The segment id.</value>
- public string SegmentId { get; set; }
- }
-
- public class HlsSegmentService : BaseApiService
- {
- private readonly IServerApplicationPaths _appPaths;
- private readonly IServerConfigurationManager _config;
- private readonly IFileSystem _fileSystem;
-
- public HlsSegmentService(IServerApplicationPaths appPaths, IServerConfigurationManager config, IFileSystem fileSystem)
- {
- _appPaths = appPaths;
- _config = config;
- _fileSystem = fileSystem;
- }
-
- public Task<object> Get(GetHlsPlaylistLegacy request)
- {
- var file = request.PlaylistId + Path.GetExtension(Request.PathInfo);
- file = Path.Combine(_appPaths.TranscodingTempPath, file);
-
- return GetFileResult(file, file);
- }
-
- public Task Delete(StopEncodingProcess request)
- {
- return ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, path => true);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetHlsVideoSegmentLegacy request)
- {
- var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
-
- var transcodeFolderPath = _config.ApplicationPaths.TranscodingTempPath;
- file = Path.Combine(transcodeFolderPath, file);
-
- var normalizedPlaylistId = request.PlaylistId;
-
- var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath)
- .FirstOrDefault(i => string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1);
-
- return GetFileResult(file, playlistPath);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetHlsAudioSegmentLegacy request)
- {
- // TODO: Deprecate with new iOS app
- var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
- file = Path.Combine(_appPaths.TranscodingTempPath, file);
-
- return ResultFactory.GetStaticFileResult(Request, file, FileShareMode.ReadWrite);
- }
-
- private Task<object> GetFileResult(string path, string playlistPath)
- {
- var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
-
- return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- {
- Path = path,
- FileShare = FileShareMode.ReadWrite,
- OnComplete = () =>
- {
- if (transcodingJob != null)
- {
- ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
- }
- }
- });
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs
deleted file mode 100644
index eb1bbfb74..000000000
--- a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-using System;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Playback.Hls
-{
- [Route("/Videos/{Id}/live.m3u8", "GET")]
- public class GetLiveHlsStream : VideoStreamRequest
- {
- }
-
- /// <summary>
- /// Class VideoHlsService
- /// </summary>
- [Authenticated]
- public class VideoHlsService : BaseHlsService
- {
- public Task<object> Get(GetLiveHlsStream request)
- {
- return ProcessRequestAsync(request, true);
- }
-
- /// <summary>
- /// Gets the audio arguments.
- /// </summary>
- protected override string GetAudioArguments(StreamState state, EncodingOptions encodingOptions)
- {
- var codec = EncodingHelper.GetAudioEncoder(state);
-
- if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- return "-codec:a:0 copy";
- }
-
- var args = "-codec:a:0 " + codec;
-
- var channels = state.OutputAudioChannels;
-
- if (channels.HasValue)
- {
- args += " -ac " + channels.Value;
- }
-
- var bitrate = state.OutputAudioBitrate;
-
- if (bitrate.HasValue)
- {
- args += " -ab " + bitrate.Value.ToString(UsCulture);
- }
-
- if (state.OutputAudioSampleRate.HasValue)
- {
- args += " -ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture);
- }
-
- args += " " + EncodingHelper.GetAudioFilterParam(state, encodingOptions, true);
-
- return args;
- }
-
- /// <summary>
- /// Gets the video arguments.
- /// </summary>
- protected override string GetVideoArguments(StreamState state, EncodingOptions encodingOptions)
- {
- if (!state.IsOutputVideo)
- {
- return string.Empty;
- }
-
- var codec = EncodingHelper.GetVideoEncoder(state, encodingOptions);
-
- var args = "-codec:v:0 " + codec;
-
- // if (state.EnableMpegtsM2TsMode)
- // {
- // args += " -mpegts_m2ts_mode 1";
- // }
-
- // See if we can save come cpu cycles by avoiding encoding
- if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
- {
- // if h264_mp4toannexb is ever added, do not use it for live tv
- if (state.VideoStream != null && EncodingHelper.IsH264(state.VideoStream) &&
- !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
- {
- args += " -bsf:v h264_mp4toannexb";
- }
- }
- else
- {
- var keyFrameArg = string.Format(" -force_key_frames \"expr:gte(t,n_forced*{0})\"",
- state.SegmentLength.ToString(UsCulture));
-
- var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
-
- args += " " + EncodingHelper.GetVideoQualityParam(state, codec, encodingOptions, GetDefaultH264Preset()) + keyFrameArg;
-
- // Add resolution params, if specified
- if (!hasGraphicalSubs)
- {
- args += EncodingHelper.GetOutputSizeParam(state, encodingOptions, codec);
- }
-
- // This is for internal graphical subs
- if (hasGraphicalSubs)
- {
- args += EncodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec);
- }
- }
-
- args += " -flags -global_header";
-
- if (!string.IsNullOrEmpty(state.OutputVideoSync))
- {
- args += " -vsync " + state.OutputVideoSync;
- }
-
- args += EncodingHelper.GetOutputFFlags(state);
-
- return args;
- }
-
- public VideoHlsService(
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext)
- : base(serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs
deleted file mode 100644
index ab3994a63..000000000
--- a/MediaBrowser.Api/Playback/MediaInfoService.cs
+++ /dev/null
@@ -1,632 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Session;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback
-{
- [Route("/Items/{Id}/PlaybackInfo", "GET", Summary = "Gets live playback media info for an item")]
- public class GetPlaybackInfo : IReturn<PlaybackInfoResponse>
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- [Route("/Items/{Id}/PlaybackInfo", "POST", Summary = "Gets live playback media info for an item")]
- public class GetPostedPlaybackInfo : PlaybackInfoRequest, IReturn<PlaybackInfoResponse>
- {
- }
-
- [Route("/LiveStreams/Open", "POST", Summary = "Opens a media source")]
- public class OpenMediaSource : LiveStreamRequest, IReturn<LiveStreamResponse>
- {
- }
-
- [Route("/LiveStreams/Close", "POST", Summary = "Closes a media source")]
- public class CloseMediaSource : IReturnVoid
- {
- [ApiMember(Name = "LiveStreamId", Description = "LiveStreamId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string LiveStreamId { get; set; }
- }
-
- [Route("/Playback/BitrateTest", "GET")]
- public class GetBitrateTestBytes
- {
- [ApiMember(Name = "Size", Description = "Size", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")]
- public long Size { get; set; }
-
- public GetBitrateTestBytes()
- {
- // 100k
- Size = 102400;
- }
- }
-
- [Authenticated]
- public class MediaInfoService : BaseApiService
- {
- private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IDeviceManager _deviceManager;
- private readonly ILibraryManager _libraryManager;
- private readonly IServerConfigurationManager _config;
- private readonly INetworkManager _networkManager;
- private readonly IMediaEncoder _mediaEncoder;
- private readonly IUserManager _userManager;
- private readonly IJsonSerializer _json;
- private readonly IAuthorizationContext _authContext;
- private readonly ILogger _logger;
-
- public MediaInfoService(
- IMediaSourceManager mediaSourceManager,
- IDeviceManager deviceManager,
- ILibraryManager libraryManager,
- IServerConfigurationManager config,
- INetworkManager networkManager,
- IMediaEncoder mediaEncoder,
- IUserManager userManager,
- IJsonSerializer json,
- IAuthorizationContext authContext,
- ILoggerFactory loggerFactory)
- {
- _mediaSourceManager = mediaSourceManager;
- _deviceManager = deviceManager;
- _libraryManager = libraryManager;
- _config = config;
- _networkManager = networkManager;
- _mediaEncoder = mediaEncoder;
- _userManager = userManager;
- _json = json;
- _authContext = authContext;
- _logger = loggerFactory.CreateLogger(nameof(MediaInfoService));
- }
-
- public object Get(GetBitrateTestBytes request)
- {
- var bytes = new byte[request.Size];
-
- for (var i = 0; i < bytes.Length; i++)
- {
- bytes[i] = 0;
- }
-
- return ResultFactory.GetResult(null, bytes, "application/octet-stream");
- }
-
- public async Task<object> Get(GetPlaybackInfo request)
- {
- var result = await GetPlaybackInfo(request.Id, request.UserId, new[] { MediaType.Audio, MediaType.Video }).ConfigureAwait(false);
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Post(OpenMediaSource request)
- {
- var result = await OpenMediaSource(request).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- private async Task<LiveStreamResponse> OpenMediaSource(OpenMediaSource request)
- {
- var authInfo = _authContext.GetAuthorizationInfo(Request);
-
- var result = await _mediaSourceManager.OpenLiveStream(request, CancellationToken.None).ConfigureAwait(false);
-
- var profile = request.DeviceProfile;
- if (profile == null)
- {
- var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
- if (caps != null)
- {
- profile = caps.DeviceProfile;
- }
- }
-
- if (profile != null)
- {
- var item = _libraryManager.GetItemById(request.ItemId);
-
- SetDeviceSpecificData(item, result.MediaSource, profile, authInfo, request.MaxStreamingBitrate,
- request.StartTimeTicks ?? 0, result.MediaSource.Id, request.AudioStreamIndex,
- request.SubtitleStreamIndex, request.MaxAudioChannels, request.PlaySessionId, request.UserId, request.EnableDirectPlay, true, request.EnableDirectStream, true, true, true);
- }
- else
- {
- if (!string.IsNullOrWhiteSpace(result.MediaSource.TranscodingUrl))
- {
- result.MediaSource.TranscodingUrl += "&LiveStreamId=" + result.MediaSource.LiveStreamId;
- }
- }
-
- if (result.MediaSource != null)
- {
- NormalizeMediaSourceContainer(result.MediaSource, profile, DlnaProfileType.Video);
- }
-
- return result;
- }
-
- public void Post(CloseMediaSource request)
- {
- var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId);
- Task.WaitAll(task);
- }
-
- public async Task<PlaybackInfoResponse> GetPlaybackInfo(GetPostedPlaybackInfo request)
- {
- var authInfo = _authContext.GetAuthorizationInfo(Request);
-
- var profile = request.DeviceProfile;
-
- //Logger.LogInformation("GetPostedPlaybackInfo profile: {profile}", _json.SerializeToString(profile));
-
- if (profile == null)
- {
- var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
- if (caps != null)
- {
- profile = caps.DeviceProfile;
- }
- }
-
- var info = await GetPlaybackInfo(request.Id, request.UserId, new[] { MediaType.Audio, MediaType.Video }, request.MediaSourceId, request.LiveStreamId).ConfigureAwait(false);
-
- if (profile != null)
- {
- var mediaSourceId = request.MediaSourceId;
-
- SetDeviceSpecificData(request.Id, info, profile, authInfo, request.MaxStreamingBitrate ?? profile.MaxStreamingBitrate, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex, request.MaxAudioChannels, request.UserId, request.EnableDirectPlay, true, request.EnableDirectStream, request.EnableTranscoding, request.AllowVideoStreamCopy, request.AllowAudioStreamCopy);
- }
-
- if (request.AutoOpenLiveStream)
- {
- var mediaSource = string.IsNullOrWhiteSpace(request.MediaSourceId) ? info.MediaSources.FirstOrDefault() : info.MediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId, StringComparison.Ordinal));
-
- if (mediaSource != null && mediaSource.RequiresOpening && string.IsNullOrWhiteSpace(mediaSource.LiveStreamId))
- {
- var openStreamResult = await OpenMediaSource(new OpenMediaSource
- {
- AudioStreamIndex = request.AudioStreamIndex,
- DeviceProfile = request.DeviceProfile,
- EnableDirectPlay = request.EnableDirectPlay,
- EnableDirectStream = request.EnableDirectStream,
- ItemId = request.Id,
- MaxAudioChannels = request.MaxAudioChannels,
- MaxStreamingBitrate = request.MaxStreamingBitrate,
- PlaySessionId = info.PlaySessionId,
- StartTimeTicks = request.StartTimeTicks,
- SubtitleStreamIndex = request.SubtitleStreamIndex,
- UserId = request.UserId,
- OpenToken = mediaSource.OpenToken,
- //EnableMediaProbe = request.EnableMediaProbe
-
- }).ConfigureAwait(false);
-
- info.MediaSources = new MediaSourceInfo[] { openStreamResult.MediaSource };
- }
- }
-
- if (info.MediaSources != null)
- {
- foreach (var mediaSource in info.MediaSources)
- {
- NormalizeMediaSourceContainer(mediaSource, profile, DlnaProfileType.Video);
- }
- }
-
- return info;
- }
-
- private void NormalizeMediaSourceContainer(MediaSourceInfo mediaSource, DeviceProfile profile, DlnaProfileType type)
- {
- mediaSource.Container = StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(mediaSource.Container, mediaSource.Path, profile, type);
- }
-
- public async Task<object> Post(GetPostedPlaybackInfo request)
- {
- var result = await GetPlaybackInfo(request).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- private T Clone<T>(T obj)
- {
- // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it
- // Should we move this directly into MediaSourceManager?
-
- var json = _json.SerializeToString(obj);
- return _json.DeserializeFromString<T>(json);
- }
-
- private async Task<PlaybackInfoResponse> GetPlaybackInfo(Guid id, Guid userId, string[] supportedLiveMediaTypes, string mediaSourceId = null, string liveStreamId = null)
- {
- var user = _userManager.GetUserById(userId);
- var item = _libraryManager.GetItemById(id);
- var result = new PlaybackInfoResponse();
-
- if (string.IsNullOrWhiteSpace(liveStreamId))
- {
- IEnumerable<MediaSourceInfo> mediaSources;
- try
- {
- // TODO handle supportedLiveMediaTypes ?
- mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- mediaSources = new List<MediaSourceInfo>();
- _logger.LogError(ex, "Could not find media sources for item id {id}", id);
- // TODO PlaybackException ??
- //result.ErrorCode = ex.ErrorCode;
- }
-
- result.MediaSources = mediaSources.ToArray();
-
- if (!string.IsNullOrWhiteSpace(mediaSourceId))
- {
- result.MediaSources = result.MediaSources
- .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
- .ToArray();
- }
- }
- else
- {
- var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
-
- result.MediaSources = new MediaSourceInfo[] { mediaSource };
- }
-
- if (result.MediaSources.Length == 0)
- {
- if (!result.ErrorCode.HasValue)
- {
- result.ErrorCode = PlaybackErrorCode.NoCompatibleStream;
- }
- }
- else
- {
- result.MediaSources = Clone(result.MediaSources);
-
- result.PlaySessionId = Guid.NewGuid().ToString("N");
- }
-
- return result;
- }
-
- private void SetDeviceSpecificData(Guid itemId,
- PlaybackInfoResponse result,
- DeviceProfile profile,
- AuthorizationInfo auth,
- long? maxBitrate,
- long startTimeTicks,
- string mediaSourceId,
- int? audioStreamIndex,
- int? subtitleStreamIndex,
- int? maxAudioChannels,
- Guid userId,
- bool enableDirectPlay,
- bool forceDirectPlayRemoteMediaSource,
- bool enableDirectStream,
- bool enableTranscoding,
- bool allowVideoStreamCopy,
- bool allowAudioStreamCopy)
- {
- var item = _libraryManager.GetItemById(itemId);
-
- foreach (var mediaSource in result.MediaSources)
- {
- SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex, maxAudioChannels, result.PlaySessionId, userId, enableDirectPlay, forceDirectPlayRemoteMediaSource, enableDirectStream, enableTranscoding, allowVideoStreamCopy, allowAudioStreamCopy);
- }
-
- SortMediaSources(result, maxBitrate);
- }
-
- private void SetDeviceSpecificData(BaseItem item,
- MediaSourceInfo mediaSource,
- DeviceProfile profile,
- AuthorizationInfo auth,
- long? maxBitrate,
- long startTimeTicks,
- string mediaSourceId,
- int? audioStreamIndex,
- int? subtitleStreamIndex,
- int? maxAudioChannels,
- string playSessionId,
- Guid userId,
- bool enableDirectPlay,
- bool forceDirectPlayRemoteMediaSource,
- bool enableDirectStream,
- bool enableTranscoding,
- bool allowVideoStreamCopy,
- bool allowAudioStreamCopy)
- {
- var streamBuilder = new StreamBuilder(_mediaEncoder, Logger);
-
- var options = new VideoOptions
- {
- MediaSources = new MediaSourceInfo[] { mediaSource },
- Context = EncodingContext.Streaming,
- DeviceId = auth.DeviceId,
- ItemId = item.Id,
- Profile = profile,
- MaxAudioChannels = maxAudioChannels
- };
-
- if (string.Equals(mediaSourceId, mediaSource.Id, StringComparison.OrdinalIgnoreCase))
- {
- options.MediaSourceId = mediaSourceId;
- options.AudioStreamIndex = audioStreamIndex;
- options.SubtitleStreamIndex = subtitleStreamIndex;
- }
-
- var user = _userManager.GetUserById(userId);
-
- if (!enableDirectPlay)
- {
- mediaSource.SupportsDirectPlay = false;
- }
- if (!enableDirectStream)
- {
- mediaSource.SupportsDirectStream = false;
- }
- if (!enableTranscoding)
- {
- mediaSource.SupportsTranscoding = false;
- }
-
- if (item is Audio)
- {
- Logger.LogInformation("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding);
- }
- else
- {
- Logger.LogInformation("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}",
- user.Name,
- user.Policy.EnablePlaybackRemuxing,
- user.Policy.EnableVideoPlaybackTranscoding,
- user.Policy.EnableAudioPlaybackTranscoding);
- }
-
- if (mediaSource.SupportsDirectPlay)
- {
- if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource)
- {
- }
- else
- {
- var supportsDirectStream = mediaSource.SupportsDirectStream;
-
- // Dummy this up to fool StreamBuilder
- mediaSource.SupportsDirectStream = true;
- options.MaxBitrate = maxBitrate;
-
- if (item is Audio)
- {
- if (!user.Policy.EnableAudioPlaybackTranscoding)
- {
- options.ForceDirectPlay = true;
- }
- }
- else if (item is Video)
- {
- if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing)
- {
- options.ForceDirectPlay = true;
- }
- }
-
- // The MediaSource supports direct stream, now test to see if the client supports it
- var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
- streamBuilder.BuildAudioItem(options) :
- streamBuilder.BuildVideoItem(options);
-
- if (streamInfo == null || !streamInfo.IsDirectStream)
- {
- mediaSource.SupportsDirectPlay = false;
- }
-
- // Set this back to what it was
- mediaSource.SupportsDirectStream = supportsDirectStream;
-
- if (streamInfo != null)
- {
- SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
- }
- }
- }
-
- if (mediaSource.SupportsDirectStream)
- {
- options.MaxBitrate = GetMaxBitrate(maxBitrate, user);
-
- if (item is Audio)
- {
- if (!user.Policy.EnableAudioPlaybackTranscoding)
- {
- options.ForceDirectStream = true;
- }
- }
- else if (item is Video)
- {
- if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing)
- {
- options.ForceDirectStream = true;
- }
- }
-
- // The MediaSource supports direct stream, now test to see if the client supports it
- var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
- streamBuilder.BuildAudioItem(options) :
- streamBuilder.BuildVideoItem(options);
-
- if (streamInfo == null || !streamInfo.IsDirectStream)
- {
- mediaSource.SupportsDirectStream = false;
- }
-
- if (streamInfo != null)
- {
- SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
- }
- }
-
- if (mediaSource.SupportsTranscoding)
- {
- options.MaxBitrate = GetMaxBitrate(maxBitrate, user);
-
- // The MediaSource supports direct stream, now test to see if the client supports it
- var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
- streamBuilder.BuildAudioItem(options) :
- streamBuilder.BuildVideoItem(options);
-
- if (streamInfo != null)
- {
- streamInfo.PlaySessionId = playSessionId;
-
- if (streamInfo.PlayMethod == PlayMethod.Transcode)
- {
- streamInfo.StartPositionTicks = startTimeTicks;
- mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-');
-
- if (!allowVideoStreamCopy)
- {
- mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false";
- }
- if (!allowAudioStreamCopy)
- {
- mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false";
- }
- mediaSource.TranscodingContainer = streamInfo.Container;
- mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
- }
-
- // Do this after the above so that StartPositionTicks is set
- SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
- }
- }
- }
-
- private long? GetMaxBitrate(long? clientMaxBitrate, User user)
- {
- var maxBitrate = clientMaxBitrate;
- var remoteClientMaxBitrate = user == null ? 0 : user.Policy.RemoteClientBitrateLimit;
-
- if (remoteClientMaxBitrate <= 0)
- {
- remoteClientMaxBitrate = _config.Configuration.RemoteClientBitrateLimit;
- }
-
- if (remoteClientMaxBitrate > 0)
- {
- var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp);
-
- Logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
- if (!isInLocalNetwork)
- {
- maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
- }
- }
-
- return maxBitrate;
- }
-
- private void SetDeviceSpecificSubtitleInfo(StreamInfo info, MediaSourceInfo mediaSource, string accessToken)
- {
- var profiles = info.GetSubtitleProfiles(_mediaEncoder, false, "-", accessToken);
- mediaSource.DefaultSubtitleStreamIndex = info.SubtitleStreamIndex;
-
- mediaSource.TranscodeReasons = info.TranscodeReasons;
-
- foreach (var profile in profiles)
- {
- foreach (var stream in mediaSource.MediaStreams)
- {
- if (stream.Type == MediaStreamType.Subtitle && stream.Index == profile.Index)
- {
- stream.DeliveryMethod = profile.DeliveryMethod;
-
- if (profile.DeliveryMethod == SubtitleDeliveryMethod.External)
- {
- stream.DeliveryUrl = profile.Url.TrimStart('-');
- stream.IsExternalUrl = profile.IsExternalUrl;
- }
- }
- }
- }
- }
-
- private void SortMediaSources(PlaybackInfoResponse result, long? maxBitrate)
- {
- var originalList = result.MediaSources.ToList();
-
- result.MediaSources = result.MediaSources.OrderBy(i =>
- {
- // Nothing beats direct playing a file
- if (i.SupportsDirectPlay && i.Protocol == MediaProtocol.File)
- {
- return 0;
- }
-
- return 1;
-
- }).ThenBy(i =>
- {
- // Let's assume direct streaming a file is just as desirable as direct playing a remote url
- if (i.SupportsDirectPlay || i.SupportsDirectStream)
- {
- return 0;
- }
-
- return 1;
-
- }).ThenBy(i =>
- {
- switch (i.Protocol)
- {
- case MediaProtocol.File:
- return 0;
- default:
- return 1;
- }
-
- }).ThenBy(i =>
- {
- if (maxBitrate.HasValue)
- {
- if (i.Bitrate.HasValue)
- {
- if (i.Bitrate.Value <= maxBitrate.Value)
- {
- return 0;
- }
-
- return 2;
- }
- }
-
- return 1;
-
- }).ThenBy(originalList.IndexOf)
- .ToArray();
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Progressive/AudioService.cs b/MediaBrowser.Api/Playback/Progressive/AudioService.cs
deleted file mode 100644
index 48b4e2f24..000000000
--- a/MediaBrowser.Api/Playback/Progressive/AudioService.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Api.Playback.Progressive
-{
- /// <summary>
- /// Class GetAudioStream
- /// </summary>
- [Route("/Audio/{Id}/stream.{Container}", "GET", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/stream", "GET", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/stream.{Container}", "HEAD", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/stream", "HEAD", Summary = "Gets an audio stream")]
- public class GetAudioStream : StreamRequest
- {
- }
-
- /// <summary>
- /// Class AudioService
- /// </summary>
- // TODO: In order to autheneticate this in the future, Dlna playback will require updating
- //[Authenticated]
- public class AudioService : BaseProgressiveStreamingService
- {
- public AudioService(
- IHttpClient httpClient,
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext,
- IEnvironmentInfo environmentInfo)
- : base(httpClient,
- serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext,
- environmentInfo)
- {
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetAudioStream request)
- {
- return ProcessRequest(request, false);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Head(GetAudioStream request)
- {
- return ProcessRequest(request, true);
- }
-
- protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
- {
- return EncodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath);
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
deleted file mode 100644
index 6a98c5e8a..000000000
--- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
+++ /dev/null
@@ -1,452 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Api.Playback.Progressive
-{
- /// <summary>
- /// Class BaseProgressiveStreamingService
- /// </summary>
- public abstract class BaseProgressiveStreamingService : BaseStreamingService
- {
- protected readonly IEnvironmentInfo EnvironmentInfo;
- protected IHttpClient HttpClient { get; private set; }
-
- public BaseProgressiveStreamingService(
- IHttpClient httpClient,
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext,
- IEnvironmentInfo environmentInfo)
- : base(serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext)
- {
- EnvironmentInfo = environmentInfo;
- HttpClient = httpClient;
- }
-
- /// <summary>
- /// Gets the output file extension.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>System.String.</returns>
- protected override string GetOutputFileExtension(StreamState state)
- {
- var ext = base.GetOutputFileExtension(state);
-
- if (!string.IsNullOrEmpty(ext))
- {
- return ext;
- }
-
- var isVideoRequest = state.VideoRequest != null;
-
- // Try to infer based on the desired video codec
- if (isVideoRequest)
- {
- var videoCodec = state.VideoRequest.VideoCodec;
-
- if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
- {
- return ".ts";
- }
- if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
- {
- return ".ogv";
- }
- if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
- {
- return ".webm";
- }
- if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
- {
- return ".asf";
- }
- }
-
- // Try to infer based on the desired audio codec
- if (!isVideoRequest)
- {
- var audioCodec = state.Request.AudioCodec;
-
- if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
- {
- return ".aac";
- }
- if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
- {
- return ".mp3";
- }
- if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
- {
- return ".ogg";
- }
- if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
- {
- return ".wma";
- }
- }
-
- return null;
- }
-
- /// <summary>
- /// Gets the type of the transcoding job.
- /// </summary>
- /// <value>The type of the transcoding job.</value>
- protected override TranscodingJobType TranscodingJobType => TranscodingJobType.Progressive;
-
- /// <summary>
- /// Processes the request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- /// <returns>Task.</returns>
- protected async Task<object> ProcessRequest(StreamRequest request, bool isHeadRequest)
- {
- var cancellationTokenSource = new CancellationTokenSource();
-
- var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
-
- var responseHeaders = new Dictionary<string, string>();
-
- if (request.Static && state.DirectStreamProvider != null)
- {
- AddDlnaHeaders(state, responseHeaders, true);
-
- using (state)
- {
- var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- // TODO: Don't hardcode this
- outputHeaders["Content-Type"] = MediaBrowser.Model.Net.MimeTypes.GetMimeType("file.ts");
-
- return new ProgressiveFileCopier(state.DirectStreamProvider, outputHeaders, null, Logger, EnvironmentInfo, CancellationToken.None)
- {
- AllowEndOfFile = false
- };
- }
- }
-
- // Static remote stream
- if (request.Static && state.InputProtocol == MediaProtocol.Http)
- {
- AddDlnaHeaders(state, responseHeaders, true);
-
- using (state)
- {
- return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
- }
- }
-
- if (request.Static && state.InputProtocol != MediaProtocol.File)
- {
- throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
- }
-
- var outputPath = state.OutputFilePath;
- var outputPathExists = File.Exists(outputPath);
-
- var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
- var isTranscodeCached = outputPathExists && transcodingJob != null;
-
- AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
-
- // Static stream
- if (request.Static)
- {
- var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
-
- using (state)
- {
- if (state.MediaSource.IsInfiniteStream)
- {
- var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- outputHeaders["Content-Type"] = contentType;
-
- return new ProgressiveFileCopier(FileSystem, state.MediaPath, outputHeaders, null, Logger, EnvironmentInfo, CancellationToken.None)
- {
- AllowEndOfFile = false
- };
- }
-
- TimeSpan? cacheDuration = null;
-
- if (!string.IsNullOrEmpty(request.Tag))
- {
- cacheDuration = TimeSpan.FromDays(365);
- }
-
- return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- {
- ResponseHeaders = responseHeaders,
- ContentType = contentType,
- IsHeadRequest = isHeadRequest,
- Path = state.MediaPath,
- CacheDuration = cacheDuration
-
- }).ConfigureAwait(false);
- }
- }
-
- //// Not static but transcode cache file exists
- //if (isTranscodeCached && state.VideoRequest == null)
- //{
- // var contentType = state.GetMimeType(outputPath);
-
- // try
- // {
- // if (transcodingJob != null)
- // {
- // ApiEntryPoint.Instance.OnTranscodeBeginRequest(transcodingJob);
- // }
-
- // return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
- // {
- // ResponseHeaders = responseHeaders,
- // ContentType = contentType,
- // IsHeadRequest = isHeadRequest,
- // Path = outputPath,
- // FileShare = FileShareMode.ReadWrite,
- // OnComplete = () =>
- // {
- // if (transcodingJob != null)
- // {
- // ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
- // }
- // }
-
- // }).ConfigureAwait(false);
- // }
- // finally
- // {
- // state.Dispose();
- // }
- //}
-
- // Need to start ffmpeg
- try
- {
- return await GetStreamResult(request, state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
- }
- catch
- {
- state.Dispose();
-
- throw;
- }
- }
-
- /// <summary>
- /// Gets the static remote stream result.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- /// <param name="cancellationTokenSource">The cancellation token source.</param>
- /// <returns>Task{System.Object}.</returns>
- private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
- {
- string useragent = null;
- state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
-
- var trySupportSeek = false;
-
- var options = new HttpRequestOptions
- {
- Url = state.MediaPath,
- UserAgent = useragent,
- BufferContent = false,
- CancellationToken = cancellationTokenSource.Token
- };
-
- if (trySupportSeek)
- {
- if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
- {
- options.RequestHeaders["Range"] = Request.QueryString["Range"];
- }
- }
- var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
-
- if (trySupportSeek)
- {
- foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
- {
- var val = response.Headers[name];
- if (!string.IsNullOrWhiteSpace(val))
- {
- responseHeaders[name] = val;
- }
- }
- }
- else
- {
- responseHeaders["Accept-Ranges"] = "none";
- }
-
- // Seeing cases of -1 here
- if (response.ContentLength.HasValue && response.ContentLength.Value >= 0)
- {
- responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
- }
-
- if (isHeadRequest)
- {
- using (response)
- {
- return ResultFactory.GetResult(null, new byte[] { }, response.ContentType, responseHeaders);
- }
- }
-
- var result = new StaticRemoteStreamWriter(response);
-
- result.Headers["Content-Type"] = response.ContentType;
-
- // Add the response headers to the result object
- foreach (var header in responseHeaders)
- {
- result.Headers[header.Key] = header.Value;
- }
-
- return result;
- }
-
- /// <summary>
- /// Gets the stream result.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- /// <param name="cancellationTokenSource">The cancellation token source.</param>
- /// <returns>Task{System.Object}.</returns>
- private async Task<object> GetStreamResult(StreamRequest request, StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
- {
- // Use the command line args with a dummy playlist path
- var outputPath = state.OutputFilePath;
-
- responseHeaders["Accept-Ranges"] = "none";
-
- var contentType = state.GetMimeType(outputPath);
-
- // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
- // What we really want to do is hunt that down and remove that
- var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
-
- if (contentLength.HasValue)
- {
- responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
- }
-
- // Headers only
- if (isHeadRequest)
- {
- var streamResult = ResultFactory.GetResult(null, new byte[] { }, contentType, responseHeaders);
-
- var hasHeaders = streamResult as IHasHeaders;
- if (hasHeaders != null)
- {
- if (contentLength.HasValue)
- {
- hasHeaders.Headers["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
- }
- else
- {
- if (hasHeaders.Headers.ContainsKey("Content-Length"))
- {
- hasHeaders.Headers.Remove("Content-Length");
- }
- }
- }
-
- return streamResult;
- }
-
- var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(outputPath);
- await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
- try
- {
- TranscodingJob job;
-
- if (!File.Exists(outputPath))
- {
- job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
- }
- else
- {
- job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
- state.Dispose();
- }
-
- var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- outputHeaders["Content-Type"] = contentType;
-
- // Add the response headers to the result object
- foreach (var item in responseHeaders)
- {
- outputHeaders[item.Key] = item.Value;
- }
-
- return new ProgressiveFileCopier(FileSystem, outputPath, outputHeaders, job, Logger, EnvironmentInfo, CancellationToken.None);
- }
- finally
- {
- transcodingLock.Release();
- }
- }
-
- /// <summary>
- /// Gets the length of the estimated content.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>System.Nullable{System.Int64}.</returns>
- private long? GetEstimatedContentLength(StreamState state)
- {
- var totalBitrate = state.TotalOutputBitrate ?? 0;
-
- if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
- {
- return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds / 8);
- }
-
- return null;
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
deleted file mode 100644
index 3dd9de2a1..000000000
--- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
+++ /dev/null
@@ -1,184 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback.Progressive
-{
- public class ProgressiveFileCopier : IAsyncStreamWriter, IHasHeaders
- {
- private readonly IFileSystem _fileSystem;
- private readonly TranscodingJob _job;
- private readonly ILogger _logger;
- private readonly string _path;
- private readonly CancellationToken _cancellationToken;
- private readonly Dictionary<string, string> _outputHeaders;
-
- const int StreamCopyToBufferSize = 81920;
-
- private long _bytesWritten = 0;
- public long StartPosition { get; set; }
- public bool AllowEndOfFile = true;
-
- private readonly IDirectStreamProvider _directStreamProvider;
- private readonly IEnvironmentInfo _environment;
-
- public ProgressiveFileCopier(IFileSystem fileSystem, string path, Dictionary<string, string> outputHeaders, TranscodingJob job, ILogger logger, IEnvironmentInfo environment, CancellationToken cancellationToken)
- {
- _fileSystem = fileSystem;
- _path = path;
- _outputHeaders = outputHeaders;
- _job = job;
- _logger = logger;
- _cancellationToken = cancellationToken;
- _environment = environment;
- }
-
- public ProgressiveFileCopier(IDirectStreamProvider directStreamProvider, Dictionary<string, string> outputHeaders, TranscodingJob job, ILogger logger, IEnvironmentInfo environment, CancellationToken cancellationToken)
- {
- _directStreamProvider = directStreamProvider;
- _outputHeaders = outputHeaders;
- _job = job;
- _logger = logger;
- _cancellationToken = cancellationToken;
- _environment = environment;
- }
-
- public IDictionary<string, string> Headers => _outputHeaders;
-
- private Stream GetInputStream(bool allowAsyncFileRead)
- {
- var fileOpenOptions = FileOpenOptions.SequentialScan;
-
- if (allowAsyncFileRead)
- {
- fileOpenOptions |= FileOpenOptions.Asynchronous;
- }
-
- return _fileSystem.GetFileStream(_path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
- }
-
- public async Task WriteToAsync(Stream outputStream, CancellationToken cancellationToken)
- {
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken).Token;
-
- try
- {
- if (_directStreamProvider != null)
- {
- await _directStreamProvider.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
- return;
- }
-
- var eofCount = 0;
-
- // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
- var allowAsyncFileRead = _environment.OperatingSystem != Model.System.OperatingSystem.Windows;
-
- using (var inputStream = GetInputStream(allowAsyncFileRead))
- {
- if (StartPosition > 0)
- {
- inputStream.Position = StartPosition;
- }
-
- while (eofCount < 20 || !AllowEndOfFile)
- {
- int bytesRead;
- if (allowAsyncFileRead)
- {
- bytesRead = await CopyToInternalAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- bytesRead = await CopyToInternalAsyncWithSyncRead(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
- }
-
- //var position = fs.Position;
- //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
-
- if (bytesRead == 0)
- {
- if (_job == null || _job.HasExited)
- {
- eofCount++;
- }
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- eofCount = 0;
- }
- }
- }
- }
- finally
- {
- if (_job != null)
- {
- ApiEntryPoint.Instance.OnTranscodeEndRequest(_job);
- }
- }
- }
-
- private async Task<int> CopyToInternalAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
- {
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
- int totalBytesRead = 0;
-
- while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
- {
- var bytesToWrite = bytesRead;
-
- if (bytesToWrite > 0)
- {
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
-
- _bytesWritten += bytesRead;
- totalBytesRead += bytesRead;
-
- if (_job != null)
- {
- _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
- }
- }
- }
-
- return totalBytesRead;
- }
-
- private async Task<int> CopyToInternalAsync(Stream source, Stream destination, CancellationToken cancellationToken)
- {
- var array = new byte[StreamCopyToBufferSize];
- int bytesRead;
- int totalBytesRead = 0;
-
- while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
- {
- var bytesToWrite = bytesRead;
-
- if (bytesToWrite > 0)
- {
- await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
-
- _bytesWritten += bytesRead;
- totalBytesRead += bytesRead;
-
- if (_job != null)
- {
- _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
- }
- }
- }
-
- return totalBytesRead;
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/Progressive/VideoService.cs b/MediaBrowser.Api/Playback/Progressive/VideoService.cs
deleted file mode 100644
index 7aeb0e9e8..000000000
--- a/MediaBrowser.Api/Playback/Progressive/VideoService.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Api.Playback.Progressive
-{
- /// <summary>
- /// Class GetVideoStream
- /// </summary>
- [Route("/Videos/{Id}/stream.mpegts", "GET")]
- [Route("/Videos/{Id}/stream.ts", "GET")]
- [Route("/Videos/{Id}/stream.webm", "GET")]
- [Route("/Videos/{Id}/stream.asf", "GET")]
- [Route("/Videos/{Id}/stream.wmv", "GET")]
- [Route("/Videos/{Id}/stream.ogv", "GET")]
- [Route("/Videos/{Id}/stream.mp4", "GET")]
- [Route("/Videos/{Id}/stream.m4v", "GET")]
- [Route("/Videos/{Id}/stream.mkv", "GET")]
- [Route("/Videos/{Id}/stream.mpeg", "GET")]
- [Route("/Videos/{Id}/stream.mpg", "GET")]
- [Route("/Videos/{Id}/stream.avi", "GET")]
- [Route("/Videos/{Id}/stream.m2ts", "GET")]
- [Route("/Videos/{Id}/stream.3gp", "GET")]
- [Route("/Videos/{Id}/stream.wmv", "GET")]
- [Route("/Videos/{Id}/stream.wtv", "GET")]
- [Route("/Videos/{Id}/stream.mov", "GET")]
- [Route("/Videos/{Id}/stream.iso", "GET")]
- [Route("/Videos/{Id}/stream.flv", "GET")]
- [Route("/Videos/{Id}/stream", "GET")]
- [Route("/Videos/{Id}/stream.ts", "HEAD")]
- [Route("/Videos/{Id}/stream.webm", "HEAD")]
- [Route("/Videos/{Id}/stream.asf", "HEAD")]
- [Route("/Videos/{Id}/stream.wmv", "HEAD")]
- [Route("/Videos/{Id}/stream.ogv", "HEAD")]
- [Route("/Videos/{Id}/stream.mp4", "HEAD")]
- [Route("/Videos/{Id}/stream.m4v", "HEAD")]
- [Route("/Videos/{Id}/stream.mkv", "HEAD")]
- [Route("/Videos/{Id}/stream.mpeg", "HEAD")]
- [Route("/Videos/{Id}/stream.mpg", "HEAD")]
- [Route("/Videos/{Id}/stream.avi", "HEAD")]
- [Route("/Videos/{Id}/stream.3gp", "HEAD")]
- [Route("/Videos/{Id}/stream.wmv", "HEAD")]
- [Route("/Videos/{Id}/stream.wtv", "HEAD")]
- [Route("/Videos/{Id}/stream.m2ts", "HEAD")]
- [Route("/Videos/{Id}/stream.mov", "HEAD")]
- [Route("/Videos/{Id}/stream.iso", "HEAD")]
- [Route("/Videos/{Id}/stream.flv", "HEAD")]
- [Route("/Videos/{Id}/stream", "HEAD")]
- public class GetVideoStream : VideoStreamRequest
- {
-
- }
-
- /// <summary>
- /// Class VideoService
- /// </summary>
- // TODO: In order to autheneticate this in the future, Dlna playback will require updating
- //[Authenticated]
- public class VideoService : BaseProgressiveStreamingService
- {
- public VideoService(
- IHttpClient httpClient,
- IServerConfigurationManager serverConfig,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- ISubtitleEncoder subtitleEncoder,
- IDeviceManager deviceManager,
- IMediaSourceManager mediaSourceManager,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext,
- IEnvironmentInfo environmentInfo)
- : base(httpClient,
- serverConfig,
- userManager,
- libraryManager,
- isoManager,
- mediaEncoder,
- fileSystem,
- dlnaManager,
- subtitleEncoder,
- deviceManager,
- mediaSourceManager,
- jsonSerializer,
- authorizationContext,
- environmentInfo)
- {
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetVideoStream request)
- {
- return ProcessRequest(request, false);
- }
-
- /// <summary>
- /// Heads the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Head(GetVideoStream request)
- {
- return ProcessRequest(request, true);
- }
-
- protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding)
- {
- return EncodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, GetDefaultH264Preset());
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/StaticRemoteStreamWriter.cs b/MediaBrowser.Api/Playback/StaticRemoteStreamWriter.cs
deleted file mode 100644
index 3b8b29995..000000000
--- a/MediaBrowser.Api/Playback/StaticRemoteStreamWriter.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Playback
-{
- /// <summary>
- /// Class StaticRemoteStreamWriter
- /// </summary>
- public class StaticRemoteStreamWriter : IAsyncStreamWriter, IHasHeaders
- {
- /// <summary>
- /// The _input stream
- /// </summary>
- private readonly HttpResponseInfo _response;
-
- /// <summary>
- /// The _options
- /// </summary>
- private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
-
- public StaticRemoteStreamWriter(HttpResponseInfo response)
- {
- _response = response;
- }
-
- /// <summary>
- /// Gets the options.
- /// </summary>
- /// <value>The options.</value>
- public IDictionary<string, string> Headers => _options;
-
- public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
- {
- using (_response)
- {
- await _response.Content.CopyToAsync(responseStream, 81920, cancellationToken).ConfigureAwait(false);
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/StreamRequest.cs b/MediaBrowser.Api/Playback/StreamRequest.cs
deleted file mode 100644
index 7626cc378..000000000
--- a/MediaBrowser.Api/Playback/StreamRequest.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.Playback
-{
- /// <summary>
- /// Class StreamRequest
- /// </summary>
- public class StreamRequest : BaseEncodingJobOptions
- {
- [ApiMember(Name = "DeviceProfileId", Description = "Optional. The dlna device profile id to utilize.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string DeviceProfileId { get; set; }
-
- public string Params { get; set; }
- public string PlaySessionId { get; set; }
- public string Tag { get; set; }
- public string SegmentContainer { get; set; }
-
- public int? SegmentLength { get; set; }
- public int? MinSegments { get; set; }
- }
-
- public class VideoStreamRequest : StreamRequest
- {
- /// <summary>
- /// Gets a value indicating whether this instance has fixed resolution.
- /// </summary>
- /// <value><c>true</c> if this instance has fixed resolution; otherwise, <c>false</c>.</value>
- public bool HasFixedResolution => Width.HasValue || Height.HasValue;
-
- public bool EnableSubtitlesInManifest { get; set; }
- }
-}
diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs
deleted file mode 100644
index 8d4b0cb3d..000000000
--- a/MediaBrowser.Api/Playback/StreamState.cs
+++ /dev/null
@@ -1,175 +0,0 @@
-using System;
-using System.IO;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback
-{
- public class StreamState : EncodingJobInfo, IDisposable
- {
- private readonly ILogger _logger;
- private readonly IMediaSourceManager _mediaSourceManager;
-
- public string RequestedUrl { get; set; }
-
- public StreamRequest Request
- {
- get => (StreamRequest)BaseRequest;
- set
- {
- BaseRequest = value;
-
- IsVideoRequest = VideoRequest != null;
- }
- }
-
- public TranscodingThrottler TranscodingThrottler { get; set; }
-
- public VideoStreamRequest VideoRequest => Request as VideoStreamRequest;
-
- /// <summary>
- /// Gets or sets the log file stream.
- /// </summary>
- /// <value>The log file stream.</value>
- public Stream LogFileStream { get; set; }
- public IDirectStreamProvider DirectStreamProvider { get; set; }
-
- public string WaitForPath { get; set; }
-
- public bool IsOutputVideo => Request is VideoStreamRequest;
-
- public int SegmentLength
- {
- get
- {
- if (Request.SegmentLength.HasValue)
- {
- return Request.SegmentLength.Value;
- }
-
- if (string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
- {
- var userAgent = UserAgent ?? string.Empty;
-
- if (userAgent.IndexOf("AppleTV", StringComparison.OrdinalIgnoreCase) != -1 ||
- userAgent.IndexOf("cfnetwork", StringComparison.OrdinalIgnoreCase) != -1 ||
- userAgent.IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
- userAgent.IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
- userAgent.IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
- {
- if (IsSegmentedLiveStream)
- {
- return 6;
- }
-
- return 6;
- }
-
- if (IsSegmentedLiveStream)
- {
- return 3;
- }
- return 6;
- }
-
- return 3;
- }
- }
-
- public int MinSegments
- {
- get
- {
- if (Request.MinSegments.HasValue)
- {
- return Request.MinSegments.Value;
- }
-
- return SegmentLength >= 10 ? 2 : 3;
- }
- }
-
- public string UserAgent { get; set; }
-
- public StreamState(IMediaSourceManager mediaSourceManager, ILogger logger, TranscodingJobType transcodingType)
- : base(transcodingType)
- {
- _mediaSourceManager = mediaSourceManager;
- _logger = logger;
- }
-
- public bool EstimateContentLength { get; set; }
- public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
-
- public bool EnableDlnaHeaders { get; set; }
-
- public override void Dispose()
- {
- DisposeTranscodingThrottler();
- DisposeLogStream();
- DisposeLiveStream();
-
- TranscodingJob = null;
- }
-
- private void DisposeTranscodingThrottler()
- {
- if (TranscodingThrottler != null)
- {
- try
- {
- TranscodingThrottler.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error disposing TranscodingThrottler");
- }
-
- TranscodingThrottler = null;
- }
- }
-
- private void DisposeLogStream()
- {
- if (LogFileStream != null)
- {
- try
- {
- LogFileStream.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error disposing log stream");
- }
-
- LogFileStream = null;
- }
- }
-
- private async void DisposeLiveStream()
- {
- if (MediaSource.RequiresClosing && string.IsNullOrWhiteSpace(Request.LiveStreamId) && !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
- {
- try
- {
- await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error closing media source");
- }
- }
- }
-
- public DeviceProfile DeviceProfile { get; set; }
-
- public TranscodingJob TranscodingJob;
- public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float framerate, double? percentComplete, long bytesTranscoded, int? bitRate)
- {
- ApiEntryPoint.Instance.ReportTranscodingProgress(TranscodingJob, this, transcodingPosition, framerate, percentComplete, bytesTranscoded, bitRate);
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs
deleted file mode 100644
index f97e88e98..000000000
--- a/MediaBrowser.Api/Playback/UniversalAudioService.cs
+++ /dev/null
@@ -1,372 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Api.Playback.Hls;
-using MediaBrowser.Api.Playback.Progressive;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Playback
-{
- public class BaseUniversalRequest
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string MediaSourceId { get; set; }
-
- [ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string DeviceId { get; set; }
-
- public Guid UserId { get; set; }
- public string AudioCodec { get; set; }
- public string Container { get; set; }
-
- public int? MaxAudioChannels { get; set; }
- public int? TranscodingAudioChannels { get; set; }
-
- public long? MaxStreamingBitrate { get; set; }
-
- [ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public long? StartTimeTicks { get; set; }
-
- public string TranscodingContainer { get; set; }
- public string TranscodingProtocol { get; set; }
- public int? MaxAudioSampleRate { get; set; }
- public int? MaxAudioBitDepth { get; set; }
-
- public bool EnableRedirection { get; set; }
- public bool EnableRemoteMedia { get; set; }
- public bool BreakOnNonKeyFrames { get; set; }
-
- public BaseUniversalRequest()
- {
- EnableRedirection = true;
- }
- }
-
- [Route("/Audio/{Id}/universal.{Container}", "GET", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/universal", "GET", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/universal.{Container}", "HEAD", Summary = "Gets an audio stream")]
- [Route("/Audio/{Id}/universal", "HEAD", Summary = "Gets an audio stream")]
- public class GetUniversalAudioStream : BaseUniversalRequest
- {
- }
-
- [Authenticated]
- public class UniversalAudioService : BaseApiService
- {
- public UniversalAudioService(
- IHttpClient httpClient,
- IServerConfigurationManager serverConfigurationManager,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IIsoManager isoManager,
- IMediaEncoder mediaEncoder,
- IFileSystem fileSystem,
- IDlnaManager dlnaManager,
- IDeviceManager deviceManager,
- ISubtitleEncoder subtitleEncoder,
- IMediaSourceManager mediaSourceManager,
- IZipClient zipClient,
- IJsonSerializer jsonSerializer,
- IAuthorizationContext authorizationContext,
- IImageProcessor imageProcessor,
- INetworkManager networkManager,
- IEnvironmentInfo environmentInfo,
- ILoggerFactory loggerFactory)
- {
- HttpClient = httpClient;
- ServerConfigurationManager = serverConfigurationManager;
- UserManager = userManager;
- LibraryManager = libraryManager;
- IsoManager = isoManager;
- MediaEncoder = mediaEncoder;
- FileSystem = fileSystem;
- DlnaManager = dlnaManager;
- DeviceManager = deviceManager;
- SubtitleEncoder = subtitleEncoder;
- MediaSourceManager = mediaSourceManager;
- ZipClient = zipClient;
- JsonSerializer = jsonSerializer;
- AuthorizationContext = authorizationContext;
- ImageProcessor = imageProcessor;
- NetworkManager = networkManager;
- EnvironmentInfo = environmentInfo;
- _loggerFactory = loggerFactory;
- _logger = loggerFactory.CreateLogger(nameof(UniversalAudioService));
- }
-
- protected IHttpClient HttpClient { get; private set; }
- protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
- protected IUserManager UserManager { get; private set; }
- protected ILibraryManager LibraryManager { get; private set; }
- protected IIsoManager IsoManager { get; private set; }
- protected IMediaEncoder MediaEncoder { get; private set; }
- protected IFileSystem FileSystem { get; private set; }
- protected IDlnaManager DlnaManager { get; private set; }
- protected IDeviceManager DeviceManager { get; private set; }
- protected ISubtitleEncoder SubtitleEncoder { get; private set; }
- protected IMediaSourceManager MediaSourceManager { get; private set; }
- protected IZipClient ZipClient { get; private set; }
- protected IJsonSerializer JsonSerializer { get; private set; }
- protected IAuthorizationContext AuthorizationContext { get; private set; }
- protected IImageProcessor ImageProcessor { get; private set; }
- protected INetworkManager NetworkManager { get; private set; }
- protected IEnvironmentInfo EnvironmentInfo { get; private set; }
- private ILoggerFactory _loggerFactory;
- private ILogger _logger;
-
- public Task<object> Get(GetUniversalAudioStream request)
- {
- return GetUniversalStream(request, false);
- }
-
- public Task<object> Head(GetUniversalAudioStream request)
- {
- return GetUniversalStream(request, true);
- }
-
- private DeviceProfile GetDeviceProfile(GetUniversalAudioStream request)
- {
- var deviceProfile = new DeviceProfile();
-
- var directPlayProfiles = new List<DirectPlayProfile>();
-
- var containers = (request.Container ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
-
- foreach (var container in containers)
- {
- var parts = container.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
-
- var audioCodecs = parts.Length == 1 ? null : string.Join(",", parts.Skip(1).ToArray());
-
- directPlayProfiles.Add(new DirectPlayProfile
- {
- Type = DlnaProfileType.Audio,
- Container = parts[0],
- AudioCodec = audioCodecs
- });
- }
-
- deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray();
-
- deviceProfile.TranscodingProfiles = new[]
- {
- new TranscodingProfile
- {
- Type = DlnaProfileType.Audio,
- Context = EncodingContext.Streaming,
- Container = request.TranscodingContainer,
- AudioCodec = request.AudioCodec,
- Protocol = request.TranscodingProtocol,
- BreakOnNonKeyFrames = request.BreakOnNonKeyFrames,
- MaxAudioChannels = request.TranscodingAudioChannels.HasValue ? request.TranscodingAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : null
- }
- };
-
- var codecProfiles = new List<CodecProfile>();
- var conditions = new List<ProfileCondition>();
-
- if (request.MaxAudioSampleRate.HasValue)
- {
- // codec profile
- conditions.Add(new ProfileCondition
- {
- Condition = ProfileConditionType.LessThanEqual,
- IsRequired = false,
- Property = ProfileConditionValue.AudioSampleRate,
- Value = request.MaxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)
- });
- }
-
- if (request.MaxAudioBitDepth.HasValue)
- {
- // codec profile
- conditions.Add(new ProfileCondition
- {
- Condition = ProfileConditionType.LessThanEqual,
- IsRequired = false,
- Property = ProfileConditionValue.AudioBitDepth,
- Value = request.MaxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture)
- });
- }
-
- if (request.MaxAudioChannels.HasValue)
- {
- // codec profile
- conditions.Add(new ProfileCondition
- {
- Condition = ProfileConditionType.LessThanEqual,
- IsRequired = false,
- Property = ProfileConditionValue.AudioChannels,
- Value = request.MaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture)
- });
- }
-
- if (conditions.Count > 0)
- {
- // codec profile
- codecProfiles.Add(new CodecProfile
- {
- Type = CodecType.Audio,
- Container = request.Container,
- Conditions = conditions.ToArray()
- });
- }
-
- deviceProfile.CodecProfiles = codecProfiles.ToArray();
-
- return deviceProfile;
- }
-
- private async Task<object> GetUniversalStream(GetUniversalAudioStream request, bool isHeadRequest)
- {
- var deviceProfile = GetDeviceProfile(request);
-
- AuthorizationContext.GetAuthorizationInfo(Request).DeviceId = request.DeviceId;
-
- var mediaInfoService = new MediaInfoService(MediaSourceManager, DeviceManager, LibraryManager, ServerConfigurationManager, NetworkManager, MediaEncoder, UserManager, JsonSerializer, AuthorizationContext, _loggerFactory)
- {
- Request = Request
- };
-
- var playbackInfoResult = await mediaInfoService.GetPlaybackInfo(new GetPostedPlaybackInfo
- {
- Id = request.Id,
- MaxAudioChannels = request.MaxAudioChannels,
- MaxStreamingBitrate = request.MaxStreamingBitrate,
- StartTimeTicks = request.StartTimeTicks,
- UserId = request.UserId,
- DeviceProfile = deviceProfile,
- MediaSourceId = request.MediaSourceId
-
- }).ConfigureAwait(false);
-
- var mediaSource = playbackInfoResult.MediaSources[0];
-
- if (mediaSource.SupportsDirectPlay && mediaSource.Protocol == MediaProtocol.Http)
- {
- if (request.EnableRedirection)
- {
- if (mediaSource.IsRemote && request.EnableRemoteMedia)
- {
- return ResultFactory.GetRedirectResult(mediaSource.Path);
- }
- }
- }
-
- var isStatic = mediaSource.SupportsDirectStream;
-
- if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
- {
- var service = new DynamicHlsService(ServerConfigurationManager,
- UserManager,
- LibraryManager,
- IsoManager,
- MediaEncoder,
- FileSystem,
- DlnaManager,
- SubtitleEncoder,
- DeviceManager,
- MediaSourceManager,
- JsonSerializer,
- AuthorizationContext,
- NetworkManager)
- {
- Request = Request
- };
-
- var transcodingProfile = deviceProfile.TranscodingProfiles[0];
-
- var newRequest = new GetMasterHlsAudioPlaylist
- {
- AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
- AudioCodec = transcodingProfile.AudioCodec,
- Container = ".m3u8",
- DeviceId = request.DeviceId,
- Id = request.Id,
- MaxAudioChannels = request.MaxAudioChannels,
- MediaSourceId = mediaSource.Id,
- PlaySessionId = playbackInfoResult.PlaySessionId,
- StartTimeTicks = request.StartTimeTicks,
- Static = isStatic,
- SegmentContainer = request.TranscodingContainer,
- AudioSampleRate = request.MaxAudioSampleRate,
- MaxAudioBitDepth = request.MaxAudioBitDepth,
- BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames,
- TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
- };
-
- if (isHeadRequest)
- {
- return await service.Head(newRequest).ConfigureAwait(false);
- }
- return await service.Get(newRequest).ConfigureAwait(false);
- }
- else
- {
- var service = new AudioService(HttpClient,
- ServerConfigurationManager,
- UserManager,
- LibraryManager,
- IsoManager,
- MediaEncoder,
- FileSystem,
- DlnaManager,
- SubtitleEncoder,
- DeviceManager,
- MediaSourceManager,
- JsonSerializer,
- AuthorizationContext,
- EnvironmentInfo)
- {
- Request = Request
- };
-
- var newRequest = new GetAudioStream
- {
- AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
- AudioCodec = request.AudioCodec,
- Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
- DeviceId = request.DeviceId,
- Id = request.Id,
- MaxAudioChannels = request.MaxAudioChannels,
- MediaSourceId = mediaSource.Id,
- PlaySessionId = playbackInfoResult.PlaySessionId,
- StartTimeTicks = request.StartTimeTicks,
- Static = isStatic,
- AudioSampleRate = request.MaxAudioSampleRate,
- MaxAudioBitDepth = request.MaxAudioBitDepth,
- TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
- };
-
- if (isHeadRequest)
- {
- return await service.Head(newRequest).ConfigureAwait(false);
- }
- return await service.Get(newRequest).ConfigureAwait(false);
- }
- }
- }
-}
diff --git a/MediaBrowser.Api/PlaylistService.cs b/MediaBrowser.Api/PlaylistService.cs
deleted file mode 100644
index 482c1a2a8..000000000
--- a/MediaBrowser.Api/PlaylistService.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Playlists;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Playlists", "POST", Summary = "Creates a new playlist")]
- public class CreatePlaylist : IReturn<PlaylistCreationResult>
- {
- [ApiMember(Name = "Name", Description = "The name of the new playlist.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Name { get; set; }
-
- [ApiMember(Name = "Ids", Description = "Item Ids to add to the playlist", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
- public string Ids { get; set; }
-
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "MediaType", Description = "The playlist media type", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string MediaType { get; set; }
- }
-
- [Route("/Playlists/{Id}/Items", "POST", Summary = "Adds items to a playlist")]
- public class AddToPlaylist : IReturnVoid
- {
- [ApiMember(Name = "Ids", Description = "Item id, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Ids { get; set; }
-
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public Guid UserId { get; set; }
- }
-
- [Route("/Playlists/{Id}/Items/{ItemId}/Move/{NewIndex}", "POST", Summary = "Moves a playlist item")]
- public class MoveItem : IReturnVoid
- {
- [ApiMember(Name = "ItemId", Description = "ItemId", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ItemId { get; set; }
-
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "NewIndex", Description = "NewIndex", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public int NewIndex { get; set; }
- }
-
- [Route("/Playlists/{Id}/Items", "DELETE", Summary = "Removes items from a playlist")]
- public class RemoveFromPlaylist : IReturnVoid
- {
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
-
- [ApiMember(Name = "EntryIds", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string EntryIds { get; set; }
- }
-
- [Route("/Playlists/{Id}/Items", "GET", Summary = "Gets the original items of a playlist")]
- public class GetPlaylistItems : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
- }
-
- [Authenticated]
- public class PlaylistService : BaseApiService
- {
- private readonly IPlaylistManager _playlistManager;
- private readonly IDtoService _dtoService;
- private readonly IUserManager _userManager;
- private readonly ILibraryManager _libraryManager;
- private readonly IAuthorizationContext _authContext;
-
- public PlaylistService(IDtoService dtoService, IPlaylistManager playlistManager, IUserManager userManager, ILibraryManager libraryManager, IAuthorizationContext authContext)
- {
- _dtoService = dtoService;
- _playlistManager = playlistManager;
- _userManager = userManager;
- _libraryManager = libraryManager;
- _authContext = authContext;
- }
-
- public void Post(MoveItem request)
- {
- _playlistManager.MoveItem(request.Id, request.ItemId, request.NewIndex);
- }
-
- public async Task<object> Post(CreatePlaylist request)
- {
- var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest
- {
- Name = request.Name,
- ItemIdList = GetGuids(request.Ids),
- UserId = request.UserId,
- MediaType = request.MediaType
-
- }).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public void Post(AddToPlaylist request)
- {
- _playlistManager.AddToPlaylist(request.Id, GetGuids(request.Ids), request.UserId);
- }
-
- public void Delete(RemoveFromPlaylist request)
- {
- _playlistManager.RemoveFromPlaylist(request.Id, request.EntryIds.Split(','));
- }
-
- public object Get(GetPlaylistItems request)
- {
- var playlist = (Playlist)_libraryManager.GetItemById(request.Id);
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var items = playlist.GetManageableItems().ToArray();
-
- var count = items.Length;
-
- if (request.StartIndex.HasValue)
- {
- items = items.Skip(request.StartIndex.Value).ToArray();
- }
-
- if (request.Limit.HasValue)
- {
- items = items.Take(request.Limit.Value).ToArray();
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
-
- var index = 0;
- foreach (var item in dtos)
- {
- item.PlaylistItemId = items[index].Item1.Id;
- index++;
- }
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = dtos,
- TotalRecordCount = count
- };
-
- return ToOptimizedResult(result);
- }
- }
-}
diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs
deleted file mode 100644
index af61887b2..000000000
--- a/MediaBrowser.Api/PluginService.cs
+++ /dev/null
@@ -1,277 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Common.Updates;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Plugins;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class Plugins
- /// </summary>
- [Route("/Plugins", "GET", Summary = "Gets a list of currently installed plugins")]
- [Authenticated]
- public class GetPlugins : IReturn<PluginInfo[]>
- {
- public bool? IsAppStoreEnabled { get; set; }
- }
-
- /// <summary>
- /// Class UninstallPlugin
- /// </summary>
- [Route("/Plugins/{Id}", "DELETE", Summary = "Uninstalls a plugin")]
- [Authenticated(Roles = "Admin")]
- public class UninstallPlugin : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Plugin Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetPluginConfiguration
- /// </summary>
- [Route("/Plugins/{Id}/Configuration", "GET", Summary = "Gets a plugin's configuration")]
- [Authenticated]
- public class GetPluginConfiguration
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Plugin Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class UpdatePluginConfiguration
- /// </summary>
- [Route("/Plugins/{Id}/Configuration", "POST", Summary = "Updates a plugin's configuration")]
- [Authenticated]
- public class UpdatePluginConfiguration : IRequiresRequestStream, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Plugin Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// The raw Http Request Input Stream
- /// </summary>
- /// <value>The request stream.</value>
- public Stream RequestStream { get; set; }
- }
-
- //TODO Once we have proper apps and plugins and decide to break compatibility with paid plugins,
- // delete all these registration endpoints. They are only kept for compatibility.
- [Route("/Registrations/{Name}", "GET", Summary = "Gets registration status for a feature", IsHidden = true)]
- [Authenticated]
- public class GetRegistration : IReturn<RegistrationInfo>
- {
- [ApiMember(Name = "Name", Description = "Feature Name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
- }
-
- /// <summary>
- /// Class GetPluginSecurityInfo
- /// </summary>
- [Route("/Plugins/SecurityInfo", "GET", Summary = "Gets plugin registration information", IsHidden = true)]
- [Authenticated]
- public class GetPluginSecurityInfo : IReturn<PluginSecurityInfo>
- {
- }
-
- /// <summary>
- /// Class UpdatePluginSecurityInfo
- /// </summary>
- [Route("/Plugins/SecurityInfo", "POST", Summary = "Updates plugin registration information", IsHidden = true)]
- [Authenticated(Roles = "Admin")]
- public class UpdatePluginSecurityInfo : PluginSecurityInfo, IReturnVoid
- {
- }
-
- [Route("/Plugins/RegistrationRecords/{Name}", "GET", Summary = "Gets registration status for a feature", IsHidden = true)]
- [Authenticated]
- public class GetRegistrationStatus
- {
- [ApiMember(Name = "Name", Description = "Feature Name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
- }
-
- // TODO these two classes are only kept for compability with paid plugins and should be removed
- public class RegistrationInfo
- {
- public string Name { get; set; }
- public DateTime ExpirationDate { get; set; }
- public bool IsTrial { get; set; }
- public bool IsRegistered { get; set; }
- }
-
- public class MBRegistrationRecord
- {
- public DateTime ExpirationDate { get; set; }
- public bool IsRegistered { get; set; }
- public bool RegChecked { get; set; }
- public bool RegError { get; set; }
- public bool TrialVersion { get; set; }
- public bool IsValid { get; set; }
- }
-
- public class PluginSecurityInfo
- {
- public string SupporterKey { get; set; }
- public bool IsMBSupporter { get; set; }
- }
- /// <summary>
- /// Class PluginsService
- /// </summary>
- public class PluginService : BaseApiService
- {
- /// <summary>
- /// The _json serializer
- /// </summary>
- private readonly IJsonSerializer _jsonSerializer;
-
- /// <summary>
- /// The _app host
- /// </summary>
- private readonly IApplicationHost _appHost;
- private readonly IInstallationManager _installationManager;
- private readonly INetworkManager _network;
- private readonly IDeviceManager _deviceManager;
-
- public PluginService(IJsonSerializer jsonSerializer,
- IApplicationHost appHost,
- IInstallationManager installationManager,
- INetworkManager network,
- IDeviceManager deviceManager)
- : base()
- {
- if (jsonSerializer == null)
- {
- throw new ArgumentNullException(nameof(jsonSerializer));
- }
-
- _appHost = appHost;
- _installationManager = installationManager;
- _network = network;
- _deviceManager = deviceManager;
- _jsonSerializer = jsonSerializer;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetRegistrationStatus request)
- {
- var record = new MBRegistrationRecord
- {
- IsRegistered = true,
- RegChecked = true,
- TrialVersion = false,
- IsValid = true,
- RegError = false
- };
-
- return ToOptimizedResult(record);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPlugins request)
- {
- var result = _appHost.Plugins.OrderBy(p => p.Name).Select(p => p.GetPluginInfo()).ToArray();
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPluginConfiguration request)
- {
- var guid = new Guid(request.Id);
- var plugin = _appHost.Plugins.First(p => p.Id == guid) as IHasPluginConfiguration;
-
- return ToOptimizedResult(plugin.Configuration);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPluginSecurityInfo request)
- {
- var result = new PluginSecurityInfo
- {
- IsMBSupporter = true,
- SupporterKey = "IAmTotallyLegit"
- };
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(UpdatePluginSecurityInfo request)
- {
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public async Task Post(UpdatePluginConfiguration request)
- {
- // We need to parse this manually because we told service stack not to with IRequiresRequestStream
- // https://code.google.com/p/servicestack/source/browse/trunk/Common/ServiceStack.Text/ServiceStack.Text/Controller/PathInfo.cs
- var id = new Guid(GetPathValue(1));
-
- var plugin = _appHost.Plugins.First(p => p.Id == id) as IHasPluginConfiguration;
-
- if (plugin == null)
- {
- throw new FileNotFoundException();
- }
-
- var configuration = (await _jsonSerializer.DeserializeFromStreamAsync(request.RequestStream, plugin.ConfigurationType).ConfigureAwait(false)) as BasePluginConfiguration;
-
- plugin.UpdateConfiguration(configuration);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Delete(UninstallPlugin request)
- {
- var guid = new Guid(request.Id);
- var plugin = _appHost.Plugins.First(p => p.Id == guid);
-
- _installationManager.UninstallPlugin(plugin);
- }
- }
-}
diff --git a/MediaBrowser.Api/Properties/AssemblyInfo.cs b/MediaBrowser.Api/Properties/AssemblyInfo.cs
deleted file mode 100644
index f86723031..000000000
--- a/MediaBrowser.Api/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MediaBrowser.Api")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs
deleted file mode 100644
index b7e94b73f..000000000
--- a/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs
+++ /dev/null
@@ -1,241 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Tasks;
-
-namespace MediaBrowser.Api.ScheduledTasks
-{
- /// <summary>
- /// Class GetScheduledTask
- /// </summary>
- [Route("/ScheduledTasks/{Id}", "GET", Summary = "Gets a scheduled task, by Id")]
- public class GetScheduledTask : IReturn<TaskInfo>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetScheduledTasks
- /// </summary>
- [Route("/ScheduledTasks", "GET", Summary = "Gets scheduled tasks")]
- public class GetScheduledTasks : IReturn<TaskInfo[]>
- {
- [ApiMember(Name = "IsHidden", Description = "Optional filter tasks that are hidden, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsHidden { get; set; }
-
- [ApiMember(Name = "IsEnabled", Description = "Optional filter tasks that are enabled, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsEnabled { get; set; }
- }
-
- /// <summary>
- /// Class StartScheduledTask
- /// </summary>
- [Route("/ScheduledTasks/Running/{Id}", "POST", Summary = "Starts a scheduled task")]
- public class StartScheduledTask : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class StopScheduledTask
- /// </summary>
- [Route("/ScheduledTasks/Running/{Id}", "DELETE", Summary = "Stops a scheduled task")]
- public class StopScheduledTask : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class UpdateScheduledTaskTriggers
- /// </summary>
- [Route("/ScheduledTasks/{Id}/Triggers", "POST", Summary = "Updates the triggers for a scheduled task")]
- public class UpdateScheduledTaskTriggers : List<TaskTriggerInfo>, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the task id.
- /// </summary>
- /// <value>The task id.</value>
- [ApiMember(Name = "Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class ScheduledTasksService
- /// </summary>
- [Authenticated(Roles = "Admin")]
- public class ScheduledTaskService : BaseApiService
- {
- /// <summary>
- /// Gets or sets the task manager.
- /// </summary>
- /// <value>The task manager.</value>
- private ITaskManager TaskManager { get; set; }
-
- private readonly IServerConfigurationManager _config;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ScheduledTaskService" /> class.
- /// </summary>
- /// <param name="taskManager">The task manager.</param>
- /// <exception cref="ArgumentNullException">taskManager</exception>
- public ScheduledTaskService(ITaskManager taskManager, IServerConfigurationManager config)
- {
- if (taskManager == null)
- {
- throw new ArgumentNullException(nameof(taskManager));
- }
-
- TaskManager = taskManager;
- _config = config;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>IEnumerable{TaskInfo}.</returns>
- public object Get(GetScheduledTasks request)
- {
- IEnumerable<IScheduledTaskWorker> result = TaskManager.ScheduledTasks
- .OrderBy(i => i.Name);
-
- if (request.IsHidden.HasValue)
- {
- var val = request.IsHidden.Value;
-
- result = result.Where(i =>
- {
- var isHidden = false;
-
- var configurableTask = i.ScheduledTask as IConfigurableScheduledTask;
-
- if (configurableTask != null)
- {
- isHidden = configurableTask.IsHidden;
- }
-
- return isHidden == val;
- });
- }
-
- if (request.IsEnabled.HasValue)
- {
- var val = request.IsEnabled.Value;
-
- result = result.Where(i =>
- {
- var isEnabled = true;
-
- var configurableTask = i.ScheduledTask as IConfigurableScheduledTask;
-
- if (configurableTask != null)
- {
- isEnabled = configurableTask.IsEnabled;
- }
-
- return isEnabled == val;
- });
- }
-
- var infos = result
- .Select(ScheduledTaskHelpers.GetTaskInfo)
- .ToArray();
-
- return ToOptimizedResult(infos);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>IEnumerable{TaskInfo}.</returns>
- /// <exception cref="ResourceNotFoundException">Task not found</exception>
- public object Get(GetScheduledTask request)
- {
- var task = TaskManager.ScheduledTasks.FirstOrDefault(i => string.Equals(i.Id, request.Id));
-
- if (task == null)
- {
- throw new ResourceNotFoundException("Task not found");
- }
-
- var result = ScheduledTaskHelpers.GetTaskInfo(task);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <exception cref="ResourceNotFoundException">Task not found</exception>
- public void Post(StartScheduledTask request)
- {
- var task = TaskManager.ScheduledTasks.FirstOrDefault(i => string.Equals(i.Id, request.Id));
-
- if (task == null)
- {
- throw new ResourceNotFoundException("Task not found");
- }
-
- TaskManager.Execute(task, new TaskOptions());
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <exception cref="ResourceNotFoundException">Task not found</exception>
- public void Delete(StopScheduledTask request)
- {
- var task = TaskManager.ScheduledTasks.FirstOrDefault(i => string.Equals(i.Id, request.Id));
-
- if (task == null)
- {
- throw new ResourceNotFoundException("Task not found");
- }
-
- TaskManager.Cancel(task);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <exception cref="ResourceNotFoundException">Task not found</exception>
- public void Post(UpdateScheduledTaskTriggers request)
- {
- // We need to parse this manually because we told service stack not to with IRequiresRequestStream
- // https://code.google.com/p/servicestack/source/browse/trunk/Common/ServiceStack.Text/ServiceStack.Text/Controller/PathInfo.cs
- var id = GetPathValue(1);
-
- var task = TaskManager.ScheduledTasks.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.Ordinal));
-
- if (task == null)
- {
- throw new ResourceNotFoundException("Task not found");
- }
-
- task.Triggers = request.ToArray();
- }
- }
-}
diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs
deleted file mode 100644
index b0c4b29c1..000000000
--- a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Tasks;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.ScheduledTasks
-{
- /// <summary>
- /// Class ScheduledTasksWebSocketListener
- /// </summary>
- public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState>
- {
- /// <summary>
- /// Gets or sets the task manager.
- /// </summary>
- /// <value>The task manager.</value>
- private ITaskManager TaskManager { get; set; }
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- protected override string Name => "ScheduledTasksInfo";
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ScheduledTasksWebSocketListener" /> class.
- /// </summary>
- public ScheduledTasksWebSocketListener(ILogger logger, ITaskManager taskManager)
- : base(logger)
- {
- TaskManager = taskManager;
-
- TaskManager.TaskExecuting += TaskManager_TaskExecuting;
- TaskManager.TaskCompleted += TaskManager_TaskCompleted;
- }
-
- void TaskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
- {
- SendData(true);
- e.Task.TaskProgress -= Argument_TaskProgress;
- }
-
- void TaskManager_TaskExecuting(object sender, GenericEventArgs<IScheduledTaskWorker> e)
- {
- SendData(true);
- e.Argument.TaskProgress += Argument_TaskProgress;
- }
-
- void Argument_TaskProgress(object sender, GenericEventArgs<double> e)
- {
- SendData(false);
- }
-
- /// <summary>
- /// Gets the data to send.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>Task{IEnumerable{TaskInfo}}.</returns>
- protected override Task<IEnumerable<TaskInfo>> GetDataToSend(WebSocketListenerState state, CancellationToken cancellationToken)
- {
- return Task.FromResult(TaskManager.ScheduledTasks
- .OrderBy(i => i.Name)
- .Select(ScheduledTaskHelpers.GetTaskInfo)
- .Where(i => !i.IsHidden));
- }
-
- protected override void Dispose(bool dispose)
- {
- TaskManager.TaskExecuting -= TaskManager_TaskExecuting;
- TaskManager.TaskCompleted -= TaskManager_TaskCompleted;
-
- base.Dispose(dispose);
- }
- }
-}
diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs
deleted file mode 100644
index ecf07c912..000000000
--- a/MediaBrowser.Api/SearchService.cs
+++ /dev/null
@@ -1,340 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Search;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetSearchHints
- /// </summary>
- [Route("/Search/Hints", "GET", Summary = "Gets search hints based on a search term")]
- public class GetSearchHints : IReturn<SearchHintResult>
- {
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Supply a user id to search within a user's library or omit to search all.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Search characters used to find items
- /// </summary>
- /// <value>The index by.</value>
- [ApiMember(Name = "SearchTerm", Description = "The search term to filter on", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SearchTerm { get; set; }
-
-
- [ApiMember(Name = "IncludePeople", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludePeople { get; set; }
-
- [ApiMember(Name = "IncludeMedia", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludeMedia { get; set; }
-
- [ApiMember(Name = "IncludeGenres", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludeGenres { get; set; }
-
- [ApiMember(Name = "IncludeStudios", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludeStudios { get; set; }
-
- [ApiMember(Name = "IncludeArtists", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool IncludeArtists { get; set; }
-
- [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string IncludeItemTypes { get; set; }
-
- [ApiMember(Name = "ExcludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ExcludeItemTypes { get; set; }
-
- [ApiMember(Name = "MediaTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string MediaTypes { get; set; }
-
- public string ParentId { get; set; }
-
- [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsMovie { get; set; }
-
- [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSeries { get; set; }
-
- [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsNews { get; set; }
-
- [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsKids { get; set; }
-
- [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSports { get; set; }
-
- public GetSearchHints()
- {
- IncludeArtists = true;
- IncludeGenres = true;
- IncludeMedia = true;
- IncludePeople = true;
- IncludeStudios = true;
- }
- }
-
- /// <summary>
- /// Class SearchService
- /// </summary>
- [Authenticated]
- public class SearchService : BaseApiService
- {
- /// <summary>
- /// The _search engine
- /// </summary>
- private readonly ISearchEngine _searchEngine;
- private readonly ILibraryManager _libraryManager;
- private readonly IDtoService _dtoService;
- private readonly IImageProcessor _imageProcessor;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SearchService" /> class.
- /// </summary>
- /// <param name="searchEngine">The search engine.</param>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="dtoService">The dto service.</param>
- /// <param name="imageProcessor">The image processor.</param>
- public SearchService(ISearchEngine searchEngine, ILibraryManager libraryManager, IDtoService dtoService, IImageProcessor imageProcessor)
- {
- _searchEngine = searchEngine;
- _libraryManager = libraryManager;
- _dtoService = dtoService;
- _imageProcessor = imageProcessor;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetSearchHints request)
- {
- var result = GetSearchHintsAsync(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the search hints async.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{IEnumerable{SearchHintResult}}.</returns>
- private SearchHintResult GetSearchHintsAsync(GetSearchHints request)
- {
- var result = _searchEngine.GetSearchHints(new SearchQuery
- {
- Limit = request.Limit,
- SearchTerm = request.SearchTerm,
- IncludeArtists = request.IncludeArtists,
- IncludeGenres = request.IncludeGenres,
- IncludeMedia = request.IncludeMedia,
- IncludePeople = request.IncludePeople,
- IncludeStudios = request.IncludeStudios,
- StartIndex = request.StartIndex,
- UserId = request.UserId,
- IncludeItemTypes = ApiEntryPoint.Split(request.IncludeItemTypes, ',', true),
- ExcludeItemTypes = ApiEntryPoint.Split(request.ExcludeItemTypes, ',', true),
- MediaTypes = ApiEntryPoint.Split(request.MediaTypes, ',', true),
- ParentId = request.ParentId,
-
- IsKids = request.IsKids,
- IsMovie = request.IsMovie,
- IsNews = request.IsNews,
- IsSeries = request.IsSeries,
- IsSports = request.IsSports
-
- });
-
- return new SearchHintResult
- {
- TotalRecordCount = result.TotalRecordCount,
-
- SearchHints = result.Items.Select(GetSearchHintResult).ToArray()
- };
- }
-
- /// <summary>
- /// Gets the search hint result.
- /// </summary>
- /// <param name="hintInfo">The hint info.</param>
- /// <returns>SearchHintResult.</returns>
- private SearchHint GetSearchHintResult(SearchHintInfo hintInfo)
- {
- var item = hintInfo.Item;
-
- var result = new SearchHint
- {
- Name = item.Name,
- IndexNumber = item.IndexNumber,
- ParentIndexNumber = item.ParentIndexNumber,
- Id = item.Id,
- Type = item.GetClientTypeName(),
- MediaType = item.MediaType,
- MatchedTerm = hintInfo.MatchedTerm,
- RunTimeTicks = item.RunTimeTicks,
- ProductionYear = item.ProductionYear,
- ChannelId = item.ChannelId,
- EndDate = item.EndDate
- };
-
- // legacy
- result.ItemId = result.Id;
-
- if (item.IsFolder)
- {
- result.IsFolder = true;
- }
-
- var primaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary);
-
- if (primaryImageTag != null)
- {
- result.PrimaryImageTag = primaryImageTag;
- result.PrimaryImageAspectRatio = _dtoService.GetPrimaryImageAspectRatio(item);
- }
-
- SetThumbImageInfo(result, item);
- SetBackdropImageInfo(result, item);
-
- var program = item as LiveTvProgram;
- if (program != null)
- {
- result.StartDate = program.StartDate;
- }
-
- var hasSeries = item as IHasSeries;
- if (hasSeries != null)
- {
- result.Series = hasSeries.SeriesName;
- }
-
- var series = item as Series;
- if (series != null)
- {
- if (series.Status.HasValue)
- {
- result.Status = series.Status.Value.ToString();
- }
- }
-
- var album = item as MusicAlbum;
-
- if (album != null)
- {
- result.Artists = album.Artists;
- result.AlbumArtist = album.AlbumArtist;
- }
-
- var song = item as Audio;
-
- if (song != null)
- {
- result.AlbumArtist = song.AlbumArtists.FirstOrDefault();
- result.Artists = song.Artists;
-
- album = song.AlbumEntity;
-
- if (album != null)
- {
- result.Album = album.Name;
- result.AlbumId = album.Id;
- }
- else
- {
- result.Album = song.Album;
- }
- }
-
- if (!item.ChannelId.Equals(Guid.Empty))
- {
- var channel = _libraryManager.GetItemById(item.ChannelId);
- result.ChannelName = channel == null ? null : channel.Name;
- }
-
- return result;
- }
-
- private void SetThumbImageInfo(SearchHint hint, BaseItem item)
- {
- var itemWithImage = item.HasImage(ImageType.Thumb) ? item : null;
-
- if (itemWithImage == null)
- {
- if (item is Episode)
- {
- itemWithImage = GetParentWithImage<Series>(item, ImageType.Thumb);
- }
- }
-
- if (itemWithImage == null)
- {
- itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Thumb);
- }
-
- if (itemWithImage != null)
- {
- var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Thumb);
-
- if (tag != null)
- {
- hint.ThumbImageTag = tag;
- hint.ThumbImageItemId = itemWithImage.Id.ToString("N");
- }
- }
- }
-
- private void SetBackdropImageInfo(SearchHint hint, BaseItem item)
- {
- var itemWithImage = item.HasImage(ImageType.Backdrop) ? item : null;
-
- if (itemWithImage == null)
- {
- itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Backdrop);
- }
-
- if (itemWithImage != null)
- {
- var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Backdrop);
-
- if (tag != null)
- {
- hint.BackdropImageTag = tag;
- hint.BackdropImageItemId = itemWithImage.Id.ToString("N");
- }
- }
- }
-
- private T GetParentWithImage<T>(BaseItem item, ImageType type)
- where T : BaseItem
- {
- return item.GetParents().OfType<T>().FirstOrDefault(i => i.HasImage(type));
- }
- }
-}
diff --git a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs
deleted file mode 100644
index beb2fb11d..000000000
--- a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Session;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.Session
-{
- /// <summary>
- /// Class SessionInfoWebSocketListener
- /// </summary>
- public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState>
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- protected override string Name => "Sessions";
-
- /// <summary>
- /// The _kernel
- /// </summary>
- private readonly ISessionManager _sessionManager;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SessionInfoWebSocketListener"/> class.
- /// </summary>
- public SessionInfoWebSocketListener(ILogger logger, ISessionManager sessionManager)
- : base(logger)
- {
- _sessionManager = sessionManager;
-
- _sessionManager.SessionStarted += _sessionManager_SessionStarted;
- _sessionManager.SessionEnded += _sessionManager_SessionEnded;
- _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
- _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress;
- _sessionManager.CapabilitiesChanged += _sessionManager_CapabilitiesChanged;
- _sessionManager.SessionActivity += _sessionManager_SessionActivity;
- }
-
- void _sessionManager_SessionActivity(object sender, SessionEventArgs e)
- {
- SendData(false);
- }
-
- void _sessionManager_CapabilitiesChanged(object sender, SessionEventArgs e)
- {
- SendData(true);
- }
-
- void _sessionManager_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
- {
- SendData(!e.IsAutomated);
- }
-
- void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
- {
- SendData(true);
- }
-
- void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
- {
- SendData(true);
- }
-
- void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
- {
- SendData(true);
- }
-
- void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
- {
- SendData(true);
- }
-
- /// <summary>
- /// Gets the data to send.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>Task{SystemInfo}.</returns>
- protected override Task<IEnumerable<SessionInfo>> GetDataToSend(WebSocketListenerState state, CancellationToken cancellationToken)
- {
- return Task.FromResult(_sessionManager.Sessions);
- }
-
- protected override void Dispose(bool dispose)
- {
- _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
- _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
- _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
- _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
- _sessionManager.PlaybackProgress -= _sessionManager_PlaybackProgress;
- _sessionManager.CapabilitiesChanged -= _sessionManager_CapabilitiesChanged;
- _sessionManager.SessionActivity -= _sessionManager_SessionActivity;
-
- base.Dispose(dispose);
- }
- }
-}
diff --git a/MediaBrowser.Api/Session/SessionsService.cs b/MediaBrowser.Api/Session/SessionsService.cs
deleted file mode 100644
index f011e6e41..000000000
--- a/MediaBrowser.Api/Session/SessionsService.cs
+++ /dev/null
@@ -1,519 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Session;
-
-namespace MediaBrowser.Api.Session
-{
- /// <summary>
- /// Class GetSessions
- /// </summary>
- [Route("/Sessions", "GET", Summary = "Gets a list of sessions")]
- [Authenticated]
- public class GetSessions : IReturn<SessionInfo[]>
- {
- [ApiMember(Name = "ControllableByUserId", Description = "Optional. Filter by sessions that a given user is allowed to remote control.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid ControllableByUserId { get; set; }
-
- [ApiMember(Name = "DeviceId", Description = "Optional. Filter by device id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string DeviceId { get; set; }
-
- public int? ActiveWithinSeconds { get; set; }
- }
-
- /// <summary>
- /// Class DisplayContent
- /// </summary>
- [Route("/Sessions/{Id}/Viewing", "POST", Summary = "Instructs a session to browse to an item or view")]
- [Authenticated]
- public class DisplayContent : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Artist, Genre, Studio, Person, or any kind of BaseItem
- /// </summary>
- /// <value>The type of the item.</value>
- [ApiMember(Name = "ItemType", Description = "The type of item to browse to.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ItemType { get; set; }
-
- /// <summary>
- /// Artist name, genre name, item Id, etc
- /// </summary>
- /// <value>The item identifier.</value>
- [ApiMember(Name = "ItemId", Description = "The Id of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ItemId { get; set; }
-
- /// <summary>
- /// Gets or sets the name of the item.
- /// </summary>
- /// <value>The name of the item.</value>
- [ApiMember(Name = "ItemName", Description = "The name of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string ItemName { get; set; }
- }
-
- [Route("/Sessions/{Id}/Playing", "POST", Summary = "Instructs a session to play an item")]
- [Authenticated]
- public class Play : PlayRequest
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Sessions/{Id}/Playing/{Command}", "POST", Summary = "Issues a playstate command to a client")]
- [Authenticated]
- public class SendPlaystateCommand : PlaystateRequest, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Sessions/{Id}/System/{Command}", "POST", Summary = "Issues a system command to a client")]
- [Authenticated]
- public class SendSystemCommand : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the command.
- /// </summary>
- /// <value>The play command.</value>
- [ApiMember(Name = "Command", Description = "The command to send.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Command { get; set; }
- }
-
- [Route("/Sessions/{Id}/Command/{Command}", "POST", Summary = "Issues a system command to a client")]
- [Authenticated]
- public class SendGeneralCommand : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the command.
- /// </summary>
- /// <value>The play command.</value>
- [ApiMember(Name = "Command", Description = "The command to send.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Command { get; set; }
- }
-
- [Route("/Sessions/{Id}/Command", "POST", Summary = "Issues a system command to a client")]
- [Authenticated]
- public class SendFullGeneralCommand : GeneralCommand, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Sessions/{Id}/Message", "POST", Summary = "Issues a command to a client to display a message to the user")]
- [Authenticated]
- public class SendMessageCommand : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "Text", Description = "The message text.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Text { get; set; }
-
- [ApiMember(Name = "Header", Description = "The message header.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Header { get; set; }
-
- [ApiMember(Name = "TimeoutMs", Description = "The message timeout. If omitted the user will have to confirm viewing the message.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public long? TimeoutMs { get; set; }
- }
-
- [Route("/Sessions/{Id}/Users/{UserId}", "POST", Summary = "Adds an additional user to a session")]
- [Authenticated]
- public class AddUserToSession : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "UserId Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
- }
-
- [Route("/Sessions/{Id}/Users/{UserId}", "DELETE", Summary = "Removes an additional user from a session")]
- [Authenticated]
- public class RemoveUserFromSession : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "UserId", Description = "UserId Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
- }
-
- [Route("/Sessions/Capabilities", "POST", Summary = "Updates capabilities for a device")]
- [Authenticated]
- public class PostCapabilities : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "PlayableMediaTypes", Description = "A list of playable media types, comma delimited. Audio, Video, Book, Photo.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string PlayableMediaTypes { get; set; }
-
- [ApiMember(Name = "SupportedCommands", Description = "A list of supported remote control commands, comma delimited", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string SupportedCommands { get; set; }
-
- [ApiMember(Name = "SupportsMediaControl", Description = "Determines whether media can be played remotely.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
- public bool SupportsMediaControl { get; set; }
-
- [ApiMember(Name = "SupportsSync", Description = "Determines whether sync is supported.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
- public bool SupportsSync { get; set; }
-
- [ApiMember(Name = "SupportsPersistentIdentifier", Description = "Determines whether the device supports a unique identifier.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
- public bool SupportsPersistentIdentifier { get; set; }
-
- public PostCapabilities()
- {
- SupportsPersistentIdentifier = true;
- }
- }
-
- [Route("/Sessions/Capabilities/Full", "POST", Summary = "Updates capabilities for a device")]
- [Authenticated]
- public class PostFullCapabilities : ClientCapabilities, IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string Id { get; set; }
- }
-
- [Route("/Sessions/Logout", "POST", Summary = "Reports that a session has ended")]
- [Authenticated]
- public class ReportSessionEnded : IReturnVoid
- {
- }
-
- [Route("/Auth/Keys", "GET")]
- [Authenticated(Roles = "Admin")]
- public class GetApiKeys
- {
- }
-
- [Route("/Auth/Providers", "GET")]
- [Authenticated(Roles = "Admin")]
- public class GetAuthProviders : IReturn<NameIdPair[]>
- {
- }
-
- [Route("/Auth/Keys/{Key}", "DELETE")]
- [Authenticated(Roles = "Admin")]
- public class RevokeKey
- {
- [ApiMember(Name = "Key", Description = "Auth Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Key { get; set; }
- }
-
- [Route("/Auth/Keys", "POST")]
- [Authenticated(Roles = "Admin")]
- public class CreateKey
- {
- [ApiMember(Name = "App", Description = "App", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string App { get; set; }
- }
-
- /// <summary>
- /// Class SessionsService
- /// </summary>
- public class SessionsService : BaseApiService
- {
- /// <summary>
- /// The _session manager
- /// </summary>
- private readonly ISessionManager _sessionManager;
-
- private readonly IUserManager _userManager;
- private readonly IAuthorizationContext _authContext;
- private readonly IAuthenticationRepository _authRepo;
- private readonly IDeviceManager _deviceManager;
- private readonly ISessionContext _sessionContext;
- private IServerApplicationHost _appHost;
-
- public SessionsService(ISessionManager sessionManager, IServerApplicationHost appHost, IUserManager userManager, IAuthorizationContext authContext, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionContext sessionContext)
- {
- _sessionManager = sessionManager;
- _userManager = userManager;
- _authContext = authContext;
- _authRepo = authRepo;
- _deviceManager = deviceManager;
- _sessionContext = sessionContext;
- _appHost = appHost;
- }
-
- public object Get(GetAuthProviders request)
- {
- return _userManager.GetAuthenticationProviders();
- }
-
- public void Delete(RevokeKey request)
- {
- _sessionManager.RevokeToken(request.Key);
-
- }
-
- public void Post(CreateKey request)
- {
- _authRepo.Create(new AuthenticationInfo
- {
- AppName = request.App,
- AccessToken = Guid.NewGuid().ToString("N"),
- DateCreated = DateTime.UtcNow,
- DeviceId = _appHost.SystemId,
- DeviceName = _appHost.FriendlyName,
- AppVersion = _appHost.ApplicationVersion
- });
- }
-
- public void Post(ReportSessionEnded request)
- {
- var auth = _authContext.GetAuthorizationInfo(Request);
-
- _sessionManager.Logout(auth.Token);
- }
-
- public object Get(GetApiKeys request)
- {
- var result = _authRepo.Get(new AuthenticationInfoQuery
- {
- HasUser = false
- });
-
- return result;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetSessions request)
- {
- var result = _sessionManager.Sessions;
-
- if (!string.IsNullOrEmpty(request.DeviceId))
- {
- result = result.Where(i => string.Equals(i.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase));
- }
-
- if (!request.ControllableByUserId.Equals(Guid.Empty))
- {
- result = result.Where(i => i.SupportsRemoteControl);
-
- var user = _userManager.GetUserById(request.ControllableByUserId);
-
- if (!user.Policy.EnableRemoteControlOfOtherUsers)
- {
- result = result.Where(i => i.UserId.Equals(Guid.Empty) || i.ContainsUser(request.ControllableByUserId));
- }
-
- if (!user.Policy.EnableSharedDeviceControl)
- {
- result = result.Where(i => !i.UserId.Equals(Guid.Empty));
- }
-
- if (request.ActiveWithinSeconds.HasValue && request.ActiveWithinSeconds.Value > 0)
- {
- var minActiveDate = DateTime.UtcNow.AddSeconds(0 - request.ActiveWithinSeconds.Value);
- result = result.Where(i => i.LastActivityDate >= minActiveDate);
- }
-
- result = result.Where(i =>
- {
- var deviceId = i.DeviceId;
-
- if (!string.IsNullOrWhiteSpace(deviceId))
- {
- if (!_deviceManager.CanAccessDevice(user, deviceId))
- {
- return false;
- }
- }
-
- return true;
- });
- }
-
- return ToOptimizedResult(result.ToArray());
- }
-
- public Task Post(SendPlaystateCommand request)
- {
- return _sessionManager.SendPlaystateCommand(GetSession(_sessionContext).Id, request.Id, request, CancellationToken.None);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(DisplayContent request)
- {
- var command = new BrowseRequest
- {
- ItemId = request.ItemId,
- ItemName = request.ItemName,
- ItemType = request.ItemType
- };
-
- return _sessionManager.SendBrowseCommand(GetSession(_sessionContext).Id, request.Id, command, CancellationToken.None);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(SendSystemCommand request)
- {
- var name = request.Command;
-
- if (Enum.TryParse(name, true, out GeneralCommandType commandType))
- {
- name = commandType.ToString();
- }
-
- var currentSession = GetSession(_sessionContext);
-
- var command = new GeneralCommand
- {
- Name = name,
- ControllingUserId = currentSession.UserId
- };
-
- return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(SendMessageCommand request)
- {
- var command = new MessageCommand
- {
- Header = string.IsNullOrEmpty(request.Header) ? "Message from Server" : request.Header,
- TimeoutMs = request.TimeoutMs,
- Text = request.Text
- };
-
- return _sessionManager.SendMessageCommand(GetSession(_sessionContext).Id, request.Id, command, CancellationToken.None);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(Play request)
- {
- return _sessionManager.SendPlayCommand(GetSession(_sessionContext).Id, request.Id, request, CancellationToken.None);
- }
-
- public Task Post(SendGeneralCommand request)
- {
- var currentSession = GetSession(_sessionContext);
-
- var command = new GeneralCommand
- {
- Name = request.Command,
- ControllingUserId = currentSession.UserId
- };
-
- return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
- }
-
- public Task Post(SendFullGeneralCommand request)
- {
- var currentSession = GetSession(_sessionContext);
-
- request.ControllingUserId = currentSession.UserId;
-
- return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, request, CancellationToken.None);
- }
-
- public void Post(AddUserToSession request)
- {
- _sessionManager.AddAdditionalUser(request.Id, new Guid(request.UserId));
- }
-
- public void Delete(RemoveUserFromSession request)
- {
- _sessionManager.RemoveAdditionalUser(request.Id, new Guid(request.UserId));
- }
-
- public void Post(PostCapabilities request)
- {
- if (string.IsNullOrWhiteSpace(request.Id))
- {
- request.Id = GetSession(_sessionContext).Id;
- }
- _sessionManager.ReportCapabilities(request.Id, new ClientCapabilities
- {
- PlayableMediaTypes = SplitValue(request.PlayableMediaTypes, ','),
-
- SupportedCommands = SplitValue(request.SupportedCommands, ','),
-
- SupportsMediaControl = request.SupportsMediaControl,
-
- SupportsSync = request.SupportsSync,
-
- SupportsPersistentIdentifier = request.SupportsPersistentIdentifier
- });
- }
-
- public void Post(PostFullCapabilities request)
- {
- if (string.IsNullOrWhiteSpace(request.Id))
- {
- request.Id = GetSession(_sessionContext).Id;
- }
- _sessionManager.ReportCapabilities(request.Id, request);
- }
- }
-}
diff --git a/MediaBrowser.Api/SimilarItemsHelper.cs b/MediaBrowser.Api/SimilarItemsHelper.cs
deleted file mode 100644
index 44bb24ef2..000000000
--- a/MediaBrowser.Api/SimilarItemsHelper.cs
+++ /dev/null
@@ -1,223 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class BaseGetSimilarItemsFromItem
- /// </summary>
- public class BaseGetSimilarItemsFromItem : BaseGetSimilarItems
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- public string ExcludeArtistIds { get; set; }
- }
-
- public class BaseGetSimilarItems : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
- }
-
- /// <summary>
- /// Class SimilarItemsHelper
- /// </summary>
- public static class SimilarItemsHelper
- {
- internal static QueryResult<BaseItemDto> GetSimilarItemsResult(DtoOptions dtoOptions, IUserManager userManager, IItemRepository itemRepository, ILibraryManager libraryManager, IUserDataManager userDataRepository, IDtoService dtoService, ILogger logger, BaseGetSimilarItemsFromItem request, Type[] includeTypes, Func<BaseItem, List<PersonInfo>, List<PersonInfo>, BaseItem, int> getSimilarityScore)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id) ?
- (!request.UserId.Equals(Guid.Empty) ? libraryManager.GetUserRootFolder() :
- libraryManager.RootFolder) : libraryManager.GetItemById(request.Id);
-
- var query = new InternalItemsQuery(user)
- {
- IncludeItemTypes = includeTypes.Select(i => i.Name).ToArray(),
- Recursive = true,
- DtoOptions = dtoOptions
- };
-
- // ExcludeArtistIds
- if (!string.IsNullOrEmpty(request.ExcludeArtistIds))
- {
- query.ExcludeArtistIds = BaseApiService.GetGuids(request.ExcludeArtistIds);
- }
-
- var inputItems = libraryManager.GetItemList(query);
-
- var items = GetSimilaritems(item, libraryManager, inputItems, getSimilarityScore)
- .ToList();
-
- var returnItems = items;
-
- if (request.Limit.HasValue)
- {
- returnItems = returnItems.Take(request.Limit.Value).ToList();
- }
-
- var dtos = dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
-
- return new QueryResult<BaseItemDto>
- {
- Items = dtos,
-
- TotalRecordCount = items.Count
- };
- }
-
- /// <summary>
- /// Gets the similaritems.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="inputItems">The input items.</param>
- /// <param name="getSimilarityScore">The get similarity score.</param>
- /// <returns>IEnumerable{BaseItem}.</returns>
- internal static IEnumerable<BaseItem> GetSimilaritems(BaseItem item, ILibraryManager libraryManager, IEnumerable<BaseItem> inputItems, Func<BaseItem, List<PersonInfo>, List<PersonInfo>, BaseItem, int> getSimilarityScore)
- {
- var itemId = item.Id;
- inputItems = inputItems.Where(i => i.Id != itemId);
- var itemPeople = libraryManager.GetPeople(item);
- var allPeople = libraryManager.GetPeople(new InternalPeopleQuery
- {
- AppearsInItemId = item.Id
- });
-
- return inputItems.Select(i => new Tuple<BaseItem, int>(i, getSimilarityScore(item, itemPeople, allPeople, i)))
- .Where(i => i.Item2 > 2)
- .OrderByDescending(i => i.Item2)
- .Select(i => i.Item1);
- }
-
- private static IEnumerable<string> GetTags(BaseItem item)
- {
- return item.Tags;
- }
-
- /// <summary>
- /// Gets the similiarity score.
- /// </summary>
- /// <param name="item1">The item1.</param>
- /// <param name="item1People">The item1 people.</param>
- /// <param name="allPeople">All people.</param>
- /// <param name="item2">The item2.</param>
- /// <returns>System.Int32.</returns>
- internal static int GetSimiliarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2)
- {
- var points = 0;
-
- if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase))
- {
- points += 10;
- }
-
- // Find common genres
- points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
-
- // Find common tags
- points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
-
- // Find common studios
- points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 3);
-
- var item2PeopleNames = allPeople.Where(i => i.ItemId == item2.Id)
- .Select(i => i.Name)
- .Where(i => !string.IsNullOrWhiteSpace(i))
- .DistinctNames()
- .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
-
- points += item1People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i =>
- {
- if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
- {
- return 5;
- }
- if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
-
- return 1;
- });
-
- if (item1.ProductionYear.HasValue && item2.ProductionYear.HasValue)
- {
- var diff = Math.Abs(item1.ProductionYear.Value - item2.ProductionYear.Value);
-
- // Add if they came out within the same decade
- if (diff < 10)
- {
- points += 2;
- }
-
- // And more if within five years
- if (diff < 5)
- {
- points += 2;
- }
- }
-
- return points;
- }
-
- }
-}
diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs
deleted file mode 100644
index 53ba7eefd..000000000
--- a/MediaBrowser.Api/StartupWizardService.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Startup/Complete", "POST", Summary = "Reports that the startup wizard has been completed", IsHidden = true)]
- public class ReportStartupWizardComplete : IReturnVoid
- {
- }
-
- [Route("/Startup/Configuration", "GET", Summary = "Gets initial server configuration", IsHidden = true)]
- public class GetStartupConfiguration : IReturn<StartupConfiguration>
- {
- }
-
- [Route("/Startup/Configuration", "POST", Summary = "Updates initial server configuration", IsHidden = true)]
- public class UpdateStartupConfiguration : StartupConfiguration, IReturnVoid
- {
- }
-
- [Route("/Startup/RemoteAccess", "POST", Summary = "Updates initial server configuration", IsHidden = true)]
- public class UpdateRemoteAccessConfiguration : IReturnVoid
- {
- public bool EnableRemoteAccess { get; set; }
- public bool EnableAutomaticPortMapping { get; set; }
- }
-
- [Route("/Startup/User", "GET", Summary = "Gets initial user info", IsHidden = true)]
- public class GetStartupUser : IReturn<StartupUser>
- {
- }
-
- [Route("/Startup/User", "POST", Summary = "Updates initial user info", IsHidden = true)]
- public class UpdateStartupUser : StartupUser
- {
- }
-
- [Authenticated(AllowBeforeStartupWizard = true, Roles = "Admin")]
- public class StartupWizardService : BaseApiService
- {
- private readonly IServerConfigurationManager _config;
- private readonly IServerApplicationHost _appHost;
- private readonly IUserManager _userManager;
- private readonly IMediaEncoder _mediaEncoder;
- private readonly IHttpClient _httpClient;
-
- public StartupWizardService(IServerConfigurationManager config, IHttpClient httpClient, IServerApplicationHost appHost, IUserManager userManager, IMediaEncoder mediaEncoder)
- {
- _config = config;
- _appHost = appHost;
- _userManager = userManager;
- _mediaEncoder = mediaEncoder;
- _httpClient = httpClient;
- }
-
- public void Post(ReportStartupWizardComplete request)
- {
- _config.Configuration.IsStartupWizardCompleted = true;
- _config.SetOptimalValues();
- _config.SaveConfiguration();
- }
-
- public object Get(GetStartupConfiguration request)
- {
- var result = new StartupConfiguration
- {
- UICulture = _config.Configuration.UICulture,
- MetadataCountryCode = _config.Configuration.MetadataCountryCode,
- PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage
- };
-
- return result;
- }
-
- public void Post(UpdateStartupConfiguration request)
- {
- _config.Configuration.UICulture = request.UICulture;
- _config.Configuration.MetadataCountryCode = request.MetadataCountryCode;
- _config.Configuration.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
- _config.SaveConfiguration();
- }
-
- public void Post(UpdateRemoteAccessConfiguration request)
- {
- _config.Configuration.EnableRemoteAccess = request.EnableRemoteAccess;
- _config.Configuration.EnableUPnP = request.EnableAutomaticPortMapping;
- _config.SaveConfiguration();
- }
-
- public object Get(GetStartupUser request)
- {
- var user = _userManager.Users.First();
-
- return new StartupUser
- {
- Name = user.Name,
- Password = user.Password
- };
- }
-
- public async Task Post(UpdateStartupUser request)
- {
- var user = _userManager.Users.First();
-
- user.Name = request.Name;
-
- _userManager.UpdateUser(user);
-
- if (!string.IsNullOrEmpty(request.Password)) {
- await _userManager.ChangePassword(user, request.Password).ConfigureAwait(false);
- }
- }
- }
-
- public class StartupConfiguration
- {
- public string UICulture { get; set; }
- public string MetadataCountryCode { get; set; }
- public string PreferredMetadataLanguage { get; set; }
- }
-
- public class StartupUser
- {
- public string Name { get; set; }
- public string Password { get; set; }
- }
-}
diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs
deleted file mode 100644
index 08aa540a5..000000000
--- a/MediaBrowser.Api/Subtitles/SubtitleService.cs
+++ /dev/null
@@ -1,292 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
-
-namespace MediaBrowser.Api.Subtitles
-{
- [Route("/Videos/{Id}/Subtitles/{Index}", "DELETE", Summary = "Deletes an external subtitle file")]
- [Authenticated(Roles = "Admin")]
- public class DeleteSubtitle
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "DELETE")]
- public int Index { get; set; }
- }
-
- [Route("/Items/{Id}/RemoteSearch/Subtitles/{Language}", "GET")]
- [Authenticated]
- public class SearchRemoteSubtitles : IReturn<RemoteSubtitleInfo[]>
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Language { get; set; }
-
- public bool? IsPerfectMatch { get; set; }
- }
-
- [Route("/Items/{Id}/RemoteSearch/Subtitles/{SubtitleId}", "POST")]
- [Authenticated]
- public class DownloadRemoteSubtitles : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "SubtitleId", Description = "SubtitleId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string SubtitleId { get; set; }
- }
-
- [Route("/Providers/Subtitles/Subtitles/{Id}", "GET")]
- [Authenticated]
- public class GetRemoteSubtitles : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
- [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/{StartPositionTicks}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
- public class GetSubtitle
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string MediaSourceId { get; set; }
-
- [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
- public int Index { get; set; }
-
- [ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Format { get; set; }
-
- [ApiMember(Name = "StartPositionTicks", Description = "StartPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public long StartPositionTicks { get; set; }
-
- [ApiMember(Name = "EndPositionTicks", Description = "EndPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public long? EndPositionTicks { get; set; }
-
- [ApiMember(Name = "CopyTimestamps", Description = "CopyTimestamps", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool CopyTimestamps { get; set; }
- public bool AddVttTimeMap { get; set; }
- }
-
- [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/subtitles.m3u8", "GET", Summary = "Gets an HLS subtitle playlist.")]
- [Authenticated]
- public class GetSubtitlePlaylist
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string MediaSourceId { get; set; }
-
- [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
- public int Index { get; set; }
-
- [ApiMember(Name = "SegmentLength", Description = "The subtitle srgment length", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int SegmentLength { get; set; }
- }
-
- public class SubtitleService : BaseApiService
- {
- private readonly ILibraryManager _libraryManager;
- private readonly ISubtitleManager _subtitleManager;
- private readonly ISubtitleEncoder _subtitleEncoder;
- private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IProviderManager _providerManager;
- private readonly IFileSystem _fileSystem;
- private readonly IAuthorizationContext _authContext;
-
- public SubtitleService(ILibraryManager libraryManager, ISubtitleManager subtitleManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IProviderManager providerManager, IFileSystem fileSystem, IAuthorizationContext authContext)
- {
- _libraryManager = libraryManager;
- _subtitleManager = subtitleManager;
- _subtitleEncoder = subtitleEncoder;
- _mediaSourceManager = mediaSourceManager;
- _providerManager = providerManager;
- _fileSystem = fileSystem;
- _authContext = authContext;
- }
-
- public async Task<object> Get(GetSubtitlePlaylist request)
- {
- var item = (Video)_libraryManager.GetItemById(new Guid(request.Id));
-
- var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
-
- var builder = new StringBuilder();
-
- var runtime = mediaSource.RunTimeTicks ?? -1;
-
- if (runtime <= 0)
- {
- throw new ArgumentException("HLS Subtitles are not supported for this media.");
- }
-
- var segmentLengthTicks = TimeSpan.FromSeconds(request.SegmentLength).Ticks;
- if (segmentLengthTicks <= 0)
- {
- throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
- }
-
- builder.AppendLine("#EXTM3U");
- builder.AppendLine("#EXT-X-TARGETDURATION:" + request.SegmentLength.ToString(CultureInfo.InvariantCulture));
- builder.AppendLine("#EXT-X-VERSION:3");
- builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
- builder.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
-
- long positionTicks = 0;
-
- var accessToken = _authContext.GetAuthorizationInfo(Request).Token;
-
- while (positionTicks < runtime)
- {
- var remaining = runtime - positionTicks;
- var lengthTicks = Math.Min(remaining, segmentLengthTicks);
-
- builder.AppendLine("#EXTINF:" + TimeSpan.FromTicks(lengthTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture) + ",");
-
- var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
-
- var url = string.Format("stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
- positionTicks.ToString(CultureInfo.InvariantCulture),
- endPositionTicks.ToString(CultureInfo.InvariantCulture),
- accessToken);
-
- builder.AppendLine(url);
-
- positionTicks += segmentLengthTicks;
- }
-
- builder.AppendLine("#EXT-X-ENDLIST");
-
- return ResultFactory.GetResult(Request, builder.ToString(), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
- }
-
- public async Task<object> Get(GetSubtitle request)
- {
- if (string.Equals(request.Format, "js", StringComparison.OrdinalIgnoreCase))
- {
- request.Format = "json";
- }
- if (string.IsNullOrEmpty(request.Format))
- {
- var item = (Video)_libraryManager.GetItemById(request.Id);
-
- var idString = request.Id.ToString("N");
- var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false, null)
- .First(i => string.Equals(i.Id, request.MediaSourceId ?? idString));
-
- var subtitleStream = mediaSource.MediaStreams
- .First(i => i.Type == MediaStreamType.Subtitle && i.Index == request.Index);
-
- return await ResultFactory.GetStaticFileResult(Request, subtitleStream.Path).ConfigureAwait(false);
- }
-
- if (string.Equals(request.Format, "vtt", StringComparison.OrdinalIgnoreCase) && request.AddVttTimeMap)
- {
- using (var stream = await GetSubtitles(request).ConfigureAwait(false))
- {
- using (var reader = new StreamReader(stream))
- {
- var text = reader.ReadToEnd();
-
- text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000");
-
- return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format));
- }
- }
- }
-
- return ResultFactory.GetResult(Request, await GetSubtitles(request).ConfigureAwait(false), MimeTypes.GetMimeType("file." + request.Format));
- }
-
- private Task<Stream> GetSubtitles(GetSubtitle request)
- {
- var item = _libraryManager.GetItemById(request.Id);
-
- return _subtitleEncoder.GetSubtitles(item,
- request.MediaSourceId,
- request.Index,
- request.Format,
- request.StartPositionTicks,
- request.EndPositionTicks ?? 0,
- request.CopyTimestamps,
- CancellationToken.None);
- }
-
- public async Task<object> Get(SearchRemoteSubtitles request)
- {
- var video = (Video)_libraryManager.GetItemById(request.Id);
-
- return await _subtitleManager.SearchSubtitles(video, request.Language, request.IsPerfectMatch, CancellationToken.None).ConfigureAwait(false);
- }
-
- public Task Delete(DeleteSubtitle request)
- {
- var item = _libraryManager.GetItemById(request.Id);
- return _subtitleManager.DeleteSubtitles(item, request.Index);
- }
-
- public async Task<object> Get(GetRemoteSubtitles request)
- {
- var result = await _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).ConfigureAwait(false);
-
- return ResultFactory.GetResult(Request, result.Stream, MimeTypes.GetMimeType("file." + result.Format));
- }
-
- public void Post(DownloadRemoteSubtitles request)
- {
- var video = (Video)_libraryManager.GetItemById(request.Id);
-
- Task.Run(async () =>
- {
- try
- {
- await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None)
- .ConfigureAwait(false);
-
- _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error downloading subtitles");
- }
-
- });
- }
- }
-}
diff --git a/MediaBrowser.Api/SuggestionsService.cs b/MediaBrowser.Api/SuggestionsService.cs
deleted file mode 100644
index 72fdae365..000000000
--- a/MediaBrowser.Api/SuggestionsService.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Users/{UserId}/Suggestions", "GET", Summary = "Gets items based on a query.")]
- public class GetSuggestedItems : IReturn<QueryResult<BaseItemDto>>
- {
- public string MediaType { get; set; }
- public string Type { get; set; }
- public Guid UserId { get; set; }
- public bool EnableTotalRecordCount { get; set; }
- public int? StartIndex { get; set; }
- public int? Limit { get; set; }
-
- public string[] GetMediaTypes()
- {
- return (MediaType ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetIncludeItemTypes()
- {
- return (Type ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
- }
-
- public class SuggestionsService : BaseApiService
- {
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
- private readonly IUserManager _userManager;
- private readonly ILibraryManager _libraryManager;
-
- public SuggestionsService(IDtoService dtoService, IAuthorizationContext authContext, IUserManager userManager, ILibraryManager libraryManager)
- {
- _dtoService = dtoService;
- _authContext = authContext;
- _userManager = userManager;
- _libraryManager = libraryManager;
- }
-
- public object Get(GetSuggestedItems request)
- {
- return GetResultItems(request);
- }
-
- private QueryResult<BaseItemDto> GetResultItems(GetSuggestedItems request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var dtoOptions = GetDtoOptions(_authContext, request);
- var result = GetItems(request, user, dtoOptions);
-
- var dtoList = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user);
-
- if (dtoList == null)
- {
- throw new InvalidOperationException("GetBaseItemDtos returned null");
- }
-
- return new QueryResult<BaseItemDto>
- {
- TotalRecordCount = result.TotalRecordCount,
- Items = dtoList
- };
- }
-
- private QueryResult<BaseItem> GetItems(GetSuggestedItems request, User user, DtoOptions dtoOptions)
- {
- return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
- {
- OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(),
- MediaTypes = request.GetMediaTypes(),
- IncludeItemTypes = request.GetIncludeItemTypes(),
- IsVirtualItem = false,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- DtoOptions = dtoOptions,
- EnableTotalRecordCount = request.EnableTotalRecordCount,
- Recursive = true
- });
- }
- }
-}
diff --git a/MediaBrowser.Api/System/ActivityLogService.cs b/MediaBrowser.Api/System/ActivityLogService.cs
deleted file mode 100644
index 4d6ce1014..000000000
--- a/MediaBrowser.Api/System/ActivityLogService.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using System;
-using System.Globalization;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.System
-{
- [Route("/System/ActivityLog/Entries", "GET", Summary = "Gets activity log entries")]
- public class GetActivityLogs : IReturn<QueryResult<ActivityLogEntry>>
- {
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "MinDate", Description = "Optional. The minimum date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MinDate { get; set; }
-
- public bool? HasUserId { get; set; }
- }
-
- [Authenticated(Roles = "Admin")]
- public class ActivityLogService : BaseApiService
- {
- private readonly IActivityManager _activityManager;
-
- public ActivityLogService(IActivityManager activityManager)
- {
- _activityManager = activityManager;
- }
-
- public object Get(GetActivityLogs request)
- {
- DateTime? minDate = string.IsNullOrWhiteSpace(request.MinDate) ?
- (DateTime?)null :
- DateTime.Parse(request.MinDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
-
- var result = _activityManager.GetActivityLogEntries(minDate, request.HasUserId, request.StartIndex, request.Limit);
-
- return ToOptimizedResult(result);
- }
- }
-}
diff --git a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs
deleted file mode 100644
index 43f3c5a22..000000000
--- a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Events;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.System
-{
- /// <summary>
- /// Class SessionInfoWebSocketListener
- /// </summary>
- public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<List<ActivityLogEntry>, WebSocketListenerState>
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- protected override string Name => "ActivityLogEntry";
-
- /// <summary>
- /// The _kernel
- /// </summary>
- private readonly IActivityManager _activityManager;
-
- public ActivityLogWebSocketListener(ILogger logger, IActivityManager activityManager) : base(logger)
- {
- _activityManager = activityManager;
- _activityManager.EntryCreated += _activityManager_EntryCreated;
- }
-
- void _activityManager_EntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e)
- {
- SendData(true);
- }
-
- /// <summary>
- /// Gets the data to send.
- /// </summary>
- /// <param name="state">The state.</param>
- /// <returns>Task{SystemInfo}.</returns>
- protected override Task<List<ActivityLogEntry>> GetDataToSend(WebSocketListenerState state, CancellationToken CancellationToken)
- {
- return Task.FromResult(new List<ActivityLogEntry>());
- }
-
-
- protected override void Dispose(bool dispose)
- {
- _activityManager.EntryCreated -= _activityManager_EntryCreated;
-
- base.Dispose(dispose);
- }
- }
-}
diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs
deleted file mode 100644
index 56184e18b..000000000
--- a/MediaBrowser.Api/System/SystemService.cs
+++ /dev/null
@@ -1,222 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.System
-{
- /// <summary>
- /// Class GetSystemInfo
- /// </summary>
- [Route("/System/Info", "GET", Summary = "Gets information about the server")]
- [Authenticated(EscapeParentalControl = true, AllowBeforeStartupWizard = true)]
- public class GetSystemInfo : IReturn<SystemInfo>
- {
-
- }
-
- [Route("/System/Info/Public", "GET", Summary = "Gets public information about the server")]
- public class GetPublicSystemInfo : IReturn<PublicSystemInfo>
- {
-
- }
-
- [Route("/System/Ping", "POST")]
- [Route("/System/Ping", "GET")]
- public class PingSystem : IReturnVoid
- {
-
- }
-
- /// <summary>
- /// Class RestartApplication
- /// </summary>
- [Route("/System/Restart", "POST", Summary = "Restarts the application, if needed")]
- [Authenticated(Roles = "Admin", AllowLocal = true)]
- public class RestartApplication
- {
- }
-
- /// <summary>
- /// This is currently not authenticated because the uninstaller needs to be able to shutdown the server.
- /// </summary>
- [Route("/System/Shutdown", "POST", Summary = "Shuts down the application")]
- [Authenticated(Roles = "Admin", AllowLocal = true)]
- public class ShutdownApplication
- {
- }
-
- [Route("/System/Logs", "GET", Summary = "Gets a list of available server log files")]
- [Authenticated(Roles = "Admin")]
- public class GetServerLogs : IReturn<LogFile[]>
- {
- }
-
- [Route("/System/Endpoint", "GET", Summary = "Gets information about the request endpoint")]
- [Authenticated]
- public class GetEndpointInfo : IReturn<EndPointInfo>
- {
- public string Endpoint { get; set; }
- }
-
- [Route("/System/Logs/Log", "GET", Summary = "Gets a log file")]
- [Authenticated(Roles = "Admin")]
- public class GetLogFile
- {
- [ApiMember(Name = "Name", Description = "The log file name.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Name { get; set; }
- }
-
- [Route("/System/WakeOnLanInfo", "GET", Summary = "Gets wake on lan information")]
- [Authenticated]
- public class GetWakeOnLanInfo : IReturn<WakeOnLanInfo[]>
- {
-
- }
-
- /// <summary>
- /// Class SystemInfoService
- /// </summary>
- public class SystemService : BaseApiService
- {
- /// <summary>
- /// The _app host
- /// </summary>
- private readonly IServerApplicationHost _appHost;
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
-
- private readonly INetworkManager _network;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SystemService" /> class.
- /// </summary>
- /// <param name="appHost">The app host.</param>
- /// <param name="appPaths">The application paths.</param>
- /// <param name="fileSystem">The file system.</param>
- /// <exception cref="ArgumentNullException">jsonSerializer</exception>
- public SystemService(IServerApplicationHost appHost, IApplicationPaths appPaths, IFileSystem fileSystem, INetworkManager network)
- {
- _appHost = appHost;
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- _network = network;
- }
-
- public object Post(PingSystem request)
- {
- return _appHost.Name;
- }
-
- public object Get(GetWakeOnLanInfo request)
- {
- var result = _appHost.GetWakeOnLanInfo();
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetServerLogs request)
- {
- IEnumerable<FileSystemMetadata> files;
-
- try
- {
- files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt", ".log" }, true, false);
- }
- catch (IOException ex)
- {
- Logger.LogError(ex, "Error getting logs");
- files = Enumerable.Empty<FileSystemMetadata>();
- }
-
- var result = files.Select(i => new LogFile
- {
- DateCreated = _fileSystem.GetCreationTimeUtc(i),
- DateModified = _fileSystem.GetLastWriteTimeUtc(i),
- Name = i.Name,
- Size = i.Length
-
- }).OrderByDescending(i => i.DateModified)
- .ThenByDescending(i => i.DateCreated)
- .ThenBy(i => i.Name)
- .ToArray();
-
- return ToOptimizedResult(result);
- }
-
- public Task<object> Get(GetLogFile request)
- {
- var file = _fileSystem.GetFiles(_appPaths.LogDirectoryPath)
- .First(i => string.Equals(i.Name, request.Name, StringComparison.OrdinalIgnoreCase));
-
- // For older files, assume fully static
- if (file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1))
- {
- return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShareMode.Read);
- }
-
- return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShareMode.ReadWrite);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetSystemInfo request)
- {
- var result = await _appHost.GetSystemInfo(CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- public async Task<object> Get(GetPublicSystemInfo request)
- {
- var result = await _appHost.GetPublicSystemInfo(CancellationToken.None).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(RestartApplication request)
- {
- _appHost.Restart();
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(ShutdownApplication request)
- {
- Task.Run(async () =>
- {
- await Task.Delay(100).ConfigureAwait(false);
- await _appHost.Shutdown().ConfigureAwait(false);
- });
- }
-
- public object Get(GetEndpointInfo request)
- {
- return ToOptimizedResult(new EndPointInfo
- {
- IsLocal = Request.IsLocal,
- IsInNetwork = _network.IsInLocalNetwork(request.Endpoint ?? Request.RemoteIp)
- });
- }
- }
-}
diff --git a/MediaBrowser.Api/TvShowsService.cs b/MediaBrowser.Api/TvShowsService.cs
deleted file mode 100644
index b0900a554..000000000
--- a/MediaBrowser.Api/TvShowsService.cs
+++ /dev/null
@@ -1,503 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.TV;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetNextUpEpisodes
- /// </summary>
- [Route("/Shows/NextUp", "GET", Summary = "Gets a list of next up episodes")]
- public class GetNextUpEpisodes : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "SeriesId", Description = "Optional. Filter by series id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SeriesId { get; set; }
-
- /// <summary>
- /// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// </summary>
- /// <value>The parent id.</value>
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
- public bool EnableTotalRecordCount { get; set; }
-
- public GetNextUpEpisodes()
- {
- EnableTotalRecordCount = true;
- }
- }
-
- [Route("/Shows/Upcoming", "GET", Summary = "Gets a list of upcoming episodes")]
- public class GetUpcomingEpisodes : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- /// <summary>
- /// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// </summary>
- /// <value>The parent id.</value>
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
- }
-
- [Route("/Shows/{Id}/Episodes", "GET", Summary = "Gets episodes for a tv season")]
- public class GetEpisodes : IReturn<QueryResult<BaseItemDto>>, IHasItemFields, IHasDtoOptions
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "Id", Description = "The series id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "Season", Description = "Optional filter by season number.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public int? Season { get; set; }
-
- [ApiMember(Name = "SeasonId", Description = "Optional. Filter by season id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SeasonId { get; set; }
-
- [ApiMember(Name = "IsMissing", Description = "Optional filter by items that are missing episodes or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsMissing { get; set; }
-
- [ApiMember(Name = "AdjacentTo", Description = "Optional. Return items that are siblings of a supplied item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string AdjacentTo { get; set; }
-
- [ApiMember(Name = "StartItemId", Description = "Optional. Skip through the list until a given item is found.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string StartItemId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- [ApiMember(Name = "SortBy", Description = "Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string SortBy { get; set; }
-
- [ApiMember(Name = "SortOrder", Description = "Sort Order - Ascending,Descending", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public SortOrder? SortOrder { get; set; }
- }
-
- [Route("/Shows/{Id}/Seasons", "GET", Summary = "Gets seasons for a tv series")]
- public class GetSeasons : IReturn<QueryResult<BaseItemDto>>, IHasItemFields, IHasDtoOptions
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "Id", Description = "The series id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Id { get; set; }
-
- [ApiMember(Name = "IsSpecialSeason", Description = "Optional. Filter by special season.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsSpecialSeason { get; set; }
-
- [ApiMember(Name = "IsMissing", Description = "Optional filter by items that are missing episodes or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsMissing { get; set; }
-
- [ApiMember(Name = "AdjacentTo", Description = "Optional. Return items that are siblings of a supplied item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string AdjacentTo { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
- }
-
- /// <summary>
- /// Class TvShowsService
- /// </summary>
- [Authenticated]
- public class TvShowsService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- /// <summary>
- /// The _user data repository
- /// </summary>
- private readonly IUserDataManager _userDataManager;
- /// <summary>
- /// The _library manager
- /// </summary>
- private readonly ILibraryManager _libraryManager;
-
- private readonly IItemRepository _itemRepo;
- private readonly IDtoService _dtoService;
- private readonly ITVSeriesManager _tvSeriesManager;
- private readonly IAuthorizationContext _authContext;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="TvShowsService" /> class.
- /// </summary>
- /// <param name="userManager">The user manager.</param>
- /// <param name="userDataManager">The user data repository.</param>
- /// <param name="libraryManager">The library manager.</param>
- public TvShowsService(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IItemRepository itemRepo, IDtoService dtoService, ITVSeriesManager tvSeriesManager, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _userDataManager = userDataManager;
- _libraryManager = libraryManager;
- _itemRepo = itemRepo;
- _dtoService = dtoService;
- _tvSeriesManager = tvSeriesManager;
- _authContext = authContext;
- }
-
- public object Get(GetUpcomingEpisodes request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var minPremiereDate = DateTime.Now.Date.ToUniversalTime().AddDays(-1);
-
- var parentIdGuid = string.IsNullOrWhiteSpace(request.ParentId) ? Guid.Empty : new Guid(request.ParentId);
-
- var options = GetDtoOptions(_authContext, request);
-
- var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user)
- {
- IncludeItemTypes = new[] { typeof(Episode).Name },
- OrderBy = new[] { ItemSortBy.PremiereDate, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
- MinPremiereDate = minPremiereDate,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- ParentId = parentIdGuid,
- Recursive = true,
- DtoOptions = options
-
- });
-
- var returnItems = _dtoService.GetBaseItemDtos(itemsResult, options, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- TotalRecordCount = itemsResult.Count,
- Items = returnItems
- };
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetNextUpEpisodes request)
- {
- var options = GetDtoOptions(_authContext, request);
-
- var result = _tvSeriesManager.GetNextUp(new NextUpQuery
- {
- Limit = request.Limit,
- ParentId = request.ParentId,
- SeriesId = request.SeriesId,
- StartIndex = request.StartIndex,
- UserId = request.UserId,
- EnableTotalRecordCount = request.EnableTotalRecordCount
- }, options);
-
- var user = _userManager.GetUserById(request.UserId);
-
- var returnItems = _dtoService.GetBaseItemDtos(result.Items, options, user);
-
- return ToOptimizedResult(new QueryResult<BaseItemDto>
- {
- TotalRecordCount = result.TotalRecordCount,
- Items = returnItems
- });
- }
-
- /// <summary>
- /// Applies the paging.
- /// </summary>
- /// <param name="items">The items.</param>
- /// <param name="startIndex">The start index.</param>
- /// <param name="limit">The limit.</param>
- /// <returns>IEnumerable{BaseItem}.</returns>
- private IEnumerable<BaseItem> ApplyPaging(IEnumerable<BaseItem> items, int? startIndex, int? limit)
- {
- // Start at
- if (startIndex.HasValue)
- {
- items = items.Skip(startIndex.Value);
- }
-
- // Return limit
- if (limit.HasValue)
- {
- items = items.Take(limit.Value);
- }
-
- return items;
- }
-
- public object Get(GetSeasons request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var series = GetSeries(request.Id, user);
-
- if (series == null)
- {
- throw new ResourceNotFoundException("Series not found");
- }
-
- var seasons = (series.GetItemList(new InternalItemsQuery(user)
- {
- IsMissing = request.IsMissing,
- IsSpecialSeason = request.IsSpecialSeason,
- AdjacentTo = request.AdjacentTo
-
- }));
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var returnItems = _dtoService.GetBaseItemDtos(seasons, dtoOptions, user);
-
- return new QueryResult<BaseItemDto>
- {
- TotalRecordCount = returnItems.Length,
- Items = returnItems
- };
- }
-
- private Series GetSeries(string seriesId, User user)
- {
- if (!string.IsNullOrWhiteSpace(seriesId))
- {
- return _libraryManager.GetItemById(seriesId) as Series;
- }
-
- return null;
- }
-
- public object Get(GetEpisodes request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- List<BaseItem> episodes;
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- if (!string.IsNullOrWhiteSpace(request.SeasonId))
- {
- var season = _libraryManager.GetItemById(new Guid(request.SeasonId)) as Season;
-
- if (season == null)
- {
- throw new ResourceNotFoundException("No season exists with Id " + request.SeasonId);
- }
-
- episodes = season.GetEpisodes(user, dtoOptions);
- }
- else if (request.Season.HasValue)
- {
- var series = GetSeries(request.Id, user);
-
- if (series == null)
- {
- throw new ResourceNotFoundException("Series not found");
- }
-
- var season = series.GetSeasons(user, dtoOptions).FirstOrDefault(i => i.IndexNumber == request.Season.Value);
-
- if (season == null)
- {
- episodes = new List<BaseItem>();
- }
- else
- {
- episodes = ((Season)season).GetEpisodes(user, dtoOptions);
- }
- }
- else
- {
- var series = GetSeries(request.Id, user);
-
- if (series == null)
- {
- throw new ResourceNotFoundException("Series not found");
- }
-
- episodes = series.GetEpisodes(user, dtoOptions).ToList();
- }
-
- // Filter after the fact in case the ui doesn't want them
- if (request.IsMissing.HasValue)
- {
- var val = request.IsMissing.Value;
- episodes = episodes.Where(i => ((Episode)i).IsMissingEpisode == val).ToList();
- }
-
- if (!string.IsNullOrWhiteSpace(request.StartItemId))
- {
- episodes = episodes.SkipWhile(i => !string.Equals(i.Id.ToString("N"), request.StartItemId, StringComparison.OrdinalIgnoreCase)).ToList();
- }
-
- // This must be the last filter
- if (!string.IsNullOrEmpty(request.AdjacentTo))
- {
- episodes = UserViewBuilder.FilterForAdjacency(episodes, request.AdjacentTo).ToList();
- }
-
- if (string.Equals(request.SortBy, ItemSortBy.Random, StringComparison.OrdinalIgnoreCase))
- {
- episodes = episodes.OrderBy(i => Guid.NewGuid()).ToList();
- }
-
- var returnItems = episodes;
-
- if (request.StartIndex.HasValue || request.Limit.HasValue)
- {
- returnItems = ApplyPaging(episodes, request.StartIndex, request.Limit).ToList();
- }
-
- var dtos = _dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
-
- return new QueryResult<BaseItemDto>
- {
- TotalRecordCount = episodes.Count,
- Items = dtos
- };
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/ArtistsService.cs b/MediaBrowser.Api/UserLibrary/ArtistsService.cs
deleted file mode 100644
index 7a8455ff2..000000000
--- a/MediaBrowser.Api/UserLibrary/ArtistsService.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetArtists
- /// </summary>
- [Route("/Artists", "GET", Summary = "Gets all artists from a given item, folder, or the entire library")]
- public class GetArtists : GetItemsByName
- {
- }
-
- [Route("/Artists/AlbumArtists", "GET", Summary = "Gets all album artists from a given item, folder, or the entire library")]
- public class GetAlbumArtists : GetItemsByName
- {
- }
-
- [Route("/Artists/{Name}", "GET", Summary = "Gets an artist, by name")]
- public class GetArtist : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The artist name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class ArtistsService
- /// </summary>
- [Authenticated]
- public class ArtistsService : BaseItemsByNameService<MusicArtist>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetArtist request)
- {
- return GetItem(request);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetArtist request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- var item = GetArtist(request.Name, LibraryManager, dtoOptions);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetArtists request)
- {
- if (string.IsNullOrWhiteSpace(request.IncludeItemTypes))
- {
- //request.IncludeItemTypes = "Audio,MusicVideo";
- }
-
- return GetResultSlim(request);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetAlbumArtists request)
- {
- if (string.IsNullOrWhiteSpace(request.IncludeItemTypes))
- {
- //request.IncludeItemTypes = "Audio,MusicVideo";
- }
-
- var result = GetResultSlim(request);
-
- return ToOptimizedResult(result);
- }
-
- protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- if (request is GetAlbumArtists)
- {
- return LibraryManager.GetAlbumArtists(query);
- }
-
- return LibraryManager.GetArtists(query);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- throw new NotImplementedException();
- }
-
- public ArtistsService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs
deleted file mode 100644
index e3c9ae58e..000000000
--- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs
+++ /dev/null
@@ -1,386 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class BaseItemsByNameService
- /// </summary>
- /// <typeparam name="TItemType">The type of the T item type.</typeparam>
- public abstract class BaseItemsByNameService<TItemType> : BaseApiService
- where TItemType : BaseItem, IItemByName
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- protected readonly IUserManager UserManager;
- /// <summary>
- /// The library manager
- /// </summary>
- protected readonly ILibraryManager LibraryManager;
- protected readonly IUserDataManager UserDataRepository;
- protected readonly IItemRepository ItemRepository;
- protected IDtoService DtoService { get; private set; }
- protected IAuthorizationContext AuthorizationContext { get; private set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="BaseItemsByNameService{TItemType}" /> class.
- /// </summary>
- /// <param name="userManager">The user manager.</param>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="userDataRepository">The user data repository.</param>
- /// <param name="itemRepository">The item repository.</param>
- /// <param name="dtoService">The dto service.</param>
- protected BaseItemsByNameService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext)
- {
- UserManager = userManager;
- LibraryManager = libraryManager;
- UserDataRepository = userDataRepository;
- ItemRepository = itemRepository;
- DtoService = dtoService;
- AuthorizationContext = authorizationContext;
- }
-
- protected BaseItem GetParentItem(GetItemsByName request)
- {
- BaseItem parentItem;
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.GetUserRootFolder() : LibraryManager.GetItemById(request.ParentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.RootFolder : LibraryManager.GetItemById(request.ParentId);
- }
-
- return parentItem;
- }
-
- protected string GetParentItemViewType(GetItemsByName request)
- {
- var parent = GetParentItem(request);
-
- var collectionFolder = parent as IHasCollectionType;
- if (collectionFolder != null)
- {
- return collectionFolder.CollectionType;
- }
-
- return null;
- }
-
- protected QueryResult<BaseItemDto> GetResultSlim(GetItemsByName request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- User user = null;
- BaseItem parentItem;
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- user = UserManager.GetUserById(request.UserId);
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.GetUserRootFolder() : LibraryManager.GetItemById(request.ParentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.RootFolder : LibraryManager.GetItemById(request.ParentId);
- }
-
- var excludeItemTypes = request.GetExcludeItemTypes();
- var includeItemTypes = request.GetIncludeItemTypes();
- var mediaTypes = request.GetMediaTypes();
-
- var query = new InternalItemsQuery(user)
- {
- ExcludeItemTypes = excludeItemTypes,
- IncludeItemTypes = includeItemTypes,
- MediaTypes = mediaTypes,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- IsFavorite = request.IsFavorite,
- NameLessThan = request.NameLessThan,
- NameStartsWith = request.NameStartsWith,
- NameStartsWithOrGreater = request.NameStartsWithOrGreater,
- Tags = request.GetTags(),
- OfficialRatings = request.GetOfficialRatings(),
- Genres = request.GetGenres(),
- GenreIds = GetGuids(request.GenreIds),
- StudioIds = GetGuids(request.StudioIds),
- Person = request.Person,
- PersonIds = GetGuids(request.PersonIds),
- PersonTypes = request.GetPersonTypes(),
- Years = request.GetYears(),
- MinCommunityRating = request.MinCommunityRating,
- DtoOptions = dtoOptions,
- SearchTerm = request.SearchTerm,
- EnableTotalRecordCount = request.EnableTotalRecordCount
- };
-
- if (!string.IsNullOrWhiteSpace(request.ParentId))
- {
- if (parentItem is Folder)
- {
- query.AncestorIds = new[] { new Guid(request.ParentId) };
- }
- else
- {
- query.ItemIds = new[] { new Guid(request.ParentId) };
- }
- }
-
- // Studios
- if (!string.IsNullOrEmpty(request.Studios))
- {
- query.StudioIds = request.Studios.Split('|').Select(i =>
- {
- try
- {
- return LibraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null).Select(i => i.Id).ToArray();
- }
-
- foreach (var filter in request.GetFilters())
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = GetItems(request, query);
-
- var dtos = result.Items.Select(i =>
- {
- var dto = DtoService.GetItemByNameDto(i.Item1, dtoOptions, null, user);
-
- if (!string.IsNullOrWhiteSpace(request.IncludeItemTypes))
- {
- SetItemCounts(dto, i.Item2);
- }
- return dto;
- });
-
- return new QueryResult<BaseItemDto>
- {
- Items = dtos.ToArray(),
- TotalRecordCount = result.TotalRecordCount
- };
- }
-
- protected virtual QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- return new QueryResult<(BaseItem, ItemCounts)>();
- }
-
- private void SetItemCounts(BaseItemDto dto, ItemCounts counts)
- {
- dto.ChildCount = counts.ItemCount;
- dto.ProgramCount = counts.ProgramCount;
- dto.SeriesCount = counts.SeriesCount;
- dto.EpisodeCount = counts.EpisodeCount;
- dto.MovieCount = counts.MovieCount;
- dto.TrailerCount = counts.TrailerCount;
- dto.AlbumCount = counts.AlbumCount;
- dto.SongCount = counts.SongCount;
- dto.ArtistCount = counts.ArtistCount;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{ItemsResult}.</returns>
- protected QueryResult<BaseItemDto> GetResult(GetItemsByName request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- User user = null;
- BaseItem parentItem;
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- user = UserManager.GetUserById(request.UserId);
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.GetUserRootFolder() : LibraryManager.GetItemById(request.ParentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.RootFolder : LibraryManager.GetItemById(request.ParentId);
- }
-
- IList<BaseItem> items;
-
- var excludeItemTypes = request.GetExcludeItemTypes();
- var includeItemTypes = request.GetIncludeItemTypes();
- var mediaTypes = request.GetMediaTypes();
-
- var query = new InternalItemsQuery(user)
- {
- ExcludeItemTypes = excludeItemTypes,
- IncludeItemTypes = includeItemTypes,
- MediaTypes = mediaTypes,
- DtoOptions = dtoOptions
- };
-
- Func<BaseItem, bool> filter = i => FilterItem(request, i, excludeItemTypes, includeItemTypes, mediaTypes);
-
- if (parentItem.IsFolder)
- {
- var folder = (Folder)parentItem;
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- items = request.Recursive ?
- folder.GetRecursiveChildren(user, query).ToList() :
- folder.GetChildren(user, true).Where(filter).ToList();
- }
- else
- {
- items = request.Recursive ?
- folder.GetRecursiveChildren(filter) :
- folder.Children.Where(filter).ToList();
- }
- }
- else
- {
- items = new[] { parentItem }.Where(filter).ToList();
- }
-
- var extractedItems = GetAllItems(request, items);
-
- var filteredItems = LibraryManager.Sort(extractedItems, user, request.GetOrderBy());
-
- var ibnItemsArray = filteredItems.ToList();
-
- IEnumerable<BaseItem> ibnItems = ibnItemsArray;
-
- var result = new QueryResult<BaseItemDto>
- {
- TotalRecordCount = ibnItemsArray.Count
- };
-
- if (request.StartIndex.HasValue || request.Limit.HasValue)
- {
- if (request.StartIndex.HasValue)
- {
- ibnItems = ibnItems.Skip(request.StartIndex.Value);
- }
-
- if (request.Limit.HasValue)
- {
- ibnItems = ibnItems.Take(request.Limit.Value);
- }
-
- }
-
- var tuples = ibnItems.Select(i => new Tuple<BaseItem, List<BaseItem>>(i, new List<BaseItem>()));
-
- var dtos = tuples.Select(i => DtoService.GetItemByNameDto(i.Item1, dtoOptions, i.Item2, user));
-
- result.Items = dtos.Where(i => i != null).ToArray();
-
- return result;
- }
-
- /// <summary>
- /// Filters the items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="f">The f.</param>
- /// <param name="excludeItemTypes">The exclude item types.</param>
- /// <param name="includeItemTypes">The include item types.</param>
- /// <param name="mediaTypes">The media types.</param>
- /// <returns>IEnumerable{BaseItem}.</returns>
- private bool FilterItem(GetItemsByName request, BaseItem f, string[] excludeItemTypes, string[] includeItemTypes, string[] mediaTypes)
- {
- // Exclude item types
- if (excludeItemTypes.Length > 0)
- {
- if (excludeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
- }
-
- // Include item types
- if (includeItemTypes.Length > 0)
- {
- if (!includeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
- }
-
- // Include MediaTypes
- if (mediaTypes.Length > 0)
- {
- if (!mediaTypes.Contains(f.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Task{`0}}.</returns>
- protected abstract IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items);
- }
-
- /// <summary>
- /// Class GetItemsByName
- /// </summary>
- public class GetItemsByName : BaseItemsRequest, IReturn<QueryResult<BaseItemDto>>
- {
- public GetItemsByName()
- {
- Recursive = true;
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs
deleted file mode 100644
index a26f59573..000000000
--- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs
+++ /dev/null
@@ -1,480 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- public abstract class BaseItemsRequest : IHasDtoOptions
- {
- protected BaseItemsRequest()
- {
- EnableImages = true;
- EnableTotalRecordCount = true;
- }
-
- /// <summary>
- /// Gets or sets the max offical rating.
- /// </summary>
- /// <value>The max offical rating.</value>
- [ApiMember(Name = "MaxOfficialRating", Description = "Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MaxOfficialRating { get; set; }
-
- [ApiMember(Name = "HasThemeSong", Description = "Optional filter by items with theme songs.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasThemeSong { get; set; }
-
- [ApiMember(Name = "HasThemeVideo", Description = "Optional filter by items with theme videos.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasThemeVideo { get; set; }
-
- [ApiMember(Name = "HasSubtitles", Description = "Optional filter by items with subtitles.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasSubtitles { get; set; }
-
- [ApiMember(Name = "HasSpecialFeature", Description = "Optional filter by items with special features.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasSpecialFeature { get; set; }
-
- [ApiMember(Name = "HasTrailer", Description = "Optional filter by items with trailers.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasTrailer { get; set; }
-
- [ApiMember(Name = "AdjacentTo", Description = "Optional. Return items that are siblings of a supplied item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string AdjacentTo { get; set; }
-
- [ApiMember(Name = "MinIndexNumber", Description = "Optional filter by minimum index number.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MinIndexNumber { get; set; }
-
- [ApiMember(Name = "ParentIndexNumber", Description = "Optional filter by parent index number.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ParentIndexNumber { get; set; }
-
- [ApiMember(Name = "HasParentalRating", Description = "Optional filter by items that have or do not have a parental rating", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasParentalRating { get; set; }
-
- [ApiMember(Name = "IsHD", Description = "Optional filter by items that are HD or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsHD { get; set; }
-
- public bool? Is4K { get; set; }
-
- [ApiMember(Name = "LocationTypes", Description = "Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string LocationTypes { get; set; }
-
- [ApiMember(Name = "ExcludeLocationTypes", Description = "Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ExcludeLocationTypes { get; set; }
-
- [ApiMember(Name = "IsMissing", Description = "Optional filter by items that are missing episodes or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsMissing { get; set; }
-
- [ApiMember(Name = "IsUnaired", Description = "Optional filter by items that are unaired episodes or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsUnaired { get; set; }
-
- [ApiMember(Name = "MinCommunityRating", Description = "Optional filter by minimum community rating.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public double? MinCommunityRating { get; set; }
-
- [ApiMember(Name = "MinCriticRating", Description = "Optional filter by minimum critic rating.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public double? MinCriticRating { get; set; }
-
- [ApiMember(Name = "AiredDuringSeason", Description = "Gets all episodes that aired during a season, including specials.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? AiredDuringSeason { get; set; }
-
- [ApiMember(Name = "MinPremiereDate", Description = "Optional. The minimum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MinPremiereDate { get; set; }
-
- [ApiMember(Name = "MinDateLastSaved", Description = "Optional. The minimum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MinDateLastSaved { get; set; }
-
- [ApiMember(Name = "MinDateLastSavedForUser", Description = "Optional. The minimum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MinDateLastSavedForUser { get; set; }
-
- [ApiMember(Name = "MaxPremiereDate", Description = "Optional. The maximum premiere date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MaxPremiereDate { get; set; }
-
- [ApiMember(Name = "HasOverview", Description = "Optional filter by items that have an overview or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasOverview { get; set; }
-
- [ApiMember(Name = "HasImdbId", Description = "Optional filter by items that have an imdb id or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasImdbId { get; set; }
-
- [ApiMember(Name = "HasTmdbId", Description = "Optional filter by items that have a tmdb id or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasTmdbId { get; set; }
-
- [ApiMember(Name = "HasTvdbId", Description = "Optional filter by items that have a tvdb id or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? HasTvdbId { get; set; }
-
- [ApiMember(Name = "ExcludeItemIds", Description = "Optional. If specified, results will be filtered by exxcluding item ids. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ExcludeItemIds { get; set; }
-
- public bool EnableTotalRecordCount { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
-
- /// <summary>
- /// Whether or not to perform the query recursively
- /// </summary>
- /// <value><c>true</c> if recursive; otherwise, <c>false</c>.</value>
- [ApiMember(Name = "Recursive", Description = "When searching within folders, this determines whether or not the search will be recursive. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool Recursive { get; set; }
-
- public string SearchTerm { get; set; }
-
- /// <summary>
- /// Gets or sets the sort order.
- /// </summary>
- /// <value>The sort order.</value>
- [ApiMember(Name = "SortOrder", Description = "Sort Order - Ascending,Descending", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string SortOrder { get; set; }
-
- /// <summary>
- /// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// </summary>
- /// <value>The parent id.</value>
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ParentId { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- /// <summary>
- /// Gets or sets the exclude item types.
- /// </summary>
- /// <value>The exclude item types.</value>
- [ApiMember(Name = "ExcludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ExcludeItemTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the include item types.
- /// </summary>
- /// <value>The include item types.</value>
- [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string IncludeItemTypes { get; set; }
-
- /// <summary>
- /// Filters to apply to the results
- /// </summary>
- /// <value>The filters.</value>
- [ApiMember(Name = "Filters", Description = "Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Filters { get; set; }
-
- /// <summary>
- /// Gets or sets the Isfavorite option
- /// </summary>
- /// <value>IsFavorite</value>
- [ApiMember(Name = "IsFavorite", Description = "Optional filter by items that are marked as favorite, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsFavorite { get; set; }
-
- /// <summary>
- /// Gets or sets the media types.
- /// </summary>
- /// <value>The media types.</value>
- [ApiMember(Name = "MediaTypes", Description = "Optional filter by MediaType. Allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string MediaTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the image types.
- /// </summary>
- /// <value>The image types.</value>
- [ApiMember(Name = "ImageTypes", Description = "Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ImageTypes { get; set; }
-
- /// <summary>
- /// What to sort the results by
- /// </summary>
- /// <value>The sort by.</value>
- [ApiMember(Name = "SortBy", Description = "Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string SortBy { get; set; }
-
- [ApiMember(Name = "IsPlayed", Description = "Optional filter by items that are played, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsPlayed { get; set; }
-
- /// <summary>
- /// Limit results to items containing specific genres
- /// </summary>
- /// <value>The genres.</value>
- [ApiMember(Name = "Genres", Description = "Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Genres { get; set; }
-
- public string GenreIds { get; set; }
-
- [ApiMember(Name = "OfficialRatings", Description = "Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string OfficialRatings { get; set; }
-
- [ApiMember(Name = "Tags", Description = "Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Tags { get; set; }
-
- /// <summary>
- /// Limit results to items containing specific years
- /// </summary>
- /// <value>The years.</value>
- [ApiMember(Name = "Years", Description = "Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Years { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- /// <summary>
- /// Limit results to items containing a specific person
- /// </summary>
- /// <value>The person.</value>
- [ApiMember(Name = "Person", Description = "Optional. If specified, results will be filtered to include only those containing the specified person.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Person { get; set; }
-
- [ApiMember(Name = "PersonIds", Description = "Optional. If specified, results will be filtered to include only those containing the specified person.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string PersonIds { get; set; }
-
- /// <summary>
- /// If the Person filter is used, this can also be used to restrict to a specific person type
- /// </summary>
- /// <value>The type of the person.</value>
- [ApiMember(Name = "PersonTypes", Description = "Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string PersonTypes { get; set; }
-
- /// <summary>
- /// Limit results to items containing specific studios
- /// </summary>
- /// <value>The studios.</value>
- [ApiMember(Name = "Studios", Description = "Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Studios { get; set; }
-
- [ApiMember(Name = "StudioIds", Description = "Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string StudioIds { get; set; }
-
- /// <summary>
- /// Gets or sets the studios.
- /// </summary>
- /// <value>The studios.</value>
- [ApiMember(Name = "Artists", Description = "Optional. If specified, results will be filtered based on artist. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Artists { get; set; }
-
- public string ExcludeArtistIds { get; set; }
-
- [ApiMember(Name = "ArtistIds", Description = "Optional. If specified, results will be filtered based on artist. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string ArtistIds { get; set; }
-
- public string AlbumArtistIds { get; set; }
-
- public string ContributingArtistIds { get; set; }
-
- [ApiMember(Name = "Albums", Description = "Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Albums { get; set; }
-
- public string AlbumIds { get; set; }
-
- /// <summary>
- /// Gets or sets the item ids.
- /// </summary>
- /// <value>The item ids.</value>
- [ApiMember(Name = "Ids", Description = "Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Ids { get; set; }
-
- /// <summary>
- /// Gets or sets the video types.
- /// </summary>
- /// <value>The video types.</value>
- [ApiMember(Name = "VideoTypes", Description = "Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string VideoTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the min offical rating.
- /// </summary>
- /// <value>The min offical rating.</value>
- [ApiMember(Name = "MinOfficialRating", Description = "Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string MinOfficialRating { get; set; }
-
- [ApiMember(Name = "IsLocked", Description = "Optional filter by items that are locked.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? IsLocked { get; set; }
-
- [ApiMember(Name = "IsPlaceHolder", Description = "Optional filter by items that are placeholders", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? IsPlaceHolder { get; set; }
-
- [ApiMember(Name = "HasOfficialRating", Description = "Optional filter by items that have official ratings", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public bool? HasOfficialRating { get; set; }
-
- [ApiMember(Name = "CollapseBoxSetItems", Description = "Whether or not to hide items behind their boxsets.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? CollapseBoxSetItems { get; set; }
-
- public int? MinWidth { get; set; }
- public int? MinHeight { get; set; }
- public int? MaxWidth { get; set; }
- public int? MaxHeight { get; set; }
-
- /// <summary>
- /// Gets or sets the video formats.
- /// </summary>
- /// <value>The video formats.</value>
- [ApiMember(Name = "Is3D", Description = "Optional filter by items that are 3D, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? Is3D { get; set; }
-
- /// <summary>
- /// Gets or sets the series status.
- /// </summary>
- /// <value>The series status.</value>
- [ApiMember(Name = "SeriesStatus", Description = "Optional filter by Series Status. Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string SeriesStatus { get; set; }
-
- [ApiMember(Name = "NameStartsWithOrGreater", Description = "Optional filter by items whose name is sorted equally or greater than a given input string.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string NameStartsWithOrGreater { get; set; }
-
- [ApiMember(Name = "NameStartsWith", Description = "Optional filter by items whose name is sorted equally than a given input string.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string NameStartsWith { get; set; }
-
- [ApiMember(Name = "NameLessThan", Description = "Optional filter by items whose name is equally or lesser than a given input string.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string NameLessThan { get; set; }
-
- public string[] GetGenres()
- {
- return (Genres ?? string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetTags()
- {
- return (Tags ?? string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetOfficialRatings()
- {
- return (OfficialRatings ?? string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetMediaTypes()
- {
- return (MediaTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetIncludeItemTypes()
- {
- return (IncludeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetExcludeItemTypes()
- {
- return (ExcludeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public int[] GetYears()
- {
- return (Years ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
- }
-
- public string[] GetStudios()
- {
- return (Studios ?? string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public string[] GetPersonTypes()
- {
- return (PersonTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public VideoType[] GetVideoTypes()
- {
- if (string.IsNullOrEmpty(VideoTypes))
- {
- return Array.Empty<VideoType>();
- }
-
- return VideoTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(v => (VideoType)Enum.Parse(typeof(VideoType), v, true)).ToArray();
- }
-
- /// <summary>
- /// Gets the filters.
- /// </summary>
- /// <returns>IEnumerable{ItemFilter}.</returns>
- public ItemFilter[] GetFilters()
- {
- var val = Filters;
-
- if (string.IsNullOrEmpty(val))
- {
- return new ItemFilter[] { };
- }
-
- return val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)).ToArray();
- }
-
- /// <summary>
- /// Gets the image types.
- /// </summary>
- /// <returns>IEnumerable{ImageType}.</returns>
- public ImageType[] GetImageTypes()
- {
- var val = ImageTypes;
-
- if (string.IsNullOrEmpty(val))
- {
- return new ImageType[] { };
- }
-
- return val.Split(',').Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)).ToArray();
- }
-
- /// <summary>
- /// Gets the order by.
- /// </summary>
- /// <returns>IEnumerable{ItemSortBy}.</returns>
- public ValueTuple<string, SortOrder>[] GetOrderBy()
- {
- return GetOrderBy(SortBy, SortOrder);
- }
-
- public static ValueTuple<string, SortOrder>[] GetOrderBy(string sortBy, string requestedSortOrder)
- {
- var val = sortBy;
-
- if (string.IsNullOrEmpty(val))
- {
- return Array.Empty<ValueTuple<string, SortOrder>>();
- }
-
- var vals = val.Split(',');
- if (string.IsNullOrWhiteSpace(requestedSortOrder))
- {
- requestedSortOrder = "Ascending";
- }
-
- var sortOrders = requestedSortOrder.Split(',');
-
- var result = new ValueTuple<string, SortOrder>[vals.Length];
-
- for (var i = 0; i < vals.Length; i++)
- {
- var sortOrderIndex = sortOrders.Length > i ? i : 0;
-
- var sortOrderValue = sortOrders.Length > sortOrderIndex ? sortOrders[sortOrderIndex] : null;
- var sortOrder = string.Equals(sortOrderValue, "Descending", StringComparison.OrdinalIgnoreCase) ? MediaBrowser.Model.Entities.SortOrder.Descending : MediaBrowser.Model.Entities.SortOrder.Ascending;
-
- result[i] = new ValueTuple<string, SortOrder>(vals[i], sortOrder);
- }
-
- return result;
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/GenresService.cs b/MediaBrowser.Api/UserLibrary/GenresService.cs
deleted file mode 100644
index 0c04d02dd..000000000
--- a/MediaBrowser.Api/UserLibrary/GenresService.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetGenres
- /// </summary>
- [Route("/Genres", "GET", Summary = "Gets all genres from a given item, folder, or the entire library")]
- public class GetGenres : GetItemsByName
- {
- }
-
- /// <summary>
- /// Class GetGenre
- /// </summary>
- [Route("/Genres/{Name}", "GET", Summary = "Gets a genre, by name")]
- public class GetGenre : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The genre name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class GenresService
- /// </summary>
- [Authenticated]
- public class GenresService : BaseItemsByNameService<Genre>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetGenre request)
- {
- var result = GetItem(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetGenre request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- var item = GetGenre(request.Name, LibraryManager, dtoOptions);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetGenres request)
- {
- var result = GetResultSlim(request);
-
- return ToOptimizedResult(result);
- }
-
- protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- var viewType = GetParentItemViewType(request);
-
- if (string.Equals(viewType, CollectionType.Music) || string.Equals(viewType, CollectionType.MusicVideos))
- {
- return LibraryManager.GetMusicGenres(query);
- }
-
- return LibraryManager.GetGenres(query);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- throw new NotImplementedException();
- }
-
- public GenresService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/ItemsService.cs b/MediaBrowser.Api/UserLibrary/ItemsService.cs
deleted file mode 100644
index 84475467f..000000000
--- a/MediaBrowser.Api/UserLibrary/ItemsService.cs
+++ /dev/null
@@ -1,516 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetItems
- /// </summary>
- [Route("/Items", "GET", Summary = "Gets items based on a query.")]
- [Route("/Users/{UserId}/Items", "GET", Summary = "Gets items based on a query.")]
- public class GetItems : BaseItemsRequest, IReturn<QueryResult<BaseItemDto>>
- {
- }
-
- [Route("/Users/{UserId}/Items/Resume", "GET", Summary = "Gets items based on a query.")]
- public class GetResumeItems : BaseItemsRequest, IReturn<QueryResult<BaseItemDto>>
- {
- }
-
- /// <summary>
- /// Class ItemsService
- /// </summary>
- [Authenticated]
- public class ItemsService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
-
- /// <summary>
- /// The _library manager
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localization;
-
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ItemsService" /> class.
- /// </summary>
- /// <param name="userManager">The user manager.</param>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="localization">The localization.</param>
- /// <param name="dtoService">The dto service.</param>
- public ItemsService(IUserManager userManager, ILibraryManager libraryManager, ILocalizationManager localization, IDtoService dtoService, IAuthorizationContext authContext)
- {
- if (userManager == null)
- {
- throw new ArgumentNullException(nameof(userManager));
- }
- if (libraryManager == null)
- {
- throw new ArgumentNullException(nameof(libraryManager));
- }
- if (localization == null)
- {
- throw new ArgumentNullException(nameof(localization));
- }
- if (dtoService == null)
- {
- throw new ArgumentNullException(nameof(dtoService));
- }
-
- _userManager = userManager;
- _libraryManager = libraryManager;
- _localization = localization;
- _dtoService = dtoService;
- _authContext = authContext;
- }
-
- public object Get(GetResumeItems request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var parentIdGuid = string.IsNullOrWhiteSpace(request.ParentId) ? Guid.Empty : new Guid(request.ParentId);
-
- var options = GetDtoOptions(_authContext, request);
-
- var ancestorIds = Array.Empty<Guid>();
-
- var excludeFolderIds = user.Configuration.LatestItemsExcludes;
- if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0)
- {
- ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
- .Where(i => i is Folder)
- .Where(i => !excludeFolderIds.Contains(i.Id.ToString("N")))
- .Select(i => i.Id)
- .ToArray();
- }
-
- var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
- {
- OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
- IsResumable = true,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- ParentId = parentIdGuid,
- Recursive = true,
- DtoOptions = options,
- MediaTypes = request.GetMediaTypes(),
- IsVirtualItem = false,
- CollapseBoxSetItems = false,
- EnableTotalRecordCount = request.EnableTotalRecordCount,
- AncestorIds = ancestorIds,
- IncludeItemTypes = request.GetIncludeItemTypes(),
- ExcludeItemTypes = request.GetExcludeItemTypes(),
- SearchTerm = request.SearchTerm
- });
-
- var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, options, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- TotalRecordCount = itemsResult.TotalRecordCount,
- Items = returnItems
- };
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetItems request)
- {
- if (request == null)
- {
- throw new ArgumentNullException(nameof(request));
- }
-
- var result = GetItems(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the items.
- /// </summary>
- /// <param name="request">The request.</param>
- private QueryResult<BaseItemDto> GetItems(GetItems request)
- {
- var user = request.UserId == Guid.Empty ? null : _userManager.GetUserById(request.UserId);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = GetQueryResult(request, dtoOptions, user);
-
- if (result == null)
- {
- throw new InvalidOperationException("GetItemsToSerialize returned null");
- }
-
- if (result.Items == null)
- {
- throw new InvalidOperationException("GetItemsToSerialize result.Items returned null");
- }
-
- var dtoList = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user);
-
- if (dtoList == null)
- {
- throw new InvalidOperationException("GetBaseItemDtos returned null");
- }
-
- return new QueryResult<BaseItemDto>
- {
- TotalRecordCount = result.TotalRecordCount,
- Items = dtoList
- };
- }
-
- /// <summary>
- /// Gets the items to serialize.
- /// </summary>
- private QueryResult<BaseItem> GetQueryResult(GetItems request, DtoOptions dtoOptions, User user)
- {
- if (string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase)
- || string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
- {
- request.ParentId = null;
- }
-
- var item = string.IsNullOrEmpty(request.ParentId) ?
- null :
- _libraryManager.GetItemById(request.ParentId);
-
- if (item == null)
- {
- item = string.IsNullOrEmpty(request.ParentId) ?
- user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder() :
- _libraryManager.GetItemById(request.ParentId);
- }
-
- // Default list type = children
-
- var folder = item as Folder;
- if (folder == null)
- {
- folder = user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder();
- }
-
- var hasCollectionType = folder as IHasCollectionType;
- var isPlaylistQuery = (hasCollectionType != null && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase));
-
- if (isPlaylistQuery)
- {
- request.Recursive = true;
- request.IncludeItemTypes = "Playlist";
- }
-
- if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Any(i => new Guid(i) == item.Id))
- {
- Logger.LogWarning("{UserName} is not permitted to access Library {ItemName}.", user.Name, item.Name);
- return new QueryResult<BaseItem>
- {
- Items = Array.Empty<BaseItem>(),
- TotalRecordCount = 0
- };
- }
-
- if (request.Recursive || !string.IsNullOrEmpty(request.Ids) || user == null)
- {
- return folder.GetItems(GetItemsQuery(request, dtoOptions, user));
- }
-
- var userRoot = item as UserRootFolder;
-
- if (userRoot == null)
- {
- return folder.GetItems(GetItemsQuery(request, dtoOptions, user));
- }
-
- var itemsArray = folder.GetChildren(user, true).ToArray();
-
- return new QueryResult<BaseItem>
- {
- Items = itemsArray,
- TotalRecordCount = itemsArray.Length
- };
- }
-
- private InternalItemsQuery GetItemsQuery(GetItems request, DtoOptions dtoOptions, User user)
- {
- var query = new InternalItemsQuery(user)
- {
- IsPlayed = request.IsPlayed,
- MediaTypes = request.GetMediaTypes(),
- IncludeItemTypes = request.GetIncludeItemTypes(),
- ExcludeItemTypes = request.GetExcludeItemTypes(),
- Recursive = request.Recursive,
- OrderBy = request.GetOrderBy(),
-
- IsFavorite = request.IsFavorite,
- Limit = request.Limit,
- StartIndex = request.StartIndex,
- IsMissing = request.IsMissing,
- IsUnaired = request.IsUnaired,
- CollapseBoxSetItems = request.CollapseBoxSetItems,
- NameLessThan = request.NameLessThan,
- NameStartsWith = request.NameStartsWith,
- NameStartsWithOrGreater = request.NameStartsWithOrGreater,
- HasImdbId = request.HasImdbId,
- IsPlaceHolder = request.IsPlaceHolder,
- IsLocked = request.IsLocked,
- MinWidth = request.MinWidth,
- MinHeight = request.MinHeight,
- MaxWidth = request.MaxWidth,
- MaxHeight = request.MaxHeight,
- Is3D = request.Is3D,
- HasTvdbId = request.HasTvdbId,
- HasTmdbId = request.HasTmdbId,
- HasOverview = request.HasOverview,
- HasOfficialRating = request.HasOfficialRating,
- HasParentalRating = request.HasParentalRating,
- HasSpecialFeature = request.HasSpecialFeature,
- HasSubtitles = request.HasSubtitles,
- HasThemeSong = request.HasThemeSong,
- HasThemeVideo = request.HasThemeVideo,
- HasTrailer = request.HasTrailer,
- IsHD = request.IsHD,
- Is4K = request.Is4K,
- Tags = request.GetTags(),
- OfficialRatings = request.GetOfficialRatings(),
- Genres = request.GetGenres(),
- ArtistIds = GetGuids(request.ArtistIds),
- AlbumArtistIds = GetGuids(request.AlbumArtistIds),
- ContributingArtistIds = GetGuids(request.ContributingArtistIds),
- GenreIds = GetGuids(request.GenreIds),
- StudioIds = GetGuids(request.StudioIds),
- Person = request.Person,
- PersonIds = GetGuids(request.PersonIds),
- PersonTypes = request.GetPersonTypes(),
- Years = request.GetYears(),
- ImageTypes = request.GetImageTypes(),
- VideoTypes = request.GetVideoTypes(),
- AdjacentTo = request.AdjacentTo,
- ItemIds = GetGuids(request.Ids),
- MinCommunityRating = request.MinCommunityRating,
- MinCriticRating = request.MinCriticRating,
- ParentId = string.IsNullOrWhiteSpace(request.ParentId) ? Guid.Empty : new Guid(request.ParentId),
- ParentIndexNumber = request.ParentIndexNumber,
- EnableTotalRecordCount = request.EnableTotalRecordCount,
- ExcludeItemIds = GetGuids(request.ExcludeItemIds),
- DtoOptions = dtoOptions,
- SearchTerm = request.SearchTerm
- };
-
- if (!string.IsNullOrWhiteSpace(request.Ids) || !string.IsNullOrWhiteSpace(request.SearchTerm))
- {
- query.CollapseBoxSetItems = false;
- }
-
- foreach (var filter in request.GetFilters())
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- if (!string.IsNullOrEmpty(request.MinDateLastSaved))
- {
- query.MinDateLastSaved = DateTime.Parse(request.MinDateLastSaved, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MinDateLastSavedForUser))
- {
- query.MinDateLastSavedForUser = DateTime.Parse(request.MinDateLastSavedForUser, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MinPremiereDate))
- {
- query.MinPremiereDate = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- if (!string.IsNullOrEmpty(request.MaxPremiereDate))
- {
- query.MaxPremiereDate = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
- }
-
- // Filter by Series Status
- if (!string.IsNullOrEmpty(request.SeriesStatus))
- {
- query.SeriesStatuses = request.SeriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
- }
-
- // ExcludeLocationTypes
- if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
- {
- var excludeLocationTypes = request.ExcludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
- if (excludeLocationTypes.Contains(LocationType.Virtual))
- {
- query.IsVirtualItem = false;
- }
- }
-
- if (!string.IsNullOrEmpty(request.LocationTypes))
- {
- var requestedLocationTypes =
- request.LocationTypes.Split(',');
-
- if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4)
- {
- query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual.ToString());
- }
- }
-
- // Min official rating
- if (!string.IsNullOrWhiteSpace(request.MinOfficialRating))
- {
- query.MinParentalRating = _localization.GetRatingLevel(request.MinOfficialRating);
- }
-
- // Max official rating
- if (!string.IsNullOrWhiteSpace(request.MaxOfficialRating))
- {
- query.MaxParentalRating = _localization.GetRatingLevel(request.MaxOfficialRating);
- }
-
- // Artists
- if (!string.IsNullOrEmpty(request.Artists))
- {
- query.ArtistIds = request.Artists.Split('|').Select(i =>
- {
- try
- {
- return _libraryManager.GetArtist(i, new DtoOptions(false));
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null).Select(i => i.Id).ToArray();
- }
-
- // ExcludeArtistIds
- if (!string.IsNullOrWhiteSpace(request.ExcludeArtistIds))
- {
- query.ExcludeArtistIds = GetGuids(request.ExcludeArtistIds);
- }
-
- if (!string.IsNullOrWhiteSpace(request.AlbumIds))
- {
- query.AlbumIds = GetGuids(request.AlbumIds);
- }
-
- // Albums
- if (!string.IsNullOrEmpty(request.Albums))
- {
- query.AlbumIds = request.Albums.Split('|').SelectMany(i =>
- {
- return _libraryManager.GetItemIds(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
- Name = i,
- Limit = 1
-
- }).Select(albumId => albumId);
-
- }).ToArray();
- }
-
- // Studios
- if (!string.IsNullOrEmpty(request.Studios))
- {
- query.StudioIds = request.Studios.Split('|').Select(i =>
- {
- try
- {
- return _libraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null).Select(i => i.Id).ToArray();
- }
-
- // Apply default sorting if none requested
- if (query.OrderBy.Length == 0)
- {
- // Albums by artist
- if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase))
- {
- query.OrderBy = new[]
- {
- new ValueTuple<string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending),
- new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending)
- };
- }
- }
-
- return query;
- }
- }
-
- /// <summary>
- /// Class DateCreatedComparer
- /// </summary>
- public class DateCreatedComparer : IComparer<BaseItem>
- {
- /// <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)
- {
- return x.DateCreated.CompareTo(y.DateCreated);
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/MusicGenresService.cs b/MediaBrowser.Api/UserLibrary/MusicGenresService.cs
deleted file mode 100644
index 94f5262b0..000000000
--- a/MediaBrowser.Api/UserLibrary/MusicGenresService.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- [Route("/MusicGenres", "GET", Summary = "Gets all music genres from a given item, folder, or the entire library")]
- public class GetMusicGenres : GetItemsByName
- {
- }
-
- [Route("/MusicGenres/{Name}", "GET", Summary = "Gets a music genre, by name")]
- public class GetMusicGenre : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The genre name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- [Authenticated]
- public class MusicGenresService : BaseItemsByNameService<MusicGenre>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetMusicGenre request)
- {
- var result = GetItem(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetMusicGenre request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- var item = GetMusicGenre(request.Name, LibraryManager, dtoOptions);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetMusicGenres request)
- {
- var result = GetResultSlim(request);
-
- return ToOptimizedResult(result);
- }
-
- protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- return LibraryManager.GetMusicGenres(query);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- throw new NotImplementedException();
- }
-
- public MusicGenresService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/PersonsService.cs b/MediaBrowser.Api/UserLibrary/PersonsService.cs
deleted file mode 100644
index c26457778..000000000
--- a/MediaBrowser.Api/UserLibrary/PersonsService.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetPersons
- /// </summary>
- [Route("/Persons", "GET", Summary = "Gets all persons from a given item, folder, or the entire library")]
- public class GetPersons : GetItemsByName
- {
- }
-
- /// <summary>
- /// Class GetPerson
- /// </summary>
- [Route("/Persons/{Name}", "GET", Summary = "Gets a person, by name")]
- public class GetPerson : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The person name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class PersonsService
- /// </summary>
- [Authenticated]
- public class PersonsService : BaseItemsByNameService<Person>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPerson request)
- {
- var result = GetItem(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetPerson request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- var item = GetPerson(request.Name, LibraryManager, dtoOptions);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetPersons request)
- {
- return GetResultSlim(request);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- throw new NotImplementedException();
- }
-
- protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- var items = LibraryManager.GetPeopleItems(new InternalPeopleQuery
- {
- PersonTypes = query.PersonTypes,
- NameContains = query.NameContains ?? query.SearchTerm
- });
-
- return new QueryResult<(BaseItem, ItemCounts)>
- {
- TotalRecordCount = items.Count,
- Items = items.Take(query.Limit ?? int.MaxValue).Select(i => (i as BaseItem, new ItemCounts())).ToArray()
- };
- }
-
- public PersonsService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/PlaystateService.cs b/MediaBrowser.Api/UserLibrary/PlaystateService.cs
deleted file mode 100644
index b40a92a7c..000000000
--- a/MediaBrowser.Api/UserLibrary/PlaystateService.cs
+++ /dev/null
@@ -1,449 +0,0 @@
-using System;
-using System.Globalization;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Session;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class MarkPlayedItem
- /// </summary>
- [Route("/Users/{UserId}/PlayedItems/{Id}", "POST", Summary = "Marks an item as played")]
- public class MarkPlayedItem : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
-
- [ApiMember(Name = "DatePlayed", Description = "The date the item was played (if any). Format = yyyyMMddHHmmss", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string DatePlayed { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class MarkUnplayedItem
- /// </summary>
- [Route("/Users/{UserId}/PlayedItems/{Id}", "DELETE", Summary = "Marks an item as unplayed")]
- public class MarkUnplayedItem : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/Sessions/Playing", "POST", Summary = "Reports playback has started within a session")]
- public class ReportPlaybackStart : PlaybackStartInfo, IReturnVoid
- {
- }
-
- [Route("/Sessions/Playing/Progress", "POST", Summary = "Reports playback progress within a session")]
- public class ReportPlaybackProgress : PlaybackProgressInfo, IReturnVoid
- {
- }
-
- [Route("/Sessions/Playing/Ping", "POST", Summary = "Pings a playback session")]
- public class PingPlaybackSession : IReturnVoid
- {
- [ApiMember(Name = "PlaySessionId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string PlaySessionId { get; set; }
- }
-
- [Route("/Sessions/Playing/Stopped", "POST", Summary = "Reports playback has stopped within a session")]
- public class ReportPlaybackStopped : PlaybackStopInfo, IReturnVoid
- {
- }
-
- /// <summary>
- /// Class OnPlaybackStart
- /// </summary>
- [Route("/Users/{UserId}/PlayingItems/{Id}", "POST", Summary = "Reports that a user has begun playing an item")]
- public class OnPlaybackStart : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "The id of the MediaSource", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string MediaSourceId { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this <see cref="UpdateUserItemRating" /> is likes.
- /// </summary>
- /// <value><c>true</c> if likes; otherwise, <c>false</c>.</value>
- [ApiMember(Name = "CanSeek", Description = "Indicates if the client can seek", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool CanSeek { get; set; }
-
- [ApiMember(Name = "AudioStreamIndex", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int? AudioStreamIndex { get; set; }
-
- [ApiMember(Name = "SubtitleStreamIndex", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int? SubtitleStreamIndex { get; set; }
-
- [ApiMember(Name = "PlayMethod", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public PlayMethod PlayMethod { get; set; }
-
- [ApiMember(Name = "LiveStreamId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string LiveStreamId { get; set; }
-
- [ApiMember(Name = "PlaySessionId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string PlaySessionId { get; set; }
- }
-
- /// <summary>
- /// Class OnPlaybackProgress
- /// </summary>
- [Route("/Users/{UserId}/PlayingItems/{Id}/Progress", "POST", Summary = "Reports a user's playback progress")]
- public class OnPlaybackProgress : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public string Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "The id of the MediaSource", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string MediaSourceId { get; set; }
-
- /// <summary>
- /// Gets or sets the position ticks.
- /// </summary>
- /// <value>The position ticks.</value>
- [ApiMember(Name = "PositionTicks", Description = "Optional. The current position, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public long? PositionTicks { get; set; }
-
- [ApiMember(Name = "IsPaused", Description = "Indicates if the player is paused.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool IsPaused { get; set; }
-
- [ApiMember(Name = "IsMuted", Description = "Indicates if the player is muted.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool IsMuted { get; set; }
-
- [ApiMember(Name = "AudioStreamIndex", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int? AudioStreamIndex { get; set; }
-
- [ApiMember(Name = "SubtitleStreamIndex", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int? SubtitleStreamIndex { get; set; }
-
- [ApiMember(Name = "VolumeLevel", Description = "Scale of 0-100", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
- public int? VolumeLevel { get; set; }
-
- [ApiMember(Name = "PlayMethod", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public PlayMethod PlayMethod { get; set; }
-
- [ApiMember(Name = "LiveStreamId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string LiveStreamId { get; set; }
-
- [ApiMember(Name = "PlaySessionId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string PlaySessionId { get; set; }
-
- [ApiMember(Name = "RepeatMode", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public RepeatMode RepeatMode { get; set; }
- }
-
- /// <summary>
- /// Class OnPlaybackStopped
- /// </summary>
- [Route("/Users/{UserId}/PlayingItems/{Id}", "DELETE", Summary = "Reports that a user has stopped playing an item")]
- public class OnPlaybackStopped : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "The id of the MediaSource", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string MediaSourceId { get; set; }
-
- [ApiMember(Name = "NextMediaType", Description = "The next media type that will play", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
- public string NextMediaType { get; set; }
-
- /// <summary>
- /// Gets or sets the position ticks.
- /// </summary>
- /// <value>The position ticks.</value>
- [ApiMember(Name = "PositionTicks", Description = "Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "DELETE")]
- public long? PositionTicks { get; set; }
-
- [ApiMember(Name = "LiveStreamId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string LiveStreamId { get; set; }
-
- [ApiMember(Name = "PlaySessionId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
- public string PlaySessionId { get; set; }
- }
-
- [Authenticated]
- public class PlaystateService : BaseApiService
- {
- private readonly IUserManager _userManager;
- private readonly IUserDataManager _userDataRepository;
- private readonly ILibraryManager _libraryManager;
- private readonly ISessionManager _sessionManager;
- private readonly ISessionContext _sessionContext;
- private readonly IAuthorizationContext _authContext;
-
- public PlaystateService(IUserManager userManager, IUserDataManager userDataRepository, ILibraryManager libraryManager, ISessionManager sessionManager, ISessionContext sessionContext, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _userDataRepository = userDataRepository;
- _libraryManager = libraryManager;
- _sessionManager = sessionManager;
- _sessionContext = sessionContext;
- _authContext = authContext;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Post(MarkPlayedItem request)
- {
- var result = MarkPlayed(request);
-
- return ToOptimizedResult(result);
- }
-
- private UserItemDataDto MarkPlayed(MarkPlayedItem request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- DateTime? datePlayed = null;
-
- if (!string.IsNullOrEmpty(request.DatePlayed))
- {
- datePlayed = DateTime.ParseExact(request.DatePlayed, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
- }
-
- var session = GetSession(_sessionContext);
-
- var dto = UpdatePlayedStatus(user, request.Id, true, datePlayed);
-
- foreach (var additionalUserInfo in session.AdditionalUsers)
- {
- var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
-
- UpdatePlayedStatus(additionalUser, request.Id, true, datePlayed);
- }
-
- return dto;
- }
-
- private PlayMethod ValidatePlayMethod(PlayMethod method, string playSessionId)
- {
- if (method == PlayMethod.Transcode)
- {
- var job = string.IsNullOrWhiteSpace(playSessionId) ? null : ApiEntryPoint.Instance.GetTranscodingJob(playSessionId);
- if (job == null)
- {
- return PlayMethod.DirectPlay;
- }
- }
-
- return method;
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(OnPlaybackStart request)
- {
- Post(new ReportPlaybackStart
- {
- CanSeek = request.CanSeek,
- ItemId = new Guid(request.Id),
- MediaSourceId = request.MediaSourceId,
- AudioStreamIndex = request.AudioStreamIndex,
- SubtitleStreamIndex = request.SubtitleStreamIndex,
- PlayMethod = request.PlayMethod,
- PlaySessionId = request.PlaySessionId,
- LiveStreamId = request.LiveStreamId
- });
- }
-
- public void Post(ReportPlaybackStart request)
- {
- request.PlayMethod = ValidatePlayMethod(request.PlayMethod, request.PlaySessionId);
-
- request.SessionId = GetSession(_sessionContext).Id;
-
- var task = _sessionManager.OnPlaybackStart(request);
-
- Task.WaitAll(task);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public void Post(OnPlaybackProgress request)
- {
- Post(new ReportPlaybackProgress
- {
- ItemId = new Guid(request.Id),
- PositionTicks = request.PositionTicks,
- IsMuted = request.IsMuted,
- IsPaused = request.IsPaused,
- MediaSourceId = request.MediaSourceId,
- AudioStreamIndex = request.AudioStreamIndex,
- SubtitleStreamIndex = request.SubtitleStreamIndex,
- VolumeLevel = request.VolumeLevel,
- PlayMethod = request.PlayMethod,
- PlaySessionId = request.PlaySessionId,
- LiveStreamId = request.LiveStreamId,
- RepeatMode = request.RepeatMode
- });
- }
-
- public void Post(ReportPlaybackProgress request)
- {
- request.PlayMethod = ValidatePlayMethod(request.PlayMethod, request.PlaySessionId);
-
- request.SessionId = GetSession(_sessionContext).Id;
-
- var task = _sessionManager.OnPlaybackProgress(request);
-
- Task.WaitAll(task);
- }
-
- public void Post(PingPlaybackSession request)
- {
- ApiEntryPoint.Instance.PingTranscodingJob(request.PlaySessionId, null);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Delete(OnPlaybackStopped request)
- {
- return Post(new ReportPlaybackStopped
- {
- ItemId = new Guid(request.Id),
- PositionTicks = request.PositionTicks,
- MediaSourceId = request.MediaSourceId,
- PlaySessionId = request.PlaySessionId,
- LiveStreamId = request.LiveStreamId,
- NextMediaType = request.NextMediaType
- });
- }
-
- public async Task Post(ReportPlaybackStopped request)
- {
- Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty);
-
- if (!string.IsNullOrWhiteSpace(request.PlaySessionId))
- {
- await ApiEntryPoint.Instance.KillTranscodingJobs(_authContext.GetAuthorizationInfo(Request).DeviceId, request.PlaySessionId, s => true);
- }
-
- request.SessionId = GetSession(_sessionContext).Id;
-
- await _sessionManager.OnPlaybackStopped(request);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Delete(MarkUnplayedItem request)
- {
- var task = MarkUnplayed(request);
-
- return ToOptimizedResult(task);
- }
-
- private UserItemDataDto MarkUnplayed(MarkUnplayedItem request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var session = GetSession(_sessionContext);
-
- var dto = UpdatePlayedStatus(user, request.Id, false, null);
-
- foreach (var additionalUserInfo in session.AdditionalUsers)
- {
- var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
-
- UpdatePlayedStatus(additionalUser, request.Id, false, null);
- }
-
- return dto;
- }
-
- /// <summary>
- /// Updates the played status.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <param name="itemId">The item id.</param>
- /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
- /// <param name="datePlayed">The date played.</param>
- /// <returns>Task.</returns>
- private UserItemDataDto UpdatePlayedStatus(User user, string itemId, bool wasPlayed, DateTime? datePlayed)
- {
- var item = _libraryManager.GetItemById(itemId);
-
- if (wasPlayed)
- {
- item.MarkPlayed(user, datePlayed, true);
- }
- else
- {
- item.MarkUnplayed(user);
- }
-
- return _userDataRepository.GetUserDataDto(item, user);
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/StudiosService.cs b/MediaBrowser.Api/UserLibrary/StudiosService.cs
deleted file mode 100644
index 890acc931..000000000
--- a/MediaBrowser.Api/UserLibrary/StudiosService.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetStudios
- /// </summary>
- [Route("/Studios", "GET", Summary = "Gets all studios from a given item, folder, or the entire library")]
- public class GetStudios : GetItemsByName
- {
- }
-
- /// <summary>
- /// Class GetStudio
- /// </summary>
- [Route("/Studios/{Name}", "GET", Summary = "Gets a studio, by name")]
- public class GetStudio : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- [ApiMember(Name = "Name", Description = "The studio name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class StudiosService
- /// </summary>
- [Authenticated]
- public class StudiosService : BaseItemsByNameService<Studio>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetStudio request)
- {
- var result = GetItem(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetStudio request)
- {
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- var item = GetStudio(request.Name, LibraryManager, dtoOptions);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetStudios request)
- {
- var result = GetResultSlim(request);
-
- return ToOptimizedResult(result);
- }
-
- protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query)
- {
- return LibraryManager.GetStudios(query);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- throw new NotImplementedException();
- }
-
- public StudiosService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs
deleted file mode 100644
index a9b06095d..000000000
--- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs
+++ /dev/null
@@ -1,550 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetItem
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}", "GET", Summary = "Gets an item from a user's library")]
- public class GetItem : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetItem
- /// </summary>
- [Route("/Users/{UserId}/Items/Root", "GET", Summary = "Gets the root folder from a user's library")]
- public class GetRootFolder : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class GetIntros
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}/Intros", "GET", Summary = "Gets intros to play before the main media item plays")]
- public class GetIntros : IReturn<QueryResult<BaseItemDto>>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the item id.
- /// </summary>
- /// <value>The item id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class MarkFavoriteItem
- /// </summary>
- [Route("/Users/{UserId}/FavoriteItems/{Id}", "POST", Summary = "Marks an item as a favorite")]
- public class MarkFavoriteItem : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class UnmarkFavoriteItem
- /// </summary>
- [Route("/Users/{UserId}/FavoriteItems/{Id}", "DELETE", Summary = "Unmarks an item as a favorite")]
- public class UnmarkFavoriteItem : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class ClearUserItemRating
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}/Rating", "DELETE", Summary = "Deletes a user's saved personal rating for an item")]
- public class DeleteUserItemRating : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class UpdateUserItemRating
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}/Rating", "POST", Summary = "Updates a user's rating for an item")]
- public class UpdateUserItemRating : IReturn<UserItemDataDto>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this <see cref="UpdateUserItemRating" /> is likes.
- /// </summary>
- /// <value><c>true</c> if likes; otherwise, <c>false</c>.</value>
- [ApiMember(Name = "Likes", Description = "Whether the user likes the item or not. true/false", IsRequired = true, DataType = "boolean", ParameterType = "query", Verb = "POST")]
- public bool Likes { get; set; }
- }
-
- /// <summary>
- /// Class GetLocalTrailers
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}/LocalTrailers", "GET", Summary = "Gets local trailers for an item")]
- public class GetLocalTrailers : IReturn<BaseItemDto[]>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- /// <summary>
- /// Class GetSpecialFeatures
- /// </summary>
- [Route("/Users/{UserId}/Items/{Id}/SpecialFeatures", "GET", Summary = "Gets special features for an item")]
- public class GetSpecialFeatures : IReturn<BaseItemDto[]>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Movie Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Users/{UserId}/Items/Latest", "GET", Summary = "Gets latest media")]
- public class GetLatestMedia : IReturn<BaseItemDto[]>, IHasDtoOptions
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "Limit", Description = "Limit", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int Limit { get; set; }
-
- [ApiMember(Name = "ParentId", Description = "Specify this to localize the search to a specific item or folder. Omit to use the root", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid ParentId { get; set; }
-
- [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string Fields { get; set; }
-
- [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
- public string IncludeItemTypes { get; set; }
-
- [ApiMember(Name = "IsFolder", Description = "Filter by items that are folders, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsFolder { get; set; }
-
- [ApiMember(Name = "IsPlayed", Description = "Filter by items that are played, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsPlayed { get; set; }
-
- [ApiMember(Name = "GroupItems", Description = "Whether or not to group items into a parent container.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool GroupItems { get; set; }
-
- [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableImages { get; set; }
-
- [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? ImageTypeLimit { get; set; }
-
- [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string EnableImageTypes { get; set; }
-
- [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? EnableUserData { get; set; }
-
- public GetLatestMedia()
- {
- Limit = 20;
- GroupItems = true;
- }
- }
-
- /// <summary>
- /// Class UserLibraryService
- /// </summary>
- [Authenticated]
- public class UserLibraryService : BaseApiService
- {
- private readonly IUserManager _userManager;
- private readonly IUserDataManager _userDataRepository;
- private readonly ILibraryManager _libraryManager;
- private readonly IDtoService _dtoService;
- private readonly IUserViewManager _userViewManager;
- private readonly IFileSystem _fileSystem;
- private readonly IAuthorizationContext _authContext;
-
- public UserLibraryService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IDtoService dtoService, IUserViewManager userViewManager, IFileSystem fileSystem, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _libraryManager = libraryManager;
- _userDataRepository = userDataRepository;
- _dtoService = dtoService;
- _userViewManager = userViewManager;
- _fileSystem = fileSystem;
- _authContext = authContext;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetSpecialFeatures request)
- {
- var result = GetAsync(request);
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetLatestMedia request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- if (!request.IsPlayed.HasValue)
- {
- if (user.Configuration.HidePlayedInLatest)
- {
- request.IsPlayed = false;
- }
- }
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var list = _userViewManager.GetLatestItems(new LatestItemsQuery
- {
- GroupItems = request.GroupItems,
- IncludeItemTypes = ApiEntryPoint.Split(request.IncludeItemTypes, ',', true),
- IsPlayed = request.IsPlayed,
- Limit = request.Limit,
- ParentId = request.ParentId,
- UserId = request.UserId,
- }, dtoOptions);
-
- var dtos = list.Select(i =>
- {
- var item = i.Item2[0];
- var childCount = 0;
-
- if (i.Item1 != null && (i.Item2.Count > 1 || i.Item1 is MusicAlbum))
- {
- item = i.Item1;
- childCount = i.Item2.Count;
- }
-
- var dto = _dtoService.GetBaseItemDto(item, dtoOptions, user);
-
- dto.ChildCount = childCount;
-
- return dto;
- });
-
- return ToOptimizedResult(dtos.ToArray());
- }
-
- private BaseItemDto[] GetAsync(GetSpecialFeatures request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ?
- _libraryManager.GetUserRootFolder() :
- _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = item.GetDisplayExtras()
- .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item));
-
- return dtos.ToArray();
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetLocalTrailers request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = item.GetExtras(new[] { ExtraType.Trailer })
- .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
- .ToArray();
-
- return ToOptimizedResult(dtos);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetItem request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(request.Id);
-
- await RefreshItemOnDemandIfNeeded(item).ConfigureAwait(false);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = _dtoService.GetBaseItemDto(item, dtoOptions, user);
-
- return ToOptimizedResult(result);
- }
-
- private async Task RefreshItemOnDemandIfNeeded(BaseItem item)
- {
- if (item is Person)
- {
- var hasMetdata = !string.IsNullOrWhiteSpace(item.Overview) && item.HasImage(ImageType.Primary);
- var performFullRefresh = !hasMetdata && (DateTime.UtcNow - item.DateLastRefreshed).TotalDays >= 3;
-
- if (!hasMetdata)
- {
- var options = new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
- {
- MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
- ImageRefreshMode = MetadataRefreshMode.FullRefresh,
- ForceSave = performFullRefresh
- };
-
- await item.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);
- }
- }
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetRootFolder request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = _libraryManager.GetUserRootFolder();
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var result = _dtoService.GetBaseItemDto(item, dtoOptions, user);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetIntros request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var item = string.IsNullOrEmpty(request.Id) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(request.Id);
-
- var items = await _libraryManager.GetIntros(item, user).ConfigureAwait(false);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var dtos = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user)).ToArray();
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = dtos,
- TotalRecordCount = dtos.Length
- };
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Post(MarkFavoriteItem request)
- {
- var dto = MarkFavorite(request.UserId, request.Id, true);
-
- return ToOptimizedResult(dto);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Delete(UnmarkFavoriteItem request)
- {
- var dto = MarkFavorite(request.UserId, request.Id, false);
-
- return ToOptimizedResult(dto);
- }
-
- /// <summary>
- /// Marks the favorite.
- /// </summary>
- /// <param name="userId">The user id.</param>
- /// <param name="itemId">The item id.</param>
- /// <param name="isFavorite">if set to <c>true</c> [is favorite].</param>
- private UserItemDataDto MarkFavorite(Guid userId, Guid itemId, bool isFavorite)
- {
- var user = _userManager.GetUserById(userId);
-
- var item = itemId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(itemId);
-
- // Get the user data for this item
- var data = _userDataRepository.GetUserData(user, item);
-
- // Set favorite status
- data.IsFavorite = isFavorite;
-
- _userDataRepository.SaveUserData(user, item, data, UserDataSaveReason.UpdateUserRating, CancellationToken.None);
-
- return _userDataRepository.GetUserDataDto(item, user);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Delete(DeleteUserItemRating request)
- {
- var dto = UpdateUserItemRating(request.UserId, request.Id, null);
-
- return ToOptimizedResult(dto);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Post(UpdateUserItemRating request)
- {
- var dto = UpdateUserItemRating(request.UserId, request.Id, request.Likes);
-
- return ToOptimizedResult(dto);
- }
-
- /// <summary>
- /// Updates the user item rating.
- /// </summary>
- /// <param name="userId">The user id.</param>
- /// <param name="itemId">The item id.</param>
- /// <param name="likes">if set to <c>true</c> [likes].</param>
- private UserItemDataDto UpdateUserItemRating(Guid userId, Guid itemId, bool? likes)
- {
- var user = _userManager.GetUserById(userId);
-
- var item = itemId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(itemId);
-
- // Get the user data for this item
- var data = _userDataRepository.GetUserData(user, item);
-
- data.Likes = likes;
-
- _userDataRepository.SaveUserData(user, item, data, UserDataSaveReason.UpdateUserRating, CancellationToken.None);
-
- return _userDataRepository.GetUserDataDto(item, user);
- }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/UserViewsService.cs b/MediaBrowser.Api/UserLibrary/UserViewsService.cs
deleted file mode 100644
index 1d61c5c1e..000000000
--- a/MediaBrowser.Api/UserLibrary/UserViewsService.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-using System;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Library;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- [Route("/Users/{UserId}/Views", "GET")]
- public class GetUserViews : IReturn<QueryResult<BaseItemDto>>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
-
- [ApiMember(Name = "IncludeExternalContent", Description = "Whether or not to include external views such as channels or live tv", IsRequired = true, DataType = "boolean", ParameterType = "query", Verb = "GET")]
- public bool? IncludeExternalContent { get; set; }
- public bool IncludeHidden { get; set; }
-
- public string PresetViews { get; set; }
- }
-
- [Route("/Users/{UserId}/GroupingOptions", "GET")]
- public class GetGroupingOptions : IReturn<SpecialViewOption[]>
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- public class UserViewsService : BaseApiService
- {
- private readonly IUserManager _userManager;
- private readonly IUserViewManager _userViewManager;
- private readonly IDtoService _dtoService;
- private readonly IAuthorizationContext _authContext;
- private readonly ILibraryManager _libraryManager;
-
- public UserViewsService(IUserManager userManager, IUserViewManager userViewManager, IDtoService dtoService, IAuthorizationContext authContext, ILibraryManager libraryManager)
- {
- _userManager = userManager;
- _userViewManager = userViewManager;
- _dtoService = dtoService;
- _authContext = authContext;
- _libraryManager = libraryManager;
- }
-
- public object Get(GetUserViews request)
- {
- var query = new UserViewQuery
- {
- UserId = request.UserId
- };
-
- if (request.IncludeExternalContent.HasValue)
- {
- query.IncludeExternalContent = request.IncludeExternalContent.Value;
- }
- query.IncludeHidden = request.IncludeHidden;
-
- if (!string.IsNullOrWhiteSpace(request.PresetViews))
- {
- query.PresetViews = request.PresetViews.Split(',');
- }
-
- var app = _authContext.GetAuthorizationInfo(Request).Client ?? string.Empty;
- if (app.IndexOf("emby rt", StringComparison.OrdinalIgnoreCase) != -1)
- {
- query.PresetViews = new[] { CollectionType.Movies, CollectionType.TvShows };
- }
-
- var folders = _userViewManager.GetUserViews(query);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
- var fields = dtoOptions.Fields.ToList();
-
- fields.Add(ItemFields.PrimaryImageAspectRatio);
- fields.Add(ItemFields.DisplayPreferencesId);
- fields.Remove(ItemFields.BasicSyncInfo);
- dtoOptions.Fields = fields.ToArray();
-
- var user = _userManager.GetUserById(request.UserId);
-
- var dtos = folders.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user))
- .ToArray();
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = dtos,
- TotalRecordCount = dtos.Length
- };
-
- return ToOptimizedResult(result);
- }
-
- public object Get(GetGroupingOptions request)
- {
- var user = _userManager.GetUserById(request.UserId);
-
- var list = _libraryManager.GetUserRootFolder()
- .GetChildren(user, true)
- .OfType<Folder>()
- .Where(UserView.IsEligibleForGrouping)
- .Select(i => new SpecialViewOption
- {
- Name = i.Name,
- Id = i.Id.ToString("N")
-
- })
- .OrderBy(i => i.Name)
- .ToArray();
-
- return ToOptimizedResult(list);
- }
- }
-
- class SpecialViewOption
- {
- public string Name { get; set; }
- public string Id { get; set; }
- }
-}
diff --git a/MediaBrowser.Api/UserLibrary/YearsService.cs b/MediaBrowser.Api/UserLibrary/YearsService.cs
deleted file mode 100644
index 0ee0fd219..000000000
--- a/MediaBrowser.Api/UserLibrary/YearsService.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api.UserLibrary
-{
- /// <summary>
- /// Class GetYears
- /// </summary>
- [Route("/Years", "GET", Summary = "Gets all years from a given item, folder, or the entire library")]
- public class GetYears : GetItemsByName
- {
- }
-
- /// <summary>
- /// Class GetYear
- /// </summary>
- [Route("/Years/{Year}", "GET", Summary = "Gets a year")]
- public class GetYear : IReturn<BaseItemDto>
- {
- /// <summary>
- /// Gets or sets the year.
- /// </summary>
- /// <value>The year.</value>
- [ApiMember(Name = "Year", Description = "The year", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
- public int Year { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
- }
-
- /// <summary>
- /// Class YearsService
- /// </summary>
- [Authenticated]
- public class YearsService : BaseItemsByNameService<Year>
- {
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetYear request)
- {
- var result = GetItem(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the item.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task{BaseItemDto}.</returns>
- private BaseItemDto GetItem(GetYear request)
- {
- var item = LibraryManager.GetYear(request.Year);
-
- var dtoOptions = GetDtoOptions(AuthorizationContext, request);
-
- if (!request.UserId.Equals(Guid.Empty))
- {
- var user = UserManager.GetUserById(request.UserId);
-
- return DtoService.GetBaseItemDto(item, dtoOptions, user);
- }
-
- return DtoService.GetBaseItemDto(item, dtoOptions);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetYears request)
- {
- var result = GetResult(request);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets all items.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="items">The items.</param>
- /// <returns>IEnumerable{Tuple{System.StringFunc{System.Int32}}}.</returns>
- protected override IEnumerable<BaseItem> GetAllItems(GetItemsByName request, IList<BaseItem> items)
- {
- return items
- .Select(i => i.ProductionYear ?? 0)
- .Where(i => i > 0)
- .Distinct()
- .Select(year => LibraryManager.GetYear(year));
- }
-
- public YearsService(IUserManager userManager, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepository, IDtoService dtoService, IAuthorizationContext authorizationContext) : base(userManager, libraryManager, userDataRepository, itemRepository, dtoService, authorizationContext)
- {
- }
- }
-}
diff --git a/MediaBrowser.Api/UserService.cs b/MediaBrowser.Api/UserService.cs
deleted file mode 100644
index a6849f75f..000000000
--- a/MediaBrowser.Api/UserService.cs
+++ /dev/null
@@ -1,578 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.Users;
-
-namespace MediaBrowser.Api
-{
- /// <summary>
- /// Class GetUsers
- /// </summary>
- [Route("/Users", "GET", Summary = "Gets a list of users")]
- [Authenticated]
- public class GetUsers : IReturn<UserDto[]>
- {
- [ApiMember(Name = "IsHidden", Description = "Optional filter by IsHidden=true or false", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsHidden { get; set; }
-
- [ApiMember(Name = "IsDisabled", Description = "Optional filter by IsDisabled=true or false", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsDisabled { get; set; }
-
- [ApiMember(Name = "IsGuest", Description = "Optional filter by IsGuest=true or false", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool? IsGuest { get; set; }
- }
-
- [Route("/Users/Public", "GET", Summary = "Gets a list of publicly visible users for display on a login screen.")]
- public class GetPublicUsers : IReturn<UserDto[]>
- {
- }
-
- /// <summary>
- /// Class GetUser
- /// </summary>
- [Route("/Users/{Id}", "GET", Summary = "Gets a user by Id")]
- [Authenticated(EscapeParentalControl = true)]
- public class GetUser : IReturn<UserDto>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class DeleteUser
- /// </summary>
- [Route("/Users/{Id}", "DELETE", Summary = "Deletes a user")]
- [Authenticated(Roles = "Admin")]
- public class DeleteUser : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class AuthenticateUser
- /// </summary>
- [Route("/Users/{Id}/Authenticate", "POST", Summary = "Authenticates a user")]
- public class AuthenticateUser : IReturn<AuthenticationResult>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "Pw", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Pw { get; set; }
-
- /// <summary>
- /// Gets or sets the password.
- /// </summary>
- /// <value>The password.</value>
- [ApiMember(Name = "Password", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Password { get; set; }
- }
-
- /// <summary>
- /// Class AuthenticateUser
- /// </summary>
- [Route("/Users/AuthenticateByName", "POST", Summary = "Authenticates a user")]
- public class AuthenticateUserByName : IReturn<AuthenticationResult>
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Username", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Username { get; set; }
-
- /// <summary>
- /// Gets or sets the password.
- /// </summary>
- /// <value>The password.</value>
- [ApiMember(Name = "Password", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Password { get; set; }
-
- [ApiMember(Name = "Pw", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Pw { get; set; }
- }
-
- /// <summary>
- /// Class UpdateUserPassword
- /// </summary>
- [Route("/Users/{Id}/Password", "POST", Summary = "Updates a user's password")]
- [Authenticated]
- public class UpdateUserPassword : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public Guid Id { get; set; }
-
- /// <summary>
- /// Gets or sets the password.
- /// </summary>
- /// <value>The password.</value>
- public string CurrentPassword { get; set; }
-
- public string CurrentPw { get; set; }
-
- public string NewPw { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [reset password].
- /// </summary>
- /// <value><c>true</c> if [reset password]; otherwise, <c>false</c>.</value>
- public bool ResetPassword { get; set; }
- }
-
- /// <summary>
- /// Class UpdateUserEasyPassword
- /// </summary>
- [Route("/Users/{Id}/EasyPassword", "POST", Summary = "Updates a user's easy password")]
- [Authenticated]
- public class UpdateUserEasyPassword : IReturnVoid
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public Guid Id { get; set; }
-
- /// <summary>
- /// Gets or sets the new password.
- /// </summary>
- /// <value>The new password.</value>
- public string NewPassword { get; set; }
-
- public string NewPw { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [reset password].
- /// </summary>
- /// <value><c>true</c> if [reset password]; otherwise, <c>false</c>.</value>
- public bool ResetPassword { get; set; }
- }
-
- /// <summary>
- /// Class UpdateUser
- /// </summary>
- [Route("/Users/{Id}", "POST", Summary = "Updates a user")]
- [Authenticated]
- public class UpdateUser : UserDto, IReturnVoid
- {
- }
-
- /// <summary>
- /// Class UpdateUser
- /// </summary>
- [Route("/Users/{Id}/Policy", "POST", Summary = "Updates a user policy")]
- [Authenticated(Roles = "admin")]
- public class UpdateUserPolicy : UserPolicy, IReturnVoid
- {
- [ApiMember(Name = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class UpdateUser
- /// </summary>
- [Route("/Users/{Id}/Configuration", "POST", Summary = "Updates a user configuration")]
- [Authenticated]
- public class UpdateUserConfiguration : UserConfiguration, IReturnVoid
- {
- [ApiMember(Name = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
- public Guid Id { get; set; }
- }
-
- /// <summary>
- /// Class CreateUser
- /// </summary>
- [Route("/Users/New", "POST", Summary = "Creates a user")]
- [Authenticated(Roles = "Admin")]
- public class CreateUserByName : IReturn<UserDto>
- {
- [ApiMember(Name = "Name", IsRequired = true, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Name { get; set; }
- }
-
- [Route("/Users/ForgotPassword", "POST", Summary = "Initiates the forgot password process for a local user")]
- public class ForgotPassword : IReturn<ForgotPasswordResult>
- {
- [ApiMember(Name = "EnteredUsername", IsRequired = false, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string EnteredUsername { get; set; }
- }
-
- [Route("/Users/ForgotPassword/Pin", "POST", Summary = "Redeems a forgot password pin")]
- public class ForgotPasswordPin : IReturn<PinRedeemResult>
- {
- [ApiMember(Name = "Pin", IsRequired = false, DataType = "string", ParameterType = "body", Verb = "POST")]
- public string Pin { get; set; }
- }
-
- /// <summary>
- /// Class UsersService
- /// </summary>
- public class UserService : BaseApiService
- {
- /// <summary>
- /// The _user manager
- /// </summary>
- private readonly IUserManager _userManager;
- private readonly ISessionManager _sessionMananger;
- private readonly IServerConfigurationManager _config;
- private readonly INetworkManager _networkManager;
- private readonly IDeviceManager _deviceManager;
- private readonly IAuthorizationContext _authContext;
-
- public UserService(IUserManager userManager, ISessionManager sessionMananger, IServerConfigurationManager config, INetworkManager networkManager, IDeviceManager deviceManager, IAuthorizationContext authContext)
- {
- _userManager = userManager;
- _sessionMananger = sessionMananger;
- _config = config;
- _networkManager = networkManager;
- _deviceManager = deviceManager;
- _authContext = authContext;
- }
-
- public object Get(GetPublicUsers request)
- {
- // If the startup wizard hasn't been completed then just return all users
- if (!_config.Configuration.IsStartupWizardCompleted)
- {
- return Get(new GetUsers
- {
- IsDisabled = false
- });
- }
-
- return Get(new GetUsers
- {
- IsHidden = false,
- IsDisabled = false
-
- }, true, true);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetUsers request)
- {
- return Get(request, false, false);
- }
-
- private object Get(GetUsers request, bool filterByDevice, bool filterByNetwork)
- {
- var users = _userManager.Users;
-
- if (request.IsDisabled.HasValue)
- {
- users = users.Where(i => i.Policy.IsDisabled == request.IsDisabled.Value);
- }
-
- if (request.IsHidden.HasValue)
- {
- users = users.Where(i => i.Policy.IsHidden == request.IsHidden.Value);
- }
-
- if (filterByDevice)
- {
- var deviceId = _authContext.GetAuthorizationInfo(Request).DeviceId;
-
- if (!string.IsNullOrWhiteSpace(deviceId))
- {
- users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
- }
- }
-
- if (filterByNetwork)
- {
- if (!_networkManager.IsInLocalNetwork(Request.RemoteIp))
- {
- users = users.Where(i => i.Policy.EnableRemoteAccess);
- }
- }
-
- var result = users
- .OrderBy(u => u.Name)
- .Select(i => _userManager.GetUserDto(i, Request.RemoteIp))
- .ToArray();
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetUser request)
- {
- var user = _userManager.GetUserById(request.Id);
-
- if (user == null)
- {
- throw new ResourceNotFoundException("User not found");
- }
-
- var result = _userManager.GetUserDto(user, Request.RemoteIp);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Deletes the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Delete(DeleteUser request)
- {
- return DeleteAsync(request);
- }
-
- public Task DeleteAsync(DeleteUser request)
- {
- var user = _userManager.GetUserById(request.Id);
-
- if (user == null)
- {
- throw new ResourceNotFoundException("User not found");
- }
-
- _sessionMananger.RevokeUserTokens(user.Id, null);
-
- return _userManager.DeleteUser(user);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public object Post(AuthenticateUser request)
- {
- var user = _userManager.GetUserById(request.Id);
-
- if (user == null)
- {
- throw new ResourceNotFoundException("User not found");
- }
-
- return Post(new AuthenticateUserByName
- {
- Username = user.Name,
- Password = request.Password,
- Pw = request.Pw
- });
- }
-
- public async Task<object> Post(AuthenticateUserByName request)
- {
- var auth = _authContext.GetAuthorizationInfo(Request);
-
- var result = await _sessionMananger.AuthenticateNewSession(new AuthenticationRequest
- {
- App = auth.Client,
- AppVersion = auth.Version,
- DeviceId = auth.DeviceId,
- DeviceName = auth.Device,
- Password = request.Pw,
- PasswordSha1 = request.Password,
- RemoteEndPoint = Request.RemoteIp,
- Username = request.Username
-
- }).ConfigureAwait(false);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public Task Post(UpdateUserPassword request)
- {
- return PostAsync(request);
- }
-
- public async Task PostAsync(UpdateUserPassword request)
- {
- AssertCanUpdateUser(_authContext, _userManager, request.Id, true);
-
- var user = _userManager.GetUserById(request.Id);
-
- if (user == null)
- {
- throw new ResourceNotFoundException("User not found");
- }
-
- if (request.ResetPassword)
- {
- await _userManager.ResetPassword(user).ConfigureAwait(false);
- }
- else
- {
- var success = await _userManager.AuthenticateUser(user.Name, request.CurrentPw, request.CurrentPassword, Request.RemoteIp, false).ConfigureAwait(false);
-
- if (success == null)
- {
- throw new ArgumentException("Invalid user or password entered.");
- }
-
- await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false);
-
- var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
-
- _sessionMananger.RevokeUserTokens(user.Id, currentToken);
- }
- }
-
- public void Post(UpdateUserEasyPassword request)
- {
- AssertCanUpdateUser(_authContext, _userManager, request.Id, true);
-
- var user = _userManager.GetUserById(request.Id);
-
- if (user == null)
- {
- throw new ResourceNotFoundException("User not found");
- }
-
- if (request.ResetPassword)
- {
- _userManager.ResetEasyPassword(user);
- }
- else
- {
- _userManager.ChangeEasyPassword(user, request.NewPw, request.NewPassword);
- }
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- public async Task Post(UpdateUser request)
- {
- var id = GetPathValue(1);
-
- AssertCanUpdateUser(_authContext, _userManager, new Guid(id), false);
-
- var dtoUser = request;
-
- var user = _userManager.GetUserById(id);
-
- if (string.Equals(user.Name, dtoUser.Name, StringComparison.Ordinal))
- {
- _userManager.UpdateUser(user);
- _userManager.UpdateConfiguration(user, dtoUser.Configuration);
- }
- else
- {
- await _userManager.RenameUser(user, dtoUser.Name).ConfigureAwait(false);
-
- _userManager.UpdateConfiguration(dtoUser.Id, dtoUser.Configuration);
- }
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Post(CreateUserByName request)
- {
- var dtoUser = request;
-
- var newUser = await _userManager.CreateUser(dtoUser.Name).ConfigureAwait(false);
-
- var result = _userManager.GetUserDto(newUser, Request.RemoteIp);
-
- return ToOptimizedResult(result);
- }
-
- /// <summary>
- /// Posts the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Post(ForgotPassword request)
- {
- var isLocal = Request.IsLocal || _networkManager.IsInLocalNetwork(Request.RemoteIp);
-
- var result = await _userManager.StartForgotPasswordProcess(request.EnteredUsername, isLocal).ConfigureAwait(false);
-
- return result;
- }
-
- public async Task<object> Post(ForgotPasswordPin request)
- {
- var result = await _userManager.RedeemPasswordResetPin(request.Pin).ConfigureAwait(false);
-
- return result;
- }
-
- public void Post(UpdateUserConfiguration request)
- {
- AssertCanUpdateUser(_authContext, _userManager, request.Id, false);
-
- _userManager.UpdateConfiguration(request.Id, request);
-
- }
-
- public void Post(UpdateUserPolicy request)
- {
- var user = _userManager.GetUserById(request.Id);
-
- // If removing admin access
- if (!request.IsAdministrator && user.Policy.IsAdministrator)
- {
- if (_userManager.Users.Count(i => i.Policy.IsAdministrator) == 1)
- {
- throw new ArgumentException("There must be at least one user in the system with administrative access.");
- }
- }
-
- // If disabling
- if (request.IsDisabled && user.Policy.IsAdministrator)
- {
- throw new ArgumentException("Administrators cannot be disabled.");
- }
-
- // If disabling
- if (request.IsDisabled && !user.Policy.IsDisabled)
- {
- if (_userManager.Users.Count(i => !i.Policy.IsDisabled) == 1)
- {
- throw new ArgumentException("There must be at least one enabled user in the system.");
- }
-
- var currentToken = _authContext.GetAuthorizationInfo(Request).Token;
- _sessionMananger.RevokeUserTokens(user.Id, currentToken);
- }
-
- _userManager.UpdateUserPolicy(request.Id, request);
- }
- }
-}
diff --git a/MediaBrowser.Api/VideosService.cs b/MediaBrowser.Api/VideosService.cs
deleted file mode 100644
index 061f72438..000000000
--- a/MediaBrowser.Api/VideosService.cs
+++ /dev/null
@@ -1,200 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/Videos/{Id}/AdditionalParts", "GET", Summary = "Gets additional parts for a video.")]
- [Authenticated]
- public class GetAdditionalParts : IReturn<QueryResult<BaseItemDto>>
- {
- [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string Id { get; set; }
- }
-
- [Route("/Videos/{Id}/AlternateSources", "DELETE", Summary = "Removes alternate video sources.")]
- [Authenticated(Roles = "Admin")]
- public class DeleteAlternateSources : IReturnVoid
- {
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
- public string Id { get; set; }
- }
-
- [Route("/Videos/MergeVersions", "POST", Summary = "Merges videos into a single record")]
- [Authenticated(Roles = "Admin")]
- public class MergeVersions : IReturnVoid
- {
- [ApiMember(Name = "Ids", Description = "Item id list. This allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
- public string Ids { get; set; }
- }
-
- public class VideosService : BaseApiService
- {
- private readonly ILibraryManager _libraryManager;
- private readonly IUserManager _userManager;
- private readonly IDtoService _dtoService;
- private readonly IFileSystem _fileSystem;
- private readonly IItemRepository _itemRepo;
- private readonly IServerConfigurationManager _config;
- private readonly IAuthorizationContext _authContext;
-
- public VideosService(ILibraryManager libraryManager, IUserManager userManager, IDtoService dtoService, IItemRepository itemRepo, IFileSystem fileSystem, IServerConfigurationManager config, IAuthorizationContext authContext)
- {
- _libraryManager = libraryManager;
- _userManager = userManager;
- _dtoService = dtoService;
- _itemRepo = itemRepo;
- _fileSystem = fileSystem;
- _config = config;
- _authContext = authContext;
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetAdditionalParts request)
- {
- var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
- var item = string.IsNullOrEmpty(request.Id)
- ? (!request.UserId.Equals(Guid.Empty)
- ? _libraryManager.GetUserRootFolder()
- : _libraryManager.RootFolder)
- : _libraryManager.GetItemById(request.Id);
-
- var dtoOptions = GetDtoOptions(_authContext, request);
-
- var video = item as Video;
- BaseItemDto[] items;
- if (video != null)
- {
- items = video.GetAdditionalParts()
- .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, video))
- .ToArray();
- }
- else
- {
- items = new BaseItemDto[] { };
- }
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = items,
- TotalRecordCount = items.Length
- };
-
- return ToOptimizedResult(result);
- }
-
- public void Delete(DeleteAlternateSources request)
- {
- var video = (Video)_libraryManager.GetItemById(request.Id);
-
- foreach (var link in video.GetLinkedAlternateVersions())
- {
- link.SetPrimaryVersionId(null);
- link.LinkedAlternateVersions = Array.Empty<LinkedChild>();
-
- link.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- }
-
- video.LinkedAlternateVersions = Array.Empty<LinkedChild>();
- video.SetPrimaryVersionId(null);
- video.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- }
-
- public void Post(MergeVersions request)
- {
- var items = request.Ids.Split(',')
- .Select(i => _libraryManager.GetItemById(i))
- .OfType<Video>()
- .ToList();
-
- if (items.Count < 2)
- {
- throw new ArgumentException("Please supply at least two videos to merge.");
- }
-
- var videosWithVersions = items.Where(i => i.MediaSourceCount > 1)
- .ToList();
-
- var primaryVersion = videosWithVersions.FirstOrDefault();
-
- if (primaryVersion == null)
- {
- primaryVersion = items.OrderBy(i =>
- {
- if (i.Video3DFormat.HasValue)
- {
- return 1;
- }
-
- if (i.VideoType != Model.Entities.VideoType.VideoFile)
- {
- return 1;
- }
-
- return 0;
- })
- .ThenByDescending(i =>
- {
- var stream = i.GetDefaultVideoStream();
-
- return stream == null || stream.Width == null ? 0 : stream.Width.Value;
-
- }).First();
- }
-
- var list = primaryVersion.LinkedAlternateVersions.ToList();
-
- foreach (var item in items.Where(i => i.Id != primaryVersion.Id))
- {
- item.SetPrimaryVersionId(primaryVersion.Id.ToString("N"));
-
- item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
-
- list.Add(new LinkedChild
- {
- Path = item.Path,
- ItemId = item.Id
- });
-
- foreach (var linkedItem in item.LinkedAlternateVersions)
- {
- if (!list.Any(i => string.Equals(i.Path, linkedItem.Path, StringComparison.OrdinalIgnoreCase)))
- {
- list.Add(linkedItem);
- }
- }
-
- if (item.LinkedAlternateVersions.Length > 0)
- {
- item.LinkedAlternateVersions = Array.Empty<LinkedChild>();
- item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- }
- }
-
- primaryVersion.LinkedAlternateVersions = list.ToArray();
- primaryVersion.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- }
- }
-}
diff --git a/MediaBrowser.Common/Configuration/ConfigurationStore.cs b/MediaBrowser.Common/Configuration/ConfigurationStore.cs
new file mode 100644
index 000000000..050ab1ab5
--- /dev/null
+++ b/MediaBrowser.Common/Configuration/ConfigurationStore.cs
@@ -0,0 +1,22 @@
+#nullable disable
+
+using System;
+
+namespace MediaBrowser.Common.Configuration
+{
+ /// <summary>
+ /// Describes a single entry in the application configuration.
+ /// </summary>
+ public class ConfigurationStore
+ {
+ /// <summary>
+ /// Gets or sets the unique identifier for the configuration.
+ /// </summary>
+ public string Key { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type used to store the data for this configuration entry.
+ /// </summary>
+ public Type ConfigurationType { get; set; }
+ }
+}
diff --git a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs
index 0b59627cc..2df87d879 100644
--- a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs
+++ b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Common.Configuration
@@ -9,6 +12,7 @@ namespace MediaBrowser.Common.Configuration
/// </summary>
/// <value>The key.</value>
public string Key { get; set; }
+
/// <summary>
/// Gets or sets the new configuration.
/// </summary>
diff --git a/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs
new file mode 100644
index 000000000..89740ae08
--- /dev/null
+++ b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs
@@ -0,0 +1,43 @@
+using System;
+using System.IO;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.Common.Configuration
+{
+ /// <summary>
+ /// Class containing extension methods for working with the encoding configuration.
+ /// </summary>
+ public static class EncodingConfigurationExtensions
+ {
+ /// <summary>
+ /// Gets the encoding options.
+ /// </summary>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <returns>The encoding options.</returns>
+ public static EncodingOptions GetEncodingOptions(this IConfigurationManager configurationManager)
+ => configurationManager.GetConfiguration<EncodingOptions>("encoding");
+
+ /// <summary>
+ /// Retrieves the transcoding temp path from the encoding configuration, falling back to a default if no path
+ /// is specified in configuration. If the directory does not exist, it will be created.
+ /// </summary>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <returns>The transcoding temp path.</returns>
+ /// <exception cref="UnauthorizedAccessException">If the directory does not exist, and the caller does not have the required permission to create it.</exception>
+ /// <exception cref="NotSupportedException">If there is a custom path transcoding path specified, but it is invalid.</exception>
+ /// <exception cref="IOException">If the directory does not exist, and it also could not be created.</exception>
+ public static string GetTranscodePath(this IConfigurationManager configurationManager)
+ {
+ // Get the configured path and fall back to a default
+ var transcodingTempPath = configurationManager.GetEncodingOptions().TranscodingTempPath;
+ if (string.IsNullOrEmpty(transcodingTempPath))
+ {
+ transcodingTempPath = Path.Combine(configurationManager.CommonApplicationPaths.ProgramDataPath, "transcodes");
+ }
+
+ // Make sure the directory exists
+ Directory.CreateDirectory(transcodingTempPath);
+ return transcodingTempPath;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Configuration/IApplicationPaths.cs b/MediaBrowser.Common/Configuration/IApplicationPaths.cs
index cb4e8bf5f..1370e6d79 100644
--- a/MediaBrowser.Common/Configuration/IApplicationPaths.cs
+++ b/MediaBrowser.Common/Configuration/IApplicationPaths.cs
@@ -1,24 +1,34 @@
+#nullable disable
+
namespace MediaBrowser.Common.Configuration
{
/// <summary>
- /// Interface IApplicationPaths
+ /// Interface IApplicationPaths.
/// </summary>
public interface IApplicationPaths
{
/// <summary>
- /// Gets the path to the program data folder
+ /// Gets the path to the program data folder.
/// </summary>
/// <value>The program data path.</value>
string ProgramDataPath { get; }
/// <summary>
- /// Gets the path to the program system folder
+ /// Gets the path to the web UI resources folder.
+ /// </summary>
+ /// <remarks>
+ /// This value is not relevant if the server is configured to not host any static web content.
+ /// </remarks>
+ string WebPath { get; }
+
+ /// <summary>
+ /// Gets the path to the program system folder.
/// </summary>
/// <value>The program data path.</value>
string ProgramSystemPath { get; }
/// <summary>
- /// Gets the folder path to the data directory
+ /// Gets the folder path to the data directory.
/// </summary>
/// <value>The data directory.</value>
string DataPath { get; }
@@ -30,48 +40,51 @@ namespace MediaBrowser.Common.Configuration
string ImageCachePath { get; }
/// <summary>
- /// Gets the path to the plugin directory
+ /// Gets the path to the plugin directory.
/// </summary>
/// <value>The plugins path.</value>
string PluginsPath { get; }
/// <summary>
- /// Gets the path to the plugin configurations directory
+ /// Gets the path to the plugin configurations directory.
/// </summary>
/// <value>The plugin configurations path.</value>
string PluginConfigurationsPath { get; }
/// <summary>
- /// Gets the path to the log directory
+ /// Gets the path to the log directory.
/// </summary>
/// <value>The log directory path.</value>
string LogDirectoryPath { get; }
/// <summary>
- /// Gets the path to the application configuration root directory
+ /// Gets the path to the application configuration root directory.
/// </summary>
/// <value>The configuration directory path.</value>
string ConfigurationDirectoryPath { get; }
/// <summary>
- /// Gets the path to the system configuration file
+ /// Gets the path to the system configuration file.
/// </summary>
/// <value>The system configuration file path.</value>
string SystemConfigurationFilePath { get; }
/// <summary>
- /// Gets the folder path to the cache directory
+ /// Gets the folder path to the cache directory.
/// </summary>
/// <value>The cache directory.</value>
string CachePath { get; }
/// <summary>
- /// Gets the folder path to the temp directory within the cache folder
+ /// Gets the folder path to the temp directory within the cache folder.
/// </summary>
/// <value>The temp directory.</value>
string TempDirectory { get; }
+ /// <summary>
+ /// Gets the magic string used for virtual path manipulation.
+ /// </summary>
+ /// <value>The magic string used for virtual path manipulation.</value>
string VirtualDataPath { get; }
}
-
}
diff --git a/MediaBrowser.Common/Configuration/IConfigurationFactory.cs b/MediaBrowser.Common/Configuration/IConfigurationFactory.cs
index 0fb2b83d1..6db1f1364 100644
--- a/MediaBrowser.Common/Configuration/IConfigurationFactory.cs
+++ b/MediaBrowser.Common/Configuration/IConfigurationFactory.cs
@@ -1,22 +1,17 @@
-using System;
using System.Collections.Generic;
namespace MediaBrowser.Common.Configuration
{
+ /// <summary>
+ /// Provides an interface to retrieve a configuration store. Classes with this interface are scanned for at
+ /// application start to dynamically register configuration for various modules/plugins.
+ /// </summary>
public interface IConfigurationFactory
{
+ /// <summary>
+ /// Get the configuration store for this module.
+ /// </summary>
+ /// <returns>The configuration store.</returns>
IEnumerable<ConfigurationStore> GetConfigurations();
}
-
- public class ConfigurationStore
- {
- public string Key { get; set; }
-
- public Type ConfigurationType { get; set; }
- }
-
- public interface IValidatingConfiguration
- {
- void Validate(object oldConfig, object newConfig);
- }
}
diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs
index 8fed2dcdf..fc63d9350 100644
--- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs
+++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Configuration;
@@ -22,7 +24,7 @@ namespace MediaBrowser.Common.Configuration
event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdated;
/// <summary>
- /// Gets or sets the application paths.
+ /// Gets the application paths.
/// </summary>
/// <value>The application paths.</value>
IApplicationPaths CommonApplicationPaths { get; }
@@ -45,6 +47,13 @@ namespace MediaBrowser.Common.Configuration
void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration);
/// <summary>
+ /// Manually pre-loads a factory so that it is available pre system initialisation.
+ /// </summary>
+ /// <typeparam name="T">Class to register.</typeparam>
+ void RegisterConfiguration<T>()
+ where T : IConfigurationFactory;
+
+ /// <summary>
/// Gets the configuration.
/// </summary>
/// <param name="key">The key.</param>
diff --git a/MediaBrowser.Common/Configuration/IValidatingConfiguration.cs b/MediaBrowser.Common/Configuration/IValidatingConfiguration.cs
new file mode 100644
index 000000000..3b1d84f3c
--- /dev/null
+++ b/MediaBrowser.Common/Configuration/IValidatingConfiguration.cs
@@ -0,0 +1,15 @@
+namespace MediaBrowser.Common.Configuration
+{
+ /// <summary>
+ /// A configuration store that can be validated.
+ /// </summary>
+ public interface IValidatingConfiguration
+ {
+ /// <summary>
+ /// Validation method to be invoked before saving the configuration.
+ /// </summary>
+ /// <param name="oldConfig">The old configuration.</param>
+ /// <param name="newConfig">The new configuration.</param>
+ void Validate(object oldConfig, object newConfig);
+ }
+}
diff --git a/MediaBrowser.Common/Crc32.cs b/MediaBrowser.Common/Crc32.cs
new file mode 100644
index 000000000..599eb4c99
--- /dev/null
+++ b/MediaBrowser.Common/Crc32.cs
@@ -0,0 +1,89 @@
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Common
+{
+ public static class Crc32
+ {
+ private static readonly uint[] _crcTable =
+ {
+ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
+ 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
+ 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
+ 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
+ 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
+ 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
+ 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
+ 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
+ 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
+ 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
+ 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
+ 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
+ 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
+ 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
+ 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
+ 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
+ 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
+ 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
+ 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
+ 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
+ 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
+ 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
+ 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
+ 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
+ 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
+ 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
+ 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
+ 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
+ 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
+ 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
+ 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
+ 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
+ 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
+ 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
+ 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
+ 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
+ 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
+ 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
+ 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
+ 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
+ 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
+ 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
+ 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
+ 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
+ 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
+ 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
+ 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
+ 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
+ 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
+ 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
+ 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
+ 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
+ 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
+ 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
+ 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
+ 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
+ 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
+ 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
+ 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
+ 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
+ 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
+ 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
+ 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
+ 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
+ };
+
+ public static uint Compute(ReadOnlySpan<byte> bytes)
+ {
+ var crc = 0xffffffff;
+ var len = bytes.Length;
+ for (var i = 0; i < len; i++)
+ {
+ crc = (crc >> 8) ^ _crcTable[(bytes[i] ^ crc) & 0xff];
+ }
+
+ return ~crc;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Cryptography/Constants.cs b/MediaBrowser.Common/Cryptography/Constants.cs
new file mode 100644
index 000000000..354114232
--- /dev/null
+++ b/MediaBrowser.Common/Cryptography/Constants.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Common.Cryptography
+{
+ /// <summary>
+ /// Class containing global constants for Jellyfin Cryptography.
+ /// </summary>
+ public static class Constants
+ {
+ /// <summary>
+ /// The default length for new salts.
+ /// </summary>
+ public const int DefaultSaltLength = 64;
+
+ /// <summary>
+ /// The default amount of iterations for hashing passwords.
+ /// </summary>
+ public const int DefaultIterations = 1000;
+ }
+}
diff --git a/MediaBrowser.Common/Cryptography/CryptoExtensions.cs b/MediaBrowser.Common/Cryptography/CryptoExtensions.cs
new file mode 100644
index 000000000..157b0ed10
--- /dev/null
+++ b/MediaBrowser.Common/Cryptography/CryptoExtensions.cs
@@ -0,0 +1,35 @@
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using MediaBrowser.Model.Cryptography;
+using static MediaBrowser.Common.Cryptography.Constants;
+
+namespace MediaBrowser.Common.Cryptography
+{
+ /// <summary>
+ /// Class containing extension methods for working with Jellyfin cryptography objects.
+ /// </summary>
+ public static class CryptoExtensions
+ {
+ /// <summary>
+ /// Creates a new <see cref="PasswordHash" /> instance.
+ /// </summary>
+ /// <param name="cryptoProvider">The <see cref="ICryptoProvider" /> instance used.</param>
+ /// <param name="password">The password that will be hashed.</param>
+ /// <returns>A <see cref="PasswordHash" /> instance with the hash method, hash, salt and number of iterations.</returns>
+ public static PasswordHash CreatePasswordHash(this ICryptoProvider cryptoProvider, string password)
+ {
+ byte[] salt = cryptoProvider.GenerateSalt();
+ return new PasswordHash(
+ cryptoProvider.DefaultHashMethod,
+ cryptoProvider.ComputeHashWithDefaultMethod(
+ Encoding.UTF8.GetBytes(password),
+ salt),
+ salt,
+ new Dictionary<string, string>
+ {
+ { "iterations", DefaultIterations.ToString(CultureInfo.InvariantCulture) }
+ });
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs
new file mode 100644
index 000000000..0e2065302
--- /dev/null
+++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs
@@ -0,0 +1,219 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace MediaBrowser.Common.Cryptography
+{
+ // Defined from this hash storage spec
+ // https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
+ // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
+ // with one slight amendment to ease the transition, we're writing out the bytes in hex
+ // rather than making them a BASE64 string with stripped padding
+ public class PasswordHash
+ {
+ private readonly Dictionary<string, string> _parameters;
+ private readonly byte[] _salt;
+ private readonly byte[] _hash;
+
+ public PasswordHash(string id, byte[] hash)
+ : this(id, hash, Array.Empty<byte>())
+ {
+ }
+
+ public PasswordHash(string id, byte[] hash, byte[] salt)
+ : this(id, hash, salt, new Dictionary<string, string>())
+ {
+ }
+
+ public PasswordHash(string id, byte[] hash, byte[] salt, Dictionary<string, string> parameters)
+ {
+ if (id == null)
+ {
+ throw new ArgumentNullException(nameof(id));
+ }
+
+ if (id.Length == 0)
+ {
+ throw new ArgumentException("String can't be empty", nameof(id));
+ }
+
+ Id = id;
+ _hash = hash;
+ _salt = salt;
+ _parameters = parameters;
+ }
+
+ /// <summary>
+ /// Gets the symbolic name for the function used.
+ /// </summary>
+ /// <value>Returns the symbolic name for the function used.</value>
+ public string Id { get; }
+
+ /// <summary>
+ /// Gets the additional parameters used by the hash function.
+ /// </summary>
+ public IReadOnlyDictionary<string, string> Parameters => _parameters;
+
+ /// <summary>
+ /// Gets the salt used for hashing the password.
+ /// </summary>
+ /// <value>Returns the salt used for hashing the password.</value>
+ public ReadOnlySpan<byte> Salt => _salt;
+
+ /// <summary>
+ /// Gets the hashed password.
+ /// </summary>
+ /// <value>Return the hashed password.</value>
+ public ReadOnlySpan<byte> Hash => _hash;
+
+ public static PasswordHash Parse(ReadOnlySpan<char> hashString)
+ {
+ if (hashString.IsEmpty)
+ {
+ throw new ArgumentException("String can't be empty", nameof(hashString));
+ }
+
+ if (hashString[0] != '$')
+ {
+ throw new FormatException("Hash string must start with a $");
+ }
+
+ // Ignore first $
+ hashString = hashString[1..];
+
+ int nextSegment = hashString.IndexOf('$');
+ if (hashString.IsEmpty || nextSegment == 0)
+ {
+ throw new FormatException("Hash string must contain a valid id");
+ }
+ else if (nextSegment == -1)
+ {
+ return new PasswordHash(hashString.ToString(), Array.Empty<byte>());
+ }
+
+ ReadOnlySpan<char> id = hashString[..nextSegment];
+ hashString = hashString[(nextSegment + 1)..];
+ Dictionary<string, string>? parameters = null;
+
+ nextSegment = hashString.IndexOf('$');
+
+ // Optional parameters
+ ReadOnlySpan<char> parametersSpan = nextSegment == -1 ? hashString : hashString[..nextSegment];
+ if (parametersSpan.Contains('='))
+ {
+ while (!parametersSpan.IsEmpty)
+ {
+ ReadOnlySpan<char> parameter;
+ int index = parametersSpan.IndexOf(',');
+ if (index == -1)
+ {
+ parameter = parametersSpan;
+ parametersSpan = ReadOnlySpan<char>.Empty;
+ }
+ else
+ {
+ parameter = parametersSpan[..index];
+ parametersSpan = parametersSpan[(index + 1)..];
+ }
+
+ int splitIndex = parameter.IndexOf('=');
+ if (splitIndex == -1 || splitIndex == 0 || splitIndex == parameter.Length - 1)
+ {
+ throw new FormatException("Malformed parameter in password hash string");
+ }
+
+ (parameters ??= new Dictionary<string, string>()).Add(
+ parameter[..splitIndex].ToString(),
+ parameter[(splitIndex + 1)..].ToString());
+ }
+
+ if (nextSegment == -1)
+ {
+ // parameters can't be null here
+ return new PasswordHash(id.ToString(), Array.Empty<byte>(), Array.Empty<byte>(), parameters!);
+ }
+
+ hashString = hashString[(nextSegment + 1)..];
+ nextSegment = hashString.IndexOf('$');
+ }
+
+ if (nextSegment == 0)
+ {
+ throw new FormatException("Hash string contains an empty segment");
+ }
+
+ byte[] hash;
+ byte[] salt;
+
+ if (nextSegment == -1)
+ {
+ salt = Array.Empty<byte>();
+ hash = Convert.FromHexString(hashString);
+ }
+ else
+ {
+ salt = Convert.FromHexString(hashString[..nextSegment]);
+ hashString = hashString[(nextSegment + 1)..];
+ nextSegment = hashString.IndexOf('$');
+ if (nextSegment != -1)
+ {
+ throw new FormatException("Hash string contains too many segments");
+ }
+
+ if (hashString.IsEmpty)
+ {
+ throw new FormatException("Hash segment is empty");
+ }
+
+ hash = Convert.FromHexString(hashString);
+ }
+
+ return new PasswordHash(id.ToString(), hash, salt, parameters ?? new Dictionary<string, string>());
+ }
+
+ private void SerializeParameters(StringBuilder stringBuilder)
+ {
+ if (_parameters.Count == 0)
+ {
+ return;
+ }
+
+ stringBuilder.Append('$');
+ foreach (var pair in _parameters)
+ {
+ stringBuilder.Append(pair.Key)
+ .Append('=')
+ .Append(pair.Value)
+ .Append(',');
+ }
+
+ // Remove last ','
+ stringBuilder.Length -= 1;
+ }
+
+ /// <inheritdoc />
+ public override string ToString()
+ {
+ var str = new StringBuilder()
+ .Append('$')
+ .Append(Id);
+ SerializeParameters(str);
+
+ if (_salt.Length != 0)
+ {
+ str.Append('$')
+ .Append(Convert.ToHexString(_salt));
+ }
+
+ if (_hash.Length != 0)
+ {
+ str.Append('$')
+ .Append(Convert.ToHexString(_hash));
+ }
+
+ return str.ToString();
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs
index 0ac7905a1..a9cf86fbc 100644
--- a/MediaBrowser.Common/Events/EventHelper.cs
+++ b/MediaBrowser.Common/Events/EventHelper.cs
@@ -4,10 +4,10 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Common.Events
{
- // TODO: @bond Remove
/// <summary>
- /// Class EventHelper
+ /// Class EventHelper.
/// </summary>
+ // TODO: @bond Remove
public static class EventHelper
{
/// <summary>
@@ -17,7 +17,7 @@ namespace MediaBrowser.Common.Events
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param>
/// <param name="logger">The logger.</param>
- public static void QueueEventIfNotNull(EventHandler handler, object sender, EventArgs args, ILogger logger)
+ public static void QueueEventIfNotNull(EventHandler? handler, object sender, EventArgs args, ILogger logger)
{
if (handler != null)
{
@@ -38,12 +38,12 @@ namespace MediaBrowser.Common.Events
/// <summary>
/// Queues the event.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">Argument type for the <c>handler</c>.</typeparam>
/// <param name="handler">The handler.</param>
/// <param name="sender">The sender.</param>
/// <param name="args">The args.</param>
/// <param name="logger">The logger.</param>
- public static void QueueEventIfNotNull<T>(EventHandler<T> handler, object sender, T args, ILogger logger)
+ public static void QueueEventIfNotNull<T>(EventHandler<T>? handler, object sender, T args, ILogger logger)
{
if (handler != null)
{
diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs
index db0514bb1..08964420e 100644
--- a/MediaBrowser.Common/Extensions/BaseExtensions.cs
+++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs
@@ -1,37 +1,42 @@
using System;
+using System.Security.Cryptography;
+using System.Text;
using System.Text.RegularExpressions;
-using MediaBrowser.Model.Cryptography;
namespace MediaBrowser.Common.Extensions
{
/// <summary>
- /// Class BaseExtensions
+ /// Class BaseExtensions.
/// </summary>
public static class BaseExtensions
{
- public static ICryptoProvider CryptographyProvider { get; set; }
-
/// <summary>
/// Strips the HTML.
/// </summary>
/// <param name="htmlString">The HTML string.</param>
- /// <returns>System.String.</returns>
+ /// <returns><see cref="string" />.</returns>
public static string StripHtml(this string htmlString)
{
// http://stackoverflow.com/questions/1349023/how-can-i-strip-html-from-text-in-net
- const string pattern = @"<(.|\n)*?>";
+ const string Pattern = @"<(.|\n)*?>";
- return Regex.Replace(htmlString, pattern, string.Empty).Trim();
+ return Regex.Replace(htmlString, Pattern, string.Empty).Trim();
}
/// <summary>
- /// Gets the M d5.
+ /// Gets the Md5.
/// </summary>
- /// <param name="str">The STR.</param>
- /// <returns>Guid.</returns>
+ /// <param name="str">The string.</param>
+ /// <returns><see cref="Guid" />.</returns>
public static Guid GetMD5(this string str)
{
- return CryptographyProvider.GetMD5(str);
+#pragma warning disable CA5351
+ using (var provider = MD5.Create())
+ {
+ return new Guid(provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
+ }
+
+#pragma warning restore CA5351
}
}
}
diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
new file mode 100644
index 000000000..1e5877c84
--- /dev/null
+++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
@@ -0,0 +1,41 @@
+using System.Net;
+using Microsoft.AspNetCore.Http;
+
+namespace MediaBrowser.Common.Extensions
+{
+ /// <summary>
+ /// Static class containing extension methods for <see cref="HttpContext"/>.
+ /// </summary>
+ public static class HttpContextExtensions
+ {
+ /// <summary>
+ /// 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>
+ public static bool IsLocal(this HttpContext context)
+ {
+ return (context.Connection.LocalIpAddress == null
+ && context.Connection.RemoteIpAddress == null)
+ || Equals(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress);
+ }
+
+ /// <summary>
+ /// Extracts the remote IP address of the caller of the HTTP context.
+ /// </summary>
+ /// <param name="context">The HTTP context.</param>
+ /// <returns>The remote caller IP address.</returns>
+ public static IPAddress GetNormalizedRemoteIp(this HttpContext context)
+ {
+ // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
+ var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;
+
+ if (ip.IsIPv4MappedToIPv6)
+ {
+ ip = ip.MapToIPv4();
+ }
+
+ return ip;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs
new file mode 100644
index 000000000..48e758ee4
--- /dev/null
+++ b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs
@@ -0,0 +1,26 @@
+using System;
+
+namespace MediaBrowser.Common.Extensions
+{
+ /// <summary>
+ /// Class MethodNotAllowedException.
+ /// </summary>
+ public class MethodNotAllowedException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MethodNotAllowedException" /> class.
+ /// </summary>
+ public MethodNotAllowedException()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MethodNotAllowedException" /> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public MethodNotAllowedException(string message)
+ : base(message)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs
new file mode 100644
index 000000000..08e01bfd6
--- /dev/null
+++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Extensions
+{
+ /// <summary>
+ /// Extension methods for <see cref="Process"/>.
+ /// </summary>
+ public static class ProcessExtensions
+ {
+ /// <summary>
+ /// Asynchronously wait for the process to exit.
+ /// </summary>
+ /// <param name="process">The process to wait for.</param>
+ /// <param name="timeout">The duration to wait before cancelling waiting for the task.</param>
+ /// <returns>True if the task exited normally, false if the timeout elapsed before the process exited.</returns>
+ /// <exception cref="InvalidOperationException">If <see cref="Process.EnableRaisingEvents"/> is not set to true for the process.</exception>
+ public static async Task<bool> WaitForExitAsync(this Process process, TimeSpan timeout)
+ {
+ using (var cancelTokenSource = new CancellationTokenSource(timeout))
+ {
+ return await WaitForExitAsync(process, cancelTokenSource.Token).ConfigureAwait(false);
+ }
+ }
+
+ /// <summary>
+ /// Asynchronously wait for the process to exit.
+ /// </summary>
+ /// <param name="process">The process to wait for.</param>
+ /// <param name="cancelToken">A <see cref="CancellationToken"/> to observe while waiting for the process to exit.</param>
+ /// <returns>True if the task exited normally, false if cancelled before the process exited.</returns>
+ public static async Task<bool> WaitForExitAsync(this Process process, CancellationToken cancelToken)
+ {
+ if (!process.EnableRaisingEvents)
+ {
+ throw new InvalidOperationException("EnableRisingEvents must be enabled to async wait for a task to exit.");
+ }
+
+ // Add an event handler for the process exit event
+ var tcs = new TaskCompletionSource<bool>();
+ process.Exited += (_, _) => tcs.TrySetResult(true);
+
+ // Return immediately if the process has already exited
+ if (process.HasExitedSafe())
+ {
+ return true;
+ }
+
+ // Register with the cancellation token then await
+ using (var cancelRegistration = cancelToken.Register(() => tcs.TrySetResult(process.HasExitedSafe())))
+ {
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the associated process has been terminated using
+ /// <see cref="Process.HasExited"/>. This is safe to call even if there is no operating system process
+ /// associated with the <see cref="Process"/>.
+ /// </summary>
+ /// <param name="process">The process to check the exit status for.</param>
+ /// <returns>
+ /// True if the operating system process referenced by the <see cref="Process"/> component has
+ /// terminated, or if there is no associated operating system process; otherwise, false.
+ /// </returns>
+ private static bool HasExitedSafe(this Process process)
+ {
+ try
+ {
+ return process.HasExited;
+ }
+ catch (InvalidOperationException)
+ {
+ return true;
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Extensions/RateLimitExceededException.cs b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs
new file mode 100644
index 000000000..95802a462
--- /dev/null
+++ b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs
@@ -0,0 +1,25 @@
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Common.Extensions
+{
+ public class RateLimitExceededException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RateLimitExceededException" /> class.
+ /// </summary>
+ public RateLimitExceededException()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RateLimitExceededException" /> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public RateLimitExceededException(string message)
+ : base(message)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs
index f62c65fd7..22130c5a1 100644
--- a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs
+++ b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs
@@ -3,7 +3,7 @@ using System;
namespace MediaBrowser.Common.Extensions
{
/// <summary>
- /// Class ResourceNotFoundException
+ /// Class ResourceNotFoundException.
/// </summary>
public class ResourceNotFoundException : Exception
{
@@ -12,7 +12,6 @@ namespace MediaBrowser.Common.Extensions
/// </summary>
public ResourceNotFoundException()
{
-
}
/// <summary>
@@ -22,42 +21,6 @@ namespace MediaBrowser.Common.Extensions
public ResourceNotFoundException(string message)
: base(message)
{
-
- }
- }
-
- public class RemoteServiceUnavailableException : Exception
- {
- public RemoteServiceUnavailableException()
- {
-
- }
-
- public RemoteServiceUnavailableException(string message)
- : base(message)
- {
-
- }
- }
-
- public class RateLimitExceededException : Exception
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="RateLimitExceededException" /> class.
- /// </summary>
- public RateLimitExceededException()
- {
-
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="RateLimitExceededException" /> class.
- /// </summary>
- /// <param name="message">The message.</param>
- public RateLimitExceededException(string message)
- : base(message)
- {
-
}
}
}
diff --git a/MediaBrowser.Common/FfmpegException.cs b/MediaBrowser.Common/FfmpegException.cs
new file mode 100644
index 000000000..be420196d
--- /dev/null
+++ b/MediaBrowser.Common/FfmpegException.cs
@@ -0,0 +1,39 @@
+using System;
+
+namespace MediaBrowser.Common
+{
+ /// <summary>
+ /// Represents errors that occur during interaction with FFmpeg.
+ /// </summary>
+ public class FfmpegException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FfmpegException"/> class.
+ /// </summary>
+ public FfmpegException()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FfmpegException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public FfmpegException(string message) : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FfmpegException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The error message that explains the reason for the exception.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if
+ /// no inner exception is specified.
+ /// </param>
+ public FfmpegException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs
index 3a4098612..192a77611 100644
--- a/MediaBrowser.Common/IApplicationHost.cs
+++ b/MediaBrowser.Common/IApplicationHost.cs
@@ -1,20 +1,28 @@
using System;
using System.Collections.Generic;
-using System.Threading;
+using System.Reflection;
using System.Threading.Tasks;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Updates;
-using Microsoft.Extensions.DependencyInjection;
namespace MediaBrowser.Common
{
/// <summary>
- /// An interface to be implemented by the applications hosting a kernel
+ /// Delegate used with GetExports{T}.
+ /// </summary>
+ /// <param name="type">Type to create.</param>
+ /// <returns>New instance of type <param>type</param>.</returns>
+ public delegate object? CreationDelegateFactory(Type type);
+
+ /// <summary>
+ /// An interface to be implemented by the applications hosting a kernel.
/// </summary>
public interface IApplicationHost
{
/// <summary>
+ /// Occurs when [has pending restart changed].
+ /// </summary>
+ event EventHandler? HasPendingRestartChanged;
+
+ /// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
@@ -27,16 +35,15 @@ namespace MediaBrowser.Common
string SystemId { get; }
/// <summary>
- /// Occurs when [application updated].
- /// </summary>
- event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has pending kernel reload.
+ /// Gets a value indicating whether this instance has pending kernel reload.
/// </summary>
/// <value><c>true</c> if this instance has pending kernel reload; otherwise, <c>false</c>.</value>
bool HasPendingRestart { get; }
+ /// <summary>
+ /// Gets a value indicating whether this instance is currently shutting down.
+ /// </summary>
+ /// <value><c>true</c> if this instance is shutting down; otherwise, <c>false</c>.</value>
bool IsShuttingDown { get; }
/// <summary>
@@ -46,25 +53,21 @@ namespace MediaBrowser.Common
bool CanSelfRestart { get; }
/// <summary>
- /// Occurs when [has pending restart changed].
- /// </summary>
- event EventHandler HasPendingRestartChanged;
-
- /// <summary>
- /// Notifies the pending restart.
+ /// Gets the application version.
/// </summary>
- void NotifyPendingRestart();
+ /// <value>The application version.</value>
+ Version ApplicationVersion { get; }
/// <summary>
- /// Restarts this instance.
+ /// Gets or sets the service provider.
/// </summary>
- void Restart();
+ IServiceProvider? ServiceProvider { get; set; }
/// <summary>
/// Gets the application version.
/// </summary>
/// <value>The application version.</value>
- string ApplicationVersion { get; }
+ string ApplicationVersionString { get; }
/// <summary>
/// Gets the application user agent.
@@ -73,41 +76,68 @@ namespace MediaBrowser.Common
string ApplicationUserAgent { get; }
/// <summary>
+ /// Gets the email address for use within a comment section of a user agent field.
+ /// Presently used to provide contact information to MusicBrainz service.
+ /// </summary>
+ string ApplicationUserAgentAddress { get; }
+
+ /// <summary>
+ /// Gets all plugin assemblies which implement a custom rest api.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{Assembly}"/> containing the plugin assemblies.</returns>
+ IEnumerable<Assembly> GetApiPluginAssemblies();
+
+ /// <summary>
+ /// Notifies the pending restart.
+ /// </summary>
+ void NotifyPendingRestart();
+
+ /// <summary>
+ /// Restarts this instance.
+ /// </summary>
+ void Restart();
+
+ /// <summary>
/// Gets the exports.
/// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
- /// <returns>IEnumerable{``0}.</returns>
- IEnumerable<T> GetExports<T>(bool manageLifetime = true);
+ /// <typeparam name="T">The type.</typeparam>
+ /// <param name="manageLifetime">If set to <c>true</c> [manage lifetime].</param>
+ /// <returns><see cref="IReadOnlyCollection{T}" />.</returns>
+ IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true);
/// <summary>
- /// Resolves this instance.
+ /// Gets the exports.
/// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns>``0.</returns>
- T Resolve<T>();
+ /// <typeparam name="T">The type.</typeparam>
+ /// <param name="defaultFunc">Delegate function that gets called to create the object.</param>
+ /// <param name="manageLifetime">If set to <c>true</c> [manage lifetime].</param>
+ /// <returns><see cref="IReadOnlyCollection{T}" />.</returns>
+ IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true);
/// <summary>
- /// Shuts down.
+ /// Gets the export types.
/// </summary>
- Task Shutdown();
+ /// <typeparam name="T">The type.</typeparam>
+ /// <returns>IEnumerable{Type}.</returns>
+ IEnumerable<Type> GetExportTypes<T>();
/// <summary>
- /// Gets the plugins.
+ /// Resolves this instance.
/// </summary>
- /// <value>The plugins.</value>
- IPlugin[] Plugins { get; }
+ /// <typeparam name="T">The <c>Type</c>.</typeparam>
+ /// <returns>``0.</returns>
+ T Resolve<T>();
/// <summary>
- /// Removes the plugin.
+ /// Shuts down.
/// </summary>
- /// <param name="plugin">The plugin.</param>
- void RemovePlugin(IPlugin plugin);
+ /// <returns>A task.</returns>
+ Task Shutdown();
/// <summary>
- /// Inits this instance.
+ /// Initializes this instance.
/// </summary>
- Task Init(IServiceCollection serviceCollection);
+ void Init();
/// <summary>
/// Creates the instance.
@@ -115,7 +145,5 @@ namespace MediaBrowser.Common
/// <param name="type">The type.</param>
/// <returns>System.Object.</returns>
object CreateInstance(Type type);
-
- PackageVersionClass SystemUpdateLevel { get; }
}
}
diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj
index 715f4fccd..9c8ce4ac5 100644
--- a/MediaBrowser.Common/MediaBrowser.Common.csproj
+++ b/MediaBrowser.Common/MediaBrowser.Common.csproj
@@ -1,18 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{9142EEFA-7570-41E1-BFCC-468BB571AF2F}</ProjectGuid>
+ </PropertyGroup>
+
<PropertyGroup>
<Authors>Jellyfin Contributors</Authors>
<PackageId>Jellyfin.Common</PackageId>
- <PackageLicenseUrl>https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt</PackageLicenseUrl>
+ <VersionPrefix>10.8.0</VersionPrefix>
<RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
</PropertyGroup>
<ItemGroup>
+ <FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
@@ -20,8 +29,31 @@
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </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>
+ <!-- Code analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
+ <_Parameter1>Jellyfin.Common.Tests</_Parameter1>
+ </AssemblyAttribute>
+ </ItemGroup>
+
</Project>
diff --git a/MediaBrowser.Common/Net/CustomHeaderNames.cs b/MediaBrowser.Common/Net/CustomHeaderNames.cs
new file mode 100644
index 000000000..5ca9897eb
--- /dev/null
+++ b/MediaBrowser.Common/Net/CustomHeaderNames.cs
@@ -0,0 +1,13 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Common.Net
+{
+ public static class CustomHeaderNames
+ {
+ // Other Headers
+ public const string XForwardedFor = "X-Forwarded-For";
+ public const string XForwardedPort = "X-Forwarded-Port";
+ public const string XForwardedProto = "X-Forwarded-Proto";
+ public const string XRealIP = "X-Real-IP";
+ }
+}
diff --git a/MediaBrowser.Common/Net/HttpRequestOptions.cs b/MediaBrowser.Common/Net/HttpRequestOptions.cs
deleted file mode 100644
index dadac5e03..000000000
--- a/MediaBrowser.Common/Net/HttpRequestOptions.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-
-namespace MediaBrowser.Common.Net
-{
- /// <summary>
- /// Class HttpRequestOptions
- /// </summary>
- public class HttpRequestOptions
- {
- /// <summary>
- /// Gets or sets the URL.
- /// </summary>
- /// <value>The URL.</value>
- public string Url { get; set; }
-
- public CompressionMethod? DecompressionMethod { get; set; }
-
- /// <summary>
- /// Gets or sets the accept header.
- /// </summary>
- /// <value>The accept header.</value>
- public string AcceptHeader
- {
- get => GetHeaderValue("Accept");
- set => RequestHeaders["Accept"] = value;
- }
- /// <summary>
- /// Gets or sets the cancellation token.
- /// </summary>
- /// <value>The cancellation token.</value>
- public CancellationToken CancellationToken { get; set; }
-
- /// <summary>
- /// Gets or sets the resource pool.
- /// </summary>
- /// <value>The resource pool.</value>
- public SemaphoreSlim ResourcePool { get; set; }
-
- /// <summary>
- /// Gets or sets the user agent.
- /// </summary>
- /// <value>The user agent.</value>
- public string UserAgent
- {
- get => GetHeaderValue("User-Agent");
- set => RequestHeaders["User-Agent"] = value;
- }
-
- /// <summary>
- /// Gets or sets the referrer.
- /// </summary>
- /// <value>The referrer.</value>
- public string Referer { get; set; }
-
- /// <summary>
- /// Gets or sets the host.
- /// </summary>
- /// <value>The host.</value>
- public string Host { get; set; }
-
- /// <summary>
- /// Gets or sets the progress.
- /// </summary>
- /// <value>The progress.</value>
- public IProgress<double> Progress { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [enable HTTP compression].
- /// </summary>
- /// <value><c>true</c> if [enable HTTP compression]; otherwise, <c>false</c>.</value>
- public bool EnableHttpCompression { get; set; }
-
- public Dictionary<string, string> RequestHeaders { get; private set; }
-
- public string RequestContentType { get; set; }
-
- public string RequestContent { get; set; }
- public byte[] RequestContentBytes { get; set; }
-
- public bool BufferContent { get; set; }
-
- public bool LogRequest { get; set; }
- public bool LogRequestAsDebug { get; set; }
- public bool LogErrors { get; set; }
- public bool LogResponse { get; set; }
- public bool LogResponseHeaders { get; set; }
-
- public bool LogErrorResponseBody { get; set; }
- public bool EnableKeepAlive { get; set; }
-
- public CacheMode CacheMode { get; set; }
- public TimeSpan CacheLength { get; set; }
-
- public int TimeoutMs { get; set; }
- public bool EnableDefaultUserAgent { get; set; }
-
- public bool AppendCharsetToMimeType { get; set; }
- public string DownloadFilePath { get; set; }
-
- private string GetHeaderValue(string name)
- {
- RequestHeaders.TryGetValue(name, out var value);
-
- return value;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestOptions"/> class.
- /// </summary>
- public HttpRequestOptions()
- {
- EnableHttpCompression = true;
-
- RequestHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- LogRequest = true;
- LogErrors = true;
- CacheMode = CacheMode.None;
-
- TimeoutMs = 20000;
- }
-
- public void SetPostData(IDictionary<string, string> values)
- {
- var strings = values.Keys.Select(key => string.Format("{0}={1}", key, values[key]));
- var postContent = string.Join("&", strings.ToArray());
-
- RequestContent = postContent;
- RequestContentType = "application/x-www-form-urlencoded";
- }
- }
-
- public enum CacheMode
- {
- None = 0,
- Unconditional = 1
- }
-
- public enum CompressionMethod
- {
- Deflate,
- Gzip
- }
-}
diff --git a/MediaBrowser.Common/Net/HttpResponseInfo.cs b/MediaBrowser.Common/Net/HttpResponseInfo.cs
deleted file mode 100644
index 186674167..000000000
--- a/MediaBrowser.Common/Net/HttpResponseInfo.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-
-namespace MediaBrowser.Common.Net
-{
- /// <summary>
- /// Class HttpResponseInfo
- /// </summary>
- public class HttpResponseInfo : IDisposable
- {
- /// <summary>
- /// Gets or sets the type of the content.
- /// </summary>
- /// <value>The type of the content.</value>
- public string ContentType { get; set; }
-
- /// <summary>
- /// Gets or sets the response URL.
- /// </summary>
- /// <value>The response URL.</value>
- public string ResponseUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the content.
- /// </summary>
- /// <value>The content.</value>
- public Stream Content { get; set; }
-
- /// <summary>
- /// Gets or sets the status code.
- /// </summary>
- /// <value>The status code.</value>
- public HttpStatusCode StatusCode { get; set; }
-
- /// <summary>
- /// Gets or sets the temp file path.
- /// </summary>
- /// <value>The temp file path.</value>
- public string TempFilePath { get; set; }
-
- /// <summary>
- /// Gets or sets the length of the content.
- /// </summary>
- /// <value>The length of the content.</value>
- public long? ContentLength { get; set; }
-
- /// <summary>
- /// Gets or sets the headers.
- /// </summary>
- /// <value>The headers.</value>
- public Dictionary<string, string> Headers { get; set; }
-
- private readonly IDisposable _disposable;
-
- public HttpResponseInfo(IDisposable disposable)
- {
- _disposable = disposable;
- Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
- public HttpResponseInfo()
- {
- Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- public void Dispose()
- {
- if (_disposable != null)
- {
- _disposable.Dispose();
- }
- }
- }
-}
diff --git a/MediaBrowser.Common/Net/IHttpClient.cs b/MediaBrowser.Common/Net/IHttpClient.cs
deleted file mode 100644
index 5aaf7e0be..000000000
--- a/MediaBrowser.Common/Net/IHttpClient.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using System.IO;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Common.Net
-{
- /// <summary>
- /// Interface IHttpClient
- /// </summary>
- public interface IHttpClient
- {
- /// <summary>
- /// Gets the response.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> GetResponse(HttpRequestOptions options);
-
- /// <summary>
- /// Gets the specified options.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{Stream}.</returns>
- Task<Stream> Get(HttpRequestOptions options);
-
- /// <summary>
- /// Sends the asynchronous.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <param name="httpMethod">The HTTP method.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod);
-
- /// <summary>
- /// Posts the specified options.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> Post(HttpRequestOptions options);
-
- /// <summary>
- /// Downloads the contents of a given url into a temporary location
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{System.String}.</returns>
- /// <exception cref="System.ArgumentNullException">progress</exception>
- /// <exception cref="Model.Net.HttpException"></exception>
- Task<string> GetTempFile(HttpRequestOptions options);
-
- /// <summary>
- /// Gets the temporary file response.
- /// </summary>
- /// <param name="options">The options.</param>
- /// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options);
- }
-}
diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs
index 72fb6e2b8..b93939730 100644
--- a/MediaBrowser.Common/Net/INetworkManager.cs
+++ b/MediaBrowser.Common/Net/INetworkManager.cs
@@ -1,66 +1,238 @@
using System;
using System.Collections.Generic;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
+using System.Collections.ObjectModel;
+using System.Net;
+using System.Net.NetworkInformation;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Common.Net
{
+ /// <summary>
+ /// Interface for the NetworkManager class.
+ /// </summary>
public interface INetworkManager
{
+ /// <summary>
+ /// Event triggered on network changes.
+ /// </summary>
event EventHandler NetworkChanged;
/// <summary>
- /// Gets a random port number that is currently available
+ /// Gets the published server urls list.
+ /// </summary>
+ Dictionary<IPNetAddress, string> PublishedServerUrls { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// </summary>
+ bool TrustAllIP6Interfaces { get; }
+
+ /// <summary>
+ /// Gets the remote address filter.
+ /// </summary>
+ Collection<IPObject> RemoteAddressFilter { get; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether iP6 is enabled.
+ /// </summary>
+ bool IsIP6Enabled { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether iP4 is enabled.
+ /// </summary>
+ bool IsIP4Enabled { get; set; }
+
+ /// <summary>
+ /// Calculates the list of interfaces to use for Kestrel.
+ /// </summary>
+ /// <returns>A Collection{IPObject} object containing all the interfaces to bind.
+ /// If all the interfaces are specified, and none are excluded, it returns zero items
+ /// to represent any address.</returns>
+ /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
+ Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
+
+ /// <summary>
+ /// Returns a collection containing the loopback interfaces.
+ /// </summary>
+ /// <returns>Collection{IPObject}.</returns>
+ Collection<IPObject> GetLoopbacks();
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// The priority of selection is as follows:-
+ ///
+ /// The value contained in the startup parameter --published-server-url.
+ ///
+ /// If the user specified custom subnet overrides, the correct subnet for the source address.
+ ///
+ /// If the user specified bind interfaces to use:-
+ /// The bind interface that contains the source subnet.
+ /// The first bind interface specified that suits best first the source's endpoint. eg. external or internal.
+ ///
+ /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:-
+ /// The first public interface that isn't a loopback and contains the source subnet.
+ /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways.
+ /// An internal interface if there are no public ip addresses.
+ ///
+ /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:-
+ /// The first private interface that contains the source subnet.
+ /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways.
+ ///
+ /// If no interfaces meet any of these criteria, then a loopback address is returned.
+ ///
+ /// Interface that have been specifically excluded from binding are not used in any of the calculations.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(IPObject source, out int? port);
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(HttpRequest source, out int? port);
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
/// </summary>
- /// <returns>System.Int32.</returns>
- int GetRandomUnusedTcpPort();
+ /// <param name="source">IP address of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(IPAddress source, out int? port);
- int GetRandomUnusedUdpPort();
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(string source, out int? port);
- Func<string[]> LocalSubnetsFn { get; set; }
+ /// <summary>
+ /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
+ /// </summary>
+ /// <param name="address">IP address to check.</param>
+ /// <returns>True if it is.</returns>
+ bool IsExcludedInterface(IPAddress address);
/// <summary>
- /// Returns MAC Address from first Network Card in Computer
+ /// Get a list of all the MAC addresses associated with active interfaces.
/// </summary>
- /// <returns>[string] MAC Address</returns>
- List<string> GetMacAddresses();
+ /// <returns>List of MAC addresses.</returns>
+ IReadOnlyCollection<PhysicalAddress> GetMacAddresses();
/// <summary>
- /// Determines whether [is in private address space] [the specified endpoint].
+ /// Checks to see if the IP Address provided matches an interface that has a gateway.
/// </summary>
- /// <param name="endpoint">The endpoint.</param>
- /// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
- bool IsInPrivateAddressSpace(string endpoint);
+ /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
+ /// <returns>Result of the check.</returns>
+ bool IsGatewayInterface(IPObject? addressObj);
/// <summary>
- /// Gets the network shares.
+ /// Checks to see if the IP Address provided matches an interface that has a gateway.
/// </summary>
- /// <param name="path">The path.</param>
- /// <returns>IEnumerable{NetworkShare}.</returns>
- IEnumerable<NetworkShare> GetNetworkShares(string path);
+ /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
+ /// <returns>Result of the check.</returns>
+ bool IsGatewayInterface(IPAddress? addressObj);
/// <summary>
- /// Gets available devices within the domain
+ /// Returns true if the address is a private address.
+ /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <returns>PC's in the Domain</returns>
- IEnumerable<FileSystemEntryInfo> GetNetworkDevices();
+ /// <param name="address">Address to check.</param>
+ /// <returns>True or False.</returns>
+ bool IsPrivateAddressRange(IPObject address);
/// <summary>
- /// Determines whether [is in local network] [the specified endpoint].
+ /// Returns true if the address is part of the user defined LAN.
+ /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <param name="endpoint">The endpoint.</param>
- /// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
- bool IsInLocalNetwork(string endpoint);
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(string address);
- IpAddressInfo[] GetLocalIpAddresses();
+ /// <summary>
+ /// Returns true if the address is part of the user defined LAN.
+ /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
+ /// </summary>
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(IPObject address);
- IpAddressInfo ParseIpAddress(string ipAddress);
+ /// <summary>
+ /// Returns true if the address is part of the user defined LAN.
+ /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
+ /// </summary>
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(IPAddress address);
- bool TryParseIpAddress(string ipAddress, out IpAddressInfo ipAddressInfo);
+ /// <summary>
+ /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes.
+ /// eg. "eth1", or "TP-LINK Wireless USB Adapter".
+ /// </summary>
+ /// <param name="token">Token to parse.</param>
+ /// <param name="result">Resultant object's ip addresses, if successful.</param>
+ /// <returns>Success of the operation.</returns>
+ bool TryParseInterface(string token, out Collection<IPObject>? result);
- Task<IpAddressInfo[]> GetHostAddressesAsync(string host);
+ /// <summary>
+ /// Parses an array of strings into a Collection{IPObject}.
+ /// </summary>
+ /// <param name="values">Values to parse.</param>
+ /// <param name="negated">When true, only include values beginning with !. When false, ignore ! values.</param>
+ /// <returns>IPCollection object containing the value strings.</returns>
+ Collection<IPObject> CreateIPCollection(string[] values, bool negated = false);
+
+ /// <summary>
+ /// Returns all the internal Bind interface addresses.
+ /// </summary>
+ /// <returns>An internal list of interfaces addresses.</returns>
+ Collection<IPObject> GetInternalBindAddresses();
- bool IsAddressInSubnets(string addressString, string[] subnets);
+ /// <summary>
+ /// Checks to see if an IP address is still a valid interface address.
+ /// </summary>
+ /// <param name="address">IP address to check.</param>
+ /// <returns>True if it is.</returns>
+ bool IsValidInterfaceAddress(IPAddress address);
+
+ /// <summary>
+ /// Returns true if the IP address is in the excluded list.
+ /// </summary>
+ /// <param name="ip">IP to check.</param>
+ /// <returns>True if excluded.</returns>
+ bool IsExcluded(IPAddress ip);
+
+ /// <summary>
+ /// Returns true if the IP address is in the excluded list.
+ /// </summary>
+ /// <param name="ip">IP to check.</param>
+ /// <returns>True if excluded.</returns>
+ bool IsExcluded(EndPoint ip);
+
+ /// <summary>
+ /// Gets the filtered LAN ip addresses.
+ /// </summary>
+ /// <param name="filter">Optional filter for the list.</param>
+ /// <returns>Returns a filtered list of LAN addresses.</returns>
+ Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
+
+ /// <summary>
+ /// Checks to see if <paramref name="remoteIp"/> has access.
+ /// </summary>
+ /// <param name="remoteIp">IP Address of client.</param>
+ /// <returns><b>True</b> if has access, otherwise <b>false</b>.</returns>
+ bool HasRemoteAccess(IPAddress remoteIp);
}
}
diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs
new file mode 100644
index 000000000..1f125f2b1
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPHost.cs
@@ -0,0 +1,441 @@
+using System;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text.RegularExpressions;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Object that holds a host name.
+ /// </summary>
+ public class IPHost : IPObject
+ {
+ /// <summary>
+ /// Gets or sets timeout value before resolve required, in minutes.
+ /// </summary>
+ public const int Timeout = 30;
+
+ /// <summary>
+ /// Represents an IPHost that has no value.
+ /// </summary>
+ public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
+
+ /// <summary>
+ /// Time when last resolved in ticks.
+ /// </summary>
+ private DateTime? _lastResolved = null;
+
+ /// <summary>
+ /// Gets the IP Addresses, attempting to resolve the name, if there are none.
+ /// </summary>
+ private IPAddress[] _addresses;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPHost"/> class.
+ /// </summary>
+ /// <param name="name">Host name to assign.</param>
+ public IPHost(string name)
+ {
+ HostName = name ?? throw new ArgumentNullException(nameof(name));
+ _addresses = Array.Empty<IPAddress>();
+ Resolved = false;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPHost"/> class.
+ /// </summary>
+ /// <param name="name">Host name to assign.</param>
+ /// <param name="address">Address to assign.</param>
+ private IPHost(string name, IPAddress address)
+ {
+ HostName = name ?? throw new ArgumentNullException(nameof(name));
+ _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) };
+ Resolved = !address.Equals(IPAddress.None);
+ }
+
+ /// <summary>
+ /// Gets or sets the object's first IP address.
+ /// </summary>
+ public override IPAddress Address
+ {
+ get
+ {
+ return ResolveHost() ? this[0] : IPAddress.None;
+ }
+
+ set
+ {
+ // Not implemented, as a host's address is determined by DNS.
+ throw new NotImplementedException("The address of a host is determined by DNS.");
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the object's first IP's subnet prefix.
+ /// The setter does nothing, but shouldn't raise an exception.
+ /// </summary>
+ public override byte PrefixLength
+ {
+ get => (byte)(ResolveHost() ? 128 : 32);
+
+ // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length,
+ // which is automatically determined by it's IP type. Anything else is meaningless.
+ set => throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the address has a value.
+ /// </summary>
+ public bool HasAddress => _addresses.Length != 0;
+
+ /// <summary>
+ /// Gets the host name of this object.
+ /// </summary>
+ public string HostName { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether this host has attempted to be resolved.
+ /// </summary>
+ public bool Resolved { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the IP Addresses associated with this object.
+ /// </summary>
+ /// <param name="index">Index of address.</param>
+ public IPAddress this[int index]
+ {
+ get
+ {
+ ResolveHost();
+ return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
+ }
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
+ /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
+ public static bool TryParse(string host, out IPHost hostObj)
+ {
+ if (string.IsNullOrWhiteSpace(host))
+ {
+ hostObj = IPHost.None;
+ return false;
+ }
+
+ // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
+ int i = host.IndexOf(']', StringComparison.Ordinal);
+ if (i != -1)
+ {
+ return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
+ }
+
+ if (IPNetAddress.TryParse(host, out var netAddress))
+ {
+ // Host name is an ip address, so fake resolve.
+ hostObj = new IPHost(host, netAddress.Address);
+ return true;
+ }
+
+ // Is it a host, IPv4/6 with/out port?
+ string[] hosts = host.Split(':');
+
+ if (hosts.Length <= 2)
+ {
+ // This is either a hostname: port, or an IP4:port.
+ host = hosts[0];
+
+ if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
+ {
+ hostObj = new IPHost(host);
+ return true;
+ }
+
+ if (IPAddress.TryParse(host, out var netIP))
+ {
+ // Host name is an ip address, so fake resolve.
+ hostObj = new IPHost(host, netIP);
+ return true;
+ }
+ }
+ else
+ {
+ // Invalid host name, as it cannot contain :
+ hostObj = new IPHost(string.Empty, IPAddress.None);
+ return false;
+ }
+
+ // Use regular expression as CheckHostName isn't RFC5892 compliant.
+ // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
+ string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$";
+
+ if (Regex.IsMatch(host, pattern))
+ {
+ hostObj = new IPHost(host);
+ return true;
+ }
+
+ hostObj = IPHost.None;
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <returns>Object representing the string, if it has successfully been parsed.</returns>
+ public static IPHost Parse(string host)
+ {
+ if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
+ {
+ return res;
+ }
+
+ throw new InvalidCastException($"Host does not contain a valid value. {host}");
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="family">Addressfamily filter.</param>
+ /// <returns>Object representing the string, if it has successfully been parsed.</returns>
+ public static IPHost Parse(string host, AddressFamily family)
+ {
+ if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
+ {
+ if (family == AddressFamily.InterNetwork)
+ {
+ res.Remove(AddressFamily.InterNetworkV6);
+ }
+ else
+ {
+ res.Remove(AddressFamily.InterNetwork);
+ }
+
+ return res;
+ }
+
+ throw new InvalidCastException($"Host does not contain a valid value. {host}");
+ }
+
+ /// <summary>
+ /// Returns the Addresses that this item resolved to.
+ /// </summary>
+ /// <returns>IPAddress Array.</returns>
+ public IPAddress[] GetAddresses()
+ {
+ ResolveHost();
+ return _addresses;
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPAddress address)
+ {
+ if (address != null && !Address.Equals(IPAddress.None))
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ foreach (var addr in GetAddresses())
+ {
+ if (address.Equals(addr))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPObject? other)
+ {
+ if (other is IPHost otherObj)
+ {
+ // Do we have the name Hostname?
+ if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+
+ if (!ResolveHost() || !otherObj.ResolveHost())
+ {
+ return false;
+ }
+
+ // Do any of our IP addresses match?
+ foreach (IPAddress addr in _addresses)
+ {
+ foreach (IPAddress otherAddress in otherObj._addresses)
+ {
+ if (addr.Equals(otherAddress))
+ {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool IsIP6()
+ {
+ // Returns true if interfaces are only IP6.
+ if (ResolveHost())
+ {
+ foreach (IPAddress i in _addresses)
+ {
+ if (i.AddressFamily != AddressFamily.InterNetworkV6)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override string ToString()
+ {
+ // StringBuilder not optimum here.
+ string output = string.Empty;
+ if (_addresses.Length > 0)
+ {
+ bool moreThanOne = _addresses.Length > 1;
+ if (moreThanOne)
+ {
+ output = "[";
+ }
+
+ foreach (var i in _addresses)
+ {
+ if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
+ {
+ output += HostName + ",";
+ }
+ else if (i.Equals(IPAddress.Any))
+ {
+ output += "Any IP4 Address,";
+ }
+ else if (Address.Equals(IPAddress.IPv6Any))
+ {
+ output += "Any IP6 Address,";
+ }
+ else if (i.Equals(IPAddress.Broadcast))
+ {
+ output += "Any Address,";
+ }
+ else if (i.AddressFamily == AddressFamily.InterNetwork)
+ {
+ output += $"{i}/32,";
+ }
+ else
+ {
+ output += $"{i}/128,";
+ }
+ }
+
+ output = output[..^1];
+
+ if (moreThanOne)
+ {
+ output += "]";
+ }
+ }
+ else
+ {
+ output = HostName;
+ }
+
+ return output;
+ }
+
+ /// <inheritdoc/>
+ public override void Remove(AddressFamily family)
+ {
+ if (ResolveHost())
+ {
+ _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
+ }
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPObject address)
+ {
+ // An IPHost cannot contain another IPObject, it can only be equal.
+ return Equals(address);
+ }
+
+ /// <inheritdoc/>
+ protected override IPObject CalculateNetworkAddress()
+ {
+ var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength);
+ return new IPNetAddress(address, prefixLength);
+ }
+
+ /// <summary>
+ /// Attempt to resolve the ip address of a host.
+ /// </summary>
+ /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
+ private bool ResolveHost()
+ {
+ // When was the last time we resolved?
+ _lastResolved ??= DateTime.UtcNow;
+
+ // If we haven't resolved before, or our timer has run out...
+ if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout)))
+ {
+ _lastResolved = DateTime.UtcNow;
+ ResolveHostInternal();
+ Resolved = true;
+ }
+
+ return _addresses.Length > 0;
+ }
+
+ /// <summary>
+ /// Task that looks up a Host name and returns its IP addresses.
+ /// </summary>
+ private void ResolveHostInternal()
+ {
+ var hostName = HostName;
+ if (string.IsNullOrEmpty(hostName))
+ {
+ return;
+ }
+
+ // Resolves the host name - so save a DNS lookup.
+ if (string.Equals(hostName, "localhost", StringComparison.OrdinalIgnoreCase))
+ {
+ _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback };
+ return;
+ }
+
+ if (Uri.CheckHostName(hostName) == UriHostNameType.Dns)
+ {
+ try
+ {
+ _addresses = Dns.GetHostEntry(hostName).AddressList;
+ }
+ catch (SocketException ex)
+ {
+ // Log and then ignore socket errors, as the result value will just be an empty array.
+ Debug.WriteLine("GetHostAddresses failed with {Message}.", ex.Message);
+ }
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs
new file mode 100644
index 000000000..f6e3971bf
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPNetAddress.cs
@@ -0,0 +1,276 @@
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// An object that holds and IP address and subnet mask.
+ /// </summary>
+ public class IPNetAddress : IPObject
+ {
+ /// <summary>
+ /// Represents an IPNetAddress that has no value.
+ /// </summary>
+ public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None);
+
+ /// <summary>
+ /// IPv4 multicast address.
+ /// </summary>
+ public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250");
+
+ /// <summary>
+ /// IPv6 local link multicast address.
+ /// </summary>
+ public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C");
+
+ /// <summary>
+ /// IPv6 site local multicast address.
+ /// </summary>
+ public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C");
+
+ /// <summary>
+ /// IP4Loopback address host.
+ /// </summary>
+ public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8");
+
+ /// <summary>
+ /// IP6Loopback address host.
+ /// </summary>
+ public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback);
+
+ /// <summary>
+ /// Object's IP address.
+ /// </summary>
+ private IPAddress _address;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
+ /// </summary>
+ /// <param name="address">Address to assign.</param>
+ public IPNetAddress(IPAddress address)
+ {
+ _address = address ?? throw new ArgumentNullException(nameof(address));
+ PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
+ /// </summary>
+ /// <param name="address">IP Address.</param>
+ /// <param name="prefixLength">Mask as a CIDR.</param>
+ public IPNetAddress(IPAddress address, byte prefixLength)
+ {
+ if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address)))
+ {
+ _address = address.MapToIPv4();
+ }
+ else
+ {
+ _address = address;
+ }
+
+ PrefixLength = prefixLength;
+ }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public override IPAddress Address
+ {
+ get
+ {
+ return _address;
+ }
+
+ set
+ {
+ _address = value ?? IPAddress.None;
+ }
+ }
+
+ /// <inheritdoc/>
+ public override byte PrefixLength { get; set; }
+
+ /// <summary>
+ /// Try to parse the address and subnet strings into an IPNetAddress object.
+ /// </summary>
+ /// <param name="addr">IP address to parse. Can be CIDR or X.X.X.X notation.</param>
+ /// <param name="ip">Resultant object.</param>
+ /// <returns>True if the values parsed successfully. False if not, resulting in the IP being null.</returns>
+ public static bool TryParse(string addr, out IPNetAddress ip)
+ {
+ if (!string.IsNullOrEmpty(addr))
+ {
+ addr = addr.Trim();
+
+ // Try to parse it as is.
+ if (IPAddress.TryParse(addr, out IPAddress? res))
+ {
+ ip = new IPNetAddress(res);
+ return true;
+ }
+
+ // Is it a network?
+ string[] tokens = addr.Split('/');
+
+ if (tokens.Length == 2)
+ {
+ tokens[0] = tokens[0].TrimEnd();
+ tokens[1] = tokens[1].TrimStart();
+
+ if (IPAddress.TryParse(tokens[0], out res))
+ {
+ // Is the subnet part a cidr?
+ if (byte.TryParse(tokens[1], out byte cidr))
+ {
+ ip = new IPNetAddress(res, cidr);
+ return true;
+ }
+
+ // Is the subnet in x.y.a.b form?
+ if (IPAddress.TryParse(tokens[1], out IPAddress? mask))
+ {
+ ip = new IPNetAddress(res, MaskToCidr(mask));
+ return true;
+ }
+ }
+ }
+ }
+
+ ip = None;
+ return false;
+ }
+
+ /// <summary>
+ /// Parses the string provided, throwing an exception if it is badly formed.
+ /// </summary>
+ /// <param name="addr">String to parse.</param>
+ /// <returns>IPNetAddress object.</returns>
+ public static IPNetAddress Parse(string addr)
+ {
+ if (TryParse(addr, out IPNetAddress o))
+ {
+ return o;
+ }
+
+ throw new ArgumentException("Unable to recognise object :" + addr);
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength);
+ return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix;
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPObject address)
+ {
+ if (address is IPHost addressObj && addressObj.HasAddress)
+ {
+ foreach (IPAddress addr in addressObj.GetAddresses())
+ {
+ if (Contains(addr))
+ {
+ return true;
+ }
+ }
+ }
+ else if (address is IPNetAddress netaddrObj)
+ {
+ // Have the same network address, but different subnets?
+ if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address))
+ {
+ return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength;
+ }
+
+ var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength).address;
+ return NetworkAddress.Address.Equals(altAddress);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPObject? other)
+ {
+ if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None))
+ {
+ return Address.Equals(otherObj.Address) &&
+ PrefixLength == otherObj.PrefixLength;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPAddress ip)
+ {
+ if (ip != null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None))
+ {
+ return ip.Equals(Address);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ /// <summary>
+ /// Returns a textual representation of this object.
+ /// </summary>
+ /// <param name="shortVersion">Set to true, if the subnet is to be excluded as part of the address.</param>
+ /// <returns>String representation of this object.</returns>
+ public string ToString(bool shortVersion)
+ {
+ if (!Address.Equals(IPAddress.None))
+ {
+ if (Address.Equals(IPAddress.Any))
+ {
+ return "Any IP4 Address";
+ }
+
+ if (Address.Equals(IPAddress.IPv6Any))
+ {
+ return "Any IP6 Address";
+ }
+
+ if (Address.Equals(IPAddress.Broadcast))
+ {
+ return "Any Address";
+ }
+
+ if (shortVersion)
+ {
+ return Address.ToString();
+ }
+
+ return $"{Address}/{PrefixLength}";
+ }
+
+ return string.Empty;
+ }
+
+ /// <inheritdoc/>
+ protected override IPObject CalculateNetworkAddress()
+ {
+ var (address, prefixLength) = NetworkAddressOf(_address, PrefixLength);
+ return new IPNetAddress(address, prefixLength);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs
new file mode 100644
index 000000000..2612268fd
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPObject.cs
@@ -0,0 +1,395 @@
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Base network object class.
+ /// </summary>
+ public abstract class IPObject : IEquatable<IPObject>
+ {
+ /// <summary>
+ /// The network address of this object.
+ /// </summary>
+ private IPObject? _networkAddress;
+
+ /// <summary>
+ /// Gets or sets a user defined value that is associated with this object.
+ /// </summary>
+ public int Tag { get; set; }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public abstract IPAddress Address { get; set; }
+
+ /// <summary>
+ /// Gets the object's network address.
+ /// </summary>
+ public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public abstract byte PrefixLength { get; set; }
+
+ /// <summary>
+ /// Gets the AddressFamily of this object.
+ /// </summary>
+ public AddressFamily AddressFamily
+ {
+ get
+ {
+ // Keep terms separate as Address performs other functions in inherited objects.
+ IPAddress address = Address;
+ return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily;
+ }
+ }
+
+ /// <summary>
+ /// Returns the network address of an object.
+ /// </summary>
+ /// <param name="address">IP Address to convert.</param>
+ /// <param name="prefixLength">Subnet prefix.</param>
+ /// <returns>IPAddress.</returns>
+ public static (IPAddress address, byte prefixLength) NetworkAddressOf(IPAddress address, byte prefixLength)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (IsLoopback(address))
+ {
+ return (address, prefixLength);
+ }
+
+ // An ip address is just a list of bytes, each one representing a segment on the network.
+ // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the
+ // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out.
+ // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept.
+
+ // GetAddressBytes
+ Span<byte> addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ address.TryWriteBytes(addressBytes, out _);
+
+ int div = prefixLength / 8;
+ int mod = prefixLength % 8;
+ if (mod != 0)
+ {
+ // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
+ mod = 8 - mod;
+
+ // Shift out the bits from the octet that we don't want, by moving right then back left.
+ addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
+ // Move on the next byte.
+ div++;
+ }
+
+ // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0)
+ for (int octet = div; octet < addressBytes.Length; octet++)
+ {
+ addressBytes[octet] = 0;
+ }
+
+ // Return the network address for the prefix.
+ return (new IPAddress(addressBytes), prefixLength);
+ }
+
+ /// <summary>
+ /// Tests to see if the ip address is a Loopback address.
+ /// </summary>
+ /// <param name="address">Value to test.</param>
+ /// <returns>True if it is.</returns>
+ public static bool IsLoopback(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (!address.Equals(IPAddress.None))
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Tests to see if the ip address is an IP6 address.
+ /// </summary>
+ /// <param name="address">Value to test.</param>
+ /// <returns>True if it is.</returns>
+ public static bool IsIP6(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
+ }
+
+ /// <summary>
+ /// Tests to see if the address in the private address range.
+ /// </summary>
+ /// <param name="address">Object to test.</param>
+ /// <returns>True if it contains a private address.</returns>
+ public static bool IsPrivateAddressRange(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (!address.Equals(IPAddress.None))
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ // GetAddressBytes
+ Span<byte> octet = stackalloc byte[4];
+ address.TryWriteBytes(octet, out _);
+
+ return (octet[0] == 10)
+ || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
+ || (octet[0] == 192 && octet[1] == 168) // RFC1918
+ || (octet[0] == 127); // RFC1122
+ }
+ else
+ {
+ // GetAddressBytes
+ Span<byte> octet = stackalloc byte[16];
+ address.TryWriteBytes(octet, out _);
+
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
+ || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns true if the IPAddress contains an IP6 Local link address.
+ /// </summary>
+ /// <param name="address">IPAddress object to check.</param>
+ /// <returns>True if it is a local link address.</returns>
+ /// <remarks>
+ /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
+ /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
+ /// </remarks>
+ public static bool IsIPv6LinkLocal(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
+ {
+ return false;
+ }
+
+ // GetAddressBytes
+ Span<byte> octet = stackalloc byte[16];
+ address.TryWriteBytes(octet, out _);
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
+ }
+
+ /// <summary>
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
+ /// </summary>
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(byte cidr, AddressFamily family)
+ {
+ uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
+ }
+
+ /// <summary>
+ /// Convert a mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
+ /// </summary>
+ /// <param name="mask">Subnet mask.</param>
+ /// <returns>Byte CIDR representing the mask.</returns>
+ public static byte MaskToCidr(IPAddress mask)
+ {
+ if (mask == null)
+ {
+ throw new ArgumentNullException(nameof(mask));
+ }
+
+ byte cidrnet = 0;
+ if (!mask.Equals(IPAddress.Any))
+ {
+ // GetAddressBytes
+ Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ mask.TryWriteBytes(bytes, out _);
+
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
+ {
+ for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
+ {
+ if (zeroed)
+ {
+ // Invalid netmask.
+ return (byte)~cidrnet;
+ }
+
+ if ((v & 0x80) == 0)
+ {
+ zeroed = true;
+ }
+ else
+ {
+ cidrnet++;
+ }
+ }
+ }
+ }
+
+ return cidrnet;
+ }
+
+ /// <summary>
+ /// Tests to see if this object is a Loopback address.
+ /// </summary>
+ /// <returns>True if it is.</returns>
+ public virtual bool IsLoopback()
+ {
+ return IsLoopback(Address);
+ }
+
+ /// <summary>
+ /// Removes all addresses of a specific type from this object.
+ /// </summary>
+ /// <param name="family">Type of address to remove.</param>
+ public virtual void Remove(AddressFamily family)
+ {
+ // This method only performs a function in the IPHost implementation of IPObject.
+ }
+
+ /// <summary>
+ /// Tests to see if this object is an IPv6 address.
+ /// </summary>
+ /// <returns>True if it is.</returns>
+ public virtual bool IsIP6()
+ {
+ return IsIP6(Address);
+ }
+
+ /// <summary>
+ /// Returns true if this IP address is in the RFC private address range.
+ /// </summary>
+ /// <returns>True this object has a private address.</returns>
+ public virtual bool IsPrivateAddressRange()
+ {
+ return IsPrivateAddressRange(Address);
+ }
+
+ /// <summary>
+ /// Compares this to the object passed as a parameter.
+ /// </summary>
+ /// <param name="ip">Object to compare to.</param>
+ /// <returns>Equality result.</returns>
+ public virtual bool Equals(IPAddress ip)
+ {
+ if (ip != null)
+ {
+ if (ip.IsIPv4MappedToIPv6)
+ {
+ ip = ip.MapToIPv4();
+ }
+
+ return !Address.Equals(IPAddress.None) && Address.Equals(ip);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares this to the object passed as a parameter.
+ /// </summary>
+ /// <param name="other">Object to compare to.</param>
+ /// <returns>Equality result.</returns>
+ public virtual bool Equals(IPObject? other)
+ {
+ if (other != null)
+ {
+ return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares the address in this object and the address in the object passed as a parameter.
+ /// </summary>
+ /// <param name="address">Object's IP address to compare to.</param>
+ /// <returns>Comparison result.</returns>
+ public abstract bool Contains(IPObject address);
+
+ /// <summary>
+ /// Compares the address in this object and the address in the object passed as a parameter.
+ /// </summary>
+ /// <param name="address">Object's IP address to compare to.</param>
+ /// <returns>Comparison result.</returns>
+ public abstract bool Contains(IPAddress address);
+
+ /// <inheritdoc/>
+ public override int GetHashCode()
+ {
+ return Address.GetHashCode();
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(object? obj)
+ {
+ return Equals(obj as IPObject);
+ }
+
+ /// <summary>
+ /// Calculates the network address of this object.
+ /// </summary>
+ /// <returns>Returns the network address of this object.</returns>
+ protected abstract IPObject CalculateNetworkAddress();
+ }
+}
diff --git a/MediaBrowser.Common/Net/NamedClient.cs b/MediaBrowser.Common/Net/NamedClient.cs
new file mode 100644
index 000000000..0f6161c32
--- /dev/null
+++ b/MediaBrowser.Common/Net/NamedClient.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Registered http client names.
+ /// </summary>
+ public static class NamedClient
+ {
+ /// <summary>
+ /// Gets the value for the default named http client.
+ /// </summary>
+ public const string Default = nameof(Default);
+
+ /// <summary>
+ /// Gets the value for the MusicBrainz named http client.
+ /// </summary>
+ public const string MusicBrainz = nameof(MusicBrainz);
+ }
+}
diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs
new file mode 100644
index 000000000..264bfacb4
--- /dev/null
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@ -0,0 +1,260 @@
+using System;
+using System.Collections.ObjectModel;
+using System.Net;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkExtensions" />.
+ /// </summary>
+ public static class NetworkExtensions
+ {
+ /// <summary>
+ /// Add an address to the collection.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="ip">Item to add.</param>
+ public static void AddItem(this Collection<IPObject> source, IPAddress ip)
+ {
+ if (!source.ContainsAddress(ip))
+ {
+ source.Add(new IPNetAddress(ip, 32));
+ }
+ }
+
+ /// <summary>
+ /// Adds a network to the collection.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">Item to add.</param>
+ /// <param name="itemsAreNetworks">If <c>true</c> the values are treated as subnets.
+ /// If <b>false</b> items are addresses.</param>
+ public static void AddItem(this Collection<IPObject> source, IPObject item, bool itemsAreNetworks = true)
+ {
+ if (!source.ContainsAddress(item) || !itemsAreNetworks)
+ {
+ source.Add(item);
+ }
+ }
+
+ /// <summary>
+ /// Converts this object to a string.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <returns>Returns a string representation of this object.</returns>
+ public static string AsString(this Collection<IPObject> source)
+ {
+ return $"[{string.Join(',', source)}]";
+ }
+
+ /// <summary>
+ /// Returns true if the collection contains an item with the ip address,
+ /// or the ip address falls within any of the collection's network ranges.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">The item to look for.</param>
+ /// <returns>True if the collection contains the item.</returns>
+ public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item)
+ {
+ if (source.Count == 0)
+ {
+ return false;
+ }
+
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ if (item.IsIPv4MappedToIPv6)
+ {
+ item = item.MapToIPv4();
+ }
+
+ foreach (var i in source)
+ {
+ if (i.Contains(item))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns true if the collection contains an item with the ip address,
+ /// or the ip address falls within any of the collection's network ranges.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">The item to look for.</param>
+ /// <returns>True if the collection contains the item.</returns>
+ public static bool ContainsAddress(this Collection<IPObject> source, IPObject item)
+ {
+ if (source.Count == 0)
+ {
+ return false;
+ }
+
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ foreach (var i in source)
+ {
+ if (i.Contains(item))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares two Collection{IPObject} objects. The order is ignored.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="dest">Item to compare to.</param>
+ /// <returns>True if both are equal.</returns>
+ public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest)
+ {
+ if (dest == null || source.Count != dest.Count)
+ {
+ return false;
+ }
+
+ foreach (var sourceItem in source)
+ {
+ bool found = false;
+ foreach (var destItem in dest)
+ {
+ if (sourceItem.Equals(destItem))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Returns a collection containing the subnets of this collection given.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <returns>Collection{IPObject} object containing the subnets.</returns>
+ public static Collection<IPObject> AsNetworks(this Collection<IPObject> source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ Collection<IPObject> res = new Collection<IPObject>();
+
+ foreach (IPObject i in source)
+ {
+ if (i is IPNetAddress nw)
+ {
+ // Add the subnet calculated from the interface address/mask.
+ var na = nw.NetworkAddress;
+ na.Tag = i.Tag;
+ res.AddItem(na);
+ }
+ else if (i is IPHost ipHost)
+ {
+ // Flatten out IPHost and add all its ip addresses.
+ foreach (var addr in ipHost.GetAddresses())
+ {
+ IPNetAddress host = new IPNetAddress(addr)
+ {
+ Tag = i.Tag
+ };
+
+ res.AddItem(host);
+ }
+ }
+ }
+
+ return res;
+ }
+
+ /// <summary>
+ /// Excludes all the items from this list that are found in excludeList.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="excludeList">Items to exclude.</param>
+ /// <param name="isNetwork">Collection is a network collection.</param>
+ /// <returns>A new collection, with the items excluded.</returns>
+ public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList, bool isNetwork)
+ {
+ if (source.Count == 0 || excludeList == null)
+ {
+ return new Collection<IPObject>(source);
+ }
+
+ Collection<IPObject> results = new Collection<IPObject>();
+
+ bool found;
+ foreach (var outer in source)
+ {
+ found = false;
+
+ foreach (var inner in excludeList)
+ {
+ if (outer.Equals(inner))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ results.AddItem(outer, isNetwork);
+ }
+ }
+
+ return results;
+ }
+
+ /// <summary>
+ /// Returns all items that co-exist in this object and target.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="target">Collection to compare with.</param>
+ /// <returns>A collection containing all the matches.</returns>
+ public static Collection<IPObject> ThatAreContainedInNetworks(this Collection<IPObject> source, Collection<IPObject> target)
+ {
+ if (source.Count == 0)
+ {
+ return new Collection<IPObject>();
+ }
+
+ if (target == null)
+ {
+ throw new ArgumentNullException(nameof(target));
+ }
+
+ Collection<IPObject> nc = new Collection<IPObject>();
+
+ foreach (IPObject i in source)
+ {
+ if (target.ContainsAddress(i))
+ {
+ nc.AddItem(i);
+ }
+ }
+
+ return nc;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs
index 1ff2e98ef..8972089a8 100644
--- a/MediaBrowser.Common/Plugins/BasePlugin.cs
+++ b/MediaBrowser.Common/Plugins/BasePlugin.cs
@@ -1,15 +1,19 @@
+#nullable disable
+
using System;
using System.IO;
-using MediaBrowser.Common.Configuration;
+using System.Reflection;
using MediaBrowser.Model.Plugins;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Common.Plugins
{
+ /// <summary>
+ /// Provides a common base class for all plugins.
+ /// </summary>
public abstract class BasePlugin : IPlugin, IPluginAssembly
{
/// <summary>
- /// Gets the name of the plugin
+ /// Gets the name of the plugin.
/// </summary>
/// <value>The name.</value>
public abstract string Name { get; }
@@ -27,42 +31,53 @@ namespace MediaBrowser.Common.Plugins
public virtual Guid Id { get; private set; }
/// <summary>
- /// Gets the plugin version
+ /// Gets the plugin version.
/// </summary>
/// <value>The version.</value>
public Version Version { get; private set; }
/// <summary>
- /// Gets the path to the assembly file
+ /// Gets the path to the assembly file.
/// </summary>
/// <value>The assembly file path.</value>
public string AssemblyFilePath { get; private set; }
/// <summary>
+ /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed.
+ /// </summary>
+ /// <value>The data folder path.</value>
+ public string DataFolderPath { get; private set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the plugin can be uninstalled.
+ /// </summary>
+ public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath)
+ .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.Ordinal);
+
+ /// <summary>
/// Gets the plugin info.
/// </summary>
/// <returns>PluginInfo.</returns>
public virtual PluginInfo GetPluginInfo()
{
- var info = new PluginInfo
- {
- Name = Name,
- Version = Version.ToString(),
- Description = Description,
- Id = Id.ToString()
- };
+ var info = new PluginInfo(
+ Name,
+ Version,
+ Description,
+ Id,
+ CanUninstall);
return info;
}
/// <summary>
- /// Called when just before the plugin is uninstalled from the server.
+ /// Called just before the plugin is uninstalled from the server.
/// </summary>
public virtual void OnUninstalling()
{
-
}
+ /// <inheritdoc />
public void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion)
{
AssemblyFilePath = assemblyFilePath;
@@ -70,180 +85,10 @@ namespace MediaBrowser.Common.Plugins
Version = assemblyVersion;
}
+ /// <inheritdoc />
public void SetId(Guid assemblyId)
{
Id = assemblyId;
}
-
- /// <summary>
- /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed
- /// </summary>
- /// <value>The data folder path.</value>
- public string DataFolderPath { get; private set; }
- }
-
- /// <summary>
- /// Provides a common base class for all plugins
- /// </summary>
- /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
- public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration
- where TConfigurationType : BasePluginConfiguration
- {
- /// <summary>
- /// Gets the application paths.
- /// </summary>
- /// <value>The application paths.</value>
- protected IApplicationPaths ApplicationPaths { get; private set; }
-
- /// <summary>
- /// Gets the XML serializer.
- /// </summary>
- /// <value>The XML serializer.</value>
- protected IXmlSerializer XmlSerializer { get; private set; }
-
- /// <summary>
- /// Gets the type of configuration this plugin uses
- /// </summary>
- /// <value>The type of the configuration.</value>
- public Type ConfigurationType => typeof(TConfigurationType);
-
- private Action<string> _directoryCreateFn;
- public void SetStartupInfo(Action<string> directoryCreateFn)
- {
- // hack alert, until the .net core transition is complete
- _directoryCreateFn = directoryCreateFn;
- }
-
- /// <summary>
- /// Gets the name the assembly file
- /// </summary>
- /// <value>The name of the assembly file.</value>
- protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath);
-
- /// <summary>
- /// The _configuration sync lock
- /// </summary>
- private readonly object _configurationSyncLock = new object();
- /// <summary>
- /// The _configuration
- /// </summary>
- private TConfigurationType _configuration;
- /// <summary>
- /// Gets the plugin's configuration
- /// </summary>
- /// <value>The configuration.</value>
- public TConfigurationType Configuration
- {
- get
- {
- // Lazy load
- if (_configuration == null)
- {
- lock (_configurationSyncLock)
- {
- if (_configuration == null)
- {
- _configuration = LoadConfiguration();
- }
- }
- }
- return _configuration;
- }
- protected set => _configuration = value;
- }
-
- private TConfigurationType LoadConfiguration()
- {
- var path = ConfigurationFilePath;
-
- try
- {
- return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path);
- }
- catch
- {
- return (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType));
- }
- }
-
- /// <summary>
- /// Gets the name of the configuration file. Subclasses should override
- /// </summary>
- /// <value>The name of the configuration file.</value>
- public virtual string ConfigurationFileName => Path.ChangeExtension(AssemblyFileName, ".xml");
-
- /// <summary>
- /// Gets the full path to the configuration file
- /// </summary>
- /// <value>The configuration file path.</value>
- public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName);
-
- /// <summary>
- /// Initializes a new instance of the <see cref="BasePlugin{TConfigurationType}" /> class.
- /// </summary>
- /// <param name="applicationPaths">The application paths.</param>
- /// <param name="xmlSerializer">The XML serializer.</param>
- protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
- {
- ApplicationPaths = applicationPaths;
- XmlSerializer = xmlSerializer;
- }
-
- /// <summary>
- /// The _save lock
- /// </summary>
- private readonly object _configurationSaveLock = new object();
-
- /// <summary>
- /// Saves the current configuration to the file system
- /// </summary>
- public virtual void SaveConfiguration()
- {
- lock (_configurationSaveLock)
- {
- _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath));
-
- XmlSerializer.SerializeToFile(Configuration, ConfigurationFilePath);
- }
- }
-
- /// <summary>
- /// Completely overwrites the current configuration with a new copy
- /// Returns true or false indicating success or failure
- /// </summary>
- /// <param name="configuration">The configuration.</param>
- /// <exception cref="ArgumentNullException">configuration</exception>
- public virtual void UpdateConfiguration(BasePluginConfiguration configuration)
- {
- if (configuration == null)
- {
- throw new ArgumentNullException(nameof(configuration));
- }
-
- Configuration = (TConfigurationType)configuration;
-
- SaveConfiguration();
- }
-
- /// <summary>
- /// Gets the plugin's configuration
- /// </summary>
- /// <value>The configuration.</value>
- BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration;
-
- public override PluginInfo GetPluginInfo()
- {
- var info = base.GetPluginInfo();
-
- info.ConfigurationFileName = ConfigurationFileName;
-
- return info;
- }
- }
-
- public interface IPluginAssembly
- {
- void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion);
- void SetId(Guid assemblyId);
}
}
diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs
new file mode 100644
index 000000000..afda83a7c
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs
@@ -0,0 +1,205 @@
+#nullable disable
+#pragma warning disable SA1649 // File name should match first type name
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace MediaBrowser.Common.Plugins
+{
+ /// <summary>
+ /// Provides a common base class for all plugins.
+ /// </summary>
+ /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
+ public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration
+ where TConfigurationType : BasePluginConfiguration
+ {
+ /// <summary>
+ /// The configuration sync lock.
+ /// </summary>
+ private readonly object _configurationSyncLock = new object();
+
+ /// <summary>
+ /// The configuration save lock.
+ /// </summary>
+ private readonly object _configurationSaveLock = new object();
+
+ /// <summary>
+ /// The configuration.
+ /// </summary>
+ private TConfigurationType _configuration;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BasePlugin{TConfigurationType}" /> class.
+ /// </summary>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="xmlSerializer">The XML serializer.</param>
+ protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ {
+ ApplicationPaths = applicationPaths;
+ XmlSerializer = xmlSerializer;
+
+ var assembly = GetType().Assembly;
+ var assemblyName = assembly.GetName();
+ var assemblyFilePath = assembly.Location;
+
+ var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
+ if (Version != null && !Directory.Exists(dataFolderPath))
+ {
+ // Try again with the version number appended to the folder name.
+ dataFolderPath += "_" + Version.ToString();
+ }
+
+ SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
+
+ var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
+ if (idAttributes.Length > 0)
+ {
+ var attribute = (GuidAttribute)idAttributes[0];
+ var assemblyId = new Guid(attribute.Value);
+
+ SetId(assemblyId);
+ }
+ }
+
+ /// <summary>
+ /// Gets the application paths.
+ /// </summary>
+ /// <value>The application paths.</value>
+ protected IApplicationPaths ApplicationPaths { get; private set; }
+
+ /// <summary>
+ /// Gets the XML serializer.
+ /// </summary>
+ /// <value>The XML serializer.</value>
+ protected IXmlSerializer XmlSerializer { get; private set; }
+
+ /// <summary>
+ /// Gets the type of configuration this plugin uses.
+ /// </summary>
+ /// <value>The type of the configuration.</value>
+ public Type ConfigurationType => typeof(TConfigurationType);
+
+ /// <summary>
+ /// Gets or sets the event handler that is triggered when this configuration changes.
+ /// </summary>
+ public EventHandler<BasePluginConfiguration> ConfigurationChanged { get; set; }
+
+ /// <summary>
+ /// Gets the name the assembly file.
+ /// </summary>
+ /// <value>The name of the assembly file.</value>
+ protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath);
+
+ /// <summary>
+ /// Gets or sets the plugin configuration.
+ /// </summary>
+ /// <value>The configuration.</value>
+ public TConfigurationType Configuration
+ {
+ get
+ {
+ // Lazy load
+ if (_configuration == null)
+ {
+ lock (_configurationSyncLock)
+ {
+ _configuration ??= LoadConfiguration();
+ }
+ }
+
+ return _configuration;
+ }
+
+ protected set => _configuration = value;
+ }
+
+ /// <summary>
+ /// Gets the name of the configuration file. Subclasses should override.
+ /// </summary>
+ /// <value>The name of the configuration file.</value>
+ public virtual string ConfigurationFileName => Path.ChangeExtension(AssemblyFileName, ".xml");
+
+ /// <summary>
+ /// Gets the full path to the configuration file.
+ /// </summary>
+ /// <value>The configuration file path.</value>
+ public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName);
+
+ /// <summary>
+ /// Gets the plugin configuration.
+ /// </summary>
+ /// <value>The configuration.</value>
+ BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration;
+
+ /// <summary>
+ /// Saves the current configuration to the file system.
+ /// </summary>
+ /// <param name="config">Configuration to save.</param>
+ public virtual void SaveConfiguration(TConfigurationType config)
+ {
+ lock (_configurationSaveLock)
+ {
+ var folder = Path.GetDirectoryName(ConfigurationFilePath);
+ if (!Directory.Exists(folder))
+ {
+ Directory.CreateDirectory(folder);
+ }
+
+ XmlSerializer.SerializeToFile(config, ConfigurationFilePath);
+ }
+ }
+
+ /// <summary>
+ /// Saves the current configuration to the file system.
+ /// </summary>
+ public virtual void SaveConfiguration()
+ {
+ SaveConfiguration(Configuration);
+ }
+
+ /// <inheritdoc />
+ public virtual void UpdateConfiguration(BasePluginConfiguration configuration)
+ {
+ if (configuration == null)
+ {
+ throw new ArgumentNullException(nameof(configuration));
+ }
+
+ Configuration = (TConfigurationType)configuration;
+
+ SaveConfiguration(Configuration);
+
+ ConfigurationChanged?.Invoke(this, configuration);
+ }
+
+ /// <inheritdoc />
+ public override PluginInfo GetPluginInfo()
+ {
+ var info = base.GetPluginInfo();
+
+ info.ConfigurationFileName = ConfigurationFileName;
+
+ return info;
+ }
+
+ private TConfigurationType LoadConfiguration()
+ {
+ var path = ConfigurationFilePath;
+
+ try
+ {
+ return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path);
+ }
+ catch
+ {
+ var config = (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType));
+ SaveConfiguration(config);
+ return config;
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs
new file mode 100644
index 000000000..af9272caa
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs
@@ -0,0 +1,27 @@
+using System;
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Common.Plugins
+{
+ /// <summary>
+ /// Defines the <see cref="IHasPluginConfiguration" />.
+ /// </summary>
+ public interface IHasPluginConfiguration
+ {
+ /// <summary>
+ /// Gets the type of configuration this plugin uses.
+ /// </summary>
+ Type ConfigurationType { get; }
+
+ /// <summary>
+ /// Gets the plugin's configuration.
+ /// </summary>
+ BasePluginConfiguration Configuration { get; }
+
+ /// <summary>
+ /// Completely overwrites the current configuration with a new copy.
+ /// </summary>
+ /// <param name="configuration">The configuration.</param>
+ void UpdateConfiguration(BasePluginConfiguration configuration);
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs
index 32527c299..01e0a536d 100644
--- a/MediaBrowser.Common/Plugins/IPlugin.cs
+++ b/MediaBrowser.Common/Plugins/IPlugin.cs
@@ -1,51 +1,52 @@
+#nullable disable
+
using System;
using MediaBrowser.Model.Plugins;
namespace MediaBrowser.Common.Plugins
{
/// <summary>
- /// Interface IPlugin
+ /// Defines the <see cref="IPlugin" />.
/// </summary>
public interface IPlugin
{
/// <summary>
- /// Gets the name of the plugin
+ /// Gets the name of the plugin.
/// </summary>
- /// <value>The name.</value>
string Name { get; }
/// <summary>
- /// Gets the description.
+ /// Gets the Description.
/// </summary>
- /// <value>The description.</value>
string Description { get; }
/// <summary>
/// Gets the unique id.
/// </summary>
- /// <value>The unique id.</value>
Guid Id { get; }
/// <summary>
- /// Gets the plugin version
+ /// Gets the plugin version.
/// </summary>
- /// <value>The version.</value>
Version Version { get; }
/// <summary>
- /// Gets the path to the assembly file
+ /// Gets the path to the assembly file.
/// </summary>
- /// <value>The assembly file path.</value>
string AssemblyFilePath { get; }
/// <summary>
- /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed
+ /// Gets a value indicating whether the plugin can be uninstalled.
+ /// </summary>
+ bool CanUninstall { get; }
+
+ /// <summary>
+ /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed.
/// </summary>
- /// <value>The data folder path.</value>
string DataFolderPath { get; }
/// <summary>
- /// Gets the plugin info.
+ /// Gets the <see cref="PluginInfo"/>.
/// </summary>
/// <returns>PluginInfo.</returns>
PluginInfo GetPluginInfo();
@@ -55,29 +56,4 @@ namespace MediaBrowser.Common.Plugins
/// </summary>
void OnUninstalling();
}
-
- public interface IHasPluginConfiguration
- {
- /// <summary>
- /// Gets the type of configuration this plugin uses
- /// </summary>
- /// <value>The type of the configuration.</value>
- Type ConfigurationType { get; }
-
- /// <summary>
- /// Completely overwrites the current configuration with a new copy
- /// Returns true or false indicating success or failure
- /// </summary>
- /// <param name="configuration">The configuration.</param>
- /// <exception cref="ArgumentNullException">configuration</exception>
- void UpdateConfiguration(BasePluginConfiguration configuration);
-
- /// <summary>
- /// Gets the plugin's configuration
- /// </summary>
- /// <value>The configuration.</value>
- BasePluginConfiguration Configuration { get; }
-
- void SetStartupInfo(Action<string> directoryCreateFn);
- }
}
diff --git a/MediaBrowser.Common/Plugins/IPluginAssembly.cs b/MediaBrowser.Common/Plugins/IPluginAssembly.cs
new file mode 100644
index 000000000..6df4fbb76
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/IPluginAssembly.cs
@@ -0,0 +1,13 @@
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Common.Plugins
+{
+ public interface IPluginAssembly
+ {
+ void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion);
+
+ void SetId(Guid assemblyId);
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs
new file mode 100644
index 000000000..176bcbbd5
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/IPluginManager.cs
@@ -0,0 +1,96 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading.Tasks;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Updates;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace MediaBrowser.Common.Plugins
+{
+ /// <summary>
+ /// Defines the <see cref="IPluginManager" />.
+ /// </summary>
+ public interface IPluginManager
+ {
+ /// <summary>
+ /// Gets the Plugins.
+ /// </summary>
+ IReadOnlyList<LocalPlugin> Plugins { get; }
+
+ /// <summary>
+ /// Creates the plugins.
+ /// </summary>
+ void CreatePlugins();
+
+ /// <summary>
+ /// Returns all the assemblies.
+ /// </summary>
+ /// <returns>An IEnumerable{Assembly}.</returns>
+ IEnumerable<Assembly> LoadAssemblies();
+
+ /// <summary>
+ /// Registers the plugin's services with the DI.
+ /// Note: DI is not yet instantiated yet.
+ /// </summary>
+ /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
+ void RegisterServices(IServiceCollection serviceCollection);
+
+ /// <summary>
+ /// Saves the manifest back to disk.
+ /// </summary>
+ /// <param name="manifest">The <see cref="PluginManifest"/> to save.</param>
+ /// <param name="path">The path where to save the manifest.</param>
+ /// <returns>True if successful.</returns>
+ bool SaveManifest(PluginManifest manifest, string path);
+
+ /// <summary>
+ /// Generates a manifest from repository data.
+ /// </summary>
+ /// <param name="packageInfo">The <see cref="PackageInfo"/> used to generate a manifest.</param>
+ /// <param name="version">Version to be installed.</param>
+ /// <param name="path">The path where to save the manifest.</param>
+ /// <param name="status">Initial status of the plugin.</param>
+ /// <returns>True if successful.</returns>
+ Task<bool> GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status);
+
+ /// <summary>
+ /// Imports plugin details from a folder.
+ /// </summary>
+ /// <param name="folder">Folder of the plugin.</param>
+ void ImportPluginFrom(string folder);
+
+ /// <summary>
+ /// Disable the plugin.
+ /// </summary>
+ /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
+ void FailPlugin(Assembly assembly);
+
+ /// <summary>
+ /// Disable the plugin.
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
+ void DisablePlugin(LocalPlugin plugin);
+
+ /// <summary>
+ /// Enables the plugin, disabling all other versions.
+ /// </summary>
+ /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
+ void EnablePlugin(LocalPlugin plugin);
+
+ /// <summary>
+ /// Attempts to find the plugin with and id of <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">Id of plugin.</param>
+ /// <param name="version">The version of the plugin to locate.</param>
+ /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
+ LocalPlugin? GetPlugin(Guid id, Version? version = null);
+
+ /// <summary>
+ /// Removes the plugin.
+ /// </summary>
+ /// <param name="plugin">The plugin.</param>
+ /// <returns>Outcome of the operation.</returns>
+ bool RemovePlugin(LocalPlugin plugin);
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs
new file mode 100644
index 000000000..3afe874c5
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs
@@ -0,0 +1,19 @@
+namespace MediaBrowser.Common.Plugins
+{
+ using Microsoft.Extensions.DependencyInjection;
+
+ /// <summary>
+ /// Defines the <see cref="IPluginServiceRegistrator" />.
+ /// </summary>
+ public interface IPluginServiceRegistrator
+ {
+ /// <summary>
+ /// Registers the plugin's services with the service collection.
+ /// </summary>
+ /// <remarks>
+ /// This interface is only used for service registration and requires a parameterless constructor.
+ /// </remarks>
+ /// <param name="serviceCollection">The service collection.</param>
+ void RegisterServices(IServiceCollection serviceCollection);
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs
new file mode 100644
index 000000000..4c8e2d504
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs
@@ -0,0 +1,139 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Common.Plugins
+{
+ /// <summary>
+ /// Local plugin class.
+ /// </summary>
+ public class LocalPlugin : IEquatable<LocalPlugin>
+ {
+ private readonly bool _supported;
+ private Version? _version;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LocalPlugin"/> class.
+ /// </summary>
+ /// <param name="path">The plugin path.</param>
+ /// <param name="isSupported"><b>True</b> if Jellyfin supports this version of the plugin.</param>
+ /// <param name="manifest">The manifest record for this plugin, or null if one does not exist.</param>
+ public LocalPlugin(string path, bool isSupported, PluginManifest manifest)
+ {
+ Path = path;
+ DllFiles = Array.Empty<string>();
+ _supported = isSupported;
+ Manifest = manifest;
+ }
+
+ /// <summary>
+ /// Gets the plugin id.
+ /// </summary>
+ public Guid Id => Manifest.Id;
+
+ /// <summary>
+ /// Gets the plugin name.
+ /// </summary>
+ public string Name => Manifest.Name;
+
+ /// <summary>
+ /// Gets the plugin version.
+ /// </summary>
+ public Version Version
+ {
+ get
+ {
+ if (_version == null)
+ {
+ _version = Version.Parse(Manifest.Version);
+ }
+
+ return _version;
+ }
+ }
+
+ /// <summary>
+ /// Gets the plugin path.
+ /// </summary>
+ public string Path { get; }
+
+ /// <summary>
+ /// Gets or sets the list of dll files for this plugin.
+ /// </summary>
+ public IReadOnlyList<string> DllFiles { get; set; }
+
+ /// <summary>
+ /// Gets or sets the instance of this plugin.
+ /// </summary>
+ public IPlugin? Instance { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether Jellyfin supports this version of the plugin, and it's enabled.
+ /// </summary>
+ public bool IsEnabledAndSupported => _supported && Manifest.Status >= PluginStatus.Active;
+
+ /// <summary>
+ /// Gets a value indicating whether the plugin has a manifest.
+ /// </summary>
+ public PluginManifest Manifest { get; }
+
+ /// <summary>
+ /// Compare two <see cref="LocalPlugin"/>.
+ /// </summary>
+ /// <param name="a">The first item.</param>
+ /// <param name="b">The second item.</param>
+ /// <returns>Comparison result.</returns>
+ public static int Compare(LocalPlugin a, LocalPlugin b)
+ {
+ if (a == null || b == null)
+ {
+ throw new ArgumentNullException(a == null ? nameof(a) : nameof(b));
+ }
+
+ var compare = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
+
+ // Id is not equal but name is.
+ if (!a.Id.Equals(b.Id) && compare == 0)
+ {
+ compare = a.Id.CompareTo(b.Id);
+ }
+
+ return compare == 0 ? a.Version.CompareTo(b.Version) : compare;
+ }
+
+ /// <summary>
+ /// Returns the plugin information.
+ /// </summary>
+ /// <returns>A <see cref="PluginInfo"/> instance containing the information.</returns>
+ public PluginInfo GetPluginInfo()
+ {
+ var inst = Instance?.GetPluginInfo() ?? new PluginInfo(Manifest.Name, Version, Manifest.Description, Manifest.Id, true);
+ inst.Status = Manifest.Status;
+ inst.HasImage = !string.IsNullOrEmpty(Manifest.ImagePath);
+ return inst;
+ }
+
+ /// <inheritdoc />
+ public override bool Equals(object? obj)
+ {
+ return obj is LocalPlugin other && this.Equals(other);
+ }
+
+ /// <inheritdoc />
+ public override int GetHashCode()
+ {
+ return Name.GetHashCode(StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <inheritdoc />
+ public bool Equals(LocalPlugin? other)
+ {
+ if (other == null)
+ {
+ return false;
+ }
+
+ return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && Id.Equals(other.Id) && Version.Equals(other.Version);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs
new file mode 100644
index 000000000..2910dbe14
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/PluginManifest.cs
@@ -0,0 +1,108 @@
+using System;
+using System.Text.Json.Serialization;
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Common.Plugins
+{
+ /// <summary>
+ /// Defines a Plugin manifest file.
+ /// </summary>
+ public class PluginManifest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginManifest"/> class.
+ /// </summary>
+ public PluginManifest()
+ {
+ Category = string.Empty;
+ Changelog = string.Empty;
+ Description = string.Empty;
+ Id = Guid.Empty;
+ Name = string.Empty;
+ Owner = string.Empty;
+ Overview = string.Empty;
+ TargetAbi = string.Empty;
+ Version = string.Empty;
+ }
+
+ /// <summary>
+ /// Gets or sets the category of the plugin.
+ /// </summary>
+ [JsonPropertyName("category")]
+ public string Category { get; set; }
+
+ /// <summary>
+ /// Gets or sets the changelog information.
+ /// </summary>
+ [JsonPropertyName("changelog")]
+ public string Changelog { get; set; }
+
+ /// <summary>
+ /// Gets or sets the description of the plugin.
+ /// </summary>
+ [JsonPropertyName("description")]
+ public string Description { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Global Unique Identifier for the plugin.
+ /// </summary>
+ [JsonPropertyName("guid")]
+ public Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Name of the plugin.
+ /// </summary>
+ [JsonPropertyName("name")]
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets an overview of the plugin.
+ /// </summary>
+ [JsonPropertyName("overview")]
+ public string Overview { get; set; }
+
+ /// <summary>
+ /// Gets or sets the owner of the plugin.
+ /// </summary>
+ [JsonPropertyName("owner")]
+ public string Owner { get; set; }
+
+ /// <summary>
+ /// Gets or sets the compatibility version for the plugin.
+ /// </summary>
+ [JsonPropertyName("targetAbi")]
+ public string TargetAbi { get; set; }
+
+ /// <summary>
+ /// Gets or sets the timestamp of the plugin.
+ /// </summary>
+ [JsonPropertyName("timestamp")]
+ public DateTime Timestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Version number of the plugin.
+ /// </summary>
+ [JsonPropertyName("version")]
+ public string Version { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating the operational status of this plugin.
+ /// </summary>
+ [JsonPropertyName("status")]
+ public PluginStatus Status { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this plugin should automatically update.
+ /// </summary>
+ [JsonPropertyName("autoUpdate")]
+ public bool AutoUpdate { get; set; } = true; // DO NOT MOVE THIS INTO THE CONSTRUCTOR.
+
+ /// <summary>
+ /// Gets or sets the ImagePath
+ /// Gets or sets a value indicating whether this plugin has an image.
+ /// Image must be located in the local plugin folder.
+ /// </summary>
+ [JsonPropertyName("imagePath")]
+ public string? ImagePath { get; set; }
+ }
+}
diff --git a/MediaBrowser.Common/Progress/ActionableProgress.cs b/MediaBrowser.Common/Progress/ActionableProgress.cs
index 9fe01931f..0ba46ea3b 100644
--- a/MediaBrowser.Common/Progress/ActionableProgress.cs
+++ b/MediaBrowser.Common/Progress/ActionableProgress.cs
@@ -1,18 +1,22 @@
+#pragma warning disable CS1591
+#pragma warning disable CA1003
+
using System;
namespace MediaBrowser.Common.Progress
{
/// <summary>
- /// Class ActionableProgress
+ /// Class ActionableProgress.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type for the action parameter.</typeparam>
public class ActionableProgress<T> : IProgress<T>
{
/// <summary>
- /// The _actions
+ /// The _actions.
/// </summary>
- private Action<T> _action;
- public event EventHandler<T> ProgressChanged;
+ private Action<T>? _action;
+
+ public event EventHandler<T>? ProgressChanged;
/// <summary>
/// Registers the action.
@@ -25,29 +29,9 @@ namespace MediaBrowser.Common.Progress
public void Report(T value)
{
- if (ProgressChanged != null)
- {
- ProgressChanged(this, value);
- }
-
- var action = _action;
- if (action != null)
- {
- action(value);
- }
- }
- }
+ ProgressChanged?.Invoke(this, value);
- public class SimpleProgress<T> : IProgress<T>
- {
- public event EventHandler<T> ProgressChanged;
-
- public void Report(T value)
- {
- if (ProgressChanged != null)
- {
- ProgressChanged(this, value);
- }
+ _action?.Invoke(value);
}
}
}
diff --git a/MediaBrowser.Common/Progress/SimpleProgress.cs b/MediaBrowser.Common/Progress/SimpleProgress.cs
new file mode 100644
index 000000000..7071f2bc3
--- /dev/null
+++ b/MediaBrowser.Common/Progress/SimpleProgress.cs
@@ -0,0 +1,17 @@
+#pragma warning disable CS1591
+#pragma warning disable CA1003
+
+using System;
+
+namespace MediaBrowser.Common.Progress
+{
+ public class SimpleProgress<T> : IProgress<T>
+ {
+ public event EventHandler<T>? ProgressChanged;
+
+ public void Report(T value)
+ {
+ ProgressChanged?.Invoke(this, value);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Properties/AssemblyInfo.cs b/MediaBrowser.Common/Properties/AssemblyInfo.cs
index 1a8fdb618..538e89fd1 100644
--- a/MediaBrowser.Common/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.Common/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs
new file mode 100644
index 000000000..487b5a6d2
--- /dev/null
+++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs
@@ -0,0 +1,123 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+
+namespace MediaBrowser.Common.Providers
+{
+ /// <summary>
+ /// Parsers for provider ids.
+ /// </summary>
+ public static class ProviderIdParsers
+ {
+ private const int ImdbMinNumbers = 7;
+ private const int ImdbMaxNumbers = 8;
+ private const string ImdbPrefix = "tt";
+
+ /// <summary>
+ /// Parses an IMDb id from a string.
+ /// </summary>
+ /// <param name="text">The text to parse.</param>
+ /// <param name="imdbId">The parsed IMDb id.</param>
+ /// <returns>True if parsing was successful, false otherwise.</returns>
+ public static bool TryFindImdbId(ReadOnlySpan<char> text, out ReadOnlySpan<char> imdbId)
+ {
+ // imdb id is at least 9 chars (tt + 7 numbers)
+ while (text.Length >= 2 + ImdbMinNumbers)
+ {
+ var ttPos = text.IndexOf(ImdbPrefix);
+ if (ttPos == -1)
+ {
+ imdbId = default;
+ return false;
+ }
+
+ text = text.Slice(ttPos);
+ var i = 2;
+ var limit = Math.Min(text.Length, ImdbMaxNumbers + 2);
+ for (; i < limit; i++)
+ {
+ var c = text[i];
+ if (!IsDigit(c))
+ {
+ break;
+ }
+ }
+
+ // skip if more than 8 digits + 2 chars for tt
+ if (i <= ImdbMaxNumbers + 2 && i >= ImdbMinNumbers + 2)
+ {
+ imdbId = text.Slice(0, i);
+ return true;
+ }
+
+ text = text.Slice(i);
+ }
+
+ imdbId = default;
+ return false;
+ }
+
+ /// <summary>
+ /// Parses an TMDb id from a movie url.
+ /// </summary>
+ /// <param name="text">The text with the url to parse.</param>
+ /// <param name="tmdbId">The parsed TMDb id.</param>
+ /// <returns>True if parsing was successful, false otherwise.</returns>
+ public static bool TryFindTmdbMovieId(ReadOnlySpan<char> text, out ReadOnlySpan<char> tmdbId)
+ => TryFindProviderId(text, "themoviedb.org/movie/", out tmdbId);
+
+ /// <summary>
+ /// Parses an TMDb id from a series url.
+ /// </summary>
+ /// <param name="text">The text with the url to parse.</param>
+ /// <param name="tmdbId">The parsed TMDb id.</param>
+ /// <returns>True if parsing was successful, false otherwise.</returns>
+ public static bool TryFindTmdbSeriesId(ReadOnlySpan<char> text, out ReadOnlySpan<char> tmdbId)
+ => TryFindProviderId(text, "themoviedb.org/tv/", out tmdbId);
+
+ /// <summary>
+ /// Parses an TVDb id from a url.
+ /// </summary>
+ /// <param name="text">The text with the url to parse.</param>
+ /// <param name="tvdbId">The parsed TVDb id.</param>
+ /// <returns>True if parsing was successful, false otherwise.</returns>
+ public static bool TryFindTvdbId(ReadOnlySpan<char> text, out ReadOnlySpan<char> tvdbId)
+ => TryFindProviderId(text, "thetvdb.com/?tab=series&id=", out tvdbId);
+
+ private static bool TryFindProviderId(ReadOnlySpan<char> text, ReadOnlySpan<char> searchString, [NotNullWhen(true)] out ReadOnlySpan<char> providerId)
+ {
+ var searchPos = text.IndexOf(searchString);
+ if (searchPos == -1)
+ {
+ providerId = default;
+ return false;
+ }
+
+ text = text.Slice(searchPos + searchString.Length);
+
+ int i = 0;
+ for (; i < text.Length; i++)
+ {
+ var c = text[i];
+
+ if (!IsDigit(c))
+ {
+ break;
+ }
+ }
+
+ if (i >= 1)
+ {
+ providerId = text.Slice(0, i);
+ return true;
+ }
+
+ providerId = default;
+ return false;
+ }
+
+ private static bool IsDigit(char c)
+ {
+ return c >= '0' && c <= '9';
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs b/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs
new file mode 100644
index 000000000..0445397ad
--- /dev/null
+++ b/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs
@@ -0,0 +1,21 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Common.Providers
+{
+ public class SubtitleConfigurationFactory : IConfigurationFactory
+ {
+ /// <inheritdoc />
+ public IEnumerable<ConfigurationStore> GetConfigurations()
+ {
+ yield return new ConfigurationStore()
+ {
+ Key = "subtitles",
+ ConfigurationType = typeof(SubtitleOptions)
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.Common/System/OperatingSystem.cs b/MediaBrowser.Common/System/OperatingSystem.cs
new file mode 100644
index 000000000..5f673d320
--- /dev/null
+++ b/MediaBrowser.Common/System/OperatingSystem.cs
@@ -0,0 +1,74 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Runtime.InteropServices;
+using System.Threading;
+using MediaBrowser.Model.System;
+
+namespace MediaBrowser.Common.System
+{
+ public static class OperatingSystem
+ {
+ // We can't use Interlocked.CompareExchange for enums
+ private static int _id = int.MaxValue;
+
+ public static OperatingSystemId Id
+ {
+ get
+ {
+ if (_id == int.MaxValue)
+ {
+ Interlocked.CompareExchange(ref _id, (int)GetId(), int.MaxValue);
+ }
+
+ return (OperatingSystemId)_id;
+ }
+ }
+
+ public static string Name
+ {
+ get
+ {
+ switch (Id)
+ {
+ case OperatingSystemId.BSD: return "BSD";
+ case OperatingSystemId.Linux: return "Linux";
+ case OperatingSystemId.Darwin: return "macOS";
+ case OperatingSystemId.Windows: return "Windows";
+ default: throw new PlatformNotSupportedException($"Unknown OS {Id}");
+ }
+ }
+ }
+
+ private static OperatingSystemId GetId()
+ {
+ switch (Environment.OSVersion.Platform)
+ {
+ // On .NET Core `MacOSX` got replaced by `Unix`, this case should never be hit.
+ case PlatformID.MacOSX:
+ return OperatingSystemId.Darwin;
+ case PlatformID.Win32NT:
+ return OperatingSystemId.Windows;
+ case PlatformID.Unix:
+ default:
+ {
+ string osDescription = RuntimeInformation.OSDescription;
+ if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
+ {
+ return OperatingSystemId.Linux;
+ }
+ else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
+ {
+ return OperatingSystemId.Darwin;
+ }
+ else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
+ {
+ return OperatingSystemId.BSD;
+ }
+
+ throw new PlatformNotSupportedException($"Can't resolve OS with description: '{osDescription}'");
+ }
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs
index a263be35f..458494bdc 100644
--- a/MediaBrowser.Common/Updates/IInstallationManager.cs
+++ b/MediaBrowser.Common/Updates/IInstallationManager.cs
@@ -3,117 +3,93 @@ using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Plugins;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Common.Updates
{
+ /// <summary>
+ /// Defines the <see cref="IInstallationManager" />.
+ /// </summary>
public interface IInstallationManager : IDisposable
{
- event EventHandler<InstallationEventArgs> PackageInstalling;
- event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
- event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
- event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
-
- /// <summary>
- /// The current installations
- /// </summary>
- List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
-
/// <summary>
- /// The completed installations
+ /// Gets the completed installations.
/// </summary>
IEnumerable<InstallationInfo> CompletedInstallations { get; }
/// <summary>
- /// Occurs when [plugin uninstalled].
- /// </summary>
- event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
-
- /// <summary>
- /// Occurs when [plugin updated].
- /// </summary>
- event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
-
- /// <summary>
- /// Occurs when [plugin updated].
- /// </summary>
- event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
-
- /// <summary>
- /// Gets all available packages.
+ /// Parses a plugin manifest at the supplied URL.
/// </summary>
+ /// <param name="manifestName">Name of the repository.</param>
+ /// <param name="manifest">The URL to query.</param>
+ /// <param name="filterIncompatible">Filter out incompatible plugins.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="withRegistration">if set to <c>true</c> [with registration].</param>
- /// <param name="packageType">Type of the package.</param>
- /// <param name="applicationVersion">The application version.</param>
- /// <returns>Task{List{PackageInfo}}.</returns>
- Task<List<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
- bool withRegistration = true, string packageType = null, Version applicationVersion = null);
+ /// <returns>Task{IReadOnlyList{PackageInfo}}.</returns>
+ Task<PackageInfo[]> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default);
/// <summary>
- /// Gets all available packages from a static resource.
+ /// Gets all available packages that are supported by this version.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{List{PackageInfo}}.</returns>
- Task<List<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken);
-
- /// <summary>
- /// Gets the package.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="guid">The assembly guid</param>
- /// <param name="classification">The classification.</param>
- /// <param name="version">The version.</param>
- /// <returns>Task{PackageVersionInfo}.</returns>
- Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version);
+ /// <returns>Task{IReadOnlyList{PackageInfo}}.</returns>
+ Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default);
/// <summary>
- /// Gets the latest compatible version.
+ /// Returns all plugins matching the requirements.
/// </summary>
- /// <param name="name">The name.</param>
- /// <param name="guid">The assembly guid</param>
- /// <param name="currentServerVersion">The current server version.</param>
- /// <param name="classification">The classification.</param>
- /// <returns>Task{PackageVersionInfo}.</returns>
- Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release);
+ /// <param name="availablePackages">The available packages.</param>
+ /// <param name="name">The name of the plugin.</param>
+ /// <param name="id">The id of the plugin.</param>
+ /// <param name="specificVersion">The version of the plugin.</param>
+ /// <returns>All plugins matching the requirements.</returns>
+ IEnumerable<PackageInfo> FilterPackages(
+ IEnumerable<PackageInfo> availablePackages,
+ string? name = null,
+ Guid id = default,
+ Version? specificVersion = null);
/// <summary>
- /// Gets the latest compatible version.
+ /// Returns all compatible versions ordered from newest to oldest.
/// </summary>
/// <param name="availablePackages">The available packages.</param>
/// <param name="name">The name.</param>
- /// <param name="guid">The assembly guid</param>
- /// <param name="currentServerVersion">The current server version.</param>
- /// <param name="classification">The classification.</param>
- /// <returns>PackageVersionInfo.</returns>
- PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release);
+ /// <param name="id">The id of the plugin.</param>
+ /// <param name="minVersion">The minimum required version of the plugin.</param>
+ /// <param name="specificVersion">The specific version of the plugin to install.</param>
+ /// <returns>All compatible versions ordered from newest to oldest.</returns>
+ IEnumerable<InstallationInfo> GetCompatibleVersions(
+ IEnumerable<PackageInfo> availablePackages,
+ string? name = null,
+ Guid id = default,
+ Version? minVersion = null,
+ Version? specificVersion = null);
/// <summary>
- /// Gets the available plugin updates.
+ /// Returns the available compatible plugin updates.
/// </summary>
- /// <param name="applicationVersion">The current server version.</param>
- /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
- Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken);
+ /// <returns>The available plugin updates.</returns>
+ Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default);
/// <summary>
/// Installs the package.
/// </summary>
/// <param name="package">The package.</param>
- /// <param name="isPlugin">if set to <c>true</c> [is plugin].</param>
- /// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">package</exception>
- Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress<double> progress, CancellationToken cancellationToken);
+ /// <returns><see cref="Task" />.</returns>
+ Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken = default);
/// <summary>
- /// Uninstalls a plugin
+ /// Uninstalls a plugin.
/// </summary>
/// <param name="plugin">The plugin.</param>
- /// <exception cref="ArgumentException"></exception>
- void UninstallPlugin(IPlugin plugin);
+ void UninstallPlugin(LocalPlugin plugin);
+
+ /// <summary>
+ /// Cancels the installation.
+ /// </summary>
+ /// <param name="id">The id of the package that is being installed.</param>
+ /// <returns>Returns true if the install was cancelled.</returns>
+ bool CancelInstallation(Guid id);
}
}
diff --git a/MediaBrowser.Common/Updates/InstallationEventArgs.cs b/MediaBrowser.Common/Updates/InstallationEventArgs.cs
index 9f215e889..f4f759955 100644
--- a/MediaBrowser.Common/Updates/InstallationEventArgs.cs
+++ b/MediaBrowser.Common/Updates/InstallationEventArgs.cs
@@ -1,11 +1,23 @@
+#nullable disable
+
+using System;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Common.Updates
{
- public class InstallationEventArgs
+ /// <summary>
+ /// Defines the <see cref="InstallationEventArgs" />.
+ /// </summary>
+ public class InstallationEventArgs : EventArgs
{
+ /// <summary>
+ /// Gets or sets the <see cref="InstallationInfo"/>.
+ /// </summary>
public InstallationInfo InstallationInfo { get; set; }
- public PackageVersionInfo PackageVersionInfo { get; set; }
+ /// <summary>
+ /// Gets or sets the <see cref="VersionInfo"/>.
+ /// </summary>
+ public VersionInfo VersionInfo { get; set; }
}
}
diff --git a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs
index 43adfb02d..d37146195 100644
--- a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs
+++ b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Common.Updates
diff --git a/MediaBrowser.Controller/Authentication/AuthenticationException.cs b/MediaBrowser.Controller/Authentication/AuthenticationException.cs
new file mode 100644
index 000000000..081f877f7
--- /dev/null
+++ b/MediaBrowser.Controller/Authentication/AuthenticationException.cs
@@ -0,0 +1,35 @@
+using System;
+
+namespace MediaBrowser.Controller.Authentication
+{
+ /// <summary>
+ /// The exception that is thrown when an attempt to authenticate fails.
+ /// </summary>
+ public class AuthenticationException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationException"/> class.
+ /// </summary>
+ public AuthenticationException() : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationException"/> class.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public AuthenticationException(string message) : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticationException"/> class.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
+ public AuthenticationException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs
index 3c65156e3..635e4eb3d 100644
--- a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs
+++ b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs
@@ -1,14 +1,20 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dto;
-
namespace MediaBrowser.Controller.Authentication
{
public class AuthenticationResult
{
public UserDto User { get; set; }
+
public SessionInfo SessionInfo { get; set; }
+
public string AccessToken { get; set; }
+
public string ServerId { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
index b9f282bd2..a56d3c822 100644
--- a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
+++ b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
@@ -1,5 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
using MediaBrowser.Model.Users;
namespace MediaBrowser.Controller.Authentication
@@ -7,9 +11,13 @@ namespace MediaBrowser.Controller.Authentication
public interface IAuthenticationProvider
{
string Name { get; }
+
bool IsEnabled { get; }
+
Task<ProviderAuthenticationResult> Authenticate(string username, string password);
- Task<bool> HasPassword(User user);
+
+ bool HasPassword(User user);
+
Task ChangePassword(User user, string newPassword);
}
@@ -26,6 +34,7 @@ namespace MediaBrowser.Controller.Authentication
public class ProviderAuthenticationResult
{
public string Username { get; set; }
+
public string DisplayName { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs b/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs
new file mode 100644
index 000000000..8c9d1baf8
--- /dev/null
+++ b/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs
@@ -0,0 +1,29 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Model.Users;
+
+namespace MediaBrowser.Controller.Authentication
+{
+ public interface IPasswordResetProvider
+ {
+ string Name { get; }
+
+ bool IsEnabled { get; }
+
+ Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork);
+
+ Task<PinRedeemResult> RedeemPasswordResetPin(string pin);
+ }
+
+ public class PasswordPinCreationResult
+ {
+ public string PinFile { get; set; }
+
+ public DateTime ExpirationDate { get; set; }
+ }
+}
diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs
new file mode 100644
index 000000000..abfdb41d8
--- /dev/null
+++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs
@@ -0,0 +1,137 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller.Channels;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.Controller.BaseItemManager
+{
+ /// <inheritdoc />
+ public class BaseItemManager : IBaseItemManager
+ {
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ private int _metadataRefreshConcurrency;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseItemManager"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public BaseItemManager(IServerConfigurationManager serverConfigurationManager)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+
+ _metadataRefreshConcurrency = GetMetadataRefreshConcurrency();
+ SetupMetadataThrottler();
+
+ _serverConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
+ }
+
+ /// <inheritdoc />
+ public SemaphoreSlim MetadataRefreshThrottler { get; private set; }
+
+ /// <inheritdoc />
+ public bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name)
+ {
+ if (baseItem is Channel)
+ {
+ // Hack alert.
+ return true;
+ }
+
+ if (baseItem.SourceType == SourceType.Channel)
+ {
+ // Hack alert.
+ return !baseItem.EnableMediaSourceDisplay;
+ }
+
+ var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name);
+ if (typeOptions != null)
+ {
+ return typeOptions.MetadataFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ if (!libraryOptions.EnableInternetProviders)
+ {
+ return false;
+ }
+
+ var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
+
+ return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <inheritdoc />
+ public bool IsImageFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name)
+ {
+ if (baseItem is Channel)
+ {
+ // Hack alert.
+ return true;
+ }
+
+ if (baseItem.SourceType == SourceType.Channel)
+ {
+ // Hack alert.
+ return !baseItem.EnableMediaSourceDisplay;
+ }
+
+ var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name);
+ if (typeOptions != null)
+ {
+ return typeOptions.ImageFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ if (!libraryOptions.EnableInternetProviders)
+ {
+ return false;
+ }
+
+ var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
+
+ return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <summary>
+ /// Called when the configuration is updated.
+ /// It will refresh the metadata throttler if the relevant config changed.
+ /// </summary>
+ private void OnConfigurationUpdated(object? sender, EventArgs e)
+ {
+ int newMetadataRefreshConcurrency = GetMetadataRefreshConcurrency();
+ if (_metadataRefreshConcurrency != newMetadataRefreshConcurrency)
+ {
+ _metadataRefreshConcurrency = newMetadataRefreshConcurrency;
+ SetupMetadataThrottler();
+ }
+ }
+
+ /// <summary>
+ /// Creates the metadata refresh throttler.
+ /// </summary>
+ [MemberNotNull(nameof(MetadataRefreshThrottler))]
+ private void SetupMetadataThrottler()
+ {
+ MetadataRefreshThrottler = new SemaphoreSlim(_metadataRefreshConcurrency);
+ }
+
+ /// <summary>
+ /// Returns the metadata refresh concurrency.
+ /// </summary>
+ private int GetMetadataRefreshConcurrency()
+ {
+ var concurrency = _serverConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency;
+
+ if (concurrency <= 0)
+ {
+ concurrency = Environment.ProcessorCount;
+ }
+
+ return concurrency;
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs
new file mode 100644
index 000000000..e18994214
--- /dev/null
+++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs
@@ -0,0 +1,35 @@
+using System.Threading;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.Controller.BaseItemManager
+{
+ /// <summary>
+ /// The <c>BaseItem</c> manager.
+ /// </summary>
+ public interface IBaseItemManager
+ {
+ /// <summary>
+ /// Gets the semaphore used to limit the amount of concurrent metadata refreshes.
+ /// </summary>
+ SemaphoreSlim MetadataRefreshThrottler { get; }
+
+ /// <summary>
+ /// Is metadata fetcher enabled.
+ /// </summary>
+ /// <param name="baseItem">The base item.</param>
+ /// <param name="libraryOptions">The library options.</param>
+ /// <param name="name">The metadata fetcher name.</param>
+ /// <returns><c>true</c> if metadata fetcher is enabled, else false.</returns>
+ bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name);
+
+ /// <summary>
+ /// Is image fetcher enabled.
+ /// </summary>
+ /// <param name="baseItem">The base item.</param>
+ /// <param name="libraryOptions">The library options.</param>
+ /// <param name="name">The image fetcher name.</param>
+ /// <returns><c>true</c> if image fetcher is enabled, else false.</returns>
+ bool IsImageFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name);
+ }
+}
diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs
index adf03fb66..e6923b55c 100644
--- a/MediaBrowser.Controller/Channels/Channel.cs
+++ b/MediaBrowser.Controller/Channels/Channel.cs
@@ -1,27 +1,42 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Channels
{
public class Channel : Folder
{
+ [JsonIgnore]
+ public override bool SupportsInheritedParentImages => false;
+
+ [JsonIgnore]
+ public override SourceType SourceType => SourceType.Channel;
+
public override bool IsVisible(User user)
{
- if (user.Policy.BlockedChannels != null)
+ var blockedChannelsPreference = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels);
+ if (blockedChannelsPreference.Length != 0)
{
- if (user.Policy.BlockedChannels.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
+ if (blockedChannelsPreference.Contains(Id))
{
return false;
}
}
else
{
- if (!user.Policy.EnableAllChannels && !user.Policy.EnabledChannels.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
+ if (!user.HasPermission(PermissionKind.EnableAllChannels)
+ && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels).Contains(Id))
{
return false;
}
@@ -30,12 +45,6 @@ namespace MediaBrowser.Controller.Channels
return base.IsVisible(user);
}
- [IgnoreDataMember]
- public override bool SupportsInheritedParentImages => false;
-
- [IgnoreDataMember]
- public override SourceType SourceType => SourceType.Channel;
-
protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
{
try
@@ -60,7 +69,7 @@ namespace MediaBrowser.Controller.Channels
public static string GetInternalMetadataPath(string basePath, Guid id)
{
- return System.IO.Path.Combine(basePath, "channels", id.ToString("N"), "metadata");
+ return System.IO.Path.Combine(basePath, "channels", id.ToString("N", CultureInfo.InvariantCulture), "metadata");
}
public override bool CanDelete()
@@ -75,7 +84,7 @@ namespace MediaBrowser.Controller.Channels
internal static bool IsChannelVisible(BaseItem channelItem, User user)
{
- var channel = ChannelManager.GetChannel(channelItem.ChannelId.ToString(""));
+ var channel = ChannelManager.GetChannel(channelItem.ChannelId.ToString(string.Empty));
return channel.IsVisible(user);
}
diff --git a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs
index aff68883b..55f80b240 100644
--- a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs
+++ b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA2227, CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Entities;
@@ -9,6 +13,19 @@ namespace MediaBrowser.Controller.Channels
{
public class ChannelItemInfo : IHasProviderIds
{
+ public ChannelItemInfo()
+ {
+ MediaSources = new List<MediaSourceInfo>();
+ TrailerTypes = new List<TrailerType>();
+ Genres = new List<string>();
+ Studios = new List<string>();
+ People = new List<PersonInfo>();
+ Tags = new List<string>();
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ Artists = new List<string>();
+ AlbumArtists = new List<string>();
+ }
+
public string Name { get; set; }
public string SeriesName { get; set; }
@@ -24,7 +41,9 @@ namespace MediaBrowser.Controller.Channels
public string Overview { get; set; }
public List<string> Genres { get; set; }
+
public List<string> Studios { get; set; }
+
public List<string> Tags { get; set; }
public List<PersonInfo> People { get; set; }
@@ -34,26 +53,33 @@ namespace MediaBrowser.Controller.Channels
public long? RunTimeTicks { get; set; }
public string ImageUrl { get; set; }
+
public string OriginalTitle { get; set; }
public ChannelMediaType MediaType { get; set; }
+
public ChannelFolderType FolderType { get; set; }
public ChannelMediaContentType ContentType { get; set; }
+
public ExtraType ExtraType { get; set; }
+
public List<TrailerType> TrailerTypes { get; set; }
public Dictionary<string, string> ProviderIds { get; set; }
public DateTime? PremiereDate { get; set; }
+
public int? ProductionYear { get; set; }
public DateTime? DateCreated { get; set; }
public DateTime? StartDate { get; set; }
+
public DateTime? EndDate { get; set; }
public int? IndexNumber { get; set; }
+
public int? ParentIndexNumber { get; set; }
public List<MediaSourceInfo> MediaSources { get; set; }
@@ -63,20 +89,9 @@ namespace MediaBrowser.Controller.Channels
public List<string> Artists { get; set; }
public List<string> AlbumArtists { get; set; }
+
public bool IsLiveStream { get; set; }
- public string Etag { get; set; }
- public ChannelItemInfo()
- {
- MediaSources = new List<MediaSourceInfo>();
- TrailerTypes = new List<TrailerType>();
- Genres = new List<string>();
- Studios = new List<string>();
- People = new List<PersonInfo>();
- Tags = new List<string>();
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- Artists = new List<string>();
- AlbumArtists = new List<string>();
- }
+ public string Etag { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Channels/ChannelItemResult.cs b/MediaBrowser.Controller/Channels/ChannelItemResult.cs
index c194c8e48..ca7721991 100644
--- a/MediaBrowser.Controller/Channels/ChannelItemResult.cs
+++ b/MediaBrowser.Controller/Channels/ChannelItemResult.cs
@@ -1,16 +1,19 @@
+#pragma warning disable CS1591
+
+using System;
using System.Collections.Generic;
namespace MediaBrowser.Controller.Channels
{
public class ChannelItemResult
{
- public List<ChannelItemInfo> Items { get; set; }
-
- public int? TotalRecordCount { get; set; }
-
public ChannelItemResult()
{
- Items = new List<ChannelItemInfo>();
+ Items = Array.Empty<ChannelItemInfo>();
}
+
+ public IReadOnlyList<ChannelItemInfo> Items { get; set; }
+
+ public int? TotalRecordCount { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Channels/ChannelItemType.cs b/MediaBrowser.Controller/Channels/ChannelItemType.cs
index 833ae75fe..3ce920e23 100644
--- a/MediaBrowser.Controller/Channels/ChannelItemType.cs
+++ b/MediaBrowser.Controller/Channels/ChannelItemType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Channels
{
public enum ChannelItemType
diff --git a/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs b/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs
new file mode 100644
index 000000000..6f0761e64
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs
@@ -0,0 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Controller.Channels
+{
+ public class ChannelLatestMediaSearch
+ {
+ public string UserId { get; set; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Channels/ChannelParentalRating.cs b/MediaBrowser.Controller/Channels/ChannelParentalRating.cs
index 1d189446d..f77d81c16 100644
--- a/MediaBrowser.Controller/Channels/ChannelParentalRating.cs
+++ b/MediaBrowser.Controller/Channels/ChannelParentalRating.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Channels
{
public enum ChannelParentalRating
diff --git a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs
index c02055b90..990b025bc 100644
--- a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs
+++ b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Channels
{
public class ChannelSearchInfo
@@ -6,9 +10,4 @@ namespace MediaBrowser.Controller.Channels
public string UserId { get; set; }
}
-
- public class ChannelLatestMediaSearch
- {
- public string UserId { get; set; }
- }
}
diff --git a/MediaBrowser.Controller/Channels/IChannel.cs b/MediaBrowser.Controller/Channels/IChannel.cs
index f8ed98a45..01bf8d5c8 100644
--- a/MediaBrowser.Controller/Channels/IChannel.cs
+++ b/MediaBrowser.Controller/Channels/IChannel.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -64,7 +68,7 @@ namespace MediaBrowser.Controller.Channels
/// </summary>
/// <param name="type">The type.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{DynamicImageInfo}.</returns>
+ /// <returns>Task{DynamicImageResponse}.</returns>
Task<DynamicImageResponse> GetChannelImage(ImageType type, CancellationToken cancellationToken);
/// <summary>
diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs
index df508fbe2..49be897ef 100644
--- a/MediaBrowser.Controller/Channels/IChannelManager.cs
+++ b/MediaBrowser.Controller/Channels/IChannelManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
@@ -22,7 +26,7 @@ namespace MediaBrowser.Controller.Channels
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>ChannelFeatures.</returns>
- ChannelFeatures GetChannelFeatures(string id);
+ ChannelFeatures GetChannelFeatures(Guid? id);
/// <summary>
/// Gets all channel features.
@@ -31,6 +35,7 @@ namespace MediaBrowser.Controller.Channels
ChannelFeatures[] GetAllChannelFeatures();
bool EnableMediaSourceDisplay(BaseItem item);
+
bool CanDelete(BaseItem item);
Task DeleteItem(BaseItem item);
@@ -46,32 +51,47 @@ namespace MediaBrowser.Controller.Channels
/// Gets the channels internal.
/// </summary>
/// <param name="query">The query.</param>
+ /// <returns>The channels.</returns>
QueryResult<Channel> GetChannelsInternal(ChannelQuery query);
/// <summary>
/// Gets the channels.
/// </summary>
/// <param name="query">The query.</param>
+ /// <returns>The channels.</returns>
QueryResult<BaseItemDto> GetChannels(ChannelQuery query);
/// <summary>
- /// Gets the latest media.
+ /// Gets the latest channel items.
/// </summary>
+ /// <param name="query">The item query.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The latest channels.</returns>
Task<QueryResult<BaseItemDto>> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
- /// Gets the latest media.
+ /// Gets the latest channel items.
/// </summary>
+ /// <param name="query">The item query.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The latest channels.</returns>
Task<QueryResult<BaseItem>> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel items.
/// </summary>
+ /// <param name="query">The query.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The channel items.</returns>
Task<QueryResult<BaseItemDto>> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken);
/// <summary>
- /// Gets the channel items internal.
+ /// Gets the channel items.
/// </summary>
+ /// <param name="query">The query.</param>
+ /// <param name="progress">The progress to report to.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The channel items.</returns>
Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQuery query, IProgress<double> progress, CancellationToken cancellationToken);
/// <summary>
@@ -79,9 +99,14 @@ namespace MediaBrowser.Controller.Channels
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{MediaSourceInfo}}.</returns>
+ /// <returns>The item media sources.</returns>
IEnumerable<MediaSourceInfo> GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken);
+ /// <summary>
+ /// Whether the item supports media probe.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <returns>Whether media probe should be enabled.</returns>
bool EnableMediaProbe(BaseItem item);
}
}
diff --git a/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs b/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs
new file mode 100644
index 000000000..0539b9048
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs
@@ -0,0 +1,12 @@
+namespace MediaBrowser.Controller.Channels
+{
+ /// <summary>
+ /// Disable media source display.
+ /// </summary>
+ /// <remarks>
+ /// <see cref="Channel"/> can inherit this interface to disable being displayed.
+ /// </remarks>
+ public interface IDisableMediaSourceDisplay
+ {
+ }
+}
diff --git a/MediaBrowser.Controller/Channels/IHasCacheKey.cs b/MediaBrowser.Controller/Channels/IHasCacheKey.cs
index d86ad0dba..9fae43033 100644
--- a/MediaBrowser.Controller/Channels/IHasCacheKey.cs
+++ b/MediaBrowser.Controller/Channels/IHasCacheKey.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Channels
{
public interface IHasCacheKey
diff --git a/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs b/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs
new file mode 100644
index 000000000..64af8496c
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs
@@ -0,0 +1,9 @@
+#pragma warning disable CA1819, CS1591
+
+namespace MediaBrowser.Controller.Channels
+{
+ public interface IHasFolderAttributes
+ {
+ string[] Attributes { get; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs b/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs
index deee46ff7..eeaa6b622 100644
--- a/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs
+++ b/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs
@@ -5,11 +5,17 @@ using MediaBrowser.Model.Dto;
namespace MediaBrowser.Controller.Channels
{
+ /// <summary>
+ /// The channel requires a media info callback.
+ /// </summary>
public interface IRequiresMediaInfoCallback
{
/// <summary>
/// Gets the channel item media information.
/// </summary>
+ /// <param name="id">The channel item id.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The enumerable of media source info.</returns>
Task<IEnumerable<MediaSourceInfo>> GetChannelItemMediaInfo(string id, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Channels/ISearchableChannel.cs b/MediaBrowser.Controller/Channels/ISearchableChannel.cs
index d5b76a160..b87943a6e 100644
--- a/MediaBrowser.Controller/Channels/ISearchableChannel.cs
+++ b/MediaBrowser.Controller/Channels/ISearchableChannel.cs
@@ -1,7 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Channels
{
@@ -15,36 +18,4 @@ namespace MediaBrowser.Controller.Channels
/// <returns>Task{IEnumerable{ChannelItemInfo}}.</returns>
Task<IEnumerable<ChannelItemInfo>> Search(ChannelSearchInfo searchInfo, CancellationToken cancellationToken);
}
-
- public interface ISupportsLatestMedia
- {
- /// <summary>
- /// Gets the latest media.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{ChannelItemInfo}}.</returns>
- Task<IEnumerable<ChannelItemInfo>> GetLatestMedia(ChannelLatestMediaSearch request, CancellationToken cancellationToken);
- }
-
- public interface ISupportsDelete
- {
- bool CanDelete(BaseItem item);
- Task DeleteItem(string id, CancellationToken cancellationToken);
- }
-
- public interface IDisableMediaSourceDisplay
- {
-
- }
-
- public interface ISupportsMediaProbe
- {
-
- }
-
- public interface IHasFolderAttributes
- {
- string[] Attributes { get; }
- }
}
diff --git a/MediaBrowser.Controller/Channels/ISupportsDelete.cs b/MediaBrowser.Controller/Channels/ISupportsDelete.cs
new file mode 100644
index 000000000..204054374
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/ISupportsDelete.cs
@@ -0,0 +1,15 @@
+#pragma warning disable CS1591
+
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+
+namespace MediaBrowser.Controller.Channels
+{
+ public interface ISupportsDelete
+ {
+ bool CanDelete(BaseItem item);
+
+ Task DeleteItem(string id, CancellationToken cancellationToken);
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs
new file mode 100644
index 000000000..dbba7cba2
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs
@@ -0,0 +1,21 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Controller.Channels
+{
+ public interface ISupportsLatestMedia
+ {
+ /// <summary>
+ /// Gets the latest media.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The latest media.</returns>
+ Task<IEnumerable<ChannelItemInfo>> GetLatestMedia(ChannelLatestMediaSearch request, CancellationToken cancellationToken);
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs b/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs
new file mode 100644
index 000000000..bc7683125
--- /dev/null
+++ b/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs
@@ -0,0 +1,9 @@
+namespace MediaBrowser.Controller.Channels
+{
+ /// <summary>
+ /// Channel supports media probe.
+ /// </summary>
+ public interface ISupportsMediaProbe
+ {
+ }
+}
diff --git a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
index 60455e68a..394996868 100644
--- a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
+++ b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA2227, CS1591
+
using System.Collections.Generic;
using MediaBrowser.Model.Channels;
@@ -5,6 +9,14 @@ namespace MediaBrowser.Controller.Channels
{
public class InternalChannelFeatures
{
+ public InternalChannelFeatures()
+ {
+ MediaTypes = new List<ChannelMediaType>();
+ ContentTypes = new List<ChannelMediaContentType>();
+
+ DefaultSortFields = new List<ChannelItemSortField>();
+ }
+
/// <summary>
/// Gets or sets the media types.
/// </summary>
@@ -18,7 +30,7 @@ namespace MediaBrowser.Controller.Channels
public List<ChannelMediaContentType> ContentTypes { get; set; }
/// <summary>
- /// Represents the maximum number of records the channel allows retrieving at a time
+ /// Gets or sets the maximum number of records the channel allows retrieving at a time.
/// </summary>
public int? MaxPageSize { get; set; }
@@ -29,9 +41,10 @@ namespace MediaBrowser.Controller.Channels
public List<ChannelItemSortField> DefaultSortFields { get; set; }
/// <summary>
- /// Indicates if a sort ascending/descending toggle is supported or not.
+ /// Gets or sets a value indicating whether a sort ascending/descending toggle is supported or not.
/// </summary>
public bool SupportsSortOrderToggle { get; set; }
+
/// <summary>
/// Gets or sets the automatic refresh levels.
/// </summary>
@@ -43,18 +56,11 @@ namespace MediaBrowser.Controller.Channels
/// </summary>
/// <value>The daily download limit.</value>
public int? DailyDownloadLimit { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [supports downloading].
/// </summary>
/// <value><c>true</c> if [supports downloading]; otherwise, <c>false</c>.</value>
public bool SupportsContentDownloading { get; set; }
-
- public InternalChannelFeatures()
- {
- MediaTypes = new List<ChannelMediaType>();
- ContentTypes = new List<ChannelMediaContentType>();
-
- DefaultSortFields = new List<ChannelItemSortField>();
- }
}
}
diff --git a/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs b/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs
index 6d5ca75af..0d837faca 100644
--- a/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs
+++ b/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs
@@ -1,7 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Channels;
-
namespace MediaBrowser.Controller.Channels
{
public class InternalChannelItemQuery
diff --git a/MediaBrowser.Controller/Chapters/IChapterManager.cs b/MediaBrowser.Controller/Chapters/IChapterManager.cs
index d061898a1..c049bb97e 100644
--- a/MediaBrowser.Controller/Chapters/IChapterManager.cs
+++ b/MediaBrowser.Controller/Chapters/IChapterManager.cs
@@ -1,16 +1,19 @@
+using System;
using System.Collections.Generic;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Chapters
{
/// <summary>
- /// Interface IChapterManager
+ /// Interface IChapterManager.
/// </summary>
public interface IChapterManager
{
/// <summary>
/// Saves the chapters.
/// </summary>
- void SaveChapters(string itemId, List<ChapterInfo> chapters);
+ /// <param name="itemId">The item.</param>
+ /// <param name="chapters">The set of chapters.</param>
+ void SaveChapters(Guid itemId, IReadOnlyList<ChapterInfo> chapters);
}
}
diff --git a/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs b/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs
new file mode 100644
index 000000000..82b3a4977
--- /dev/null
+++ b/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs
@@ -0,0 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using MediaBrowser.Controller.Entities.Movies;
+
+namespace MediaBrowser.Controller.Collections
+{
+ public class CollectionCreatedEventArgs : EventArgs
+ {
+ /// <summary>
+ /// Gets or sets the collection.
+ /// </summary>
+ /// <value>The collection.</value>
+ public BoxSet Collection { get; set; }
+
+ /// <summary>
+ /// Gets or sets the options.
+ /// </summary>
+ /// <value>The options.</value>
+ public CollectionCreationOptions Options { get; set; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
index 51fe4ce29..30f5f4efa 100644
--- a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
+++ b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Entities;
@@ -6,6 +10,13 @@ namespace MediaBrowser.Controller.Collections
{
public class CollectionCreationOptions : IHasProviderIds
{
+ public CollectionCreationOptions()
+ {
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ ItemIdList = Array.Empty<string>();
+ UserIds = Array.Empty<Guid>();
+ }
+
public string Name { get; set; }
public Guid? ParentId { get; set; }
@@ -14,14 +25,8 @@ namespace MediaBrowser.Controller.Collections
public Dictionary<string, string> ProviderIds { get; set; }
- public string[] ItemIdList { get; set; }
- public Guid[] UserIds { get; set; }
+ public IReadOnlyList<string> ItemIdList { get; set; }
- public CollectionCreationOptions()
- {
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ItemIdList = Array.Empty<string>();
- UserIds = Array.Empty<Guid>();
- }
+ public IReadOnlyList<Guid> UserIds { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Collections/CollectionEvents.cs b/MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs
index bfc6af463..e538fa4b3 100644
--- a/MediaBrowser.Controller/Collections/CollectionEvents.cs
+++ b/MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Entities;
@@ -5,23 +7,14 @@ using MediaBrowser.Controller.Entities.Movies;
namespace MediaBrowser.Controller.Collections
{
- public class CollectionCreatedEventArgs : EventArgs
- {
- /// <summary>
- /// Gets or sets the collection.
- /// </summary>
- /// <value>The collection.</value>
- public BoxSet Collection { get; set; }
-
- /// <summary>
- /// Gets or sets the options.
- /// </summary>
- /// <value>The options.</value>
- public CollectionCreationOptions Options { get; set; }
- }
-
public class CollectionModifiedEventArgs : EventArgs
{
+ public CollectionModifiedEventArgs(BoxSet collection, IReadOnlyCollection<BaseItem> itemsChanged)
+ {
+ Collection = collection;
+ ItemsChanged = itemsChanged;
+ }
+
/// <summary>
/// Gets or sets the collection.
/// </summary>
@@ -32,6 +25,6 @@ namespace MediaBrowser.Controller.Collections
/// Gets or sets the items changed.
/// </summary>
/// <value>The items changed.</value>
- public List<BaseItem> ItemsChanged { get; set; }
+ public IReadOnlyCollection<BaseItem> ItemsChanged { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Collections/ICollectionManager.cs b/MediaBrowser.Controller/Collections/ICollectionManager.cs
index cfe8493d3..b8c33ee5a 100644
--- a/MediaBrowser.Controller/Collections/ICollectionManager.cs
+++ b/MediaBrowser.Controller/Collections/ICollectionManager.cs
@@ -1,5 +1,9 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
@@ -10,40 +14,40 @@ namespace MediaBrowser.Controller.Collections
/// <summary>
/// Occurs when [collection created].
/// </summary>
- event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
+ event EventHandler<CollectionCreatedEventArgs>? CollectionCreated;
/// <summary>
/// Occurs when [items added to collection].
/// </summary>
- event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
+ event EventHandler<CollectionModifiedEventArgs>? ItemsAddedToCollection;
/// <summary>
/// Occurs when [items removed from collection].
/// </summary>
- event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
+ event EventHandler<CollectionModifiedEventArgs>? ItemsRemovedFromCollection;
/// <summary>
/// Creates the collection.
/// </summary>
/// <param name="options">The options.</param>
- BoxSet CreateCollection(CollectionCreationOptions options);
+ /// <returns>BoxSet wrapped in an awaitable task.</returns>
+ Task<BoxSet> CreateCollectionAsync(CollectionCreationOptions options);
/// <summary>
/// Adds to collection.
/// </summary>
/// <param name="collectionId">The collection identifier.</param>
/// <param name="itemIds">The item ids.</param>
- void AddToCollection(Guid collectionId, IEnumerable<string> itemIds);
+ /// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
+ Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds);
/// <summary>
/// Removes from collection.
/// </summary>
/// <param name="collectionId">The collection identifier.</param>
/// <param name="itemIds">The item ids.</param>
- void RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds);
-
- void AddToCollection(Guid collectionId, IEnumerable<Guid> itemIds);
- void RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds);
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ Task RemoveFromCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds);
/// <summary>
/// Collapses the items within box sets.
diff --git a/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs b/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs
index 6660743e6..43ad04dba 100644
--- a/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs
+++ b/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Model.Configuration;
namespace MediaBrowser.Controller.Configuration
{
/// <summary>
- /// Interface IServerConfigurationManager
+ /// Interface IServerConfigurationManager.
/// </summary>
public interface IServerConfigurationManager : IConfigurationManager
{
@@ -19,7 +19,5 @@ namespace MediaBrowser.Controller.Configuration
/// </summary>
/// <value>The configuration.</value>
ServerConfiguration Configuration { get; }
-
- bool SetOptimalValues();
}
}
diff --git a/MediaBrowser.Controller/Devices/CameraImageUploadInfo.cs b/MediaBrowser.Controller/Devices/CameraImageUploadInfo.cs
deleted file mode 100644
index 89d0be58f..000000000
--- a/MediaBrowser.Controller/Devices/CameraImageUploadInfo.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using MediaBrowser.Model.Devices;
-
-namespace MediaBrowser.Controller.Devices
-{
- public class CameraImageUploadInfo
- {
- public LocalFileInfo FileInfo { get; set; }
- public DeviceInfo Device { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Devices/IDeviceManager.cs b/MediaBrowser.Controller/Devices/IDeviceManager.cs
index 77d567631..8362db1a7 100644
--- a/MediaBrowser.Controller/Devices/IDeviceManager.cs
+++ b/MediaBrowser.Controller/Devices/IDeviceManager.cs
@@ -1,9 +1,14 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.IO;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
using MediaBrowser.Model.Devices;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Session;
@@ -11,63 +16,65 @@ namespace MediaBrowser.Controller.Devices
{
public interface IDeviceManager
{
+ event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
+
/// <summary>
- /// Occurs when [camera image uploaded].
+ /// Creates a new device.
/// </summary>
- event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
+ /// <param name="device">The device to create.</param>
+ /// <returns>A <see cref="Task{Device}"/> representing the creation of the device.</returns>
+ Task<Device> CreateDevice(Device device);
/// <summary>
/// Saves the capabilities.
/// </summary>
- /// <param name="reportedId">The reported identifier.</param>
+ /// <param name="deviceId">The device id.</param>
/// <param name="capabilities">The capabilities.</param>
- /// <returns>Task.</returns>
- void SaveCapabilities(string reportedId, ClientCapabilities capabilities);
+ void SaveCapabilities(string deviceId, ClientCapabilities capabilities);
/// <summary>
/// Gets the capabilities.
/// </summary>
- /// <param name="reportedId">The reported identifier.</param>
+ /// <param name="deviceId">The device id.</param>
/// <returns>ClientCapabilities.</returns>
- ClientCapabilities GetCapabilities(string reportedId);
+ ClientCapabilities GetCapabilities(string deviceId);
/// <summary>
/// Gets the device information.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>DeviceInfo.</returns>
- DeviceInfo GetDevice(string id);
+ Task<DeviceInfo> GetDevice(string id);
/// <summary>
- /// Gets the devices.
+ /// Gets devices based on the provided query.
/// </summary>
- /// <param name="query">The query.</param>
- /// <returns>IEnumerable&lt;DeviceInfo&gt;.</returns>
- QueryResult<DeviceInfo> GetDevices(DeviceQuery query);
+ /// <param name="query">The device query.</param>
+ /// <returns>A <see cref="Task{QueryResult}"/> representing the retrieval of the devices.</returns>
+ Task<QueryResult<Device>> GetDevices(DeviceQuery query);
- /// <summary>
- /// Gets the upload history.
- /// </summary>
- /// <param name="deviceId">The device identifier.</param>
- /// <returns>ContentUploadHistory.</returns>
- ContentUploadHistory GetCameraUploadHistory(string deviceId);
+ Task<QueryResult<DeviceInfo>> GetDeviceInfos(DeviceQuery query);
/// <summary>
- /// Accepts the upload.
+ /// Gets the devices.
/// </summary>
- /// <param name="deviceId">The device identifier.</param>
- /// <param name="stream">The stream.</param>
- /// <param name="file">The file.</param>
- /// <returns>Task.</returns>
- Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file);
+ /// <param name="userId">The user's id, or <c>null</c>.</param>
+ /// <param name="supportsSync">A value indicating whether the device supports sync, or <c>null</c>.</param>
+ /// <returns>IEnumerable&lt;DeviceInfo&gt;.</returns>
+ Task<QueryResult<DeviceInfo>> GetDevicesForUser(Guid? userId, bool? supportsSync);
+
+ Task DeleteDevice(Device device);
/// <summary>
/// Determines whether this instance [can access device] the specified user identifier.
/// </summary>
+ /// <param name="user">The user to test.</param>
+ /// <param name="deviceId">The device id to test.</param>
+ /// <returns>Whether the user can access the device.</returns>
bool CanAccessDevice(User user, string deviceId);
- void UpdateDeviceOptions(string deviceId, DeviceOptions options);
- DeviceOptions GetDeviceOptions(string deviceId);
- event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
+ Task UpdateDeviceOptions(string deviceId, string deviceName);
+
+ Task<DeviceOptions> GetDeviceOptions(string deviceId);
}
}
diff --git a/MediaBrowser.Controller/Dlna/IDlnaManager.cs b/MediaBrowser.Controller/Dlna/IDlnaManager.cs
index a6ee7c505..06da5ea09 100644
--- a/MediaBrowser.Controller/Dlna/IDlnaManager.cs
+++ b/MediaBrowser.Controller/Dlna/IDlnaManager.cs
@@ -1,6 +1,9 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Dlna;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Dlna
{
@@ -17,7 +20,7 @@ namespace MediaBrowser.Controller.Dlna
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>DeviceProfile.</returns>
- DeviceProfile GetProfile(IDictionary<string, string> headers);
+ DeviceProfile? GetProfile(IHeaderDictionary headers);
/// <summary>
/// Gets the default profile.
@@ -34,8 +37,9 @@ namespace MediaBrowser.Controller.Dlna
/// <summary>
/// Updates the profile.
/// </summary>
+ /// <param name="profileId">The profile id.</param>
/// <param name="profile">The profile.</param>
- void UpdateProfile(DeviceProfile profile);
+ void UpdateProfile(string profileId, DeviceProfile profile);
/// <summary>
/// Deletes the profile.
@@ -48,14 +52,14 @@ namespace MediaBrowser.Controller.Dlna
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>DeviceProfile.</returns>
- DeviceProfile GetProfile(string id);
+ DeviceProfile? GetProfile(string id);
/// <summary>
/// Gets the profile.
/// </summary>
/// <param name="deviceInfo">The device information.</param>
/// <returns>DeviceProfile.</returns>
- DeviceProfile GetProfile(DeviceIdentification deviceInfo);
+ DeviceProfile? GetProfile(DeviceIdentification deviceInfo);
/// <summary>
/// Gets the server description XML.
@@ -64,13 +68,13 @@ namespace MediaBrowser.Controller.Dlna
/// <param name="serverUuId">The server uu identifier.</param>
/// <param name="serverAddress">The server address.</param>
/// <returns>System.String.</returns>
- string GetServerDescriptionXml(IDictionary<string, string> headers, string serverUuId, string serverAddress);
+ string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress);
/// <summary>
/// Gets the icon.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>DlnaIconResponse.</returns>
- ImageStream GetIcon(string filename);
+ ImageStream? GetIcon(string filename);
}
}
diff --git a/MediaBrowser.Controller/Drawing/IImageEncoder.cs b/MediaBrowser.Controller/Drawing/IImageEncoder.cs
index 4eaecd0a0..4e67cfee4 100644
--- a/MediaBrowser.Controller/Drawing/IImageEncoder.cs
+++ b/MediaBrowser.Controller/Drawing/IImageEncoder.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Drawing;
@@ -11,6 +13,7 @@ namespace MediaBrowser.Controller.Drawing
/// </summary>
/// <value>The supported input formats.</value>
IReadOnlyCollection<string> SupportedInputFormats { get; }
+
/// <summary>
/// Gets the supported output formats.
/// </summary>
@@ -18,19 +21,9 @@ namespace MediaBrowser.Controller.Drawing
IReadOnlyCollection<ImageFormat> SupportedOutputFormats { get; }
/// <summary>
- /// Encodes the image.
- /// </summary>
- string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat);
-
- /// <summary>
- /// Creates the image collage.
- /// </summary>
- /// <param name="options">The options.</param>
- void CreateImageCollage(ImageCollageOptions options);
- /// <summary>
- /// Gets the name.
+ /// Gets the display name for the encoder.
/// </summary>
- /// <value>The name.</value>
+ /// <value>The display name.</value>
string Name { get; }
/// <summary>
@@ -45,6 +38,41 @@ namespace MediaBrowser.Controller.Drawing
/// <value><c>true</c> if [supports image encoding]; otherwise, <c>false</c>.</value>
bool SupportsImageEncoding { get; }
+ /// <summary>
+ /// Get the dimensions of an image from the filesystem.
+ /// </summary>
+ /// <param name="path">The filepath of the image.</param>
+ /// <returns>The image dimensions.</returns>
ImageDimensions GetImageSize(string path);
+
+ /// <summary>
+ /// Gets the blurhash of an image.
+ /// </summary>
+ /// <param name="xComp">Amount of X components of DCT to take.</param>
+ /// <param name="yComp">Amount of Y components of DCT to take.</param>
+ /// <param name="path">The filepath of the image.</param>
+ /// <returns>The blurhash.</returns>
+ string GetImageBlurHash(int xComp, int yComp, string path);
+
+ /// <summary>
+ /// Encode an image.
+ /// </summary>
+ /// <param name="inputPath">Input path of image.</param>
+ /// <param name="dateModified">Date modified.</param>
+ /// <param name="outputPath">Output path of image.</param>
+ /// <param name="autoOrient">Auto-orient image.</param>
+ /// <param name="orientation">Desired orientation of image.</param>
+ /// <param name="quality">Quality of encoded image.</param>
+ /// <param name="options">Image processing options.</param>
+ /// <param name="outputFormat">Image format of output.</param>
+ /// <returns>Path of encoded image.</returns>
+ string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat);
+
+ /// <summary>
+ /// Create an image collage.
+ /// </summary>
+ /// <param name="options">The options to use when creating the collage.</param>
+ /// <param name="libraryName">Optional. </param>
+ void CreateImageCollage(ImageCollageOptions options, string? libraryName);
}
}
diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs
index a11e2186f..7ca0e851b 100644
--- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs
+++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs
@@ -1,16 +1,18 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Drawing
{
/// <summary>
- /// Interface IImageProcessor
+ /// Interface IImageProcessor.
/// </summary>
public interface IImageProcessor
{
@@ -21,16 +23,16 @@ namespace MediaBrowser.Controller.Drawing
IReadOnlyCollection<string> SupportedInputFormats { get; }
/// <summary>
- /// Gets the image enhancers.
+ /// Gets a value indicating whether [supports image collage creation].
/// </summary>
- /// <value>The image enhancers.</value>
- IImageEnhancer[] ImageEnhancers { get; }
+ /// <value><c>true</c> if [supports image collage creation]; otherwise, <c>false</c>.</value>
+ bool SupportsImageCollageCreation { get; }
/// <summary>
/// Gets the dimensions of the image.
/// </summary>
/// <param name="path">Path to the image file.</param>
- /// <returns>ImageDimensions</returns>
+ /// <returns>ImageDimensions.</returns>
ImageDimensions GetImageDimensions(string path);
/// <summary>
@@ -38,31 +40,15 @@ namespace MediaBrowser.Controller.Drawing
/// </summary>
/// <param name="item">The base item.</param>
/// <param name="info">The information.</param>
- /// <returns>ImageDimensions</returns>
+ /// <returns>ImageDimensions.</returns>
ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info);
/// <summary>
- /// Gets the dimensions of the image.
+ /// Gets the blurhash of the image.
/// </summary>
- /// <param name="item">The base item.</param>
- /// <param name="info">The information.</param>
- /// <param name="updateItem">Whether or not the item info should be updated.</param>
- /// <returns>ImageDimensions</returns>
- ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem);
-
- /// <summary>
- /// Adds the parts.
- /// </summary>
- /// <param name="enhancers">The enhancers.</param>
- void AddParts(IEnumerable<IImageEnhancer> enhancers);
-
- /// <summary>
- /// Gets the supported enhancers.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <returns>IEnumerable{IImageEnhancer}.</returns>
- IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType);
+ /// <param name="path">Path to the image file.</param>
+ /// <returns>BlurHash.</returns>
+ string GetImageBlurHash(string path);
/// <summary>
/// Gets the image cache tag.
@@ -71,16 +57,10 @@ namespace MediaBrowser.Controller.Drawing
/// <param name="image">The image.</param>
/// <returns>Guid.</returns>
string GetImageCacheTag(BaseItem item, ItemImageInfo image);
- string GetImageCacheTag(BaseItem item, ChapterInfo info);
- /// <summary>
- /// Gets the image cache tag.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="image">The image.</param>
- /// <param name="imageEnhancers">The image enhancers.</param>
- /// <returns>Guid.</returns>
- string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers);
+ string GetImageCacheTag(BaseItem item, ChapterInfo chapter);
+
+ string? GetImageCacheTag(User user);
/// <summary>
/// Processes the image.
@@ -95,36 +75,20 @@ namespace MediaBrowser.Controller.Drawing
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task.</returns>
- Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options);
-
- /// <summary>
- /// Gets the enhanced image.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <returns>Task{System.String}.</returns>
- Task<string> GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex);
+ Task<(string path, string? mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options);
/// <summary>
/// Gets the supported image output formats.
/// </summary>
- /// <returns>IReadOnlyCollection{ImageOutput}.</returns>
+ /// <returns><see cref="IReadOnlyCollection{ImageOutput}" />.</returns>
IReadOnlyCollection<ImageFormat> GetSupportedImageOutputFormats();
/// <summary>
/// Creates the image collage.
/// </summary>
/// <param name="options">The options.</param>
- void CreateImageCollage(ImageCollageOptions options);
-
- /// <summary>
- /// Gets a value indicating whether [supports image collage creation].
- /// </summary>
- /// <value><c>true</c> if [supports image collage creation]; otherwise, <c>false</c>.</value>
- bool SupportsImageCollageCreation { get; }
-
- IImageEncoder ImageEncoder { get; set; }
+ /// <param name="libraryName">The library name to draw onto the collage.</param>
+ void CreateImageCollage(ImageCollageOptions options, string? libraryName);
bool SupportsTransparency(string path);
}
diff --git a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs
index 3f762fad0..e9c88ffb5 100644
--- a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs
+++ b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs
@@ -1,3 +1,9 @@
+#nullable disable
+
+using System.Collections.Generic;
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Drawing
{
public class ImageCollageOptions
@@ -6,17 +12,20 @@ namespace MediaBrowser.Controller.Drawing
/// Gets or sets the input paths.
/// </summary>
/// <value>The input paths.</value>
- public string[] InputPaths { get; set; }
+ public IReadOnlyList<string> InputPaths { get; set; }
+
/// <summary>
/// Gets or sets the output path.
/// </summary>
/// <value>The output path.</value>
public string OutputPath { get; set; }
+
/// <summary>
/// Gets or sets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get; set; }
+
/// <summary>
/// Gets or sets the height.
/// </summary>
diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs
index 432cf8042..9ef92bc98 100644
--- a/MediaBrowser.Controller/Drawing/ImageHelper.cs
+++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs
@@ -1,73 +1,17 @@
-using System;
-using MediaBrowser.Controller.Entities;
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Drawing
{
public static class ImageHelper
{
- public static ImageDimensions GetNewImageSize(ImageProcessingOptions options, ImageDimensions? originalImageSize)
- {
- if (originalImageSize.HasValue)
- {
- // Determine the output size based on incoming parameters
- var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width ?? 0, options.Height ?? 0, options.MaxWidth ?? 0, options.MaxHeight ?? 0);
-
- return newSize;
- }
- return GetSizeEstimate(options);
- }
-
- public static IImageProcessor ImageProcessor { get; set; }
-
- private static ImageDimensions GetSizeEstimate(ImageProcessingOptions options)
- {
- if (options.Width.HasValue && options.Height.HasValue)
- {
- return new ImageDimensions(options.Width.Value, options.Height.Value);
- }
-
- double aspect = GetEstimatedAspectRatio(options.Image.Type, options.Item);
-
- int? width = options.Width ?? options.MaxWidth;
-
- if (width.HasValue)
- {
- int heightValue = Convert.ToInt32((double)width.Value / aspect);
- return new ImageDimensions(width.Value, heightValue);
- }
-
- var height = options.Height ?? options.MaxHeight ?? 200;
- int widthValue = Convert.ToInt32(aspect * height);
- return new ImageDimensions(widthValue, height);
- }
-
- private static double GetEstimatedAspectRatio(ImageType type, BaseItem item)
+ public static ImageDimensions GetNewImageSize(ImageProcessingOptions options, ImageDimensions originalImageSize)
{
- switch (type)
- {
- case ImageType.Art:
- case ImageType.Backdrop:
- case ImageType.Chapter:
- case ImageType.Screenshot:
- case ImageType.Thumb:
- return 1.78;
- case ImageType.Banner:
- return 5.4;
- case ImageType.Box:
- case ImageType.BoxRear:
- case ImageType.Disc:
- case ImageType.Menu:
- return 1;
- case ImageType.Logo:
- return 2.58;
- case ImageType.Primary:
- double defaultPrimaryImageAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
- return defaultPrimaryImageAspectRatio > 0 ? defaultPrimaryImageAspectRatio : 2.0 / 3;
- default:
- return 1;
- }
+ // Determine the output size based on incoming parameters
+ var newSize = DrawingUtils.Resize(originalImageSize, options.Width ?? 0, options.Height ?? 0, options.MaxWidth ?? 0, options.MaxHeight ?? 0);
+ newSize = DrawingUtils.ResizeFill(newSize, options.FillWidth, options.FillHeight);
+ return newSize;
}
}
}
diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs
index db432f500..11e663301 100644
--- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs
+++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
namespace MediaBrowser.Controller.Drawing
@@ -15,14 +19,13 @@ namespace MediaBrowser.Controller.Drawing
}
public Guid ItemId { get; set; }
+
public BaseItem Item { get; set; }
public ItemImageInfo Image { get; set; }
public int ImageIndex { get; set; }
- public bool CropWhiteSpace { get; set; }
-
public int? Width { get; set; }
public int? Height { get; set; }
@@ -31,21 +34,26 @@ namespace MediaBrowser.Controller.Drawing
public int? MaxHeight { get; set; }
- public int Quality { get; set; }
+ public int? FillWidth { get; set; }
- public IImageEnhancer[] Enhancers { get; set; }
+ public int? FillHeight { get; set; }
- public ImageFormat[] SupportedOutputFormats { get; set; }
+ public int Quality { get; set; }
+
+ public IReadOnlyCollection<ImageFormat> SupportedOutputFormats { get; set; }
public bool AddPlayedIndicator { get; set; }
public int? UnplayedCount { get; set; }
+
public int? Blur { get; set; }
public double PercentPlayed { get; set; }
public string BackgroundColor { get; set; }
+
public string ForegroundLayer { get; set; }
+
public bool RequiresAutoOrientation { get; set; }
private bool HasDefaultOptions(string originalImagePath)
@@ -75,19 +83,27 @@ namespace MediaBrowser.Controller.Drawing
{
return false;
}
+
if (Height.HasValue && !sizeValue.Height.Equals(Height.Value))
{
return false;
}
+
if (MaxWidth.HasValue && sizeValue.Width > MaxWidth.Value)
{
return false;
}
+
if (MaxHeight.HasValue && sizeValue.Height > MaxHeight.Value)
{
return false;
}
+ if (sizeValue.Width > FillWidth || sizeValue.Height > FillHeight)
+ {
+ return false;
+ }
+
return true;
}
@@ -99,7 +115,6 @@ namespace MediaBrowser.Controller.Drawing
PercentPlayed.Equals(0) &&
!UnplayedCount.HasValue &&
!Blur.HasValue &&
- !CropWhiteSpace &&
string.IsNullOrEmpty(BackgroundColor) &&
string.IsNullOrEmpty(ForegroundLayer);
}
diff --git a/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs b/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs
index df9050de5..b036425ab 100644
--- a/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs
+++ b/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
diff --git a/MediaBrowser.Controller/Drawing/ImageStream.cs b/MediaBrowser.Controller/Drawing/ImageStream.cs
index 74ac24ec9..f4c305799 100644
--- a/MediaBrowser.Controller/Drawing/ImageStream.cs
+++ b/MediaBrowser.Controller/Drawing/ImageStream.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CA1711, CS1591
+
using System;
using System.IO;
using MediaBrowser.Model.Drawing;
@@ -6,11 +8,17 @@ namespace MediaBrowser.Controller.Drawing
{
public class ImageStream : IDisposable
{
+ public ImageStream(Stream stream)
+ {
+ Stream = stream;
+ }
+
/// <summary>
- /// Gets or sets the stream.
+ /// Gets the stream.
/// </summary>
/// <value>The stream.</value>
- public Stream Stream { get; set; }
+ public Stream Stream { get; }
+
/// <summary>
/// Gets or sets the format.
/// </summary>
@@ -19,9 +27,15 @@ namespace MediaBrowser.Controller.Drawing
public void Dispose()
{
- if (Stream != null)
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
{
- Stream.Dispose();
+ Stream?.Dispose();
}
}
}
diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs
index aa99f6b58..ecc833154 100644
--- a/MediaBrowser.Controller/Dto/DtoOptions.cs
+++ b/MediaBrowser.Controller/Dto/DtoOptions.cs
@@ -1,4 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
@@ -13,31 +18,15 @@ namespace MediaBrowser.Controller.Dto
ItemFields.RefreshState
};
- public ItemFields[] Fields { get; set; }
- public ImageType[] ImageTypes { get; set; }
- public int ImageTypeLimit { get; set; }
- public bool EnableImages { get; set; }
- public bool AddProgramRecordingInfo { get; set; }
- public bool EnableUserData { get; set; }
- public bool AddCurrentProgram { get; set; }
-
- public DtoOptions()
- : this(true)
- {
- }
-
- private static readonly ImageType[] AllImageTypes = Enum.GetNames(typeof(ImageType))
- .Select(i => (ImageType)Enum.Parse(typeof(ImageType), i, true))
- .ToArray();
+ private static readonly ImageType[] AllImageTypes = Enum.GetValues<ImageType>();
- private static readonly ItemFields[] AllItemFields = Enum.GetNames(typeof(ItemFields))
- .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
+ private static readonly ItemFields[] AllItemFields = Enum.GetValues<ItemFields>()
.Except(DefaultExcludedFields)
.ToArray();
- public bool ContainsField(ItemFields field)
+ public DtoOptions()
+ : this(true)
{
- return AllItemFields.Contains(field);
}
public DtoOptions(bool allFields)
@@ -47,18 +36,27 @@ namespace MediaBrowser.Controller.Dto
EnableUserData = true;
AddCurrentProgram = true;
- if (allFields)
- {
- Fields = AllItemFields;
- }
- else
- {
- Fields = new ItemFields[] { };
- }
-
+ Fields = allFields ? AllItemFields : Array.Empty<ItemFields>();
ImageTypes = AllImageTypes;
}
+ public IReadOnlyList<ItemFields> Fields { get; set; }
+
+ public IReadOnlyList<ImageType> ImageTypes { get; set; }
+
+ public int ImageTypeLimit { get; set; }
+
+ public bool EnableImages { get; set; }
+
+ public bool AddProgramRecordingInfo { get; set; }
+
+ public bool EnableUserData { get; set; }
+
+ public bool AddCurrentProgram { get; set; }
+
+ public bool ContainsField(ItemFields field)
+ => Fields.Contains(field);
+
public int GetImageLimit(ImageType type)
{
if (EnableImages && ImageTypes.Contains(type))
diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs
index df5ec5dd0..89aafc84f 100644
--- a/MediaBrowser.Controller/Dto/IDtoService.cs
+++ b/MediaBrowser.Controller/Dto/IDtoService.cs
@@ -1,30 +1,19 @@
+#nullable disable
+#pragma warning disable CA1002
+
using System.Collections.Generic;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.Dto
{
/// <summary>
- /// Interface IDtoService
+ /// Interface IDtoService.
/// </summary>
public interface IDtoService
{
/// <summary>
- /// Gets the dto id.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
- string GetDtoId(BaseItem item);
-
- /// <summary>
- /// Attaches the primary image aspect ratio.
- /// </summary>
- /// <param name="dto">The dto.</param>
- /// <param name="item">The item.</param>
- void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item);
-
- /// <summary>
/// Gets the primary image aspect ratio.
/// </summary>
/// <param name="item">The item.</param>
@@ -35,15 +24,6 @@ namespace MediaBrowser.Controller.Dto
/// Gets the base item dto.
/// </summary>
/// <param name="item">The item.</param>
- /// <param name="fields">The fields.</param>
- /// <param name="user">The user.</param>
- /// <param name="owner">The owner.</param>
- BaseItemDto GetBaseItemDto(BaseItem item, ItemFields[] fields, User user = null, BaseItem owner = null);
-
- /// <summary>
- /// Gets the base item dto.
- /// </summary>
- /// <param name="item">The item.</param>
/// <param name="options">The options.</param>
/// <param name="user">The user.</param>
/// <param name="owner">The owner.</param>
@@ -57,13 +37,17 @@ namespace MediaBrowser.Controller.Dto
/// <param name="options">The options.</param>
/// <param name="user">The user.</param>
/// <param name="owner">The owner.</param>
- BaseItemDto[] GetBaseItemDtos(BaseItem[] items, DtoOptions options, User user = null, BaseItem owner = null);
-
- BaseItemDto[] GetBaseItemDtos(List<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null);
+ /// <returns>The <see cref="IReadOnlyList{T}"/> of <see cref="BaseItemDto"/>.</returns>
+ IReadOnlyList<BaseItemDto> GetBaseItemDtos(IReadOnlyList<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null);
/// <summary>
/// Gets the item by name dto.
/// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="options">The dto options.</param>
+ /// <param name="taggedItems">The list of tagged items.</param>
+ /// <param name="user">The user.</param>
+ /// <returns>The item dto.</returns>
BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null);
}
}
diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs
index 054df21e5..9589f5245 100644
--- a/MediaBrowser.Controller/Entities/AggregateFolder.cs
+++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs
@@ -1,43 +1,40 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
/// Specialized folder that can have items added to it's children by external entities.
- /// Used for our RootFolder so plug-ins can add items.
+ /// Used for our RootFolder so plugins can add items.
/// </summary>
public class AggregateFolder : Folder
{
- public AggregateFolder()
- {
- PhysicalLocationsList = Array.Empty<string>();
- }
-
- [IgnoreDataMember]
- public override bool IsPhysicalRoot => true;
-
- public override bool CanDelete()
- {
- return false;
- }
-
- [IgnoreDataMember]
- public override bool SupportsPlayedStatus => false;
+ private readonly object _childIdsLock = new object();
/// <summary>
- /// The _virtual children
+ /// The _virtual children.
/// </summary>
private readonly ConcurrentBag<BaseItem> _virtualChildren = new ConcurrentBag<BaseItem>();
+ private bool _requiresRefresh;
+ private Guid[] _childrenIds = null;
+
+ public AggregateFolder()
+ {
+ PhysicalLocationsList = Array.Empty<string>();
+ }
/// <summary>
/// Gets the virtual children.
@@ -45,18 +42,27 @@ namespace MediaBrowser.Controller.Entities
/// <value>The virtual children.</value>
public ConcurrentBag<BaseItem> VirtualChildren => _virtualChildren;
- [IgnoreDataMember]
+ [JsonIgnore]
+ public override bool IsPhysicalRoot => true;
+
+ [JsonIgnore]
+ public override bool SupportsPlayedStatus => false;
+
+ [JsonIgnore]
public override string[] PhysicalLocations => PhysicalLocationsList;
public string[] PhysicalLocationsList { get; set; }
+ public override bool CanDelete()
+ {
+ return false;
+ }
+
protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
{
return CreateResolveArgs(directoryService, true).FileSystemChildren;
}
- private Guid[] _childrenIds = null;
- private readonly object _childIdsLock = new object();
protected override List<BaseItem> LoadChildren()
{
lock (_childIdsLock)
@@ -80,7 +86,6 @@ namespace MediaBrowser.Controller.Entities
}
}
- private bool _requiresRefresh;
public override bool RequiresRefresh()
{
var changed = base.RequiresRefresh() || _requiresRefresh;
@@ -89,7 +94,7 @@ namespace MediaBrowser.Controller.Entities
{
var locations = PhysicalLocations;
- var newLocations = CreateResolveArgs(new DirectoryService(Logger, FileSystem), false).PhysicalLocations;
+ var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations;
if (!locations.SequenceEqual(newLocations))
{
@@ -100,11 +105,11 @@ namespace MediaBrowser.Controller.Entities
return changed;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
ClearCache();
- var changed = base.BeforeMetadataRefresh(replaceAllMetdata) || _requiresRefresh;
+ var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh;
_requiresRefresh = false;
return changed;
}
@@ -117,8 +122,7 @@ namespace MediaBrowser.Controller.Entities
var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
{
- FileInfo = FileSystem.GetDirectoryInfo(path),
- Path = path
+ FileInfo = FileSystem.GetDirectoryInfo(path)
};
// Gather child folder and files
@@ -150,11 +154,11 @@ namespace MediaBrowser.Controller.Entities
return base.GetNonCachedChildren(directoryService).Concat(_virtualChildren);
}
- protected override async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected override async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
ClearCache();
- await base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService)
+ await base.ValidateChildrenInternal(progress, recursive, refreshChildMetadata, refreshOptions, directoryService, cancellationToken)
.ConfigureAwait(false);
ClearCache();
@@ -164,7 +168,7 @@ namespace MediaBrowser.Controller.Entities
/// Adds the virtual child.
/// </summary>
/// <param name="child">The child.</param>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if child is null.</exception>
public void AddVirtualChild(BaseItem child)
{
if (child == null)
@@ -180,7 +184,7 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
/// <param name="id">The id.</param>
/// <returns>BaseItem.</returns>
- /// <exception cref="ArgumentNullException">id</exception>
+ /// <exception cref="ArgumentNullException">The id is empty.</exception>
public BaseItem FindVirtualChild(Guid id)
{
if (id.Equals(Guid.Empty))
@@ -195,6 +199,7 @@ namespace MediaBrowser.Controller.Entities
return child;
}
}
+
return null;
}
}
diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs
index 13a6fe44a..536668e50 100644
--- a/MediaBrowser.Controller/Entities/Audio/Audio.cs
+++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs
@@ -1,16 +1,22 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA1724, CA1826, CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities.Audio
{
/// <summary>
- /// Class Audio
+ /// Class Audio.
/// </summary>
public class Audio : BaseItem,
IHasAlbumArtist,
@@ -19,105 +25,79 @@ namespace MediaBrowser.Controller.Entities.Audio
IHasLookupInfo<SongInfo>,
IHasMediaSources
{
- /// <summary>
- /// Gets or sets the artist.
- /// </summary>
- /// <value>The artist.</value>
- [IgnoreDataMember]
- public string[] Artists { get; set; }
-
- [IgnoreDataMember]
- public string[] AlbumArtists { get; set; }
-
public Audio()
{
Artists = Array.Empty<string>();
AlbumArtists = Array.Empty<string>();
}
- public override double GetDefaultPrimaryImageAspectRatio()
- {
- return 1;
- }
+ /// <inheritdoc />
+ [JsonIgnore]
+ public IReadOnlyList<string> Artists { get; set; }
+
+ /// <inheritdoc />
+ [JsonIgnore]
+ public IReadOnlyList<string> AlbumArtists { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => true;
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
+ [JsonIgnore]
+ public override bool SupportsPeople => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
protected override bool SupportsOwnedItems => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override Folder LatestItemsIndexContainer => AlbumEntity;
- public override bool CanDownload()
- {
- return IsFileProtocol;
- }
-
- [IgnoreDataMember]
- public string[] AllArtists
- {
- get
- {
- var list = new string[AlbumArtists.Length + Artists.Length];
-
- var index = 0;
- foreach (var artist in AlbumArtists)
- {
- list[index] = artist;
- index++;
- }
- foreach (var artist in Artists)
- {
- list[index] = artist;
- index++;
- }
-
- return list;
-
- }
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public MusicAlbum AlbumEntity => FindParent<MusicAlbum>();
/// <summary>
/// Gets the type of the media.
/// </summary>
/// <value>The type of the media.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public override string MediaType => Model.Entities.MediaType.Audio;
+ public override double GetDefaultPrimaryImageAspectRatio()
+ {
+ return 1;
+ }
+
+ public override bool CanDownload()
+ {
+ return IsFileProtocol;
+ }
+
/// <summary>
/// Creates the name of the sort.
/// </summary>
/// <returns>System.String.</returns>
protected override string CreateSortName()
{
- return (ParentIndexNumber != null ? ParentIndexNumber.Value.ToString("0000 - ") : "")
- + (IndexNumber != null ? IndexNumber.Value.ToString("0000 - ") : "") + Name;
+ return (ParentIndexNumber != null ? ParentIndexNumber.Value.ToString("0000 - ", CultureInfo.InvariantCulture) : string.Empty)
+ + (IndexNumber != null ? IndexNumber.Value.ToString("0000 - ", CultureInfo.InvariantCulture) : string.Empty) + Name;
}
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
- var songKey = IndexNumber.HasValue ? IndexNumber.Value.ToString("0000") : string.Empty;
-
+ var songKey = IndexNumber.HasValue ? IndexNumber.Value.ToString("0000", CultureInfo.InvariantCulture) : string.Empty;
if (ParentIndexNumber.HasValue)
{
- songKey = ParentIndexNumber.Value.ToString("0000") + "-" + songKey;
+ songKey = ParentIndexNumber.Value.ToString("0000", CultureInfo.InvariantCulture) + "-" + songKey;
}
+
songKey += Name;
if (!string.IsNullOrEmpty(Album))
@@ -125,7 +105,7 @@ namespace MediaBrowser.Controller.Entities.Audio
songKey = Album + "-" + songKey;
}
- var albumArtist = AlbumArtists.Length == 0 ? null : AlbumArtists[0];
+ var albumArtist = AlbumArtists.FirstOrDefault();
if (!string.IsNullOrEmpty(albumArtist))
{
songKey = albumArtist + "-" + songKey;
@@ -142,6 +122,7 @@ namespace MediaBrowser.Controller.Entities.Audio
{
return UnratedItem.Music;
}
+
return base.GetBlockUnratedType();
}
diff --git a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs
index a269b3486..1625c748a 100644
--- a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs
+++ b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs
@@ -1,14 +1,33 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Controller.Library;
+
namespace MediaBrowser.Controller.Entities.Audio
{
public interface IHasAlbumArtist
{
- string[] AlbumArtists { get; set; }
+ IReadOnlyList<string> AlbumArtists { get; set; }
}
public interface IHasArtist
{
- string[] AllArtists { get; }
+ /// <summary>
+ /// Gets or sets the artists.
+ /// </summary>
+ /// <value>The artists.</value>
+ IReadOnlyList<string> Artists { get; set; }
+ }
- string[] Artists { get; set; }
+ public static class Extentions
+ {
+ public static IEnumerable<string> GetAllArtists<T>(this T item)
+ where T : IHasArtist, IHasAlbumArtist
+ {
+ return item.AlbumArtists.Concat(item.Artists).DistinctNames();
+ }
}
}
diff --git a/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs b/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs
index 5ae056050..c2dae5a2d 100644
--- a/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs
+++ b/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
namespace MediaBrowser.Controller.Entities.Audio
{
public interface IHasMusicGenres
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
index 5b2939b75..03d1f3304 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
@@ -1,48 +1,74 @@
+#nullable disable
+
+#pragma warning disable CA1721, CA1826, CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
+using MetadataProvider = MediaBrowser.Model.Entities.MetadataProvider;
namespace MediaBrowser.Controller.Entities.Audio
{
/// <summary>
- /// Class MusicAlbum
+ /// Class MusicAlbum.
/// </summary>
public class MusicAlbum : Folder, IHasAlbumArtist, IHasArtist, IHasMusicGenres, IHasLookupInfo<AlbumInfo>, IMetadataContainer
{
- public string[] AlbumArtists { get; set; }
- public string[] Artists { get; set; }
-
public MusicAlbum()
{
Artists = Array.Empty<string>();
AlbumArtists = Array.Empty<string>();
}
- [IgnoreDataMember]
+ /// <inheritdoc />
+ public IReadOnlyList<string> AlbumArtists { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<string> Artists { get; set; }
+
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public MusicArtist MusicArtist => GetMusicArtist(new DtoOptions(true));
+ [JsonIgnore]
+ public override bool SupportsPlayedStatus => false;
+
+ [JsonIgnore]
+ public override bool SupportsCumulativeRunTimeTicks => true;
+
+ [JsonIgnore]
+ public string AlbumArtist => AlbumArtists.FirstOrDefault();
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
+ /// <summary>
+ /// Gets the tracks.
+ /// </summary>
+ /// <value>The tracks.</value>
+ [JsonIgnore]
+ public IEnumerable<Audio> Tracks => GetRecursiveChildren(i => i is Audio).Cast<Audio>();
+
public MusicArtist GetMusicArtist(DtoOptions options)
{
var parents = GetParents();
foreach (var parent in parents)
{
- var artist = parent as MusicArtist;
- if (artist != null)
+ if (parent is MusicArtist artist)
{
return artist;
}
@@ -53,51 +79,10 @@ namespace MediaBrowser.Controller.Entities.Audio
{
return LibraryManager.GetArtist(name, options);
}
- return null;
- }
-
- [IgnoreDataMember]
- public override bool SupportsPlayedStatus => false;
- [IgnoreDataMember]
- public override bool SupportsCumulativeRunTimeTicks => true;
-
- [IgnoreDataMember]
- public string[] AllArtists
- {
- get
- {
- var list = new string[AlbumArtists.Length + Artists.Length];
-
- var index = 0;
- foreach (var artist in AlbumArtists)
- {
- list[index] = artist;
- index++;
- }
- foreach (var artist in Artists)
- {
- list[index] = artist;
- index++;
- }
-
- return list;
- }
+ return null;
}
- [IgnoreDataMember]
- public string AlbumArtist => AlbumArtists.Length == 0 ? null : AlbumArtists[0];
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
- /// <summary>
- /// Gets the tracks.
- /// </summary>
- /// <value>The tracks.</value>
- [IgnoreDataMember]
- public IEnumerable<Audio> Tracks => GetRecursiveChildren(i => i is Audio).Cast<Audio>();
-
protected override IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
{
return Tracks;
@@ -118,14 +103,14 @@ namespace MediaBrowser.Controller.Entities.Audio
list.Insert(0, albumArtist + "-" + Name);
}
- var id = this.GetProviderId(MetadataProviders.MusicBrainzAlbum);
+ var id = this.GetProviderId(MetadataProvider.MusicBrainzAlbum);
if (!string.IsNullOrEmpty(id))
{
list.Insert(0, "MusicAlbum-Musicbrainz-" + id);
}
- id = this.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
+ id = this.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup);
if (!string.IsNullOrEmpty(id))
{
@@ -135,9 +120,9 @@ namespace MediaBrowser.Controller.Entities.Audio
return list;
}
- protected override bool GetBlockUnratedValue(UserPolicy config)
+ protected override bool GetBlockUnratedValue(User user)
{
- return config.BlockUnratedItems.Contains(UnratedItem.Music);
+ return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music);
}
public override UnratedItem GetBlockUnratedType()
@@ -216,8 +201,7 @@ namespace MediaBrowser.Controller.Entities.Audio
private async Task RefreshArtists(MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
{
- var all = AllArtists;
- foreach (var i in all)
+ foreach (var i in this.GetAllArtists())
{
// This should not be necessary but we're seeing some cases of it
if (string.IsNullOrEmpty(i))
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
index 2d464bd32..f30f8ce7f 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
@@ -1,44 +1,79 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Extensions;
+using Diacritics.Extensions;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
using Microsoft.Extensions.Logging;
+using MetadataProvider = MediaBrowser.Model.Entities.MetadataProvider;
namespace MediaBrowser.Controller.Entities.Audio
{
/// <summary>
- /// Class MusicArtist
+ /// Class MusicArtist.
/// </summary>
public class MusicArtist : Folder, IItemByName, IHasMusicGenres, IHasDualAccess, IHasLookupInfo<ArtistInfo>
{
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsAccessedByName => ParentId.Equals(Guid.Empty);
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsFolder => !IsAccessedByName;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsCumulativeRunTimeTicks => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsDisplayedAsFolder => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => false;
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ [JsonIgnore]
+ public override IEnumerable<BaseItem> Children
+ {
+ get
+ {
+ if (IsAccessedByName)
+ {
+ return new List<BaseItem>();
+ }
+
+ return base.Children;
+ }
+ }
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
+ public static string GetPath(string name)
+ {
+ return GetPath(name, true);
+ }
+
public override double GetDefaultPrimaryImageAspectRatio()
{
return 1;
@@ -53,34 +88,16 @@ namespace MediaBrowser.Controller.Entities.Audio
{
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Audio).Name, typeof(MusicVideo).Name, typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio), nameof(MusicVideo), nameof(MusicAlbum) };
query.ArtistIds = new[] { Id };
}
return LibraryManager.GetItemList(query);
}
- [IgnoreDataMember]
- public override IEnumerable<BaseItem> Children
- {
- get
- {
- if (IsAccessedByName)
- {
- return new List<BaseItem>();
- }
-
- return base.Children;
- }
- }
-
public override int GetChildCount(User user)
{
- if (IsAccessedByName)
- {
- return 0;
- }
- return base.GetChildCount(user);
+ return IsAccessedByName ? 0 : base.GetChildCount(user);
}
public override bool IsSaveLocalMetadataEnabled()
@@ -93,7 +110,7 @@ namespace MediaBrowser.Controller.Entities.Audio
return base.IsSaveLocalMetadataEnabled();
}
- protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
if (IsAccessedByName)
{
@@ -101,7 +118,7 @@ namespace MediaBrowser.Controller.Entities.Audio
return Task.CompletedTask;
}
- return base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
+ return base.ValidateChildrenInternal(progress, recursive, refreshChildMetadata, refreshOptions, directoryService, cancellationToken);
}
public override List<string> GetUserDataKeys()
@@ -113,14 +130,6 @@ namespace MediaBrowser.Controller.Entities.Audio
}
/// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
- /// <summary>
/// Gets the user data key.
/// </summary>
/// <param name="item">The item.</param>
@@ -128,7 +137,7 @@ namespace MediaBrowser.Controller.Entities.Audio
private static List<string> GetUserDataKeys(MusicArtist item)
{
var list = new List<string>();
- var id = item.GetProviderId(MetadataProviders.MusicBrainzArtist);
+ var id = item.GetProviderId(MetadataProvider.MusicBrainzArtist);
if (!string.IsNullOrEmpty(id))
{
@@ -138,13 +147,15 @@ namespace MediaBrowser.Controller.Entities.Audio
list.Add("Artist-" + (item.Name ?? string.Empty).RemoveDiacritics());
return list;
}
+
public override string CreatePresentationUniqueKey()
{
return "Artist-" + (Name ?? string.Empty).RemoveDiacritics();
}
- protected override bool GetBlockUnratedValue(UserPolicy config)
+
+ protected override bool GetBlockUnratedValue(User user)
{
- return config.BlockUnratedItems.Contains(UnratedItem.Music);
+ return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music);
}
public override UnratedItem GetBlockUnratedType()
@@ -164,14 +175,6 @@ namespace MediaBrowser.Controller.Entities.Audio
return info;
}
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
- public static string GetPath(string name)
- {
- return GetPath(name, true);
- }
-
public static string GetPath(string name, bool normalizeName)
{
// Trim the period at the end because windows will have a hard time with that
@@ -198,15 +201,18 @@ namespace MediaBrowser.Controller.Entities.Audio
return true;
}
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true or false indicating if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata">Option to replace metadata.</param>
+ /// <returns>True if metadata changed.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (IsAccessedByName)
{
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
index d26aaf2bb..dc6fcc55a 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
@@ -1,16 +1,40 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Serialization;
+using System.Text.Json.Serialization;
+using Diacritics.Extensions;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.Audio
{
/// <summary>
- /// Class MusicGenre
+ /// Class MusicGenre.
/// </summary>
public class MusicGenre : BaseItem, IItemByName
{
+ [JsonIgnore]
+ public override bool SupportsAddingToPlaylist => true;
+
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
+ [JsonIgnore]
+ public override bool IsDisplayedAsFolder => true;
+
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
@@ -18,28 +42,12 @@ namespace MediaBrowser.Controller.Entities.Audio
list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics());
return list;
}
+
public override string CreatePresentationUniqueKey()
{
return GetUserDataKeys()[0];
}
- [IgnoreDataMember]
- public override bool SupportsAddingToPlaylist => true;
-
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
- [IgnoreDataMember]
- public override bool IsDisplayedAsFolder => true;
-
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
public override double GetDefaultPrimaryImageAspectRatio()
{
return 1;
@@ -55,13 +63,10 @@ namespace MediaBrowser.Controller.Entities.Audio
return true;
}
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
public IList<BaseItem> GetTaggedItems(InternalItemsQuery query)
{
query.GenreIds = new[] { Id };
- query.IncludeItemTypes = new[] { typeof(MusicVideo).Name, typeof(Audio).Name, typeof(MusicAlbum).Name, typeof(MusicArtist).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicVideo), nameof(Audio), nameof(MusicAlbum), nameof(MusicArtist) };
return LibraryManager.GetItemList(query);
}
@@ -94,15 +99,18 @@ namespace MediaBrowser.Controller.Entities.Audio
Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true or false indicating if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata">Option to replace metadata.</param>
+ /// <returns>True if metadata changed.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
diff --git a/MediaBrowser.Controller/Entities/AudioBook.cs b/MediaBrowser.Controller/Entities/AudioBook.cs
index 65c8a5fdd..782481fbc 100644
--- a/MediaBrowser.Controller/Entities/AudioBook.cs
+++ b/MediaBrowser.Controller/Entities/AudioBook.cs
@@ -1,33 +1,41 @@
+#nullable disable
+
+#pragma warning disable CA1724, CS1591
+
using System;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class AudioBook : Audio.Audio, IHasSeries, IHasLookupInfo<SongInfo>
{
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPositionTicksResume => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public string SeriesPresentationUniqueKey { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public string SeriesName { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public Guid SeriesId { get; set; }
public string FindSeriesSortName()
{
return SeriesName;
}
+
public string FindSeriesName()
{
return SeriesName;
}
+
public string FindSeriesPresentationUniqueKey()
{
return SeriesPresentationUniqueKey;
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index 43fee79a1..838a9f2f8 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -1,141 +1,223 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1401
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Diacritics.Extensions;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Extensions;
+using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class BaseItem
+ /// Class BaseItem.
/// </summary>
- public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>
+ public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
{
- protected static MetadataFields[] EmptyMetadataFieldsArray = Array.Empty<MetadataFields>();
- protected static MediaUrl[] EmptyMediaUrlArray = Array.Empty<MediaUrl>();
- protected static ItemImageInfo[] EmptyItemImageInfoArray = Array.Empty<ItemImageInfo>();
- public static readonly LinkedChild[] EmptyLinkedChildArray = Array.Empty<LinkedChild>();
+ /// <summary>
+ /// The trailer folder name.
+ /// </summary>
+ public const string TrailersFolderName = "trailers";
+ public const string ThemeSongsFolderName = "theme-music";
+ public const string ThemeSongFileName = "theme";
+ public const string ThemeVideosFolderName = "backdrops";
+
+ /// <summary>
+ /// The supported image extensions.
+ /// </summary>
+ public static readonly string[] SupportedImageExtensions
+ = new[] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
+
+ private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
+ {
+ ".nfo",
+ ".xml",
+ ".srt",
+ ".vtt",
+ ".sub",
+ ".idx",
+ ".txt",
+ ".edl",
+ ".bif",
+ ".smi",
+ ".ttml"
+ };
+
+ /// <summary>
+ /// Extra types that should be counted and displayed as "Special Features" in the UI.
+ /// </summary>
+ public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
+ {
+ Model.Entities.ExtraType.Unknown,
+ Model.Entities.ExtraType.BehindTheScenes,
+ Model.Entities.ExtraType.Clip,
+ Model.Entities.ExtraType.DeletedScene,
+ Model.Entities.ExtraType.Interview,
+ Model.Entities.ExtraType.Sample,
+ Model.Entities.ExtraType.Scene
+ };
+
+ public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
+
+ /// <summary>
+ /// The supported extra folder names and types. See <see cref="Emby.Naming.Common.NamingOptions" />.
+ /// </summary>
+ public static readonly Dictionary<string, ExtraType> AllExtrasTypesFolderNames = new Dictionary<string, ExtraType>(StringComparer.OrdinalIgnoreCase)
+ {
+ ["extras"] = MediaBrowser.Model.Entities.ExtraType.Unknown,
+ ["behind the scenes"] = MediaBrowser.Model.Entities.ExtraType.BehindTheScenes,
+ ["deleted scenes"] = MediaBrowser.Model.Entities.ExtraType.DeletedScene,
+ ["interviews"] = MediaBrowser.Model.Entities.ExtraType.Interview,
+ ["scenes"] = MediaBrowser.Model.Entities.ExtraType.Scene,
+ ["samples"] = MediaBrowser.Model.Entities.ExtraType.Sample,
+ ["shorts"] = MediaBrowser.Model.Entities.ExtraType.Clip,
+ ["featurettes"] = MediaBrowser.Model.Entities.ExtraType.Clip
+ };
+
+ private string _sortName;
+ private Guid[] _themeSongIds;
+ private Guid[] _themeVideoIds;
+
+ private string _forcedSortName;
+
+ private string _name;
+
+ public const char SlugChar = '-';
protected BaseItem()
{
- ThemeSongIds = Array.Empty<Guid>();
- ThemeVideoIds = Array.Empty<Guid>();
Tags = Array.Empty<string>();
Genres = Array.Empty<string>();
Studios = Array.Empty<string>();
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- LockedFields = EmptyMetadataFieldsArray;
- ImageInfos = EmptyItemImageInfoArray;
+ LockedFields = Array.Empty<MetadataField>();
+ ImageInfos = Array.Empty<ItemImageInfo>();
ProductionLocations = Array.Empty<string>();
RemoteTrailers = Array.Empty<MediaUrl>();
ExtraIds = Array.Empty<Guid>();
}
- public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
- public static char SlugChar = '-';
+ [JsonIgnore]
+ public Guid[] ThemeSongIds
+ {
+ get
+ {
+ return _themeSongIds ??= GetExtras()
+ .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeSong)
+ .Select(song => song.Id)
+ .ToArray();
+ }
- /// <summary>
- /// The supported image extensions
- /// </summary>
- public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
+ private set
+ {
+ _themeSongIds = value;
+ }
+ }
- /// <summary>
- /// The trailer folder name
- /// </summary>
- public static string TrailerFolderName = "trailers";
- public static string ThemeSongsFolderName = "theme-music";
- public static string ThemeSongFilename = "theme";
- public static string ThemeVideosFolderName = "backdrops";
+ [JsonIgnore]
+ public Guid[] ThemeVideoIds
+ {
+ get
+ {
+ return _themeVideoIds ??= GetExtras()
+ .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeVideo)
+ .Select(song => song.Id)
+ .ToArray();
+ }
- [IgnoreDataMember]
- public Guid[] ThemeSongIds { get; set; }
- [IgnoreDataMember]
- public Guid[] ThemeVideoIds { get; set; }
+ private set
+ {
+ _themeVideoIds = value;
+ }
+ }
- [IgnoreDataMember]
+ [JsonIgnore]
public string PreferredMetadataCountryCode { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public string PreferredMetadataLanguage { get; set; }
public long? Size { get; set; }
+
public string Container { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string Tagline { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual ItemImageInfo[] ImageInfos { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsVirtualItem { get; set; }
/// <summary>
/// Gets or sets the album.
/// </summary>
/// <value>The album.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string Album { get; set; }
/// <summary>
/// Gets or sets the channel identifier.
/// </summary>
/// <value>The channel identifier.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public Guid ChannelId { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsAddingToPlaylist => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool AlwaysScanInternalMetadataPath => false;
/// <summary>
- /// Gets a value indicating whether this instance is in mixed folder.
+ /// Gets or sets a value indicating whether this instance is in mixed folder.
/// </summary>
/// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsInMixedFolder { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsPlayedStatus => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsPositionTicksResume => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsRemoteImageDownloading => true;
- private string _name;
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string Name
{
get => _name;
@@ -148,43 +230,44 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
- [IgnoreDataMember]
+ [JsonIgnore]
public int? TotalBitrate { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public ExtraType? ExtraType { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
- [IgnoreDataMember]
+ [JsonIgnore]
public string OriginalTitle { get; set; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public Guid Id { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public Guid OwnerId { get; set; }
/// <summary>
/// Gets or sets the audio.
/// </summary>
/// <value>The audio.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public ProgramAudio? Audio { get; set; }
/// <summary>
- /// Return the id that should be used to key display prefs for this item.
+ /// Gets the id that should be used to key display prefs for this item.
/// Default is based on the type for everything except actual generic folders.
/// </summary>
/// <value>The display prefs id.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual Guid DisplayPreferencesId
{
get
@@ -198,10 +281,10 @@ namespace MediaBrowser.Controller.Entities
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string Path { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual SourceType SourceType
{
get
@@ -216,10 +299,10 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
/// </summary>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string ContainingFolderPath
{
get
@@ -237,47 +320,44 @@ namespace MediaBrowser.Controller.Entities
/// Gets or sets the name of the service.
/// </summary>
/// <value>The name of the service.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string ServiceName { get; set; }
/// <summary>
- /// If this content came from an external service, the id of the content on that service
+ /// Gets or sets the external id.
/// </summary>
- [IgnoreDataMember]
+ /// <remarks>
+ /// If this content came from an external service, the id of the content on that service.
+ /// </remarks>
+ [JsonIgnore]
public string ExternalId { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string ExternalSeriesId { get; set; }
/// <summary>
/// Gets or sets the etag.
/// </summary>
/// <value>The etag.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string ExternalEtag { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool IsHidden => false;
- public BaseItem GetOwner()
- {
- var ownerId = OwnerId;
- return ownerId.Equals(Guid.Empty) ? null : LibraryManager.GetItemById(ownerId);
- }
-
/// <summary>
- /// Gets or sets the type of the location.
+ /// Gets the type of the location.
/// </summary>
/// <value>The type of the location.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual LocationType LocationType
{
get
{
- //if (IsOffline)
- //{
+ // if (IsOffline)
+ // {
// return LocationType.Offline;
- //}
+ // }
var path = Path;
if (string.IsNullOrEmpty(path))
@@ -294,7 +374,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public MediaProtocol? PathProtocol
{
get
@@ -310,20 +390,13 @@ namespace MediaBrowser.Controller.Entities
}
}
- public bool IsPathProtocol(MediaProtocol protocol)
- {
- var current = PathProtocol;
-
- return current.HasValue && current.Value == protocol;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File);
- [IgnoreDataMember]
+ [JsonIgnore]
public bool HasPathProtocol => PathProtocol.HasValue;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsLocalMetadata
{
get
@@ -337,7 +410,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string FileNameWithoutExtension
{
get
@@ -351,452 +424,165 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool EnableAlphaNumericSorting => true;
- private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
- {
- var list = new List<Tuple<StringBuilder, bool>>();
-
- int thisMarker = 0;
-
- while (thisMarker < s1.Length)
- {
- if (thisMarker >= s1.Length)
- {
- break;
- }
- char thisCh = s1[thisMarker];
+ public virtual bool IsHD => Height >= 720;
- var thisChunk = new StringBuilder();
+ public bool IsShortcut { get; set; }
- while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
- {
- thisChunk.Append(thisCh);
- thisMarker++;
+ public string ShortcutPath { get; set; }
- if (thisMarker < s1.Length)
- {
- thisCh = s1[thisMarker];
- }
- }
+ public int Width { get; set; }
- var isNumeric = thisChunk.Length > 0 && char.IsDigit(thisChunk[0]);
- list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
- }
+ public int Height { get; set; }
- return list;
- }
+ public Guid[] ExtraIds { get; set; }
/// <summary>
- /// This is just a helper for convenience
+ /// Gets the primary image path.
/// </summary>
+ /// <remarks>
+ /// This is just a helper for convenience.
+ /// </remarks>
/// <value>The primary image path.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
- public bool IsMetadataFetcherEnabled(LibraryOptions libraryOptions, string name)
- {
- if (SourceType == SourceType.Channel)
- {
- // hack alert
- return !EnableMediaSourceDisplay;
- }
-
- var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
- if (typeOptions != null)
- {
- return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
- }
-
- if (!libraryOptions.EnableInternetProviders)
- {
- return false;
- }
-
- var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
-
- return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
- }
-
- public bool IsImageFetcherEnabled(LibraryOptions libraryOptions, string name)
- {
- if (this is Channel)
- {
- // hack alert
- return true;
- }
- if (SourceType == SourceType.Channel)
- {
- // hack alert
- return !EnableMediaSourceDisplay;
- }
-
- var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
- if (typeOptions != null)
- {
- return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
- }
-
- if (!libraryOptions.EnableInternetProviders)
- {
- return false;
- }
-
- var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
-
- return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
- }
-
- public virtual bool CanDelete()
- {
- if (SourceType == SourceType.Channel)
- {
- return ChannelManager.CanDelete(this);
- }
-
- return IsFileProtocol;
- }
-
- public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
- {
- if (user.Policy.EnableContentDeletion)
- {
- return true;
- }
-
- var allowed = user.Policy.EnableContentDeletionFromFolders;
-
- if (SourceType == SourceType.Channel)
- {
- return allowed.Contains(ChannelId.ToString(""), StringComparer.OrdinalIgnoreCase);
- }
- else
- {
- var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
-
- foreach (var folder in collectionFolders)
- {
- if (allowed.Contains(folder.Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public bool CanDelete(User user, List<Folder> allCollectionFolders)
- {
- return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
- }
-
- public bool CanDelete(User user)
- {
- var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
-
- return CanDelete(user, allCollectionFolders);
- }
-
- public virtual bool CanDownload()
- {
- return false;
- }
-
- public virtual bool IsAuthorizedToDownload(User user)
- {
- return user.Policy.EnableContentDownloading;
- }
-
- public bool CanDownload(User user)
- {
- return CanDownload() && IsAuthorizedToDownload(user);
- }
-
/// <summary>
/// Gets or sets the date created.
/// </summary>
/// <value>The date created.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime DateCreated { get; set; }
/// <summary>
/// Gets or sets the date modified.
/// </summary>
/// <value>The date modified.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime DateModified { get; set; }
- [IgnoreDataMember]
public DateTime DateLastSaved { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime DateLastRefreshed { get; set; }
- /// <summary>
- /// The logger
- /// </summary>
- public static ILogger Logger { get; set; }
- public static ILibraryManager LibraryManager { get; set; }
- public static IServerConfigurationManager ConfigurationManager { get; set; }
- public static IProviderManager ProviderManager { get; set; }
- public static ILocalizationManager LocalizationManager { get; set; }
- public static IItemRepository ItemRepository { get; set; }
- public static IFileSystem FileSystem { get; set; }
- public static IUserDataManager UserDataManager { get; set; }
- public static IChannelManager ChannelManager { get; set; }
- public static IMediaSourceManager MediaSourceManager { get; set; }
-
- /// <summary>
- /// Returns a <see cref="string" /> that represents this instance.
- /// </summary>
- /// <returns>A <see cref="string" /> that represents this instance.</returns>
- public override string ToString()
- {
- return Name;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsLocked { get; set; }
/// <summary>
/// Gets or sets the locked fields.
/// </summary>
/// <value>The locked fields.</value>
- [IgnoreDataMember]
- public MetadataFields[] LockedFields { get; set; }
+ [JsonIgnore]
+ public MetadataField[] LockedFields { get; set; }
/// <summary>
/// Gets the type of the media.
/// </summary>
/// <value>The type of the media.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string MediaType => null;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string[] PhysicalLocations
{
get
{
if (!IsFileProtocol)
{
- return new string[] { };
+ return Array.Empty<string>();
}
return new[] { Path };
}
}
- private string _forcedSortName;
- /// <summary>
- /// Gets or sets the name of the forced sort.
- /// </summary>
- /// <value>The name of the forced sort.</value>
- [IgnoreDataMember]
- public string ForcedSortName
- {
- get => _forcedSortName;
- set { _forcedSortName = value; _sortName = null; }
- }
-
- private string _sortName;
- /// <summary>
- /// Gets the name of the sort.
- /// </summary>
- /// <value>The name of the sort.</value>
- [IgnoreDataMember]
- public string SortName
+ [JsonIgnore]
+ public bool EnableMediaSourceDisplay
{
get
{
- if (_sortName == null)
+ if (SourceType == SourceType.Channel)
{
- if (!string.IsNullOrEmpty(ForcedSortName))
- {
- // Need the ToLower because that's what CreateSortName does
- _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
- }
- else
- {
- _sortName = CreateSortName();
- }
+ return ChannelManager.EnableMediaSourceDisplay(this);
}
- return _sortName;
- }
- set => _sortName = value;
- }
-
- public string GetInternalMetadataPath()
- {
- var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
- return GetInternalMetadataPath(basePath);
- }
-
- protected virtual string GetInternalMetadataPath(string basePath)
- {
- if (SourceType == SourceType.Channel)
- {
- return System.IO.Path.Combine(basePath, "channels", ChannelId.ToString("N"), Id.ToString("N"));
+ return true;
}
-
- var idString = Id.ToString("N");
-
- basePath = System.IO.Path.Combine(basePath, "library");
-
- return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
}
+ [JsonIgnore]
+ public Guid ParentId { get; set; }
+
/// <summary>
- /// Creates the name of the sort.
+ /// Gets or sets the logger.
/// </summary>
- /// <returns>System.String.</returns>
- protected virtual string CreateSortName()
- {
- if (Name == null) return null; //some items may not have name filled in properly
-
- if (!EnableAlphaNumericSorting)
- {
- return Name.TrimStart();
- }
-
- var sortable = Name.Trim().ToLowerInvariant();
+ public static ILogger<BaseItem> Logger { get; set; }
- foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
- {
- sortable = sortable.Replace(removeChar, string.Empty);
- }
-
- foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
- {
- sortable = sortable.Replace(replaceChar, " ");
- }
-
- foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
- {
- // Remove from beginning if a space follows
- if (sortable.StartsWith(search + " "))
- {
- sortable = sortable.Remove(0, search.Length + 1);
- }
- // Remove from middle if surrounded by spaces
- sortable = sortable.Replace(" " + search + " ", " ");
-
- // Remove from end if followed by a space
- if (sortable.EndsWith(" " + search))
- {
- sortable = sortable.Remove(sortable.Length - (search.Length + 1));
- }
- }
-
- return ModifySortChunks(sortable);
- }
+ public static ILibraryManager LibraryManager { get; set; }
- private string ModifySortChunks(string name)
- {
- var chunks = GetSortChunks(name);
+ public static IServerConfigurationManager ConfigurationManager { get; set; }
- var builder = new StringBuilder();
+ public static IProviderManager ProviderManager { get; set; }
- foreach (var chunk in chunks)
- {
- var chunkBuilder = chunk.Item1;
+ public static ILocalizationManager LocalizationManager { get; set; }
- // This chunk is numeric
- if (chunk.Item2)
- {
- while (chunkBuilder.Length < 10)
- {
- chunkBuilder.Insert(0, '0');
- }
- }
+ public static IItemRepository ItemRepository { get; set; }
- builder.Append(chunkBuilder);
- }
- //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
- return builder.ToString().RemoveDiacritics();
- }
+ public static IFileSystem FileSystem { get; set; }
- [IgnoreDataMember]
- public bool EnableMediaSourceDisplay
- {
- get
- {
- if (SourceType == SourceType.Channel)
- {
- return ChannelManager.EnableMediaSourceDisplay(this);
- }
+ public static IUserDataManager UserDataManager { get; set; }
- return true;
- }
- }
+ public static IChannelManager ChannelManager { get; set; }
- [IgnoreDataMember]
- public Guid ParentId { get; set; }
+ public static IMediaSourceManager MediaSourceManager { get; set; }
/// <summary>
- /// Gets or sets the parent.
+ /// Gets or sets the name of the forced sort.
/// </summary>
- /// <value>The parent.</value>
- [IgnoreDataMember]
- public Folder Parent
+ /// <value>The name of the forced sort.</value>
+ [JsonIgnore]
+ public string ForcedSortName
{
- get => GetParent() as Folder;
+ get => _forcedSortName;
set
{
-
- }
- }
-
- public void SetParent(Folder parent)
- {
- ParentId = parent == null ? Guid.Empty : parent.Id;
- }
-
- public BaseItem GetParent()
- {
- var parentId = ParentId;
- if (!parentId.Equals(Guid.Empty))
- {
- return LibraryManager.GetItemById(parentId);
- }
-
- return null;
- }
-
- public IEnumerable<BaseItem> GetParents()
- {
- var parent = GetParent();
-
- while (parent != null)
- {
- yield return parent;
-
- parent = parent.GetParent();
+ _forcedSortName = value;
+ _sortName = null;
}
}
/// <summary>
- /// Finds a parent of a given type
+ /// Gets or sets the name of the sort.
/// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns>``0.</returns>
- public T FindParent<T>()
- where T : Folder
+ /// <value>The name of the sort.</value>
+ [JsonIgnore]
+ public string SortName
{
- foreach (var parent in GetParents())
+ get
{
- var item = parent as T;
- if (item != null)
+ if (_sortName == null)
{
- return item;
+ if (!string.IsNullOrEmpty(ForcedSortName))
+ {
+ // Need the ToLower because that's what CreateSortName does
+ _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
+ }
+ else
+ {
+ _sortName = CreateSortName();
+ }
}
+
+ return _sortName;
}
- return null;
+
+ set => _sortName = value;
}
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual Guid DisplayParentId
{
get
@@ -806,7 +592,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public BaseItem DisplayParent
{
get
@@ -816,126 +602,127 @@ namespace MediaBrowser.Controller.Entities
{
return null;
}
+
return LibraryManager.GetItemById(id);
}
}
/// <summary>
- /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
+ /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be first aired.
/// </summary>
/// <value>The premiere date.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime? PremiereDate { get; set; }
/// <summary>
/// Gets or sets the end date.
/// </summary>
/// <value>The end date.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime? EndDate { get; set; }
/// <summary>
/// Gets or sets the official rating.
/// </summary>
/// <value>The official rating.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string OfficialRating { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public int InheritedParentalRatingValue { get; set; }
/// <summary>
/// Gets or sets the critic rating.
/// </summary>
/// <value>The critic rating.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public float? CriticRating { get; set; }
/// <summary>
/// Gets or sets the custom rating.
/// </summary>
/// <value>The custom rating.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string CustomRating { get; set; }
/// <summary>
/// Gets or sets the overview.
/// </summary>
/// <value>The overview.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string Overview { get; set; }
/// <summary>
/// Gets or sets the studios.
/// </summary>
/// <value>The studios.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string[] Studios { get; set; }
/// <summary>
/// Gets or sets the genres.
/// </summary>
/// <value>The genres.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string[] Genres { get; set; }
/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>The tags.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string[] Tags { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string[] ProductionLocations { get; set; }
/// <summary>
/// Gets or sets the home page URL.
/// </summary>
/// <value>The home page URL.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string HomePageUrl { get; set; }
/// <summary>
/// Gets or sets the community rating.
/// </summary>
/// <value>The community rating.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public float? CommunityRating { get; set; }
/// <summary>
/// Gets or sets the run time ticks.
/// </summary>
/// <value>The run time ticks.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public long? RunTimeTicks { get; set; }
/// <summary>
/// Gets or sets the production year.
/// </summary>
/// <value>The production year.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public int? ProductionYear { get; set; }
/// <summary>
- /// If the item is part of a series, this is it's number in the series.
+ /// Gets or sets the index number. If the item is part of a series, this is it's number in the series.
/// This could be episode number, album track number, etc.
/// </summary>
/// <value>The index number.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public int? IndexNumber { get; set; }
/// <summary>
- /// For an episode this could be the season number, or for a song this could be the disc number.
+ /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this could be the disc number.
/// </summary>
/// <value>The parent index number.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public int? ParentIndexNumber { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool HasLocalAlternateVersions => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public string OfficialRatingForComparison
{
get
@@ -956,7 +743,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public string CustomRatingForComparison
{
get
@@ -978,21 +765,364 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
+ /// Gets or sets the provider ids.
+ /// </summary>
+ /// <value>The provider ids.</value>
+ [JsonIgnore]
+ public Dictionary<string, string> ProviderIds { get; set; }
+
+ [JsonIgnore]
+ public virtual Folder LatestItemsIndexContainer => null;
+
+ [JsonIgnore]
+ public string PresentationUniqueKey { get; set; }
+
+ [JsonIgnore]
+ public virtual bool EnableRememberingTrackSelections => true;
+
+ [JsonIgnore]
+ public virtual bool IsTopParent
+ {
+ get
+ {
+ if (this is BasePluginFolder || this is Channel)
+ {
+ return true;
+ }
+
+ if (this is IHasCollectionType view)
+ {
+ if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ }
+
+ if (GetParent() is AggregateFolder)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual bool SupportsAncestors => true;
+
+ [JsonIgnore]
+ public virtual bool StopRefreshIfLocalMetadataFound => true;
+
+ [JsonIgnore]
+ protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
+
+ [JsonIgnore]
+ public virtual bool SupportsPeople => false;
+
+ [JsonIgnore]
+ public virtual bool SupportsThemeMedia => false;
+
+ [JsonIgnore]
+ public virtual bool SupportsInheritedParentImages => false;
+
+ /// <summary>
+ /// Gets a value indicating whether this instance is folder.
+ /// </summary>
+ /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public virtual bool IsFolder => false;
+
+ [JsonIgnore]
+ public virtual bool IsDisplayedAsFolder => false;
+
+ /// <summary>
+ /// Gets or sets the remote trailers.
+ /// </summary>
+ /// <value>The remote trailers.</value>
+ public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
+
+ public virtual bool SupportsExternalTransfer => false;
+
+ public virtual double GetDefaultPrimaryImageAspectRatio()
+ {
+ return 0;
+ }
+
+ public virtual string CreatePresentationUniqueKey()
+ {
+ return Id.ToString("N", CultureInfo.InvariantCulture);
+ }
+
+ public bool IsPathProtocol(MediaProtocol protocol)
+ {
+ var current = PathProtocol;
+
+ return current.HasValue && current.Value == protocol;
+ }
+
+ private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
+ {
+ var list = new List<Tuple<StringBuilder, bool>>();
+
+ int thisMarker = 0;
+
+ while (thisMarker < s1.Length)
+ {
+ char thisCh = s1[thisMarker];
+
+ var thisChunk = new StringBuilder();
+ bool isNumeric = char.IsDigit(thisCh);
+
+ while (thisMarker < s1.Length && char.IsDigit(thisCh) == isNumeric)
+ {
+ thisChunk.Append(thisCh);
+ thisMarker++;
+
+ if (thisMarker < s1.Length)
+ {
+ thisCh = s1[thisMarker];
+ }
+ }
+
+ list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
+ }
+
+ return list;
+ }
+
+ public virtual bool CanDelete()
+ {
+ if (SourceType == SourceType.Channel)
+ {
+ return ChannelManager.CanDelete(this);
+ }
+
+ return IsFileProtocol;
+ }
+
+ public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
+ {
+ if (user.HasPermission(PermissionKind.EnableContentDeletion))
+ {
+ return true;
+ }
+
+ var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
+
+ if (SourceType == SourceType.Channel)
+ {
+ return allowed.Contains(ChannelId);
+ }
+ else
+ {
+ var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
+
+ foreach (var folder in collectionFolders)
+ {
+ if (allowed.Contains(folder.Id))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public BaseItem GetOwner()
+ {
+ var ownerId = OwnerId;
+ return ownerId.Equals(Guid.Empty) ? null : LibraryManager.GetItemById(ownerId);
+ }
+
+ public bool CanDelete(User user, List<Folder> allCollectionFolders)
+ {
+ return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
+ }
+
+ public bool CanDelete(User user)
+ {
+ var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
+
+ return CanDelete(user, allCollectionFolders);
+ }
+
+ public virtual bool CanDownload()
+ {
+ return false;
+ }
+
+ public virtual bool IsAuthorizedToDownload(User user)
+ {
+ return user.HasPermission(PermissionKind.EnableContentDownloading);
+ }
+
+ public bool CanDownload(User user)
+ {
+ return CanDownload() && IsAuthorizedToDownload(user);
+ }
+
+ /// <summary>
+ /// Returns a <see cref="string" /> that represents this instance.
+ /// </summary>
+ /// <returns>A <see cref="string" /> that represents this instance.</returns>
+ public override string ToString()
+ {
+ return Name;
+ }
+
+ public string GetInternalMetadataPath()
+ {
+ var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
+
+ return GetInternalMetadataPath(basePath);
+ }
+
+ protected virtual string GetInternalMetadataPath(string basePath)
+ {
+ if (SourceType == SourceType.Channel)
+ {
+ return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
+ }
+
+ ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
+
+ return System.IO.Path.Join(basePath, "library", idString.Slice(0, 2), idString);
+ }
+
+ /// <summary>
+ /// Creates the name of the sort.
+ /// </summary>
+ /// <returns>System.String.</returns>
+ protected virtual string CreateSortName()
+ {
+ if (Name == null)
+ {
+ return null; // some items may not have name filled in properly
+ }
+
+ if (!EnableAlphaNumericSorting)
+ {
+ return Name.TrimStart();
+ }
+
+ var sortable = Name.Trim().ToLowerInvariant();
+
+ foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
+ {
+ sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
+ }
+
+ foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
+ {
+ sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
+ }
+
+ foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
+ {
+ // Remove from beginning if a space follows
+ if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
+ {
+ sortable = sortable.Remove(0, search.Length + 1);
+ }
+
+ // Remove from middle if surrounded by spaces
+ sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
+
+ // Remove from end if followed by a space
+ if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
+ {
+ sortable = sortable.Remove(sortable.Length - (search.Length + 1));
+ }
+ }
+
+ return ModifySortChunks(sortable);
+ }
+
+ private string ModifySortChunks(string name)
+ {
+ var chunks = GetSortChunks(name);
+
+ var builder = new StringBuilder();
+
+ foreach (var chunk in chunks)
+ {
+ var chunkBuilder = chunk.Item1;
+
+ // This chunk is numeric
+ if (chunk.Item2)
+ {
+ while (chunkBuilder.Length < 10)
+ {
+ chunkBuilder.Insert(0, '0');
+ }
+ }
+
+ builder.Append(chunkBuilder);
+ }
+
+ // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
+ return builder.ToString().RemoveDiacritics();
+ }
+
+ public BaseItem GetParent()
+ {
+ var parentId = ParentId;
+ if (!parentId.Equals(Guid.Empty))
+ {
+ return LibraryManager.GetItemById(parentId);
+ }
+
+ return null;
+ }
+
+ public IEnumerable<BaseItem> GetParents()
+ {
+ var parent = GetParent();
+
+ while (parent != null)
+ {
+ yield return parent;
+
+ parent = parent.GetParent();
+ }
+ }
+
+ /// <summary>
+ /// Finds a parent of a given type.
+ /// </summary>
+ /// <typeparam name="T">Type of parent.</typeparam>
+ /// <returns>``0.</returns>
+ public T FindParent<T>()
+ where T : Folder
+ {
+ foreach (var parent in GetParents())
+ {
+ if (parent is T item)
+ {
+ return item;
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
/// Gets the play access.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>PlayAccess.</returns>
public PlayAccess GetPlayAccess(User user)
{
- if (!user.Policy.EnableMediaPlayback)
+ if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
{
return PlayAccess.None;
}
- //if (!user.IsParentalScheduleAllowed())
- //{
+ // if (!user.IsParentalScheduleAllowed())
+ // {
// return PlayAccess.None;
- //}
+ // }
return PlayAccess.Full;
}
@@ -1042,7 +1172,6 @@ namespace MediaBrowser.Controller.Entities
}
return 1;
-
}).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
.ThenByDescending(i =>
{
@@ -1069,9 +1198,10 @@ namespace MediaBrowser.Controller.Entities
var info = new MediaSourceInfo
{
- Id = item.Id.ToString("N"),
+ Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
Protocol = protocol ?? MediaProtocol.File,
MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
+ MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
Name = GetMediaSourceName(item),
Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
RunTimeTicks = item.RunTimeTicks,
@@ -1087,7 +1217,7 @@ namespace MediaBrowser.Controller.Entities
if (info.Protocol == MediaProtocol.File)
{
- info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N");
+ info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
var video = item as Video;
@@ -1192,11 +1322,11 @@ namespace MediaBrowser.Controller.Entities
{
if (video.IsoType.HasValue)
{
- if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
+ if (video.IsoType.Value == IsoType.BluRay)
{
terms.Add("Bluray");
}
- else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
+ else if (video.IsoType.Value == IsoType.Dvd)
{
terms.Add("DVD");
}
@@ -1208,7 +1338,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- return string.Join("/", terms.ToArray());
+ return string.Join('/', terms.ToArray());
}
/// <summary>
@@ -1224,8 +1354,7 @@ namespace MediaBrowser.Controller.Entities
// Support plex/xbmc convention
files.AddRange(fileSystemChildren
- .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
- );
+ .Where(i => !i.IsDirectory && System.IO.Path.GetFileNameWithoutExtension(i.FullName.AsSpan()).Equals(ThemeSongFileName, StringComparison.OrdinalIgnoreCase)));
return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
.OfType<Audio.Audio>()
@@ -1265,16 +1394,15 @@ namespace MediaBrowser.Controller.Entities
.Select(item =>
{
// Try to retrieve it from the db. If we don't find it, use the resolved version
- var dbItem = LibraryManager.GetItemById(item.Id) as Video;
- if (dbItem != null)
+ if (LibraryManager.GetItemById(item.Id) is Video dbItem)
{
item = dbItem;
}
else
{
// item is new
- item.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo;
+ item.ExtraType = Model.Entities.ExtraType.ThemeVideo;
}
return item;
@@ -1285,54 +1413,45 @@ namespace MediaBrowser.Controller.Entities
protected virtual BaseItem[] LoadExtras(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
{
- var files = fileSystemChildren.Where(i => i.IsDirectory)
- .SelectMany(i => FileSystem.GetFiles(i.FullName));
-
- return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
- .OfType<Video>()
- .Select(item =>
- {
- // Try to retrieve it from the db. If we don't find it, use the resolved version
- var dbItem = LibraryManager.GetItemById(item.Id) as Video;
-
- if (dbItem != null)
- {
- item = dbItem;
- }
- else
+ return fileSystemChildren
+ .Where(child => child.IsDirectory && AllExtrasTypesFolderNames.ContainsKey(child.Name))
+ .SelectMany(folder => LibraryManager
+ .ResolvePaths(FileSystem.GetFiles(folder.FullName), directoryService, null, new LibraryOptions())
+ .OfType<Video>()
+ .Select(video =>
{
- // item is new
- item.ExtraType = MediaBrowser.Model.Entities.ExtraType.Clip;
- }
-
- return item;
+ // Try to retrieve it from the db. If we don't find it, use the resolved version
+ if (LibraryManager.GetItemById(video.Id) is Video dbItem)
+ {
+ video = dbItem;
+ }
- // Sort them so that the list can be easily compared for changes
- }).OrderBy(i => i.Path).ToArray();
+ video.ExtraType = AllExtrasTypesFolderNames[folder.Name];
+ return video;
+ })
+ .OrderBy(video => video.Path)) // Sort them so that the list can be easily compared for changes
+ .ToArray();
}
-
public Task RefreshMetadata(CancellationToken cancellationToken)
{
- return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken);
+ return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
}
protected virtual void TriggerOnRefreshStart()
{
-
}
protected virtual void TriggerOnRefreshComplete()
{
-
}
/// <summary>
- /// Overrides the base implementation to refresh metadata for local trailers
+ /// Overrides the base implementation to refresh metadata for local trailers.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>true if a provider reports we changed</returns>
+ /// <returns>true if a provider reports we changed.</returns>
public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
{
TriggerOnRefreshStart();
@@ -1348,6 +1467,7 @@ namespace MediaBrowser.Controller.Entities
new List<FileSystemMetadata>();
var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
+ await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
if (ownedItemsChanged)
{
@@ -1377,23 +1497,55 @@ namespace MediaBrowser.Controller.Entities
}
}
- [IgnoreDataMember]
- protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
+ protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
+ {
+ if (!IsVisible(user))
+ {
+ return false;
+ }
- [IgnoreDataMember]
- public virtual bool SupportsPeople => false;
+ if (GetParents().Any(i => !i.IsVisible(user)))
+ {
+ return false;
+ }
- [IgnoreDataMember]
- public virtual bool SupportsThemeMedia => false;
+ if (checkFolders)
+ {
+ var topParent = GetParents().LastOrDefault() ?? this;
+
+ if (string.IsNullOrEmpty(topParent.Path))
+ {
+ return true;
+ }
+
+ var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
+
+ if (itemCollectionFolders.Count > 0)
+ {
+ var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
+ if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public void SetParent(Folder parent)
+ {
+ ParentId = parent == null ? Guid.Empty : parent.Id;
+ }
/// <summary>
/// Refreshes owned items such as trailers, theme videos, special features, etc.
/// Returns true or false indicating if changes were found.
/// </summary>
- /// <param name="options"></param>
- /// <param name="fileSystemChildren"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
+ /// <param name="options">The metadata refresh options.</param>
+ /// <param name="fileSystemChildren">The list of filesystem children.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
{
var themeSongsChanged = false;
@@ -1470,7 +1622,13 @@ namespace MediaBrowser.Controller.Entities
private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
{
- var newExtras = LoadExtras(fileSystemChildren, options.DirectoryService).Concat(LoadThemeVideos(fileSystemChildren, options.DirectoryService)).Concat(LoadThemeSongs(fileSystemChildren, options.DirectoryService));
+ var extras = LoadExtras(fileSystemChildren, options.DirectoryService);
+ var themeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
+ var themeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
+ var newExtras = new BaseItem[extras.Length + themeVideos.Length + themeSongs.Length];
+ extras.CopyTo(newExtras, 0);
+ themeVideos.CopyTo(newExtras, extras.Length);
+ themeSongs.CopyTo(newExtras, extras.Length + themeVideos.Length);
var newExtraIds = newExtras.Select(i => i.Id).ToArray();
@@ -1482,7 +1640,15 @@ namespace MediaBrowser.Controller.Entities
var tasks = newExtras.Select(i =>
{
- return RefreshMetadataForOwnedItem(i, true, new MetadataRefreshOptions(options), cancellationToken);
+ var subOptions = new MetadataRefreshOptions(options);
+ if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
+ {
+ i.OwnerId = ownerId;
+ i.ParentId = Guid.Empty;
+ subOptions.ForceSave = true;
+ }
+
+ return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
});
await Task.WhenAll(tasks).ConfigureAwait(false);
@@ -1523,7 +1689,8 @@ namespace MediaBrowser.Controller.Entities
await Task.WhenAll(tasks).ConfigureAwait(false);
- item.ThemeVideoIds = newThemeVideoIds;
+ // They are expected to be sorted by SortName
+ item.ThemeVideoIds = newThemeVideos.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
return themeVideosChanged;
}
@@ -1560,34 +1727,12 @@ namespace MediaBrowser.Controller.Entities
await Task.WhenAll(tasks).ConfigureAwait(false);
- item.ThemeSongIds = newThemeSongIds;
+ // They are expected to be sorted by SortName
+ item.ThemeSongIds = newThemeSongs.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
return themeSongsChanged;
}
- /// <summary>
- /// Gets or sets the provider ids.
- /// </summary>
- /// <value>The provider ids.</value>
- [IgnoreDataMember]
- public Dictionary<string, string> ProviderIds { get; set; }
-
- [IgnoreDataMember]
- public virtual Folder LatestItemsIndexContainer => null;
-
- public virtual double GetDefaultPrimaryImageAspectRatio()
- {
- return 0;
- }
-
- public virtual string CreatePresentationUniqueKey()
- {
- return Id.ToString("N");
- }
-
- [IgnoreDataMember]
- public string PresentationUniqueKey { get; set; }
-
public string GetPresentationUniqueKey()
{
return PresentationUniqueKey ?? CreatePresentationUniqueKey();
@@ -1715,11 +1860,11 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Determines if a given user has access to this item
+ /// Determines if a given user has access to this item.
/// </summary>
/// <param name="user">The user.</param>
/// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
+ /// <exception cref="ArgumentNullException">If user is null.</exception>
public bool IsParentalAllowed(User user)
{
if (user == null)
@@ -1732,7 +1877,7 @@ namespace MediaBrowser.Controller.Entities
return false;
}
- var maxAllowedRating = user.Policy.MaxParentalRating;
+ var maxAllowedRating = user.MaxParentalAgeRating;
if (maxAllowedRating == null)
{
@@ -1748,7 +1893,7 @@ namespace MediaBrowser.Controller.Entities
if (string.IsNullOrEmpty(rating))
{
- return !GetBlockUnratedValue(user.Policy);
+ return !GetBlockUnratedValue(user);
}
var value = LocalizationManager.GetRatingLevel(rating);
@@ -1756,7 +1901,7 @@ namespace MediaBrowser.Controller.Entities
// Could not determine the integer value
if (!value.HasValue)
{
- var isAllowed = !GetBlockUnratedValue(user.Policy);
+ var isAllowed = !GetBlockUnratedValue(user);
if (!isAllowed)
{
@@ -1818,8 +1963,7 @@ namespace MediaBrowser.Controller.Entities
private bool IsVisibleViaTags(User user)
{
- var policy = user.Policy;
- if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
+ if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
{
return false;
}
@@ -1845,22 +1989,18 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Gets the block unrated value.
/// </summary>
- /// <param name="config">The configuration.</param>
+ /// <param name="user">The configuration.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- protected virtual bool GetBlockUnratedValue(UserPolicy config)
+ protected virtual bool GetBlockUnratedValue(User user)
{
// Don't block plain folders that are unrated. Let the media underneath get blocked
// Special folders like series and albums will override this method.
- if (IsFolder)
- {
- return false;
- }
- if (this is IItemByName)
+ if (IsFolder || this is IItemByName)
{
return false;
}
- return config.BlockUnratedItems.Contains(GetBlockUnratedType());
+ return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType());
}
/// <summary>
@@ -1869,7 +2009,7 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
/// <param name="user">The user.</param>
/// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
public virtual bool IsVisible(User user)
{
if (user == null)
@@ -1890,58 +2030,9 @@ namespace MediaBrowser.Controller.Entities
return IsVisibleStandaloneInternal(user, true);
}
- [IgnoreDataMember]
- public virtual bool SupportsInheritedParentImages => false;
-
- protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
- {
- if (!IsVisible(user))
- {
- return false;
- }
-
- if (GetParents().Any(i => !i.IsVisible(user)))
- {
- return false;
- }
-
- if (checkFolders)
- {
- var topParent = GetParents().LastOrDefault() ?? this;
-
- if (string.IsNullOrEmpty(topParent.Path))
- {
- return true;
- }
-
- var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
-
- if (itemCollectionFolders.Count > 0)
- {
- var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
- if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Gets a value indicating whether this instance is folder.
- /// </summary>
- /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public virtual bool IsFolder => false;
-
- [IgnoreDataMember]
- public virtual bool IsDisplayedAsFolder => false;
-
public virtual string GetClientTypeName()
{
- if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
+ if (IsFolder && SourceType == SourceType.Channel && this is not Channel)
{
return "ChannelFolderItem";
}
@@ -1949,6 +2040,11 @@ namespace MediaBrowser.Controller.Entities
return GetType().Name;
}
+ public BaseItemKind GetBaseItemKind()
+ {
+ return Enum.Parse<BaseItemKind>(GetClientTypeName());
+ }
+
/// <summary>
/// Gets the linked child.
/// </summary>
@@ -2001,7 +2097,7 @@ namespace MediaBrowser.Controller.Entities
if (itemByPath == null)
{
- //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
+ Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
}
return itemByPath;
@@ -2013,7 +2109,7 @@ namespace MediaBrowser.Controller.Entities
if (item == null)
{
- //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
+ Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
}
return item;
@@ -2022,14 +2118,11 @@ namespace MediaBrowser.Controller.Entities
return null;
}
- [IgnoreDataMember]
- public virtual bool EnableRememberingTrackSelections => true;
-
/// <summary>
- /// Adds a studio to the item
+ /// Adds a studio to the item.
/// </summary>
/// <param name="name">The name.</param>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
public void AddStudio(string name)
{
if (string.IsNullOrEmpty(name))
@@ -2041,14 +2134,17 @@ namespace MediaBrowser.Controller.Entities
if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
{
- if (current.Length == 0)
+ int curLen = current.Length;
+ if (curLen == 0)
{
Studios = new[] { name };
}
else
{
- var list =
- Studios = current.Concat(new[] { name }).ToArray();
+ var newArr = new string[curLen + 1];
+ current.CopyTo(newArr, 0);
+ newArr[curLen] = name;
+ Studios = newArr;
}
}
}
@@ -2059,10 +2155,10 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Adds a genre to the item
+ /// Adds a genre to the item.
/// </summary>
/// <param name="name">The name.</param>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throwns if name is null.</exception>
public void AddGenre(string name)
{
if (string.IsNullOrEmpty(name))
@@ -2085,9 +2181,9 @@ namespace MediaBrowser.Controller.Entities
/// <param name="user">The user.</param>
/// <param name="datePlayed">The date played.</param>
/// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- public virtual void MarkPlayed(User user,
+ /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
+ public virtual void MarkPlayed(
+ User user,
DateTime? datePlayed,
bool resetPosition)
{
@@ -2122,8 +2218,7 @@ namespace MediaBrowser.Controller.Entities
/// Marks the unplayed.
/// </summary>
/// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
public virtual void MarkUnplayed(User user)
{
if (user == null)
@@ -2133,7 +2228,7 @@ namespace MediaBrowser.Controller.Entities
var data = UserDataManager.GetUserData(user, this);
- //I think it is okay to do this here.
+ // I think it is okay to do this here.
// if this is only called when a user is manually forcing something to un-played
// then it probably is what we want to do...
data.PlayCount = 0;
@@ -2147,22 +2242,18 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
/// </summary>
- /// <returns>Task.</returns>
public virtual void ChangedExternally()
{
- ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem))
- {
-
- }, RefreshPriority.High);
+ ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
}
/// <summary>
- /// Gets an image
+ /// Gets an image.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
+ /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
public bool HasImage(ImageType type, int imageIndex)
{
return GetImageInfo(type, imageIndex) != null;
@@ -2183,12 +2274,16 @@ namespace MediaBrowser.Controller.Entities
existingImage.DateModified = image.DateModified;
existingImage.Width = image.Width;
existingImage.Height = image.Height;
+ existingImage.BlurHash = image.BlurHash;
}
-
else
{
- var currentCount = ImageInfos.Length;
- ImageInfos = ImageInfos.Concat(new[] { image }).ToArray();
+ var current = ImageInfos;
+ var currentCount = current.Length;
+ var newArr = new ItemImageInfo[currentCount + 1];
+ current.CopyTo(newArr, 0);
+ newArr[currentCount] = image;
+ ImageInfos = newArr;
}
}
@@ -2223,8 +2318,8 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
/// <param name="type">The type.</param>
/// <param name="index">The index.</param>
- /// <returns>Task.</returns>
- public void DeleteImage(ImageType type, int index)
+ /// <returns>A task.</returns>
+ public async Task DeleteImageAsync(ImageType type, int index)
{
var info = GetImageInfo(type, index);
@@ -2242,7 +2337,7 @@ namespace MediaBrowser.Controller.Entities
FileSystem.DeleteFile(info.Path);
}
- UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
+ await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
}
public void RemoveImage(ItemImageInfo image)
@@ -2255,21 +2350,21 @@ namespace MediaBrowser.Controller.Entities
ImageInfos = ImageInfos.Except(deletedImages).ToArray();
}
- public virtual void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
- {
- LibraryManager.UpdateItem(this, GetParent(), updateReason, cancellationToken);
- }
+ public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
+ => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
/// <summary>
- /// Validates that images within the item are still on the file system
+ /// Validates that images within the item are still on the filesystem.
/// </summary>
+ /// <param name="directoryService">The directory service to use.</param>
+ /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
public bool ValidateImages(IDirectoryService directoryService)
{
var allFiles = ImageInfos
.Where(i => i.IsLocalFile)
.Select(i => System.IO.Path.GetDirectoryName(i.Path))
.Distinct(StringComparer.OrdinalIgnoreCase)
- .SelectMany(i => directoryService.GetFilePaths(i))
+ .SelectMany(path => directoryService.GetFilePaths(path))
.ToList();
var deletedImages = ImageInfos
@@ -2290,9 +2385,7 @@ namespace MediaBrowser.Controller.Entities
/// <param name="imageType">Type of the image.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <returns>System.String.</returns>
- /// <exception cref="InvalidOperationException">
- /// </exception>
- /// <exception cref="ArgumentNullException">item</exception>
+ /// <exception cref="ArgumentNullException">Item is null.</exception>
public string GetImagePath(ImageType imageType, int imageIndex)
=> GetImageInfo(imageType, imageIndex)?.Path;
@@ -2328,10 +2421,61 @@ namespace MediaBrowser.Controller.Entities
};
}
+ // Music albums usually don't have dedicated backdrops, so return one from the artist instead
+ if (GetType() == typeof(MusicAlbum) && imageType == ImageType.Backdrop)
+ {
+ var artist = FindParent<MusicArtist>();
+
+ if (artist != null)
+ {
+ return artist.GetImages(imageType).ElementAtOrDefault(imageIndex);
+ }
+ }
+
return GetImages(imageType)
.ElementAtOrDefault(imageIndex);
}
+ /// <summary>
+ /// Computes image index for given image or raises if no matching image found.
+ /// </summary>
+ /// <param name="image">Image to compute index for.</param>
+ /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
+ /// </exception>
+ /// <returns>Image index.</returns>
+ public int GetImageIndex(ItemImageInfo image)
+ {
+ if (image == null)
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
+
+ if (image.Type == ImageType.Chapter)
+ {
+ var chapters = ItemRepository.GetChapters(this);
+ for (var i = 0; i < chapters.Count; i++)
+ {
+ if (chapters[i].ImagePath == image.Path)
+ {
+ return i;
+ }
+ }
+
+ throw new ArgumentException("No chapter index found for image path", image.Path);
+ }
+
+ var images = GetImages(image.Type).ToArray();
+ for (var i = 0; i < images.Length; i++)
+ {
+ if (images[i].Path == image.Path)
+ {
+ return i;
+ }
+ }
+
+ throw new ArgumentException("No image index found for image path", image.Path);
+ }
+
public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
{
if (imageType == ImageType.Chapter)
@@ -2339,7 +2483,15 @@ namespace MediaBrowser.Controller.Entities
throw new ArgumentException("No image info for chapter images");
}
- return ImageInfos.Where(i => i.Type == imageType);
+ // Yield return is more performant than LINQ Where on an Array
+ for (var i = 0; i < ImageInfos.Length; i++)
+ {
+ var imageInfo = ImageInfos[i];
+ if (imageInfo.Type == imageType)
+ {
+ yield return imageInfo;
+ }
+ }
}
/// <summary>
@@ -2348,7 +2500,7 @@ namespace MediaBrowser.Controller.Entities
/// <param name="imageType">Type of the image.</param>
/// <param name="images">The images.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
+ /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
{
if (imageType == ImageType.Chapter)
@@ -2371,7 +2523,7 @@ namespace MediaBrowser.Controller.Entities
}
var existing = existingImages
- .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
+ .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
@@ -2402,8 +2554,7 @@ namespace MediaBrowser.Controller.Entities
var newImagePaths = images.Select(i => i.FullName).ToList();
var deleted = existingImages
- .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
- .ToList();
+ .FindAll(i => i.IsLocalFile && !newImagePaths.Contains(i.Path.AsSpan(), StringComparison.OrdinalIgnoreCase) && !File.Exists(i.Path));
if (deleted.Count > 0)
{
@@ -2430,12 +2581,13 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Gets the file system path to delete when the item is to be deleted
+ /// Gets the file system path to delete when the item is to be deleted.
/// </summary>
- /// <returns></returns>
+ /// <returns>The metadata for the deleted paths.</returns>
public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
{
- return new[] {
+ return new[]
+ {
new FileSystemMetadata
{
FullName = Path,
@@ -2452,10 +2604,8 @@ namespace MediaBrowser.Controller.Entities
}
var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
- var extensions = new List<string> { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" };
- extensions.AddRange(SupportedImageExtensions);
- return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), extensions.ToArray(), false, false)
+ return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
.Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
.ToList();
}
@@ -2465,11 +2615,11 @@ namespace MediaBrowser.Controller.Entities
return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
}
- public void SwapImages(ImageType type, int index1, int index2)
+ public Task SwapImagesAsync(ImageType type, int index1, int index2)
{
if (!AllowsMultipleImages(type))
{
- throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
+ throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots");
}
var info1 = GetImageInfo(type, index1);
@@ -2478,13 +2628,13 @@ namespace MediaBrowser.Controller.Entities
if (info1 == null || info2 == null)
{
// Nothing to do
- return;
+ return Task.CompletedTask;
}
if (!info1.IsLocalFile || !info2.IsLocalFile)
{
// TODO: Not supported yet
- return;
+ return Task.CompletedTask;
}
var path1 = info1.Path;
@@ -2501,7 +2651,7 @@ namespace MediaBrowser.Controller.Entities
info2.Width = 0;
info2.Height = 0;
- UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
+ return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
}
public virtual bool IsPlayed(User user)
@@ -2540,9 +2690,11 @@ namespace MediaBrowser.Controller.Entities
{
return new T
{
+ Path = Path,
MetadataCountryCode = GetPreferredMetadataCountryCode(),
MetadataLanguage = GetPreferredMetadataLanguage(),
Name = GetNameForMetadataLookup(),
+ OriginalTitle = OriginalTitle,
ProviderIds = ProviderIds,
IndexNumber = IndexNumber,
ParentIndexNumber = ParentIndexNumber,
@@ -2557,9 +2709,11 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true if changes were made.
/// </summary>
- public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
+ /// <returns>true if the item has change, else false.</returns>
+ public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
_sortName = null;
@@ -2617,36 +2771,43 @@ namespace MediaBrowser.Controller.Entities
newOptions.ForceSave = true;
ownedItem.Genres = item.Genres;
}
+
if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
{
newOptions.ForceSave = true;
ownedItem.Studios = item.Studios;
}
+
if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
{
newOptions.ForceSave = true;
ownedItem.ProductionLocations = item.ProductionLocations;
}
+
if (item.CommunityRating != ownedItem.CommunityRating)
{
ownedItem.CommunityRating = item.CommunityRating;
newOptions.ForceSave = true;
}
+
if (item.CriticRating != ownedItem.CriticRating)
{
ownedItem.CriticRating = item.CriticRating;
newOptions.ForceSave = true;
}
+
if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
{
ownedItem.Overview = item.Overview;
newOptions.ForceSave = true;
}
+
if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
{
ownedItem.OfficialRating = item.OfficialRating;
newOptions.ForceSave = true;
}
+
if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
{
ownedItem.CustomRating = item.CustomRating;
@@ -2674,13 +2835,13 @@ namespace MediaBrowser.Controller.Entities
newOptions.ForceSave = true;
}
- //var parentId = Id;
- //if (!video.IsOwnedItem || video.ParentId != parentId)
- //{
+ // var parentId = Id;
+ // if (!video.IsOwnedItem || video.ParentId != parentId)
+ // {
// video.IsOwnedItem = true;
// video.ParentId = parentId;
// newOptions.ForceSave = true;
- //}
+ // }
if (video == null)
{
@@ -2694,7 +2855,7 @@ namespace MediaBrowser.Controller.Entities
{
var list = GetEtagValues(user);
- return string.Join("|", list.ToArray()).GetMD5().ToString("N");
+ return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
protected virtual List<string> GetEtagValues(User user)
@@ -2717,50 +2878,9 @@ namespace MediaBrowser.Controller.Entities
return this;
}
- foreach (var parent in GetParents())
- {
- if (parent.IsTopParent)
- {
- return parent;
- }
- }
- return null;
+ return GetParents().FirstOrDefault(parent => parent.IsTopParent);
}
- [IgnoreDataMember]
- public virtual bool IsTopParent
- {
- get
- {
- if (this is BasePluginFolder || this is Channel)
- {
- return true;
- }
-
- var view = this as IHasCollectionType;
- if (view != null)
- {
- if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- if (GetParent() is AggregateFolder)
- {
- return true;
- }
-
- return false;
- }
- }
-
- [IgnoreDataMember]
- public virtual bool SupportsAncestors => true;
-
- [IgnoreDataMember]
- public virtual bool StopRefreshIfLocalMetadataFound => true;
-
public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
{
return new[] { Id };
@@ -2795,7 +2915,8 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Updates the official rating based on content and returns true or false indicating if it changed.
/// </summary>
- /// <returns></returns>
+ /// <param name="children">Media children.</param>
+ /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
public bool UpdateRatingToItems(IList<BaseItem> children)
{
var currentOfficialRating = OfficialRating;
@@ -2811,55 +2932,74 @@ namespace MediaBrowser.Controller.Entities
OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
- return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
+ return !string.Equals(
+ currentOfficialRating ?? string.Empty,
+ OfficialRating ?? string.Empty,
StringComparison.OrdinalIgnoreCase);
}
public IEnumerable<BaseItem> GetThemeSongs()
{
- return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeSong)).OrderBy(i => i.SortName);
+ return ThemeSongIds.Select(LibraryManager.GetItemById);
}
public IEnumerable<BaseItem> GetThemeVideos()
{
- return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
+ return ThemeVideoIds.Select(LibraryManager.GetItemById);
}
/// <summary>
- /// Gets or sets the remote trailers.
+ /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
/// </summary>
- /// <value>The remote trailers.</value>
- public MediaUrl[] RemoteTrailers { get; set; }
-
+ /// <returns>An enumerable containing the items.</returns>
public IEnumerable<BaseItem> GetExtras()
{
- return ExtraIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
+ return ExtraIds
+ .Select(LibraryManager.GetItemById)
+ .Where(i => i != null)
+ .OrderBy(i => i.SortName);
}
- public IEnumerable<BaseItem> GetExtras(ExtraType[] extraTypes)
+ /// <summary>
+ /// Get all extras with specific types that are associated with this item.
+ /// </summary>
+ /// <param name="extraTypes">The types of extras to retrieve.</param>
+ /// <returns>An enumerable containing the extras.</returns>
+ public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
{
- return ExtraIds.Select(LibraryManager.GetItemById).Where(i => i != null && extraTypes.Contains(i.ExtraType.Value)).OrderBy(i => i.SortName);
+ return ExtraIds
+ .Select(LibraryManager.GetItemById)
+ .Where(i => i != null)
+ .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
}
- public IEnumerable<BaseItem> GetDisplayExtras()
+ public IEnumerable<BaseItem> GetTrailers()
{
- return GetExtras(DisplayExtraTypes);
+ if (this is IHasTrailers)
+ {
+ return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
+ }
+ else
+ {
+ return Array.Empty<BaseItem>();
+ }
}
- public virtual bool IsHD => Height >= 720;
- public bool IsShortcut { get; set; }
- public string ShortcutPath { get; set; }
- public int Width { get; set; }
- public int Height { get; set; }
- public Guid[] ExtraIds { get; set; }
public virtual long GetRunTimeTicksForPlayState()
{
return RunTimeTicks ?? 0;
}
- // Possible types of extra videos
- public static ExtraType[] DisplayExtraTypes = new[] { Model.Entities.ExtraType.BehindTheScenes, Model.Entities.ExtraType.Clip, Model.Entities.ExtraType.DeletedScene, Model.Entities.ExtraType.Interview, Model.Entities.ExtraType.Sample, Model.Entities.ExtraType.Scene };
+ /// <inheritdoc />
+ public override bool Equals(object obj)
+ {
+ return obj is BaseItem baseItem && this.Equals(baseItem);
+ }
- public virtual bool SupportsExternalTransfer => false;
+ /// <inheritdoc />
+ public bool Equals(BaseItem other) => Equals(Id, other?.Id);
+
+ /// <inheritdoc />
+ public override int GetHashCode() => HashCode.Combine(Id);
}
}
diff --git a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
index 9c955a724..33870e2fb 100644
--- a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
+++ b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System;
using System.Linq;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
@@ -41,9 +44,10 @@ namespace MediaBrowser.Controller.Entities
/// <param name="file">The file.</param>
public static void SetImagePath(this BaseItem item, ImageType imageType, string file)
{
- if (file.StartsWith("http", System.StringComparison.OrdinalIgnoreCase))
+ if (file.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- item.SetImage(new ItemImageInfo
+ item.SetImage(
+ new ItemImageInfo
{
Path = file,
Type = imageType
@@ -60,40 +64,63 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
/// <param name="source">The source object.</param>
/// <param name="dest">The destination object.</param>
+ /// <typeparam name="T">Source type.</typeparam>
+ /// <typeparam name="TU">Destination type.</typeparam>
public static void DeepCopy<T, TU>(this T source, TU dest)
- where T : BaseItem
- where TU : BaseItem
+ where T : BaseItem
+ where TU : BaseItem
{
- var sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList();
- var destProps = typeof(TU).GetProperties()
- .Where(x => x.CanWrite)
- .ToList();
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (dest == null)
+ {
+ throw new ArgumentNullException(nameof(dest));
+ }
- foreach (var sourceProp in sourceProps)
+ var destProps = typeof(TU).GetProperties().Where(x => x.CanWrite).ToList();
+
+ foreach (var sourceProp in typeof(T).GetProperties())
{
- if (destProps.Any(x => x.Name == sourceProp.Name))
+ // We should be able to write to the property
+ // for both the source and destination type
+ // This is only false when the derived type hides the base member
+ // (which we shouldn't copy anyway)
+ if (!sourceProp.CanRead || !sourceProp.CanWrite)
{
- var p = destProps.First(x => x.Name == sourceProp.Name);
- p.SetValue(dest, sourceProp.GetValue(source, null), null);
+ continue;
}
- }
+ var v = sourceProp.GetValue(source);
+ if (v == null)
+ {
+ continue;
+ }
+ var p = destProps.Find(x => x.Name == sourceProp.Name);
+ if (p != null)
+ {
+ p.SetValue(dest, v);
+ }
+ }
}
/// <summary>
/// Copies all properties on newly created object. Skips properties that do not exist.
/// </summary>
/// <param name="source">The source object.</param>
+ /// <typeparam name="T">Source type.</typeparam>
+ /// <typeparam name="TU">Destination type.</typeparam>
+ /// <returns>Destination object.</returns>
public static TU DeepCopy<T, TU>(this T source)
- where T : BaseItem
- where TU : BaseItem, new()
+ where T : BaseItem
+ where TU : BaseItem, new()
{
var dest = new TU();
source.DeepCopy(dest);
return dest;
}
-
-
}
}
diff --git a/MediaBrowser.Controller/Entities/BasePluginFolder.cs b/MediaBrowser.Controller/Entities/BasePluginFolder.cs
index 8cdb9695c..272a37df1 100644
--- a/MediaBrowser.Controller/Entities/BasePluginFolder.cs
+++ b/MediaBrowser.Controller/Entities/BasePluginFolder.cs
@@ -1,4 +1,8 @@
-using MediaBrowser.Model.Serialization;
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Text.Json.Serialization;
namespace MediaBrowser.Controller.Entities
{
@@ -8,9 +12,15 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
public abstract class BasePluginFolder : Folder, ICollectionFolder
{
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual string CollectionType => null;
+ [JsonIgnore]
+ public override bool SupportsInheritedParentImages => false;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
public override bool CanDelete()
{
return false;
@@ -20,19 +30,5 @@ namespace MediaBrowser.Controller.Entities
{
return true;
}
-
- [IgnoreDataMember]
- public override bool SupportsInheritedParentImages => false;
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
- //public override double? GetDefaultPrimaryImageAspectRatio()
- //{
- // double value = 16;
- // value /= 9;
-
- // return value;
- //}
}
}
diff --git a/MediaBrowser.Controller/Entities/Book.cs b/MediaBrowser.Controller/Entities/Book.cs
index 7a23d9a66..d75beb06d 100644
--- a/MediaBrowser.Controller/Entities/Book.cs
+++ b/MediaBrowser.Controller/Entities/Book.cs
@@ -1,31 +1,48 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class Book : BaseItem, IHasLookupInfo<BookInfo>, IHasSeries
{
- [IgnoreDataMember]
+ public Book()
+ {
+ this.RunTimeTicks = TimeSpan.TicksPerSecond;
+ }
+
+ [JsonIgnore]
public override string MediaType => Model.Entities.MediaType.Book;
- [IgnoreDataMember]
+ public override bool SupportsPlayedStatus => true;
+
+ public override bool SupportsPositionTicksResume => true;
+
+ [JsonIgnore]
public string SeriesPresentationUniqueKey { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public string SeriesName { get; set; }
- [IgnoreDataMember]
+
+ [JsonIgnore]
public Guid SeriesId { get; set; }
public string FindSeriesSortName()
{
return SeriesName;
}
+
public string FindSeriesName()
{
return SeriesName;
}
+
public string FindSeriesPresentationUniqueKey()
{
return SeriesPresentationUniqueKey;
@@ -36,11 +53,13 @@ namespace MediaBrowser.Controller.Entities
return SeriesId;
}
+ /// <inheritdoc />
public override bool CanDownload()
{
return IsFileProtocol;
}
+ /// <inheritdoc />
public override UnratedItem GetBlockUnratedType()
{
return UnratedItem.Book;
diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs
index 275052d48..7dc7f774d 100644
--- a/MediaBrowser.Controller/Entities/CollectionFolder.cs
+++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs
@@ -1,15 +1,20 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
-
+using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
@@ -19,34 +24,70 @@ namespace MediaBrowser.Controller.Entities
{
/// <summary>
/// Specialized Folder class that points to a subset of the physical folders in the system.
- /// It is created from the user-specific folders within the system root
+ /// It is created from the user-specific folders within the system root.
/// </summary>
public class CollectionFolder : Folder, ICollectionFolder
{
- public static IXmlSerializer XmlSerializer { get; set; }
- public static IJsonSerializer JsonSerializer { get; set; }
- public static IServerApplicationHost ApplicationHost { get; set; }
+ private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private static readonly Dictionary<string, LibraryOptions> _libraryOptions = new Dictionary<string, LibraryOptions>();
+ private bool _requiresRefresh;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionFolder"/> class.
+ /// </summary>
public CollectionFolder()
{
PhysicalLocationsList = Array.Empty<string>();
PhysicalFolderIds = Array.Empty<Guid>();
}
- [IgnoreDataMember]
+ /// <summary>
+ /// Gets the display preferences id.
+ /// </summary>
+ /// <remarks>
+ /// Allow different display preferences for each collection folder.
+ /// </remarks>
+ /// <value>The display prefs id.</value>
+ [JsonIgnore]
+ public override Guid DisplayPreferencesId => Id;
+
+ [JsonIgnore]
+ public override string[] PhysicalLocations => PhysicalLocationsList;
+
+ public string[] PhysicalLocationsList { get; set; }
+
+ public Guid[] PhysicalFolderIds { get; set; }
+
+ public static IXmlSerializer XmlSerializer { get; set; }
+
+ public static IServerApplicationHost ApplicationHost { get; set; }
+
+ [JsonIgnore]
public override bool SupportsPlayedStatus => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
+ public string CollectionType { get; set; }
+
+ /// <summary>
+ /// Gets the item's children.
+ /// </summary>
+ /// <remarks>
+ /// Our children are actually just references to the ones in the physical root...
+ /// </remarks>
+ /// <value>The actual children.</value>
+ [JsonIgnore]
+ public override IEnumerable<BaseItem> Children => GetActualChildren();
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
public override bool CanDelete()
{
return false;
}
- public string CollectionType { get; set; }
-
- private static readonly Dictionary<string, LibraryOptions> LibraryOptions = new Dictionary<string, LibraryOptions>();
public LibraryOptions GetLibraryOptions()
{
return GetLibraryOptions(Path);
@@ -56,9 +97,7 @@ namespace MediaBrowser.Controller.Entities
{
try
{
- var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
-
- if (result == null)
+ if (XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) is not LibraryOptions result)
{
return new LibraryOptions();
}
@@ -101,12 +140,12 @@ namespace MediaBrowser.Controller.Entities
public static LibraryOptions GetLibraryOptions(string path)
{
- lock (LibraryOptions)
+ lock (_libraryOptions)
{
- if (!LibraryOptions.TryGetValue(path, out var options))
+ if (!_libraryOptions.TryGetValue(path, out var options))
{
options = LoadLibraryOptions(path);
- LibraryOptions[path] = options;
+ _libraryOptions[path] = options;
}
return options;
@@ -115,11 +154,11 @@ namespace MediaBrowser.Controller.Entities
public static void SaveLibraryOptions(string path, LibraryOptions options)
{
- lock (LibraryOptions)
+ lock (_libraryOptions)
{
- LibraryOptions[path] = options;
+ _libraryOptions[path] = options;
- var clone = JsonSerializer.DeserializeFromString<LibraryOptions>(JsonSerializer.SerializeToString(options));
+ var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions);
foreach (var mediaPath in clone.PathInfos)
{
if (!string.IsNullOrEmpty(mediaPath.Path))
@@ -134,36 +173,22 @@ namespace MediaBrowser.Controller.Entities
public static void OnCollectionFolderChange()
{
- lock (LibraryOptions)
+ lock (_libraryOptions)
{
- LibraryOptions.Clear();
+ _libraryOptions.Clear();
}
}
- /// <summary>
- /// Allow different display preferences for each collection folder
- /// </summary>
- /// <value>The display prefs id.</value>
- [IgnoreDataMember]
- public override Guid DisplayPreferencesId => Id;
-
- [IgnoreDataMember]
- public override string[] PhysicalLocations => PhysicalLocationsList;
-
public override bool IsSaveLocalMetadataEnabled()
{
return true;
}
- public string[] PhysicalLocationsList { get; set; }
- public Guid[] PhysicalFolderIds { get; set; }
-
protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
{
return CreateResolveArgs(directoryService, true).FileSystemChildren;
}
- private bool _requiresRefresh;
public override bool RequiresRefresh()
{
var changed = base.RequiresRefresh() || _requiresRefresh;
@@ -172,7 +197,7 @@ namespace MediaBrowser.Controller.Entities
{
var locations = PhysicalLocations;
- var newLocations = CreateResolveArgs(new DirectoryService(Logger, FileSystem), false).PhysicalLocations;
+ var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations;
if (!locations.SequenceEqual(newLocations))
{
@@ -195,9 +220,9 @@ namespace MediaBrowser.Controller.Entities
return changed;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var changed = base.BeforeMetadataRefresh(replaceAllMetdata) || _requiresRefresh;
+ var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh;
_requiresRefresh = false;
return changed;
}
@@ -223,7 +248,7 @@ namespace MediaBrowser.Controller.Entities
return null;
}
- return (totalProgresses / foldersWithProgress);
+ return totalProgresses / foldersWithProgress;
}
protected override bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
@@ -266,7 +291,6 @@ namespace MediaBrowser.Controller.Entities
var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
{
FileInfo = FileSystem.GetDirectoryInfo(path),
- Path = path,
Parent = GetParent() as Folder,
CollectionType = CollectionType
};
@@ -293,27 +317,20 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
- /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
+ /// ***Currently does not contain logic to maintain items that are unavailable in the file system***.
/// </summary>
/// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="recursive">if set to <c>true</c> [recursive].</param>
/// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
/// <param name="refreshOptions">The refresh options.</param>
/// <param name="directoryService">The directory service.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
- /// <summary>
- /// Our children are actually just references to the ones in the physical root...
- /// </summary>
- /// <value>The actual children.</value>
- [IgnoreDataMember]
- public override IEnumerable<BaseItem> Children => GetActualChildren();
-
public IEnumerable<BaseItem> GetActualChildren()
{
return GetPhysicalFolders(true).SelectMany(c => c.Children);
@@ -350,9 +367,7 @@ namespace MediaBrowser.Controller.Entities
if (result.Count == 0)
{
- var folder = LibraryManager.FindByPath(path, true) as Folder;
-
- if (folder != null)
+ if (LibraryManager.FindByPath(path, true) is Folder folder)
{
result.Add(folder);
}
@@ -360,8 +375,5 @@ namespace MediaBrowser.Controller.Entities
return result;
}
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/DayOfWeekHelper.cs b/MediaBrowser.Controller/Entities/DayOfWeekHelper.cs
deleted file mode 100644
index 8a79e0783..000000000
--- a/MediaBrowser.Controller/Entities/DayOfWeekHelper.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Model.Configuration;
-
-namespace MediaBrowser.Controller.Entities
-{
- public static class DayOfWeekHelper
- {
- public static List<DayOfWeek> GetDaysOfWeek(DynamicDayOfWeek day)
- {
- return GetDaysOfWeek(new List<DynamicDayOfWeek> { day });
- }
-
- public static List<DayOfWeek> GetDaysOfWeek(List<DynamicDayOfWeek> days)
- {
- var list = new List<DayOfWeek>();
-
- if (days.Contains(DynamicDayOfWeek.Sunday) ||
- days.Contains(DynamicDayOfWeek.Weekend) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Sunday);
- }
-
- if (days.Contains(DynamicDayOfWeek.Saturday) ||
- days.Contains(DynamicDayOfWeek.Weekend) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Saturday);
- }
-
- if (days.Contains(DynamicDayOfWeek.Monday) ||
- days.Contains(DynamicDayOfWeek.Weekday) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Monday);
- }
-
- if (days.Contains(DynamicDayOfWeek.Tuesday) ||
- days.Contains(DynamicDayOfWeek.Weekday) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Tuesday
- );
- }
-
- if (days.Contains(DynamicDayOfWeek.Wednesday) ||
- days.Contains(DynamicDayOfWeek.Weekday) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Wednesday);
- }
-
- if (days.Contains(DynamicDayOfWeek.Thursday) ||
- days.Contains(DynamicDayOfWeek.Weekday) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Thursday);
- }
-
- if (days.Contains(DynamicDayOfWeek.Friday) ||
- days.Contains(DynamicDayOfWeek.Weekday) ||
- days.Contains(DynamicDayOfWeek.Everyday))
- {
- list.Add(DayOfWeek.Friday);
- }
-
- return list;
- }
- }
-}
diff --git a/MediaBrowser.Controller/Entities/Extensions.cs b/MediaBrowser.Controller/Entities/Extensions.cs
index f3bddd29c..9ce8eebe3 100644
--- a/MediaBrowser.Controller/Entities/Extensions.cs
+++ b/MediaBrowser.Controller/Entities/Extensions.cs
@@ -1,17 +1,22 @@
+#nullable disable
+
using System;
using System.Linq;
+using Jellyfin.Extensions;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Extensions
+ /// Class Extensions.
/// </summary>
public static class Extensions
{
/// <summary>
/// Adds the trailer URL.
/// </summary>
+ /// <param name="item">Media item.</param>
+ /// <param name="url">Trailer URL.</param>
public static void AddTrailerUrl(this BaseItem item, string url)
{
if (string.IsNullOrEmpty(url))
@@ -28,13 +33,17 @@ namespace MediaBrowser.Controller.Entities
Url = url
};
- if (item.RemoteTrailers.Length == 0)
+ if (item.RemoteTrailers.Count == 0)
{
item.RemoteTrailers = new[] { mediaUrl };
}
else
{
- item.RemoteTrailers = item.RemoteTrailers.Concat(new[] { mediaUrl }).ToArray();
+ var oldIds = item.RemoteTrailers;
+ var newIds = new MediaUrl[oldIds.Count + 1];
+ oldIds.CopyTo(newIds);
+ newIds[oldIds.Count] = mediaUrl;
+ item.RemoteTrailers = newIds;
}
}
}
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index 8bfadbee6..18b4ec3c6 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -1,9 +1,17 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA1721, CA1819, CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using System.Threading.Tasks.Dataflow;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Collections;
@@ -11,23 +19,29 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Folder
+ /// Class Folder.
/// </summary>
public class Folder : BaseItem
{
- public static IUserManager UserManager { get; set; }
+ public Folder()
+ {
+ LinkedChildren = Array.Empty<LinkedChild>();
+ }
+
public static IUserViewManager UserViewManager { get; set; }
/// <summary>
@@ -38,45 +52,121 @@ namespace MediaBrowser.Controller.Entities
public LinkedChild[] LinkedChildren { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime? DateLastMediaAdded { get; set; }
- public Folder()
- {
- LinkedChildren = EmptyLinkedChildArray;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsThemeMedia => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool IsPreSorted => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool IsPhysicalRoot => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => true;
/// <summary>
/// Gets a value indicating whether this instance is folder.
/// </summary>
/// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsFolder => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsDisplayedAsFolder => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsCumulativeRunTimeTicks => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public virtual bool SupportsDateLastMediaAdded => false;
+ [JsonIgnore]
+ public override string FileNameWithoutExtension
+ {
+ get
+ {
+ if (IsFileProtocol)
+ {
+ return System.IO.Path.GetFileName(Path);
+ }
+
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Gets the actual children.
+ /// </summary>
+ /// <value>The actual children.</value>
+ [JsonIgnore]
+ public virtual IEnumerable<BaseItem> Children => LoadChildren();
+
+ /// <summary>
+ /// Gets thread-safe access to all recursive children of this folder - without regard to user.
+ /// </summary>
+ /// <value>The recursive children.</value>
+ [JsonIgnore]
+ public IEnumerable<BaseItem> RecursiveChildren => GetRecursiveChildren();
+
+ [JsonIgnore]
+ protected virtual bool SupportsShortcutChildren => false;
+
+ protected virtual bool FilterLinkedChildrenPerUser => false;
+
+ [JsonIgnore]
+ protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
+
+ [JsonIgnore]
+ public virtual bool SupportsUserDataFromChildren
+ {
+ get
+ {
+ // These are just far too slow.
+ if (this is ICollectionFolder)
+ {
+ return false;
+ }
+
+ if (this is UserView)
+ {
+ return false;
+ }
+
+ if (this is UserRootFolder)
+ {
+ return false;
+ }
+
+ if (this is Channel)
+ {
+ return false;
+ }
+
+ if (SourceType != SourceType.Library)
+ {
+ return false;
+ }
+
+ if (this is IItemByName)
+ {
+ if (this is not IHasDualAccess hasDualAccess || hasDualAccess.IsAccessedByName)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+
+ public static ICollectionManager CollectionManager { get; set; }
+
public override bool CanDelete()
{
if (IsRoot)
@@ -99,44 +189,27 @@ namespace MediaBrowser.Controller.Entities
return baseResult;
}
- [IgnoreDataMember]
- public override string FileNameWithoutExtension
- {
- get
- {
- if (IsFileProtocol)
- {
- return System.IO.Path.GetFileName(Path);
- }
-
- return null;
- }
- }
-
protected override bool IsAllowTagFilterEnforced()
{
if (this is ICollectionFolder)
{
return false;
}
+
if (this is UserView)
{
return false;
}
+
return true;
}
- [IgnoreDataMember]
- protected virtual bool SupportsShortcutChildren => false;
-
/// <summary>
/// Adds the child.
/// </summary>
/// <param name="item">The item.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="InvalidOperationException">Unable to add + item.Name</exception>
- public void AddChild(BaseItem item, CancellationToken cancellationToken)
+ /// <exception cref="InvalidOperationException">Unable to add + item.Name.</exception>
+ public void AddChild(BaseItem item)
{
item.SetParent(this);
@@ -149,6 +222,7 @@ namespace MediaBrowser.Controller.Entities
{
item.DateCreated = DateTime.UtcNow;
}
+
if (item.DateModified == DateTime.MinValue)
{
item.DateModified = DateTime.UtcNow;
@@ -157,37 +231,22 @@ namespace MediaBrowser.Controller.Entities
LibraryManager.CreateItem(item, this);
}
- /// <summary>
- /// Gets the actual children.
- /// </summary>
- /// <value>The actual children.</value>
- [IgnoreDataMember]
- public virtual IEnumerable<BaseItem> Children => LoadChildren();
-
- /// <summary>
- /// thread-safe access to all recursive children of this folder - without regard to user
- /// </summary>
- /// <value>The recursive children.</value>
- [IgnoreDataMember]
- public IEnumerable<BaseItem> RecursiveChildren => GetRecursiveChildren();
-
public override bool IsVisible(User user)
{
- if (this is ICollectionFolder && !(this is BasePluginFolder))
+ if (this is ICollectionFolder && this is not BasePluginFolder)
{
- if (user.Policy.BlockedMediaFolders != null)
+ var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders);
+ if (blockedMediaFolders.Length > 0)
{
- if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
-
- // Backwards compatibility
- user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
+ if (blockedMediaFolders.Contains(Id))
{
return false;
}
}
else
{
- if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
+ if (!user.HasPermission(PermissionKind.EnableAllFolders)
+ && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(Id))
{
return false;
}
@@ -199,12 +258,13 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Loads our children. Validation will occur externally.
- /// We want this sychronous.
+ /// We want this synchronous.
/// </summary>
+ /// <returns>Returns children.</returns>
protected virtual List<BaseItem> LoadChildren()
{
- //logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
- //just load our children from the repo - the library will be validated and maintained in other processes
+ // logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
+ // just load our children from the repo - the library will be validated and maintained in other processes
return GetCachedChildren();
}
@@ -215,20 +275,20 @@ namespace MediaBrowser.Controller.Entities
public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
{
- return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)));
+ return ValidateChildren(progress, new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken: cancellationToken);
}
/// <summary>
- /// Validates that the children of the folder still exist
+ /// Validates that the children of the folder still exist.
/// </summary>
/// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="metadataRefreshOptions">The metadata refresh options.</param>
/// <param name="recursive">if set to <c>true</c> [recursive].</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
+ public Task ValidateChildren(IProgress<double> progress, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true, CancellationToken cancellationToken = default)
{
- return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
+ return ValidateChildrenInternal(progress, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService, cancellationToken);
}
private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
@@ -242,7 +302,8 @@ namespace MediaBrowser.Controller.Entities
var id = child.Id;
if (dictionary.ContainsKey(id))
{
- Logger.LogError("Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}",
+ Logger.LogError(
+ "Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}",
Path ?? Name,
child.Path ?? child.Name);
}
@@ -267,13 +328,13 @@ namespace MediaBrowser.Controller.Entities
/// Validates the children internal.
/// </summary>
/// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="recursive">if set to <c>true</c> [recursive].</param>
/// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
/// <param name="refreshOptions">The refresh options.</param>
/// <param name="directoryService">The directory service.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
if (recursive)
{
@@ -282,7 +343,7 @@ namespace MediaBrowser.Controller.Entities
try
{
- await ValidateChildrenInternal2(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService).ConfigureAwait(false);
+ await ValidateChildrenInternal2(progress, recursive, refreshChildMetadata, refreshOptions, directoryService, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -293,7 +354,7 @@ namespace MediaBrowser.Controller.Entities
}
}
- private async Task ValidateChildrenInternal2(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ private async Task ValidateChildrenInternal2(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -314,17 +375,17 @@ namespace MediaBrowser.Controller.Entities
return;
}
- progress.Report(5);
+ progress.Report(ProgressHelpers.RetrievedChildren);
if (recursive)
{
- ProviderManager.OnRefreshProgress(this, 5);
+ ProviderManager.OnRefreshProgress(this, ProgressHelpers.RetrievedChildren);
}
- //build a dictionary of the current children we have now by Id so we can compare quickly and easily
+ // Build a dictionary of the current children we have now by Id so we can compare quickly and easily
var currentChildren = GetActualChildrenDictionary();
- //create a list for our validated children
+ // Create a list for our validated children
var newItems = new List<BaseItem>();
cancellationToken.ThrowIfCancellationRequested();
@@ -337,7 +398,12 @@ namespace MediaBrowser.Controller.Entities
if (currentChild.UpdateFromResolvedItem(child) > ItemUpdateType.None)
{
- currentChild.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken);
+ await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ // metadata is up-to-date; make sure DB has correct images dimensions and hash
+ await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false);
}
continue;
@@ -374,11 +440,11 @@ namespace MediaBrowser.Controller.Entities
validChildrenNeedGeneration = true;
}
- progress.Report(10);
+ progress.Report(ProgressHelpers.UpdatedChildItems);
if (recursive)
{
- ProviderManager.OnRefreshProgress(this, 10);
+ ProviderManager.OnRefreshProgress(this, ProgressHelpers.UpdatedChildItems);
}
cancellationToken.ThrowIfCancellationRequested();
@@ -388,11 +454,13 @@ namespace MediaBrowser.Controller.Entities
var innerProgress = new ActionableProgress<double>();
var folder = this;
- innerProgress.RegisterAction(p =>
+ innerProgress.RegisterAction(innerPercent =>
{
- double newPct = .80 * p + 10;
- progress.Report(newPct);
- ProviderManager.OnRefreshProgress(folder, newPct);
+ var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.ScannedSubfolders, innerPercent);
+
+ progress.Report(percent);
+
+ ProviderManager.OnRefreshProgress(folder, percent);
});
if (validChildrenNeedGeneration)
@@ -406,11 +474,11 @@ namespace MediaBrowser.Controller.Entities
if (refreshChildMetadata)
{
- progress.Report(90);
+ progress.Report(ProgressHelpers.ScannedSubfolders);
if (recursive)
{
- ProviderManager.OnRefreshProgress(this, 90);
+ ProviderManager.OnRefreshProgress(this, ProgressHelpers.ScannedSubfolders);
}
var container = this as IMetadataContainer;
@@ -418,13 +486,15 @@ namespace MediaBrowser.Controller.Entities
var innerProgress = new ActionableProgress<double>();
var folder = this;
- innerProgress.RegisterAction(p =>
+ innerProgress.RegisterAction(innerPercent =>
{
- double newPct = .10 * p + 90;
- progress.Report(newPct);
+ var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.RefreshedMetadata, innerPercent);
+
+ progress.Report(percent);
+
if (recursive)
{
- ProviderManager.OnRefreshProgress(folder, newPct);
+ ProviderManager.OnRefreshProgress(folder, percent);
}
});
@@ -439,55 +509,35 @@ namespace MediaBrowser.Controller.Entities
validChildren = Children.ToList();
}
- await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken);
+ await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken).ConfigureAwait(false);
}
}
}
- private async Task RefreshMetadataRecursive(List<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
+ private Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
{
- var numComplete = 0;
- var count = children.Count;
- double currentPercent = 0;
-
- foreach (var child in children)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var innerProgress = new ActionableProgress<double>();
-
- // Avoid implicitly captured closure
- var currentInnerPercent = currentPercent;
-
- innerProgress.RegisterAction(p =>
- {
- double innerPercent = currentInnerPercent;
- innerPercent += p / (count);
- progress.Report(innerPercent);
- });
-
- await RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken)
- .ConfigureAwait(false);
-
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
- currentPercent = percent;
-
- progress.Report(percent);
- }
+ return RunTasks(
+ (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken),
+ children,
+ progress,
+ cancellationToken);
}
private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
{
- var series = container as Series;
- if (series != null)
- {
- await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
+ // limit the amount of concurrent metadata refreshes
+ await ProviderManager.RunMetadataRefresh(
+ async () =>
+ {
+ var series = container as Series;
+ if (series != null)
+ {
+ await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
+ }
- }
- await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
+ await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
+ },
+ cancellationToken).ConfigureAwait(false);
}
private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
@@ -502,12 +552,15 @@ namespace MediaBrowser.Controller.Entities
{
if (refreshOptions.RefreshItem(child))
{
- await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
+ // limit the amount of concurrent metadata refreshes
+ await ProviderManager.RunMetadataRefresh(
+ async () => await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false),
+ cancellationToken).ConfigureAwait(false);
}
if (recursive && child is Folder folder)
{
- await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken);
+ await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -520,45 +573,80 @@ namespace MediaBrowser.Controller.Entities
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
+ private Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
{
- var numComplete = 0;
- var count = children.Count;
- double currentPercent = 0;
+ return RunTasks(
+ (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, null, directoryService, cancellationToken),
+ children,
+ progress,
+ cancellationToken);
+ }
- foreach (var child in children)
+ /// <summary>
+ /// Runs an action block on a list of children.
+ /// </summary>
+ /// <param name="task">The task to run for each child.</param>
+ /// <param name="children">The list of children.</param>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ private async Task RunTasks<T>(Func<T, IProgress<double>, Task> task, IList<T> children, IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var childrenCount = children.Count;
+ var childrenProgress = new double[childrenCount];
+
+ void UpdateProgress()
{
- cancellationToken.ThrowIfCancellationRequested();
+ progress.Report(childrenProgress.Average());
+ }
- var innerProgress = new ActionableProgress<double>();
+ var fanoutConcurrency = ConfigurationManager.Configuration.LibraryScanFanoutConcurrency;
+ var parallelism = fanoutConcurrency == 0 ? Environment.ProcessorCount : fanoutConcurrency;
+
+ var actionBlock = new ActionBlock<int>(
+ async i =>
+ {
+ var innerProgress = new ActionableProgress<double>();
+
+ innerProgress.RegisterAction(innerPercent =>
+ {
+ // round the percent and only update progress if it changed to prevent excessive UpdateProgress calls
+ var innerPercentRounded = Math.Round(innerPercent);
+ if (childrenProgress[i] != innerPercentRounded)
+ {
+ childrenProgress[i] = innerPercentRounded;
+ UpdateProgress();
+ }
+ });
+
+ await task(children[i], innerProgress).ConfigureAwait(false);
- // Avoid implicitly captured closure
- var currentInnerPercent = currentPercent;
+ childrenProgress[i] = 100;
- innerProgress.RegisterAction(p =>
+ UpdateProgress();
+ },
+ new ExecutionDataflowBlockOptions
{
- double innerPercent = currentInnerPercent;
- innerPercent += p / (count);
- progress.Report(innerPercent);
+ MaxDegreeOfParallelism = parallelism,
+ CancellationToken = cancellationToken,
});
- await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
- .ConfigureAwait(false);
+ for (var i = 0; i < childrenCount; i++)
+ {
+ actionBlock.Post(i);
+ }
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
- currentPercent = percent;
+ actionBlock.Complete();
- progress.Report(percent);
- }
+ await actionBlock.Completion.ConfigureAwait(false);
}
/// <summary>
- /// Get the children of this folder from the actual file system
+ /// Get the children of this folder from the actual file system.
/// </summary>
/// <returns>IEnumerable{BaseItem}.</returns>
+ /// <param name="directoryService">The directory service to use for operation.</param>
+ /// <returns>Returns set of base items.</returns>
protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
{
var collectionType = LibraryManager.GetContentType(this);
@@ -568,7 +656,7 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Get our children from the repo - stubbed for now
+ /// Get our children from the repo - stubbed for now.
/// </summary>
/// <returns>IEnumerable{BaseItem}.</returns>
protected List<BaseItem> GetCachedChildren()
@@ -585,7 +673,7 @@ namespace MediaBrowser.Controller.Entities
{
if (LinkedChildren.Length > 0)
{
- if (!(this is ICollectionFolder))
+ if (this is not ICollectionFolder)
{
return GetChildren(user, true).Count;
}
@@ -600,7 +688,6 @@ namespace MediaBrowser.Controller.Entities
{
EnableImages = false
}
-
});
return result.TotalRecordCount;
@@ -619,7 +706,6 @@ namespace MediaBrowser.Controller.Entities
{
EnableImages = false
}
-
}).TotalRecordCount;
}
@@ -644,7 +730,7 @@ namespace MediaBrowser.Controller.Entities
return PostFilterAndSort(items, query, true);
}
- if (!(this is UserRootFolder) && !(this is AggregateFolder) && query.ParentId == Guid.Empty)
+ if (this is not UserRootFolder && this is not AggregateFolder && query.ParentId == Guid.Empty)
{
query.Parent = this;
}
@@ -665,36 +751,36 @@ namespace MediaBrowser.Controller.Entities
query.StartIndex = null;
query.Limit = null;
- var itemsList = LibraryManager.GetItemList(query);
+ IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
var user = query.User;
if (user != null)
{
// needed for boxsets
- itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User)).ToList();
+ itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
}
- BaseItem[] returnItems;
+ IEnumerable<BaseItem> returnItems;
int totalCount = 0;
if (query.EnableTotalRecordCount)
{
- var itemsArray = itemsList.ToArray();
- totalCount = itemsArray.Length;
- returnItems = itemsArray;
+ var itemArray = itemsList.ToArray();
+ totalCount = itemArray.Length;
+ returnItems = itemArray;
}
else
{
- returnItems = itemsList.ToArray();
+ returnItems = itemsList;
}
if (limit.HasValue)
{
- returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value).ToArray();
+ returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
}
else if (startIndex.HasValue)
{
- returnItems = returnItems.Skip(startIndex.Value).ToArray();
+ returnItems = returnItems.Skip(startIndex.Value);
}
return new QueryResult<BaseItem>
@@ -706,7 +792,7 @@ namespace MediaBrowser.Controller.Entities
private bool RequiresPostFiltering2(InternalItemsQuery query)
{
- if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
+ if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase))
{
Logger.LogDebug("Query requires post-filtering due to BoxSet query");
return true;
@@ -719,7 +805,7 @@ namespace MediaBrowser.Controller.Entities
{
if (LinkedChildren.Length > 0)
{
- if (!(this is ICollectionFolder))
+ if (this is not ICollectionFolder)
{
Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
return true;
@@ -796,7 +882,7 @@ namespace MediaBrowser.Controller.Entities
if (query.IsPlayed.HasValue)
{
- if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
+ if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(nameof(Series)))
{
Logger.LogDebug("Query requires post-filtering due to IsPlayed");
return true;
@@ -806,26 +892,51 @@ namespace MediaBrowser.Controller.Entities
return false;
}
+ private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
+ {
+ var ids = query.ItemIds;
+ int size = items.Count;
+
+ // ids can potentially contain non-unique guids, but query result cannot,
+ // so we include only first occurrence of each guid
+ var positions = new Dictionary<Guid, int>(size);
+ int index = 0;
+ for (int i = 0; i < ids.Length; i++)
+ {
+ if (positions.TryAdd(ids[i], index))
+ {
+ index++;
+ }
+ }
+
+ var newItems = new BaseItem[size];
+ for (int i = 0; i < size; i++)
+ {
+ var item = items[i];
+ newItems[positions[item.Id]] = item;
+ }
+
+ return newItems;
+ }
+
public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
{
if (query.ItemIds.Length > 0)
{
var result = LibraryManager.GetItemsResult(query);
- if (query.OrderBy.Length == 0)
+ if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
{
- var ids = query.ItemIds.ToList();
-
- // Try to preserve order
- result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id)).ToArray();
+ result.Items = SortItemsByRequest(query, result.Items);
}
+
return result;
}
return GetItemsInternal(query);
}
- public BaseItem[] GetItemList(InternalItemsQuery query)
+ public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
{
query.EnableTotalRecordCount = false;
@@ -833,14 +944,12 @@ namespace MediaBrowser.Controller.Entities
{
var result = LibraryManager.GetItemList(query);
- if (query.OrderBy.Length == 0)
+ if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
{
- var ids = query.ItemIds.ToList();
-
- // Try to preserve order
- return result.OrderBy(i => ids.IndexOf(i.Id)).ToArray();
+ return SortItemsByRequest(query, result);
}
- return result.ToArray();
+
+ return result;
}
return GetItemsInternal(query).Items;
@@ -853,7 +962,7 @@ namespace MediaBrowser.Controller.Entities
try
{
query.Parent = this;
- query.ChannelIds = new Guid[] { ChannelId };
+ query.ChannelIds = new[] { ChannelId };
// Don't blow up here because it could cause parent screens with other content to fail
return ChannelManager.GetChannelItemsInternal(query, new SimpleProgress<double>(), CancellationToken.None).Result;
@@ -882,14 +991,18 @@ namespace MediaBrowser.Controller.Entities
}
else
{
- items = GetChildren(user, true).Where(filter);
+ // need to pass this param to the children.
+ var childQuery = new InternalItemsQuery
+ {
+ DisplayAlbumFolders = query.DisplayAlbumFolders
+ };
+
+ items = GetChildren(user, true, childQuery).Where(filter);
}
return PostFilterAndSort(items, query, true);
}
- public static ICollectionManager CollectionManager { get; set; }
-
protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool enableSorting)
{
var user = query.User;
@@ -902,16 +1015,17 @@ namespace MediaBrowser.Controller.Entities
if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
{
- items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.CurrentCultureIgnoreCase) < 1);
+ items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.InvariantCultureIgnoreCase) < 1);
}
+
if (!string.IsNullOrEmpty(query.NameStartsWith))
{
- items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.OrdinalIgnoreCase));
+ items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIgnoreCase));
}
if (!string.IsNullOrEmpty(query.NameLessThan))
{
- items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.CurrentCultureIgnoreCase) == 1);
+ items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultureIgnoreCase) == 1);
}
// This must be the last filter
@@ -923,11 +1037,13 @@ namespace MediaBrowser.Controller.Entities
return UserViewBuilder.SortAndPage(items, null, query, LibraryManager, enableSorting);
}
- private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(IEnumerable<BaseItem> items,
+ private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
+ IEnumerable<BaseItem> items,
InternalItemsQuery query,
BaseItem queryParent,
User user,
- IServerConfigurationManager configurationManager, ICollectionManager collectionManager)
+ IServerConfigurationManager configurationManager,
+ ICollectionManager collectionManager)
{
if (items == null)
{
@@ -942,7 +1058,8 @@ namespace MediaBrowser.Controller.Entities
return items;
}
- private static bool CollapseBoxSetItems(InternalItemsQuery query,
+ private static bool CollapseBoxSetItems(
+ InternalItemsQuery query,
BaseItem queryParent,
User user,
IServerConfigurationManager configurationManager)
@@ -952,18 +1069,22 @@ namespace MediaBrowser.Controller.Entities
{
return false;
}
+
if (queryParent is Series)
{
return false;
}
+
if (queryParent is Season)
{
return false;
}
+
if (queryParent is MusicAlbum)
{
return false;
}
+
if (queryParent is MusicArtist)
{
return false;
@@ -993,33 +1114,38 @@ namespace MediaBrowser.Controller.Entities
{
return false;
}
+
if (request.IsFavoriteOrLiked.HasValue)
{
return false;
}
+
if (request.IsLiked.HasValue)
{
return false;
}
+
if (request.IsPlayed.HasValue)
{
return false;
}
+
if (request.IsResumable.HasValue)
{
return false;
}
+
if (request.IsFolder.HasValue)
{
return false;
}
- if (request.Genres.Length > 0)
+ if (request.Genres.Count > 0)
{
return false;
}
- if (request.GenreIds.Length > 0)
+ if (request.GenreIds.Count > 0)
{
return false;
}
@@ -1124,7 +1250,7 @@ namespace MediaBrowser.Controller.Entities
return false;
}
- if (request.GenreIds.Length > 0)
+ if (request.GenreIds.Count > 0)
{
return false;
}
@@ -1169,6 +1295,11 @@ namespace MediaBrowser.Controller.Entities
public List<BaseItem> GetChildren(User user, bool includeLinkedChildren)
{
+ if (user == null)
+ {
+ throw new ArgumentNullException(nameof(user));
+ }
+
return GetChildren(user, includeLinkedChildren, null);
}
@@ -1179,8 +1310,11 @@ namespace MediaBrowser.Controller.Entities
throw new ArgumentNullException(nameof(user));
}
- //the true root should return our users root folder children
- if (IsPhysicalRoot) return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren);
+ // the true root should return our users root folder children
+ if (IsPhysicalRoot)
+ {
+ return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren);
+ }
var result = new Dictionary<Guid, BaseItem>();
@@ -1197,10 +1331,23 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Adds the children to list.
/// </summary>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
{
- foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
+ // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums.
+ IEnumerable<BaseItem> children = null;
+ if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
+ {
+ children = Children;
+ query = null;
+ }
+
+ // If there are not sub-folders, proceed as normal.
+ if (children == null)
+ {
+ children = GetEligibleChildrenForRecursiveChildren(user);
+ }
+
+ foreach (var child in children)
{
bool? isVisibleToUser = null;
@@ -1240,18 +1387,6 @@ namespace MediaBrowser.Controller.Entities
}
}
- /// <summary>
- /// Gets allowed recursive children of an item
- /// </summary>
- /// <param name="user">The user.</param>
- /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
- /// <returns>IEnumerable{BaseItem}.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
- {
- return GetRecursiveChildren(user, null);
- }
-
public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
{
if (user == null)
@@ -1327,7 +1462,6 @@ namespace MediaBrowser.Controller.Entities
}
}
-
/// <summary>
/// Gets the linked children.
/// </summary>
@@ -1346,19 +1480,23 @@ namespace MediaBrowser.Controller.Entities
list.Add(child);
}
}
+
return list;
}
- protected virtual bool FilterLinkedChildrenPerUser => false;
-
public bool ContainsLinkedChildByItemId(Guid itemId)
{
var linkedChildren = LinkedChildren;
foreach (var i in linkedChildren)
{
- if (i.ItemId.HasValue && i.ItemId.Value == itemId)
+ if (i.ItemId.HasValue)
{
- return true;
+ if (i.ItemId.Value == itemId)
+ {
+ return true;
+ }
+
+ continue;
}
var child = GetLinkedChild(i);
@@ -1368,6 +1506,7 @@ namespace MediaBrowser.Controller.Entities
return true;
}
}
+
return false;
}
@@ -1406,7 +1545,7 @@ namespace MediaBrowser.Controller.Entities
var childOwner = child.GetOwner() ?? child;
- if (childOwner != null && !(child is IItemByName))
+ if (child is not IItemByName)
{
var childProtocol = childOwner.PathProtocol;
if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
@@ -1445,9 +1584,6 @@ namespace MediaBrowser.Controller.Entities
.Where(i => i.Item2 != null);
}
- [IgnoreDataMember]
- protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
-
protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
{
var changesFound = false;
@@ -1468,7 +1604,8 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// Refreshes the linked children.
/// </summary>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
+ /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
+ /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
{
if (SupportsShortcutChildren)
@@ -1532,8 +1669,8 @@ namespace MediaBrowser.Controller.Entities
/// <param name="user">The user.</param>
/// <param name="datePlayed">The date played.</param>
/// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
- /// <returns>Task.</returns>
- public override void MarkPlayed(User user,
+ public override void MarkPlayed(
+ User user,
DateTime? datePlayed,
bool resetPosition)
{
@@ -1545,7 +1682,7 @@ namespace MediaBrowser.Controller.Entities
EnableTotalRecordCount = false
};
- if (!user.Configuration.DisplayMissingEpisodes)
+ if (!user.DisplayMissingEpisodes)
{
query.IsVirtualItem = false;
}
@@ -1573,7 +1710,6 @@ namespace MediaBrowser.Controller.Entities
/// Marks the unplayed.
/// </summary>
/// <param name="user">The user.</param>
- /// <returns>Task.</returns>
public override void MarkUnplayed(User user)
{
var itemsResult = GetItemList(new InternalItemsQuery
@@ -1582,7 +1718,6 @@ namespace MediaBrowser.Controller.Entities
Recursive = true,
IsFolder = false,
EnableTotalRecordCount = false
-
});
// Sweep through recursively and update status
@@ -1600,7 +1735,6 @@ namespace MediaBrowser.Controller.Entities
IsFolder = false,
IsVirtualItem = false,
EnableTotalRecordCount = false
-
});
return itemsResult
@@ -1612,46 +1746,6 @@ namespace MediaBrowser.Controller.Entities
return !IsPlayed(user);
}
- [IgnoreDataMember]
- public virtual bool SupportsUserDataFromChildren
- {
- get
- {
- // These are just far too slow.
- if (this is ICollectionFolder)
- {
- return false;
- }
- if (this is UserView)
- {
- return false;
- }
- if (this is UserRootFolder)
- {
- return false;
- }
- if (this is Channel)
- {
- return false;
- }
- if (SourceType != SourceType.Library)
- {
- return false;
- }
- var iItemByName = this as IItemByName;
- if (iItemByName != null)
- {
- var hasDualAccess = this as IHasDualAccess;
- if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
- {
- return false;
- }
- }
-
- return true;
- }
- }
-
public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
{
if (!SupportsUserDataFromChildren)
@@ -1681,21 +1775,15 @@ namespace MediaBrowser.Controller.Entities
{
EnableImages = false
}
+ }).TotalRecordCount;
- });
-
- double unplayedCount = unplayedQueryResult.TotalRecordCount;
-
- dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
+ dto.UnplayedItemCount = unplayedQueryResult;
- if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
+ if (itemDto?.RecursiveItemCount > 0)
{
- if (itemDto.RecursiveItemCount.Value > 0)
- {
- var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
- dto.PlayedPercentage = 100 - unplayedPercentage;
- dto.Played = dto.PlayedPercentage.Value >= 100;
- }
+ var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
+ dto.PlayedPercentage = 100 - unplayedPercentage;
+ dto.Played = dto.PlayedPercentage.Value >= 100;
}
else
{
@@ -1703,5 +1791,45 @@ namespace MediaBrowser.Controller.Entities
}
}
}
+
+ /// <summary>
+ /// Contains constants used when reporting scan progress.
+ /// </summary>
+ private static class ProgressHelpers
+ {
+ /// <summary>
+ /// Reported after the folders immediate children are retrieved.
+ /// </summary>
+ public const int RetrievedChildren = 5;
+
+ /// <summary>
+ /// Reported after add, updating, or deleting child items from the LibraryManager.
+ /// </summary>
+ public const int UpdatedChildItems = 10;
+
+ /// <summary>
+ /// Reported once subfolders are scanned.
+ /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
+ /// </summary>
+ public const int ScannedSubfolders = 50;
+
+ /// <summary>
+ /// Reported once metadata is refreshed.
+ /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
+ /// </summary>
+ public const int RefreshedMetadata = 100;
+
+ /// <summary>
+ /// Gets the current progress given the previous step, next step, and progress in between.
+ /// </summary>
+ /// <param name="previousProgressStep">The previous progress step.</param>
+ /// <param name="nextProgressStep">The next progress step.</param>
+ /// <param name="currentProgress">The current progress step.</param>
+ /// <returns>The progress.</returns>
+ public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
+ {
+ return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
+ }
+ }
}
}
diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs
index 44cb62d22..338f96204 100644
--- a/MediaBrowser.Controller/Entities/Genre.cs
+++ b/MediaBrowser.Controller/Entities/Genre.cs
@@ -1,17 +1,38 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Diacritics.Extensions;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Genre
+ /// Class Genre.
/// </summary>
public class Genre : BaseItem, IItemByName
{
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ [JsonIgnore]
+ public override bool IsDisplayedAsFolder => true;
+
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
@@ -19,6 +40,7 @@ namespace MediaBrowser.Controller.Entities
list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics());
return list;
}
+
public override string CreatePresentationUniqueKey()
{
return GetUserDataKeys()[0];
@@ -29,20 +51,6 @@ namespace MediaBrowser.Controller.Entities
return 1;
}
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
- [IgnoreDataMember]
- public override bool IsDisplayedAsFolder => true;
-
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
public override bool IsSaveLocalMetadataEnabled()
{
return true;
@@ -56,14 +64,17 @@ namespace MediaBrowser.Controller.Entities
public IList<BaseItem> GetTaggedItems(InternalItemsQuery query)
{
query.GenreIds = new[] { Id };
- query.ExcludeItemTypes = new[] { typeof(MusicVideo).Name, typeof(Audio.Audio).Name, typeof(MusicAlbum).Name, typeof(MusicArtist).Name };
+ query.ExcludeItemTypes = new[]
+ {
+ nameof(MusicVideo),
+ nameof(Entities.Audio.Audio),
+ nameof(MusicAlbum),
+ nameof(MusicArtist)
+ };
return LibraryManager.GetItemList(query);
}
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
public static string GetPath(string name)
{
return GetPath(name, true);
@@ -92,15 +103,18 @@ namespace MediaBrowser.Controller.Entities
Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
+ /// <returns>true if the item has change, else false.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
diff --git a/MediaBrowser.Controller/Entities/ICollectionFolder.cs b/MediaBrowser.Controller/Entities/ICollectionFolder.cs
index a6a9a0783..89e494ebc 100644
--- a/MediaBrowser.Controller/Entities/ICollectionFolder.cs
+++ b/MediaBrowser.Controller/Entities/ICollectionFolder.cs
@@ -1,15 +1,22 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
using System;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// This is just a marker interface to denote top level folders
+ /// This is just a marker interface to denote top level folders.
/// </summary>
public interface ICollectionFolder : IHasCollectionType
{
string Path { get; }
+
string Name { get; }
+
Guid Id { get; }
+
string[] PhysicalLocations { get; }
}
diff --git a/MediaBrowser.Controller/Entities/IHasAspectRatio.cs b/MediaBrowser.Controller/Entities/IHasAspectRatio.cs
index 149c1e5ab..3aeb7468f 100644
--- a/MediaBrowser.Controller/Entities/IHasAspectRatio.cs
+++ b/MediaBrowser.Controller/Entities/IHasAspectRatio.cs
@@ -1,7 +1,9 @@
+#nullable disable
+
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Interface IHasAspectRatio
+ /// Interface IHasAspectRatio.
/// </summary>
public interface IHasAspectRatio
{
diff --git a/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs b/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs
index abee75a28..14459624e 100644
--- a/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs
+++ b/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs
@@ -1,7 +1,9 @@
+#nullable disable
+
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Interface IHasDisplayOrder
+ /// Interface IHasDisplayOrder.
/// </summary>
public interface IHasDisplayOrder
{
diff --git a/MediaBrowser.Controller/Entities/IHasMediaSources.cs b/MediaBrowser.Controller/Entities/IHasMediaSources.cs
index 4635b9062..90d9bdd2d 100644
--- a/MediaBrowser.Controller/Entities/IHasMediaSources.cs
+++ b/MediaBrowser.Controller/Entities/IHasMediaSources.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Dto;
@@ -7,13 +11,19 @@ namespace MediaBrowser.Controller.Entities
{
public interface IHasMediaSources
{
+ Guid Id { get; set; }
+
+ long? RunTimeTicks { get; set; }
+
+ string Path { get; }
+
/// <summary>
/// Gets the media sources.
/// </summary>
+ /// <param name="enablePathSubstitution"><c>true</c> to enable path substitution, <c>false</c> to not.</param>
+ /// <returns>A list of media sources.</returns>
List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution);
+
List<MediaStream> GetMediaStreams();
- Guid Id { get; set; }
- long? RunTimeTicks { get; set; }
- string Path { get; }
}
}
diff --git a/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs b/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs
index 777b40828..f80f7c304 100644
--- a/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs
+++ b/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Model.LiveTv;
namespace MediaBrowser.Controller.Entities
@@ -5,13 +9,21 @@ namespace MediaBrowser.Controller.Entities
public interface IHasProgramAttributes
{
bool IsMovie { get; set; }
+
bool IsSports { get; }
+
bool IsNews { get; }
+
bool IsKids { get; }
+
bool IsRepeat { get; set; }
+
bool IsSeries { get; set; }
+
ProgramAudio? Audio { get; set; }
+
string EpisodeTitle { get; set; }
+
string ServiceName { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/IHasScreenshots.cs b/MediaBrowser.Controller/Entities/IHasScreenshots.cs
index 0975242f5..ae01c223e 100644
--- a/MediaBrowser.Controller/Entities/IHasScreenshots.cs
+++ b/MediaBrowser.Controller/Entities/IHasScreenshots.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Interface IHasScreenshots
+ /// The item has screenshots.
/// </summary>
public interface IHasScreenshots
{
diff --git a/MediaBrowser.Controller/Entities/IHasSeries.cs b/MediaBrowser.Controller/Entities/IHasSeries.cs
index 7da53f730..5f774bbde 100644
--- a/MediaBrowser.Controller/Entities/IHasSeries.cs
+++ b/MediaBrowser.Controller/Entities/IHasSeries.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Entities
@@ -5,15 +9,21 @@ namespace MediaBrowser.Controller.Entities
public interface IHasSeries
{
/// <summary>
- /// Gets the name of the series.
+ /// Gets or sets the name of the series.
/// </summary>
/// <value>The name of the series.</value>
string SeriesName { get; set; }
+
+ Guid SeriesId { get; set; }
+
+ string SeriesPresentationUniqueKey { get; set; }
+
string FindSeriesName();
+
string FindSeriesSortName();
- Guid SeriesId { get; set; }
+
Guid FindSeriesId();
- string SeriesPresentationUniqueKey { get; set; }
+
string FindSeriesPresentationUniqueKey();
}
}
diff --git a/MediaBrowser.Controller/Entities/IHasShares.cs b/MediaBrowser.Controller/Entities/IHasShares.cs
new file mode 100644
index 000000000..dca5af873
--- /dev/null
+++ b/MediaBrowser.Controller/Entities/IHasShares.cs
@@ -0,0 +1,11 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
+namespace MediaBrowser.Controller.Entities
+{
+ public interface IHasShares
+ {
+ Share[] Shares { get; set; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs b/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs
index 688439e6c..f317a02ff 100644
--- a/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs
+++ b/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs
@@ -1,4 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Controller.Entities
{
@@ -8,6 +13,6 @@ namespace MediaBrowser.Controller.Entities
/// Gets or sets the special feature ids.
/// </summary>
/// <value>The special feature ids.</value>
- Guid[] SpecialFeatureIds { get; set; }
+ IReadOnlyList<Guid> SpecialFeatureIds { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/IHasStartDate.cs b/MediaBrowser.Controller/Entities/IHasStartDate.cs
index 1ecde9af4..dab15eb01 100644
--- a/MediaBrowser.Controller/Entities/IHasStartDate.cs
+++ b/MediaBrowser.Controller/Entities/IHasStartDate.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Entities
diff --git a/MediaBrowser.Controller/Entities/IHasTrailers.cs b/MediaBrowser.Controller/Entities/IHasTrailers.cs
index 3bdb9b64a..f4271678d 100644
--- a/MediaBrowser.Controller/Entities/IHasTrailers.cs
+++ b/MediaBrowser.Controller/Entities/IHasTrailers.cs
@@ -1,6 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Linq;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Entities
@@ -11,29 +14,85 @@ namespace MediaBrowser.Controller.Entities
/// Gets or sets the remote trailers.
/// </summary>
/// <value>The remote trailers.</value>
- MediaUrl[] RemoteTrailers { get; set; }
+ IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
/// <summary>
/// Gets or sets the local trailer ids.
/// </summary>
/// <value>The local trailer ids.</value>
- Guid[] LocalTrailerIds { get; set; }
- Guid[] RemoteTrailerIds { get; set; }
+ IReadOnlyList<Guid> LocalTrailerIds { get; set; }
+
+ /// <summary>
+ /// Gets or sets the remote trailer ids.
+ /// </summary>
+ /// <value>The remote trailer ids.</value>
+ IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
+
Guid Id { get; set; }
}
+ /// <summary>
+ /// Class providing extension methods for working with <see cref="IHasTrailers" />.
+ /// </summary>
public static class HasTrailerExtensions
{
/// <summary>
+ /// Gets the trailer count.
+ /// </summary>
+ /// <param name="item">Media item.</param>
+ /// <returns><see cref="IReadOnlyList{Guid}" />.</returns>
+ public static int GetTrailerCount(this IHasTrailers item)
+ => item.LocalTrailerIds.Count + item.RemoteTrailerIds.Count;
+
+ /// <summary>
/// Gets the trailer ids.
/// </summary>
- /// <returns>List&lt;Guid&gt;.</returns>
- public static List<Guid> GetTrailerIds(this IHasTrailers item)
+ /// <param name="item">Media item.</param>
+ /// <returns><see cref="IReadOnlyList{Guid}" />.</returns>
+ public static IReadOnlyList<Guid> GetTrailerIds(this IHasTrailers item)
{
- var list = item.LocalTrailerIds.ToList();
- list.AddRange(item.RemoteTrailerIds);
- return list;
+ var localIds = item.LocalTrailerIds;
+ var remoteIds = item.RemoteTrailerIds;
+
+ var all = new Guid[localIds.Count + remoteIds.Count];
+ var index = 0;
+ foreach (var id in localIds)
+ {
+ all[index++] = id;
+ }
+
+ foreach (var id in remoteIds)
+ {
+ all[index++] = id;
+ }
+
+ return all;
}
+ /// <summary>
+ /// Gets the trailers.
+ /// </summary>
+ /// <param name="item">Media item.</param>
+ /// <returns><see cref="IReadOnlyList{BaseItem}" />.</returns>
+ public static IReadOnlyList<BaseItem> GetTrailers(this IHasTrailers item)
+ {
+ var localIds = item.LocalTrailerIds;
+ var remoteIds = item.RemoteTrailerIds;
+ var libraryManager = BaseItem.LibraryManager;
+
+ var all = new BaseItem[localIds.Count + remoteIds.Count];
+ var index = 0;
+ foreach (var id in localIds)
+ {
+ all[index++] = libraryManager.GetItemById(id);
+ }
+
+ foreach (var id in remoteIds)
+ {
+ all[index++] = libraryManager.GetItemById(id);
+ }
+
+ return all;
+ }
}
}
diff --git a/MediaBrowser.Controller/Entities/IItemByName.cs b/MediaBrowser.Controller/Entities/IItemByName.cs
index 89b5dfee3..cac8aa61a 100644
--- a/MediaBrowser.Controller/Entities/IItemByName.cs
+++ b/MediaBrowser.Controller/Entities/IItemByName.cs
@@ -1,9 +1,11 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Marker interface
+ /// Marker interface.
/// </summary>
public interface IItemByName
{
diff --git a/MediaBrowser.Controller/Entities/IMetadataContainer.cs b/MediaBrowser.Controller/Entities/IMetadataContainer.cs
index a384c0df3..77f5cfb79 100644
--- a/MediaBrowser.Controller/Entities/IMetadataContainer.cs
+++ b/MediaBrowser.Controller/Entities/IMetadataContainer.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading;
using System.Threading.Tasks;
diff --git a/MediaBrowser.Controller/Entities/ISupportsPlaceHolders.cs b/MediaBrowser.Controller/Entities/ISupportsPlaceHolders.cs
index 3e96771c3..cdda8ea39 100644
--- a/MediaBrowser.Controller/Entities/ISupportsPlaceHolders.cs
+++ b/MediaBrowser.Controller/Entities/ISupportsPlaceHolders.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Entities
{
public interface ISupportsPlaceHolders
diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
index 78f859069..0baa7725e 100644
--- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
@@ -1,254 +1,365 @@
+#pragma warning disable CA1044, CA1819, CA2227, CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Entities
{
public class InternalItemsQuery
{
+ public InternalItemsQuery()
+ {
+ AlbumArtistIds = Array.Empty<Guid>();
+ AlbumIds = Array.Empty<Guid>();
+ AncestorIds = Array.Empty<Guid>();
+ ArtistIds = Array.Empty<Guid>();
+ BlockUnratedItems = Array.Empty<UnratedItem>();
+ BoxSetLibraryFolders = Array.Empty<Guid>();
+ ChannelIds = Array.Empty<Guid>();
+ ContributingArtistIds = Array.Empty<Guid>();
+ DtoOptions = new DtoOptions();
+ EnableTotalRecordCount = true;
+ ExcludeArtistIds = Array.Empty<Guid>();
+ ExcludeInheritedTags = Array.Empty<string>();
+ ExcludeItemIds = Array.Empty<Guid>();
+ ExcludeItemTypes = Array.Empty<string>();
+ ExcludeTags = Array.Empty<string>();
+ GenreIds = Array.Empty<Guid>();
+ Genres = Array.Empty<string>();
+ GroupByPresentationUniqueKey = true;
+ ImageTypes = Array.Empty<ImageType>();
+ IncludeItemTypes = Array.Empty<string>();
+ ItemIds = Array.Empty<Guid>();
+ MediaTypes = Array.Empty<string>();
+ MinSimilarityScore = 20;
+ OfficialRatings = Array.Empty<string>();
+ OrderBy = Array.Empty<ValueTuple<string, SortOrder>>();
+ PersonIds = Array.Empty<Guid>();
+ PersonTypes = Array.Empty<string>();
+ PresetViews = Array.Empty<string>();
+ SeriesStatuses = Array.Empty<SeriesStatus>();
+ SourceTypes = Array.Empty<SourceType>();
+ StudioIds = Array.Empty<Guid>();
+ Tags = Array.Empty<string>();
+ TopParentIds = Array.Empty<Guid>();
+ TrailerTypes = Array.Empty<TrailerType>();
+ VideoTypes = Array.Empty<VideoType>();
+ Years = Array.Empty<int>();
+ }
+
+ public InternalItemsQuery(User? user)
+ : this()
+ {
+ if (user != null)
+ {
+ SetUser(user);
+ }
+ }
+
public bool Recursive { get; set; }
public int? StartIndex { get; set; }
public int? Limit { get; set; }
- public User User { get; set; }
+ public User? User { get; set; }
- public BaseItem SimilarTo { get; set; }
+ public BaseItem? SimilarTo { get; set; }
public bool? IsFolder { get; set; }
+
public bool? IsFavorite { get; set; }
+
public bool? IsFavoriteOrLiked { get; set; }
+
public bool? IsLiked { get; set; }
+
public bool? IsPlayed { get; set; }
+
public bool? IsResumable { get; set; }
+
public bool? IncludeItemsByName { get; set; }
public string[] MediaTypes { get; set; }
+
public string[] IncludeItemTypes { get; set; }
+
public string[] ExcludeItemTypes { get; set; }
+
public string[] ExcludeTags { get; set; }
+
public string[] ExcludeInheritedTags { get; set; }
- public string[] Genres { get; set; }
+
+ public IReadOnlyList<string> Genres { get; set; }
public bool? IsSpecialSeason { get; set; }
+
public bool? IsMissing { get; set; }
+
public bool? IsUnaired { get; set; }
+
public bool? CollapseBoxSetItems { get; set; }
- public string NameStartsWithOrGreater { get; set; }
- public string NameStartsWith { get; set; }
- public string NameLessThan { get; set; }
- public string NameContains { get; set; }
- public string MinSortName { get; set; }
+ public string? NameStartsWithOrGreater { get; set; }
+
+ public string? NameStartsWith { get; set; }
+
+ public string? NameLessThan { get; set; }
+
+ public string? NameContains { get; set; }
+
+ public string? MinSortName { get; set; }
+
+ public string? PresentationUniqueKey { get; set; }
- public string PresentationUniqueKey { get; set; }
- public string Path { get; set; }
- public string Name { get; set; }
+ public string? Path { get; set; }
+
+ public string? Name { get; set; }
+
+ public string? Person { get; set; }
- public string Person { get; set; }
public Guid[] PersonIds { get; set; }
+
public Guid[] ItemIds { get; set; }
+
public Guid[] ExcludeItemIds { get; set; }
- public string AdjacentTo { get; set; }
+
+ public string? AdjacentTo { get; set; }
+
public string[] PersonTypes { get; set; }
public bool? Is3D { get; set; }
+
public bool? IsHD { get; set; }
+
public bool? IsLocked { get; set; }
+
public bool? IsPlaceHolder { get; set; }
public bool? HasImdbId { get; set; }
+
public bool? HasOverview { get; set; }
+
public bool? HasTmdbId { get; set; }
+
public bool? HasOfficialRating { get; set; }
+
public bool? HasTvdbId { get; set; }
+
public bool? HasThemeSong { get; set; }
+
public bool? HasThemeVideo { get; set; }
+
public bool? HasSubtitles { get; set; }
+
public bool? HasSpecialFeature { get; set; }
+
public bool? HasTrailer { get; set; }
+
public bool? HasParentalRating { get; set; }
public Guid[] StudioIds { get; set; }
- public Guid[] GenreIds { get; set; }
+
+ public IReadOnlyList<Guid> GenreIds { get; set; }
+
public ImageType[] ImageTypes { get; set; }
+
public VideoType[] VideoTypes { get; set; }
+
public UnratedItem[] BlockUnratedItems { get; set; }
+
public int[] Years { get; set; }
+
public string[] Tags { get; set; }
+
public string[] OfficialRatings { get; set; }
public DateTime? MinPremiereDate { get; set; }
+
public DateTime? MaxPremiereDate { get; set; }
+
public DateTime? MinStartDate { get; set; }
+
public DateTime? MaxStartDate { get; set; }
+
public DateTime? MinEndDate { get; set; }
+
public DateTime? MaxEndDate { get; set; }
+
public bool? IsAiring { get; set; }
public bool? IsMovie { get; set; }
+
public bool? IsSports { get; set; }
+
public bool? IsKids { get; set; }
+
public bool? IsNews { get; set; }
+
public bool? IsSeries { get; set; }
+
public int? MinIndexNumber { get; set; }
+
public int? AiredDuringSeason { get; set; }
+
public double? MinCriticRating { get; set; }
+
public double? MinCommunityRating { get; set; }
- public Guid[] ChannelIds { get; set; }
+ public IReadOnlyList<Guid> ChannelIds { get; set; }
public int? ParentIndexNumber { get; set; }
+
public int? ParentIndexNumberNotEquals { get; set; }
+
public int? IndexNumber { get; set; }
+
public int? MinParentalRating { get; set; }
+
public int? MaxParentalRating { get; set; }
public bool? HasDeadParentId { get; set; }
+
public bool? IsVirtualItem { get; set; }
public Guid ParentId { get; set; }
- public string ParentType { get; set; }
+
+ public string? ParentType { get; set; }
+
public Guid[] AncestorIds { get; set; }
- public Guid[] TopParentIds { get; set; }
- public BaseItem Parent
- {
- set
- {
- if (value == null)
- {
- ParentId = Guid.Empty;
- ParentType = null;
- }
- else
- {
- ParentId = value.Id;
- ParentType = value.GetType().Name;
- }
- }
- }
+ public Guid[] TopParentIds { get; set; }
public string[] PresetViews { get; set; }
+
public TrailerType[] TrailerTypes { get; set; }
+
public SourceType[] SourceTypes { get; set; }
public SeriesStatus[] SeriesStatuses { get; set; }
- public string ExternalSeriesId { get; set; }
- public string ExternalId { get; set; }
+
+ public string? ExternalSeriesId { get; set; }
+
+ public string? ExternalId { get; set; }
public Guid[] AlbumIds { get; set; }
+
public Guid[] ArtistIds { get; set; }
+
public Guid[] ExcludeArtistIds { get; set; }
- public string AncestorWithPresentationUniqueKey { get; set; }
- public string SeriesPresentationUniqueKey { get; set; }
+
+ public string? AncestorWithPresentationUniqueKey { get; set; }
+
+ public string? SeriesPresentationUniqueKey { get; set; }
public bool GroupByPresentationUniqueKey { get; set; }
+
public bool GroupBySeriesPresentationUniqueKey { get; set; }
+
public bool EnableTotalRecordCount { get; set; }
+
public bool ForceDirect { get; set; }
- public Dictionary<string, string> ExcludeProviderIds { get; set; }
+
+ public Dictionary<string, string>? ExcludeProviderIds { get; set; }
+
public bool EnableGroupByMetadataKey { get; set; }
+
public bool? HasChapterImages { get; set; }
- public ValueTuple<string, SortOrder>[] OrderBy { get; set; }
+ public IReadOnlyList<(string, SortOrder)> OrderBy { get; set; }
public DateTime? MinDateCreated { get; set; }
+
public DateTime? MinDateLastSaved { get; set; }
+
public DateTime? MinDateLastSavedForUser { get; set; }
public DtoOptions DtoOptions { get; set; }
+
public int MinSimilarityScore { get; set; }
- public string HasNoAudioTrackWithLanguage { get; set; }
- public string HasNoInternalSubtitleTrackWithLanguage { get; set; }
- public string HasNoExternalSubtitleTrackWithLanguage { get; set; }
- public string HasNoSubtitleTrackWithLanguage { get; set; }
+
+ public string? HasNoAudioTrackWithLanguage { get; set; }
+
+ public string? HasNoInternalSubtitleTrackWithLanguage { get; set; }
+
+ public string? HasNoExternalSubtitleTrackWithLanguage { get; set; }
+
+ public string? HasNoSubtitleTrackWithLanguage { get; set; }
+
public bool? IsDeadArtist { get; set; }
+
public bool? IsDeadStudio { get; set; }
- public bool? IsDeadPerson { get; set; }
- public InternalItemsQuery()
- {
- AlbumArtistIds = Array.Empty<Guid>();
- AlbumIds = Array.Empty<Guid>();
- AncestorIds = Array.Empty<Guid>();
- ArtistIds = Array.Empty<Guid>();
- BlockUnratedItems = Array.Empty<UnratedItem>();
- BoxSetLibraryFolders = Array.Empty<Guid>();
- ChannelIds = Array.Empty<Guid>();
- ContributingArtistIds = Array.Empty<Guid>();
- DtoOptions = new DtoOptions();
- EnableTotalRecordCount = true;
- ExcludeArtistIds = Array.Empty<Guid>();
- ExcludeInheritedTags = Array.Empty<string>();
- ExcludeItemIds = Array.Empty<Guid>();
- ExcludeItemTypes = Array.Empty<string>();
- ExcludeProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ExcludeTags = Array.Empty<string>();
- GenreIds = Array.Empty<Guid>();
- Genres = Array.Empty<string>();
- GroupByPresentationUniqueKey = true;
- HasAnyProviderId = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ImageTypes = Array.Empty<ImageType>();
- IncludeItemTypes = Array.Empty<string>();
- ItemIds = Array.Empty<Guid>();
- MediaTypes = Array.Empty<string>();
- MinSimilarityScore = 20;
- OfficialRatings = Array.Empty<string>();
- OrderBy = Array.Empty<ValueTuple<string, SortOrder>>();
- PersonIds = Array.Empty<Guid>();
- PersonTypes = Array.Empty<string>();
- PresetViews = Array.Empty<string>();
- SeriesStatuses = Array.Empty<SeriesStatus>();
- SourceTypes = Array.Empty<SourceType>();
- StudioIds = Array.Empty<Guid>();
- Tags = Array.Empty<string>();
- TopParentIds = Array.Empty<Guid>();
- TrailerTypes = Array.Empty<TrailerType>();
- VideoTypes = Array.Empty<VideoType>();
- Years = Array.Empty<int>();
- }
+ public bool? IsDeadPerson { get; set; }
- public InternalItemsQuery(User user)
- : this()
- {
- SetUser(user);
- }
+ /// <summary>
+ /// Gets or sets a value indicating whether album sub-folders should be returned if they exist.
+ /// </summary>
+ public bool? DisplayAlbumFolders { get; set; }
- public void SetUser(User user)
+ public BaseItem? Parent
{
- if (user != null)
+ set
{
- var policy = user.Policy;
- MaxParentalRating = policy.MaxParentalRating;
-
- if (policy.MaxParentalRating.HasValue)
+ if (value == null)
+ {
+ ParentId = Guid.Empty;
+ ParentType = null;
+ }
+ else
{
- BlockUnratedItems = policy.BlockUnratedItems.Where(i => i != UnratedItem.Other).ToArray();
+ ParentId = value.Id;
+ ParentType = value.GetType().Name;
}
-
- ExcludeInheritedTags = policy.BlockedTags;
-
- User = user;
}
}
- public Dictionary<string, string> HasAnyProviderId { get; set; }
+ public Dictionary<string, string>? HasAnyProviderId { get; set; }
+
public Guid[] AlbumArtistIds { get; set; }
+
public Guid[] BoxSetLibraryFolders { get; set; }
+
public Guid[] ContributingArtistIds { get; set; }
+
public bool? HasAired { get; set; }
+
public bool? HasOwnerId { get; set; }
+
public bool? Is4K { get; set; }
+
public int? MaxHeight { get; set; }
+
public int? MaxWidth { get; set; }
+
public int? MinHeight { get; set; }
+
public int? MinWidth { get; set; }
- public string SearchTerm { get; set; }
- public string SeriesTimerId { get; set; }
+
+ public string? SearchTerm { get; set; }
+
+ public string? SeriesTimerId { get; set; }
+
+ public void SetUser(User user)
+ {
+ MaxParentalRating = user.MaxParentalAgeRating;
+
+ if (MaxParentalRating.HasValue)
+ {
+ string 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);
+
+ User = user;
+ }
}
}
diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
index 1613531b5..3e1d89274 100644
--- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
@@ -1,20 +1,45 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
+using Jellyfin.Data.Entities;
namespace MediaBrowser.Controller.Entities
{
public class InternalPeopleQuery
{
+ public InternalPeopleQuery()
+ : this(Array.Empty<string>(), Array.Empty<string>())
+ {
+ }
+
+ public InternalPeopleQuery(IReadOnlyList<string> personTypes, IReadOnlyList<string> excludePersonTypes)
+ {
+ PersonTypes = personTypes;
+ ExcludePersonTypes = excludePersonTypes;
+ }
+
+ /// <summary>
+ /// Gets or sets the maximum number of items the query should return.
+ /// </summary>
+ public int Limit { get; set; }
+
public Guid ItemId { get; set; }
- public string[] PersonTypes { get; set; }
- public string[] ExcludePersonTypes { get; set; }
+
+ public IReadOnlyList<string> PersonTypes { get; }
+
+ public IReadOnlyList<string> ExcludePersonTypes { get; }
+
public int? MaxListOrder { get; set; }
+
public Guid AppearsInItemId { get; set; }
+
public string NameContains { get; set; }
- public InternalPeopleQuery()
- {
- PersonTypes = Array.Empty<string>();
- ExcludePersonTypes = Array.Empty<string>();
- }
+ public User User { get; set; }
+
+ public bool? IsFavorite { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/ItemImageInfo.cs b/MediaBrowser.Controller/Entities/ItemImageInfo.cs
index ff6b13398..ea8555dbf 100644
--- a/MediaBrowser.Controller/Entities/ItemImageInfo.cs
+++ b/MediaBrowser.Controller/Entities/ItemImageInfo.cs
@@ -1,6 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Text.Json.Serialization;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
@@ -25,22 +29,16 @@ namespace MediaBrowser.Controller.Entities
public DateTime DateModified { get; set; }
public int Width { get; set; }
+
public int Height { get; set; }
- [IgnoreDataMember]
- public bool IsLocalFile
- {
- get
- {
- if (Path != null)
- {
- if (Path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- }
- return true;
- }
- }
+ /// <summary>
+ /// Gets or sets the blurhash.
+ /// </summary>
+ /// <value>The blurhash.</value>
+ public string BlurHash { get; set; }
+
+ [JsonIgnore]
+ public bool IsLocalFile => Path == null || !Path.StartsWith("http", StringComparison.OrdinalIgnoreCase);
}
}
diff --git a/MediaBrowser.Controller/Entities/LinkedChild.cs b/MediaBrowser.Controller/Entities/LinkedChild.cs
index bb2d03246..fd5fef3dc 100644
--- a/MediaBrowser.Controller/Entities/LinkedChild.cs
+++ b/MediaBrowser.Controller/Entities/LinkedChild.cs
@@ -1,21 +1,31 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Generic;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
+using System.Globalization;
+using System.Text.Json.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class LinkedChild
{
+ public LinkedChild()
+ {
+ Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ }
+
public string Path { get; set; }
+
public LinkedChildType Type { get; set; }
+
public string LibraryItemId { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string Id { get; set; }
/// <summary>
- /// Serves as a cache
+ /// Gets or sets the linked item id.
/// </summary>
public Guid? ItemId { get; set; }
@@ -29,45 +39,10 @@ namespace MediaBrowser.Controller.Entities
if (string.IsNullOrEmpty(child.Path))
{
- child.LibraryItemId = item.Id.ToString("N");
+ child.LibraryItemId = item.Id.ToString("N", CultureInfo.InvariantCulture);
}
return child;
}
-
- public LinkedChild()
- {
- Id = Guid.NewGuid().ToString("N");
- }
- }
-
- public enum LinkedChildType
- {
- Manual = 0,
- Shortcut = 1
- }
-
- public class LinkedChildComparer : IEqualityComparer<LinkedChild>
- {
- private readonly IFileSystem _fileSystem;
-
- public LinkedChildComparer(IFileSystem fileSystem)
- {
- _fileSystem = fileSystem;
- }
-
- public bool Equals(LinkedChild x, LinkedChild y)
- {
- if (x.Type == y.Type)
- {
- return _fileSystem.AreEqual(x.Path, y.Path);
- }
- return false;
- }
-
- public int GetHashCode(LinkedChild obj)
- {
- return ((obj.Path ?? string.Empty) + (obj.LibraryItemId ?? string.Empty) + obj.Type).GetHashCode();
- }
}
}
diff --git a/MediaBrowser.Controller/Entities/LinkedChildComparer.cs b/MediaBrowser.Controller/Entities/LinkedChildComparer.cs
new file mode 100644
index 000000000..4e58e2942
--- /dev/null
+++ b/MediaBrowser.Controller/Entities/LinkedChildComparer.cs
@@ -0,0 +1,35 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.IO;
+
+namespace MediaBrowser.Controller.Entities
+{
+ public class LinkedChildComparer : IEqualityComparer<LinkedChild>
+ {
+ private readonly IFileSystem _fileSystem;
+
+ public LinkedChildComparer(IFileSystem fileSystem)
+ {
+ _fileSystem = fileSystem;
+ }
+
+ public bool Equals(LinkedChild x, LinkedChild y)
+ {
+ if (x.Type == y.Type)
+ {
+ return _fileSystem.AreEqual(x.Path, y.Path);
+ }
+
+ return false;
+ }
+
+ public int GetHashCode(LinkedChild obj)
+ {
+ return ((obj.Path ?? string.Empty) + (obj.LibraryItemId ?? string.Empty) + obj.Type).GetHashCode(StringComparison.Ordinal);
+ }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Entities/LinkedChildType.cs b/MediaBrowser.Controller/Entities/LinkedChildType.cs
new file mode 100644
index 000000000..9ddb7b620
--- /dev/null
+++ b/MediaBrowser.Controller/Entities/LinkedChildType.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Controller.Entities
+{
+ /// <summary>
+ /// The linked child type.
+ /// </summary>
+ public enum LinkedChildType
+ {
+ /// <summary>
+ /// Manually linked child.
+ /// </summary>
+ Manual = 0,
+
+ /// <summary>
+ /// Shortcut linked child.
+ /// </summary>
+ Shortcut = 1
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
index 124a943ef..e46f99cd5 100644
--- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
+++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
@@ -1,40 +1,47 @@
+#nullable disable
+
+#pragma warning disable CA1721, CA1819, CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
namespace MediaBrowser.Controller.Entities.Movies
{
/// <summary>
- /// Class BoxSet
+ /// Class BoxSet.
/// </summary>
public class BoxSet : Folder, IHasTrailers, IHasDisplayOrder, IHasLookupInfo<BoxSetInfo>
{
public BoxSet()
{
- RemoteTrailers = EmptyMediaUrlArray;
+ RemoteTrailers = Array.Empty<MediaUrl>();
LocalTrailerIds = Array.Empty<Guid>();
RemoteTrailerIds = Array.Empty<Guid>();
DisplayOrder = ItemSortBy.PremiereDate;
}
- [IgnoreDataMember]
+ [JsonIgnore]
protected override bool FilterLinkedChildrenPerUser => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPeople => true;
- public Guid[] LocalTrailerIds { get; set; }
- public Guid[] RemoteTrailerIds { get; set; }
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> LocalTrailerIds { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
/// <summary>
/// Gets or sets the display order.
@@ -42,9 +49,33 @@ namespace MediaBrowser.Controller.Entities.Movies
/// <value>The display order.</value>
public string DisplayOrder { get; set; }
- protected override bool GetBlockUnratedValue(UserPolicy config)
+ [JsonIgnore]
+ private bool IsLegacyBoxSet
+ {
+ get
+ {
+ if (string.IsNullOrEmpty(Path))
+ {
+ return false;
+ }
+
+ if (LinkedChildren.Length > 0)
+ {
+ return false;
+ }
+
+ return !FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.DataPath, Path);
+ }
+ }
+
+ [JsonIgnore]
+ public override bool IsPreSorted => true;
+
+ public Guid[] LibraryFolderIds { get; set; }
+
+ protected override bool GetBlockUnratedValue(User user)
{
- return config.BlockUnratedItems.Contains(UnratedItem.Movie);
+ return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Movie);
}
public override double GetDefaultPrimaryImageAspectRatio()
@@ -61,7 +92,8 @@ namespace MediaBrowser.Controller.Entities.Movies
{
return base.GetNonCachedChildren(directoryService);
}
- return new List<BaseItem>();
+
+ return Enumerable.Empty<BaseItem>();
}
protected override List<BaseItem> LoadChildren()
@@ -75,28 +107,6 @@ namespace MediaBrowser.Controller.Entities.Movies
return new List<BaseItem>();
}
- [IgnoreDataMember]
- private bool IsLegacyBoxSet
- {
- get
- {
- if (string.IsNullOrEmpty(Path))
- {
- return false;
- }
-
- if (LinkedChildren.Length > 0)
- {
- return false;
- }
-
- return !FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.DataPath, Path);
- }
- }
-
- [IgnoreDataMember]
- public override bool IsPreSorted => true;
-
public override bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
{
return true;
@@ -183,8 +193,6 @@ namespace MediaBrowser.Controller.Entities.Movies
return IsVisible(user);
}
- public Guid[] LibraryFolderIds { get; set; }
-
private Guid[] GetLibraryFolderIds(User user)
{
return LibraryManager.GetUserRootFolder().GetChildren(user, true)
@@ -194,7 +202,7 @@ namespace MediaBrowser.Controller.Entities.Movies
public Guid[] GetLibraryFolderIds()
{
- var expandedFolders = new List<Guid>() { };
+ var expandedFolders = new List<Guid>();
return FlattenItems(this, expandedFolders)
.SelectMany(i => LibraryManager.GetCollectionFolders(i))
@@ -211,8 +219,7 @@ namespace MediaBrowser.Controller.Entities.Movies
private IEnumerable<BaseItem> FlattenItems(BaseItem item, List<Guid> expandedFolders)
{
- var boxset = item as BoxSet;
- if (boxset != null)
+ if (item is BoxSet boxset)
{
if (!expandedFolders.Contains(item.Id))
{
diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs
index 232d11624..b54bbf5eb 100644
--- a/MediaBrowser.Controller/Entities/Movies/Movie.cs
+++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs
@@ -1,34 +1,43 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities.Movies
{
/// <summary>
- /// Class Movie
+ /// Class Movie.
/// </summary>
public class Movie : Video, IHasSpecialFeatures, IHasTrailers, IHasLookupInfo<MovieInfo>, ISupportsBoxSetGrouping
{
- public Guid[] SpecialFeatureIds { get; set; }
-
public Movie()
{
- SpecialFeatureIds = new Guid[] { };
- RemoteTrailers = EmptyMediaUrlArray;
- LocalTrailerIds = new Guid[] { };
- RemoteTrailerIds = new Guid[] { };
+ SpecialFeatureIds = Array.Empty<Guid>();
+ RemoteTrailers = Array.Empty<MediaUrl>();
+ LocalTrailerIds = Array.Empty<Guid>();
+ RemoteTrailerIds = Array.Empty<Guid>();
}
- public Guid[] LocalTrailerIds { get; set; }
- public Guid[] RemoteTrailerIds { get; set; }
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> SpecialFeatureIds { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> LocalTrailerIds { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
/// <summary>
/// Gets or sets the name of the TMDB collection.
@@ -36,13 +45,16 @@ namespace MediaBrowser.Controller.Entities.Movies
/// <value>The name of the TMDB collection.</value>
public string TmdbCollectionName { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string CollectionName
{
get => TmdbCollectionName;
set => TmdbCollectionName = value;
}
+ [JsonIgnore]
+ public override bool StopRefreshIfLocalMetadataFound => false;
+
public override double GetDefaultPrimaryImageAspectRatio()
{
// hack for tv plugins
@@ -102,6 +114,7 @@ namespace MediaBrowser.Controller.Entities.Movies
return itemsChanged;
}
+ /// <inheritdoc />
public override UnratedItem GetBlockUnratedType()
{
return UnratedItem.Movie;
@@ -130,9 +143,10 @@ namespace MediaBrowser.Controller.Entities.Movies
return info;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <inheritdoc />
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (!ProductionYear.HasValue)
{
@@ -166,24 +180,22 @@ namespace MediaBrowser.Controller.Entities.Movies
return hasChanges;
}
+ /// <inheritdoc />
public override List<ExternalUrl> GetRelatedUrls()
{
var list = base.GetRelatedUrls();
- var imdbId = this.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
list.Add(new ExternalUrl
{
Name = "Trakt",
- Url = string.Format("https://trakt.tv/movies/{0}", imdbId)
+ Url = string.Format(CultureInfo.InvariantCulture, "https://trakt.tv/movies/{0}", imdbId)
});
}
return list;
}
-
- [IgnoreDataMember]
- public override bool StopRefreshIfLocalMetadataFound => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs
index 5bf082b7e..237ad5198 100644
--- a/MediaBrowser.Controller/Entities/MusicVideo.cs
+++ b/MediaBrowser.Controller/Entities/MusicVideo.cs
@@ -1,23 +1,26 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class MusicVideo : Video, IHasArtist, IHasMusicGenres, IHasLookupInfo<MusicVideoInfo>
{
- [IgnoreDataMember]
- public string[] Artists { get; set; }
-
public MusicVideo()
{
Artists = Array.Empty<string>();
}
- [IgnoreDataMember]
- public string[] AllArtists => Artists;
+ /// <inheritdoc />
+ [JsonIgnore]
+ public IReadOnlyList<string> Artists { get; set; }
public override UnratedItem GetBlockUnratedType()
{
@@ -33,9 +36,9 @@ namespace MediaBrowser.Controller.Entities
return info;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (!ProductionYear.HasValue)
{
diff --git a/MediaBrowser.Controller/Entities/PeopleHelper.cs b/MediaBrowser.Controller/Entities/PeopleHelper.cs
index 2fb613768..687ce1ec8 100644
--- a/MediaBrowser.Controller/Entities/PeopleHelper.cs
+++ b/MediaBrowser.Controller/Entities/PeopleHelper.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -98,22 +100,5 @@ namespace MediaBrowser.Controller.Entities
existing.SetProviderId(id.Key, id.Value);
}
}
-
- public static bool ContainsPerson(List<PersonInfo> people, string name)
- {
- if (string.IsNullOrEmpty(name))
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- foreach (var i in people)
- {
- if (string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
- return false;
- }
}
}
diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs
index dd0183489..045c1b89f 100644
--- a/MediaBrowser.Controller/Entities/Person.cs
+++ b/MediaBrowser.Controller/Entities/Person.cs
@@ -1,9 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using MediaBrowser.Controller.Extensions;
+using System.Text.Json.Serialization;
+using Diacritics.Extensions;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
@@ -13,6 +16,26 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
public class Person : BaseItem, IItemByName, IHasLookupInfo<PersonLookupInfo>
{
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ /// <summary>
+ /// Gets a value indicating whether to enable alpha numeric sorting.
+ /// </summary>
+ [JsonIgnore]
+ public override bool EnableAlphaNumericSorting => false;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
@@ -20,6 +43,7 @@ namespace MediaBrowser.Controller.Entities
list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics());
return list;
}
+
public override string CreatePresentationUniqueKey()
{
return GetUserDataKeys()[0];
@@ -45,14 +69,6 @@ namespace MediaBrowser.Controller.Entities
return LibraryManager.GetItemList(query);
}
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
public override bool CanDelete()
{
return false;
@@ -63,15 +79,6 @@ namespace MediaBrowser.Controller.Entities
return true;
}
- [IgnoreDataMember]
- public override bool EnableAlphaNumericSorting => false;
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
public static string GetPath(string name)
{
return GetPath(name, true);
@@ -115,15 +122,18 @@ namespace MediaBrowser.Controller.Entities
Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true or false indicating if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata"><c>true</c> to replace all metadata, <c>false</c> to not.</param>
+ /// <returns><c>true</c> if changes were made, <c>false</c> if not.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
@@ -135,57 +145,4 @@ namespace MediaBrowser.Controller.Entities
return hasChanges;
}
}
-
- /// <summary>
- /// This is the small Person stub that is attached to BaseItems
- /// </summary>
- public class PersonInfo : IHasProviderIds
- {
- public PersonInfo()
- {
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
-
- public Guid ItemId { get; set; }
-
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets the role.
- /// </summary>
- /// <value>The role.</value>
- public string Role { get; set; }
- /// <summary>
- /// Gets or sets the type.
- /// </summary>
- /// <value>The type.</value>
- public string Type { get; set; }
-
- /// <summary>
- /// Gets or sets the sort order - ascending
- /// </summary>
- /// <value>The sort order.</value>
- public int? SortOrder { get; set; }
-
- public string ImageUrl { get; set; }
-
- public Dictionary<string, string> ProviderIds { get; set; }
-
- /// <summary>
- /// Returns a <see cref="string" /> that represents this instance.
- /// </summary>
- /// <returns>A <see cref="string" /> that represents this instance.</returns>
- public override string ToString()
- {
- return Name;
- }
-
- public bool IsType(string type)
- {
- return string.Equals(Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(Role, type, StringComparison.OrdinalIgnoreCase);
- }
- }
}
diff --git a/MediaBrowser.Controller/Entities/PersonInfo.cs b/MediaBrowser.Controller/Entities/PersonInfo.cs
new file mode 100644
index 000000000..2b689ae7e
--- /dev/null
+++ b/MediaBrowser.Controller/Entities/PersonInfo.cs
@@ -0,0 +1,66 @@
+#nullable disable
+
+#pragma warning disable CA2227, CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Entities;
+
+namespace MediaBrowser.Controller.Entities
+{
+ /// <summary>
+ /// This is a small Person stub that is attached to BaseItems.
+ /// </summary>
+ public sealed class PersonInfo : IHasProviderIds
+ {
+ public PersonInfo()
+ {
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
+ public Guid ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the role.
+ /// </summary>
+ /// <value>The role.</value>
+ public string Role { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type.
+ /// </summary>
+ /// <value>The type.</value>
+ public string Type { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ascending sort order.
+ /// </summary>
+ /// <value>The sort order.</value>
+ public int? SortOrder { get; set; }
+
+ public string ImageUrl { get; set; }
+
+ public Dictionary<string, string> ProviderIds { get; set; }
+
+ /// <summary>
+ /// Returns a <see cref="string" /> that represents this instance.
+ /// </summary>
+ /// <returns>A <see cref="string" /> that represents this instance.</returns>
+ public override string ToString()
+ {
+ return Name;
+ }
+
+ public bool IsType(string type)
+ {
+ return string.Equals(Type, type, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(Role, type, StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs
index 60c832189..ba6ce189a 100644
--- a/MediaBrowser.Controller/Entities/Photo.cs
+++ b/MediaBrowser.Controller/Entities/Photo.cs
@@ -1,21 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Text.Json.Serialization;
using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class Photo : BaseItem
{
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsLocalMetadata => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override string MediaType => Model.Entities.MediaType.Photo;
- [IgnoreDataMember]
+ [JsonIgnore]
public override Folder LatestItemsIndexContainer => AlbumEntity;
-
- [IgnoreDataMember]
+ [JsonIgnore]
public PhotoAlbum AlbumEntity
{
get
@@ -23,16 +26,40 @@ namespace MediaBrowser.Controller.Entities
var parents = GetParents();
foreach (var parent in parents)
{
- var photoAlbum = parent as PhotoAlbum;
- if (photoAlbum != null)
+ if (parent is PhotoAlbum photoAlbum)
{
return photoAlbum;
}
}
+
return null;
}
}
+ public string CameraMake { get; set; }
+
+ public string CameraModel { get; set; }
+
+ public string Software { get; set; }
+
+ public double? ExposureTime { get; set; }
+
+ public double? FocalLength { get; set; }
+
+ public ImageOrientation? Orientation { get; set; }
+
+ public double? Aperture { get; set; }
+
+ public double? ShutterSpeed { get; set; }
+
+ public double? Latitude { get; set; }
+
+ public double? Longitude { get; set; }
+
+ public double? Altitude { get; set; }
+
+ public int? IsoSpeedRating { get; set; }
+
public override bool CanDownload()
{
return true;
@@ -41,10 +68,10 @@ namespace MediaBrowser.Controller.Entities
public override double GetDefaultPrimaryImageAspectRatio()
{
// REVIEW: @bond
- if (Width.HasValue && Height.HasValue)
+ if (Width != 0 && Height != 0)
{
- double width = Width.Value;
- double height = Height.Value;
+ double width = Width;
+ double height = Height;
if (Orientation.HasValue)
{
@@ -66,21 +93,5 @@ namespace MediaBrowser.Controller.Entities
return base.GetDefaultPrimaryImageAspectRatio();
}
-
- public new int? Width { get; set; }
- public new int? Height { get; set; }
- public string CameraMake { get; set; }
- public string CameraModel { get; set; }
- public string Software { get; set; }
- public double? ExposureTime { get; set; }
- public double? FocalLength { get; set; }
- public ImageOrientation? Orientation { get; set; }
- public double? Aperture { get; set; }
- public double? ShutterSpeed { get; set; }
-
- public double? Latitude { get; set; }
- public double? Longitude { get; set; }
- public double? Altitude { get; set; }
- public int? IsoSpeedRating { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/PhotoAlbum.cs b/MediaBrowser.Controller/Entities/PhotoAlbum.cs
index 4cd0c8b66..a7ecb9061 100644
--- a/MediaBrowser.Controller/Entities/PhotoAlbum.cs
+++ b/MediaBrowser.Controller/Entities/PhotoAlbum.cs
@@ -1,16 +1,18 @@
-using MediaBrowser.Model.Serialization;
+#pragma warning disable CS1591
+
+using System.Text.Json.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class PhotoAlbum : Folder
{
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool AlwaysScanInternalMetadataPath => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/Share.cs b/MediaBrowser.Controller/Entities/Share.cs
index c17789ccc..64f446eef 100644
--- a/MediaBrowser.Controller/Entities/Share.cs
+++ b/MediaBrowser.Controller/Entities/Share.cs
@@ -1,13 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Entities
{
- public interface IHasShares
- {
- Share[] Shares { get; set; }
- }
-
public class Share
{
public string UserId { get; set; }
+
public bool CanEdit { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/SourceType.cs b/MediaBrowser.Controller/Entities/SourceType.cs
index 927483b93..be19e1bda 100644
--- a/MediaBrowser.Controller/Entities/SourceType.cs
+++ b/MediaBrowser.Controller/Entities/SourceType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Entities
{
public enum SourceType
diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs
index d6da0d48c..c8feb1c94 100644
--- a/MediaBrowser.Controller/Entities/Studio.cs
+++ b/MediaBrowser.Controller/Entities/Studio.cs
@@ -1,16 +1,37 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Serialization;
+using System.Text.Json.Serialization;
+using Diacritics.Extensions;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Studio
+ /// Class Studio.
/// </summary>
public class Studio : BaseItem, IItemByName
{
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ [JsonIgnore]
+ public override bool IsDisplayedAsFolder => true;
+
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
@@ -18,25 +39,12 @@ namespace MediaBrowser.Controller.Entities
list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics());
return list;
}
+
public override string CreatePresentationUniqueKey()
{
return GetUserDataKeys()[0];
}
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
- [IgnoreDataMember]
- public override bool IsDisplayedAsFolder => true;
-
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
public override double GetDefaultPrimaryImageAspectRatio()
{
double value = 16;
@@ -62,9 +70,6 @@ namespace MediaBrowser.Controller.Entities
return LibraryManager.GetItemList(query);
}
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
public static string GetPath(string name)
{
return GetPath(name, true);
@@ -93,15 +98,18 @@ namespace MediaBrowser.Controller.Entities
Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true or false indicating if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata"><c>true</c> to replace all metadata, <c>false</c> to not.</param>
+ /// <returns><c>true</c> if changes were made, <c>false</c> if not.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs
index 072b1d89a..27c3ff81b 100644
--- a/MediaBrowser.Controller/Entities/TV/Episode.cs
+++ b/MediaBrowser.Controller/Entities/TV/Episode.cs
@@ -1,107 +1,80 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.TV
{
/// <summary>
- /// Class Episode
+ /// Class Episode.
/// </summary>
public class Episode : Video, IHasTrailers, IHasLookupInfo<EpisodeInfo>, IHasSeries
{
public Episode()
{
- RemoteTrailers = EmptyMediaUrlArray;
+ RemoteTrailers = Array.Empty<MediaUrl>();
LocalTrailerIds = Array.Empty<Guid>();
RemoteTrailerIds = Array.Empty<Guid>();
}
- public Guid[] LocalTrailerIds { get; set; }
- public Guid[] RemoteTrailerIds { get; set; }
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> LocalTrailerIds { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
/// <summary>
- /// Gets the season in which it aired.
+ /// Gets or sets the season in which it aired.
/// </summary>
/// <value>The aired season.</value>
public int? AirsBeforeSeasonNumber { get; set; }
+
public int? AirsAfterSeasonNumber { get; set; }
+
public int? AirsBeforeEpisodeNumber { get; set; }
/// <summary>
- /// This is the ending episode number for double episodes.
+ /// Gets or sets the ending episode number for double episodes.
/// </summary>
/// <value>The index number.</value>
public int? IndexNumberEnd { get; set; }
- public string FindSeriesSortName()
- {
- var series = Series;
- return series == null ? SeriesName : series.SortName;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
protected override bool SupportsOwnedItems => IsStacked || MediaSourceCount > 1;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPeople => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public int? AiredSeasonNumber => AirsAfterSeasonNumber ?? AirsBeforeSeasonNumber ?? ParentIndexNumber;
- [IgnoreDataMember]
+ [JsonIgnore]
public override Folder LatestItemsIndexContainer => Series;
- [IgnoreDataMember]
+ [JsonIgnore]
public override Guid DisplayParentId => SeasonId;
- [IgnoreDataMember]
+ [JsonIgnore]
protected override bool EnableDefaultVideoUserDataKeys => false;
- public override double GetDefaultPrimaryImageAspectRatio()
- {
- // hack for tv plugins
- if (SourceType == SourceType.Channel)
- {
- return 0;
- }
-
- return 16.0 / 9;
- }
-
- public override List<string> GetUserDataKeys()
- {
- var list = base.GetUserDataKeys();
-
- var series = Series;
- if (series != null && ParentIndexNumber.HasValue && IndexNumber.HasValue)
- {
- var seriesUserDataKeys = series.GetUserDataKeys();
- var take = seriesUserDataKeys.Count;
- if (seriesUserDataKeys.Count > 1)
- {
- take--;
- }
- list.InsertRange(0, seriesUserDataKeys.Take(take).Select(i => i + ParentIndexNumber.Value.ToString("000") + IndexNumber.Value.ToString("000")));
- }
-
- return list;
- }
-
/// <summary>
- /// This Episode's Series Instance
+ /// Gets the Episode's Series Instance.
/// </summary>
/// <value>The series.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public Series Series
{
get
@@ -111,11 +84,12 @@ namespace MediaBrowser.Controller.Entities.TV
{
seriesId = FindSeriesId();
}
+
return !seriesId.Equals(Guid.Empty) ? (LibraryManager.GetItemById(seriesId) as Series) : null;
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public Season Season
{
get
@@ -125,22 +99,91 @@ namespace MediaBrowser.Controller.Entities.TV
{
seasonId = FindSeasonId();
}
+
return !seasonId.Equals(Guid.Empty) ? (LibraryManager.GetItemById(seasonId) as Season) : null;
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsInSeasonFolder => FindParent<Season>() != null;
- [IgnoreDataMember]
+ [JsonIgnore]
public string SeriesPresentationUniqueKey { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string SeriesName { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string SeasonName { get; set; }
+ [JsonIgnore]
+ public override bool SupportsRemoteImageDownloading
+ {
+ get
+ {
+ if (IsMissingEpisode)
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ [JsonIgnore]
+ public bool IsMissingEpisode => LocationType == LocationType.Virtual;
+
+ [JsonIgnore]
+ public Guid SeasonId { get; set; }
+
+ [JsonIgnore]
+ public Guid SeriesId { get; set; }
+
+ public string FindSeriesSortName()
+ {
+ var series = Series;
+ return series == null ? SeriesName : series.SortName;
+ }
+
+ public override double GetDefaultPrimaryImageAspectRatio()
+ {
+ // hack for tv plugins
+ if (SourceType == SourceType.Channel)
+ {
+ return 0;
+ }
+
+ return 16.0 / 9;
+ }
+
+ public override List<string> GetUserDataKeys()
+ {
+ var list = base.GetUserDataKeys();
+
+ var series = Series;
+ if (series != null && ParentIndexNumber.HasValue && IndexNumber.HasValue)
+ {
+ var seriesUserDataKeys = series.GetUserDataKeys();
+ var take = seriesUserDataKeys.Count;
+ if (seriesUserDataKeys.Count > 1)
+ {
+ take--;
+ }
+
+ var newList = seriesUserDataKeys.GetRange(0, take);
+ var suffix = ParentIndexNumber.Value.ToString("000", CultureInfo.InvariantCulture) + IndexNumber.Value.ToString("000", CultureInfo.InvariantCulture);
+ for (int i = 0; i < take; i++)
+ {
+ newList[i] = newList[i] + suffix;
+ }
+
+ newList.AddRange(list);
+ list = newList;
+ }
+
+ return list;
+ }
+
public string FindSeriesPresentationUniqueKey()
{
var series = Series;
@@ -157,6 +200,7 @@ namespace MediaBrowser.Controller.Entities.TV
{
return "Season " + ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture);
}
+
return "Season Unknown";
}
@@ -197,8 +241,8 @@ namespace MediaBrowser.Controller.Entities.TV
/// <returns>System.String.</returns>
protected override string CreateSortName()
{
- return (ParentIndexNumber != null ? ParentIndexNumber.Value.ToString("000 - ") : "")
- + (IndexNumber != null ? IndexNumber.Value.ToString("0000 - ") : "") + Name;
+ return (ParentIndexNumber != null ? ParentIndexNumber.Value.ToString("000 - ", CultureInfo.InvariantCulture) : string.Empty)
+ + (IndexNumber != null ? IndexNumber.Value.ToString("0000 - ", CultureInfo.InvariantCulture) : string.Empty) + Name;
}
/// <summary>
@@ -221,28 +265,6 @@ namespace MediaBrowser.Controller.Entities.TV
return false;
}
- [IgnoreDataMember]
- public override bool SupportsRemoteImageDownloading
- {
- get
- {
- if (IsMissingEpisode)
- {
- return false;
- }
-
- return true;
- }
- }
-
- [IgnoreDataMember]
- public bool IsMissingEpisode => LocationType == LocationType.Virtual;
-
- [IgnoreDataMember]
- public Guid SeasonId { get; set; }
- [IgnoreDataMember]
- public Guid SeriesId { get; set; }
-
public Guid FindSeriesId()
{
var series = FindParent<Series>();
@@ -265,7 +287,8 @@ namespace MediaBrowser.Controller.Entities.TV
public override IEnumerable<FileSystemMetadata> GetDeletePaths()
{
- return new[] {
+ return new[]
+ {
new FileSystemMetadata
{
FullName = Path,
@@ -297,9 +320,9 @@ namespace MediaBrowser.Controller.Entities.TV
return id;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (!IsLocked)
{
@@ -307,7 +330,7 @@ namespace MediaBrowser.Controller.Entities.TV
{
try
{
- if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetdata))
+ if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetadata))
{
hasChanges = true;
}
diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs
index 5d7c260d1..926c7b045 100644
--- a/MediaBrowser.Controller/Entities/TV/Season.cs
+++ b/MediaBrowser.Controller/Entities/TV/Season.cs
@@ -1,38 +1,87 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
namespace MediaBrowser.Controller.Entities.TV
{
/// <summary>
- /// Class Season
+ /// Class Season.
/// </summary>
public class Season : Folder, IHasSeries, IHasLookupInfo<SeasonInfo>
{
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsPreSorted => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsDateLastMediaAdded => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPeople => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override Guid DisplayParentId => SeriesId;
+ /// <summary>
+ /// Gets this Episode's Series Instance.
+ /// </summary>
+ /// <value>The series.</value>
+ [JsonIgnore]
+ public Series Series
+ {
+ get
+ {
+ var seriesId = SeriesId;
+ if (seriesId == Guid.Empty)
+ {
+ seriesId = FindSeriesId();
+ }
+
+ return seriesId == Guid.Empty ? null : (LibraryManager.GetItemById(seriesId) as Series);
+ }
+ }
+
+ [JsonIgnore]
+ public string SeriesPath
+ {
+ get
+ {
+ var series = Series;
+
+ if (series != null)
+ {
+ return series.Path;
+ }
+
+ return System.IO.Path.GetDirectoryName(Path);
+ }
+ }
+
+ [JsonIgnore]
+ public string SeriesPresentationUniqueKey { get; set; }
+
+ [JsonIgnore]
+ public string SeriesName { get; set; }
+
+ [JsonIgnore]
+ public Guid SeriesId { get; set; }
+
public override double GetDefaultPrimaryImageAspectRatio()
{
double value = 2;
@@ -54,7 +103,15 @@ namespace MediaBrowser.Controller.Entities.TV
var series = Series;
if (series != null)
{
- list.InsertRange(0, series.GetUserDataKeys().Select(i => i + (IndexNumber ?? 0).ToString("000")));
+ var newList = series.GetUserDataKeys();
+ var suffix = (IndexNumber ?? 0).ToString("000", CultureInfo.InvariantCulture);
+ for (int i = 0; i < newList.Count; i++)
+ {
+ newList[i] = newList[i] + suffix;
+ }
+
+ newList.AddRange(list);
+ list = newList;
}
return list;
@@ -67,40 +124,6 @@ namespace MediaBrowser.Controller.Entities.TV
return result;
}
- /// <summary>
- /// This Episode's Series Instance
- /// </summary>
- /// <value>The series.</value>
- [IgnoreDataMember]
- public Series Series
- {
- get
- {
- var seriesId = SeriesId;
- if (seriesId == Guid.Empty)
- {
- seriesId = FindSeriesId();
- }
- return seriesId == Guid.Empty ? null : (LibraryManager.GetItemById(seriesId) as Series);
- }
- }
-
- [IgnoreDataMember]
- public string SeriesPath
- {
- get
- {
- var series = Series;
-
- if (series != null)
- {
- return series.Path;
- }
-
- return System.IO.Path.GetDirectoryName(Path);
- }
- }
-
public override string CreatePresentationUniqueKey()
{
if (IndexNumber.HasValue)
@@ -108,7 +131,7 @@ namespace MediaBrowser.Controller.Entities.TV
var series = Series;
if (series != null)
{
- return series.PresentationUniqueKey + "-" + (IndexNumber ?? 0).ToString("000");
+ return series.PresentationUniqueKey + "-" + (IndexNumber ?? 0).ToString("000", CultureInfo.InvariantCulture);
}
}
@@ -121,7 +144,7 @@ namespace MediaBrowser.Controller.Entities.TV
/// <returns>System.String.</returns>
protected override string CreateSortName()
{
- return IndexNumber != null ? IndexNumber.Value.ToString("0000") : Name;
+ return IndexNumber != null ? IndexNumber.Value.ToString("0000", CultureInfo.InvariantCulture) : Name;
}
protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
@@ -143,6 +166,9 @@ namespace MediaBrowser.Controller.Entities.TV
/// <summary>
/// Gets the episodes.
/// </summary>
+ /// <param name="user">The user.</param>
+ /// <param name="options">The options to use.</param>
+ /// <returns>Set of episodes.</returns>
public List<BaseItem> GetEpisodes(User user, DtoOptions options)
{
return GetEpisodes(Series, user, options);
@@ -168,7 +194,7 @@ namespace MediaBrowser.Controller.Entities.TV
return GetEpisodes(user, new DtoOptions(true));
}
- protected override bool GetBlockUnratedValue(UserPolicy config)
+ protected override bool GetBlockUnratedValue(User user)
{
// Don't block. Let either the entire series rating or episode rating determine it
return false;
@@ -179,15 +205,6 @@ namespace MediaBrowser.Controller.Entities.TV
return UnratedItem.Series;
}
- [IgnoreDataMember]
- public string SeriesPresentationUniqueKey { get; set; }
-
- [IgnoreDataMember]
- public string SeriesName { get; set; }
-
- [IgnoreDataMember]
- public Guid SeriesId { get; set; }
-
public string FindSeriesPresentationUniqueKey()
{
var series = Series;
@@ -203,7 +220,7 @@ namespace MediaBrowser.Controller.Entities.TV
public Guid FindSeriesId()
{
var series = FindParent<Series>();
- return series == null ? Guid.Empty : series.Id;
+ return series?.Id ?? Guid.Empty;
}
/// <summary>
@@ -225,16 +242,17 @@ namespace MediaBrowser.Controller.Entities.TV
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true or false indicating if changes were made.
/// </summary>
+ /// <param name="replaceAllMetadata"><c>true</c> to replace metdata, <c>false</c> to not.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (!IndexNumber.HasValue && !string.IsNullOrEmpty(Path))
{
- IndexNumber = IndexNumber ?? LibraryManager.GetSeasonNumberFromPath(Path);
+ IndexNumber ??= LibraryManager.GetSeasonNumberFromPath(Path);
// If a change was made record it
if (IndexNumber.HasValue)
diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs
index 570e9389e..e4933e968 100644
--- a/MediaBrowser.Controller/Entities/TV/Series.cs
+++ b/MediaBrowser.Controller/Entities/TV/Series.cs
@@ -1,57 +1,69 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
+using MetadataProvider = MediaBrowser.Model.Entities.MetadataProvider;
namespace MediaBrowser.Controller.Entities.TV
{
/// <summary>
- /// Class Series
+ /// Class Series.
/// </summary>
public class Series : Folder, IHasTrailers, IHasDisplayOrder, IHasLookupInfo<SeriesInfo>, IMetadataContainer
{
public Series()
{
- RemoteTrailers = EmptyMediaUrlArray;
+ RemoteTrailers = Array.Empty<MediaUrl>();
LocalTrailerIds = Array.Empty<Guid>();
RemoteTrailerIds = Array.Empty<Guid>();
AirDays = Array.Empty<DayOfWeek>();
}
public DayOfWeek[] AirDays { get; set; }
+
public string AirTime { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool IsPreSorted => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsDateLastMediaAdded => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPeople => true;
- public Guid[] LocalTrailerIds { get; set; }
- public Guid[] RemoteTrailerIds { get; set; }
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> LocalTrailerIds { get; set; }
+
+ /// <inheritdoc />
+ public IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
/// <summary>
- /// airdate, dvd or absolute
+ /// Gets or sets the display order.
/// </summary>
+ /// <remarks>
+ /// Valid options are airdate, dvd or absolute.
+ /// </remarks>
public string DisplayOrder { get; set; }
/// <summary>
@@ -60,6 +72,9 @@ namespace MediaBrowser.Controller.Entities.TV
/// <value>The status.</value>
public SeriesStatus? Status { get; set; }
+ [JsonIgnore]
+ public override bool StopRefreshIfLocalMetadataFound => false;
+
public override double GetDefaultPrimaryImageAspectRatio()
{
double value = 2;
@@ -92,7 +107,7 @@ namespace MediaBrowser.Controller.Entities.TV
}
var folders = LibraryManager.GetCollectionFolders(this)
- .Select(i => i.Id.ToString("N"))
+ .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.ToArray();
if (folders.Length == 0)
@@ -100,7 +115,7 @@ namespace MediaBrowser.Controller.Entities.TV
return key;
}
- return key + "-" + string.Join("-", folders);
+ return key + "-" + string.Join('-', folders);
}
private static string GetUniqueSeriesKey(BaseItem series)
@@ -116,7 +131,7 @@ namespace MediaBrowser.Controller.Entities.TV
{
AncestorWithPresentationUniqueKey = null,
SeriesPresentationUniqueKey = seriesKey,
- IncludeItemTypes = new[] { typeof(Season).Name },
+ IncludeItemTypes = new[] { nameof(Season) },
IsVirtualItem = false,
Limit = 0,
DtoOptions = new DtoOptions(false)
@@ -144,8 +159,9 @@ namespace MediaBrowser.Controller.Entities.TV
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
}
+
query.IsVirtualItem = false;
query.Limit = 0;
var totalRecordCount = LibraryManager.GetCount(query);
@@ -161,14 +177,12 @@ namespace MediaBrowser.Controller.Entities.TV
{
var list = base.GetUserDataKeys();
- var key = this.GetProviderId(MetadataProviders.Imdb);
- if (!string.IsNullOrEmpty(key))
+ if (this.TryGetProviderId(MetadataProvider.Imdb, out var key))
{
list.Insert(0, key);
}
- key = this.GetProviderId(MetadataProviders.Tvdb);
- if (!string.IsNullOrEmpty(key))
+ if (this.TryGetProviderId(MetadataProvider.Tvdb, out key))
{
list.Insert(0, key);
}
@@ -199,17 +213,12 @@ namespace MediaBrowser.Controller.Entities.TV
query.AncestorWithPresentationUniqueKey = null;
query.SeriesPresentationUniqueKey = seriesKey;
- query.IncludeItemTypes = new[] { typeof(Season).Name };
- query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray();
+ query.IncludeItemTypes = new[] { nameof(Season) };
+ query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) };
- if (user != null)
+ if (user != null && !user.DisplayMissingEpisodes)
{
- var config = user.Configuration;
-
- if (!config.DisplayMissingEpisodes)
- {
- query.IsMissing = false;
- }
+ query.IsMissing = false;
}
}
@@ -223,14 +232,16 @@ namespace MediaBrowser.Controller.Entities.TV
query.AncestorWithPresentationUniqueKey = null;
query.SeriesPresentationUniqueKey = seriesKey;
- if (query.OrderBy.Length == 0)
+ if (query.OrderBy.Count == 0)
{
- query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray();
+ query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) };
}
+
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode), nameof(Season) };
}
+
query.IsVirtualItem = false;
return LibraryManager.GetItemsResult(query);
}
@@ -248,12 +259,12 @@ namespace MediaBrowser.Controller.Entities.TV
{
AncestorWithPresentationUniqueKey = null,
SeriesPresentationUniqueKey = seriesKey,
- IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name },
- OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
+ IncludeItemTypes = new[] { nameof(Episode), nameof(Season) },
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
DtoOptions = options
};
- var config = user.Configuration;
- if (!config.DisplayMissingEpisodes)
+
+ if (!user.DisplayMissingEpisodes)
{
query.IsMissing = false;
}
@@ -285,7 +296,7 @@ namespace MediaBrowser.Controller.Entities.TV
// Refresh seasons
foreach (var item in items)
{
- if (!(item is Season))
+ if (item is not Season)
{
continue;
}
@@ -306,27 +317,20 @@ namespace MediaBrowser.Controller.Entities.TV
// Refresh episodes and other children
foreach (var item in items)
{
- if ((item is Season))
+ if (item is Season)
{
continue;
}
cancellationToken.ThrowIfCancellationRequested();
- var skipItem = false;
-
- var episode = item as Episode;
-
- if (episode != null
+ bool skipItem = item is Episode episode
&& refreshOptions.MetadataRefreshMode != MetadataRefreshMode.FullRefresh
&& !refreshOptions.ReplaceAllMetadata
&& episode.IsMissingEpisode
&& episode.LocationType == LocationType.Virtual
&& episode.PremiereDate.HasValue
- && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30)
- {
- skipItem = true;
- }
+ && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30;
if (!skipItem)
{
@@ -359,14 +363,13 @@ namespace MediaBrowser.Controller.Entities.TV
{
AncestorWithPresentationUniqueKey = queryFromSeries ? null : seriesKey,
SeriesPresentationUniqueKey = queryFromSeries ? seriesKey : null,
- IncludeItemTypes = new[] { typeof(Episode).Name },
- OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
+ IncludeItemTypes = new[] { nameof(Episode) },
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
DtoOptions = options
};
if (user != null)
{
- var config = user.Configuration;
- if (!config.DisplayMissingEpisodes)
+ if (!user.DisplayMissingEpisodes)
{
query.IsMissing = false;
}
@@ -394,6 +397,10 @@ namespace MediaBrowser.Controller.Entities.TV
/// <summary>
/// Filters the episodes by season.
/// </summary>
+ /// <param name="episodes">The episodes.</param>
+ /// <param name="parentSeason">The season.</param>
+ /// <param name="includeSpecials"><c>true</c> to include special, <c>false</c> to not.</param>
+ /// <returns>The set of episodes.</returns>
public static IEnumerable<BaseItem> FilterEpisodesBySeason(IEnumerable<BaseItem> episodes, Season parentSeason, bool includeSpecials)
{
var seasonNumber = parentSeason.IndexNumber;
@@ -424,6 +431,10 @@ namespace MediaBrowser.Controller.Entities.TV
/// <summary>
/// Filters the episodes by season.
/// </summary>
+ /// <param name="episodes">The episodes.</param>
+ /// <param name="seasonNumber">The season.</param>
+ /// <param name="includeSpecials"><c>true</c> to include special, <c>false</c> to not.</param>
+ /// <returns>The set of episodes.</returns>
public static IEnumerable<Episode> FilterEpisodesBySeason(IEnumerable<Episode> episodes, int seasonNumber, bool includeSpecials)
{
if (!includeSpecials || seasonNumber < 1)
@@ -446,10 +457,9 @@ namespace MediaBrowser.Controller.Entities.TV
});
}
-
- protected override bool GetBlockUnratedValue(UserPolicy config)
+ protected override bool GetBlockUnratedValue(User user)
{
- return config.BlockUnratedItems.Contains(UnratedItem.Series);
+ return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series);
}
public override UnratedItem GetBlockUnratedType()
@@ -488,20 +498,17 @@ namespace MediaBrowser.Controller.Entities.TV
{
var list = base.GetRelatedUrls();
- var imdbId = this.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
list.Add(new ExternalUrl
{
Name = "Trakt",
- Url = string.Format("https://trakt.tv/shows/{0}", imdbId)
+ Url = string.Format(CultureInfo.InvariantCulture, "https://trakt.tv/shows/{0}", imdbId)
});
}
return list;
}
-
- [IgnoreDataMember]
- public override bool StopRefreshIfLocalMetadataFound => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/TagExtensions.cs b/MediaBrowser.Controller/Entities/TagExtensions.cs
index 97f590635..2ce396daf 100644
--- a/MediaBrowser.Controller/Entities/TagExtensions.cs
+++ b/MediaBrowser.Controller/Entities/TagExtensions.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Linq;
diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs
index 5bf22d7bc..1c558d419 100644
--- a/MediaBrowser.Controller/Entities/Trailer.cs
+++ b/MediaBrowser.Controller/Entities/Trailer.cs
@@ -1,15 +1,20 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Trailer
+ /// Class Trailer.
/// </summary>
public class Trailer : Video, IHasLookupInfo<TrailerInfo>
{
@@ -18,6 +23,9 @@ namespace MediaBrowser.Controller.Entities
TrailerTypes = Array.Empty<TrailerType>();
}
+ [JsonIgnore]
+ public override bool StopRefreshIfLocalMetadataFound => false;
+
public TrailerType[] TrailerTypes { get; set; }
public override double GetDefaultPrimaryImageAspectRatio()
@@ -40,9 +48,9 @@ namespace MediaBrowser.Controller.Entities
return info;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (!ProductionYear.HasValue)
{
@@ -80,20 +88,17 @@ namespace MediaBrowser.Controller.Entities
{
var list = base.GetRelatedUrls();
- var imdbId = this.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
list.Add(new ExternalUrl
{
Name = "Trakt",
- Url = string.Format("https://trakt.tv/movies/{0}", imdbId)
+ Url = string.Format(CultureInfo.InvariantCulture, "https://trakt.tv/movies/{0}", imdbId)
});
}
return list;
}
-
- [IgnoreDataMember]
- public override bool StopRefreshIfLocalMetadataFound => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/User.cs b/MediaBrowser.Controller/Entities/User.cs
deleted file mode 100644
index 0d5f508dd..000000000
--- a/MediaBrowser.Controller/Entities/User.cs
+++ /dev/null
@@ -1,297 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
-
-namespace MediaBrowser.Controller.Entities
-{
- /// <summary>
- /// Class User
- /// </summary>
- public class User : BaseItem
- {
- public static IUserManager UserManager { get; set; }
- public static IXmlSerializer XmlSerializer { get; set; }
-
- /// <summary>
- /// From now on all user paths will be Id-based.
- /// This is for backwards compatibility.
- /// </summary>
- public bool UsesIdForConfigurationPath { get; set; }
-
- /// <summary>
- /// Gets or sets the password.
- /// </summary>
- /// <value>The password.</value>
- public string Password { get; set; }
- public string EasyPassword { get; set; }
- public string Salt { get; set; }
-
- // Strictly to remove IgnoreDataMember
- public override ItemImageInfo[] ImageInfos
- {
- get => base.ImageInfos;
- set => base.ImageInfos = value;
- }
-
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- [IgnoreDataMember]
- public override string Path
- {
- get => ConfigurationDirectoryPath;
- set => base.Path = value;
- }
-
- private string _name;
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public override string Name
- {
- get => _name;
- set
- {
- _name = value;
-
- // lazy load this again
- SortName = null;
- }
- }
-
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
- /// <summary>
- /// Gets the root folder.
- /// </summary>
- /// <value>The root folder.</value>
- [IgnoreDataMember]
- public Folder RootFolder => LibraryManager.GetUserRootFolder();
-
- /// <summary>
- /// Gets or sets the last login date.
- /// </summary>
- /// <value>The last login date.</value>
- public DateTime? LastLoginDate { get; set; }
- /// <summary>
- /// Gets or sets the last activity date.
- /// </summary>
- /// <value>The last activity date.</value>
- public DateTime? LastActivityDate { get; set; }
-
- private volatile UserConfiguration _config;
- private readonly object _configSyncLock = new object();
- [IgnoreDataMember]
- public UserConfiguration Configuration
- {
- get
- {
- if (_config == null)
- {
- lock (_configSyncLock)
- {
- if (_config == null)
- {
- _config = UserManager.GetUserConfiguration(this);
- }
- }
- }
-
- return _config;
- }
- set => _config = value;
- }
-
- private volatile UserPolicy _policy;
- private readonly object _policySyncLock = new object();
- [IgnoreDataMember]
- public UserPolicy Policy
- {
- get
- {
- if (_policy == null)
- {
- lock (_policySyncLock)
- {
- if (_policy == null)
- {
- _policy = UserManager.GetUserPolicy(this);
- }
- }
- }
-
- return _policy;
- }
- set => _policy = value;
- }
-
- /// <summary>
- /// Renames the user.
- /// </summary>
- /// <param name="newName">The new name.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException"></exception>
- public Task Rename(string newName)
- {
- if (string.IsNullOrEmpty(newName))
- {
- throw new ArgumentNullException(nameof(newName));
- }
-
- // If only the casing is changing, leave the file system alone
- if (!UsesIdForConfigurationPath && !string.Equals(newName, Name, StringComparison.OrdinalIgnoreCase))
- {
- UsesIdForConfigurationPath = true;
-
- // Move configuration
- var newConfigDirectory = GetConfigurationDirectoryPath(newName);
- var oldConfigurationDirectory = ConfigurationDirectoryPath;
-
- // Exceptions will be thrown if these paths already exist
- if (Directory.Exists(newConfigDirectory))
- {
- Directory.Delete(newConfigDirectory, true);
- }
-
- if (Directory.Exists(oldConfigurationDirectory))
- {
- Directory.Move(oldConfigurationDirectory, newConfigDirectory);
- }
- else
- {
- Directory.CreateDirectory(newConfigDirectory);
- }
- }
-
- Name = newName;
-
- return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem))
- {
- ReplaceAllMetadata = true,
- ImageRefreshMode = MetadataRefreshMode.FullRefresh,
- MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
- ForceSave = true
-
- }, CancellationToken.None);
- }
-
- public override void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
- {
- UserManager.UpdateUser(this);
- }
-
- /// <summary>
- /// Gets the path to the user's configuration directory
- /// </summary>
- /// <value>The configuration directory path.</value>
- [IgnoreDataMember]
- public string ConfigurationDirectoryPath => GetConfigurationDirectoryPath(Name);
-
- public override double GetDefaultPrimaryImageAspectRatio()
- {
- return 1;
- }
-
- /// <summary>
- /// Gets the configuration directory path.
- /// </summary>
- /// <param name="username">The username.</param>
- /// <returns>System.String.</returns>
- private string GetConfigurationDirectoryPath(string username)
- {
- var parentPath = ConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath;
-
- // Legacy
- if (!UsesIdForConfigurationPath)
- {
- if (string.IsNullOrEmpty(username))
- {
- throw new ArgumentNullException(nameof(username));
- }
-
- var safeFolderName = FileSystem.GetValidFilename(username);
-
- return System.IO.Path.Combine(ConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, safeFolderName);
- }
-
- return System.IO.Path.Combine(parentPath, Id.ToString("N"));
- }
-
- public bool IsParentalScheduleAllowed()
- {
- return IsParentalScheduleAllowed(DateTime.UtcNow);
- }
-
- public bool IsParentalScheduleAllowed(DateTime date)
- {
- var schedules = Policy.AccessSchedules;
-
- if (schedules.Length == 0)
- {
- return true;
- }
-
- foreach (var i in schedules)
- {
- if (IsParentalScheduleAllowed(i, date))
- {
- return true;
- }
- }
- return false;
- }
-
- private bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date)
- {
- if (date.Kind != DateTimeKind.Utc)
- {
- throw new ArgumentException("Utc date expected");
- }
-
- var localTime = date.ToLocalTime();
-
- return DayOfWeekHelper.GetDaysOfWeek(schedule.DayOfWeek).Contains(localTime.DayOfWeek) &&
- IsWithinTime(schedule, localTime);
- }
-
- private bool IsWithinTime(AccessSchedule schedule, DateTime localTime)
- {
- var hour = localTime.TimeOfDay.TotalHours;
-
- return hour >= schedule.StartHour && hour <= schedule.EndHour;
- }
-
- public bool IsFolderGrouped(Guid id)
- {
- foreach (var i in Configuration.GroupedFolders)
- {
- if (new Guid(i) == id)
- {
- return true;
- }
- }
- return false;
- }
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
- public long InternalId { get; set; }
-
-
- }
-}
diff --git a/MediaBrowser.Controller/Entities/UserItemData.cs b/MediaBrowser.Controller/Entities/UserItemData.cs
index f7136bdf2..50ba9ef30 100644
--- a/MediaBrowser.Controller/Entities/UserItemData.cs
+++ b/MediaBrowser.Controller/Entities/UserItemData.cs
@@ -1,13 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Serialization;
+using System.Text.Json.Serialization;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class UserItemData
+ /// Class UserItemData.
/// </summary>
public class UserItemData
{
+ public const double MinLikeValue = 6.5;
+
+ /// <summary>
+ /// The _rating.
+ /// </summary>
+ private double? _rating;
+
/// <summary>
/// Gets or sets the user id.
/// </summary>
@@ -21,11 +32,7 @@ namespace MediaBrowser.Controller.Entities
public string Key { get; set; }
/// <summary>
- /// The _rating
- /// </summary>
- private double? _rating;
- /// <summary>
- /// Gets or sets the users 0-10 rating
+ /// Gets or sets the users 0-10 rating.
/// </summary>
/// <value>The rating.</value>
/// <exception cref="ArgumentOutOfRangeException">Rating;A 0 to 10 rating is required for UserItemData.</exception>
@@ -75,25 +82,25 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
/// <value><c>true</c> if played; otherwise, <c>false</c>.</value>
public bool Played { get; set; }
+
/// <summary>
/// Gets or sets the index of the audio stream.
/// </summary>
/// <value>The index of the audio stream.</value>
public int? AudioStreamIndex { get; set; }
+
/// <summary>
/// Gets or sets the index of the subtitle stream.
/// </summary>
/// <value>The index of the subtitle stream.</value>
public int? SubtitleStreamIndex { get; set; }
- public const double MinLikeValue = 6.5;
-
/// <summary>
- /// This is an interpreted property to indicate likes or dislikes
+ /// Gets or sets a value indicating whether the item is liked or not.
/// This should never be serialized.
/// </summary>
/// <value><c>null</c> if [likes] contains no value, <c>true</c> if [likes]; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool? Likes
{
get
@@ -105,6 +112,7 @@ namespace MediaBrowser.Controller.Entities
return null;
}
+
set
{
if (value.HasValue)
diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs
index 7fe8df8af..e547db523 100644
--- a/MediaBrowser.Controller/Entities/UserRootFolder.cs
+++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs
@@ -1,12 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
@@ -16,29 +21,29 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
public class UserRootFolder : Folder
{
- private List<Guid> _childrenIds = null;
private readonly object _childIdsLock = new object();
- protected override List<BaseItem> LoadChildren()
- {
- lock (_childIdsLock)
- {
- if (_childrenIds == null)
- {
- var list = base.LoadChildren();
- _childrenIds = list.Select(i => i.Id).ToList();
- return list;
- }
+ private List<Guid> _childrenIds = null;
- return _childrenIds.Select(LibraryManager.GetItemById).Where(i => i != null).ToList();
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserRootFolder"/> class.
+ /// </summary>
+ public UserRootFolder()
+ {
+ IsRoot = true;
}
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => false;
+ [JsonIgnore]
+ protected override bool SupportsShortcutChildren => true;
+
+ [JsonIgnore]
+ public override bool IsPreSorted => true;
+
private void ClearCache()
{
lock (_childIdsLock)
@@ -47,6 +52,21 @@ namespace MediaBrowser.Controller.Entities
}
}
+ protected override List<BaseItem> LoadChildren()
+ {
+ lock (_childIdsLock)
+ {
+ if (_childrenIds == null)
+ {
+ var list = base.LoadChildren();
+ _childrenIds = list.Select(i => i.Id).ToList();
+ return list;
+ }
+
+ return _childrenIds.Select(LibraryManager.GetItemById).Where(i => i != null).ToList();
+ }
+ }
+
protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
{
if (query.Recursive)
@@ -60,14 +80,7 @@ namespace MediaBrowser.Controller.Entities
PresetViews = query.PresetViews
});
- var itemsArray = result;
- var totalCount = itemsArray.Length;
-
- return new QueryResult<BaseItem>
- {
- TotalRecordCount = totalCount,
- Items = itemsArray //TODO Fix The co-variant conversion between Folder[] and BaseItem[], this can generate runtime issues.
- };
+ return UserViewBuilder.SortAndPage(result, null, query, LibraryManager, true);
}
public override int GetChildCount(User user)
@@ -75,12 +88,6 @@ namespace MediaBrowser.Controller.Entities
return GetChildren(user, true).Count;
}
- [IgnoreDataMember]
- protected override bool SupportsShortcutChildren => true;
-
- [IgnoreDataMember]
- public override bool IsPreSorted => true;
-
protected override IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
{
var list = base.GetEligibleChildrenForRecursiveChildren(user).ToList();
@@ -89,10 +96,10 @@ namespace MediaBrowser.Controller.Entities
return list;
}
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
ClearCache();
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
if (string.Equals("default", Name, StringComparison.OrdinalIgnoreCase))
{
@@ -110,11 +117,11 @@ namespace MediaBrowser.Controller.Entities
return base.GetNonCachedChildren(directoryService);
}
- protected override async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected override async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
ClearCache();
- await base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService)
+ await base.ValidateChildrenInternal(progress, recursive, refreshChildMetadata, refreshOptions, directoryService, cancellationToken)
.ConfigureAwait(false);
ClearCache();
diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs
index 3e2191376..62f3c4b55 100644
--- a/MediaBrowser.Controller/Entities/UserView.cs
+++ b/MediaBrowser.Controller/Entities/UserView.cs
@@ -1,57 +1,94 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Playlists;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
public class UserView : Folder, IHasCollectionType
{
+ private static readonly string[] _viewTypesEligibleForGrouping = new string[]
+ {
+ Model.Entities.CollectionType.Movies,
+ Model.Entities.CollectionType.TvShows,
+ string.Empty
+ };
+
+ private static readonly string[] _originalFolderViewTypes = new string[]
+ {
+ Model.Entities.CollectionType.Books,
+ Model.Entities.CollectionType.MusicVideos,
+ Model.Entities.CollectionType.HomeVideos,
+ Model.Entities.CollectionType.Photos,
+ Model.Entities.CollectionType.Music,
+ Model.Entities.CollectionType.BoxSets
+ };
+
+ public static ITVSeriesManager TVSeriesManager { get; set; }
+
+ /// <summary>
+ /// Gets or sets the view type.
+ /// </summary>
public string ViewType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the display parent id.
+ /// </summary>
public new Guid DisplayParentId { get; set; }
+ /// <summary>
+ /// Gets or sets the user id.
+ /// </summary>
public Guid? UserId { get; set; }
- public static ITVSeriesManager TVSeriesManager;
- public static IPlaylistManager PlaylistManager;
-
- [IgnoreDataMember]
+ /// <inheritdoc />
+ [JsonIgnore]
public string CollectionType => ViewType;
+ /// <inheritdoc />
+ [JsonIgnore]
+ public override bool SupportsInheritedParentImages => false;
+
+ /// <inheritdoc />
+ [JsonIgnore]
+ public override bool SupportsPlayedStatus => false;
+
+ /// <inheritdoc />
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
+ /// <inheritdoc />
public override IEnumerable<Guid> GetIdsForAncestorQuery()
{
- var list = new List<Guid>();
-
if (!DisplayParentId.Equals(Guid.Empty))
{
- list.Add(DisplayParentId);
+ yield return DisplayParentId;
}
else if (!ParentId.Equals(Guid.Empty))
{
- list.Add(ParentId);
+ yield return ParentId;
}
else
{
- list.Add(Id);
+ yield return Id;
}
- return list;
}
- [IgnoreDataMember]
- public override bool SupportsInheritedParentImages => false;
-
- [IgnoreDataMember]
- public override bool SupportsPlayedStatus => false;
-
+ /// <inheritdoc />
public override int GetChildCount(User user)
{
return GetChildren(user, true).Count;
}
+ /// <inheritdoc />
protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
{
var parent = this as Folder;
@@ -65,16 +102,14 @@ namespace MediaBrowser.Controller.Entities
parent = LibraryManager.GetItemById(ParentId) as Folder ?? parent;
}
- return new UserViewBuilder(UserViewManager, LibraryManager, Logger, UserDataManager, TVSeriesManager, ConfigurationManager, PlaylistManager)
+ return new UserViewBuilder(UserViewManager, LibraryManager, Logger, UserDataManager, TVSeriesManager, ConfigurationManager)
.GetUserItems(parent, this, CollectionType, query);
}
+ /// <inheritdoc />
public override List<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
{
- if (query == null)
- {
- query = new InternalItemsQuery(user);
- }
+ query ??= new InternalItemsQuery(user);
query.EnableTotalRecordCount = false;
var result = GetItemList(query);
@@ -82,16 +117,19 @@ namespace MediaBrowser.Controller.Entities
return result.ToList();
}
+ /// <inheritdoc />
public override bool CanDelete()
{
return false;
}
+ /// <inheritdoc />
public override bool IsSaveLocalMetadataEnabled()
{
return true;
}
+ /// <inheritdoc />
public override IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
{
query.SetUser(user);
@@ -102,32 +140,26 @@ namespace MediaBrowser.Controller.Entities
return GetItemList(query);
}
+ /// <inheritdoc />
protected override IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
{
return GetChildren(user, false);
}
- private static string[] UserSpecificViewTypes = new string[]
- {
- MediaBrowser.Model.Entities.CollectionType.Playlists
- };
-
public static bool IsUserSpecific(Folder folder)
{
- var collectionFolder = folder as ICollectionFolder;
-
- if (collectionFolder == null)
+ if (folder is not ICollectionFolder collectionFolder)
{
return false;
}
- var supportsUserSpecific = folder as ISupportsUserSpecificView;
- if (supportsUserSpecific != null && supportsUserSpecific.EnableUserSpecificView)
+ if (folder is ISupportsUserSpecificView supportsUserSpecific
+ && supportsUserSpecific.EnableUserSpecificView)
{
return true;
}
- return UserSpecificViewTypes.Contains(collectionFolder.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ return string.Equals(Model.Entities.CollectionType.Playlists, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase);
}
public static bool IsEligibleForGrouping(Folder folder)
@@ -136,39 +168,19 @@ namespace MediaBrowser.Controller.Entities
&& IsEligibleForGrouping(collectionFolder.CollectionType);
}
- private static string[] ViewTypesEligibleForGrouping = new string[]
- {
- MediaBrowser.Model.Entities.CollectionType.Movies,
- MediaBrowser.Model.Entities.CollectionType.TvShows,
- string.Empty
- };
-
public static bool IsEligibleForGrouping(string viewType)
{
- return ViewTypesEligibleForGrouping.Contains(viewType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ return _viewTypesEligibleForGrouping.Contains(viewType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
}
- private static string[] OriginalFolderViewTypes = new string[]
- {
- MediaBrowser.Model.Entities.CollectionType.Books,
- MediaBrowser.Model.Entities.CollectionType.MusicVideos,
- MediaBrowser.Model.Entities.CollectionType.HomeVideos,
- MediaBrowser.Model.Entities.CollectionType.Photos,
- MediaBrowser.Model.Entities.CollectionType.Music,
- MediaBrowser.Model.Entities.CollectionType.BoxSets
- };
-
public static bool EnableOriginalFolder(string viewType)
{
- return OriginalFolderViewTypes.Contains(viewType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ return _originalFolderViewTypes.Contains(viewType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
}
- protected override Task ValidateChildrenInternal(IProgress<double> progress, System.Threading.CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, Providers.MetadataRefreshOptions refreshOptions, Providers.IDirectoryService directoryService)
+ protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, Providers.MetadataRefreshOptions refreshOptions, Providers.IDirectoryService directoryService, System.Threading.CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
-
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
}
}
diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
index 683218a9e..266fda767 100644
--- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs
+++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
@@ -1,15 +1,25 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using MetadataProvider = MediaBrowser.Model.Entities.MetadataProvider;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace MediaBrowser.Controller.Entities
{
@@ -17,13 +27,18 @@ namespace MediaBrowser.Controller.Entities
{
private readonly IUserViewManager _userViewManager;
private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<BaseItem> _logger;
private readonly IUserDataManager _userDataManager;
private readonly ITVSeriesManager _tvSeriesManager;
private readonly IServerConfigurationManager _config;
- private readonly IPlaylistManager _playlistManager;
- public UserViewBuilder(IUserViewManager userViewManager, ILibraryManager libraryManager, ILogger logger, IUserDataManager userDataManager, ITVSeriesManager tvSeriesManager, IServerConfigurationManager config, IPlaylistManager playlistManager)
+ public UserViewBuilder(
+ IUserViewManager userViewManager,
+ ILibraryManager libraryManager,
+ ILogger<BaseItem> logger,
+ IUserDataManager userDataManager,
+ ITVSeriesManager tvSeriesManager,
+ IServerConfigurationManager config)
{
_userViewManager = userViewManager;
_libraryManager = libraryManager;
@@ -31,27 +46,26 @@ namespace MediaBrowser.Controller.Entities
_userDataManager = userDataManager;
_tvSeriesManager = tvSeriesManager;
_config = config;
- _playlistManager = playlistManager;
}
public QueryResult<BaseItem> GetUserItems(Folder queryParent, Folder displayParent, string viewType, InternalItemsQuery query)
{
var user = query.User;
- //if (query.IncludeItemTypes != null &&
+ // if (query.IncludeItemTypes != null &&
// query.IncludeItemTypes.Length == 1 &&
// string.Equals(query.IncludeItemTypes[0], "Playlist", StringComparison.OrdinalIgnoreCase))
- //{
+ // {
// if (!string.Equals(viewType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
// {
// return await FindPlaylists(queryParent, user, query).ConfigureAwait(false);
// }
- //}
+ // }
switch (viewType)
{
case CollectionType.Folders:
- return GetResult(_libraryManager.GetUserRootFolder().GetChildren(user, true), queryParent, query);
+ return GetResult(_libraryManager.GetUserRootFolder().GetChildren(user, true), query);
case CollectionType.TvShows:
return GetTvView(queryParent, user, query);
@@ -96,7 +110,7 @@ namespace MediaBrowser.Controller.Entities
return GetMovieMovies(queryParent, user, query);
case SpecialFolder.MovieCollections:
- return GetMovieCollections(queryParent, user, query);
+ return GetMovieCollections(user, query);
case SpecialFolder.TvFavoriteEpisodes:
return GetFavoriteEpisodes(queryParent, user, query);
@@ -108,8 +122,9 @@ namespace MediaBrowser.Controller.Entities
{
if (queryParent is UserView)
{
- return GetResult(GetMediaFolders(user).OfType<Folder>().SelectMany(i => i.GetChildren(user, true)), queryParent, query);
+ return GetResult(GetMediaFolders(user).OfType<Folder>().SelectMany(i => i.GetChildren(user, true)), query);
}
+
return queryParent.GetItems(query);
}
}
@@ -129,22 +144,23 @@ namespace MediaBrowser.Controller.Entities
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
}
return parent.QueryRecursive(query);
}
- var list = new List<BaseItem>();
-
- list.Add(GetUserView(SpecialFolder.MovieResume, "HeaderContinueWatching", "0", parent));
- list.Add(GetUserView(SpecialFolder.MovieLatest, "Latest", "1", parent));
- list.Add(GetUserView(SpecialFolder.MovieMovies, "Movies", "2", parent));
- list.Add(GetUserView(SpecialFolder.MovieCollections, "Collections", "3", parent));
- list.Add(GetUserView(SpecialFolder.MovieFavorites, "Favorites", "4", parent));
- list.Add(GetUserView(SpecialFolder.MovieGenres, "Genres", "5", parent));
+ var list = new List<BaseItem>
+ {
+ GetUserView(SpecialFolder.MovieResume, "HeaderContinueWatching", "0", parent),
+ GetUserView(SpecialFolder.MovieLatest, "Latest", "1", parent),
+ GetUserView(SpecialFolder.MovieMovies, "Movies", "2", parent),
+ GetUserView(SpecialFolder.MovieCollections, "Collections", "3", parent),
+ GetUserView(SpecialFolder.MovieFavorites, "Favorites", "4", parent),
+ GetUserView(SpecialFolder.MovieGenres, "Genres", "5", parent)
+ };
- return GetResult(list, parent, query);
+ return GetResult(list, query);
}
private QueryResult<BaseItem> GetFavoriteMovies(Folder parent, User user, InternalItemsQuery query)
@@ -153,7 +169,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
@@ -164,7 +180,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -175,7 +191,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
return _libraryManager.GetItemsResult(query);
}
@@ -186,15 +202,15 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
- private QueryResult<BaseItem> GetMovieCollections(Folder parent, User user, InternalItemsQuery query)
+ private QueryResult<BaseItem> GetMovieCollections(User user, InternalItemsQuery query)
{
query.Parent = null;
- query.IncludeItemTypes = new[] { typeof(BoxSet).Name };
+ query.IncludeItemTypes = new[] { nameof(BoxSet) };
query.SetUser(user);
query.Recursive = true;
@@ -203,26 +219,25 @@ namespace MediaBrowser.Controller.Entities
private QueryResult<BaseItem> GetMovieLatest(Folder parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray();
-
+ query.OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) };
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
private QueryResult<BaseItem> GetMovieResume(Folder parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray();
+ query.OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) };
query.IsResumable = true;
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
@@ -241,10 +256,9 @@ namespace MediaBrowser.Controller.Entities
{
var genres = parent.QueryRecursive(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Movie).Name },
+ IncludeItemTypes = new[] { nameof(Movie) },
Recursive = true,
EnableTotalRecordCount = false
-
}).Items
.SelectMany(i => i.Genres)
.DistinctNames()
@@ -259,12 +273,11 @@ namespace MediaBrowser.Controller.Entities
_logger.LogError(ex, "Error getting genre");
return null;
}
-
})
.Where(i => i != null)
- .Select(i => GetUserViewWithName(i.Name, SpecialFolder.MovieGenre, i.SortName, parent));
+ .Select(i => GetUserViewWithName(SpecialFolder.MovieGenre, i.SortName, parent));
- return GetResult(genres, parent, query);
+ return GetResult(genres, query);
}
private QueryResult<BaseItem> GetMovieGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
@@ -274,7 +287,7 @@ namespace MediaBrowser.Controller.Entities
query.GenreIds = new[] { displayParent.Id };
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
@@ -288,34 +301,39 @@ namespace MediaBrowser.Controller.Entities
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Series).Name, typeof(Season).Name, typeof(Episode).Name };
+ query.IncludeItemTypes = new[]
+ {
+ nameof(Series),
+ nameof(Season),
+ nameof(Episode)
+ };
}
return parent.QueryRecursive(query);
}
- var list = new List<BaseItem>();
-
- list.Add(GetUserView(SpecialFolder.TvResume, "HeaderContinueWatching", "0", parent));
- list.Add(GetUserView(SpecialFolder.TvNextUp, "HeaderNextUp", "1", parent));
- list.Add(GetUserView(SpecialFolder.TvLatest, "Latest", "2", parent));
- list.Add(GetUserView(SpecialFolder.TvShowSeries, "Shows", "3", parent));
- list.Add(GetUserView(SpecialFolder.TvFavoriteSeries, "HeaderFavoriteShows", "4", parent));
- list.Add(GetUserView(SpecialFolder.TvFavoriteEpisodes, "HeaderFavoriteEpisodes", "5", parent));
- list.Add(GetUserView(SpecialFolder.TvGenres, "Genres", "6", parent));
+ var list = new List<BaseItem>
+ {
+ GetUserView(SpecialFolder.TvResume, "HeaderContinueWatching", "0", parent),
+ GetUserView(SpecialFolder.TvNextUp, "HeaderNextUp", "1", parent),
+ GetUserView(SpecialFolder.TvLatest, "Latest", "2", parent),
+ GetUserView(SpecialFolder.TvShowSeries, "Shows", "3", parent),
+ GetUserView(SpecialFolder.TvFavoriteSeries, "HeaderFavoriteShows", "4", parent),
+ GetUserView(SpecialFolder.TvFavoriteEpisodes, "HeaderFavoriteEpisodes", "5", parent),
+ GetUserView(SpecialFolder.TvGenres, "Genres", "6", parent)
+ };
- return GetResult(list, parent, query);
+ return GetResult(list, query);
}
private QueryResult<BaseItem> GetTvLatest(Folder parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray();
-
+ query.OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) };
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
query.IsVirtualItem = false;
return ConvertToResult(_libraryManager.GetItemList(query));
@@ -325,26 +343,28 @@ namespace MediaBrowser.Controller.Entities
{
var parentFolders = GetMediaFolders(parent, query.User, new[] { CollectionType.TvShows, string.Empty });
- var result = _tvSeriesManager.GetNextUp(new NextUpQuery
- {
- Limit = query.Limit,
- StartIndex = query.StartIndex,
- UserId = query.User.Id
-
- }, parentFolders, query.DtoOptions);
+ var result = _tvSeriesManager.GetNextUp(
+ new NextUpQuery
+ {
+ Limit = query.Limit,
+ StartIndex = query.StartIndex,
+ UserId = query.User.Id
+ },
+ parentFolders,
+ query.DtoOptions);
return result;
}
private QueryResult<BaseItem> GetTvResume(Folder parent, User user, InternalItemsQuery query)
{
- query.OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray();
+ query.OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) };
query.IsResumable = true;
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
@@ -355,7 +375,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -364,10 +384,9 @@ namespace MediaBrowser.Controller.Entities
{
var genres = parent.QueryRecursive(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Series).Name },
+ IncludeItemTypes = new[] { nameof(Series) },
Recursive = true,
EnableTotalRecordCount = false
-
}).Items
.SelectMany(i => i.Genres)
.DistinctNames()
@@ -382,12 +401,11 @@ namespace MediaBrowser.Controller.Entities
_logger.LogError(ex, "Error getting genre");
return null;
}
-
})
.Where(i => i != null)
- .Select(i => GetUserViewWithName(i.Name, SpecialFolder.TvGenre, i.SortName, parent));
+ .Select(i => GetUserViewWithName(SpecialFolder.TvGenre, i.SortName, parent));
- return GetResult(genres, parent, query);
+ return GetResult(genres, query);
}
private QueryResult<BaseItem> GetTvGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
@@ -397,7 +415,7 @@ namespace MediaBrowser.Controller.Entities
query.GenreIds = new[] { displayParent.Id };
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -407,19 +425,19 @@ namespace MediaBrowser.Controller.Entities
{
return new QueryResult<BaseItem>
{
- Items = result.Items, //TODO Fix The co-variant conversion between T[] and BaseItem[], this can generate runtime issues if T is not BaseItem.
+ Items = result.Items, // TODO Fix The co-variant conversion between T[] and BaseItem[], this can generate runtime issues if T is not BaseItem.
TotalRecordCount = result.TotalRecordCount
};
}
- private QueryResult<BaseItem> GetResult<T>(IEnumerable<T> items,
- BaseItem queryParent,
+ private QueryResult<BaseItem> GetResult<T>(
+ IEnumerable<T> items,
InternalItemsQuery query)
where T : BaseItem
{
items = items.Where(i => Filter(i, query.User, query, _userDataManager, _libraryManager));
- return PostFilterAndSort(items, queryParent, null, query, _libraryManager, _config);
+ return PostFilterAndSort(items, null, query, _libraryManager);
}
public static bool FilterItem(BaseItem item, InternalItemsQuery query)
@@ -427,12 +445,11 @@ namespace MediaBrowser.Controller.Entities
return Filter(item, query.User, query, BaseItem.UserDataManager, BaseItem.LibraryManager);
}
- public static QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items,
- BaseItem queryParent,
+ public static QueryResult<BaseItem> PostFilterAndSort(
+ IEnumerable<BaseItem> items,
int? totalRecordLimit,
InternalItemsQuery query,
- ILibraryManager libraryManager,
- IServerConfigurationManager configurationManager)
+ ILibraryManager libraryManager)
{
var user = query.User;
@@ -445,14 +462,16 @@ namespace MediaBrowser.Controller.Entities
return SortAndPage(items, totalRecordLimit, query, libraryManager, true);
}
- public static QueryResult<BaseItem> SortAndPage(IEnumerable<BaseItem> items,
+ public static QueryResult<BaseItem> SortAndPage(
+ IEnumerable<BaseItem> items,
int? totalRecordLimit,
InternalItemsQuery query,
- ILibraryManager libraryManager, bool enableSorting)
+ ILibraryManager libraryManager,
+ bool enableSorting)
{
if (enableSorting)
{
- if (query.OrderBy.Length > 0)
+ if (query.OrderBy.Count > 0)
{
items = libraryManager.Sort(items, query.User, query.OrderBy);
}
@@ -604,7 +623,7 @@ namespace MediaBrowser.Controller.Entities
{
var filterValue = query.HasImdbId.Value;
- var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Imdb));
+ var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Imdb));
if (hasValue != filterValue)
{
@@ -616,7 +635,7 @@ namespace MediaBrowser.Controller.Entities
{
var filterValue = query.HasTmdbId.Value;
- var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb));
+ var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Tmdb));
if (hasValue != filterValue)
{
@@ -628,7 +647,7 @@ namespace MediaBrowser.Controller.Entities
{
var filterValue = query.HasTvdbId.Value;
- var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tvdb));
+ var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Tvdb));
if (hasValue != filterValue)
{
@@ -654,9 +673,7 @@ namespace MediaBrowser.Controller.Entities
var isPlaceHolder = false;
- var hasPlaceHolder = item as ISupportsPlaceHolders;
-
- if (hasPlaceHolder != null)
+ if (item is ISupportsPlaceHolders hasPlaceHolder)
{
isPlaceHolder = hasPlaceHolder.IsPlaceHolder;
}
@@ -671,13 +688,11 @@ namespace MediaBrowser.Controller.Entities
{
var filterValue = query.HasSpecialFeature.Value;
- var movie = item as IHasSpecialFeatures;
-
- if (movie != null)
+ if (item is IHasSpecialFeatures movie)
{
var ok = filterValue
- ? movie.SpecialFeatureIds.Length > 0
- : movie.SpecialFeatureIds.Length == 0;
+ ? movie.SpecialFeatureIds.Count > 0
+ : movie.SpecialFeatureIds.Count == 0;
if (!ok)
{
@@ -775,7 +790,7 @@ namespace MediaBrowser.Controller.Entities
}
// Apply genre filter
- if (query.Genres.Length > 0 && !query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)))
+ if (query.Genres.Count > 0 && !query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)))
{
return false;
}
@@ -806,7 +821,7 @@ namespace MediaBrowser.Controller.Entities
}
// Apply genre filter
- if (query.GenreIds.Length > 0 && !query.GenreIds.Any(id =>
+ if (query.GenreIds.Count > 0 && !query.GenreIds.Any(id =>
{
var genreItem = libraryManager.GetItemById(id);
return genreItem != null && item.Genres.Contains(genreItem.Name, StringComparer.OrdinalIgnoreCase);
@@ -944,6 +959,7 @@ namespace MediaBrowser.Controller.Entities
.OfType<Folder>()
.Where(UserView.IsEligibleForGrouping);
}
+
return _libraryManager.GetUserRootFolder()
.GetChildren(user, true)
.OfType<Folder>()
@@ -962,6 +978,7 @@ namespace MediaBrowser.Controller.Entities
return folder != null && viewTypes.Contains(folder.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
}).ToArray();
}
+
return GetMediaFolders(user)
.Where(i =>
{
@@ -981,9 +998,9 @@ namespace MediaBrowser.Controller.Entities
return new BaseItem[] { parent };
}
- private UserView GetUserViewWithName(string name, string type, string sortName, BaseItem parent)
+ private UserView GetUserViewWithName(string type, string sortName, BaseItem parent)
{
- return _userViewManager.GetUserSubView(parent.Id, parent.Id.ToString("N"), type, sortName);
+ return _userViewManager.GetUserSubView(parent.Id, parent.Id.ToString("N", CultureInfo.InvariantCulture), type, sortName);
}
private UserView GetUserView(string type, string localizationKey, string sortName, BaseItem parent)
diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs
index 31cd42975..7dd95b85c 100644
--- a/MediaBrowser.Controller/Entities/Video.cs
+++ b/MediaBrowser.Controller/Entities/Video.cs
@@ -1,47 +1,60 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Video
+ /// Class Video.
/// </summary>
public class Video : BaseItem,
IHasAspectRatio,
ISupportsPlaceHolders,
IHasMediaSources
{
- [IgnoreDataMember]
+ public Video()
+ {
+ AdditionalParts = Array.Empty<string>();
+ LocalAlternateVersions = Array.Empty<string>();
+ SubtitleFiles = Array.Empty<string>();
+ LinkedAlternateVersions = Array.Empty<LinkedChild>();
+ }
+
+ [JsonIgnore]
public string PrimaryVersionId { get; set; }
public string[] AdditionalParts { get; set; }
+
public string[] LocalAlternateVersions { get; set; }
+
public LinkedChild[] LinkedAlternateVersions { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPeople => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPositionTicksResume
{
get
@@ -53,44 +66,23 @@ namespace MediaBrowser.Controller.Entities
{
return false;
}
+
if (extraType.Value == Model.Entities.ExtraType.ThemeVideo)
{
return false;
}
+
if (extraType.Value == Model.Entities.ExtraType.Trailer)
{
return false;
}
}
- return true;
- }
- }
- public void SetPrimaryVersionId(string id)
- {
- if (string.IsNullOrEmpty(id))
- {
- PrimaryVersionId = null;
- }
- else
- {
- PrimaryVersionId = id;
- }
-
- PresentationUniqueKey = CreatePresentationUniqueKey();
- }
-
- public override string CreatePresentationUniqueKey()
- {
- if (!string.IsNullOrEmpty(PrimaryVersionId))
- {
- return PrimaryVersionId;
+ return true;
}
-
- return base.CreatePresentationUniqueKey();
}
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsThemeMedia => true;
/// <summary>
@@ -137,53 +129,16 @@ namespace MediaBrowser.Controller.Entities
/// <value>The video3 D format.</value>
public Video3DFormat? Video3DFormat { get; set; }
- public string[] GetPlayableStreamFileNames(IMediaEncoder mediaEncoder)
- {
- var videoType = VideoType;
-
- if (videoType == VideoType.Iso && IsoType == Model.Entities.IsoType.BluRay)
- {
- videoType = VideoType.BluRay;
- }
- else if (videoType == VideoType.Iso && IsoType == Model.Entities.IsoType.Dvd)
- {
- videoType = VideoType.Dvd;
- }
- else
- {
- return Array.Empty<string>();
- }
- return mediaEncoder.GetPlayableStreamFileNames(Path, videoType);
- }
-
/// <summary>
/// Gets or sets the aspect ratio.
/// </summary>
/// <value>The aspect ratio.</value>
public string AspectRatio { get; set; }
- public Video()
- {
- AdditionalParts = Array.Empty<string>();
- LocalAlternateVersions = Array.Empty<string>();
- SubtitleFiles = Array.Empty<string>();
- LinkedAlternateVersions = EmptyLinkedChildArray;
- }
-
- public override bool CanDownload()
- {
- if (VideoType == VideoType.Dvd || VideoType == VideoType.BluRay)
- {
- return false;
- }
-
- return IsFileProtocol;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public int MediaSourceCount
{
get
@@ -196,29 +151,20 @@ namespace MediaBrowser.Controller.Entities
return video.MediaSourceCount;
}
}
+
return LinkedAlternateVersions.Length + LocalAlternateVersions.Length + 1;
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsStacked => AdditionalParts.Length > 0;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool HasLocalAlternateVersions => LocalAlternateVersions.Length > 0;
- public IEnumerable<Guid> GetAdditionalPartIds()
- {
- return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
- }
-
- public IEnumerable<Guid> GetLocalAlternateVersionIds()
- {
- return LocalAlternateVersions.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
- }
-
public static ILiveTvManager LiveTvManager { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override SourceType SourceType
{
get
@@ -232,37 +178,77 @@ namespace MediaBrowser.Controller.Entities
}
}
- protected override bool IsActiveRecording()
+ [JsonIgnore]
+ public bool IsCompleteMedia
{
- return LiveTvManager.GetActiveRecordingInfo(Path) != null;
+ get
+ {
+ if (SourceType == SourceType.Channel)
+ {
+ return !Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase);
+ }
+
+ return !IsActiveRecording();
+ }
}
- public override bool CanDelete()
+ [JsonIgnore]
+ protected virtual bool EnableDefaultVideoUserDataKeys => true;
+
+ [JsonIgnore]
+ public override string ContainingFolderPath
{
- if (IsActiveRecording())
+ get
{
- return false;
- }
+ if (IsStacked)
+ {
+ return System.IO.Path.GetDirectoryName(Path);
+ }
- return base.CanDelete();
+ if (!IsPlaceHolder)
+ {
+ if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
+ {
+ return Path;
+ }
+ }
+
+ return base.ContainingFolderPath;
+ }
}
- [IgnoreDataMember]
- public bool IsCompleteMedia
+ [JsonIgnore]
+ public override string FileNameWithoutExtension
{
get
{
- if (SourceType == SourceType.Channel)
+ if (IsFileProtocol)
{
- return !Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase);
+ if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
+ {
+ return System.IO.Path.GetFileName(Path);
+ }
+
+ return System.IO.Path.GetFileNameWithoutExtension(Path);
}
- return !IsActiveRecording();
+ return null;
}
}
- [IgnoreDataMember]
- protected virtual bool EnableDefaultVideoUserDataKeys => true;
+ /// <summary>
+ /// Gets a value indicating whether [is3 D].
+ /// </summary>
+ /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public bool Is3D => Video3DFormat.HasValue;
+
+ /// <summary>
+ /// Gets the type of the media.
+ /// </summary>
+ /// <value>The type of the media.</value>
+ [JsonIgnore]
+ public override string MediaType => Model.Entities.MediaType.Video;
public override List<string> GetUserDataKeys()
{
@@ -272,13 +258,13 @@ namespace MediaBrowser.Controller.Entities
{
if (ExtraType.HasValue)
{
- var key = this.GetProviderId(MetadataProviders.Tmdb);
+ var key = this.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, GetUserDataKey(key));
}
- key = this.GetProviderId(MetadataProviders.Imdb);
+ key = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, GetUserDataKey(key));
@@ -286,13 +272,13 @@ namespace MediaBrowser.Controller.Entities
}
else
{
- var key = this.GetProviderId(MetadataProviders.Imdb);
+ var key = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, key);
}
- key = this.GetProviderId(MetadataProviders.Tmdb);
+ key = this.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, key);
@@ -303,6 +289,65 @@ namespace MediaBrowser.Controller.Entities
return list;
}
+ public void SetPrimaryVersionId(string id)
+ {
+ if (string.IsNullOrEmpty(id))
+ {
+ PrimaryVersionId = null;
+ }
+ else
+ {
+ PrimaryVersionId = id;
+ }
+
+ PresentationUniqueKey = CreatePresentationUniqueKey();
+ }
+
+ public override string CreatePresentationUniqueKey()
+ {
+ if (!string.IsNullOrEmpty(PrimaryVersionId))
+ {
+ return PrimaryVersionId;
+ }
+
+ return base.CreatePresentationUniqueKey();
+ }
+
+ public override bool CanDownload()
+ {
+ if (VideoType == VideoType.Dvd || VideoType == VideoType.BluRay)
+ {
+ return false;
+ }
+
+ return IsFileProtocol;
+ }
+
+ protected override bool IsActiveRecording()
+ {
+ return LiveTvManager.GetActiveRecordingInfo(Path) != null;
+ }
+
+ public override bool CanDelete()
+ {
+ if (IsActiveRecording())
+ {
+ return false;
+ }
+
+ return base.CanDelete();
+ }
+
+ public IEnumerable<Guid> GetAdditionalPartIds()
+ {
+ return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
+ }
+
+ public IEnumerable<Guid> GetLocalAlternateVersionIds()
+ {
+ return LocalAlternateVersions.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
+ }
+
private string GetUserDataKey(string providerId)
{
var key = providerId + "-" + ExtraType.ToString().ToLowerInvariant();
@@ -338,47 +383,6 @@ namespace MediaBrowser.Controller.Entities
.OrderBy(i => i.SortName);
}
- [IgnoreDataMember]
- public override string ContainingFolderPath
- {
- get
- {
- if (IsStacked)
- {
- return System.IO.Path.GetDirectoryName(Path);
- }
-
- if (!IsPlaceHolder)
- {
- if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
- {
- return Path;
- }
- }
-
- return base.ContainingFolderPath;
- }
- }
-
- [IgnoreDataMember]
- public override string FileNameWithoutExtension
- {
- get
- {
- if (IsFileProtocol)
- {
- if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
- {
- return System.IO.Path.GetFileName(Path);
- }
-
- return System.IO.Path.GetFileNameWithoutExtension(Path);
- }
-
- return null;
- }
- }
-
internal override ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
{
var updateType = base.UpdateFromResolvedItem(newItem);
@@ -390,11 +394,13 @@ namespace MediaBrowser.Controller.Entities
AdditionalParts = newVideo.AdditionalParts;
updateType |= ItemUpdateType.MetadataImport;
}
+
if (!LocalAlternateVersions.SequenceEqual(newVideo.LocalAlternateVersions, StringComparer.Ordinal))
{
LocalAlternateVersions = newVideo.LocalAlternateVersions;
updateType |= ItemUpdateType.MetadataImport;
}
+
if (VideoType != newVideo.VideoType)
{
VideoType = newVideo.VideoType;
@@ -405,43 +411,6 @@ namespace MediaBrowser.Controller.Entities
return updateType;
}
- public static string[] QueryPlayableStreamFiles(string rootPath, VideoType videoType)
- {
- if (videoType == VideoType.Dvd)
- {
- return FileSystem.GetFiles(rootPath, new[] { ".vob" }, false, true)
- .OrderByDescending(i => i.Length)
- .ThenBy(i => i.FullName)
- .Take(1)
- .Select(i => i.FullName)
- .ToArray();
- }
- if (videoType == VideoType.BluRay)
- {
- return FileSystem.GetFiles(rootPath, new[] { ".m2ts" }, false, true)
- .OrderByDescending(i => i.Length)
- .ThenBy(i => i.FullName)
- .Take(1)
- .Select(i => i.FullName)
- .ToArray();
- }
- return Array.Empty<string>();
- }
-
- /// <summary>
- /// Gets a value indicating whether [is3 D].
- /// </summary>
- /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool Is3D => Video3DFormat.HasValue;
-
- /// <summary>
- /// Gets the type of the media.
- /// </summary>
- /// <value>The type of the media.</value>
- [IgnoreDataMember]
- public override string MediaType => Model.Entities.MediaType.Video;
-
protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
{
var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
@@ -485,9 +454,10 @@ namespace MediaBrowser.Controller.Entities
}
}
- public override void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public override async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
{
- base.UpdateToRepository(updateReason, cancellationToken);
+ await base.UpdateToRepositoryAsync(updateReason, cancellationToken).ConfigureAwait(false);
var localAlternates = GetLocalAlternateVersionIds()
.Select(i => LibraryManager.GetItemById(i))
@@ -504,7 +474,7 @@ namespace MediaBrowser.Controller.Entities
item.Genres = Genres;
item.ProviderIds = ProviderIds;
- item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
}
}
@@ -512,7 +482,8 @@ namespace MediaBrowser.Controller.Entities
{
if (!IsInMixedFolder)
{
- return new[] {
+ return new[]
+ {
new FileSystemMetadata
{
FullName = ContainingFolderPath,
@@ -535,7 +506,6 @@ namespace MediaBrowser.Controller.Entities
{
ItemId = Id,
Index = DefaultVideoStreamIndex.Value
-
}).FirstOrDefault();
}
diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs
index 13e82fada..afdaf448b 100644
--- a/MediaBrowser.Controller/Entities/Year.cs
+++ b/MediaBrowser.Controller/Entities/Year.cs
@@ -1,16 +1,39 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
-using MediaBrowser.Model.Serialization;
+using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
/// <summary>
- /// Class Year
+ /// Class Year.
/// </summary>
public class Year : BaseItem, IItemByName
{
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
+ [JsonIgnore]
+ public override bool SupportsPeople => false;
+
+ /// <summary>
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
+ /// </summary>
+ /// <value>The containing folder path.</value>
+ [JsonIgnore]
+ public override string ContainingFolderPath => Path;
+
+ public override bool CanDelete()
+ {
+ return false;
+ }
+
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
@@ -19,14 +42,6 @@ namespace MediaBrowser.Controller.Entities
return list;
}
- /// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
- /// </summary>
- /// <value>The containing folder path.</value>
- [IgnoreDataMember]
- public override string ContainingFolderPath => Path;
-
public override double GetDefaultPrimaryImageAspectRatio()
{
double value = 2;
@@ -35,14 +50,6 @@ namespace MediaBrowser.Controller.Entities
return value;
}
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
- public override bool CanDelete()
- {
- return false;
- }
-
public override bool IsSaveLocalMetadataEnabled()
{
return true;
@@ -50,9 +57,7 @@ namespace MediaBrowser.Controller.Entities
public IList<BaseItem> GetTaggedItems(InternalItemsQuery query)
{
- var usCulture = new CultureInfo("en-US");
-
- if (!int.TryParse(Name, NumberStyles.Integer, usCulture, out var year))
+ if (!int.TryParse(Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year))
{
return new List<BaseItem>();
}
@@ -72,9 +77,6 @@ namespace MediaBrowser.Controller.Entities
return null;
}
- [IgnoreDataMember]
- public override bool SupportsPeople => false;
-
public static string GetPath(string name)
{
return GetPath(name, true);
@@ -103,15 +105,18 @@ namespace MediaBrowser.Controller.Entities
Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
+
return base.RequiresRefresh();
}
/// <summary>
- /// This is called before any metadata refresh and returns true or false indicating if changes were made
+ /// This is called before any metadata refresh and returns true if changes were made.
/// </summary>
- public override bool BeforeMetadataRefresh(bool replaceAllMetdata)
+ /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
+ /// <returns>true if the item has change, else false.</returns>
+ public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
{
- var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata);
+ var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
diff --git a/MediaBrowser.Controller/Events/IEventConsumer.cs b/MediaBrowser.Controller/Events/IEventConsumer.cs
new file mode 100644
index 000000000..93005134a
--- /dev/null
+++ b/MediaBrowser.Controller/Events/IEventConsumer.cs
@@ -0,0 +1,20 @@
+using System;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Controller.Events
+{
+ /// <summary>
+ /// An interface representing a type that consumes events of type <c>T</c>.
+ /// </summary>
+ /// <typeparam name="T">The type of events this consumes.</typeparam>
+ public interface IEventConsumer<in T>
+ where T : EventArgs
+ {
+ /// <summary>
+ /// A method that is called when an event of type <c>T</c> is fired.
+ /// </summary>
+ /// <param name="eventArgs">The event.</param>
+ /// <returns>A task representing the consumption of the event.</returns>
+ Task OnEvent(T eventArgs);
+ }
+}
diff --git a/MediaBrowser.Controller/Events/IEventManager.cs b/MediaBrowser.Controller/Events/IEventManager.cs
new file mode 100644
index 000000000..074e3f1fe
--- /dev/null
+++ b/MediaBrowser.Controller/Events/IEventManager.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Controller.Events
+{
+ /// <summary>
+ /// An interface that handles eventing.
+ /// </summary>
+ public interface IEventManager
+ {
+ /// <summary>
+ /// Publishes an event.
+ /// </summary>
+ /// <param name="eventArgs">the event arguments.</param>
+ /// <typeparam name="T">The type of event.</typeparam>
+ void Publish<T>(T eventArgs)
+ where T : EventArgs;
+
+ /// <summary>
+ /// Publishes an event asynchronously.
+ /// </summary>
+ /// <param name="eventArgs">The event arguments.</param>
+ /// <typeparam name="T">The type of event.</typeparam>
+ /// <returns>A task representing the publishing of the event.</returns>
+ Task PublishAsync<T>(T eventArgs)
+ where T : EventArgs;
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs b/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs
new file mode 100644
index 000000000..3a331ad00
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Session;
+
+namespace MediaBrowser.Controller.Events.Session
+{
+ /// <summary>
+ /// An event that fires when a session is ended.
+ /// </summary>
+ public class SessionEndedEventArgs : GenericEventArgs<SessionInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionEndedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The session info.</param>
+ public SessionEndedEventArgs(SessionInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs b/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs
new file mode 100644
index 000000000..deeaaf55d
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Controller.Session;
+
+namespace MediaBrowser.Controller.Events.Session
+{
+ /// <summary>
+ /// An event that fires when a session is started.
+ /// </summary>
+ public class SessionStartedEventArgs : GenericEventArgs<SessionInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SessionStartedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The session info.</param>
+ public SessionStartedEventArgs(SessionInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs
new file mode 100644
index 000000000..0dd8b0dbf
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Model.Updates;
+
+namespace MediaBrowser.Controller.Events.Updates
+{
+ /// <summary>
+ /// An event that occurs when a plugin installation is cancelled.
+ /// </summary>
+ public class PluginInstallationCancelledEventArgs : GenericEventArgs<InstallationInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallationCancelledEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The installation info.</param>
+ public PluginInstallationCancelledEventArgs(InstallationInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs
new file mode 100644
index 000000000..c1d503a7e
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Model.Updates;
+
+namespace MediaBrowser.Controller.Events.Updates
+{
+ /// <summary>
+ /// An event that occurs when a plugin is installed.
+ /// </summary>
+ public class PluginInstalledEventArgs : GenericEventArgs<InstallationInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstalledEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The installation info.</param>
+ public PluginInstalledEventArgs(InstallationInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs
new file mode 100644
index 000000000..7a9866834
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Model.Updates;
+
+namespace MediaBrowser.Controller.Events.Updates
+{
+ /// <summary>
+ /// An event that occurs when a plugin is installing.
+ /// </summary>
+ public class PluginInstallingEventArgs : GenericEventArgs<InstallationInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginInstallingEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The installation info.</param>
+ public PluginInstallingEventArgs(InstallationInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs
new file mode 100644
index 000000000..0f27be9bb
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Controller.Events.Updates
+{
+ /// <summary>
+ /// An event that occurs when a plugin is uninstalled.
+ /// </summary>
+ public class PluginUninstalledEventArgs : GenericEventArgs<PluginInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginUninstalledEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The plugin.</param>
+ public PluginUninstalledEventArgs(PluginInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs
new file mode 100644
index 000000000..b078e06dc
--- /dev/null
+++ b/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs
@@ -0,0 +1,19 @@
+using Jellyfin.Data.Events;
+using MediaBrowser.Model.Updates;
+
+namespace MediaBrowser.Controller.Events.Updates
+{
+ /// <summary>
+ /// An event that occurs when a plugin is updated.
+ /// </summary>
+ public class PluginUpdatedEventArgs : GenericEventArgs<InstallationInfo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PluginUpdatedEventArgs"/> class.
+ /// </summary>
+ /// <param name="arg">The installation info.</param>
+ public PluginUpdatedEventArgs(InstallationInfo arg) : base(arg)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Extensions/ConfigurationExtensions.cs b/MediaBrowser.Controller/Extensions/ConfigurationExtensions.cs
new file mode 100644
index 000000000..f9285c768
--- /dev/null
+++ b/MediaBrowser.Controller/Extensions/ConfigurationExtensions.cs
@@ -0,0 +1,101 @@
+using System;
+using Microsoft.Extensions.Configuration;
+
+namespace MediaBrowser.Controller.Extensions
+{
+ /// <summary>
+ /// Configuration extensions for <c>MediaBrowser.Controller</c>.
+ /// </summary>
+ public static class ConfigurationExtensions
+ {
+ /// <summary>
+ /// The key for a setting that specifies the default redirect path
+ /// to use for requests where the URL base prefix is invalid or missing..
+ /// </summary>
+ public const string DefaultRedirectKey = "DefaultRedirectPath";
+
+ /// <summary>
+ /// The key for a setting that indicates whether the application should host web client content.
+ /// </summary>
+ public const string HostWebClientKey = "hostwebclient";
+
+ /// <summary>
+ /// The key for the FFmpeg probe size option.
+ /// </summary>
+ public const string FfmpegProbeSizeKey = "FFmpeg:probesize";
+
+ /// <summary>
+ /// The key for the FFmpeg analyze duration option.
+ /// </summary>
+ public const string FfmpegAnalyzeDurationKey = "FFmpeg:analyzeduration";
+
+ /// <summary>
+ /// The key for the FFmpeg path option.
+ /// </summary>
+ public const string FfmpegPathKey = "ffmpeg";
+
+ /// <summary>
+ /// The key for a setting that indicates whether playlists should allow duplicate entries.
+ /// </summary>
+ public const string PlaylistsAllowDuplicatesKey = "playlists:allowDuplicates";
+
+ /// <summary>
+ /// The key for a setting that indicates whether kestrel should bind to a unix socket.
+ /// </summary>
+ public const string BindToUnixSocketKey = "kestrel:socket";
+
+ /// <summary>
+ /// The key for the unix socket path.
+ /// </summary>
+ public const string UnixSocketPathKey = "kestrel:socketPath";
+
+ /// <summary>
+ /// Gets a value indicating whether the application should host static web content from the <see cref="IConfiguration"/>.
+ /// </summary>
+ /// <param name="configuration">The configuration to retrieve the value from.</param>
+ /// <returns>The parsed config value.</returns>
+ /// <exception cref="FormatException">The config value is not a valid bool string. See <see cref="bool.Parse(string)"/>.</exception>
+ public static bool HostWebClient(this IConfiguration configuration)
+ => configuration.GetValue<bool>(HostWebClientKey);
+
+ /// <summary>
+ /// Gets the FFmpeg probe size from the <see cref="IConfiguration" />.
+ /// </summary>
+ /// <param name="configuration">The configuration to read the setting from.</param>
+ /// <returns>The FFmpeg probe size option.</returns>
+ public static string GetFFmpegProbeSize(this IConfiguration configuration)
+ => configuration[FfmpegProbeSizeKey];
+
+ /// <summary>
+ /// Gets the FFmpeg analyze duration from the <see cref="IConfiguration" />.
+ /// </summary>
+ /// <param name="configuration">The configuration to read the setting from.</param>
+ /// <returns>The FFmpeg analyze duration option.</returns>
+ public static string GetFFmpegAnalyzeDuration(this IConfiguration configuration)
+ => configuration[FfmpegAnalyzeDurationKey];
+
+ /// <summary>
+ /// Gets a value indicating whether playlists should allow duplicate entries from the <see cref="IConfiguration"/>.
+ /// </summary>
+ /// <param name="configuration">The configuration to read the setting from.</param>
+ /// <returns>True if playlists should allow duplicates, otherwise false.</returns>
+ public static bool DoPlaylistsAllowDuplicates(this IConfiguration configuration)
+ => configuration.GetValue<bool>(PlaylistsAllowDuplicatesKey);
+
+ /// <summary>
+ /// Gets a value indicating whether kestrel should bind to a unix socket from the <see cref="IConfiguration" />.
+ /// </summary>
+ /// <param name="configuration">The configuration to read the setting from.</param>
+ /// <returns><c>true</c> if kestrel should bind to a unix socket, otherwise <c>false</c>.</returns>
+ public static bool UseUnixSocket(this IConfiguration configuration)
+ => configuration.GetValue<bool>(BindToUnixSocketKey);
+
+ /// <summary>
+ /// Gets the path for the unix socket from the <see cref="IConfiguration" />.
+ /// </summary>
+ /// <param name="configuration">The configuration to read the setting from.</param>
+ /// <returns>The unix socket path.</returns>
+ public static string GetUnixSocketPath(this IConfiguration configuration)
+ => configuration[UnixSocketPathKey];
+ }
+}
diff --git a/MediaBrowser.Controller/Extensions/StringExtensions.cs b/MediaBrowser.Controller/Extensions/StringExtensions.cs
deleted file mode 100644
index b1aaf6534..000000000
--- a/MediaBrowser.Controller/Extensions/StringExtensions.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace MediaBrowser.Controller.Extensions
-{
- /// <summary>
- /// Class BaseExtensions
- /// </summary>
- public static class StringExtensions
- {
- public static string RemoveDiacritics(this string text)
- {
- if (text == null)
- {
- throw new ArgumentNullException(nameof(text));
- }
-
- var chars = Normalize(text, NormalizationForm.FormD)
- .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark);
-
- return Normalize(string.Concat(chars), NormalizationForm.FormC);
- }
-
- private static string Normalize(string text, NormalizationForm form, bool stripStringOnFailure = true)
- {
- if (stripStringOnFailure)
- {
- try
- {
- return text.Normalize(form);
- }
- catch (ArgumentException)
- {
- // will throw if input contains invalid unicode chars
- // https://mnaoumov.wordpress.com/2014/06/14/stripping-invalid-characters-from-utf-16-strings/
- text = Regex.Replace(text, "([\ud800-\udbff](?![\udc00-\udfff]))|((?<![\ud800-\udbff])[\udc00-\udfff])", "");
- return Normalize(text, form, false);
- }
- }
-
- try
- {
- return text.Normalize(form);
- }
- catch (ArgumentException)
- {
- // if it still fails, return the original text
- return text;
- }
- }
- }
-}
diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs
new file mode 100644
index 000000000..1678d5067
--- /dev/null
+++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs
@@ -0,0 +1,69 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using Jellyfin.Data.Entities;
+
+namespace MediaBrowser.Controller
+{
+ /// <summary>
+ /// Manages the storage and retrieval of display preferences.
+ /// </summary>
+ public interface IDisplayPreferencesManager
+ {
+ /// <summary>
+ /// Gets the display preferences for the user and client.
+ /// </summary>
+ /// <remarks>
+ /// This will create the display preferences if it does not exist, but it will not save automatically.
+ /// </remarks>
+ /// <param name="userId">The user's id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client string.</param>
+ /// <returns>The associated display preferences.</returns>
+ DisplayPreferences GetDisplayPreferences(Guid userId, Guid itemId, string client);
+
+ /// <summary>
+ /// Gets the default item display preferences for the user and client.
+ /// </summary>
+ /// <remarks>
+ /// This will create the item display preferences if it does not exist, but it will not save automatically.
+ /// </remarks>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client string.</param>
+ /// <returns>The item display preferences.</returns>
+ ItemDisplayPreferences GetItemDisplayPreferences(Guid userId, Guid itemId, string client);
+
+ /// <summary>
+ /// Gets all of the item display preferences for the user and client.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="client">The client string.</param>
+ /// <returns>A list of item display preferences.</returns>
+ IList<ItemDisplayPreferences> ListItemDisplayPreferences(Guid userId, string client);
+
+ /// <summary>
+ /// Gets all of the custom item display preferences for the user and client.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client string.</param>
+ /// <returns>The dictionary of custom item display preferences.</returns>
+ Dictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client);
+
+ /// <summary>
+ /// Sets the custom item display preference for the user and client.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="client">The client id.</param>
+ /// <param name="customPreferences">A dictionary of custom item display preferences.</param>
+ void SetCustomItemDisplayPreferences(Guid userId, Guid itemId, string client, Dictionary<string, string> customPreferences);
+
+ /// <summary>
+ /// Saves changes made to the database.
+ /// </summary>
+ void SaveChanges();
+ }
+}
diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs
index 4bbb60283..b8a0bf331 100644
--- a/MediaBrowser.Controller/IO/FileData.cs
+++ b/MediaBrowser.Controller/IO/FileData.cs
@@ -8,34 +8,25 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.IO
{
/// <summary>
- /// Provides low level File access that is much faster than the File/Directory api's
+ /// Provides low level File access that is much faster than the File/Directory api's.
/// </summary>
public static class FileData
{
- private static Dictionary<string, FileSystemMetadata> GetFileSystemDictionary(FileSystemMetadata[] list)
- {
- var dict = new Dictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);
-
- foreach (var file in list)
- {
- dict[file.FullName] = file;
- }
- return dict;
- }
-
/// <summary>
/// Gets the filtered file system entries.
/// </summary>
/// <param name="directoryService">The directory service.</param>
/// <param name="path">The path.</param>
/// <param name="fileSystem">The file system.</param>
+ /// <param name="appHost">The application host.</param>
/// <param name="logger">The logger.</param>
/// <param name="args">The args.</param>
/// <param name="flattenFolderDepth">The flatten folder depth.</param>
/// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
/// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
- /// <exception cref="ArgumentNullException">path</exception>
- public static FileSystemMetadata[] GetFilteredFileSystemEntries(IDirectoryService directoryService,
+ /// <exception cref="ArgumentNullException"><paramref name="path" /> is <c>null</c> or empty.</exception>
+ public static FileSystemMetadata[] GetFilteredFileSystemEntries(
+ IDirectoryService directoryService,
string path,
IFileSystem fileSystem,
IServerApplicationHost appHost,
@@ -48,6 +39,7 @@ namespace MediaBrowser.Controller.IO
{
throw new ArgumentNullException(nameof(path));
}
+
if (args == null)
{
throw new ArgumentNullException(nameof(args));
@@ -76,7 +68,7 @@ namespace MediaBrowser.Controller.IO
if (string.IsNullOrEmpty(newPath))
{
- //invalid shortcut - could be old or target could just be unavailable
+ // invalid shortcut - could be old or target could just be unavailable
logger.LogWarning("Encountered invalid shortcut: " + fullName);
continue;
}
@@ -115,9 +107,8 @@ namespace MediaBrowser.Controller.IO
returnResult[index] = value;
index++;
}
+
return returnResult;
}
-
}
-
}
diff --git a/MediaBrowser.Controller/IResourceFileManager.cs b/MediaBrowser.Controller/IResourceFileManager.cs
deleted file mode 100644
index f70ea6a17..000000000
--- a/MediaBrowser.Controller/IResourceFileManager.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller
-{
- public interface IResourceFileManager
- {
- Task<object> GetStaticFileResult(IRequest request, string basePath, string virtualPath, string contentType, TimeSpan? cacheDuration);
-
- Stream GetResourceFileStream(string basePath, string virtualPath);
-
- string ReadAllText(string basePath, string virtualPath);
- }
-}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index 22797aa0d..7e5e742f5 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -1,27 +1,21 @@
-using System;
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
+using System.Net;
using MediaBrowser.Common;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller
{
/// <summary>
- /// Interface IServerApplicationHost
+ /// Interface IServerApplicationHost.
/// </summary>
public interface IServerApplicationHost : IApplicationHost
{
- event EventHandler HasUpdateAvailableChanged;
-
- /// <summary>
- /// Gets the system info.
- /// </summary>
- /// <returns>SystemInfo.</returns>
- Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken);
-
- Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken);
+ bool CoreStartupHasCompleted { get; }
bool CanLaunchWebBrowser { get; }
@@ -38,16 +32,9 @@ namespace MediaBrowser.Controller
int HttpsPort { get; }
/// <summary>
- /// Gets a value indicating whether [supports HTTPS].
- /// </summary>
- /// <value><c>true</c> if [supports HTTPS]; otherwise, <c>false</c>.</value>
- bool EnableHttps { get; }
-
- /// <summary>
- /// Gets a value indicating whether this instance has update available.
+ /// Gets a value indicating whether the server should listen on an HTTPS port.
/// </summary>
- /// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
- bool HasUpdateAvailable { get; }
+ bool ListenWithHttps { get; }
/// <summary>
/// Gets the name of the friendly.
@@ -56,38 +43,70 @@ namespace MediaBrowser.Controller
string FriendlyName { get; }
/// <summary>
- /// Gets the local ip address.
+ /// Gets the configured published server url.
/// </summary>
- /// <value>The local ip address.</value>
- Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken);
+ string PublishedServerUrl { get; }
/// <summary>
- /// Gets the local API URL.
+ /// Gets the system info.
/// </summary>
- /// <value>The local API URL.</value>
- Task<string> GetLocalApiUrl(CancellationToken cancellationToken);
+ /// <param name="request">The HTTP request.</param>
+ /// <returns>SystemInfo.</returns>
+ SystemInfo GetSystemInfo(HttpRequest request);
+
+ PublicSystemInfo GetPublicSystemInfo(HttpRequest request);
/// <summary>
- /// Gets the local API URL.
+ /// Gets a URL specific for the request.
/// </summary>
- /// <param name="host">The host.</param>
- /// <returns>System.String.</returns>
- string GetLocalApiUrl(string host);
+ /// <param name="request">The <see cref="HttpRequest"/> instance.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(HttpRequest request, int? port = null);
/// <summary>
- /// Gets the local API URL.
+ /// Gets a URL specific for the request.
/// </summary>
- string GetLocalApiUrl(IpAddressInfo address);
+ /// <param name="remoteAddr">The remote <see cref="IPAddress"/> of the connection.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(IPAddress remoteAddr, int? port = null);
- void LaunchUrl(string url);
-
- void EnableLoopback(string appName);
+ /// <summary>
+ /// Gets a URL specific for the request.
+ /// </summary>
+ /// <param name="hostname">The hostname used in the connection.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(string hostname, int? port = null);
- string PackageRuntime { get; }
+ /// <summary>
+ /// Gets a localhost URL that can be used to access the API using the loop-back IP address.
+ /// over HTTP (not HTTPS).
+ /// </summary>
+ /// <returns>The API URL.</returns>
+ string GetLoopbackHttpApiUrl();
- WakeOnLanInfo[] GetWakeOnLanInfo();
+ /// <summary>
+ /// Gets a local (LAN) URL that can be used to access the API.
+ /// Note: if passing non-null scheme or port it is up to the caller to ensure they form the correct pair.
+ /// </summary>
+ /// <param name="hostname">The hostname to use in the URL.</param>
+ /// <param name="scheme">
+ /// The scheme to use for the URL. If null, the scheme will be selected automatically,
+ /// preferring HTTPS, if available.
+ /// </param>
+ /// <param name="port">
+ /// The port to use for the URL. If null, the port will be selected automatically,
+ /// preferring the HTTPS port, if available.
+ /// </param>
+ /// <returns>The API URL.</returns>
+ string GetLocalApiUrl(string hostname, string scheme = null, int? port = null);
+
+ IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo();
string ExpandVirtualPath(string path);
+
string ReverseVirtualPath(string path);
}
}
diff --git a/MediaBrowser.Controller/IServerApplicationPaths.cs b/MediaBrowser.Controller/IServerApplicationPaths.cs
index 15d7e9f62..1890dbb36 100644
--- a/MediaBrowser.Controller/IServerApplicationPaths.cs
+++ b/MediaBrowser.Controller/IServerApplicationPaths.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Common.Configuration;
namespace MediaBrowser.Controller
@@ -5,37 +9,25 @@ namespace MediaBrowser.Controller
public interface IServerApplicationPaths : IApplicationPaths
{
/// <summary>
- /// Gets the path to the base root media directory
+ /// Gets the path to the base root media directory.
/// </summary>
/// <value>The root folder path.</value>
string RootFolderPath { get; }
/// <summary>
- /// Gets the application resources path. This is the path to the folder containing resources that are deployed as part of the application
- /// </summary>
- /// <value>The application resources path.</value>
- string ApplicationResourcesPath { get; }
-
- /// <summary>
/// Gets the path to the default user view directory. Used if no specific user view is defined.
/// </summary>
/// <value>The default user views path.</value>
string DefaultUserViewsPath { get; }
/// <summary>
- /// Gets the path to localization data.
- /// </summary>
- /// <value>The localization path.</value>
- string LocalizationPath { get; }
-
- /// <summary>
- /// Gets the path to the People directory
+ /// Gets the path to the People directory.
/// </summary>
/// <value>The people path.</value>
string PeoplePath { get; }
/// <summary>
- /// Gets the path to the Genre directory
+ /// Gets the path to the Genre directory.
/// </summary>
/// <value>The genre path.</value>
string GenrePath { get; }
@@ -47,25 +39,25 @@ namespace MediaBrowser.Controller
string MusicGenrePath { get; }
/// <summary>
- /// Gets the path to the Studio directory
+ /// Gets the path to the Studio directory.
/// </summary>
/// <value>The studio path.</value>
string StudioPath { get; }
/// <summary>
- /// Gets the path to the Year directory
+ /// Gets the path to the Year directory.
/// </summary>
/// <value>The year path.</value>
string YearPath { get; }
/// <summary>
- /// Gets the path to the General IBN directory
+ /// Gets the path to the General IBN directory.
/// </summary>
/// <value>The general path.</value>
string GeneralPath { get; }
/// <summary>
- /// Gets the path to the Ratings IBN directory
+ /// Gets the path to the Ratings IBN directory.
/// </summary>
/// <value>The ratings path.</value>
string RatingsPath { get; }
@@ -77,26 +69,32 @@ namespace MediaBrowser.Controller
string MediaInfoImagesPath { get; }
/// <summary>
- /// Gets the path to the user configuration directory
+ /// Gets the path to the user configuration directory.
/// </summary>
/// <value>The user configuration directory path.</value>
string UserConfigurationDirectoryPath { get; }
/// <summary>
- /// Gets the transcoding temporary path.
+ /// Gets the default internal metadata path.
/// </summary>
- /// <value>The transcoding temporary path.</value>
- string TranscodingTempPath { get; }
+ string DefaultInternalMetadataPath { get; }
/// <summary>
- /// Gets the internal metadata path.
+ /// Gets the internal metadata path, either a custom path or the default.
/// </summary>
/// <value>The internal metadata path.</value>
string InternalMetadataPath { get; }
+
+ /// <summary>
+ /// Gets the virtual internal metadata path, either a custom path or the default.
+ /// </summary>
+ /// <value>The virtual internal metadata path.</value>
string VirtualInternalMetadataPath { get; }
+ /// <summary>
+ /// Gets the path to the artists directory.
+ /// </summary>
+ /// <value>The artists path.</value>
string ArtistsPath { get; }
-
- string GetTranscodingTempPath();
}
}
diff --git a/MediaBrowser.Controller/Library/DeleteOptions.cs b/MediaBrowser.Controller/Library/DeleteOptions.cs
index 751b90481..408e70284 100644
--- a/MediaBrowser.Controller/Library/DeleteOptions.cs
+++ b/MediaBrowser.Controller/Library/DeleteOptions.cs
@@ -1,13 +1,16 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Library
{
public class DeleteOptions
{
- public bool DeleteFileLocation { get; set; }
- public bool DeleteFromExternalProvider { get; set; }
-
public DeleteOptions()
{
DeleteFromExternalProvider = true;
}
+
+ public bool DeleteFileLocation { get; set; }
+
+ public bool DeleteFromExternalProvider { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Library/IDirectStreamProvider.cs b/MediaBrowser.Controller/Library/IDirectStreamProvider.cs
new file mode 100644
index 000000000..96f8b7eba
--- /dev/null
+++ b/MediaBrowser.Controller/Library/IDirectStreamProvider.cs
@@ -0,0 +1,19 @@
+using System.IO;
+
+namespace MediaBrowser.Controller.Library
+{
+ /// <summary>
+ /// The direct live TV stream provider.
+ /// </summary>
+ /// <remarks>
+ /// Deprecated.
+ /// </remarks>
+ public interface IDirectStreamProvider
+ {
+ /// <summary>
+ /// Gets the live stream, shared streams seek to the end of the file first.
+ /// </summary>
+ /// <returns>The stream.</returns>
+ Stream GetStream();
+ }
+}
diff --git a/MediaBrowser.Controller/Library/IIntroProvider.cs b/MediaBrowser.Controller/Library/IIntroProvider.cs
index d9d1ca8c7..a74d1b9f0 100644
--- a/MediaBrowser.Controller/Library/IIntroProvider.cs
+++ b/MediaBrowser.Controller/Library/IIntroProvider.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System.Collections.Generic;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -5,28 +7,28 @@ using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Class BaseIntroProvider
+ /// Class BaseIntroProvider.
/// </summary>
public interface IIntroProvider
{
/// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ string Name { get; }
+
+ /// <summary>
/// Gets the intros.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="user">The user.</param>
/// <returns>IEnumerable{System.String}.</returns>
- Task<IEnumerable<IntroInfo>> GetIntros(BaseItem item, User user);
+ Task<IEnumerable<IntroInfo>> GetIntros(BaseItem item, Jellyfin.Data.Entities.User user);
/// <summary>
/// Gets all intro files.
/// </summary>
/// <returns>IEnumerable{System.String}.</returns>
IEnumerable<string> GetAllIntroFiles();
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
}
}
diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs
index 511356aa4..d40e56c7d 100644
--- a/MediaBrowser.Controller/Library/ILibraryManager.cs
+++ b/MediaBrowser.Controller/Library/ILibraryManager.cs
@@ -1,11 +1,17 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
+using Emby.Naming.Common;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Controller.Sorting;
@@ -14,42 +20,70 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Genre = MediaBrowser.Controller.Entities.Genre;
+using Person = MediaBrowser.Controller.Entities.Person;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Interface ILibraryManager
+ /// Interface ILibraryManager.
/// </summary>
public interface ILibraryManager
{
/// <summary>
+ /// Occurs when [item added].
+ /// </summary>
+ event EventHandler<ItemChangeEventArgs> ItemAdded;
+
+ /// <summary>
+ /// Occurs when [item updated].
+ /// </summary>
+ event EventHandler<ItemChangeEventArgs> ItemUpdated;
+
+ /// <summary>
+ /// Occurs when [item removed].
+ /// </summary>
+ event EventHandler<ItemChangeEventArgs> ItemRemoved;
+
+ /// <summary>
+ /// Gets the root folder.
+ /// </summary>
+ /// <value>The root folder.</value>
+ AggregateFolder RootFolder { get; }
+
+ bool IsScanRunning { get; }
+
+ /// <summary>
/// Resolves the path.
/// </summary>
/// <param name="fileInfo">The file information.</param>
/// <param name="parent">The parent.</param>
/// <returns>BaseItem.</returns>
- BaseItem ResolvePath(FileSystemMetadata fileInfo,
+ BaseItem ResolvePath(
+ FileSystemMetadata fileInfo,
Folder parent = null);
/// <summary>
- /// Resolves a set of files into a list of BaseItem
+ /// Resolves a set of files into a list of BaseItem.
/// </summary>
- IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
+ /// <param name="files">The list of tiles.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ /// <param name="parent">The parent folder.</param>
+ /// <param name="libraryOptions">The library options.</param>
+ /// <param name="collectionType">The collection type.</param>
+ /// <returns>The items resolved from the paths.</returns>
+ IEnumerable<BaseItem> ResolvePaths(
+ IEnumerable<FileSystemMetadata> files,
IDirectoryService directoryService,
Folder parent,
LibraryOptions libraryOptions,
string collectionType = null);
/// <summary>
- /// Gets the root folder.
+ /// Gets a Person.
/// </summary>
- /// <value>The root folder.</value>
- AggregateFolder RootFolder { get; }
-
- /// <summary>
- /// Gets a Person
- /// </summary>
- /// <param name="name">The name.</param>
+ /// <param name="name">The name of the person.</param>
/// <returns>Task{Person}.</returns>
Person GetPerson(string name);
@@ -57,43 +91,46 @@ namespace MediaBrowser.Controller.Library
/// Finds the by path.
/// </summary>
/// <param name="path">The path.</param>
+ /// <param name="isFolder"><c>true</c> is the path is a directory; otherwise <c>false</c>.</param>
/// <returns>BaseItem.</returns>
BaseItem FindByPath(string path, bool? isFolder);
/// <summary>
/// Gets the artist.
/// </summary>
- /// <param name="name">The name.</param>
+ /// <param name="name">The name of the artist.</param>
/// <returns>Task{Artist}.</returns>
MusicArtist GetArtist(string name);
+
MusicArtist GetArtist(string name, DtoOptions options);
+
/// <summary>
- /// Gets a Studio
+ /// Gets a Studio.
/// </summary>
- /// <param name="name">The name.</param>
+ /// <param name="name">The name of the studio.</param>
/// <returns>Task{Studio}.</returns>
Studio GetStudio(string name);
/// <summary>
- /// Gets a Genre
+ /// Gets a Genre.
/// </summary>
- /// <param name="name">The name.</param>
+ /// <param name="name">The name of the genre.</param>
/// <returns>Task{Genre}.</returns>
Genre GetGenre(string name);
/// <summary>
/// Gets the genre.
/// </summary>
- /// <param name="name">The name.</param>
+ /// <param name="name">The name of the music genre.</param>
/// <returns>Task{MusicGenre}.</returns>
MusicGenre GetMusicGenre(string name);
/// <summary>
- /// Gets a Year
+ /// Gets a Year.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>Task{Year}.</returns>
- /// <exception cref="ArgumentOutOfRangeException"></exception>
+ /// <exception cref="ArgumentOutOfRangeException">Throws if year is invalid.</exception>
Year GetYear(int value);
/// <summary>
@@ -106,7 +143,7 @@ namespace MediaBrowser.Controller.Library
Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress);
/// <summary>
- /// Reloads the root media folder
+ /// Reloads the root media folder.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
@@ -118,7 +155,7 @@ namespace MediaBrowser.Controller.Library
/// </summary>
void QueueLibraryScan();
- void UpdateImages(BaseItem item);
+ Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false);
/// <summary>
/// Gets the default view.
@@ -157,7 +194,8 @@ namespace MediaBrowser.Controller.Library
/// <param name="introProviders">The intro providers.</param>
/// <param name="itemComparers">The item comparers.</param>
/// <param name="postscanTasks">The postscan tasks.</param>
- void AddParts(IEnumerable<IResolverIgnoreRule> rules,
+ void AddParts(
+ IEnumerable<IResolverIgnoreRule> rules,
IEnumerable<IItemResolver> resolvers,
IEnumerable<IIntroProvider> introProviders,
IEnumerable<IBaseItemComparer> itemComparers,
@@ -172,6 +210,7 @@ namespace MediaBrowser.Controller.Library
/// <param name="sortOrder">The sort order.</param>
/// <returns>IEnumerable{BaseItem}.</returns>
IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder);
+
IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<ValueTuple<string, SortOrder>> orderBy);
/// <summary>
@@ -183,18 +222,37 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Creates the item.
/// </summary>
+ /// <param name="item">Item to create.</param>
+ /// <param name="parent">Parent of new item.</param>
void CreateItem(BaseItem item, BaseItem parent);
/// <summary>
/// Creates the items.
/// </summary>
- void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken);
+ /// <param name="items">Items to create.</param>
+ /// <param name="parent">Parent of new items.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ void CreateItems(IReadOnlyList<BaseItem> items, BaseItem parent, CancellationToken cancellationToken);
/// <summary>
/// Updates the item.
/// </summary>
- void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken);
- void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken);
+ /// <param name="items">Items to update.</param>
+ /// <param name="parent">Parent of updated items.</param>
+ /// <param name="updateReason">Reason for update.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>Returns a Task that can be awaited.</returns>
+ Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Updates the item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="parent">The parent item.</param>
+ /// <param name="updateReason">The update reason.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Returns a Task that can be awaited.</returns>
+ Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken);
/// <summary>
/// Retrieves the item.
@@ -203,22 +261,6 @@ namespace MediaBrowser.Controller.Library
/// <returns>BaseItem.</returns>
BaseItem RetrieveItem(Guid id);
- bool IsScanRunning { get; }
-
- /// <summary>
- /// Occurs when [item added].
- /// </summary>
- event EventHandler<ItemChangeEventArgs> ItemAdded;
-
- /// <summary>
- /// Occurs when [item updated].
- /// </summary>
- event EventHandler<ItemChangeEventArgs> ItemUpdated;
- /// <summary>
- /// Occurs when [item removed].
- /// </summary>
- event EventHandler<ItemChangeEventArgs> ItemRemoved;
-
/// <summary>
/// Finds the type of the collection.
/// </summary>
@@ -263,16 +305,25 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Deletes the item.
/// </summary>
+ /// <param name="item">Item to delete.</param>
+ /// <param name="options">Options to use for deletion.</param>
void DeleteItem(BaseItem item, DeleteOptions options);
/// <summary>
/// Deletes the item.
/// </summary>
+ /// <param name="item">Item to delete.</param>
+ /// <param name="options">Options to use for deletion.</param>
+ /// <param name="notifyParentItem">Notify parent of deletion.</param>
void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem);
/// <summary>
/// Deletes the item.
/// </summary>
+ /// <param name="item">Item to delete.</param>
+ /// <param name="options">Options to use for deletion.</param>
+ /// <param name="parent">Parent of item.</param>
+ /// <param name="notifyParentItem">Notify parent of deletion.</param>
void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem);
/// <summary>
@@ -283,7 +334,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="parentId">The parent identifier.</param>
/// <param name="viewType">Type of the view.</param>
/// <param name="sortName">Name of the sort.</param>
- UserView GetNamedView(User user,
+ /// <returns>The named view.</returns>
+ UserView GetNamedView(
+ User user,
string name,
Guid parentId,
string viewType,
@@ -296,7 +349,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="name">The name.</param>
/// <param name="viewType">Type of the view.</param>
/// <param name="sortName">Name of the sort.</param>
- UserView GetNamedView(User user,
+ /// <returns>The named view.</returns>
+ UserView GetNamedView(
+ User user,
string name,
string viewType,
string sortName);
@@ -307,7 +362,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="name">The name.</param>
/// <param name="viewType">Type of the view.</param>
/// <param name="sortName">Name of the sort.</param>
- UserView GetNamedView(string name,
+ /// <returns>The named view.</returns>
+ UserView GetNamedView(
+ string name,
string viewType,
string sortName);
@@ -319,7 +376,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="viewType">Type of the view.</param>
/// <param name="sortName">Name of the sort.</param>
/// <param name="uniqueId">The unique identifier.</param>
- UserView GetNamedView(string name,
+ /// <returns>The named view.</returns>
+ UserView GetNamedView(
+ string name,
Guid parentId,
string viewType,
string sortName,
@@ -331,9 +390,11 @@ namespace MediaBrowser.Controller.Library
/// <param name="parent">The parent.</param>
/// <param name="viewType">Type of the view.</param>
/// <param name="sortName">Name of the sort.</param>
- UserView GetShadowView(BaseItem parent,
- string viewType,
- string sortName);
+ /// <returns>The shadow view.</returns>
+ UserView GetShadowView(
+ BaseItem parent,
+ string viewType,
+ string sortName);
/// <summary>
/// Determines whether [is video file] [the specified path].
@@ -349,9 +410,6 @@ namespace MediaBrowser.Controller.Library
/// <returns><c>true</c> if [is audio file] [the specified path]; otherwise, <c>false</c>.</returns>
bool IsAudioFile(string path);
- bool IsAudioFile(string path, LibraryOptions libraryOptions);
- bool IsVideoFile(string path, LibraryOptions libraryOptions);
-
/// <summary>
/// Gets the season number from path.
/// </summary>
@@ -362,6 +420,9 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Fills the missing episode numbers from path.
/// </summary>
+ /// <param name="episode">Episode to use.</param>
+ /// <param name="forceRefresh">Option to force refresh of episode numbers.</param>
+ /// <returns>True if successful.</returns>
bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh);
/// <summary>
@@ -386,7 +447,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="fileSystemChildren">The file system children.</param>
/// <param name="directoryService">The directory service.</param>
/// <returns>IEnumerable&lt;Trailer&gt;.</returns>
- IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren,
+ IEnumerable<Video> FindTrailers(
+ BaseItem owner,
+ List<FileSystemMetadata> fileSystemChildren,
IDirectoryService directoryService);
/// <summary>
@@ -396,7 +459,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="fileSystemChildren">The file system children.</param>
/// <param name="directoryService">The directory service.</param>
/// <returns>IEnumerable&lt;Video&gt;.</returns>
- IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren,
+ IEnumerable<Video> FindExtras(
+ BaseItem owner,
+ List<FileSystemMetadata> fileSystemChildren,
IDirectoryService directoryService);
/// <summary>
@@ -439,6 +504,15 @@ namespace MediaBrowser.Controller.Library
void UpdatePeople(BaseItem item, List<PersonInfo> people);
/// <summary>
+ /// Asynchronously updates the people.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="people">The people.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The async task.</returns>
+ Task UpdatePeopleAsync(BaseItem item, List<PersonInfo> people, CancellationToken cancellationToken);
+
+ /// <summary>
/// Gets the item ids.
/// </summary>
/// <param name="query">The query.</param>
@@ -491,6 +565,9 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Gets the items.
/// </summary>
+ /// <param name="query">The query to use.</param>
+ /// <param name="parents">Items to use for query.</param>
+ /// <returns>List of items.</returns>
List<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents);
/// <summary>
@@ -514,23 +591,45 @@ namespace MediaBrowser.Controller.Library
Guid GetMusicGenreId(string name);
- Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary);
+ Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary);
+
Task RemoveVirtualFolder(string name, bool refreshLibrary);
- void AddMediaPath(string virtualFolderName, MediaPathInfo path);
- void UpdateMediaPath(string virtualFolderName, MediaPathInfo path);
- void RemoveMediaPath(string virtualFolderName, string path);
+
+ void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath);
+
+ void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath);
+
+ void RemoveMediaPath(string virtualFolderName, string mediaPath);
QueryResult<(BaseItem, ItemCounts)> GetGenres(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetMusicGenres(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetStudios(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetArtists(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetAlbumArtists(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetAllArtists(InternalItemsQuery query);
int GetCount(InternalItemsQuery query);
- void AddExternalSubtitleStreams(List<MediaStream> streams,
+ void AddExternalSubtitleStreams(
+ List<MediaStream> streams,
string videoPath,
string[] files);
+
+ Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason);
+
+ BaseItem GetParentItem(string parentId, Guid? userId);
+
+ BaseItem GetParentItem(Guid? parentId, Guid? userId);
+
+ /// <summary>
+ /// Gets or creates a static instance of <see cref="NamingOptions"/>.
+ /// </summary>
+ /// <returns>An instance of the <see cref="NamingOptions"/> class.</returns>
+ NamingOptions GetNamingOptions();
}
}
diff --git a/MediaBrowser.Controller/Library/ILibraryMonitor.cs b/MediaBrowser.Controller/Library/ILibraryMonitor.cs
index 233cfb197..455054bd1 100644
--- a/MediaBrowser.Controller/Library/ILibraryMonitor.cs
+++ b/MediaBrowser.Controller/Library/ILibraryMonitor.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Library
diff --git a/MediaBrowser.Controller/Library/ILibraryPostScanTask.cs b/MediaBrowser.Controller/Library/ILibraryPostScanTask.cs
index cba5e8fd7..4032e9d83 100644
--- a/MediaBrowser.Controller/Library/ILibraryPostScanTask.cs
+++ b/MediaBrowser.Controller/Library/ILibraryPostScanTask.cs
@@ -5,7 +5,7 @@ using System.Threading.Tasks;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// An interface for tasks that run after the media library scan
+ /// An interface for tasks that run after the media library scan.
/// </summary>
public interface ILibraryPostScanTask
{
diff --git a/MediaBrowser.Controller/Library/ILiveStream.cs b/MediaBrowser.Controller/Library/ILiveStream.cs
index 734932f17..4c44a17fd 100644
--- a/MediaBrowser.Controller/Library/ILiveStream.cs
+++ b/MediaBrowser.Controller/Library/ILiveStream.cs
@@ -1,3 +1,8 @@
+#nullable disable
+
+#pragma warning disable CA1711, CS1591
+
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Dto;
@@ -6,13 +11,22 @@ namespace MediaBrowser.Controller.Library
{
public interface ILiveStream
{
- Task Open(CancellationToken openCancellationToken);
- Task Close();
int ConsumerCount { get; set; }
+
string OriginalStreamId { get; set; }
+
string TunerHostId { get; }
+
bool EnableStreamSharing { get; }
+
MediaSourceInfo MediaSource { get; set; }
+
string UniqueId { get; }
+
+ Task Open(CancellationToken openCancellationToken);
+
+ Task Close();
+
+ Stream GetStream();
}
}
diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
index fbae4edb0..e802796d3 100644
--- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs
+++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
-using System.IO;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Dto;
@@ -25,12 +29,14 @@ namespace MediaBrowser.Controller.Library
/// <param name="itemId">The item identifier.</param>
/// <returns>IEnumerable&lt;MediaStream&gt;.</returns>
List<MediaStream> GetMediaStreams(Guid itemId);
+
/// <summary>
/// Gets the media streams.
/// </summary>
/// <param name="mediaSourceId">The media source identifier.</param>
/// <returns>IEnumerable&lt;MediaStream&gt;.</returns>
List<MediaStream> GetMediaStreams(string mediaSourceId);
+
/// <summary>
/// Gets the media streams.
/// </summary>
@@ -39,18 +45,48 @@ namespace MediaBrowser.Controller.Library
List<MediaStream> GetMediaStreams(MediaStreamQuery query);
/// <summary>
+ /// Gets the media attachments.
+ /// </summary>
+ /// <param name="itemId">The item identifier.</param>
+ /// <returns>IEnumerable&lt;MediaAttachment&gt;.</returns>
+ List<MediaAttachment> GetMediaAttachments(Guid itemId);
+
+ /// <summary>
+ /// Gets the media attachments.
+ /// </summary>
+ /// <param name="query">The query.</param>
+ /// <returns>IEnumerable&lt;MediaAttachment&gt;.</returns>
+ List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query);
+
+ /// <summary>
/// Gets the playack media sources.
/// </summary>
- Task<List<MediaSourceInfo>> GetPlayackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken);
+ /// <param name="item">Item to use.</param>
+ /// <param name="user">User to use for operation.</param>
+ /// <param name="allowMediaProbe">Option to allow media probe.</param>
+ /// <param name="enablePathSubstitution">Option to enable path substitution.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>List of media sources wrapped in an awaitable task.</returns>
+ Task<List<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken);
/// <summary>
/// Gets the static media sources.
/// </summary>
+ /// <param name="item">Item to use.</param>
+ /// <param name="enablePathSubstitution">Option to enable path substitution.</param>
+ /// <param name="user">User to use for operation.</param>
+ /// <returns>List of media sources.</returns>
List<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User user = null);
/// <summary>
/// Gets the static media source.
/// </summary>
+ /// <param name="item">Item to use.</param>
+ /// <param name="mediaSourceId">Media source to get.</param>
+ /// <param name="liveStreamId">Live stream to use.</param>
+ /// <param name="enablePathSubstitution">Option to enable path substitution.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>The static media source wrapped in an awaitable task.</returns>
Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId, bool enablePathSubstitution, CancellationToken cancellationToken);
/// <summary>
@@ -74,6 +110,20 @@ namespace MediaBrowser.Controller.Library
Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, CancellationToken cancellationToken);
/// <summary>
+ /// Gets the live stream info.
+ /// </summary>
+ /// <param name="id">The identifier.</param>
+ /// <returns>An instance of <see cref="ILiveStream"/>.</returns>
+ public ILiveStream GetLiveStreamInfo(string id);
+
+ /// <summary>
+ /// Gets the live stream info using the stream's unique id.
+ /// </summary>
+ /// <param name="uniqueId">The unique identifier.</param>
+ /// <returns>An instance of <see cref="ILiveStream"/>.</returns>
+ public ILiveStream GetLiveStreamInfoByUniqueId(string uniqueId);
+
+ /// <summary>
/// Closes the media source.
/// </summary>
/// <param name="id">The live stream identifier.</param>
@@ -89,12 +139,5 @@ namespace MediaBrowser.Controller.Library
void SetDefaultAudioAndSubtitleStreamIndexes(BaseItem item, MediaSourceInfo source, User user);
Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, bool isLiveStream, CancellationToken cancellationToken);
-
- Task<IDirectStreamProvider> GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken);
- }
-
- public interface IDirectStreamProvider
- {
- Task CopyToAsync(Stream stream, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
index 9e74879fc..ca4b53fbe 100644
--- a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
+++ b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CA1002, CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,6 +21,10 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Opens the media source.
/// </summary>
+ /// <param name="openToken">Token to use.</param>
+ /// <param name="currentLiveStreams">List of live streams.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>The media source wrapped as an awaitable task.</returns>
Task<ILiveStream> OpenMediaSource(string openToken, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Library/IMetadataFileSaver.cs b/MediaBrowser.Controller/Library/IMetadataFileSaver.cs
index 5b92388ce..9c6f03a23 100644
--- a/MediaBrowser.Controller/Library/IMetadataFileSaver.cs
+++ b/MediaBrowser.Controller/Library/IMetadataFileSaver.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Library
diff --git a/MediaBrowser.Controller/Library/IMetadataSaver.cs b/MediaBrowser.Controller/Library/IMetadataSaver.cs
index dd119984e..d963fd249 100644
--- a/MediaBrowser.Controller/Library/IMetadataSaver.cs
+++ b/MediaBrowser.Controller/Library/IMetadataSaver.cs
@@ -1,10 +1,12 @@
+#nullable disable
+
using System.Threading;
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Interface IMetadataSaver
+ /// Interface IMetadataSaver.
/// </summary>
public interface IMetadataSaver
{
@@ -27,7 +29,6 @@ namespace MediaBrowser.Controller.Library
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
void Save(BaseItem item, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Library/IMusicManager.cs b/MediaBrowser.Controller/Library/IMusicManager.cs
index 554dd0895..ec34a868b 100644
--- a/MediaBrowser.Controller/Library/IMusicManager.cs
+++ b/MediaBrowser.Controller/Library/IMusicManager.cs
@@ -1,4 +1,9 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System.Collections.Generic;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
@@ -10,16 +15,28 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Gets the instant mix from song.
/// </summary>
+ /// <param name="item">The item to use.</param>
+ /// <param name="user">The user to use.</param>
+ /// <param name="dtoOptions">The options to use.</param>
+ /// <returns>List of items.</returns>
List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions);
/// <summary>
/// Gets the instant mix from artist.
/// </summary>
+ /// <param name="artist">The artist to use.</param>
+ /// <param name="user">The user to use.</param>
+ /// <param name="dtoOptions">The options to use.</param>
+ /// <returns>List of items.</returns>
List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User user, DtoOptions dtoOptions);
/// <summary>
/// Gets the instant mix from genre.
/// </summary>
+ /// <param name="genres">The genres to use.</param>
+ /// <param name="user">The user to use.</param>
+ /// <param name="dtoOptions">The options to use.</param>
+ /// <returns>List of items.</returns>
List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User user, DtoOptions dtoOptions);
}
}
diff --git a/MediaBrowser.Controller/Library/ISearchEngine.cs b/MediaBrowser.Controller/Library/ISearchEngine.cs
index 8498b92ae..31dcbba5b 100644
--- a/MediaBrowser.Controller/Library/ISearchEngine.cs
+++ b/MediaBrowser.Controller/Library/ISearchEngine.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Model.Search;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Interface ILibrarySearchEngine
+ /// Interface ILibrarySearchEngine.
/// </summary>
public interface ISearchEngine
{
diff --git a/MediaBrowser.Controller/Library/IUserDataManager.cs b/MediaBrowser.Controller/Library/IUserDataManager.cs
index ce4e3f530..034c40591 100644
--- a/MediaBrowser.Controller/Library/IUserDataManager.cs
+++ b/MediaBrowser.Controller/Library/IUserDataManager.cs
@@ -1,6 +1,11 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA1707, CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
@@ -9,7 +14,7 @@ using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Interface IUserDataManager
+ /// Interface IUserDataManager.
/// </summary>
public interface IUserDataManager
{
@@ -26,41 +31,46 @@ namespace MediaBrowser.Controller.Library
/// <param name="userData">The user data.</param>
/// <param name="reason">The reason.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
void SaveUserData(Guid userId, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken);
- void SaveUserData(User userId, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken);
+
+ void SaveUserData(User user, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken);
UserItemData GetUserData(User user, BaseItem item);
- UserItemData GetUserData(string userId, BaseItem item);
UserItemData GetUserData(Guid userId, BaseItem item);
/// <summary>
/// Gets the user data dto.
/// </summary>
+ /// <param name="item">Item to use.</param>
+ /// <param name="user">User to use.</param>
+ /// <returns>User data dto.</returns>
UserItemDataDto GetUserDataDto(BaseItem item, User user);
- UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto itemDto, User user, DtoOptions dto_options);
+ UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto itemDto, User user, DtoOptions options);
/// <summary>
- /// Get all user data for the given user
+ /// Get all user data for the given user.
/// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <returns>The user item data.</returns>
List<UserItemData> GetAllUserData(Guid userId);
/// <summary>
- /// Save the all provided user data for the given user
+ /// Save the all provided user data for the given user.
/// </summary>
- /// <param name="userId"></param>
- /// <param name="userData"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <param name="userData">The array of user data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
void SaveAllUserData(Guid userId, UserItemData[] userData, CancellationToken cancellationToken);
/// <summary>
- /// Updates playstate for an item and returns true or false indicating if it was played to completion
+ /// Updates playstate for an item and returns true or false indicating if it was played to completion.
/// </summary>
- bool UpdatePlayState(BaseItem item, UserItemData data, long? positionTicks);
+ /// <param name="item">Item to update.</param>
+ /// <param name="data">Data to update.</param>
+ /// <param name="reportedPositionTicks">New playstate.</param>
+ /// <returns>True if playstate was updated.</returns>
+ bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks);
}
}
diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs
index 925d91a37..993e3e18f 100644
--- a/MediaBrowser.Controller/Library/IUserManager.cs
+++ b/MediaBrowser.Controller/Library/IUserManager.cs
@@ -1,59 +1,55 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Users;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Interface IUserManager
+ /// Interface IUserManager.
/// </summary>
public interface IUserManager
{
/// <summary>
+ /// Occurs when a user is updated.
+ /// </summary>
+ event EventHandler<GenericEventArgs<User>> OnUserUpdated;
+
+ /// <summary>
/// Gets the users.
/// </summary>
/// <value>The users.</value>
IEnumerable<User> Users { get; }
/// <summary>
- /// Occurs when [user updated].
+ /// Gets the user ids.
/// </summary>
- event EventHandler<GenericEventArgs<User>> UserUpdated;
+ /// <value>The users ids.</value>
+ IEnumerable<Guid> UsersIds { get; }
/// <summary>
- /// Occurs when [user deleted].
+ /// Initializes the user manager and ensures that a user exists.
/// </summary>
- event EventHandler<GenericEventArgs<User>> UserDeleted;
-
- event EventHandler<GenericEventArgs<User>> UserCreated;
- event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
- event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
- event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
- event EventHandler<GenericEventArgs<User>> UserLockedOut;
+ /// <returns>Awaitable task.</returns>
+ Task InitializeAsync();
/// <summary>
- /// Gets a User by Id
+ /// Gets a user by Id.
/// </summary>
/// <param name="id">The id.</param>
- /// <returns>User.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <returns>The user with the specified Id, or <c>null</c> if the user doesn't exist.</returns>
+ /// <exception cref="ArgumentException"><c>id</c> is an empty Guid.</exception>
User GetUserById(Guid id);
/// <summary>
- /// Gets the user by identifier.
- /// </summary>
- /// <param name="id">The identifier.</param>
- /// <returns>User.</returns>
- User GetUserById(string id);
-
- /// <summary>
/// Gets the name of the user by.
/// </summary>
/// <param name="name">The name.</param>
@@ -61,47 +57,39 @@ namespace MediaBrowser.Controller.Library
User GetUserByName(string name);
/// <summary>
- /// Refreshes metadata for each user
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- Task RefreshUsersMetadata(CancellationToken cancellationToken);
-
- /// <summary>
/// Renames the user.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="newName">The new name.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
+ /// <exception cref="ArgumentNullException">If user is <c>null</c>.</exception>
+ /// <exception cref="ArgumentException">If the provided user doesn't exist.</exception>
Task RenameUser(User user, string newName);
/// <summary>
/// Updates the user.
/// </summary>
/// <param name="user">The user.</param>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
- void UpdateUser(User user);
+ /// <exception cref="ArgumentNullException">If user is <c>null</c>.</exception>
+ /// <exception cref="ArgumentException">If the provided user doesn't exist.</exception>
+ /// <returns>A task representing the update of the user.</returns>
+ Task UpdateUserAsync(User user);
/// <summary>
- /// Creates the user.
+ /// Creates a user with the specified name.
/// </summary>
- /// <param name="name">The name.</param>
- /// <returns>User.</returns>
- /// <exception cref="ArgumentNullException">name</exception>
- /// <exception cref="ArgumentException"></exception>
- Task<User> CreateUser(string name);
+ /// <param name="name">The name of the new user.</param>
+ /// <returns>The created user.</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c> or empty.</exception>
+ /// <exception cref="ArgumentException"><paramref name="name"/> already exists.</exception>
+ Task<User> CreateUserAsync(string name);
/// <summary>
- /// Deletes the user.
+ /// Deletes the specified user.
/// </summary>
- /// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">user</exception>
- /// <exception cref="ArgumentException"></exception>
- Task DeleteUser(User user);
+ /// <param name="userId">The id of the user to be deleted.</param>
+ /// <returns>A task representing the deletion of the user.</returns>
+ Task DeleteUserAsync(Guid userId);
/// <summary>
/// Resets the password.
@@ -111,28 +99,28 @@ namespace MediaBrowser.Controller.Library
Task ResetPassword(User user);
/// <summary>
- /// Gets the offline user dto.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>UserDto.</returns>
- UserDto GetOfflineUserDto(User user);
-
- /// <summary>
/// Resets the easy password.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
- void ResetEasyPassword(User user);
+ Task ResetEasyPassword(User user);
/// <summary>
/// Changes the password.
/// </summary>
+ /// <param name="user">The user.</param>
+ /// <param name="newPassword">New password to use.</param>
+ /// <returns>Awaitable task.</returns>
Task ChangePassword(User user, string newPassword);
/// <summary>
/// Changes the easy password.
/// </summary>
- void ChangeEasyPassword(User user, string newPassword, string newPasswordSha1);
+ /// <param name="user">The user.</param>
+ /// <param name="newPassword">New password to use.</param>
+ /// <param name="newPasswordSha1">Hash of new password.</param>
+ /// <returns>Task.</returns>
+ Task ChangeEasyPassword(User user, string newPassword, string newPasswordSha1);
/// <summary>
/// Gets the user dto.
@@ -145,6 +133,12 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Authenticates the user.
/// </summary>
+ /// <param name="username">The user.</param>
+ /// <param name="password">The password to use.</param>
+ /// <param name="passwordSha1">Hash of password.</param>
+ /// <param name="remoteEndPoint">Remove endpoint to use.</param>
+ /// <param name="isUserSession">Specifies if a user session.</param>
+ /// <returns>User wrapped in awaitable task.</returns>
Task<User> AuthenticateUser(string username, string password, string passwordSha1, string remoteEndPoint, bool isUserSession);
/// <summary>
@@ -162,46 +156,35 @@ namespace MediaBrowser.Controller.Library
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
Task<PinRedeemResult> RedeemPasswordResetPin(string pin);
- /// <summary>
- /// Gets the user policy.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>UserPolicy.</returns>
- UserPolicy GetUserPolicy(User user);
+ NameIdPair[] GetAuthenticationProviders();
- /// <summary>
- /// Gets the user configuration.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>UserConfiguration.</returns>
- UserConfiguration GetUserConfiguration(User user);
+ NameIdPair[] GetPasswordResetProviders();
/// <summary>
- /// Updates the configuration.
+ /// This method updates the user's configuration.
+ /// This is only included as a stopgap until the new API, using this internally is not recommended.
+ /// Instead, modify the user object directly, then call <see cref="UpdateUserAsync"/>.
/// </summary>
- /// <param name="userId">The user identifier.</param>
- /// <param name="newConfiguration">The new configuration.</param>
- /// <returns>Task.</returns>
- void UpdateConfiguration(Guid userId, UserConfiguration newConfiguration);
-
- void UpdateConfiguration(User user, UserConfiguration newConfiguration);
+ /// <param name="userId">The user's Id.</param>
+ /// <param name="config">The request containing the new user configuration.</param>
+ /// <returns>A task representing the update.</returns>
+ Task UpdateConfigurationAsync(Guid userId, UserConfiguration config);
/// <summary>
- /// Updates the user policy.
+ /// This method updates the user's policy.
+ /// This is only included as a stopgap until the new API, using this internally is not recommended.
+ /// Instead, modify the user object directly, then call <see cref="UpdateUserAsync"/>.
/// </summary>
- /// <param name="userId">The user identifier.</param>
- /// <param name="userPolicy">The user policy.</param>
- void UpdateUserPolicy(Guid userId, UserPolicy userPolicy);
+ /// <param name="userId">The user's Id.</param>
+ /// <param name="policy">The request containing the new user policy.</param>
+ /// <returns>A task representing the update.</returns>
+ Task UpdatePolicyAsync(Guid userId, UserPolicy policy);
/// <summary>
- /// Makes the valid username.
+ /// Clears the user's profile image.
/// </summary>
- /// <param name="username">The username.</param>
- /// <returns>System.String.</returns>
- string MakeValidUsername(string username);
-
- void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders);
-
- NameIdPair[] GetAuthenticationProviders();
+ /// <param name="user">The user.</param>
+ /// <returns>A task representing the clearing of the profile image.</returns>
+ Task ClearProfileImageAsync(User user);
}
}
diff --git a/MediaBrowser.Controller/Library/IUserViewManager.cs b/MediaBrowser.Controller/Library/IUserViewManager.cs
index 0d7da7579..055627d3e 100644
--- a/MediaBrowser.Controller/Library/IUserViewManager.cs
+++ b/MediaBrowser.Controller/Library/IUserViewManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Dto;
@@ -9,9 +13,29 @@ namespace MediaBrowser.Controller.Library
{
public interface IUserViewManager
{
+ /// <summary>
+ /// Gets user views.
+ /// </summary>
+ /// <param name="query">Query to use.</param>
+ /// <returns>Set of folders.</returns>
Folder[] GetUserViews(UserViewQuery query);
+
+ /// <summary>
+ /// Gets user sub views.
+ /// </summary>
+ /// <param name="parentId">Parent to use.</param>
+ /// <param name="type">Type to use.</param>
+ /// <param name="localizationKey">Localization key to use.</param>
+ /// <param name="sortName">Sort to use.</param>
+ /// <returns>User view.</returns>
UserView GetUserSubView(Guid parentId, string type, string localizationKey, string sortName);
+ /// <summary>
+ /// Gets latest items.
+ /// </summary>
+ /// <param name="request">Query to use.</param>
+ /// <param name="options">Options to use.</param>
+ /// <returns>Set of items.</returns>
List<Tuple<BaseItem, List<BaseItem>>> GetLatestItems(LatestItemsQuery request, DtoOptions options);
}
}
diff --git a/MediaBrowser.Controller/Library/IntroInfo.cs b/MediaBrowser.Controller/Library/IntroInfo.cs
index 0e761d549..90786786b 100644
--- a/MediaBrowser.Controller/Library/IntroInfo.cs
+++ b/MediaBrowser.Controller/Library/IntroInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Library
diff --git a/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs b/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs
index c9671de47..3586dc69d 100644
--- a/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs
+++ b/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs
@@ -1,9 +1,13 @@
+#nullable disable
+
+#pragma warning disable CA1711, CS1591
+
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Class ItemChangeEventArgs
+ /// Class ItemChangeEventArgs.
/// </summary>
public class ItemChangeEventArgs
{
diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
index 0222b926e..bfc1e4857 100644
--- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs
+++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1721, CA1819, CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -12,14 +16,14 @@ namespace MediaBrowser.Controller.Library
/// These are arguments relating to the file system that are collected once and then referred to
/// whenever needed. Primarily for entity resolution.
/// </summary>
- public class ItemResolveArgs : EventArgs
+ public class ItemResolveArgs
{
/// <summary>
- /// The _app paths
+ /// The _app paths.
/// </summary>
private readonly IServerApplicationPaths _appPaths;
- public IDirectoryService DirectoryService { get; private set; }
+ private LibraryOptions _libraryOptions;
/// <summary>
/// Initializes a new instance of the <see cref="ItemResolveArgs" /> class.
@@ -32,17 +36,18 @@ namespace MediaBrowser.Controller.Library
DirectoryService = directoryService;
}
+ public IDirectoryService DirectoryService { get; }
+
/// <summary>
- /// Gets the file system children.
+ /// Gets or sets the file system children.
/// </summary>
/// <value>The file system children.</value>
public FileSystemMetadata[] FileSystemChildren { get; set; }
- public LibraryOptions LibraryOptions { get; set; }
-
- public LibraryOptions GetLibraryOptions()
+ public LibraryOptions LibraryOptions
{
- return LibraryOptions ?? (LibraryOptions = (Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent)));
+ get => _libraryOptions ??= Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent);
+ set => _libraryOptions = value;
}
/// <summary>
@@ -58,10 +63,10 @@ namespace MediaBrowser.Controller.Library
public FileSystemMetadata FileInfo { get; set; }
/// <summary>
- /// Gets or sets the path.
+ /// Gets the path.
/// </summary>
/// <value>The path.</value>
- public string Path { get; set; }
+ public string Path => FileInfo.FullName;
/// <summary>
/// Gets a value indicating whether this instance is directory.
@@ -89,7 +94,6 @@ namespace MediaBrowser.Controller.Library
return parentDir.Length > _appPaths.RootFolderPath.Length
&& parentDir.StartsWith(_appPaths.RootFolderPath, StringComparison.OrdinalIgnoreCase);
-
}
}
@@ -105,6 +109,21 @@ namespace MediaBrowser.Controller.Library
/// <value>The additional locations.</value>
private List<string> AdditionalLocations { get; set; }
+ /// <summary>
+ /// Gets the physical locations.
+ /// </summary>
+ /// <value>The physical locations.</value>
+ public string[] PhysicalLocations
+ {
+ get
+ {
+ var paths = string.IsNullOrEmpty(Path) ? Array.Empty<string>() : new[] { Path };
+ return AdditionalLocations == null ? paths : paths.Concat(AdditionalLocations).ToArray();
+ }
+ }
+
+ public string CollectionType { get; set; }
+
public bool HasParent<T>()
where T : Folder
{
@@ -129,16 +148,26 @@ namespace MediaBrowser.Controller.Library
}
return item != null;
-
}
+
return false;
}
/// <summary>
+ /// Determines whether the specified <see cref="object" /> is equal to this instance.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns><c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
+ public override bool Equals(object obj)
+ {
+ return Equals(obj as ItemResolveArgs);
+ }
+
+ /// <summary>
/// Adds the additional location.
/// </summary>
/// <param name="path">The path.</param>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException"><paramref name="path"/> is <c>null</c> or empty.</exception>
public void AddAdditionalLocation(string path)
{
if (string.IsNullOrEmpty(path))
@@ -146,34 +175,18 @@ namespace MediaBrowser.Controller.Library
throw new ArgumentException("The path was empty or null.", nameof(path));
}
- if (AdditionalLocations == null)
- {
- AdditionalLocations = new List<string>();
- }
-
+ AdditionalLocations ??= new List<string>();
AdditionalLocations.Add(path);
}
// REVIEW: @bond
- /// <summary>
- /// Gets the physical locations.
- /// </summary>
- /// <value>The physical locations.</value>
- public string[] PhysicalLocations
- {
- get
- {
- var paths = string.IsNullOrEmpty(Path) ? Array.Empty<string>() : new[] { Path };
- return AdditionalLocations == null ? paths : paths.Concat(AdditionalLocations).ToArray();
- }
- }
/// <summary>
/// Gets the name of the file system entry by.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>FileSystemInfo.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c> or empty.</exception>
public FileSystemMetadata GetFileSystemEntryByName(string name)
{
if (string.IsNullOrEmpty(name))
@@ -189,7 +202,7 @@ namespace MediaBrowser.Controller.Library
/// </summary>
/// <param name="path">The path.</param>
/// <returns>FileSystemInfo.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if path is invalid.</exception>
public FileSystemMetadata GetFileSystemEntryByPath(string path)
{
if (string.IsNullOrEmpty(path))
@@ -223,45 +236,33 @@ namespace MediaBrowser.Controller.Library
return CollectionType;
}
- public string CollectionType { get; set; }
-
- #region Equality Overrides
-
- /// <summary>
- /// Determines whether the specified <see cref="object" /> is equal to this instance.
- /// </summary>
- /// <param name="obj">The object to compare with the current object.</param>
- /// <returns><c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
- public override bool Equals(object obj)
- {
- return Equals(obj as ItemResolveArgs);
- }
-
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
- return Path.GetHashCode();
+ return Path.GetHashCode(StringComparison.Ordinal);
}
/// <summary>
/// Equals the specified args.
/// </summary>
/// <param name="args">The args.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
+ /// <returns><c>true</c> if the arguments are the same, <c>false</c> otherwise.</returns>
protected bool Equals(ItemResolveArgs args)
{
if (args != null)
{
- if (args.Path == null && Path == null) return true;
+ if (args.Path == null && Path == null)
+ {
+ return true;
+ }
+
return args.Path != null && BaseItem.FileSystem.AreEqual(args.Path, Path);
}
+
return false;
}
-
- #endregion
}
-
}
diff --git a/MediaBrowser.Controller/Library/ItemUpdateType.cs b/MediaBrowser.Controller/Library/ItemUpdateType.cs
index b62f314ba..1f3ebb499 100644
--- a/MediaBrowser.Controller/Library/ItemUpdateType.cs
+++ b/MediaBrowser.Controller/Library/ItemUpdateType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Library
diff --git a/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs b/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs
index 037b0b62c..7bc8fa5ab 100644
--- a/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs
+++ b/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
diff --git a/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs
new file mode 100644
index 000000000..41cfcae16
--- /dev/null
+++ b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs
@@ -0,0 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.Controller.Library
+{
+ public static class MetadataConfigurationExtensions
+ {
+ public static MetadataConfiguration GetMetadataConfiguration(this IConfigurationManager config)
+ {
+ return config.GetConfiguration<MetadataConfiguration>("metadata");
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs b/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs
index 31adbdcf3..a6be6c0d3 100644
--- a/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs
+++ b/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration;
@@ -12,18 +14,10 @@ namespace MediaBrowser.Controller.Library
{
new ConfigurationStore
{
- Key = "metadata",
- ConfigurationType = typeof(MetadataConfiguration)
+ Key = "metadata",
+ ConfigurationType = typeof(MetadataConfiguration)
}
};
}
}
-
- public static class MetadataConfigurationExtensions
- {
- public static MetadataConfiguration GetMetadataConfiguration(this IConfigurationManager config)
- {
- return config.GetConfiguration<MetadataConfiguration>("metadata");
- }
- }
}
diff --git a/MediaBrowser.Controller/Library/NameExtensions.cs b/MediaBrowser.Controller/Library/NameExtensions.cs
index 6b0b7e53a..d2ed3465a 100644
--- a/MediaBrowser.Controller/Library/NameExtensions.cs
+++ b/MediaBrowser.Controller/Library/NameExtensions.cs
@@ -1,13 +1,19 @@
+#pragma warning disable CS1591
+
using System;
-using System.Linq;
using System.Collections.Generic;
-using MediaBrowser.Controller.Extensions;
+using System.Linq;
+using Diacritics.Extensions;
namespace MediaBrowser.Controller.Library
{
public static class NameExtensions
{
- private static string RemoveDiacritics(string name)
+ public static IEnumerable<string> DistinctNames(this IEnumerable<string> names)
+ => names.GroupBy(RemoveDiacritics, StringComparer.OrdinalIgnoreCase)
+ .Select(x => x.First());
+
+ private static string RemoveDiacritics(string? name)
{
if (name == null)
{
@@ -16,9 +22,5 @@ namespace MediaBrowser.Controller.Library
return name.RemoveDiacritics();
}
-
- public static IEnumerable<string> DistinctNames(this IEnumerable<string> names)
- => names.GroupBy(RemoveDiacritics, StringComparer.OrdinalIgnoreCase)
- .Select(x => x.First());
}
}
diff --git a/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs b/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs
index b0302d04c..76e9eb1f5 100644
--- a/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs
+++ b/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs
@@ -1,5 +1,10 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA2227, CS1591
+
using System;
using System.Collections.Generic;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dto;
@@ -7,28 +12,37 @@ using MediaBrowser.Model.Dto;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Holds information about a playback progress event
+ /// Holds information about a playback progress event.
/// </summary>
public class PlaybackProgressEventArgs : EventArgs
{
+ public PlaybackProgressEventArgs()
+ {
+ Users = new List<User>();
+ }
+
public List<User> Users { get; set; }
+
public long? PlaybackPositionTicks { get; set; }
+
public BaseItem Item { get; set; }
+
public BaseItemDto MediaInfo { get; set; }
+
public string MediaSourceId { get; set; }
+
public bool IsPaused { get; set; }
+
public bool IsAutomated { get; set; }
public string DeviceId { get; set; }
+
public string DeviceName { get; set; }
+
public string ClientName { get; set; }
public string PlaySessionId { get; set; }
- public SessionInfo Session { get; set; }
- public PlaybackProgressEventArgs()
- {
- Users = new List<User>();
- }
+ public SessionInfo Session { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs b/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs
new file mode 100644
index 000000000..2138fef58
--- /dev/null
+++ b/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs
@@ -0,0 +1,9 @@
+namespace MediaBrowser.Controller.Library
+{
+ /// <summary>
+ /// An event that occurs when playback is started.
+ /// </summary>
+ public class PlaybackStartEventArgs : PlaybackProgressEventArgs
+ {
+ }
+}
diff --git a/MediaBrowser.Controller/Library/PlaybackStopEventArgs.cs b/MediaBrowser.Controller/Library/PlaybackStopEventArgs.cs
index 12add2573..f0d77ba2d 100644
--- a/MediaBrowser.Controller/Library/PlaybackStopEventArgs.cs
+++ b/MediaBrowser.Controller/Library/PlaybackStopEventArgs.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Library
{
public class PlaybackStopEventArgs : PlaybackProgressEventArgs
diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs
deleted file mode 100644
index 9fe175a7c..000000000
--- a/MediaBrowser.Controller/Library/Profiler.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System;
-using System.Diagnostics;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Controller.Library
-{
- /// <summary>
- /// Class Profiler
- /// </summary>
- public class Profiler : IDisposable
- {
- /// <summary>
- /// The name
- /// </summary>
- readonly string _name;
- /// <summary>
- /// The stopwatch
- /// </summary>
- readonly Stopwatch _stopwatch;
-
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Profiler" /> class.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="logger">The logger.</param>
- public Profiler(string name, ILogger logger)
- {
- this._name = name;
-
- _logger = logger;
-
- _stopwatch = new Stopwatch();
- _stopwatch.Start();
- }
- #region IDisposable Members
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- }
-
- /// <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)
- {
- _stopwatch.Stop();
- string message;
- if (_stopwatch.ElapsedMilliseconds > 300000)
- {
- message = string.Format("{0} took {1} minutes.",
- _name, ((float)_stopwatch.ElapsedMilliseconds / 60000).ToString("F"));
- }
- else
- {
- message = string.Format("{0} took {1} seconds.",
- _name, ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000"));
- }
- _logger.LogInformation(message);
- }
- }
-
- #endregion
- }
-}
diff --git a/MediaBrowser.Controller/Library/SearchHintInfo.cs b/MediaBrowser.Controller/Library/SearchHintInfo.cs
index 692431e34..de7806adc 100644
--- a/MediaBrowser.Controller/Library/SearchHintInfo.cs
+++ b/MediaBrowser.Controller/Library/SearchHintInfo.cs
@@ -1,9 +1,11 @@
+#nullable disable
+
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Class SearchHintInfo
+ /// Class SearchHintInfo.
/// </summary>
public class SearchHintInfo
{
diff --git a/MediaBrowser.Controller/Library/TVUtils.cs b/MediaBrowser.Controller/Library/TVUtils.cs
index fd5fb6748..968338dc6 100644
--- a/MediaBrowser.Controller/Library/TVUtils.cs
+++ b/MediaBrowser.Controller/Library/TVUtils.cs
@@ -1,9 +1,10 @@
using System;
+using System.Diagnostics.CodeAnalysis;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Class TVUtils
+ /// Class TVUtils.
/// </summary>
public static class TVUtils
{
@@ -12,7 +13,8 @@ namespace MediaBrowser.Controller.Library
/// </summary>
/// <param name="day">The day.</param>
/// <returns>List{DayOfWeek}.</returns>
- public static DayOfWeek[] GetAirDays(string day)
+ [return: NotNullIfNotNull("day")]
+ public static DayOfWeek[]? GetAirDays(string? day)
{
if (!string.IsNullOrEmpty(day))
{
@@ -38,8 +40,9 @@ namespace MediaBrowser.Controller.Library
};
}
- return new DayOfWeek[] { };
+ return Array.Empty<DayOfWeek>();
}
+
return null;
}
}
diff --git a/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs b/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs
index 3e7351b8b..4d90346f2 100644
--- a/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs
+++ b/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA2227, CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Entities;
@@ -6,7 +10,7 @@ using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Library
{
/// <summary>
- /// Class UserDataSaveEventArgs
+ /// Class UserDataSaveEventArgs.
/// </summary>
public class UserDataSaveEventArgs : EventArgs
{
diff --git a/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs b/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs
new file mode 100644
index 000000000..463061e68
--- /dev/null
+++ b/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs
@@ -0,0 +1,19 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Threading;
+
+namespace MediaBrowser.Controller.LiveTv
+{
+ public class ActiveRecordingInfo
+ {
+ public string Id { get; set; }
+
+ public string Path { get; set; }
+
+ public TimerInfo Timer { get; set; }
+
+ public CancellationTokenSource CancellationTokenSource { get; set; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
index 70477fce7..699c15f93 100644
--- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
@@ -1,9 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Model.LiveTv;
namespace MediaBrowser.Controller.LiveTv
{
/// <summary>
- /// Class ChannelInfo
+ /// Class ChannelInfo.
/// </summary>
public class ChannelInfo
{
@@ -20,7 +24,7 @@ namespace MediaBrowser.Controller.LiveTv
public string Number { get; set; }
/// <summary>
- /// Get or sets the Id.
+ /// Gets or sets the Id.
/// </summary>
/// <value>The id of the channel.</value>
public string Id { get; set; }
@@ -44,13 +48,19 @@ namespace MediaBrowser.Controller.LiveTv
public ChannelType ChannelType { get; set; }
/// <summary>
- /// Supply the image path if it can be accessed directly from the file system
+ /// Gets or sets the group of the channel.
+ /// </summary>
+ /// <value>The group of the channel.</value>
+ public string ChannelGroup { get; set; }
+
+ /// <summary>
+ /// Gets or sets the the image path if it can be accessed directly from the file system.
/// </summary>
/// <value>The image path.</value>
public string ImagePath { get; set; }
/// <summary>
- /// Supply the image url if it can be downloaded
+ /// Gets or sets the image url if it can be downloaded.
/// </summary>
/// <value>The image URL.</value>
public string ImageUrl { get; set; }
@@ -60,6 +70,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value><c>null</c> if [has image] contains no value, <c>true</c> if [has image]; otherwise, <c>false</c>.</value>
public bool? HasImage { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is favorite.
/// </summary>
@@ -67,8 +78,11 @@ namespace MediaBrowser.Controller.LiveTv
public bool? IsFavorite { get; set; }
public bool? IsHD { get; set; }
+
public string AudioCodec { get; set; }
+
public string VideoCodec { get; set; }
+
public string[] Tags { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/IListingsProvider.cs b/MediaBrowser.Controller/LiveTv/IListingsProvider.cs
index c719ad81c..2bd4b20e8 100644
--- a/MediaBrowser.Controller/LiveTv/IListingsProvider.cs
+++ b/MediaBrowser.Controller/LiveTv/IListingsProvider.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
@@ -10,10 +14,15 @@ namespace MediaBrowser.Controller.LiveTv
public interface IListingsProvider
{
string Name { get; }
+
string Type { get; }
+
Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken);
+
Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings);
+
Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location);
+
Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
index f99df6c7c..dbd18165d 100644
--- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
+++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
@@ -1,28 +1,43 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.LiveTv
{
/// <summary>
- /// Manages all live tv services installed on the server
+ /// Manages all live tv services installed on the server.
/// </summary>
public interface ILiveTvManager
{
+ event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
+
+ event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
+
+ event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
+
+ event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
+
/// <summary>
/// Gets the services.
/// </summary>
/// <value>The services.</value>
IReadOnlyList<ILiveTvService> Services { get; }
+ IListingsProvider[] ListingProviders { get; }
+
/// <summary>
/// Gets the new timer defaults asynchronous.
/// </summary>
@@ -81,6 +96,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <param name="query">The query.</param>
/// <param name="options">The options.</param>
+ /// <returns>A recording.</returns>
QueryResult<BaseItemDto> GetRecordings(RecordingQuery query, DtoOptions options);
/// <summary>
@@ -104,6 +120,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="mediaSourceId">The media source identifier.</param>
+ /// <param name="currentLiveStreams">The current live streams.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{StreamResponseInfo}.</returns>
Task<Tuple<MediaSourceInfo, ILiveStream>> GetChannelStream(string id, string mediaSourceId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
@@ -170,11 +187,16 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="query">The query.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Recommended programs.</returns>
QueryResult<BaseItemDto> GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken);
/// <summary>
/// Gets the recommended programs internal.
/// </summary>
+ /// <param name="query">The query.</param>
+ /// <param name="options">The options.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Recommended programs.</returns>
QueryResult<BaseItem> GetRecommendedProgramsInternal(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken);
/// <summary>
@@ -196,6 +218,7 @@ namespace MediaBrowser.Controller.LiveTv
/// Gets the live tv folder.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Live TV folder.</returns>
Folder GetInternalLiveTvFolder(CancellationToken cancellationToken);
/// <summary>
@@ -207,11 +230,18 @@ namespace MediaBrowser.Controller.LiveTv
/// <summary>
/// Gets the internal channels.
/// </summary>
+ /// <param name="query">The query.</param>
+ /// <param name="dtoOptions">The options.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Internal channels.</returns>
QueryResult<BaseItem> GetInternalChannels(LiveTvChannelQuery query, DtoOptions dtoOptions, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel media sources.
/// </summary>
+ /// <param name="item">Item to search for.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>Channel media sources wrapped in a task.</returns>
Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(BaseItem item, CancellationToken cancellationToken);
/// <summary>
@@ -221,12 +251,16 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="fields">The fields.</param>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
- Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> programs, ItemFields[] fields, User user = null);
+ Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, IReadOnlyList<ItemFields> fields, User user = null);
/// <summary>
/// Saves the tuner host.
/// </summary>
+ /// <param name="info">Turner host to save.</param>
+ /// <param name="dataSourceChanged">Option to specify that data source has changed.</param>
+ /// <returns>Tuner host information wrapped in a task.</returns>
Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true);
+
/// <summary>
/// Saves the listing provider.
/// </summary>
@@ -240,7 +274,7 @@ namespace MediaBrowser.Controller.LiveTv
Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber);
- TunerChannelMapping GetTunerChannelMapping(ChannelInfo channel, NameValuePair[] mappings, List<ChannelInfo> providerChannels);
+ TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> providerChannels);
/// <summary>
/// Gets the lineups.
@@ -258,20 +292,15 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="items">The items.</param>
/// <param name="options">The options.</param>
/// <param name="user">The user.</param>
- void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> items, DtoOptions options, User user);
+ void AddChannelInfo(IReadOnlyCollection<(BaseItemDto, LiveTvChannel)> items, DtoOptions options, User user);
Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken);
- Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken);
- IListingsProvider[] ListingProviders { get; }
+ Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken);
List<NameIdPair> GetTunerHostTypes();
- Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken);
- event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
- event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
- event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
- event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
+ Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken);
string GetEmbyTvActiveRecordingPath(string id);
@@ -281,12 +310,4 @@ namespace MediaBrowser.Controller.LiveTv
List<BaseItem> GetRecordingFolders(User user);
}
-
- public class ActiveRecordingInfo
- {
- public string Id { get; set; }
- public string Path { get; set; }
- public TimerInfo Timer { get; set; }
- public CancellationTokenSource CancellationTokenSource { get; set; }
- }
}
diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvService.cs b/MediaBrowser.Controller/LiveTv/ILiveTvService.cs
index b71a76648..ce34954e3 100644
--- a/MediaBrowser.Controller/LiveTv/ILiveTvService.cs
+++ b/MediaBrowser.Controller/LiveTv/ILiveTvService.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
@@ -66,10 +70,10 @@ namespace MediaBrowser.Controller.LiveTv
/// <summary>
/// Updates the timer asynchronous.
/// </summary>
- /// <param name="info">The information.</param>
+ /// <param name="updatedTimer">The updated timer information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken);
+ Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken);
/// <summary>
/// Updates the series timer asynchronous.
diff --git a/MediaBrowser.Controller/LiveTv/ITunerHost.cs b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
index 240ba8c23..24820abb9 100644
--- a/MediaBrowser.Controller/LiveTv/ITunerHost.cs
+++ b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -14,28 +18,40 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The name.</value>
string Name { get; }
+
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
string Type { get; }
+
+ bool IsSupported { get; }
+
/// <summary>
/// Gets the channels.
/// </summary>
+ /// <param name="enableCache">Option to enable using cache.</param>
+ /// <param name="cancellationToken">The CancellationToken for this operation.</param>
/// <returns>Task&lt;IEnumerable&lt;ChannelInfo&gt;&gt;.</returns>
Task<List<ChannelInfo>> GetChannels(bool enableCache, CancellationToken cancellationToken);
+
/// <summary>
/// Gets the tuner infos.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task&lt;List&lt;LiveTvTunerInfo&gt;&gt;.</returns>
Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken);
+
/// <summary>
/// Gets the channel stream.
/// </summary>
/// <param name="channelId">The channel identifier.</param>
/// <param name="streamId">The stream identifier.</param>
+ /// <param name="currentLiveStreams">The current live streams.</param>
+ /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
+ /// <returns>Live stream wrapped in a task.</returns>
Task<ILiveStream> GetChannelStream(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
+
/// <summary>
/// Gets the channel stream media sources.
/// </summary>
@@ -45,11 +61,8 @@ namespace MediaBrowser.Controller.LiveTv
Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken);
Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken);
- bool IsSupported
- {
- get;
- }
}
+
public interface IConfigurableTunerHost
{
/// <summary>
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
index 55f47aae9..074e023e8 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
@@ -1,43 +1,30 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.LiveTv
{
public class LiveTvChannel : BaseItem, IHasMediaSources, IHasProgramAttributes
{
- public override List<string> GetUserDataKeys()
- {
- var list = base.GetUserDataKeys();
-
- if (!ConfigurationManager.Configuration.DisableLiveTvChannelUserDataName)
- {
- list.Insert(0, GetClientTypeName() + "-" + Name);
- }
-
- return list;
- }
-
- public override UnratedItem GetBlockUnratedType()
- {
- return UnratedItem.LiveTvChannel;
- }
-
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPositionTicksResume => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override SourceType SourceType => SourceType.LiveTV;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool EnableRememberingTrackSelections => false;
/// <summary>
@@ -52,9 +39,70 @@ namespace MediaBrowser.Controller.LiveTv
/// <value>The type of the channel.</value>
public ChannelType ChannelType { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override LocationType LocationType => LocationType.Remote;
+ [JsonIgnore]
+ public override string MediaType => ChannelType == ChannelType.Radio ? Model.Entities.MediaType.Audio : Model.Entities.MediaType.Video;
+
+ [JsonIgnore]
+ public bool IsMovie { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is sports.
+ /// </summary>
+ /// <value><c>true</c> if this instance is sports; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public bool IsSports { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is series.
+ /// </summary>
+ /// <value><c>true</c> if this instance is series; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public bool IsSeries { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is news.
+ /// </summary>
+ /// <value><c>true</c> if this instance is news; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public bool IsNews { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether this instance is kids.
+ /// </summary>
+ /// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
+ [JsonIgnore]
+ public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase);
+
+ [JsonIgnore]
+ public bool IsRepeat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the episode title.
+ /// </summary>
+ /// <value>The episode title.</value>
+ [JsonIgnore]
+ public string EpisodeTitle { get; set; }
+
+ public override List<string> GetUserDataKeys()
+ {
+ var list = base.GetUserDataKeys();
+
+ if (!ConfigurationManager.Configuration.DisableLiveTvChannelUserDataName)
+ {
+ list.Insert(0, GetClientTypeName() + "-" + Name);
+ }
+
+ return list;
+ }
+
+ public override UnratedItem GetBlockUnratedType()
+ {
+ return UnratedItem.LiveTvChannel;
+ }
+
protected override string CreateSortName()
{
if (!string.IsNullOrEmpty(Number))
@@ -63,22 +111,19 @@ namespace MediaBrowser.Controller.LiveTv
if (double.TryParse(Number, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
{
- return string.Format("{0:00000.0}", number) + "-" + (Name ?? string.Empty);
+ return string.Format(CultureInfo.InvariantCulture, "{0:00000.0}", number) + "-" + (Name ?? string.Empty);
}
}
return (Number ?? string.Empty) + "-" + (Name ?? string.Empty);
}
- [IgnoreDataMember]
- public override string MediaType => ChannelType == ChannelType.Radio ? Model.Entities.MediaType.Audio : Model.Entities.MediaType.Video;
-
public override string GetClientTypeName()
{
return "TvChannel";
}
- public IEnumerable<BaseItem> GetTaggedItems(IEnumerable<BaseItem> inputItems)
+ public IEnumerable<BaseItem> GetTaggedItems()
{
return new List<BaseItem>();
}
@@ -89,7 +134,7 @@ namespace MediaBrowser.Controller.LiveTv
var info = new MediaSourceInfo
{
- Id = Id.ToString("N"),
+ Id = Id.ToString("N", CultureInfo.InvariantCulture),
Protocol = PathProtocol ?? MediaProtocol.File,
MediaStreams = new List<MediaStream>(),
Name = Name,
@@ -111,53 +156,12 @@ namespace MediaBrowser.Controller.LiveTv
protected override string GetInternalMetadataPath(string basePath)
{
- return System.IO.Path.Combine(basePath, "livetv", Id.ToString("N"), "metadata");
+ return System.IO.Path.Combine(basePath, "livetv", Id.ToString("N", CultureInfo.InvariantCulture), "metadata");
}
public override bool CanDelete()
{
return false;
}
-
- [IgnoreDataMember]
- public bool IsMovie { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is sports.
- /// </summary>
- /// <value><c>true</c> if this instance is sports; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool IsSports { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is series.
- /// </summary>
- /// <value><c>true</c> if this instance is series; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool IsSeries { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is news.
- /// </summary>
- /// <value><c>true</c> if this instance is news; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool IsNews { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is kids.
- /// </summary>
- /// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase);
-
- [IgnoreDataMember]
- public bool IsRepeat { get; set; }
-
- /// <summary>
- /// Gets or sets the episode title.
- /// </summary>
- /// <value>The episode title.</value>
- [IgnoreDataMember]
- public string EpisodeTitle { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvConflictException.cs b/MediaBrowser.Controller/LiveTv/LiveTvConflictException.cs
index df8f91eec..881c42c73 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvConflictException.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvConflictException.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.LiveTv
@@ -9,12 +11,11 @@ namespace MediaBrowser.Controller.LiveTv
{
public LiveTvConflictException()
{
-
}
+
public LiveTvConflictException(string message)
: base(message)
{
-
}
}
}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
index 8bde6a5da..111dc0d27 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
@@ -1,160 +1,126 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1306
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.LiveTv
{
public class LiveTvProgram : BaseItem, IHasLookupInfo<ItemLookupInfo>, IHasStartDate, IHasProgramAttributes
{
+ private static string EmbyServiceName = "Emby";
+
public LiveTvProgram()
{
IsVirtualItem = true;
}
- public override List<string> GetUserDataKeys()
- {
- var list = base.GetUserDataKeys();
-
- if (!IsSeries)
- {
- var key = this.GetProviderId(MetadataProviders.Imdb);
- if (!string.IsNullOrEmpty(key))
- {
- list.Insert(0, key);
- }
-
- key = this.GetProviderId(MetadataProviders.Tmdb);
- if (!string.IsNullOrEmpty(key))
- {
- list.Insert(0, key);
- }
- }
- else if (!string.IsNullOrEmpty(EpisodeTitle))
- {
- var name = GetClientTypeName();
-
- list.Insert(0, name + "-" + Name + (EpisodeTitle ?? string.Empty));
- }
-
- return list;
- }
-
- private static string EmbyServiceName = "Emby";
- public override double GetDefaultPrimaryImageAspectRatio()
- {
- var serviceName = ServiceName;
-
- if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
- {
- return 2.0 / 3;
- }
- else
- {
- return 16.0 / 9;
- }
- }
+ public string SeriesName { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public override SourceType SourceType => SourceType.LiveTV;
/// <summary>
- /// The start date of the program, in UTC.
+ /// Gets or sets start date of the program, in UTC.
/// </summary>
- [IgnoreDataMember]
+ [JsonIgnore]
public DateTime StartDate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is repeat.
/// </summary>
/// <value><c>true</c> if this instance is repeat; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsRepeat { get; set; }
/// <summary>
/// Gets or sets the episode title.
/// </summary>
/// <value>The episode title.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public string EpisodeTitle { get; set; }
- [IgnoreDataMember]
+ [JsonIgnore]
public string ShowId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is movie.
/// </summary>
/// <value><c>true</c> if this instance is movie; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsMovie { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether this instance is sports.
+ /// Gets a value indicating whether this instance is sports.
/// </summary>
/// <value><c>true</c> if this instance is sports; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsSports => Tags.Contains("Sports", StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets a value indicating whether this instance is series.
/// </summary>
/// <value><c>true</c> if this instance is series; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsSeries { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether this instance is live.
+ /// Gets a value indicating whether this instance is live.
/// </summary>
/// <value><c>true</c> if this instance is live; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsLive => Tags.Contains("Live", StringComparer.OrdinalIgnoreCase);
/// <summary>
- /// Gets or sets a value indicating whether this instance is news.
+ /// Gets a value indicating whether this instance is news.
/// </summary>
/// <value><c>true</c> if this instance is news; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsNews => Tags.Contains("News", StringComparer.OrdinalIgnoreCase);
/// <summary>
- /// Gets or sets a value indicating whether this instance is kids.
+ /// Gets a value indicating whether this instance is kids.
/// </summary>
/// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase);
/// <summary>
- /// Gets or sets a value indicating whether this instance is premiere.
+ /// Gets a value indicating whether this instance is premiere.
/// </summary>
/// <value><c>true</c> if this instance is premiere; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsPremiere => Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase);
/// <summary>
- /// Returns the folder containing the item.
- /// If the item is a folder, it returns the folder itself
+ /// Gets the folder containing the item.
+ /// If the item is a folder, it returns the folder itself.
/// </summary>
/// <value>The containing folder path.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public override string ContainingFolderPath => Path;
- //[IgnoreDataMember]
- //public override string MediaType
- //{
+ // [JsonIgnore]
+ // public override string MediaType
+ // {
// get
// {
// return ChannelType == ChannelType.TV ? Model.Entities.MediaType.Video : Model.Entities.MediaType.Audio;
// }
- //}
+ // }
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsAiring
{
get
@@ -165,7 +131,7 @@ namespace MediaBrowser.Controller.LiveTv
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
public bool HasAired
{
get
@@ -176,6 +142,66 @@ namespace MediaBrowser.Controller.LiveTv
}
}
+ [JsonIgnore]
+ public override bool SupportsPeople
+ {
+ get
+ {
+ // Optimization
+ if (IsNews || IsSports)
+ {
+ return false;
+ }
+
+ return base.SupportsPeople;
+ }
+ }
+
+ [JsonIgnore]
+ public override bool SupportsAncestors => false;
+
+ public override List<string> GetUserDataKeys()
+ {
+ var list = base.GetUserDataKeys();
+
+ if (!IsSeries)
+ {
+ var key = this.GetProviderId(MetadataProvider.Imdb);
+ if (!string.IsNullOrEmpty(key))
+ {
+ list.Insert(0, key);
+ }
+
+ key = this.GetProviderId(MetadataProvider.Tmdb);
+ if (!string.IsNullOrEmpty(key))
+ {
+ list.Insert(0, key);
+ }
+ }
+ else if (!string.IsNullOrEmpty(EpisodeTitle))
+ {
+ var name = GetClientTypeName();
+
+ list.Insert(0, name + "-" + Name + (EpisodeTitle ?? string.Empty));
+ }
+
+ return list;
+ }
+
+ public override double GetDefaultPrimaryImageAspectRatio()
+ {
+ var serviceName = ServiceName;
+
+ if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
+ {
+ return 2.0 / 3;
+ }
+ else
+ {
+ return 16.0 / 9;
+ }
+ }
+
public override string GetClientTypeName()
{
return "Program";
@@ -188,7 +214,7 @@ namespace MediaBrowser.Controller.LiveTv
protected override string GetInternalMetadataPath(string basePath)
{
- return System.IO.Path.Combine(basePath, "livetv", Id.ToString("N"));
+ return System.IO.Path.Combine(basePath, "livetv", Id.ToString("N", CultureInfo.InvariantCulture));
}
public override bool CanDelete()
@@ -196,24 +222,6 @@ namespace MediaBrowser.Controller.LiveTv
return false;
}
- [IgnoreDataMember]
- public override bool SupportsPeople
- {
- get
- {
- // Optimization
- if (IsNews || IsSports)
- {
- return false;
- }
-
- return base.SupportsPeople;
- }
- }
-
- [IgnoreDataMember]
- public override bool SupportsAncestors => false;
-
private LiveTvOptions GetConfiguration()
{
return ConfigurationManager.GetConfiguration<LiveTvOptions>("livetv");
@@ -252,7 +260,7 @@ namespace MediaBrowser.Controller.LiveTv
{
var list = base.GetRelatedUrls();
- var imdbId = this.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = this.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
if (IsMovie)
@@ -260,14 +268,12 @@ namespace MediaBrowser.Controller.LiveTv
list.Add(new ExternalUrl
{
Name = "Trakt",
- Url = string.Format("https://trakt.tv/movies/{0}", imdbId)
+ Url = string.Format(CultureInfo.InvariantCulture, "https://trakt.tv/movies/{0}", imdbId)
});
}
}
return list;
}
-
- public string SeriesName { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
index 67b2f0eb1..eb3babc18 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Model.LiveTv;
@@ -5,6 +9,12 @@ namespace MediaBrowser.Controller.LiveTv
{
public class LiveTvServiceStatusInfo
{
+ public LiveTvServiceStatusInfo()
+ {
+ Tuners = new List<LiveTvTunerInfo>();
+ IsVisible = true;
+ }
+
/// <summary>
/// Gets or sets the status.
/// </summary>
@@ -34,16 +44,11 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The tuners.</value>
public List<LiveTvTunerInfo> Tuners { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is visible.
/// </summary>
/// <value><c>true</c> if this instance is visible; otherwise, <c>false</c>.</value>
public bool IsVisible { get; set; }
-
- public LiveTvServiceStatusInfo()
- {
- Tuners = new List<LiveTvTunerInfo>();
- IsVisible = true;
- }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs b/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs
index 2857f73f6..aa5eb59d1 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Model.LiveTv;
@@ -5,6 +9,11 @@ namespace MediaBrowser.Controller.LiveTv
{
public class LiveTvTunerInfo
{
+ public LiveTvTunerInfo()
+ {
+ Clients = new List<string>();
+ }
+
/// <summary>
/// Gets or sets the type of the source.
/// </summary>
@@ -64,10 +73,5 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value><c>true</c> if this instance can reset; otherwise, <c>false</c>.</value>
public bool CanReset { get; set; }
-
- public LiveTvTunerInfo()
- {
- Clients = new List<string>();
- }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
index 5d0f13192..3c3ac2471 100644
--- a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.LiveTv;
@@ -6,8 +10,16 @@ namespace MediaBrowser.Controller.LiveTv
{
public class ProgramInfo
{
+ public ProgramInfo()
+ {
+ Genres = new List<string>();
+
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
/// <summary>
- /// Id of the program.
+ /// Gets or sets the id of the program.
/// </summary>
public string Id { get; set; }
@@ -18,7 +30,7 @@ namespace MediaBrowser.Controller.LiveTv
public string ChannelId { get; set; }
/// <summary>
- /// Name of the program
+ /// Gets or sets the name of the program.
/// </summary>
public string Name { get; set; }
@@ -33,6 +45,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The overview.</value>
public string Overview { get; set; }
+
/// <summary>
/// Gets or sets the short overview.
/// </summary>
@@ -40,17 +53,17 @@ namespace MediaBrowser.Controller.LiveTv
public string ShortOverview { get; set; }
/// <summary>
- /// The start date of the program, in UTC.
+ /// Gets or sets the start date of the program, in UTC.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
- /// The end date of the program, in UTC.
+ /// Gets or sets the end date of the program, in UTC.
/// </summary>
public DateTime EndDate { get; set; }
/// <summary>
- /// Genre of the program.
+ /// Gets or sets the genre of the program.
/// </summary>
public List<string> Genres { get; set; }
@@ -66,6 +79,9 @@ namespace MediaBrowser.Controller.LiveTv
/// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
public bool? IsHD { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is 3d.
+ /// </summary>
public bool? Is3D { get; set; }
/// <summary>
@@ -95,13 +111,13 @@ namespace MediaBrowser.Controller.LiveTv
public string EpisodeTitle { get; set; }
/// <summary>
- /// Supply the image path if it can be accessed directly from the file system
+ /// Gets or sets the image path if it can be accessed directly from the file system.
/// </summary>
/// <value>The image path.</value>
public string ImagePath { get; set; }
/// <summary>
- /// Supply the image url if it can be downloaded
+ /// Gets or sets the image url if it can be downloaded.
/// </summary>
/// <value>The image URL.</value>
public string ImageUrl { get; set; }
@@ -167,31 +183,37 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The production year.</value>
public int? ProductionYear { get; set; }
+
/// <summary>
/// Gets or sets the home page URL.
/// </summary>
/// <value>The home page URL.</value>
public string HomePageUrl { get; set; }
+
/// <summary>
/// Gets or sets the series identifier.
/// </summary>
/// <value>The series identifier.</value>
public string SeriesId { get; set; }
+
/// <summary>
/// Gets or sets the show identifier.
/// </summary>
/// <value>The show identifier.</value>
public string ShowId { get; set; }
+
/// <summary>
/// Gets or sets the season number.
/// </summary>
/// <value>The season number.</value>
public int? SeasonNumber { get; set; }
+
/// <summary>
/// Gets or sets the episode number.
/// </summary>
/// <value>The episode number.</value>
public int? EpisodeNumber { get; set; }
+
/// <summary>
/// Gets or sets the etag.
/// </summary>
@@ -199,14 +221,7 @@ namespace MediaBrowser.Controller.LiveTv
public string Etag { get; set; }
public Dictionary<string, string> ProviderIds { get; set; }
- public Dictionary<string, string> SeriesProviderIds { get; set; }
-
- public ProgramInfo()
- {
- Genres = new List<string>();
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
+ public Dictionary<string, string> SeriesProviderIds { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
index 432388d6b..1dcf7a58f 100644
--- a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.LiveTv;
@@ -6,8 +10,13 @@ namespace MediaBrowser.Controller.LiveTv
{
public class RecordingInfo
{
+ public RecordingInfo()
+ {
+ Genres = new List<string>();
+ }
+
/// <summary>
- /// Id of the recording.
+ /// Gets or sets the id of the recording.
/// </summary>
public string Id { get; set; }
@@ -24,7 +33,7 @@ namespace MediaBrowser.Controller.LiveTv
public string TimerId { get; set; }
/// <summary>
- /// ChannelId of the recording.
+ /// Gets or sets the channelId of the recording.
/// </summary>
public string ChannelId { get; set; }
@@ -35,7 +44,7 @@ namespace MediaBrowser.Controller.LiveTv
public ChannelType ChannelType { get; set; }
/// <summary>
- /// Name of the recording.
+ /// Gets or sets the name of the recording.
/// </summary>
public string Name { get; set; }
@@ -58,12 +67,12 @@ namespace MediaBrowser.Controller.LiveTv
public string Overview { get; set; }
/// <summary>
- /// The start date of the recording, in UTC.
+ /// Gets or sets the start date of the recording, in UTC.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
- /// The end date of the recording, in UTC.
+ /// Gets or sets the end date of the recording, in UTC.
/// </summary>
public DateTime EndDate { get; set; }
@@ -80,7 +89,7 @@ namespace MediaBrowser.Controller.LiveTv
public RecordingStatus Status { get; set; }
/// <summary>
- /// Genre of the program.
+ /// Gets or sets the genre of the program.
/// </summary>
public List<string> Genres { get; set; }
@@ -169,13 +178,13 @@ namespace MediaBrowser.Controller.LiveTv
public float? CommunityRating { get; set; }
/// <summary>
- /// Supply the image path if it can be accessed directly from the file system
+ /// Gets or sets the image path if it can be accessed directly from the file system.
/// </summary>
/// <value>The image path.</value>
public string ImagePath { get; set; }
/// <summary>
- /// Supply the image url if it can be downloaded
+ /// Gets or sets the image url if it can be downloaded.
/// </summary>
/// <value>The image URL.</value>
public string ImageUrl { get; set; }
@@ -185,6 +194,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value><c>null</c> if [has image] contains no value, <c>true</c> if [has image]; otherwise, <c>false</c>.</value>
public bool? HasImage { get; set; }
+
/// <summary>
/// Gets or sets the show identifier.
/// </summary>
@@ -196,10 +206,5 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The date last updated.</value>
public DateTime DateLastUpdated { get; set; }
-
- public RecordingInfo()
- {
- Genres = new List<string>();
- }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs b/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs
index 99460a686..0b943c939 100644
--- a/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs
+++ b/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.LiveTv;
diff --git a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
index 4fbd496c5..d6811fe14 100644
--- a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.LiveTv;
@@ -6,13 +10,20 @@ namespace MediaBrowser.Controller.LiveTv
{
public class SeriesTimerInfo
{
+ public SeriesTimerInfo()
+ {
+ Days = new List<DayOfWeek>();
+ SkipEpisodesInLibrary = true;
+ KeepUntil = KeepUntil.UntilDeleted;
+ }
+
/// <summary>
- /// Id of the recording.
+ /// Gets or sets the id of the recording.
/// </summary>
public string Id { get; set; }
/// <summary>
- /// ChannelId of the recording.
+ /// Gets or sets the channelId of the recording.
/// </summary>
public string ChannelId { get; set; }
@@ -23,24 +34,27 @@ namespace MediaBrowser.Controller.LiveTv
public string ProgramId { get; set; }
/// <summary>
- /// Name of the recording.
+ /// Gets or sets the name of the recording.
/// </summary>
public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets the service name.
+ /// </summary>
public string ServiceName { get; set; }
/// <summary>
- /// Description of the recording.
+ /// Gets or sets the description of the recording.
/// </summary>
public string Overview { get; set; }
/// <summary>
- /// The start date of the recording, in UTC.
+ /// Gets or sets the start date of the recording, in UTC.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
- /// The end date of the recording, in UTC.
+ /// Gets or sets the end date of the recording, in UTC.
/// </summary>
public DateTime EndDate { get; set; }
@@ -57,6 +71,7 @@ namespace MediaBrowser.Controller.LiveTv
public bool RecordAnyChannel { get; set; }
public int KeepUpTo { get; set; }
+
public KeepUntil KeepUntil { get; set; }
public bool SkipEpisodesInLibrary { get; set; }
@@ -108,12 +123,5 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The series identifier.</value>
public string SeriesId { get; set; }
-
- public SeriesTimerInfo()
- {
- Days = new List<DayOfWeek>();
- SkipEpisodesInLibrary = true;
- KeepUntil = KeepUntil.UntilDeleted;
- }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs b/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs
index cfec39b4e..92eb0be9c 100644
--- a/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs
@@ -1,10 +1,18 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.LiveTv
{
public class TimerEventInfo
{
- public string Id { get; set; }
- public Guid ProgramId { get; set; }
+ public TimerEventInfo(string id)
+ {
+ Id = id;
+ }
+
+ public string Id { get; }
+
+ public Guid? ProgramId { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
index 2fea6a8cb..1a2e8acb3 100644
--- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
@@ -1,8 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.LiveTv
{
@@ -18,22 +22,23 @@ namespace MediaBrowser.Controller.LiveTv
}
public Dictionary<string, string> ProviderIds { get; set; }
+
public Dictionary<string, string> SeriesProviderIds { get; set; }
+
public string[] Tags { get; set; }
/// <summary>
- /// Id of the recording.
+ /// Gets or sets the id of the recording.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the series timer identifier.
/// </summary>
- /// <value>The series timer identifier.</value>
public string SeriesTimerId { get; set; }
/// <summary>
- /// ChannelId of the recording.
+ /// Gets or sets the channelId of the recording.
/// </summary>
public string ChannelId { get; set; }
@@ -46,24 +51,24 @@ namespace MediaBrowser.Controller.LiveTv
public string ShowId { get; set; }
/// <summary>
- /// Name of the recording.
+ /// Gets or sets the name of the recording.
/// </summary>
public string Name { get; set; }
/// <summary>
- /// Description of the recording.
+ /// Gets or sets the description of the recording.
/// </summary>
public string Overview { get; set; }
public string SeriesId { get; set; }
/// <summary>
- /// The start date of the recording, in UTC.
+ /// Gets or sets the start date of the recording, in UTC.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
- /// The end date of the recording, in UTC.
+ /// Gets or sets the end date of the recording, in UTC.
/// </summary>
public DateTime EndDate { get; set; }
@@ -109,6 +114,7 @@ namespace MediaBrowser.Controller.LiveTv
// Program properties
public int? SeasonNumber { get; set; }
+
/// <summary>
/// Gets or sets the episode number.
/// </summary>
@@ -126,13 +132,13 @@ namespace MediaBrowser.Controller.LiveTv
public bool IsSeries { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether this instance is live.
+ /// Gets a value indicating whether this instance is live.
/// </summary>
/// <value><c>true</c> if this instance is live; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsLive => Tags.Contains("Live", StringComparer.OrdinalIgnoreCase);
- [IgnoreDataMember]
+ [JsonIgnore]
public bool IsPremiere => Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase);
public int? ProductionYear { get; set; }
@@ -146,10 +152,15 @@ namespace MediaBrowser.Controller.LiveTv
public bool IsRepeat { get; set; }
public string HomePageUrl { get; set; }
+
public float? CommunityRating { get; set; }
+
public string OfficialRating { get; set; }
+
public string[] Genres { get; set; }
+
public string RecordingPath { get; set; }
+
public KeepUntil KeepUntil { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs b/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
index cb02da635..1c1a4417d 100644
--- a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
+++ b/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
@@ -1,10 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.LiveTv
{
public class TunerChannelMapping
{
public string Name { get; set; }
+
public string ProviderChannelName { get; set; }
+
public string ProviderChannelId { get; set; }
+
public string Id { get; set; }
}
}
diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
index 01893f1b5..d37880865 100644
--- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj
+++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
@@ -1,15 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}</ProjectGuid>
+ </PropertyGroup>
+
<PropertyGroup>
<Authors>Jellyfin Contributors</Authors>
<PackageId>Jellyfin.Controller</PackageId>
- <PackageLicenseUrl>https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt</PackageLicenseUrl>
+ <VersionPrefix>10.8.0</VersionPrefix>
<RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
</PropertyGroup>
<ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
+ <PackageReference Include="Diacritics" Version="3.3.4" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
+ <PackageReference Include="System.Threading.Tasks.Dataflow" Version="6.0.0-rc.2*" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../Emby.Naming/Emby.Naming.csproj" />
+ <ProjectReference Include="../MediaBrowser.Model/MediaBrowser.Model.csproj" />
+ <ProjectReference Include="../MediaBrowser.Common/MediaBrowser.Common.csproj" />
</ItemGroup>
<ItemGroup>
@@ -17,8 +32,25 @@
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </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>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs
new file mode 100644
index 000000000..dd6f468da
--- /dev/null
+++ b/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs
@@ -0,0 +1,204 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Dlna;
+
+namespace MediaBrowser.Controller.MediaEncoding
+{
+ public class BaseEncodingJobOptions
+ {
+ public BaseEncodingJobOptions()
+ {
+ EnableAutoStreamCopy = true;
+ AllowVideoStreamCopy = true;
+ AllowAudioStreamCopy = true;
+ Context = EncodingContext.Streaming;
+ StreamOptions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
+ /// <summary>
+ /// Gets or sets the id.
+ /// </summary>
+ /// <value>The id.</value>
+ public Guid Id { get; set; }
+
+ public string MediaSourceId { get; set; }
+
+ public string DeviceId { get; set; }
+
+ public string Container { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio codec.
+ /// </summary>
+ /// <value>The audio codec.</value>
+ public string AudioCodec { get; set; }
+
+ public bool EnableAutoStreamCopy { get; set; }
+
+ public bool AllowVideoStreamCopy { get; set; }
+
+ public bool AllowAudioStreamCopy { get; set; }
+
+ public bool BreakOnNonKeyFrames { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio sample rate.
+ /// </summary>
+ /// <value>The audio sample rate.</value>
+ public int? AudioSampleRate { get; set; }
+
+ public int? MaxAudioBitDepth { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio bit rate.
+ /// </summary>
+ /// <value>The audio bit rate.</value>
+ public int? AudioBitRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the audio channels.
+ /// </summary>
+ /// <value>The audio channels.</value>
+ public int? AudioChannels { get; set; }
+
+ public int? MaxAudioChannels { get; set; }
+
+ public bool Static { get; set; }
+
+ /// <summary>
+ /// Gets or sets the profile.
+ /// </summary>
+ /// <value>The profile.</value>
+ public string Profile { get; set; }
+
+ /// <summary>
+ /// Gets or sets the level.
+ /// </summary>
+ /// <value>The level.</value>
+ public string Level { get; set; }
+
+ /// <summary>
+ /// Gets or sets the framerate.
+ /// </summary>
+ /// <value>The framerate.</value>
+ public float? Framerate { get; set; }
+
+ public float? MaxFramerate { get; set; }
+
+ public bool CopyTimestamps { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start time ticks.
+ /// </summary>
+ /// <value>The start time ticks.</value>
+ public long? StartTimeTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the width.
+ /// </summary>
+ /// <value>The width.</value>
+ public int? Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height.
+ /// </summary>
+ /// <value>The height.</value>
+ public int? Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets the width of the max.
+ /// </summary>
+ /// <value>The width of the max.</value>
+ public int? MaxWidth { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height of the max.
+ /// </summary>
+ /// <value>The height of the max.</value>
+ public int? MaxHeight { get; set; }
+
+ /// <summary>
+ /// Gets or sets the video bit rate.
+ /// </summary>
+ /// <value>The video bit rate.</value>
+ public int? VideoBitRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index of the subtitle stream.
+ /// </summary>
+ /// <value>The index of the subtitle stream.</value>
+ public int? SubtitleStreamIndex { get; set; }
+
+ public SubtitleDeliveryMethod SubtitleMethod { get; set; }
+
+ public int? MaxRefFrames { get; set; }
+
+ public int? MaxVideoBitDepth { get; set; }
+
+ public bool RequireAvc { get; set; }
+
+ public bool DeInterlace { get; set; }
+
+ public bool RequireNonAnamorphic { get; set; }
+
+ public int? TranscodingMaxAudioChannels { get; set; }
+
+ public int? CpuCoreLimit { get; set; }
+
+ public string LiveStreamId { get; set; }
+
+ public bool EnableMpegtsM2TsMode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the video codec.
+ /// </summary>
+ /// <value>The video codec.</value>
+ public string VideoCodec { get; set; }
+
+ public string SubtitleCodec { get; set; }
+
+ public string TranscodeReasons { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index of the audio stream.
+ /// </summary>
+ /// <value>The index of the audio stream.</value>
+ public int? AudioStreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index of the video stream.
+ /// </summary>
+ /// <value>The index of the video stream.</value>
+ public int? VideoStreamIndex { get; set; }
+
+ public EncodingContext Context { get; set; }
+
+ public Dictionary<string, string> StreamOptions { get; set; }
+
+ public string GetOption(string qualifier, string name)
+ {
+ var value = GetOption(qualifier + "-" + name);
+
+ if (string.IsNullOrEmpty(value))
+ {
+ value = GetOption(name);
+ }
+
+ return value;
+ }
+
+ public string GetOption(string name)
+ {
+ if (StreamOptions.TryGetValue(name, out var value))
+ {
+ return value;
+ }
+
+ return null;
+ }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index f5f147db1..5715194b8 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -1,136 +1,225 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
using System.Threading;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Controller.MediaEncoding
{
public class EncodingHelper
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
private readonly IMediaEncoder _mediaEncoder;
- private readonly IFileSystem _fileSystem;
private readonly ISubtitleEncoder _subtitleEncoder;
- // private readonly IApplicationPaths _appPaths;
- // private readonly IAssemblyInfo _assemblyInfo;
- public EncodingHelper(IMediaEncoder mediaEncoder, IFileSystem fileSystem, ISubtitleEncoder subtitleEncoder)
+ private static readonly string[] _videoProfiles = new[]
+ {
+ "ConstrainedBaseline",
+ "Baseline",
+ "Extended",
+ "Main",
+ "High",
+ "ProgressiveHigh",
+ "ConstrainedHigh"
+ };
+
+ private static readonly Version _minVersionForCudaOverlay = new Version(4, 4);
+
+ public EncodingHelper(
+ IMediaEncoder mediaEncoder,
+ ISubtitleEncoder subtitleEncoder)
{
_mediaEncoder = mediaEncoder;
- _fileSystem = fileSystem;
_subtitleEncoder = subtitleEncoder;
}
public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
- {
- var defaultEncoder = "libx264";
+ => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
+
+ public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
+ => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
+ private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
+ {
// Only use alternative encoders for video files.
// When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
- // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
+ // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
if (state.VideoType == VideoType.VideoFile)
{
var hwType = encodingOptions.HardwareAccelerationType;
var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
- {"qsv", "h264_qsv"},
- {"h264_qsv", "h264_qsv"},
- {"nvenc", "h264_nvenc"},
- {"amf", "h264_amf"},
- {"omx", "h264_omx"},
- {"h264_v4l2m2m", "h264_v4l2m2m"},
- {"mediacodec", "h264_mediacodec"},
- {"vaapi", "h264_vaapi"}
+ { "qsv", hwEncoder + "_qsv" },
+ { hwEncoder + "_qsv", hwEncoder + "_qsv" },
+ { "nvenc", hwEncoder + "_nvenc" },
+ { "amf", hwEncoder + "_amf" },
+ { "omx", hwEncoder + "_omx" },
+ { hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m" },
+ { "mediacodec", hwEncoder + "_mediacodec" },
+ { "vaapi", hwEncoder + "_vaapi" },
+ { "videotoolbox", hwEncoder + "_videotoolbox" }
};
if (!string.IsNullOrEmpty(hwType)
- && encodingOptions.EnableHardwareEncoding && codecMap.ContainsKey(hwType))
+ && encodingOptions.EnableHardwareEncoding
+ && codecMap.ContainsKey(hwType))
{
- if (CheckVaapi(state, hwType, encodingOptions))
- {
- var preferredEncoder = codecMap[hwType];
+ var preferredEncoder = codecMap[hwType];
- if (_mediaEncoder.SupportsEncoder(preferredEncoder))
- {
- return preferredEncoder;
- }
+ if (_mediaEncoder.SupportsEncoder(preferredEncoder))
+ {
+ return preferredEncoder;
}
}
-
}
- // Avoid performing a second attempt when the first one
- // hasn't tried hardware encoding anyway.
- encodingOptions.EnableHardwareEncoding = false;
return defaultEncoder;
}
- private bool CheckVaapi(EncodingJobInfo state, string hwType, EncodingOptions encodingOptions)
+ private bool IsVaapiSupported(EncodingJobInfo state)
{
- if (!string.Equals(hwType, "vaapi", StringComparison.OrdinalIgnoreCase))
+ var videoStream = state.VideoStream;
+
+ // vaapi will throw an error with this input
+ // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
+ if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
{
- // No vaapi requested, return OK.
- return true;
+ return false;
}
- if (string.IsNullOrEmpty(encodingOptions.VaapiDevice))
+ return _mediaEncoder.SupportsHwaccel("vaapi");
+ }
+
+ private bool IsCudaSupported()
+ {
+ return _mediaEncoder.SupportsHwaccel("cuda")
+ && _mediaEncoder.SupportsFilter("scale_cuda")
+ && _mediaEncoder.SupportsFilter("yadif_cuda")
+ && _mediaEncoder.SupportsFilter("hwupload_cuda");
+ }
+
+ private bool IsOpenclTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
+ {
+ var videoStream = state.VideoStream;
+ if (videoStream == null)
{
- // No device specified, return OK.
- return true;
+ return false;
}
- return IsVaapiSupported(state);
+ return options.EnableTonemapping
+ && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
+ && IsColorDepth10(state)
+ && _mediaEncoder.SupportsHwaccel("opencl")
+ && _mediaEncoder.SupportsFilter("tonemap_opencl");
}
- private bool IsVaapiSupported(EncodingJobInfo state)
+ private bool IsCudaTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
{
var videoStream = state.VideoStream;
+ if (videoStream == null)
+ {
+ return false;
+ }
- if (videoStream != null)
+ return options.EnableTonemapping
+ && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
+ && IsColorDepth10(state)
+ && _mediaEncoder.SupportsHwaccel("cuda")
+ && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapCudaName);
+ }
+
+ private bool IsVppTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
+ {
+ var videoStream = state.VideoStream;
+ if (videoStream == null)
{
- // vaapi will throw an error with this input
- // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
- if (string.Equals(videoStream.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
+ // Remote stream doesn't have media info, disable vpp tonemapping.
+ return false;
}
- return true;
+
+ var codec = videoStream.Codec;
+ if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ // Limited to HEVC for now since the filter doesn't accept master data from VP9.
+ return options.EnableVppTonemapping
+ && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
+ && IsColorDepth10(state)
+ && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ && _mediaEncoder.SupportsHwaccel("vaapi")
+ && _mediaEncoder.SupportsFilter("tonemap_vaapi");
+ }
+
+ // Hybrid VPP tonemapping for QSV with VAAPI
+ if (OperatingSystem.IsLinux() && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
+ {
+ // Limited to HEVC for now since the filter doesn't accept master data from VP9.
+ return options.EnableVppTonemapping
+ && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
+ && IsColorDepth10(state)
+ && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ && _mediaEncoder.SupportsHwaccel("vaapi")
+ && _mediaEncoder.SupportsFilter("tonemap_vaapi")
+ && _mediaEncoder.SupportsHwaccel("qsv");
+ }
+
+ // Native VPP tonemapping may come to QSV in the future.
+ return false;
}
/// <summary>
- /// Gets the name of the output video codec
+ /// Gets the name of the output video codec.
/// </summary>
+ /// <param name="state">Encording state.</param>
+ /// <param name="encodingOptions">Encoding options.</param>
+ /// <returns>Encoder string.</returns>
public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
{
var codec = state.OutputVideoCodec;
if (!string.IsNullOrEmpty(codec))
{
+ if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetH265Encoder(state, encodingOptions);
+ }
+
if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
{
return GetH264Encoder(state, encodingOptions);
}
- if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
+
+ if (string.Equals(codec, "vp8", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
{
return "libvpx";
}
+
+ if (string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
+ {
+ return "libvpx-vp9";
+ }
+
if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
{
return "wmv2";
}
+
if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
{
return "libtheora";
@@ -149,11 +238,7 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <returns>System.String.</returns>
public string GetUserAgentParam(EncodingJobInfo state)
{
- string useragent = null;
-
- state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
-
- if (!string.IsNullOrEmpty(useragent))
+ if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
{
return "-user_agent \"" + useragent + "\"";
}
@@ -161,7 +246,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return string.Empty;
}
- public string GetInputFormat(string container)
+ public static string GetInputFormat(string container)
{
if (string.IsNullOrEmpty(container))
{
@@ -180,56 +265,68 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return null;
}
+
if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
{
return null;
}
- // Seeing reported failures here, not sure yet if this is related to specfying input format
+ // Seeing reported failures here, not sure yet if this is related to specifying input format
if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
{
return null;
@@ -241,9 +338,20 @@ namespace MediaBrowser.Controller.MediaEncoding
return null;
}
+ // ISO files don't have an ffmpeg format
+ if (string.Equals(container, "iso", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
return container;
}
+ /// <summary>
+ /// Gets decoder from a codec.
+ /// </summary>
+ /// <param name="codec">Codec to use.</param>
+ /// <returns>Decoder string.</returns>
public string GetDecoderFromCodec(string codec)
{
// For these need to find out the ffmpeg names
@@ -251,10 +359,12 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return null;
}
+
if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
{
return null;
}
+
if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
{
return null;
@@ -269,8 +379,10 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Infers the audio codec based on the url
+ /// Infers the audio codec based on the url.
/// </summary>
+ /// <param name="container">Container to use.</param>
+ /// <returns>Codec string.</returns>
public string InferAudioCodec(string container)
{
var ext = "." + (container ?? string.Empty);
@@ -279,30 +391,37 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return "mp3";
}
+
if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
{
return "aac";
}
+
if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
{
return "wma";
}
+
if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
{
return "vorbis";
}
+
if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
{
return "vorbis";
}
+
if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
{
return "vorbis";
}
+
if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
{
return "vorbis";
}
+
if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
{
return "vorbis";
@@ -324,14 +443,18 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return "wmv";
}
+
if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
{
- return "vpx";
+ // TODO: this may not always mean VP8, as the codec ages
+ return "vp8";
}
+
if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
{
return "theora";
}
+
if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
{
return "h264";
@@ -342,37 +465,16 @@ namespace MediaBrowser.Controller.MediaEncoding
public int GetVideoProfileScore(string profile)
{
- var list = new[]
- {
- "ConstrainedBaseline",
- "Baseline",
- "Extended",
- "Main",
- "High",
- "ProgressiveHigh",
- "ConstrainedHigh"
- };
-
// strip spaces because they may be stripped out on the query string
- return Array.FindIndex(list, t => string.Equals(t, profile.Replace(" ", ""), StringComparison.OrdinalIgnoreCase));
+ profile = profile.Replace(" ", string.Empty, StringComparison.Ordinal);
+ return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
}
public string GetInputPathArgument(EncodingJobInfo state)
{
- var protocol = state.InputProtocol;
var mediaPath = state.MediaPath ?? string.Empty;
- var inputPath = new[] { mediaPath };
-
- if (state.IsInputVideo)
- {
- if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
- {
- inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
- }
- }
-
- return _mediaEncoder.GetInputArgument(inputPath, protocol);
+ return _mediaEncoder.GetInputArgument(mediaPath, state.MediaSource);
}
/// <summary>
@@ -386,81 +488,215 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
{
- return "aac -strict experimental";
+ // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
+ if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
+ {
+ return "libfdk_aac";
+ }
+
+ return "aac";
}
+
if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
{
return "libmp3lame";
}
+
if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
{
return "libvorbis";
}
+
if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
{
return "wmav2";
}
+
if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
{
return "libopus";
}
+ if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase))
+ {
+ // flac is experimental in mp4 muxer
+ return "flac -strict -2";
+ }
+
return codec.ToLowerInvariant();
}
/// <summary>
/// Gets the input argument.
/// </summary>
- public string GetInputArgument(EncodingJobInfo state, EncodingOptions encodingOptions)
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <returns>Input arguments.</returns>
+ public string GetInputArgument(EncodingJobInfo state, EncodingOptions options)
{
- var request = state.BaseRequest;
+ var arg = new StringBuilder();
+ var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
+ var outputVideoCodec = GetVideoEncoder(state, options) ?? string.Empty;
+ var isWindows = OperatingSystem.IsWindows();
+ var isLinux = OperatingSystem.IsLinux();
+ var isMacOS = OperatingSystem.IsMacOS();
+#pragma warning disable CA1508 // Defaults to string.Empty
+ var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
+#pragma warning restore CA1508
+ var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
+ var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
+ var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
+ var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
+ var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
+ var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
+ var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
+ var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
+
+ if (!IsCopyCodec(outputVideoCodec))
+ {
+ if (state.IsVideoRequest
+ && _mediaEncoder.SupportsHwaccel("vaapi")
+ && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ if (isVaapiDecoder)
+ {
+ if (isOpenclTonemappingSupported && !isVppTonemappingSupported)
+ {
+ arg.Append("-init_hw_device vaapi=va:")
+ .Append(options.VaapiDevice)
+ .Append(" -init_hw_device opencl=ocl@va ")
+ .Append("-hwaccel_device va ")
+ .Append("-hwaccel_output_format vaapi ")
+ .Append("-filter_hw_device ocl ");
+ }
+ else
+ {
+ arg.Append("-hwaccel_output_format vaapi ")
+ .Append("-vaapi_device ")
+ .Append(options.VaapiDevice)
+ .Append(' ');
+ }
+ }
+ else if (!isVaapiDecoder && isVaapiEncoder)
+ {
+ arg.Append("-vaapi_device ")
+ .Append(options.VaapiDevice)
+ .Append(' ');
+ }
- var arg = string.Format("-i {0}", GetInputPathArgument(state));
+ arg.Append("-autorotate 0 ");
+ }
- if (state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
- {
- if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
+ if (state.IsVideoRequest
+ && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
{
- if (state.VideoStream != null && state.VideoStream.Width.HasValue)
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+
+ if (isQsvEncoder)
{
- // This is hacky but not sure how to get the exact subtitle resolution
- int height = Convert.ToInt32((double)state.VideoStream.Width.Value / 16.0 * 9.0);
+ if (isQsvDecoder)
+ {
+ if (isLinux)
+ {
+ if (hasGraphicalSubs)
+ {
+ arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
+ }
+ else
+ {
+ arg.Append("-hwaccel qsv ");
+ }
+ }
- arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), height.ToString(CultureInfo.InvariantCulture));
- }
+ if (isWindows)
+ {
+ arg.Append("-hwaccel qsv ");
+ }
+ }
- var subtitlePath = state.SubtitleStream.Path;
+ // While using SW decoder
+ else if (isSwDecoder)
+ {
+ arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
+ }
- if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
- {
- var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
- if (File.Exists(idxFile))
+ // Hybrid VPP tonemapping with VAAPI
+ else if (isVaapiDecoder && isVppTonemappingSupported)
{
- subtitlePath = idxFile;
+ arg.Append("-init_hw_device vaapi=va:")
+ .Append(options.VaapiDevice)
+ .Append(" -init_hw_device qsv@va ")
+ .Append("-hwaccel_output_format vaapi ");
}
+
+ arg.Append("-autorotate 0 ");
}
+ }
- arg += " -i \"" + subtitlePath + "\"";
+ if (state.IsVideoRequest
+ && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
+ && isNvdecDecoder)
+ {
+ // Fix for 'No decoder surfaces left' error. https://trac.ffmpeg.org/ticket/7562
+ arg.Append("-hwaccel_output_format cuda -extra_hw_frames 3 -autorotate 0 ");
}
- }
- if (state.IsVideoRequest)
- {
- if (GetVideoEncoder(state, encodingOptions).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
+ if (state.IsVideoRequest
+ && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
+ && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder))
{
- var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
- var hwOutputFormat = "vaapi";
+ if (!isCudaTonemappingSupported && isOpenclTonemappingSupported)
+ {
+ arg.Append("-init_hw_device opencl=ocl:")
+ .Append(options.OpenclDevice)
+ .Append(" -filter_hw_device ocl ");
+ }
+ }
- if (hasGraphicalSubs)
+ if (state.IsVideoRequest
+ && string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase)
+ && (isD3d11vaDecoder || isSwDecoder))
+ {
+ if (isOpenclTonemappingSupported)
{
- hwOutputFormat = "yuv420p";
+ arg.Append("-init_hw_device opencl=ocl:")
+ .Append(options.OpenclDevice)
+ .Append(" -filter_hw_device ocl ");
}
+ }
- arg = "-hwaccel vaapi -hwaccel_output_format " + hwOutputFormat + " -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
+ if (state.IsVideoRequest
+ && string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
+ {
+ arg.Append("-hwaccel videotoolbox ");
}
}
- return arg.Trim();
+ arg.Append("-i ")
+ .Append(GetInputPathArgument(state));
+
+ if (state.SubtitleStream != null
+ && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
+ && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
+ {
+ var subtitlePath = state.SubtitleStream.Path;
+
+ if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
+ {
+ var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
+ if (File.Exists(idxFile))
+ {
+ subtitlePath = idxFile;
+ }
+ }
+
+ arg.Append(" -i \"").Append(subtitlePath).Append('\"');
+ }
+
+ return arg.ToString();
}
/// <summary>
@@ -468,57 +704,138 @@ namespace MediaBrowser.Controller.MediaEncoding
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
- public bool IsH264(MediaStream stream)
+ public static bool IsH264(MediaStream stream)
{
var codec = stream.Codec ?? string.Empty;
- return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
- codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
+ return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
+ || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
}
- public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
+ public static bool IsH265(MediaStream stream)
{
- var bitrate = state.OutputVideoBitrate;
+ var codec = stream.Codec ?? string.Empty;
- if (bitrate.HasValue)
+ return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
+ || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
+ }
+
+ public static bool IsAAC(MediaStream stream)
+ {
+ var codec = stream.Codec ?? string.Empty;
+
+ return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1;
+ }
+
+ public static string GetBitStreamArgs(MediaStream stream)
+ {
+ // 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))
{
- if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
- {
- // With vpx when crf is used, b:v becomes a max rate
- // https://trac.ffmpeg.org/wiki/vpxEncodingGuide.
- return string.Format(" -maxrate:v {0} -bufsize:v {1} -b:v {0}", bitrate.Value.ToString(_usCulture), (bitrate.Value * 2).ToString(_usCulture));
- }
+ return "-bsf:v h264_mp4toannexb";
+ }
+ else if (IsH265(stream))
+ {
+ return "-bsf:v hevc_mp4toannexb";
+ }
+ else if (IsAAC(stream))
+ {
+ // Convert adts header(mpegts) to asc header(mp4).
+ return "-bsf:a aac_adtstoasc";
+ }
+ else
+ {
+ return null;
+ }
+ }
- if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
- {
- return string.Format(" -b:v {0}", bitrate.Value.ToString(_usCulture));
- }
+ public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
+ {
+ var bitStreamArgs = string.Empty;
+ var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.');
- if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
- {
- // h264
- return string.Format(" -maxrate {0} -bufsize {1}",
- bitrate.Value.ToString(_usCulture),
- (bitrate.Value * 2).ToString(_usCulture));
- }
+ // Apply aac_adtstoasc bitstream filter when media source is in mpegts.
+ if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)
+ && (string.Equals(mediaSourceContainer, "mpegts", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase)))
+ {
+ bitStreamArgs = GetBitStreamArgs(state.AudioStream);
+ bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;
+ }
- // h264
- return string.Format(" -b:v {0} -maxrate {0} -bufsize {1}",
- bitrate.Value.ToString(_usCulture),
- (bitrate.Value * 2).ToString(_usCulture));
+ return bitStreamArgs;
+ }
+
+ public static string GetSegmentFileExtension(string segmentContainer)
+ {
+ if (!string.IsNullOrWhiteSpace(segmentContainer))
+ {
+ return "." + segmentContainer;
}
- return string.Empty;
+ return ".ts";
+ }
+
+ public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
+ {
+ if (state.OutputVideoBitrate == null)
+ {
+ return string.Empty;
+ }
+
+ int bitrate = state.OutputVideoBitrate.Value;
+
+ // Currently use the same buffer size for all encoders
+ int bufsize = bitrate * 2;
+
+ if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase))
+ {
+ // When crf is used with vpx, b:v becomes a max rate
+ // https://trac.ffmpeg.org/wiki/Encode/VP8
+ // https://trac.ffmpeg.org/wiki/Encode/VP9
+ return FormattableString.Invariant($" -maxrate:v {bitrate} -bufsize:v {bufsize} -b:v {bitrate}");
+ }
+
+ if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
+ {
+ return FormattableString.Invariant($" -b:v {bitrate}");
+ }
+
+ if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
+ {
+ return FormattableString.Invariant($" -maxrate {bitrate} -bufsize {bufsize}");
+ }
+
+ return FormattableString.Invariant($" -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
}
- public string NormalizeTranscodingLevel(string videoCodec, string level)
+ public static string NormalizeTranscodingLevel(EncodingJobInfo state, string level)
{
- // Clients may direct play higher than level 41, but there's no reason to transcode higher
- if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)
- && string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)
- && requestLevel > 41)
+ if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double requestLevel))
{
- return "41";
+ if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase))
+ {
+ // Transcode to level 5.0 and lower for maximum compatibility.
+ // Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it.
+ // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
+ // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880.
+ if (requestLevel >= 150)
+ {
+ return "150";
+ }
+ }
+ else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ // Clients may direct play higher than level 41, but there's no reason to transcode higher.
+ if (requestLevel >= 41)
+ {
+ return "41";
+ }
+ }
}
return level;
@@ -536,7 +853,7 @@ namespace MediaBrowser.Controller.MediaEncoding
// hls always copies timestamps
var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
? string.Empty
- : string.Format(",setpts=PTS -{0}/TB", seconds.ToString(_usCulture));
+ : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
// TODO
// var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
@@ -547,14 +864,14 @@ namespace MediaBrowser.Controller.MediaEncoding
// _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
// using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
// {
- // using (var fileStream = _fileSystem.GetFileStream(fallbackFontPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
// {
// stream.CopyTo(fileStream);
// }
// }
// }
- // fallbackFontParam = string.Format(":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
+ // fallbackFontParam = string.Format(CultureInfo.InvariantCulture, ":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
if (state.SubtitleStream.IsExternal)
{
@@ -564,7 +881,11 @@ namespace MediaBrowser.Controller.MediaEncoding
if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
{
- var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.SubtitleStream.Language, state.MediaSource.Protocol, CancellationToken.None).Result;
+ var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
+ subtitlePath,
+ state.SubtitleStream.Language,
+ state.MediaSource.Protocol,
+ CancellationToken.None).GetAwaiter().GetResult();
if (!string.IsNullOrEmpty(charenc))
{
@@ -573,7 +894,9 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// TODO: Perhaps also use original_size=1920x800 ??
- return string.Format("subtitles=filename='{0}'{1}{2}{3}",
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "subtitles=filename='{0}'{1}{2}",
_mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
charsetParam,
// fallbackFontParam,
@@ -582,9 +905,11 @@ namespace MediaBrowser.Controller.MediaEncoding
var mediaPath = state.MediaPath ?? string.Empty;
- return string.Format("subtitles='{0}:si={1}'{2}",
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "subtitles='{0}:si={1}'{2}",
_mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
- state.InternalSubtitleStreamOffset.ToString(_usCulture),
+ state.InternalSubtitleStreamOffset.ToString(CultureInfo.InvariantCulture),
// fallbackFontParam,
setPtsParam);
}
@@ -613,79 +938,199 @@ namespace MediaBrowser.Controller.MediaEncoding
return null;
}
+ public string GetHlsVideoKeyFrameArguments(
+ EncodingJobInfo state,
+ string codec,
+ int segmentLength,
+ bool isEventPlaylist,
+ int? startNumber)
+ {
+ var args = string.Empty;
+ var gopArg = string.Empty;
+ var keyFrameArg = string.Empty;
+ if (isEventPlaylist)
+ {
+ keyFrameArg = string.Format(
+ CultureInfo.InvariantCulture,
+ " -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"",
+ segmentLength);
+ }
+ else if (startNumber.HasValue)
+ {
+ keyFrameArg = string.Format(
+ CultureInfo.InvariantCulture,
+ " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
+ startNumber.Value * segmentLength,
+ segmentLength);
+ }
+
+ var framerate = state.VideoStream?.RealFrameRate;
+ if (framerate.HasValue)
+ {
+ // This is to make sure keyframe interval is limited to our segment,
+ // as forcing keyframes is not enough.
+ // Example: we encoded half of desired length, then codec detected
+ // scene cut and inserted a keyframe; next forced keyframe would
+ // be created outside of segment, which breaks seeking.
+ // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe.
+ gopArg = string.Format(
+ CultureInfo.InvariantCulture,
+ " -g:v:0 {0} -keyint_min:v:0 {0} -sc_threshold:v:0 0",
+ Math.Ceiling(segmentLength * framerate.Value));
+ }
+
+ // Unable to force key frames using these encoders, set key frames by GOP.
+ if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase))
+ {
+ args += gopArg;
+ }
+ else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ args += " " + keyFrameArg;
+ }
+ else
+ {
+ args += " " + keyFrameArg + gopArg;
+ }
+
+ return args;
+ }
+
/// <summary>
- /// Gets the video bitrate to specify on the command line
+ /// Gets the video bitrate to specify on the command line.
/// </summary>
- public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultH264Preset)
+ /// <param name="state">Encoding state.</param>
+ /// <param name="videoEncoder">Video encoder to use.</param>
+ /// <param name="encodingOptions">Encoding options.</param>
+ /// <param name="defaultPreset">Default present to use for encoding.</param>
+ /// <returns>Video bitrate.</returns>
+ public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
{
var param = string.Empty;
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -pix_fmt yuv420p";
+ }
+
+ if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
+ {
+ var videoStream = state.VideoStream;
+ var isColorDepth10 = IsColorDepth10(state);
+ var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
+ var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
+
+ if (!isNvdecDecoder)
+ {
+ if (isColorDepth10
+ && _mediaEncoder.SupportsHwaccel("opencl")
+ && encodingOptions.EnableTonemapping
+ && !string.IsNullOrEmpty(videoStream.VideoRange)
+ && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -pix_fmt nv12";
+ }
+ else
+ {
+ param += " -pix_fmt yuv420p";
+ }
+ }
+ }
+
+ if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -pix_fmt nv21";
+ }
+
var isVc1 = state.VideoStream != null &&
string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
+ var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
- if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
{
- if (!string.IsNullOrEmpty(encodingOptions.H264Preset))
+ if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
{
- param += "-preset " + encodingOptions.H264Preset;
+ param += " -preset " + encodingOptions.EncoderPreset;
}
else
{
- param += "-preset " + defaultH264Preset;
+ param += " -preset " + defaultPreset;
}
- if (encodingOptions.H264Crf >= 0 && encodingOptions.H264Crf <= 51)
+ int encodeCrf = encodingOptions.H264Crf;
+ if (isLibX265)
{
- param += " -crf " + encodingOptions.H264Crf.ToString(CultureInfo.InvariantCulture);
+ encodeCrf = encodingOptions.H265Crf;
}
- else
+
+ if (encodeCrf >= 0 && encodeCrf <= 51)
{
- param += " -crf 23";
+ param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
}
- }
-
- else if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
- {
- param += "-preset fast";
+ else
+ {
+ string defaultCrf = "23";
+ if (isLibX265)
+ {
+ defaultCrf = "28";
+ }
- param += " -crf 28";
+ param += " -crf " + defaultCrf;
+ }
}
-
- // h264 (h264_qsv)
- else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv)
+ || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv)
{
string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
- if (valid_h264_qsv.Contains(encodingOptions.H264Preset, StringComparer.OrdinalIgnoreCase))
+ if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
{
- param += "-preset " + encodingOptions.H264Preset;
+ param += " -preset " + encodingOptions.EncoderPreset;
}
else
{
- param += "-preset 7";
+ param += " -preset 7";
}
param += " -look_ahead 0";
-
}
-
- // h264 (h264_nvenc)
- else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
+ || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc)
{
- switch (encodingOptions.H264Preset)
+ switch (encodingOptions.EncoderPreset)
{
case "veryslow":
- param += "-preset slow"; //lossless is only supported on maxwell and newer(2014+)
+ param += " -preset slow"; // lossless is only supported on maxwell and newer(2014+)
break;
case "slow":
case "slower":
- param += "-preset slow";
+ param += " -preset slow";
break;
case "medium":
- param += "-preset medium";
+ param += " -preset medium";
break;
case "fast":
@@ -693,17 +1138,61 @@ namespace MediaBrowser.Controller.MediaEncoding
case "veryfast":
case "superfast":
case "ultrafast":
- param += "-preset fast";
+ param += " -preset fast";
break;
default:
- param += "-preset default";
+ param += " -preset default";
break;
}
}
+ else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf)
+ || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf)
+ {
+ switch (encodingOptions.EncoderPreset)
+ {
+ case "veryslow":
+ case "slow":
+ case "slower":
+ param += " -quality quality";
+ break;
+
+ case "medium":
+ param += " -quality balanced";
+ break;
+
+ case "fast":
+ case "faster":
+ case "veryfast":
+ case "superfast":
+ case "ultrafast":
+ param += " -quality speed";
+ break;
+
+ default:
+ param += " -quality speed";
+ break;
+ }
+
+ var videoStream = state.VideoStream;
+ var isColorDepth10 = IsColorDepth10(state);
- // webm
- else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase))
+ if (isColorDepth10
+ && _mediaEncoder.SupportsHwaccel("opencl")
+ && encodingOptions.EnableTonemapping
+ && !string.IsNullOrEmpty(videoStream.VideoRange)
+ && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
+ {
+ // Enhance workload when tone mapping with AMF on some APUs
+ param += " -preanalysis true";
+ }
+
+ if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -header_insertion_mode gop -gops_per_idr 1";
+ }
+ }
+ else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // vp8
{
// Values 0-3, 0 being highest quality but slower
var profileScore = 0;
@@ -723,27 +1212,74 @@ namespace MediaBrowser.Controller.MediaEncoding
profileScore = Math.Min(profileScore, 2);
// http://www.webmproject.org/docs/encoder-parameters/
- param += string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
- profileScore.ToString(_usCulture),
+ param += string.Format(
+ CultureInfo.InvariantCulture,
+ " -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
+ profileScore.ToString(CultureInfo.InvariantCulture),
crf,
qmin,
qmax);
}
+ else if (string.Equals(videoEncoder, "libvpx-vp9", StringComparison.OrdinalIgnoreCase)) // vp9
+ {
+ // When `-deadline` is set to `good` or `best`, `-cpu-used` ranges from 0-5.
+ // When `-deadline` is set to `realtime`, `-cpu-used` ranges from 0-15.
+ // Resources:
+ // * https://trac.ffmpeg.org/wiki/Encode/VP9
+ // * https://superuser.com/questions/1586934
+ // * https://developers.google.com/media/vp9
+ param += encodingOptions.EncoderPreset switch
+ {
+ "veryslow" => " -deadline best -cpu-used 0",
+ "slower" => " -deadline best -cpu-used 2",
+ "slow" => " -deadline best -cpu-used 3",
+ "medium" => " -deadline good -cpu-used 0",
+ "fast" => " -deadline good -cpu-used 1",
+ "faster" => " -deadline good -cpu-used 2",
+ "veryfast" => " -deadline good -cpu-used 3",
+ "superfast" => " -deadline good -cpu-used 4",
+ "ultrafast" => " -deadline good -cpu-used 5",
+ _ => " -deadline good -cpu-used 1"
+ };
+
+ // TODO: until VP9 gets its own CRF setting, base CRF on H.265.
+ int h265Crf = encodingOptions.H265Crf;
+ int defaultVp9Crf = 31;
+ if (h265Crf >= 0 && h265Crf <= 51)
+ {
+ // This conversion factor is chosen to match the default CRF for H.265 to the
+ // recommended 1080p CRF from Google. The factor also maps the logarithmic CRF
+ // scale of x265 [0, 51] to that of VP9 [0, 63] relatively well.
+
+ // Resources:
+ // * https://developers.google.com/media/vp9/settings/vod
+ const float H265ToVp9CrfConversionFactor = 1.12F;
+ var vp9Crf = Convert.ToInt32(h265Crf * H265ToVp9CrfConversionFactor);
+
+ // Encoder allows for CRF values in the range [0, 63].
+ vp9Crf = Math.Clamp(vp9Crf, 0, 63);
+
+ param += FormattableString.Invariant($" -crf {vp9Crf}");
+ }
+ else
+ {
+ param += FormattableString.Invariant($" -crf {defaultVp9Crf}");
+ }
+
+ param += " -row-mt 1 -profile 1";
+ }
else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
{
- param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
+ param += " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
}
-
- // asf/wmv
- else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
{
- param += "-qmin 2";
+ param += " -qmin 2";
}
-
else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
- param += "-mbd 2";
+ param += " -mbd 2";
}
param += GetVideoBitrateParam(state, videoEncoder);
@@ -751,29 +1287,92 @@ namespace MediaBrowser.Controller.MediaEncoding
var framerate = GetFramerateParam(state);
if (framerate.HasValue)
{
- param += string.Format(" -r {0}", framerate.Value.ToString(_usCulture));
+ param += string.Format(CultureInfo.InvariantCulture, " -r {0}", framerate.Value.ToString(CultureInfo.InvariantCulture));
}
var targetVideoCodec = state.ActualOutputVideoCodec;
+ if (string.Equals(targetVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(targetVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ targetVideoCodec = "hevc";
+ }
- var request = state.BaseRequest;
- var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault();
+ var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault() ?? string.Empty;
+ profile = Regex.Replace(profile, @"\s+", string.Empty);
+
+ // We only transcode to HEVC 8-bit for now, force Main Profile.
+ if (profile.Contains("main10", StringComparison.OrdinalIgnoreCase)
+ || profile.Contains("mainstill", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "main";
+ }
+
+ // Extended Profile is not supported by any known h264 encoders, force Main Profile.
+ if (profile.Contains("extended", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "main";
+ }
+
+ // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile.
+ if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
+ && profile.Contains("high10", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "high";
+ }
+
+ // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case,
+ // which is compatible (and ugly).
+ if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "constrained_baseline";
+ }
+
+ // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
+ if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "baseline";
+ }
+
+ // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
+ if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ && profile.Contains("high", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "high";
+ }
+
+ if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "constrained_baseline";
+ }
- // vaapi does not support Baseline profile, force Constrained Baseline in this case,
- // which is compatible (and ugly)
- if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) &&
- profile != null && profile.ToLowerInvariant().Contains("baseline"))
+ if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ && profile.Contains("constrainedhigh", StringComparison.OrdinalIgnoreCase))
{
- profile = "constrained_baseline";
+ profile = "constrained_high";
+ }
+
+ // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile.
+ if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)
+ && profile.Contains("main10", StringComparison.OrdinalIgnoreCase))
+ {
+ profile = "main";
}
if (!string.IsNullOrEmpty(profile))
{
- if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
{
// not supported by h264_omx
- param += " -profile:v " + profile;
+ param += " -profile:v:0 " + profile;
}
}
@@ -781,53 +1380,35 @@ namespace MediaBrowser.Controller.MediaEncoding
if (!string.IsNullOrEmpty(level))
{
- level = NormalizeTranscodingLevel(state.OutputVideoCodec, level);
-
- // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
- // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307
- if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
- {
- switch (level)
- {
- case "30":
- param += " -level 3.0";
- break;
- case "31":
- param += " -level 3.1";
- break;
- case "32":
- param += " -level 3.2";
- break;
- case "40":
- param += " -level 4.0";
- break;
- case "41":
- param += " -level 4.1";
- break;
- case "42":
- param += " -level 4.2";
- break;
- case "50":
- param += " -level 5.0";
- break;
- case "51":
- param += " -level 5.1";
- break;
- case "52":
- param += " -level 5.2";
- break;
- default:
- param += " -level " + level;
- break;
- }
- }
- // nvenc doesn't decode with param -level set ?!
- else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
- {
- //param += "";
- }
- else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
+ level = NormalizeTranscodingLevel(state, level);
+
+ // libx264, QSV, AMF, VAAPI can adjust the given level to match the output.
+ if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -level " + level;
+ }
+ else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
+ {
+ // hevc_qsv use -level 51 instead of -level 153.
+ if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double hevcLevel))
+ {
+ param += " -level " + (hevcLevel / 3);
+ }
+ }
+ else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -level " + level;
+ }
+ else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
+ {
+ // level option may cause NVENC to fail.
+ // NVENC cannot adjust the given level, just throw an error.
+ }
+ else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
+ || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
{
param += " -level " + level;
}
@@ -838,17 +1419,13 @@ namespace MediaBrowser.Controller.MediaEncoding
param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
}
- if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
{
- param = "-pix_fmt yuv420p " + param;
- }
-
- if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
- {
- param = "-pix_fmt nv21 " + param;
+ // libx265 only accept level option in -x265-params.
+ // level option may cause libx265 to fail.
+ // libx265 cannot adjust the given level, just throw an error.
+ // TODO: set fine tuned params.
+ param += " -x265-params:0 no-info=1";
}
return param;
@@ -863,12 +1440,10 @@ namespace MediaBrowser.Controller.MediaEncoding
return false;
}
- if (videoStream.IsInterlaced)
+ if (videoStream.IsInterlaced
+ && state.DeInterlace(videoStream.Codec, false))
{
- if (state.DeInterlace(videoStream.Codec, false))
- {
- return false;
- }
+ return false;
}
if (videoStream.IsAnamorphic ?? false)
@@ -880,24 +1455,23 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Can't stream copy if we're burning in subtitles
- if (request.SubtitleStreamIndex.HasValue)
+ if (request.SubtitleStreamIndex.HasValue
+ && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
{
- if (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
- {
- return false;
- }
+ return false;
}
- if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
+ if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
+ && videoStream.IsAVC.HasValue
+ && !videoStream.IsAVC.Value
+ && request.RequireAvc)
{
- if (videoStream.IsAVC.HasValue && !videoStream.IsAVC.Value && request.RequireAvc)
- {
- return false;
- }
+ return false;
}
// Source and target codecs must match
- if (string.IsNullOrEmpty(videoStream.Codec) || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
+ if (string.IsNullOrEmpty(videoStream.Codec)
+ || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
{
return false;
}
@@ -909,12 +1483,13 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (string.IsNullOrEmpty(videoStream.Profile))
{
- //return false;
+ // return false;
}
var requestedProfile = requestedProfiles[0];
// strip spaces because they may be stripped out on the query string as well
- if (!string.IsNullOrEmpty(videoStream.Profile) && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", ""), StringComparer.OrdinalIgnoreCase))
+ if (!string.IsNullOrEmpty(videoStream.Profile)
+ && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparer.OrdinalIgnoreCase))
{
var currentScore = GetVideoProfileScore(videoStream.Profile);
var requestedScore = GetVideoProfileScore(requestedProfile);
@@ -927,21 +1502,17 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Video width must fall within requested value
- if (request.MaxWidth.HasValue)
+ if (request.MaxWidth.HasValue
+ && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
{
- if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
- {
- return false;
- }
+ return false;
}
// Video height must fall within requested value
- if (request.MaxHeight.HasValue)
+ if (request.MaxHeight.HasValue
+ && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
{
- if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
- {
- return false;
- }
+ return false;
}
// Video framerate must fall within requested value
@@ -957,12 +1528,10 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Video bitrate must fall within requested value
- if (request.VideoBitRate.HasValue)
+ if (request.VideoBitRate.HasValue
+ && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
{
- if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
- {
- return false;
- }
+ return false;
}
var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
@@ -975,35 +1544,31 @@ namespace MediaBrowser.Controller.MediaEncoding
}
var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
- if (maxRefFrames.HasValue)
+ if (maxRefFrames.HasValue
+ && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
{
- if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
- {
- return false;
- }
+ return false;
}
// If a specific level was requested, the source must match or be less than
var level = state.GetRequestedLevel(videoStream.Codec);
- if (!string.IsNullOrEmpty(level))
+ if (!string.IsNullOrEmpty(level)
+ && double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out var requestLevel))
{
- if (double.TryParse(level, NumberStyles.Any, _usCulture, out var requestLevel))
+ if (!videoStream.Level.HasValue)
{
- if (!videoStream.Level.HasValue)
- {
- //return false;
- }
+ // return false;
+ }
- if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
- {
- return false;
- }
+ if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
+ {
+ return false;
}
}
- if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase) &&
- string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase) &&
- !(videoStream.IsAVC ?? false))
+ if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
+ && !(videoStream.IsAVC ?? false))
{
// see Coach S01E01 - Kelly and the Professor(0).avi
return false;
@@ -1012,7 +1577,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return request.EnableAutoStreamCopy;
}
- public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, string[] supportedAudioCodecs)
+ public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
{
var request = state.BaseRequest;
@@ -1022,16 +1587,16 @@ namespace MediaBrowser.Controller.MediaEncoding
}
var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
- if (maxBitDepth.HasValue)
+ if (maxBitDepth.HasValue
+ && audioStream.BitDepth.HasValue
+ && audioStream.BitDepth.Value > maxBitDepth.Value)
{
- if (audioStream.BitDepth.HasValue && audioStream.BitDepth.Value > maxBitDepth.Value)
- {
- return false;
- }
+ return false;
}
// Source and target codecs must match
- if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
+ if (string.IsNullOrEmpty(audioStream.Codec)
+ || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
{
return false;
}
@@ -1044,6 +1609,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return false;
}
+
if (audioStream.Channels.Value > channels.Value)
{
return false;
@@ -1057,6 +1623,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return false;
}
+
if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
{
return false;
@@ -1070,6 +1637,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return false;
}
+
if (audioStream.BitRate.Value > request.AudioBitRate.Value)
{
return false;
@@ -1083,14 +1651,21 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var bitrate = request.VideoBitRate;
- // If specific values were requested, then force the caller to supply a bitrate as well
- if (request.Height.HasValue && request.Width.HasValue)
- {
- return bitrate;
- }
-
if (videoStream != null)
{
+ var isUpscaling = request.Height.HasValue
+ && videoStream.Height.HasValue
+ && request.Height.Value > videoStream.Height.Value
+ && request.Width.HasValue
+ && videoStream.Width.HasValue
+ && request.Width.Value > videoStream.Width.Value;
+
+ // Don't allow bitrate increases unless upscaling
+ if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
+ {
+ bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
+ }
+
if (bitrate.HasValue)
{
var inputVideoCodec = videoStream.Codec;
@@ -1107,14 +1682,32 @@ namespace MediaBrowser.Controller.MediaEncoding
return bitrate;
}
+ private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
+ {
+ // these values were chosen from testing to improve low bitrate streams
+ if (sourceBitrate <= 2000000)
+ {
+ sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
+ }
+ else if (sourceBitrate <= 3000000)
+ {
+ sourceBitrate *= 2;
+ }
+
+ var bitrate = Math.Min(sourceBitrate, requestedBitrate);
+
+ return bitrate;
+ }
+
private static double GetVideoBitrateScaleFactor(string codec)
{
- if (StringHelper.EqualsIgnoreCase(codec, "h265") ||
- StringHelper.EqualsIgnoreCase(codec, "hevc") ||
- StringHelper.EqualsIgnoreCase(codec, "vp9"))
+ if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
{
- return .5;
+ return .6;
}
+
return 1;
}
@@ -1141,39 +1734,74 @@ namespace MediaBrowser.Controller.MediaEncoding
scaleFactor = Math.Max(scaleFactor, 2);
}
- var newBitrate = scaleFactor * bitrate;
-
- return Convert.ToInt32(newBitrate);
+ return Convert.ToInt32(scaleFactor * bitrate);
}
public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
{
- if (request.AudioBitRate.HasValue)
+ return GetAudioBitrateParam(request.AudioBitRate, request.AudioCodec, audioStream);
+ }
+
+ public int? GetAudioBitrateParam(int? audioBitRate, string audioCodec, MediaStream audioStream)
+ {
+ if (audioStream == null)
{
- // Make sure we don't request a bitrate higher than the source
- var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
+ return null;
+ }
- // Don't encode any higher than this
- return Math.Min(384000, request.AudioBitRate.Value);
- //return Math.Min(currentBitrate, request.AudioBitRate.Value);
+ if (audioBitRate.HasValue && string.IsNullOrEmpty(audioCodec))
+ {
+ return Math.Min(384000, audioBitRate.Value);
}
- return null;
+ if (audioBitRate.HasValue && !string.IsNullOrEmpty(audioCodec))
+ {
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
+ {
+ if ((audioStream.Channels ?? 0) >= 6)
+ {
+ return Math.Min(640000, audioBitRate.Value);
+ }
+
+ return Math.Min(384000, audioBitRate.Value);
+ }
+
+ if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
+ {
+ if ((audioStream.Channels ?? 0) >= 6)
+ {
+ return Math.Min(3584000, audioBitRate.Value);
+ }
+
+ return Math.Min(1536000, audioBitRate.Value);
+ }
+ }
+
+ // Empty bitrate area is not allow on iOS
+ // Default audio bitrate to 128K if it is not being requested
+ // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
+ return 128000;
}
- public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
+ public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions)
{
var channels = state.OutputAudioChannels;
var filters = new List<string>();
// Boost volume to 200% when downsampling from 6ch to 2ch
- if (channels.HasValue && channels.Value <= 2)
+ if (channels.HasValue
+ && channels.Value <= 2
+ && state.AudioStream != null
+ && state.AudioStream.Channels.HasValue
+ && state.AudioStream.Channels.Value > 5
+ && !encodingOptions.DownMixAudioBoost.Equals(1))
{
- if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5 && !encodingOptions.DownMixAudioBoost.Equals(1))
- {
- filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(_usCulture));
- }
+ filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(CultureInfo.InvariantCulture));
}
var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
@@ -1181,19 +1809,23 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
- filters.Add(string.Format("asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(_usCulture)));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "asetpts=PTS-{0}/TB",
+ Math.Round(seconds)));
}
if (filters.Count > 0)
{
- return "-af \"" + string.Join(",", filters.ToArray()) + "\"";
+ return " -af \"" + string.Join(',', filters) + "\"";
}
return string.Empty;
}
/// <summary>
- /// Gets the number of audio channels to specify on the command line
+ /// Gets the number of audio channels to specify on the command line.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="audioStream">The audio stream.</param>
@@ -1201,38 +1833,45 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <returns>System.Nullable{System.Int32}.</returns>
public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
{
+ if (audioStream == null)
+ {
+ return null;
+ }
+
var request = state.BaseRequest;
- var inputChannels = audioStream == null
- ? null
- : audioStream.Channels;
+ var inputChannels = audioStream.Channels;
if (inputChannels <= 0)
{
inputChannels = null;
}
- int? transcoderChannelLimit = null;
var codec = outputAudioCodec ?? string.Empty;
+ int? transcoderChannelLimit;
if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
{
// wmav2 currently only supports two channel output
transcoderChannelLimit = 2;
}
-
else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
{
// libmp3lame currently only supports two channel output
transcoderChannelLimit = 2;
}
+ else if (codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ // aac is able to handle 8ch(7.1 layout)
+ transcoderChannelLimit = 8;
+ }
else
{
// If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
transcoderChannelLimit = 6;
}
- var isTranscodingAudio = !string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
+ var isTranscodingAudio = !IsCopyCodec(codec);
int? resultChannels = state.GetRequestedAudioChannels(codec);
if (isTranscodingAudio)
@@ -1254,6 +1893,16 @@ namespace MediaBrowser.Controller.MediaEncoding
: transcoderChannelLimit.Value;
}
+ // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout).
+ // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
+ if (isTranscodingAudio
+ && state.TranscodingType != TranscodingJobType.Progressive
+ && resultChannels.HasValue
+ && ((resultChannels.Value > 2 && resultChannels.Value < 6) || resultChannels.Value == 7))
+ {
+ resultChannels = 2;
+ }
+
return resultChannels;
}
@@ -1263,6 +1912,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return val2;
}
+
if (!val2.HasValue)
{
return val1;
@@ -1299,7 +1949,7 @@ namespace MediaBrowser.Controller.MediaEncoding
if (time > 0)
{
- return string.Format("-ss {0}", _mediaEncoder.GetTimeParameter(time));
+ return string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(time));
}
return string.Empty;
@@ -1336,7 +1986,10 @@ namespace MediaBrowser.Controller.MediaEncoding
if (state.VideoStream != null)
{
- args += string.Format("-map 0:{0}", state.VideoStream.Index);
+ args += string.Format(
+ CultureInfo.InvariantCulture,
+ "-map 0:{0}",
+ state.VideoStream.Index);
}
else
{
@@ -1346,9 +1999,11 @@ namespace MediaBrowser.Controller.MediaEncoding
if (state.AudioStream != null)
{
- args += string.Format(" -map 0:{0}", state.AudioStream.Index);
+ args += string.Format(
+ CultureInfo.InvariantCulture,
+ " -map 0:{0}",
+ state.AudioStream.Index);
}
-
else
{
args += " -map -0:a";
@@ -1361,7 +2016,10 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
{
- args += string.Format(" -map 0:{0}", state.SubtitleStream.Index);
+ args += string.Format(
+ CultureInfo.InvariantCulture,
+ " -map 0:{0}",
+ state.SubtitleStream.Index);
}
else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
{
@@ -1372,7 +2030,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Determines which stream will be used for playback
+ /// Determines which stream will be used for playback.
/// </summary>
/// <param name="allStream">All stream.</param>
/// <param name="desiredIndex">Index of the desired.</param>
@@ -1404,56 +2062,90 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Gets the internal graphical subtitle param.
+ /// Gets the graphical subtitle parameter.
/// </summary>
- public string GetGraphicalSubtitleParam(EncodingJobInfo state, EncodingOptions options, string outputVideoCodec)
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="outputVideoCodec">Video codec to use.</param>
+ /// <returns>Graphical subtitle parameter.</returns>
+ public string GetGraphicalSubtitleParam(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string outputVideoCodec)
{
- var outputSizeParam = string.Empty;
+ outputVideoCodec ??= string.Empty;
+ var outputSizeParam = ReadOnlySpan<char>.Empty;
var request = state.BaseRequest;
- // Add resolution params, if specified
- if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
+ outputSizeParam = GetOutputSizeParamInternal(state, options, outputVideoCodec);
+
+ var videoSizeParam = string.Empty;
+ var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
+ var isLinux = OperatingSystem.IsLinux();
+
+ var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isQsvH264Encoder = outputVideoCodec.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
+ var isQsvHevcEncoder = outputVideoCodec.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
+ var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
+ var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
+ var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
+ var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
+ var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
+ var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
+
+ var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
+ var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
+ var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
+
+ // Tonemapping and burn-in graphical subtitles requires overlay_vaapi.
+ // But it's still in ffmpeg mailing list. Disable it for now.
+ if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
+ {
+ return GetOutputSizeParam(state, options, outputVideoCodec);
+ }
+
+ // Setup subtitle scaling
+ if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
{
- outputSizeParam = GetOutputSizeParam(state, options, outputVideoCodec).TrimEnd('"');
+ // Adjust the size of graphical subtitles to fit the video stream.
+ var videoStream = state.VideoStream;
+ var inputWidth = videoStream.Width;
+ var inputHeight = videoStream.Height;
+ var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
- if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (width.HasValue && height.HasValue)
{
- var index = outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase);
- if (index != -1)
- {
- outputSizeParam = "," + outputSizeParam.Substring(index);
- }
+ videoSizeParam = string.Format(
+ CultureInfo.InvariantCulture,
+ "scale={0}x{1}",
+ width.Value,
+ height.Value);
}
- else
+
+ if (!string.IsNullOrEmpty(videoSizeParam)
+ && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
{
- var index = outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase);
- if (index != -1)
+ // upload graphical subtitle to QSV
+ if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)))
{
- outputSizeParam = "," + outputSizeParam.Substring(index);
+ videoSizeParam += ",hwupload=extra_hw_frames=64";
}
}
- }
-
- if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
- {
- outputSizeParam = ",format=nv12|vaapi,hwupload";
- // Add parameters to use VAAPI with burn-in subttiles (GH issue #642)
- if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode) {
- outputSizeParam += ",hwmap=mode=read+write+direct";
+ if (!string.IsNullOrEmpty(videoSizeParam))
+ {
+ // upload graphical subtitle to cuda
+ if (isNvdecDecoder && isNvencEncoder && isCudaOverlaySupported && isCudaFormatConversionSupported)
+ {
+ videoSizeParam += ",hwupload_cuda";
+ }
}
}
- var videoSizeParam = string.Empty;
-
- if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
- {
- videoSizeParam = string.Format("scale={0}:{1}", state.VideoStream.Width.Value.ToString(_usCulture), state.VideoStream.Height.Value.ToString(_usCulture));
-
- videoSizeParam += ":force_original_aspect_ratio=decrease";
- }
-
var mapPrefix = state.SubtitleStream.IsExternal ?
1 :
0;
@@ -1462,15 +2154,88 @@ namespace MediaBrowser.Controller.MediaEncoding
? 0
: state.SubtitleStream.Index;
- return string.Format(" -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay{3}\"",
- mapPrefix.ToString(_usCulture),
- subtitleStreamIndex.ToString(_usCulture),
- state.VideoStream.Index.ToString(_usCulture),
- outputSizeParam,
+ // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
+ // Always put the scaler before the overlay for better performance
+ var retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
+
+ // When the input may or may not be hardware VAAPI decodable
+ if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(outputVideoCodec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ /*
+ [base]: HW scaling video to OutputSize
+ [sub]: SW scaling subtitle to FixedOutputSize
+ [base][sub]: SW overlay
+ */
+ retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwdownload[base];[base][sub]overlay,format=nv12,hwupload\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
+ }
+
+ // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
+ else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
+ && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase)))
+ {
+ /*
+ [base]: SW scaling video to OutputSize
+ [sub]: SW scaling subtitle to FixedOutputSize
+ [base][sub]: SW overlay
+ */
+ retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
+ }
+ else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
+ {
+ /*
+ QSV in FFMpeg can now setup hardware overlay for transcodes.
+ For software decoding and hardware encoding option, frames must be hwuploaded into hardware
+ with fixed frame size.
+ Currently only supports linux.
+ */
+ if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
+ {
+ retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload,format=nv12[base];[base][sub]overlay\"";
+ }
+ else if (isLinux)
+ {
+ retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_qsv\"";
+ }
+ }
+ else if (isNvdecDecoder && isNvencEncoder)
+ {
+ if (isCudaOverlaySupported && isCudaFormatConversionSupported)
+ {
+ retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]scale_cuda=format=yuv420p[base];[base][sub]overlay_cuda\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_cuda\"";
+ }
+ else
+ {
+ retStr = outputSizeParam.IsEmpty
+ ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=nv12|yuv420p,hwupload_cuda\""
+ : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=nv12|yuv420p,hwupload_cuda\"";
+ }
+ }
+
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ retStr,
+ mapPrefix,
+ subtitleStreamIndex,
+ state.VideoStream.Index,
+ outputSizeParam.ToString(),
videoSizeParam);
}
- private ValueTuple<int?, int?> GetFixedOutputSize(int? videoWidth,
+ public static (int? width, int? height) GetFixedOutputSize(
+ int? videoWidth,
int? videoHeight,
int? requestedWidth,
int? requestedHeight,
@@ -1479,15 +2244,16 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (!videoWidth.HasValue && !requestedWidth.HasValue)
{
- return new ValueTuple<int?, int?>(null, null);
+ return (null, null);
}
+
if (!videoHeight.HasValue && !requestedHeight.HasValue)
{
- return new ValueTuple<int?, int?>(null, null);
+ return (null, null);
}
- decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth);
- decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight);
+ decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth, CultureInfo.InvariantCulture);
+ decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight, CultureInfo.InvariantCulture);
decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
@@ -1503,10 +2269,13 @@ namespace MediaBrowser.Controller.MediaEncoding
outputWidth = 2 * Math.Truncate(outputWidth / 2);
outputHeight = 2 * Math.Truncate(outputHeight / 2);
- return new ValueTuple<int?, int?>(Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
+ return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
}
- public List<string> GetScalingFilters(int? videoWidth,
+ public List<string> GetScalingFilters(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ int? videoWidth,
int? videoHeight,
Video3DFormat? threedFormat,
string videoDecoder,
@@ -1517,25 +2286,140 @@ namespace MediaBrowser.Controller.MediaEncoding
int? requestedMaxHeight)
{
var filters = new List<string>();
- var fixedOutputSize = GetFixedOutputSize(videoWidth, videoHeight, requestedWidth, requestedHeight, requestedMaxWidth, requestedMaxHeight);
-
- if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && fixedOutputSize.Item1.HasValue && fixedOutputSize.Item2.HasValue)
+ var (width, height) = GetFixedOutputSize(
+ videoWidth,
+ videoHeight,
+ requestedWidth,
+ requestedHeight,
+ requestedMaxWidth,
+ requestedMaxHeight);
+
+ if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
+ && width.HasValue
+ && height.HasValue)
{
- // Work around vaapi's reduced scaling features
- var scaler = "scale_vaapi";
-
// Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
// (outputWidth, outputHeight). The user may request precise output dimensions or maximum
// output dimensions. Output dimensions are guaranteed to be even.
- var outputWidth = fixedOutputSize.Item1.Value;
- var outputHeight = fixedOutputSize.Item2.Value;
+ var outputWidth = width.Value;
+ var outputHeight = height.Value;
+ var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase);
+ var isDeintEnabled = state.DeInterlace("h264", true)
+ || state.DeInterlace("avc", true)
+ || state.DeInterlace("h265", true)
+ || state.DeInterlace("hevc", true);
+
+ var isVaapiDecoder = videoDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
+ var isVaapiH264Encoder = videoEncoder.Contains("h264_vaapi", StringComparison.OrdinalIgnoreCase);
+ var isVaapiHevcEncoder = videoEncoder.Contains("hevc_vaapi", StringComparison.OrdinalIgnoreCase);
+ var isQsvH264Encoder = videoEncoder.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
+ var isQsvHevcEncoder = videoEncoder.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
+ var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
+ var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
+ var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
+ var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
+ var isP010PixFmtRequired = (isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported))
+ || (isTonemappingSupportedOnQsv && isVppTonemappingSupported);
+
+ var outputPixFmt = "format=nv12";
+ if (isP010PixFmtRequired)
+ {
+ outputPixFmt = "format=p010";
+ }
+
+ if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
+ {
+ qsv_or_vaapi = false;
+ }
+
+ if (!videoWidth.HasValue
+ || outputWidth != videoWidth.Value
+ || !videoHeight.HasValue
+ || outputHeight != videoHeight.Value)
+ {
+ // Force nv12 pixel format to enable 10-bit to 8-bit colour conversion.
+ // use vpp_qsv filter to avoid green bar when the fixed output size is requested.
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}=w={1}:h={2}{3}{4}",
+ qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
+ outputWidth,
+ outputHeight,
+ ":" + outputPixFmt,
+ (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
+ }
- if (!videoWidth.HasValue || outputWidth != videoWidth.Value || !videoHeight.HasValue || outputHeight != videoHeight.Value)
+ // Assert 10-bit is P010 so as we can avoid the extra scaler to get a bit more fps on high res HDR videos.
+ else if (!isP010PixFmtRequired)
{
- filters.Add(string.Format("{0}=w={1}:h={2}", scaler, outputWidth.ToString(_usCulture), outputHeight.ToString(_usCulture)));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}={1}{2}",
+ qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
+ outputPixFmt,
+ (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
}
}
- else if ((videoDecoder ?? string.Empty).IndexOf("_cuvid", StringComparison.OrdinalIgnoreCase) != -1 && fixedOutputSize.Item1.HasValue && fixedOutputSize.Item2.HasValue)
+ else if ((videoDecoder ?? string.Empty).Contains("cuda", StringComparison.OrdinalIgnoreCase)
+ && width.HasValue
+ && height.HasValue)
+ {
+ var outputWidth = width.Value;
+ var outputHeight = height.Value;
+
+ var isNvencEncoder = videoEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
+ var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
+ var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
+ var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase);
+ var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
+ var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
+ var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+
+ var outputPixFmt = string.Empty;
+ if (isCudaFormatConversionSupported)
+ {
+ outputPixFmt = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
+ ? "format=yuv420p"
+ : "format=nv12";
+ if ((isOpenclTonemappingSupported || isCudaTonemappingSupported)
+ && isTonemappingSupportedOnNvenc)
+ {
+ outputPixFmt = "format=p010";
+ }
+ }
+
+ if (!videoWidth.HasValue
+ || outputWidth != videoWidth.Value
+ || !videoHeight.HasValue
+ || outputHeight != videoHeight.Value)
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale_cuda=w={0}:h={1}{2}",
+ outputWidth,
+ outputHeight,
+ isCudaFormatConversionSupported ? (":" + outputPixFmt) : string.Empty));
+ }
+ else if (isCudaFormatConversionSupported)
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale_cuda={0}",
+ outputPixFmt));
+ }
+ }
+ else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
+ && width.HasValue
+ && height.HasValue)
{
// Nothing to do, it's handled as an input resize filter
}
@@ -1548,10 +2432,15 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (isExynosV4L2)
{
- var widthParam = requestedWidth.Value.ToString(_usCulture);
- var heightParam = requestedHeight.Value.ToString(_usCulture);
-
- filters.Add(string.Format("scale=trunc({0}/64)*64:trunc({1}/2)*2", widthParam, heightParam));
+ var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
+ var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
+
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc({0}/64)*64:trunc({1}/2)*2",
+ widthParam,
+ heightParam));
}
else
{
@@ -1562,16 +2451,26 @@ namespace MediaBrowser.Controller.MediaEncoding
// If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
{
- var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
- var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
+ var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
+ var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
if (isExynosV4L2)
{
- filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/64)*64:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/64)*64:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
+ maxWidthParam,
+ maxHeightParam));
}
else
{
- filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
+ maxWidthParam,
+ maxHeightParam));
}
}
@@ -1585,54 +2484,82 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else
{
- var widthParam = requestedWidth.Value.ToString(_usCulture);
+ var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
- filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale={0}:trunc(ow/a/2)*2",
+ widthParam));
}
}
// If a fixed height was requested
else if (requestedHeight.HasValue)
{
- var heightParam = requestedHeight.Value.ToString(_usCulture);
+ var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
if (isExynosV4L2)
{
- filters.Add(string.Format("scale=trunc(oh*a/64)*64:{0}", heightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(oh*a/64)*64:{0}",
+ heightParam));
}
else
{
- filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(oh*a/2)*2:{0}",
+ heightParam));
}
}
// If a max width was requested
else if (requestedMaxWidth.HasValue)
{
- var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
+ var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
if (isExynosV4L2)
{
- filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2", maxWidthParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2",
+ maxWidthParam));
}
else
{
- filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2", maxWidthParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2",
+ maxWidthParam));
}
}
// If a max height was requested
else if (requestedMaxHeight.HasValue)
{
- var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
+ var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
if (isExynosV4L2)
{
- filters.Add(string.Format("scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})", maxHeightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})",
+ maxHeightParam));
}
else
{
- filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})", maxHeightParam));
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})",
+ maxHeightParam));
}
}
}
@@ -1642,8 +2569,8 @@ namespace MediaBrowser.Controller.MediaEncoding
private string GetFixedSizeScalingFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
{
- var widthParam = requestedWidth.ToString(_usCulture);
- var heightParam = requestedHeight.ToString(_usCulture);
+ var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
+ var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
string filter = null;
@@ -1657,11 +2584,11 @@ namespace MediaBrowser.Controller.MediaEncoding
break;
case Video3DFormat.FullSideBySide:
filter = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
- //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
+ // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
break;
case Video3DFormat.HalfTopAndBottom:
filter = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
- //htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
+ // htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
break;
case Video3DFormat.FullTopAndBottom:
filter = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
@@ -1685,62 +2612,490 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
- return string.Format(filter, widthParam, heightParam);
+ return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
}
/// <summary>
- /// If we're going to put a fixed size on the command line, this will calculate it
+ /// Gets the output size parameter.
/// </summary>
- public string GetOutputSizeParam(EncodingJobInfo state,
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="outputVideoCodec">Video codec to use.</param>
+ /// <returns>The output size parameter.</returns>
+ public string GetOutputSizeParam(
+ EncodingJobInfo state,
EncodingOptions options,
- string outputVideoCodec,
- bool allowTimeStampCopy = true)
+ string outputVideoCodec)
+ {
+ string filters = GetOutputSizeParamInternal(state, options, outputVideoCodec);
+ return string.IsNullOrEmpty(filters) ? string.Empty : " -vf \"" + filters + "\"";
+ }
+
+ /// <summary>
+ /// Gets the output size parameter.
+ /// If we're going to put a fixed size on the command line, this will calculate it.
+ /// </summary>
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="outputVideoCodec">Video codec to use.</param>
+ /// <returns>The output size parameter.</returns>
+ public string GetOutputSizeParamInternal(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string outputVideoCodec)
{
// http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
var request = state.BaseRequest;
-
+ var videoStream = state.VideoStream;
var filters = new List<string>();
- if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
+ var inputWidth = videoStream?.Width;
+ var inputHeight = videoStream?.Height;
+ var threeDFormat = state.MediaSource.Video3DFormat;
+
+ var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
+ var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
+ var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1;
+ var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1;
+ var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
+ var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
+ var isCuvidH264Decoder = videoDecoder.Contains("h264_cuvid", StringComparison.OrdinalIgnoreCase);
+ var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
+ var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
+ var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1;
+ var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1;
+ var isLinux = OperatingSystem.IsLinux();
+ var isColorDepth10 = IsColorDepth10(state);
+
+ var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder);
+ var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder);
+ var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
+ var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
+ var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
+ var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
+ var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
+ var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
+ var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
+
+ var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+ var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+
+ // If double rate deinterlacing is enabled and the input framerate is 30fps or below, otherwise the output framerate will be too high for many devices
+ var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.AverageFrameRate ?? 60) <= 30;
+
+ var isScalingInAdvance = false;
+ var isCudaDeintInAdvance = false;
+ var isHwuploadCudaRequired = false;
+ var isNoTonemapFilterApplied = true;
+ var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
+ var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
+
+ // Add OpenCL tonemapping filter for NVENC/AMF/VAAPI.
+ if ((isTonemappingSupportedOnNvenc && !isCudaTonemappingSupported) || isTonemappingSupportedOnAmf || (isTonemappingSupportedOnVaapi && !isVppTonemappingSupported))
+ {
+ // NVIDIA Pascal and Turing or higher are recommended.
+ // AMD Polaris and Vega or higher are recommended.
+ // Intel Kaby Lake or newer is required.
+ if (isOpenclTonemappingSupported)
+ {
+ isNoTonemapFilterApplied = false;
+ var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
+ if (!string.IsNullOrEmpty(inputHdrParams))
+ {
+ filters.Add(inputHdrParams);
+ }
+
+ var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}";
+
+ if (options.TonemappingParam != 0)
+ {
+ parameters += ":param={4}";
+ }
+
+ if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
+ {
+ parameters += ":range={5}";
+ }
+
+ if (isSwDecoder || isD3d11vaDecoder)
+ {
+ isScalingInAdvance = true;
+ // Add zscale filter before tone mapping filter for performance.
+ var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
+ if (width.HasValue && height.HasValue)
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "zscale=s={0}x{1}",
+ width.Value,
+ height.Value));
+ }
+
+ // Convert to hardware pixel format p010 when using SW decoder.
+ filters.Add("format=p010");
+ }
+
+ if ((isDeinterlaceH264 || isDeinterlaceHevc) && isNvdecDecoder)
+ {
+ isCudaDeintInAdvance = true;
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "yadif_cuda={0}:-1:0",
+ doubleRateDeinterlace ? "1" : "0"));
+ }
+
+ if (isVaapiDecoder || isNvdecDecoder)
+ {
+ isScalingInAdvance = true;
+ filters.AddRange(
+ GetScalingFilters(
+ state,
+ options,
+ inputWidth,
+ inputHeight,
+ threeDFormat,
+ videoDecoder,
+ outputVideoCodec,
+ request.Width,
+ request.Height,
+ request.MaxWidth,
+ request.MaxHeight));
+ }
+
+ // hwmap the HDR data to opencl device by cl-va p010 interop.
+ if (isVaapiDecoder)
+ {
+ filters.Add("hwmap");
+ }
+
+ // convert cuda device data to p010 host data.
+ if (isNvdecDecoder)
+ {
+ filters.Add("hwdownload,format=p010");
+ }
+
+ if (isNvdecDecoder
+ || isCuvidHevcDecoder
+ || isCuvidVp9Decoder
+ || isSwDecoder
+ || isD3d11vaDecoder)
+ {
+ // Upload the HDR10 or HLG data to the OpenCL device,
+ // use tonemap_opencl filter for tone mapping,
+ // and then download the SDR data to memory.
+ filters.Add("hwupload");
+ }
+
+ // Fallback to hable if bt2390 is chosen but not supported in tonemap_opencl.
+ var isBt2390SupportedInOpenclTonemap = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapOpenclBt2390);
+ if (string.Equals(options.TonemappingAlgorithm, "bt2390", StringComparison.OrdinalIgnoreCase)
+ && !isBt2390SupportedInOpenclTonemap)
+ {
+ options.TonemappingAlgorithm = "hable";
+ }
+
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ parameters,
+ options.TonemappingAlgorithm,
+ options.TonemappingDesat,
+ options.TonemappingThreshold,
+ options.TonemappingPeak,
+ options.TonemappingParam,
+ options.TonemappingRange));
+
+ if (isNvdecDecoder
+ || isCuvidHevcDecoder
+ || isCuvidVp9Decoder
+ || isSwDecoder
+ || isD3d11vaDecoder)
+ {
+ filters.Add("hwdownload");
+ filters.Add("format=nv12");
+ }
+
+ if (isNvdecDecoder && isNvencEncoder)
+ {
+ isHwuploadCudaRequired = true;
+ }
+
+ if (isVaapiDecoder)
+ {
+ // Reverse the data route from opencl to vaapi.
+ filters.Add("hwmap=derive_device=vaapi:reverse=1");
+ }
+
+ var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
+ if (!string.IsNullOrEmpty(outputSdrParams))
+ {
+ filters.Add(outputSdrParams);
+ }
+ }
+ }
+
+ // When the input may or may not be hardware VAAPI decodable.
+ if ((isVaapiH264Encoder || isVaapiHevcEncoder)
+ && !(isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported)))
{
filters.Add("format=nv12|vaapi");
filters.Add("hwupload");
}
- if (state.DeInterlace("h264", true) && string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context.
+ else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)
+ && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
{
- filters.Add(string.Format("deinterlace_vaapi"));
+ filters.Add("hwupload=extra_hw_frames=64");
}
- var videoStream = state.VideoStream;
+ // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first.
+ else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)
+ && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
+ {
+ var codec = videoStream.Codec;
+
+ // Assert 10-bit hardware VAAPI decodable
+ if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
+ {
+ /*
+ Download data from GPU to CPU as p010le format.
+ Colorspace conversion is unnecessary here as libx264 will handle it.
+ If this step is missing, it will fail on AMD but not on intel.
+ */
+ filters.Add("hwdownload");
+ filters.Add("format=p010le");
+ }
+
+ // Assert 8-bit hardware VAAPI decodable
+ else if (!isColorDepth10)
+ {
+ filters.Add("hwdownload");
+ filters.Add("format=nv12");
+ }
+ }
- if (state.DeInterlace("h264", true) && !string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ // Add hardware deinterlace filter before scaling filter.
+ if (isDeinterlaceH264 || isDeinterlaceHevc)
{
- var inputFramerate = videoStream == null ? null : videoStream.RealFrameRate;
+ if (isVaapiEncoder
+ || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "deinterlace_vaapi=rate={0}",
+ doubleRateDeinterlace ? "field" : "frame"));
+ }
+ else if (isNvdecDecoder && !isCudaDeintInAdvance)
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "yadif_cuda={0}:-1:0",
+ doubleRateDeinterlace ? "1" : "0"));
+ }
+ }
- // If it is already 60fps then it will create an output framerate that is much too high for roku and others to handle
- if (string.Equals(options.DeinterlaceMethod, "bobandweave", StringComparison.OrdinalIgnoreCase) && (inputFramerate ?? 60) <= 30)
+ // Add software deinterlace filter before scaling filter.
+ if ((isDeinterlaceH264 || isDeinterlaceHevc)
+ && !isVaapiH264Encoder
+ && !isVaapiHevcEncoder
+ && !isQsvH264Encoder
+ && !isQsvHevcEncoder
+ && !isNvdecDecoder
+ && !isCuvidH264Decoder)
+ {
+ if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase))
{
- filters.Add("yadif=1:-1:0");
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "bwdif={0}:-1:0",
+ doubleRateDeinterlace ? "1" : "0"));
}
else
{
- filters.Add("yadif=0:-1:0");
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "yadif={0}:-1:0",
+ doubleRateDeinterlace ? "1" : "0"));
}
}
- var inputWidth = videoStream == null ? null : videoStream.Width;
- var inputHeight = videoStream == null ? null : videoStream.Height;
- var threeDFormat = state.MediaSource.Video3DFormat;
+ // Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
+ if (!isScalingInAdvance)
+ {
+ filters.AddRange(
+ GetScalingFilters(
+ state,
+ options,
+ inputWidth,
+ inputHeight,
+ threeDFormat,
+ videoDecoder,
+ outputVideoCodec,
+ request.Width,
+ request.Height,
+ request.MaxWidth,
+ request.MaxHeight));
+ }
- var videoDecoder = this.GetHardwareAcceleratedVideoDecoder(state, options);
+ // Add Cuda tonemapping filter.
+ if (isNvdecDecoder && isCudaTonemappingSupported)
+ {
+ isNoTonemapFilterApplied = false;
+ var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
+ if (!string.IsNullOrEmpty(inputHdrParams))
+ {
+ filters.Add(inputHdrParams);
+ }
- filters.AddRange(GetScalingFilters(inputWidth, inputHeight, threeDFormat, videoDecoder, outputVideoCodec, request.Width, request.Height, request.MaxWidth, request.MaxHeight));
+ var parameters = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
+ ? "tonemap_cuda=format=yuv420p:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}"
+ : "tonemap_cuda=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}";
- var output = string.Empty;
+ if (options.TonemappingParam != 0)
+ {
+ parameters += ":param={3}";
+ }
- if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
+ if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
+ {
+ parameters += ":range={4}";
+ }
+
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ parameters,
+ options.TonemappingAlgorithm,
+ options.TonemappingPeak,
+ options.TonemappingDesat,
+ options.TonemappingParam,
+ options.TonemappingRange));
+
+ if (isLibX264Encoder
+ || isLibX265Encoder
+ || hasTextSubs
+ || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
+ {
+ if (isNvencEncoder)
+ {
+ isHwuploadCudaRequired = true;
+ }
+
+ filters.Add("hwdownload");
+ filters.Add("format=nv12");
+ }
+
+ var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
+ if (!string.IsNullOrEmpty(outputSdrParams))
+ {
+ filters.Add(outputSdrParams);
+ }
+ }
+
+ // Add VPP tonemapping filter for VAAPI.
+ // Full hardware based video post processing, faster than OpenCL but lacks fine tuning options.
+ if ((isTonemappingSupportedOnVaapi || isTonemappingSupportedOnQsv)
+ && isVppTonemappingSupported)
+ {
+ filters.Add("tonemap_vaapi=format=nv12:transfer=bt709:matrix=bt709:primaries=bt709");
+ }
+
+ // Another case is when using Nvenc decoder.
+ if (isNvdecDecoder && !isOpenclTonemappingSupported && !isCudaTonemappingSupported)
+ {
+ var codec = videoStream.Codec;
+ var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
+
+ // Assert 10-bit hardware decodable
+ if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
+ {
+ if (isCudaFormatConversionSupported)
+ {
+ if (isLibX264Encoder
+ || isLibX265Encoder
+ || hasTextSubs
+ || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
+ {
+ if (isNvencEncoder)
+ {
+ isHwuploadCudaRequired = true;
+ }
+
+ filters.Add("hwdownload");
+ filters.Add("format=nv12");
+ }
+ }
+ else
+ {
+ // Download data from GPU to CPU as p010 format.
+ filters.Add("hwdownload");
+ filters.Add("format=p010");
+
+ // Cuda lacks of a pixel format converter.
+ if (isNvencEncoder)
+ {
+ isHwuploadCudaRequired = true;
+ filters.Add("format=yuv420p");
+ }
+ }
+ }
+
+ // Assert 8-bit hardware decodable
+ else if (!isColorDepth10
+ && (isLibX264Encoder
+ || isLibX265Encoder
+ || hasTextSubs
+ || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder)))
+ {
+ if (isNvencEncoder)
+ {
+ isHwuploadCudaRequired = true;
+ }
+
+ filters.Add("hwdownload");
+ filters.Add("format=nv12");
+ }
+ }
+
+ // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642)
+ if (isVaapiH264Encoder
+ || isVaapiHevcEncoder
+ || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
+ {
+ if (hasTextSubs)
+ {
+ // Convert hw context from ocl to va.
+ // For tonemapping and text subs burn-in.
+ if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
+ {
+ filters.Add("scale_vaapi");
+ }
+
+ // Test passed on Intel and AMD gfx
+ filters.Add("hwmap=mode=read+write");
+ filters.Add("format=nv12");
+ }
+ }
+
+ if (hasTextSubs)
{
var subParam = GetTextSubtitleParam(state);
@@ -1748,49 +3103,116 @@ namespace MediaBrowser.Controller.MediaEncoding
// Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
// Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
- if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (isVaapiH264Encoder || isVaapiHevcEncoder)
{
filters.Add("hwmap");
}
- if (allowTimeStampCopy)
+
+ if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
+ {
+ filters.Add("hwmap,format=vaapi");
+ }
+
+ if (isNvdecDecoder && isNvencEncoder)
{
- output += " -copyts";
+ isHwuploadCudaRequired = true;
}
}
+ // Interop the VAAPI data to QSV for hybrid tonemapping
+ if (isTonemappingSupportedOnQsv && isVppTonemappingSupported && !hasGraphicalSubs)
+ {
+ filters.Add("hwmap=derive_device=qsv,scale_qsv");
+ }
+
+ if (isHwuploadCudaRequired && !hasGraphicalSubs)
+ {
+ filters.Add("hwupload_cuda");
+ }
+
+ // If no tonemap filter is applied,
+ // tag the video range as SDR to prevent the encoder from encoding HDR video.
+ if (isNoTonemapFilterApplied)
+ {
+ var outputSdrParams = GetOutputSdrParams(null);
+ if (!string.IsNullOrEmpty(outputSdrParams))
+ {
+ filters.Add(outputSdrParams);
+ }
+ }
+
+ var output = string.Empty;
if (filters.Count > 0)
{
- output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
+ output += string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}",
+ string.Join(',', filters));
}
return output;
}
+ public static string GetInputHdrParams(string colorTransfer)
+ {
+ if (string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
+ {
+ // HLG
+ return "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc";
+ }
+ else
+ {
+ // HDR10
+ return "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc";
+ }
+ }
+
+ public static string GetOutputSdrParams(string tonemappingRange)
+ {
+ // SDR
+ if (string.Equals(tonemappingRange, "tv", StringComparison.OrdinalIgnoreCase))
+ {
+ return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv";
+ }
+
+ if (string.Equals(tonemappingRange, "pc", StringComparison.OrdinalIgnoreCase))
+ {
+ return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=pc";
+ }
+
+ return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709";
+ }
/// <summary>
/// Gets the number of threads.
/// </summary>
- public int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec)
+ /// <param name="state">Encoding state.</param>
+ /// <param name="encodingOptions">Encoding options.</param>
+ /// <param name="outputVideoCodec">Video codec to use.</param>
+ /// <returns>Number of threads.</returns>
+#nullable enable
+ public static int GetNumberOfThreads(EncodingJobInfo? state, EncodingOptions encodingOptions, string? outputVideoCodec)
{
- if (string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
- {
- // per docs:
- // -threads number of threads to use for encoding, can't be 0 [auto] with VP8
- // (recommended value : number of real cores - 1)
- return Math.Max(Environment.ProcessorCount - 1, 1);
- }
+ // VP8 and VP9 encoders must have their thread counts set.
+ bool mustSetThreadCount = string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(outputVideoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase);
- var threads = state.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
+ var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
- // Automatic
- if (threads <= 0 || threads >= Environment.ProcessorCount)
+ if (threads <= 0)
{
- return 0;
+ // Automatically set thread count
+ return mustSetThreadCount ? Math.Max(Environment.ProcessorCount - 1, 1) : 0;
+ }
+ else if (threads >= Environment.ProcessorCount)
+ {
+ return Environment.ProcessorCount;
}
return threads;
}
+#nullable disable
public void TryStreamCopy(EncodingJobInfo state)
{
if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
@@ -1802,13 +3224,14 @@ namespace MediaBrowser.Controller.MediaEncoding
var user = state.User;
// If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
- if (user != null && !user.Policy.EnableVideoPlaybackTranscoding)
+ if (user != null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
{
state.OutputVideoCodec = "copy";
}
}
- if (state.AudioStream != null && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
+ if (state.AudioStream != null
+ && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
{
state.OutputAudioCodec = "copy";
}
@@ -1817,29 +3240,17 @@ namespace MediaBrowser.Controller.MediaEncoding
var user = state.User;
// If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
- if (user != null && !user.Policy.EnableAudioPlaybackTranscoding)
+ if (user != null && !user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
{
state.OutputAudioCodec = "copy";
}
}
}
- public static string GetProbeSizeArgument(int numInputFiles)
- {
- return numInputFiles > 1 ? "-probesize 1G" : "";
- }
-
- public static string GetAnalyzeDurationArgument(int numInputFiles)
- {
- return numInputFiles > 1 ? "-analyzeduration 200M" : "";
- }
-
public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
{
var inputModifier = string.Empty;
-
- var numInputFiles = state.PlayableStreamFileNames.Length > 0 ? state.PlayableStreamFileNames.Length : 1;
- var probeSizeArgument = GetProbeSizeArgument(numInputFiles);
+ var probeSizeArgument = string.Empty;
string analyzeDurationArgument;
if (state.MediaSource.AnalyzeDurationMs.HasValue)
@@ -1848,7 +3259,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else
{
- analyzeDurationArgument = GetAnalyzeDurationArgument(numInputFiles);
+ analyzeDurationArgument = string.Empty;
}
if (!string.IsNullOrEmpty(probeSizeArgument))
@@ -1900,18 +3311,22 @@ namespace MediaBrowser.Controller.MediaEncoding
{
flags.Add("+igndts");
}
+
if (state.IgnoreInputIndex)
{
flags.Add("+ignidx");
}
- if (state.GenPtsInput)
+
+ if (state.GenPtsInput || IsCopyCodec(state.OutputVideoCodec))
{
flags.Add("+genpts");
}
+
if (state.DiscardCorruptFramesInput)
{
flags.Add("+discardcorrupt");
}
+
if (state.EnableFastSeekInput)
{
flags.Add("+fastseek");
@@ -1919,24 +3334,48 @@ namespace MediaBrowser.Controller.MediaEncoding
if (flags.Count > 0)
{
- inputModifier += " -fflags " + string.Join("", flags.ToArray());
+ inputModifier += " -fflags " + string.Join(string.Empty, flags);
}
- var videoDecoder = this.GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
+ var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
+
if (!string.IsNullOrEmpty(videoDecoder))
{
inputModifier += " " + videoDecoder;
- var videoStream = state.VideoStream;
- var inputWidth = videoStream == null ? null : videoStream.Width;
- var inputHeight = videoStream == null ? null : videoStream.Height;
- var request = state.BaseRequest;
+ if (!IsCopyCodec(state.OutputVideoCodec)
+ && videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase))
+ {
+ var videoStream = state.VideoStream;
+ var inputWidth = videoStream?.Width;
+ var inputHeight = videoStream?.Height;
+ var request = state.BaseRequest;
- var fixedOutputSize = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
+ var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
- if ((videoDecoder ?? string.Empty).IndexOf("_cuvid", StringComparison.OrdinalIgnoreCase) != -1 && fixedOutputSize.Item1.HasValue && fixedOutputSize.Item2.HasValue)
- {
- inputModifier += string.Format(" -resize {0}x{1}", fixedOutputSize.Item1.Value.ToString(_usCulture), fixedOutputSize.Item2.Value.ToString(_usCulture));
+ if (videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase)
+ && width.HasValue
+ && height.HasValue)
+ {
+ if (width.HasValue && height.HasValue)
+ {
+ inputModifier += string.Format(
+ CultureInfo.InvariantCulture,
+ " -resize {0}x{1}",
+ width.Value,
+ height.Value);
+ }
+
+ if (state.DeInterlace("h264", true))
+ {
+ inputModifier += " -deint 1";
+
+ if (!encodingOptions.DeinterlaceDoubleRate || (videoStream?.AverageFrameRate ?? 60) > 30)
+ {
+ inputModifier += " -drop_second_field 1";
+ }
+ }
+ }
}
}
@@ -1945,9 +3384,10 @@ namespace MediaBrowser.Controller.MediaEncoding
var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
// Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
- if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase) &&
- state.TranscodingType != TranscodingJobType.Progressive &&
- state.EnableBreakOnNonKeyFrames(outputVideoCodec))
+ if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
+ && state.TranscodingType != TranscodingJobType.Progressive
+ && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
+ && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
{
inputModifier += " -noaccurate_seek";
}
@@ -1970,15 +3410,17 @@ namespace MediaBrowser.Controller.MediaEncoding
return inputModifier;
}
-
- public void AttachMediaSourceInfo(EncodingJobInfo state,
- MediaSourceInfo mediaSource,
- string requestedUrl)
+ public void AttachMediaSourceInfo(
+ EncodingJobInfo state,
+ EncodingOptions encodingOptions,
+ MediaSourceInfo mediaSource,
+ string requestedUrl)
{
if (state == null)
{
throw new ArgumentNullException(nameof(state));
}
+
if (mediaSource == null)
{
throw new ArgumentNullException(nameof(mediaSource));
@@ -2001,32 +3443,6 @@ namespace MediaBrowser.Controller.MediaEncoding
state.IsoType = mediaSource.IsoType;
- if (mediaSource.VideoType.HasValue)
- {
- state.VideoType = mediaSource.VideoType.Value;
-
- if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
- {
- state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, mediaSource.VideoType.Value).Select(Path.GetFileName).ToArray();
- }
- else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.BluRay)
- {
- state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.BluRay).Select(Path.GetFileName).ToArray();
- }
- else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.Dvd)
- {
- state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.Dvd).Select(Path.GetFileName).ToArray();
- }
- else
- {
- state.PlayableStreamFileNames = Array.Empty<string>();
- }
- }
- else
- {
- state.PlayableStreamFileNames = Array.Empty<string>();
- }
-
if (mediaSource.Timestamp.HasValue)
{
state.InputTimestamp = mediaSource.Timestamp.Value;
@@ -2036,15 +3452,16 @@ namespace MediaBrowser.Controller.MediaEncoding
state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
- if (state.ReadInputAtNativeFramerate ||
- mediaSource.Protocol == MediaProtocol.File && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
+ if (state.ReadInputAtNativeFramerate
+ || (mediaSource.Protocol == MediaProtocol.File
+ && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase)))
{
state.InputVideoSync = "-1";
state.InputAudioSync = "1";
}
- if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
{
// Seeing some stuttering when transcoding wma to audio-only HLS
state.InputAudioSync = "1";
@@ -2088,9 +3505,10 @@ namespace MediaBrowser.Controller.MediaEncoding
state.MediaSource = mediaSource;
var request = state.BaseRequest;
- if (!string.IsNullOrWhiteSpace(request.AudioCodec))
+ var supportedAudioCodecs = state.SupportedAudioCodecs;
+ if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0)
{
- var supportedAudioCodecsList = request.AudioCodec.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
+ var supportedAudioCodecsList = supportedAudioCodecs.ToList();
ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
@@ -2099,11 +3517,23 @@ namespace MediaBrowser.Controller.MediaEncoding
request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
?? state.SupportedAudioCodecs.FirstOrDefault();
}
+
+ var supportedVideoCodecs = state.SupportedVideoCodecs;
+ if (request != null && supportedVideoCodecs != null && supportedVideoCodecs.Length > 0)
+ {
+ var supportedVideoCodecsList = supportedVideoCodecs.ToList();
+
+ ShiftVideoCodecsIfNeeded(supportedVideoCodecsList, encodingOptions);
+
+ state.SupportedVideoCodecs = supportedVideoCodecsList.ToArray();
+
+ request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
+ }
}
private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
{
- // Nothing to do here
+ // No need to shift if there is only one supported audio codec.
if (audioCodecs.Count < 2)
{
return;
@@ -2131,6 +3561,34 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
+ private void ShiftVideoCodecsIfNeeded(List<string> videoCodecs, EncodingOptions encodingOptions)
+ {
+ // Shift hevc/h265 to the end of list if hevc encoding is not allowed.
+ if (encodingOptions.AllowHevcEncoding)
+ {
+ return;
+ }
+
+ // No need to shift if there is only one supported video codec.
+ if (videoCodecs.Count < 2)
+ {
+ return;
+ }
+
+ var shiftVideoCodecs = new[] { "hevc", "h265" };
+ if (videoCodecs.All(i => shiftVideoCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
+ {
+ return;
+ }
+
+ while (shiftVideoCodecs.Contains(videoCodecs[0], StringComparer.OrdinalIgnoreCase))
+ {
+ var removed = shiftVideoCodecs[0];
+ videoCodecs.RemoveAt(0);
+ videoCodecs.Add(removed);
+ }
+ }
+
private void NormalizeSubtitleEmbed(EncodingJobInfo state)
{
if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
@@ -2147,209 +3605,321 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Gets the name of the output video codec
+ /// Gets the ffmpeg option string for the hardware accelerated video decoder.
/// </summary>
+ /// <param name="state">The encoding job info.</param>
+ /// <param name="encodingOptions">The encoding options.</param>
+ /// <returns>The option string or null if none available.</returns>
protected string GetHardwareAcceleratedVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
{
- if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ var videoStream = state.VideoStream;
+
+ if (videoStream == null)
{
return null;
}
- return this.GetHardwareAcceleratedVideoDecoder(state.MediaSource.VideoType ?? VideoType.VideoFile, state.VideoStream, encodingOptions);
- }
-
- public string GetHardwareAcceleratedVideoDecoder(VideoType videoType, MediaStream videoStream, EncodingOptions encodingOptions)
- {
+ var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
// Only use alternative encoders for video files.
// When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
- // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
+ // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
if (videoType != VideoType.VideoFile)
{
return null;
}
- if (videoStream != null &&
- !string.IsNullOrEmpty(videoStream.Codec) &&
- !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
+ if (IsCopyCodec(state.OutputVideoCodec))
+ {
+ return null;
+ }
+
+ if (!string.IsNullOrEmpty(videoStream.Codec) && !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
{
+ var isColorDepth10 = IsColorDepth10(state);
+
+ // Only hevc and vp9 formats have 10-bit hardware decoder support now.
+ if (isColorDepth10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)))
+ {
+ return null;
+ }
+
+ // Hybrid VPP tonemapping with VAAPI
+ if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
+ && IsVppTonemappingSupported(state, encodingOptions))
+ {
+ var outputVideoCodec = GetVideoEncoder(state, encodingOptions) ?? string.Empty;
+ var isQsvEncoder = outputVideoCodec.Contains("qsv", StringComparison.OrdinalIgnoreCase);
+ if (isQsvEncoder)
+ {
+ // Since tonemap_vaapi only support HEVC for now, no need to check the codec again.
+ return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
+ }
+ }
+
if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
{
switch (videoStream.Codec.ToLowerInvariant())
{
case "avc":
case "h264":
- if (_mediaEncoder.SupportsDecoder("h264_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
- {
- // qsv decoder does not support 10-bit input
- if ((videoStream.BitDepth ?? 8) > 8)
- {
- encodingOptions.HardwareDecodingCodecs = Array.Empty<string>();
- return null;
- }
- return "-c:v h264_qsv ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "h264_qsv", "h264", isColorDepth10);
case "hevc":
case "h265":
- if (_mediaEncoder.SupportsDecoder("hevc_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
- {
- //return "-c:v hevc_qsv -load_plugin hevc_hw ";
- return "-c:v hevc_qsv ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "hevc_qsv", "hevc", isColorDepth10);
case "mpeg2video":
- if (_mediaEncoder.SupportsDecoder("mpeg2_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg2_qsv ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "mpeg2_qsv", "mpeg2video", isColorDepth10);
case "vc1":
- if (_mediaEncoder.SupportsDecoder("vc1_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v vc1_qsv ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "vc1_qsv", "vc1", isColorDepth10);
+ case "vp8":
+ return GetHwDecoderName(encodingOptions, "vp8_qsv", "vp8", isColorDepth10);
+ case "vp9":
+ return GetHwDecoderName(encodingOptions, "vp9_qsv", "vp9", isColorDepth10);
}
}
-
else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
{
switch (videoStream.Codec.ToLowerInvariant())
{
case "avc":
case "h264":
- if (_mediaEncoder.SupportsDecoder("h264_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v h264_cuvid ";
- }
- break;
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "h264", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "h264_cuvid", "h264", isColorDepth10);
case "hevc":
case "h265":
- if (_mediaEncoder.SupportsDecoder("hevc_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v hevc_cuvid ";
- }
- break;
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "hevc_cuvid", "hevc", isColorDepth10);
case "mpeg2video":
- if (_mediaEncoder.SupportsDecoder("mpeg2_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg2_cuvid ";
- }
- break;
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "mpeg2_cuvid", "mpeg2video", isColorDepth10);
case "vc1":
- if (_mediaEncoder.SupportsDecoder("vc1_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v vc1_cuvid ";
- }
- break;
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "vc1_cuvid", "vc1", isColorDepth10);
case "mpeg4":
- if (_mediaEncoder.SupportsDecoder("mpeg4_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg4_cuvid ";
- }
- break;
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "mpeg4_cuvid", "mpeg4", isColorDepth10);
+ case "vp8":
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "vp8_cuvid", "vp8", isColorDepth10);
+ case "vp9":
+ return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
+ ? GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10)
+ : GetHwDecoderName(encodingOptions, "vp9_cuvid", "vp9", isColorDepth10);
}
}
-
else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
{
switch (videoStream.Codec.ToLowerInvariant())
{
case "avc":
case "h264":
- if (_mediaEncoder.SupportsDecoder("h264_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v h264_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "h264_mediacodec", "h264", isColorDepth10);
case "hevc":
case "h265":
- if (_mediaEncoder.SupportsDecoder("hevc_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v hevc_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "hevc_mediacodec", "hevc", isColorDepth10);
case "mpeg2video":
- if (_mediaEncoder.SupportsDecoder("mpeg2_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg2_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "mpeg2_mediacodec", "mpeg2video", isColorDepth10);
case "mpeg4":
- if (_mediaEncoder.SupportsDecoder("mpeg4_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg4_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "mpeg4_mediacodec", "mpeg4", isColorDepth10);
case "vp8":
- if (_mediaEncoder.SupportsDecoder("vp8_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v vp8_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "vp8_mediacodec", "vp8", isColorDepth10);
case "vp9":
- if (_mediaEncoder.SupportsDecoder("vp9_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v vp9_mediacodec ";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "vp9_mediacodec", "vp9", isColorDepth10);
}
}
-
else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
{
switch (videoStream.Codec.ToLowerInvariant())
{
case "avc":
case "h264":
- if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v h264_mmal";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "h264_mmal", "h264", isColorDepth10);
case "mpeg2video":
- if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg2_mmal";
- }
- break;
+ return GetHwDecoderName(encodingOptions, "mpeg2_mmal", "mpeg2video", isColorDepth10);
+ case "mpeg4":
+ return GetHwDecoderName(encodingOptions, "mpeg4_mmal", "mpeg4", isColorDepth10);
+ case "vc1":
+ return GetHwDecoderName(encodingOptions, "vc1_mmal", "vc1", isColorDepth10);
}
}
-
else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
{
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+ switch (videoStream.Codec.ToLowerInvariant())
{
- return "-hwaccel dxva2";
+ case "avc":
+ case "h264":
+ return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
+ case "hevc":
+ case "h265":
+ return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
+ case "mpeg2video":
+ return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
+ case "vc1":
+ return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
+ case "mpeg4":
+ return GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10);
+ case "vp9":
+ return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
}
-
+ }
+ else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
+ {
switch (videoStream.Codec.ToLowerInvariant())
{
case "avc":
case "h264":
- if (_mediaEncoder.SupportsDecoder("h264_amf") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v h264_amf";
- }
- break;
+ return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
+ case "hevc":
+ case "h265":
+ return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
case "mpeg2video":
- if (_mediaEncoder.SupportsDecoder("hevc_amf") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
- {
- return "-c:v mpeg2_mmal";
- }
- break;
+ return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
+ case "vc1":
+ return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
+ case "vp8":
+ return GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10);
+ case "vp9":
+ return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
+ }
+ }
+ else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
+ {
+ switch (videoStream.Codec.ToLowerInvariant())
+ {
+ case "avc":
+ case "h264":
+ return GetHwDecoderName(encodingOptions, "h264_opencl", "h264", isColorDepth10);
+ case "hevc":
+ case "h265":
+ return GetHwDecoderName(encodingOptions, "hevc_opencl", "hevc", isColorDepth10);
+ case "mpeg2video":
+ return GetHwDecoderName(encodingOptions, "mpeg2_opencl", "mpeg2video", isColorDepth10);
+ case "mpeg4":
+ return GetHwDecoderName(encodingOptions, "mpeg4_opencl", "mpeg4", isColorDepth10);
+ case "vc1":
+ return GetHwDecoderName(encodingOptions, "vc1_opencl", "vc1", isColorDepth10);
+ case "vp8":
+ return GetHwDecoderName(encodingOptions, "vp8_opencl", "vp8", isColorDepth10);
+ case "vp9":
+ return GetHwDecoderName(encodingOptions, "vp9_opencl", "vp9", isColorDepth10);
}
}
}
+ var whichCodec = videoStream.Codec?.ToLowerInvariant();
+ switch (whichCodec)
+ {
+ case "avc":
+ whichCodec = "h264";
+ break;
+ case "h265":
+ whichCodec = "hevc";
+ break;
+ }
+
// Avoid a second attempt if no hardware acceleration is being used
- encodingOptions.HardwareDecodingCodecs = Array.Empty<string>();
+ encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
// leave blank so ffmpeg will decide
return null;
}
+ /// <summary>
+ /// Gets a hw decoder name.
+ /// </summary>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="decoder">Decoder to use.</param>
+ /// <param name="videoCodec">Video codec to use.</param>
+ /// <param name="isColorDepth10">Specifies if color depth 10.</param>
+ /// <returns>Hardware decoder name.</returns>
+ public string GetHwDecoderName(EncodingOptions options, string decoder, string videoCodec, bool isColorDepth10)
+ {
+ var isCodecAvailable = _mediaEncoder.SupportsDecoder(decoder) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
+ if (isColorDepth10 && isCodecAvailable)
+ {
+ if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
+ || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
+ {
+ return null;
+ }
+ }
+
+ return isCodecAvailable ? ("-c:v " + decoder) : null;
+ }
+
+ /// <summary>
+ /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system.
+ /// </summary>
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="videoCodec">Video codec to use.</param>
+ /// <param name="isColorDepth10">Specifies if color depth 10.</param>
+ /// <returns>Hardware accelerator type.</returns>
+ public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec, bool isColorDepth10)
+ {
+ var isWindows = OperatingSystem.IsWindows();
+ var isLinux = OperatingSystem.IsLinux();
+ var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
+ var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
+ var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
+
+ if (isColorDepth10 && isCodecAvailable)
+ {
+ if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
+ || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
+ {
+ return null;
+ }
+ }
+
+ if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
+ {
+ // Currently there is no AMF decoder on Linux, only have h264 encoder.
+ if (isDxvaSupported && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
+ {
+ if (isWindows && isWindows8orLater)
+ {
+ return "-hwaccel d3d11va";
+ }
+
+ if (isWindows && !isWindows8orLater)
+ {
+ return "-hwaccel dxva2";
+ }
+ }
+ }
+
+ if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
+ || (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
+ && IsVppTonemappingSupported(state, options)))
+ {
+ if (IsVaapiSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
+ {
+ if (isLinux)
+ {
+ return "-hwaccel vaapi";
+ }
+ }
+ }
+
+ if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
+ {
+ if (options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
+ {
+ return "-hwaccel cuda";
+ }
+ }
+
+ return null;
+ }
+
public string GetSubtitleEmbedArguments(EncodingJobInfo state)
{
if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
@@ -2369,14 +3939,10 @@ namespace MediaBrowser.Controller.MediaEncoding
codec = format;
}
- var args = " -codec:s:0 " + codec;
-
- args += " -disposition:s:0 default";
-
- return args;
+ return " -codec:s:0 " + codec + " -disposition:s:0 default";
}
- public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultH264Preset)
+ public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
{
// Get the output codec name
var videoCodec = GetVideoEncoder(state, encodingOptions);
@@ -2384,8 +3950,8 @@ namespace MediaBrowser.Controller.MediaEncoding
var format = string.Empty;
var keyFrame = string.Empty;
- if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase) &&
- state.BaseRequest.Context == EncodingContext.Streaming)
+ if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
+ && state.BaseRequest.Context == EncodingContext.Streaming)
{
// Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
format = " -f mp4 -movflags frag_keyframe+empty_moov";
@@ -2395,18 +3961,19 @@ namespace MediaBrowser.Controller.MediaEncoding
var inputModifier = GetInputModifier(state, encodingOptions);
- return string.Format("{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
inputModifier,
GetInputArgument(state, encodingOptions),
keyFrame,
GetMapArgs(state),
- GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultH264Preset),
+ GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
threads,
GetProgressiveVideoAudioArguments(state, encodingOptions),
GetSubtitleEmbedArguments(state),
format,
- outputPath
- ).Trim();
+ outputPath).Trim();
}
public string GetOutputFFlags(EncodingJobInfo state)
@@ -2419,13 +3986,13 @@ namespace MediaBrowser.Controller.MediaEncoding
if (flags.Count > 0)
{
- return " -fflags " + string.Join("", flags.ToArray());
+ return " -fflags " + string.Join(string.Empty, flags);
}
return string.Empty;
}
- public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultH264Preset)
+ public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
{
var args = "-codec:v:0 " + videoCodec;
@@ -2434,13 +4001,17 @@ namespace MediaBrowser.Controller.MediaEncoding
args += " -mpegts_m2ts_mode 1";
}
- if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (IsCopyCodec(videoCodec))
{
- if (state.VideoStream != null && IsH264(state.VideoStream) &&
- string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
+ if (state.VideoStream != null
+ && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
{
- args += " -bsf:v h264_mp4toannexb";
+ string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
+ if (!string.IsNullOrEmpty(bitStreamArgs))
+ {
+ args += " " + bitStreamArgs;
+ }
}
if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
@@ -2450,53 +4021,63 @@ namespace MediaBrowser.Controller.MediaEncoding
if (!state.RunTimeTicks.HasValue)
{
- args += " -flags -global_header -fflags +genpts";
+ args += " -fflags +genpts";
}
}
else
{
- var keyFrameArg = string.Format(" -force_key_frames \"expr:gte(t,n_forced*{0})\"",
- 5.ToString(_usCulture));
+ var keyFrameArg = string.Format(
+ CultureInfo.InvariantCulture,
+ " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
+ 5);
args += keyFrameArg;
var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
var hasCopyTs = false;
+
// Add resolution params, if specified
if (!hasGraphicalSubs)
{
var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
+
args += outputSizeParam;
+
hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
}
+ // This is for graphical subs
+ if (hasGraphicalSubs)
+ {
+ var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
+
+ args += graphicalSubtitleParam;
+
+ hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
+ }
+
if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
{
if (!hasCopyTs)
{
args += " -copyts";
}
- args += " -avoid_negative_ts disabled -start_at_zero";
- }
- // This is for internal graphical subs
- if (hasGraphicalSubs)
- {
- args += GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
+ args += " -avoid_negative_ts disabled";
+
+ if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
+ {
+ args += " -start_at_zero";
+ }
}
- var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultH264Preset);
+ var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
if (!string.IsNullOrEmpty(qualityParam))
{
args += " " + qualityParam.Trim();
}
-
- if (!state.RunTimeTicks.HasValue)
- {
- args += " -flags -global_header";
- }
}
if (!string.IsNullOrEmpty(state.OutputVideoSync))
@@ -2522,7 +4103,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var args = "-codec:a:0 " + codec;
- if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (IsCopyCodec(codec))
{
return args;
}
@@ -2539,15 +4120,15 @@ namespace MediaBrowser.Controller.MediaEncoding
if (bitrate.HasValue)
{
- args += " -ab " + bitrate.Value.ToString(_usCulture);
+ args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
}
if (state.OutputAudioSampleRate.HasValue)
{
- args += " -ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture);
+ args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
}
- args += " " + GetAudioFilterParam(state, encodingOptions, false);
+ args += GetAudioFilterParam(state, encodingOptions);
return args;
}
@@ -2560,12 +4141,12 @@ namespace MediaBrowser.Controller.MediaEncoding
if (bitrate.HasValue)
{
- audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(_usCulture));
+ audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture));
}
if (state.OutputAudioChannels.HasValue)
{
- audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(_usCulture));
+ audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture));
}
// opus will fail on 44100
@@ -2573,44 +4154,67 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (state.OutputAudioSampleRate.HasValue)
{
- audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture));
+ audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture));
}
}
- var albumCoverInput = string.Empty;
- var mapArgs = string.Empty;
- var metadata = string.Empty;
- var vn = string.Empty;
-
- var hasArt = !string.IsNullOrEmpty(state.AlbumCoverPath);
- hasArt = false;
-
- if (hasArt)
- {
- albumCoverInput = " -i \"" + state.AlbumCoverPath + "\"";
- mapArgs = " -map 0:a -map 1:v -c:1:v copy";
- metadata = " -metadata:s:v title=\"Album cover\" -metadata:s:v comment=\"Cover(Front)\"";
- }
- else
- {
- vn = " -vn";
- }
-
var threads = GetNumberOfThreads(state, encodingOptions, null);
var inputModifier = GetInputModifier(state, encodingOptions);
- return string.Format("{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
inputModifier,
GetInputArgument(state, encodingOptions),
threads,
- vn,
- string.Join(" ", audioTranscodeParams.ToArray()),
+ " -vn",
+ string.Join(' ', audioTranscodeParams),
outputPath,
- metadata,
- albumCoverInput,
- mapArgs).Trim();
+ string.Empty,
+ string.Empty,
+ string.Empty).Trim();
}
+ public static bool IsCopyCodec(string codec)
+ {
+ return string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsColorDepth10(EncodingJobInfo state)
+ {
+ var result = false;
+ var videoStream = state.VideoStream;
+
+ if (videoStream != null)
+ {
+ if (videoStream.BitDepth.HasValue)
+ {
+ return videoStream.BitDepth.Value == 10;
+ }
+
+ if (!string.IsNullOrEmpty(videoStream.PixelFormat))
+ {
+ result = videoStream.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase);
+ if (result)
+ {
+ return true;
+ }
+ }
+
+ if (!string.IsNullOrEmpty(videoStream.Profile))
+ {
+ result = videoStream.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
+ || videoStream.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
+ || videoStream.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase);
+ if (result)
+ {
+ return true;
+ }
+ }
+ }
+
+ return result;
+ }
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
index 916d691b8..e92c4a08a 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
@@ -1,60 +1,39 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1401
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Session;
using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
namespace MediaBrowser.Controller.MediaEncoding
{
// For now, a common base class until the API and MediaEncoding classes are unified
public class EncodingJobInfo
{
- public MediaStream VideoStream { get; set; }
- public VideoType VideoType { get; set; }
- public Dictionary<string, string> RemoteHttpHeaders { get; set; }
- public string OutputVideoCodec { get; set; }
- public MediaProtocol InputProtocol { get; set; }
- public string MediaPath { get; set; }
- public bool IsInputVideo { get; set; }
- public IIsoMount IsoMount { get; set; }
- public string[] PlayableStreamFileNames { get; set; }
- public string OutputAudioCodec { get; set; }
- public int? OutputVideoBitrate { get; set; }
- public MediaStream SubtitleStream { get; set; }
- public SubtitleDeliveryMethod SubtitleDeliveryMethod { get; set; }
- public string[] SupportedSubtitleCodecs { get; set; }
-
- public int InternalSubtitleStreamOffset { get; set; }
- public MediaSourceInfo MediaSource { get; set; }
- public User User { get; set; }
-
- public long? RunTimeTicks { get; set; }
-
- public bool ReadInputAtNativeFramerate { get; set; }
-
- public string OutputFilePath { get; set; }
+ public int? OutputAudioBitrate;
+ public int? OutputAudioChannels;
- public string MimeType { get; set; }
+ private TranscodeReason[] _transcodeReasons = null;
- public string GetMimeType(string outputPath, bool enableStreamDefault = true)
+ public EncodingJobInfo(TranscodingJobType jobType)
{
- if (!string.IsNullOrEmpty(MimeType))
- {
- return MimeType;
- }
-
- return MimeTypes.GetMimeType(outputPath, enableStreamDefault);
+ TranscodingType = jobType;
+ RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ SupportedAudioCodecs = Array.Empty<string>();
+ SupportedVideoCodecs = Array.Empty<string>();
+ SupportedSubtitleCodecs = Array.Empty<string>();
}
- private TranscodeReason[] _transcodeReasons = null;
public TranscodeReason[] TranscodeReasons
{
get
@@ -77,6 +56,46 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
+ public IProgress<double> Progress { get; set; }
+
+ public MediaStream VideoStream { get; set; }
+
+ public VideoType VideoType { get; set; }
+
+ public Dictionary<string, string> RemoteHttpHeaders { get; set; }
+
+ public string OutputVideoCodec { get; set; }
+
+ public MediaProtocol InputProtocol { get; set; }
+
+ public string MediaPath { get; set; }
+
+ public bool IsInputVideo { get; set; }
+
+ public string OutputAudioCodec { get; set; }
+
+ public int? OutputVideoBitrate { get; set; }
+
+ public MediaStream SubtitleStream { get; set; }
+
+ public SubtitleDeliveryMethod SubtitleDeliveryMethod { get; set; }
+
+ public string[] SupportedSubtitleCodecs { get; set; }
+
+ public int InternalSubtitleStreamOffset { get; set; }
+
+ public MediaSourceInfo MediaSource { get; set; }
+
+ public User User { get; set; }
+
+ public long? RunTimeTicks { get; set; }
+
+ public bool ReadInputAtNativeFramerate { get; set; }
+
+ public string OutputFilePath { get; set; }
+
+ public string MimeType { get; set; }
+
public bool IgnoreInputDts => MediaSource.IgnoreDts;
public bool IgnoreInputIndex => MediaSource.IgnoreIndex;
@@ -112,202 +131,34 @@ namespace MediaBrowser.Controller.MediaEncoding
public string AlbumCoverPath { get; set; }
public string InputAudioSync { get; set; }
+
public string InputVideoSync { get; set; }
+
public TransportStreamTimestamp InputTimestamp { get; set; }
public MediaStream AudioStream { get; set; }
+
public string[] SupportedAudioCodecs { get; set; }
+
public string[] SupportedVideoCodecs { get; set; }
+
public string InputContainer { get; set; }
+
public IsoType? IsoType { get; set; }
public BaseEncodingJobOptions BaseRequest { get; set; }
- public long? StartTimeTicks => BaseRequest.StartTimeTicks;
-
- public bool CopyTimestamps => BaseRequest.CopyTimestamps;
-
- public int? OutputAudioBitrate;
- public int? OutputAudioChannels;
-
- public bool DeInterlace(string videoCodec, bool forceDeinterlaceIfSourceIsInterlaced)
- {
- var videoStream = VideoStream;
- var isInputInterlaced = videoStream != null && videoStream.IsInterlaced;
-
- if (!isInputInterlaced)
- {
- return false;
- }
-
- // Support general param
- if (BaseRequest.DeInterlace)
- {
- return true;
- }
-
- if (!string.IsNullOrEmpty(videoCodec))
- {
- if (string.Equals(BaseRequest.GetOption(videoCodec, "deinterlace"), "true", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- return forceDeinterlaceIfSourceIsInterlaced && isInputInterlaced;
- }
-
- public string[] GetRequestedProfiles(string codec)
- {
- if (!string.IsNullOrEmpty(BaseRequest.Profile))
- {
- return BaseRequest.Profile.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- var profile = BaseRequest.GetOption(codec, "profile");
-
- if (!string.IsNullOrEmpty(profile))
- {
- return profile.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
- }
-
- return Array.Empty<string>();
- }
-
- public string GetRequestedLevel(string codec)
- {
- if (!string.IsNullOrEmpty(BaseRequest.Level))
- {
- return BaseRequest.Level;
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- return BaseRequest.GetOption(codec, "level");
- }
-
- return null;
- }
-
- public int? GetRequestedMaxRefFrames(string codec)
- {
- if (BaseRequest.MaxRefFrames.HasValue)
- {
- return BaseRequest.MaxRefFrames;
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- var value = BaseRequest.GetOption(codec, "maxrefframes");
- if (!string.IsNullOrEmpty(value)
- && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
- }
-
- return null;
- }
-
- public int? GetRequestedVideoBitDepth(string codec)
- {
- if (BaseRequest.MaxVideoBitDepth.HasValue)
- {
- return BaseRequest.MaxVideoBitDepth;
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- var value = BaseRequest.GetOption(codec, "videobitdepth");
- if (!string.IsNullOrEmpty(value)
- && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
- }
-
- return null;
- }
-
- public int? GetRequestedAudioBitDepth(string codec)
- {
- if (BaseRequest.MaxAudioBitDepth.HasValue)
- {
- return BaseRequest.MaxAudioBitDepth;
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- var value = BaseRequest.GetOption(codec, "audiobitdepth");
- if (!string.IsNullOrEmpty(value)
- && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
- }
-
- return null;
- }
-
- public int? GetRequestedAudioChannels(string codec)
- {
- if (BaseRequest.MaxAudioChannels.HasValue)
- {
- return BaseRequest.MaxAudioChannels;
- }
-
- if (BaseRequest.AudioChannels.HasValue)
- {
- return BaseRequest.AudioChannels;
- }
-
- if (!string.IsNullOrEmpty(codec))
- {
- var value = BaseRequest.GetOption(codec, "audiochannels");
- if (!string.IsNullOrEmpty(value)
- && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
- }
-
- return null;
- }
-
public bool IsVideoRequest { get; set; }
+
public TranscodingJobType TranscodingType { get; set; }
- public EncodingJobInfo(TranscodingJobType jobType)
- {
- TranscodingType = jobType;
- RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- PlayableStreamFileNames = Array.Empty<string>();
- SupportedAudioCodecs = Array.Empty<string>();
- SupportedVideoCodecs = Array.Empty<string>();
- SupportedSubtitleCodecs = Array.Empty<string>();
- }
+ public long? StartTimeTicks => BaseRequest.StartTimeTicks;
+
+ public bool CopyTimestamps => BaseRequest.CopyTimestamps;
public bool IsSegmentedLiveStream
=> TranscodingType != TranscodingJobType.Progressive && !RunTimeTicks.HasValue;
- public bool EnableBreakOnNonKeyFrames(string videoCodec)
- {
- if (TranscodingType != TranscodingJobType.Progressive)
- {
- if (IsSegmentedLiveStream)
- {
- return false;
- }
-
- return BaseRequest.BreakOnNonKeyFrames && string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase);
- }
-
- return false;
- }
-
public int? TotalOutputBitrate => (OutputAudioBitrate ?? 0) + (OutputVideoBitrate ?? 0);
public int? OutputWidth
@@ -316,13 +167,10 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
{
- var size = new ImageDimensions
- {
- Width = VideoStream.Width.Value,
- Height = VideoStream.Height.Value
- };
+ var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value);
- var newSize = DrawingUtils.Resize(size,
+ var newSize = DrawingUtils.Resize(
+ size,
BaseRequest.Width ?? 0,
BaseRequest.Height ?? 0,
BaseRequest.MaxWidth ?? 0,
@@ -346,13 +194,10 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
{
- var size = new ImageDimensions
- {
- Width = VideoStream.Width.Value,
- Height = VideoStream.Height.Value
- };
+ var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value);
- var newSize = DrawingUtils.Resize(size,
+ var newSize = DrawingUtils.Resize(
+ size,
BaseRequest.Width ?? 0,
BaseRequest.Height ?? 0,
BaseRequest.MaxWidth ?? 0,
@@ -374,19 +219,19 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputAudioCodec))
{
if (AudioStream != null)
{
return AudioStream.SampleRate;
}
}
-
else if (BaseRequest.AudioSampleRate.HasValue)
{
// Don't exceed what the encoder supports
// Seeing issues of attempting to encode to 88200
- return Math.Min(44100, BaseRequest.AudioSampleRate.Value);
+ return BaseRequest.AudioSampleRate.Value;
}
return null;
@@ -397,7 +242,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputAudioCodec))
{
if (AudioStream != null)
{
@@ -405,25 +251,18 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
- //else if (BaseRequest.AudioSampleRate.HasValue)
- //{
- // // Don't exceed what the encoder supports
- // // Seeing issues of attempting to encode to 88200
- // return Math.Min(44100, BaseRequest.AudioSampleRate.Value);
- //}
-
return null;
}
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the target video level.
/// </summary>
public double? TargetVideoLevel
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.Level;
}
@@ -440,13 +279,14 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the target video bit depth.
/// </summary>
public int? TargetVideoBitDepth
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.BitDepth;
}
@@ -463,7 +303,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.RefFrames;
}
@@ -473,13 +314,14 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the target framerate.
/// </summary>
public float? TargetFramerate
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream == null ? null : (VideoStream.AverageFrameRate ?? VideoStream.RealFrameRate);
}
@@ -504,13 +346,13 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the target packet length.
/// </summary>
public int? TargetPacketLength
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.PacketLength;
}
@@ -520,13 +362,13 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the target video profile.
/// </summary>
public string TargetVideoProfile
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.Profile;
}
@@ -545,7 +387,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.CodecTag;
}
@@ -558,7 +401,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.IsAnamorphic;
}
@@ -571,14 +415,17 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- var codec = OutputVideoCodec;
+ if (VideoStream == null)
+ {
+ return null;
+ }
- if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
- return VideoStream?.Codec;
+ return VideoStream.Codec;
}
- return codec;
+ return OutputVideoCodec;
}
}
@@ -586,14 +433,17 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- var codec = OutputAudioCodec;
+ if (AudioStream == null)
+ {
+ return null;
+ }
- if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (EncodingHelper.IsCopyCodec(OutputAudioCodec))
{
- return AudioStream?.Codec;
+ return AudioStream.Codec;
}
- return codec;
+ return OutputAudioCodec;
}
}
@@ -601,7 +451,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static
+ || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.IsInterlaced;
}
@@ -619,7 +470,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
get
{
- if (BaseRequest.Static || string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (BaseRequest.Static || EncodingHelper.IsCopyCodec(OutputVideoCodec))
{
return VideoStream?.IsAVC;
}
@@ -636,6 +487,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
}
+
return GetMediaStreamCount(MediaStreamType.Video, 1);
}
}
@@ -648,16 +500,26 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
}
+
return GetMediaStreamCount(MediaStreamType.Audio, 1);
}
}
- public int HlsListSize
+ public int HlsListSize => 0;
+
+ public bool EnableBreakOnNonKeyFrames(string videoCodec)
{
- get
+ if (TranscodingType != TranscodingJobType.Progressive)
{
- return 0;
+ if (IsSegmentedLiveStream)
+ {
+ return false;
+ }
+
+ return BaseRequest.BreakOnNonKeyFrames && EncodingHelper.IsCopyCodec(videoCodec);
}
+
+ return false;
}
private int? GetMediaStreamCount(MediaStreamType type, int limit)
@@ -672,33 +534,176 @@ namespace MediaBrowser.Controller.MediaEncoding
return count;
}
- public IProgress<double> Progress { get; set; }
- public virtual void ReportTranscodingProgress(TimeSpan? transcodingPosition, float framerate, double? percentComplete, long bytesTranscoded, int? bitRate)
+ public string GetMimeType(string outputPath, bool enableStreamDefault = true)
{
- Progress.Report(percentComplete.Value);
+ if (!string.IsNullOrEmpty(MimeType))
+ {
+ return MimeType;
+ }
+
+ if (enableStreamDefault)
+ {
+ return MimeTypes.GetMimeType(outputPath);
+ }
+
+ return MimeTypes.GetMimeType(outputPath, null);
}
- public virtual void Dispose()
+ public bool DeInterlace(string videoCodec, bool forceDeinterlaceIfSourceIsInterlaced)
{
+ var videoStream = VideoStream;
+ var isInputInterlaced = videoStream != null && videoStream.IsInterlaced;
+
+ if (!isInputInterlaced)
+ {
+ return false;
+ }
+
+ // Support general param
+ if (BaseRequest.DeInterlace)
+ {
+ return true;
+ }
+
+ if (!string.IsNullOrEmpty(videoCodec))
+ {
+ if (string.Equals(BaseRequest.GetOption(videoCodec, "deinterlace"), "true", StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ }
+
+ return forceDeinterlaceIfSourceIsInterlaced;
}
- }
- /// <summary>
- /// Enum TranscodingJobType
- /// </summary>
- public enum TranscodingJobType
- {
- /// <summary>
- /// The progressive
- /// </summary>
- Progressive,
- /// <summary>
- /// The HLS
- /// </summary>
- Hls,
- /// <summary>
- /// The dash
- /// </summary>
- Dash
+ public string[] GetRequestedProfiles(string codec)
+ {
+ if (!string.IsNullOrEmpty(BaseRequest.Profile))
+ {
+ return BaseRequest.Profile.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var profile = BaseRequest.GetOption(codec, "profile");
+
+ if (!string.IsNullOrEmpty(profile))
+ {
+ return profile.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
+ }
+ }
+
+ return Array.Empty<string>();
+ }
+
+ public string GetRequestedLevel(string codec)
+ {
+ if (!string.IsNullOrEmpty(BaseRequest.Level))
+ {
+ return BaseRequest.Level;
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ return BaseRequest.GetOption(codec, "level");
+ }
+
+ return null;
+ }
+
+ public int? GetRequestedMaxRefFrames(string codec)
+ {
+ if (BaseRequest.MaxRefFrames.HasValue)
+ {
+ return BaseRequest.MaxRefFrames;
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var value = BaseRequest.GetOption(codec, "maxrefframes");
+ if (!string.IsNullOrEmpty(value)
+ && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ public int? GetRequestedVideoBitDepth(string codec)
+ {
+ if (BaseRequest.MaxVideoBitDepth.HasValue)
+ {
+ return BaseRequest.MaxVideoBitDepth;
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var value = BaseRequest.GetOption(codec, "videobitdepth");
+ if (!string.IsNullOrEmpty(value)
+ && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ public int? GetRequestedAudioBitDepth(string codec)
+ {
+ if (BaseRequest.MaxAudioBitDepth.HasValue)
+ {
+ return BaseRequest.MaxAudioBitDepth;
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var value = BaseRequest.GetOption(codec, "audiobitdepth");
+ if (!string.IsNullOrEmpty(value)
+ && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ public int? GetRequestedAudioChannels(string codec)
+ {
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var value = BaseRequest.GetOption(codec, "audiochannels");
+ if (!string.IsNullOrEmpty(value)
+ && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+ }
+
+ if (BaseRequest.MaxAudioChannels.HasValue)
+ {
+ return BaseRequest.MaxAudioChannels;
+ }
+
+ if (BaseRequest.AudioChannels.HasValue)
+ {
+ return BaseRequest.AudioChannels;
+ }
+
+ if (BaseRequest.TranscodingMaxAudioChannels.HasValue)
+ {
+ return BaseRequest.TranscodingMaxAudioChannels;
+ }
+
+ return null;
+ }
+
+ public virtual void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
+ {
+ Progress.Report(percentComplete.Value);
+ }
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs
deleted file mode 100644
index be97c75a2..000000000
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs
+++ /dev/null
@@ -1,271 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.MediaEncoding
-{
- public class EncodingJobOptions : BaseEncodingJobOptions
- {
- public string OutputDirectory { get; set; }
- public string ItemId { get; set; }
-
- public string TempDirectory { get; set; }
- public bool ReadInputAtNativeFramerate { get; set; }
-
- /// <summary>
- /// Gets a value indicating whether this instance has fixed resolution.
- /// </summary>
- /// <value><c>true</c> if this instance has fixed resolution; otherwise, <c>false</c>.</value>
- public bool HasFixedResolution => Width.HasValue || Height.HasValue;
-
- public DeviceProfile DeviceProfile { get; set; }
-
- public EncodingJobOptions(StreamInfo info, DeviceProfile deviceProfile)
- {
- Container = info.Container;
- StartTimeTicks = info.StartPositionTicks;
- MaxWidth = info.MaxWidth;
- MaxHeight = info.MaxHeight;
- MaxFramerate = info.MaxFramerate;
- Id = info.ItemId;
- MediaSourceId = info.MediaSourceId;
- AudioCodec = info.TargetAudioCodec.FirstOrDefault();
- MaxAudioChannels = info.GlobalMaxAudioChannels;
- AudioBitRate = info.AudioBitrate;
- AudioSampleRate = info.TargetAudioSampleRate;
- DeviceProfile = deviceProfile;
- VideoCodec = info.TargetVideoCodec.FirstOrDefault();
- VideoBitRate = info.VideoBitrate;
- AudioStreamIndex = info.AudioStreamIndex;
- SubtitleMethod = info.SubtitleDeliveryMethod;
- Context = info.Context;
- TranscodingMaxAudioChannels = info.TranscodingMaxAudioChannels;
-
- if (info.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External)
- {
- SubtitleStreamIndex = info.SubtitleStreamIndex;
- }
- StreamOptions = info.StreamOptions;
- }
- }
-
- // For now until api and media encoding layers are unified
- public class BaseEncodingJobOptions
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public Guid Id { get; set; }
-
- [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
- public string MediaSourceId { get; set; }
-
- [ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string DeviceId { get; set; }
-
- [ApiMember(Name = "Container", Description = "Container", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Container { get; set; }
-
- /// <summary>
- /// Gets or sets the audio codec.
- /// </summary>
- /// <value>The audio codec.</value>
- [ApiMember(Name = "AudioCodec", Description = "Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string AudioCodec { get; set; }
-
- [ApiMember(Name = "EnableAutoStreamCopy", Description = "Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool EnableAutoStreamCopy { get; set; }
-
- public bool AllowVideoStreamCopy { get; set; }
- public bool AllowAudioStreamCopy { get; set; }
- public bool BreakOnNonKeyFrames { get; set; }
-
- /// <summary>
- /// Gets or sets the audio sample rate.
- /// </summary>
- /// <value>The audio sample rate.</value>
- [ApiMember(Name = "AudioSampleRate", Description = "Optional. Specify a specific audio sample rate, e.g. 44100", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? AudioSampleRate { get; set; }
-
- public int? MaxAudioBitDepth { get; set; }
-
- /// <summary>
- /// Gets or sets the audio bit rate.
- /// </summary>
- /// <value>The audio bit rate.</value>
- [ApiMember(Name = "AudioBitRate", Description = "Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? AudioBitRate { get; set; }
-
- /// <summary>
- /// Gets or sets the audio channels.
- /// </summary>
- /// <value>The audio channels.</value>
- [ApiMember(Name = "AudioChannels", Description = "Optional. Specify a specific number of audio channels to encode to, e.g. 2", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? AudioChannels { get; set; }
-
- [ApiMember(Name = "MaxAudioChannels", Description = "Optional. Specify a maximum number of audio channels to encode to, e.g. 2", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxAudioChannels { get; set; }
-
- [ApiMember(Name = "Static", Description = "Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool Static { get; set; }
-
- /// <summary>
- /// Gets or sets the profile.
- /// </summary>
- /// <value>The profile.</value>
- [ApiMember(Name = "Profile", Description = "Optional. Specify a specific h264 profile, e.g. main, baseline, high.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Profile { get; set; }
-
- /// <summary>
- /// Gets or sets the level.
- /// </summary>
- /// <value>The level.</value>
- [ApiMember(Name = "Level", Description = "Optional. Specify a level for the h264 profile, e.g. 3, 3.1.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string Level { get; set; }
-
- /// <summary>
- /// Gets or sets the framerate.
- /// </summary>
- /// <value>The framerate.</value>
- [ApiMember(Name = "Framerate", Description = "Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.", IsRequired = false, DataType = "double", ParameterType = "query", Verb = "GET")]
- public float? Framerate { get; set; }
-
- [ApiMember(Name = "MaxFramerate", Description = "Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.", IsRequired = false, DataType = "double", ParameterType = "query", Verb = "GET")]
- public float? MaxFramerate { get; set; }
-
- [ApiMember(Name = "CopyTimestamps", Description = "Whether or not to copy timestamps when transcoding with an offset. Defaults to false.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
- public bool CopyTimestamps { get; set; }
-
- /// <summary>
- /// Gets or sets the start time ticks.
- /// </summary>
- /// <value>The start time ticks.</value>
- [ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public long? StartTimeTicks { get; set; }
-
- /// <summary>
- /// Gets or sets the width.
- /// </summary>
- /// <value>The width.</value>
- [ApiMember(Name = "Width", Description = "Optional. The fixed horizontal resolution of the encoded video.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Width { get; set; }
-
- /// <summary>
- /// Gets or sets the height.
- /// </summary>
- /// <value>The height.</value>
- [ApiMember(Name = "Height", Description = "Optional. The fixed vertical resolution of the encoded video.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Height { get; set; }
-
- /// <summary>
- /// Gets or sets the width of the max.
- /// </summary>
- /// <value>The width of the max.</value>
- [ApiMember(Name = "MaxWidth", Description = "Optional. The maximum horizontal resolution of the encoded video.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxWidth { get; set; }
-
- /// <summary>
- /// Gets or sets the height of the max.
- /// </summary>
- /// <value>The height of the max.</value>
- [ApiMember(Name = "MaxHeight", Description = "Optional. The maximum vertical resolution of the encoded video.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxHeight { get; set; }
-
- /// <summary>
- /// Gets or sets the video bit rate.
- /// </summary>
- /// <value>The video bit rate.</value>
- [ApiMember(Name = "VideoBitRate", Description = "Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? VideoBitRate { get; set; }
-
- /// <summary>
- /// Gets or sets the index of the subtitle stream.
- /// </summary>
- /// <value>The index of the subtitle stream.</value>
- [ApiMember(Name = "SubtitleStreamIndex", Description = "Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? SubtitleStreamIndex { get; set; }
-
- [ApiMember(Name = "SubtitleMethod", Description = "Optional. Specify the subtitle delivery method.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public SubtitleDeliveryMethod SubtitleMethod { get; set; }
-
- [ApiMember(Name = "MaxRefFrames", Description = "Optional.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxRefFrames { get; set; }
-
- [ApiMember(Name = "MaxVideoBitDepth", Description = "Optional.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? MaxVideoBitDepth { get; set; }
- public bool RequireAvc { get; set; }
- public bool DeInterlace { get; set; }
- public bool RequireNonAnamorphic { get; set; }
- public int? TranscodingMaxAudioChannels { get; set; }
- public int? CpuCoreLimit { get; set; }
-
- public string LiveStreamId { get; set; }
-
- public bool EnableMpegtsM2TsMode { get; set; }
-
- /// <summary>
- /// Gets or sets the video codec.
- /// </summary>
- /// <value>The video codec.</value>
- [ApiMember(Name = "VideoCodec", Description = "Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h264, mpeg4, theora, vpx, wmv.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string VideoCodec { get; set; }
-
- public string SubtitleCodec { get; set; }
-
- public string TranscodeReasons { get; set; }
-
- /// <summary>
- /// Gets or sets the index of the audio stream.
- /// </summary>
- /// <value>The index of the audio stream.</value>
- [ApiMember(Name = "AudioStreamIndex", Description = "Optional. The index of the audio stream to use. If omitted the first audio stream will be used.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? AudioStreamIndex { get; set; }
-
- /// <summary>
- /// Gets or sets the index of the video stream.
- /// </summary>
- /// <value>The index of the video stream.</value>
- [ApiMember(Name = "VideoStreamIndex", Description = "Optional. The index of the video stream to use. If omitted the first video stream will be used.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? VideoStreamIndex { get; set; }
-
- public EncodingContext Context { get; set; }
-
- public Dictionary<string, string> StreamOptions { get; set; }
-
- public string GetOption(string qualifier, string name)
- {
- var value = GetOption(qualifier + "-" + name);
-
- if (string.IsNullOrEmpty(value))
- {
- value = GetOption(name);
- }
-
- return value;
- }
-
- public string GetOption(string name)
- {
- if (StreamOptions.TryGetValue(name, out var value))
- {
- return value;
- }
-
- return null;
- }
-
- public BaseEncodingJobOptions()
- {
- EnableAutoStreamCopy = true;
- AllowVideoStreamCopy = true;
- AllowAudioStreamCopy = true;
- Context = EncodingContext.Streaming;
- StreamOptions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
- }
-}
diff --git a/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs b/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs
new file mode 100644
index 000000000..7ce707b19
--- /dev/null
+++ b/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs
@@ -0,0 +1,23 @@
+namespace MediaBrowser.Controller.MediaEncoding
+{
+ /// <summary>
+ /// Enum FilterOptionType.
+ /// </summary>
+ public enum FilterOptionType
+ {
+ /// <summary>
+ /// The scale_cuda_format.
+ /// </summary>
+ ScaleCudaFormat = 0,
+
+ /// <summary>
+ /// The tonemap_cuda_name.
+ /// </summary>
+ TonemapCudaName = 1,
+
+ /// <summary>
+ /// The tonemap_opencl_bt2390.
+ /// </summary>
+ TonemapOpenclBt2390 = 2
+ }
+}
diff --git a/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs
new file mode 100644
index 000000000..c38e7ec3b
--- /dev/null
+++ b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs
@@ -0,0 +1,21 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+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);
+ }
+}
diff --git a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs
index e560999e8..8ce40a58d 100644
--- a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -12,6 +16,13 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <summary>
/// Refreshes the chapter images.
/// </summary>
- Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken);
+ /// <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 057e43910..e6511ca8d 100644
--- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
@@ -1,21 +1,23 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Controller.MediaEncoding
{
/// <summary>
- /// Interface IMediaEncoder
+ /// Interface IMediaEncoder.
/// </summary>
public interface IMediaEncoder : ITranscoderSupport
{
- string EncoderLocationType { get; }
-
/// <summary>
/// Gets the encoder path.
/// </summary>
@@ -23,13 +25,47 @@ namespace MediaBrowser.Controller.MediaEncoding
string EncoderPath { get; }
/// <summary>
- /// Supportses the decoder.
+ /// Whether given encoder codec is supported.
+ /// </summary>
+ /// <param name="encoder">The encoder.</param>
+ /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
+ bool SupportsEncoder(string encoder);
+
+ /// <summary>
+ /// Whether given decoder codec is supported.
/// </summary>
/// <param name="decoder">The decoder.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
bool SupportsDecoder(string decoder);
/// <summary>
+ /// Whether given hardware acceleration type is supported.
+ /// </summary>
+ /// <param name="hwaccel">The hwaccel.</param>
+ /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
+ bool SupportsHwaccel(string hwaccel);
+
+ /// <summary>
+ /// Whether given filter is supported.
+ /// </summary>
+ /// <param name="filter">The filter.</param>
+ /// <returns><c>true</c> if the filter is supported, <c>false</c> otherwise.</returns>
+ bool SupportsFilter(string filter);
+
+ /// <summary>
+ /// Whether filter is supported with the given option.
+ /// </summary>
+ /// <param name="option">The option.</param>
+ /// <returns><c>true</c> if the filter is supported, <c>false</c> otherwise.</returns>
+ bool SupportsFilterWithOption(FilterOptionType option);
+
+ /// <summary>
+ /// Get the version of media encoder.
+ /// </summary>
+ /// <returns>The version of media encoder.</returns>
+ Version GetMediaEncoderVersion();
+
+ /// <summary>
/// Extracts the audio image.
/// </summary>
/// <param name="path">The path.</param>
@@ -41,17 +77,48 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <summary>
/// Extracts the video image.
/// </summary>
- Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken);
+ /// <param name="inputFile">Input file.</param>
+ /// <param name="container">Video container type.</param>
+ /// <param name="mediaSource">Media source information.</param>
+ /// <param name="videoStream">Media stream information.</param>
+ /// <param name="threedFormat">Video 3D format.</param>
+ /// <param name="offset">Time offset.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>Location of video image.</returns>
+ Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken);
- Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken);
+ /// <summary>
+ /// Extracts the video image.
+ /// </summary>
+ /// <param name="inputFile">Input file.</param>
+ /// <param name="container">Video container type.</param>
+ /// <param name="mediaSource">Media source information.</param>
+ /// <param name="imageStream">Media stream information.</param>
+ /// <param name="imageStreamIndex">Index of the stream to extract from.</param>
+ /// <param name="outputExtension">The extension of the file to write, including the '.'.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>Location of video image.</returns>
+ Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken);
/// <summary>
/// Extracts the video images on interval.
/// </summary>
- Task ExtractVideoImagesOnInterval(string[] inputFiles,
+ /// <param name="inputFile">Input file.</param>
+ /// <param name="container">Video container type.</param>
+ /// <param name="videoStream">Media stream information.</param>
+ /// <param name="mediaSource">Media source information.</param>
+ /// <param name="threedFormat">Video 3D format.</param>
+ /// <param name="interval">Time interval.</param>
+ /// <param name="targetDirectory">Directory to write images.</param>
+ /// <param name="filenamePrefix">Filename prefix to use.</param>
+ /// <param name="maxWidth">Maximum width of image.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns>A task.</returns>
+ Task ExtractVideoImagesOnInterval(
+ string inputFile,
string container,
MediaStream videoStream,
- MediaProtocol protocol,
+ MediaSourceInfo mediaSource,
Video3DFormat? threedFormat,
TimeSpan interval,
string targetDirectory,
@@ -70,10 +137,10 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <summary>
/// Gets the input argument.
/// </summary>
- /// <param name="inputFiles">The input files.</param>
- /// <param name="protocol">The protocol.</param>
+ /// <param name="inputFile">The input file.</param>
+ /// <param name="mediaSource">The mediaSource.</param>
/// <returns>System.String.</returns>
- string GetInputArgument(string[] inputFiles, MediaProtocol protocol);
+ string GetInputArgument(string inputFile, MediaSourceInfo mediaSource);
/// <summary>
/// Gets the time parameter.
@@ -91,12 +158,24 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <returns>System.String.</returns>
string EscapeSubtitleFilterPath(string path);
- void Init();
+ /// <summary>
+ /// Sets the path to find FFmpeg.
+ /// </summary>
+ void SetFFmpegPath();
+ /// <summary>
+ /// Updates the encoder path.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="pathType">The type of path.</param>
void UpdateEncoderPath(string path, string pathType);
- bool SupportsEncoder(string encoder);
- string[] GetPlayableStreamFileNames(string path, VideoType videoType);
- IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber);
+ /// <summary>
+ /// Gets the primary playlist of .vob files.
+ /// </summary>
+ /// <param name="path">The to the .vob files.</param>
+ /// <param name="titleNumber">The title number to start with.</param>
+ /// <returns>A playlist.</returns>
+ IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber);
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs b/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs
index 174e74f34..4483cf708 100644
--- a/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs
+++ b/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -11,8 +15,17 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <summary>
/// Gets the subtitles.
/// </summary>
+ /// <param name="item">Item to use.</param>
+ /// <param name="mediaSourceId">Media source.</param>
+ /// <param name="subtitleStreamIndex">Subtitle stream to use.</param>
+ /// <param name="outputFormat">Output format to use.</param>
+ /// <param name="startTimeTicks">Start time.</param>
+ /// <param name="endTimeTicks">End time.</param>
+ /// <param name="preserveOriginalTimestamps">Option to preserve original timestamps.</param>
+ /// <param name="cancellationToken">The cancellation token for the operation.</param>
/// <returns>Task{Stream}.</returns>
- Task<Stream> GetSubtitles(BaseItem item,
+ Task<Stream> GetSubtitles(
+ BaseItem item,
string mediaSourceId,
int subtitleStreamIndex,
string outputFormat,
@@ -25,6 +38,7 @@ namespace MediaBrowser.Controller.MediaEncoding
/// Gets the subtitle language encoding parameter.
/// </summary>
/// <param name="path">The path.</param>
+ /// <param name="language">The language.</param>
/// <param name="protocol">The protocol.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>System.String.</returns>
diff --git a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs
index 361dd79dc..044ba6d33 100644
--- a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs
+++ b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.MediaEncoding
{
public class ImageEncodingOptions
diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
index b812a8ddc..933f440ac 100644
--- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
+++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
@@ -1,16 +1,18 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Globalization;
using System.IO;
-using System.Linq;
using System.Text;
-using MediaBrowser.Model.Extensions;
+using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.MediaEncoding
{
public class JobLogger
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly ILogger _logger;
public JobLogger(ILogger logger)
@@ -18,13 +20,14 @@ namespace MediaBrowser.Controller.MediaEncoding
_logger = logger;
}
- public async void StartStreamingLog(EncodingJobInfo state, Stream source, Stream target)
+ public async Task StartStreamingLog(EncodingJobInfo state, Stream source, Stream target)
{
try
{
+ using (target)
using (var reader = new StreamReader(source))
{
- while (!reader.EndOfStream)
+ while (!reader.EndOfStream && reader.BaseStream.CanRead)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
@@ -32,16 +35,24 @@ namespace MediaBrowser.Controller.MediaEncoding
var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
+ // If ffmpeg process is closed, the state is disposed, so don't write to target in that case
+ if (!target.CanWrite)
+ {
+ break;
+ }
+
await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
+
+ // Check again, the stream could have been closed
+ if (!target.CanWrite)
+ {
+ break;
+ }
+
await target.FlushAsync().ConfigureAwait(false);
}
}
}
- catch (ObjectDisposedException)
- {
- //TODO Investigate and properly fix.
- // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
- }
catch (Exception ex)
{
_logger.LogError(ex, "Error reading ffmpeg log");
@@ -75,7 +86,16 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var rate = parts[i + 1];
- if (float.TryParse(rate, NumberStyles.Any, _usCulture, out var val))
+ if (float.TryParse(rate, NumberStyles.Any, CultureInfo.InvariantCulture, out var val))
+ {
+ framerate = val;
+ }
+ }
+ else if (part.StartsWith("fps=", StringComparison.OrdinalIgnoreCase))
+ {
+ var rate = part.Split('=', 2)[^1];
+
+ if (float.TryParse(rate, NumberStyles.Any, CultureInfo.InvariantCulture, out var val))
{
framerate = val;
}
@@ -83,24 +103,23 @@ namespace MediaBrowser.Controller.MediaEncoding
else if (state.RunTimeTicks.HasValue &&
part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
{
- var time = part.Split(new[] { '=' }, 2).Last();
+ var time = part.Split('=', 2)[^1];
- if (TimeSpan.TryParse(time, _usCulture, out var val))
+ if (TimeSpan.TryParse(time, CultureInfo.InvariantCulture, out var val))
{
var currentMs = startMs + val.TotalMilliseconds;
- var percentVal = currentMs / totalMs;
- percent = 100 * percentVal;
+ percent = 100.0 * currentMs / totalMs;
transcodingPosition = val;
}
}
else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
{
- var size = part.Split(new[] { '=' }, 2).Last();
+ var size = part.Split('=', 2)[^1];
int? scale = null;
- if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
+ if (size.Contains("kb", StringComparison.OrdinalIgnoreCase))
{
scale = 1024;
size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase);
@@ -108,7 +127,7 @@ namespace MediaBrowser.Controller.MediaEncoding
if (scale.HasValue)
{
- if (long.TryParse(size, NumberStyles.Any, _usCulture, out var val))
+ if (long.TryParse(size, NumberStyles.Any, CultureInfo.InvariantCulture, out var val))
{
bytesTranscoded = val * scale.Value;
}
@@ -116,10 +135,10 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase))
{
- var rate = part.Split(new[] { '=' }, 2).Last();
+ var rate = part.Split('=', 2)[^1];
int? scale = null;
- if (rate.IndexOf("kbits/s", StringComparison.OrdinalIgnoreCase) != -1)
+ if (rate.Contains("kbits/s", StringComparison.OrdinalIgnoreCase))
{
scale = 1024;
rate = rate.Replace("kbits/s", string.Empty, StringComparison.OrdinalIgnoreCase);
@@ -127,7 +146,7 @@ namespace MediaBrowser.Controller.MediaEncoding
if (scale.HasValue)
{
- if (float.TryParse(rate, NumberStyles.Any, _usCulture, out var val))
+ if (float.TryParse(rate, NumberStyles.Any, CultureInfo.InvariantCulture, out var val))
{
bitRate = (int)Math.Ceiling(val * scale.Value);
}
@@ -137,7 +156,7 @@ namespace MediaBrowser.Controller.MediaEncoding
if (framerate.HasValue || percent.HasValue)
{
- state.ReportTranscodingProgress(transcodingPosition, 0, percent, 0, bitRate);
+ state.ReportTranscodingProgress(transcodingPosition, framerate, percent, bytesTranscoded, bitRate);
}
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs
index 7f842c1d0..841e7b287 100644
--- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs
+++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs
@@ -1,53 +1,11 @@
-using System;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
+#pragma warning disable CS1591
namespace MediaBrowser.Controller.MediaEncoding
{
/// <summary>
- /// Class MediaEncoderHelpers
+ /// Class MediaEncoderHelpers.
/// </summary>
public static class MediaEncoderHelpers
{
- /// <summary>
- /// Gets the input argument.
- /// </summary>
- /// <param name="fileSystem">The file system.</param>
- /// <param name="videoPath">The video path.</param>
- /// <param name="protocol">The protocol.</param>
- /// <param name="isoMount">The iso mount.</param>
- /// <param name="playableStreamFileNames">The playable stream file names.</param>
- /// <returns>System.String[][].</returns>
- public static string[] GetInputArgument(IFileSystem fileSystem, string videoPath, MediaProtocol protocol, IIsoMount isoMount, string[] playableStreamFileNames)
- {
- if (playableStreamFileNames.Length > 0)
- {
- if (isoMount == null)
- {
- return GetPlayableStreamFiles(fileSystem, videoPath, playableStreamFileNames);
- }
- return GetPlayableStreamFiles(fileSystem, isoMount.MountedPath, playableStreamFileNames);
- }
-
- return new[] { videoPath };
- }
-
- private static string[] GetPlayableStreamFiles(IFileSystem fileSystem, string rootPath, string[] filenames)
- {
- if (filenames.Length == 0)
- {
- return new string[] { };
- }
-
- var allFiles = fileSystem
- .GetFilePaths(rootPath, true)
- .ToArray();
-
- return filenames.Select(name => allFiles.FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
- .Where(f => !string.IsNullOrEmpty(f))
- .ToArray();
- }
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
index b78ef0b80..1dd8bcf31 100644
--- a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
+++ b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
@@ -1,21 +1,18 @@
-using System;
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.IO;
namespace MediaBrowser.Controller.MediaEncoding
{
public class MediaInfoRequest
{
public MediaSourceInfo MediaSource { get; set; }
+
public bool ExtractChapters { get; set; }
- public DlnaProfileType MediaType { get; set; }
- public IIsoMount MountedIso { get; set; }
- public string[] PlayableStreamFileNames { get; set; }
- public MediaInfoRequest()
- {
- PlayableStreamFileNames = Array.Empty<string>();
- }
+ public DlnaProfileType MediaType { get; set; }
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs b/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs
new file mode 100644
index 000000000..66b628371
--- /dev/null
+++ b/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs
@@ -0,0 +1,23 @@
+namespace MediaBrowser.Controller.MediaEncoding
+{
+ /// <summary>
+ /// Enum TranscodingJobType.
+ /// </summary>
+ public enum TranscodingJobType
+ {
+ /// <summary>
+ /// The progressive.
+ /// </summary>
+ Progressive,
+
+ /// <summary>
+ /// The HLS.
+ /// </summary>
+ Hls,
+
+ /// <summary>
+ /// The dash.
+ /// </summary>
+ Dash
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Net/AuthenticatedAttribute.cs b/MediaBrowser.Controller/Net/AuthenticatedAttribute.cs
deleted file mode 100644
index 64c2294e3..000000000
--- a/MediaBrowser.Controller/Net/AuthenticatedAttribute.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-using System;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.Net
-{
- public class AuthenticatedAttribute : Attribute, IHasRequestFilter, IAuthenticationAttributes
- {
- public static IAuthService AuthService { get; set; }
-
- /// <summary>
- /// Gets or sets the roles.
- /// </summary>
- /// <value>The roles.</value>
- public string Roles { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [escape parental control].
- /// </summary>
- /// <value><c>true</c> if [escape parental control]; otherwise, <c>false</c>.</value>
- public bool EscapeParentalControl { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [allow before startup wizard].
- /// </summary>
- /// <value><c>true</c> if [allow before startup wizard]; otherwise, <c>false</c>.</value>
- public bool AllowBeforeStartupWizard { get; set; }
-
- public bool AllowLocal { get; set; }
-
- /// <summary>
- /// The request filter is executed before the service.
- /// </summary>
- /// <param name="request">The http request wrapper</param>
- /// <param name="response">The http response wrapper</param>
- /// <param name="requestDto">The request DTO</param>
- public void RequestFilter(IRequest request, IResponse response, object requestDto)
- {
- AuthService.Authenticate(request, this);
- }
-
- /// <summary>
- /// Order in which Request Filters are executed.
- /// &lt;0 Executed before global request filters
- /// &gt;0 Executed after global request filters
- /// </summary>
- /// <value>The priority.</value>
- public int Priority => 0;
-
- public string[] GetRoles()
- {
- return (Roles ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- }
-
- public bool AllowLocalOnly { get; set; }
- }
-
- public interface IAuthenticationAttributes
- {
- bool EscapeParentalControl { get; }
- bool AllowBeforeStartupWizard { get; }
- bool AllowLocal { get; }
- bool AllowLocalOnly { get; }
-
- string[] GetRoles();
- }
-}
diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
index 3e004763d..2452b25ab 100644
--- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs
+++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
@@ -1,42 +1,69 @@
+#nullable disable
+
using System;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
namespace MediaBrowser.Controller.Net
{
+ /// <summary>
+ /// The request authorization info.
+ /// </summary>
public class AuthorizationInfo
{
/// <summary>
- /// Gets or sets the user identifier.
+ /// Gets the user identifier.
/// </summary>
/// <value>The user identifier.</value>
- public Guid UserId => User == null ? Guid.Empty : User.Id;
+ public Guid UserId => User?.Id ?? Guid.Empty;
/// <summary>
/// Gets or sets the device identifier.
/// </summary>
/// <value>The device identifier.</value>
public string DeviceId { get; set; }
+
/// <summary>
/// Gets or sets the device.
/// </summary>
/// <value>The device.</value>
public string Device { get; set; }
+
/// <summary>
/// Gets or sets the client.
/// </summary>
/// <value>The client.</value>
public string Client { get; set; }
+
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
+
/// <summary>
/// Gets or sets the token.
/// </summary>
/// <value>The token.</value>
public string Token { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether the authorization is from an api key.
+ /// </summary>
+ public bool IsApiKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user making the request.
+ /// </summary>
public User User { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the token is authenticated.
+ /// </summary>
+ public bool IsAuthenticated { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the request has a token.
+ /// </summary>
+ public bool HasToken { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
index 4242a00e2..0813a8e7d 100644
--- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
+++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1306, SA1401
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -6,12 +10,13 @@ using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Net
{
/// <summary>
- /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received
+ /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received.
/// </summary>
/// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
/// <typeparam name="TStateType">The type of the T state type.</typeparam>
@@ -20,30 +25,17 @@ namespace MediaBrowser.Controller.Net
where TReturnDataType : class
{
/// <summary>
- /// The _active connections
- /// </summary>
- protected readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>> ActiveConnections =
- new List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>>();
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- protected abstract string Name { get; }
-
- /// <summary>
- /// Gets the data to send.
+ /// The _active connections.
/// </summary>
- /// <param name="state">The state.</param>
- /// <returns>Task{`1}.</returns>
- protected abstract Task<TReturnDataType> GetDataToSend(TStateType state, CancellationToken cancellationToken);
+ private readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>> _activeConnections =
+ new List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>>();
/// <summary>
- /// The logger
+ /// The logger.
/// </summary>
- protected ILogger Logger;
+ protected ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> Logger;
- protected BasePeriodicWebSocketListener(ILogger logger)
+ protected BasePeriodicWebSocketListener(ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> logger)
{
if (logger == null)
{
@@ -54,62 +46,71 @@ namespace MediaBrowser.Controller.Net
}
/// <summary>
+ /// Gets the type used for the messages sent to the client.
+ /// </summary>
+ /// <value>The type.</value>
+ protected abstract SessionMessageType Type { get; }
+
+ /// <summary>
+ /// Gets the message type received from the client to start sending messages.
+ /// </summary>
+ /// <value>The type.</value>
+ protected abstract SessionMessageType StartType { get; }
+
+ /// <summary>
+ /// Gets the message type received from the client to stop sending messages.
+ /// </summary>
+ /// <value>The type.</value>
+ protected abstract SessionMessageType StopType { get; }
+
+ /// <summary>
+ /// Gets the data to send.
+ /// </summary>
+ /// <returns>Task{`1}.</returns>
+ protected abstract Task<TReturnDataType> GetDataToSend();
+
+ /// <summary>
/// Processes the message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Task.</returns>
- public Task ProcessMessage(WebSocketMessageInfo message)
+ public Task ProcessMessageAsync(WebSocketMessageInfo message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
- if (string.Equals(message.MessageType, Name + "Start", StringComparison.OrdinalIgnoreCase))
+ if (message.MessageType == StartType)
{
Start(message);
}
- if (string.Equals(message.MessageType, Name + "Stop", StringComparison.OrdinalIgnoreCase))
+ if (message.MessageType == StopType)
{
Stop(message);
}
- return Task.FromResult(true);
+ return Task.CompletedTask;
}
- protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- protected virtual bool SendOnTimer => false;
-
- protected virtual void ParseMessageParams(string[] values)
- {
-
- }
+ /// <inheritdoc />
+ public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection) => Task.CompletedTask;
/// <summary>
- /// Starts sending messages over a web socket
+ /// Starts sending messages over a web socket.
/// </summary>
/// <param name="message">The message.</param>
private void Start(WebSocketMessageInfo message)
{
var vals = message.Data.Split(',');
- var dueTimeMs = long.Parse(vals[0], UsCulture);
- var periodMs = long.Parse(vals[1], UsCulture);
-
- if (vals.Length > 2)
- {
- ParseMessageParams(vals.Skip(2).ToArray());
- }
+ var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
+ var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
var cancellationTokenSource = new CancellationTokenSource();
- Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
-
- var timer = SendOnTimer ?
- new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) :
- null;
+ Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
var state = new TStateType
{
@@ -117,58 +118,24 @@ namespace MediaBrowser.Controller.Net
InitialDelayMs = dueTimeMs
};
- lock (ActiveConnections)
+ lock (_activeConnections)
{
- ActiveConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>(message.Connection, cancellationTokenSource, timer, state));
+ _activeConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>(message.Connection, cancellationTokenSource, state));
}
-
- if (timer != null)
- {
- timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
- }
- }
-
- /// <summary>
- /// Timers the callback.
- /// </summary>
- /// <param name="state">The state.</param>
- private void TimerCallback(object state)
- {
- var connection = (IWebSocketConnection)state;
-
- Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple;
-
- lock (ActiveConnections)
- {
- tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
- }
-
- if (tuple == null)
- {
- return;
- }
-
- if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
- {
- DisposeConnection(tuple);
- return;
- }
-
- SendData(tuple);
}
- protected void SendData(bool force)
+ protected async Task SendData(bool force)
{
- Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>[] tuples;
+ Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>[] tuples;
- lock (ActiveConnections)
+ lock (_activeConnections)
{
- tuples = ActiveConnections
+ tuples = _activeConnections
.Where(c =>
{
if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
{
- var state = c.Item4;
+ var state = c.Item3;
if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
{
@@ -181,32 +148,39 @@ namespace MediaBrowser.Controller.Net
.ToArray();
}
- foreach (var tuple in tuples)
+ IEnumerable<Task> GetTasks()
{
- SendData(tuple);
+ foreach (var tuple in tuples)
+ {
+ yield return SendData(tuple);
+ }
}
+
+ await Task.WhenAll(GetTasks()).ConfigureAwait(false);
}
- private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple)
+ private async Task SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
{
var connection = tuple.Item1;
try
{
- var state = tuple.Item4;
+ var state = tuple.Item3;
var cancellationToken = tuple.Item2.Token;
- var data = await GetDataToSend(state, cancellationToken).ConfigureAwait(false);
+ var data = await GetDataToSend().ConfigureAwait(false);
if (data != null)
{
- await connection.SendAsync(new WebSocketMessage<TReturnDataType>
- {
- MessageType = Name,
- Data = data
-
- }, cancellationToken).ConfigureAwait(false);
+ await connection.SendAsync(
+ new WebSocketMessage<TReturnDataType>
+ {
+ MessageId = Guid.NewGuid(),
+ MessageType = Type,
+ Data = data
+ },
+ cancellationToken).ConfigureAwait(false);
state.DateLastSendUtc = DateTime.UtcNow;
}
@@ -220,20 +194,20 @@ namespace MediaBrowser.Controller.Net
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error sending web socket message {Name}", Name);
+ Logger.LogError(ex, "Error sending web socket message {Name}", Type);
DisposeConnection(tuple);
}
}
/// <summary>
- /// Stops sending messages over a web socket
+ /// Stops sending messages over a web socket.
/// </summary>
/// <param name="message">The message.</param>
private void Stop(WebSocketMessageInfo message)
{
- lock (ActiveConnections)
+ lock (_activeConnections)
{
- var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
+ var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
if (connection != null)
{
@@ -246,23 +220,12 @@ namespace MediaBrowser.Controller.Net
/// Disposes the connection.
/// </summary>
/// <param name="connection">The connection.</param>
- private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> connection)
+ private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
{
- Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
+ Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
- var timer = connection.Item3;
-
- if (timer != null)
- {
- try
- {
- timer.Dispose();
- }
- catch (ObjectDisposedException)
- {
- //TODO Investigate and properly fix.
- }
- }
+ // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
+ // connection.Item1.Dispose();
try
{
@@ -271,12 +234,12 @@ namespace MediaBrowser.Controller.Net
}
catch (ObjectDisposedException)
{
- //TODO Investigate and properly fix.
+ // TODO Investigate and properly fix.
}
- lock (ActiveConnections)
+ lock (_activeConnections)
{
- ActiveConnections.Remove(connection);
+ _activeConnections.Remove(connection);
}
}
@@ -288,9 +251,9 @@ namespace MediaBrowser.Controller.Net
{
if (dispose)
{
- lock (ActiveConnections)
+ lock (_activeConnections)
{
- foreach (var connection in ActiveConnections.ToArray())
+ foreach (var connection in _activeConnections.ToArray())
{
DisposeConnection(connection);
}
@@ -304,13 +267,7 @@ namespace MediaBrowser.Controller.Net
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
}
-
- public class WebSocketListenerState
- {
- public DateTime DateLastSendUtc { get; set; }
- public long InitialDelayMs { get; set; }
- public long IntervalMs { get; set; }
- }
}
diff --git a/MediaBrowser.Controller/Net/IAuthService.cs b/MediaBrowser.Controller/Net/IAuthService.cs
index 142f1d91c..a7da740e0 100644
--- a/MediaBrowser.Controller/Net/IAuthService.cs
+++ b/MediaBrowser.Controller/Net/IAuthService.cs
@@ -1,9 +1,18 @@
-using MediaBrowser.Model.Services;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net
{
+ /// <summary>
+ /// IAuthService.
+ /// </summary>
public interface IAuthService
{
- void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues);
+ /// <summary>
+ /// Authenticate request.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <returns>Authorization information. Null if unauthenticated.</returns>
+ Task<AuthorizationInfo> Authenticate(HttpRequest request);
}
}
diff --git a/MediaBrowser.Controller/Net/IAuthorizationContext.cs b/MediaBrowser.Controller/Net/IAuthorizationContext.cs
index 61598391f..5c6ca43d1 100644
--- a/MediaBrowser.Controller/Net/IAuthorizationContext.cs
+++ b/MediaBrowser.Controller/Net/IAuthorizationContext.cs
@@ -1,21 +1,25 @@
-using MediaBrowser.Model.Services;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net
{
+ /// <summary>
+ /// IAuthorization context.
+ /// </summary>
public interface IAuthorizationContext
{
/// <summary>
/// Gets the authorization information.
/// </summary>
/// <param name="requestContext">The request context.</param>
- /// <returns>AuthorizationInfo.</returns>
- AuthorizationInfo GetAuthorizationInfo(object requestContext);
+ /// <returns>A task containing the authorization info.</returns>
+ Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext);
/// <summary>
/// Gets the authorization information.
/// </summary>
/// <param name="requestContext">The request context.</param>
- /// <returns>AuthorizationInfo.</returns>
- AuthorizationInfo GetAuthorizationInfo(IRequest requestContext);
+ /// <returns>A <see cref="Task"/> containing the authorization info.</returns>
+ Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext);
}
}
diff --git a/MediaBrowser.Controller/Net/IHasResultFactory.cs b/MediaBrowser.Controller/Net/IHasResultFactory.cs
deleted file mode 100644
index b8cf8cd78..000000000
--- a/MediaBrowser.Controller/Net/IHasResultFactory.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.Net
-{
- /// <summary>
- /// Interface IHasResultFactory
- /// Services that require a ResultFactory should implement this
- /// </summary>
- public interface IHasResultFactory : IRequiresRequest
- {
- /// <summary>
- /// Gets or sets the result factory.
- /// </summary>
- /// <value>The result factory.</value>
- IHttpResultFactory ResultFactory { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Net/IHttpResultFactory.cs b/MediaBrowser.Controller/Net/IHttpResultFactory.cs
deleted file mode 100644
index ff9ecf8af..000000000
--- a/MediaBrowser.Controller/Net/IHttpResultFactory.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.Net
-{
- /// <summary>
- /// Interface IHttpResultFactory
- /// </summary>
- public interface IHttpResultFactory
- {
- /// <summary>
- /// Gets the result.
- /// </summary>
- /// <param name="content">The content.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <returns>System.Object.</returns>
- object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null);
-
- object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null);
- object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null);
- object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null);
-
- object GetRedirectResult(string url);
-
- object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
- where T : class;
-
- /// <summary>
- /// Gets the static result.
- /// </summary>
- /// <param name="requestContext">The request context.</param>
- /// <param name="cacheKey">The cache key.</param>
- /// <param name="lastDateModified">The last date modified.</param>
- /// <param name="cacheDuration">Duration of the cache.</param>
- /// <param name="contentType">Type of the content.</param>
- /// <param name="factoryFn">The factory fn.</param>
- /// <param name="responseHeaders">The response headers.</param>
- /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
- /// <returns>System.Object.</returns>
- Task<object> GetStaticResult(IRequest requestContext,
- Guid cacheKey,
- DateTime? lastDateModified,
- TimeSpan? cacheDuration,
- string contentType, Func<Task<Stream>> factoryFn,
- IDictionary<string, string> responseHeaders = null,
- bool isHeadRequest = false);
-
- /// <summary>
- /// Gets the static result.
- /// </summary>
- /// <param name="requestContext">The request context.</param>
- /// <param name="options">The options.</param>
- /// <returns>System.Object.</returns>
- Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options);
-
- /// <summary>
- /// Gets the static file result.
- /// </summary>
- /// <param name="requestContext">The request context.</param>
- /// <param name="path">The path.</param>
- /// <param name="fileShare">The file share.</param>
- /// <returns>System.Object.</returns>
- Task<object> GetStaticFileResult(IRequest requestContext, string path, FileShareMode fileShare = FileShareMode.Read);
-
- /// <summary>
- /// Gets the static file result.
- /// </summary>
- /// <param name="requestContext">The request context.</param>
- /// <param name="options">The options.</param>
- /// <returns>System.Object.</returns>
- Task<object> GetStaticFileResult(IRequest requestContext,
- StaticFileResultOptions options);
- }
-}
diff --git a/MediaBrowser.Controller/Net/IHttpServer.cs b/MediaBrowser.Controller/Net/IHttpServer.cs
deleted file mode 100644
index f41303007..000000000
--- a/MediaBrowser.Controller/Net/IHttpServer.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.Net
-{
- /// <summary>
- /// Interface IHttpServer
- /// </summary>
- public interface IHttpServer : IDisposable
- {
- /// <summary>
- /// Gets the URL prefix.
- /// </summary>
- /// <value>The URL prefix.</value>
- string[] UrlPrefixes { get; }
-
- /// <summary>
- /// Stops this instance.
- /// </summary>
- void Stop();
-
- /// <summary>
- /// Occurs when [web socket connected].
- /// </summary>
- event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
-
- /// <summary>
- /// Inits this instance.
- /// </summary>
- void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listener);
-
- /// <summary>
- /// If set, all requests will respond with this message
- /// </summary>
- string GlobalResponse { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Net/ISessionContext.cs b/MediaBrowser.Controller/Net/ISessionContext.cs
index 5c3c19f6b..b48181b3f 100644
--- a/MediaBrowser.Controller/Net/ISessionContext.cs
+++ b/MediaBrowser.Controller/Net/ISessionContext.cs
@@ -1,15 +1,20 @@
-using MediaBrowser.Controller.Entities;
+#pragma warning disable CS1591
+
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net
{
public interface ISessionContext
{
- SessionInfo GetSession(object requestContext);
- User GetUser(object requestContext);
+ Task<SessionInfo> GetSession(object requestContext);
+
+ Task<User?> GetUser(object requestContext);
+
+ Task<SessionInfo> GetSession(HttpContext requestContext);
- SessionInfo GetSession(IRequest requestContext);
- User GetUser(IRequest requestContext);
+ Task<User?> GetUser(HttpContext requestContext);
}
}
diff --git a/MediaBrowser.Controller/Net/IWebSocketConnection.cs b/MediaBrowser.Controller/Net/IWebSocketConnection.cs
index a09b2f7a2..c8c5caf80 100644
--- a/MediaBrowser.Controller/Net/IWebSocketConnection.cs
+++ b/MediaBrowser.Controller/Net/IWebSocketConnection.cs
@@ -1,24 +1,21 @@
+#pragma warning disable CS1591
+
using System;
+using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net
{
- public interface IWebSocketConnection : IDisposable
+ public interface IWebSocketConnection
{
/// <summary>
/// Occurs when [closed].
/// </summary>
- event EventHandler<EventArgs> Closed;
-
- /// <summary>
- /// Gets the id.
- /// </summary>
- /// <value>The id.</value>
- Guid Id { get; }
+ event EventHandler<EventArgs>? Closed;
/// <summary>
/// Gets the last activity date.
@@ -27,21 +24,22 @@ namespace MediaBrowser.Controller.Net
DateTime LastActivityDate { get; }
/// <summary>
- /// Gets or sets the URL.
+ /// Gets or sets the date of last Keeplive received.
/// </summary>
- /// <value>The URL.</value>
- string Url { get; set; }
+ /// <value>The date of last Keeplive received.</value>
+ DateTime LastKeepAliveDate { get; set; }
+
/// <summary>
- /// Gets or sets the query string.
+ /// Gets the query string.
/// </summary>
/// <value>The query string.</value>
- QueryParamCollection QueryString { get; set; }
+ IQueryCollection QueryString { get; }
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
- Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
+ Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
/// <summary>
/// Gets the state.
@@ -53,33 +51,18 @@ namespace MediaBrowser.Controller.Net
/// Gets the remote end point.
/// </summary>
/// <value>The remote end point.</value>
- string RemoteEndPoint { get; }
+ IPAddress? RemoteEndPoint { get; }
/// <summary>
/// Sends a message asynchronously.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of websocket message data.</typeparam>
/// <param name="message">The message.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">message</exception>
+ /// <exception cref="ArgumentNullException">The message is null.</exception>
Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken);
- /// <summary>
- /// Sends a message asynchronously.
- /// </summary>
- /// <param name="buffer">The buffer.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- Task SendAsync(byte[] buffer, CancellationToken cancellationToken);
-
- /// <summary>
- /// Sends a message asynchronously.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">buffer</exception>
- Task SendAsync(string text, CancellationToken cancellationToken);
+ Task ProcessAsync(CancellationToken cancellationToken = default);
}
}
diff --git a/MediaBrowser.Controller/Net/IWebSocketListener.cs b/MediaBrowser.Controller/Net/IWebSocketListener.cs
index e38f0e259..f1a75d518 100644
--- a/MediaBrowser.Controller/Net/IWebSocketListener.cs
+++ b/MediaBrowser.Controller/Net/IWebSocketListener.cs
@@ -3,7 +3,7 @@ using System.Threading.Tasks;
namespace MediaBrowser.Controller.Net
{
/// <summary>
- ///This is an interface for listening to messages coming through a web socket connection
+ /// Interface for listening to messages coming through a web socket connection.
/// </summary>
public interface IWebSocketListener
{
@@ -12,6 +12,13 @@ namespace MediaBrowser.Controller.Net
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Task.</returns>
- Task ProcessMessage(WebSocketMessageInfo message);
+ Task ProcessMessageAsync(WebSocketMessageInfo message);
+
+ /// <summary>
+ /// Processes a new web socket connection.
+ /// </summary>
+ /// <param name="connection">An instance of the <see cref="IWebSocketConnection"/> interface.</param>
+ /// <returns>Task.</returns>
+ Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection);
}
}
diff --git a/MediaBrowser.Controller/Net/IWebSocketManager.cs b/MediaBrowser.Controller/Net/IWebSocketManager.cs
new file mode 100644
index 000000000..bb0ae83be
--- /dev/null
+++ b/MediaBrowser.Controller/Net/IWebSocketManager.cs
@@ -0,0 +1,18 @@
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+
+namespace MediaBrowser.Controller.Net
+{
+ /// <summary>
+ /// Interface IHttpServer.
+ /// </summary>
+ public interface IWebSocketManager
+ {
+ /// <summary>
+ /// The HTTP request handler.
+ /// </summary>
+ /// <param name="context">The current HTTP context.</param>
+ /// <returns>The task.</returns>
+ Task WebSocketRequestHandler(HttpContext context);
+ }
+}
diff --git a/MediaBrowser.Controller/Net/SecurityException.cs b/MediaBrowser.Controller/Net/SecurityException.cs
index 3ccecf0eb..f0d0b45a0 100644
--- a/MediaBrowser.Controller/Net/SecurityException.cs
+++ b/MediaBrowser.Controller/Net/SecurityException.cs
@@ -2,20 +2,36 @@ using System;
namespace MediaBrowser.Controller.Net
{
+ /// <summary>
+ /// The exception that is thrown when a user is authenticated, but not authorized to access a requested resource.
+ /// </summary>
public class SecurityException : Exception
{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SecurityException"/> class.
+ /// </summary>
+ public SecurityException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SecurityException"/> class.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
public SecurityException(string message)
: base(message)
{
-
}
- public SecurityExceptionType SecurityExceptionType { get; set; }
- }
-
- public enum SecurityExceptionType
- {
- Unauthenticated = 0,
- ParentalControl = 1
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SecurityException"/> class.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
+ public SecurityException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
}
}
diff --git a/MediaBrowser.Controller/Net/StaticResultOptions.cs b/MediaBrowser.Controller/Net/StaticResultOptions.cs
deleted file mode 100644
index 7a179913a..000000000
--- a/MediaBrowser.Controller/Net/StaticResultOptions.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-
-using MediaBrowser.Model.IO;
-
-namespace MediaBrowser.Controller.Net
-{
- public class StaticResultOptions
- {
- public string ContentType { get; set; }
- public TimeSpan? CacheDuration { get; set; }
- public DateTime? DateLastModified { get; set; }
- public Func<Task<Stream>> ContentFactory { get; set; }
-
- public bool IsHeadRequest { get; set; }
-
- public IDictionary<string, string> ResponseHeaders { get; set; }
-
- public Action OnComplete { get; set; }
- public Action OnError { get; set; }
-
- public string Path { get; set; }
- public long? ContentLength { get; set; }
-
- public FileShareMode FileShare { get; set; }
-
- public StaticResultOptions()
- {
- ResponseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- FileShare = FileShareMode.Read;
- }
- }
-
- public class StaticFileResultOptions : StaticResultOptions
- {
- }
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs b/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs
deleted file mode 100644
index f26b764bb..000000000
--- a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Controller.Net
-{
- /// <summary>
- /// Class WebSocketConnectEventArgs
- /// </summary>
- public class WebSocketConnectingEventArgs : EventArgs
- {
- /// <summary>
- /// Gets or sets the URL.
- /// </summary>
- /// <value>The URL.</value>
- public string Url { get; set; }
- /// <summary>
- /// Gets or sets the endpoint.
- /// </summary>
- /// <value>The endpoint.</value>
- public string Endpoint { get; set; }
- /// <summary>
- /// Gets or sets the query string.
- /// </summary>
- /// <value>The query string.</value>
- public QueryParamCollection QueryString { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether [allow connection].
- /// </summary>
- /// <value><c>true</c> if [allow connection]; otherwise, <c>false</c>.</value>
- public bool AllowConnection { get; set; }
-
- public WebSocketConnectingEventArgs()
- {
- QueryString = new QueryParamCollection();
- AllowConnection = true;
- }
- }
-
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketListenerState.cs b/MediaBrowser.Controller/Net/WebSocketListenerState.cs
new file mode 100644
index 000000000..70604d60a
--- /dev/null
+++ b/MediaBrowser.Controller/Net/WebSocketListenerState.cs
@@ -0,0 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Controller.Net
+{
+ public class WebSocketListenerState
+ {
+ public DateTime DateLastSendUtc { get; set; }
+
+ public long InitialDelayMs { get; set; }
+
+ public long IntervalMs { get; set; }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs b/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs
index 5bf39cae6..6f7ebf156 100644
--- a/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs
+++ b/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs
@@ -1,9 +1,11 @@
+#nullable disable
+
using MediaBrowser.Model.Net;
namespace MediaBrowser.Controller.Net
{
/// <summary>
- /// Class WebSocketMessageInfo
+ /// Class WebSocketMessageInfo.
/// </summary>
public class WebSocketMessageInfo : WebSocketMessage<string>
{
diff --git a/MediaBrowser.Controller/Notifications/INotificationManager.cs b/MediaBrowser.Controller/Notifications/INotificationManager.cs
index 44defbe0b..7caba1097 100644
--- a/MediaBrowser.Controller/Notifications/INotificationManager.cs
+++ b/MediaBrowser.Controller/Notifications/INotificationManager.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -17,7 +19,7 @@ namespace MediaBrowser.Controller.Notifications
/// <returns>Task.</returns>
Task SendNotification(NotificationRequest request, CancellationToken cancellationToken);
- Task SendNotification(NotificationRequest request, BaseItem relatedItem, CancellationToken cancellationToken);
+ Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken);
/// <summary>
/// Adds the parts.
diff --git a/MediaBrowser.Controller/Notifications/INotificationService.cs b/MediaBrowser.Controller/Notifications/INotificationService.cs
index 8c6019923..535c08795 100644
--- a/MediaBrowser.Controller/Notifications/INotificationService.cs
+++ b/MediaBrowser.Controller/Notifications/INotificationService.cs
@@ -1,6 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
namespace MediaBrowser.Controller.Notifications
{
diff --git a/MediaBrowser.Controller/Notifications/INotificationTypeFactory.cs b/MediaBrowser.Controller/Notifications/INotificationTypeFactory.cs
index 9f1d2841d..52a3e120b 100644
--- a/MediaBrowser.Controller/Notifications/INotificationTypeFactory.cs
+++ b/MediaBrowser.Controller/Notifications/INotificationTypeFactory.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Model.Notifications;
diff --git a/MediaBrowser.Controller/Notifications/UserNotification.cs b/MediaBrowser.Controller/Notifications/UserNotification.cs
index 3f46468b3..4be0e09ae 100644
--- a/MediaBrowser.Controller/Notifications/UserNotification.cs
+++ b/MediaBrowser.Controller/Notifications/UserNotification.cs
@@ -1,5 +1,9 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Controller.Entities;
+using Jellyfin.Data.Entities;
using MediaBrowser.Model.Notifications;
namespace MediaBrowser.Controller.Notifications
diff --git a/MediaBrowser.Controller/Persistence/IDisplayPreferencesRepository.cs b/MediaBrowser.Controller/Persistence/IDisplayPreferencesRepository.cs
deleted file mode 100644
index 4424e044b..000000000
--- a/MediaBrowser.Controller/Persistence/IDisplayPreferencesRepository.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Controller.Persistence
-{
- /// <summary>
- /// Interface IDisplayPreferencesRepository
- /// </summary>
- public interface IDisplayPreferencesRepository : IRepository
- {
- /// <summary>
- /// Saves display preferences for an item
- /// </summary>
- /// <param name="displayPreferences">The display preferences.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="client">The client.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- void SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client,
- CancellationToken cancellationToken);
-
- /// <summary>
- /// Saves all display preferences for a user
- /// </summary>
- /// <param name="displayPreferences">The display preferences.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- void SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId,
- CancellationToken cancellationToken);
- /// <summary>
- /// Gets the display preferences.
- /// </summary>
- /// <param name="displayPreferencesId">The display preferences id.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="client">The client.</param>
- /// <returns>Task{DisplayPreferences}.</returns>
- DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client);
-
- /// <summary>
- /// Gets all display preferences for the given user.
- /// </summary>
- /// <param name="userId">The user id.</param>
- /// <returns>Task{DisplayPreferences}.</returns>
- IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId);
- }
-}
diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs
index 47e0f3453..a084f9196 100644
--- a/MediaBrowser.Controller/Persistence/IItemRepository.cs
+++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
@@ -9,12 +13,12 @@ using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.Persistence
{
/// <summary>
- /// Provides an interface to implement an Item repository
+ /// Provides an interface to implement an Item repository.
/// </summary>
public interface IItemRepository : IRepository
{
/// <summary>
- /// Saves an item
+ /// Saves an item.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
@@ -24,8 +28,7 @@ namespace MediaBrowser.Controller.Persistence
/// Deletes the item.
/// </summary>
/// <param name="id">The identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- void DeleteItem(Guid id, CancellationToken cancellationToken);
+ void DeleteItem(Guid id);
/// <summary>
/// Saves the items.
@@ -44,24 +47,26 @@ namespace MediaBrowser.Controller.Persistence
BaseItem RetrieveItem(Guid id);
/// <summary>
- /// Gets chapters for an item
+ /// Gets chapters for an item.
/// </summary>
- /// <param name="id"></param>
- /// <returns></returns>
- List<ChapterInfo> GetChapters(BaseItem id);
+ /// <param name="item">The item.</param>
+ /// <returns>The list of chapter info.</returns>
+ List<ChapterInfo> GetChapters(BaseItem item);
/// <summary>
- /// Gets a single chapter for an item
+ /// Gets a single chapter for an item.
/// </summary>
- /// <param name="id"></param>
- /// <param name="index"></param>
- /// <returns></returns>
- ChapterInfo GetChapter(BaseItem id, int index);
+ /// <param name="item">The item.</param>
+ /// <param name="index">The chapter index.</param>
+ /// <returns>The chapter info at the specified index.</returns>
+ ChapterInfo GetChapter(BaseItem item, int index);
/// <summary>
/// Saves the chapters.
/// </summary>
- void SaveChapters(Guid id, List<ChapterInfo> chapters);
+ /// <param name="id">The item id.</param>
+ /// <param name="chapters">The list of chapters to save.</param>
+ void SaveChapters(Guid id, IReadOnlyList<ChapterInfo> chapters);
/// <summary>
/// Gets the media streams.
@@ -79,11 +84,27 @@ namespace MediaBrowser.Controller.Persistence
void SaveMediaStreams(Guid id, List<MediaStream> streams, CancellationToken cancellationToken);
/// <summary>
+ /// Gets the media attachments.
+ /// </summary>
+ /// <param name="query">The query.</param>
+ /// <returns>IEnumerable{MediaAttachment}.</returns>
+ List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query);
+
+ /// <summary>
+ /// Saves the media attachments.
+ /// </summary>
+ /// <param name="id">The identifier.</param>
+ /// <param name="attachments">The attachments.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void SaveMediaAttachments(Guid id, IReadOnlyList<MediaAttachment> attachments, CancellationToken cancellationToken);
+
+ /// <summary>
/// Gets the item ids.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>IEnumerable&lt;Guid&gt;.</returns>
QueryResult<Guid> GetItemIds(InternalItemsQuery query);
+
/// <summary>
/// Gets the items.
/// </summary>
@@ -136,22 +157,28 @@ namespace MediaBrowser.Controller.Persistence
/// <summary>
/// Updates the inherited values.
/// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- void UpdateInheritedValues(CancellationToken cancellationToken);
+ void UpdateInheritedValues();
int GetCount(InternalItemsQuery query);
QueryResult<(BaseItem, ItemCounts)> GetGenres(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetMusicGenres(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetStudios(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetArtists(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetAlbumArtists(InternalItemsQuery query);
+
QueryResult<(BaseItem, ItemCounts)> GetAllArtists(InternalItemsQuery query);
List<string> GetMusicGenreNames();
+
List<string> GetStudioNames();
+
List<string> GetGenreNames();
+
List<string> GetAllArtistNames();
}
}
-
diff --git a/MediaBrowser.Controller/Persistence/IRepository.cs b/MediaBrowser.Controller/Persistence/IRepository.cs
index 56bf1dd5a..42f285076 100644
--- a/MediaBrowser.Controller/Persistence/IRepository.cs
+++ b/MediaBrowser.Controller/Persistence/IRepository.cs
@@ -3,12 +3,12 @@ using System;
namespace MediaBrowser.Controller.Persistence
{
/// <summary>
- /// Provides a base interface for all the repository interfaces
+ /// Provides a base interface for all the repository interfaces.
/// </summary>
public interface IRepository : IDisposable
{
/// <summary>
- /// Gets the name of the repository
+ /// Gets the name of the repository.
/// </summary>
/// <value>The name.</value>
string Name { get; }
diff --git a/MediaBrowser.Controller/Persistence/IUserDataRepository.cs b/MediaBrowser.Controller/Persistence/IUserDataRepository.cs
index a4bdf60d7..c43acfb6d 100644
--- a/MediaBrowser.Controller/Persistence/IUserDataRepository.cs
+++ b/MediaBrowser.Controller/Persistence/IUserDataRepository.cs
@@ -1,3 +1,5 @@
+#nullable disable
+
using System.Collections.Generic;
using System.Threading;
using MediaBrowser.Controller.Entities;
@@ -5,7 +7,7 @@ using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Persistence
{
/// <summary>
- /// Provides an interface to implement a UserData repository
+ /// Provides an interface to implement a UserData repository.
/// </summary>
public interface IUserDataRepository : IRepository
{
@@ -16,7 +18,6 @@ namespace MediaBrowser.Controller.Persistence
/// <param name="key">The key.</param>
/// <param name="userData">The user data.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
void SaveUserData(long userId, string key, UserItemData userData, CancellationToken cancellationToken);
/// <summary>
@@ -24,26 +25,30 @@ namespace MediaBrowser.Controller.Persistence
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
- /// <returns>Task{UserItemData}.</returns>
+ /// <returns>The user data.</returns>
UserItemData GetUserData(long userId, string key);
+ /// <summary>
+ /// Gets the user data.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="keys">The keys.</param>
+ /// <returns>The user data.</returns>
UserItemData GetUserData(long userId, List<string> keys);
/// <summary>
- /// Return all user data associated with the given user
+ /// Return all user data associated with the given user.
/// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <returns>The list of user item data.</returns>
List<UserItemData> GetAllUserData(long userId);
/// <summary>
- /// Save all user data associated with the given user
+ /// Save all user data associated with the given user.
/// </summary>
- /// <param name="userId"></param>
- /// <param name="userData"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
+ /// <param name="userId">The user id.</param>
+ /// <param name="userData">The user item data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
void SaveAllUserData(long userId, UserItemData[] userData, CancellationToken cancellationToken);
-
}
}
diff --git a/MediaBrowser.Controller/Persistence/IUserRepository.cs b/MediaBrowser.Controller/Persistence/IUserRepository.cs
deleted file mode 100644
index cd23e5223..000000000
--- a/MediaBrowser.Controller/Persistence/IUserRepository.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Controller.Entities;
-
-namespace MediaBrowser.Controller.Persistence
-{
- /// <summary>
- /// Provides an interface to implement a User repository
- /// </summary>
- public interface IUserRepository : IRepository
- {
- /// <summary>
- /// Deletes the user.
- /// </summary>
- /// <param name="user">The user.</param>
- /// <returns>Task.</returns>
- void DeleteUser(User user);
-
- /// <summary>
- /// Retrieves all users.
- /// </summary>
- /// <returns>IEnumerable{User}.</returns>
- List<User> RetrieveAllUsers();
-
- void CreateUser(User user);
- void UpdateUser(User user);
- }
-}
diff --git a/MediaBrowser.Controller/Persistence/MediaAttachmentQuery.cs b/MediaBrowser.Controller/Persistence/MediaAttachmentQuery.cs
new file mode 100644
index 000000000..e07e96f73
--- /dev/null
+++ b/MediaBrowser.Controller/Persistence/MediaAttachmentQuery.cs
@@ -0,0 +1,21 @@
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Controller.Persistence
+{
+ public class MediaAttachmentQuery
+ {
+ /// <summary>
+ /// Gets or sets the index.
+ /// </summary>
+ /// <value>The index.</value>
+ public int? Index { get; set; }
+
+ /// <summary>
+ /// Gets or sets the item identifier.
+ /// </summary>
+ /// <value>The item identifier.</value>
+ public Guid ItemId { get; set; }
+ }
+}
diff --git a/MediaBrowser.Controller/Persistence/MediaStreamQuery.cs b/MediaBrowser.Controller/Persistence/MediaStreamQuery.cs
index 7dc563b3a..f9295c8fd 100644
--- a/MediaBrowser.Controller/Persistence/MediaStreamQuery.cs
+++ b/MediaBrowser.Controller/Persistence/MediaStreamQuery.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
diff --git a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
index 5001f6842..f6c592070 100644
--- a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
+++ b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
@@ -29,7 +31,7 @@ namespace MediaBrowser.Controller.Playlists
/// <param name="itemIds">The item ids.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>Task.</returns>
- void AddToPlaylist(string playlistId, IEnumerable<Guid> itemIds, Guid userId);
+ Task AddToPlaylistAsync(Guid playlistId, IReadOnlyCollection<Guid> itemIds, Guid userId);
/// <summary>
/// Removes from playlist.
@@ -37,7 +39,7 @@ namespace MediaBrowser.Controller.Playlists
/// <param name="playlistId">The playlist identifier.</param>
/// <param name="entryIds">The entry ids.</param>
/// <returns>Task.</returns>
- void RemoveFromPlaylist(string playlistId, IEnumerable<string> entryIds);
+ Task RemoveFromPlaylistAsync(string playlistId, IEnumerable<string> entryIds);
/// <summary>
/// Gets the playlists folder.
@@ -53,6 +55,6 @@ namespace MediaBrowser.Controller.Playlists
/// <param name="entryId">The entry identifier.</param>
/// <param name="newIndex">The new index.</param>
/// <returns>Task.</returns>
- void MoveItem(string playlistId, string entryId, int newIndex);
+ Task MoveItemAsync(string playlistId, string entryId, int newIndex);
}
}
diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs
index e83260725..5e671a725 100644
--- a/MediaBrowser.Controller/Playlists/Playlist.cs
+++ b/MediaBrowser.Controller/Playlists/Playlist.cs
@@ -1,47 +1,49 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.Playlists
{
public class Playlist : Folder, IHasShares
{
- public static string[] SupportedExtensions =
- {
- ".m3u",
- ".m3u8",
- ".pls",
- ".wpl",
- ".zpl"
- };
-
- public Guid OwnerUserId { get; set; }
-
- public Share[] Shares { get; set; }
+ public static readonly IReadOnlyList<string> SupportedExtensions = new[]
+ {
+ ".m3u",
+ ".m3u8",
+ ".pls",
+ ".wpl",
+ ".zpl"
+ };
public Playlist()
{
Shares = Array.Empty<Share>();
}
- [IgnoreDataMember]
- public bool IsFile => IsPlaylistFile(Path);
+ public Guid OwnerUserId { get; set; }
- public static bool IsPlaylistFile(string path)
- {
- return System.IO.Path.HasExtension(path);
- }
+ public Share[] Shares { get; set; }
+
+ [JsonIgnore]
+ public bool IsFile => IsPlaylistFile(Path);
- [IgnoreDataMember]
+ [JsonIgnore]
public override string ContainingFolderPath
{
get
@@ -57,21 +59,56 @@ namespace MediaBrowser.Controller.Playlists
}
}
- [IgnoreDataMember]
+ [JsonIgnore]
protected override bool FilterLinkedChildrenPerUser => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsInheritedParentImages => false;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsPlayedStatus => string.Equals(MediaType, "Video", StringComparison.OrdinalIgnoreCase);
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool AlwaysScanInternalMetadataPath => true;
- [IgnoreDataMember]
+ [JsonIgnore]
public override bool SupportsCumulativeRunTimeTicks => true;
+ [JsonIgnore]
+ public override bool IsPreSorted => true;
+
+ public string PlaylistMediaType { get; set; }
+
+ [JsonIgnore]
+ public override string MediaType => PlaylistMediaType;
+
+ [JsonIgnore]
+ private bool IsSharedItem
+ {
+ get
+ {
+ var path = Path;
+
+ if (string.IsNullOrEmpty(path))
+ {
+ return false;
+ }
+
+ return FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.DataPath, path);
+ }
+ }
+
+ public static bool IsPlaylistFile(string path)
+ {
+ // The path will sometimes be a directory and "Path.HasExtension" returns true if the name contains a '.' (dot).
+ return System.IO.Path.HasExtension(path) && !Directory.Exists(path);
+ }
+
+ public void SetMediaType(string value)
+ {
+ PlaylistMediaType = value;
+ }
+
public override double GetDefaultPrimaryImageAspectRatio()
{
return 1;
@@ -93,7 +130,7 @@ namespace MediaBrowser.Controller.Playlists
return new List<BaseItem>();
}
- protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
+ protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
@@ -120,10 +157,7 @@ namespace MediaBrowser.Controller.Playlists
private List<BaseItem> GetPlayableItems(User user, InternalItemsQuery query)
{
- if (query == null)
- {
- query = new InternalItemsQuery(user);
- }
+ query ??= new InternalItemsQuery(user);
query.IsFolder = false;
@@ -155,9 +189,9 @@ namespace MediaBrowser.Controller.Playlists
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
Recursive = true,
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
GenreIds = new[] { musicGenre.Id },
- OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
+ OrderBy = new[] { (ItemSortBy.AlbumArtist, SortOrder.Ascending), (ItemSortBy.Album, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) },
DtoOptions = options
});
}
@@ -167,9 +201,9 @@ namespace MediaBrowser.Controller.Playlists
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
Recursive = true,
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
ArtistIds = new[] { musicArtist.Id },
- OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
+ OrderBy = new[] { (ItemSortBy.AlbumArtist, SortOrder.Ascending), (ItemSortBy.Album, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) },
DtoOptions = options
});
}
@@ -180,7 +214,7 @@ namespace MediaBrowser.Controller.Playlists
{
Recursive = true,
IsFolder = false,
- OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
+ OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
MediaTypes = new[] { mediaType },
EnableTotalRecordCount = false,
DtoOptions = options
@@ -192,35 +226,6 @@ namespace MediaBrowser.Controller.Playlists
return new[] { item };
}
- [IgnoreDataMember]
- public override bool IsPreSorted => true;
-
- public string PlaylistMediaType { get; set; }
-
- [IgnoreDataMember]
- public override string MediaType => PlaylistMediaType;
-
- public void SetMediaType(string value)
- {
- PlaylistMediaType = value;
- }
-
- [IgnoreDataMember]
- private bool IsSharedItem
- {
- get
- {
- var path = Path;
-
- if (string.IsNullOrEmpty(path))
- {
- return false;
- }
-
- return FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.DataPath, path);
- }
- }
-
public override bool IsVisible(User user)
{
if (!IsSharedItem)
@@ -239,16 +244,8 @@ namespace MediaBrowser.Controller.Playlists
return base.IsVisible(user);
}
- var userId = user.Id.ToString("N");
- foreach (var share in shares)
- {
- if (string.Equals(share.UserId, userId, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
+ var userId = user.Id.ToString("N", CultureInfo.InvariantCulture);
+ return shares.Any(share => string.Equals(share.UserId, userId, StringComparison.OrdinalIgnoreCase));
}
public override bool IsVisibleStandalone(User user)
diff --git a/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs b/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs
deleted file mode 100644
index 5deb165f6..000000000
--- a/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.IO;
-using System.Reflection;
-
-namespace MediaBrowser.Controller.Plugins
-{
- public interface ILocalizablePlugin
- {
- Stream GetDictionary(string culture);
- }
-
- public static class LocalizablePluginHelper
- {
- public static Stream GetDictionary(Assembly assembly, string manifestPrefix, string culture)
- {
- // Find all dictionaries using GetManifestResourceNames, start start with the prefix
- // Return the one for the culture if exists, otherwise return the default
- return null;
- }
- }
-}
diff --git a/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs b/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs
deleted file mode 100644
index c156da924..000000000
--- a/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System.IO;
-using MediaBrowser.Common.Plugins;
-
-namespace MediaBrowser.Controller.Plugins
-{
- /// <summary>
- /// Interface IConfigurationPage
- /// </summary>
- public interface IPluginConfigurationPage
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
-
- /// <summary>
- /// Gets the type of the configuration page.
- /// </summary>
- /// <value>The type of the configuration page.</value>
- ConfigurationPageType ConfigurationPageType { get; }
-
- /// <summary>
- /// Gets the plugin.
- /// </summary>
- /// <value>The plugin.</value>
- IPlugin Plugin { get; }
-
- /// <summary>
- /// Gets the HTML stream.
- /// </summary>
- /// <returns>Stream.</returns>
- Stream GetHtmlStream();
- }
-
- /// <summary>
- /// Enum ConfigurationPageType
- /// </summary>
- public enum ConfigurationPageType
- {
- /// <summary>
- /// The plugin configuration
- /// </summary>
- PluginConfiguration,
- /// <summary>
- /// The none
- /// </summary>
- None
- }
-}
diff --git a/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs b/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs
new file mode 100644
index 000000000..2b831103a
--- /dev/null
+++ b/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs
@@ -0,0 +1,9 @@
+namespace MediaBrowser.Controller.Plugins
+{
+ /// <summary>
+ /// Indicates that a <see cref="IServerEntryPoint"/> should be invoked as a pre-startup task.
+ /// </summary>
+ public interface IRunBeforeStartup
+ {
+ }
+}
diff --git a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs b/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs
index e57929989..6024661e1 100644
--- a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs
+++ b/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs
@@ -4,18 +4,17 @@ using System.Threading.Tasks;
namespace MediaBrowser.Controller.Plugins
{
/// <summary>
- /// Interface IServerEntryPoint
+ /// Represents an entry point for a module in the application. This interface is scanned for automatically and
+ /// provides a hook to initialize the module at application start.
+ /// The entry point can additionally be flagged as a pre-startup task by implementing the
+ /// <see cref="IRunBeforeStartup"/> interface.
/// </summary>
public interface IServerEntryPoint : IDisposable
{
/// <summary>
- /// Runs this instance.
+ /// Run the initialization for this module. This method is invoked at application start.
/// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task RunAsync();
}
-
- public interface IRunBeforeStartup
- {
-
- }
}
diff --git a/MediaBrowser.Controller/Properties/AssemblyInfo.cs b/MediaBrowser.Controller/Properties/AssemblyInfo.cs
index 007a1d739..60e792309 100644
--- a/MediaBrowser.Controller/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.Controller/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/MediaBrowser.Controller/Providers/AlbumInfo.cs b/MediaBrowser.Controller/Providers/AlbumInfo.cs
index b0b443fc0..aefa520e7 100644
--- a/MediaBrowser.Controller/Providers/AlbumInfo.cs
+++ b/MediaBrowser.Controller/Providers/AlbumInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CA1002, CA2227, CS1591
+
using System;
using System.Collections.Generic;
@@ -5,24 +7,25 @@ namespace MediaBrowser.Controller.Providers
{
public class AlbumInfo : ItemLookupInfo
{
+ public AlbumInfo()
+ {
+ ArtistProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ SongInfos = new List<SongInfo>();
+ AlbumArtists = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the album artist.
/// </summary>
/// <value>The album artist.</value>
- public string[] AlbumArtists { get; set; }
+ public IReadOnlyList<string> AlbumArtists { get; set; }
/// <summary>
/// Gets or sets the artist provider ids.
/// </summary>
/// <value>The artist provider ids.</value>
public Dictionary<string, string> ArtistProviderIds { get; set; }
- public List<SongInfo> SongInfos { get; set; }
- public AlbumInfo()
- {
- ArtistProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- SongInfos = new List<SongInfo>();
- AlbumArtists = Array.Empty<string>();
- }
+ public List<SongInfo> SongInfos { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/ArtistInfo.cs b/MediaBrowser.Controller/Providers/ArtistInfo.cs
index 08bf3982b..4854d1a5f 100644
--- a/MediaBrowser.Controller/Providers/ArtistInfo.cs
+++ b/MediaBrowser.Controller/Providers/ArtistInfo.cs
@@ -1,14 +1,16 @@
+#pragma warning disable CA1002, CA2227, CS1591
+
using System.Collections.Generic;
namespace MediaBrowser.Controller.Providers
{
public class ArtistInfo : ItemLookupInfo
{
- public List<SongInfo> SongInfos { get; set; }
-
public ArtistInfo()
{
SongInfos = new List<SongInfo>();
}
+
+ public List<SongInfo> SongInfos { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/BookInfo.cs b/MediaBrowser.Controller/Providers/BookInfo.cs
index 03a6737c5..3055c5d87 100644
--- a/MediaBrowser.Controller/Providers/BookInfo.cs
+++ b/MediaBrowser.Controller/Providers/BookInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class BookInfo : ItemLookupInfo
diff --git a/MediaBrowser.Controller/Providers/BoxSetInfo.cs b/MediaBrowser.Controller/Providers/BoxSetInfo.cs
index 4cbe2d6ef..f43ea6717 100644
--- a/MediaBrowser.Controller/Providers/BoxSetInfo.cs
+++ b/MediaBrowser.Controller/Providers/BoxSetInfo.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class BoxSetInfo : ItemLookupInfo
{
-
}
}
diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs
index 133e7c115..b31270270 100644
--- a/MediaBrowser.Controller/Providers/DirectoryService.cs
+++ b/MediaBrowser.Controller/Providers/DirectoryService.cs
@@ -1,94 +1,82 @@
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Model.IO;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Providers
{
public class DirectoryService : IDirectoryService
{
- private readonly ILogger _logger;
private readonly IFileSystem _fileSystem;
- private readonly Dictionary<string, FileSystemMetadata[]> _cache = new Dictionary<string, FileSystemMetadata[]>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, FileSystemMetadata[]> _cache = new (StringComparer.Ordinal);
- private readonly Dictionary<string, FileSystemMetadata> _fileCache = new Dictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, FileSystemMetadata> _fileCache = new (StringComparer.Ordinal);
- private readonly Dictionary<string, List<string>> _filePathCache = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, List<string>> _filePathCache = new (StringComparer.Ordinal);
- public DirectoryService(ILogger logger, IFileSystem fileSystem)
+ public DirectoryService(IFileSystem fileSystem)
{
- _logger = logger;
_fileSystem = fileSystem;
}
public FileSystemMetadata[] GetFileSystemEntries(string path)
{
- if (!_cache.TryGetValue(path, out FileSystemMetadata[] entries))
- {
- //_logger.LogDebug("Getting files for " + path);
-
- entries = _fileSystem.GetFileSystemEntries(path).ToArray();
-
- //_cache.TryAdd(path, entries);
- _cache[path] = entries;
- }
-
- return entries;
+ return _cache.GetOrAdd(path, (p, fileSystem) => fileSystem.GetFileSystemEntries(p).ToArray(), _fileSystem);
}
public List<FileSystemMetadata> GetFiles(string path)
{
var list = new List<FileSystemMetadata>();
var items = GetFileSystemEntries(path);
- foreach (var item in items)
+ for (var i = 0; i < items.Length; i++)
{
+ var item = items[i];
if (!item.IsDirectory)
{
list.Add(item);
}
}
+
return list;
}
- public FileSystemMetadata GetFile(string path)
+ public FileSystemMetadata? GetFile(string path)
{
- if (!_fileCache.TryGetValue(path, out FileSystemMetadata file))
+ if (!_fileCache.TryGetValue(path, out var result))
{
- file = _fileSystem.GetFileInfo(path);
-
- if (file != null && file.Exists)
- {
- //_fileCache.TryAdd(path, file);
- _fileCache[path] = file;
- }
- else
+ var file = _fileSystem.GetFileInfo(path);
+ if (file.Exists)
{
- return null;
+ result = file;
+ _fileCache.TryAdd(path, result);
}
}
- return file;
- //return _fileSystem.GetFileInfo(path);
+ return result;
}
- public List<string> GetFilePaths(string path)
- {
- return GetFilePaths(path, false);
- }
+ public IReadOnlyList<string> GetFilePaths(string path)
+ => GetFilePaths(path, false);
- public List<string> GetFilePaths(string path, bool clearCache)
+ public IReadOnlyList<string> GetFilePaths(string path, bool clearCache, bool sort = false)
{
- if (clearCache || !_filePathCache.TryGetValue(path, out List<string> result))
+ if (clearCache)
{
- result = _fileSystem.GetFilePaths(path).ToList();
+ _filePathCache.TryRemove(path, out _);
+ }
- _filePathCache[path] = result;
+ var filePaths = _filePathCache.GetOrAdd(path, (p, fileSystem) => fileSystem.GetFilePaths(p).ToList(), _fileSystem);
+
+ if (sort)
+ {
+ filePaths.Sort();
}
- return result;
+ return filePaths;
}
-
}
}
diff --git a/MediaBrowser.Controller/Providers/DynamicImageInfo.cs b/MediaBrowser.Controller/Providers/DynamicImageInfo.cs
deleted file mode 100644
index 0791783c6..000000000
--- a/MediaBrowser.Controller/Providers/DynamicImageInfo.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Controller.Providers
-{
- public class DynamicImageInfo
- {
- public string ImageId { get; set; }
- public ImageType Type { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Providers/DynamicImageResponse.cs b/MediaBrowser.Controller/Providers/DynamicImageResponse.cs
index 11c7ccbe5..66fddb0e3 100644
--- a/MediaBrowser.Controller/Providers/DynamicImageResponse.cs
+++ b/MediaBrowser.Controller/Providers/DynamicImageResponse.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using MediaBrowser.Model.Drawing;
@@ -8,9 +12,13 @@ namespace MediaBrowser.Controller.Providers
public class DynamicImageResponse
{
public string Path { get; set; }
+
public MediaProtocol Protocol { get; set; }
+
public Stream Stream { get; set; }
+
public ImageFormat Format { get; set; }
+
public bool HasImage { get; set; }
public void SetFormatFromMimeType(string mimeType)
diff --git a/MediaBrowser.Controller/Providers/EpisodeInfo.cs b/MediaBrowser.Controller/Providers/EpisodeInfo.cs
index 6ecf4edc5..b59a03738 100644
--- a/MediaBrowser.Controller/Providers/EpisodeInfo.cs
+++ b/MediaBrowser.Controller/Providers/EpisodeInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA2227, CS1591
+
using System;
using System.Collections.Generic;
@@ -5,16 +9,17 @@ namespace MediaBrowser.Controller.Providers
{
public class EpisodeInfo : ItemLookupInfo
{
+ public EpisodeInfo()
+ {
+ SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
public Dictionary<string, string> SeriesProviderIds { get; set; }
public int? IndexNumberEnd { get; set; }
public bool IsMissingEpisode { get; set; }
- public string SeriesDisplayOrder { get; set; }
- public EpisodeInfo()
- {
- SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
+ public string SeriesDisplayOrder { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/ExtraInfo.cs b/MediaBrowser.Controller/Providers/ExtraInfo.cs
deleted file mode 100644
index 413ff2e78..000000000
--- a/MediaBrowser.Controller/Providers/ExtraInfo.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Controller.Providers
-{
- public class ExtraInfo
- {
- public string Path { get; set; }
-
- public LocationType LocationType { get; set; }
-
- public bool IsDownloadable { get; set; }
-
- public ExtraType ExtraType { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Providers/ExtraSource.cs b/MediaBrowser.Controller/Providers/ExtraSource.cs
deleted file mode 100644
index 46b246fbc..000000000
--- a/MediaBrowser.Controller/Providers/ExtraSource.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace MediaBrowser.Controller.Providers
-{
- public enum ExtraSource
- {
- Local = 1,
- Metadata = 2,
- Remote = 3
- }
-}
diff --git a/MediaBrowser.Controller/Providers/ICustomMetadataProvider.cs b/MediaBrowser.Controller/Providers/ICustomMetadataProvider.cs
index 2d5a0b364..32a9cbef2 100644
--- a/MediaBrowser.Controller/Providers/ICustomMetadataProvider.cs
+++ b/MediaBrowser.Controller/Providers/ICustomMetadataProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -13,7 +15,7 @@ namespace MediaBrowser.Controller.Providers
where TItemType : BaseItem
{
/// <summary>
- /// Fetches the asynchronous.
+ /// Fetches the metadata asynchronously.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="options">The options.</param>
diff --git a/MediaBrowser.Controller/Providers/IDirectoryService.cs b/MediaBrowser.Controller/Providers/IDirectoryService.cs
index 8059d2bd1..48d627691 100644
--- a/MediaBrowser.Controller/Providers/IDirectoryService.cs
+++ b/MediaBrowser.Controller/Providers/IDirectoryService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CA1002, CA1819, CS1591
+
using System.Collections.Generic;
using MediaBrowser.Model.IO;
@@ -6,10 +8,13 @@ namespace MediaBrowser.Controller.Providers
public interface IDirectoryService
{
FileSystemMetadata[] GetFileSystemEntries(string path);
+
List<FileSystemMetadata> GetFiles(string path);
- FileSystemMetadata GetFile(string path);
- List<string> GetFilePaths(string path);
- List<string> GetFilePaths(string path, bool clearCache);
+ FileSystemMetadata? GetFile(string path);
+
+ IReadOnlyList<string> GetFilePaths(string path);
+
+ IReadOnlyList<string> GetFilePaths(string path, bool clearCache, bool sort = false);
}
}
diff --git a/MediaBrowser.Controller/Providers/IDynamicImageProvider.cs b/MediaBrowser.Controller/Providers/IDynamicImageProvider.cs
index dec327d66..ab66462fa 100644
--- a/MediaBrowser.Controller/Providers/IDynamicImageProvider.cs
+++ b/MediaBrowser.Controller/Providers/IDynamicImageProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
diff --git a/MediaBrowser.Controller/Providers/IExternalId.cs b/MediaBrowser.Controller/Providers/IExternalId.cs
index d7e337bda..0d847520d 100644
--- a/MediaBrowser.Controller/Providers/IExternalId.cs
+++ b/MediaBrowser.Controller/Providers/IExternalId.cs
@@ -1,15 +1,45 @@
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
namespace MediaBrowser.Controller.Providers
{
+ /// <summary>
+ /// Represents an identifier for an external provider.
+ /// </summary>
public interface IExternalId
{
- string Name { get; }
+ /// <summary>
+ /// Gets the display name of the provider associated with this ID type.
+ /// </summary>
+ string ProviderName { get; }
+ /// <summary>
+ /// Gets the unique key to distinguish this provider/type pair. This should be unique across providers.
+ /// </summary>
+ // TODO: This property is not actually unique across the concrete types at the moment. It should be updated to be unique.
string Key { get; }
- string UrlFormatString { get; }
+ /// <summary>
+ /// Gets the specific media type for this id. This is used to distinguish between the different
+ /// external id types for providers with multiple ids.
+ /// A null value indicates there is no specific media type associated with the external id, or this is the
+ /// default id for the external provider so there is no need to specify a type.
+ /// </summary>
+ /// <remarks>
+ /// This can be used along with the <see cref="ProviderName"/> to localize the external id on the client.
+ /// </remarks>
+ ExternalIdMediaType? Type { get; }
+ /// <summary>
+ /// Gets the URL format string for this id.
+ /// </summary>
+ string? UrlFormatString { get; }
+
+ /// <summary>
+ /// Determines whether this id supports a given item type.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <returns>True if this item is supported, otherwise false.</returns>
bool Supports(IHasProviderIds item);
}
}
diff --git a/MediaBrowser.Controller/Providers/IExtrasProvider.cs b/MediaBrowser.Controller/Providers/IExtrasProvider.cs
deleted file mode 100644
index fa31635cb..000000000
--- a/MediaBrowser.Controller/Providers/IExtrasProvider.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using MediaBrowser.Controller.Entities;
-
-namespace MediaBrowser.Controller.Providers
-{
- public interface IExtrasProvider
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
-
- /// <summary>
- /// Supportses the specified item.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- bool Supports(BaseItem item);
- }
-}
diff --git a/MediaBrowser.Controller/Providers/IForcedProvider.cs b/MediaBrowser.Controller/Providers/IForcedProvider.cs
index 35fa29d94..5ae4a56ef 100644
--- a/MediaBrowser.Controller/Providers/IForcedProvider.cs
+++ b/MediaBrowser.Controller/Providers/IForcedProvider.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// This is a marker interface that will cause a provider to run even if IsLocked=true
+ /// This is a marker interface that will cause a provider to run even if an item is locked from changes.
/// </summary>
public interface IForcedProvider
{
diff --git a/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs b/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs
index 68acb3910..a0e20e312 100644
--- a/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs
+++ b/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Providers
diff --git a/MediaBrowser.Controller/Providers/IHasLookupInfo.cs b/MediaBrowser.Controller/Providers/IHasLookupInfo.cs
index 4c0c38442..42cb52371 100644
--- a/MediaBrowser.Controller/Providers/IHasLookupInfo.cs
+++ b/MediaBrowser.Controller/Providers/IHasLookupInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public interface IHasLookupInfo<out TLookupInfoType>
diff --git a/MediaBrowser.Controller/Providers/IHasOrder.cs b/MediaBrowser.Controller/Providers/IHasOrder.cs
index a3db61225..9fde0e695 100644
--- a/MediaBrowser.Controller/Providers/IHasOrder.cs
+++ b/MediaBrowser.Controller/Providers/IHasOrder.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public interface IHasOrder
diff --git a/MediaBrowser.Controller/Providers/IImageEnhancer.cs b/MediaBrowser.Controller/Providers/IImageEnhancer.cs
deleted file mode 100644
index c27c00ca2..000000000
--- a/MediaBrowser.Controller/Providers/IImageEnhancer.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Controller.Providers
-{
- public interface IImageEnhancer
- {
- /// <summary>
- /// Return true only if the given image for the given item will be enhanced by this enhancer.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <returns><c>true</c> if this enhancer will enhance the supplied image for the supplied item, <c>false</c> otherwise</returns>
- bool Supports(BaseItem item, ImageType imageType);
-
- /// <summary>
- /// Gets the priority or order in which this enhancer should be run.
- /// </summary>
- /// <value>The priority.</value>
- MetadataProviderPriority Priority { get; }
-
- /// <summary>
- /// Return a key incorporating all configuration information related to this item
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <returns>Cache key relating to the current state of this item and configuration</returns>
- string GetConfigurationCacheKey(BaseItem item, ImageType imageType);
-
- /// <summary>
- /// Gets the size of the enhanced image.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <param name="originalImageSize">Size of the original image.</param>
- /// <returns>ImageSize.</returns>
- ImageDimensions GetEnhancedImageSize(BaseItem item, ImageType imageType, int imageIndex, ImageDimensions originalImageSize);
-
- EnhancedImageInfo GetEnhancedImageInfo(BaseItem item, string inputFile, ImageType imageType, int imageIndex);
-
- /// <summary>
- /// Enhances the image async.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="inputFile">The input file.</param>
- /// <param name="outputFile">The output file.</param>
- /// <param name="imageType">Type of the image.</param>
- /// <param name="imageIndex">Index of the image.</param>
- /// <returns>Task{Image}.</returns>
- /// <exception cref="System.ArgumentNullException"></exception>
- Task EnhanceImageAsync(BaseItem item, string inputFile, string outputFile, ImageType imageType, int imageIndex);
- }
-
- public class EnhancedImageInfo
- {
- public bool RequiresTransparency { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Providers/IImageProvider.cs b/MediaBrowser.Controller/Providers/IImageProvider.cs
index 2df3d5ff8..29ab323f8 100644
--- a/MediaBrowser.Controller/Providers/IImageProvider.cs
+++ b/MediaBrowser.Controller/Providers/IImageProvider.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// Interface IImageProvider
+ /// Interface IImageProvider.
/// </summary>
public interface IImageProvider
{
@@ -14,10 +14,10 @@ namespace MediaBrowser.Controller.Providers
string Name { get; }
/// <summary>
- /// Supportses the specified item.
+ /// Supports the specified item.
/// </summary>
/// <param name="item">The item.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
+ /// <returns><c>true</c> if the provider supports the item.</returns>
bool Supports(BaseItem item);
}
}
diff --git a/MediaBrowser.Controller/Providers/ILocalImageFileProvider.cs b/MediaBrowser.Controller/Providers/ILocalImageFileProvider.cs
deleted file mode 100644
index 72bc56390..000000000
--- a/MediaBrowser.Controller/Providers/ILocalImageFileProvider.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Controller.Entities;
-
-namespace MediaBrowser.Controller.Providers
-{
- public interface ILocalImageFileProvider : ILocalImageProvider
- {
- List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService);
- }
-}
diff --git a/MediaBrowser.Controller/Providers/ILocalImageProvider.cs b/MediaBrowser.Controller/Providers/ILocalImageProvider.cs
index 09aaab3de..f78bd6ddf 100644
--- a/MediaBrowser.Controller/Providers/ILocalImageProvider.cs
+++ b/MediaBrowser.Controller/Providers/ILocalImageProvider.cs
@@ -1,9 +1,15 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using MediaBrowser.Controller.Entities;
+
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// This is just a marker interface
+ /// This is just a marker interface.
/// </summary>
public interface ILocalImageProvider : IImageProvider
{
+ IEnumerable<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService);
}
}
diff --git a/MediaBrowser.Controller/Providers/ILocalMetadataProvider.cs b/MediaBrowser.Controller/Providers/ILocalMetadataProvider.cs
index 2a2c379f6..e771c881d 100644
--- a/MediaBrowser.Controller/Providers/ILocalMetadataProvider.cs
+++ b/MediaBrowser.Controller/Providers/ILocalMetadataProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -17,8 +19,9 @@ namespace MediaBrowser.Controller.Providers
/// <param name="info">The information.</param>
/// <param name="directoryService">The directory service.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{MetadataResult{`0}}.</returns>
- Task<MetadataResult<TItemType>> GetMetadata(ItemInfo info,
+ /// <returns>Task{MetadataResult{0}}.</returns>
+ Task<MetadataResult<TItemType>> GetMetadata(
+ ItemInfo info,
IDirectoryService directoryService,
CancellationToken cancellationToken);
}
diff --git a/MediaBrowser.Controller/Providers/IMetadataProvider.cs b/MediaBrowser.Controller/Providers/IMetadataProvider.cs
index 3e595ff93..1a87e0625 100644
--- a/MediaBrowser.Controller/Providers/IMetadataProvider.cs
+++ b/MediaBrowser.Controller/Providers/IMetadataProvider.cs
@@ -1,9 +1,11 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// Marker interface
+ /// Marker interface.
/// </summary>
public interface IMetadataProvider
{
diff --git a/MediaBrowser.Controller/Providers/IMetadataService.cs b/MediaBrowser.Controller/Providers/IMetadataService.cs
index 49f6a7830..05fbb18ee 100644
--- a/MediaBrowser.Controller/Providers/IMetadataService.cs
+++ b/MediaBrowser.Controller/Providers/IMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -9,11 +11,18 @@ namespace MediaBrowser.Controller.Providers
public interface IMetadataService
{
/// <summary>
+ /// Gets the order.
+ /// </summary>
+ /// <value>The order.</value>
+ int Order { get; }
+
+ /// <summary>
/// Determines whether this instance can refresh the specified item.
/// </summary>
/// <param name="item">The item.</param>
- /// <returns><c>true</c> if this instance can refresh the specified item; otherwise, <c>false</c>.</returns>
+ /// <returns><c>true</c> if this instance can refresh the specified item.</returns>
bool CanRefresh(BaseItem item);
+
bool CanRefreshPrimary(Type type);
/// <summary>
@@ -24,11 +33,5 @@ namespace MediaBrowser.Controller.Providers
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken);
-
- /// <summary>
- /// Gets the order.
- /// </summary>
- /// <value>The order.</value>
- int Order { get; }
}
}
diff --git a/MediaBrowser.Controller/Providers/IPreRefreshProvider.cs b/MediaBrowser.Controller/Providers/IPreRefreshProvider.cs
index 058010e1a..6d98af33e 100644
--- a/MediaBrowser.Controller/Providers/IPreRefreshProvider.cs
+++ b/MediaBrowser.Controller/Providers/IPreRefreshProvider.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public interface IPreRefreshProvider : ICustomMetadataProvider
{
-
}
}
diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs
index 925ace895..9f7a76be6 100644
--- a/MediaBrowser.Controller/Providers/IProviderManager.cs
+++ b/MediaBrowser.Controller/Providers/IProviderManager.cs
@@ -1,26 +1,39 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Providers;
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// Interface IProviderManager
+ /// Interface IProviderManager.
/// </summary>
public interface IProviderManager
{
+ event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted;
+
+ event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted;
+
+ event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress;
+
/// <summary>
/// Queues the refresh.
/// </summary>
+ /// <param name="itemId">Item ID.</param>
+ /// <param name="options">MetadataRefreshOptions for operation.</param>
+ /// <param name="priority">RefreshPriority for operation.</param>
void QueueRefresh(Guid itemId, MetadataRefreshOptions options, RefreshPriority priority);
/// <summary>
@@ -42,6 +55,14 @@ namespace MediaBrowser.Controller.Providers
Task<ItemUpdateType> RefreshSingleItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken);
/// <summary>
+ /// Runs multiple metadata refreshes concurrently.
+ /// </summary>
+ /// <param name="action">The action to run.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
+ Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken);
+
+ /// <summary>
/// Saves the image.
/// </summary>
/// <param name="item">The item.</param>
@@ -67,14 +88,31 @@ namespace MediaBrowser.Controller.Providers
/// <summary>
/// Saves the image.
/// </summary>
+ /// <param name="item">Image to save.</param>
+ /// <param name="source">Source of image.</param>
+ /// <param name="mimeType">Mime type image.</param>
+ /// <param name="type">Type of image.</param>
+ /// <param name="imageIndex">Index of image.</param>
+ /// <param name="saveLocallyWithMedia">Option to save locally.</param>
+ /// <param name="cancellationToken">CancellationToken to use with operation.</param>
/// <returns>Task.</returns>
Task SaveImage(BaseItem item, string source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken);
+ Task SaveImage(Stream source, string mimeType, string path);
+
/// <summary>
/// Adds the metadata providers.
/// </summary>
- void AddParts(IEnumerable<IImageProvider> imageProviders, IEnumerable<IMetadataService> metadataServices, IEnumerable<IMetadataProvider> metadataProviders,
- IEnumerable<IMetadataSaver> savers,
+ /// <param name="imageProviders">Image providers to use.</param>
+ /// <param name="metadataServices">Metadata services to use.</param>
+ /// <param name="metadataProviders">Metadata providers to use.</param>
+ /// <param name="metadataSavers">Metadata savers to use.</param>
+ /// <param name="externalIds">External IDs to use.</param>
+ void AddParts(
+ IEnumerable<IImageProvider> imageProviders,
+ IEnumerable<IMetadataService> metadataServices,
+ IEnumerable<IMetadataProvider> metadataProviders,
+ IEnumerable<IMetadataSaver> metadataSavers,
IEnumerable<IExternalId> externalIds);
/// <summary>
@@ -118,12 +156,14 @@ namespace MediaBrowser.Controller.Providers
/// </summary>
/// <param name="item">The item.</param>
/// <param name="updateType">Type of the update.</param>
- /// <returns>Task.</returns>
void SaveMetadata(BaseItem item, ItemUpdateType updateType);
/// <summary>
/// Saves the metadata.
/// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="updateType">Type of the update.</param>
+ /// <param name="savers">The metadata savers.</param>
void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<string> savers);
/// <summary>
@@ -154,25 +194,16 @@ namespace MediaBrowser.Controller.Providers
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> GetSearchImage(string providerName, string url, CancellationToken cancellationToken);
+ Task<HttpResponseMessage> GetSearchImage(string providerName, string url, CancellationToken cancellationToken);
Dictionary<Guid, Guid> GetRefreshQueue();
void OnRefreshStart(BaseItem item);
+
void OnRefreshProgress(BaseItem item, double progress);
+
void OnRefreshComplete(BaseItem item);
double? GetRefreshProgress(Guid id);
-
- event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted;
- event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted;
- event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress;
- }
-
- public enum RefreshPriority
- {
- High = 0,
- Normal = 1,
- Low = 2
}
}
diff --git a/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs b/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs
index e56bba3e3..de1631dcf 100644
--- a/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs
+++ b/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs
@@ -1,7 +1,7 @@
using System.Collections.Generic;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
@@ -9,7 +9,7 @@ using MediaBrowser.Model.Providers;
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// Interface IImageProvider
+ /// Interface IImageProvider.
/// </summary>
public interface IRemoteImageProvider : IImageProvider
{
@@ -34,6 +34,6 @@ namespace MediaBrowser.Controller.Providers
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken);
+ Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Providers/IRemoteMetadataProvider.cs b/MediaBrowser.Controller/Providers/IRemoteMetadataProvider.cs
index c143b15cd..f146decb6 100644
--- a/MediaBrowser.Controller/Providers/IRemoteMetadataProvider.cs
+++ b/MediaBrowser.Controller/Providers/IRemoteMetadataProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
diff --git a/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs b/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs
index fdb0c8eb5..e401ed211 100644
--- a/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs
+++ b/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs
@@ -1,6 +1,8 @@
+#pragma warning disable CS1591
+
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
namespace MediaBrowser.Controller.Providers
{
@@ -12,6 +14,6 @@ namespace MediaBrowser.Controller.Providers
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
- Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken);
+ Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
index aac41369c..2ac4c728b 100644
--- a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
+++ b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
using System;
using System.Linq;
using MediaBrowser.Model.Entities;
@@ -6,14 +10,6 @@ namespace MediaBrowser.Controller.Providers
{
public class ImageRefreshOptions
{
- public MetadataRefreshMode ImageRefreshMode { get; set; }
- public IDirectoryService DirectoryService { get; private set; }
-
- public bool ReplaceAllImages { get; set; }
-
- public ImageType[] ReplaceImages { get; set; }
- public bool IsAutomated { get; set; }
-
public ImageRefreshOptions(IDirectoryService directoryService)
{
ImageRefreshMode = MetadataRefreshMode.Default;
@@ -23,6 +19,16 @@ namespace MediaBrowser.Controller.Providers
IsAutomated = true;
}
+ public MetadataRefreshMode ImageRefreshMode { get; set; }
+
+ public IDirectoryService DirectoryService { get; private set; }
+
+ public bool ReplaceAllImages { get; set; }
+
+ public ImageType[] ReplaceImages { get; set; }
+
+ public bool IsAutomated { get; set; }
+
public bool IsReplacingImage(ImageType type)
{
return ImageRefreshMode == MetadataRefreshMode.FullRefresh &&
diff --git a/MediaBrowser.Controller/Providers/ItemInfo.cs b/MediaBrowser.Controller/Providers/ItemInfo.cs
index f29a8aa70..b8dd416a2 100644
--- a/MediaBrowser.Controller/Providers/ItemInfo.cs
+++ b/MediaBrowser.Controller/Providers/ItemInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
@@ -12,8 +16,7 @@ namespace MediaBrowser.Controller.Providers
ContainingFolderPath = item.ContainingFolderPath;
IsInMixedFolder = item.IsInMixedFolder;
- var video = item as Video;
- if (video != null)
+ if (item is Video video)
{
VideoType = video.VideoType;
IsPlaceHolder = video.IsPlaceHolder;
@@ -23,10 +26,15 @@ namespace MediaBrowser.Controller.Providers
}
public Type ItemType { get; set; }
+
public string Path { get; set; }
+
public string ContainingFolderPath { get; set; }
+
public VideoType VideoType { get; set; }
+
public bool IsInMixedFolder { get; set; }
+
public bool IsPlaceHolder { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
index 0aaab9a94..460f4e500 100644
--- a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
+++ b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA2227, CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Entities;
@@ -6,40 +10,60 @@ namespace MediaBrowser.Controller.Providers
{
public class ItemLookupInfo : IHasProviderIds
{
+ public ItemLookupInfo()
+ {
+ IsAutomated = true;
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the original title.
+ /// </summary>
+ /// <value>The original title of the item.</value>
+ public string OriginalTitle { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path.
+ /// </summary>
+ /// <value>The path.</value>
+ public string Path { get; set; }
+
/// <summary>
/// Gets or sets the metadata language.
/// </summary>
/// <value>The metadata language.</value>
public string MetadataLanguage { get; set; }
+
/// <summary>
/// Gets or sets the metadata country code.
/// </summary>
/// <value>The metadata country code.</value>
public string MetadataCountryCode { get; set; }
+
/// <summary>
/// Gets or sets the provider ids.
/// </summary>
/// <value>The provider ids.</value>
public Dictionary<string, string> ProviderIds { get; set; }
+
/// <summary>
/// Gets or sets the year.
/// </summary>
/// <value>The year.</value>
public int? Year { get; set; }
+
public int? IndexNumber { get; set; }
+
public int? ParentIndexNumber { get; set; }
+
public DateTime? PremiereDate { get; set; }
- public bool IsAutomated { get; set; }
- public ItemLookupInfo()
- {
- IsAutomated = true;
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
+ public bool IsAutomated { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/LocalImageInfo.cs b/MediaBrowser.Controller/Providers/LocalImageInfo.cs
index 24cded79b..a8e70e6d0 100644
--- a/MediaBrowser.Controller/Providers/LocalImageInfo.cs
+++ b/MediaBrowser.Controller/Providers/LocalImageInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
@@ -6,6 +10,7 @@ namespace MediaBrowser.Controller.Providers
public class LocalImageInfo
{
public FileSystemMetadata FileInfo { get; set; }
+
public ImageType Type { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/MetadataProviderPriority.cs b/MediaBrowser.Controller/Providers/MetadataProviderPriority.cs
deleted file mode 100644
index 0076bb972..000000000
--- a/MediaBrowser.Controller/Providers/MetadataProviderPriority.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace MediaBrowser.Controller.Providers
-{
- /// <summary>
- /// Determines when a provider should execute, relative to others
- /// </summary>
- public enum MetadataProviderPriority
- {
- // Run this provider at the beginning
- /// <summary>
- /// The first
- /// </summary>
- First = 1,
-
- // Run this provider after all first priority providers
- /// <summary>
- /// The second
- /// </summary>
- Second = 2,
-
- // Run this provider after all second priority providers
- /// <summary>
- /// The third
- /// </summary>
- Third = 3,
-
- /// <summary>
- /// The fourth
- /// </summary>
- Fourth = 4,
-
- Fifth = 5,
-
- // Run this provider last
- /// <summary>
- /// The last
- /// </summary>
- Last = 999
- }
-}
diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshMode.cs b/MediaBrowser.Controller/Providers/MetadataRefreshMode.cs
index 02152ee33..920e3da5b 100644
--- a/MediaBrowser.Controller/Providers/MetadataRefreshMode.cs
+++ b/MediaBrowser.Controller/Providers/MetadataRefreshMode.cs
@@ -1,24 +1,26 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public enum MetadataRefreshMode
{
/// <summary>
- /// The none
+ /// The none.
/// </summary>
None = 0,
/// <summary>
- /// The validation only
+ /// The validation only.
/// </summary>
ValidationOnly = 1,
/// <summary>
- /// Providers will be executed based on default rules
+ /// Providers will be executed based on default rules.
/// </summary>
Default = 2,
/// <summary>
- /// All providers will be executed to search for new metadata
+ /// All providers will be executed to search for new metadata.
/// </summary>
FullRefresh = 3
}
diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
index b3eb8cdd1..a42c7f8b5 100644
--- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
+++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1819, CS1591
+
using System;
using System.Linq;
using MediaBrowser.Controller.Entities;
@@ -7,19 +11,6 @@ namespace MediaBrowser.Controller.Providers
{
public class MetadataRefreshOptions : ImageRefreshOptions
{
- /// <summary>
- /// When paired with MetadataRefreshMode=FullRefresh, all existing data will be overwritten with new data from the providers.
- /// </summary>
- public bool ReplaceAllMetadata { get; set; }
-
- public MetadataRefreshMode MetadataRefreshMode { get; set; }
- public RemoteSearchResult SearchResult { get; set; }
-
- public string[] RefreshPaths { get; set; }
-
- public bool ForceSave { get; set; }
- public bool EnableRemoteContentProbe { get; set; }
-
public MetadataRefreshOptions(IDirectoryService directoryService)
: base(directoryService)
{
@@ -41,15 +32,28 @@ namespace MediaBrowser.Controller.Providers
if (copy.RefreshPaths != null && copy.RefreshPaths.Length > 0)
{
- if (RefreshPaths == null)
- {
- RefreshPaths = Array.Empty<string>();
- }
+ RefreshPaths ??= Array.Empty<string>();
RefreshPaths = copy.RefreshPaths.ToArray();
}
}
+ /// <summary>
+ /// Gets or sets a value indicating whether all existing data should be overwritten with new data from providers
+ /// when paired with MetadataRefreshMode=FullRefresh.
+ /// </summary>
+ public bool ReplaceAllMetadata { get; set; }
+
+ public MetadataRefreshMode MetadataRefreshMode { get; set; }
+
+ public RemoteSearchResult SearchResult { get; set; }
+
+ public string[] RefreshPaths { get; set; }
+
+ public bool ForceSave { get; set; }
+
+ public bool EnableRemoteContentProbe { get; set; }
+
public bool RefreshItem(BaseItem item)
{
if (RefreshPaths != null && RefreshPaths.Length > 0)
diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs
index f4b915c06..2085ae4ad 100644
--- a/MediaBrowser.Controller/Providers/MetadataResult.cs
+++ b/MediaBrowser.Controller/Providers/MetadataResult.cs
@@ -1,39 +1,61 @@
+#nullable disable
+
+#pragma warning disable CA1002, CA2227, CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Providers
{
public class MetadataResult<T>
{
- public List<LocalImageInfo> Images { get; set; }
- public List<UserItemData> UserDataList { get; set; }
+ // Images aren't always used so the allocation is a waste a lot of the time
+ private List<LocalImageInfo> _images;
+ private List<(string url, ImageType type)> _remoteImages;
public MetadataResult()
{
- Images = new List<LocalImageInfo>();
ResultLanguage = "en";
}
+ public List<LocalImageInfo> Images
+ {
+ get => _images ??= new List<LocalImageInfo>();
+ set => _images = value;
+ }
+
+ public List<(string url, ImageType type)> RemoteImages
+ {
+ get => _remoteImages ??= new List<(string url, ImageType type)>();
+ set => _remoteImages = value;
+ }
+
+ public List<UserItemData> UserDataList { get; set; }
+
public List<PersonInfo> People { get; set; }
public bool HasMetadata { get; set; }
+
public T Item { get; set; }
+
public string ResultLanguage { get; set; }
+
public string Provider { get; set; }
+
public bool QueriedById { get; set; }
+
public void AddPerson(PersonInfo p)
{
- if (People == null)
- {
- People = new List<PersonInfo>();
- }
+ People ??= new List<PersonInfo>();
PeopleHelper.AddPerson(People, p);
}
/// <summary>
- /// Not only does this clear, but initializes the list so that services can differentiate between a null list and zero people
+ /// Not only does this clear, but initializes the list so that services can differentiate between a null list and zero people.
/// </summary>
public void ResetPeople()
{
@@ -41,21 +63,21 @@ namespace MediaBrowser.Controller.Providers
{
People = new List<PersonInfo>();
}
- People.Clear();
+ else
+ {
+ People.Clear();
+ }
}
public UserItemData GetOrAddUserData(string userId)
{
- if (UserDataList == null)
- {
- UserDataList = new List<UserItemData>();
- }
+ UserDataList ??= new List<UserItemData>();
UserItemData userData = null;
foreach (var i in UserDataList)
{
- if (string.Equals(userId, i.UserId.ToString("N"), StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(userId, i.UserId.ToString("N", CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase))
{
userData = i;
}
diff --git a/MediaBrowser.Controller/Providers/MovieInfo.cs b/MediaBrowser.Controller/Providers/MovieInfo.cs
index c9a766fe7..20e6b697a 100644
--- a/MediaBrowser.Controller/Providers/MovieInfo.cs
+++ b/MediaBrowser.Controller/Providers/MovieInfo.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class MovieInfo : ItemLookupInfo
{
-
}
}
diff --git a/MediaBrowser.Controller/Providers/MusicVideoInfo.cs b/MediaBrowser.Controller/Providers/MusicVideoInfo.cs
index 194b26484..322320abd 100644
--- a/MediaBrowser.Controller/Providers/MusicVideoInfo.cs
+++ b/MediaBrowser.Controller/Providers/MusicVideoInfo.cs
@@ -1,7 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+
namespace MediaBrowser.Controller.Providers
{
public class MusicVideoInfo : ItemLookupInfo
{
- public string[] Artists { get; set; }
+ public IReadOnlyList<string> Artists { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/PersonLookupInfo.cs b/MediaBrowser.Controller/Providers/PersonLookupInfo.cs
index 3fa6e50b7..11cb71f90 100644
--- a/MediaBrowser.Controller/Providers/PersonLookupInfo.cs
+++ b/MediaBrowser.Controller/Providers/PersonLookupInfo.cs
@@ -1,7 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class PersonLookupInfo : ItemLookupInfo
{
-
}
}
diff --git a/MediaBrowser.Controller/Providers/RefreshPriority.cs b/MediaBrowser.Controller/Providers/RefreshPriority.cs
new file mode 100644
index 000000000..3619f679d
--- /dev/null
+++ b/MediaBrowser.Controller/Providers/RefreshPriority.cs
@@ -0,0 +1,23 @@
+namespace MediaBrowser.Controller.Providers
+{
+ /// <summary>
+ /// Provider refresh priority.
+ /// </summary>
+ public enum RefreshPriority
+ {
+ /// <summary>
+ /// High priority.
+ /// </summary>
+ High = 0,
+
+ /// <summary>
+ /// Normal priority.
+ /// </summary>
+ Normal = 1,
+
+ /// <summary>
+ /// Low priority.
+ /// </summary>
+ Low = 2
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs
index 078125673..d4df5fa0d 100644
--- a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs
+++ b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Providers
@@ -10,14 +14,14 @@ namespace MediaBrowser.Controller.Providers
public Guid ItemId { get; set; }
/// <summary>
- /// If set will only search within the given provider
+ /// Gets or sets the provider name to search within if set.
/// </summary>
public string SearchProviderName { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether [include disabled providers].
+ /// Gets or sets a value indicating whether disabled providers should be included.
/// </summary>
- /// <value><c>true</c> if [include disabled providers]; otherwise, <c>false</c>.</value>
+ /// <value><c>true</c> if disabled providers should be included.</value>
public bool IncludeDisabledProviders { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/SeasonInfo.cs b/MediaBrowser.Controller/Providers/SeasonInfo.cs
index dd2ef9ad7..1edceb0e4 100644
--- a/MediaBrowser.Controller/Providers/SeasonInfo.cs
+++ b/MediaBrowser.Controller/Providers/SeasonInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CA2227, CS1591
+
using System;
using System.Collections.Generic;
@@ -5,11 +7,11 @@ namespace MediaBrowser.Controller.Providers
{
public class SeasonInfo : ItemLookupInfo
{
- public Dictionary<string, string> SeriesProviderIds { get; set; }
-
public SeasonInfo()
{
SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
+
+ public Dictionary<string, string> SeriesProviderIds { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/SeriesInfo.cs b/MediaBrowser.Controller/Providers/SeriesInfo.cs
index 6c206e031..976fa175a 100644
--- a/MediaBrowser.Controller/Providers/SeriesInfo.cs
+++ b/MediaBrowser.Controller/Providers/SeriesInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class SeriesInfo : ItemLookupInfo
diff --git a/MediaBrowser.Controller/Providers/SongInfo.cs b/MediaBrowser.Controller/Providers/SongInfo.cs
index 61e950130..4b64a8a98 100644
--- a/MediaBrowser.Controller/Providers/SongInfo.cs
+++ b/MediaBrowser.Controller/Providers/SongInfo.cs
@@ -1,17 +1,24 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Controller.Providers
{
public class SongInfo : ItemLookupInfo
{
- public string[] AlbumArtists { get; set; }
- public string Album { get; set; }
- public string[] Artists { get; set; }
-
public SongInfo()
{
Artists = Array.Empty<string>();
AlbumArtists = Array.Empty<string>();
}
+
+ public IReadOnlyList<string> AlbumArtists { get; set; }
+
+ public string Album { get; set; }
+
+ public IReadOnlyList<string> Artists { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Providers/TrailerInfo.cs b/MediaBrowser.Controller/Providers/TrailerInfo.cs
index 13f07562d..630850f9d 100644
--- a/MediaBrowser.Controller/Providers/TrailerInfo.cs
+++ b/MediaBrowser.Controller/Providers/TrailerInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Controller.Providers
{
public class TrailerInfo : ItemLookupInfo
diff --git a/MediaBrowser.Controller/Providers/VideoContentType.cs b/MediaBrowser.Controller/Providers/VideoContentType.cs
index c3b8964a3..49d587f6c 100644
--- a/MediaBrowser.Controller/Providers/VideoContentType.cs
+++ b/MediaBrowser.Controller/Providers/VideoContentType.cs
@@ -1,17 +1,17 @@
namespace MediaBrowser.Controller.Providers
{
/// <summary>
- /// Enum VideoContentType
+ /// Enum VideoContentType.
/// </summary>
public enum VideoContentType
{
/// <summary>
- /// The episode
+ /// The episode.
/// </summary>
Episode = 0,
/// <summary>
- /// The movie
+ /// The movie.
/// </summary>
Movie = 1
}
diff --git a/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs b/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs
new file mode 100644
index 000000000..ec3706773
--- /dev/null
+++ b/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs
@@ -0,0 +1,48 @@
+using System;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.QuickConnect;
+
+namespace MediaBrowser.Controller.QuickConnect
+{
+ /// <summary>
+ /// Quick connect standard interface.
+ /// </summary>
+ public interface IQuickConnect
+ {
+ /// <summary>
+ /// Gets a value indicating whether quick connect is enabled or not.
+ /// </summary>
+ bool IsEnabled { get; }
+
+ /// <summary>
+ /// Initiates a new quick connect request.
+ /// </summary>
+ /// <param name="authorizationInfo">The initiator authorization info.</param>
+ /// <returns>A quick connect result with tokens to proceed or throws an exception if not active.</returns>
+ QuickConnectResult TryConnect(AuthorizationInfo authorizationInfo);
+
+ /// <summary>
+ /// Checks the status of an individual request.
+ /// </summary>
+ /// <param name="secret">Unique secret identifier of the request.</param>
+ /// <returns>Quick connect result.</returns>
+ QuickConnectResult CheckRequestStatus(string secret);
+
+ /// <summary>
+ /// Authorizes a quick connect request to connect as the calling user.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="code">Identifying code for the request.</param>
+ /// <returns>A boolean indicating if the authorization completed successfully.</returns>
+ Task<bool> AuthorizeRequest(Guid userId, string code);
+
+ /// <summary>
+ /// Gets the authorized request for the secret.
+ /// </summary>
+ /// <param name="secret">The secret.</param>
+ /// <returns>The authentication result.</returns>
+ AuthenticationResult GetAuthorizedRequest(string secret);
+ }
+}
diff --git a/MediaBrowser.Controller/Resolvers/IItemResolver.cs b/MediaBrowser.Controller/Resolvers/IItemResolver.cs
index 16e37d249..b95d00aa3 100644
--- a/MediaBrowser.Controller/Resolvers/IItemResolver.cs
+++ b/MediaBrowser.Controller/Resolvers/IItemResolver.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -7,26 +9,28 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.Controller.Resolvers
{
/// <summary>
- /// Interface IItemResolver
+ /// Interface IItemResolver.
/// </summary>
public interface IItemResolver
{
/// <summary>
+ /// Gets the priority.
+ /// </summary>
+ /// <value>The priority.</value>
+ ResolverPriority Priority { get; }
+
+ /// <summary>
/// Resolves the path.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>BaseItem.</returns>
BaseItem ResolvePath(ItemResolveArgs args);
- /// <summary>
- /// Gets the priority.
- /// </summary>
- /// <value>The priority.</value>
- ResolverPriority Priority { get; }
}
public interface IMultiItemResolver
{
- MultiItemResolverResult ResolveMultiple(Folder parent,
+ MultiItemResolverResult ResolveMultiple(
+ Folder parent,
List<FileSystemMetadata> files,
string collectionType,
IDirectoryService directoryService);
@@ -34,13 +38,14 @@ namespace MediaBrowser.Controller.Resolvers
public class MultiItemResolverResult
{
- public List<BaseItem> Items { get; set; }
- public List<FileSystemMetadata> ExtraFiles { get; set; }
-
public MultiItemResolverResult()
{
Items = new List<BaseItem>();
ExtraFiles = new List<FileSystemMetadata>();
}
+
+ public List<BaseItem> Items { get; set; }
+
+ public List<FileSystemMetadata> ExtraFiles { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs b/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs
index b40cc157a..a07b3e898 100644
--- a/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs
+++ b/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs
@@ -4,10 +4,16 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.Controller.Resolvers
{
/// <summary>
- /// Provides a base "rule" that anyone can use to have paths ignored by the resolver
+ /// Provides a base "rule" that anyone can use to have paths ignored by the resolver.
/// </summary>
public interface IResolverIgnoreRule
{
+ /// <summary>
+ /// Checks whether or not the file should be 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>
bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem parent);
}
}
diff --git a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs b/MediaBrowser.Controller/Resolvers/ItemResolver.cs
index 637a7e3f0..7fd54fcc6 100644
--- a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs
+++ b/MediaBrowser.Controller/Resolvers/ItemResolver.cs
@@ -1,33 +1,35 @@
+#nullable disable
+
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
namespace MediaBrowser.Controller.Resolvers
{
/// <summary>
- /// Class ItemResolver
+ /// Class ItemResolver.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of BaseItem.</typeparam>
public abstract class ItemResolver<T> : IItemResolver
where T : BaseItem, new()
{
/// <summary>
+ /// Gets the priority.
+ /// </summary>
+ /// <value>The priority.</value>
+ public virtual ResolverPriority Priority => ResolverPriority.First;
+
+ /// <summary>
/// Resolves the specified args.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>`0.</returns>
- protected virtual T Resolve(ItemResolveArgs args)
+ public virtual T Resolve(ItemResolveArgs args)
{
return null;
}
/// <summary>
- /// Gets the priority.
- /// </summary>
- /// <value>The priority.</value>
- public virtual ResolverPriority Priority => ResolverPriority.First;
-
- /// <summary>
- /// Sets initial values on the newly resolved item
+ /// Sets initial values on the newly resolved item.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="args">The args.</param>
diff --git a/MediaBrowser.Controller/Resolvers/ResolverPriority.cs b/MediaBrowser.Controller/Resolvers/ResolverPriority.cs
index e39310095..d4f975b6d 100644
--- a/MediaBrowser.Controller/Resolvers/ResolverPriority.cs
+++ b/MediaBrowser.Controller/Resolvers/ResolverPriority.cs
@@ -1,26 +1,38 @@
namespace MediaBrowser.Controller.Resolvers
{
/// <summary>
- /// Enum ResolverPriority
+ /// Enum ResolverPriority.
/// </summary>
public enum ResolverPriority
{
/// <summary>
- /// The first
+ /// The first.
/// </summary>
First = 1,
+
/// <summary>
- /// The second
+ /// The second.
/// </summary>
Second = 2,
+
/// <summary>
- /// The third
+ /// The third.
/// </summary>
Third = 3,
+
+ /// <summary>
+ /// The Fourth.
+ /// </summary>
Fourth = 4,
+
+ /// <summary>
+ /// The Fifth.
+ /// </summary>
+ Fifth = 5,
+
/// <summary>
- /// The last
+ /// The last.
/// </summary>
- Last = 5
+ Last = 6
}
}
diff --git a/MediaBrowser.Controller/Security/AuthenticationInfo.cs b/MediaBrowser.Controller/Security/AuthenticationInfo.cs
index 828213588..b4b242f1b 100644
--- a/MediaBrowser.Controller/Security/AuthenticationInfo.cs
+++ b/MediaBrowser.Controller/Security/AuthenticationInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Security
@@ -65,6 +69,7 @@ namespace MediaBrowser.Controller.Security
public DateTime? DateRevoked { get; set; }
public DateTime DateLastActivity { get; set; }
+
public string UserName { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs b/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs
deleted file mode 100644
index 2bd17eb26..000000000
--- a/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-
-namespace MediaBrowser.Controller.Security
-{
- public class AuthenticationInfoQuery
- {
- /// <summary>
- /// Gets or sets the device identifier.
- /// </summary>
- /// <value>The device identifier.</value>
- public string DeviceId { get; set; }
-
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public Guid UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the access token.
- /// </summary>
- /// <value>The access token.</value>
- public string AccessToken { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is active.
- /// </summary>
- /// <value><c>null</c> if [is active] contains no value, <c>true</c> if [is active]; otherwise, <c>false</c>.</value>
- public bool? IsActive { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has user.
- /// </summary>
- /// <value><c>null</c> if [has user] contains no value, <c>true</c> if [has user]; otherwise, <c>false</c>.</value>
- public bool? HasUser { get; set; }
-
- /// <summary>
- /// Gets or sets the start index.
- /// </summary>
- /// <value>The start index.</value>
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// Gets or sets the limit.
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Security/IAuthenticationManager.cs b/MediaBrowser.Controller/Security/IAuthenticationManager.cs
new file mode 100644
index 000000000..e3d18c8c0
--- /dev/null
+++ b/MediaBrowser.Controller/Security/IAuthenticationManager.cs
@@ -0,0 +1,33 @@
+#nullable enable
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Controller.Security
+{
+ /// <summary>
+ /// Handles the retrieval and storage of API keys.
+ /// </summary>
+ public interface IAuthenticationManager
+ {
+ /// <summary>
+ /// Creates an API key.
+ /// </summary>
+ /// <param name="name">The name of the key.</param>
+ /// <returns>A task representing the creation of the key.</returns>
+ Task CreateApiKey(string name);
+
+ /// <summary>
+ /// Gets the API keys.
+ /// </summary>
+ /// <returns>A task representing the retrieval of the API keys.</returns>
+ Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys();
+
+ /// <summary>
+ /// Deletes an API key with the provided access token.
+ /// </summary>
+ /// <param name="accessToken">The access token.</param>
+ /// <returns>A task representing the deletion of the API key.</returns>
+ Task DeleteApiKey(string accessToken);
+ }
+}
diff --git a/MediaBrowser.Controller/Security/IAuthenticationRepository.cs b/MediaBrowser.Controller/Security/IAuthenticationRepository.cs
deleted file mode 100644
index 6a9625613..000000000
--- a/MediaBrowser.Controller/Security/IAuthenticationRepository.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using MediaBrowser.Model.Devices;
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Controller.Security
-{
- public interface IAuthenticationRepository
- {
- /// <summary>
- /// Creates the specified information.
- /// </summary>
- /// <param name="info">The information.</param>
- /// <returns>Task.</returns>
- void Create(AuthenticationInfo info);
-
- /// <summary>
- /// Updates the specified information.
- /// </summary>
- /// <param name="info">The information.</param>
- /// <returns>Task.</returns>
- void Update(AuthenticationInfo info);
-
- /// <summary>
- /// Gets the specified query.
- /// </summary>
- /// <param name="query">The query.</param>
- /// <returns>QueryResult{AuthenticationInfo}.</returns>
- QueryResult<AuthenticationInfo> Get(AuthenticationInfoQuery query);
-
- void Delete(AuthenticationInfo info);
-
- DeviceOptions GetDeviceOptions(string deviceId);
- void UpdateDeviceOptions(string deviceId, DeviceOptions options);
- }
-}
diff --git a/MediaBrowser.Controller/Security/IEncryptionManager.cs b/MediaBrowser.Controller/Security/IEncryptionManager.cs
deleted file mode 100644
index 68680fdf3..000000000
--- a/MediaBrowser.Controller/Security/IEncryptionManager.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-namespace MediaBrowser.Controller.Security
-{
- public interface IEncryptionManager
- {
- /// <summary>
- /// Encrypts the string.
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>System.String.</returns>
- string EncryptString(string value);
-
- /// <summary>
- /// Decrypts the string.
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>System.String.</returns>
- string DecryptString(string value);
- }
-}
diff --git a/MediaBrowser.Controller/Session/AuthenticationRequest.cs b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
index a28f47a9c..647c75e66 100644
--- a/MediaBrowser.Controller/Session/AuthenticationRequest.cs
+++ b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Session
@@ -5,13 +9,22 @@ namespace MediaBrowser.Controller.Session
public class AuthenticationRequest
{
public string Username { get; set; }
+
public Guid UserId { get; set; }
+
public string Password { get; set; }
+
+ [Obsolete("Send full password in Password field")]
public string PasswordSha1 { get; set; }
+
public string App { get; set; }
+
public string AppVersion { get; set; }
+
public string DeviceId { get; set; }
+
public string DeviceName { get; set; }
+
public string RemoteEndPoint { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Session/ISessionController.cs b/MediaBrowser.Controller/Session/ISessionController.cs
index a59c96ac7..b38ee1146 100644
--- a/MediaBrowser.Controller/Session/ISessionController.cs
+++ b/MediaBrowser.Controller/Session/ISessionController.cs
@@ -1,5 +1,11 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Model.Session;
namespace MediaBrowser.Controller.Session
{
@@ -20,6 +26,12 @@ namespace MediaBrowser.Controller.Session
/// <summary>
/// Sends the message.
/// </summary>
- Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken);
+ /// <typeparam name="T">The type of data.</typeparam>
+ /// <param name="name">Name of message type.</param>
+ /// <param name="messageId">Message ID.</param>
+ /// <param name="data">Data to send.</param>
+ /// <param name="cancellationToken">CancellationToken for operation.</param>
+ /// <returns>A task.</returns>
+ Task SendMessage<T>(SessionMessageType name, Guid messageId, T data, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs
index 771027103..c86556095 100644
--- a/MediaBrowser.Controller/Session/ISessionManager.cs
+++ b/MediaBrowser.Controller/Session/ISessionManager.cs
@@ -1,19 +1,22 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities.Security;
+using Jellyfin.Data.Events;
using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Events;
using MediaBrowser.Model.Session;
+using MediaBrowser.Model.SyncPlay;
namespace MediaBrowser.Controller.Session
{
/// <summary>
- /// Interface ISessionManager
+ /// Interface ISessionManager.
/// </summary>
public interface ISessionManager
{
@@ -45,6 +48,11 @@ namespace MediaBrowser.Controller.Session
event EventHandler<SessionEventArgs> SessionActivity;
/// <summary>
+ /// Occurs when [session controller connected].
+ /// </summary>
+ event EventHandler<SessionEventArgs> SessionControllerConnected;
+
+ /// <summary>
/// Occurs when [capabilities changed].
/// </summary>
event EventHandler<SessionEventArgs> CapabilitiesChanged;
@@ -74,40 +82,46 @@ namespace MediaBrowser.Controller.Session
/// <param name="deviceName">Name of the device.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="user">The user.</param>
- SessionInfo LogSessionActivity(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user);
+ /// <returns>A task containing the session information.</returns>
+ Task<SessionInfo> LogSessionActivity(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Jellyfin.Data.Entities.User user);
+
+ /// <summary>
+ /// Used to report that a session controller has connected.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ void OnSessionControllerConnected(SessionInfo session);
void UpdateDeviceName(string sessionId, string reportedDeviceName);
/// <summary>
- /// Used to report that playback has started for an item
+ /// Used to report that playback has started for an item.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
Task OnPlaybackStart(PlaybackStartInfo info);
/// <summary>
- /// Used to report playback progress for an item
+ /// Used to report playback progress for an item.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if an argument is null.</exception>
Task OnPlaybackProgress(PlaybackProgressInfo info);
Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated);
/// <summary>
- /// Used to report that playback has ended for an item
+ /// Used to report that playback has ended for an item.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Throws if an argument is null.</exception>
Task OnPlaybackStopped(PlaybackStopInfo info);
/// <summary>
/// Reports the session ended.
/// </summary>
/// <param name="sessionId">The session identifier.</param>
- /// <returns>Task.</returns>
void ReportSessionEnded(string sessionId);
/// <summary>
@@ -141,6 +155,25 @@ namespace MediaBrowser.Controller.Session
Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken);
/// <summary>
+ /// Sends a SyncPlayCommand to a session.
+ /// </summary>
+ /// <param name="sessionId">The identifier of the session.</param>
+ /// <param name="command">The command.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Sends a SyncPlayGroupUpdate to a session.
+ /// </summary>
+ /// <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>
+ /// <returns>Task.</returns>
+ Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancellationToken);
+
+ /// <summary>
/// Sends the browse command.
/// </summary>
/// <param name="controllingSessionId">The controlling session identifier.</param>
@@ -163,32 +196,45 @@ namespace MediaBrowser.Controller.Session
/// <summary>
/// Sends the message to admin sessions.
/// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="name">The name.</param>
+ /// <typeparam name="T">Type of data.</typeparam>
+ /// <param name="name">Message type name.</param>
/// <param name="data">The data.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToAdminSessions<T>(SessionMessageType name, T data, CancellationToken cancellationToken);
/// <summary>
/// Sends the message to user sessions.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">Type of data.</typeparam>
+ /// <param name="userIds">Users to send messages to.</param>
+ /// <param name="name">Message type name.</param>
+ /// <param name="data">The data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, T data, CancellationToken cancellationToken);
- Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken);
+ /// <summary>
+ /// Sends the message to user sessions.
+ /// </summary>
+ /// <typeparam name="T">Type of data.</typeparam>
+ /// <param name="userIds">Users to send messages to.</param>
+ /// <param name="name">Message type name.</param>
+ /// <param name="dataFn">Data function.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, Func<T> dataFn, CancellationToken cancellationToken);
/// <summary>
/// Sends the message to user device sessions.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">Type of data.</typeparam>
/// <param name="deviceId">The device identifier.</param>
- /// <param name="name">The name.</param>
+ /// <param name="name">Message type name.</param>
/// <param name="data">The data.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToUserDeviceSessions<T>(string deviceId, SessionMessageType name, T data, CancellationToken cancellationToken);
/// <summary>
/// Sends the restart required message.
@@ -233,25 +279,13 @@ namespace MediaBrowser.Controller.Session
void ReportNowViewingItem(string sessionId, string itemId);
/// <summary>
- /// Reports the now viewing item.
- /// </summary>
- /// <param name="sessionId">The session identifier.</param>
- /// <param name="item">The item.</param>
- void ReportNowViewingItem(string sessionId, BaseItemDto item);
-
- /// <summary>
/// Authenticates the new session.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task{SessionInfo}.</returns>
Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request);
- /// <summary>
- /// Creates the new session.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>Task&lt;AuthenticationResult&gt;.</returns>
- Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request);
+ Task<AuthenticationResult> AuthenticateDirect(AuthenticationRequest request);
/// <summary>
/// Reports the capabilities.
@@ -289,7 +323,7 @@ namespace MediaBrowser.Controller.Session
/// <param name="deviceId">The device identifier.</param>
/// <param name="remoteEndpoint">The remote endpoint.</param>
/// <returns>SessionInfo.</returns>
- SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint);
+ Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint);
/// <summary>
/// Gets the session by authentication token.
@@ -299,28 +333,24 @@ namespace MediaBrowser.Controller.Session
/// <param name="remoteEndpoint">The remote endpoint.</param>
/// <param name="appVersion">The application version.</param>
/// <returns>Task&lt;SessionInfo&gt;.</returns>
- SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion);
+ Task<SessionInfo> GetSessionByAuthenticationToken(Device info, string deviceId, string remoteEndpoint, string appVersion);
/// <summary>
/// Logouts the specified access token.
/// </summary>
/// <param name="accessToken">The access token.</param>
- /// <returns>Task.</returns>
- void Logout(string accessToken);
- void Logout(AuthenticationInfo accessToken);
+ /// <returns>A <see cref="Task"/> representing the log out process.</returns>
+ Task Logout(string accessToken);
- /// <summary>
- /// Revokes the user tokens.
- /// </summary>
- /// <returns>Task.</returns>
- void RevokeUserTokens(Guid userId, string currentAccessToken);
+ Task Logout(Device device);
/// <summary>
- /// Revokes the token.
+ /// Revokes the user tokens.
/// </summary>
- /// <param name="id">The identifier.</param>
+ /// <param name="userId">The user's id.</param>
+ /// <param name="currentAccessToken">The current access token.</param>
/// <returns>Task.</returns>
- void RevokeToken(string id);
+ Task RevokeUserTokens(Guid userId, string currentAccessToken);
void CloseIfNeeded(SessionInfo session);
}
diff --git a/MediaBrowser.Controller/Session/SessionEventArgs.cs b/MediaBrowser.Controller/Session/SessionEventArgs.cs
index 08baaf647..269fe7dc4 100644
--- a/MediaBrowser.Controller/Session/SessionEventArgs.cs
+++ b/MediaBrowser.Controller/Session/SessionEventArgs.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Controller.Session
diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs
index f0e81e8e7..6134c0cf3 100644
--- a/MediaBrowser.Controller/Session/SessionInfo.cs
+++ b/MediaBrowser.Controller/Session/SessionInfo.cs
@@ -1,22 +1,36 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
using System.Linq;
+using System.Text.Json.Serialization;
using System.Threading;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Session
{
/// <summary>
- /// Class SessionInfo
+ /// Class SessionInfo.
/// </summary>
- public class SessionInfo : IDisposable
+ public sealed class SessionInfo : IDisposable
{
- private ISessionManager _sessionManager;
+ // 1 second
+ private const long ProgressIncrement = 10000000;
+
+ private readonly ISessionManager _sessionManager;
private readonly ILogger _logger;
+ private readonly object _progressLock = new object();
+ private Timer _progressTimer;
+ private PlaybackProgressInfo _lastProgressInfo;
+
+ private bool _disposed = false;
+
public SessionInfo(ISessionManager sessionManager, ILogger logger)
{
_sessionManager = sessionManager;
@@ -40,10 +54,10 @@ namespace MediaBrowser.Controller.Session
public string RemoteEndPoint { get; set; }
/// <summary>
- /// Gets or sets the playable media types.
+ /// Gets the playable media types.
/// </summary>
/// <value>The playable media types.</value>
- public string[] PlayableMediaTypes
+ public IReadOnlyList<string> PlayableMediaTypes
{
get
{
@@ -51,6 +65,7 @@ namespace MediaBrowser.Controller.Session
{
return Array.Empty<string>();
}
+
return Capabilities.PlayableMediaTypes;
}
}
@@ -97,6 +112,10 @@ namespace MediaBrowser.Controller.Session
/// <value>The name of the device.</value>
public string DeviceName { get; set; }
+ /// <summary>
+ /// Gets or sets the type of the device.
+ /// </summary>
+ /// <value>The type of the device.</value>
public string DeviceType { get; set; }
/// <summary>
@@ -107,6 +126,8 @@ namespace MediaBrowser.Controller.Session
public BaseItem FullNowPlayingItem { get; set; }
+ public BaseItemDto NowViewingItem { get; set; }
+
/// <summary>
/// Gets or sets the device id.
/// </summary>
@@ -123,31 +144,9 @@ namespace MediaBrowser.Controller.Session
/// Gets or sets the session controller.
/// </summary>
/// <value>The session controller.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public ISessionController[] SessionControllers { get; set; }
- /// <summary>
- /// Gets or sets the application icon URL.
- /// </summary>
- /// <value>The application icon URL.</value>
- public string AppIconUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the supported commands.
- /// </summary>
- /// <value>The supported commands.</value>
- public string[] SupportedCommands
- {
- get
- {
- if (Capabilities == null)
- {
- return new string[] { };
- }
- return Capabilities.SupportedCommands;
- }
- }
-
public TranscodingInfo TranscodingInfo { get; set; }
/// <summary>
@@ -166,6 +165,7 @@ namespace MediaBrowser.Controller.Session
return true;
}
}
+
if (controllers.Length > 0)
{
return false;
@@ -219,6 +219,23 @@ namespace MediaBrowser.Controller.Session
}
}
+ public QueueItem[] NowPlayingQueue { get; set; }
+
+ public bool HasCustomDeviceName { get; set; }
+
+ public string PlaylistItemId { get; set; }
+
+ public string ServerId { get; set; }
+
+ public string UserPrimaryImageTag { get; set; }
+
+ /// <summary>
+ /// Gets the supported commands.
+ /// </summary>
+ /// <value>The supported commands.</value>
+ public IReadOnlyList<GeneralCommandType> SupportedCommands
+ => Capabilities == null ? Array.Empty<GeneralCommandType>() : Capabilities.SupportedCommands;
+
public Tuple<ISessionController, bool> EnsureController<T>(Func<SessionInfo, ISessionController> factory)
{
var controllers = SessionControllers.ToList();
@@ -245,11 +262,6 @@ namespace MediaBrowser.Controller.Session
SessionControllers = controllers.ToArray();
}
- public bool ContainsUser(string userId)
- {
- return ContainsUser(new Guid(userId));
- }
-
public bool ContainsUser(Guid userId)
{
if (UserId.Equals(userId))
@@ -259,18 +271,15 @@ namespace MediaBrowser.Controller.Session
foreach (var additionalUser in AdditionalUsers)
{
- if (userId.Equals(userId))
+ if (additionalUser.UserId.Equals(userId))
{
return true;
}
}
+
return false;
}
- private readonly object _progressLock = new object();
- private Timer _progressTimer;
- private PlaybackProgressInfo _lastProgressInfo;
-
public void StartAutomaticProgress(PlaybackProgressInfo progressInfo)
{
if (_disposed)
@@ -293,9 +302,6 @@ namespace MediaBrowser.Controller.Session
}
}
- // 1 second
- private const long ProgressIncrement = 10000000;
-
private async void OnProgressTimerCallback(object state)
{
if (_disposed)
@@ -308,6 +314,7 @@ namespace MediaBrowser.Controller.Session
{
return;
}
+
if (progressInfo.IsPaused)
{
return;
@@ -321,7 +328,7 @@ namespace MediaBrowser.Controller.Session
var newPositionTicks = positionTicks + ProgressIncrement;
var item = progressInfo.Item;
- long? runtimeTicks = item == null ? null : item.RunTimeTicks;
+ long? runtimeTicks = item?.RunTimeTicks;
// Don't report beyond the runtime
if (runtimeTicks.HasValue && newPositionTicks >= runtimeTicks.Value)
@@ -350,12 +357,12 @@ namespace MediaBrowser.Controller.Session
_progressTimer.Dispose();
_progressTimer = null;
}
+
_lastProgressInfo = null;
}
}
- private bool _disposed = false;
-
+ /// <inheritdoc />
public void Dispose()
{
_disposed = true;
@@ -367,30 +374,12 @@ namespace MediaBrowser.Controller.Session
foreach (var controller in controllers)
{
- var disposable = controller as IDisposable;
-
- if (disposable != null)
+ if (controller is IDisposable disposable)
{
_logger.LogDebug("Disposing session controller {0}", disposable.GetType().Name);
-
- try
- {
- disposable.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error disposing session controller");
- }
+ disposable.Dispose();
}
}
-
- _sessionManager = null;
}
-
- public QueueItem[] NowPlayingQueue { get; set; }
- public bool HasCustomDeviceName { get; set; }
- public string PlaylistItemId { get; set; }
- public string ServerId { get; set; }
- public string UserPrimaryImageTag { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs b/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs
index 31087edec..07fe1ea8a 100644
--- a/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs
+++ b/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs
@@ -4,9 +4,9 @@ using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.Sorting
{
/// <summary>
- /// Interface IBaseItemComparer
+ /// Interface IBaseItemComparer.
/// </summary>
- public interface IBaseItemComparer : IComparer<BaseItem>
+ public interface IBaseItemComparer : IComparer<BaseItem?>
{
/// <summary>
/// Gets the name.
diff --git a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
index 1e2df37bf..bd47db39a 100644
--- a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
+++ b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
@@ -1,10 +1,11 @@
-using MediaBrowser.Controller.Entities;
+#nullable disable
+
using MediaBrowser.Controller.Library;
namespace MediaBrowser.Controller.Sorting
{
/// <summary>
- /// Represents a BaseItem comparer that requires a User to perform it's comparison
+ /// Represents a BaseItem comparer that requires a User to perform it's comparison.
/// </summary>
public interface IUserBaseItemComparer : IBaseItemComparer
{
@@ -12,7 +13,7 @@ namespace MediaBrowser.Controller.Sorting
/// Gets or sets the user.
/// </summary>
/// <value>The user.</value>
- User User { get; set; }
+ Jellyfin.Data.Entities.User User { get; set; }
/// <summary>
/// Gets or sets the user manager.
diff --git a/MediaBrowser.Controller/Sorting/SortExtensions.cs b/MediaBrowser.Controller/Sorting/SortExtensions.cs
index 111f4f17f..f9c0d39dd 100644
--- a/MediaBrowser.Controller/Sorting/SortExtensions.cs
+++ b/MediaBrowser.Controller/Sorting/SortExtensions.cs
@@ -1,143 +1,34 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
+using Jellyfin.Extensions;
namespace MediaBrowser.Controller.Sorting
{
public static class SortExtensions
{
+ private static readonly AlphanumericComparator _comparer = new AlphanumericComparator();
+
public static IEnumerable<T> OrderByString<T>(this IEnumerable<T> list, Func<T, string> getName)
{
- return list.OrderBy(getName, new AlphanumComparator());
+ return list.OrderBy(getName, _comparer);
}
public static IEnumerable<T> OrderByStringDescending<T>(this IEnumerable<T> list, Func<T, string> getName)
{
- return list.OrderByDescending(getName, new AlphanumComparator());
+ return list.OrderByDescending(getName, _comparer);
}
public static IOrderedEnumerable<T> ThenByString<T>(this IOrderedEnumerable<T> list, Func<T, string> getName)
{
- return list.ThenBy(getName, new AlphanumComparator());
+ return list.ThenBy(getName, _comparer);
}
public static IOrderedEnumerable<T> ThenByStringDescending<T>(this IOrderedEnumerable<T> list, Func<T, string> getName)
{
- return list.ThenByDescending(getName, new AlphanumComparator());
- }
-
- private class AlphanumComparator : IComparer<string>
- {
- private enum ChunkType { Alphanumeric, Numeric };
-
- private static bool InChunk(char ch, char otherCh)
- {
- var type = ChunkType.Alphanumeric;
-
- if (char.IsDigit(otherCh))
- {
- type = ChunkType.Numeric;
- }
-
- if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
- || (type == ChunkType.Numeric && !char.IsDigit(ch)))
- {
- return false;
- }
-
- return true;
- }
-
- public static int CompareValues(string s1, string s2)
- {
- if (s1 == null || s2 == null)
- {
- return 0;
- }
-
- int thisMarker = 0, thisNumericChunk = 0;
- int thatMarker = 0, thatNumericChunk = 0;
-
- while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
- {
- if (thisMarker >= s1.Length)
- {
- return -1;
- }
- else if (thatMarker >= s2.Length)
- {
- return 1;
- }
- char thisCh = s1[thisMarker];
- char thatCh = s2[thatMarker];
-
- var thisChunk = new StringBuilder();
- var thatChunk = new StringBuilder();
-
- while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || InChunk(thisCh, thisChunk[0])))
- {
- thisChunk.Append(thisCh);
- thisMarker++;
-
- if (thisMarker < s1.Length)
- {
- thisCh = s1[thisMarker];
- }
- }
-
- while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || InChunk(thatCh, thatChunk[0])))
- {
- thatChunk.Append(thatCh);
- thatMarker++;
-
- if (thatMarker < s2.Length)
- {
- thatCh = s2[thatMarker];
- }
- }
-
- int result = 0;
- // If both chunks contain numeric characters, sort them numerically
- if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
- {
- if (!int.TryParse(thisChunk.ToString(), out thisNumericChunk))
- {
- return 0;
- }
- if (!int.TryParse(thatChunk.ToString(), out thatNumericChunk))
- {
- return 0;
- }
-
- if (thisNumericChunk < thatNumericChunk)
- {
- result = -1;
- }
-
- if (thisNumericChunk > thatNumericChunk)
- {
- result = 1;
- }
- }
- else
- {
- result = thisChunk.ToString().CompareTo(thatChunk.ToString());
- }
-
- if (result != 0)
- {
- return result;
- }
- }
-
- return 0;
- }
-
- public int Compare(string x, string y)
- {
- return CompareValues(x, y);
- }
+ return list.ThenByDescending(getName, _comparer);
}
}
}
diff --git a/MediaBrowser.Controller/Sorting/SortHelper.cs b/MediaBrowser.Controller/Sorting/SortHelper.cs
deleted file mode 100644
index 05981d975..000000000
--- a/MediaBrowser.Controller/Sorting/SortHelper.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-namespace MediaBrowser.Controller.Sorting
-{
- public static class SortHelper
- {
- private enum ChunkType { Alphanumeric, Numeric };
-
- public static bool InChunk(char ch, char otherCh)
- {
- var type = ChunkType.Alphanumeric;
-
- if (char.IsDigit(otherCh))
- {
- type = ChunkType.Numeric;
- }
-
- if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
- || (type == ChunkType.Numeric && !char.IsDigit(ch)))
- {
- return false;
- }
-
- return true;
- }
- }
-}
diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
index 0872335c5..52aa44024 100644
--- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
+++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading;
@@ -24,9 +28,17 @@ namespace MediaBrowser.Controller.Subtitles
/// <summary>
/// Searches the subtitles.
/// </summary>
- Task<RemoteSubtitleInfo[]> SearchSubtitles(Video video,
+ /// <param name="video">The video.</param>
+ /// <param name="language">Subtitle language.</param>
+ /// <param name="isPerfectMatch">Require perfect match.</param>
+ /// <param name="isAutomated">Request is automated.</param>
+ /// <param name="cancellationToken">CancellationToken to use for the operation.</param>
+ /// <returns>Subtitles, wrapped in task.</returns>
+ Task<RemoteSubtitleInfo[]> SearchSubtitles(
+ Video video,
string language,
bool? isPerfectMatch,
+ bool isAutomated,
CancellationToken cancellationToken);
/// <summary>
@@ -34,36 +46,59 @@ namespace MediaBrowser.Controller.Subtitles
/// </summary>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{RemoteSubtitleInfo}}.</returns>
- Task<RemoteSubtitleInfo[]> SearchSubtitles(SubtitleSearchRequest request,
+ /// <returns>Task{RemoteSubtitleInfo[]}.</returns>
+ Task<RemoteSubtitleInfo[]> SearchSubtitles(
+ SubtitleSearchRequest request,
CancellationToken cancellationToken);
/// <summary>
/// Downloads the subtitles.
/// </summary>
+ /// <param name="video">The video.</param>
+ /// <param name="subtitleId">Subtitle ID.</param>
+ /// <param name="cancellationToken">CancellationToken to use for the operation.</param>
+ /// <returns>A task.</returns>
Task DownloadSubtitles(Video video, string subtitleId, CancellationToken cancellationToken);
/// <summary>
/// Downloads the subtitles.
/// </summary>
+ /// <param name="video">The video.</param>
+ /// <param name="libraryOptions">Library options to use.</param>
+ /// <param name="subtitleId">Subtitle ID.</param>
+ /// <param name="cancellationToken">CancellationToken to use for the operation.</param>
+ /// <returns>A task.</returns>
Task DownloadSubtitles(Video video, LibraryOptions libraryOptions, string subtitleId, CancellationToken cancellationToken);
/// <summary>
+ /// Upload new subtitle.
+ /// </summary>
+ /// <param name="video">The video the subtitle belongs to.</param>
+ /// <param name="response">The subtitle response.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ Task UploadSubtitle(Video video, SubtitleResponse response);
+
+ /// <summary>
/// Gets the remote subtitles.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{SubtitleResponse}.</returns>
+ /// <returns><see cref="Task{SubtitleResponse}" />.</returns>
Task<SubtitleResponse> GetRemoteSubtitles(string id, CancellationToken cancellationToken);
/// <summary>
/// Deletes the subtitles.
/// </summary>
+ /// <param name="item">Media item.</param>
+ /// <param name="index">Subtitle index.</param>
+ /// <returns>A task.</returns>
Task DeleteSubtitles(BaseItem item, int index);
/// <summary>
/// Gets the providers.
/// </summary>
+ /// <param name="item">The media item.</param>
+ /// <returns>Subtitles providers.</returns>
SubtitleProviderInfo[] GetSupportedProviders(BaseItem item);
}
}
diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs b/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs
index 8ffd7c530..326348d58 100644
--- a/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs
+++ b/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
diff --git a/MediaBrowser.Controller/Subtitles/SubtitleDownloadEventArgs.cs b/MediaBrowser.Controller/Subtitles/SubtitleDownloadEventArgs.cs
deleted file mode 100644
index 5703aea17..000000000
--- a/MediaBrowser.Controller/Subtitles/SubtitleDownloadEventArgs.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System;
-using MediaBrowser.Controller.Entities;
-
-namespace MediaBrowser.Controller.Subtitles
-{
- public class SubtitleDownloadEventArgs
- {
- public BaseItem Item { get; set; }
-
- public string Format { get; set; }
-
- public string Language { get; set; }
-
- public bool IsForced { get; set; }
-
- public string Provider { get; set; }
- }
-
- public class SubtitleDownloadFailureEventArgs
- {
- public BaseItem Item { get; set; }
-
- public string Provider { get; set; }
-
- public Exception Exception { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs b/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs
new file mode 100644
index 000000000..c782f5796
--- /dev/null
+++ b/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs
@@ -0,0 +1,28 @@
+#nullable disable
+
+using System;
+using MediaBrowser.Controller.Entities;
+
+namespace MediaBrowser.Controller.Subtitles
+{
+ /// <summary>
+ /// An event that occurs when subtitle downloading fails.
+ /// </summary>
+ public class SubtitleDownloadFailureEventArgs : EventArgs
+ {
+ /// <summary>
+ /// Gets or sets the item.
+ /// </summary>
+ public BaseItem Item { get; set; }
+
+ /// <summary>
+ /// Gets or sets the provider.
+ /// </summary>
+ public string Provider { get; set; }
+
+ /// <summary>
+ /// Gets or sets the exception.
+ /// </summary>
+ public Exception Exception { get; set; }
+ }
+}
diff --git a/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs b/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs
index b8ba35a5f..85b3e6fbd 100644
--- a/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs
+++ b/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.IO;
namespace MediaBrowser.Controller.Subtitles
@@ -5,8 +9,11 @@ namespace MediaBrowser.Controller.Subtitles
public class SubtitleResponse
{
public string Language { get; set; }
+
public string Format { get; set; }
+
public bool IsForced { get; set; }
+
public Stream Stream { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
index 61dc72258..ef052237a 100644
--- a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
+++ b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Providers;
@@ -7,33 +11,47 @@ namespace MediaBrowser.Controller.Subtitles
{
public class SubtitleSearchRequest : IHasProviderIds
{
+ public SubtitleSearchRequest()
+ {
+ SearchAllProviders = true;
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+
+ DisabledSubtitleFetchers = Array.Empty<string>();
+ SubtitleFetcherOrder = Array.Empty<string>();
+ }
+
public string Language { get; set; }
+
public string TwoLetterISOLanguageName { get; set; }
public VideoContentType ContentType { get; set; }
public string MediaPath { get; set; }
+
public string SeriesName { get; set; }
+
public string Name { get; set; }
+
public int? IndexNumber { get; set; }
+
public int? IndexNumberEnd { get; set; }
+
public int? ParentIndexNumber { get; set; }
+
public int? ProductionYear { get; set; }
+
public long? RuntimeTicks { get; set; }
+
public bool IsPerfectMatch { get; set; }
+
public Dictionary<string, string> ProviderIds { get; set; }
public bool SearchAllProviders { get; set; }
+
public string[] DisabledSubtitleFetchers { get; set; }
- public string[] SubtitleFetcherOrder { get; set; }
- public SubtitleSearchRequest()
- {
- SearchAllProviders = true;
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ public string[] SubtitleFetcherOrder { get; set; }
- DisabledSubtitleFetchers = Array.Empty<string>();
- SubtitleFetcherOrder = Array.Empty<string>();
- }
+ public bool IsAutomated { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs b/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs
deleted file mode 100644
index d6bac23be..000000000
--- a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Sync;
-
-namespace MediaBrowser.Controller.Sync
-{
- public interface IHasDynamicAccess
- {
- /// <summary>
- /// Gets the synced file information.
- /// </summary>
- /// <param name="id">The identifier.</param>
- /// <param name="target">The target.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task&lt;SyncedFileInfo&gt;.</returns>
- Task<SyncedFileInfo> GetSyncedFileInfo(string id, SyncTarget target, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs b/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs
deleted file mode 100644
index c0b62b753..000000000
--- a/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace MediaBrowser.Controller.Sync
-{
- /// <summary>
- /// A marker interface
- /// </summary>
- public interface IRemoteSyncProvider
- {
- }
-}
diff --git a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs b/MediaBrowser.Controller/Sync/IServerSyncProvider.cs
deleted file mode 100644
index 8b2d5d779..000000000
--- a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Sync;
-
-namespace MediaBrowser.Controller.Sync
-{
- public interface IServerSyncProvider : ISyncProvider
- {
- /// <summary>
- /// Transfers the file.
- /// </summary>
- Task<SyncedFileInfo> SendFile(SyncJob syncJob, string originalMediaPath, Stream inputStream, bool isMedia, string[] outputPathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken);
-
- Task<QueryResult<FileSystemMetadata>> GetFiles(string[] directoryPathParts, SyncTarget target, CancellationToken cancellationToken);
- }
-
- public interface ISupportsDirectCopy
- {
- /// <summary>
- /// Sends the file.
- /// </summary>
- Task<SyncedFileInfo> SendFile(SyncJob syncJob, string originalMediaPath, string inputPath, bool isMedia, string[] outputPathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Controller/Sync/ISyncProvider.cs b/MediaBrowser.Controller/Sync/ISyncProvider.cs
deleted file mode 100644
index 56f6f3729..000000000
--- a/MediaBrowser.Controller/Sync/ISyncProvider.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Model.Sync;
-
-namespace MediaBrowser.Controller.Sync
-{
- public interface ISyncProvider
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
-
- /// <summary>
- /// Gets the synchronize targets.
- /// </summary>
- /// <param name="userId">The user identifier.</param>
- /// <returns>IEnumerable&lt;SyncTarget&gt;.</returns>
- List<SyncTarget> GetSyncTargets(string userId);
-
- /// <summary>
- /// Gets all synchronize targets.
- /// </summary>
- /// <returns>IEnumerable&lt;SyncTarget&gt;.</returns>
- List<SyncTarget> GetAllSyncTargets();
- }
-}
diff --git a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs b/MediaBrowser.Controller/Sync/SyncedFileInfo.cs
deleted file mode 100644
index 2ff40addb..000000000
--- a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Model.MediaInfo;
-
-namespace MediaBrowser.Controller.Sync
-{
- public class SyncedFileInfo
- {
- /// <summary>
- /// Gets or sets the path.
- /// </summary>
- /// <value>The path.</value>
- public string Path { get; set; }
- public string[] PathParts { get; set; }
- /// <summary>
- /// Gets or sets the protocol.
- /// </summary>
- /// <value>The protocol.</value>
- public MediaProtocol Protocol { get; set; }
- /// <summary>
- /// Gets or sets the required HTTP headers.
- /// </summary>
- /// <value>The required HTTP headers.</value>
- public Dictionary<string, string> RequiredHttpHeaders { get; set; }
- /// <summary>
- /// Gets or sets the identifier.
- /// </summary>
- /// <value>The identifier.</value>
- public string Id { get; set; }
-
- public SyncedFileInfo()
- {
- RequiredHttpHeaders = new Dictionary<string, string>();
- }
- }
-}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupMember.cs b/MediaBrowser.Controller/SyncPlay/GroupMember.cs
new file mode 100644
index 000000000..b973672c4
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupMember.cs
@@ -0,0 +1,60 @@
+#nullable disable
+
+using System;
+using MediaBrowser.Controller.Session;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Class GroupMember.
+ /// </summary>
+ public class GroupMember
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GroupMember"/> class.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ public GroupMember(SessionInfo session)
+ {
+ SessionId = session.Id;
+ UserId = session.UserId;
+ UserName = session.UserName;
+ }
+
+ /// <summary>
+ /// Gets the identifier of the session.
+ /// </summary>
+ /// <value>The session identifier.</value>
+ public string SessionId { get; }
+
+ /// <summary>
+ /// Gets the identifier of the user.
+ /// </summary>
+ /// <value>The user identifier.</value>
+ public Guid UserId { get; }
+
+ /// <summary>
+ /// Gets the username.
+ /// </summary>
+ /// <value>The username.</value>
+ public string UserName { get; }
+
+ /// <summary>
+ /// Gets or sets the ping, in milliseconds.
+ /// </summary>
+ /// <value>The ping.</value>
+ public long Ping { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this member is buffering.
+ /// </summary>
+ /// <value><c>true</c> if member is buffering; <c>false</c> otherwise.</value>
+ public bool IsBuffering { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this member is following group playback.
+ /// </summary>
+ /// <value><c>true</c> to ignore member on group wait; <c>false</c> if they're following group playback.</value>
+ public bool IgnoreGroupWait { get; set; }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs
new file mode 100644
index 000000000..51c95a1bb
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs
@@ -0,0 +1,233 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Controller.SyncPlay.GroupStates
+{
+ /// <summary>
+ /// Class AbstractGroupState.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public abstract class AbstractGroupState : IGroupState
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<AbstractGroupState> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AbstractGroupState"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ protected AbstractGroupState(ILoggerFactory loggerFactory)
+ {
+ LoggerFactory = loggerFactory;
+ _logger = loggerFactory.CreateLogger<AbstractGroupState>();
+ }
+
+ /// <inheritdoc />
+ public abstract GroupStateType Type { get; }
+
+ /// <summary>
+ /// Gets the logger factory.
+ /// </summary>
+ protected ILoggerFactory LoggerFactory { get; }
+
+ /// <inheritdoc />
+ public abstract void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <inheritdoc />
+ public abstract void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(IGroupPlaybackRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(RemoveFromPlaylistGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ bool playingItemRemoved;
+ if (request.ClearPlaylist)
+ {
+ context.ClearPlayQueue(request.ClearPlayingItem);
+ playingItemRemoved = request.ClearPlayingItem;
+ }
+ else
+ {
+ playingItemRemoved = context.RemoveFromPlayQueue(request.PlaylistItemIds);
+ }
+
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RemoveItems);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ if (playingItemRemoved && !context.PlayQueue.IsItemPlaying())
+ {
+ _logger.LogDebug("Play queue in group {GroupId} is now empty.", context.GroupId.ToString());
+
+ IGroupState idleState = new IdleGroupState(LoggerFactory);
+ context.SetState(idleState);
+ var stopRequest = new StopGroupRequest();
+ idleState.HandleRequest(stopRequest, context, Type, session, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(MovePlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ var result = context.MoveItemInPlayQueue(request.PlaylistItemId, request.NewIndex);
+
+ if (!result)
+ {
+ _logger.LogError("Unable to move item in group {GroupId}.", context.GroupId.ToString());
+ return;
+ }
+
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.MoveItem);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(QueueGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ var result = context.AddToPlayQueue(request.ItemIds, request.Mode);
+
+ if (!result)
+ {
+ _logger.LogError("Unable to add items to play queue in group {GroupId}.", context.GroupId.ToString());
+ return;
+ }
+
+ var reason = request.Mode switch
+ {
+ GroupQueueMode.QueueNext => PlayQueueUpdateReason.QueueNext,
+ _ => PlayQueueUpdateReason.Queue
+ };
+ var playQueueUpdate = context.GetPlayQueueUpdate(reason);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ UnhandledRequest(request);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(SetRepeatModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ context.SetRepeatMode(request.Mode);
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RepeatMode);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(SetShuffleModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ context.SetShuffleMode(request.Mode);
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.ShuffleMode);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(PingGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Collected pings are used to account for network latency when unpausing playback.
+ context.UpdatePing(session, request.Ping);
+ }
+
+ /// <inheritdoc />
+ public virtual void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ context.SetIgnoreGroupWait(session, request.IgnoreWait);
+ }
+
+ /// <summary>
+ /// Sends a group state update to all group.
+ /// </summary>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="reason">The reason of the state change.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ protected void SendGroupStateUpdate(IGroupStateContext context, IGroupPlaybackRequest reason, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Notify relevant state change event.
+ var stateUpdate = new GroupStateUpdate(Type, reason.Action);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+ }
+
+ private void UnhandledRequest(IGroupPlaybackRequest request)
+ {
+ _logger.LogWarning("Unhandled request of type {RequestType} in {StateType} state.", request.Action, Type);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs
new file mode 100644
index 000000000..6b5a7cdf9
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs
@@ -0,0 +1,128 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Controller.SyncPlay.GroupStates
+{
+ /// <summary>
+ /// Class IdleGroupState.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public class IdleGroupState : AbstractGroupState
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<IdleGroupState> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IdleGroupState"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public IdleGroupState(ILoggerFactory loggerFactory)
+ : base(loggerFactory)
+ {
+ _logger = LoggerFactory.CreateLogger<IdleGroupState>();
+ }
+
+ /// <inheritdoc />
+ public override GroupStateType Type { get; } = GroupStateType.Idle;
+
+ /// <inheritdoc />
+ public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Do nothing.
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, prevState, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, prevState, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, prevState, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, prevState, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ SendStopCommand(context, prevState, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ private void SendStopCommand(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ var command = context.NewSyncPlayCommand(SendCommandType.Stop);
+ if (!prevState.Equals(Type))
+ {
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+ }
+ else
+ {
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs
new file mode 100644
index 000000000..b9786ddb0
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs
@@ -0,0 +1,167 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Controller.SyncPlay.GroupStates
+{
+ /// <summary>
+ /// Class PausedGroupState.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public class PausedGroupState : AbstractGroupState
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<PausedGroupState> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PausedGroupState"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public PausedGroupState(ILoggerFactory loggerFactory)
+ : base(loggerFactory)
+ {
+ _logger = LoggerFactory.CreateLogger<PausedGroupState>();
+ }
+
+ /// <inheritdoc />
+ public override GroupStateType Type { get; } = GroupStateType.Paused;
+
+ /// <inheritdoc />
+ public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Wait for session to be ready.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.SessionJoined(context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Do nothing.
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var playingState = new PlayingGroupState(LoggerFactory);
+ context.SetState(playingState);
+ playingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ if (!prevState.Equals(Type))
+ {
+ // Pause group and compute the media playback position.
+ var currentTime = DateTime.UtcNow;
+ var elapsedTime = currentTime - context.LastActivity;
+ context.LastActivity = currentTime;
+ // Elapsed time is negative if event happens
+ // during the delay added to account for latency.
+ // In this phase clients haven't started the playback yet.
+ // In other words, LastActivity is in the future,
+ // when playback unpause is supposed to happen.
+ // Seek only if playback actually started.
+ context.PositionTicks += Math.Max(elapsedTime.Ticks, 0);
+
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+ else
+ {
+ // Client got lost, sending current state.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var idleState = new IdleGroupState(LoggerFactory);
+ context.SetState(idleState);
+ idleState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ if (prevState.Equals(Type))
+ {
+ // Client got lost, sending current state.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ else if (prevState.Equals(GroupStateType.Waiting))
+ {
+ // Sending current state to all clients.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs
new file mode 100644
index 000000000..cb1cadf0b
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs
@@ -0,0 +1,170 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Controller.SyncPlay.GroupStates
+{
+ /// <summary>
+ /// Class PlayingGroupState.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public class PlayingGroupState : AbstractGroupState
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<PlayingGroupState> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlayingGroupState"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public PlayingGroupState(ILoggerFactory loggerFactory)
+ : base(loggerFactory)
+ {
+ _logger = LoggerFactory.CreateLogger<PlayingGroupState>();
+ }
+
+ /// <inheritdoc />
+ public override GroupStateType Type { get; } = GroupStateType.Playing;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether requests for buffering should be ignored.
+ /// </summary>
+ public bool IgnoreBuffering { get; set; }
+
+ /// <inheritdoc />
+ public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Wait for session to be ready.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.SessionJoined(context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Do nothing.
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ if (!prevState.Equals(Type))
+ {
+ // Pick a suitable time that accounts for latency.
+ var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing);
+
+ // Unpause group and set starting point in future.
+ // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position).
+ // The added delay does not guarantee, of course, that the command will be received in time.
+ // Playback synchronization will mainly happen client side.
+ context.LastActivity = DateTime.UtcNow.AddMilliseconds(delayMillis);
+
+ var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+ else
+ {
+ // Client got lost, sending current state.
+ var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var pausedState = new PausedGroupState(LoggerFactory);
+ context.SetState(pausedState);
+ pausedState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var idleState = new IdleGroupState(LoggerFactory);
+ context.SetState(idleState);
+ idleState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ if (IgnoreBuffering)
+ {
+ return;
+ }
+
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ if (prevState.Equals(Type))
+ {
+ // Group was not waiting, make sure client has latest state.
+ var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ else if (prevState.Equals(GroupStateType.Waiting))
+ {
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Change state.
+ var waitingState = new WaitingGroupState(LoggerFactory);
+ context.SetState(waitingState);
+ waitingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs
new file mode 100644
index 000000000..a0c38b309
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs
@@ -0,0 +1,682 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Controller.SyncPlay.GroupStates
+{
+ /// <summary>
+ /// Class WaitingGroupState.
+ /// </summary>
+ /// <remarks>
+ /// Class is not thread-safe, external locking is required when accessing methods.
+ /// </remarks>
+ public class WaitingGroupState : AbstractGroupState
+ {
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<WaitingGroupState> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WaitingGroupState"/> class.
+ /// </summary>
+ /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
+ public WaitingGroupState(ILoggerFactory loggerFactory)
+ : base(loggerFactory)
+ {
+ _logger = LoggerFactory.CreateLogger<WaitingGroupState>();
+ }
+
+ /// <inheritdoc />
+ public override GroupStateType Type { get; } = GroupStateType.Waiting;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether playback should resume when group is ready.
+ /// </summary>
+ public bool ResumePlaying { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the initial state has been set.
+ /// </summary>
+ private bool InitialStateSet { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets the group state before the first ever event.
+ /// </summary>
+ private GroupStateType InitialState { get; set; }
+
+ /// <inheritdoc />
+ public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ if (prevState.Equals(GroupStateType.Playing))
+ {
+ ResumePlaying = true;
+ // Pause group and compute the media playback position.
+ var currentTime = DateTime.UtcNow;
+ var elapsedTime = currentTime - context.LastActivity;
+ context.LastActivity = currentTime;
+ // Elapsed time is negative if event happens
+ // during the delay added to account for latency.
+ // In this phase clients haven't started the playback yet.
+ // In other words, LastActivity is in the future,
+ // when playback unpause is supposed to happen.
+ // Seek only if playback actually started.
+ context.PositionTicks += Math.Max(elapsedTime.Ticks, 0);
+ }
+
+ // Prepare new session.
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);
+
+ context.SetBuffering(session, true);
+
+ // Send pause command to all non-buffering sessions.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ context.SetBuffering(session, false);
+
+ if (!context.IsBuffering())
+ {
+ if (ResumePlaying)
+ {
+ _logger.LogDebug("Session {SessionId} left group {GroupId}, notifying others to resume.", session.Id, context.GroupId.ToString());
+
+ // Client, that was buffering, left the group.
+ var playingState = new PlayingGroupState(LoggerFactory);
+ context.SetState(playingState);
+ var unpauseRequest = new UnpauseGroupRequest();
+ playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken);
+ }
+ else
+ {
+ _logger.LogDebug("Session {SessionId} left group {GroupId}, returning to previous state.", session.Id, context.GroupId.ToString());
+
+ // Group is ready, returning to previous state.
+ var pausedState = new PausedGroupState(LoggerFactory);
+ context.SetState(pausedState);
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ ResumePlaying = true;
+
+ var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks);
+ if (!setQueueStatus)
+ {
+ _logger.LogError("Unable to set playing queue in group {GroupId}.", context.GroupId.ToString());
+
+ // Ignore request and return to previous state.
+ IGroupState newState = prevState switch {
+ GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
+ GroupStateType.Paused => new PausedGroupState(LoggerFactory),
+ _ => new IdleGroupState(LoggerFactory)
+ };
+
+ context.SetState(newState);
+ return;
+ }
+
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+
+ _logger.LogDebug("Session {SessionId} set a new play queue in group {GroupId}.", session.Id, context.GroupId.ToString());
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ ResumePlaying = true;
+
+ var result = context.SetPlayingItem(request.PlaylistItemId);
+ if (result)
+ {
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+ }
+ else
+ {
+ // Return to old state.
+ IGroupState newState = prevState switch
+ {
+ GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
+ GroupStateType.Paused => new PausedGroupState(LoggerFactory),
+ _ => new IdleGroupState(LoggerFactory)
+ };
+
+ context.SetState(newState);
+
+ _logger.LogDebug("Unable to change current playing item in group {GroupId}.", context.GroupId.ToString());
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ if (prevState.Equals(GroupStateType.Idle))
+ {
+ ResumePlaying = true;
+ context.RestartCurrentItem();
+
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+
+ _logger.LogDebug("Group {GroupId} is waiting for all ready events.", context.GroupId.ToString());
+ }
+ else
+ {
+ if (ResumePlaying)
+ {
+ _logger.LogDebug("Forcing the playback to start in group {GroupId}. Group-wait is disabled until next state change.", context.GroupId.ToString());
+
+ // An Unpause request is forcing the playback to start, ignoring sessions that are not ready.
+ context.SetAllBuffering(false);
+
+ // Change state.
+ var playingState = new PlayingGroupState(LoggerFactory)
+ {
+ IgnoreBuffering = true
+ };
+ context.SetState(playingState);
+ playingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+ else
+ {
+ // Group would have gone to paused state, now will go to playing state when ready.
+ ResumePlaying = true;
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ // Wait for sessions to be ready, then switch to paused state.
+ ResumePlaying = false;
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ // Change state.
+ var idleState = new IdleGroupState(LoggerFactory);
+ context.SetState(idleState);
+ idleState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ if (prevState.Equals(GroupStateType.Playing))
+ {
+ ResumePlaying = true;
+ }
+ else if (prevState.Equals(GroupStateType.Paused))
+ {
+ ResumePlaying = false;
+ }
+
+ // Sanitize PositionTicks.
+ var ticks = context.SanitizePositionTicks(request.PositionTicks);
+
+ // Seek.
+ context.PositionTicks = ticks;
+ context.LastActivity = DateTime.UtcNow;
+
+ var command = context.NewSyncPlayCommand(SendCommandType.Seek);
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ // Make sure the client is playing the correct item.
+ if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
+ {
+ _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);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
+ context.SetBuffering(session, true);
+
+ return;
+ }
+
+ if (prevState.Equals(GroupStateType.Playing))
+ {
+ // Resume playback when all ready.
+ ResumePlaying = true;
+
+ context.SetBuffering(session, true);
+
+ // Pause group and compute the media playback position.
+ var currentTime = DateTime.UtcNow;
+ var elapsedTime = currentTime - context.LastActivity;
+ context.LastActivity = currentTime;
+ // Elapsed time is negative if event happens
+ // during the delay added to account for latency.
+ // In this phase clients haven't started the playback yet.
+ // In other words, LastActivity is in the future,
+ // when playback unpause is supposed to happen.
+ // Seek only if playback actually started.
+ context.PositionTicks += Math.Max(elapsedTime.Ticks, 0);
+
+ // Send pause command to all non-buffering sessions.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken);
+ }
+ else if (prevState.Equals(GroupStateType.Paused))
+ {
+ // Don't resume playback when all ready.
+ ResumePlaying = false;
+
+ context.SetBuffering(session, true);
+
+ // Send pause command to buffering session.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ else if (prevState.Equals(GroupStateType.Waiting))
+ {
+ // Another session is now buffering.
+ context.SetBuffering(session, true);
+
+ if (!ResumePlaying)
+ {
+ // Force update for this session that should be paused.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+ }
+ }
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ // Make sure the client is playing the correct item.
+ if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
+ {
+ _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);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);
+ context.SetBuffering(session, true);
+
+ return;
+ }
+
+ // Compute elapsed time between the client reported time and now.
+ // Elapsed time is used to estimate the client position when playback is unpaused.
+ // Ideally, the request is received and handled without major delays.
+ // However, to avoid waiting indefinitely when a client is not reporting a correct time,
+ // the elapsed time is ignored after a certain threshold.
+ var currentTime = DateTime.UtcNow;
+ var elapsedTime = currentTime.Subtract(request.When);
+ var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks;
+ if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks)
+ {
+ _logger.LogWarning("Session {SessionId} is not time syncing properly. Ignoring elapsed time.", session.Id);
+
+ elapsedTime = TimeSpan.Zero;
+ }
+
+ // Ignore elapsed time if client is paused.
+ if (!request.IsPlaying)
+ {
+ elapsedTime = TimeSpan.Zero;
+ }
+
+ var requestTicks = context.SanitizePositionTicks(request.PositionTicks);
+ var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime;
+ var delayTicks = context.PositionTicks - clientPosition.Ticks;
+ var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks;
+
+ _logger.LogDebug("Session {SessionId} is at {PositionTicks} (delay of {Delay} seconds) in group {GroupId}.", session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString());
+
+ if (ResumePlaying)
+ {
+ // Handle case where session reported as ready but in reality
+ // it has no clue of the real position nor the playback state.
+ if (!request.IsPlaying && Math.Abs(delayTicks) > maxPlaybackOffsetTicks)
+ {
+ // Session not ready at all.
+ context.SetBuffering(session, true);
+
+ // Correcting session's position.
+ var command = context.NewSyncPlayCommand(SendCommandType.Seek);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+
+ _logger.LogWarning("Session {SessionId} got lost in time, correcting.", session.Id);
+ return;
+ }
+
+ // Session is ready.
+ context.SetBuffering(session, false);
+
+ if (context.IsBuffering())
+ {
+ // Others are still buffering, tell this client to pause when ready.
+ var command = context.NewSyncPlayCommand(SendCommandType.Pause);
+ command.When = currentTime.AddTicks(delayTicks);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+
+ _logger.LogInformation("Session {SessionId} will pause when ready in {Delay} seconds. Group {GroupId} is waiting for all ready events.", session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString());
+ }
+ else
+ {
+ // If all ready, then start playback.
+ // Let other clients resume as soon as the buffering client catches up.
+ if (delayTicks > context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond)
+ {
+ // Client that was buffering is recovering, notifying others to resume.
+ context.LastActivity = currentTime.AddTicks(delayTicks);
+ var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
+ var filter = SyncPlayBroadcastType.AllExceptCurrentSession;
+ if (!request.IsPlaying)
+ {
+ filter = SyncPlayBroadcastType.AllGroup;
+ }
+
+ context.SendCommand(session, filter, command, cancellationToken);
+
+ _logger.LogInformation("Session {SessionId} is recovering, group {GroupId} will resume in {Delay} seconds.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds);
+ }
+ else
+ {
+ // Client, that was buffering, resumed playback but did not update others in time.
+ delayTicks = context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond;
+ delayTicks = Math.Max(delayTicks, context.DefaultPing);
+
+ context.LastActivity = currentTime.AddTicks(delayTicks);
+
+ var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
+ context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
+
+ _logger.LogWarning("Session {SessionId} resumed playback, group {GroupId} has {Delay} seconds to recover.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds);
+ }
+
+ // Change state.
+ var playingState = new PlayingGroupState(LoggerFactory);
+ context.SetState(playingState);
+ playingState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+ }
+ else
+ {
+ // Check that session is really ready, tolerate player imperfections under a certain threshold.
+ if (Math.Abs(context.PositionTicks - requestTicks) > maxPlaybackOffsetTicks)
+ {
+ // Session still not ready.
+ context.SetBuffering(session, true);
+ // Session is seeking to wrong position, correcting.
+ var command = context.NewSyncPlayCommand(SendCommandType.Seek);
+ context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
+
+ // Notify relevant state change event.
+ SendGroupStateUpdate(context, request, session, cancellationToken);
+
+ _logger.LogWarning("Session {SessionId} is seeking to wrong position, correcting.", session.Id);
+ return;
+ }
+ else
+ {
+ // Session is ready.
+ context.SetBuffering(session, false);
+ }
+
+ if (!context.IsBuffering())
+ {
+ _logger.LogDebug("Session {SessionId} is ready, group {GroupId} is ready.", session.Id, context.GroupId.ToString());
+
+ // Group is ready, returning to previous state.
+ var pausedState = new PausedGroupState(LoggerFactory);
+ context.SetState(pausedState);
+
+ if (InitialState.Equals(GroupStateType.Playing))
+ {
+ // Group went from playing to waiting state and a pause request occured while waiting.
+ var pauseRequest = new PauseGroupRequest();
+ pausedState.HandleRequest(pauseRequest, context, Type, session, cancellationToken);
+ }
+ else if (InitialState.Equals(GroupStateType.Paused))
+ {
+ pausedState.HandleRequest(request, context, Type, session, cancellationToken);
+ }
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ ResumePlaying = true;
+
+ // Make sure the client knows the playing item, to avoid duplicate requests.
+ if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
+ {
+ _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString());
+ return;
+ }
+
+ var newItem = context.NextItemInQueue();
+ if (newItem)
+ {
+ // Send playing-queue update.
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextItem);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+ }
+ else
+ {
+ // Return to old state.
+ IGroupState newState = prevState switch
+ {
+ GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
+ GroupStateType.Paused => new PausedGroupState(LoggerFactory),
+ _ => new IdleGroupState(LoggerFactory)
+ };
+
+ context.SetState(newState);
+
+ _logger.LogDebug("No next item available in group {GroupId}.", context.GroupId.ToString());
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ // Save state if first event.
+ if (!InitialStateSet)
+ {
+ InitialState = prevState;
+ InitialStateSet = true;
+ }
+
+ ResumePlaying = true;
+
+ // Make sure the client knows the playing item, to avoid duplicate requests.
+ if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
+ {
+ _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString());
+ return;
+ }
+
+ var newItem = context.PreviousItemInQueue();
+ if (newItem)
+ {
+ // Send playing-queue update.
+ var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousItem);
+ var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
+
+ // Reset status of sessions and await for all Ready events.
+ context.SetAllBuffering(true);
+ }
+ else
+ {
+ // Return to old state.
+ IGroupState newState = prevState switch
+ {
+ GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
+ GroupStateType.Paused => new PausedGroupState(LoggerFactory),
+ _ => new IdleGroupState(LoggerFactory)
+ };
+
+ context.SetState(newState);
+
+ _logger.LogDebug("No previous item available in group {GroupId}.", context.GroupId.ToString());
+ }
+ }
+
+ /// <inheritdoc />
+ public override void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
+ {
+ context.SetIgnoreGroupWait(session, request.IgnoreWait);
+
+ if (!context.IsBuffering())
+ {
+ _logger.LogDebug("Ignoring session {SessionId}, group {GroupId} is ready.", session.Id, context.GroupId.ToString());
+
+ if (ResumePlaying)
+ {
+ // Client, that was buffering, stopped following playback.
+ var playingState = new PlayingGroupState(LoggerFactory);
+ context.SetState(playingState);
+ var unpauseRequest = new UnpauseGroupRequest();
+ playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken);
+ }
+ else
+ {
+ // Group is ready, returning to previous state.
+ var pausedState = new PausedGroupState(LoggerFactory);
+ context.SetState(pausedState);
+ }
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs
new file mode 100644
index 000000000..9045063ee
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs
@@ -0,0 +1,29 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Interface IGroupPlaybackRequest.
+ /// </summary>
+ public interface IGroupPlaybackRequest : ISyncPlayRequest
+ {
+ /// <summary>
+ /// Gets the playback request type.
+ /// </summary>
+ /// <returns>The playback request type.</returns>
+ PlaybackRequestType Action { get; }
+
+ /// <summary>
+ /// Applies the request to a group.
+ /// </summary>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="state">The current state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken);
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs
new file mode 100644
index 000000000..0666a62a8
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs
@@ -0,0 +1,219 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Interface IGroupState.
+ /// </summary>
+ public interface IGroupState
+ {
+ /// <summary>
+ /// Gets the group state type.
+ /// </summary>
+ /// <value>The group state type.</value>
+ GroupStateType Type { get; }
+
+ /// <summary>
+ /// Handles a session that joined the group.
+ /// </summary>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a session that is leaving the group.
+ /// </summary>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Generic handler. Context's state can change.
+ /// </summary>
+ /// <param name="request">The generic request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(IGroupPlaybackRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a play request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The play request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a set-playlist-item request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The set-playlist-item request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a remove-items request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The remove-items request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(RemoveFromPlaylistGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a move-playlist-item request from a session. Context's state should not change.
+ /// </summary>
+ /// <param name="request">The move-playlist-item request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(MovePlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a queue request from a session. Context's state should not change.
+ /// </summary>
+ /// <param name="request">The queue request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(QueueGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles an unpause request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The unpause request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a pause request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The pause request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a stop request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The stop request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a seek request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The seek request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a buffer request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The buffer request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a ready request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The ready request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a next-item request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The next-item request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a previous-item request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The previous-item request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a set-repeat-mode request from a session. Context's state should not change.
+ /// </summary>
+ /// <param name="request">The repeat-mode request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(SetRepeatModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a set-shuffle-mode request from a session. Context's state should not change.
+ /// </summary>
+ /// <param name="request">The shuffle-mode request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(SetShuffleModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Updates the ping of a session. Context's state should not change.
+ /// </summary>
+ /// <param name="request">The ping request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(PingGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Handles a ignore-wait request from a session. Context's state can change.
+ /// </summary>
+ /// <param name="request">The ignore-wait request.</param>
+ /// <param name="context">The context of the state.</param>
+ /// <param name="prevState">The previous state.</param>
+ /// <param name="session">The session.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken);
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs
new file mode 100644
index 000000000..d2de22450
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs
@@ -0,0 +1,230 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.Queue;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Interface IGroupStateContext.
+ /// </summary>
+ public interface IGroupStateContext
+ {
+ /// <summary>
+ /// Gets the default ping value used for sessions, in milliseconds.
+ /// </summary>
+ /// <value>The default ping value used for sessions, in milliseconds.</value>
+ long DefaultPing { get; }
+
+ /// <summary>
+ /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds.
+ /// </summary>
+ /// <value>The maximum offset error accepted, in milliseconds.</value>
+ long TimeSyncOffset { get; }
+
+ /// <summary>
+ /// Gets the maximum offset error accepted for position reported by clients, in milliseconds.
+ /// </summary>
+ /// <value>The maximum offset error accepted, in milliseconds.</value>
+ long MaxPlaybackOffset { get; }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ Guid GroupId { get; }
+
+ /// <summary>
+ /// Gets or sets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ long PositionTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the last activity.
+ /// </summary>
+ /// <value>The last activity.</value>
+ DateTime LastActivity { get; set; }
+
+ /// <summary>
+ /// Gets the play queue.
+ /// </summary>
+ /// <value>The play queue.</value>
+ PlayQueueManager PlayQueue { get; }
+
+ /// <summary>
+ /// Sets a new state.
+ /// </summary>
+ /// <param name="state">The new state.</param>
+ void SetState(IGroupState state);
+
+ /// <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>
+ /// <returns>The task.</returns>
+ Task SendGroupUpdate<T>(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Sends a playback command to the interested sessions.
+ /// </summary>
+ /// <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>
+ /// <returns>The task.</returns>
+ Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Builds a new playback command with some default values.
+ /// </summary>
+ /// <param name="type">The command type.</param>
+ /// <returns>The command.</returns>
+ 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>
+ /// <returns>The sanitized position ticks.</returns>
+ long SanitizePositionTicks(long? positionTicks);
+
+ /// <summary>
+ /// Updates the ping of a session, in milliseconds.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="ping">The ping, in milliseconds.</param>
+ void UpdatePing(SessionInfo session, long ping);
+
+ /// <summary>
+ /// Gets the highest ping in the group, in milliseconds.
+ /// </summary>
+ /// <returns>The highest ping in the group.</returns>
+ long GetHighestPing();
+
+ /// <summary>
+ /// Sets the session's buffering state.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="isBuffering">The state.</param>
+ void SetBuffering(SessionInfo session, bool isBuffering);
+
+ /// <summary>
+ /// Sets the buffering state of all the sessions.
+ /// </summary>
+ /// <param name="isBuffering">The state.</param>
+ void SetAllBuffering(bool isBuffering);
+
+ /// <summary>
+ /// Gets the group buffering state.
+ /// </summary>
+ /// <returns><c>true</c> if there is a session buffering in the group; <c>false</c> otherwise.</returns>
+ bool IsBuffering();
+
+ /// <summary>
+ /// Sets the session's group wait state.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="ignoreGroupWait">The state.</param>
+ void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait);
+
+ /// <summary>
+ /// Sets a new play queue.
+ /// </summary>
+ /// <param name="playQueue">The new play queue.</param>
+ /// <param name="playingItemPosition">The playing item position in the play queue.</param>
+ /// <param name="startPositionTicks">The start position ticks.</param>
+ /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns>
+ bool SetPlayQueue(IReadOnlyList<Guid> playQueue, int playingItemPosition, long startPositionTicks);
+
+ /// <summary>
+ /// Sets the playing item.
+ /// </summary>
+ /// <param name="playlistItemId">The new playing item identifier.</param>
+ /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns>
+ bool SetPlayingItem(Guid playlistItemId);
+
+ /// <summary>
+ /// Clears the play queue.
+ /// </summary>
+ /// <param name="clearPlayingItem">Whether to remove the playing item as well.</param>
+ void ClearPlayQueue(bool clearPlayingItem);
+
+ /// <summary>
+ /// Removes items from the play queue.
+ /// </summary>
+ /// <param name="playlistItemIds">The items to remove.</param>
+ /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns>
+ bool RemoveFromPlayQueue(IReadOnlyList<Guid> playlistItemIds);
+
+ /// <summary>
+ /// Moves an item in the play queue.
+ /// </summary>
+ /// <param name="playlistItemId">The playlist identifier of the item to move.</param>
+ /// <param name="newIndex">The new position.</param>
+ /// <returns><c>true</c> if item has been moved; <c>false</c> if something went wrong.</returns>
+ bool MoveItemInPlayQueue(Guid playlistItemId, int newIndex);
+
+ /// <summary>
+ /// Updates the play queue.
+ /// </summary>
+ /// <param name="newItems">The new items to add to the play queue.</param>
+ /// <param name="mode">The mode with which the items will be added.</param>
+ /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns>
+ bool AddToPlayQueue(IReadOnlyList<Guid> newItems, GroupQueueMode mode);
+
+ /// <summary>
+ /// Restarts current item in play queue.
+ /// </summary>
+ void RestartCurrentItem();
+
+ /// <summary>
+ /// Picks next item in play queue.
+ /// </summary>
+ /// <returns><c>true</c> if the item changed; <c>false</c> otherwise.</returns>
+ bool NextItemInQueue();
+
+ /// <summary>
+ /// Picks previous item in play queue.
+ /// </summary>
+ /// <returns><c>true</c> if the item changed; <c>false</c> otherwise.</returns>
+ bool PreviousItemInQueue();
+
+ /// <summary>
+ /// Sets the repeat mode.
+ /// </summary>
+ /// <param name="mode">The new mode.</param>
+ void SetRepeatMode(GroupRepeatMode mode);
+
+ /// <summary>
+ /// Sets the shuffle mode.
+ /// </summary>
+ /// <param name="mode">The new mode.</param>
+ void SetShuffleMode(GroupShuffleMode mode);
+
+ /// <summary>
+ /// Creates a play queue update.
+ /// </summary>
+ /// <param name="reason">The reason for the update.</param>
+ /// <returns>The play queue update.</returns>
+ PlayQueueUpdate GetPlayQueueUpdate(PlayQueueUpdateReason reason);
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs
new file mode 100644
index 000000000..a6999a12c
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs
@@ -0,0 +1,64 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Controller.SyncPlay.Requests;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Interface ISyncPlayManager.
+ /// </summary>
+ public interface ISyncPlayManager
+ {
+ /// <summary>
+ /// Creates a new group.
+ /// </summary>
+ /// <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);
+
+ /// <summary>
+ /// Adds the session to a group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Removes the session from a group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Gets list of available groups for a session.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <returns>The list of available groups.</returns>
+ List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request);
+
+ /// <summary>
+ /// Handle a request by a session in a group.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="request">The request.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Checks whether a user has an active session using SyncPlay.
+ /// </summary>
+ /// <param name="userId">The user identifier to check.</param>
+ /// <returns><c>true</c> if the user is using SyncPlay; <c>false</c> otherwise.</returns>
+ bool IsUserActive(Guid userId);
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs
new file mode 100644
index 000000000..bf1981773
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs
@@ -0,0 +1,16 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay
+{
+ /// <summary>
+ /// Interface ISyncPlayRequest.
+ /// </summary>
+ public interface ISyncPlayRequest
+ {
+ /// <summary>
+ /// Gets the request type.
+ /// </summary>
+ /// <returns>The request type.</returns>
+ RequestType Type { get; }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs
new file mode 100644
index 000000000..ef496c103
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs
@@ -0,0 +1,31 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class AbstractPlaybackRequest.
+ /// </summary>
+ public abstract class AbstractPlaybackRequest : IGroupPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AbstractPlaybackRequest"/> class.
+ /// </summary>
+ protected AbstractPlaybackRequest()
+ {
+ // Do nothing.
+ }
+
+ /// <inheritdoc />
+ public RequestType Type { get; } = RequestType.Playback;
+
+ /// <inheritdoc />
+ public abstract PlaybackRequestType Action { get; }
+
+ /// <inheritdoc />
+ public abstract void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken);
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs
new file mode 100644
index 000000000..d188114c3
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs
@@ -0,0 +1,63 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class BufferGroupRequest.
+ /// </summary>
+ public class BufferGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BufferGroupRequest"/> class.
+ /// </summary>
+ /// <param name="when">When the request has been made, as reported by the client.</param>
+ /// <param name="positionTicks">The position ticks.</param>
+ /// <param name="isPlaying">Whether the client playback is unpaused.</param>
+ /// <param name="playlistItemId">The playlist item identifier of the playing item.</param>
+ public BufferGroupRequest(DateTime when, long positionTicks, bool isPlaying, Guid playlistItemId)
+ {
+ When = when;
+ PositionTicks = positionTicks;
+ IsPlaying = isPlaying;
+ PlaylistItemId = playlistItemId;
+ }
+
+ /// <summary>
+ /// Gets when the request has been made by the client.
+ /// </summary>
+ /// <value>The date of the request.</value>
+ public DateTime When { get; }
+
+ /// <summary>
+ /// Gets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the client playback is unpaused.
+ /// </summary>
+ /// <value>The client playback status.</value>
+ public bool IsPlaying { get; }
+
+ /// <summary>
+ /// Gets the playlist item identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist item identifier.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Buffer;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs
new file mode 100644
index 000000000..464c81dfd
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs
@@ -0,0 +1,38 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class IgnoreWaitGroupRequest.
+ /// </summary>
+ public class IgnoreWaitGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IgnoreWaitGroupRequest"/> class.
+ /// </summary>
+ /// <param name="ignoreWait">Whether the client should be ignored.</param>
+ public IgnoreWaitGroupRequest(bool ignoreWait)
+ {
+ IgnoreWait = ignoreWait;
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the client should be ignored.
+ /// </summary>
+ /// <value>The client group-wait status.</value>
+ public bool IgnoreWait { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.IgnoreWait;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs
new file mode 100644
index 000000000..be314e807
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs
@@ -0,0 +1,47 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class MovePlaylistItemGroupRequest.
+ /// </summary>
+ public class MovePlaylistItemGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovePlaylistItemGroupRequest"/> class.
+ /// </summary>
+ /// <param name="playlistItemId">The playlist identifier of the item.</param>
+ /// <param name="newIndex">The new position.</param>
+ public MovePlaylistItemGroupRequest(Guid playlistItemId, int newIndex)
+ {
+ PlaylistItemId = playlistItemId;
+ NewIndex = newIndex;
+ }
+
+ /// <summary>
+ /// Gets the playlist identifier of the item.
+ /// </summary>
+ /// <value>The playlist identifier of the item.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <summary>
+ /// Gets the new position.
+ /// </summary>
+ /// <value>The new position.</value>
+ public int NewIndex { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.MovePlaylistItem;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs
new file mode 100644
index 000000000..679076239
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs
@@ -0,0 +1,39 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class NextItemGroupRequest.
+ /// </summary>
+ public class NextItemGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NextItemGroupRequest"/> class.
+ /// </summary>
+ /// <param name="playlistItemId">The playing item identifier.</param>
+ public NextItemGroupRequest(Guid playlistItemId)
+ {
+ PlaylistItemId = playlistItemId;
+ }
+
+ /// <summary>
+ /// Gets the playing item identifier.
+ /// </summary>
+ /// <value>The playing item identifier.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.NextItem;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs
new file mode 100644
index 000000000..7ee18a366
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs
@@ -0,0 +1,23 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class PauseGroupRequest.
+ /// </summary>
+ public class PauseGroupRequest : AbstractPlaybackRequest
+ {
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Pause;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs
new file mode 100644
index 000000000..beab655c5
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs
@@ -0,0 +1,38 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class PingGroupRequest.
+ /// </summary>
+ public class PingGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PingGroupRequest"/> class.
+ /// </summary>
+ /// <param name="ping">The ping time.</param>
+ public PingGroupRequest(long ping)
+ {
+ Ping = ping;
+ }
+
+ /// <summary>
+ /// Gets the ping time.
+ /// </summary>
+ /// <value>The ping time.</value>
+ public long Ping { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Ping;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs
new file mode 100644
index 000000000..05ff262c1
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs
@@ -0,0 +1,56 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class PlayGroupRequest.
+ /// </summary>
+ public class PlayGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlayGroupRequest"/> class.
+ /// </summary>
+ /// <param name="playingQueue">The playing queue.</param>
+ /// <param name="playingItemPosition">The playing item position.</param>
+ /// <param name="startPositionTicks">The start position ticks.</param>
+ public PlayGroupRequest(IReadOnlyList<Guid> playingQueue, int playingItemPosition, long startPositionTicks)
+ {
+ PlayingQueue = playingQueue ?? Array.Empty<Guid>();
+ PlayingItemPosition = playingItemPosition;
+ StartPositionTicks = startPositionTicks;
+ }
+
+ /// <summary>
+ /// Gets the playing queue.
+ /// </summary>
+ /// <value>The playing queue.</value>
+ public IReadOnlyList<Guid> PlayingQueue { get; }
+
+ /// <summary>
+ /// Gets the position of the playing item in the queue.
+ /// </summary>
+ /// <value>The playing item position.</value>
+ public int PlayingItemPosition { get; }
+
+ /// <summary>
+ /// Gets the start position ticks.
+ /// </summary>
+ /// <value>The start position ticks.</value>
+ public long StartPositionTicks { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Play;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs
new file mode 100644
index 000000000..3e34b6ce4
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs
@@ -0,0 +1,39 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class PreviousItemGroupRequest.
+ /// </summary>
+ public class PreviousItemGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PreviousItemGroupRequest"/> class.
+ /// </summary>
+ /// <param name="playlistItemId">The playing item identifier.</param>
+ public PreviousItemGroupRequest(Guid playlistItemId)
+ {
+ PlaylistItemId = playlistItemId;
+ }
+
+ /// <summary>
+ /// Gets the playing item identifier.
+ /// </summary>
+ /// <value>The playing item identifier.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.PreviousItem;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs
new file mode 100644
index 000000000..0f91476de
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs
@@ -0,0 +1,48 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class QueueGroupRequest.
+ /// </summary>
+ public class QueueGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QueueGroupRequest"/> class.
+ /// </summary>
+ /// <param name="items">The items to add to the queue.</param>
+ /// <param name="mode">The enqueue mode.</param>
+ public QueueGroupRequest(IReadOnlyList<Guid> items, GroupQueueMode mode)
+ {
+ ItemIds = items ?? Array.Empty<Guid>();
+ Mode = mode;
+ }
+
+ /// <summary>
+ /// Gets the items to enqueue.
+ /// </summary>
+ /// <value>The items to enqueue.</value>
+ public IReadOnlyList<Guid> ItemIds { get; }
+
+ /// <summary>
+ /// Gets the mode in which to add the new items.
+ /// </summary>
+ /// <value>The enqueue mode.</value>
+ public GroupQueueMode Mode { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Queue;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs
new file mode 100644
index 000000000..b1f0bd360
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs
@@ -0,0 +1,63 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class ReadyGroupRequest.
+ /// </summary>
+ public class ReadyGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReadyGroupRequest"/> class.
+ /// </summary>
+ /// <param name="when">When the request has been made, as reported by the client.</param>
+ /// <param name="positionTicks">The position ticks.</param>
+ /// <param name="isPlaying">Whether the client playback is unpaused.</param>
+ /// <param name="playlistItemId">The playlist item identifier of the playing item.</param>
+ public ReadyGroupRequest(DateTime when, long positionTicks, bool isPlaying, Guid playlistItemId)
+ {
+ When = when;
+ PositionTicks = positionTicks;
+ IsPlaying = isPlaying;
+ PlaylistItemId = playlistItemId;
+ }
+
+ /// <summary>
+ /// Gets when the request has been made by the client.
+ /// </summary>
+ /// <value>The date of the request.</value>
+ public DateTime When { get; }
+
+ /// <summary>
+ /// Gets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the client playback is unpaused.
+ /// </summary>
+ /// <value>The client playback status.</value>
+ public bool IsPlaying { get; }
+
+ /// <summary>
+ /// Gets the playlist item identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist item identifier.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Ready;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs
new file mode 100644
index 000000000..2f38d6adc
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs
@@ -0,0 +1,56 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class RemoveFromPlaylistGroupRequest.
+ /// </summary>
+ public class RemoveFromPlaylistGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RemoveFromPlaylistGroupRequest"/> class.
+ /// </summary>
+ /// <param name="items">The playlist ids of the items to remove.</param>
+ /// <param name="clearPlaylist">Whether to clear the entire playlist. The items list will be ignored.</param>
+ /// <param name="clearPlayingItem">Whether to remove the playing item as well. Used only when clearing the playlist.</param>
+ public RemoveFromPlaylistGroupRequest(IReadOnlyList<Guid> items, bool clearPlaylist = false, bool clearPlayingItem = false)
+ {
+ PlaylistItemIds = items ?? Array.Empty<Guid>();
+ ClearPlaylist = clearPlaylist;
+ ClearPlayingItem = clearPlayingItem;
+ }
+
+ /// <summary>
+ /// Gets the playlist identifiers ot the items.
+ /// </summary>
+ /// <value>The playlist identifiers ot the items.</value>
+ public IReadOnlyList<Guid> PlaylistItemIds { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the entire playlist should be cleared.
+ /// </summary>
+ /// <value>Whether the entire playlist should be cleared.</value>
+ public bool ClearPlaylist { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the playing item should be removed as well.
+ /// </summary>
+ /// <value>Whether the playing item should be removed as well.</value>
+ public bool ClearPlayingItem { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.RemoveFromPlaylist;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs
new file mode 100644
index 000000000..196113374
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs
@@ -0,0 +1,38 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class SeekGroupRequest.
+ /// </summary>
+ public class SeekGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeekGroupRequest"/> class.
+ /// </summary>
+ /// <param name="positionTicks">The position ticks.</param>
+ public SeekGroupRequest(long positionTicks)
+ {
+ PositionTicks = positionTicks;
+ }
+
+ /// <summary>
+ /// Gets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long PositionTicks { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Seek;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs
new file mode 100644
index 000000000..44df127a6
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs
@@ -0,0 +1,39 @@
+#nullable disable
+
+using System;
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class SetPlaylistItemGroupRequest.
+ /// </summary>
+ public class SetPlaylistItemGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetPlaylistItemGroupRequest"/> class.
+ /// </summary>
+ /// <param name="playlistItemId">The playlist identifier of the item.</param>
+ public SetPlaylistItemGroupRequest(Guid playlistItemId)
+ {
+ PlaylistItemId = playlistItemId;
+ }
+
+ /// <summary>
+ /// Gets the playlist identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist identifier of the playing item.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetPlaylistItem;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs
new file mode 100644
index 000000000..d250eab56
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs
@@ -0,0 +1,38 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class SetRepeatModeGroupRequest.
+ /// </summary>
+ public class SetRepeatModeGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetRepeatModeGroupRequest"/> class.
+ /// </summary>
+ /// <param name="mode">The repeat mode.</param>
+ public SetRepeatModeGroupRequest(GroupRepeatMode mode)
+ {
+ Mode = mode;
+ }
+
+ /// <summary>
+ /// Gets the repeat mode.
+ /// </summary>
+ /// <value>The repeat mode.</value>
+ public GroupRepeatMode Mode { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetRepeatMode;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs
new file mode 100644
index 000000000..5034e992e
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs
@@ -0,0 +1,38 @@
+#nullable disable
+
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class SetShuffleModeGroupRequest.
+ /// </summary>
+ public class SetShuffleModeGroupRequest : AbstractPlaybackRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetShuffleModeGroupRequest"/> class.
+ /// </summary>
+ /// <param name="mode">The shuffle mode.</param>
+ public SetShuffleModeGroupRequest(GroupShuffleMode mode)
+ {
+ Mode = mode;
+ }
+
+ /// <summary>
+ /// Gets the shuffle mode.
+ /// </summary>
+ /// <value>The shuffle mode.</value>
+ public GroupShuffleMode Mode { get; }
+
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetShuffleMode;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs
new file mode 100644
index 000000000..ad739213c
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs
@@ -0,0 +1,21 @@
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class StopGroupRequest.
+ /// </summary>
+ public class StopGroupRequest : AbstractPlaybackRequest
+ {
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Stop;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs
new file mode 100644
index 000000000..aaf3d65a8
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs
@@ -0,0 +1,21 @@
+using System.Threading;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests
+{
+ /// <summary>
+ /// Class UnpauseGroupRequest.
+ /// </summary>
+ public class UnpauseGroupRequest : AbstractPlaybackRequest
+ {
+ /// <inheritdoc />
+ public override PlaybackRequestType Action { get; } = PlaybackRequestType.Unpause;
+
+ /// <inheritdoc />
+ public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken)
+ {
+ state.HandleRequest(this, context, state.Type, session, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs
new file mode 100644
index 000000000..f49876cca
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs
@@ -0,0 +1,557 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Jellyfin.Extensions;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.Queue
+{
+ /// <summary>
+ /// Class PlayQueueManager.
+ /// </summary>
+ public class PlayQueueManager
+ {
+ /// <summary>
+ /// Placeholder index for when no item is playing.
+ /// </summary>
+ /// <value>The no-playing item index.</value>
+ private const int NoPlayingItemIndex = -1;
+
+ /// <summary>
+ /// The sorted playlist.
+ /// </summary>
+ /// <value>The sorted playlist, or play queue of the group.</value>
+ private List<QueueItem> _sortedPlaylist = new List<QueueItem>();
+
+ /// <summary>
+ /// The shuffled playlist.
+ /// </summary>
+ /// <value>The shuffled playlist, or play queue of the group.</value>
+ private List<QueueItem> _shuffledPlaylist = new List<QueueItem>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlayQueueManager" /> class.
+ /// </summary>
+ public PlayQueueManager()
+ {
+ Reset();
+ }
+
+ /// <summary>
+ /// Gets the playing item index.
+ /// </summary>
+ /// <value>The playing item index.</value>
+ public int PlayingItemIndex { get; private set; }
+
+ /// <summary>
+ /// Gets the last time the queue has been changed.
+ /// </summary>
+ /// <value>The last time the queue has been changed.</value>
+ public DateTime LastChange { get; private set; }
+
+ /// <summary>
+ /// Gets the shuffle mode.
+ /// </summary>
+ /// <value>The shuffle mode.</value>
+ public GroupShuffleMode ShuffleMode { get; private set; } = GroupShuffleMode.Sorted;
+
+ /// <summary>
+ /// Gets the repeat mode.
+ /// </summary>
+ /// <value>The repeat mode.</value>
+ public GroupRepeatMode RepeatMode { get; private set; } = GroupRepeatMode.RepeatNone;
+
+ /// <summary>
+ /// Checks if an item is playing.
+ /// </summary>
+ /// <returns><c>true</c> if an item is playing; <c>false</c> otherwise.</returns>
+ public bool IsItemPlaying()
+ {
+ return PlayingItemIndex != NoPlayingItemIndex;
+ }
+
+ /// <summary>
+ /// Gets the current playlist considering the shuffle mode.
+ /// </summary>
+ /// <returns>The playlist.</returns>
+ public IReadOnlyList<QueueItem> GetPlaylist()
+ {
+ return GetPlaylistInternal();
+ }
+
+ /// <summary>
+ /// Sets a new playlist. Playing item is reset.
+ /// </summary>
+ /// <param name="items">The new items of the playlist.</param>
+ public void SetPlaylist(IReadOnlyList<Guid> items)
+ {
+ _sortedPlaylist.Clear();
+ _shuffledPlaylist.Clear();
+
+ _sortedPlaylist = CreateQueueItemsFromArray(items);
+ if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ _shuffledPlaylist = new List<QueueItem>(_sortedPlaylist);
+ _shuffledPlaylist.Shuffle();
+ }
+
+ PlayingItemIndex = NoPlayingItemIndex;
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Appends new items to the playlist. The specified order is mantained.
+ /// </summary>
+ /// <param name="items">The items to add to the playlist.</param>
+ public void Queue(IReadOnlyList<Guid> items)
+ {
+ var newItems = CreateQueueItemsFromArray(items);
+
+ _sortedPlaylist.AddRange(newItems);
+ if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ _shuffledPlaylist.AddRange(newItems);
+ }
+
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Shuffles the playlist. Shuffle mode is changed. The playlist gets re-shuffled if already shuffled.
+ /// </summary>
+ public void ShufflePlaylist()
+ {
+ if (PlayingItemIndex == NoPlayingItemIndex)
+ {
+ _shuffledPlaylist = new List<QueueItem>(_sortedPlaylist);
+ _shuffledPlaylist.Shuffle();
+ }
+ else if (ShuffleMode.Equals(GroupShuffleMode.Sorted))
+ {
+ // First time shuffle.
+ var playingItem = _sortedPlaylist[PlayingItemIndex];
+ _shuffledPlaylist = new List<QueueItem>(_sortedPlaylist);
+ _shuffledPlaylist.RemoveAt(PlayingItemIndex);
+ _shuffledPlaylist.Shuffle();
+ _shuffledPlaylist.Insert(0, playingItem);
+ PlayingItemIndex = 0;
+ }
+ else
+ {
+ // Re-shuffle playlist.
+ var playingItem = _shuffledPlaylist[PlayingItemIndex];
+ _shuffledPlaylist.RemoveAt(PlayingItemIndex);
+ _shuffledPlaylist.Shuffle();
+ _shuffledPlaylist.Insert(0, playingItem);
+ PlayingItemIndex = 0;
+ }
+
+ ShuffleMode = GroupShuffleMode.Shuffle;
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Resets the playlist to sorted mode. Shuffle mode is changed.
+ /// </summary>
+ public void RestoreSortedPlaylist()
+ {
+ if (PlayingItemIndex != NoPlayingItemIndex)
+ {
+ var playingItem = _shuffledPlaylist[PlayingItemIndex];
+ PlayingItemIndex = _sortedPlaylist.IndexOf(playingItem);
+ }
+
+ _shuffledPlaylist.Clear();
+
+ ShuffleMode = GroupShuffleMode.Sorted;
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Clears the playlist. Shuffle mode is preserved.
+ /// </summary>
+ /// <param name="clearPlayingItem">Whether to remove the playing item as well.</param>
+ public void ClearPlaylist(bool clearPlayingItem)
+ {
+ var playingItem = GetPlayingItem();
+ _sortedPlaylist.Clear();
+ _shuffledPlaylist.Clear();
+ LastChange = DateTime.UtcNow;
+
+ if (!clearPlayingItem && playingItem != null)
+ {
+ _sortedPlaylist.Add(playingItem);
+ if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ _shuffledPlaylist.Add(playingItem);
+ }
+
+ PlayingItemIndex = 0;
+ }
+ else
+ {
+ PlayingItemIndex = NoPlayingItemIndex;
+ }
+ }
+
+ /// <summary>
+ /// Adds new items to the playlist right after the playing item. The specified order is mantained.
+ /// </summary>
+ /// <param name="items">The items to add to the playlist.</param>
+ public void QueueNext(IReadOnlyList<Guid> items)
+ {
+ var newItems = CreateQueueItemsFromArray(items);
+
+ if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ var playingItem = GetPlayingItem();
+ var sortedPlayingItemIndex = _sortedPlaylist.IndexOf(playingItem);
+ // Append items to sorted and shuffled playlist as they are.
+ _sortedPlaylist.InsertRange(sortedPlayingItemIndex + 1, newItems);
+ _shuffledPlaylist.InsertRange(PlayingItemIndex + 1, newItems);
+ }
+ else
+ {
+ _sortedPlaylist.InsertRange(PlayingItemIndex + 1, newItems);
+ }
+
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets playlist identifier of the playing item, if any.
+ /// </summary>
+ /// <returns>The playlist identifier of the playing item.</returns>
+ public Guid GetPlayingItemPlaylistId()
+ {
+ var playingItem = GetPlayingItem();
+ return playingItem?.PlaylistItemId ?? Guid.Empty;
+ }
+
+ /// <summary>
+ /// Gets the playing item identifier, if any.
+ /// </summary>
+ /// <returns>The playing item identifier.</returns>
+ public Guid GetPlayingItemId()
+ {
+ var playingItem = GetPlayingItem();
+ return playingItem?.ItemId ?? Guid.Empty;
+ }
+
+ /// <summary>
+ /// Sets the playing item using its identifier. If not in the playlist, the playing item is reset.
+ /// </summary>
+ /// <param name="itemId">The new playing item identifier.</param>
+ public void SetPlayingItemById(Guid itemId)
+ {
+ var playlist = GetPlaylistInternal();
+ PlayingItemIndex = playlist.FindIndex(item => item.ItemId.Equals(itemId));
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Sets the playing item using its playlist identifier. If not in the playlist, the playing item is reset.
+ /// </summary>
+ /// <param name="playlistItemId">The new playing item identifier.</param>
+ /// <returns><c>true</c> if playing item has been set; <c>false</c> if item is not in the playlist.</returns>
+ public bool SetPlayingItemByPlaylistId(Guid playlistItemId)
+ {
+ var playlist = GetPlaylistInternal();
+ PlayingItemIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId));
+ LastChange = DateTime.UtcNow;
+
+ return PlayingItemIndex != NoPlayingItemIndex;
+ }
+
+ /// <summary>
+ /// Sets the playing item using its position. If not in range, the playing item is reset.
+ /// </summary>
+ /// <param name="playlistIndex">The new playing item index.</param>
+ public void SetPlayingItemByIndex(int playlistIndex)
+ {
+ var playlist = GetPlaylistInternal();
+ if (playlistIndex < 0 || playlistIndex > playlist.Count)
+ {
+ PlayingItemIndex = NoPlayingItemIndex;
+ }
+ else
+ {
+ PlayingItemIndex = playlistIndex;
+ }
+
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Removes items from the playlist. If not removed, the playing item is preserved.
+ /// </summary>
+ /// <param name="playlistItemIds">The items to remove.</param>
+ /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns>
+ public bool RemoveFromPlaylist(IReadOnlyList<Guid> playlistItemIds)
+ {
+ var playingItem = GetPlayingItem();
+
+ _sortedPlaylist.RemoveAll(item => playlistItemIds.Contains(item.PlaylistItemId));
+ _shuffledPlaylist.RemoveAll(item => playlistItemIds.Contains(item.PlaylistItemId));
+
+ LastChange = DateTime.UtcNow;
+
+ if (playingItem != null)
+ {
+ if (playlistItemIds.Contains(playingItem.PlaylistItemId))
+ {
+ // Playing item has been removed, picking previous item.
+ PlayingItemIndex--;
+ if (PlayingItemIndex < 0)
+ {
+ // Was first element, picking next if available.
+ // Default to no playing item otherwise.
+ PlayingItemIndex = _sortedPlaylist.Count > 0 ? 0 : NoPlayingItemIndex;
+ }
+
+ return true;
+ }
+ else
+ {
+ // Restoring playing item.
+ SetPlayingItemByPlaylistId(playingItem.PlaylistItemId);
+ return false;
+ }
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Moves an item in the playlist to another position.
+ /// </summary>
+ /// <param name="playlistItemId">The item to move.</param>
+ /// <param name="newIndex">The new position.</param>
+ /// <returns><c>true</c> if the item has been moved; <c>false</c> otherwise.</returns>
+ public bool MovePlaylistItem(Guid playlistItemId, int newIndex)
+ {
+ var playlist = GetPlaylistInternal();
+ var playingItem = GetPlayingItem();
+
+ var oldIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId));
+ if (oldIndex < 0)
+ {
+ return false;
+ }
+
+ var queueItem = playlist[oldIndex];
+ playlist.RemoveAt(oldIndex);
+ newIndex = Math.Clamp(newIndex, 0, playlist.Count);
+ playlist.Insert(newIndex, queueItem);
+
+ LastChange = DateTime.UtcNow;
+ PlayingItemIndex = playlist.IndexOf(playingItem);
+ return true;
+ }
+
+ /// <summary>
+ /// Resets the playlist to its initial state.
+ /// </summary>
+ public void Reset()
+ {
+ _sortedPlaylist.Clear();
+ _shuffledPlaylist.Clear();
+ PlayingItemIndex = NoPlayingItemIndex;
+ ShuffleMode = GroupShuffleMode.Sorted;
+ RepeatMode = GroupRepeatMode.RepeatNone;
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Sets the repeat mode.
+ /// </summary>
+ /// <param name="mode">The new mode.</param>
+ public void SetRepeatMode(GroupRepeatMode mode)
+ {
+ RepeatMode = mode;
+ LastChange = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Sets the shuffle mode.
+ /// </summary>
+ /// <param name="mode">The new mode.</param>
+ public void SetShuffleMode(GroupShuffleMode mode)
+ {
+ if (mode.Equals(GroupShuffleMode.Shuffle))
+ {
+ ShufflePlaylist();
+ }
+ else
+ {
+ RestoreSortedPlaylist();
+ }
+ }
+
+ /// <summary>
+ /// Toggles the shuffle mode between sorted and shuffled.
+ /// </summary>
+ public void ToggleShuffleMode()
+ {
+ if (ShuffleMode.Equals(GroupShuffleMode.Sorted))
+ {
+ ShufflePlaylist();
+ }
+ else
+ {
+ RestoreSortedPlaylist();
+ }
+ }
+
+ /// <summary>
+ /// Gets the next item in the playlist considering repeat mode and shuffle mode.
+ /// </summary>
+ /// <returns>The next item in the playlist.</returns>
+ public QueueItem GetNextItemPlaylistId()
+ {
+ int newIndex;
+ var playlist = GetPlaylistInternal();
+
+ switch (RepeatMode)
+ {
+ case GroupRepeatMode.RepeatOne:
+ newIndex = PlayingItemIndex;
+ break;
+ case GroupRepeatMode.RepeatAll:
+ newIndex = PlayingItemIndex + 1;
+ if (newIndex >= playlist.Count)
+ {
+ newIndex = 0;
+ }
+
+ break;
+ default:
+ newIndex = PlayingItemIndex + 1;
+ break;
+ }
+
+ if (newIndex < 0 || newIndex >= playlist.Count)
+ {
+ return null;
+ }
+
+ return playlist[newIndex];
+ }
+
+ /// <summary>
+ /// Sets the next item in the queue as playing item.
+ /// </summary>
+ /// <returns><c>true</c> if the playing item changed; <c>false</c> otherwise.</returns>
+ public bool Next()
+ {
+ if (RepeatMode.Equals(GroupRepeatMode.RepeatOne))
+ {
+ LastChange = DateTime.UtcNow;
+ return true;
+ }
+
+ PlayingItemIndex++;
+ if (PlayingItemIndex >= _sortedPlaylist.Count)
+ {
+ if (RepeatMode.Equals(GroupRepeatMode.RepeatAll))
+ {
+ PlayingItemIndex = 0;
+ }
+ else
+ {
+ PlayingItemIndex = _sortedPlaylist.Count - 1;
+ return false;
+ }
+ }
+
+ LastChange = DateTime.UtcNow;
+ return true;
+ }
+
+ /// <summary>
+ /// Sets the previous item in the queue as playing item.
+ /// </summary>
+ /// <returns><c>true</c> if the playing item changed; <c>false</c> otherwise.</returns>
+ public bool Previous()
+ {
+ if (RepeatMode.Equals(GroupRepeatMode.RepeatOne))
+ {
+ LastChange = DateTime.UtcNow;
+ return true;
+ }
+
+ PlayingItemIndex--;
+ if (PlayingItemIndex < 0)
+ {
+ if (RepeatMode.Equals(GroupRepeatMode.RepeatAll))
+ {
+ PlayingItemIndex = _sortedPlaylist.Count - 1;
+ }
+ else
+ {
+ PlayingItemIndex = 0;
+ return false;
+ }
+ }
+
+ LastChange = DateTime.UtcNow;
+ return true;
+ }
+
+ /// <summary>
+ /// Creates a list from the array of items. Each item is given an unique playlist identifier.
+ /// </summary>
+ /// <returns>The list of queue items.</returns>
+ private List<QueueItem> CreateQueueItemsFromArray(IReadOnlyList<Guid> items)
+ {
+ var list = new List<QueueItem>();
+ foreach (var item in items)
+ {
+ var queueItem = new QueueItem(item);
+ list.Add(queueItem);
+ }
+
+ return list;
+ }
+
+ /// <summary>
+ /// Gets the current playlist considering the shuffle mode.
+ /// </summary>
+ /// <returns>The playlist.</returns>
+ private List<QueueItem> GetPlaylistInternal()
+ {
+ if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ return _shuffledPlaylist;
+ }
+ else
+ {
+ return _sortedPlaylist;
+ }
+ }
+
+ /// <summary>
+ /// Gets the current playing item, depending on the shuffle mode.
+ /// </summary>
+ /// <returns>The playing item.</returns>
+ private QueueItem GetPlayingItem()
+ {
+ if (PlayingItemIndex == NoPlayingItemIndex)
+ {
+ return null;
+ }
+ else if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
+ {
+ return _shuffledPlaylist[PlayingItemIndex];
+ }
+ else
+ {
+ return _sortedPlaylist[PlayingItemIndex];
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs
new file mode 100644
index 000000000..38c9e8e20
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs
@@ -0,0 +1,29 @@
+using System;
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.Requests
+{
+ /// <summary>
+ /// Class JoinGroupRequest.
+ /// </summary>
+ public class JoinGroupRequest : ISyncPlayRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JoinGroupRequest"/> class.
+ /// </summary>
+ /// <param name="groupId">The identifier of the group to join.</param>
+ public JoinGroupRequest(Guid groupId)
+ {
+ GroupId = groupId;
+ }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The identifier of the group to join.</value>
+ public Guid GroupId { get; }
+
+ /// <inheritdoc />
+ public RequestType Type { get; } = RequestType.JoinGroup;
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs
new file mode 100644
index 000000000..545778264
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs
@@ -0,0 +1,13 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.Requests
+{
+ /// <summary>
+ /// Class LeaveGroupRequest.
+ /// </summary>
+ public class LeaveGroupRequest : ISyncPlayRequest
+ {
+ /// <inheritdoc />
+ public RequestType Type { get; } = RequestType.LeaveGroup;
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs
new file mode 100644
index 000000000..4a234fdab
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs
@@ -0,0 +1,13 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.Requests
+{
+ /// <summary>
+ /// Class ListGroupsRequest.
+ /// </summary>
+ public class ListGroupsRequest : ISyncPlayRequest
+ {
+ /// <inheritdoc />
+ public RequestType Type { get; } = RequestType.ListGroups;
+ }
+}
diff --git a/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs
new file mode 100644
index 000000000..1321f0de8
--- /dev/null
+++ b/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs
@@ -0,0 +1,28 @@
+using MediaBrowser.Model.SyncPlay;
+
+namespace MediaBrowser.Controller.SyncPlay.Requests
+{
+ /// <summary>
+ /// Class NewGroupRequest.
+ /// </summary>
+ public class NewGroupRequest : ISyncPlayRequest
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NewGroupRequest"/> class.
+ /// </summary>
+ /// <param name="groupName">The name of the new group.</param>
+ public NewGroupRequest(string groupName)
+ {
+ GroupName = groupName;
+ }
+
+ /// <summary>
+ /// Gets the group name.
+ /// </summary>
+ /// <value>The name of the new group.</value>
+ public string GroupName { get; }
+
+ /// <inheritdoc />
+ public RequestType Type { get; } = RequestType.NewGroup;
+ }
+}
diff --git a/MediaBrowser.Controller/TV/ITVSeriesManager.cs b/MediaBrowser.Controller/TV/ITVSeriesManager.cs
index 09a0f6fea..e066c03fd 100644
--- a/MediaBrowser.Controller/TV/ITVSeriesManager.cs
+++ b/MediaBrowser.Controller/TV/ITVSeriesManager.cs
@@ -1,19 +1,31 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.TV
{
+ /// <summary>
+ /// The TV Series manager.
+ /// </summary>
public interface ITVSeriesManager
{
/// <summary>
/// Gets the next up.
/// </summary>
+ /// <param name="query">The next up query.</param>
+ /// <param name="options">The dto options.</param>
+ /// <returns>The next up items.</returns>
QueryResult<BaseItem> GetNextUp(NextUpQuery query, DtoOptions options);
/// <summary>
/// Gets the next up.
/// </summary>
+ /// <param name="request">The next up request.</param>
+ /// <param name="parentsFolders">The list of parent folders.</param>
+ /// <param name="options">The dto options.</param>
+ /// <returns>The next up items.</returns>
QueryResult<BaseItem> GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions options);
}
}
diff --git a/MediaBrowser.LocalMetadata/BaseXmlProvider.cs b/MediaBrowser.LocalMetadata/BaseXmlProvider.cs
index a6553563f..9f8e921b4 100644
--- a/MediaBrowser.LocalMetadata/BaseXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/BaseXmlProvider.cs
@@ -7,12 +7,43 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.LocalMetadata
{
+ /// <summary>
+ /// The BaseXmlProvider.
+ /// </summary>
+ /// <typeparam name="T">Type of provider.</typeparam>
public abstract class BaseXmlProvider<T> : ILocalMetadataProvider<T>, IHasItemChangeMonitor, IHasOrder
where T : BaseItem, new()
{
- protected IFileSystem FileSystem;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseXmlProvider{T}"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ protected BaseXmlProvider(IFileSystem fileSystem)
+ {
+ this.FileSystem = fileSystem;
+ }
+
+ /// <inheritdoc />
+ public string Name => XmlProviderUtils.Name;
- public Task<MetadataResult<T>> GetMetadata(ItemInfo info,
+ /// After Nfo
+ /// <inheritdoc />
+ public virtual int Order => 1;
+
+ /// <summary>
+ /// Gets the IFileSystem.
+ /// </summary>
+ protected IFileSystem FileSystem { get; }
+
+ /// <summary>
+ /// Gets metadata for item.
+ /// </summary>
+ /// <param name="info">The item info.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The metadata for item.</returns>
+ public Task<MetadataResult<T>> GetMetadata(
+ ItemInfo info,
IDirectoryService directoryService,
CancellationToken cancellationToken)
{
@@ -46,15 +77,23 @@ namespace MediaBrowser.LocalMetadata
return Task.FromResult(result);
}
+ /// <summary>
+ /// Get metadata from path.
+ /// </summary>
+ /// <param name="result">Resulting metadata.</param>
+ /// <param name="path">The path.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
protected abstract void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken);
- protected BaseXmlProvider(IFileSystem fileSystem)
- {
- FileSystem = fileSystem;
- }
-
- protected abstract FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService);
+ /// <summary>
+ /// Get metadata from xml file.
+ /// </summary>
+ /// <param name="info">Item inf.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ /// <returns>The file system metadata.</returns>
+ protected abstract FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService);
+ /// <inheritdoc />
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
var file = GetXmlFile(new ItemInfo(item), directoryService);
@@ -66,15 +105,5 @@ namespace MediaBrowser.LocalMetadata
return file.Exists && FileSystem.GetLastWriteTimeUtc(file) > item.DateLastSaved;
}
-
- public string Name => XmlProviderUtils.Name;
-
- //After Nfo
- public virtual int Order => 1;
- }
-
- static class XmlProviderUtils
- {
- public static string Name => "Emby Xml";
}
}
diff --git a/MediaBrowser.LocalMetadata/Images/CollectionFolderImageProvider.cs b/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs
index 206e761bb..b6189bcdd 100644
--- a/MediaBrowser.LocalMetadata/Images/CollectionFolderImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs
@@ -5,30 +5,41 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.LocalMetadata.Images
{
- public class CollectionFolderLocalImageProvider : ILocalImageFileProvider, IHasOrder
+ /// <summary>
+ /// Collection folder local image provider.
+ /// </summary>
+ public class CollectionFolderLocalImageProvider : ILocalImageProvider, IHasOrder
{
private readonly IFileSystem _fileSystem;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionFolderLocalImageProvider"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
public CollectionFolderLocalImageProvider(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
+ /// <inheritdoc />
public string Name => "Collection Folder Images";
+ /// Run after LocalImageProvider
+ /// <inheritdoc />
+ public int Order => 1;
+
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
return item is CollectionFolder && item.SupportsLocalMetadata;
}
- // Run after LocalImageProvider
- public int Order => 1;
-
- public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
+ /// <inheritdoc />
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
{
var collectionFolder = (CollectionFolder)item;
- return new LocalImageProvider(_fileSystem).GetImages(item, collectionFolder.PhysicalLocations, true, directoryService);
+ return new LocalImageProvider(_fileSystem).GetImages(item, collectionFolder.PhysicalLocations, directoryService);
}
}
}
diff --git a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs
index 443f3fbb5..dc13bf4f6 100644
--- a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
@@ -10,38 +11,42 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.LocalMetadata.Images
{
- public class EpisodeLocalLocalImageProvider : ILocalImageFileProvider, IHasOrder
+ /// <summary>
+ /// Episode local image provider.
+ /// </summary>
+ public class EpisodeLocalImageProvider : ILocalImageProvider, IHasOrder
{
- private readonly IFileSystem _fileSystem;
-
- public EpisodeLocalLocalImageProvider(IFileSystem fileSystem)
- {
- _fileSystem = fileSystem;
- }
-
+ /// <inheritdoc />
public string Name => "Local Images";
+ /// <inheritdoc />
public int Order => 0;
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
return item is Episode && item.SupportsLocalMetadata;
}
- public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
+ /// <inheritdoc />
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
{
var parentPath = Path.GetDirectoryName(item.Path);
+ if (parentPath == null)
+ {
+ return Enumerable.Empty<LocalImageInfo>();
+ }
var parentPathFiles = directoryService.GetFiles(parentPath);
- var nameWithoutExtension = Path.GetFileNameWithoutExtension(item.Path);
+ var nameWithoutExtension = Path.GetFileNameWithoutExtension(item.Path.AsSpan());
return GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles);
}
- private List<LocalImageInfo> GetFilesFromParentFolder(string filenameWithoutExtension, List<FileSystemMetadata> parentPathFiles)
+ private List<LocalImageInfo> GetFilesFromParentFolder(ReadOnlySpan<char> filenameWithoutExtension, List<FileSystemMetadata> parentPathFiles)
{
- var thumbName = filenameWithoutExtension + "-thumb";
+ var thumbName = string.Concat(filenameWithoutExtension, "-thumb");
var list = new List<LocalImageInfo>(1);
@@ -52,29 +57,21 @@ namespace MediaBrowser.LocalMetadata.Images
continue;
}
- if (BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
+ if (BaseItem.SupportedImageExtensions.Contains(i.Extension.AsSpan(), StringComparison.OrdinalIgnoreCase))
{
- var currentNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(i);
+ var currentNameWithoutExtension = Path.GetFileNameWithoutExtension(i.FullName.AsSpan());
- if (string.Equals(filenameWithoutExtension, currentNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
+ if (filenameWithoutExtension.Equals(currentNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
{
- list.Add(new LocalImageInfo
- {
- FileInfo = i,
- Type = ImageType.Primary
- });
+ list.Add(new LocalImageInfo { FileInfo = i, Type = ImageType.Primary });
}
-
- else if (string.Equals(thumbName, currentNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
+ else if (currentNameWithoutExtension.Equals(thumbName, StringComparison.OrdinalIgnoreCase))
{
- list.Add(new LocalImageInfo
- {
- FileInfo = i,
- Type = ImageType.Primary
- });
+ list.Add(new LocalImageInfo { FileInfo = i, Type = ImageType.Primary });
}
}
}
+
return list;
}
}
diff --git a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs
index c0706ceeb..10d691b3e 100644
--- a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs
@@ -1,26 +1,48 @@
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Images
{
- public class InternalMetadataFolderImageProvider : ILocalImageFileProvider, IHasOrder
+ /// <summary>
+ /// Internal metadata folder image provider.
+ /// </summary>
+ public class InternalMetadataFolderImageProvider : ILocalImageProvider, IHasOrder
{
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
+ private readonly ILogger<InternalMetadataFolderImageProvider> _logger;
- public InternalMetadataFolderImageProvider(IServerConfigurationManager config, IFileSystem fileSystem)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InternalMetadataFolderImageProvider"/> class.
+ /// </summary>
+ /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{InternalMetadataFolderImageProvider}"/> interface.</param>
+ public InternalMetadataFolderImageProvider(
+ IServerConfigurationManager config,
+ IFileSystem fileSystem,
+ ILogger<InternalMetadataFolderImageProvider> logger)
{
_config = config;
_fileSystem = fileSystem;
+ _logger = logger;
}
+ /// Make sure this is last so that all other locations are scanned first
+ /// <inheritdoc />
+ public int Order => 1000;
+
+ /// <inheritdoc />
public string Name => "Internal Images";
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
if (item is Photo)
@@ -46,20 +68,25 @@ namespace MediaBrowser.LocalMetadata.Images
return true;
}
- // Make sure this is last so that all other locations are scanned first
- public int Order => 1000;
- public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
+ /// <inheritdoc />
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
{
var path = item.GetInternalMetadataPath();
+ if (!Directory.Exists(path))
+ {
+ return Enumerable.Empty<LocalImageInfo>();
+ }
+
try
{
- return new LocalImageProvider(_fileSystem).GetImages(item, path, false, directoryService);
+ return new LocalImageProvider(_fileSystem).GetImages(item, path, directoryService);
}
- catch (IOException)
+ catch (IOException ex)
{
- return new List<LocalImageInfo>();
+ _logger.LogError(ex, "Error while getting images for {Library}", item.Name);
+ return Enumerable.Empty<LocalImageInfo>();
}
}
}
diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
index 1a7654bfd..988581df9 100644
--- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.IO;
using System.Linq;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
@@ -12,24 +13,74 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.LocalMetadata.Images
{
- public class LocalImageProvider : ILocalImageFileProvider, IHasOrder
+ /// <summary>
+ /// Local image provider.
+ /// </summary>
+ public class LocalImageProvider : ILocalImageProvider, IHasOrder
{
+ private static readonly string[] _commonImageFileNames =
+ {
+ "poster",
+ "folder",
+ "cover",
+ "default"
+ };
+
+ private static readonly string[] _musicImageFileNames =
+ {
+ "folder",
+ "poster",
+ "cover",
+ "default"
+ };
+
+ private static readonly string[] _personImageFileNames =
+ {
+ "folder",
+ "poster"
+ };
+
+ private static readonly string[] _seriesImageFileNames =
+ {
+ "poster",
+ "folder",
+ "cover",
+ "default",
+ "show"
+ };
+
+ private static readonly string[] _videoImageFileNames =
+ {
+ "poster",
+ "folder",
+ "cover",
+ "default",
+ "movie"
+ };
+
private readonly IFileSystem _fileSystem;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LocalImageProvider"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
public LocalImageProvider(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
+ /// <inheritdoc />
public string Name => "Local Images";
+ /// <inheritdoc />
public int Order => 0;
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
if (item.SupportsLocalMetadata)
{
- // Episode has it's own provider
+ // Episode has its own provider
if (item is Episode || item is Audio || item is Photo)
{
return false;
@@ -41,15 +92,10 @@ namespace MediaBrowser.LocalMetadata.Images
if (item.LocationType == LocationType.Virtual)
{
var season = item as Season;
-
- if (season != null)
+ var series = season?.Series;
+ if (series != null && series.IsFileProtocol)
{
- var series = season.Series;
-
- if (series != null && series.IsFileProtocol)
- {
- return true;
- }
+ return true;
}
}
@@ -60,11 +106,17 @@ namespace MediaBrowser.LocalMetadata.Images
{
if (!item.IsFileProtocol)
{
- return new List<FileSystemMetadata>();
+ return Enumerable.Empty<FileSystemMetadata>();
}
var path = item.ContainingFolderPath;
+ // Exit if the cache dir does not exist, alternative solution is to create it, but that's a lot of empty dirs...
+ if (!Directory.Exists(path))
+ {
+ return Enumerable.Empty<FileSystemMetadata>();
+ }
+
if (includeDirectories)
{
return directoryService.GetFileSystemEntries(path)
@@ -78,7 +130,8 @@ namespace MediaBrowser.LocalMetadata.Images
.OrderBy(i => Array.IndexOf(BaseItem.SupportedImageExtensions, i.Extension ?? string.Empty));
}
- public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
+ /// <inheritdoc />
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
{
var files = GetFiles(item, true, directoryService).ToList();
@@ -89,12 +142,26 @@ namespace MediaBrowser.LocalMetadata.Images
return list;
}
- public List<LocalImageInfo> GetImages(BaseItem item, string path, bool isPathInMediaFolder, IDirectoryService directoryService)
+ /// <summary>
+ /// Get images for item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="path">The images path.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ /// <returns>The local image info.</returns>
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, string path, IDirectoryService directoryService)
{
- return GetImages(item, new[] { path }, isPathInMediaFolder, directoryService);
+ return GetImages(item, new[] { path }, directoryService);
}
- public List<LocalImageInfo> GetImages(BaseItem item, IEnumerable<string> paths, bool arePathsInMediaFolders, IDirectoryService directoryService)
+ /// <summary>
+ /// Get images for item from multiple paths.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="paths">The image paths.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ /// <returns>The local image info.</returns>
+ public IEnumerable<LocalImageInfo> GetImages(BaseItem item, IEnumerable<string> paths, IDirectoryService directoryService)
{
IEnumerable<FileSystemMetadata> files = paths.SelectMany(i => _fileSystem.GetFiles(i, BaseItem.SupportedImageExtensions, true, false));
@@ -112,9 +179,7 @@ namespace MediaBrowser.LocalMetadata.Images
{
if (supportParentSeriesFiles)
{
- var season = item as Season;
-
- if (season != null)
+ if (item is Season season)
{
PopulateSeasonImagesFromSeriesFolder(season, images, directoryService);
}
@@ -189,7 +254,7 @@ namespace MediaBrowser.LocalMetadata.Images
if (!isEpisode && !isSong && !isPerson)
{
- PopulateBackdrops(item, images, files, imagePrefix, isInMixedFolder, directoryService);
+ PopulateBackdrops(item, images, files, imagePrefix, isInMixedFolder);
}
if (item is IHasScreenshots)
@@ -198,46 +263,6 @@ namespace MediaBrowser.LocalMetadata.Images
}
}
- private static readonly string[] CommonImageFileNames = new[]
- {
- "poster",
- "folder",
- "cover",
- "default"
- };
-
- private static readonly string[] MusicImageFileNames = new[]
- {
- "folder",
- "poster",
- "cover",
- "default"
- };
-
- private static readonly string[] PersonImageFileNames = new[]
- {
- "folder",
- "poster"
- };
-
- private static readonly string[] SeriesImageFileNames = new[]
- {
- "poster",
- "folder",
- "cover",
- "default",
- "show"
- };
-
- private static readonly string[] VideoImageFileNames = new[]
- {
- "poster",
- "folder",
- "cover",
- "default",
- "movie"
- };
-
private void PopulatePrimaryImages(BaseItem item, List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder)
{
string[] imageFileNames;
@@ -245,24 +270,24 @@ namespace MediaBrowser.LocalMetadata.Images
if (item is MusicAlbum || item is MusicArtist || item is PhotoAlbum)
{
// these prefer folder
- imageFileNames = MusicImageFileNames;
+ imageFileNames = _musicImageFileNames;
}
else if (item is Person)
{
// these prefer folder
- imageFileNames = PersonImageFileNames;
+ imageFileNames = _personImageFileNames;
}
else if (item is Series)
{
- imageFileNames = SeriesImageFileNames;
+ imageFileNames = _seriesImageFileNames;
}
- else if (item is Video && !(item is Episode))
+ else if (item is Video && item is not Episode)
{
- imageFileNames = VideoImageFileNames;
+ imageFileNames = _videoImageFileNames;
}
else
{
- imageFileNames = CommonImageFileNames;
+ imageFileNames = _commonImageFileNames;
}
var fileNameWithoutExtension = item.FileNameWithoutExtension;
@@ -294,7 +319,7 @@ namespace MediaBrowser.LocalMetadata.Images
}
}
- private void PopulateBackdrops(BaseItem item, List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder, IDirectoryService directoryService)
+ private void PopulateBackdrops(BaseItem item, List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder)
{
if (!string.IsNullOrEmpty(item.Path))
{
@@ -321,13 +346,13 @@ namespace MediaBrowser.LocalMetadata.Images
if (extraFanartFolder != null)
{
- PopulateBackdropsFromExtraFanart(extraFanartFolder.FullName, images, directoryService);
+ PopulateBackdropsFromExtraFanart(extraFanartFolder.FullName, images);
}
PopulateBackdrops(images, files, imagePrefix, "backdrop", "backdrop", isInMixedFolder, ImageType.Backdrop);
}
- private void PopulateBackdropsFromExtraFanart(string path, List<LocalImageInfo> images, IDirectoryService directoryService)
+ private void PopulateBackdropsFromExtraFanart(string path, List<LocalImageInfo> images)
{
var imageFiles = _fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, false);
@@ -388,8 +413,6 @@ namespace MediaBrowser.LocalMetadata.Images
}
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
private void PopulateSeasonImagesFromSeriesFolder(Season season, List<LocalImageInfo> images, IDirectoryService directoryService)
{
var seasonNumber = season.IndexNumber;
@@ -403,13 +426,13 @@ namespace MediaBrowser.LocalMetadata.Images
var seriesFiles = GetFiles(series, false, directoryService).ToList();
// Try using the season name
- var prefix = season.Name.ToLowerInvariant().Replace(" ", string.Empty);
+ var prefix = season.Name.Replace(" ", string.Empty, StringComparison.Ordinal).ToLowerInvariant();
var filenamePrefixes = new List<string> { prefix };
var seasonMarker = seasonNumber.Value == 0
? "-specials"
- : seasonNumber.Value.ToString("00", _usCulture);
+ : seasonNumber.Value.ToString("00", CultureInfo.InvariantCulture);
// Get this one directly from the file system since we have to go up a level
if (!string.Equals(prefix, seasonMarker, StringComparison.OrdinalIgnoreCase))
@@ -441,7 +464,7 @@ namespace MediaBrowser.LocalMetadata.Images
return added;
}
- private bool AddImage(IEnumerable<FileSystemMetadata> files, List<LocalImageInfo> images, string name, ImageType type)
+ private bool AddImage(List<FileSystemMetadata> files, List<LocalImageInfo> images, string name, ImageType type)
{
var image = GetImage(files, name);
@@ -459,9 +482,20 @@ namespace MediaBrowser.LocalMetadata.Images
return false;
}
- private FileSystemMetadata GetImage(IEnumerable<FileSystemMetadata> files, string name)
+ private static FileSystemMetadata? GetImage(IReadOnlyList<FileSystemMetadata> files, string name)
{
- return files.FirstOrDefault(i => !i.IsDirectory && string.Equals(name, _fileSystem.GetFileNameWithoutExtension(i), StringComparison.OrdinalIgnoreCase) && i.Length > 0);
+ for (var i = 0; i < files.Count; i++)
+ {
+ var file = files[i];
+ if (!file.IsDirectory
+ && file.Length > 0
+ && Path.GetFileNameWithoutExtension(file.FullName.AsSpan()).Equals(name, StringComparison.OrdinalIgnoreCase))
+ {
+ return file;
+ }
+ }
+
+ return null;
}
}
}
diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
index 867b82ede..a3db717b9 100644
--- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
+++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
@@ -1,17 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
</ItemGroup>
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ </PropertyGroup>
+
<ItemGroup>
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
</Project>
diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
index 38458e34c..5a36c1663 100644
--- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
@@ -6,52 +6,51 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
+using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Parsers
{
/// <summary>
- /// Provides a base class for parsing metadata xml
+ /// Provides a base class for parsing metadata xml.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">Type of item xml parser.</typeparam>
public class BaseItemXmlParser<T>
where T : BaseItem
{
- /// <summary>
- /// The logger
- /// </summary>
- protected ILogger Logger { get; private set; }
- protected IProviderManager ProviderManager { get; private set; }
-
- private Dictionary<string, string> _validProviderIds;
-
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
- protected IFileSystem FileSystem { get; private set; }
+ private Dictionary<string, string>? _validProviderIds;
/// <summary>
/// Initializes a new instance of the <see cref="BaseItemXmlParser{T}" /> class.
/// </summary>
- /// <param name="logger">The logger.</param>
- public BaseItemXmlParser(ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, IFileSystem fileSystem)
+ /// <param name="logger">Instance of the <see cref="ILogger{BaseItemXmlParser}"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ public BaseItemXmlParser(ILogger<BaseItemXmlParser<T>> logger, IProviderManager providerManager)
{
Logger = logger;
ProviderManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
- FileSystem = fileSystem;
}
/// <summary>
- /// Fetches metadata for an item from one xml file
+ /// Gets the logger.
+ /// </summary>
+ protected ILogger<BaseItemXmlParser<T>> Logger { get; private set; }
+
+ /// <summary>
+ /// Gets the provider manager.
+ /// </summary>
+ protected IProviderManager ProviderManager { get; private set; }
+
+ /// <summary>
+ /// Fetches metadata for an item from one xml file.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="metadataFile">The metadata file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <exception cref="ArgumentNullException"></exception>
+ /// <exception cref="ArgumentNullException">Item is null.</exception>
public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
{
if (item == null)
@@ -64,11 +63,13 @@ namespace MediaBrowser.LocalMetadata.Parsers
throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile));
}
- var settings = XmlReaderSettingsFactory.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ var settings = new XmlReaderSettings
+ {
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
_validProviderIds = _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
@@ -83,10 +84,10 @@ namespace MediaBrowser.LocalMetadata.Parsers
}
}
- //Additional Mappings
+ // Additional Mappings
_validProviderIds.Add("IMDB", "Imdb");
- //Fetch(item, metadataFile, settings, Encoding.GetEncoding("ISO-8859-1"), cancellationToken);
+ // Fetch(item, metadataFile, settings, Encoding.GetEncoding("ISO-8859-1"), cancellationToken);
Fetch(item, metadataFile, settings, Encoding.UTF8, cancellationToken);
}
@@ -102,39 +103,30 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
item.ResetPeople();
- using (var fileStream = File.OpenRead(metadataFile))
- {
- using (var streamReader = new StreamReader(fileStream, encoding))
- {
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(streamReader, settings))
- {
- reader.MoveToContent();
- reader.Read();
+ using var fileStream = File.OpenRead(metadataFile);
+ using var streamReader = new StreamReader(fileStream, encoding);
+ using var reader = XmlReader.Create(streamReader, settings);
+ reader.MoveToContent();
+ reader.Read();
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- else
- {
- reader.Read();
- }
- }
- }
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ FetchDataFromXmlNode(reader, item);
+ }
+ else
+ {
+ reader.Read();
}
}
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
/// <summary>
- /// Fetches metadata from one Xml Element
+ /// Fetches metadata from one Xml Element.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="itemResult">The item result.</param>
@@ -146,607 +138,569 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
// DateCreated
case "Added":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var added))
{
- if (DateTime.TryParse(val, out var added))
- {
- item.DateCreated = added.ToUniversalTime();
- }
- else
- {
- Logger.LogWarning("Invalid Added value found: " + val);
- }
+ item.DateCreated = added;
+ }
+ else
+ {
+ Logger.LogWarning("Invalid Added value found: " + val);
}
- break;
}
+ break;
+ }
+
case "OriginalTitle":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrEmpty(val))
- {
- item.OriginalTitle = val;
- }
- break;
+ if (!string.IsNullOrEmpty(val))
+ {
+ item.OriginalTitle = val;
}
+ break;
+ }
+
case "LocalTitle":
item.Name = reader.ReadElementContentAsString();
break;
case "CriticRating":
- {
- var text = reader.ReadElementContentAsString();
+ {
+ var text = reader.ReadElementContentAsString();
- if (!string.IsNullOrEmpty(text))
+ if (!string.IsNullOrEmpty(text))
+ {
+ if (float.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
- if (float.TryParse(text, NumberStyles.Any, _usCulture, out var value))
- {
- item.CriticRating = value;
- }
+ item.CriticRating = value;
}
-
- break;
}
+ break;
+ }
+
case "SortTitle":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.ForcedSortName = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.ForcedSortName = val;
}
+ break;
+ }
+
case "Overview":
case "Description":
- {
- var val = reader.ReadElementContentAsString();
-
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.Overview = val;
- }
+ {
+ var val = reader.ReadElementContentAsString();
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.Overview = val;
}
+ break;
+ }
+
case "Language":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- item.PreferredMetadataLanguage = val;
+ item.PreferredMetadataLanguage = val;
- break;
- }
+ break;
+ }
case "CountryCode":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- item.PreferredMetadataCountryCode = val;
+ item.PreferredMetadataCountryCode = val;
- break;
- }
+ break;
+ }
case "PlaceOfBirth":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ if (item is Person person)
{
- var person = item as Person;
- if (person != null)
- {
- person.ProductionLocations = new string[] { val };
- }
+ person.ProductionLocations = new[] { val };
}
-
- break;
}
+ break;
+ }
+
case "LockedFields":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.LockedFields = val.Split('|').Select(i =>
{
- item.LockedFields = val.Split('|').Select(i =>
+ if (Enum.TryParse(i, true, out MetadataField field))
{
- if (Enum.TryParse(i, true, out MetadataFields field))
- {
- return (MetadataFields?)field;
- }
-
- return null;
-
- }).Where(i => i.HasValue).Select(i => i.Value).ToArray();
- }
+ return (MetadataField?)field;
+ }
- break;
+ return null;
+ }).Where(i => i.HasValue).Select(i => i!.Value).ToArray();
}
+ break;
+ }
+
case "TagLines":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
+ using (var subtree = reader.ReadSubtree())
{
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromTaglinesNode(subtree, item);
- }
+ FetchFromTaglinesNode(subtree, item);
}
- else
- {
- reader.Read();
- }
- break;
}
+ else
+ {
+ reader.Read();
+ }
+
+ break;
+ }
case "Countries":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromCountriesNode(subtree, item);
- }
- }
- else
+ using (var subtree = reader.ReadSubtree())
{
- reader.Read();
+ FetchFromCountriesNode(subtree);
}
- break;
+ }
+ else
+ {
+ reader.Read();
}
+ break;
+ }
+
case "ContentRating":
case "MPAARating":
- {
- var rating = reader.ReadElementContentAsString();
+ {
+ var rating = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rating))
- {
- item.OfficialRating = rating;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(rating))
+ {
+ item.OfficialRating = rating;
}
+ break;
+ }
+
case "CustomRating":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.CustomRating = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.CustomRating = val;
}
+ break;
+ }
+
case "RunningTime":
- {
- var text = reader.ReadElementContentAsString();
+ {
+ var text = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(text))
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ if (int.TryParse(text.AsSpan().LeftPart(' '), NumberStyles.Integer, CultureInfo.InvariantCulture, out var runtime))
{
- if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out var runtime))
- {
- item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
- }
+ item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
}
- break;
}
+ break;
+ }
+
case "AspectRatio":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- var hasAspectRatio = item as IHasAspectRatio;
- if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
- {
- hasAspectRatio.AspectRatio = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val) && item is IHasAspectRatio hasAspectRatio)
+ {
+ hasAspectRatio.AspectRatio = val;
}
+ break;
+ }
+
case "LockData":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
+ break;
+ }
+
case "Network":
+ {
+ foreach (var name in SplitNames(reader.ReadElementContentAsString()))
{
- foreach (var name in SplitNames(reader.ReadElementContentAsString()))
+ if (string.IsNullOrWhiteSpace(name))
{
- if (string.IsNullOrWhiteSpace(name))
- {
- continue;
- }
- item.AddStudio(name);
+ continue;
}
- break;
+
+ item.AddStudio(name);
}
+ break;
+ }
+
case "Director":
+ {
+ foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
{
- foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
+ if (string.IsNullOrWhiteSpace(p.Name))
{
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
+ continue;
}
- break;
+
+ itemResult.AddPerson(p);
}
+
+ break;
+ }
+
case "Writer":
+ {
+ foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
{
- foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
+ if (string.IsNullOrWhiteSpace(p.Name))
{
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
+ continue;
}
- break;
+
+ itemResult.AddPerson(p);
}
- case "Actors":
- {
+ break;
+ }
- var actors = reader.ReadInnerXml();
+ case "Actors":
+ {
+ var actors = reader.ReadInnerXml();
- if (actors.Contains("<"))
- {
- // This is one of the mis-named "Actors" full nodes created by MB2
- // Create a reader and pass it to the persons node processor
- FetchDataFromPersonsNode(XmlReader.Create(new StringReader("<Persons>" + actors + "</Persons>")), itemResult);
- }
- else
- {
- // Old-style piped string
- foreach (var p in SplitNames(actors).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Actor }))
- {
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
- }
- }
- break;
+ if (actors.Contains("<", StringComparison.Ordinal))
+ {
+ // This is one of the mis-named "Actors" full nodes created by MB2
+ // Create a reader and pass it to the persons node processor
+ using var xmlReader = XmlReader.Create(new StringReader($"<Persons>{actors}</Persons>"));
+ FetchDataFromPersonsNode(xmlReader, itemResult);
}
-
- case "GuestStars":
+ else
{
- foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.GuestStar }))
+ // Old-style piped string
+ foreach (var p in SplitNames(actors).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Actor }))
{
if (string.IsNullOrWhiteSpace(p.Name))
{
continue;
}
+
itemResult.AddPerson(p);
}
- break;
}
- case "Trailer":
- {
- var val = reader.ReadElementContentAsString();
+ break;
+ }
- if (!string.IsNullOrWhiteSpace(val))
+ case "GuestStars":
+ {
+ foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.GuestStar }))
+ {
+ if (string.IsNullOrWhiteSpace(p.Name))
{
- item.AddTrailerUrl(val);
+ continue;
}
- break;
+
+ itemResult.AddPerson(p);
}
- case "DisplayOrder":
+ break;
+ }
+
+ case "Trailer":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(val))
{
- var val = reader.ReadElementContentAsString();
+ item.AddTrailerUrl(val);
+ }
+
+ break;
+ }
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null)
+ case "DisplayOrder":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (item is IHasDisplayOrder hasDisplayOrder)
+ {
+ if (!string.IsNullOrWhiteSpace(val))
{
- if (!string.IsNullOrWhiteSpace(val))
- {
- hasDisplayOrder.DisplayOrder = val;
- }
+ hasDisplayOrder.DisplayOrder = val;
}
- break;
}
+ break;
+ }
+
case "Trailers":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchDataFromTrailersNode(subtree, item);
- }
- }
- else
- {
- reader.Read();
- }
- break;
+ using var subtree = reader.ReadSubtree();
+ FetchDataFromTrailersNode(subtree, item);
+ }
+ else
+ {
+ reader.Read();
}
+ break;
+ }
+
case "ProductionYear":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ if (int.TryParse(val, out var productionYear) && productionYear > 1850)
{
- if (int.TryParse(val, out var productionYear) && productionYear > 1850)
- {
- item.ProductionYear = productionYear;
- }
+ item.ProductionYear = productionYear;
}
-
- break;
}
+ break;
+ }
+
case "Rating":
case "IMDBrating":
- {
-
- var rating = reader.ReadElementContentAsString();
+ {
+ var rating = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rating))
+ if (!string.IsNullOrWhiteSpace(rating))
+ {
+ // All external meta is saving this as '.' for decimal I believe...but just to be sure
+ if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
{
- // All external meta is saving this as '.' for decimal I believe...but just to be sure
- if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
- {
- item.CommunityRating = val;
- }
+ item.CommunityRating = val;
}
- break;
}
+ break;
+ }
+
case "BirthDate":
case "PremiereDate":
case "FirstAired":
- {
- var firstAired = reader.ReadElementContentAsString();
+ {
+ var firstAired = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(firstAired))
+ if (!string.IsNullOrWhiteSpace(firstAired))
+ {
+ if (DateTime.TryParseExact(firstAired, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal, out var airDate) && airDate.Year > 1850)
{
- if (DateTime.TryParseExact(firstAired, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var airDate) && airDate.Year > 1850)
- {
- item.PremiereDate = airDate.ToUniversalTime();
- item.ProductionYear = airDate.Year;
- }
+ item.PremiereDate = airDate;
+ item.ProductionYear = airDate.Year;
}
-
- break;
}
+ break;
+ }
+
case "DeathDate":
case "EndDate":
- {
- var firstAired = reader.ReadElementContentAsString();
+ {
+ var firstAired = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(firstAired))
+ if (!string.IsNullOrWhiteSpace(firstAired))
+ {
+ if (DateTime.TryParseExact(firstAired, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal, out var airDate) && airDate.Year > 1850)
{
- if (DateTime.TryParseExact(firstAired, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var airDate) && airDate.Year > 1850)
- {
- item.EndDate = airDate.ToUniversalTime();
- }
+ item.EndDate = airDate;
}
-
- break;
}
+ break;
+ }
+
case "CollectionNumber":
var tmdbCollection = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(tmdbCollection))
{
- item.SetProviderId(MetadataProviders.TmdbCollection, tmdbCollection);
+ item.SetProviderId(MetadataProvider.TmdbCollection, tmdbCollection);
}
+
break;
case "Genres":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromGenresNode(subtree, item);
- }
- }
- else
- {
- reader.Read();
- }
- break;
+ using var subtree = reader.ReadSubtree();
+ FetchFromGenresNode(subtree, item);
}
+ else
+ {
+ reader.Read();
+ }
+
+ break;
+ }
case "Tags":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromTagsNode(subtree, item);
- }
- }
- else
- {
- reader.Read();
- }
- break;
+ using var subtree = reader.ReadSubtree();
+ FetchFromTagsNode(subtree, item);
+ }
+ else
+ {
+ reader.Read();
}
+ break;
+ }
+
case "Persons":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchDataFromPersonsNode(subtree, itemResult);
- }
- }
- else
- {
- reader.Read();
- }
- break;
+ using var subtree = reader.ReadSubtree();
+ FetchDataFromPersonsNode(subtree, itemResult);
+ }
+ else
+ {
+ reader.Read();
}
+ break;
+ }
+
case "Studios":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromStudiosNode(subtree, item);
- }
- }
- else
- {
- reader.Read();
- }
- break;
+ using var subtree = reader.ReadSubtree();
+ FetchFromStudiosNode(subtree, item);
+ }
+ else
+ {
+ reader.Read();
}
+ break;
+ }
+
case "Shares":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
+ using var subtree = reader.ReadSubtree();
+ if (item is IHasShares hasShares)
{
- using (var subtree = reader.ReadSubtree())
- {
- var hasShares = item as IHasShares;
- if (hasShares != null)
- {
- FetchFromSharesNode(subtree, hasShares);
- }
- }
+ FetchFromSharesNode(subtree, hasShares);
}
- else
- {
- reader.Read();
- }
- break;
}
-
- case "Format3D":
+ else
{
- var val = reader.ReadElementContentAsString();
+ reader.Read();
+ }
- var video = item as Video;
+ break;
+ }
- if (video != null)
- {
- if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.HalfSideBySide;
- }
- else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
- }
- else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.FullTopAndBottom;
- }
- else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.FullSideBySide;
- }
- else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.MVC;
- }
- }
- break;
- }
+ case "Format3D":
+ {
+ var val = reader.ReadElementContentAsString();
- default:
+ if (item is Video video)
{
- string readerName = reader.Name;
- if (_validProviderIds.TryGetValue(readerName, out string providerIdValue))
+ if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
{
- var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
- {
- item.SetProviderId(providerIdValue, id);
- }
+ video.Video3DFormat = Video3DFormat.HalfSideBySide;
}
- else
+ else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
{
- reader.Skip();
+ video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
+ }
+ else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
+ {
+ video.Video3DFormat = Video3DFormat.FullTopAndBottom;
+ }
+ else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
+ {
+ video.Video3DFormat = Video3DFormat.FullSideBySide;
+ }
+ else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
+ {
+ video.Video3DFormat = Video3DFormat.MVC;
}
-
- break;
-
}
- }
- }
- private void FetchFromSharesNode(XmlReader reader, IHasShares item)
- {
- var list = new List<Share>();
- reader.MoveToContent();
- reader.Read();
+ break;
+ }
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
+ default:
{
- switch (reader.Name)
+ string readerName = reader.Name;
+ if (_validProviderIds!.TryGetValue(readerName, out string? providerIdValue))
{
- case "Share":
- {
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
-
- using (var subReader = reader.ReadSubtree())
- {
- var child = GetShare(subReader);
-
- if (child != null)
- {
- list.Add(child);
- }
- }
-
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
+ var id = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(id))
+ {
+ item.SetProviderId(providerIdValue, id);
+ }
}
- }
- else
- {
- reader.Read();
+ else
+ {
+ reader.Skip();
+ }
+
+ break;
}
}
-
- item.Shares = list.ToArray();
}
- private Share GetShareFromNode(XmlReader reader)
+ private void FetchFromSharesNode(XmlReader reader, IHasShares item)
{
- var share = new Share();
+ var list = new List<Share>();
reader.MoveToContent();
reader.Read();
@@ -758,21 +712,32 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
switch (reader.Name)
{
- case "UserId":
+ case "Share":
+ {
+ if (reader.IsEmptyElement)
{
- share.UserId = reader.ReadElementContentAsString();
- break;
+ reader.Read();
+ continue;
}
- case "CanEdit":
+ using (var subReader = reader.ReadSubtree())
{
- share.CanEdit = string.Equals(reader.ReadElementContentAsString(), true.ToString(), StringComparison.OrdinalIgnoreCase);
- break;
+ var child = GetShare(subReader);
+
+ if (child != null)
+ {
+ list.Add(child);
+ }
}
+ break;
+ }
+
default:
+ {
reader.Skip();
break;
+ }
}
}
else
@@ -781,10 +746,10 @@ namespace MediaBrowser.LocalMetadata.Parsers
}
}
- return share;
+ item.Shares = list.ToArray();
}
- private void FetchFromCountriesNode(XmlReader reader, T item)
+ private void FetchFromCountriesNode(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
@@ -797,15 +762,16 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Country":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -836,15 +802,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Tagline":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.Tagline = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.Tagline = val;
}
+
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -875,16 +843,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Genre":
- {
- var genre = reader.ReadElementContentAsString();
+ {
+ var genre = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(genre))
- {
- item.AddGenre(genre);
- }
- break;
+ if (!string.IsNullOrWhiteSpace(genre))
+ {
+ item.AddGenre(genre);
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -912,16 +881,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Tag":
- {
- var tag = reader.ReadElementContentAsString();
+ {
+ var tag = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(tag))
- {
- tags.Add(tag);
- }
- break;
+ if (!string.IsNullOrWhiteSpace(tag))
+ {
+ tags.Add(tag);
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -955,26 +925,29 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
case "Person":
case "Actor":
+ {
+ if (reader.IsEmptyElement)
{
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- using (var subtree = reader.ReadSubtree())
+ reader.Read();
+ continue;
+ }
+
+ using (var subtree = reader.ReadSubtree())
+ {
+ foreach (var person in GetPersonsFromXmlNode(subtree))
{
- foreach (var person in GetPersonsFromXmlNode(subtree))
+ if (string.IsNullOrWhiteSpace(person.Name))
{
- if (string.IsNullOrWhiteSpace(person.Name))
- {
- continue;
- }
- item.AddPerson(person);
+ continue;
}
+
+ item.AddPerson(person);
}
- break;
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -1000,16 +973,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Trailer":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.AddTrailerUrl(val);
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ item.AddTrailerUrl(val);
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -1040,16 +1014,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Studio":
- {
- var studio = reader.ReadElementContentAsString();
+ {
+ var studio = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(studio))
- {
- item.AddStudio(studio);
- }
- break;
+ if (!string.IsNullOrWhiteSpace(studio))
+ {
+ item.AddStudio(studio);
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -1070,7 +1045,7 @@ namespace MediaBrowser.LocalMetadata.Parsers
private IEnumerable<PersonInfo> GetPersonsFromXmlNode(XmlReader reader)
{
var name = string.Empty;
- var type = PersonType.Actor; // If type is not specified assume actor
+ var type = PersonType.Actor; // If type is not specified assume actor
var role = string.Empty;
int? sortOrder = null;
@@ -1085,44 +1060,48 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Name":
- name = reader.ReadElementContentAsString() ?? string.Empty;
+ name = reader.ReadElementContentAsString();
break;
case "Type":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- type = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ type = val;
}
+ break;
+ }
+
case "Role":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- role = val;
- }
- break;
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ role = val;
}
+
+ break;
+ }
+
case "SortOrder":
- {
- var val = reader.ReadElementContentAsString();
+ {
+ var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intVal))
{
- if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var intVal))
- {
- sortOrder = intVal;
- }
+ sortOrder = intVal;
}
- break;
}
+ break;
+ }
+
default:
reader.Skip();
break;
@@ -1134,23 +1113,19 @@ namespace MediaBrowser.LocalMetadata.Parsers
}
}
- var personInfo = new PersonInfo
- {
- Name = name.Trim(),
- Role = role,
- Type = type,
- SortOrder = sortOrder
- };
+ var personInfo = new PersonInfo { Name = name.Trim(), Role = role, Type = type, SortOrder = sortOrder };
return new[] { personInfo };
}
- protected LinkedChild GetLinkedChild(XmlReader reader)
+ /// <summary>
+ /// Get linked child.
+ /// </summary>
+ /// <param name="reader">The xml reader.</param>
+ /// <returns>The linked child.</returns>
+ protected LinkedChild? GetLinkedChild(XmlReader reader)
{
- var linkedItem = new LinkedChild
- {
- Type = LinkedChildType.Manual
- };
+ var linkedItem = new LinkedChild { Type = LinkedChildType.Manual };
reader.MoveToContent();
reader.Read();
@@ -1163,15 +1138,16 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "Path":
- {
- linkedItem.Path = reader.ReadElementContentAsString();
- break;
- }
+ {
+ linkedItem.Path = reader.ReadElementContentAsString();
+ break;
+ }
+
case "ItemId":
- {
- linkedItem.LibraryItemId = reader.ReadElementContentAsString();
- break;
- }
+ {
+ linkedItem.LibraryItemId = reader.ReadElementContentAsString();
+ break;
+ }
default:
reader.Skip();
@@ -1193,7 +1169,12 @@ namespace MediaBrowser.LocalMetadata.Parsers
return null;
}
- protected Share GetShare(XmlReader reader)
+ /// <summary>
+ /// Get share.
+ /// </summary>
+ /// <param name="reader">The xml reader.</param>
+ /// <returns>The share.</returns>
+ protected Share? GetShare(XmlReader reader)
{
var item = new Share();
@@ -1208,21 +1189,22 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "UserId":
- {
- item.UserId = reader.ReadElementContentAsString();
- break;
- }
+ {
+ item.UserId = reader.ReadElementContentAsString();
+ break;
+ }
case "CanEdit":
- {
- item.CanEdit = string.Equals(reader.ReadElementContentAsString(), "true", StringComparison.OrdinalIgnoreCase);
- break;
- }
+ {
+ item.CanEdit = string.Equals(reader.ReadElementContentAsString(), "true", StringComparison.OrdinalIgnoreCase);
+ break;
+ }
+
default:
- {
- reader.Skip();
- break;
- }
+ {
+ reader.Skip();
+ break;
+ }
}
}
else
@@ -1240,19 +1222,17 @@ namespace MediaBrowser.LocalMetadata.Parsers
return null;
}
-
/// <summary>
- /// Used to split names of comma or pipe delimeted genres and people
+ /// Used to split names of comma or pipe delimited genres and people.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>IEnumerable{System.String}.</returns>
private IEnumerable<string> SplitNames(string value)
{
- value = value ?? string.Empty;
-
// Only split by comma if there is no pipe in the string
// We have to be careful to not split names like Matthew, Jr.
- var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
+ var separator = !value.Contains('|', StringComparison.Ordinal)
+ && !value.Contains(';', StringComparison.Ordinal) ? new[] { ',' } : new[] { '|', ';' };
value = value.Trim().Trim(separator);
@@ -1260,7 +1240,7 @@ namespace MediaBrowser.LocalMetadata.Parsers
}
/// <summary>
- /// Provides an additional overload for string.split
+ /// Provides an additional overload for string.split.
/// </summary>
/// <param name="val">The val.</param>
/// <param name="separators">The separators.</param>
@@ -1270,6 +1250,5 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
return val.Split(separators, options);
}
-
}
}
diff --git a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
index e595e9d06..7df800971 100644
--- a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
@@ -3,15 +3,27 @@ using System.Xml;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Parsers
{
+ /// <summary>
+ /// The box set xml parser.
+ /// </summary>
public class BoxSetXmlParser : BaseItemXmlParser<BoxSet>
{
- protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<BoxSet> item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BoxSetXmlParser"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{BoxSetXmlParset}"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ public BoxSetXmlParser(ILogger<BoxSetXmlParser> logger, IProviderManager providerManager)
+ : base(logger, providerManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<BoxSet> itemResult)
{
switch (reader.Name)
{
@@ -21,17 +33,18 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
using (var subReader = reader.ReadSubtree())
{
- FetchFromCollectionItemsNode(subReader, item);
+ FetchFromCollectionItemsNode(subReader, itemResult);
}
}
else
{
reader.Read();
}
+
break;
default:
- base.FetchDataFromXmlNode(reader, item);
+ base.FetchDataFromXmlNode(reader, itemResult);
break;
}
}
@@ -51,31 +64,32 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "CollectionItem":
+ {
+ if (!reader.IsEmptyElement)
{
- if (!reader.IsEmptyElement)
+ using (var subReader = reader.ReadSubtree())
{
- using (var subReader = reader.ReadSubtree())
- {
- var child = GetLinkedChild(subReader);
+ var child = GetLinkedChild(subReader);
- if (child != null)
- {
- list.Add(child);
- }
+ if (child != null)
+ {
+ list.Add(child);
}
}
- else
- {
- reader.Read();
- }
-
- break;
}
- default:
+ else
{
- reader.Skip();
- break;
+ reader.Read();
}
+
+ break;
+ }
+
+ default:
+ {
+ reader.Skip();
+ break;
+ }
}
}
else
@@ -86,9 +100,5 @@ namespace MediaBrowser.LocalMetadata.Parsers
item.Item.LinkedChildren = list.ToArray();
}
-
- public BoxSetXmlParser(ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, IFileSystem fileSystem) : base(logger, providerManager, xmlReaderSettingsFactory, fileSystem)
- {
- }
}
}
diff --git a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
index ff69cb023..b84307cb2 100644
--- a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
@@ -3,26 +3,38 @@ using System.Xml;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Parsers
{
+ /// <summary>
+ /// Playlist xml parser.
+ /// </summary>
public class PlaylistXmlParser : BaseItemXmlParser<Playlist>
{
- protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Playlist> result)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaylistXmlParser"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{PlaylistXmlParser}"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ public PlaylistXmlParser(ILogger<PlaylistXmlParser> logger, IProviderManager providerManager)
+ : base(logger, providerManager)
{
- var item = result.Item;
+ }
+
+ /// <inheritdoc />
+ protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Playlist> itemResult)
+ {
+ var item = itemResult.Item;
switch (reader.Name)
{
case "PlaylistMediaType":
- {
- item.PlaylistMediaType = reader.ReadElementContentAsString();
+ {
+ item.PlaylistMediaType = reader.ReadElementContentAsString();
- break;
- }
+ break;
+ }
case "PlaylistItems":
@@ -37,10 +49,11 @@ namespace MediaBrowser.LocalMetadata.Parsers
{
reader.Read();
}
+
break;
default:
- base.FetchDataFromXmlNode(reader, result);
+ base.FetchDataFromXmlNode(reader, itemResult);
break;
}
}
@@ -60,30 +73,31 @@ namespace MediaBrowser.LocalMetadata.Parsers
switch (reader.Name)
{
case "PlaylistItem":
+ {
+ if (reader.IsEmptyElement)
{
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
+ reader.Read();
+ continue;
+ }
- using (var subReader = reader.ReadSubtree())
- {
- var child = GetLinkedChild(subReader);
+ using (var subReader = reader.ReadSubtree())
+ {
+ var child = GetLinkedChild(subReader);
- if (child != null)
- {
- list.Add(child);
- }
+ if (child != null)
+ {
+ list.Add(child);
}
-
- break;
}
+
+ break;
+ }
+
default:
- {
- reader.Skip();
- break;
- }
+ {
+ reader.Skip();
+ break;
+ }
}
}
else
@@ -94,9 +108,5 @@ namespace MediaBrowser.LocalMetadata.Parsers
item.LinkedChildren = list.ToArray();
}
-
- public PlaylistXmlParser(ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, IFileSystem fileSystem) : base(logger, providerManager, xmlReaderSettingsFactory, fileSystem)
- {
- }
}
}
diff --git a/MediaBrowser.LocalMetadata/Properties/AssemblyInfo.cs b/MediaBrowser.LocalMetadata/Properties/AssemblyInfo.cs
index 3eac83708..580cef9da 100644
--- a/MediaBrowser.LocalMetadata/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.LocalMetadata/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
index 539f818c6..ea123bbf2 100644
--- a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
@@ -4,7 +4,6 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Providers
@@ -14,24 +13,30 @@ namespace MediaBrowser.LocalMetadata.Providers
/// </summary>
public class BoxSetXmlProvider : BaseXmlProvider<BoxSet>
{
- private readonly ILogger _logger;
+ private readonly ILogger<BoxSetXmlParser> _logger;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
- public BoxSetXmlProvider(IFileSystem fileSystem, ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BoxSetXmlProvider"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{BoxSetXmlParser}"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ public BoxSetXmlProvider(IFileSystem fileSystem, ILogger<BoxSetXmlParser> logger, IProviderManager providerManager)
: base(fileSystem)
{
_logger = logger;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<BoxSet> result, string path, CancellationToken cancellationToken)
{
- new BoxSetXmlParser(_logger, _providerManager, XmlReaderSettingsFactory, FileSystem).Fetch(result, path, cancellationToken);
+ new BoxSetXmlParser(_logger, _providerManager).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
{
return directoryService.GetFile(Path.Combine(info.Path, "collection.xml"));
}
diff --git a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
index 442a18cb9..899035652 100644
--- a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
@@ -4,33 +4,44 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
using MediaBrowser.LocalMetadata.Savers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Providers
{
+ /// <summary>
+ /// Playlist xml provider.
+ /// </summary>
public class PlaylistXmlProvider : BaseXmlProvider<Playlist>
{
- private readonly ILogger _logger;
+ private readonly ILogger<PlaylistXmlParser> _logger;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
- public PlaylistXmlProvider(IFileSystem fileSystem, ILogger logger, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaylistXmlProvider"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{PlaylistXmlParser}"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ public PlaylistXmlProvider(
+ IFileSystem fileSystem,
+ ILogger<PlaylistXmlParser> logger,
+ IProviderManager providerManager)
: base(fileSystem)
{
_logger = logger;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<Playlist> result, string path, CancellationToken cancellationToken)
{
- new PlaylistXmlParser(_logger, _providerManager, XmlReaderSettingsFactory, FileSystem).Fetch(result, path, cancellationToken);
+ new PlaylistXmlParser(_logger, _providerManager).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
{
- return directoryService.GetFile(PlaylistXmlSaver.GetSavePath(info.Path, FileSystem));
+ return directoryService.GetFile(PlaylistXmlSaver.GetSavePath(info.Path));
}
}
}
diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
index 438b84252..5e7af23fc 100644
--- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
@@ -14,38 +13,57 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Savers
{
+ /// <inheritdoc />
public abstract class BaseXmlSaver : IMetadataFileSaver
{
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
+ /// <summary>
+ /// Gets the date added format.
+ /// </summary>
+ public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
- public BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BaseXmlSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{BaseXmlSaver}"/> interface.</param>
+ protected BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger<BaseXmlSaver> logger)
{
FileSystem = fileSystem;
ConfigurationManager = configurationManager;
LibraryManager = libraryManager;
- UserManager = userManager;
- UserDataManager = userDataManager;
Logger = logger;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
}
+ /// <summary>
+ /// Gets the file system.
+ /// </summary>
protected IFileSystem FileSystem { get; private set; }
+
+ /// <summary>
+ /// Gets the configuration manager.
+ /// </summary>
protected IServerConfigurationManager ConfigurationManager { get; private set; }
+
+ /// <summary>
+ /// Gets the library manager.
+ /// </summary>
protected ILibraryManager LibraryManager { get; private set; }
- protected IUserManager UserManager { get; private set; }
- protected IUserDataManager UserDataManager { get; private set; }
- protected ILogger Logger { get; private set; }
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
- protected ItemUpdateType MinimumUpdateType => ItemUpdateType.MetadataDownload;
+ /// <summary>
+ /// Gets the logger.
+ /// </summary>
+ protected ILogger<BaseXmlSaver> Logger { get; private set; }
+ /// <inheritdoc />
public string Name => XmlProviderUtils.Name;
+ /// <inheritdoc />
public string GetSavePath(BaseItem item)
{
return GetLocalSavePath(item);
@@ -76,29 +94,38 @@ namespace MediaBrowser.LocalMetadata.Savers
/// <returns><c>true</c> if [is enabled for] [the specified item]; otherwise, <c>false</c>.</returns>
public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType);
+ /// <inheritdoc />
public void Save(BaseItem item, CancellationToken cancellationToken)
{
var path = GetSavePath(item);
- using (var memoryStream = new MemoryStream())
- {
- Save(item, memoryStream, path);
+ using var memoryStream = new MemoryStream();
+ Save(item, memoryStream);
- memoryStream.Position = 0;
+ memoryStream.Position = 0;
- cancellationToken.ThrowIfCancellationRequested();
+ cancellationToken.ThrowIfCancellationRequested();
- SaveToFile(memoryStream, path);
- }
+ SaveToFile(memoryStream, path);
}
private void SaveToFile(Stream stream, string path)
{
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
+ Directory.CreateDirectory(directory);
+
// On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false);
- using (var filestream = FileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ var fileStreamOptions = new FileStreamOptions()
+ {
+ Mode = FileMode.Create,
+ Access = FileAccess.Write,
+ Share = FileShare.None,
+ PreallocationSize = stream.Length
+ };
+
+ using (var filestream = new FileStream(path, fileStreamOptions))
{
stream.CopyTo(filestream);
}
@@ -121,7 +148,7 @@ namespace MediaBrowser.LocalMetadata.Savers
}
}
- private void Save(BaseItem item, Stream stream, string xmlPath)
+ private void Save(BaseItem item, Stream stream)
{
var settings = new XmlWriterSettings
{
@@ -142,7 +169,7 @@ namespace MediaBrowser.LocalMetadata.Savers
if (baseItem != null)
{
- AddCommonNodes(baseItem, writer, LibraryManager, UserManager, UserDataManager, FileSystem, ConfigurationManager);
+ AddCommonNodes(baseItem, writer, LibraryManager);
}
WriteCustomElements(item, writer);
@@ -153,35 +180,38 @@ namespace MediaBrowser.LocalMetadata.Savers
}
}
+ /// <summary>
+ /// Write custom elements.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="writer">The xml writer.</param>
protected abstract void WriteCustomElements(BaseItem item, XmlWriter writer);
- public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
-
/// <summary>
/// Adds the common nodes.
/// </summary>
- /// <returns>Task.</returns>
- public static void AddCommonNodes(BaseItem item, XmlWriter writer, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepo, IFileSystem fileSystem, IServerConfigurationManager config)
+ /// <param name="item">The item.</param>
+ /// <param name="writer">The xml writer.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ public static void AddCommonNodes(BaseItem item, XmlWriter writer, ILibraryManager libraryManager)
{
- var writtenProviderIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
-
if (!string.IsNullOrEmpty(item.OfficialRating))
{
writer.WriteElementString("ContentRating", item.OfficialRating);
}
- writer.WriteElementString("Added", item.DateCreated.ToLocalTime().ToString("G"));
+ writer.WriteElementString("Added", item.DateCreated.ToLocalTime().ToString("G", CultureInfo.InvariantCulture));
writer.WriteElementString("LockData", item.IsLocked.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (item.LockedFields.Length > 0)
{
- writer.WriteElementString("LockedFields", string.Join("|", item.LockedFields));
+ writer.WriteElementString("LockedFields", string.Join('|', item.LockedFields));
}
if (item.CriticRating.HasValue)
{
- writer.WriteElementString("CriticRating", item.CriticRating.Value.ToString(UsCulture));
+ writer.WriteElementString("CriticRating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(item.Overview))
@@ -193,12 +223,13 @@ namespace MediaBrowser.LocalMetadata.Savers
{
writer.WriteElementString("OriginalTitle", item.OriginalTitle);
}
+
if (!string.IsNullOrEmpty(item.CustomRating))
{
writer.WriteElementString("CustomRating", item.CustomRating);
}
- if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
+ if (!string.IsNullOrEmpty(item.Name) && item is not Episode)
{
writer.WriteElementString("LocalTitle", item.Name);
}
@@ -213,11 +244,11 @@ namespace MediaBrowser.LocalMetadata.Savers
{
if (item is Person)
{
- writer.WriteElementString("BirthDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
+ writer.WriteElementString("BirthDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
- else if (!(item is Episode))
+ else if (item is not Episode)
{
- writer.WriteElementString("PremiereDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
+ writer.WriteElementString("PremiereDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
}
@@ -225,15 +256,15 @@ namespace MediaBrowser.LocalMetadata.Savers
{
if (item is Person)
{
- writer.WriteElementString("DeathDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
+ writer.WriteElementString("DeathDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
- else if (!(item is Episode))
+ else if (item is not Episode)
{
- writer.WriteElementString("EndDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
+ writer.WriteElementString("EndDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
}
- if (item.RemoteTrailers.Length > 0)
+ if (item.RemoteTrailers.Count > 0)
{
writer.WriteStartElement("Trailers");
@@ -257,24 +288,22 @@ namespace MediaBrowser.LocalMetadata.Savers
writer.WriteEndElement();
}
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
+ if (item is IHasDisplayOrder hasDisplayOrder && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
{
writer.WriteElementString("DisplayOrder", hasDisplayOrder.DisplayOrder);
}
if (item.CommunityRating.HasValue)
{
- writer.WriteElementString("Rating", item.CommunityRating.Value.ToString(UsCulture));
+ writer.WriteElementString("Rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
}
- if (item.ProductionYear.HasValue && !(item is Person))
+ if (item.ProductionYear.HasValue && item is not Person)
{
- writer.WriteElementString("ProductionYear", item.ProductionYear.Value.ToString(UsCulture));
+ writer.WriteElementString("ProductionYear", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
}
- var hasAspectRatio = item as IHasAspectRatio;
- if (hasAspectRatio != null)
+ if (item is IHasAspectRatio hasAspectRatio)
{
if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
{
@@ -286,6 +315,7 @@ namespace MediaBrowser.LocalMetadata.Savers
{
writer.WriteElementString("Language", item.PreferredMetadataLanguage);
}
+
if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
{
writer.WriteElementString("CountryCode", item.PreferredMetadataCountryCode);
@@ -298,7 +328,7 @@ namespace MediaBrowser.LocalMetadata.Savers
{
var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
- writer.WriteElementString("RunningTime", Math.Floor(timespan.TotalMinutes).ToString(UsCulture));
+ writer.WriteElementString("RunningTime", Math.Floor(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture));
}
if (item.ProviderIds != null)
@@ -371,7 +401,7 @@ namespace MediaBrowser.LocalMetadata.Savers
if (person.SortOrder.HasValue)
{
- writer.WriteElementString("SortOrder", person.SortOrder.Value.ToString(UsCulture));
+ writer.WriteElementString("SortOrder", person.SortOrder.Value.ToString(CultureInfo.InvariantCulture));
}
writer.WriteEndElement();
@@ -380,20 +410,17 @@ namespace MediaBrowser.LocalMetadata.Savers
writer.WriteEndElement();
}
- var boxset = item as BoxSet;
- if (boxset != null)
+ if (item is BoxSet boxset)
{
AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem");
}
- var playlist = item as Playlist;
- if (playlist != null && !Playlist.IsPlaylistFile(playlist.Path))
+ if (item is Playlist playlist && !Playlist.IsPlaylistFile(playlist.Path))
{
AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem");
}
- var hasShares = item as IHasShares;
- if (hasShares != null)
+ if (item is IHasShares hasShares)
{
AddShares(hasShares, writer);
}
@@ -401,6 +428,11 @@ namespace MediaBrowser.LocalMetadata.Savers
AddMediaInfo(item, writer);
}
+ /// <summary>
+ /// Add shares.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="writer">The xml writer.</param>
public static void AddShares(IHasShares item, XmlWriter writer)
{
writer.WriteStartElement("Shares");
@@ -423,13 +455,13 @@ namespace MediaBrowser.LocalMetadata.Savers
/// <summary>
/// Appends the media info.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <param name="item">The item.</param>
+ /// <param name="writer">The xml writer.</param>
+ /// <typeparam name="T">Type of item.</typeparam>
public static void AddMediaInfo<T>(T item, XmlWriter writer)
where T : BaseItem
{
- var video = item as Video;
-
- if (video != null)
+ if (item is Video video)
{
if (video.Video3DFormat.HasValue)
{
@@ -455,6 +487,13 @@ namespace MediaBrowser.LocalMetadata.Savers
}
}
+ /// <summary>
+ /// ADd linked children.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="writer">The xml writer.</param>
+ /// <param name="pluralNodeName">The plural node name.</param>
+ /// <param name="singularNodeName">The singular node name.</param>
public static void AddLinkedChildren(Folder item, XmlWriter writer, string pluralNodeName, string singularNodeName)
{
var items = item.LinkedChildren
@@ -489,10 +528,5 @@ namespace MediaBrowser.LocalMetadata.Savers
writer.WriteEndElement();
}
-
- private bool IsPersonType(PersonInfo person, string type)
- {
- return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
- }
}
}
diff --git a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
index b4d5440a5..8a5da95bf 100644
--- a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
@@ -5,13 +5,28 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Savers
{
+ /// <summary>
+ /// Box set xml saver.
+ /// </summary>
public class BoxSetXmlSaver : BaseXmlSaver
{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BoxSetXmlSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{BoxSetXmlSaver}"/> interface.</param>
+ public BoxSetXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger<BoxSetXmlSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, logger)
+ {
+ }
+
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
{
if (!item.SupportsLocalMetadata)
@@ -22,17 +37,15 @@ namespace MediaBrowser.LocalMetadata.Savers
return item is BoxSet && updateType >= ItemUpdateType.MetadataDownload;
}
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
}
+ /// <inheritdoc />
protected override string GetLocalSavePath(BaseItem item)
{
return Path.Combine(item.Path, "collection.xml");
}
-
- public BoxSetXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
- }
}
}
diff --git a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
index 09bb6d8f7..76252bc09 100644
--- a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
@@ -5,13 +5,33 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Savers
{
+ /// <summary>
+ /// Playlist xml saver.
+ /// </summary>
public class PlaylistXmlSaver : BaseXmlSaver
{
+ /// <summary>
+ /// The default file name to use when creating a new playlist.
+ /// </summary>
+ public const string DefaultPlaylistFilename = "playlist.xml";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaylistXmlSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger{PlaylistXmlSaver}"/> interface.</param>
+ public PlaylistXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger<PlaylistXmlSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, logger)
+ {
+ }
+
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
{
if (!item.SupportsLocalMetadata)
@@ -22,6 +42,7 @@ namespace MediaBrowser.LocalMetadata.Savers
return item is Playlist && updateType >= ItemUpdateType.MetadataImport;
}
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var game = (Playlist)item;
@@ -32,12 +53,18 @@ namespace MediaBrowser.LocalMetadata.Savers
}
}
+ /// <inheritdoc />
protected override string GetLocalSavePath(BaseItem item)
{
- return GetSavePath(item.Path, FileSystem);
+ return GetSavePath(item.Path);
}
- public static string GetSavePath(string itemPath, IFileSystem fileSystem)
+ /// <summary>
+ /// Get the save path.
+ /// </summary>
+ /// <param name="itemPath">The item path.</param>
+ /// <returns>The save path.</returns>
+ public static string GetSavePath(string itemPath)
{
var path = itemPath;
@@ -46,11 +73,7 @@ namespace MediaBrowser.LocalMetadata.Savers
return Path.ChangeExtension(itemPath, ".xml");
}
- return Path.Combine(path, "playlist.xml");
- }
-
- public PlaylistXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ return Path.Combine(path, DefaultPlaylistFilename);
}
}
}
diff --git a/MediaBrowser.LocalMetadata/XmlProviderUtils.cs b/MediaBrowser.LocalMetadata/XmlProviderUtils.cs
new file mode 100644
index 000000000..e247b8bb8
--- /dev/null
+++ b/MediaBrowser.LocalMetadata/XmlProviderUtils.cs
@@ -0,0 +1,13 @@
+namespace MediaBrowser.LocalMetadata
+{
+ /// <summary>
+ /// The xml provider utils.
+ /// </summary>
+ public static class XmlProviderUtils
+ {
+ /// <summary>
+ /// Gets the name.
+ /// </summary>
+ public static string Name => "Emby Xml";
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
new file mode 100644
index 000000000..a524aeaa9
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
@@ -0,0 +1,280 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.MediaEncoding.Attachments
+{
+ public 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 ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
+ new ConcurrentDictionary<string, SemaphoreSlim>();
+
+ private bool _disposed = false;
+
+ public AttachmentExtractor(
+ ILogger<AttachmentExtractor> logger,
+ IApplicationPaths appPaths,
+ IFileSystem fileSystem,
+ IMediaEncoder mediaEncoder,
+ IMediaSourceManager mediaSourceManager)
+ {
+ _logger = logger;
+ _appPaths = appPaths;
+ _fileSystem = fileSystem;
+ _mediaEncoder = mediaEncoder;
+ _mediaSourceManager = mediaSourceManager;
+ }
+
+ /// <inheritdoc />
+ public async Task<(MediaAttachment attachment, Stream stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ if (string.IsNullOrWhiteSpace(mediaSourceId))
+ {
+ throw new ArgumentNullException(nameof(mediaSourceId));
+ }
+
+ var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
+ var mediaSource = mediaSources
+ .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
+ if (mediaSource == null)
+ {
+ throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
+ }
+
+ var mediaAttachment = mediaSource.MediaAttachments
+ .FirstOrDefault(i => i.Index == attachmentStreamIndex);
+ if (mediaAttachment == null)
+ {
+ throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
+ }
+
+ var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
+ .ConfigureAwait(false);
+
+ return (mediaAttachment, attachmentStream);
+ }
+
+ 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)
+ {
+ var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
+ await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
+ .ConfigureAwait(false);
+
+ return outputPath;
+ }
+
+ private async Task ExtractAttachment(
+ string inputFile,
+ MediaSourceInfo mediaSource,
+ int attachmentStreamIndex,
+ string outputPath,
+ CancellationToken cancellationToken)
+ {
+ var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
+
+ await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ if (!File.Exists(outputPath))
+ {
+ await ExtractAttachmentInternal(
+ _mediaEncoder.GetInputArgument(inputFile, mediaSource),
+ attachmentStreamIndex,
+ outputPath,
+ cancellationToken).ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ semaphore.Release();
+ }
+ }
+
+ private async Task ExtractAttachmentInternal(
+ string inputPath,
+ int attachmentStreamIndex,
+ string outputPath,
+ CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrEmpty(inputPath))
+ {
+ throw new ArgumentNullException(nameof(inputPath));
+ }
+
+ if (string.IsNullOrEmpty(outputPath))
+ {
+ throw new ArgumentNullException(nameof(outputPath));
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+
+ var processArgs = string.Format(
+ CultureInfo.InvariantCulture,
+ "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
+ inputPath,
+ attachmentStreamIndex,
+ outputPath);
+
+ int exitCode;
+
+ using (var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ 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();
+
+ var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
+
+ if (!ranToCompletion)
+ {
+ try
+ {
+ _logger.LogWarning("Killing ffmpeg attachment extraction process");
+ process.Kill();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error killing attachment extraction process");
+ }
+ }
+
+ exitCode = ranToCompletion ? process.ExitCode : -1;
+ }
+
+ var failed = false;
+
+ if (exitCode != 0)
+ {
+ failed = true;
+
+ _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
+ try
+ {
+ if (File.Exists(outputPath))
+ {
+ _fileSystem.DeleteFile(outputPath);
+ }
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
+ }
+ }
+ else if (!File.Exists(outputPath))
+ {
+ failed = true;
+ }
+
+ if (failed)
+ {
+ var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}";
+
+ _logger.LogError(msg);
+
+ throw new InvalidOperationException(msg);
+ }
+ else
+ {
+ _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", 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.Substring(0, 1);
+ return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
+ {
+ }
+
+ _disposed = true;
+ }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs
new file mode 100644
index 000000000..409379c35
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs
@@ -0,0 +1,83 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Linq;
+using BDInfo.IO;
+using MediaBrowser.Model.IO;
+
+namespace MediaBrowser.MediaEncoding.BdInfo
+{
+ public class BdInfoDirectoryInfo : IDirectoryInfo
+ {
+ private readonly IFileSystem _fileSystem;
+
+ private readonly FileSystemMetadata _impl;
+
+ public BdInfoDirectoryInfo(IFileSystem fileSystem, string path)
+ {
+ _fileSystem = fileSystem;
+ _impl = _fileSystem.GetDirectoryInfo(path);
+ }
+
+ private BdInfoDirectoryInfo(IFileSystem fileSystem, FileSystemMetadata impl)
+ {
+ _fileSystem = fileSystem;
+ _impl = impl;
+ }
+
+ public string Name => _impl.Name;
+
+ public string FullName => _impl.FullName;
+
+ public IDirectoryInfo? Parent
+ {
+ get
+ {
+ var parentFolder = System.IO.Path.GetDirectoryName(_impl.FullName);
+ if (parentFolder != null)
+ {
+ return new BdInfoDirectoryInfo(_fileSystem, parentFolder);
+ }
+
+ return null;
+ }
+ }
+
+ public IDirectoryInfo[] GetDirectories()
+ {
+ return Array.ConvertAll(
+ _fileSystem.GetDirectories(_impl.FullName).ToArray(),
+ x => new BdInfoDirectoryInfo(_fileSystem, x));
+ }
+
+ public IFileInfo[] GetFiles()
+ {
+ return Array.ConvertAll(
+ _fileSystem.GetFiles(_impl.FullName).ToArray(),
+ x => new BdInfoFileInfo(x));
+ }
+
+ public IFileInfo[] GetFiles(string searchPattern)
+ {
+ return Array.ConvertAll(
+ _fileSystem.GetFiles(_impl.FullName, new[] { searchPattern }, false, false).ToArray(),
+ x => new BdInfoFileInfo(x));
+ }
+
+ public IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption)
+ {
+ return Array.ConvertAll(
+ _fileSystem.GetFiles(
+ _impl.FullName,
+ new[] { searchPattern },
+ false,
+ (searchOption & System.IO.SearchOption.AllDirectories) == System.IO.SearchOption.AllDirectories).ToArray(),
+ x => new BdInfoFileInfo(x));
+ }
+
+ public static IDirectoryInfo FromFileSystemPath(IFileSystem fs, string path)
+ {
+ return new BdInfoDirectoryInfo(fs, path);
+ }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs
index 3b6b91684..6ebaa4fff 100644
--- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs
+++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using BDInfo;
@@ -9,12 +9,16 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.BdInfo
{
/// <summary>
- /// Class BdInfoExaminer
+ /// Class BdInfoExaminer.
/// </summary>
public class BdInfoExaminer : IBlurayExaminer
{
private readonly IFileSystem _fileSystem;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BdInfoExaminer" /> class.
+ /// </summary>
+ /// <param name="fileSystem">The filesystem.</param>
public BdInfoExaminer(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
@@ -32,7 +36,7 @@ namespace MediaBrowser.MediaEncoding.BdInfo
throw new ArgumentNullException(nameof(path));
}
- var bdrom = new BDROM(path, _fileSystem);
+ var bdrom = new BDROM(BdInfoDirectoryInfo.FromFileSystemPath(_fileSystem, path));
bdrom.Scan();
@@ -41,7 +45,7 @@ namespace MediaBrowser.MediaEncoding.BdInfo
var outputStream = new BlurayDiscInfo
{
- MediaStreams = new MediaStream[] { }
+ MediaStreams = Array.Empty<MediaStream>()
};
if (playlist == null)
@@ -57,33 +61,25 @@ namespace MediaBrowser.MediaEncoding.BdInfo
foreach (var stream in playlist.SortedStreams)
{
- var videoStream = stream as TSVideoStream;
-
- if (videoStream != null)
+ if (stream is TSVideoStream videoStream)
{
AddVideoStream(mediaStreams, videoStream);
continue;
}
- var audioStream = stream as TSAudioStream;
-
- if (audioStream != null)
+ if (stream is TSAudioStream audioStream)
{
AddAudioStream(mediaStreams, audioStream);
continue;
}
- var textStream = stream as TSTextStream;
-
- if (textStream != null)
+ if (stream is TSTextStream textStream)
{
AddSubtitleStream(mediaStreams, textStream);
continue;
}
- var graphicsStream = stream as TSGraphicsStream;
-
- if (graphicsStream != null)
+ if (stream is TSGraphicsStream graphicsStream)
{
AddSubtitleStream(mediaStreams, graphicsStream);
}
diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs
new file mode 100644
index 000000000..d55688e3d
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs
@@ -0,0 +1,41 @@
+#pragma warning disable CS1591
+
+using System.IO;
+using MediaBrowser.Model.IO;
+
+namespace MediaBrowser.MediaEncoding.BdInfo
+{
+ public class BdInfoFileInfo : BDInfo.IO.IFileInfo
+ {
+ private FileSystemMetadata _impl;
+
+ public BdInfoFileInfo(FileSystemMetadata impl)
+ {
+ _impl = impl;
+ }
+
+ public string Name => _impl.Name;
+
+ public string FullName => _impl.FullName;
+
+ public string Extension => _impl.Extension;
+
+ public long Length => _impl.Length;
+
+ public bool IsDir => _impl.IsDirectory;
+
+ public Stream OpenRead()
+ {
+ return new FileStream(
+ FullName,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.Read);
+ }
+
+ public StreamReader OpenText()
+ {
+ return new StreamReader(OpenRead());
+ }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs
index bb806ee55..f81a337db 100644
--- a/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs
+++ b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs
@@ -1,56 +1,18 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
-using System.IO;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.IO;
namespace MediaBrowser.MediaEncoding.Configuration
{
public class EncodingConfigurationFactory : IConfigurationFactory
{
- private readonly IFileSystem _fileSystem;
-
- public EncodingConfigurationFactory(IFileSystem fileSystem)
- {
- _fileSystem = fileSystem;
- }
-
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new[]
{
- new EncodingConfigurationStore(_fileSystem)
+ new EncodingConfigurationStore()
};
}
}
-
- public class EncodingConfigurationStore : ConfigurationStore, IValidatingConfiguration
- {
- private readonly IFileSystem _fileSystem;
-
- public EncodingConfigurationStore(IFileSystem fileSystem)
- {
- ConfigurationType = typeof(EncodingOptions);
- Key = "encoding";
- _fileSystem = fileSystem;
- }
-
- public void Validate(object oldConfig, object newConfig)
- {
- var oldEncodingConfig = (EncodingOptions)oldConfig;
- var newEncodingConfig = (EncodingOptions)newConfig;
-
- var newPath = newEncodingConfig.TranscodingTempPath;
-
- if (!string.IsNullOrWhiteSpace(newPath)
- && !string.Equals(oldEncodingConfig.TranscodingTempPath ?? string.Empty, newPath))
- {
- // Validate
- if (!Directory.Exists(newPath))
- {
- throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
- }
- }
- }
- }
}
diff --git a/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationStore.cs b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationStore.cs
new file mode 100644
index 000000000..2f158157e
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationStore.cs
@@ -0,0 +1,38 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Globalization;
+using System.IO;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.MediaEncoding.Configuration
+{
+ public class EncodingConfigurationStore : ConfigurationStore, IValidatingConfiguration
+ {
+ public EncodingConfigurationStore()
+ {
+ ConfigurationType = typeof(EncodingOptions);
+ Key = "encoding";
+ }
+
+ public void Validate(object oldConfig, object newConfig)
+ {
+ var newPath = ((EncodingOptions)newConfig).TranscodingTempPath;
+
+ if (!string.IsNullOrWhiteSpace(newPath)
+ && !string.Equals(((EncodingOptions)oldConfig).TranscodingTempPath, newPath, StringComparison.Ordinal))
+ {
+ // Validate
+ if (!Directory.Exists(newPath))
+ {
+ throw new DirectoryNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} does not exist.",
+ newPath));
+ }
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index 262772959..60a2d39e5 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -1,135 +1,386 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
-using MediaBrowser.Model.Diagnostics;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
public class EncoderValidator
{
+ private static readonly string[] _requiredDecoders = new[]
+ {
+ "h264",
+ "hevc",
+ "mpeg2video",
+ "mpeg4",
+ "msmpeg4",
+ "dts",
+ "ac3",
+ "aac",
+ "mp3",
+ "flac",
+ "h264_qsv",
+ "hevc_qsv",
+ "mpeg2_qsv",
+ "vc1_qsv",
+ "vp8_qsv",
+ "vp9_qsv",
+ "h264_cuvid",
+ "hevc_cuvid",
+ "mpeg2_cuvid",
+ "vc1_cuvid",
+ "mpeg4_cuvid",
+ "vp8_cuvid",
+ "vp9_cuvid",
+ "h264_mmal",
+ "mpeg2_mmal",
+ "mpeg4_mmal",
+ "vc1_mmal",
+ "h264_mediacodec",
+ "hevc_mediacodec",
+ "mpeg2_mediacodec",
+ "mpeg4_mediacodec",
+ "vp8_mediacodec",
+ "vp9_mediacodec",
+ "h264_opencl",
+ "hevc_opencl",
+ "mpeg2_opencl",
+ "mpeg4_opencl",
+ "vp8_opencl",
+ "vp9_opencl",
+ "vc1_opencl"
+ };
+
+ private static readonly string[] _requiredEncoders = new[]
+ {
+ "libx264",
+ "libx265",
+ "mpeg4",
+ "msmpeg4",
+ "libvpx",
+ "libvpx-vp9",
+ "aac",
+ "libfdk_aac",
+ "ac3",
+ "libmp3lame",
+ "libopus",
+ "libvorbis",
+ "flac",
+ "srt",
+ "h264_amf",
+ "hevc_amf",
+ "h264_qsv",
+ "hevc_qsv",
+ "h264_nvenc",
+ "hevc_nvenc",
+ "h264_vaapi",
+ "hevc_vaapi",
+ "h264_omx",
+ "hevc_omx",
+ "h264_v4l2m2m",
+ "h264_videotoolbox",
+ "hevc_videotoolbox"
+ };
+
+ private static readonly string[] _requiredFilters = new[]
+ {
+ "scale_cuda",
+ "yadif_cuda",
+ "hwupload_cuda",
+ "overlay_cuda",
+ "tonemap_cuda",
+ "tonemap_opencl",
+ "tonemap_vaapi",
+ };
+
+ private static readonly IReadOnlyDictionary<int, string[]> _filterOptionsDict = new Dictionary<int, string[]>
+ {
+ { 0, new string[] { "scale_cuda", "Output format (default \"same\")" } },
+ { 1, new string[] { "tonemap_cuda", "GPU accelerated HDR to SDR tonemapping" } },
+ { 2, new string[] { "tonemap_opencl", "bt2390" } }
+ };
+
+ // These are the library versions that corresponds to our minimum ffmpeg version 4.x according to the version table below
+ private static readonly IReadOnlyDictionary<string, Version> _ffmpegMinimumLibraryVersions = new Dictionary<string, Version>
+ {
+ { "libavutil", new Version(56, 14) },
+ { "libavcodec", new Version(58, 18) },
+ { "libavformat", new Version(58, 12) },
+ { "libavdevice", new Version(58, 3) },
+ { "libavfilter", new Version(7, 16) },
+ { "libswscale", new Version(5, 1) },
+ { "libswresample", new Version(3, 1) },
+ { "libpostproc", new Version(55, 1) }
+ };
+
private readonly ILogger _logger;
- private readonly IProcessFactory _processFactory;
- public EncoderValidator(ILogger logger, IProcessFactory processFactory)
+ private readonly string _encoderPath;
+
+ public EncoderValidator(ILogger logger, string encoderPath)
{
_logger = logger;
- _processFactory = processFactory;
+ _encoderPath = encoderPath;
}
- public (IEnumerable<string> decoders, IEnumerable<string> encoders) Validate(string encoderPath)
+ private enum Codec
{
- _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath);
-
- var decoders = GetCodecs(encoderPath, Codec.Decoder);
- var encoders = GetCodecs(encoderPath, Codec.Encoder);
+ Encoder,
+ Decoder
+ }
- _logger.LogInformation("Encoder validation complete");
+ // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions
+ public static Version MinVersion { get; } = new Version(4, 0);
- return (decoders, encoders);
- }
+ public static Version? MaxVersion { get; } = null;
- public bool ValidateVersion(string encoderAppPath, bool logOutput)
+ public bool ValidateVersion()
{
- string output = null;
+ string output;
try
{
- output = GetProcessOutput(encoderAppPath, "-version");
+ output = GetProcessOutput(_encoderPath, "-version");
}
catch (Exception ex)
{
- if (logOutput)
- {
- _logger.LogError(ex, "Error validating encoder");
- }
+ _logger.LogError(ex, "Error validating encoder");
+ return false;
}
if (string.IsNullOrWhiteSpace(output))
{
+ _logger.LogError("FFmpeg validation: The process returned no result");
return false;
}
_logger.LogDebug("ffmpeg output: {Output}", output);
- if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
+ return ValidateVersionInternal(output);
+ }
+
+ internal bool ValidateVersionInternal(string versionOutput)
+ {
+ if (versionOutput.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
{
+ _logger.LogError("FFmpeg validation: avconv instead of ffmpeg is not supported");
return false;
}
- output = " " + output + " ";
+ // Work out what the version under test is
+ var version = GetFFmpegVersionInternal(versionOutput);
- for (var i = 2013; i <= 2015; i++)
+ _logger.LogInformation("Found ffmpeg version {Version}", version != null ? version.ToString() : "unknown");
+
+ if (version == null)
{
- var yearString = i.ToString(CultureInfo.InvariantCulture);
- if (output.IndexOf(" " + yearString + " ", StringComparison.OrdinalIgnoreCase) != -1)
+ if (MaxVersion != null) // Version is unknown
+ {
+ if (MinVersion == MaxVersion)
+ {
+ _logger.LogWarning("FFmpeg validation: We recommend version {MinVersion}", MinVersion);
+ }
+ else
+ {
+ _logger.LogWarning("FFmpeg validation: We recommend a minimum of {MinVersion} and maximum of {MaxVersion}", MinVersion, MaxVersion);
+ }
+ }
+ else
{
- return false;
+ _logger.LogWarning("FFmpeg validation: We recommend minimum version {MinVersion}", MinVersion);
}
+
+ return false;
+ }
+ else if (version < MinVersion) // Version is below what we recommend
+ {
+ _logger.LogWarning("FFmpeg validation: The minimum recommended version is {MinVersion}", MinVersion);
+ return false;
+ }
+ else if (MaxVersion != null && version > MaxVersion) // Version is above what we recommend
+ {
+ _logger.LogWarning("FFmpeg validation: The maximum recommended version is {MaxVersion}", MaxVersion);
+ return false;
}
return true;
}
- private static readonly string[] requiredDecoders = new[]
- {
- "mpeg2video",
- "h264_qsv",
- "hevc_qsv",
- "mpeg2_qsv",
- "vc1_qsv",
- "h264_cuvid",
- "hevc_cuvid",
- "dts",
- "ac3",
- "aac",
- "mp3",
- "h264",
- "hevc"
- };
-
- private static readonly string[] requiredEncoders = new[]
- {
- "libx264",
- "libx265",
- "mpeg4",
- "msmpeg4",
- "libvpx",
- "libvpx-vp9",
- "aac",
- "libmp3lame",
- "libopus",
- "libvorbis",
- "srt",
- "h264_nvenc",
- "hevc_nvenc",
- "h264_qsv",
- "hevc_qsv",
- "h264_omx",
- "hevc_omx",
- "h264_vaapi",
- "hevc_vaapi",
- "ac3"
- };
+ public IEnumerable<string> GetDecoders() => GetCodecs(Codec.Decoder);
- private enum Codec
+ public IEnumerable<string> GetEncoders() => GetCodecs(Codec.Encoder);
+
+ public IEnumerable<string> GetHwaccels() => GetHwaccelTypes();
+
+ public IEnumerable<string> GetFilters() => GetFFmpegFilters();
+
+ public IDictionary<int, bool> GetFiltersWithOption() => GetFFmpegFiltersWithOption();
+
+ public Version? GetFFmpegVersion()
{
- Encoder,
- Decoder
+ string output;
+ try
+ {
+ output = GetProcessOutput(_encoderPath, "-version");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error validating encoder");
+ return null;
+ }
+
+ if (string.IsNullOrWhiteSpace(output))
+ {
+ _logger.LogError("FFmpeg validation: The process returned no result");
+ return null;
+ }
+
+ _logger.LogDebug("ffmpeg output: {Output}", output);
+
+ return GetFFmpegVersionInternal(output);
+ }
+
+ /// <summary>
+ /// Using the output from "ffmpeg -version" work out the FFmpeg version.
+ /// For pre-built binaries the first line should contain a string like "ffmpeg version x.y", which is easy
+ /// to parse. If this is not available, then we try to match known library versions to FFmpeg versions.
+ /// If that fails then we test the libraries to determine if they're newer than our minimum versions.
+ /// </summary>
+ /// <param name="output">The output from "ffmpeg -version".</param>
+ /// <returns>The FFmpeg version.</returns>
+ internal Version? GetFFmpegVersionInternal(string output)
+ {
+ // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output
+ var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)");
+
+ if (match.Success)
+ {
+ if (Version.TryParse(match.Groups[1].Value, out var result))
+ {
+ return result;
+ }
+ }
+
+ var versionMap = GetFFmpegLibraryVersions(output);
+
+ var allVersionsValidated = true;
+
+ foreach (var minimumVersion in _ffmpegMinimumLibraryVersions)
+ {
+ if (versionMap.TryGetValue(minimumVersion.Key, out var foundVersion))
+ {
+ if (foundVersion >= minimumVersion.Value)
+ {
+ _logger.LogInformation("Found {Library} version {FoundVersion} ({MinimumVersion})", minimumVersion.Key, foundVersion, minimumVersion.Value);
+ }
+ else
+ {
+ _logger.LogWarning("Found {Library} version {FoundVersion} lower than recommended version {MinimumVersion}", minimumVersion.Key, foundVersion, minimumVersion.Value);
+ allVersionsValidated = false;
+ }
+ }
+ else
+ {
+ _logger.LogError("{Library} version not found", minimumVersion.Key);
+ allVersionsValidated = false;
+ }
+ }
+
+ return allVersionsValidated ? MinVersion : null;
}
- private IEnumerable<string> GetCodecs(string encoderAppPath, Codec codec)
+ /// <summary>
+ /// Grabs the library names and major.minor version numbers from the 'ffmpeg -version' output
+ /// and condenses them on to one line. Output format is "name1=major.minor,name2=major.minor,etc.".
+ /// </summary>
+ /// <param name="output">The 'ffmpeg -version' output.</param>
+ /// <returns>The library names and major.minor version numbers.</returns>
+ private static IReadOnlyDictionary<string, Version> GetFFmpegLibraryVersions(string output)
+ {
+ var map = new Dictionary<string, Version>();
+
+ foreach (Match match in Regex.Matches(
+ output,
+ @"((?<name>lib\w+)\s+(?<major>[0-9]+)\.\s*(?<minor>[0-9]+))",
+ RegexOptions.Multiline))
+ {
+ var version = new Version(
+ int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture),
+ int.Parse(match.Groups["minor"].Value, CultureInfo.InvariantCulture));
+
+ map.Add(match.Groups["name"].Value, version);
+ }
+
+ return map;
+ }
+
+ private IEnumerable<string> GetHwaccelTypes()
+ {
+ string? output = null;
+ try
+ {
+ output = GetProcessOutput(_encoderPath, "-hwaccels");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error detecting available hwaccel types");
+ }
+
+ if (string.IsNullOrWhiteSpace(output))
+ {
+ return Enumerable.Empty<string>();
+ }
+
+ var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
+ _logger.LogInformation("Available hwaccel types: {Types}", found);
+
+ return found;
+ }
+
+ public bool CheckFilterWithOption(string filter, string option)
+ {
+ if (string.IsNullOrEmpty(filter) || string.IsNullOrEmpty(option))
+ {
+ return false;
+ }
+
+ string output;
+ try
+ {
+ output = GetProcessOutput(_encoderPath, "-h filter=" + filter);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error detecting the given filter");
+ return false;
+ }
+
+ if (output.Contains("Filter " + filter, StringComparison.Ordinal))
+ {
+ return output.Contains(option, StringComparison.Ordinal);
+ }
+
+ _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option);
+
+ return false;
+ }
+
+ private IEnumerable<string> GetCodecs(Codec codec)
{
string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
- string output = null;
+ string output;
try
{
- output = GetProcessOutput(encoderAppPath, "-" + codecstr);
+ output = GetProcessOutput(_encoderPath, "-" + codecstr);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error detecting available {Codec}", codecstr);
+ return Enumerable.Empty<string>();
}
if (string.IsNullOrWhiteSpace(output))
@@ -137,7 +388,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return Enumerable.Empty<string>();
}
- var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders;
+ var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
var found = Regex
.Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
@@ -150,47 +401,70 @@ namespace MediaBrowser.MediaEncoding.Encoder
return found;
}
- private string GetProcessOutput(string path, string arguments)
+ private IEnumerable<string> GetFFmpegFilters()
{
- IProcess process = _processFactory.Create(new ProcessOptions
+ string output;
+ try
{
- CreateNoWindow = true,
- UseShellExecute = false,
- FileName = path,
- Arguments = arguments,
- IsHidden = true,
- ErrorDialog = false,
- RedirectStandardOutput = true,
- // ffmpeg uses stderr to log info, don't show this
- RedirectStandardError = true
- });
-
- _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
+ output = GetProcessOutput(_encoderPath, "-filters");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error detecting available filters");
+ return Enumerable.Empty<string>();
+ }
- using (process)
+ if (string.IsNullOrWhiteSpace(output))
{
- process.Start();
+ return Enumerable.Empty<string>();
+ }
+
+ var found = Regex
+ .Matches(output, @"^\s\S{3}\s(?<filter>[\w|-]+)\s+.+$", RegexOptions.Multiline)
+ .Cast<Match>()
+ .Select(x => x.Groups["filter"].Value)
+ .Where(x => _requiredFilters.Contains(x));
+
+ _logger.LogInformation("Available filters: {Filters}", found);
- try
+ return found;
+ }
+
+ private IDictionary<int, bool> GetFFmpegFiltersWithOption()
+ {
+ IDictionary<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)
{
- return process.StandardOutput.ReadToEnd();
+ dict.Add(i, CheckFilterWithOption(val[0], val[1]));
}
- catch
- {
- _logger.LogWarning("Killing process {Path} {Arguments}", path, arguments);
+ }
- // Hate having to do this
- try
- {
- process.Kill();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error killing process");
- }
+ return dict;
+ }
- throw;
+ private string GetProcessOutput(string path, string arguments)
+ {
+ using (var process = new Process()
+ {
+ StartInfo = new ProcessStartInfo(path, arguments)
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false,
+ RedirectStandardOutput = true,
+ // ffmpeg uses stderr to log info, don't show this
+ RedirectStandardError = true
}
+ })
+ {
+ _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
+
+ process.Start();
+
+ return process.StandardOutput.ReadToEnd();
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
index 44e62446b..d0ea0429b 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
@@ -1,59 +1,54 @@
-using System.Collections.Generic;
-using System.Linq;
+#pragma warning disable CS1591
+
+using System;
+using System.Globalization;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.Encoder
{
public static class EncodingUtils
{
- public static string GetInputArgument(List<string> inputFiles, MediaProtocol protocol)
+ public static string GetInputArgument(string inputPrefix, string inputFile, MediaProtocol protocol)
{
if (protocol != MediaProtocol.File)
{
- var url = inputFiles.First();
-
- return string.Format("\"{0}\"", url);
+ return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", inputFile);
}
- return GetConcatInputArgument(inputFiles);
+ return GetConcatInputArgument(inputFile, inputPrefix);
}
/// <summary>
/// Gets the concat input argument.
/// </summary>
- /// <param name="inputFiles">The input files.</param>
+ /// <param name="inputFile">The input file.</param>
+ /// <param name="inputPrefix">The input prefix.</param>
/// <returns>System.String.</returns>
- private static string GetConcatInputArgument(IReadOnlyList<string> inputFiles)
+ private static string GetConcatInputArgument(string inputFile, string inputPrefix)
{
// Get all streams
// If there's more than one we'll need to use the concat command
- if (inputFiles.Count > 1)
- {
- var files = string.Join("|", inputFiles.Select(NormalizePath).ToArray());
-
- return string.Format("concat:\"{0}\"", files);
- }
-
// Determine the input path for video files
- return GetFileInputArgument(inputFiles[0]);
+ return GetFileInputArgument(inputFile, inputPrefix);
}
/// <summary>
/// Gets the file input argument.
/// </summary>
/// <param name="path">The path.</param>
+ /// <param name="inputPrefix">The path prefix.</param>
/// <returns>System.String.</returns>
- private static string GetFileInputArgument(string path)
+ private static string GetFileInputArgument(string path, string inputPrefix)
{
- if (path.IndexOf("://") != -1)
+ if (path.IndexOf("://", StringComparison.Ordinal) != -1)
{
- return string.Format("\"{0}\"", path);
+ return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", path);
}
// Quotes are valid path characters in linux and they need to be escaped here with a leading \
path = NormalizePath(path);
- return string.Format("file:\"{0}\"", path);
+ return string.Format(CultureInfo.InvariantCulture, "{1}:\"{0}\"", path, inputPrefix);
}
/// <summary>
@@ -64,7 +59,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
private static string NormalizePath(string path)
{
// Quotes are valid path characters in linux and they need to be escaped here with a leading \
- return path.Replace("\"", "\\\"");
+ return path.Replace("\"", "\\\"", StringComparison.Ordinal);
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index d922f1068..fbc7ba72f 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -1,385 +1,273 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text.Json;
+using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Session;
using MediaBrowser.MediaEncoding.Probing;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
/// <summary>
- /// Class MediaEncoder
+ /// Class MediaEncoder.
/// </summary>
public class MediaEncoder : IMediaEncoder, IDisposable
{
/// <summary>
- /// The _logger
+ /// The default SDR image extraction timeout in milliseconds.
/// </summary>
- private readonly ILogger _logger;
+ internal const int DefaultSdrImageExtractionTimeout = 10000;
/// <summary>
- /// Gets the json serializer.
+ /// The default HDR image extraction timeout in milliseconds.
/// </summary>
- /// <value>The json serializer.</value>
- private readonly IJsonSerializer _jsonSerializer;
+ internal const int DefaultHdrImageExtractionTimeout = 20000;
- /// <summary>
- /// The _thumbnail resource pool
- /// </summary>
- private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
+ private readonly ILogger<MediaEncoder> _logger;
+ private readonly IServerConfigurationManager _configurationManager;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+ private readonly string _startupOptionFFmpegPath;
- public string FFMpegPath { get; private set; }
+ private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(2, 2);
- public string FFProbePath { get; private set; }
+ private readonly object _runningProcessesLock = new object();
+ private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
- protected readonly IServerConfigurationManager ConfigurationManager;
- protected readonly IFileSystem FileSystem;
- protected readonly ILiveTvManager LiveTvManager;
- protected readonly IIsoManager IsoManager;
- protected readonly ILibraryManager LibraryManager;
- protected readonly IChannelManager ChannelManager;
- protected readonly ISessionManager SessionManager;
- protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
- protected readonly Func<IMediaSourceManager> MediaSourceManager;
- private readonly IHttpClient _httpClient;
- private readonly IZipClient _zipClient;
- private readonly IProcessFactory _processFactory;
+ // MediaEncoder is registered as a Singleton
+ private readonly JsonSerializerOptions _jsonSerializerOptions;
- private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
- private readonly bool _hasExternalEncoder;
- private readonly string _originalFFMpegPath;
- private readonly string _originalFFProbePath;
- private readonly int DefaultImageExtractionTimeoutMs;
+ private List<string> _encoders = new List<string>();
+ 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 Version _ffmpegVersion = null;
+ private string _ffmpegPath = string.Empty;
+ private string _ffprobePath;
+ private int _threads;
public MediaEncoder(
- ILoggerFactory loggerFactory,
- IJsonSerializer jsonSerializer,
- string ffMpegPath,
- string ffProbePath,
- bool hasExternalEncoder,
+ ILogger<MediaEncoder> logger,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
- ILiveTvManager liveTvManager,
- IIsoManager isoManager,
- ILibraryManager libraryManager,
- IChannelManager channelManager,
- ISessionManager sessionManager,
- Func<ISubtitleEncoder> subtitleEncoder,
- Func<IMediaSourceManager> mediaSourceManager,
- IHttpClient httpClient,
- IZipClient zipClient,
- IProcessFactory processFactory,
- int defaultImageExtractionTimeoutMs)
+ ILocalizationManager localization,
+ IConfiguration config)
{
- _logger = loggerFactory.CreateLogger(nameof(MediaEncoder));
- _jsonSerializer = jsonSerializer;
- ConfigurationManager = configurationManager;
- FileSystem = fileSystem;
- LiveTvManager = liveTvManager;
- IsoManager = isoManager;
- LibraryManager = libraryManager;
- ChannelManager = channelManager;
- SessionManager = sessionManager;
- SubtitleEncoder = subtitleEncoder;
- MediaSourceManager = mediaSourceManager;
- _httpClient = httpClient;
- _zipClient = zipClient;
- _processFactory = processFactory;
- DefaultImageExtractionTimeoutMs = defaultImageExtractionTimeoutMs;
- FFProbePath = ffProbePath;
- FFMpegPath = ffMpegPath;
- _originalFFProbePath = ffProbePath;
- _originalFFMpegPath = ffMpegPath;
- _hasExternalEncoder = hasExternalEncoder;
+ _logger = logger;
+ _configurationManager = configurationManager;
+ _fileSystem = fileSystem;
+ _localization = localization;
+ _startupOptionFFmpegPath = config.GetValue<string>(Controller.Extensions.ConfigurationExtensions.FfmpegPathKey) ?? string.Empty;
+ _jsonSerializerOptions = JsonDefaults.Options;
}
- public string EncoderLocationType
+ /// <inheritdoc />
+ public string EncoderPath => _ffmpegPath;
+
+ /// <summary>
+ /// Run at startup or if the user removes a Custom path from transcode page.
+ /// Sets global variables FFmpegPath.
+ /// Precedence is: Config > CLI > $PATH.
+ /// </summary>
+ public void SetFFmpegPath()
{
- get
+ // 1) Custom path stored in config/encoding xml file under tag <EncoderAppPath> takes precedence
+ var ffmpegPath = _configurationManager.GetEncodingOptions().EncoderAppPath;
+ if (string.IsNullOrEmpty(ffmpegPath))
{
- if (_hasExternalEncoder)
+ // 2) Check if the --ffmpeg CLI switch has been given
+ ffmpegPath = _startupOptionFFmpegPath;
+ if (string.IsNullOrEmpty(ffmpegPath))
{
- return "External";
+ // 3) Check "ffmpeg"
+ ffmpegPath = "ffmpeg";
}
-
- if (string.IsNullOrWhiteSpace(FFMpegPath))
- {
- return null;
- }
-
- if (IsSystemInstalledPath(FFMpegPath))
- {
- return "System";
- }
-
- return "Custom";
- }
- }
-
- private bool IsSystemInstalledPath(string path)
- {
- if (path.IndexOf("/", StringComparison.Ordinal) == -1 && path.IndexOf("\\", StringComparison.Ordinal) == -1)
- {
- return true;
}
- return false;
- }
-
- public void Init()
- {
- InitPaths();
-
- if (!string.IsNullOrWhiteSpace(FFMpegPath))
+ if (!ValidatePath(ffmpegPath))
{
- var result = new EncoderValidator(_logger, _processFactory).Validate(FFMpegPath);
-
- SetAvailableDecoders(result.decoders);
- SetAvailableEncoders(result.encoders);
+ _ffmpegPath = null;
}
- }
- private void InitPaths()
- {
- ConfigureEncoderPaths();
+ // Write the FFmpeg path to the config/encoding.xml file as <EncoderAppPathDisplay> so it appears in UI
+ var config = _configurationManager.GetEncodingOptions();
+ config.EncoderAppPathDisplay = _ffmpegPath ?? string.Empty;
+ _configurationManager.SaveConfiguration("encoding", config);
- if (_hasExternalEncoder)
+ // Only if mpeg path is set, try and set path to probe
+ if (_ffmpegPath != null)
{
- LogPaths();
- return;
- }
+ // Determine a probe path from the mpeg path
+ _ffprobePath = Regex.Replace(_ffmpegPath, @"[^\/\\]+?(\.[^\/\\\n.]+)?$", @"ffprobe$1");
- // If the path was passed in, save it into config now.
- var encodingOptions = GetEncodingOptions();
- var appPath = encodingOptions.EncoderAppPath;
+ // Interrogate to understand what coders are supported
+ var validator = new EncoderValidator(_logger, _ffmpegPath);
- var valueToSave = FFMpegPath;
+ SetAvailableDecoders(validator.GetDecoders());
+ SetAvailableEncoders(validator.GetEncoders());
+ SetAvailableFilters(validator.GetFilters());
+ SetAvailableFiltersWithOption(validator.GetFiltersWithOption());
+ SetAvailableHwaccels(validator.GetHwaccels());
+ SetMediaEncoderVersion(validator);
- if (!string.IsNullOrWhiteSpace(valueToSave))
- {
- // if using system variable, don't save this.
- if (IsSystemInstalledPath(valueToSave) || _hasExternalEncoder)
- {
- valueToSave = null;
- }
+ _threads = EncodingHelper.GetNumberOfThreads(null, _configurationManager.GetEncodingOptions(), null);
}
- if (!string.Equals(valueToSave, appPath, StringComparison.Ordinal))
- {
- encodingOptions.EncoderAppPath = valueToSave;
- ConfigurationManager.SaveConfiguration("encoding", encodingOptions);
- }
+ _logger.LogInformation("FFmpeg: {FfmpegPath}", _ffmpegPath ?? string.Empty);
}
+ /// <summary>
+ /// Triggered from the Settings > Transcoding UI page when users submits Custom FFmpeg path to use.
+ /// Only write the new path to xml if it exists. Do not perform validation checks on ffmpeg here.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="pathType">The path type.</param>
public void UpdateEncoderPath(string path, string pathType)
{
- if (_hasExternalEncoder)
+ var config = _configurationManager.GetEncodingOptions();
+
+ // Filesystem may not be case insensitive, but EncoderAppPathDisplay should always point to a valid file?
+ if (string.IsNullOrEmpty(config.EncoderAppPath)
+ && string.Equals(config.EncoderAppPathDisplay, path, StringComparison.OrdinalIgnoreCase))
{
+ _logger.LogDebug("Existing ffmpeg path is empty and the new path is the same as {EncoderAppPathDisplay}. Skipping", nameof(config.EncoderAppPathDisplay));
return;
}
- _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty);
+ string newPath;
- Tuple<string, string> newPaths;
+ _logger.LogInformation("Attempting to update encoder path to {Path}. pathType: {PathType}", path ?? string.Empty, pathType ?? string.Empty);
- if (string.Equals(pathType, "system", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(pathType, "custom", StringComparison.OrdinalIgnoreCase))
{
- path = "ffmpeg";
+ throw new ArgumentException("Unexpected pathType value");
+ }
- newPaths = TestForInstalledVersions();
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ // User had cleared the custom path in UI
+ newPath = string.Empty;
}
- else if (string.Equals(pathType, "custom", StringComparison.OrdinalIgnoreCase))
+ else
{
- if (string.IsNullOrWhiteSpace(path))
+ if (Directory.Exists(path))
{
- throw new ArgumentNullException(nameof(path));
+ // Given path is directory, so resolve down to filename
+ newPath = GetEncoderPathFromDirectory(path, "ffmpeg");
+ }
+ else
+ {
+ newPath = path;
}
- if (!File.Exists(path) && !Directory.Exists(path))
+ if (!new EncoderValidator(_logger, newPath).ValidateVersion())
{
throw new ResourceNotFoundException();
}
- newPaths = GetEncoderPaths(path);
- }
- else
- {
- throw new ArgumentException("Unexpected pathType value");
- }
-
- if (string.IsNullOrWhiteSpace(newPaths.Item1))
- {
- throw new ResourceNotFoundException("ffmpeg not found");
- }
- if (string.IsNullOrWhiteSpace(newPaths.Item2))
- {
- throw new ResourceNotFoundException("ffprobe not found");
- }
-
- path = newPaths.Item1;
-
- if (!ValidateVersion(path, true))
- {
- throw new ResourceNotFoundException("ffmpeg version 3.0 or greater is required.");
}
- var config = GetEncodingOptions();
- config.EncoderAppPath = path;
- ConfigurationManager.SaveConfiguration("encoding", config);
-
- Init();
- }
+ // Write the new ffmpeg path to the xml as <EncoderAppPath>
+ // This ensures its not lost on next startup
+ config.EncoderAppPath = newPath;
+ _configurationManager.SaveConfiguration("encoding", config);
- private bool ValidateVersion(string path, bool logOutput)
- {
- return new EncoderValidator(_logger, _processFactory).ValidateVersion(path, logOutput);
+ // Trigger SetFFmpegPath so we validate the new path and setup probe path
+ SetFFmpegPath();
}
- private void ConfigureEncoderPaths()
+ /// <summary>
+ /// Validates the supplied FQPN to ensure it is a ffmpeg utility.
+ /// If checks pass, global variable FFmpegPath is updated.
+ /// </summary>
+ /// <param name="path">FQPN to test.</param>
+ /// <returns><c>true</c> if the version validation succeeded; otherwise, <c>false</c>.</returns>
+ private bool ValidatePath(string path)
{
- if (_hasExternalEncoder)
+ if (string.IsNullOrEmpty(path))
{
- return;
+ return false;
}
- var appPath = GetEncodingOptions().EncoderAppPath;
-
- if (string.IsNullOrWhiteSpace(appPath))
+ bool rc = new EncoderValidator(_logger, path).ValidateVersion();
+ if (!rc)
{
- appPath = Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "ffmpeg");
+ _logger.LogWarning("FFmpeg: Failed version check: {Path}", path);
+ return false;
}
- var newPaths = GetEncoderPaths(appPath);
- if (string.IsNullOrWhiteSpace(newPaths.Item1) || string.IsNullOrWhiteSpace(newPaths.Item2) || IsSystemInstalledPath(appPath))
- {
- newPaths = TestForInstalledVersions();
- }
-
- if (!string.IsNullOrWhiteSpace(newPaths.Item1) && !string.IsNullOrWhiteSpace(newPaths.Item2))
- {
- FFMpegPath = newPaths.Item1;
- FFProbePath = newPaths.Item2;
- }
-
- LogPaths();
+ _ffmpegPath = path;
+ return true;
}
- private Tuple<string, string> GetEncoderPaths(string configuredPath)
+ private string GetEncoderPathFromDirectory(string path, string filename, bool recursive = false)
{
- var appPath = configuredPath;
-
- if (!string.IsNullOrWhiteSpace(appPath))
+ try
{
- if (Directory.Exists(appPath))
- {
- return GetPathsFromDirectory(appPath);
- }
-
- if (File.Exists(appPath))
- {
- return new Tuple<string, string>(appPath, GetProbePathFromEncoderPath(appPath));
- }
- }
+ var files = _fileSystem.GetFilePaths(path, recursive);
- return new Tuple<string, string>(null, null);
- }
+ var excludeExtensions = new[] { ".c" };
- private Tuple<string, string> TestForInstalledVersions()
- {
- string encoderPath = null;
- string probePath = null;
-
- if (_hasExternalEncoder && ValidateVersion(_originalFFMpegPath, true))
- {
- encoderPath = _originalFFMpegPath;
- probePath = _originalFFProbePath;
+ return files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), filename, StringComparison.OrdinalIgnoreCase)
+ && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
}
-
- if (string.IsNullOrWhiteSpace(encoderPath))
+ catch (Exception)
{
- if (ValidateVersion("ffmpeg", true) && ValidateVersion("ffprobe", false))
- {
- encoderPath = "ffmpeg";
- probePath = "ffprobe";
- }
+ // Trap all exceptions, like DirNotExists, and return null
+ return null;
}
-
- return new Tuple<string, string>(encoderPath, probePath);
}
- private Tuple<string, string> GetPathsFromDirectory(string path)
+ public void SetAvailableEncoders(IEnumerable<string> list)
{
- // Since we can't predict the file extension, first try directly within the folder
- // If that doesn't pan out, then do a recursive search
- var files = FileSystem.GetFilePaths(path);
-
- var excludeExtensions = new[] { ".c" };
-
- var ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
- var ffprobePath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
-
- if (string.IsNullOrWhiteSpace(ffmpegPath) || !File.Exists(ffmpegPath))
- {
- files = FileSystem.GetFilePaths(path, true);
-
- ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
-
- if (!string.IsNullOrWhiteSpace(ffmpegPath))
- {
- ffprobePath = GetProbePathFromEncoderPath(ffmpegPath);
- }
- }
-
- return new Tuple<string, string>(ffmpegPath, ffprobePath);
+ _encoders = list.ToList();
}
- private string GetProbePathFromEncoderPath(string appPath)
+ public void SetAvailableDecoders(IEnumerable<string> list)
{
- return FileSystem.GetFilePaths(Path.GetDirectoryName(appPath))
- .FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase));
+ _decoders = list.ToList();
}
- private void LogPaths()
+ public void SetAvailableHwaccels(IEnumerable<string> list)
{
- _logger.LogInformation("FFMpeg: {0}", FFMpegPath ?? "not found");
- _logger.LogInformation("FFProbe: {0}", FFProbePath ?? "not found");
+ _hwaccels = list.ToList();
}
- private EncodingOptions GetEncodingOptions()
+ public void SetAvailableFilters(IEnumerable<string> list)
{
- return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
+ _filters = list.ToList();
}
- private List<string> _encoders = new List<string>();
- public void SetAvailableEncoders(IEnumerable<string> list)
+ public void SetAvailableFiltersWithOption(IDictionary<int, bool> dict)
{
- _encoders = list.ToList();
- //_logger.Info("Supported encoders: {0}", string.Join(",", list.ToArray()));
+ _filtersWithOption = dict;
}
- private List<string> _decoders = new List<string>();
- public void SetAvailableDecoders(IEnumerable<string> list)
+ public void SetMediaEncoderVersion(EncoderValidator validator)
{
- _decoders = list.ToList();
- //_logger.Info("Supported decoders: {0}", string.Join(",", list.ToArray()));
+ _ffmpegVersion = validator.GetFFmpegVersion();
}
public bool SupportsEncoder(string encoder)
@@ -392,6 +280,31 @@ namespace MediaBrowser.MediaEncoding.Encoder
return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase);
}
+ public bool SupportsHwaccel(string hwaccel)
+ {
+ return _hwaccels.Contains(hwaccel, StringComparer.OrdinalIgnoreCase);
+ }
+
+ public bool SupportsFilter(string filter)
+ {
+ return _filters.Contains(filter, StringComparer.OrdinalIgnoreCase);
+ }
+
+ public bool SupportsFilterWithOption(FilterOptionType option)
+ {
+ if (_filtersWithOption.TryGetValue((int)option, out var val))
+ {
+ return val;
+ }
+
+ return false;
+ }
+
+ public Version GetMediaEncoderVersion()
+ {
+ return _ffmpegVersion;
+ }
+
public bool CanEncodeToAudioCodec(string codec)
{
if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
@@ -413,12 +326,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
/// <summary>
- /// Gets the encoder path.
- /// </summary>
- /// <value>The encoder path.</value>
- public string EncoderPath => FFMpegPath;
-
- /// <summary>
/// Gets the media info.
/// </summary>
/// <param name="request">The request.</param>
@@ -427,48 +334,55 @@ namespace MediaBrowser.MediaEncoding.Encoder
public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
{
var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
+ var inputFile = request.MediaSource.Path;
- var inputFiles = MediaEncoderHelpers.GetInputArgument(FileSystem, request.MediaSource.Path, request.MediaSource.Protocol, request.MountedIso, request.PlayableStreamFileNames);
-
- var probeSize = EncodingHelper.GetProbeSizeArgument(inputFiles.Length);
- string analyzeDuration;
+ string analyzeDuration = string.Empty;
if (request.MediaSource.AnalyzeDurationMs > 0)
{
analyzeDuration = "-analyzeduration " +
(request.MediaSource.AnalyzeDurationMs * 1000).ToString();
}
- else
- {
- analyzeDuration = EncodingHelper.GetAnalyzeDurationArgument(inputFiles.Length);
- }
-
- probeSize = probeSize + " " + analyzeDuration;
- probeSize = probeSize.Trim();
var forceEnableLogging = request.MediaSource.Protocol != MediaProtocol.File;
- return GetMediaInfoInternal(GetInputArgument(inputFiles, request.MediaSource.Protocol), request.MediaSource.Path, request.MediaSource.Protocol, extractChapters,
- probeSize, request.MediaType == DlnaProfileType.Audio, request.MediaSource.VideoType, forceEnableLogging, cancellationToken);
+ return GetMediaInfoInternal(
+ GetInputArgument(inputFile, request.MediaSource),
+ request.MediaSource.Path,
+ request.MediaSource.Protocol,
+ extractChapters,
+ analyzeDuration,
+ request.MediaType == DlnaProfileType.Audio,
+ request.MediaSource.VideoType,
+ forceEnableLogging,
+ cancellationToken);
}
/// <summary>
/// Gets the input argument.
/// </summary>
- /// <param name="inputFiles">The input files.</param>
- /// <param name="protocol">The protocol.</param>
+ /// <param name="inputFile">The input file.</param>
+ /// <param name="mediaSource">The mediaSource.</param>
/// <returns>System.String.</returns>
- /// <exception cref="ArgumentException">Unrecognized InputType</exception>
- public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
+ /// <exception cref="ArgumentException">Unrecognized InputType.</exception>
+ public string GetInputArgument(string inputFile, MediaSourceInfo mediaSource)
{
- return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
+ var prefix = "file";
+ if (mediaSource.VideoType == VideoType.BluRay
+ || mediaSource.IsoType == IsoType.BluRay)
+ {
+ prefix = "bluray";
+ }
+
+ return EncodingUtils.GetInputArgument(prefix, inputFile, mediaSource.Protocol);
}
/// <summary>
/// Gets the media info internal.
/// </summary>
/// <returns>Task{MediaInfoResult}.</returns>
- private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,
+ private async Task<MediaInfo> GetMediaInfoInternal(
+ string inputPath,
string primaryPath,
MediaProtocol protocol,
bool extractChapters,
@@ -479,113 +393,150 @@ namespace MediaBrowser.MediaEncoding.Encoder
CancellationToken cancellationToken)
{
var args = extractChapters
- ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
- : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
+ ? "{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";
+ args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, _threads).Trim();
- var process = _processFactory.Create(new ProcessOptions
+ var process = new Process
{
- CreateNoWindow = true,
- UseShellExecute = false,
+ StartInfo = new ProcessStartInfo
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+
+ // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
+ RedirectStandardOutput = true,
- // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
- RedirectStandardOutput = true,
- FileName = FFProbePath,
- Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),
+ FileName = _ffprobePath,
+ Arguments = args,
- IsHidden = true,
- ErrorDialog = false,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false,
+ },
EnableRaisingEvents = true
- });
+ };
if (forceEnableLogging)
{
- _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogInformation("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
}
else
{
- _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogDebug("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
}
- using (var processWrapper = new ProcessWrapper(process, this, _logger))
+ using (var processWrapper = new ProcessWrapper(process, this))
{
+ _logger.LogDebug("Starting ffprobe with args {Args}", args);
StartProcess(processWrapper);
+ InternalMediaInfoResult result;
try
{
- //process.BeginErrorReadLine();
+ result = await JsonSerializer.DeserializeAsync<InternalMediaInfoResult>(
+ process.StandardOutput.BaseStream,
+ _jsonSerializerOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+ catch
+ {
+ StopProcess(processWrapper, 100);
- var result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
+ throw;
+ }
- if (result == null || (result.streams == null && result.format == null))
- {
- throw new Exception("ffprobe failed - streams and format are both null.");
- }
+ if (result == null || (result.Streams == null && result.Format == null))
+ {
+ throw new FfmpegException("ffprobe failed - streams and format are both null.");
+ }
- if (result.streams != null)
+ if (result.Streams != null)
+ {
+ // Normalize aspect ratio if invalid
+ foreach (var stream in result.Streams)
{
- // Normalize aspect ratio if invalid
- foreach (var stream in result.streams)
+ if (string.Equals(stream.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
{
- if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
- {
- stream.display_aspect_ratio = string.Empty;
- }
- if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
- {
- stream.sample_aspect_ratio = string.Empty;
- }
+ stream.DisplayAspectRatio = string.Empty;
}
- }
- return new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
+ if (string.Equals(stream.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
+ {
+ stream.SampleAspectRatio = string.Empty;
+ }
+ }
}
- catch
- {
- StopProcess(processWrapper, 100);
- throw;
- }
+ return new ProbeResultNormalizer(_logger, _localization).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
}
}
- /// <summary>
- /// The us culture
- /// </summary>
- protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken)
{
- return ExtractImage(new[] { path }, null, null, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken);
+ var mediaSource = new MediaSourceInfo
+ {
+ Protocol = MediaProtocol.File
+ };
+
+ return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, ".jpg", cancellationToken);
}
- public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
+ public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
{
- return ExtractImage(inputFiles, container, videoStream, null, protocol, false, threedFormat, offset, cancellationToken);
+ return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, ".jpg", cancellationToken);
}
- public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken)
+ public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken)
{
- return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, protocol, false, null, null, cancellationToken);
+ return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, outputExtension, cancellationToken);
}
- private async Task<string> ExtractImage(string[] inputFiles, string container, MediaStream videoStream, int? imageStreamIndex, MediaProtocol protocol, bool isAudio,
- Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
+ private async Task<string> ExtractImage(
+ string inputFile,
+ string container,
+ MediaStream videoStream,
+ int? imageStreamIndex,
+ MediaSourceInfo mediaSource,
+ bool isAudio,
+ Video3DFormat? threedFormat,
+ TimeSpan? offset,
+ string outputExtension,
+ CancellationToken cancellationToken)
{
- var inputArgument = GetInputArgument(inputFiles, protocol);
+ var inputArgument = GetInputArgument(inputFile, mediaSource);
- if (isAudio)
+ if (!isAudio)
{
- if (imageStreamIndex.HasValue && imageStreamIndex.Value > 0)
+ // The failure of HDR extraction usually occurs when using custom ffmpeg that does not contain the zscale filter.
+ try
{
- // It seems for audio files we need to subtract 1 (for the audio stream??)
- imageStreamIndex = imageStreamIndex.Value - 1;
+ return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, true, outputExtension, cancellationToken).ConfigureAwait(false);
}
- }
- else
- {
+ catch (ArgumentException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "I-frame or HDR image extraction failed, will attempt with I-frame extraction disabled. Input: {Arguments}", inputArgument);
+ }
+
+ try
+ {
+ return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, true, outputExtension, cancellationToken).ConfigureAwait(false);
+ }
+ catch (ArgumentException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "HDR image extraction failed, will fallback to SDR image extraction. Input: {Arguments}", inputArgument);
+ }
+
try
{
- return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, cancellationToken).ConfigureAwait(false);
+ return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, false, outputExtension, cancellationToken).ConfigureAwait(false);
}
catch (ArgumentException)
{
@@ -593,141 +544,149 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument);
+ _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments}", inputArgument);
}
}
- return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, cancellationToken).ConfigureAwait(false);
+ return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, false, outputExtension, cancellationToken).ConfigureAwait(false);
}
- private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, CancellationToken cancellationToken)
+ private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, bool allowTonemap, string outputExtension, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(inputPath))
{
throw new ArgumentNullException(nameof(inputPath));
}
- var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");
+ if (string.IsNullOrEmpty(outputExtension))
+ {
+ outputExtension = ".jpg";
+ }
+ else if (outputExtension[0] != '.')
+ {
+ outputExtension = "." + outputExtension;
+ }
+
+ var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + outputExtension);
Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));
- // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
+ // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar.
// This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
- var vf = "scale=600:trunc(600/dar/2)*2";
-
- if (threedFormat.HasValue)
+ var vf = threedFormat switch
{
- switch (threedFormat.Value)
+ // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
+ Video3DFormat.HalfSideBySide => "-vf crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
+ // fsbs crop width in half,set the display aspect,crop out any black bars we may have made
+ Video3DFormat.FullSideBySide => "-vf crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
+ // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made
+ Video3DFormat.HalfTopAndBottom => "-vf crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
+ // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made
+ Video3DFormat.FullTopAndBottom => "-vf crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
+ _ => string.Empty
+ };
+
+ var mapArg = imageStreamIndex.HasValue ? (" -map 0:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
+
+ var enableHdrExtraction = allowTonemap && string.Equals(videoStream?.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase);
+ if (enableHdrExtraction)
+ {
+ string tonemapFilters = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p";
+ if (vf.Length == 0)
+ {
+ vf = "-vf " + tonemapFilters;
+ }
+ else
{
- case Video3DFormat.HalfSideBySide:
- vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
- // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
- break;
- case Video3DFormat.FullSideBySide:
- vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
- //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
- break;
- case Video3DFormat.HalfTopAndBottom:
- vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
- //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
- break;
- case Video3DFormat.FullTopAndBottom:
- vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
- // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
- break;
- default:
- break;
+ vf += "," + tonemapFilters;
}
}
- var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
-
- var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase);
// 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.
- var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty;
-
- var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) :
- string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);
-
- var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
- var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
-
- if (!string.IsNullOrWhiteSpace(probeSizeArgument))
+ // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will lower the processing speed.
+ var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase);
+ if (enableThumbnail)
{
- args = probeSizeArgument + " " + args;
+ var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase);
+ var batchSize = useLargerBatchSize ? "50" : "24";
+ if (string.IsNullOrEmpty(vf))
+ {
+ vf = "-vf thumbnail=" + batchSize;
+ }
+ else
+ {
+ vf += ",thumbnail=" + batchSize;
+ }
}
- if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
- {
- args = analyzeDurationArgument + " " + args;
- }
+ var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, _threads);
if (offset.HasValue)
{
- args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
- }
-
- var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
- if (videoStream != null)
- {
- /* fix
- var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
- if (!string.IsNullOrWhiteSpace(decoder))
- {
- args = decoder + " " + args;
- }
- */
+ args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args;
}
if (!string.IsNullOrWhiteSpace(container))
{
- var inputFormat = encodinghelper.GetInputFormat(container);
+ var inputFormat = EncodingHelper.GetInputFormat(container);
if (!string.IsNullOrWhiteSpace(inputFormat))
{
args = "-f " + inputFormat + " " + args;
}
}
- var process = _processFactory.Create(new ProcessOptions
+ var process = new Process
{
- CreateNoWindow = true,
- UseShellExecute = false,
- FileName = FFMpegPath,
- Arguments = args,
- IsHidden = true,
- ErrorDialog = false
- });
+ StartInfo = new ProcessStartInfo
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ FileName = _ffmpegPath,
+ Arguments = args,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false,
+ },
+ EnableRaisingEvents = true
+ };
- _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogDebug("{ProcessFileName} {ProcessArguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
- using (var processWrapper = new ProcessWrapper(process, this, _logger))
+ using (var processWrapper = new ProcessWrapper(process, this))
{
bool ranToCompletion;
- StartProcess(processWrapper);
-
- var timeoutMs = ConfigurationManager.Configuration.ImageExtractionTimeoutMs;
- if (timeoutMs <= 0)
+ await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
{
- timeoutMs = DefaultImageExtractionTimeoutMs;
- }
+ StartProcess(processWrapper);
- ranToCompletion = await process.WaitForExitAsync(timeoutMs).ConfigureAwait(false);
+ var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs;
+ if (timeoutMs <= 0)
+ {
+ timeoutMs = enableHdrExtraction ? DefaultHdrImageExtractionTimeout : DefaultSdrImageExtractionTimeout;
+ }
- if (!ranToCompletion)
+ ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false);
+
+ if (!ranToCompletion)
+ {
+ StopProcess(processWrapper, 1000);
+ }
+ }
+ finally
{
- StopProcess(processWrapper, 1000);
+ _thumbnailResourcePool.Release();
}
var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
- var file = FileSystem.GetFileInfo(tempExtractPath);
+ var file = _fileSystem.GetFileInfo(tempExtractPath);
if (exitCode == -1 || !file.Exists || file.Length == 0)
{
- var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
+ var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputPath);
_logger.LogError(msg);
- throw new Exception(msg);
+ throw new FfmpegException(msg);
}
return tempExtractPath;
@@ -743,13 +702,14 @@ namespace MediaBrowser.MediaEncoding.Encoder
public string GetTimeParameter(TimeSpan time)
{
- return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
+ return time.ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture);
}
- public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
+ public async Task ExtractVideoImagesOnInterval(
+ string inputFile,
string container,
MediaStream videoStream,
- MediaProtocol protocol,
+ MediaSourceInfo mediaSource,
Video3DFormat? threedFormat,
TimeSpan interval,
string targetDirectory,
@@ -757,75 +717,53 @@ namespace MediaBrowser.MediaEncoding.Encoder
int? maxWidth,
CancellationToken cancellationToken)
{
- var resourcePool = _thumbnailResourcePool;
-
- var inputArgument = GetInputArgument(inputFiles, protocol);
+ var inputArgument = GetInputArgument(inputFile, mediaSource);
- var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
+ var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(CultureInfo.InvariantCulture);
if (maxWidth.HasValue)
{
- var maxWidthParam = maxWidth.Value.ToString(UsCulture);
+ var maxWidthParam = maxWidth.Value.ToString(CultureInfo.InvariantCulture);
- vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
+ vf += string.Format(CultureInfo.InvariantCulture, ",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
}
Directory.CreateDirectory(targetDirectory);
var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
- var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
-
- var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
- var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
-
- if (!string.IsNullOrWhiteSpace(probeSizeArgument))
- {
- args = probeSizeArgument + " " + args;
- }
-
- if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
- {
- args = analyzeDurationArgument + " " + args;
- }
-
- var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
- if (videoStream != null)
- {
- /* fix
- var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
- if (!string.IsNullOrWhiteSpace(decoder))
- {
- args = decoder + " " + args;
- }
- */
- }
+ var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet {2} -f image2 \"{1}\"", inputArgument, outputPath, vf, _threads);
if (!string.IsNullOrWhiteSpace(container))
{
- var inputFormat = encodinghelper.GetInputFormat(container);
+ var inputFormat = EncodingHelper.GetInputFormat(container);
if (!string.IsNullOrWhiteSpace(inputFormat))
{
args = "-f " + inputFormat + " " + args;
}
}
- var process = _processFactory.Create(new ProcessOptions
+ var processStartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
- FileName = FFMpegPath,
+ FileName = _ffmpegPath,
Arguments = args,
- IsHidden = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false
- });
+ };
- _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
+ _logger.LogInformation(processStartInfo.FileName + " " + processStartInfo.Arguments);
- await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
+ await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
bool ranToCompletion = false;
- using (var processWrapper = new ProcessWrapper(process, this, _logger))
+ var process = new Process
+ {
+ StartInfo = processStartInfo,
+ EnableRaisingEvents = true
+ };
+ using (var processWrapper = new ProcessWrapper(process, this))
{
try
{
@@ -840,7 +778,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
while (isResponsive)
{
- if (await process.WaitForExitAsync(30000).ConfigureAwait(false))
+ if (await process.WaitForExitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false))
{
ranToCompletion = true;
break;
@@ -848,10 +786,10 @@ namespace MediaBrowser.MediaEncoding.Encoder
cancellationToken.ThrowIfCancellationRequested();
- var jpegCount = FileSystem.GetFilePaths(targetDirectory)
+ var jpegCount = _fileSystem.GetFilePaths(targetDirectory)
.Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
- isResponsive = (jpegCount > lastCount);
+ isResponsive = jpegCount > lastCount;
lastCount = jpegCount;
}
@@ -862,18 +800,18 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
finally
{
- resourcePool.Release();
+ _thumbnailResourcePool.Release();
}
var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
if (exitCode == -1)
{
- var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
+ var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputArgument);
_logger.LogError(msg);
- throw new Exception(msg);
+ throw new FfmpegException(msg);
}
}
}
@@ -882,11 +820,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
process.Process.Start();
- lock (_runningProcesses)
+ lock (_runningProcessesLock)
{
_runningProcesses.Add(process);
}
}
+
private void StopProcess(ProcessWrapper process, int waitTimeMs)
{
try
@@ -895,18 +834,16 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
return;
}
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in WaitForExit");
- }
- try
- {
_logger.LogInformation("Killing ffmpeg process");
process.Process.Kill();
}
+ catch (InvalidOperationException)
+ {
+ // The process has already exited or
+ // there is no process associated with this Process object.
+ }
catch (Exception ex)
{
_logger.LogError(ex, "Error killing process");
@@ -916,7 +853,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
private void StopProcesses()
{
List<ProcessWrapper> proceses;
- lock (_runningProcesses)
+ lock (_runningProcessesLock)
{
proceses = _runningProcesses.ToList();
_runningProcesses.Clear();
@@ -936,15 +873,14 @@ namespace MediaBrowser.MediaEncoding.Encoder
// https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping
// We need to double escape
- return path.Replace('\\', '/').Replace(":", "\\:").Replace("'", "'\\\\\\''");
+ return path.Replace('\\', '/').Replace(":", "\\:", StringComparison.Ordinal).Replace("'", "'\\\\\\''", StringComparison.Ordinal);
}
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
+ /// <inheritdoc />
public void Dispose()
{
Dispose(true);
+ GC.SuppressFinalize(this);
}
/// <summary>
@@ -956,22 +892,93 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (dispose)
{
StopProcesses();
+ _thumbnailResourcePool.Dispose();
}
}
+ /// <inheritdoc />
public Task ConvertImage(string inputPath, string outputPath)
{
throw new NotImplementedException();
}
- public string[] GetPlayableStreamFileNames(string path, VideoType videoType)
+ /// <inheritdoc />
+ public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber)
{
- throw new NotImplementedException();
- }
+ // min size 300 mb
+ const long MinPlayableSize = 314572800;
+
+ // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
+ // Once we reach a file that is at least the minimum, return all subsequent ones
+ var allVobs = _fileSystem.GetFiles(path, true)
+ .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
+ .OrderBy(i => i.FullName)
+ .ToList();
+
+ // If we didn't find any satisfying the min length, just take them all
+ if (allVobs.Count == 0)
+ {
+ _logger.LogWarning("No vobs found in dvd structure.");
+ return Enumerable.Empty<string>();
+ }
- public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber)
- {
- throw new NotImplementedException();
+ if (titleNumber.HasValue)
+ {
+ var prefix = string.Format(
+ CultureInfo.InvariantCulture,
+ titleNumber.Value >= 10 ? "VTS_{0}_" : "VTS_0{0}_",
+ titleNumber.Value);
+ var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
+
+ if (vobs.Count > 0)
+ {
+ var minSizeVobs = vobs
+ .SkipWhile(f => f.Length < MinPlayableSize)
+ .ToList();
+
+ return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
+ }
+
+ _logger.LogWarning("Could not determine vob file list for {Path} using DvdLib. Will scan using file sizes.", path);
+ }
+
+ var files = allVobs
+ .SkipWhile(f => f.Length < MinPlayableSize)
+ .ToList();
+
+ // If we didn't find any satisfying the min length, just take them all
+ if (files.Count == 0)
+ {
+ _logger.LogWarning("Vob size filter resulted in zero matches. Taking all vobs.");
+ files = allVobs;
+ }
+
+ // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
+ if (files.Count > 0)
+ {
+ var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
+
+ if (parts.Length == 3)
+ {
+ var title = parts[1];
+
+ files = files.TakeWhile(f =>
+ {
+ var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
+
+ return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
+ }).ToList();
+
+ // If this resulted in not getting any vobs, just take them all
+ if (files.Count == 0)
+ {
+ _logger.LogWarning("Vob filename filter resulted in zero matches. Taking all vobs.");
+ files = allVobs;
+ }
+ }
+ }
+
+ return files.Select(i => i.FullName);
}
public bool CanExtractSubtitles(string codec)
@@ -982,23 +989,26 @@ namespace MediaBrowser.MediaEncoding.Encoder
private class ProcessWrapper : IDisposable
{
- public readonly IProcess Process;
- public bool HasExited;
- public int? ExitCode;
private readonly MediaEncoder _mediaEncoder;
- private readonly ILogger _logger;
- public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder, ILogger logger)
+ private bool _disposed = false;
+
+ public ProcessWrapper(Process process, MediaEncoder mediaEncoder)
{
Process = process;
_mediaEncoder = mediaEncoder;
- _logger = logger;
- Process.Exited += Process_Exited;
+ Process.Exited += OnProcessExited;
}
- void Process_Exited(object sender, EventArgs e)
+ public Process Process { get; }
+
+ public bool HasExited { get; private set; }
+
+ public int? ExitCode { get; private set; }
+
+ private void OnProcessExited(object sender, EventArgs e)
{
- var process = (IProcess)sender;
+ var process = (Process)sender;
HasExited = true;
@@ -1013,9 +1023,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
DisposeProcess(process);
}
- private void DisposeProcess(IProcess process)
+ private void DisposeProcess(Process process)
{
- lock (_mediaEncoder._runningProcesses)
+ lock (_mediaEncoder._runningProcessesLock)
{
_mediaEncoder._runningProcesses.Remove(this);
}
@@ -1029,23 +1039,18 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
}
- private bool _disposed;
- private readonly object _syncLock = new object();
public void Dispose()
{
- lock (_syncLock)
+ if (!_disposed)
{
- if (!_disposed)
+ if (Process != null)
{
- if (Process != null)
- {
- Process.Exited -= Process_Exited;
- DisposeProcess(Process);
- }
+ Process.Exited -= OnProcessExited;
+ DisposeProcess(Process);
}
-
- _disposed = true;
}
+
+ _disposed = true;
}
}
}
diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
index 68b8bd4fa..c1fd8e5fb 100644
--- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
+++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
@@ -1,8 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <ProjectGuid>{960295EE-4AF4-4440-A525-B4C295B01A61}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -10,16 +16,24 @@
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\BDInfo\BDInfo.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
- <PackageReference Include="UTF.Unknown" Version="1.0.0-beta1" />
+ <PackageReference Include="BDInfo" Version="0.7.6.1" />
+ <PackageReference Include="libse" Version="3.6.2" />
+ <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" />
+ <PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0-rc.2*" />
+ <PackageReference Include="UTF.Unknown" Version="2.5.0" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
</ItemGroup>
</Project>
diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets
deleted file mode 100644
index f793e09bc..000000000
--- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8" standalone="no"?>
-<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <Target Name="EmitMSBuildWarning" BeforeTargets="Build">
- <Warning Text="Packages containing MSBuild targets and props files cannot be fully installed in projects targeting multiple frameworks. The MSBuild targets and props files have been ignored." />
- </Target>
-</Project> \ No newline at end of file
diff --git a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs
index e4eabaf38..a9e753726 100644
--- a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs
+++ b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs
@@ -1,8 +1,12 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
namespace MediaBrowser.MediaEncoding.Probing
{
+ /// <summary>
+ /// Class containing helper methods for working with FFprobe output.
+ /// </summary>
public static class FFProbeHelpers
{
/// <summary>
@@ -16,94 +20,64 @@ namespace MediaBrowser.MediaEncoding.Probing
throw new ArgumentNullException(nameof(result));
}
- if (result.format != null && result.format.tags != null)
+ if (result.Format?.Tags != null)
{
- result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
+ result.Format.Tags = ConvertDictionaryToCaseInsensitive(result.Format.Tags);
}
- if (result.streams != null)
+ if (result.Streams != null)
{
// Convert all dictionaries to case insensitive
- foreach (var stream in result.streams)
+ foreach (var stream in result.Streams)
{
- if (stream.tags != null)
+ if (stream.Tags != null)
{
- stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
- }
-
- if (stream.disposition != null)
- {
- stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
+ stream.Tags = ConvertDictionaryToCaseInsensitive(stream.Tags);
}
}
}
}
/// <summary>
- /// Gets a string from an FFProbeResult tags dictionary
- /// </summary>
- /// <param name="tags">The tags.</param>
- /// <param name="key">The key.</param>
- /// <returns>System.String.</returns>
- public static string GetDictionaryValue(Dictionary<string, string> tags, string key)
- {
- if (tags == null)
- {
- return null;
- }
-
- tags.TryGetValue(key, out var val);
- return val;
- }
-
- /// <summary>
- /// Gets an int from an FFProbeResult tags dictionary
+ /// Gets an int from an FFProbeResult tags dictionary.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="key">The key.</param>
/// <returns>System.Nullable{System.Int32}.</returns>
- public static int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
+ public static int? GetDictionaryNumericValue(IReadOnlyDictionary<string, string> tags, string key)
{
- var val = GetDictionaryValue(tags, key);
-
- if (!string.IsNullOrEmpty(val))
+ if (tags.TryGetValue(key, out var val) && int.TryParse(val, out var i))
{
- if (int.TryParse(val, out var i))
- {
- return i;
- }
+ return i;
}
return null;
}
/// <summary>
- /// Gets a DateTime from an FFProbeResult tags dictionary
+ /// Gets a DateTime from an FFProbeResult tags dictionary.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="key">The key.</param>
/// <returns>System.Nullable{DateTime}.</returns>
- public static DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
+ public static DateTime? GetDictionaryDateTime(IReadOnlyDictionary<string, string> tags, string key)
{
- var val = GetDictionaryValue(tags, key);
-
- if (!string.IsNullOrEmpty(val))
+ if (tags.TryGetValue(key, out var val)
+ && (DateTime.TryParse(val, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var dateTime)
+ || DateTime.TryParseExact(val, "yyyy", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out dateTime)))
{
- if (DateTime.TryParse(val, out var i))
- {
- return i.ToUniversalTime();
- }
+ return dateTime;
}
return null;
}
/// <summary>
- /// Converts a dictionary to case insensitive
+ /// Converts a dictionary to case insensitive.
/// </summary>
/// <param name="dict">The dict.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
- private static Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
+ private static Dictionary<string, string> ConvertDictionaryToCaseInsensitive(IReadOnlyDictionary<string, string> dict)
{
return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
}
diff --git a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
index cc9d27608..d4d153b08 100644
--- a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
+++ b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
@@ -1,9 +1,12 @@
+#nullable disable
+
using System.Collections.Generic;
+using System.Text.Json.Serialization;
namespace MediaBrowser.MediaEncoding.Probing
{
/// <summary>
- /// Class MediaInfoResult
+ /// Class MediaInfoResult.
/// </summary>
public class InternalMediaInfoResult
{
@@ -11,331 +14,21 @@ namespace MediaBrowser.MediaEncoding.Probing
/// Gets or sets the streams.
/// </summary>
/// <value>The streams.</value>
- public MediaStreamInfo[] streams { get; set; }
+ [JsonPropertyName("streams")]
+ public IReadOnlyList<MediaStreamInfo> Streams { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>The format.</value>
- public MediaFormatInfo format { get; set; }
+ [JsonPropertyName("format")]
+ public MediaFormatInfo Format { get; set; }
/// <summary>
/// Gets or sets the chapters.
/// </summary>
/// <value>The chapters.</value>
- public MediaChapter[] Chapters { get; set; }
- }
-
- public class MediaChapter
- {
- public int id { get; set; }
- public string time_base { get; set; }
- public long start { get; set; }
- public string start_time { get; set; }
- public long end { get; set; }
- public string end_time { get; set; }
- public Dictionary<string, string> tags { get; set; }
- }
-
- /// <summary>
- /// Represents a stream within the output
- /// </summary>
- public class MediaStreamInfo
- {
- /// <summary>
- /// Gets or sets the index.
- /// </summary>
- /// <value>The index.</value>
- public int index { get; set; }
-
- /// <summary>
- /// Gets or sets the profile.
- /// </summary>
- /// <value>The profile.</value>
- public string profile { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_name.
- /// </summary>
- /// <value>The codec_name.</value>
- public string codec_name { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_long_name.
- /// </summary>
- /// <value>The codec_long_name.</value>
- public string codec_long_name { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_type.
- /// </summary>
- /// <value>The codec_type.</value>
- public string codec_type { get; set; }
-
- /// <summary>
- /// Gets or sets the sample_rate.
- /// </summary>
- /// <value>The sample_rate.</value>
- public string sample_rate { get; set; }
-
- /// <summary>
- /// Gets or sets the channels.
- /// </summary>
- /// <value>The channels.</value>
- public int channels { get; set; }
-
- /// <summary>
- /// Gets or sets the channel_layout.
- /// </summary>
- /// <value>The channel_layout.</value>
- public string channel_layout { get; set; }
-
- /// <summary>
- /// Gets or sets the avg_frame_rate.
- /// </summary>
- /// <value>The avg_frame_rate.</value>
- public string avg_frame_rate { get; set; }
-
- /// <summary>
- /// Gets or sets the duration.
- /// </summary>
- /// <value>The duration.</value>
- public string duration { get; set; }
-
- /// <summary>
- /// Gets or sets the bit_rate.
- /// </summary>
- /// <value>The bit_rate.</value>
- public string bit_rate { get; set; }
-
- /// <summary>
- /// Gets or sets the width.
- /// </summary>
- /// <value>The width.</value>
- public int width { get; set; }
-
- /// <summary>
- /// Gets or sets the refs.
- /// </summary>
- /// <value>The refs.</value>
- public int refs { get; set; }
-
- /// <summary>
- /// Gets or sets the height.
- /// </summary>
- /// <value>The height.</value>
- public int height { get; set; }
-
- /// <summary>
- /// Gets or sets the display_aspect_ratio.
- /// </summary>
- /// <value>The display_aspect_ratio.</value>
- public string display_aspect_ratio { get; set; }
-
- /// <summary>
- /// Gets or sets the tags.
- /// </summary>
- /// <value>The tags.</value>
- public Dictionary<string, string> tags { get; set; }
-
- /// <summary>
- /// Gets or sets the bits_per_sample.
- /// </summary>
- /// <value>The bits_per_sample.</value>
- public int bits_per_sample { get; set; }
-
- /// <summary>
- /// Gets or sets the bits_per_raw_sample.
- /// </summary>
- /// <value>The bits_per_raw_sample.</value>
- public int bits_per_raw_sample { get; set; }
-
- /// <summary>
- /// Gets or sets the r_frame_rate.
- /// </summary>
- /// <value>The r_frame_rate.</value>
- public string r_frame_rate { get; set; }
-
- /// <summary>
- /// Gets or sets the has_b_frames.
- /// </summary>
- /// <value>The has_b_frames.</value>
- public int has_b_frames { get; set; }
-
- /// <summary>
- /// Gets or sets the sample_aspect_ratio.
- /// </summary>
- /// <value>The sample_aspect_ratio.</value>
- public string sample_aspect_ratio { get; set; }
-
- /// <summary>
- /// Gets or sets the pix_fmt.
- /// </summary>
- /// <value>The pix_fmt.</value>
- public string pix_fmt { get; set; }
-
- /// <summary>
- /// Gets or sets the level.
- /// </summary>
- /// <value>The level.</value>
- public int level { get; set; }
-
- /// <summary>
- /// Gets or sets the time_base.
- /// </summary>
- /// <value>The time_base.</value>
- public string time_base { get; set; }
-
- /// <summary>
- /// Gets or sets the start_time.
- /// </summary>
- /// <value>The start_time.</value>
- public string start_time { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_time_base.
- /// </summary>
- /// <value>The codec_time_base.</value>
- public string codec_time_base { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_tag.
- /// </summary>
- /// <value>The codec_tag.</value>
- public string codec_tag { get; set; }
-
- /// <summary>
- /// Gets or sets the codec_tag_string.
- /// </summary>
- /// <value>The codec_tag_string.</value>
- public string codec_tag_string { get; set; }
-
- /// <summary>
- /// Gets or sets the sample_fmt.
- /// </summary>
- /// <value>The sample_fmt.</value>
- public string sample_fmt { get; set; }
-
- /// <summary>
- /// Gets or sets the dmix_mode.
- /// </summary>
- /// <value>The dmix_mode.</value>
- public string dmix_mode { get; set; }
-
- /// <summary>
- /// Gets or sets the start_pts.
- /// </summary>
- /// <value>The start_pts.</value>
- public string start_pts { get; set; }
-
- /// <summary>
- /// Gets or sets the is_avc.
- /// </summary>
- /// <value>The is_avc.</value>
- public string is_avc { get; set; }
-
- /// <summary>
- /// Gets or sets the nal_length_size.
- /// </summary>
- /// <value>The nal_length_size.</value>
- public string nal_length_size { get; set; }
-
- /// <summary>
- /// Gets or sets the ltrt_cmixlev.
- /// </summary>
- /// <value>The ltrt_cmixlev.</value>
- public string ltrt_cmixlev { get; set; }
-
- /// <summary>
- /// Gets or sets the ltrt_surmixlev.
- /// </summary>
- /// <value>The ltrt_surmixlev.</value>
- public string ltrt_surmixlev { get; set; }
-
- /// <summary>
- /// Gets or sets the loro_cmixlev.
- /// </summary>
- /// <value>The loro_cmixlev.</value>
- public string loro_cmixlev { get; set; }
-
- /// <summary>
- /// Gets or sets the loro_surmixlev.
- /// </summary>
- /// <value>The loro_surmixlev.</value>
- public string loro_surmixlev { get; set; }
-
- public string field_order { get; set; }
-
- /// <summary>
- /// Gets or sets the disposition.
- /// </summary>
- /// <value>The disposition.</value>
- public Dictionary<string, string> disposition { get; set; }
- }
-
- /// <summary>
- /// Class MediaFormat
- /// </summary>
- public class MediaFormatInfo
- {
- /// <summary>
- /// Gets or sets the filename.
- /// </summary>
- /// <value>The filename.</value>
- public string filename { get; set; }
-
- /// <summary>
- /// Gets or sets the nb_streams.
- /// </summary>
- /// <value>The nb_streams.</value>
- public int nb_streams { get; set; }
-
- /// <summary>
- /// Gets or sets the format_name.
- /// </summary>
- /// <value>The format_name.</value>
- public string format_name { get; set; }
-
- /// <summary>
- /// Gets or sets the format_long_name.
- /// </summary>
- /// <value>The format_long_name.</value>
- public string format_long_name { get; set; }
-
- /// <summary>
- /// Gets or sets the start_time.
- /// </summary>
- /// <value>The start_time.</value>
- public string start_time { get; set; }
-
- /// <summary>
- /// Gets or sets the duration.
- /// </summary>
- /// <value>The duration.</value>
- public string duration { get; set; }
-
- /// <summary>
- /// Gets or sets the size.
- /// </summary>
- /// <value>The size.</value>
- public string size { get; set; }
-
- /// <summary>
- /// Gets or sets the bit_rate.
- /// </summary>
- /// <value>The bit_rate.</value>
- public string bit_rate { get; set; }
-
- /// <summary>
- /// Gets or sets the probe_score.
- /// </summary>
- /// <value>The probe_score.</value>
- public int probe_score { get; set; }
-
- /// <summary>
- /// Gets or sets the tags.
- /// </summary>
- /// <value>The tags.</value>
- public Dictionary<string, string> tags { get; set; }
+ [JsonPropertyName("chapters")]
+ public IReadOnlyList<MediaChapter> Chapters { get; set; }
}
}
diff --git a/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs b/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs
new file mode 100644
index 000000000..a1cef7a9f
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs
@@ -0,0 +1,35 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.MediaEncoding.Probing
+{
+ /// <summary>
+ /// Class MediaChapter.
+ /// </summary>
+ public class MediaChapter
+ {
+ [JsonPropertyName("id")]
+ public int Id { get; set; }
+
+ [JsonPropertyName("time_base")]
+ public string TimeBase { get; set; }
+
+ [JsonPropertyName("start")]
+ public long Start { get; set; }
+
+ [JsonPropertyName("start_time")]
+ public string StartTime { get; set; }
+
+ [JsonPropertyName("end")]
+ public long End { get; set; }
+
+ [JsonPropertyName("end_time")]
+ public string EndTime { get; set; }
+
+ [JsonPropertyName("tags")]
+ public IReadOnlyDictionary<string, string> Tags { get; set; }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs
new file mode 100644
index 000000000..d50da37b8
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs
@@ -0,0 +1,83 @@
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.MediaEncoding.Probing
+{
+ /// <summary>
+ /// Class MediaFormat.
+ /// </summary>
+ public class MediaFormatInfo
+ {
+ /// <summary>
+ /// Gets or sets the filename.
+ /// </summary>
+ /// <value>The filename.</value>
+ [JsonPropertyName("filename")]
+ public string FileName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the nb_streams.
+ /// </summary>
+ /// <value>The nb_streams.</value>
+ [JsonPropertyName("nb_streams")]
+ public int NbStreams { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format_name.
+ /// </summary>
+ /// <value>The format_name.</value>
+ [JsonPropertyName("format_name")]
+ public string FormatName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format_long_name.
+ /// </summary>
+ /// <value>The format_long_name.</value>
+ [JsonPropertyName("format_long_name")]
+ public string FormatLongName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start_time.
+ /// </summary>
+ /// <value>The start_time.</value>
+ [JsonPropertyName("start_time")]
+ public string StartTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the duration.
+ /// </summary>
+ /// <value>The duration.</value>
+ [JsonPropertyName("duration")]
+ public string Duration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the size.
+ /// </summary>
+ /// <value>The size.</value>
+ [JsonPropertyName("size")]
+ public string Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the bit_rate.
+ /// </summary>
+ /// <value>The bit_rate.</value>
+ [JsonPropertyName("bit_rate")]
+ public string BitRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the probe_score.
+ /// </summary>
+ /// <value>The probe_score.</value>
+ [JsonPropertyName("probe_score")]
+ public int ProbeScore { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tags.
+ /// </summary>
+ /// <value>The tags.</value>
+ [JsonPropertyName("tags")]
+ public IReadOnlyDictionary<string, string> Tags { get; set; }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs
new file mode 100644
index 000000000..c9c8c34c2
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs
@@ -0,0 +1,314 @@
+#nullable disable
+
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.MediaEncoding.Probing
+{
+ /// <summary>
+ /// Represents a stream within the output.
+ /// </summary>
+ public class MediaStreamInfo
+ {
+ /// <summary>
+ /// Gets or sets the index.
+ /// </summary>
+ /// <value>The index.</value>
+ [JsonPropertyName("index")]
+ public int Index { get; set; }
+
+ /// <summary>
+ /// Gets or sets the profile.
+ /// </summary>
+ /// <value>The profile.</value>
+ [JsonPropertyName("profile")]
+ public string Profile { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_name.
+ /// </summary>
+ /// <value>The codec_name.</value>
+ [JsonPropertyName("codec_name")]
+ public string CodecName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_long_name.
+ /// </summary>
+ /// <value>The codec_long_name.</value>
+ [JsonPropertyName("codec_long_name")]
+ public string CodecLongName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_type.
+ /// </summary>
+ /// <value>The codec_type.</value>
+ [JsonPropertyName("codec_type")]
+ public string CodecType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sample_rate.
+ /// </summary>
+ /// <value>The sample_rate.</value>
+ [JsonPropertyName("sample_rate")]
+ public string SampleRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the channels.
+ /// </summary>
+ /// <value>The channels.</value>
+ [JsonPropertyName("channels")]
+ public int Channels { get; set; }
+
+ /// <summary>
+ /// Gets or sets the channel_layout.
+ /// </summary>
+ /// <value>The channel_layout.</value>
+ [JsonPropertyName("channel_layout")]
+ public string ChannelLayout { get; set; }
+
+ /// <summary>
+ /// Gets or sets the avg_frame_rate.
+ /// </summary>
+ /// <value>The avg_frame_rate.</value>
+ [JsonPropertyName("avg_frame_rate")]
+ public string AverageFrameRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the duration.
+ /// </summary>
+ /// <value>The duration.</value>
+ [JsonPropertyName("duration")]
+ public string Duration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the bit_rate.
+ /// </summary>
+ /// <value>The bit_rate.</value>
+ [JsonPropertyName("bit_rate")]
+ public string BitRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the width.
+ /// </summary>
+ /// <value>The width.</value>
+ [JsonPropertyName("width")]
+ public int Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets the refs.
+ /// </summary>
+ /// <value>The refs.</value>
+ [JsonPropertyName("refs")]
+ public int Refs { get; set; }
+
+ /// <summary>
+ /// Gets or sets the height.
+ /// </summary>
+ /// <value>The height.</value>
+ [JsonPropertyName("height")]
+ public int Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets the display_aspect_ratio.
+ /// </summary>
+ /// <value>The display_aspect_ratio.</value>
+ [JsonPropertyName("display_aspect_ratio")]
+ public string DisplayAspectRatio { get; set; }
+
+ /// <summary>
+ /// Gets or sets the tags.
+ /// </summary>
+ /// <value>The tags.</value>
+ [JsonPropertyName("tags")]
+ public IReadOnlyDictionary<string, string> Tags { get; set; }
+
+ /// <summary>
+ /// Gets or sets the bits_per_sample.
+ /// </summary>
+ /// <value>The bits_per_sample.</value>
+ [JsonPropertyName("bits_per_sample")]
+ public int BitsPerSample { get; set; }
+
+ /// <summary>
+ /// Gets or sets the bits_per_raw_sample.
+ /// </summary>
+ /// <value>The bits_per_raw_sample.</value>
+ [JsonPropertyName("bits_per_raw_sample")]
+ public int BitsPerRawSample { get; set; }
+
+ /// <summary>
+ /// Gets or sets the r_frame_rate.
+ /// </summary>
+ /// <value>The r_frame_rate.</value>
+ [JsonPropertyName("r_frame_rate")]
+ public string RFrameRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the has_b_frames.
+ /// </summary>
+ /// <value>The has_b_frames.</value>
+ [JsonPropertyName("has_b_frames")]
+ public int HasBFrames { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sample_aspect_ratio.
+ /// </summary>
+ /// <value>The sample_aspect_ratio.</value>
+ [JsonPropertyName("sample_aspect_ratio")]
+ public string SampleAspectRatio { get; set; }
+
+ /// <summary>
+ /// Gets or sets the pix_fmt.
+ /// </summary>
+ /// <value>The pix_fmt.</value>
+ [JsonPropertyName("pix_fmt")]
+ public string PixelFormat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the level.
+ /// </summary>
+ /// <value>The level.</value>
+ [JsonPropertyName("level")]
+ public int Level { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time_base.
+ /// </summary>
+ /// <value>The time_base.</value>
+ [JsonPropertyName("time_base")]
+ public string TimeBase { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start_time.
+ /// </summary>
+ /// <value>The start_time.</value>
+ [JsonPropertyName("start_time")]
+ public string StartTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_time_base.
+ /// </summary>
+ /// <value>The codec_time_base.</value>
+ [JsonPropertyName("codec_time_base")]
+ public string CodecTimeBase { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_tag.
+ /// </summary>
+ /// <value>The codec_tag.</value>
+ [JsonPropertyName("codec_tag")]
+ public string CodecTag { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec_tag_string.
+ /// </summary>
+ /// <value>The codec_tag_string.</value>
+ [JsonPropertyName("codec_tag_string")]
+ public string CodecTagString { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sample_fmt.
+ /// </summary>
+ /// <value>The sample_fmt.</value>
+ [JsonPropertyName("sample_fmt")]
+ public string SampleFmt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the dmix_mode.
+ /// </summary>
+ /// <value>The dmix_mode.</value>
+ [JsonPropertyName("dmix_mode")]
+ public string DmixMode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start_pts.
+ /// </summary>
+ /// <value>The start_pts.</value>
+ [JsonPropertyName("start_pts")]
+ public long StartPts { get; set; }
+
+ /// <summary>
+ /// Gets or sets the is_avc.
+ /// </summary>
+ /// <value>The is_avc.</value>
+ [JsonPropertyName("is_avc")]
+ public string IsAvc { get; set; }
+
+ /// <summary>
+ /// Gets or sets the nal_length_size.
+ /// </summary>
+ /// <value>The nal_length_size.</value>
+ [JsonPropertyName("nal_length_size")]
+ public string NalLengthSize { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ltrt_cmixlev.
+ /// </summary>
+ /// <value>The ltrt_cmixlev.</value>
+ [JsonPropertyName("ltrt_cmixlev")]
+ public string LtrtCmixlev { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ltrt_surmixlev.
+ /// </summary>
+ /// <value>The ltrt_surmixlev.</value>
+ [JsonPropertyName("ltrt_surmixlev")]
+ public string LtrtSurmixlev { get; set; }
+
+ /// <summary>
+ /// Gets or sets the loro_cmixlev.
+ /// </summary>
+ /// <value>The loro_cmixlev.</value>
+ [JsonPropertyName("loro_cmixlev")]
+ public string LoroCmixlev { get; set; }
+
+ /// <summary>
+ /// Gets or sets the loro_surmixlev.
+ /// </summary>
+ /// <value>The loro_surmixlev.</value>
+ [JsonPropertyName("loro_surmixlev")]
+ public string LoroSurmixlev { get; set; }
+
+ /// <summary>
+ /// Gets or sets the field_order.
+ /// </summary>
+ /// <value>The field_order.</value>
+ [JsonPropertyName("field_order")]
+ public string FieldOrder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the disposition.
+ /// </summary>
+ /// <value>The disposition.</value>
+ [JsonPropertyName("disposition")]
+ public IReadOnlyDictionary<string, int> Disposition { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color range.
+ /// </summary>
+ /// <value>The color range.</value>
+ [JsonPropertyName("color_range")]
+ public string ColorRange { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color space.
+ /// </summary>
+ /// <value>The color space.</value>
+ [JsonPropertyName("color_space")]
+ public string ColorSpace { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color transfer.
+ /// </summary>
+ /// <value>The color transfer.</value>
+ [JsonPropertyName("color_transfer")]
+ public string ColorTransfer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color primaries.
+ /// </summary>
+ /// <value>The color primaries.</value>
+ [JsonPropertyName("color_primaries")]
+ public string ColorPrimaries { get; set; }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 5099ccb2a..9279cb220 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -1,15 +1,19 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
+using System.Text.RegularExpressions;
using System.Xml;
+using Jellyfin.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
@@ -17,42 +21,69 @@ namespace MediaBrowser.MediaEncoding.Probing
{
public class ProbeResultNormalizer
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+ // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
+ private const int MaxSubtitleDescriptionExtractionLength = 100;
+
+ private const string ArtistReplaceValue = " | ";
+
+ private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
+
+ private static readonly Regex _performerPattern = new (@"(?<name>.*) \((?<instrument>.*)\)");
+
private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+
+ private string[] _splitWhiteList;
- public ProbeResultNormalizer(ILogger logger, IFileSystem fileSystem)
+ public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
{
_logger = logger;
- _fileSystem = fileSystem;
+ _localization = localization;
}
+ private IReadOnlyList<string> SplitWhitelist => _splitWhiteList ??= new string[]
+ {
+ "AC/DC",
+ "Au/Ra",
+ "이달의 소녀 1/3",
+ "LOONA 1/3",
+ "LOONA / yyxy",
+ "LOONA / ODD EYE CIRCLE",
+ "K/DA",
+ "22/7"
+ };
+
public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, MediaProtocol protocol)
{
var info = new MediaInfo
{
Path = path,
- Protocol = protocol
+ Protocol = protocol,
+ VideoType = videoType
};
FFProbeHelpers.NormalizeFFProbeResult(data);
SetSize(data, info);
- var internalStreams = data.streams ?? new MediaStreamInfo[] { };
+ var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
- info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.format))
+ info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format))
.Where(i => i != 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))
.ToList();
- if (data.format != null)
+ info.MediaAttachments = internalStreams.Select(GetMediaAttachment)
+ .Where(i => i != null)
+ .ToList();
+
+ if (data.Format != null)
{
- info.Container = NormalizeFormat(data.format.format_name);
+ info.Container = NormalizeFormat(data.Format.FormatName);
- if (!string.IsNullOrEmpty(data.format.bit_rate))
+ if (!string.IsNullOrEmpty(data.Format.BitRate))
{
- if (int.TryParse(data.format.bit_rate, NumberStyles.Any, _usCulture, out var value))
+ if (int.TryParse(data.Format.BitRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
info.Bitrate = value;
}
@@ -62,58 +93,66 @@ namespace MediaBrowser.MediaEncoding.Probing
var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var tagStreamType = isAudio ? "audio" : "video";
- if (data.streams != null)
- {
- var tagStream = data.streams.FirstOrDefault(i => string.Equals(i.codec_type, tagStreamType, StringComparison.OrdinalIgnoreCase));
+ var tagStream = data.Streams?.FirstOrDefault(i => string.Equals(i.CodecType, tagStreamType, StringComparison.OrdinalIgnoreCase));
- if (tagStream != null && tagStream.tags != null)
+ if (tagStream?.Tags != null)
+ {
+ foreach (var (key, value) in tagStream.Tags)
{
- foreach (var pair in tagStream.tags)
- {
- tags[pair.Key] = pair.Value;
- }
+ tags[key] = value;
}
}
- if (data.format != null && data.format.tags != null)
+ if (data.Format?.Tags != null)
{
- foreach (var pair in data.format.tags)
+ foreach (var (key, value) in data.Format.Tags)
{
- tags[pair.Key] = pair.Value;
+ tags[key] = value;
}
}
FetchGenres(info, tags);
- var overview = FFProbeHelpers.GetDictionaryValue(tags, "synopsis");
- if (string.IsNullOrWhiteSpace(overview))
- {
- overview = FFProbeHelpers.GetDictionaryValue(tags, "description");
- }
- if (string.IsNullOrWhiteSpace(overview))
+ info.Name = tags.GetFirstNotNullNorWhiteSpaceValue("title", "title-eng");
+ info.ForcedSortName = tags.GetFirstNotNullNorWhiteSpaceValue("sort_name", "title-sort", "titlesort");
+ info.Overview = tags.GetFirstNotNullNorWhiteSpaceValue("synopsis", "description", "desc");
+
+ info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
+ info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
+ info.ShowName = tags.GetValueOrDefault("show_name");
+ info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
+
+ // Several different forms of retail/premiere date
+ info.PremiereDate =
+ FFProbeHelpers.GetDictionaryDateTime(tags, "originaldate") ??
+ FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
+ FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
+ FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
+ FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ??
+ FFProbeHelpers.GetDictionaryDateTime(tags, "date");
+
+ // Set common metadata for music (audio) and music videos (video)
+ info.Album = tags.GetValueOrDefault("album");
+
+ if (tags.TryGetValue("artists", out var artists) && !string.IsNullOrWhiteSpace(artists))
{
- overview = FFProbeHelpers.GetDictionaryValue(tags, "desc");
+ info.Artists = SplitDistinctArtists(artists, new[] { '/', ';' }, false).ToArray();
}
-
- if (!string.IsNullOrWhiteSpace(overview))
+ else
{
- info.Overview = overview;
+ var artist = tags.GetFirstNotNullNorWhiteSpaceValue("artist");
+ info.Artists = artist == null
+ ? Array.Empty<string>()
+ : SplitDistinctArtists(artist, _nameDelimiters, true).ToArray();
}
- var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
- if (!string.IsNullOrWhiteSpace(title))
+ // Guess ProductionYear from PremiereDate if missing
+ if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue)
{
- info.Name = title;
+ info.ProductionYear = info.PremiereDate.Value.Year;
}
- info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
-
- // Several different forms of retaildate
- info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
- FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
- FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
- FFProbeHelpers.GetDictionaryDateTime(tags, "date");
-
+ // Set mediaType-specific metadata
if (isAudio)
{
SetAudioRuntimeTicks(data, info);
@@ -127,10 +166,10 @@ namespace MediaBrowser.MediaEncoding.Probing
{
FetchStudios(info, tags, "copyright");
- var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
- if (!string.IsNullOrWhiteSpace(iTunEXTC))
+ var iTunExtc = tags.GetFirstNotNullNorWhiteSpaceValue("iTunEXTC");
+ if (iTunExtc != null)
{
- var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = iTunExtc.Split('|', StringSplitOptions.RemoveEmptyEntries);
// Example
// mpaa|G|100|For crude humor
if (parts.Length > 1)
@@ -144,15 +183,15 @@ namespace MediaBrowser.MediaEncoding.Probing
}
}
- var itunesXml = FFProbeHelpers.GetDictionaryValue(tags, "iTunMOVI");
- if (!string.IsNullOrWhiteSpace(itunesXml))
+ var iTunXml = tags.GetFirstNotNullNorWhiteSpaceValue("iTunMOVI");
+ if (iTunXml != null)
{
- FetchFromItunesInfo(itunesXml, info);
+ FetchFromItunesInfo(iTunXml, info);
}
- if (data.format != null && !string.IsNullOrEmpty(data.format.duration))
+ if (data.Format != null && !string.IsNullOrEmpty(data.Format.Duration))
{
- info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
+ info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, CultureInfo.InvariantCulture)).Ticks;
}
FetchWtvInfo(info, data);
@@ -164,8 +203,7 @@ namespace MediaBrowser.MediaEncoding.Probing
ExtractTimestamp(info);
- var stereoMode = GetDictionaryValue(tags, "stereo_mode");
- if (string.Equals(stereoMode, "left_right", StringComparison.OrdinalIgnoreCase))
+ if (tags.TryGetValue("stereo_mode", out var stereoMode) && string.Equals(stereoMode, "left_right", StringComparison.OrdinalIgnoreCase))
{
info.Video3DFormat = Video3DFormat.FullSideBySide;
}
@@ -215,17 +253,39 @@ namespace MediaBrowser.MediaEncoding.Probing
var channelsValue = channels.Value;
- if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
+ {
+ switch (channelsValue)
+ {
+ case <= 2:
+ return 192000;
+ case >= 5:
+ return 320000;
+ }
+ }
+
+ if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
{
- if (channelsValue <= 2)
+ switch (channelsValue)
{
- return 192000;
+ case <= 2:
+ return 192000;
+ case >= 5:
+ return 640000;
}
+ }
- if (channelsValue >= 5)
+ if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase))
+ {
+ switch (channelsValue)
{
- return 320000;
+ case <= 2:
+ return 960000;
+ case >= 5:
+ return 2880000;
}
}
@@ -246,52 +306,51 @@ namespace MediaBrowser.MediaEncoding.Probing
// <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>cast</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Blender Foundation</string>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Janus Bager Kristensen</string>\n\t\t</dict>\n\t</array>\n\t<key>directors</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Sacha Goedegebure</string>\n\t\t</dict>\n\t</array>\n\t<key>studio</key>\n\t<string>Blender Foundation</string>\n</dict>\n</plist>\n
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
+ using (var streamReader = new StreamReader(stream))
{
- using (var streamReader = new StreamReader(stream))
+ try
{
- try
+ using (var reader = XmlReader.Create(streamReader))
{
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(streamReader))
- {
- reader.MoveToContent();
- reader.Read();
+ reader.MoveToContent();
+ reader.Read();
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
{
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "dict":
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- using (var subtree = reader.ReadSubtree())
- {
- ReadFromDictNode(subtree, info);
- }
- break;
- default:
- reader.Skip();
- break;
- }
- }
- else
+ switch (reader.Name)
{
- reader.Read();
+ case "dict":
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ continue;
+ }
+
+ using (var subtree = reader.ReadSubtree())
+ {
+ ReadFromDictNode(subtree, info);
+ }
+
+ break;
+ default:
+ reader.Skip();
+ break;
}
}
+ else
+ {
+ reader.Read();
+ }
}
}
- catch (XmlException)
- {
- // I've seen probe examples where the iTunMOVI value is just "<"
- // So we should not allow this to fail the entire probing operation
- }
+ }
+ catch (XmlException)
+ {
+ // I've seen probe examples where the iTunMOVI value is just "<"
+ // So we should not allow this to fail the entire probing operation
}
}
}
@@ -316,6 +375,7 @@ namespace MediaBrowser.MediaEncoding.Probing
{
ProcessPairs(currentKey, pairs, info);
}
+
currentKey = reader.ReadElementContentAsString();
pairs = new List<NameValuePair>();
break;
@@ -329,6 +389,7 @@ namespace MediaBrowser.MediaEncoding.Probing
Value = value
});
}
+
break;
case "array":
if (reader.IsEmptyElement)
@@ -336,6 +397,7 @@ namespace MediaBrowser.MediaEncoding.Probing
reader.Read();
continue;
}
+
using (var subtree = reader.ReadSubtree())
{
if (!string.IsNullOrWhiteSpace(currentKey))
@@ -343,6 +405,7 @@ namespace MediaBrowser.MediaEncoding.Probing
pairs.AddRange(ReadValueArray(subtree));
}
}
+
break;
default:
reader.Skip();
@@ -358,7 +421,6 @@ namespace MediaBrowser.MediaEncoding.Probing
private List<NameValuePair> ReadValueArray(XmlReader reader)
{
-
var pairs = new List<NameValuePair>();
reader.MoveToContent();
@@ -378,6 +440,7 @@ namespace MediaBrowser.MediaEncoding.Probing
reader.Read();
continue;
}
+
using (var subtree = reader.ReadSubtree())
{
var dict = GetNameValuePair(subtree);
@@ -386,6 +449,7 @@ namespace MediaBrowser.MediaEncoding.Probing
pairs.Add(dict);
}
}
+
break;
default:
reader.Skip();
@@ -410,7 +474,6 @@ namespace MediaBrowser.MediaEncoding.Probing
.Where(i => !string.IsNullOrWhiteSpace(i))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
-
}
else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
{
@@ -422,7 +485,6 @@ namespace MediaBrowser.MediaEncoding.Probing
Type = PersonType.Writer
});
}
-
}
else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
{
@@ -514,7 +576,41 @@ namespace MediaBrowser.MediaEncoding.Probing
}
/// <summary>
- /// Converts ffprobe stream info to our MediaStream class
+ /// Converts ffprobe stream info to our MediaAttachment class.
+ /// </summary>
+ /// <param name="streamInfo">The stream info.</param>
+ /// <returns>MediaAttachments.</returns>
+ private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
+ {
+ if (!string.Equals(streamInfo.CodecType, "attachment", StringComparison.OrdinalIgnoreCase)
+ && streamInfo.Disposition?.GetValueOrDefault("attached_pic") != 1)
+ {
+ return null;
+ }
+
+ var attachment = new MediaAttachment
+ {
+ Codec = streamInfo.CodecName,
+ Index = streamInfo.Index
+ };
+
+ if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
+ {
+ attachment.CodecTag = streamInfo.CodecTagString;
+ }
+
+ if (streamInfo.Tags != null)
+ {
+ attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
+ attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
+ attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
+ }
+
+ return attachment;
+ }
+
+ /// <summary>
+ /// Converts ffprobe stream info to our MediaStream class.
/// </summary>
/// <param name="isAudio">if set to <c>true</c> [is info].</param>
/// <param name="streamInfo">The stream info.</param>
@@ -523,91 +619,114 @@ namespace MediaBrowser.MediaEncoding.Probing
private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
{
// These are mp4 chapters
- if (string.Equals(streamInfo.codec_name, "mov_text", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
{
// Edit: but these are also sometimes subtitles?
- //return null;
+ // return null;
}
var stream = new MediaStream
{
- Codec = streamInfo.codec_name,
- Profile = streamInfo.profile,
- Level = streamInfo.level,
- Index = streamInfo.index,
- PixelFormat = streamInfo.pix_fmt,
- NalLengthSize = streamInfo.nal_length_size,
- TimeBase = streamInfo.time_base,
- CodecTimeBase = streamInfo.codec_time_base
+ Codec = streamInfo.CodecName,
+ Profile = streamInfo.Profile,
+ Level = streamInfo.Level,
+ Index = streamInfo.Index,
+ PixelFormat = streamInfo.PixelFormat,
+ NalLengthSize = streamInfo.NalLengthSize,
+ TimeBase = streamInfo.TimeBase,
+ CodecTimeBase = streamInfo.CodecTimeBase
};
- if (string.Equals(streamInfo.is_avc, "true", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(streamInfo.is_avc, "1", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(streamInfo.IsAvc, "true", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(streamInfo.IsAvc, "1", StringComparison.OrdinalIgnoreCase))
{
stream.IsAVC = true;
}
- else if (string.Equals(streamInfo.is_avc, "false", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(streamInfo.is_avc, "0", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(streamInfo.IsAvc, "false", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(streamInfo.IsAvc, "0", StringComparison.OrdinalIgnoreCase))
{
stream.IsAVC = false;
}
- if (!string.IsNullOrWhiteSpace(streamInfo.field_order) && !string.Equals(streamInfo.field_order, "progressive", StringComparison.OrdinalIgnoreCase))
+ if (!string.IsNullOrWhiteSpace(streamInfo.FieldOrder) && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase))
{
stream.IsInterlaced = true;
}
// Filter out junk
- if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
+ if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", StringComparison.OrdinalIgnoreCase))
{
- stream.CodecTag = streamInfo.codec_tag_string;
+ stream.CodecTag = streamInfo.CodecTagString;
}
- if (streamInfo.tags != null)
+ if (streamInfo.Tags != null)
{
- stream.Language = GetDictionaryValue(streamInfo.tags, "language");
- stream.Comment = GetDictionaryValue(streamInfo.tags, "comment");
- stream.Title = GetDictionaryValue(streamInfo.tags, "title");
+ stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
+ stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
+ stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
}
- if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase))
{
stream.Type = MediaStreamType.Audio;
- stream.Channels = streamInfo.channels;
+ stream.Channels = streamInfo.Channels;
- if (!string.IsNullOrEmpty(streamInfo.sample_rate))
+ if (!string.IsNullOrEmpty(streamInfo.SampleRate))
{
- if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out var value))
+ if (int.TryParse(streamInfo.SampleRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
stream.SampleRate = value;
}
}
- stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
+ stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
- if (streamInfo.bits_per_sample > 0)
+ if (streamInfo.BitsPerSample > 0)
+ {
+ stream.BitDepth = streamInfo.BitsPerSample;
+ }
+ else if (streamInfo.BitsPerRawSample > 0)
{
- stream.BitDepth = streamInfo.bits_per_sample;
+ stream.BitDepth = streamInfo.BitsPerRawSample;
}
- else if (streamInfo.bits_per_raw_sample > 0)
+
+ if (string.IsNullOrEmpty(stream.Title))
{
- stream.BitDepth = streamInfo.bits_per_raw_sample;
+ // mp4 missing track title workaround: fall back to handler_name if populated
+ string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
+ if (!string.IsNullOrEmpty(handlerName))
+ {
+ stream.Title = handlerName;
+ }
}
}
- else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(streamInfo.CodecType, "subtitle", StringComparison.OrdinalIgnoreCase))
{
stream.Type = MediaStreamType.Subtitle;
stream.Codec = NormalizeSubtitleCodec(stream.Codec);
+ stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
+ stream.LocalizedDefault = _localization.GetLocalizedString("Default");
+ stream.LocalizedForced = _localization.GetLocalizedString("Forced");
+
+ if (string.IsNullOrEmpty(stream.Title))
+ {
+ // mp4 missing track title workaround: fall back to handler_name if populated and not the default "SubtitleHandler"
+ string handlerName = GetDictionaryValue(streamInfo.Tags, "handler_name");
+ if (!string.IsNullOrEmpty(handlerName) && !string.Equals(handlerName, "SubtitleHandler", StringComparison.OrdinalIgnoreCase))
+ {
+ stream.Title = handlerName;
+ }
+ }
}
- else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))
{
stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
? MediaStreamType.EmbeddedImage
: MediaStreamType.Video;
- stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
- stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
+ stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
+ stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
@@ -632,29 +751,66 @@ namespace MediaBrowser.MediaEncoding.Probing
stream.Type = MediaStreamType.Video;
}
- stream.Width = streamInfo.width;
- stream.Height = streamInfo.height;
+ stream.Width = streamInfo.Width;
+ stream.Height = streamInfo.Height;
stream.AspectRatio = GetAspectRatio(streamInfo);
- if (streamInfo.bits_per_sample > 0)
+ if (streamInfo.BitsPerSample > 0)
{
- stream.BitDepth = streamInfo.bits_per_sample;
+ stream.BitDepth = streamInfo.BitsPerSample;
}
- else if (streamInfo.bits_per_raw_sample > 0)
+ else if (streamInfo.BitsPerRawSample > 0)
{
- stream.BitDepth = streamInfo.bits_per_raw_sample;
+ stream.BitDepth = streamInfo.BitsPerRawSample;
}
- //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
+ if (!stream.BitDepth.HasValue)
+ {
+ if (!string.IsNullOrEmpty(streamInfo.PixelFormat)
+ && streamInfo.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase))
+ {
+ stream.BitDepth = 10;
+ }
+
+ if (!string.IsNullOrEmpty(streamInfo.Profile)
+ && (streamInfo.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
+ || streamInfo.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
+ || streamInfo.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase)))
+ {
+ stream.BitDepth = 10;
+ }
+ }
+
+ // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
// string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
// string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
// http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
- stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
+ stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase);
+
+ if (streamInfo.Refs > 0)
+ {
+ stream.RefFrames = streamInfo.Refs;
+ }
- if (streamInfo.refs > 0)
+ if (!string.IsNullOrEmpty(streamInfo.ColorRange))
{
- stream.RefFrames = streamInfo.refs;
+ stream.ColorRange = streamInfo.ColorRange;
+ }
+
+ if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
+ {
+ stream.ColorSpace = streamInfo.ColorSpace;
+ }
+
+ if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
+ {
+ stream.ColorTransfer = streamInfo.ColorTransfer;
+ }
+
+ if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
+ {
+ stream.ColorPrimaries = streamInfo.ColorPrimaries;
}
}
else
@@ -665,18 +821,22 @@ namespace MediaBrowser.MediaEncoding.Probing
// Get stream bitrate
var bitrate = 0;
- if (!string.IsNullOrEmpty(streamInfo.bit_rate))
+ if (!string.IsNullOrEmpty(streamInfo.BitRate))
{
- if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out var value))
+ if (int.TryParse(streamInfo.BitRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
bitrate = value;
}
}
- if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
+ // The bitrate info of FLAC musics and some videos is included in formatInfo.
+ if (bitrate == 0
+ && formatInfo != null
+ && !string.IsNullOrEmpty(formatInfo.BitRate)
+ && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio)))
{
// If the stream info doesn't have a bitrate get the value from the media format info
- if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out var value))
+ if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
bitrate = value;
}
@@ -687,14 +847,47 @@ namespace MediaBrowser.MediaEncoding.Probing
stream.BitRate = bitrate;
}
- if (streamInfo.disposition != null)
+ // Extract bitrate info from tag "BPS" if possible.
+ if (!stream.BitRate.HasValue
+ && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
+ {
+ var bps = GetBPSFromTags(streamInfo);
+ if (bps > 0)
+ {
+ stream.BitRate = bps;
+ }
+ }
+
+ // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
+ if (!stream.BitRate.HasValue
+ && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)))
{
- var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
- var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
+ var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
+ var bytes = GetNumberOfBytesFromTags(streamInfo);
+ if (durationInSeconds != null && bytes != null)
+ {
+ var bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
+ if (bps > 0)
+ {
+ stream.BitRate = bps;
+ }
+ }
+ }
- stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
+ var disposition = streamInfo.Disposition;
+ if (disposition != null)
+ {
+ if (disposition.GetValueOrDefault("default") == 1)
+ {
+ stream.IsDefault = true;
+ }
- stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
+ if (disposition.GetValueOrDefault("forced") == 1)
+ {
+ stream.IsForced = true;
+ }
}
NormalizeStreamTitle(stream);
@@ -716,12 +909,12 @@ namespace MediaBrowser.MediaEncoding.Probing
}
/// <summary>
- /// Gets a string from an FFProbeResult tags dictionary
+ /// Gets a string from an FFProbeResult tags dictionary.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="key">The key.</param>
/// <returns>System.String.</returns>
- private string GetDictionaryValue(Dictionary<string, string> tags, string key)
+ private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
{
if (tags == null)
{
@@ -729,6 +922,7 @@ namespace MediaBrowser.MediaEncoding.Probing
}
tags.TryGetValue(key, out var val);
+
return val;
}
@@ -736,7 +930,7 @@ namespace MediaBrowser.MediaEncoding.Probing
{
if (string.IsNullOrEmpty(input))
{
- return input;
+ return null;
}
return input.Split('(').FirstOrDefault();
@@ -744,17 +938,17 @@ namespace MediaBrowser.MediaEncoding.Probing
private string GetAspectRatio(MediaStreamInfo info)
{
- var original = info.display_aspect_ratio;
+ var original = info.DisplayAspectRatio;
var parts = (original ?? string.Empty).Split(':');
if (!(parts.Length == 2 &&
- int.TryParse(parts[0], NumberStyles.Any, _usCulture, out var width) &&
- int.TryParse(parts[1], NumberStyles.Any, _usCulture, out var height) &&
+ int.TryParse(parts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out var width) &&
+ int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out var height) &&
width > 0 &&
height > 0))
{
- width = info.width;
- height = info.height;
+ width = info.Width;
+ height = info.Height;
}
if (width > 0 && height > 0)
@@ -824,176 +1018,219 @@ namespace MediaBrowser.MediaEncoding.Probing
/// <returns>System.Nullable{System.Single}.</returns>
private float? GetFrameRate(string value)
{
- if (!string.IsNullOrEmpty(value))
+ if (string.IsNullOrEmpty(value))
{
- var parts = value.Split('/');
+ return null;
+ }
- float result;
+ var parts = value.Split('/');
- if (parts.Length == 2)
- {
- result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
- }
- else
- {
- result = float.Parse(parts[0], _usCulture);
- }
+ float result;
- return float.IsNaN(result) ? (float?)null : result;
+ if (parts.Length == 2)
+ {
+ result = float.Parse(parts[0], CultureInfo.InvariantCulture) / float.Parse(parts[1], CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ result = float.Parse(parts[0], CultureInfo.InvariantCulture);
}
- return null;
+ return float.IsNaN(result) ? null : result;
}
private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
{
- if (result.streams != null)
+ // Get the first info stream
+ var stream = result.Streams?.FirstOrDefault(s => string.Equals(s.CodecType, "audio", StringComparison.OrdinalIgnoreCase));
+ if (stream == null)
{
- // Get the first info stream
- var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
+ return;
+ }
- if (stream != null)
- {
- // Get duration from stream properties
- var duration = stream.duration;
+ // Get duration from stream properties
+ var duration = stream.Duration;
- // If it's not there go into format properties
- if (string.IsNullOrEmpty(duration))
- {
- duration = result.format.duration;
- }
+ // If it's not there go into format properties
+ if (string.IsNullOrEmpty(duration))
+ {
+ duration = result.Format.Duration;
+ }
- // If we got something, parse it
- if (!string.IsNullOrEmpty(duration))
- {
- data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
- }
- }
+ // If we got something, parse it
+ if (!string.IsNullOrEmpty(duration))
+ {
+ data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, CultureInfo.InvariantCulture)).Ticks;
}
}
- private void SetSize(InternalMediaInfoResult data, MediaInfo info)
+ private int? GetBPSFromTags(MediaStreamInfo streamInfo)
{
- if (data.format != null)
+ if (streamInfo?.Tags == null)
{
- if (!string.IsNullOrEmpty(data.format.size))
- {
- info.Size = long.Parse(data.format.size, _usCulture);
- }
- else
- {
- info.Size = null;
- }
+ return null;
+ }
+
+ var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS");
+ if (!string.IsNullOrEmpty(bps)
+ && int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps))
+ {
+ return parsedBps;
}
+
+ return null;
}
- private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
+ private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo)
{
- var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
- if (!string.IsNullOrWhiteSpace(composer))
+ if (streamInfo?.Tags == null)
{
- var peoples = new List<BaseItemPerson>();
- foreach (var person in Split(composer, false))
- {
- peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
- }
- audio.People = peoples.ToArray();
+ return null;
}
- //var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
- //if (!string.IsNullOrWhiteSpace(conductor))
- //{
- // foreach (var person in Split(conductor, false))
- // {
- // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
- // }
- //}
+ var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION");
+ if (!string.IsNullOrEmpty(duration) && TimeSpan.TryParse(duration, out var parsedDuration))
+ {
+ return parsedDuration.TotalSeconds;
+ }
- //var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
- //if (!string.IsNullOrWhiteSpace(lyricist))
- //{
- // foreach (var person in Split(lyricist, false))
- // {
- // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
- // }
- //}
+ return null;
+ }
- // Check for writer some music is tagged that way as alternative to composer/lyricist
- var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
+ private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo)
+ {
+ if (streamInfo?.Tags == null)
+ {
+ return null;
+ }
- if (!string.IsNullOrWhiteSpace(writer))
+ var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng")
+ ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES");
+ if (!string.IsNullOrEmpty(numberOfBytes)
+ && long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes))
{
- var peoples = new List<BaseItemPerson>();
- foreach (var person in Split(writer, false))
- {
- peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
- }
- audio.People = peoples.ToArray();
+ return parsedBytes;
}
- audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
+ return null;
+ }
- var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
+ private void SetSize(InternalMediaInfoResult data, MediaInfo info)
+ {
+ if (data.Format == null)
+ {
+ return;
+ }
- if (!string.IsNullOrWhiteSpace(artists))
+ info.Size = string.IsNullOrEmpty(data.Format.Size) ? null : long.Parse(data.Format.Size, CultureInfo.InvariantCulture);
+ }
+
+ private void SetAudioInfoFromTags(MediaInfo audio, IReadOnlyDictionary<string, string> tags)
+ {
+ var people = new List<BaseItemPerson>();
+ if (tags.TryGetValue("composer", out var composer) && !string.IsNullOrWhiteSpace(composer))
{
- audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
- .DistinctNames()
- .ToArray();
+ foreach (var person in Split(composer, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
+ }
}
- else
+
+ if (tags.TryGetValue("conductor", out var conductor) && !string.IsNullOrWhiteSpace(conductor))
{
- var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
- if (string.IsNullOrWhiteSpace(artist))
+ foreach (var person in Split(conductor, false))
{
- audio.Artists = new string[] { };
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
}
- else
+ }
+
+ if (tags.TryGetValue("lyricist", out var lyricist) && !string.IsNullOrWhiteSpace(lyricist))
+ {
+ foreach (var person in Split(lyricist, false))
{
- audio.Artists = SplitArtists(artist, _nameDelimiters, true)
- .DistinctNames()
- .ToArray();
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
}
}
- var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
- if (string.IsNullOrWhiteSpace(albumArtist))
+ if (tags.TryGetValue("performer", out var performer) && !string.IsNullOrWhiteSpace(performer))
{
- albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
+ foreach (var person in Split(performer, false))
+ {
+ Match match = _performerPattern.Match(person);
+
+ // If the performer doesn't have any instrument/role associated, it won't match. In that case, chances are it's simply a band name, so we skip it.
+ if (match.Success)
+ {
+ people.Add(new BaseItemPerson
+ {
+ Name = match.Groups["name"].Value,
+ Type = PersonType.Actor,
+ Role = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Groups["instrument"].Value)
+ });
+ }
+ }
}
- if (string.IsNullOrWhiteSpace(albumArtist))
+
+ // In cases where there isn't sufficient information as to which role a writer performed on a recording, tagging software uses the "writer" tag.
+ if (tags.TryGetValue("writer", out var writer) && !string.IsNullOrWhiteSpace(writer))
{
- albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
+ foreach (var person in Split(writer, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
+ }
}
- if (string.IsNullOrWhiteSpace(albumArtist))
+ if (tags.TryGetValue("arranger", out var arranger) && !string.IsNullOrWhiteSpace(arranger))
{
- audio.AlbumArtists = new string[] { };
+ foreach (var person in Split(arranger, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Arranger });
+ }
}
- else
+
+ if (tags.TryGetValue("engineer", out var engineer) && !string.IsNullOrWhiteSpace(engineer))
{
- audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
- .DistinctNames()
- .ToArray();
+ foreach (var person in Split(engineer, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Engineer });
+ }
+ }
+
+ if (tags.TryGetValue("mixer", out var mixer) && !string.IsNullOrWhiteSpace(mixer))
+ {
+ foreach (var person in Split(mixer, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Mixer });
+ }
+ }
+ if (tags.TryGetValue("remixer", out var remixer) && !string.IsNullOrWhiteSpace(remixer))
+ {
+ foreach (var person in Split(remixer, false))
+ {
+ people.Add(new BaseItemPerson { Name = person, Type = PersonType.Remixer });
+ }
}
+ audio.People = people.ToArray();
+
+ // Set album artist
+ var albumArtist = tags.GetFirstNotNullNorWhiteSpaceValue("albumartist", "album artist", "album_artist");
+ audio.AlbumArtists = albumArtist != null
+ ? SplitDistinctArtists(albumArtist, _nameDelimiters, true).ToArray()
+ : Array.Empty<string>();
+
+ // Set album artist to artist if empty
if (audio.AlbumArtists.Length == 0)
{
audio.AlbumArtists = audio.Artists;
}
// Track number
- audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
+ audio.IndexNumber = GetDictionaryTrackOrDiscNumber(tags, "track");
// Disc number
- audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
-
- // If we don't have a ProductionYear try and get it from PremiereDate
- if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
- {
- audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
- }
+ audio.ParentIndexNumber = GetDictionaryTrackOrDiscNumber(tags, "disc");
// There's several values in tags may or may not be present
FetchStudios(audio, tags, "organization");
@@ -1001,26 +1238,26 @@ namespace MediaBrowser.MediaEncoding.Probing
FetchStudios(audio, tags, "publisher");
FetchStudios(audio, tags, "label");
- // These support mulitple values, but for now we only store the first.
- var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
- if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
- audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
+ // These support multiple values, but for now we only store the first.
+ var mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Artist Id"))
+ ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMARTISTID"));
+ audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
- mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
- if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
- audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
+ mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Artist Id"))
+ ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ARTISTID"));
+ audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
- mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
- if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
- audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
+ mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Album Id"))
+ ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_ALBUMID"));
+ audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
- mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
- if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
- audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
+ mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Group Id"))
+ ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASEGROUPID"));
+ audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
- mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
- if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
- audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
+ mb = GetMultipleMusicBrainzId(tags.GetValueOrDefault("MusicBrainz Release Track Id"))
+ ?? GetMultipleMusicBrainzId(tags.GetValueOrDefault("MUSICBRAINZ_RELEASETRACKID"));
+ audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
}
private string GetMultipleMusicBrainzId(string value)
@@ -1030,13 +1267,11 @@ namespace MediaBrowser.MediaEncoding.Probing
return null;
}
- return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
+ return value.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
}
- private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
-
/// <summary>
/// Splits the specified val.
/// </summary>
@@ -1045,20 +1280,18 @@ namespace MediaBrowser.MediaEncoding.Probing
/// <returns>System.String[][].</returns>
private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
{
- // Only use the comma as a delimeter if there are no slashes or pipes.
+ // Only use the comma as a delimiter if there are no slashes or pipes.
// We want to be careful not to split names that have commas in them
- var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
+ var delimiter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i, StringComparison.Ordinal) != -1) ?
_nameDelimiters :
new[] { ',' };
- return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
+ return val.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
.Where(i => !string.IsNullOrWhiteSpace(i))
.Select(i => i.Trim());
}
- private const string ArtistReplaceValue = " | ";
-
- private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
+ private IEnumerable<string> SplitDistinctArtists(string val, char[] delimiters, bool splitFeaturing)
{
if (splitFeaturing)
{
@@ -1068,7 +1301,7 @@ namespace MediaBrowser.MediaEncoding.Probing
var artistsFound = new List<string>();
- foreach (var whitelistArtist in GetSplitWhitelist())
+ foreach (var whitelistArtist in SplitWhitelist)
{
var originalVal = val;
val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
@@ -1084,123 +1317,107 @@ namespace MediaBrowser.MediaEncoding.Probing
.Select(i => i.Trim());
artistsFound.AddRange(artists);
- return artistsFound;
- }
-
-
- private List<string> _splitWhiteList = null;
-
- private IEnumerable<string> GetSplitWhitelist()
- {
- if (_splitWhiteList == null)
- {
- _splitWhiteList = new List<string>
- {
- "AC/DC"
- };
- }
-
- return _splitWhiteList;
+ return artistsFound.DistinctNames();
}
/// <summary>
- /// Gets the studios from the tags collection
+ /// Gets the studios from the tags collection.
/// </summary>
/// <param name="info">The info.</param>
/// <param name="tags">The tags.</param>
/// <param name="tagName">Name of the tag.</param>
- private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
+ private void FetchStudios(MediaInfo info, IReadOnlyDictionary<string, string> tags, string tagName)
{
- var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
+ var val = tags.GetValueOrDefault(tagName);
- if (!string.IsNullOrEmpty(val))
+ if (string.IsNullOrEmpty(val))
{
- var studios = Split(val, true);
- var studioList = new List<string>();
+ return;
+ }
+
+ var studios = Split(val, true);
+ var studioList = new List<string>();
- foreach (var studio in studios)
+ foreach (var studio in studios)
+ {
+ if (string.IsNullOrWhiteSpace(studio))
{
- // Sometimes the artist name is listed here, account for that
- if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
- if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
+ continue;
+ }
- studioList.Add(studio);
+ // Don't add artist/album artist name to studios, even if it's listed there
+ if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase)
+ || info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
}
- info.Studios = studioList
- .Where(i => !string.IsNullOrWhiteSpace(i))
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .ToArray();
+ studioList.Add(studio);
}
+
+ info.Studios = studioList
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToArray();
}
/// <summary>
- /// Gets the genres from the tags collection
+ /// Gets the genres from the tags collection.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="tags">The tags.</param>
- private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
+ private void FetchGenres(MediaInfo info, IReadOnlyDictionary<string, string> tags)
{
- var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
+ var genreVal = tags.GetValueOrDefault("genre");
+ if (string.IsNullOrEmpty(genreVal))
+ {
+ return;
+ }
- if (!string.IsNullOrEmpty(val))
+ var genres = new List<string>(info.Genres);
+ foreach (var genre in Split(genreVal, true))
{
- var genres = new List<string>(info.Genres);
- foreach (var genre in Split(val, true))
+ if (string.IsNullOrWhiteSpace(genre))
{
- genres.Add(genre);
+ continue;
}
- info.Genres = genres
- .Where(i => !string.IsNullOrWhiteSpace(i))
- .Distinct(StringComparer.OrdinalIgnoreCase)
- .ToArray();
+ genres.Add(genre);
}
+
+ info.Genres = genres
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToArray();
}
/// <summary>
- /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
+ /// Gets the track or disc number, which can be in the form of '1', or '1/3'.
/// </summary>
/// <param name="tags">The tags.</param>
/// <param name="tagName">Name of the tag.</param>
- /// <returns>System.Nullable{System.Int32}.</returns>
- private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
+ /// <returns>The track or disc number, or null, if missing or not parseable.</returns>
+ private static int? GetDictionaryTrackOrDiscNumber(IReadOnlyDictionary<string, string> tags, string tagName)
{
- var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
+ var disc = tags.GetValueOrDefault(tagName);
- if (!string.IsNullOrEmpty(disc))
+ if (!string.IsNullOrEmpty(disc) && int.TryParse(disc.AsSpan().LeftPart('/'), out var discNum))
{
- disc = disc.Split('/')[0];
-
- if (int.TryParse(disc, out var num))
- {
- return num;
- }
+ return discNum;
}
return null;
}
- private ChapterInfo GetChapterInfo(MediaChapter chapter)
+ private static ChapterInfo GetChapterInfo(MediaChapter chapter)
{
var info = new ChapterInfo();
- if (chapter.tags != null)
+ if (chapter.Tags != null && chapter.Tags.TryGetValue("title", out string name))
{
- if (chapter.tags.TryGetValue("title", out string name))
- {
- info.Name = name;
- }
+ info.Name = name;
}
// Limit accuracy to milliseconds to match xml saving
- var secondsString = chapter.start_time;
+ var secondsString = chapter.StartTime;
if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
{
@@ -1211,18 +1428,16 @@ namespace MediaBrowser.MediaEncoding.Probing
return info;
}
- private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
-
private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
{
- if (data.format == null || data.format.tags == null)
+ var tags = data.Format?.Tags;
+
+ if (tags == null)
{
return;
}
- var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
-
- if (!string.IsNullOrWhiteSpace(genres))
+ if (tags.TryGetValue("WM/Genre", out var genres) && !string.IsNullOrWhiteSpace(genres))
{
var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Where(i => !string.IsNullOrWhiteSpace(i))
@@ -1236,16 +1451,12 @@ namespace MediaBrowser.MediaEncoding.Probing
}
}
- var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
-
- if (!string.IsNullOrWhiteSpace(officialRating))
+ if (tags.TryGetValue("WM/ParentalRating", out var officialRating) && !string.IsNullOrWhiteSpace(officialRating))
{
video.OfficialRating = officialRating;
}
- var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
-
- if (!string.IsNullOrEmpty(people))
+ if (tags.TryGetValue("WM/MediaCredits", out var people) && !string.IsNullOrEmpty(people))
{
video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
.Where(i => !string.IsNullOrWhiteSpace(i))
@@ -1253,29 +1464,21 @@ namespace MediaBrowser.MediaEncoding.Probing
.ToArray();
}
- var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
- if (!string.IsNullOrWhiteSpace(year))
+ if (tags.TryGetValue("WM/OriginalReleaseTime", out var year) && int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
{
- if (int.TryParse(year, NumberStyles.Integer, _usCulture, out var val))
- {
- video.ProductionYear = val;
- }
+ video.ProductionYear = parsedYear;
}
- var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
- if (!string.IsNullOrWhiteSpace(premiereDateString))
+ // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
+ // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
+ if (tags.TryGetValue("WM/MediaOriginalBroadcastDateTime", out var premiereDateString) && DateTime.TryParse(year, null, DateTimeStyles.AdjustToUniversal, out var parsedDate))
{
- // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
- // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
- if (DateTime.TryParse(year, null, DateTimeStyles.None, out var val))
- {
- video.PremiereDate = val.ToUniversalTime();
- }
+ video.PremiereDate = parsedDate;
}
- var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
+ var description = tags.GetValueOrDefault("WM/SubTitleDescription");
- var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
+ var subTitle = tags.GetValueOrDefault("WM/SubTitle");
// For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
@@ -1284,31 +1487,51 @@ namespace MediaBrowser.MediaEncoding.Probing
// OR -> COMMENT. SUBTITLE: DESCRIPTION
// e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the Doctor puts Amy, Rory and his beloved TARDIS in grave danger. Also in HD. [AD,S]
// e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in the middle of the big city. Some of Abney and Teal's favourite objects are missing. [S]
- if (string.IsNullOrWhiteSpace(subTitle) && !string.IsNullOrWhiteSpace(description) && description.Substring(0, Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)).Contains(":")) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
+ if (string.IsNullOrWhiteSpace(subTitle)
+ && !string.IsNullOrWhiteSpace(description)
+ && description.AsSpan()[..Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)].Contains(':')) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
{
- string[] parts = description.Split(':');
- if (parts.Length > 0)
+ string[] descriptionParts = description.Split(':');
+ if (descriptionParts.Length > 0)
{
- string subtitle = parts[0];
+ string subtitle = descriptionParts[0];
try
{
- if (subtitle.Contains("/")) // It contains a episode number and season number
+ // Check if it contains a episode number and season number
+ if (subtitle.Contains('/', StringComparison.Ordinal))
{
- string[] numbers = subtitle.Split(' ');
- video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
- int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
+ string[] subtitleParts = subtitle.Split(' ');
+ string[] numbers = subtitleParts[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/');
+ video.IndexNumber = int.Parse(numbers[0], CultureInfo.InvariantCulture);
+ // int totalEpisodesInSeason = int.Parse(numbers[1], CultureInfo.InvariantCulture);
- description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
+ // Skip the numbers, concatenate the rest, trim and set as new description
+ description = string.Join(' ', subtitleParts, 1, subtitleParts.Length - 1).Trim();
+ }
+ else if (subtitle.Contains('.', StringComparison.Ordinal))
+ {
+ var subtitleParts = subtitle.Split('.');
+ description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
}
else
- throw new Exception(); // Switch to default parsing
+ {
+ description = subtitle.Trim();
+ }
}
- catch // Default parsing
+ catch (Exception ex)
{
- if (subtitle.Contains(".")) // skip the comment, keep the subtitle
- description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
+ _logger.LogError(ex, "Error while parsing subtitle field");
+
+ // Fallback to default parsing
+ if (subtitle.Contains('.', StringComparison.Ordinal))
+ {
+ var subtitleParts = subtitle.Split('.');
+ description = string.Join('.', subtitleParts, 1, subtitleParts.Length - 1).Trim();
+ }
else
- description = subtitle.Trim(); // Clean up whitespaces and save it
+ {
+ description = subtitle.Trim();
+ }
}
}
}
@@ -1321,34 +1544,38 @@ namespace MediaBrowser.MediaEncoding.Probing
private void ExtractTimestamp(MediaInfo video)
{
- if (video.VideoType == VideoType.VideoFile)
+ if (video.VideoType != VideoType.VideoFile)
{
- if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- video.Timestamp = GetMpegTimestamp(video.Path);
+ return;
+ }
- _logger.LogDebug("Video has {timestamp} timestamp", video.Timestamp);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error extracting timestamp info from {path}", video.Path);
- video.Timestamp = null;
- }
- }
+ if (!string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ try
+ {
+ video.Timestamp = GetMpegTimestamp(video.Path);
+ _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
+ }
+ catch (Exception ex)
+ {
+ video.Timestamp = null;
+ _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
}
}
+ // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
private TransportStreamTimestamp GetMpegTimestamp(string path)
{
- var packetBuffer = new byte['Å'];
+ var packetBuffer = new byte[197];
- using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
+ using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1))
{
- fs.Read(packetBuffer, 0, packetBuffer.Length);
+ fs.Read(packetBuffer);
}
if (packetBuffer[0] == 71)
@@ -1356,17 +1583,17 @@ namespace MediaBrowser.MediaEncoding.Probing
return TransportStreamTimestamp.None;
}
- if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
+ if ((packetBuffer[4] != 71) || (packetBuffer[196] != 71))
{
- if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
- {
- return TransportStreamTimestamp.Zero;
- }
+ return TransportStreamTimestamp.None;
+ }
- return TransportStreamTimestamp.Valid;
+ if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
+ {
+ return TransportStreamTimestamp.Zero;
}
- return TransportStreamTimestamp.None;
+ return TransportStreamTimestamp.Valid;
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs b/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs
index 6ecdf89bc..7b74cfc89 100644
--- a/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -9,11 +10,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.MediaEncoding.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs
index 605504418..08ee5c72e 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs
@@ -1,122 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
+using Nikse.SubtitleEdit.Core.SubtitleFormats;
namespace MediaBrowser.MediaEncoding.Subtitles
{
- public class AssParser : ISubtitleParser
+ /// <summary>
+ /// Advanced SubStation Alpha subtitle parser.
+ /// </summary>
+ public class AssParser : SubtitleEditParser<AdvancedSubStationAlpha>
{
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
- {
- var trackInfo = new SubtitleTrackInfo();
- var trackEvents = new List<SubtitleTrackEvent>();
- var eventIndex = 1;
- using (var reader = new StreamReader(stream))
- {
- string line;
- while (reader.ReadLine() != "[Events]")
- { }
- var headers = ParseFieldHeaders(reader.ReadLine());
-
- while ((line = reader.ReadLine()) != null)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
- if (line.StartsWith("["))
- break;
- if (string.IsNullOrEmpty(line))
- continue;
- var subEvent = new SubtitleTrackEvent { Id = eventIndex.ToString(_usCulture) };
- eventIndex++;
- var sections = line.Substring(10).Split(',');
-
- subEvent.StartPositionTicks = GetTicks(sections[headers["Start"]]);
- subEvent.EndPositionTicks = GetTicks(sections[headers["End"]]);
-
- subEvent.Text = string.Join(",", sections.Skip(headers["Text"]));
- RemoteNativeFormatting(subEvent);
-
- subEvent.Text = subEvent.Text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
-
- subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase);
-
- trackEvents.Add(subEvent);
- }
- }
- trackInfo.TrackEvents = trackEvents.ToArray();
- return trackInfo;
- }
-
- long GetTicks(string time)
- {
- return TimeSpan.TryParseExact(time, @"h\:mm\:ss\.ff", _usCulture, out var span)
- ? span.Ticks : 0;
- }
-
- private Dictionary<string, int> ParseFieldHeaders(string line)
- {
- var fields = line.Substring(8).Split(',').Select(x => x.Trim()).ToList();
-
- var result = new Dictionary<string, int> {
- {"Start", fields.IndexOf("Start")},
- {"End", fields.IndexOf("End")},
- {"Text", fields.IndexOf("Text")}
- };
- return result;
- }
-
/// <summary>
- /// Credit: https://github.com/SubtitleEdit/subtitleedit/blob/master/src/Logic/SubtitleFormats/AdvancedSubStationAlpha.cs
+ /// Initializes a new instance of the <see cref="AssParser"/> class.
/// </summary>
- private void RemoteNativeFormatting(SubtitleTrackEvent p)
+ /// <param name="logger">The logger.</param>
+ public AssParser(ILogger logger) : base(logger)
{
- int indexOfBegin = p.Text.IndexOf('{');
- string pre = string.Empty;
- while (indexOfBegin >= 0 && p.Text.IndexOf('}') > indexOfBegin)
- {
- string s = p.Text.Substring(indexOfBegin);
- if (s.StartsWith("{\\an1}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an2}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an3}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an4}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an5}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an6}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an7}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an8}", StringComparison.Ordinal) ||
- s.StartsWith("{\\an9}", StringComparison.Ordinal))
- {
- pre = s.Substring(0, 6);
- }
- else if (s.StartsWith("{\\an1\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an2\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an3\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an4\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an5\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an6\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an7\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an8\\", StringComparison.Ordinal) ||
- s.StartsWith("{\\an9\\", StringComparison.Ordinal))
- {
- pre = s.Substring(0, 5) + "}";
- }
- int indexOfEnd = p.Text.IndexOf('}');
- p.Text = p.Text.Remove(indexOfBegin, (indexOfEnd - indexOfBegin) + 1);
-
- indexOfBegin = p.Text.IndexOf('{');
- }
- p.Text = pre + p.Text;
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/ConfigurationExtension.cs b/MediaBrowser.MediaEncoding/Subtitles/ConfigurationExtension.cs
deleted file mode 100644
index 92544f4f6..000000000
--- a/MediaBrowser.MediaEncoding/Subtitles/ConfigurationExtension.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Providers;
-
-namespace MediaBrowser.MediaEncoding.Subtitles
-{
- public static class ConfigurationExtension
- {
- public static SubtitleOptions GetSubtitleConfiguration(this IConfigurationManager manager)
- {
- return manager.GetConfiguration<SubtitleOptions>("subtitles");
- }
- }
-
- public class SubtitleConfigurationFactory : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new List<ConfigurationStore>
- {
- new ConfigurationStore
- {
- Key = "subtitles",
- ConfigurationType = typeof (SubtitleOptions)
- }
- };
- }
- }
-}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs b/MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs
index f0d107196..c0023ebf2 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.IO;
using System.Threading;
using MediaBrowser.Model.MediaInfo;
diff --git a/MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs
index 3401c2d67..dec714121 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.Subtitles
{
/// <summary>
- /// Interface ISubtitleWriter
+ /// Interface ISubtitleWriter.
/// </summary>
public interface ISubtitleWriter
{
diff --git a/MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs
index 8995fcfe1..1b452b0ce 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs
@@ -1,27 +1,43 @@
using System.IO;
-using System.Text;
+using System.Text.Json;
using System.Threading;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.MediaEncoding.Subtitles
{
+ /// <summary>
+ /// JSON subtitle writer.
+ /// </summary>
public class JsonWriter : ISubtitleWriter
{
- private readonly IJsonSerializer _json;
-
- public JsonWriter(IJsonSerializer json)
- {
- _json = json;
- }
-
+ /// <inheritdoc />
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
{
- using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
+ using (var writer = new Utf8JsonWriter(stream))
{
- var json = _json.SerializeToString(info);
+ var trackevents = info.TrackEvents;
+ writer.WriteStartObject();
+ writer.WriteStartArray("TrackEvents");
+
+ for (int i = 0; i < trackevents.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var current = trackevents[i];
+ writer.WriteStartObject();
+
+ writer.WriteString("Id", current.Id);
+ writer.WriteString("Text", current.Text);
+ writer.WriteNumber("StartPositionTicks", current.StartPositionTicks);
+ writer.WriteNumber("EndPositionTicks", current.EndPositionTicks);
+
+ writer.WriteEndObject();
+ }
+
+ writer.WriteEndArray();
+ writer.WriteEndObject();
- writer.Write(json);
+ writer.Flush();
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
deleted file mode 100644
index 6a5162b8d..000000000
--- a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
+++ /dev/null
@@ -1,346 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Controller.Security;
-using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-using OpenSubtitlesHandler;
-
-namespace MediaBrowser.MediaEncoding.Subtitles
-{
- public class OpenSubtitleDownloader : ISubtitleProvider, IDisposable
- {
- private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- private readonly IServerConfigurationManager _config;
- private readonly IEncryptionManager _encryption;
-
- private readonly IJsonSerializer _json;
- private readonly IFileSystem _fileSystem;
-
- public OpenSubtitleDownloader(ILoggerFactory loggerFactory, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem)
- {
- _logger = loggerFactory.CreateLogger(GetType().Name);
- _httpClient = httpClient;
- _config = config;
- _encryption = encryption;
- _json = json;
- _fileSystem = fileSystem;
-
- _config.NamedConfigurationUpdating += _config_NamedConfigurationUpdating;
-
- Utilities.HttpClient = httpClient;
- OpenSubtitles.SetUserAgent("jellyfin");
- }
-
- private const string PasswordHashPrefix = "h:";
- void _config_NamedConfigurationUpdating(object sender, ConfigurationUpdateEventArgs e)
- {
- if (!string.Equals(e.Key, "subtitles", StringComparison.OrdinalIgnoreCase))
- {
- return;
- }
-
- var options = (SubtitleOptions)e.NewConfiguration;
-
- if (options != null &&
- !string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash) &&
- !options.OpenSubtitlesPasswordHash.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
- {
- options.OpenSubtitlesPasswordHash = EncryptPassword(options.OpenSubtitlesPasswordHash);
- }
- }
-
- private string EncryptPassword(string password)
- {
- return PasswordHashPrefix + _encryption.EncryptString(password);
- }
-
- private string DecryptPassword(string password)
- {
- if (password == null ||
- !password.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
- {
- return string.Empty;
- }
-
- return _encryption.DecryptString(password.Substring(2));
- }
-
- public string Name => "Open Subtitles";
-
- private SubtitleOptions GetOptions()
- {
- return _config.GetSubtitleConfiguration();
- }
-
- public IEnumerable<VideoContentType> SupportedMediaTypes
- {
- get
- {
- var options = GetOptions();
-
- if (string.IsNullOrWhiteSpace(options.OpenSubtitlesUsername) ||
- string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash))
- {
- return new VideoContentType[] { };
- }
-
- return new[] { VideoContentType.Episode, VideoContentType.Movie };
- }
- }
-
- public Task<SubtitleResponse> GetSubtitles(string id, CancellationToken cancellationToken)
- {
- return GetSubtitlesInternal(id, GetOptions(), cancellationToken);
- }
-
- private DateTime _lastRateLimitException;
- private async Task<SubtitleResponse> GetSubtitlesInternal(string id,
- SubtitleOptions options,
- CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(id))
- {
- throw new ArgumentNullException(nameof(id));
- }
-
- var idParts = id.Split(new[] { '-' }, 3);
-
- var format = idParts[0];
- var language = idParts[1];
- var ossId = idParts[2];
-
- var downloadsList = new[] { int.Parse(ossId, _usCulture) };
-
- await Login(cancellationToken).ConfigureAwait(false);
-
- if ((DateTime.UtcNow - _lastRateLimitException).TotalHours < 1)
- {
- throw new RateLimitExceededException("OpenSubtitles rate limit reached");
- }
-
- var resultDownLoad = await OpenSubtitles.DownloadSubtitlesAsync(downloadsList, cancellationToken).ConfigureAwait(false);
-
- if ((resultDownLoad.Status ?? string.Empty).IndexOf("407", StringComparison.OrdinalIgnoreCase) != -1)
- {
- _lastRateLimitException = DateTime.UtcNow;
- throw new RateLimitExceededException("OpenSubtitles rate limit reached");
- }
-
- if (!(resultDownLoad is MethodResponseSubtitleDownload))
- {
- throw new Exception("Invalid response type");
- }
-
- var results = ((MethodResponseSubtitleDownload)resultDownLoad).Results;
-
- _lastRateLimitException = DateTime.MinValue;
-
- if (results.Count == 0)
- {
- var msg = string.Format("Subtitle with Id {0} was not found. Name: {1}. Status: {2}. Message: {3}",
- ossId,
- resultDownLoad.Name ?? string.Empty,
- resultDownLoad.Status ?? string.Empty,
- resultDownLoad.Message ?? string.Empty);
-
- throw new ResourceNotFoundException(msg);
- }
-
- var data = Convert.FromBase64String(results.First().Data);
-
- return new SubtitleResponse
- {
- Format = format,
- Language = language,
-
- Stream = new MemoryStream(Utilities.Decompress(new MemoryStream(data)))
- };
- }
-
- private DateTime _lastLogin;
- private async Task Login(CancellationToken cancellationToken)
- {
- if ((DateTime.UtcNow - _lastLogin).TotalSeconds < 60)
- {
- return;
- }
-
- var options = GetOptions();
-
- var user = options.OpenSubtitlesUsername ?? string.Empty;
- var password = DecryptPassword(options.OpenSubtitlesPasswordHash);
-
- var loginResponse = await OpenSubtitles.LogInAsync(user, password, "en", cancellationToken).ConfigureAwait(false);
-
- if (!(loginResponse is MethodResponseLogIn))
- {
- throw new Exception("Authentication to OpenSubtitles failed.");
- }
-
- _lastLogin = DateTime.UtcNow;
- }
-
- public async Task<IEnumerable<NameIdPair>> GetSupportedLanguages(CancellationToken cancellationToken)
- {
- await Login(cancellationToken).ConfigureAwait(false);
-
- var result = OpenSubtitles.GetSubLanguages("en");
- if (!(result is MethodResponseGetSubLanguages))
- {
- _logger.LogError("Invalid response type");
- return new List<NameIdPair>();
- }
-
- var results = ((MethodResponseGetSubLanguages)result).Languages;
-
- return results.Select(i => new NameIdPair
- {
- Name = i.LanguageName,
- Id = i.SubLanguageID
- });
- }
-
- private string NormalizeLanguage(string language)
- {
- // Problem with Greek subtitle download #1349
- if (string.Equals(language, "gre", StringComparison.OrdinalIgnoreCase))
- {
-
- return "ell";
- }
-
- return language;
- }
-
- public async Task<IEnumerable<RemoteSubtitleInfo>> Search(SubtitleSearchRequest request, CancellationToken cancellationToken)
- {
- var imdbIdText = request.GetProviderId(MetadataProviders.Imdb);
- long imdbId = 0;
-
- switch (request.ContentType)
- {
- case VideoContentType.Episode:
- if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName))
- {
- _logger.LogDebug("Episode information missing");
- return new List<RemoteSubtitleInfo>();
- }
- break;
- case VideoContentType.Movie:
- if (string.IsNullOrEmpty(request.Name))
- {
- _logger.LogDebug("Movie name missing");
- return new List<RemoteSubtitleInfo>();
- }
- if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId))
- {
- _logger.LogDebug("Imdb id missing");
- return new List<RemoteSubtitleInfo>();
- }
- break;
- }
-
- if (string.IsNullOrEmpty(request.MediaPath))
- {
- _logger.LogDebug("Path Missing");
- return new List<RemoteSubtitleInfo>();
- }
-
- await Login(cancellationToken).ConfigureAwait(false);
-
- var subLanguageId = NormalizeLanguage(request.Language);
- string hash;
-
- using (var fileStream = File.OpenRead(request.MediaPath))
- {
- hash = Utilities.ComputeHash(fileStream);
- }
- var fileInfo = _fileSystem.GetFileInfo(request.MediaPath);
- var movieByteSize = fileInfo.Length;
- var searchImdbId = request.ContentType == VideoContentType.Movie ? imdbId.ToString(_usCulture) : "";
- var subtitleSearchParameters = request.ContentType == VideoContentType.Episode
- ? new List<SubtitleSearchParameters> {
- new SubtitleSearchParameters(subLanguageId,
- query: request.SeriesName,
- season: request.ParentIndexNumber.Value.ToString(_usCulture),
- episode: request.IndexNumber.Value.ToString(_usCulture))
- }
- : new List<SubtitleSearchParameters> {
- new SubtitleSearchParameters(subLanguageId, imdbid: searchImdbId),
- new SubtitleSearchParameters(subLanguageId, query: request.Name, imdbid: searchImdbId)
- };
- var parms = new List<SubtitleSearchParameters> {
- new SubtitleSearchParameters( subLanguageId,
- movieHash: hash,
- movieByteSize: movieByteSize,
- imdbid: searchImdbId ),
- };
- parms.AddRange(subtitleSearchParameters);
- var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false);
- if (!(result is MethodResponseSubtitleSearch))
- {
- _logger.LogError("Invalid response type");
- return new List<RemoteSubtitleInfo>();
- }
-
- Predicate<SubtitleSearchResult> mediaFilter =
- x =>
- request.ContentType == VideoContentType.Episode
- ? !string.IsNullOrEmpty(x.SeriesSeason) && !string.IsNullOrEmpty(x.SeriesEpisode) &&
- int.Parse(x.SeriesSeason, _usCulture) == request.ParentIndexNumber &&
- int.Parse(x.SeriesEpisode, _usCulture) == request.IndexNumber
- : !string.IsNullOrEmpty(x.IDMovieImdb) && long.Parse(x.IDMovieImdb, _usCulture) == imdbId;
-
- var results = ((MethodResponseSubtitleSearch)result).Results;
-
- // Avoid implicitly captured closure
- var hasCopy = hash;
-
- return results.Where(x => x.SubBad == "0" && mediaFilter(x) && (!request.IsPerfectMatch || string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase)))
- .OrderBy(x => (string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase) ? 0 : 1))
- .ThenBy(x => Math.Abs(long.Parse(x.MovieByteSize, _usCulture) - movieByteSize))
- .ThenByDescending(x => int.Parse(x.SubDownloadsCnt, _usCulture))
- .ThenByDescending(x => double.Parse(x.SubRating, _usCulture))
- .Select(i => new RemoteSubtitleInfo
- {
- Author = i.UserNickName,
- Comment = i.SubAuthorComment,
- CommunityRating = float.Parse(i.SubRating, _usCulture),
- DownloadCount = int.Parse(i.SubDownloadsCnt, _usCulture),
- Format = i.SubFormat,
- ProviderName = Name,
- ThreeLetterISOLanguageName = i.SubLanguageID,
-
- Id = i.SubFormat + "-" + i.SubLanguageID + "-" + i.IDSubtitleFile,
-
- Name = i.SubFileName,
- DateCreated = DateTime.Parse(i.SubAddDate, _usCulture),
- IsHashMatch = i.MovieHash == hasCopy
-
- }).Where(i => !string.Equals(i.Format, "sub", StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Format, "idx", StringComparison.OrdinalIgnoreCase));
- }
-
- public void Dispose()
- {
- _config.NamedConfigurationUpdating -= _config_NamedConfigurationUpdating;
- }
- }
-}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs b/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs
deleted file mode 100644
index bf8808eb8..000000000
--- a/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MediaBrowser.MediaEncoding.Subtitles
-{
- public class ParserValues
- {
- public const string NewLine = "\r\n";
- }
-}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
index 0606dbdb2..78d54ca51 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
@@ -1,92 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Text.RegularExpressions;
-using System.Threading;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
+using Nikse.SubtitleEdit.Core.SubtitleFormats;
namespace MediaBrowser.MediaEncoding.Subtitles
{
- public class SrtParser : ISubtitleParser
+ /// <summary>
+ /// SubRip subtitle parser.
+ /// </summary>
+ public class SrtParser : SubtitleEditParser<SubRip>
{
- private readonly ILogger _logger;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public SrtParser(ILogger logger)
- {
- _logger = logger;
- }
-
- public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
- {
- var trackInfo = new SubtitleTrackInfo();
- var trackEvents = new List<SubtitleTrackEvent>();
- using (var reader = new StreamReader(stream))
- {
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
- var subEvent = new SubtitleTrackEvent { Id = line };
- line = reader.ReadLine();
-
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
-
- var time = Regex.Split(line, @"[\t ]*-->[\t ]*");
-
- if (time.Length < 2)
- {
- // This occurs when subtitle text has an empty line as part of the text.
- // Need to adjust the break statement below to resolve this.
- _logger.LogWarning("Unrecognized line in srt: {0}", line);
- continue;
- }
- subEvent.StartPositionTicks = GetTicks(time[0]);
- var endTime = time[1];
- var idx = endTime.IndexOf(" ", StringComparison.Ordinal);
- if (idx > 0)
- endTime = endTime.Substring(0, idx);
- subEvent.EndPositionTicks = GetTicks(endTime);
- var multiline = new List<string>();
- while ((line = reader.ReadLine()) != null)
- {
- if (string.IsNullOrEmpty(line))
- {
- break;
- }
- multiline.Add(line);
- }
- subEvent.Text = string.Join(ParserValues.NewLine, multiline);
- subEvent.Text = subEvent.Text.Replace(@"\N", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
- subEvent.Text = Regex.Replace(subEvent.Text, @"\{(?:\\\d?[\w.-]+(?:\([^\)]*\)|&H?[0-9A-Fa-f]+&|))+\}", string.Empty, RegexOptions.IgnoreCase);
- subEvent.Text = Regex.Replace(subEvent.Text, "<", "&lt;", RegexOptions.IgnoreCase);
- subEvent.Text = Regex.Replace(subEvent.Text, ">", "&gt;", RegexOptions.IgnoreCase);
- subEvent.Text = Regex.Replace(subEvent.Text, "&lt;(\\/?(font|b|u|i|s))((\\s+(\\w|\\w[\\w\\-]*\\w)(\\s*=\\s*(?:\\\".*?\\\"|'.*?'|[^'\\\">\\s]+))?)+\\s*|\\s*)(\\/?)&gt;", "<$1$3$7>", RegexOptions.IgnoreCase);
- trackEvents.Add(subEvent);
- }
- }
- trackInfo.TrackEvents = trackEvents.ToArray();
- return trackInfo;
- }
-
- long GetTicks(string time)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SrtParser"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ public SrtParser(ILogger logger) : base(logger)
{
- return TimeSpan.TryParseExact(time, @"hh\:mm\:ss\.fff", _usCulture, out var span)
- ? span.Ticks
- : (TimeSpan.TryParseExact(time, @"hh\:mm\:ss\,fff", _usCulture, out span)
- ? span.Ticks : 0);
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
index 6f96a641e..143c010b7 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
@@ -8,20 +8,29 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.Subtitles
{
+ /// <summary>
+ /// SRT subtitle writer.
+ /// </summary>
public class SrtWriter : ISubtitleWriter
{
+ /// <inheritdoc />
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
{
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
{
- var index = 1;
+ var trackEvents = info.TrackEvents;
- foreach (var trackEvent in info.TrackEvents)
+ for (int i = 0; i < trackEvents.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
- writer.WriteLine(index.ToString(CultureInfo.InvariantCulture));
- writer.WriteLine(@"{0:hh\:mm\:ss\,fff} --> {1:hh\:mm\:ss\,fff}", TimeSpan.FromTicks(trackEvent.StartPositionTicks), TimeSpan.FromTicks(trackEvent.EndPositionTicks));
+ var trackEvent = trackEvents[i];
+
+ writer.WriteLine((i + 1).ToString(CultureInfo.InvariantCulture));
+ writer.WriteLine(
+ @"{0:hh\:mm\:ss\,fff} --> {1:hh\:mm\:ss\,fff}",
+ TimeSpan.FromTicks(trackEvent.StartPositionTicks),
+ TimeSpan.FromTicks(trackEvent.EndPositionTicks));
var text = trackEvent.Text;
@@ -29,9 +38,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = Regex.Replace(text, @"\\n", " ", RegexOptions.IgnoreCase);
writer.WriteLine(text);
- writer.WriteLine(string.Empty);
-
- index++;
+ writer.WriteLine();
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs
index 0d696b906..17c2ae40e 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs
@@ -1,396 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using System.Threading;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
+using Nikse.SubtitleEdit.Core.SubtitleFormats;
namespace MediaBrowser.MediaEncoding.Subtitles
{
/// <summary>
- /// Credit to https://github.com/SubtitleEdit/subtitleedit/blob/a299dc4407a31796364cc6ad83f0d3786194ba22/src/Logic/SubtitleFormats/SubStationAlpha.cs
+ /// SubStation Alpha subtitle parser.
/// </summary>
- public class SsaParser : ISubtitleParser
+ public class SsaParser : SubtitleEditParser<SubStationAlpha>
{
- public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SsaParser"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ public SsaParser(ILogger logger) : base(logger)
{
- var trackInfo = new SubtitleTrackInfo();
- var trackEvents = new List<SubtitleTrackEvent>();
-
- using (var reader = new StreamReader(stream))
- {
- bool eventsStarted = false;
-
- string[] format = "Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text".Split(',');
- int indexLayer = 0;
- int indexStart = 1;
- int indexEnd = 2;
- int indexStyle = 3;
- int indexName = 4;
- int indexEffect = 8;
- int indexText = 9;
- int lineNumber = 0;
-
- var header = new StringBuilder();
-
- string line;
-
- while ((line = reader.ReadLine()) != null)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- lineNumber++;
- if (!eventsStarted)
- header.AppendLine(line);
-
- if (line.Trim().ToLowerInvariant() == "[events]")
- {
- eventsStarted = true;
- }
- else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(";"))
- {
- // skip comment lines
- }
- else if (eventsStarted && line.Trim().Length > 0)
- {
- string s = line.Trim().ToLowerInvariant();
- if (s.StartsWith("format:"))
- {
- if (line.Length > 10)
- {
- format = line.ToLowerInvariant().Substring(8).Split(',');
- for (int i = 0; i < format.Length; i++)
- {
- if (format[i].Trim().ToLowerInvariant() == "layer")
- indexLayer = i;
- else if (format[i].Trim().ToLowerInvariant() == "start")
- indexStart = i;
- else if (format[i].Trim().ToLowerInvariant() == "end")
- indexEnd = i;
- else if (format[i].Trim().ToLowerInvariant() == "text")
- indexText = i;
- else if (format[i].Trim().ToLowerInvariant() == "effect")
- indexEffect = i;
- else if (format[i].Trim().ToLowerInvariant() == "style")
- indexStyle = i;
- }
- }
- }
- else if (!string.IsNullOrEmpty(s))
- {
- string text = string.Empty;
- string start = string.Empty;
- string end = string.Empty;
- string style = string.Empty;
- string layer = string.Empty;
- string effect = string.Empty;
- string name = string.Empty;
-
- string[] splittedLine;
-
- if (s.StartsWith("dialogue:"))
- splittedLine = line.Substring(10).Split(',');
- else
- splittedLine = line.Split(',');
-
- for (int i = 0; i < splittedLine.Length; i++)
- {
- if (i == indexStart)
- start = splittedLine[i].Trim();
- else if (i == indexEnd)
- end = splittedLine[i].Trim();
- else if (i == indexLayer)
- layer = splittedLine[i];
- else if (i == indexEffect)
- effect = splittedLine[i];
- else if (i == indexText)
- text = splittedLine[i];
- else if (i == indexStyle)
- style = splittedLine[i];
- else if (i == indexName)
- name = splittedLine[i];
- else if (i > indexText)
- text += "," + splittedLine[i];
- }
-
- try
- {
- var p = new SubtitleTrackEvent();
-
- p.StartPositionTicks = GetTimeCodeFromString(start);
- p.EndPositionTicks = GetTimeCodeFromString(end);
- p.Text = GetFormattedText(text);
-
- trackEvents.Add(p);
- }
- catch
- {
- }
- }
- }
- }
-
- //if (header.Length > 0)
- //subtitle.Header = header.ToString();
-
- //subtitle.Renumber(1);
- }
- trackInfo.TrackEvents = trackEvents.ToArray();
- return trackInfo;
- }
-
- private static long GetTimeCodeFromString(string time)
- {
- // h:mm:ss.cc
- string[] timeCode = time.Split(':', '.');
- return new TimeSpan(0, int.Parse(timeCode[0]),
- int.Parse(timeCode[1]),
- int.Parse(timeCode[2]),
- int.Parse(timeCode[3]) * 10).Ticks;
- }
-
- public static string GetFormattedText(string text)
- {
- text = text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
-
- bool italic = false;
-
- for (int i = 0; i < 10; i++) // just look ten times...
- {
- if (text.Contains(@"{\fn"))
- {
- int start = text.IndexOf(@"{\fn");
- int end = text.IndexOf('}', start);
- if (end > 0 && !text.Substring(start).StartsWith("{\\fn}"))
- {
- string fontName = text.Substring(start + 4, end - (start + 4));
- string extraTags = string.Empty;
- CheckAndAddSubTags(ref fontName, ref extraTags, out italic);
- text = text.Remove(start, end - start + 1);
- if (italic)
- text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>");
- else
- text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">");
-
- int indexOfEndTag = text.IndexOf("{\\fn}", start);
- if (indexOfEndTag > 0)
- text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>");
- else
- text += "</font>";
- }
- }
-
- if (text.Contains(@"{\fs"))
- {
- int start = text.IndexOf(@"{\fs");
- int end = text.IndexOf('}', start);
- if (end > 0 && !text.Substring(start).StartsWith("{\\fs}"))
- {
- string fontSize = text.Substring(start + 4, end - (start + 4));
- string extraTags = string.Empty;
- CheckAndAddSubTags(ref fontSize, ref extraTags, out italic);
- if (IsInteger(fontSize))
- {
- text = text.Remove(start, end - start + 1);
- if (italic)
- text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>");
- else
- text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">");
-
- int indexOfEndTag = text.IndexOf("{\\fs}", start);
- if (indexOfEndTag > 0)
- text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>");
- else
- text += "</font>";
- }
- }
- }
-
- if (text.Contains(@"{\c"))
- {
- int start = text.IndexOf(@"{\c");
- int end = text.IndexOf('}', start);
- if (end > 0 && !text.Substring(start).StartsWith("{\\c}"))
- {
- string color = text.Substring(start + 4, end - (start + 4));
- string extraTags = string.Empty;
- CheckAndAddSubTags(ref color, ref extraTags, out italic);
-
- color = color.Replace("&", string.Empty).TrimStart('H');
- color = color.PadLeft(6, '0');
-
- // switch to rrggbb from bbggrr
- color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
- color = color.ToLowerInvariant();
-
- text = text.Remove(start, end - start + 1);
- if (italic)
- text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
- else
- text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
- int indexOfEndTag = text.IndexOf("{\\c}", start);
- if (indexOfEndTag > 0)
- text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>");
- else
- text += "</font>";
- }
- }
-
- if (text.Contains(@"{\1c")) // "1" specifices primary color
- {
- int start = text.IndexOf(@"{\1c");
- int end = text.IndexOf('}', start);
- if (end > 0 && !text.Substring(start).StartsWith("{\\1c}"))
- {
- string color = text.Substring(start + 5, end - (start + 5));
- string extraTags = string.Empty;
- CheckAndAddSubTags(ref color, ref extraTags, out italic);
-
- color = color.Replace("&", string.Empty).TrimStart('H');
- color = color.PadLeft(6, '0');
-
- // switch to rrggbb from bbggrr
- color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
- color = color.ToLowerInvariant();
-
- text = text.Remove(start, end - start + 1);
- if (italic)
- text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
- else
- text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
- text += "</font>";
- }
- }
-
- }
-
- text = text.Replace(@"{\i1}", "<i>");
- text = text.Replace(@"{\i0}", "</i>");
- text = text.Replace(@"{\i}", "</i>");
- if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>"))
- text += "</i>";
-
- text = text.Replace(@"{\u1}", "<u>");
- text = text.Replace(@"{\u0}", "</u>");
- text = text.Replace(@"{\u}", "</u>");
- if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>"))
- text += "</u>";
-
- text = text.Replace(@"{\b1}", "<b>");
- text = text.Replace(@"{\b0}", "</b>");
- text = text.Replace(@"{\b}", "</b>");
- if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>"))
- text += "</b>";
-
- return text;
- }
-
- private static bool IsInteger(string s)
- {
- if (int.TryParse(s, out var i))
- return true;
- return false;
- }
-
- private static int CountTagInText(string text, string tag)
- {
- int count = 0;
- int index = text.IndexOf(tag);
- while (index >= 0)
- {
- count++;
- if (index == text.Length)
- return count;
- index = text.IndexOf(tag, index + 1);
- }
- return count;
- }
-
- private static void CheckAndAddSubTags(ref string tagName, ref string extraTags, out bool italic)
- {
- italic = false;
- int indexOfSPlit = tagName.IndexOf(@"\");
- if (indexOfSPlit > 0)
- {
- string rest = tagName.Substring(indexOfSPlit).TrimStart('\\');
- tagName = tagName.Remove(indexOfSPlit);
-
- for (int i = 0; i < 10; i++)
- {
- if (rest.StartsWith("fs") && rest.Length > 2)
- {
- indexOfSPlit = rest.IndexOf(@"\");
- string fontSize = rest;
- if (indexOfSPlit > 0)
- {
- fontSize = rest.Substring(0, indexOfSPlit);
- rest = rest.Substring(indexOfSPlit).TrimStart('\\');
- }
- else
- {
- rest = string.Empty;
- }
- extraTags += " size=\"" + fontSize.Substring(2) + "\"";
- }
- else if (rest.StartsWith("fn") && rest.Length > 2)
- {
- indexOfSPlit = rest.IndexOf(@"\");
- string fontName = rest;
- if (indexOfSPlit > 0)
- {
- fontName = rest.Substring(0, indexOfSPlit);
- rest = rest.Substring(indexOfSPlit).TrimStart('\\');
- }
- else
- {
- rest = string.Empty;
- }
- extraTags += " face=\"" + fontName.Substring(2) + "\"";
- }
- else if (rest.StartsWith("c") && rest.Length > 2)
- {
- indexOfSPlit = rest.IndexOf(@"\");
- string fontColor = rest;
- if (indexOfSPlit > 0)
- {
- fontColor = rest.Substring(0, indexOfSPlit);
- rest = rest.Substring(indexOfSPlit).TrimStart('\\');
- }
- else
- {
- rest = string.Empty;
- }
-
- string color = fontColor.Substring(2);
- color = color.Replace("&", string.Empty).TrimStart('H');
- color = color.PadLeft(6, '0');
- // switch to rrggbb from bbggrr
- color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
- color = color.ToLowerInvariant();
-
- extraTags += " color=\"" + color + "\"";
- }
- else if (rest.StartsWith("i1") && rest.Length > 1)
- {
- indexOfSPlit = rest.IndexOf(@"\");
- italic = true;
- if (indexOfSPlit > 0)
- {
- rest = rest.Substring(indexOfSPlit).TrimStart('\\');
- }
- else
- {
- rest = string.Empty;
- }
- }
- else if (rest.Length > 0 && rest.Contains("\\"))
- {
- indexOfSPlit = rest.IndexOf(@"\");
- rest = rest.Substring(indexOfSPlit).TrimStart('\\');
- }
- }
- }
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs
new file mode 100644
index 000000000..52c1b6467
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs
@@ -0,0 +1,61 @@
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using Jellyfin.Extensions;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
+using Nikse.SubtitleEdit.Core.Common;
+using ILogger = Microsoft.Extensions.Logging.ILogger;
+using SubtitleFormat = Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat;
+
+namespace MediaBrowser.MediaEncoding.Subtitles
+{
+ /// <summary>
+ /// SubStation Alpha subtitle parser.
+ /// </summary>
+ /// <typeparam name="T">The <see cref="SubtitleFormat" />.</typeparam>
+ public abstract class SubtitleEditParser<T> : ISubtitleParser
+ where T : SubtitleFormat, new()
+ {
+ private readonly ILogger _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubtitleEditParser{T}"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ protected SubtitleEditParser(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ /// <inheritdoc />
+ public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
+ {
+ var subtitle = new Subtitle();
+ var subRip = new T();
+ var lines = stream.ReadAllLines().ToList();
+ subRip.LoadSubtitle(subtitle, lines, "untitled");
+ if (subRip.ErrorCount > 0)
+ {
+ _logger.LogError("{ErrorCount} errors encountered while parsing subtitle", subRip.ErrorCount);
+ }
+
+ var trackInfo = new SubtitleTrackInfo();
+ int len = subtitle.Paragraphs.Count;
+ var trackEvents = new SubtitleTrackEvent[len];
+ for (int i = 0; i < len; i++)
+ {
+ var p = subtitle.Paragraphs[i];
+ trackEvents[i] = new SubtitleTrackEvent(p.Number.ToString(CultureInfo.InvariantCulture), p.Text)
+ {
+ StartPositionTicks = p.StartTime.TimeSpan.Ticks,
+ EndPositionTicks = p.EndTime.TimeSpan.Ticks
+ };
+ }
+
+ trackInfo.TrackEvents = trackEvents;
+ return trackInfo;
+ }
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
index d978359c7..2b2de2ff6 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
@@ -1,65 +1,67 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using UtfUnknown;
namespace MediaBrowser.MediaEncoding.Subtitles
{
- public class SubtitleEncoder : ISubtitleEncoder
+ public sealed class SubtitleEncoder : ISubtitleEncoder
{
- private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
+ private readonly ILogger<SubtitleEncoder> _logger;
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
private readonly IMediaEncoder _mediaEncoder;
- private readonly IJsonSerializer _json;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IMediaSourceManager _mediaSourceManager;
- private readonly IProcessFactory _processFactory;
+
+ /// <summary>
+ /// The _semaphoreLocks.
+ /// </summary>
+ private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
+ new ConcurrentDictionary<string, SemaphoreSlim>();
public SubtitleEncoder(
- ILibraryManager libraryManager,
- ILoggerFactory loggerFactory,
+ ILogger<SubtitleEncoder> logger,
IApplicationPaths appPaths,
IFileSystem fileSystem,
IMediaEncoder mediaEncoder,
- IJsonSerializer json,
- IHttpClient httpClient,
- IMediaSourceManager mediaSourceManager,
- IProcessFactory processFactory)
+ IHttpClientFactory httpClientFactory,
+ IMediaSourceManager mediaSourceManager)
{
- _libraryManager = libraryManager;
- _logger = loggerFactory.CreateLogger(nameof(SubtitleEncoder));
+ _logger = logger;
_appPaths = appPaths;
_fileSystem = fileSystem;
_mediaEncoder = mediaEncoder;
- _json = json;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_mediaSourceManager = mediaSourceManager;
- _processFactory = processFactory;
}
private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
- private Stream ConvertSubtitles(Stream stream,
+ private Stream ConvertSubtitles(
+ Stream stream,
string inputFormat,
string outputFormat,
long startTimeTicks,
@@ -71,8 +73,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try
{
- var reader = GetReader(inputFormat, true);
-
+ var reader = GetReader(inputFormat);
var trackInfo = reader.Parse(stream, cancellationToken);
FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
@@ -121,13 +122,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
throw new ArgumentNullException(nameof(item));
}
+
if (string.IsNullOrWhiteSpace(mediaSourceId))
{
throw new ArgumentNullException(nameof(mediaSourceId));
}
- // TODO network path substition useful ?
- var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, true, cancellationToken).ConfigureAwait(false);
+ var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
var mediaSource = mediaSources
.First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
@@ -139,10 +140,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
.ConfigureAwait(false);
var inputFormat = subtitle.format;
- var writer = TryGetWriter(outputFormat);
// Return the original if we don't have any way of converting it
- if (writer == null)
+ if (!TryGetWriter(outputFormat, out var writer))
{
return subtitle.stream;
}
@@ -165,58 +165,39 @@ namespace MediaBrowser.MediaEncoding.Subtitles
MediaStream subtitleStream,
CancellationToken cancellationToken)
{
- string[] inputFiles;
+ var fileInfo = await GetReadableFile(mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false);
- if (mediaSource.VideoType.HasValue
- && (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd))
- {
- var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
- inputFiles = mediaSourceItem.GetPlayableStreamFileNames(_mediaEncoder);
- }
- else
- {
- inputFiles = new[] { mediaSource.Path };
- }
-
- var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
-
- var stream = await GetSubtitleStream(fileInfo.Path, subtitleStream.Language, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false);
+ var stream = await GetSubtitleStream(fileInfo, cancellationToken).ConfigureAwait(false);
return (stream, fileInfo.Format);
}
- private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
+ private async Task<Stream> GetSubtitleStream(SubtitleInfo fileInfo, CancellationToken cancellationToken)
{
- if (requiresCharset)
+ if (fileInfo.IsExternal)
{
- var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
-
- var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
- _logger.LogDebug("charset {CharSet} detected for {Path}", charset ?? "null", path);
-
- if (!string.IsNullOrEmpty(charset))
+ using (var stream = await GetStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false))
{
- // Make sure we have all the code pages we can get
- Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- using (var inputStream = new MemoryStream(bytes))
- using (var reader = new StreamReader(inputStream, Encoding.GetEncoding(charset)))
+ var result = CharsetDetector.DetectFromStream(stream).Detected;
+ stream.Position = 0;
+
+ if (result != null)
{
- var text = await reader.ReadToEndAsync().ConfigureAwait(false);
+ _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, fileInfo.Path);
- bytes = Encoding.UTF8.GetBytes(text);
+ using var reader = new StreamReader(stream, result.Encoding);
+ var text = await reader.ReadToEndAsync().ConfigureAwait(false);
- return new MemoryStream(bytes);
+ return new MemoryStream(Encoding.UTF8.GetBytes(text));
}
}
}
- return File.OpenRead(path);
+ return AsyncFile.OpenRead(fileInfo.Path);
}
- private async Task<SubtitleInfo> GetReadableFile(
- string mediaPath,
- string[] inputFiles,
- MediaProtocol protocol,
+ internal async Task<SubtitleInfo> GetReadableFile(
+ MediaSourceInfo mediaSource,
MediaStream subtitleStream,
CancellationToken cancellationToken)
{
@@ -225,9 +206,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
string outputFormat;
string outputCodec;
- if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
{
// Extract
outputCodec = "copy";
@@ -247,9 +228,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
// Extract
- var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFormat);
- await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
+ await ExtractTextSubtitle(mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
.ConfigureAwait(false);
return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
@@ -258,64 +239,55 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
.TrimStart('.');
- if (GetReader(currentFormat, false) == null)
+ if (!TryGetReader(currentFormat, out _))
{
// Convert
- var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt");
- await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
+ await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
}
- return new SubtitleInfo(subtitleStream.Path, protocol, currentFormat, true);
- }
-
- private struct SubtitleInfo
- {
- public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
- {
- Path = path;
- Protocol = protocol;
- Format = format;
- IsExternal = isExternal;
- }
-
- public string Path { get; set; }
- public MediaProtocol Protocol { get; set; }
- public string Format { get; set; }
- public bool IsExternal { get; set; }
+ // It's possbile that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with local subs)
+ return new SubtitleInfo(subtitleStream.Path, _mediaSourceManager.GetPathProtocol(subtitleStream.Path), currentFormat, true);
}
- private ISubtitleParser GetReader(string format, bool throwIfMissing)
+ private bool TryGetReader(string format, [NotNullWhen(true)] out ISubtitleParser? value)
{
- if (string.IsNullOrEmpty(format))
- {
- throw new ArgumentNullException(nameof(format));
- }
-
if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
{
- return new SrtParser(_logger);
+ value = new SrtParser(_logger);
+ return true;
}
+
if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
{
- return new SsaParser();
+ value = new SsaParser(_logger);
+ return true;
}
+
if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
{
- return new AssParser();
+ value = new AssParser(_logger);
+ return true;
}
- if (throwIfMissing)
+ value = null;
+ return false;
+ }
+
+ private ISubtitleParser GetReader(string format)
+ {
+ if (TryGetReader(format, out var reader))
{
- throw new ArgumentException("Unsupported format: " + format);
+ return reader;
}
- return null;
+ throw new ArgumentException("Unsupported format: " + format);
}
- private ISubtitleWriter TryGetWriter(string format)
+ private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value)
{
if (string.IsNullOrEmpty(format))
{
@@ -324,29 +296,35 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
{
- return new JsonWriter(_json);
+ value = new JsonWriter();
+ return true;
}
+
if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
{
- return new SrtWriter();
+ value = new SrtWriter();
+ return true;
}
+
if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
{
- return new VttWriter();
+ value = new VttWriter();
+ return true;
}
+
if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
{
- return new TtmlWriter();
+ value = new TtmlWriter();
+ return true;
}
- return null;
+ value = null;
+ return false;
}
private ISubtitleWriter GetWriter(string format)
{
- var writer = TryGetWriter(format);
-
- if (writer != null)
+ if (TryGetWriter(format, out var writer))
{
return writer;
}
@@ -355,30 +333,25 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
/// <summary>
- /// The _semaphoreLocks
- /// </summary>
- private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
- new ConcurrentDictionary<string, SemaphoreSlim>();
-
- /// <summary>
/// Gets the lock.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.Object.</returns>
private SemaphoreSlim GetLock(string filename)
{
- return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
+ return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
}
/// <summary>
/// Converts the text subtitle to SRT.
/// </summary>
/// <param name="inputPath">The input path.</param>
- /// <param name="inputProtocol">The input protocol.</param>
+ /// <param name="language">The language.</param>
+ /// <param name="mediaSource">The input mediaSource.</param>
/// <param name="outputPath">The output path.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
+ private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
{
var semaphore = GetLock(outputPath);
@@ -388,7 +361,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
if (!File.Exists(outputPath))
{
- await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
+ await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
}
}
finally
@@ -401,16 +374,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// Converts the text subtitle to SRT internal.
/// </summary>
/// <param name="inputPath">The input path.</param>
- /// <param name="inputProtocol">The input protocol.</param>
+ /// <param name="language">The language.</param>
+ /// <param name="mediaSource">The input mediaSource.</param>
/// <param name="outputPath">The output path.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="ArgumentNullException">
- /// inputPath
- /// or
- /// outputPath
+ /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
/// </exception>
- private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
+ private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(inputPath))
{
@@ -422,58 +394,70 @@ namespace MediaBrowser.MediaEncoding.Subtitles
throw new ArgumentNullException(nameof(outputPath));
}
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
- var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
+ var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
- if (!string.IsNullOrEmpty(encodingParam))
+ // FFmpeg automatically convert character encoding when it is UTF-16
+ // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
+ if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
+ (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
+ encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
{
- encodingParam = " -sub_charenc " + encodingParam;
+ encodingParam = string.Empty;
}
-
- var process = _processFactory.Create(new ProcessOptions
- {
- CreateNoWindow = true,
- UseShellExecute = false,
- FileName = _mediaEncoder.EncoderPath,
- Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
- EnableRaisingEvents = true,
- IsHidden = true,
- ErrorDialog = false
- });
-
- _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
-
- try
+ else if (!string.IsNullOrEmpty(encodingParam))
{
- process.Start();
+ encodingParam = " -sub_charenc " + encodingParam;
}
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error starting ffmpeg");
- throw;
- }
+ int exitCode;
- var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
+ using (var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ FileName = _mediaEncoder.EncoderPath,
+ Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false
+ },
+ EnableRaisingEvents = true
+ })
+ {
+ _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
- if (!ranToCompletion)
- {
try
{
- _logger.LogInformation("Killing ffmpeg subtitle conversion process");
-
- process.Kill();
+ process.Start();
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error killing subtitle conversion process");
+ _logger.LogError(ex, "Error starting ffmpeg");
+
+ throw;
}
- }
- var exitCode = ranToCompletion ? process.ExitCode : -1;
+ var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
+
+ if (!ranToCompletion)
+ {
+ try
+ {
+ _logger.LogInformation("Killing ffmpeg subtitle conversion process");
+
+ process.Kill();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error killing subtitle conversion process");
+ }
+ }
- process.Dispose();
+ exitCode = ranToCompletion ? process.ExitCode : -1;
+ }
var failed = false;
@@ -501,13 +485,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (failed)
{
- var msg = string.Format("ffmpeg subtitle conversion failed for {Path}", inputPath);
-
- _logger.LogError(msg);
+ _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
- throw new Exception(msg);
+ throw new FfmpegException(
+ string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
}
- await SetAssFont(outputPath).ConfigureAwait(false);
+
+ await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
}
@@ -515,17 +499,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// <summary>
/// Extracts the text subtitle.
/// </summary>
- /// <param name="inputFiles">The input files.</param>
- /// <param name="protocol">The protocol.</param>
+ /// <param name="mediaSource">The mediaSource.</param>
/// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
/// <param name="outputCodec">The output codec.</param>
/// <param name="outputPath">The output path.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentException">Must use inputPath list overload</exception>
+ /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
private async Task ExtractTextSubtitle(
- string[] inputFiles,
- MediaProtocol protocol,
+ MediaSourceInfo mediaSource,
int subtitleStreamIndex,
string outputCodec,
string outputPath,
@@ -539,7 +521,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
if (!File.Exists(outputPath))
{
- await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
+ await ExtractTextSubtitleInternal(
+ _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource),
+ subtitleStreamIndex,
+ outputCodec,
+ outputPath,
+ cancellationToken).ConfigureAwait(false);
}
}
finally
@@ -565,54 +552,63 @@ namespace MediaBrowser.MediaEncoding.Subtitles
throw new ArgumentNullException(nameof(outputPath));
}
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
-
- var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
- subtitleStreamIndex, outputCodec, outputPath);
-
- var process = _processFactory.Create(new ProcessOptions
- {
- CreateNoWindow = true,
- UseShellExecute = false,
- EnableRaisingEvents = true,
- FileName = _mediaEncoder.EncoderPath,
- Arguments = processArgs,
- IsHidden = true,
- ErrorDialog = false
- });
-
- _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
- try
- {
- process.Start();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error starting ffmpeg");
+ var processArgs = string.Format(
+ CultureInfo.InvariantCulture,
+ "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
+ inputPath,
+ subtitleStreamIndex,
+ outputCodec,
+ outputPath);
- throw;
- }
+ int exitCode;
- var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
+ using (var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ FileName = _mediaEncoder.EncoderPath,
+ Arguments = processArgs,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false
+ },
+ EnableRaisingEvents = true
+ })
+ {
+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
- if (!ranToCompletion)
- {
try
{
- _logger.LogWarning("Killing ffmpeg subtitle extraction process");
-
- process.Kill();
+ process.Start();
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error killing subtitle extraction process");
+ _logger.LogError(ex, "Error starting ffmpeg");
+
+ throw;
}
- }
- var exitCode = ranToCompletion ? process.ExitCode : -1;
+ var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
+
+ if (!ranToCompletion)
+ {
+ try
+ {
+ _logger.LogWarning("Killing ffmpeg subtitle extraction process");
+
+ process.Kill();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error killing subtitle extraction process");
+ }
+ }
- process.Dispose();
+ exitCode = ranToCompletion ? process.ExitCode : -1;
+ }
var failed = false;
@@ -627,7 +623,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
catch (FileNotFoundException)
{
-
}
catch (IOException ex)
{
@@ -645,7 +640,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
_logger.LogError(msg);
- throw new Exception(msg);
+ throw new FfmpegException(msg);
}
else
{
@@ -656,7 +651,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
{
- await SetAssFont(outputPath).ConfigureAwait(false);
+ await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
}
}
@@ -664,15 +659,16 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// Sets the ass font.
/// </summary>
/// <param name="file">The file.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
/// <returns>Task.</returns>
- private async Task SetAssFont(string file)
+ private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
{
_logger.LogInformation("Setting ass font within {File}", file);
string text;
Encoding encoding;
- using (var fileStream = File.OpenRead(file))
+ using (var fileStream = AsyncFile.OpenRead(file))
using (var reader = new StreamReader(fileStream, true))
{
encoding = reader.CurrentEncoding;
@@ -680,77 +676,99 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = await reader.ReadToEndAsync().ConfigureAwait(false);
}
- var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
+ var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
- if (!string.Equals(text, newText))
+ if (!string.Equals(text, newText, StringComparison.Ordinal))
{
- using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous))
using (var writer = new StreamWriter(fileStream, encoding))
{
- writer.Write(newText);
+ await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
}
}
}
- private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
+ private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
{
- if (protocol == MediaProtocol.File)
+ if (mediaSource.Protocol == MediaProtocol.File)
{
var ticksParam = string.Empty;
- var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
+ var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path);
- var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
+ ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
- var prefix = filename.Substring(0, 1);
+ var prefix = filename.Slice(0, 1);
- return Path.Combine(SubtitleCachePath, prefix, filename);
+ return Path.Join(SubtitleCachePath, prefix, filename);
}
else
{
- var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
+ ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
- var prefix = filename.Substring(0, 1);
+ var prefix = filename.Slice(0, 1);
- return Path.Combine(SubtitleCachePath, prefix, filename);
+ return Path.Join(SubtitleCachePath, prefix, filename);
}
}
+ /// <inheritdoc />
public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
{
- var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
+ using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
+ {
+ var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName ?? string.Empty;
- var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
+ // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
+ if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
+ && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
+ {
+ charset = string.Empty;
+ }
- _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
+ _logger.LogDebug("charset {0} detected for {Path}", charset, path);
- return charset;
+ return charset;
+ }
}
- private async Task<byte[]> GetBytes(string path, MediaProtocol protocol, CancellationToken cancellationToken)
+ private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
{
- if (protocol == MediaProtocol.Http)
+ switch (protocol)
{
- var opts = new HttpRequestOptions()
- {
- Url = path,
- CancellationToken = cancellationToken
- };
- using (var file = await _httpClient.Get(opts).ConfigureAwait(false))
- using (var memoryStream = new MemoryStream())
+ case MediaProtocol.Http:
{
- await file.CopyToAsync(memoryStream).ConfigureAwait(false);
- memoryStream.Position = 0;
-
- return memoryStream.ToArray();
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .GetAsync(new Uri(path), cancellationToken)
+ .ConfigureAwait(false);
+ return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
}
+
+ case MediaProtocol.File:
+ return AsyncFile.OpenRead(path);
+ default:
+ throw new ArgumentOutOfRangeException(nameof(protocol));
}
- if (protocol == MediaProtocol.File)
+ }
+
+ internal readonly struct SubtitleInfo
+ {
+ public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
{
- return File.ReadAllBytes(path);
+ Path = path;
+ Protocol = protocol;
+ Format = format;
+ IsExternal = isExternal;
}
- throw new ArgumentOutOfRangeException(nameof(protocol));
+ public string Path { get; }
+
+ public MediaProtocol Protocol { get; }
+
+ public string Format { get; }
+
+ public bool IsExternal { get; }
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs
index cdaf94964..e5c785bc5 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs
@@ -1,4 +1,3 @@
-using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
@@ -7,8 +6,12 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.Subtitles
{
+ /// <summary>
+ /// TTML subtitle writer.
+ /// </summary>
public class TtmlWriter : ISubtitleWriter
{
+ /// <inheritdoc />
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
{
// Example: https://github.com/zmalltalker/ttml2vtt/blob/master/data/sample.xml
@@ -37,9 +40,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = Regex.Replace(text, @"\\n", "<br/>", RegexOptions.IgnoreCase);
- writer.WriteLine("<p begin=\"{0}\" dur=\"{1}\">{2}</p>",
+ writer.WriteLine(
+ "<p begin=\"{0}\" dur=\"{1}\">{2}</p>",
trackEvent.StartPositionTicks,
- (trackEvent.EndPositionTicks - trackEvent.StartPositionTicks),
+ trackEvent.EndPositionTicks - trackEvent.StartPositionTicks,
text);
}
@@ -49,12 +53,5 @@ namespace MediaBrowser.MediaEncoding.Subtitles
writer.WriteLine("</tt>");
}
}
-
- private string FormatTime(long ticks)
- {
- var time = TimeSpan.FromTicks(ticks);
-
- return string.Format(@"{0:hh\:mm\:ss\,fff}", time);
- }
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs
index 2e328ba63..6d56dda91 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs
@@ -7,14 +7,25 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.MediaEncoding.Subtitles
{
+ /// <summary>
+ /// Subtitle writer for the WebVTT format.
+ /// </summary>
public class VttWriter : ISubtitleWriter
{
+ /// <inheritdoc />
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
{
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
{
writer.WriteLine("WEBVTT");
- writer.WriteLine(string.Empty);
+ writer.WriteLine();
+ writer.WriteLine("REGION");
+ writer.WriteLine("id:subtitle");
+ writer.WriteLine("width:80%");
+ writer.WriteLine("lines:3");
+ writer.WriteLine("regionanchor:50%,100%");
+ writer.WriteLine("viewportanchor:50%,90%");
+ writer.WriteLine();
foreach (var trackEvent in info.TrackEvents)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -22,13 +33,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var startTime = TimeSpan.FromTicks(trackEvent.StartPositionTicks);
var endTime = TimeSpan.FromTicks(trackEvent.EndPositionTicks);
- // make sure the start and end times are different and seqential
+ // make sure the start and end times are different and sequential
if (endTime.TotalMilliseconds <= startTime.TotalMilliseconds)
{
endTime = startTime.Add(TimeSpan.FromMilliseconds(1));
}
- writer.WriteLine(@"{0:hh\:mm\:ss\.fff} --> {1:hh\:mm\:ss\.fff}", startTime, endTime);
+ writer.WriteLine(@"{0:hh\:mm\:ss\.fff} --> {1:hh\:mm\:ss\.fff} region:subtitle", startTime, endTime);
var text = trackEvent.Text;
@@ -36,7 +47,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = Regex.Replace(text, @"\\n", " ", RegexOptions.IgnoreCase);
writer.WriteLine(text);
- writer.WriteLine(string.Empty);
+ writer.WriteLine();
}
}
}
diff --git a/MediaBrowser.MediaEncoding/packages.config b/MediaBrowser.MediaEncoding/packages.config
deleted file mode 100644
index bbeaf5f00..000000000
--- a/MediaBrowser.MediaEncoding/packages.config
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<packages>
-</packages> \ No newline at end of file
diff --git a/MediaBrowser.Model/Activity/ActivityLogEntry.cs b/MediaBrowser.Model/Activity/ActivityLogEntry.cs
index 186fd89ee..f83dde56d 100644
--- a/MediaBrowser.Model/Activity/ActivityLogEntry.cs
+++ b/MediaBrowser.Model/Activity/ActivityLogEntry.cs
@@ -3,9 +3,25 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Model.Activity
{
+ /// <summary>
+ /// An activity log entry.
+ /// </summary>
public class ActivityLogEntry
{
/// <summary>
+ /// Initializes a new instance of the <see cref="ActivityLogEntry"/> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="userId">The user id.</param>
+ public ActivityLogEntry(string name, string type, Guid userId)
+ {
+ Name = name;
+ Type = type;
+ UserId = userId;
+ }
+
+ /// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
@@ -21,13 +37,13 @@ namespace MediaBrowser.Model.Activity
/// Gets or sets the overview.
/// </summary>
/// <value>The overview.</value>
- public string Overview { get; set; }
+ public string? Overview { get; set; }
/// <summary>
/// Gets or sets the short overview.
/// </summary>
/// <value>The short overview.</value>
- public string ShortOverview { get; set; }
+ public string? ShortOverview { get; set; }
/// <summary>
/// Gets or sets the type.
@@ -39,7 +55,7 @@ namespace MediaBrowser.Model.Activity
/// Gets or sets the item identifier.
/// </summary>
/// <value>The item identifier.</value>
- public string ItemId { get; set; }
+ public string? ItemId { get; set; }
/// <summary>
/// Gets or sets the date.
@@ -57,7 +73,8 @@ namespace MediaBrowser.Model.Activity
/// Gets or sets the user primary image tag.
/// </summary>
/// <value>The user primary image tag.</value>
- public string UserPrimaryImageTag { get; set; }
+ [Obsolete("UserPrimaryImageTag is not used.")]
+ public string? UserPrimaryImageTag { get; set; }
/// <summary>
/// Gets or sets the log severity.
diff --git a/MediaBrowser.Model/Activity/IActivityManager.cs b/MediaBrowser.Model/Activity/IActivityManager.cs
index 897d93d79..28073fb8d 100644
--- a/MediaBrowser.Model/Activity/IActivityManager.cs
+++ b/MediaBrowser.Model/Activity/IActivityManager.cs
@@ -1,5 +1,10 @@
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Events;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
using MediaBrowser.Model.Querying;
namespace MediaBrowser.Model.Activity
@@ -8,10 +13,15 @@ namespace MediaBrowser.Model.Activity
{
event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated;
- void Create(ActivityLogEntry entry);
+ Task CreateAsync(ActivityLog entry);
- QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit);
+ Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query);
- QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? x, int? y);
+ /// <summary>
+ /// Remove all activity logs before the specified date.
+ /// </summary>
+ /// <param name="startDate">Activity log start date.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ Task CleanAsync(DateTime startDate);
}
}
diff --git a/MediaBrowser.Model/Activity/IActivityRepository.cs b/MediaBrowser.Model/Activity/IActivityRepository.cs
deleted file mode 100644
index f0e3b902c..000000000
--- a/MediaBrowser.Model/Activity/IActivityRepository.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Model.Activity
-{
- public interface IActivityRepository
- {
- void Create(ActivityLogEntry entry);
-
- QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? z, int? startIndex, int? limit);
- }
-}
diff --git a/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs b/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs
index d1f3577f7..f9f474586 100644
--- a/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs
+++ b/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs
@@ -1,26 +1,43 @@
namespace MediaBrowser.Model.ApiClient
{
+ /// <summary>
+ /// The server discovery info model.
+ /// </summary>
public class ServerDiscoveryInfo
{
/// <summary>
- /// Gets or sets the address.
+ /// Initializes a new instance of the <see cref="ServerDiscoveryInfo"/> class.
/// </summary>
- /// <value>The address.</value>
- public string Address { get; set; }
+ /// <param name="address">The server address.</param>
+ /// <param name="id">The server id.</param>
+ /// <param name="name">The server name.</param>
+ /// <param name="endpointAddress">The endpoint address.</param>
+ public ServerDiscoveryInfo(string address, string id, string name, string? endpointAddress = null)
+ {
+ Address = address;
+ Id = id;
+ Name = name;
+ EndpointAddress = endpointAddress;
+ }
+
/// <summary>
- /// Gets or sets the server identifier.
+ /// Gets the address.
/// </summary>
- /// <value>The server identifier.</value>
- public string Id { get; set; }
+ public string Address { get; }
+
/// <summary>
- /// Gets or sets the name.
+ /// Gets the server identifier.
/// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
+ public string Id { get; }
+
/// <summary>
- /// Gets or sets the endpoint address.
+ /// Gets the name.
/// </summary>
- /// <value>The endpoint address.</value>
- public string EndpointAddress { get; set; }
+ public string Name { get; }
+
+ /// <summary>
+ /// Gets the endpoint address.
+ /// </summary>
+ public string? EndpointAddress { get; }
}
}
diff --git a/MediaBrowser.Model/Branding/BrandingOptions.cs b/MediaBrowser.Model/Branding/BrandingOptions.cs
index f83558df5..7f19a5b85 100644
--- a/MediaBrowser.Model/Branding/BrandingOptions.cs
+++ b/MediaBrowser.Model/Branding/BrandingOptions.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Branding
{
public class BrandingOptions
@@ -6,11 +8,12 @@ namespace MediaBrowser.Model.Branding
/// Gets or sets the login disclaimer.
/// </summary>
/// <value>The login disclaimer.</value>
- public string LoginDisclaimer { get; set; }
+ public string? LoginDisclaimer { get; set; }
+
/// <summary>
/// Gets or sets the custom CSS.
/// </summary>
/// <value>The custom CSS.</value>
- public string CustomCss { get; set; }
+ public string? CustomCss { get; set; }
}
}
diff --git a/MediaBrowser.Model/Channels/ChannelFeatures.cs b/MediaBrowser.Model/Channels/ChannelFeatures.cs
index ee1d11bc0..1ca8e80a6 100644
--- a/MediaBrowser.Model/Channels/ChannelFeatures.cs
+++ b/MediaBrowser.Model/Channels/ChannelFeatures.cs
@@ -1,9 +1,21 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Channels
{
public class ChannelFeatures
{
+ public ChannelFeatures(string name, Guid id)
+ {
+ MediaTypes = Array.Empty<ChannelMediaType>();
+ ContentTypes = Array.Empty<ChannelMediaContentType>();
+ DefaultSortFields = Array.Empty<ChannelItemSortField>();
+
+ Name = name;
+ Id = id;
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
@@ -14,7 +26,7 @@ namespace MediaBrowser.Model.Channels
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
- public string Id { get; set; }
+ public Guid Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance can search.
@@ -35,7 +47,7 @@ namespace MediaBrowser.Model.Channels
public ChannelMediaContentType[] ContentTypes { get; set; }
/// <summary>
- /// Represents the maximum number of records the channel allows retrieving at a time
+ /// Gets or sets the maximum number of records the channel allows retrieving at a time.
/// </summary>
public int? MaxPageSize { get; set; }
@@ -52,7 +64,7 @@ namespace MediaBrowser.Model.Channels
public ChannelItemSortField[] DefaultSortFields { get; set; }
/// <summary>
- /// Indicates if a sort ascending/descending toggle is supported or not.
+ /// Gets or sets a value indicating whether a sort ascending/descending toggle is supported.
/// </summary>
public bool SupportsSortOrderToggle { get; set; }
@@ -73,12 +85,5 @@ namespace MediaBrowser.Model.Channels
/// </summary>
/// <value><c>true</c> if [supports content downloading]; otherwise, <c>false</c>.</value>
public bool SupportsContentDownloading { get; set; }
-
- public ChannelFeatures()
- {
- MediaTypes = Array.Empty<ChannelMediaType>();
- ContentTypes = Array.Empty<ChannelMediaContentType>();
- DefaultSortFields = Array.Empty<ChannelItemSortField>();
- }
}
}
diff --git a/MediaBrowser.Model/Channels/ChannelFolderType.cs b/MediaBrowser.Model/Channels/ChannelFolderType.cs
index 6039eb929..9ead74261 100644
--- a/MediaBrowser.Model/Channels/ChannelFolderType.cs
+++ b/MediaBrowser.Model/Channels/ChannelFolderType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Channels
{
public enum ChannelFolderType
diff --git a/MediaBrowser.Model/Channels/ChannelInfo.cs b/MediaBrowser.Model/Channels/ChannelInfo.cs
deleted file mode 100644
index 9b2d31bf3..000000000
--- a/MediaBrowser.Model/Channels/ChannelInfo.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-namespace MediaBrowser.Model.Channels
-{
- public class ChannelInfo
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the identifier.
- /// </summary>
- /// <value>The identifier.</value>
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the home page URL.
- /// </summary>
- /// <value>The home page URL.</value>
- public string HomePageUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the features.
- /// </summary>
- /// <value>The features.</value>
- public ChannelFeatures Features { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Channels/ChannelItemSortField.cs b/MediaBrowser.Model/Channels/ChannelItemSortField.cs
index af75e3edd..2c88e99af 100644
--- a/MediaBrowser.Model/Channels/ChannelItemSortField.cs
+++ b/MediaBrowser.Model/Channels/ChannelItemSortField.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Channels
{
public enum ChannelItemSortField
diff --git a/MediaBrowser.Model/Channels/ChannelMediaContentType.cs b/MediaBrowser.Model/Channels/ChannelMediaContentType.cs
index fc7c21706..61afcbc56 100644
--- a/MediaBrowser.Model/Channels/ChannelMediaContentType.cs
+++ b/MediaBrowser.Model/Channels/ChannelMediaContentType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Channels
{
public enum ChannelMediaContentType
diff --git a/MediaBrowser.Model/Channels/ChannelMediaType.cs b/MediaBrowser.Model/Channels/ChannelMediaType.cs
index a3fa5cdf9..ba2c06d1b 100644
--- a/MediaBrowser.Model/Channels/ChannelMediaType.cs
+++ b/MediaBrowser.Model/Channels/ChannelMediaType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Channels
{
public enum ChannelMediaType
diff --git a/MediaBrowser.Model/Channels/ChannelQuery.cs b/MediaBrowser.Model/Channels/ChannelQuery.cs
index 32b368922..f9380ce3a 100644
--- a/MediaBrowser.Model/Channels/ChannelQuery.cs
+++ b/MediaBrowser.Model/Channels/ChannelQuery.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
@@ -7,13 +9,16 @@ namespace MediaBrowser.Model.Channels
public class ChannelQuery
{
/// <summary>
- /// Fields to return within the items, in addition to basic information
+ /// Gets or sets the fields to return within the items, in addition to basic information.
/// </summary>
/// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
+ public ItemFields[]? Fields { get; set; }
+
public bool? EnableImages { get; set; }
+
public int? ImageTypeLimit { get; set; }
- public ImageType[] EnableImageTypes { get; set; }
+
+ public ImageType[]? EnableImageTypes { get; set; }
/// <summary>
/// Gets or sets the user identifier.
@@ -22,13 +27,13 @@ namespace MediaBrowser.Model.Channels
public Guid UserId { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Use for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
@@ -46,7 +51,9 @@ namespace MediaBrowser.Model.Channels
/// </summary>
/// <value><c>null</c> if [is favorite] contains no value, <c>true</c> if [is favorite]; otherwise, <c>false</c>.</value>
public bool? IsFavorite { get; set; }
+
public bool? IsRecordingsFolder { get; set; }
+
public bool RefreshLatestChannelItems { get; set; }
}
}
diff --git a/MediaBrowser.Model/Collections/CollectionCreationResult.cs b/MediaBrowser.Model/Collections/CollectionCreationResult.cs
index 2691f7970..2f1d903a5 100644
--- a/MediaBrowser.Model/Collections/CollectionCreationResult.cs
+++ b/MediaBrowser.Model/Collections/CollectionCreationResult.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Collections
diff --git a/MediaBrowser.Model/Configuration/AccessSchedule.cs b/MediaBrowser.Model/Configuration/AccessSchedule.cs
deleted file mode 100644
index d34e27383..000000000
--- a/MediaBrowser.Model/Configuration/AccessSchedule.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace MediaBrowser.Model.Configuration
-{
- public class AccessSchedule
- {
- /// <summary>
- /// Gets or sets the day of week.
- /// </summary>
- /// <value>The day of week.</value>
- public DynamicDayOfWeek DayOfWeek { get; set; }
- /// <summary>
- /// Gets or sets the start hour.
- /// </summary>
- /// <value>The start hour.</value>
- public double StartHour { get; set; }
- /// <summary>
- /// Gets or sets the end hour.
- /// </summary>
- /// <value>The end hour.</value>
- public double EndHour { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
index 6a1a0f090..57759a7d3 100644
--- a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
@@ -1,3 +1,6 @@
+using System;
+using System.Xml.Serialization;
+
namespace MediaBrowser.Model.Configuration
{
/// <summary>
@@ -8,7 +11,15 @@ namespace MediaBrowser.Model.Configuration
public class BaseApplicationConfiguration
{
/// <summary>
- /// The number of days we should retain log files
+ /// Initializes a new instance of the <see cref="BaseApplicationConfiguration" /> class.
+ /// </summary>
+ public BaseApplicationConfiguration()
+ {
+ LogFileRetentionDays = 3;
+ }
+
+ /// <summary>
+ /// Gets or sets the number of days we should retain log files.
/// </summary>
/// <value>The log file retention days.</value>
public int LogFileRetentionDays { get; set; }
@@ -23,14 +34,30 @@ namespace MediaBrowser.Model.Configuration
/// Gets or sets the cache path.
/// </summary>
/// <value>The cache path.</value>
- public string CachePath { get; set; }
+ public string? CachePath { get; set; }
/// <summary>
- /// Initializes a new instance of the <see cref="BaseApplicationConfiguration" /> class.
+ /// Gets or sets the last known version that was ran using the configuration.
/// </summary>
- public BaseApplicationConfiguration()
+ /// <value>The version from previous run.</value>
+ [XmlIgnore]
+ public Version? PreviousVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets the stringified PreviousVersion to be stored/loaded,
+ /// because System.Version itself isn't xml-serializable.
+ /// </summary>
+ /// <value>String value of PreviousVersion.</value>
+ public string? PreviousVersionStr
{
- LogFileRetentionDays = 3;
+ get => PreviousVersion?.ToString();
+ set
+ {
+ if (Version.TryParse(value, out var version))
+ {
+ PreviousVersion = version;
+ }
+ }
}
}
}
diff --git a/MediaBrowser.Model/Configuration/DynamicDayOfWeek.cs b/MediaBrowser.Model/Configuration/DynamicDayOfWeek.cs
deleted file mode 100644
index 73dda5a77..000000000
--- a/MediaBrowser.Model/Configuration/DynamicDayOfWeek.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace MediaBrowser.Model.Configuration
-{
- public enum DynamicDayOfWeek
- {
- Sunday = 0,
- Monday = 1,
- Tuesday = 2,
- Wednesday = 3,
- Thursday = 4,
- Friday = 5,
- Saturday = 6,
- Everyday = 7,
- Weekday = 8,
- Weekend = 9
- }
-}
diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs
index 8584bd3dd..365bbeef6 100644
--- a/MediaBrowser.Model/Configuration/EncodingOptions.cs
+++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs
@@ -1,35 +1,115 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
public class EncodingOptions
{
+ public EncodingOptions()
+ {
+ EnableFallbackFont = false;
+ DownMixAudioBoost = 2;
+ MaxMuxingQueueSize = 2048;
+ EnableThrottling = false;
+ ThrottleDelaySeconds = 180;
+ EncodingThreadCount = -1;
+ // This is a DRM device that is almost guaranteed to be there on every intel platform,
+ // plus it's the default one in ffmpeg if you don't specify anything
+ VaapiDevice = "/dev/dri/renderD128";
+ // This is the OpenCL device that is used for tonemapping.
+ // The left side of the dot is the platform number, and the right side is the device number on the platform.
+ OpenclDevice = "0.0";
+ EnableTonemapping = false;
+ EnableVppTonemapping = false;
+ TonemappingAlgorithm = "hable";
+ TonemappingRange = "auto";
+ TonemappingDesat = 0;
+ TonemappingThreshold = 0.8;
+ TonemappingPeak = 100;
+ TonemappingParam = 0;
+ H264Crf = 23;
+ H265Crf = 28;
+ DeinterlaceDoubleRate = false;
+ DeinterlaceMethod = "yadif";
+ EnableDecodingColorDepth10Hevc = true;
+ EnableDecodingColorDepth10Vp9 = true;
+ EnableEnhancedNvdecDecoder = true;
+ EnableHardwareEncoding = true;
+ AllowHevcEncoding = false;
+ EnableSubtitleExtraction = true;
+ HardwareDecodingCodecs = new string[] { "h264", "vc1" };
+ }
+
public int EncodingThreadCount { get; set; }
+
public string TranscodingTempPath { get; set; }
+
+ public string FallbackFontPath { get; set; }
+
+ public bool EnableFallbackFont { get; set; }
+
public double DownMixAudioBoost { get; set; }
+
+ public int MaxMuxingQueueSize { get; set; }
+
public bool EnableThrottling { get; set; }
+
public int ThrottleDelaySeconds { get; set; }
+
public string HardwareAccelerationType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the FFmpeg path as set by the user via the UI.
+ /// </summary>
public string EncoderAppPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current FFmpeg path being used by the system and displayed on the transcode page.
+ /// </summary>
+ public string EncoderAppPathDisplay { get; set; }
+
public string VaapiDevice { get; set; }
+
+ public string OpenclDevice { get; set; }
+
+ public bool EnableTonemapping { get; set; }
+
+ public bool EnableVppTonemapping { get; set; }
+
+ public string TonemappingAlgorithm { get; set; }
+
+ public string TonemappingRange { get; set; }
+
+ public double TonemappingDesat { get; set; }
+
+ public double TonemappingThreshold { get; set; }
+
+ public double TonemappingPeak { get; set; }
+
+ public double TonemappingParam { get; set; }
+
public int H264Crf { get; set; }
- public string H264Preset { get; set; }
+
+ public int H265Crf { get; set; }
+
+ public string EncoderPreset { get; set; }
+
+ public bool DeinterlaceDoubleRate { get; set; }
+
public string DeinterlaceMethod { get; set; }
+
+ public bool EnableDecodingColorDepth10Hevc { get; set; }
+
+ public bool EnableDecodingColorDepth10Vp9 { get; set; }
+
+ public bool EnableEnhancedNvdecDecoder { get; set; }
+
public bool EnableHardwareEncoding { get; set; }
+
+ public bool AllowHevcEncoding { get; set; }
+
public bool EnableSubtitleExtraction { get; set; }
public string[] HardwareDecodingCodecs { get; set; }
-
- public EncodingOptions()
- {
- DownMixAudioBoost = 2;
- EnableThrottling = true;
- ThrottleDelaySeconds = 180;
- EncodingThreadCount = -1;
- // This is a DRM device that is almost guaranteed to be there on every intel platform, plus it's the default one in ffmpeg if you don't specify anything
- VaapiDevice = "/dev/dri/renderD128";
- H264Crf = 23;
- EnableHardwareEncoding = true;
- EnableSubtitleExtraction = true;
- HardwareDecodingCodecs = new string[] { "h264", "vc1" };
- }
}
}
diff --git a/MediaBrowser.Model/Configuration/FanartOptions.cs b/MediaBrowser.Model/Configuration/FanartOptions.cs
deleted file mode 100644
index 9c8be39be..000000000
--- a/MediaBrowser.Model/Configuration/FanartOptions.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace MediaBrowser.Model.Configuration
-{
- public class FanartOptions
- {
- /// <summary>
- /// Gets or sets the user API key.
- /// </summary>
- /// <value>The user API key.</value>
- public string UserApiKey { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Configuration/ImageOption.cs b/MediaBrowser.Model/Configuration/ImageOption.cs
index 3b985bb1b..0af7b7e14 100644
--- a/MediaBrowser.Model/Configuration/ImageOption.cs
+++ b/MediaBrowser.Model/Configuration/ImageOption.cs
@@ -1,14 +1,22 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Configuration
{
public class ImageOption
{
+ public ImageOption()
+ {
+ Limit = 1;
+ }
+
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public ImageType Type { get; set; }
+
/// <summary>
/// Gets or sets the limit.
/// </summary>
@@ -20,10 +28,5 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
/// <value>The minimum width.</value>
public int MinWidth { get; set; }
-
- public ImageOption()
- {
- Limit = 1;
- }
}
}
diff --git a/MediaBrowser.Model/Configuration/ImageSavingConvention.cs b/MediaBrowser.Model/Configuration/ImageSavingConvention.cs
index 7206fa5fc..485a4d2f8 100644
--- a/MediaBrowser.Model/Configuration/ImageSavingConvention.cs
+++ b/MediaBrowser.Model/Configuration/ImageSavingConvention.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
public enum ImageSavingConvention
diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs
index ba33bee87..aae5359b1 100644
--- a/MediaBrowser.Model/Configuration/LibraryOptions.cs
+++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs
@@ -1,67 +1,11 @@
+#pragma warning disable CS1591
+
using System;
-using System.Collections.Generic;
-using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Configuration
{
public class LibraryOptions
{
- public bool EnablePhotos { get; set; }
- public bool EnableRealtimeMonitor { get; set; }
- public bool EnableChapterImageExtraction { get; set; }
- public bool ExtractChapterImagesDuringLibraryScan { get; set; }
- public bool DownloadImagesInAdvance { get; set; }
- public MediaPathInfo[] PathInfos { get; set; }
-
- public bool SaveLocalMetadata { get; set; }
- public bool EnableInternetProviders { get; set; }
- public bool ImportMissingEpisodes { get; set; }
- public bool EnableAutomaticSeriesGrouping { get; set; }
- public bool EnableEmbeddedTitles { get; set; }
-
- public int AutomaticRefreshIntervalDays { get; set; }
-
- /// <summary>
- /// Gets or sets the preferred metadata language.
- /// </summary>
- /// <value>The preferred metadata language.</value>
- public string PreferredMetadataLanguage { get; set; }
-
- /// <summary>
- /// Gets or sets the metadata country code.
- /// </summary>
- /// <value>The metadata country code.</value>
- public string MetadataCountryCode { get; set; }
-
- public string SeasonZeroDisplayName { get; set; }
- public string[] MetadataSavers { get; set; }
- public string[] DisabledLocalMetadataReaders { get; set; }
- public string[] LocalMetadataReaderOrder { get; set; }
-
- public string[] DisabledSubtitleFetchers { get; set; }
- public string[] SubtitleFetcherOrder { get; set; }
-
- public bool SkipSubtitlesIfEmbeddedSubtitlesPresent { get; set; }
- public bool SkipSubtitlesIfAudioTrackMatches { get; set; }
- public string[] SubtitleDownloadLanguages { get; set; }
- public bool RequirePerfectSubtitleMatch { get; set; }
- public bool SaveSubtitlesWithMedia { get; set; }
-
- public TypeOptions[] TypeOptions { get; set; }
-
- public TypeOptions GetTypeOptions(string type)
- {
- foreach (var options in TypeOptions)
- {
- if (string.Equals(options.Type, type, StringComparison.OrdinalIgnoreCase))
- {
- return options;
- }
- }
-
- return null;
- }
-
public LibraryOptions()
{
TypeOptions = Array.Empty<TypeOptions>();
@@ -80,363 +24,76 @@ namespace MediaBrowser.Model.Configuration
EnableAutomaticSeriesGrouping = true;
SeasonZeroDisplayName = "Specials";
}
- }
-
- public class MediaPathInfo
- {
- public string Path { get; set; }
- public string NetworkPath { get; set; }
- }
-
- public class TypeOptions
- {
- public string Type { get; set; }
- public string[] MetadataFetchers { get; set; }
- public string[] MetadataFetcherOrder { get; set; }
-
- public string[] ImageFetchers { get; set; }
- public string[] ImageFetcherOrder { get; set; }
- public ImageOption[] ImageOptions { get; set; }
-
- public ImageOption GetImageOptions(ImageType type)
- {
- foreach (var i in ImageOptions)
- {
- if (i.Type == type)
- {
- return i;
- }
- }
-
- if (DefaultImageOptions.TryGetValue(Type, out ImageOption[] options))
- {
- foreach (var i in options)
- {
- if (i.Type == type)
- {
- return i;
- }
- }
- }
-
- return DefaultInstance;
- }
-
- public int GetLimit(ImageType type)
- {
- return GetImageOptions(type).Limit;
- }
-
- public int GetMinWidth(ImageType type)
- {
- return GetImageOptions(type).MinWidth;
- }
-
- public bool IsEnabled(ImageType type)
- {
- return GetLimit(type) > 0;
- }
-
- public TypeOptions()
- {
- MetadataFetchers = Array.Empty<string>();
- MetadataFetcherOrder = Array.Empty<string>();
- ImageFetchers = Array.Empty<string>();
- ImageFetcherOrder = Array.Empty<string>();
- ImageOptions = Array.Empty<ImageOption>();
- }
-
- public static Dictionary<string, ImageOption[]> DefaultImageOptions = new Dictionary<string, ImageOption[]>
- {
- {
- "Movie", new []
- {
- new ImageOption
- {
- Limit = 1,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
-
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Art
- },
-
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Disc
- },
-
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- },
-
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Banner
- },
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Thumb
- },
+ public bool EnablePhotos { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Logo
- }
- }
- },
- {
- "MusicVideo", new []
- {
- new ImageOption
- {
- Limit = 1,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ public bool EnableRealtimeMonitor { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Art
- },
+ public bool EnableChapterImageExtraction { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Disc
- },
+ public bool ExtractChapterImagesDuringLibraryScan { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- },
+ public MediaPathInfo[] PathInfos { get; set; }
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Banner
- },
+ public bool SaveLocalMetadata { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Thumb
- },
+ public bool EnableInternetProviders { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Logo
- }
- }
- },
- {
- "Series", new []
- {
- new ImageOption
- {
- Limit = 1,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ public bool EnableAutomaticSeriesGrouping { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Art
- },
+ public bool EnableEmbeddedTitles { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- },
+ public bool EnableEmbeddedEpisodeInfos { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Banner
- },
+ public int AutomaticRefreshIntervalDays { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Thumb
- },
+ /// <summary>
+ /// Gets or sets the preferred metadata language.
+ /// </summary>
+ /// <value>The preferred metadata language.</value>
+ public string? PreferredMetadataLanguage { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Logo
- }
- }
- },
- {
- "MusicAlbum", new []
- {
- new ImageOption
- {
- Limit = 0,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ /// <summary>
+ /// Gets or sets the metadata country code.
+ /// </summary>
+ /// <value>The metadata country code.</value>
+ public string? MetadataCountryCode { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Disc
- }
- }
- },
- {
- "MusicArtist", new []
- {
- new ImageOption
- {
- Limit = 1,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ public string SeasonZeroDisplayName { get; set; }
- // Don't download this by default
- // They do look great, but most artists won't have them, which means a banner view isn't really possible
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Banner
- },
+ public string[]? MetadataSavers { get; set; }
- // Don't download this by default
- // Generally not used
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Art
- },
+ public string[] DisabledLocalMetadataReaders { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Logo
- }
- }
- },
- {
- "BoxSet", new []
- {
- new ImageOption
- {
- Limit = 1,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ public string[]? LocalMetadataReaderOrder { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- },
+ public string[] DisabledSubtitleFetchers { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Thumb
- },
+ public string[] SubtitleFetcherOrder { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Logo
- },
+ public bool SkipSubtitlesIfEmbeddedSubtitlesPresent { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Art
- },
+ public bool SkipSubtitlesIfAudioTrackMatches { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Disc
- },
+ public string[]? SubtitleDownloadLanguages { get; set; }
- // Don't download this by default as it's rarely used.
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Banner
- }
- }
- },
- {
- "Season", new []
- {
- new ImageOption
- {
- Limit = 0,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
+ public bool RequirePerfectSubtitleMatch { get; set; }
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- },
+ public bool SaveSubtitlesWithMedia { get; set; }
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Banner
- },
+ public TypeOptions[] TypeOptions { get; set; }
- new ImageOption
- {
- Limit = 0,
- Type = ImageType.Thumb
- }
- }
- },
+ public TypeOptions? GetTypeOptions(string type)
+ {
+ foreach (var options in TypeOptions)
{
- "Episode", new []
+ if (string.Equals(options.Type, type, StringComparison.OrdinalIgnoreCase))
{
- new ImageOption
- {
- Limit = 0,
- MinWidth = 1280,
- Type = ImageType.Backdrop
- },
-
- new ImageOption
- {
- Limit = 1,
- Type = ImageType.Primary
- }
+ return options;
}
}
- };
- public static ImageOption DefaultInstance = new ImageOption();
+ return null;
+ }
}
}
diff --git a/MediaBrowser.Model/Configuration/MediaPathInfo.cs b/MediaBrowser.Model/Configuration/MediaPathInfo.cs
new file mode 100644
index 000000000..a7bc43590
--- /dev/null
+++ b/MediaBrowser.Model/Configuration/MediaPathInfo.cs
@@ -0,0 +1,22 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Configuration
+{
+ public class MediaPathInfo
+ {
+ public MediaPathInfo(string path)
+ {
+ Path = path;
+ }
+
+ // Needed for xml serialization
+ public MediaPathInfo()
+ {
+ Path = string.Empty;
+ }
+
+ public string Path { get; set; }
+
+ public string? NetworkPath { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Configuration/MetadataConfiguration.cs b/MediaBrowser.Model/Configuration/MetadataConfiguration.cs
index 87e02d054..be044243d 100644
--- a/MediaBrowser.Model/Configuration/MetadataConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/MetadataConfiguration.cs
@@ -1,12 +1,14 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
public class MetadataConfiguration
{
- public bool UseFileCreationTimeForDateAdded { get; set; }
-
public MetadataConfiguration()
{
UseFileCreationTimeForDateAdded = true;
}
+
+ public bool UseFileCreationTimeForDateAdded { get; set; }
}
}
diff --git a/MediaBrowser.Model/Configuration/MetadataOptions.cs b/MediaBrowser.Model/Configuration/MetadataOptions.cs
index c095b8cdd..384a7997f 100644
--- a/MediaBrowser.Model/Configuration/MetadataOptions.cs
+++ b/MediaBrowser.Model/Configuration/MetadataOptions.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591, CA1819
+
using System;
namespace MediaBrowser.Model.Configuration
@@ -7,25 +10,28 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
public class MetadataOptions
{
+ public MetadataOptions()
+ {
+ DisabledMetadataSavers = Array.Empty<string>();
+ LocalMetadataReaderOrder = Array.Empty<string>();
+ DisabledMetadataFetchers = Array.Empty<string>();
+ MetadataFetcherOrder = Array.Empty<string>();
+ DisabledImageFetchers = Array.Empty<string>();
+ ImageFetcherOrder = Array.Empty<string>();
+ }
+
public string ItemType { get; set; }
public string[] DisabledMetadataSavers { get; set; }
+
public string[] LocalMetadataReaderOrder { get; set; }
public string[] DisabledMetadataFetchers { get; set; }
+
public string[] MetadataFetcherOrder { get; set; }
public string[] DisabledImageFetchers { get; set; }
- public string[] ImageFetcherOrder { get; set; }
- public MetadataOptions()
- {
- DisabledMetadataSavers = Array.Empty<string>();
- LocalMetadataReaderOrder = Array.Empty<string>();
- DisabledMetadataFetchers = Array.Empty<string>();
- MetadataFetcherOrder = Array.Empty<string>();
- DisabledImageFetchers = Array.Empty<string>();
- ImageFetcherOrder = Array.Empty<string>();
- }
+ public string[] ImageFetcherOrder { get; set; }
}
}
diff --git a/MediaBrowser.Model/Configuration/MetadataPlugin.cs b/MediaBrowser.Model/Configuration/MetadataPlugin.cs
index d6f863e55..db8cd1875 100644
--- a/MediaBrowser.Model/Configuration/MetadataPlugin.cs
+++ b/MediaBrowser.Model/Configuration/MetadataPlugin.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
public class MetadataPlugin
diff --git a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
index 0bd20f837..aa07d6623 100644
--- a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
+++ b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
@@ -5,6 +8,12 @@ namespace MediaBrowser.Model.Configuration
{
public class MetadataPluginSummary
{
+ public MetadataPluginSummary()
+ {
+ SupportedImageTypes = Array.Empty<ImageType>();
+ Plugins = Array.Empty<MetadataPlugin>();
+ }
+
/// <summary>
/// Gets or sets the type of the item.
/// </summary>
@@ -22,11 +31,5 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
/// <value>The supported image types.</value>
public ImageType[] SupportedImageTypes { get; set; }
-
- public MetadataPluginSummary()
- {
- SupportedImageTypes = Array.Empty<ImageType>();
- Plugins = Array.Empty<MetadataPlugin>();
- }
}
}
diff --git a/MediaBrowser.Model/Configuration/MetadataPluginType.cs b/MediaBrowser.Model/Configuration/MetadataPluginType.cs
index 985107ac9..4c5e95266 100644
--- a/MediaBrowser.Model/Configuration/MetadataPluginType.cs
+++ b/MediaBrowser.Model/Configuration/MetadataPluginType.cs
@@ -1,7 +1,9 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
/// <summary>
- /// Enum MetadataPluginType
+ /// Enum MetadataPluginType.
/// </summary>
public enum MetadataPluginType
{
diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs
new file mode 100644
index 000000000..2c9b5f005
--- /dev/null
+++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Model.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="PathSubstitution" />.
+ /// </summary>
+ public class PathSubstitution
+ {
+ /// <summary>
+ /// Gets or sets the value to substitute.
+ /// </summary>
+ public string From { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the value to substitution with.
+ /// </summary>
+ public string To { get; set; } = string.Empty;
+ }
+}
diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
index ed5800329..d1e999666 100644
--- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
@@ -1,5 +1,10 @@
+#pragma warning disable CS1591
+#pragma warning disable CA1819
+
using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Updates;
namespace MediaBrowser.Model.Configuration
{
@@ -8,52 +13,210 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
public class ServerConfiguration : BaseApplicationConfiguration
{
+ /// <summary>
+ /// The default value for <see cref="HttpServerPortNumber"/>.
+ /// </summary>
public const int DefaultHttpPort = 8096;
+
+ /// <summary>
+ /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>.
+ /// </summary>
public const int DefaultHttpsPort = 8920;
+ private string _baseUrl = string.Empty;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
+ /// </summary>
+ public ServerConfiguration()
+ {
+ MetadataOptions = new[]
+ {
+ new MetadataOptions()
+ {
+ ItemType = "Book"
+ },
+ new MetadataOptions()
+ {
+ ItemType = "Movie"
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicVideo",
+ DisabledMetadataFetchers = new[] { "The Open Movie Database" },
+ DisabledImageFetchers = new[] { "The Open Movie Database" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "Series",
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicAlbum",
+ DisabledMetadataFetchers = new[] { "TheAudioDB" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicArtist",
+ DisabledMetadataFetchers = new[] { "TheAudioDB" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "BoxSet"
+ },
+ new MetadataOptions
+ {
+ ItemType = "Season",
+ },
+ new MetadataOptions
+ {
+ ItemType = "Episode",
+ }
+ };
+ }
+
/// <summary>
- /// Gets or sets a value indicating whether [enable u pn p].
+ /// Gets or sets a value indicating whether to enable automatic port forwarding.
/// </summary>
- /// <value><c>true</c> if [enable u pn p]; otherwise, <c>false</c>.</value>
- public bool EnableUPnP { get; set; }
+ public bool EnableUPnP { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable prometheus metrics exporting.
+ /// </summary>
+ public bool EnableMetrics { get; set; } = false;
/// <summary>
/// Gets or sets the public mapped port.
/// </summary>
/// <value>The public mapped port.</value>
- public int PublicPort { get; set; }
+ public int PublicPort { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
+ /// </summary>
+ public bool UPnPCreateHttpPortMap { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets client udp port range.
+ /// </summary>
+ public string UDPPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IPV6 capability is enabled.
+ /// </summary>
+ public bool EnableIPV6 { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IPV4 capability is enabled.
+ /// </summary>
+ public bool EnableIPV4 { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log.
+ /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.
+ /// </summary>
+ public bool EnableSSDPTracing { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
+ /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public string SSDPTracingFilter { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the number of times SSDP UDP messages are sent.
+ /// </summary>
+ public int UDPSendCount { get; set; } = 2;
+
+ /// <summary>
+ /// Gets or sets the delay between each groups of SSDP messages (in ms).
+ /// </summary>
+ public int UDPSendDelay { get; set; } = 100;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
+ /// </summary>
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
+ /// </summary>
+ public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+
+ /// <summary>
+ /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
+ /// </summary>
+ public int GatewayMonitorPeriod { get; set; } = 60;
+
+ /// <summary>
+ /// Gets a value indicating whether multi-socket binding is available.
+ /// </summary>
+ public bool EnableMultiSocketBinding { get; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
+ /// Depending on the address range implemented ULA ranges might not be used.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets the ports that HDHomerun uses.
+ /// </summary>
+ public string HDHomerunPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ /// </summary>
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
+ /// </summary>
+ public bool AutoDiscoveryTracing { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery is enabled.
+ /// </summary>
+ public bool AutoDiscovery { get; set; } = true;
/// <summary>
/// Gets or sets the public HTTPS port.
/// </summary>
/// <value>The public HTTPS port.</value>
- public int PublicHttpsPort { get; set; }
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
/// <summary>
/// Gets or sets the HTTP server port number.
/// </summary>
/// <value>The HTTP server port number.</value>
- public int HttpServerPortNumber { get; set; }
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
/// <summary>
/// Gets or sets the HTTPS server port number.
/// </summary>
/// <value>The HTTPS server port number.</value>
- public int HttpsPortNumber { get; set; }
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
/// <summary>
- /// Gets or sets a value indicating whether [use HTTPS].
+ /// Gets or sets a value indicating whether to use HTTPS.
/// </summary>
- /// <value><c>true</c> if [use HTTPS]; otherwise, <c>false</c>.</value>
- public bool EnableHttps { get; set; }
- public bool EnableNormalizedItemByNameIds { get; set; }
+ /// <remarks>
+ /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be
+ /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>.
+ /// </remarks>
+ public bool EnableHttps { get; set; } = false;
+
+ public bool EnableNormalizedItemByNameIds { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
+ /// </summary>
+ public string CertificatePath { get; set; } = string.Empty;
/// <summary>
- /// Gets or sets the value pointing to the file system where the ssl certiifcate is located..
+ /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
/// </summary>
- /// <value>The value pointing to the file system where the ssl certiifcate is located..</value>
- public string CertificatePath { get; set; }
- public string CertificatePassword { get; set; }
+ public string CertificatePassword { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether this instance is port authorized.
@@ -61,94 +224,106 @@ namespace MediaBrowser.Model.Configuration
/// <value><c>true</c> if this instance is port authorized; otherwise, <c>false</c>.</value>
public bool IsPortAuthorized { get; set; }
- public bool AutoRunWebApp { get; set; }
- public bool EnableRemoteAccess { get; set; }
- public bool CameraUploadUpgraded { get; set; }
- public bool CollectionsUpgraded { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether quick connect is available for use on this server.
+ /// </summary>
+ public bool QuickConnectAvailable { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// </summary>
+ public bool EnableRemoteAccess { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether [enable case sensitive item ids].
/// </summary>
/// <value><c>true</c> if [enable case sensitive item ids]; otherwise, <c>false</c>.</value>
- public bool EnableCaseSensitiveItemIds { get; set; }
+ public bool EnableCaseSensitiveItemIds { get; set; } = true;
- public bool DisableLiveTvChannelUserDataName { get; set; }
+ public bool DisableLiveTvChannelUserDataName { get; set; } = true;
/// <summary>
/// Gets or sets the metadata path.
/// </summary>
/// <value>The metadata path.</value>
- public string MetadataPath { get; set; }
- public string MetadataNetworkPath { get; set; }
+ public string MetadataPath { get; set; } = string.Empty;
+
+ public string MetadataNetworkPath { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the preferred metadata language.
/// </summary>
/// <value>The preferred metadata language.</value>
- public string PreferredMetadataLanguage { get; set; }
+ public string PreferredMetadataLanguage { get; set; } = "en";
/// <summary>
/// Gets or sets the metadata country code.
/// </summary>
/// <value>The metadata country code.</value>
- public string MetadataCountryCode { get; set; }
+ public string MetadataCountryCode { get; set; } = "US";
/// <summary>
- /// Characters to be replaced with a ' ' in strings to create a sort name
+ /// Gets or sets characters to be replaced with a ' ' in strings to create a sort name.
/// </summary>
/// <value>The sort replace characters.</value>
- public string[] SortReplaceCharacters { get; set; }
+ public string[] SortReplaceCharacters { get; set; } = new[] { ".", "+", "%" };
/// <summary>
- /// Characters to be removed from strings to create a sort name
+ /// Gets or sets characters to be removed from strings to create a sort name.
/// </summary>
/// <value>The sort remove characters.</value>
- public string[] SortRemoveCharacters { get; set; }
+ public string[] SortRemoveCharacters { get; set; } = new[] { ",", "&", "-", "{", "}", "'" };
/// <summary>
- /// Words to be removed from strings to create a sort name
+ /// Gets or sets words to be removed from strings to create a sort name.
/// </summary>
/// <value>The sort remove words.</value>
- public string[] SortRemoveWords { get; set; }
+ public string[] SortRemoveWords { get; set; } = new[] { "the", "a", "an" };
/// <summary>
/// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated.
/// </summary>
/// <value>The min resume PCT.</value>
- public int MinResumePct { get; set; }
+ public int MinResumePct { get; set; } = 5;
/// <summary>
/// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched.
/// </summary>
/// <value>The max resume PCT.</value>
- public int MaxResumePct { get; set; }
+ public int MaxResumePct { get; set; } = 90;
/// <summary>
/// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates..
/// </summary>
/// <value>The min resume duration seconds.</value>
- public int MinResumeDurationSeconds { get; set; }
+ public int MinResumeDurationSeconds { get; set; } = 300;
/// <summary>
- /// The delay in seconds that we will wait after a file system change to try and discover what has been added/removed
+ /// Gets or sets the minimum minutes of a book that must be played in order for playstate to be updated.
+ /// </summary>
+ /// <value>The min resume in minutes.</value>
+ public int MinAudiobookResume { get; set; } = 5;
+
+ /// <summary>
+ /// Gets or sets the remaining minutes of a book that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched.
+ /// </summary>
+ /// <value>The remaining time in minutes.</value>
+ public int MaxAudiobookResume { get; set; } = 5;
+
+ /// <summary>
+ /// Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed
/// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several
/// different directories and files.
/// </summary>
/// <value>The file watcher delay.</value>
- public int LibraryMonitorDelay { get; set; }
+ public int LibraryMonitorDelay { get; set; } = 60;
/// <summary>
/// Gets or sets a value indicating whether [enable dashboard response caching].
/// Allows potential contributors without visual studio to modify production dashboard code and test changes.
/// </summary>
/// <value><c>true</c> if [enable dashboard response caching]; otherwise, <c>false</c>.</value>
- public bool EnableDashboardResponseCaching { get; set; }
-
- /// <summary>
- /// Allows the dashboard to be served from a custom path.
- /// </summary>
- /// <value>The dashboard source path.</value>
- public string DashboardSourcePath { get; set; }
+ public bool EnableDashboardResponseCaching { get; set; } = true;
/// <summary>
/// Gets or sets the image saving convention.
@@ -158,146 +333,131 @@ namespace MediaBrowser.Model.Configuration
public MetadataOptions[] MetadataOptions { get; set; }
- public bool EnableAutomaticRestart { get; set; }
- public bool SkipDeserializationForBasicTypes { get; set; }
+ public bool SkipDeserializationForBasicTypes { get; set; } = true;
- public string ServerName { get; set; }
- public string WanDdns { get; set; }
+ public string ServerName { get; set; } = string.Empty;
- public string UICulture { get; set; }
+ public string BaseUrl
+ {
+ get => _baseUrl;
+ set
+ {
+ // Normalize the start of the string
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ // If baseUrl is empty, set an empty prefix string
+ _baseUrl = string.Empty;
+ return;
+ }
- public bool SaveMetadataHidden { get; set; }
+ if (value[0] != '/')
+ {
+ // If baseUrl was not configured with a leading slash, append one for consistency
+ value = "/" + value;
+ }
- public NameValuePair[] ContentTypes { get; set; }
+ // Normalize the end of the string
+ if (value[value.Length - 1] == '/')
+ {
+ // If baseUrl was configured with a trailing slash, remove it for consistency
+ value = value.Remove(value.Length - 1);
+ }
- public int RemoteClientBitrateLimit { get; set; }
+ _baseUrl = value;
+ }
+ }
+
+ public string UICulture { get; set; } = "en-US";
- public bool EnableFolderView { get; set; }
- public bool EnableGroupingIntoCollections { get; set; }
- public bool DisplaySpecialsWithinSeasons { get; set; }
- public string[] LocalNetworkSubnets { get; set; }
- public string[] LocalNetworkAddresses { get; set; }
- public string[] CodecsUsed { get; set; }
- public bool EnableExternalContentInSuggestions { get; set; }
- public bool RequireHttps { get; set; }
- public bool IsBehindProxy { get; set; }
- public bool EnableNewOmdbSupport { get; set; }
+ public bool SaveMetadataHidden { get; set; } = false;
- public string[] RemoteIPFilter { get; set; }
- public bool IsRemoteIPFilterBlacklist { get; set; }
+ public NameValuePair[] ContentTypes { get; set; } = Array.Empty<NameValuePair>();
- public int ImageExtractionTimeoutMs { get; set; }
+ public int RemoteClientBitrateLimit { get; set; } = 0;
- public PathSubstitution[] PathSubstitutions { get; set; }
- public bool EnableSimpleArtistDetection { get; set; }
+ public bool EnableFolderView { get; set; } = false;
- public string[] UninstalledPlugins { get; set; }
+ public bool EnableGroupingIntoCollections { get; set; } = false;
+
+ public bool DisplaySpecialsWithinSeasons { get; set; } = true;
/// <summary>
- /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
+ /// Gets or sets the subnets that are deemed to make up the LAN.
/// </summary>
- public ServerConfiguration()
- {
- UninstalledPlugins = Array.Empty<string>();
- RemoteIPFilter = Array.Empty<string>();
- LocalNetworkSubnets = Array.Empty<string>();
- LocalNetworkAddresses = Array.Empty<string>();
- CodecsUsed = Array.Empty<string>();
- ImageExtractionTimeoutMs = 0;
- PathSubstitutions = Array.Empty<PathSubstitution>();
- EnableSimpleArtistDetection = true;
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
- DisplaySpecialsWithinSeasons = true;
- EnableExternalContentInSuggestions = true;
+ /// <summary>
+ /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
+ /// </summary>
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
- ImageSavingConvention = ImageSavingConvention.Compatible;
- PublicPort = DefaultHttpPort;
- PublicHttpsPort = DefaultHttpsPort;
- HttpServerPortNumber = DefaultHttpPort;
- HttpsPortNumber = DefaultHttpsPort;
- EnableHttps = true;
- EnableDashboardResponseCaching = true;
- EnableCaseSensitiveItemIds = true;
+ public string[] CodecsUsed { get; set; } = Array.Empty<string>();
- EnableAutomaticRestart = true;
- AutoRunWebApp = true;
- EnableRemoteAccess = true;
+ public List<RepositoryInfo> PluginRepositories { get; set; } = new List<RepositoryInfo>();
- EnableUPnP = true;
- MinResumePct = 5;
- MaxResumePct = 90;
+ public bool EnableExternalContentInSuggestions { get; set; } = true;
- // 5 minutes
- MinResumeDurationSeconds = 300;
+ /// <summary>
+ /// Gets or sets a value indicating whether the server should force connections over HTTPS.
+ /// </summary>
+ public bool RequireHttps { get; set; } = false;
- LibraryMonitorDelay = 60;
+ public bool EnableNewOmdbSupport { get; set; } = true;
- ContentTypes = Array.Empty<NameValuePair>();
+ /// <summary>
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
+ /// </summary>
+ public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
- PreferredMetadataLanguage = "en";
- MetadataCountryCode = "US";
+ /// <summary>
+ /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
+ /// </summary>
+ public bool IsRemoteIPFilterBlacklist { get; set; } = false;
- SortReplaceCharacters = new[] { ".", "+", "%" };
- SortRemoveCharacters = new[] { ",", "&", "-", "{", "}", "'" };
- SortRemoveWords = new[] { "the", "a", "an" };
+ public int ImageExtractionTimeoutMs { get; set; } = 0;
- UICulture = "en-US";
+ public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty<PathSubstitution>();
- MetadataOptions = new[]
- {
- new MetadataOptions()
- {
- ItemType = "Book"
- },
- new MetadataOptions()
- {
- ItemType = "Movie"
- },
- new MetadataOptions
- {
- ItemType = "MusicVideo",
- DisabledMetadataFetchers = new [] { "The Open Movie Database" },
- DisabledImageFetchers = new [] { "The Open Movie Database", "FanArt" }
- },
- new MetadataOptions
- {
- ItemType = "Series",
- DisabledMetadataFetchers = new [] { "TheMovieDb" },
- DisabledImageFetchers = new [] { "TheMovieDb" }
- },
- new MetadataOptions
- {
- ItemType = "MusicAlbum",
- DisabledMetadataFetchers = new [] { "TheAudioDB" }
- },
- new MetadataOptions
- {
- ItemType = "MusicArtist",
- DisabledMetadataFetchers = new [] { "TheAudioDB" }
- },
- new MetadataOptions
- {
- ItemType = "BoxSet"
- },
- new MetadataOptions
- {
- ItemType = "Season",
- DisabledMetadataFetchers = new [] { "TheMovieDb" },
- DisabledImageFetchers = new [] { "FanArt" }
- },
- new MetadataOptions
- {
- ItemType = "Episode",
- DisabledMetadataFetchers = new [] { "The Open Movie Database", "TheMovieDb" },
- DisabledImageFetchers = new [] { "The Open Movie Database", "TheMovieDb" }
- }
- };
- }
- }
+ public string[] UninstalledPlugins { get; set; } = Array.Empty<string>();
- public class PathSubstitution
- {
- public string From { get; set; }
- public string To { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether slow server responses should be logged as a warning.
+ /// </summary>
+ public bool EnableSlowResponseWarning { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the threshold for the slow response time warning in ms.
+ /// </summary>
+ public long SlowResponseThresholdMs { get; set; } = 500;
+
+ /// <summary>
+ /// Gets or sets the cors hosts.
+ /// </summary>
+ public string[] CorsHosts { get; set; } = new[] { "*" };
+
+ /// <summary>
+ /// Gets or sets the known proxies.
+ /// </summary>
+ public string[] KnownProxies { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the number of days we should retain activity logs.
+ /// </summary>
+ public int? ActivityLogRetentionDays { get; set; } = 30;
+
+ /// <summary>
+ /// Gets or sets the how the library scan fans out.
+ /// </summary>
+ public int LibraryScanFanoutConcurrency { get; set; }
+
+ /// <summary>
+ /// Gets or sets the how many metadata refreshes can run concurrently.
+ /// </summary>
+ public int LibraryMetadataRefreshConcurrency { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether older plugins should automatically be deleted from the plugin folder.
+ /// </summary>
+ public bool RemoveOldPlugins { get; set; }
}
}
diff --git a/MediaBrowser.Model/Configuration/SubtitlePlaybackMode.cs b/MediaBrowser.Model/Configuration/SubtitlePlaybackMode.cs
deleted file mode 100644
index fc429934f..000000000
--- a/MediaBrowser.Model/Configuration/SubtitlePlaybackMode.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace MediaBrowser.Model.Configuration
-{
- public enum SubtitlePlaybackMode
- {
- Default = 0,
- Always = 1,
- OnlyForced = 2,
- None = 3,
- Smart = 4
- }
-}
diff --git a/MediaBrowser.Model/Configuration/TypeOptions.cs b/MediaBrowser.Model/Configuration/TypeOptions.cs
new file mode 100644
index 000000000..d0179e5aa
--- /dev/null
+++ b/MediaBrowser.Model/Configuration/TypeOptions.cs
@@ -0,0 +1,365 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Entities;
+
+namespace MediaBrowser.Model.Configuration
+{
+ public class TypeOptions
+ {
+ public static readonly ImageOption DefaultInstance = new ImageOption();
+
+ public static readonly Dictionary<string, ImageOption[]> DefaultImageOptions = new Dictionary<string, ImageOption[]>
+ {
+ {
+ "Movie", new[]
+ {
+ new ImageOption
+ {
+ Limit = 1,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Art
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Disc
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ },
+
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Banner
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Thumb
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Logo
+ }
+ }
+ },
+ {
+ "MusicVideo", new[]
+ {
+ new ImageOption
+ {
+ Limit = 1,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Art
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Disc
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ },
+
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Banner
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Thumb
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Logo
+ }
+ }
+ },
+ {
+ "Series", new[]
+ {
+ new ImageOption
+ {
+ Limit = 1,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Art
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Banner
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Thumb
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Logo
+ }
+ }
+ },
+ {
+ "MusicAlbum", new[]
+ {
+ new ImageOption
+ {
+ Limit = 0,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Disc
+ }
+ }
+ },
+ {
+ "MusicArtist", new[]
+ {
+ new ImageOption
+ {
+ Limit = 1,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ // Don't download this by default
+ // They do look great, but most artists won't have them, which means a banner view isn't really possible
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Banner
+ },
+
+ // Don't download this by default
+ // Generally not used
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Art
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Logo
+ }
+ }
+ },
+ {
+ "BoxSet", new[]
+ {
+ new ImageOption
+ {
+ Limit = 1,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Thumb
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Logo
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Art
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Disc
+ },
+
+ // Don't download this by default as it's rarely used.
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Banner
+ }
+ }
+ },
+ {
+ "Season", new[]
+ {
+ new ImageOption
+ {
+ Limit = 0,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ },
+
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Banner
+ },
+
+ new ImageOption
+ {
+ Limit = 0,
+ Type = ImageType.Thumb
+ }
+ }
+ },
+ {
+ "Episode", new[]
+ {
+ new ImageOption
+ {
+ Limit = 0,
+ MinWidth = 1280,
+ Type = ImageType.Backdrop
+ },
+
+ new ImageOption
+ {
+ Limit = 1,
+ Type = ImageType.Primary
+ }
+ }
+ }
+ };
+
+ public TypeOptions()
+ {
+ MetadataFetchers = Array.Empty<string>();
+ MetadataFetcherOrder = Array.Empty<string>();
+ ImageFetchers = Array.Empty<string>();
+ ImageFetcherOrder = Array.Empty<string>();
+ ImageOptions = Array.Empty<ImageOption>();
+ }
+
+ public string Type { get; set; }
+
+ public string[] MetadataFetchers { get; set; }
+
+ public string[] MetadataFetcherOrder { get; set; }
+
+ public string[] ImageFetchers { get; set; }
+
+ public string[] ImageFetcherOrder { get; set; }
+
+ public ImageOption[] ImageOptions { get; set; }
+
+ public ImageOption GetImageOptions(ImageType type)
+ {
+ foreach (var i in ImageOptions)
+ {
+ if (i.Type == type)
+ {
+ return i;
+ }
+ }
+
+ if (DefaultImageOptions.TryGetValue(Type, out ImageOption[] options))
+ {
+ foreach (var i in options)
+ {
+ if (i.Type == type)
+ {
+ return i;
+ }
+ }
+ }
+
+ return DefaultInstance;
+ }
+
+ public int GetLimit(ImageType type)
+ {
+ return GetImageOptions(type).Limit;
+ }
+
+ public int GetMinWidth(ImageType type)
+ {
+ return GetImageOptions(type).MinWidth;
+ }
+
+ public bool IsEnabled(ImageType type)
+ {
+ return GetLimit(type) > 0;
+ }
+ }
+}
diff --git a/MediaBrowser.Model/Configuration/UnratedItem.cs b/MediaBrowser.Model/Configuration/UnratedItem.cs
deleted file mode 100644
index 107b4e520..000000000
--- a/MediaBrowser.Model/Configuration/UnratedItem.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace MediaBrowser.Model.Configuration
-{
- public enum UnratedItem
- {
- Movie,
- Trailer,
- Series,
- Music,
- Book,
- LiveTvChannel,
- LiveTvProgram,
- ChannelContent,
- Other
- }
-}
diff --git a/MediaBrowser.Model/Configuration/UserConfiguration.cs b/MediaBrowser.Model/Configuration/UserConfiguration.cs
index 689459eba..81359462c 100644
--- a/MediaBrowser.Model/Configuration/UserConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/UserConfiguration.cs
@@ -1,17 +1,38 @@
+#pragma warning disable CS1591
+
using System;
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Configuration
{
/// <summary>
- /// Class UserConfiguration
+ /// Class UserConfiguration.
/// </summary>
public class UserConfiguration
{
/// <summary>
+ /// Initializes a new instance of the <see cref="UserConfiguration" /> class.
+ /// </summary>
+ public UserConfiguration()
+ {
+ EnableNextEpisodeAutoPlay = true;
+ RememberAudioSelections = true;
+ RememberSubtitleSelections = true;
+
+ HidePlayedInLatest = true;
+ PlayDefaultAudioTrack = true;
+
+ LatestItemsExcludes = Array.Empty<string>();
+ OrderedViews = Array.Empty<string>();
+ MyMediaExcludes = Array.Empty<string>();
+ GroupedFolders = Array.Empty<string>();
+ }
+
+ /// <summary>
/// Gets or sets the audio language preference.
/// </summary>
/// <value>The audio language preference.</value>
- public string AudioLanguagePreference { get; set; }
+ public string? AudioLanguagePreference { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [play default audio track].
@@ -23,13 +44,14 @@ namespace MediaBrowser.Model.Configuration
/// Gets or sets the subtitle language preference.
/// </summary>
/// <value>The subtitle language preference.</value>
- public string SubtitleLanguagePreference { get; set; }
+ public string? SubtitleLanguagePreference { get; set; }
public bool DisplayMissingEpisodes { get; set; }
public string[] GroupedFolders { get; set; }
public SubtitlePlaybackMode SubtitleMode { get; set; }
+
public bool DisplayCollectionsView { get; set; }
public bool EnableLocalPassword { get; set; }
@@ -37,30 +59,15 @@ namespace MediaBrowser.Model.Configuration
public string[] OrderedViews { get; set; }
public string[] LatestItemsExcludes { get; set; }
+
public string[] MyMediaExcludes { get; set; }
public bool HidePlayedInLatest { get; set; }
public bool RememberAudioSelections { get; set; }
- public bool RememberSubtitleSelections { get; set; }
- public bool EnableNextEpisodeAutoPlay { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="UserConfiguration" /> class.
- /// </summary>
- public UserConfiguration()
- {
- EnableNextEpisodeAutoPlay = true;
- RememberAudioSelections = true;
- RememberSubtitleSelections = true;
- HidePlayedInLatest = true;
- PlayDefaultAudioTrack = true;
+ public bool RememberSubtitleSelections { get; set; }
- LatestItemsExcludes = Array.Empty<string>();
- OrderedViews = Array.Empty<string>();
- MyMediaExcludes = Array.Empty<string>();
- GroupedFolders = Array.Empty<string>();
- }
+ public bool EnableNextEpisodeAutoPlay { get; set; }
}
}
diff --git a/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs b/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs
index 19e6be166..07129d715 100644
--- a/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs
+++ b/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs
@@ -1,16 +1,9 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Configuration
{
public class XbmcMetadataOptions
{
- public string UserId { get; set; }
-
- public string ReleaseDateFormat { get; set; }
-
- public bool SaveImagePathsInNfo { get; set; }
- public bool EnablePathSubstitution { get; set; }
-
- public bool EnableExtraThumbsDuplication { get; set; }
-
public XbmcMetadataOptions()
{
ReleaseDateFormat = "yyyy-MM-dd";
@@ -18,5 +11,15 @@ namespace MediaBrowser.Model.Configuration
SaveImagePathsInNfo = true;
EnablePathSubstitution = true;
}
+
+ public string? UserId { get; set; }
+
+ public string ReleaseDateFormat { get; set; }
+
+ public bool SaveImagePathsInNfo { get; set; }
+
+ public bool EnablePathSubstitution { get; set; }
+
+ public bool EnableExtraThumbsDuplication { get; set; }
}
}
diff --git a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs
index b027d2ad0..d8b7d848a 100644
--- a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs
+++ b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs
@@ -1,13 +1,21 @@
-using System;
-using System.IO;
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
namespace MediaBrowser.Model.Cryptography
{
public interface ICryptoProvider
{
- Guid GetMD5(string str);
- byte[] ComputeMD5(Stream str);
- byte[] ComputeMD5(byte[] bytes);
- byte[] ComputeSHA1(byte[] bytes);
+ string DefaultHashMethod { get; }
+
+ IEnumerable<string> GetSupportedHashMethods();
+
+ byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt);
+
+ byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt);
+
+ byte[] GenerateSalt();
+
+ byte[] GenerateSalt(int length);
}
}
diff --git a/MediaBrowser.Model/Devices/ContentUploadHistory.cs b/MediaBrowser.Model/Devices/ContentUploadHistory.cs
deleted file mode 100644
index 5dd9bf2d0..000000000
--- a/MediaBrowser.Model/Devices/ContentUploadHistory.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace MediaBrowser.Model.Devices
-{
- public class ContentUploadHistory
- {
- public string DeviceId { get; set; }
- public LocalFileInfo[] FilesUploaded { get; set; }
-
- public ContentUploadHistory()
- {
- FilesUploaded = new LocalFileInfo[] { };
- }
- }
-}
diff --git a/MediaBrowser.Model/Devices/DeviceInfo.cs b/MediaBrowser.Model/Devices/DeviceInfo.cs
index 214c49e5e..7a1c7a738 100644
--- a/MediaBrowser.Model/Devices/DeviceInfo.cs
+++ b/MediaBrowser.Model/Devices/DeviceInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Session;
@@ -5,49 +8,60 @@ namespace MediaBrowser.Model.Devices
{
public class DeviceInfo
{
+ public DeviceInfo()
+ {
+ Capabilities = new ClientCapabilities();
+ }
+
public string Name { get; set; }
/// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ public string AccessToken { get; set; }
+
+ /// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public string Id { get; set; }
+
/// <summary>
/// Gets or sets the last name of the user.
/// </summary>
/// <value>The last name of the user.</value>
public string LastUserName { get; set; }
+
/// <summary>
/// Gets or sets the name of the application.
/// </summary>
/// <value>The name of the application.</value>
public string AppName { get; set; }
+
/// <summary>
/// Gets or sets the application version.
/// </summary>
/// <value>The application version.</value>
public string AppVersion { get; set; }
+
/// <summary>
/// Gets or sets the last user identifier.
/// </summary>
/// <value>The last user identifier.</value>
public Guid LastUserId { get; set; }
+
/// <summary>
/// Gets or sets the date last modified.
/// </summary>
/// <value>The date last modified.</value>
public DateTime DateLastActivity { get; set; }
+
/// <summary>
/// Gets or sets the capabilities.
/// </summary>
/// <value>The capabilities.</value>
public ClientCapabilities Capabilities { get; set; }
- public DeviceInfo()
- {
- Capabilities = new ClientCapabilities();
- }
-
public string IconUrl { get; set; }
}
}
diff --git a/MediaBrowser.Model/Devices/DeviceQuery.cs b/MediaBrowser.Model/Devices/DeviceQuery.cs
deleted file mode 100644
index 48d7ec142..000000000
--- a/MediaBrowser.Model/Devices/DeviceQuery.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Devices
-{
- public class DeviceQuery
- {
- /// <summary>
- /// Gets or sets a value indicating whether [supports synchronize].
- /// </summary>
- /// <value><c>null</c> if [supports synchronize] contains no value, <c>true</c> if [supports synchronize]; otherwise, <c>false</c>.</value>
- public bool? SupportsSync { get; set; }
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public Guid UserId { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Devices/DevicesOptions.cs b/MediaBrowser.Model/Devices/DevicesOptions.cs
deleted file mode 100644
index 5bbd33b73..000000000
--- a/MediaBrowser.Model/Devices/DevicesOptions.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Devices
-{
- public class DevicesOptions
- {
- public string[] EnabledCameraUploadDevices { get; set; }
- public string CameraUploadPath { get; set; }
- public bool EnableCameraUploadSubfolders { get; set; }
-
- public DevicesOptions()
- {
- EnabledCameraUploadDevices = Array.Empty<string>();
- }
- }
-
- public class DeviceOptions
- {
- public string CustomName { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Devices/LocalFileInfo.cs b/MediaBrowser.Model/Devices/LocalFileInfo.cs
deleted file mode 100644
index cc5c9250b..000000000
--- a/MediaBrowser.Model/Devices/LocalFileInfo.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace MediaBrowser.Model.Devices
-{
- public class LocalFileInfo
- {
- public string Name { get; set; }
- public string Id { get; set; }
- public string Album { get; set; }
- public string MimeType { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Diagnostics/IProcess.cs b/MediaBrowser.Model/Diagnostics/IProcess.cs
deleted file mode 100644
index cade631c9..000000000
--- a/MediaBrowser.Model/Diagnostics/IProcess.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.Diagnostics
-{
- public interface IProcess : IDisposable
- {
- event EventHandler Exited;
-
- void Kill();
- bool WaitForExit(int timeMs);
- Task<bool> WaitForExitAsync(int timeMs);
- int ExitCode { get; }
- void Start();
- StreamWriter StandardInput { get; }
- StreamReader StandardError { get; }
- StreamReader StandardOutput { get; }
- ProcessOptions StartInfo { get; }
- }
-}
diff --git a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs b/MediaBrowser.Model/Diagnostics/IProcessFactory.cs
deleted file mode 100644
index a11be8f4e..000000000
--- a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-namespace MediaBrowser.Model.Diagnostics
-{
- public interface IProcessFactory
- {
- IProcess Create(ProcessOptions options);
- }
-
- public class ProcessOptions
- {
- public string FileName { get; set; }
- public string Arguments { get; set; }
- public string WorkingDirectory { get; set; }
- public bool CreateNoWindow { get; set; }
- public bool UseShellExecute { get; set; }
- public bool EnableRaisingEvents { get; set; }
- public bool ErrorDialog { get; set; }
- public bool RedirectStandardError { get; set; }
- public bool RedirectStandardInput { get; set; }
- public bool RedirectStandardOutput { get; set; }
- public bool IsHidden { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Dlna/AudioOptions.cs b/MediaBrowser.Model/Dlna/AudioOptions.cs
index 6dfe8093e..4d4d8d78c 100644
--- a/MediaBrowser.Model/Dlna/AudioOptions.cs
+++ b/MediaBrowser.Model/Dlna/AudioOptions.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dto;
@@ -17,31 +20,36 @@ namespace MediaBrowser.Model.Dlna
}
public bool EnableDirectPlay { get; set; }
+
public bool EnableDirectStream { get; set; }
+
public bool ForceDirectPlay { get; set; }
+
public bool ForceDirectStream { get; set; }
public Guid ItemId { get; set; }
+
public MediaSourceInfo[] MediaSources { get; set; }
+
public DeviceProfile Profile { get; set; }
/// <summary>
- /// Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested.
+ /// Gets or sets a media source id. Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested.
/// </summary>
public string MediaSourceId { get; set; }
public string DeviceId { get; set; }
/// <summary>
- /// Allows an override of supported number of audio channels
- /// Example: DeviceProfile supports five channel, but user only has stereo speakers
+ /// Gets or sets an override of supported number of audio channels
+ /// Example: DeviceProfile supports five channel, but user only has stereo speakers.
/// </summary>
public int? MaxAudioChannels { get; set; }
/// <summary>
- /// The application's configured quality setting
+ /// Gets or sets the application's configured quality setting.
/// </summary>
- public long? MaxBitrate { get; set; }
+ public int? MaxBitrate { get; set; }
/// <summary>
/// Gets or sets the context.
@@ -58,8 +66,9 @@ namespace MediaBrowser.Model.Dlna
/// <summary>
/// Gets the maximum bitrate.
/// </summary>
+ /// <param name="isAudio">Whether or not this is audio.</param>
/// <returns>System.Nullable&lt;System.Int32&gt;.</returns>
- public long? GetMaxBitrate(bool isAudio)
+ public int? GetMaxBitrate(bool isAudio)
{
if (MaxBitrate.HasValue)
{
@@ -77,6 +86,7 @@ namespace MediaBrowser.Model.Dlna
{
return Profile.MaxStaticMusicBitrate;
}
+
return Profile.MaxStaticBitrate;
}
diff --git a/MediaBrowser.Model/Dlna/CodecProfile.cs b/MediaBrowser.Model/Dlna/CodecProfile.cs
index 9ea248908..8343cf028 100644
--- a/MediaBrowser.Model/Dlna/CodecProfile.cs
+++ b/MediaBrowser.Model/Dlna/CodecProfile.cs
@@ -1,10 +1,20 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Linq;
using System.Xml.Serialization;
-using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
public class CodecProfile
{
+ public CodecProfile()
+ {
+ Conditions = Array.Empty<ProfileCondition>();
+ ApplyConditions = Array.Empty<ProfileCondition>();
+ }
+
[XmlAttribute("type")]
public CodecType Type { get; set; }
@@ -18,12 +28,6 @@ namespace MediaBrowser.Model.Dlna
[XmlAttribute("container")]
public string Container { get; set; }
- public CodecProfile()
- {
- Conditions = new ProfileCondition[] { };
- ApplyConditions = new ProfileCondition[] { };
- }
-
public string[] GetCodecs()
{
return ContainerProfile.SplitValue(Codec);
@@ -54,7 +58,7 @@ namespace MediaBrowser.Model.Dlna
foreach (var val in codec)
{
- if (ListHelper.ContainsIgnoreCase(codecs, val))
+ if (codecs.Contains(val, StringComparer.OrdinalIgnoreCase))
{
return true;
}
diff --git a/MediaBrowser.Model/Dlna/CodecType.cs b/MediaBrowser.Model/Dlna/CodecType.cs
index d777be4c2..c9f090e4c 100644
--- a/MediaBrowser.Model/Dlna/CodecType.cs
+++ b/MediaBrowser.Model/Dlna/CodecType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum CodecType
diff --git a/MediaBrowser.Model/Dlna/ConditionProcessor.cs b/MediaBrowser.Model/Dlna/ConditionProcessor.cs
index 3629d1547..55c4dd074 100644
--- a/MediaBrowser.Model/Dlna/ConditionProcessor.cs
+++ b/MediaBrowser.Model/Dlna/ConditionProcessor.cs
@@ -1,6 +1,8 @@
+#pragma warning disable CS1591
+
using System;
using System.Globalization;
-using MediaBrowser.Model.Extensions;
+using System.Linq;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Dlna
@@ -13,7 +15,7 @@ namespace MediaBrowser.Model.Dlna
int? height,
int? videoBitDepth,
int? videoBitrate,
- string videoProfile,
+ string? videoProfile,
double? videoLevel,
float? videoFramerate,
int? packetLength,
@@ -23,7 +25,7 @@ namespace MediaBrowser.Model.Dlna
int? refFrames,
int? numVideoStreams,
int? numAudioStreams,
- string videoCodecTag,
+ string? videoCodecTag,
bool? isAvc)
{
switch (condition.Property)
@@ -101,7 +103,7 @@ namespace MediaBrowser.Model.Dlna
int? audioBitrate,
int? audioSampleRate,
int? audioBitDepth,
- string audioProfile,
+ string? audioProfile,
bool? isSecondaryTrack)
{
switch (condition.Property)
@@ -152,7 +154,7 @@ namespace MediaBrowser.Model.Dlna
return false;
}
- private static bool IsConditionSatisfied(ProfileCondition condition, string currentValue)
+ private static bool IsConditionSatisfied(ProfileCondition condition, string? currentValue)
{
if (string.IsNullOrEmpty(currentValue))
{
@@ -165,13 +167,11 @@ namespace MediaBrowser.Model.Dlna
switch (condition.Condition)
{
case ProfileConditionType.EqualsAny:
- {
- return ListHelper.ContainsIgnoreCase(expected.Split('|'), currentValue);
- }
+ return expected.Split('|').Contains(currentValue, StringComparer.OrdinalIgnoreCase);
case ProfileConditionType.Equals:
- return StringHelper.EqualsIgnoreCase(currentValue, expected);
+ return string.Equals(currentValue, expected, StringComparison.OrdinalIgnoreCase);
case ProfileConditionType.NotEquals:
- return !StringHelper.EqualsIgnoreCase(currentValue, expected);
+ return !string.Equals(currentValue, expected, StringComparison.OrdinalIgnoreCase);
default:
throw new InvalidOperationException("Unexpected ProfileConditionType: " + condition.Condition);
}
@@ -201,34 +201,6 @@ namespace MediaBrowser.Model.Dlna
return false;
}
- private static bool IsConditionSatisfied(ProfileCondition condition, float currentValue)
- {
- if (currentValue <= 0)
- {
- // If the value is unknown, it satisfies if not marked as required
- return !condition.IsRequired;
- }
-
- if (float.TryParse(condition.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out var expected))
- {
- switch (condition.Condition)
- {
- case ProfileConditionType.Equals:
- return currentValue.Equals(expected);
- case ProfileConditionType.GreaterThanEqual:
- return currentValue >= expected;
- case ProfileConditionType.LessThanEqual:
- return currentValue <= expected;
- case ProfileConditionType.NotEquals:
- return !currentValue.Equals(expected);
- default:
- throw new InvalidOperationException("Unexpected ProfileConditionType: " + condition.Condition);
- }
- }
-
- return false;
- }
-
private static bool IsConditionSatisfied(ProfileCondition condition, double? currentValue)
{
if (!currentValue.HasValue)
diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs
index 073324c26..740966088 100644
--- a/MediaBrowser.Model/Dlna/ContainerProfile.cs
+++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs
@@ -1,6 +1,8 @@
+#pragma warning disable CS1591
+
using System;
+using System.Linq;
using System.Xml.Serialization;
-using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
@@ -8,42 +10,33 @@ namespace MediaBrowser.Model.Dlna
{
[XmlAttribute("type")]
public DlnaProfileType Type { get; set; }
- public ProfileCondition[] Conditions { get; set; }
-
- [XmlAttribute("container")]
- public string Container { get; set; }
- public ContainerProfile()
- {
- Conditions = Array.Empty<ProfileCondition>();
- }
+ public ProfileCondition[]? Conditions { get; set; } = Array.Empty<ProfileCondition>();
- public string[] GetContainers()
- {
- return SplitValue(Container);
- }
+ [XmlAttribute("container")]
+ public string Container { get; set; } = string.Empty;
- public static string[] SplitValue(string value)
+ public static string[] SplitValue(string? value)
{
if (string.IsNullOrEmpty(value))
{
return Array.Empty<string>();
}
- return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+ return value.Split(',', StringSplitOptions.RemoveEmptyEntries);
}
- public bool ContainsContainer(string container)
+ public bool ContainsContainer(string? container)
{
- var containers = GetContainers();
+ var containers = SplitValue(Container);
return ContainsContainer(containers, container);
}
- public static bool ContainsContainer(string profileContainers, string inputContainer)
+ public static bool ContainsContainer(string? profileContainers, string? inputContainer)
{
var isNegativeList = false;
- if (profileContainers != null && profileContainers.StartsWith("-"))
+ if (profileContainers != null && profileContainers.StartsWith('-'))
{
isNegativeList = true;
profileContainers = profileContainers.Substring(1);
@@ -52,46 +45,30 @@ namespace MediaBrowser.Model.Dlna
return ContainsContainer(SplitValue(profileContainers), isNegativeList, inputContainer);
}
- public static bool ContainsContainer(string[] profileContainers, string inputContainer)
+ public static bool ContainsContainer(string[]? profileContainers, string? inputContainer)
{
return ContainsContainer(profileContainers, false, inputContainer);
}
- public static bool ContainsContainer(string[] profileContainers, bool isNegativeList, string inputContainer)
+ public static bool ContainsContainer(string[]? profileContainers, bool isNegativeList, string? inputContainer)
{
- if (profileContainers.Length == 0)
+ if (profileContainers == null || profileContainers.Length == 0)
{
+ // Empty profiles always support all containers/codecs
return true;
}
- if (isNegativeList)
- {
- var allInputContainers = SplitValue(inputContainer);
+ var allInputContainers = SplitValue(inputContainer);
- foreach (var container in allInputContainers)
- {
- if (ListHelper.ContainsIgnoreCase(profileContainers, container))
- {
- return false;
- }
- }
-
- return true;
- }
- else
+ foreach (var container in allInputContainers)
{
- var allInputContainers = SplitValue(inputContainer);
-
- foreach (var container in allInputContainers)
+ if (profileContainers.Contains(container, StringComparer.OrdinalIgnoreCase))
{
- if (ListHelper.ContainsIgnoreCase(profileContainers, container))
- {
- return true;
- }
+ return !isNegativeList;
}
-
- return false;
}
+
+ return isNegativeList;
}
}
}
diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
index 901d81c5f..e8fd18ae4 100644
--- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
+++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
@@ -1,19 +1,18 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Dlna
{
public class ContentFeatureBuilder
{
- private readonly DeviceProfile _profile;
-
- public ContentFeatureBuilder(DeviceProfile profile)
- {
- _profile = profile;
- }
-
- public string BuildImageHeader(string container,
+ public static string BuildImageHeader(
+ DeviceProfile profile,
+ string container,
int? width,
int? height,
bool isDirectStream,
@@ -28,29 +27,37 @@ namespace MediaBrowser.Model.Dlna
DlnaFlags.InteractiveTransferMode |
DlnaFlags.DlnaV15;
- string dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}",
- DlnaMaps.FlagsToString(flagValue));
-
- ResponseProfile mediaProfile = _profile.GetImageMediaProfile(container,
- width,
- height);
+ string dlnaflags = string.Format(
+ CultureInfo.InvariantCulture,
+ ";DLNA.ORG_FLAGS={0}",
+ DlnaMaps.FlagsToString(flagValue));
if (string.IsNullOrEmpty(orgPn))
{
- orgPn = mediaProfile == null ? null : mediaProfile.OrgPn;
+ ResponseProfile mediaProfile = profile.GetImageMediaProfile(
+ container,
+ width,
+ height);
+
+ orgPn = mediaProfile?.OrgPn;
+
+ if (string.IsNullOrEmpty(orgPn))
+ {
+ orgPn = GetImageOrgPnValue(container, width, height);
+ }
}
if (string.IsNullOrEmpty(orgPn))
{
- orgPn = GetImageOrgPnValue(container, width, height);
+ return orgOp.TrimStart(';') + orgCi + dlnaflags;
}
- string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn;
-
- return (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
+ return "DLNA.ORG_PN=" + orgPn + orgOp + orgCi + dlnaflags;
}
- public string BuildAudioHeader(string container,
+ public static string BuildAudioHeader(
+ DeviceProfile profile,
+ string container,
string audioCodec,
int? audioBitrate,
int? audioSampleRate,
@@ -71,38 +78,46 @@ namespace MediaBrowser.Model.Dlna
DlnaFlags.InteractiveTransferMode |
DlnaFlags.DlnaV15;
- //if (isDirectStream)
- //{
- // flagValue = flagValue | DlnaFlags.ByteBasedSeek;
- //}
- //else if (runtimeTicks.HasValue)
- //{
- // flagValue = flagValue | DlnaFlags.TimeBasedSeek;
- //}
-
- string dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}",
- DlnaMaps.FlagsToString(flagValue));
-
- ResponseProfile mediaProfile = _profile.GetAudioMediaProfile(container,
+ // if (isDirectStream)
+ // {
+ // flagValue = flagValue | DlnaFlags.ByteBasedSeek;
+ // }
+ // else if (runtimeTicks.HasValue)
+ // {
+ // flagValue = flagValue | DlnaFlags.TimeBasedSeek;
+ // }
+
+ string dlnaflags = string.Format(
+ CultureInfo.InvariantCulture,
+ ";DLNA.ORG_FLAGS={0}",
+ DlnaMaps.FlagsToString(flagValue));
+
+ ResponseProfile mediaProfile = profile.GetAudioMediaProfile(
+ container,
audioCodec,
audioChannels,
audioBitrate,
audioSampleRate,
audioBitDepth);
- string orgPn = mediaProfile == null ? null : mediaProfile.OrgPn;
+ string orgPn = mediaProfile?.OrgPn;
if (string.IsNullOrEmpty(orgPn))
{
orgPn = GetAudioOrgPnValue(container, audioBitrate, audioSampleRate, audioChannels);
}
- string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn;
+ if (string.IsNullOrEmpty(orgPn))
+ {
+ return orgOp.TrimStart(';') + orgCi + dlnaflags;
+ }
- return (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
+ return "DLNA.ORG_PN=" + orgPn + orgOp + orgCi + dlnaflags;
}
- public List<string> BuildVideoHeader(string container,
+ public static List<string> BuildVideoHeader(
+ DeviceProfile profile,
+ string container,
string videoCodec,
string audioCodec,
int? width,
@@ -136,19 +151,22 @@ namespace MediaBrowser.Model.Dlna
DlnaFlags.InteractiveTransferMode |
DlnaFlags.DlnaV15;
- //if (isDirectStream)
- //{
- // flagValue = flagValue | DlnaFlags.ByteBasedSeek;
- //}
- //else if (runtimeTicks.HasValue)
- //{
- // flagValue = flagValue | DlnaFlags.TimeBasedSeek;
- //}
-
- string dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}",
- DlnaMaps.FlagsToString(flagValue));
-
- ResponseProfile mediaProfile = _profile.GetVideoMediaProfile(container,
+ // if (isDirectStream)
+ // {
+ // flagValue = flagValue | DlnaFlags.ByteBasedSeek;
+ // }
+ // else if (runtimeTicks.HasValue)
+ // {
+ // flagValue = flagValue | DlnaFlags.TimeBasedSeek;
+ // }
+
+ string dlnaflags = string.Format(
+ CultureInfo.InvariantCulture,
+ ";DLNA.ORG_FLAGS={0}",
+ DlnaMaps.FlagsToString(flagValue));
+
+ ResponseProfile mediaProfile = profile.GetVideoMediaProfile(
+ container,
audioCodec,
videoCodec,
width,
@@ -172,13 +190,13 @@ namespace MediaBrowser.Model.Dlna
if (mediaProfile != null && !string.IsNullOrEmpty(mediaProfile.OrgPn))
{
- orgPnValues.AddRange(mediaProfile.OrgPn.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
+ orgPnValues.AddRange(mediaProfile.OrgPn.Split(',', StringSplitOptions.RemoveEmptyEntries));
}
else
{
- foreach (string s in GetVideoOrgPnValue(container, videoCodec, audioCodec, width, height, timestamp))
+ foreach (var s in GetVideoOrgPnValue(container, videoCodec, audioCodec, width, height, timestamp))
{
- orgPnValues.Add(s);
+ orgPnValues.Add(s.ToString());
break;
}
}
@@ -187,39 +205,35 @@ namespace MediaBrowser.Model.Dlna
foreach (string orgPn in orgPnValues)
{
- string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn;
-
- var value = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
-
- contentFeatureList.Add(value);
+ if (string.IsNullOrEmpty(orgPn))
+ {
+ contentFeatureList.Add(orgOp.TrimStart(';') + orgCi + dlnaflags);
+ }
+ else
+ {
+ contentFeatureList.Add("DLNA.ORG_PN=" + orgPn + orgCi + dlnaflags);
+ }
}
if (orgPnValues.Count == 0)
{
- string contentFeatures = string.Empty;
-
- var value = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
-
- contentFeatureList.Add(value);
+ contentFeatureList.Add(orgOp.TrimStart(';') + orgCi + dlnaflags);
}
return contentFeatureList;
}
- private string GetImageOrgPnValue(string container, int? width, int? height)
+ private static string GetImageOrgPnValue(string container, int? width, int? height)
{
- MediaFormatProfile? format = new MediaFormatProfileResolver()
- .ResolveImageFormat(container,
- width,
- height);
+ MediaFormatProfile? format = MediaFormatProfileResolver.ResolveImageFormat(container, width, height);
return format.HasValue ? format.Value.ToString() : null;
}
- private string GetAudioOrgPnValue(string container, int? audioBitrate, int? audioSampleRate, int? audioChannels)
+ private static string GetAudioOrgPnValue(string container, int? audioBitrate, int? audioSampleRate, int? audioChannels)
{
- MediaFormatProfile? format = new MediaFormatProfileResolver()
- .ResolveAudioFormat(container,
+ MediaFormatProfile? format = MediaFormatProfileResolver.ResolveAudioFormat(
+ container,
audioBitrate,
audioSampleRate,
audioChannels);
@@ -227,9 +241,9 @@ namespace MediaBrowser.Model.Dlna
return format.HasValue ? format.Value.ToString() : null;
}
- private string[] GetVideoOrgPnValue(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestamp)
+ private static MediaFormatProfile[] GetVideoOrgPnValue(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestamp)
{
- return new MediaFormatProfileResolver().ResolveVideoFormat(container, videoCodec, audioCodec, width, height, timestamp);
+ return MediaFormatProfileResolver.ResolveVideoFormat(container, videoCodec, audioCodec, width, height, timestamp);
}
}
}
diff --git a/MediaBrowser.Model/Dlna/DeviceIdentification.cs b/MediaBrowser.Model/Dlna/DeviceIdentification.cs
index 84573521a..6625b7981 100644
--- a/MediaBrowser.Model/Dlna/DeviceIdentification.cs
+++ b/MediaBrowser.Model/Dlna/DeviceIdentification.cs
@@ -1,3 +1,7 @@
+#pragma warning disable CS1591
+
+using System;
+
namespace MediaBrowser.Model.Dlna
{
public class DeviceIdentification
@@ -6,56 +10,54 @@ namespace MediaBrowser.Model.Dlna
/// Gets or sets the name of the friendly.
/// </summary>
/// <value>The name of the friendly.</value>
- public string FriendlyName { get; set; }
+ public string FriendlyName { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the model number.
/// </summary>
/// <value>The model number.</value>
- public string ModelNumber { get; set; }
+ public string ModelNumber { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the serial number.
/// </summary>
/// <value>The serial number.</value>
- public string SerialNumber { get; set; }
+ public string SerialNumber { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the name of the model.
/// </summary>
/// <value>The name of the model.</value>
- public string ModelName { get; set; }
+ public string ModelName { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the model description.
/// </summary>
/// <value>The model description.</value>
- public string ModelDescription { get; set; }
- /// <summary>
- /// Gets or sets the device description.
- /// </summary>
- /// <value>The device description.</value>
- public string DeviceDescription { get; set; }
+ public string ModelDescription { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the model URL.
/// </summary>
/// <value>The model URL.</value>
- public string ModelUrl { get; set; }
+ public string ModelUrl { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the manufacturer.
/// </summary>
/// <value>The manufacturer.</value>
- public string Manufacturer { get; set; }
+ public string Manufacturer { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the manufacturer URL.
/// </summary>
/// <value>The manufacturer URL.</value>
- public string ManufacturerUrl { get; set; }
+ public string ManufacturerUrl { get; set; } = string.Empty;
+
/// <summary>
/// Gets or sets the headers.
/// </summary>
/// <value>The headers.</value>
- public HttpHeaderInfo[] Headers { get; set; }
-
- public DeviceIdentification()
- {
- Headers = new HttpHeaderInfo[] { };
- }
+ public HttpHeaderInfo[] Headers { get; set; } = Array.Empty<HttpHeaderInfo>();
}
}
diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs
index 8d8fe9eb5..feb3d880e 100644
--- a/MediaBrowser.Model/Dlna/DeviceProfile.cs
+++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs
@@ -1,174 +1,319 @@
+#pragma warning disable CA1819 // Properties should not return arrays
using System;
+using System.ComponentModel;
+using System.Linq;
using System.Xml.Serialization;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Dlna
{
+ /// <summary>
+ /// A <see cref="DeviceProfile" /> represents a set of metadata which determines which content a certain device is able to play.
+ /// <br/>
+ /// Specifically, it defines the supported <see cref="ContainerProfiles">containers</see> and
+ /// <see cref="CodecProfiles">codecs</see> (video and/or audio, including codec profiles and levels)
+ /// the device is able to direct play (without transcoding or remuxing),
+ /// as well as which <see cref="TranscodingProfiles">containers/codecs to transcode to</see> in case it isn't.
+ /// </summary>
[XmlRoot("Profile")]
public class DeviceProfile
{
/// <summary>
- /// Gets or sets the name.
+ /// Gets or sets the name of this device profile.
/// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
+ public string? Name { get; set; }
+ /// <summary>
+ /// Gets or sets the Id.
+ /// </summary>
[XmlIgnore]
- public string Id { get; set; }
+ public string? Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Identification.
+ /// </summary>
+ public DeviceIdentification? Identification { get; set; }
+
+ /// <summary>
+ /// Gets or sets the friendly name of the device profile, which can be shown to users.
+ /// </summary>
+ public string? FriendlyName { get; set; }
/// <summary>
- /// Gets or sets the identification.
+ /// Gets or sets the manufacturer of the device which this profile represents.
/// </summary>
- /// <value>The identification.</value>
- public DeviceIdentification Identification { get; set; }
+ public string? Manufacturer { get; set; }
- public string FriendlyName { get; set; }
- public string Manufacturer { get; set; }
- public string ManufacturerUrl { get; set; }
- public string ModelName { get; set; }
- public string ModelDescription { get; set; }
- public string ModelNumber { get; set; }
- public string ModelUrl { get; set; }
- public string SerialNumber { get; set; }
+ /// <summary>
+ /// Gets or sets an url for the manufacturer of the device which this profile represents.
+ /// </summary>
+ public string? ManufacturerUrl { get; set; }
+ /// <summary>
+ /// Gets or sets the model name of the device which this profile represents.
+ /// </summary>
+ public string? ModelName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the model description of the device which this profile represents.
+ /// </summary>
+ public string? ModelDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the model number of the device which this profile represents.
+ /// </summary>
+ public string? ModelNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ModelUrl.
+ /// </summary>
+ public string? ModelUrl { get; set; }
+
+ /// <summary>
+ /// Gets or sets the serial number of the device which this profile represents.
+ /// </summary>
+ public string? SerialNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether EnableAlbumArtInDidl.
+ /// </summary>
+ [DefaultValue(false)]
public bool EnableAlbumArtInDidl { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether EnableSingleAlbumArtLimit.
+ /// </summary>
+ [DefaultValue(false)]
public bool EnableSingleAlbumArtLimit { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether EnableSingleSubtitleLimit.
+ /// </summary>
+ [DefaultValue(false)]
public bool EnableSingleSubtitleLimit { get; set; }
- public string SupportedMediaTypes { get; set; }
+ /// <summary>
+ /// Gets or sets the SupportedMediaTypes.
+ /// </summary>
+ public string SupportedMediaTypes { get; set; } = "Audio,Photo,Video";
- public string UserId { get; set; }
+ /// <summary>
+ /// Gets or sets the UserId.
+ /// </summary>
+ public string? UserId { get; set; }
- public string AlbumArtPn { get; set; }
+ /// <summary>
+ /// Gets or sets the AlbumArtPn.
+ /// </summary>
+ public string? AlbumArtPn { get; set; }
- public int MaxAlbumArtWidth { get; set; }
- public int MaxAlbumArtHeight { get; set; }
+ /// <summary>
+ /// Gets or sets the MaxAlbumArtWidth.
+ /// </summary>
+ public int? MaxAlbumArtWidth { get; set; }
+ /// <summary>
+ /// Gets or sets the MaxAlbumArtHeight.
+ /// </summary>
+ public int? MaxAlbumArtHeight { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum allowed width of embedded icons.
+ /// </summary>
public int? MaxIconWidth { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum allowed height of embedded icons.
+ /// </summary>
public int? MaxIconHeight { get; set; }
- public long? MaxStreamingBitrate { get; set; }
- public long? MaxStaticBitrate { get; set; }
+ /// <summary>
+ /// Gets or sets the maximum allowed bitrate for all streamed content.
+ /// </summary>
+ public int? MaxStreamingBitrate { get; set; } = 8000000;
- public int? MusicStreamingTranscodingBitrate { get; set; }
- public int? MaxStaticMusicBitrate { get; set; }
+ /// <summary>
+ /// Gets or sets the maximum allowed bitrate for statically streamed content (= direct played files).
+ /// </summary>
+ public int? MaxStaticBitrate { get; set; } = 8000000;
/// <summary>
- /// Controls the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace.
+ /// Gets or sets the maximum allowed bitrate for transcoded music streams.
/// </summary>
- public string SonyAggregationFlags { get; set; }
+ public int? MusicStreamingTranscodingBitrate { get; set; } = 128000;
- public string ProtocolInfo { get; set; }
+ /// <summary>
+ /// Gets or sets the maximum allowed bitrate for statically streamed (= direct played) music files.
+ /// </summary>
+ public int? MaxStaticMusicBitrate { get; set; } = 8000000;
+
+ /// <summary>
+ /// Gets or sets the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace.
+ /// </summary>
+ public string? SonyAggregationFlags { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ProtocolInfo.
+ /// </summary>
+ public string? ProtocolInfo { get; set; }
+ /// <summary>
+ /// Gets or sets the TimelineOffsetSeconds.
+ /// </summary>
+ [DefaultValue(0)]
public int TimelineOffsetSeconds { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether RequiresPlainVideoItems.
+ /// </summary>
+ [DefaultValue(false)]
public bool RequiresPlainVideoItems { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether RequiresPlainFolders.
+ /// </summary>
+ [DefaultValue(false)]
public bool RequiresPlainFolders { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether EnableMSMediaReceiverRegistrar.
+ /// </summary>
+ [DefaultValue(false)]
public bool EnableMSMediaReceiverRegistrar { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IgnoreTranscodeByteRangeRequests.
+ /// </summary>
+ [DefaultValue(false)]
public bool IgnoreTranscodeByteRangeRequests { get; set; }
- public XmlAttribute[] XmlRootAttributes { get; set; }
+ /// <summary>
+ /// Gets or sets the XmlRootAttributes.
+ /// </summary>
+ public XmlAttribute[] XmlRootAttributes { get; set; } = Array.Empty<XmlAttribute>();
/// <summary>
/// Gets or sets the direct play profiles.
/// </summary>
- /// <value>The direct play profiles.</value>
- public DirectPlayProfile[] DirectPlayProfiles { get; set; }
+ public DirectPlayProfile[] DirectPlayProfiles { get; set; } = Array.Empty<DirectPlayProfile>();
/// <summary>
/// Gets or sets the transcoding profiles.
/// </summary>
- /// <value>The transcoding profiles.</value>
- public TranscodingProfile[] TranscodingProfiles { get; set; }
+ public TranscodingProfile[] TranscodingProfiles { get; set; } = Array.Empty<TranscodingProfile>();
- public ContainerProfile[] ContainerProfiles { get; set; }
+ /// <summary>
+ /// Gets or sets the container profiles.
+ /// </summary>
+ public ContainerProfile[] ContainerProfiles { get; set; } = Array.Empty<ContainerProfile>();
- public CodecProfile[] CodecProfiles { get; set; }
- public ResponseProfile[] ResponseProfiles { get; set; }
+ /// <summary>
+ /// Gets or sets the codec profiles.
+ /// </summary>
+ public CodecProfile[] CodecProfiles { get; set; } = Array.Empty<CodecProfile>();
- public SubtitleProfile[] SubtitleProfiles { get; set; }
+ /// <summary>
+ /// Gets or sets the ResponseProfiles.
+ /// </summary>
+ public ResponseProfile[] ResponseProfiles { get; set; } = Array.Empty<ResponseProfile>();
- public DeviceProfile()
- {
- DirectPlayProfiles = new DirectPlayProfile[] { };
- TranscodingProfiles = new TranscodingProfile[] { };
- ResponseProfiles = new ResponseProfile[] { };
- CodecProfiles = new CodecProfile[] { };
- ContainerProfiles = new ContainerProfile[] { };
- SubtitleProfiles = Array.Empty<SubtitleProfile>();
-
- XmlRootAttributes = new XmlAttribute[] { };
-
- SupportedMediaTypes = "Audio,Photo,Video";
- MaxStreamingBitrate = 8000000;
- MaxStaticBitrate = 8000000;
- MusicStreamingTranscodingBitrate = 128000;
- }
+ /// <summary>
+ /// Gets or sets the subtitle profiles.
+ /// </summary>
+ public SubtitleProfile[] SubtitleProfiles { get; set; } = Array.Empty<SubtitleProfile>();
+ /// <summary>
+ /// The GetSupportedMediaTypes.
+ /// </summary>
+ /// <returns>The .</returns>
public string[] GetSupportedMediaTypes()
{
return ContainerProfile.SplitValue(SupportedMediaTypes);
}
- public TranscodingProfile GetAudioTranscodingProfile(string container, string audioCodec)
+ /// <summary>
+ /// Gets the audio transcoding profile.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ /// <param name="audioCodec">The audio Codec.</param>
+ /// <returns>A <see cref="TranscodingProfile"/>.</returns>
+ public TranscodingProfile? GetAudioTranscodingProfile(string? container, string? audioCodec)
{
container = (container ?? string.Empty).TrimStart('.');
foreach (var i in TranscodingProfiles)
{
- if (i.Type != MediaBrowser.Model.Dlna.DlnaProfileType.Audio)
+ if (i.Type != DlnaProfileType.Audio)
{
continue;
}
- if (!StringHelper.EqualsIgnoreCase(container, i.Container))
+ if (!string.Equals(container, i.Container, StringComparison.OrdinalIgnoreCase))
{
continue;
}
- if (!ListHelper.ContainsIgnoreCase(i.GetAudioCodecs(), audioCodec ?? string.Empty))
+ if (!i.GetAudioCodecs().Contains(audioCodec ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
continue;
}
return i;
}
+
return null;
}
- public TranscodingProfile GetVideoTranscodingProfile(string container, string audioCodec, string videoCodec)
+ /// <summary>
+ /// Gets the video transcoding profile.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ /// <param name="audioCodec">The audio Codec.</param>
+ /// <param name="videoCodec">The video Codec.</param>
+ /// <returns>The <see cref="TranscodingProfile"/>.</returns>
+ public TranscodingProfile? GetVideoTranscodingProfile(string? container, string? audioCodec, string? videoCodec)
{
container = (container ?? string.Empty).TrimStart('.');
foreach (var i in TranscodingProfiles)
{
- if (i.Type != MediaBrowser.Model.Dlna.DlnaProfileType.Video)
+ if (i.Type != DlnaProfileType.Video)
{
continue;
}
- if (!StringHelper.EqualsIgnoreCase(container, i.Container))
+ if (!string.Equals(container, i.Container, StringComparison.OrdinalIgnoreCase))
{
continue;
}
- if (!ListHelper.ContainsIgnoreCase(i.GetAudioCodecs(), audioCodec ?? string.Empty))
+ if (!i.GetAudioCodecs().Contains(audioCodec ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
continue;
}
- if (!StringHelper.EqualsIgnoreCase(videoCodec, i.VideoCodec ?? string.Empty))
+ if (!string.Equals(videoCodec, i.VideoCodec, StringComparison.OrdinalIgnoreCase))
{
continue;
}
return i;
}
+
return null;
}
- public ResponseProfile GetAudioMediaProfile(string container, string audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth)
+ /// <summary>
+ /// Gets the audio media profile.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ /// <param name="audioCodec">The audio codec.</param>
+ /// <param name="audioChannels">The audio channels.</param>
+ /// <param name="audioBitrate">The audio bitrate.</param>
+ /// <param name="audioSampleRate">The audio sample rate.</param>
+ /// <param name="audioBitDepth">The audio bit depth.</param>
+ /// <returns>The <see cref="ResponseProfile"/>.</returns>
+ public ResponseProfile? GetAudioMediaProfile(string container, string? audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth)
{
foreach (var i in ResponseProfiles)
{
@@ -183,7 +328,7 @@ namespace MediaBrowser.Model.Dlna
}
var audioCodecs = i.GetAudioCodecs();
- if (audioCodecs.Length > 0 && !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec ?? string.Empty))
+ if (audioCodecs.Length > 0 && !audioCodecs.Contains(audioCodec ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
continue;
}
@@ -205,9 +350,15 @@ namespace MediaBrowser.Model.Dlna
return i;
}
+
return null;
}
+ /// <summary>
+ /// Gets the model profile condition.
+ /// </summary>
+ /// <param name="c">The c<see cref="ProfileCondition"/>.</param>
+ /// <returns>The <see cref="ProfileCondition"/>.</returns>
private ProfileCondition GetModelProfileCondition(ProfileCondition c)
{
return new ProfileCondition
@@ -219,7 +370,14 @@ namespace MediaBrowser.Model.Dlna
};
}
- public ResponseProfile GetImageMediaProfile(string container, int? width, int? height)
+ /// <summary>
+ /// Gets the image media profile.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
+ /// <returns>The <see cref="ResponseProfile"/>.</returns>
+ public ResponseProfile? GetImageMediaProfile(string container, int? width, int? height)
{
foreach (var i in ResponseProfiles)
{
@@ -250,12 +408,37 @@ namespace MediaBrowser.Model.Dlna
return i;
}
+
return null;
}
- public ResponseProfile GetVideoMediaProfile(string container,
- string audioCodec,
- string videoCodec,
+ /// <summary>
+ /// Gets the video media profile.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ /// <param name="audioCodec">The audio codec.</param>
+ /// <param name="videoCodec">The video codec.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
+ /// <param name="bitDepth">The bit depth.</param>
+ /// <param name="videoBitrate">The video bitrate.</param>
+ /// <param name="videoProfile">The video profile.</param>
+ /// <param name="videoLevel">The video level.</param>
+ /// <param name="videoFramerate">The video framerate.</param>
+ /// <param name="packetLength">The packet length.</param>
+ /// <param name="timestamp">The timestamp<see cref="TransportStreamTimestamp"/>.</param>
+ /// <param name="isAnamorphic">True if anamorphic.</param>
+ /// <param name="isInterlaced">True if interlaced.</param>
+ /// <param name="refFrames">The ref frames.</param>
+ /// <param name="numVideoStreams">The number of video streams.</param>
+ /// <param name="numAudioStreams">The number of audio streams.</param>
+ /// <param name="videoCodecTag">The video Codec tag.</param>
+ /// <param name="isAvc">True if Avc.</param>
+ /// <returns>The <see cref="ResponseProfile"/>.</returns>
+ public ResponseProfile? GetVideoMediaProfile(
+ string container,
+ string? audioCodec,
+ string? videoCodec,
int? width,
int? height,
int? bitDepth,
@@ -286,13 +469,13 @@ namespace MediaBrowser.Model.Dlna
}
var audioCodecs = i.GetAudioCodecs();
- if (audioCodecs.Length > 0 && !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec ?? string.Empty))
+ if (audioCodecs.Length > 0 && !audioCodecs.Contains(audioCodec ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
continue;
}
var videoCodecs = i.GetVideoCodecs();
- if (videoCodecs.Length > 0 && !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec ?? string.Empty))
+ if (videoCodecs.Length > 0 && !videoCodecs.Contains(videoCodec ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
continue;
}
@@ -314,6 +497,7 @@ namespace MediaBrowser.Model.Dlna
return i;
}
+
return null;
}
}
diff --git a/MediaBrowser.Model/Dlna/DeviceProfileInfo.cs b/MediaBrowser.Model/Dlna/DeviceProfileInfo.cs
index c78f0d9b2..74c32c523 100644
--- a/MediaBrowser.Model/Dlna/DeviceProfileInfo.cs
+++ b/MediaBrowser.Model/Dlna/DeviceProfileInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public class DeviceProfileInfo
diff --git a/MediaBrowser.Model/Dlna/DeviceProfileType.cs b/MediaBrowser.Model/Dlna/DeviceProfileType.cs
index 2449fa434..46062abd0 100644
--- a/MediaBrowser.Model/Dlna/DeviceProfileType.cs
+++ b/MediaBrowser.Model/Dlna/DeviceProfileType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum DeviceProfileType
diff --git a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs
index 5a54847d7..03c3a7265 100644
--- a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs
+++ b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
@@ -5,13 +7,13 @@ namespace MediaBrowser.Model.Dlna
public class DirectPlayProfile
{
[XmlAttribute("container")]
- public string Container { get; set; }
+ public string? Container { get; set; }
[XmlAttribute("audioCodec")]
- public string AudioCodec { get; set; }
+ public string? AudioCodec { get; set; }
[XmlAttribute("videoCodec")]
- public string VideoCodec { get; set; }
+ public string? VideoCodec { get; set; }
[XmlAttribute("type")]
public DlnaProfileType Type { get; set; }
@@ -23,12 +25,12 @@ namespace MediaBrowser.Model.Dlna
public bool SupportsVideoCodec(string codec)
{
- return ContainerProfile.ContainsContainer(VideoCodec, codec);
+ return Type == DlnaProfileType.Video && ContainerProfile.ContainsContainer(VideoCodec, codec);
}
public bool SupportsAudioCodec(string codec)
{
- return ContainerProfile.ContainsContainer(AudioCodec, codec);
+ return (Type == DlnaProfileType.Audio || Type == DlnaProfileType.Video) && ContainerProfile.ContainsContainer(AudioCodec, codec);
}
}
}
diff --git a/MediaBrowser.Model/Dlna/DlnaFlags.cs b/MediaBrowser.Model/Dlna/DlnaFlags.cs
index d076e73ec..02d9ea9c5 100644
--- a/MediaBrowser.Model/Dlna/DlnaFlags.cs
+++ b/MediaBrowser.Model/Dlna/DlnaFlags.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Dlna
diff --git a/MediaBrowser.Model/Dlna/DlnaMaps.cs b/MediaBrowser.Model/Dlna/DlnaMaps.cs
index 880d05724..95cd0ac27 100644
--- a/MediaBrowser.Model/Dlna/DlnaMaps.cs
+++ b/MediaBrowser.Model/Dlna/DlnaMaps.cs
@@ -1,16 +1,20 @@
+#pragma warning disable CS1591
+
+using System.Globalization;
+
namespace MediaBrowser.Model.Dlna
{
- public class DlnaMaps
+ public static class DlnaMaps
{
private static readonly string DefaultStreaming =
- FlagsToString(DlnaFlags.StreamingTransferMode |
+ FlagsToString(DlnaFlags.StreamingTransferMode |
DlnaFlags.BackgroundTransferMode |
DlnaFlags.ConnectionStall |
DlnaFlags.ByteBasedSeek |
DlnaFlags.DlnaV15);
private static readonly string DefaultInteractive =
- FlagsToString(DlnaFlags.InteractiveTransferMode |
+ FlagsToString(DlnaFlags.InteractiveTransferMode |
DlnaFlags.BackgroundTransferMode |
DlnaFlags.ConnectionStall |
DlnaFlags.ByteBasedSeek |
@@ -18,7 +22,7 @@ namespace MediaBrowser.Model.Dlna
public static string FlagsToString(DlnaFlags flags)
{
- return string.Format("{0:X8}{1:D24}", (ulong)flags, 0);
+ return string.Format(CultureInfo.InvariantCulture, "{0:X8}{1:D24}", (ulong)flags, 0);
}
public static string GetOrgOpValue(bool hasKnownRuntime, bool isDirectStream, TranscodeSeekInfo profileTranscodeSeekInfo)
diff --git a/MediaBrowser.Model/Dlna/DlnaProfileType.cs b/MediaBrowser.Model/Dlna/DlnaProfileType.cs
index 6a23bbb04..e30ed0f3c 100644
--- a/MediaBrowser.Model/Dlna/DlnaProfileType.cs
+++ b/MediaBrowser.Model/Dlna/DlnaProfileType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum DlnaProfileType
diff --git a/MediaBrowser.Model/Dlna/EncodingContext.cs b/MediaBrowser.Model/Dlna/EncodingContext.cs
index 7352bdd19..79ca6366d 100644
--- a/MediaBrowser.Model/Dlna/EncodingContext.cs
+++ b/MediaBrowser.Model/Dlna/EncodingContext.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum EncodingContext
diff --git a/MediaBrowser.Model/Dlna/HeaderMatchType.cs b/MediaBrowser.Model/Dlna/HeaderMatchType.cs
index b0a1438f6..2a9abb20e 100644
--- a/MediaBrowser.Model/Dlna/HeaderMatchType.cs
+++ b/MediaBrowser.Model/Dlna/HeaderMatchType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum HeaderMatchType
diff --git a/MediaBrowser.Model/Dlna/HttpHeaderInfo.cs b/MediaBrowser.Model/Dlna/HttpHeaderInfo.cs
index d15727504..17c4dffcc 100644
--- a/MediaBrowser.Model/Dlna/HttpHeaderInfo.cs
+++ b/MediaBrowser.Model/Dlna/HttpHeaderInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
diff --git a/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs b/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs
index 3de3fe761..086088dea 100644
--- a/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs
+++ b/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs
@@ -1,11 +1,14 @@
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Events;
+using Jellyfin.Data.Events;
namespace MediaBrowser.Model.Dlna
{
public interface IDeviceDiscovery
{
event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscovered;
+
event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceLeft;
}
}
diff --git a/MediaBrowser.Model/Dlna/ITranscoderSupport.cs b/MediaBrowser.Model/Dlna/ITranscoderSupport.cs
index c0ff54c3f..a70ce44cc 100644
--- a/MediaBrowser.Model/Dlna/ITranscoderSupport.cs
+++ b/MediaBrowser.Model/Dlna/ITranscoderSupport.cs
@@ -1,9 +1,13 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public interface ITranscoderSupport
{
bool CanEncodeToAudioCodec(string codec);
+
bool CanEncodeToSubtitleCodec(string codec);
+
bool CanExtractSubtitles(string codec);
}
@@ -13,10 +17,12 @@ namespace MediaBrowser.Model.Dlna
{
return true;
}
+
public bool CanEncodeToSubtitleCodec(string codec)
{
return true;
}
+
public bool CanExtractSubtitles(string codec)
{
return true;
diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfile.cs b/MediaBrowser.Model/Dlna/MediaFormatProfile.cs
index 7c56fc5f4..06f6660f4 100644
--- a/MediaBrowser.Model/Dlna/MediaFormatProfile.cs
+++ b/MediaBrowser.Model/Dlna/MediaFormatProfile.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591, CA1707
+
namespace MediaBrowser.Model.Dlna
{
public enum MediaFormatProfile
diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs
index 672784589..93a9ae615 100644
--- a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs
+++ b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs
@@ -1,77 +1,84 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Model.Extensions;
+using System.Globalization;
using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Dlna
{
- public class MediaFormatProfileResolver
+ public static class MediaFormatProfileResolver
{
- public string[] ResolveVideoFormat(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType)
- {
- return ResolveVideoFormatInternal(container, videoCodec, audioCodec, width, height, timestampType)
- .Select(i => i.ToString())
- .ToArray();
- }
-
- private MediaFormatProfile[] ResolveVideoFormatInternal(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType)
+ public static MediaFormatProfile[] ResolveVideoFormat(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType)
{
- if (StringHelper.EqualsIgnoreCase(container, "asf"))
+ if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase))
{
MediaFormatProfile? val = ResolveVideoASFFormat(videoCodec, audioCodec, width, height);
- return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { };
+ return val.HasValue ? new MediaFormatProfile[] { val.Value } : Array.Empty<MediaFormatProfile>();
}
- if (StringHelper.EqualsIgnoreCase(container, "mp4"))
+ if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase))
{
MediaFormatProfile? val = ResolveVideoMP4Format(videoCodec, audioCodec, width, height);
- return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { };
+ return val.HasValue ? new MediaFormatProfile[] { val.Value } : Array.Empty<MediaFormatProfile>();
}
- if (StringHelper.EqualsIgnoreCase(container, "avi"))
+ if (string.Equals(container, "avi", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.AVI };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mkv"))
+ if (string.Equals(container, "mkv", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.MATROSKA };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mpeg2ps") ||
- StringHelper.EqualsIgnoreCase(container, "ts"))
-
+ if (string.Equals(container, "mpeg2ps", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.MPEG_PS_NTSC, MediaFormatProfile.MPEG_PS_PAL };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mpeg1video"))
+ if (string.Equals(container, "mpeg1video", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.MPEG1 };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mpeg2ts") ||
- StringHelper.EqualsIgnoreCase(container, "mpegts") ||
- StringHelper.EqualsIgnoreCase(container, "m2ts"))
+ if (string.Equals(container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
{
-
return ResolveVideoMPEG2TSFormat(videoCodec, audioCodec, width, height, timestampType);
}
- if (StringHelper.EqualsIgnoreCase(container, "flv"))
+ if (string.Equals(container, "flv", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.FLV };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "wtv"))
+ if (string.Equals(container, "wtv", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.WTV };
+ }
- if (StringHelper.EqualsIgnoreCase(container, "3gp"))
+ if (string.Equals(container, "3gp", StringComparison.OrdinalIgnoreCase))
{
MediaFormatProfile? val = ResolveVideo3GPFormat(videoCodec, audioCodec);
- return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { };
+ return val.HasValue ? new MediaFormatProfile[] { val.Value } : Array.Empty<MediaFormatProfile>();
}
- if (StringHelper.EqualsIgnoreCase(container, "ogv") || StringHelper.EqualsIgnoreCase(container, "ogg"))
+ if (string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.OGV };
+ }
- return new MediaFormatProfile[] { };
+ return Array.Empty<MediaFormatProfile>();
}
- private MediaFormatProfile[] ResolveVideoMPEG2TSFormat(string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType)
+ private static MediaFormatProfile[] ResolveVideoMPEG2TSFormat(string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType)
{
- string suffix = "";
+ string suffix = string.Empty;
switch (timestampType)
{
@@ -89,146 +96,182 @@ namespace MediaBrowser.Model.Dlna
resolution = "H";
}
- if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg2video"))
+ if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase))
{
- var list = new List<MediaFormatProfile>();
-
- list.Add(ValueOf("MPEG_TS_SD_NA" + suffix));
- list.Add(ValueOf("MPEG_TS_SD_EU" + suffix));
- list.Add(ValueOf("MPEG_TS_SD_KO" + suffix));
+ var list = new List<MediaFormatProfile>
+ {
+ ValueOf("MPEG_TS_SD_NA" + suffix),
+ ValueOf("MPEG_TS_SD_EU" + suffix),
+ ValueOf("MPEG_TS_SD_KO" + suffix)
+ };
- if ((timestampType == TransportStreamTimestamp.Valid) && StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if ((timestampType == TransportStreamTimestamp.Valid) && string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
list.Add(MediaFormatProfile.MPEG_TS_JP_T);
}
+
return list.ToArray();
}
- if (StringHelper.EqualsIgnoreCase(videoCodec, "h264"))
+
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "lpcm"))
+ if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase))
+ {
return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_50_LPCM_T };
+ }
- if (StringHelper.EqualsIgnoreCase(audioCodec, "dts"))
+ if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase))
{
if (timestampType == TransportStreamTimestamp.None)
{
return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_DTS_ISO };
}
+
return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_DTS_T };
}
- if (StringHelper.EqualsIgnoreCase(audioCodec, "mp2"))
+ if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase))
{
if (timestampType == TransportStreamTimestamp.None)
{
- return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_HP_{0}D_MPEG1_L2_ISO", resolution)) };
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "AVC_TS_HP_{0}D_MPEG1_L2_ISO", resolution)) };
}
- return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_HP_{0}D_MPEG1_L2_T", resolution)) };
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "AVC_TS_HP_{0}D_MPEG1_L2_T", resolution)) };
}
- if (StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
- return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AAC_MULT5{1}", resolution, suffix)) };
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "AVC_TS_MP_{0}D_AAC_MULT5{1}", resolution, suffix)) };
+ }
- if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3"))
- return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_MPEG1_L3{1}", resolution, suffix)) };
+ if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "AVC_TS_MP_{0}D_MPEG1_L3{1}", resolution, suffix)) };
+ }
if (string.IsNullOrEmpty(audioCodec) ||
- StringHelper.EqualsIgnoreCase(audioCodec, "ac3"))
- return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AC3{1}", resolution, suffix)) };
+ string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "AVC_TS_MP_{0}D_AC3{1}", resolution, suffix)) };
+ }
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "vc1"))
+ else if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase))
{
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "ac3"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
{
if ((width.HasValue && width.Value > 720) || (height.HasValue && height.Value > 576))
{
return new MediaFormatProfile[] { MediaFormatProfile.VC1_TS_AP_L2_AC3_ISO };
}
+
return new MediaFormatProfile[] { MediaFormatProfile.VC1_TS_AP_L1_AC3_ISO };
}
- if (StringHelper.EqualsIgnoreCase(audioCodec, "dts"))
+
+ if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase))
{
- suffix = StringHelper.EqualsIgnoreCase(suffix, "_ISO") ? suffix : "_T";
+ suffix = string.Equals(suffix, "_ISO", StringComparison.OrdinalIgnoreCase) ? suffix : "_T";
- return new MediaFormatProfile[] { ValueOf(string.Format("VC1_TS_HD_DTS{0}", suffix)) };
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "VC1_TS_HD_DTS{0}", suffix)) };
}
-
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") || StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4"))
+ else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
- return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AAC{0}", suffix)) };
- if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3"))
- return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG1_L3{0}", suffix)) };
- if (StringHelper.EqualsIgnoreCase(audioCodec, "mp2"))
- return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG2_L2{0}", suffix)) };
- if (StringHelper.EqualsIgnoreCase(audioCodec, "ac3"))
- return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AC3{0}", suffix)) };
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "MPEG4_P2_TS_ASP_AAC{0}", suffix)) };
+ }
+
+ if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "MPEG4_P2_TS_ASP_MPEG1_L3{0}", suffix)) };
+ }
+
+ if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "MPEG4_P2_TS_ASP_MPEG2_L2{0}", suffix)) };
+ }
+
+ if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MediaFormatProfile[] { ValueOf(string.Format(CultureInfo.InvariantCulture, "MPEG4_P2_TS_ASP_AC3{0}", suffix)) };
+ }
}
- return new MediaFormatProfile[] { };
+ return Array.Empty<MediaFormatProfile>();
}
- private MediaFormatProfile ValueOf(string value)
+ private static MediaFormatProfile ValueOf(string value)
{
return (MediaFormatProfile)Enum.Parse(typeof(MediaFormatProfile), value, true);
}
- private MediaFormatProfile? ResolveVideoMP4Format(string videoCodec, string audioCodec, int? width, int? height)
+ private static MediaFormatProfile? ResolveVideoMP4Format(string videoCodec, string audioCodec, int? width, int? height)
{
- if (StringHelper.EqualsIgnoreCase(videoCodec, "h264"))
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "lpcm"))
+ if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.AVC_MP4_LPCM;
+ }
+
if (string.IsNullOrEmpty(audioCodec) ||
- StringHelper.EqualsIgnoreCase(audioCodec, "ac3"))
+ string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_MP_SD_AC3;
}
- if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3"))
+
+ if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_MP_SD_MPEG1_L3;
}
+
if (width.HasValue && height.HasValue)
{
if ((width.Value <= 720) && (height.Value <= 576))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.AVC_MP4_MP_SD_AAC_MULT5;
+ }
}
else if ((width.Value <= 1280) && (height.Value <= 720))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.AVC_MP4_MP_HD_720p_AAC;
+ }
}
else if ((width.Value <= 1920) && (height.Value <= 1080))
{
- if (StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_MP_HD_1080i_AAC;
}
}
}
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") ||
- StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4"))
+ else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
if (width.HasValue && height.HasValue && width.Value <= 720 && height.Value <= 576)
{
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.MPEG4_P2_MP4_ASP_AAC;
- if (StringHelper.EqualsIgnoreCase(audioCodec, "ac3") || StringHelper.EqualsIgnoreCase(audioCodec, "mp3"))
+ }
+
+ if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_P2_MP4_NDSD;
}
}
- else if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ else if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_P2_MP4_SP_L6_AAC;
}
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "h263") && StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_H263_MP4_P0_L10_AAC;
}
@@ -236,22 +279,29 @@ namespace MediaBrowser.Model.Dlna
return null;
}
- private MediaFormatProfile? ResolveVideo3GPFormat(string videoCodec, string audioCodec)
+ private static MediaFormatProfile? ResolveVideo3GPFormat(string videoCodec, string audioCodec)
{
- if (StringHelper.EqualsIgnoreCase(videoCodec, "h264"))
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.AVC_3GPP_BL_QCIF15_AAC;
+ }
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") ||
- StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4"))
+ else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AAC;
- if (StringHelper.EqualsIgnoreCase(audioCodec, "amrnb"))
+ }
+
+ if (string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AMR;
+ }
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "h263") && StringHelper.EqualsIgnoreCase(audioCodec, "amrnb"))
+ else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_H263_3GPP_P0_L10_AMR;
}
@@ -259,44 +309,53 @@ namespace MediaBrowser.Model.Dlna
return null;
}
- private MediaFormatProfile? ResolveVideoASFFormat(string videoCodec, string audioCodec, int? width, int? height)
+ private static MediaFormatProfile? ResolveVideoASFFormat(string videoCodec, string audioCodec, int? width, int? height)
{
- if (StringHelper.EqualsIgnoreCase(videoCodec, "wmv") &&
- (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma") || StringHelper.EqualsIgnoreCase(videoCodec, "wmapro")))
+ if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase) &&
+ (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "wmapro", StringComparison.OrdinalIgnoreCase)))
{
-
if (width.HasValue && height.HasValue)
{
if ((width.Value <= 720) && (height.Value <= 576))
{
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.WMVMED_FULL;
}
+
return MediaFormatProfile.WMVMED_PRO;
}
}
- if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma"))
+ if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.WMVHIGH_FULL;
}
+
return MediaFormatProfile.WMVHIGH_PRO;
}
- if (StringHelper.EqualsIgnoreCase(videoCodec, "vc1"))
+ if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase))
{
if (width.HasValue && height.HasValue)
{
if ((width.Value <= 720) && (height.Value <= 576))
+ {
return MediaFormatProfile.VC1_ASF_AP_L1_WMA;
+ }
+
if ((width.Value <= 1280) && (height.Value <= 720))
+ {
return MediaFormatProfile.VC1_ASF_AP_L2_WMA;
+ }
+
if ((width.Value <= 1920) && (height.Value <= 1080))
+ {
return MediaFormatProfile.VC1_ASF_AP_L3_WMA;
+ }
}
}
- else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg2video"))
+ else if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.DVR_MS;
}
@@ -304,44 +363,59 @@ namespace MediaBrowser.Model.Dlna
return null;
}
- public MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels)
+ public static MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels)
{
- if (StringHelper.EqualsIgnoreCase(container, "asf"))
+ if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveAudioASFFormat(bitrate);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mp3"))
+ if (string.Equals(container, "mp3", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.MP3;
+ }
- if (StringHelper.EqualsIgnoreCase(container, "lpcm"))
+ if (string.Equals(container, "lpcm", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveAudioLPCMFormat(frequency, channels);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "mp4") ||
- StringHelper.EqualsIgnoreCase(container, "aac"))
+ if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "aac", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveAudioMP4Format(bitrate);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "adts"))
+ if (string.Equals(container, "adts", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveAudioADTSFormat(bitrate);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "flac"))
+ if (string.Equals(container, "flac", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.FLAC;
+ }
- if (StringHelper.EqualsIgnoreCase(container, "oga") ||
- StringHelper.EqualsIgnoreCase(container, "ogg"))
+ if (string.Equals(container, "oga", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.OGG;
+ }
return null;
}
- private MediaFormatProfile ResolveAudioASFFormat(int? bitrate)
+ private static MediaFormatProfile ResolveAudioASFFormat(int? bitrate)
{
if (bitrate.HasValue && bitrate.Value <= 193)
{
return MediaFormatProfile.WMA_BASE;
}
+
return MediaFormatProfile.WMA_FULL;
}
- private MediaFormatProfile? ResolveAudioLPCMFormat(int? frequency, int? channels)
+ private static MediaFormatProfile? ResolveAudioLPCMFormat(int? frequency, int? channels)
{
if (frequency.HasValue && channels.HasValue)
{
@@ -349,14 +423,17 @@ namespace MediaBrowser.Model.Dlna
{
return MediaFormatProfile.LPCM16_44_MONO;
}
+
if (frequency.Value == 44100 && channels.Value == 2)
{
return MediaFormatProfile.LPCM16_44_STEREO;
}
+
if (frequency.Value == 48000 && channels.Value == 1)
{
return MediaFormatProfile.LPCM16_48_MONO;
}
+
if (frequency.Value == 48000 && channels.Value == 2)
{
return MediaFormatProfile.LPCM16_48_STEREO;
@@ -368,51 +445,65 @@ namespace MediaBrowser.Model.Dlna
return MediaFormatProfile.LPCM16_48_STEREO;
}
- private MediaFormatProfile ResolveAudioMP4Format(int? bitrate)
+ private static MediaFormatProfile ResolveAudioMP4Format(int? bitrate)
{
if (bitrate.HasValue && bitrate.Value <= 320)
{
return MediaFormatProfile.AAC_ISO_320;
}
+
return MediaFormatProfile.AAC_ISO;
}
- private MediaFormatProfile ResolveAudioADTSFormat(int? bitrate)
+ private static MediaFormatProfile ResolveAudioADTSFormat(int? bitrate)
{
if (bitrate.HasValue && bitrate.Value <= 320)
{
return MediaFormatProfile.AAC_ADTS_320;
}
+
return MediaFormatProfile.AAC_ADTS;
}
- public MediaFormatProfile? ResolveImageFormat(string container, int? width, int? height)
+ public static MediaFormatProfile? ResolveImageFormat(string container, int? width, int? height)
{
- if (StringHelper.EqualsIgnoreCase(container, "jpeg") ||
- StringHelper.EqualsIgnoreCase(container, "jpg"))
+ if (string.Equals(container, "jpeg", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(container, "jpg", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveImageJPGFormat(width, height);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "png"))
+ if (string.Equals(container, "png", StringComparison.OrdinalIgnoreCase))
+ {
return ResolveImagePNGFormat(width, height);
+ }
- if (StringHelper.EqualsIgnoreCase(container, "gif"))
+ if (string.Equals(container, "gif", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.GIF_LRG;
+ }
- if (StringHelper.EqualsIgnoreCase(container, "raw"))
+ if (string.Equals(container, "raw", StringComparison.OrdinalIgnoreCase))
+ {
return MediaFormatProfile.RAW;
+ }
return null;
}
- private MediaFormatProfile ResolveImageJPGFormat(int? width, int? height)
+ private static MediaFormatProfile ResolveImageJPGFormat(int? width, int? height)
{
if (width.HasValue && height.HasValue)
{
if ((width.Value <= 160) && (height.Value <= 160))
+ {
return MediaFormatProfile.JPEG_TN;
+ }
if ((width.Value <= 640) && (height.Value <= 480))
+ {
return MediaFormatProfile.JPEG_SM;
+ }
if ((width.Value <= 1024) && (height.Value <= 768))
{
@@ -425,12 +516,14 @@ namespace MediaBrowser.Model.Dlna
return MediaFormatProfile.JPEG_SM;
}
- private MediaFormatProfile ResolveImagePNGFormat(int? width, int? height)
+ private static MediaFormatProfile ResolveImagePNGFormat(int? width, int? height)
{
if (width.HasValue && height.HasValue)
{
if ((width.Value <= 160) && (height.Value <= 160))
+ {
return MediaFormatProfile.PNG_TN;
+ }
}
return MediaFormatProfile.PNG_LRG;
diff --git a/MediaBrowser.Model/Dlna/PlaybackErrorCode.cs b/MediaBrowser.Model/Dlna/PlaybackErrorCode.cs
index 5080bc286..300fab5c5 100644
--- a/MediaBrowser.Model/Dlna/PlaybackErrorCode.cs
+++ b/MediaBrowser.Model/Dlna/PlaybackErrorCode.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum PlaybackErrorCode
diff --git a/MediaBrowser.Model/Dlna/ProfileCondition.cs b/MediaBrowser.Model/Dlna/ProfileCondition.cs
index b83566f6e..4b39d6875 100644
--- a/MediaBrowser.Model/Dlna/ProfileCondition.cs
+++ b/MediaBrowser.Model/Dlna/ProfileCondition.cs
@@ -1,21 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
{
public class ProfileCondition
{
- [XmlAttribute("condition")]
- public ProfileConditionType Condition { get; set; }
-
- [XmlAttribute("property")]
- public ProfileConditionValue Property { get; set; }
-
- [XmlAttribute("value")]
- public string Value { get; set; }
-
- [XmlAttribute("isRequired")]
- public bool IsRequired { get; set; }
-
public ProfileCondition()
{
IsRequired = true;
@@ -24,7 +15,6 @@ namespace MediaBrowser.Model.Dlna
public ProfileCondition(ProfileConditionType condition, ProfileConditionValue property, string value)
: this(condition, property, value, false)
{
-
}
public ProfileCondition(ProfileConditionType condition, ProfileConditionValue property, string value, bool isRequired)
@@ -34,5 +24,17 @@ namespace MediaBrowser.Model.Dlna
Value = value;
IsRequired = isRequired;
}
+
+ [XmlAttribute("condition")]
+ public ProfileConditionType Condition { get; set; }
+
+ [XmlAttribute("property")]
+ public ProfileConditionValue Property { get; set; }
+
+ [XmlAttribute("value")]
+ public string Value { get; set; }
+
+ [XmlAttribute("isRequired")]
+ public bool IsRequired { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/ProfileConditionType.cs b/MediaBrowser.Model/Dlna/ProfileConditionType.cs
index 262841262..fbf133857 100644
--- a/MediaBrowser.Model/Dlna/ProfileConditionType.cs
+++ b/MediaBrowser.Model/Dlna/ProfileConditionType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum ProfileConditionType
diff --git a/MediaBrowser.Model/Dlna/ProfileConditionValue.cs b/MediaBrowser.Model/Dlna/ProfileConditionValue.cs
index bae46bdcf..eb81fde75 100644
--- a/MediaBrowser.Model/Dlna/ProfileConditionValue.cs
+++ b/MediaBrowser.Model/Dlna/ProfileConditionValue.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum ProfileConditionValue
diff --git a/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs b/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs
index 6b1f85440..f8f76c69d 100644
--- a/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs
+++ b/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs
@@ -1,14 +1,17 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public class ResolutionConfiguration
{
- public int MaxWidth { get; set; }
- public int MaxBitrate { get; set; }
-
public ResolutionConfiguration(int maxWidth, int maxBitrate)
{
MaxWidth = maxWidth;
MaxBitrate = maxBitrate;
}
+
+ public int MaxWidth { get; set; }
+
+ public int MaxBitrate { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
index cf92633c3..94071b419 100644
--- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
+++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
@@ -1,9 +1,11 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
- public class ResolutionNormalizer
+ public static class ResolutionNormalizer
{
private static readonly ResolutionConfiguration[] Configurations =
new[]
@@ -13,19 +15,17 @@ namespace MediaBrowser.Model.Dlna
new ResolutionConfiguration(720, 950000),
new ResolutionConfiguration(1280, 2500000),
new ResolutionConfiguration(1920, 4000000),
+ new ResolutionConfiguration(2560, 20000000),
new ResolutionConfiguration(3840, 35000000)
};
- public static ResolutionOptions Normalize(int? inputBitrate,
- int? unused1,
- int? unused2,
+ public static ResolutionOptions Normalize(
+ int? inputBitrate,
int outputBitrate,
- string inputCodec,
- string outputCodec,
int? maxWidth,
int? maxHeight)
{
- // If the bitrate isn't changing, then don't downlscale the resolution
+ // If the bitrate isn't changing, then don't downscale the resolution
if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
{
if (maxWidth.HasValue || maxHeight.HasValue)
@@ -76,12 +76,13 @@ namespace MediaBrowser.Model.Dlna
private static double GetVideoBitrateScaleFactor(string codec)
{
- if (StringHelper.EqualsIgnoreCase(codec, "h265") ||
- StringHelper.EqualsIgnoreCase(codec, "hevc") ||
- StringHelper.EqualsIgnoreCase(codec, "vp9"))
+ if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
{
- return .5;
+ return .6;
}
+
return 1;
}
diff --git a/MediaBrowser.Model/Dlna/ResolutionOptions.cs b/MediaBrowser.Model/Dlna/ResolutionOptions.cs
index 30c078b55..774592abc 100644
--- a/MediaBrowser.Model/Dlna/ResolutionOptions.cs
+++ b/MediaBrowser.Model/Dlna/ResolutionOptions.cs
@@ -1,8 +1,11 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public class ResolutionOptions
{
public int? MaxWidth { get; set; }
+
public int? MaxHeight { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/ResponseProfile.cs b/MediaBrowser.Model/Dlna/ResponseProfile.cs
index 8c6b0806f..bf9661f7f 100644
--- a/MediaBrowser.Model/Dlna/ResponseProfile.cs
+++ b/MediaBrowser.Model/Dlna/ResponseProfile.cs
@@ -1,9 +1,18 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
{
public class ResponseProfile
{
+ public ResponseProfile()
+ {
+ Conditions = Array.Empty<ProfileCondition>();
+ }
+
[XmlAttribute("container")]
public string Container { get; set; }
@@ -24,11 +33,6 @@ namespace MediaBrowser.Model.Dlna
public ProfileCondition[] Conditions { get; set; }
- public ResponseProfile()
- {
- Conditions = new ProfileCondition[] { };
- }
-
public string[] GetContainers()
{
return ContainerProfile.SplitValue(Container);
diff --git a/MediaBrowser.Model/Dlna/SearchCriteria.cs b/MediaBrowser.Model/Dlna/SearchCriteria.cs
index 4f47c2821..b1fc48c08 100644
--- a/MediaBrowser.Model/Dlna/SearchCriteria.cs
+++ b/MediaBrowser.Model/Dlna/SearchCriteria.cs
@@ -1,41 +1,17 @@
+#pragma warning disable CS1591
+
using System;
using System.Text.RegularExpressions;
-using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
public class SearchCriteria
{
- public SearchType SearchType { get; set; }
-
- /// <summary>
- /// Splits the specified string.
- /// </summary>
- /// <param name="str">The string.</param>
- /// <param name="term">The term.</param>
- /// <param name="limit">The limit.</param>
- /// <returns>System.String[].</returns>
- private static string[] RegexSplit(string str, string term, int limit)
- {
- return new Regex(term).Split(str, limit);
- }
-
- /// <summary>
- /// Splits the specified string.
- /// </summary>
- /// <param name="str">The string.</param>
- /// <param name="term">The term.</param>
- /// <returns>System.String[].</returns>
- private static string[] RegexSplit(string str, string term)
- {
- return Regex.Split(str, term, RegexOptions.IgnoreCase);
- }
-
public SearchCriteria(string search)
{
- if (string.IsNullOrEmpty(search))
+ if (search.Length == 0)
{
- throw new ArgumentNullException(nameof(search));
+ throw new ArgumentException("String can't be empty.", nameof(search));
}
SearchType = SearchType.Unknown;
@@ -47,23 +23,22 @@ namespace MediaBrowser.Model.Dlna
if (subFactors.Length == 3)
{
-
- if (StringHelper.EqualsIgnoreCase("upnp:class", subFactors[0]) &&
- (StringHelper.EqualsIgnoreCase("=", subFactors[1]) || StringHelper.EqualsIgnoreCase("derivedfrom", subFactors[1])))
+ if (string.Equals("upnp:class", subFactors[0], StringComparison.OrdinalIgnoreCase)
+ && (string.Equals("=", subFactors[1], StringComparison.Ordinal) || string.Equals("derivedfrom", subFactors[1], StringComparison.OrdinalIgnoreCase)))
{
- if (StringHelper.EqualsIgnoreCase("\"object.item.imageItem\"", subFactors[2]) || StringHelper.EqualsIgnoreCase("\"object.item.imageItem.photo\"", subFactors[2]))
+ if (string.Equals("\"object.item.imageItem\"", subFactors[2], StringComparison.Ordinal) || string.Equals("\"object.item.imageItem.photo\"", subFactors[2], StringComparison.OrdinalIgnoreCase))
{
SearchType = SearchType.Image;
}
- else if (StringHelper.EqualsIgnoreCase("\"object.item.videoItem\"", subFactors[2]))
+ else if (string.Equals("\"object.item.videoItem\"", subFactors[2], StringComparison.OrdinalIgnoreCase))
{
SearchType = SearchType.Video;
}
- else if (StringHelper.EqualsIgnoreCase("\"object.container.playlistContainer\"", subFactors[2]))
+ else if (string.Equals("\"object.container.playlistContainer\"", subFactors[2], StringComparison.OrdinalIgnoreCase))
{
SearchType = SearchType.Playlist;
}
- else if (StringHelper.EqualsIgnoreCase("\"object.container.album.musicAlbum\"", subFactors[2]))
+ else if (string.Equals("\"object.container.album.musicAlbum\"", subFactors[2], StringComparison.OrdinalIgnoreCase))
{
SearchType = SearchType.MusicAlbum;
}
@@ -71,5 +46,30 @@ namespace MediaBrowser.Model.Dlna
}
}
}
+
+ public SearchType SearchType { get; set; }
+
+ /// <summary>
+ /// Splits the specified string.
+ /// </summary>
+ /// <param name="str">The string.</param>
+ /// <param name="term">The term.</param>
+ /// <param name="limit">The limit.</param>
+ /// <returns>System.String[].</returns>
+ private static string[] RegexSplit(string str, string term, int limit)
+ {
+ return new Regex(term).Split(str, limit);
+ }
+
+ /// <summary>
+ /// Splits the specified string.
+ /// </summary>
+ /// <param name="str">The string.</param>
+ /// <param name="term">The term.</param>
+ /// <returns>System.String[].</returns>
+ private static string[] RegexSplit(string str, string term)
+ {
+ return Regex.Split(str, term, RegexOptions.IgnoreCase);
+ }
}
}
diff --git a/MediaBrowser.Model/Dlna/SearchType.cs b/MediaBrowser.Model/Dlna/SearchType.cs
index 05c59f5de..8bc7c5249 100644
--- a/MediaBrowser.Model/Dlna/SearchType.cs
+++ b/MediaBrowser.Model/Dlna/SearchType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum SearchType
diff --git a/MediaBrowser.Model/Dlna/SortCriteria.cs b/MediaBrowser.Model/Dlna/SortCriteria.cs
index b5c1ac408..7769d0bd3 100644
--- a/MediaBrowser.Model/Dlna/SortCriteria.cs
+++ b/MediaBrowser.Model/Dlna/SortCriteria.cs
@@ -1,14 +1,15 @@
-using MediaBrowser.Model.Entities;
+#pragma warning disable CS1591
+
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Dlna
{
public class SortCriteria
{
- public SortOrder SortOrder => SortOrder.Ascending;
-
public SortCriteria(string value)
{
-
}
+
+ public SortOrder SortOrder => SortOrder.Ascending;
}
}
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index 586e322e4..84d99d550 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -1,10 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
@@ -22,7 +24,7 @@ namespace MediaBrowser.Model.Dlna
_logger = logger;
}
- public StreamBuilder(ILogger logger)
+ public StreamBuilder(ILogger<StreamBuilder> logger)
: this(new FullTranscoderSupport(), logger)
{
}
@@ -35,7 +37,7 @@ namespace MediaBrowser.Model.Dlna
foreach (MediaSourceInfo i in options.MediaSources)
{
if (string.IsNullOrEmpty(options.MediaSourceId) ||
- StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
+ string.Equals(i.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase))
{
mediaSources.Add(i);
}
@@ -68,7 +70,7 @@ namespace MediaBrowser.Model.Dlna
foreach (MediaSourceInfo i in options.MediaSources)
{
if (string.IsNullOrEmpty(options.MediaSourceId) ||
- StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
+ string.Equals(i.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase))
{
mediaSources.Add(i);
}
@@ -107,7 +109,6 @@ namespace MediaBrowser.Model.Dlna
}
return 1;
-
}).ThenBy(i =>
{
switch (i.PlayMethod)
@@ -119,7 +120,6 @@ namespace MediaBrowser.Model.Dlna
default:
return 1;
}
-
}).ThenBy(i =>
{
switch (i.MediaSource.Protocol)
@@ -129,7 +129,6 @@ namespace MediaBrowser.Model.Dlna
default:
return 1;
}
-
}).ThenBy(i =>
{
if (maxBitrate > 0)
@@ -141,7 +140,6 @@ namespace MediaBrowser.Model.Dlna
}
return 0;
-
}).ThenBy(streams.IndexOf);
}
@@ -229,7 +227,7 @@ namespace MediaBrowser.Model.Dlna
}
}
- public static string NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, string _, DeviceProfile profile, DlnaProfileType type)
+ public static string NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, DeviceProfile profile, DlnaProfileType type)
{
if (string.IsNullOrEmpty(inputContainer))
{
@@ -276,14 +274,14 @@ namespace MediaBrowser.Model.Dlna
if (options.ForceDirectPlay)
{
playlistItem.PlayMethod = PlayMethod.DirectPlay;
- playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio);
+ playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio);
return playlistItem;
}
if (options.ForceDirectStream)
{
playlistItem.PlayMethod = PlayMethod.DirectStream;
- playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio);
+ playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio);
return playlistItem;
}
@@ -299,7 +297,7 @@ namespace MediaBrowser.Model.Dlna
int? inputAudioSampleRate = audioStream?.SampleRate;
int? inputAudioBitDepth = audioStream?.BitDepth;
- if (directPlayMethods.Count() > 0)
+ if (directPlayMethods.Any())
{
string audioCodec = audioStream?.Codec;
@@ -338,6 +336,7 @@ namespace MediaBrowser.Model.Dlna
{
transcodeReasons.Add(transcodeReason.Value);
}
+
all = false;
break;
}
@@ -350,7 +349,7 @@ namespace MediaBrowser.Model.Dlna
playlistItem.PlayMethod = PlayMethod.DirectStream;
}
- playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio);
+ playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio);
return playlistItem;
}
@@ -385,7 +384,10 @@ namespace MediaBrowser.Model.Dlna
audioCodecProfiles.Add(i);
}
- if (audioCodecProfiles.Count >= 1) break;
+ if (audioCodecProfiles.Count >= 1)
+ {
+ break;
+ }
}
var audioTranscodingConditions = new List<ProfileCondition>();
@@ -453,9 +455,11 @@ namespace MediaBrowser.Model.Dlna
if (directPlayProfile == null)
{
- _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
+ _logger.LogInformation(
+ "Profile: {0}, No audio direct play profiles found for {1} with codec {2}",
options.Profile.Name ?? "Unknown Profile",
- item.Path ?? "Unknown path");
+ item.Path ?? "Unknown path",
+ audioStream.Codec ?? "Unknown codec");
return (Enumerable.Empty<PlayMethod>(), GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles));
}
@@ -496,7 +500,6 @@ namespace MediaBrowser.Model.Dlna
}
}
-
if (playMethods.Count > 0)
{
transcodeReasons.Clear();
@@ -511,6 +514,8 @@ namespace MediaBrowser.Model.Dlna
private static List<TranscodeReason> GetTranscodeReasonsFromDirectPlayProfile(MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream, IEnumerable<DirectPlayProfile> directPlayProfiles)
{
+ var mediaType = videoStream == null ? DlnaProfileType.Audio : DlnaProfileType.Video;
+
var containerSupported = false;
var audioSupported = false;
var videoSupported = false;
@@ -518,7 +523,7 @@ namespace MediaBrowser.Model.Dlna
foreach (var profile in directPlayProfiles)
{
// Check container type
- if (profile.SupportsContainer(item.Container))
+ if (profile.Type == mediaType && profile.SupportsContainer(item.Container))
{
containerSupported = true;
@@ -582,7 +587,7 @@ namespace MediaBrowser.Model.Dlna
{
foreach (var profile in subtitleProfiles)
{
- if (profile.Method == SubtitleDeliveryMethod.External && StringHelper.EqualsIgnoreCase(profile.Format, stream.Codec))
+ if (profile.Method == SubtitleDeliveryMethod.External && string.Equals(profile.Format, stream.Codec, StringComparison.OrdinalIgnoreCase))
{
return stream.Index;
}
@@ -628,10 +633,12 @@ namespace MediaBrowser.Model.Dlna
{
playlistItem.MinSegments = transcodingProfile.MinSegments;
}
+
if (transcodingProfile.SegmentLength > 0)
{
playlistItem.SegmentLength = transcodingProfile.SegmentLength;
}
+
playlistItem.SubProtocol = transcodingProfile.Protocol;
if (!string.IsNullOrEmpty(transcodingProfile.MaxAudioChannels)
@@ -669,13 +676,14 @@ namespace MediaBrowser.Model.Dlna
var videoStream = item.VideoStream;
- // TODO: This doesn't accout for situation of device being able to handle media bitrate, but wifi connection not fast enough
+ // TODO: This doesn't account for situations where the device is able to handle the media's bitrate, but the connection isn't fast enough
var directPlayEligibilityResult = IsEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options, true) ?? 0, subtitleStream, options, PlayMethod.DirectPlay);
var directStreamEligibilityResult = IsEligibleForDirectPlay(item, options.GetMaxBitrate(false) ?? 0, subtitleStream, options, PlayMethod.DirectStream);
bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1);
bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1);
- _logger.LogInformation("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
+ _logger.LogInformation(
+ "Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
options.Profile.Name ?? "Unknown Profile",
item.Path ?? "Unknown path",
isEligibleForDirectPlay,
@@ -686,13 +694,13 @@ namespace MediaBrowser.Model.Dlna
if (isEligibleForDirectPlay || isEligibleForDirectStream)
{
// See if it can be direct played
- var directPlayInfo = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, isEligibleForDirectPlay, isEligibleForDirectStream);
+ var directPlayInfo = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, isEligibleForDirectStream);
var directPlay = directPlayInfo.Item1;
if (directPlay != null)
{
playlistItem.PlayMethod = directPlay.Value;
- playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Video);
+ playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Video);
if (subtitleStream != null)
{
@@ -778,7 +786,7 @@ namespace MediaBrowser.Model.Dlna
if (!ConditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
{
- //LogConditionFailure(options.Profile, "VideoCodecProfile.ApplyConditions", applyCondition, item);
+ // LogConditionFailure(options.Profile, "VideoCodecProfile.ApplyConditions", applyCondition, item);
applyConditions = false;
break;
}
@@ -802,7 +810,7 @@ namespace MediaBrowser.Model.Dlna
// Honor requested max channels
playlistItem.GlobalMaxAudioChannels = options.MaxAudioChannels;
- int audioBitrate = GetAudioBitrate(playlistItem.SubProtocol, options.GetMaxBitrate(false) ?? 0, playlistItem.TargetAudioCodec, audioStream, playlistItem);
+ int audioBitrate = GetAudioBitrate(options.GetMaxBitrate(false) ?? 0, playlistItem.TargetAudioCodec, audioStream, playlistItem);
playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
isFirstAppliedCodecProfile = true;
@@ -822,7 +830,7 @@ namespace MediaBrowser.Model.Dlna
if (!ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth, audioProfile, isSecondaryAudio))
{
- //LogConditionFailure(options.Profile, "VideoCodecProfile.ApplyConditions", applyCondition, item);
+ // LogConditionFailure(options.Profile, "VideoCodecProfile.ApplyConditions", applyCondition, item);
applyConditions = false;
break;
}
@@ -866,17 +874,40 @@ namespace MediaBrowser.Model.Dlna
return playlistItem;
}
- private static int GetDefaultAudioBitrateIfUnknown(MediaStream audioStream)
+ private static int GetDefaultAudioBitrate(string audioCodec, int? audioChannels)
{
- if ((audioStream.Channels ?? 0) >= 6)
+ if (!string.IsNullOrEmpty(audioCodec))
{
- return 384000;
+ // Default to a higher bitrate for stream copy
+ if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
+ {
+ if ((audioChannels ?? 0) < 2)
+ {
+ return 128000;
+ }
+
+ return (audioChannels ?? 0) >= 6 ? 640000 : 384000;
+ }
+
+ if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
+ {
+ if ((audioChannels ?? 0) < 2)
+ {
+ return 768000;
+ }
+
+ return (audioChannels ?? 0) >= 6 ? 3584000 : 1536000;
+ }
}
return 192000;
}
- private static int GetAudioBitrate(string subProtocol, long maxTotalBitrate, string[] targetAudioCodecs, MediaStream audioStream, StreamInfo item)
+ private static int GetAudioBitrate(long maxTotalBitrate, string[] targetAudioCodecs, MediaStream audioStream, StreamInfo item)
{
string targetAudioCodec = targetAudioCodecs.Length == 0 ? null : targetAudioCodecs[0];
@@ -891,14 +922,27 @@ namespace MediaBrowser.Model.Dlna
}
else
{
- if (targetAudioChannels.HasValue && audioStream.Channels.HasValue && targetAudioChannels.Value < audioStream.Channels.Value)
+ if (targetAudioChannels.HasValue
+ && audioStream.Channels.HasValue
+ && audioStream.Channels.Value > targetAudioChannels.Value)
{
- // Reduce the bitrate if we're downmixing
- defaultBitrate = targetAudioChannels.Value < 2 ? 128000 : 192000;
+ // Reduce the bitrate if we're downmixing.
+ defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels);
+ }
+ else if (targetAudioChannels.HasValue
+ && audioStream.Channels.HasValue
+ && audioStream.Channels.Value <= targetAudioChannels.Value
+ && !string.IsNullOrEmpty(audioStream.Codec)
+ && targetAudioCodecs != null
+ && targetAudioCodecs.Length > 0
+ && !Array.Exists(targetAudioCodecs, elem => string.Equals(audioStream.Codec, elem, StringComparison.OrdinalIgnoreCase)))
+ {
+ // Shift the bitrate if we're transcoding to a different audio codec.
+ defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, audioStream.Channels.Value);
}
else
{
- defaultBitrate = audioStream.BitRate ?? GetDefaultAudioBitrateIfUnknown(audioStream);
+ defaultBitrate = audioStream.BitRate ?? GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels);
}
// Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
@@ -932,8 +976,28 @@ namespace MediaBrowser.Model.Dlna
{
return 448000;
}
+ else if (totalBitrate <= 4000000)
+ {
+ return 640000;
+ }
+ else if (totalBitrate <= 5000000)
+ {
+ return 768000;
+ }
+ else if (totalBitrate <= 10000000)
+ {
+ return 1536000;
+ }
+ else if (totalBitrate <= 15000000)
+ {
+ return 2304000;
+ }
+ else if (totalBitrate <= 20000000)
+ {
+ return 3584000;
+ }
- return 640000;
+ return 7168000;
}
private (PlayMethod?, List<TranscodeReason>) GetVideoDirectPlayProfile(
@@ -941,49 +1005,52 @@ namespace MediaBrowser.Model.Dlna
MediaSourceInfo mediaSource,
MediaStream videoStream,
MediaStream audioStream,
- bool isEligibleForDirectPlay,
bool isEligibleForDirectStream)
{
if (options.ForceDirectPlay)
{
return (PlayMethod.DirectPlay, new List<TranscodeReason>());
}
+
if (options.ForceDirectStream)
{
return (PlayMethod.DirectStream, new List<TranscodeReason>());
}
DeviceProfile profile = options.Profile;
+ string container = mediaSource.Container;
// See if it can be direct played
DirectPlayProfile directPlay = null;
- foreach (var i in profile.DirectPlayProfiles)
+ foreach (var p in profile.DirectPlayProfiles)
{
- if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream))
+ if (p.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(p, container, videoStream, audioStream))
{
- directPlay = i;
+ directPlay = p;
break;
}
}
if (directPlay == null)
{
- _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
- profile.Name ?? "Unknown Profile",
- mediaSource.Path ?? "Unknown path");
+ _logger.LogInformation(
+ "Container: {Container}, Video: {Video}, Audio: {Audio} cannot be direct played by profile: {Profile} for path: {Path}",
+ container,
+ videoStream?.Codec ?? "no video",
+ audioStream?.Codec ?? "no audio",
+ profile.Name ?? "unknown profile",
+ mediaSource.Path ?? "unknown path");
return (null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles));
}
- string container = mediaSource.Container;
-
var conditions = new List<ProfileCondition>();
- foreach (var i in profile.ContainerProfiles)
+ foreach (var p in profile.ContainerProfiles)
{
- if (i.Type == DlnaProfileType.Video
- && i.ContainsContainer(container))
+ if (p.Type == DlnaProfileType.Video
+ && p.ContainsContainer(container))
{
- foreach (var c in i.Conditions)
+ foreach (var c in p.Conditions)
{
conditions.Add(c);
}
@@ -1043,7 +1110,7 @@ namespace MediaBrowser.Model.Dlna
{
if (!ConditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
{
- //LogConditionFailure(profile, "VideoCodecProfile.ApplyConditions", applyCondition, mediaSource);
+ // LogConditionFailure(profile, "VideoCodecProfile.ApplyConditions", applyCondition, mediaSource);
applyConditions = false;
break;
}
@@ -1078,7 +1145,7 @@ namespace MediaBrowser.Model.Dlna
{
string audioCodec = audioStream.Codec;
conditions = new List<ProfileCondition>();
- bool? isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream);
+ bool? isSecondaryAudio = mediaSource.IsSecondaryAudio(audioStream);
foreach (var i in profile.CodecProfiles)
{
@@ -1089,7 +1156,7 @@ namespace MediaBrowser.Model.Dlna
{
if (!ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio))
{
- //LogConditionFailure(profile, "VideoAudioCodecProfile.ApplyConditions", applyCondition, mediaSource);
+ // LogConditionFailure(profile, "VideoAudioCodecProfile.ApplyConditions", applyCondition, mediaSource);
applyConditions = false;
break;
}
@@ -1131,7 +1198,8 @@ namespace MediaBrowser.Model.Dlna
private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
{
- _logger.LogInformation("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
+ _logger.LogInformation(
+ "Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
type,
profile.Name ?? "Unknown Profile",
condition.Property,
@@ -1161,7 +1229,7 @@ namespace MediaBrowser.Model.Dlna
bool result = IsAudioEligibleForDirectPlay(item, maxBitrate, playMethod);
- return (result, result ? (TranscodeReason?)null : TranscodeReason.ContainerBitrateExceedsLimit);
+ return (result, result ? null : TranscodeReason.ContainerBitrateExceedsLimit);
}
public static SubtitleProfile GetSubtitleProfile(
@@ -1193,12 +1261,12 @@ namespace MediaBrowser.Model.Dlna
continue;
}
- if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, outputContainer))
+ if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(outputContainer))
{
continue;
}
- if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
+ if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && string.Equals(profile.Format, subtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
{
return profile;
}
@@ -1222,7 +1290,7 @@ namespace MediaBrowser.Model.Dlna
continue;
}
- if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, outputContainer))
+ if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(outputContainer))
{
continue;
}
@@ -1244,7 +1312,7 @@ namespace MediaBrowser.Model.Dlna
};
}
- private static bool IsSubtitleEmbedSupported(MediaStream subtitleStream, SubtitleProfile subtitleProfile, string transcodingSubProtocol, string transcodingContainer)
+ private static bool IsSubtitleEmbedSupported(string transcodingContainer)
{
if (!string.IsNullOrEmpty(transcodingContainer))
{
@@ -1262,6 +1330,7 @@ namespace MediaBrowser.Model.Dlna
return true;
}
}
+
return false;
}
@@ -1292,7 +1361,7 @@ namespace MediaBrowser.Model.Dlna
if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) ||
(profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
{
- bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);
+ bool requiresConversion = !string.Equals(subtitleStream.Codec, profile.Format, StringComparison.OrdinalIgnoreCase);
if (!requiresConversion)
{
@@ -1335,8 +1404,11 @@ namespace MediaBrowser.Model.Dlna
if (itemBitrate > requestedMaxBitrate)
{
- _logger.LogInformation("Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}",
- playMethod, itemBitrate, requestedMaxBitrate);
+ _logger.LogInformation(
+ "Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}",
+ playMethod,
+ itemBitrate,
+ requestedMaxBitrate);
return false;
}
@@ -1364,14 +1436,17 @@ namespace MediaBrowser.Model.Dlna
{
throw new ArgumentException("ItemId is required");
}
+
if (string.IsNullOrEmpty(options.DeviceId))
{
throw new ArgumentException("DeviceId is required");
}
+
if (options.Profile == null)
{
throw new ArgumentException("Profile is required");
}
+
if (options.MediaSources == null)
{
throw new ArgumentException("MediaSources is required");
@@ -1419,8 +1494,36 @@ namespace MediaBrowser.Model.Dlna
item.AudioBitrate = Math.Max(num, item.AudioBitrate ?? num);
}
}
+
+ break;
+ }
+
+ case ProfileConditionValue.AudioSampleRate:
+ {
+ if (!enableNonQualifiedConditions)
+ {
+ continue;
+ }
+
+ if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var num))
+ {
+ if (condition.Condition == ProfileConditionType.Equals)
+ {
+ item.AudioSampleRate = num;
+ }
+ else if (condition.Condition == ProfileConditionType.LessThanEqual)
+ {
+ item.AudioSampleRate = Math.Min(num, item.AudioSampleRate ?? num);
+ }
+ else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
+ {
+ item.AudioSampleRate = Math.Max(num, item.AudioSampleRate ?? num);
+ }
+ }
+
break;
}
+
case ProfileConditionValue.AudioChannels:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1453,8 +1556,10 @@ namespace MediaBrowser.Model.Dlna
item.SetOption(qualifier, "audiochannels", Math.Max(num, item.GetTargetAudioChannels(qualifier) ?? num).ToString(CultureInfo.InvariantCulture));
}
}
+
break;
}
+
case ProfileConditionValue.IsAvc:
{
if (!enableNonQualifiedConditions)
@@ -1473,8 +1578,10 @@ namespace MediaBrowser.Model.Dlna
item.RequireAvc = true;
}
}
+
break;
}
+
case ProfileConditionValue.IsAnamorphic:
{
if (!enableNonQualifiedConditions)
@@ -1493,8 +1600,10 @@ namespace MediaBrowser.Model.Dlna
item.RequireNonAnamorphic = true;
}
}
+
break;
}
+
case ProfileConditionValue.IsInterlaced:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1523,8 +1632,10 @@ namespace MediaBrowser.Model.Dlna
item.SetOption(qualifier, "deinterlace", "true");
}
}
+
break;
}
+
case ProfileConditionValue.AudioProfile:
case ProfileConditionValue.Has64BitOffsets:
case ProfileConditionValue.PacketLength:
@@ -1536,6 +1647,7 @@ namespace MediaBrowser.Model.Dlna
// Not supported yet
break;
}
+
case ProfileConditionValue.RefFrames:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1568,8 +1680,10 @@ namespace MediaBrowser.Model.Dlna
item.SetOption(qualifier, "maxrefframes", Math.Max(num, item.GetTargetRefFrames(qualifier) ?? num).ToString(CultureInfo.InvariantCulture));
}
}
+
break;
}
+
case ProfileConditionValue.VideoBitDepth:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1602,8 +1716,10 @@ namespace MediaBrowser.Model.Dlna
item.SetOption(qualifier, "videobitdepth", Math.Max(num, item.GetTargetVideoBitDepth(qualifier) ?? num).ToString(CultureInfo.InvariantCulture));
}
}
+
break;
}
+
case ProfileConditionValue.VideoProfile:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1611,21 +1727,19 @@ namespace MediaBrowser.Model.Dlna
continue;
}
- if (!string.IsNullOrEmpty(value))
- {
- // change from split by | to comma
-
- // strip spaces to avoid having to encode
- var values = value
- .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ // change from split by | to comma
+ // strip spaces to avoid having to encode
+ var values = value
+ .Split('|', StringSplitOptions.RemoveEmptyEntries);
- if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny)
- {
- item.SetOption(qualifier, "profile", string.Join(",", values));
- }
+ if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny)
+ {
+ item.SetOption(qualifier, "profile", string.Join(',', values));
}
+
break;
}
+
case ProfileConditionValue.Height:
{
if (!enableNonQualifiedConditions)
@@ -1648,8 +1762,10 @@ namespace MediaBrowser.Model.Dlna
item.MaxHeight = Math.Max(num, item.MaxHeight ?? num);
}
}
+
break;
}
+
case ProfileConditionValue.VideoBitrate:
{
if (!enableNonQualifiedConditions)
@@ -1672,8 +1788,10 @@ namespace MediaBrowser.Model.Dlna
item.VideoBitrate = Math.Max(num, item.VideoBitrate ?? num);
}
}
+
break;
}
+
case ProfileConditionValue.VideoFramerate:
{
if (!enableNonQualifiedConditions)
@@ -1696,8 +1814,10 @@ namespace MediaBrowser.Model.Dlna
item.MaxFramerate = Math.Max(num, item.MaxFramerate ?? num);
}
}
+
break;
}
+
case ProfileConditionValue.VideoLevel:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1720,8 +1840,10 @@ namespace MediaBrowser.Model.Dlna
item.SetOption(qualifier, "level", Math.Max(num, item.GetTargetVideoLevel(qualifier) ?? num).ToString(CultureInfo.InvariantCulture));
}
}
+
break;
}
+
case ProfileConditionValue.Width:
{
if (!enableNonQualifiedConditions)
@@ -1744,8 +1866,10 @@ namespace MediaBrowser.Model.Dlna
item.MaxWidth = Math.Max(num, item.MaxWidth ?? num);
}
}
+
break;
}
+
default:
break;
}
@@ -1770,10 +1894,10 @@ namespace MediaBrowser.Model.Dlna
return true;
}
- private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
+ private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, string container, MediaStream videoStream, MediaStream audioStream)
{
// Check container type
- if (!profile.SupportsContainer(item.Container))
+ if (!profile.SupportsContainer(container))
{
return false;
}
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index 10efb9b38..4414415a2 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -5,7 +8,6 @@ using System.Linq;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
@@ -25,48 +27,10 @@ namespace MediaBrowser.Model.Dlna
StreamOptions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
- public void SetOption(string qualifier, string name, string value)
- {
- if (string.IsNullOrEmpty(qualifier))
- {
- SetOption(name, value);
- }
- else
- {
- SetOption(qualifier + "-" + name, value);
- }
- }
-
- public void SetOption(string name, string value)
- {
- StreamOptions[name] = value;
- }
-
- public string GetOption(string qualifier, string name)
- {
- var value = GetOption(qualifier + "-" + name);
-
- if (string.IsNullOrEmpty(value))
- {
- value = GetOption(name);
- }
-
- return value;
- }
-
- public string GetOption(string name)
- {
- if (StreamOptions.TryGetValue(name, out var value))
- {
- return value;
- }
-
- return null;
- }
-
public Guid ItemId { get; set; }
public PlayMethod PlayMethod { get; set; }
+
public EncodingContext Context { get; set; }
public DlnaProfileType MediaType { get; set; }
@@ -78,15 +42,23 @@ namespace MediaBrowser.Model.Dlna
public long StartPositionTicks { get; set; }
public int? SegmentLength { get; set; }
+
public int? MinSegments { get; set; }
+
public bool BreakOnNonKeyFrames { get; set; }
public bool RequireAvc { get; set; }
+
public bool RequireNonAnamorphic { get; set; }
+
public bool CopyTimestamps { get; set; }
+
public bool EnableMpegtsM2TsMode { get; set; }
+
public bool EnableSubtitlesInManifest { get; set; }
+
public string[] AudioCodecs { get; set; }
+
public string[] VideoCodecs { get; set; }
public int? AudioStreamIndex { get; set; }
@@ -94,19 +66,25 @@ namespace MediaBrowser.Model.Dlna
public int? SubtitleStreamIndex { get; set; }
public int? TranscodingMaxAudioChannels { get; set; }
+
public int? GlobalMaxAudioChannels { get; set; }
public int? AudioBitrate { get; set; }
+ public int? AudioSampleRate { get; set; }
+
public int? VideoBitrate { get; set; }
public int? MaxWidth { get; set; }
+
public int? MaxHeight { get; set; }
public float? MaxFramerate { get; set; }
public DeviceProfile DeviceProfile { get; set; }
+
public string DeviceProfileId { get; set; }
+
public string DeviceId { get; set; }
public long? RunTimeTicks { get; set; }
@@ -118,396 +96,49 @@ namespace MediaBrowser.Model.Dlna
public MediaSourceInfo MediaSource { get; set; }
public string[] SubtitleCodecs { get; set; }
+
public SubtitleDeliveryMethod SubtitleDeliveryMethod { get; set; }
+
public string SubtitleFormat { get; set; }
public string PlaySessionId { get; set; }
+
public TranscodeReason[] TranscodeReasons { get; set; }
public Dictionary<string, string> StreamOptions { get; private set; }
- public string MediaSourceId => MediaSource == null ? null : MediaSource.Id;
+ public string MediaSourceId => MediaSource?.Id;
public bool IsDirectStream =>
PlayMethod == PlayMethod.DirectStream ||
PlayMethod == PlayMethod.DirectPlay;
- public string ToUrl(string baseUrl, string accessToken)
- {
- if (PlayMethod == PlayMethod.DirectPlay)
- {
- return MediaSource.Path;
- }
-
- if (string.IsNullOrEmpty(baseUrl))
- {
- throw new ArgumentNullException(nameof(baseUrl));
- }
-
- var list = new List<string>();
- foreach (NameValuePair pair in BuildParams(this, accessToken))
- {
- if (string.IsNullOrEmpty(pair.Value))
- {
- continue;
- }
-
- // Try to keep the url clean by omitting defaults
- if (StringHelper.EqualsIgnoreCase(pair.Name, "StartTimeTicks") &&
- StringHelper.EqualsIgnoreCase(pair.Value, "0"))
- {
- continue;
- }
- if (StringHelper.EqualsIgnoreCase(pair.Name, "SubtitleStreamIndex") &&
- StringHelper.EqualsIgnoreCase(pair.Value, "-1"))
- {
- continue;
- }
- if (StringHelper.EqualsIgnoreCase(pair.Name, "Static") &&
- StringHelper.EqualsIgnoreCase(pair.Value, "false"))
- {
- continue;
- }
-
- var encodedValue = pair.Value.Replace(" ", "%20");
-
- list.Add(string.Format("{0}={1}", pair.Name, encodedValue));
- }
-
- string queryString = string.Join("&", list.ToArray());
-
- return GetUrl(baseUrl, queryString);
- }
-
- private string GetUrl(string baseUrl, string queryString)
- {
- if (string.IsNullOrEmpty(baseUrl))
- {
- throw new ArgumentNullException(nameof(baseUrl));
- }
-
- string extension = string.IsNullOrEmpty(Container) ? string.Empty : "." + Container;
-
- baseUrl = baseUrl.TrimEnd('/');
-
- if (MediaType == DlnaProfileType.Audio)
- {
- if (StringHelper.EqualsIgnoreCase(SubProtocol, "hls"))
- {
- return string.Format("{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
- }
-
- return string.Format("{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
- }
-
- if (StringHelper.EqualsIgnoreCase(SubProtocol, "hls"))
- {
- return string.Format("{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
- }
-
- return string.Format("{0}/videos/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
- }
-
- private static List<NameValuePair> BuildParams(StreamInfo item, string accessToken)
- {
- var list = new List<NameValuePair>();
-
- string audioCodecs = item.AudioCodecs.Length == 0 ?
- string.Empty :
- string.Join(",", item.AudioCodecs);
-
- string videoCodecs = item.VideoCodecs.Length == 0 ?
- string.Empty :
- string.Join(",", item.VideoCodecs);
-
- list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty));
- list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty));
- list.Add(new NameValuePair("MediaSourceId", item.MediaSourceId ?? string.Empty));
- list.Add(new NameValuePair("Static", item.IsDirectStream.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- 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("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("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
- list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
- list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? item.MaxHeight.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
-
- long startPositionTicks = item.StartPositionTicks;
-
- var isHls = StringHelper.EqualsIgnoreCase(item.SubProtocol, "hls");
-
- if (isHls)
- {
- list.Add(new NameValuePair("StartTimeTicks", string.Empty));
- }
- else
- {
- list.Add(new NameValuePair("StartTimeTicks", startPositionTicks.ToString(CultureInfo.InvariantCulture)));
- }
-
- list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty));
- list.Add(new NameValuePair("api_key", accessToken ?? string.Empty));
-
- string liveStreamId = item.MediaSource?.LiveStreamId;
- list.Add(new NameValuePair("LiveStreamId", liveStreamId ?? string.Empty));
-
- list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
-
-
- if (!item.IsDirectStream)
- {
- if (item.RequireNonAnamorphic)
- {
- list.Add(new NameValuePair("RequireNonAnamorphic", item.RequireNonAnamorphic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- list.Add(new NameValuePair("TranscodingMaxAudioChannels", item.TranscodingMaxAudioChannels.HasValue ? item.TranscodingMaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
-
- if (item.EnableSubtitlesInManifest)
- {
- list.Add(new NameValuePair("EnableSubtitlesInManifest", item.EnableSubtitlesInManifest.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- if (item.EnableMpegtsM2TsMode)
- {
- list.Add(new NameValuePair("EnableMpegtsM2TsMode", item.EnableMpegtsM2TsMode.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- if (item.EstimateContentLength)
- {
- list.Add(new NameValuePair("EstimateContentLength", item.EstimateContentLength.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- if (item.TranscodeSeekInfo != TranscodeSeekInfo.Auto)
- {
- list.Add(new NameValuePair("TranscodeSeekInfo", item.TranscodeSeekInfo.ToString().ToLowerInvariant()));
- }
-
- if (item.CopyTimestamps)
- {
- list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
-
- list.Add(new NameValuePair("Tag", item.MediaSource.ETag ?? string.Empty));
-
- string subtitleCodecs = item.SubtitleCodecs.Length == 0 ?
- string.Empty :
- string.Join(",", item.SubtitleCodecs);
-
- list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty));
-
- if (isHls)
- {
- list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty));
-
- if (item.SegmentLength.HasValue)
- {
- list.Add(new NameValuePair("SegmentLength", item.SegmentLength.Value.ToString(CultureInfo.InvariantCulture)));
- }
-
- if (item.MinSegments.HasValue)
- {
- list.Add(new NameValuePair("MinSegments", item.MinSegments.Value.ToString(CultureInfo.InvariantCulture)));
- }
-
- list.Add(new NameValuePair("BreakOnNonKeyFrames", item.BreakOnNonKeyFrames.ToString(CultureInfo.InvariantCulture)));
- }
-
- foreach (var pair in item.StreamOptions)
- {
- if (string.IsNullOrEmpty(pair.Value))
- {
- continue;
- }
-
- // strip spaces to avoid having to encode h264 profile names
- list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", "")));
- }
-
- if (!item.IsDirectStream)
- {
- list.Add(new NameValuePair("TranscodeReasons", string.Join(",", item.TranscodeReasons.Distinct().Select(i => i.ToString()))));
- }
-
- return list;
- }
-
- public List<SubtitleStreamInfo> GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken)
- {
- return GetExternalSubtitles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken);
- }
-
- public List<SubtitleStreamInfo> GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken)
- {
- var list = GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, enableAllProfiles, baseUrl, accessToken);
- var newList = new List<SubtitleStreamInfo>();
-
- // First add the selected track
- foreach (SubtitleStreamInfo stream in list)
- {
- if (stream.DeliveryMethod == SubtitleDeliveryMethod.External)
- {
- newList.Add(stream);
- }
- }
-
- return newList;
- }
-
- public List<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken)
- {
- return GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken);
- }
-
- public List<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken)
- {
- var list = new List<SubtitleStreamInfo>();
-
- // HLS will preserve timestamps so we can just grab the full subtitle stream
- long startPositionTicks = StringHelper.EqualsIgnoreCase(SubProtocol, "hls")
- ? 0
- : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0);
-
- // First add the selected track
- if (SubtitleStreamIndex.HasValue)
- {
- foreach (var stream in MediaSource.MediaStreams)
- {
- if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value)
- {
- AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
- }
- }
- }
-
- if (!includeSelectedTrackOnly)
- {
- foreach (var stream in MediaSource.MediaStreams)
- {
- if (stream.Type == MediaStreamType.Subtitle && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value))
- {
- AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
- }
- }
- }
-
- return list;
- }
-
- private void AddSubtitleProfiles(List<SubtitleStreamInfo> list, MediaStream stream, ITranscoderSupport transcoderSupport, bool enableAllProfiles, string baseUrl, string accessToken, long startPositionTicks)
- {
- if (enableAllProfiles)
- {
- foreach (var profile in DeviceProfile.SubtitleProfiles)
- {
- var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, new[] { profile }, transcoderSupport);
-
- list.Add(info);
- }
- }
- else
- {
- var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, DeviceProfile.SubtitleProfiles, transcoderSupport);
-
- list.Add(info);
- }
- }
-
- private SubtitleStreamInfo GetSubtitleStreamInfo(MediaStream stream, string baseUrl, string accessToken, long startPositionTicks, SubtitleProfile[] subtitleProfiles, ITranscoderSupport transcoderSupport)
- {
- var subtitleProfile = StreamBuilder.GetSubtitleProfile(MediaSource, stream, subtitleProfiles, PlayMethod, transcoderSupport, Container, SubProtocol);
- var info = new SubtitleStreamInfo
- {
- IsForced = stream.IsForced,
- Language = stream.Language,
- Name = stream.Language ?? "Unknown",
- Format = subtitleProfile.Format,
- Index = stream.Index,
- DeliveryMethod = subtitleProfile.Method,
- DisplayTitle = stream.DisplayTitle
- };
-
- if (info.DeliveryMethod == SubtitleDeliveryMethod.External)
- {
- if (MediaSource.Protocol == MediaProtocol.File || !StringHelper.EqualsIgnoreCase(stream.Codec, subtitleProfile.Format) || !stream.IsExternal)
- {
- info.Url = string.Format("{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}",
- baseUrl,
- ItemId,
- MediaSourceId,
- stream.Index.ToString(CultureInfo.InvariantCulture),
- startPositionTicks.ToString(CultureInfo.InvariantCulture),
- subtitleProfile.Format);
-
- if (!string.IsNullOrEmpty(accessToken))
- {
- info.Url += "?api_key=" + accessToken;
- }
-
- info.IsExternalUrl = false;
- }
- else
- {
- info.Url = stream.Path;
- info.IsExternalUrl = true;
- }
- }
-
- return info;
- }
-
/// <summary>
- /// Returns the audio stream that will be used
+ /// Gets the audio stream that will be used.
/// </summary>
- public MediaStream TargetAudioStream
- {
- get
- {
- if (MediaSource != null)
- {
- return MediaSource.GetDefaultAudioStream(AudioStreamIndex);
- }
-
- return null;
- }
- }
+ public MediaStream TargetAudioStream => MediaSource?.GetDefaultAudioStream(AudioStreamIndex);
/// <summary>
- /// Returns the video stream that will be used
+ /// Gets the video stream that will be used.
/// </summary>
- public MediaStream TargetVideoStream
- {
- get
- {
- if (MediaSource != null)
- {
- return MediaSource.VideoStream;
- }
-
- return null;
- }
- }
+ public MediaStream TargetVideoStream => MediaSource?.VideoStream;
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public int? TargetAudioSampleRate
{
get
{
var stream = TargetAudioStream;
- return stream == null ? null : stream.SampleRate;
+ return AudioSampleRate.HasValue && !IsDirectStream
+ ? AudioSampleRate
+ : stream?.SampleRate;
}
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public int? TargetAudioBitDepth
{
@@ -515,7 +146,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetAudioStream == null ? (int?)null : TargetAudioStream.BitDepth;
+ return TargetAudioStream?.BitDepth;
}
var targetAudioCodecs = TargetAudioCodec;
@@ -525,12 +156,12 @@ namespace MediaBrowser.Model.Dlna
return GetTargetAudioBitDepth(audioCodec);
}
- return TargetAudioStream == null ? (int?)null : TargetAudioStream.BitDepth;
+ return TargetAudioStream?.BitDepth;
}
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public int? TargetVideoBitDepth
{
@@ -538,7 +169,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? (int?)null : TargetVideoStream.BitDepth;
+ return TargetVideoStream?.BitDepth;
}
var targetVideoCodecs = TargetVideoCodec;
@@ -548,7 +179,7 @@ namespace MediaBrowser.Model.Dlna
return GetTargetVideoBitDepth(videoCodec);
}
- return TargetVideoStream == null ? (int?)null : TargetVideoStream.BitDepth;
+ return TargetVideoStream?.BitDepth;
}
}
@@ -562,7 +193,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? (int?)null : TargetVideoStream.RefFrames;
+ return TargetVideoStream?.RefFrames;
}
var targetVideoCodecs = TargetVideoCodec;
@@ -572,12 +203,12 @@ namespace MediaBrowser.Model.Dlna
return GetTargetRefFrames(videoCodec);
}
- return TargetVideoStream == null ? (int?)null : TargetVideoStream.RefFrames;
+ return TargetVideoStream?.RefFrames;
}
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public float? TargetFramerate
{
@@ -591,7 +222,7 @@ namespace MediaBrowser.Model.Dlna
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public double? TargetVideoLevel
{
@@ -599,7 +230,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? (double?)null : TargetVideoStream.Level;
+ return TargetVideoStream?.Level;
}
var targetVideoCodecs = TargetVideoCodec;
@@ -609,76 +240,12 @@ namespace MediaBrowser.Model.Dlna
return GetTargetVideoLevel(videoCodec);
}
- return TargetVideoStream == null ? (double?)null : TargetVideoStream.Level;
+ return TargetVideoStream?.Level;
}
}
- public int? GetTargetVideoBitDepth(string codec)
- {
- var value = GetOption(codec, "videobitdepth");
- if (string.IsNullOrEmpty(value))
- {
- return null;
- }
-
- if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return null;
- }
-
- public int? GetTargetAudioBitDepth(string codec)
- {
- var value = GetOption(codec, "audiobitdepth");
- if (string.IsNullOrEmpty(value))
- {
- return null;
- }
-
- if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return null;
- }
-
- public double? GetTargetVideoLevel(string codec)
- {
- var value = GetOption(codec, "level");
- if (string.IsNullOrEmpty(value))
- {
- return null;
- }
-
- if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return null;
- }
-
- public int? GetTargetRefFrames(string codec)
- {
- var value = GetOption(codec, "maxrefframes");
- if (string.IsNullOrEmpty(value))
- {
- return null;
- }
-
- if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
- {
- return result;
- }
-
- return null;
- }
-
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public int? TargetPacketLength
{
@@ -687,12 +254,12 @@ namespace MediaBrowser.Model.Dlna
var stream = TargetVideoStream;
return !IsDirectStream
? null
- : stream == null ? null : stream.PacketLength;
+ : stream?.PacketLength;
}
}
/// <summary>
- /// Predicts the audio sample rate that will be in the output stream
+ /// Gets the audio sample rate that will be in the output stream.
/// </summary>
public string TargetVideoProfile
{
@@ -700,7 +267,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? null : TargetVideoStream.Profile;
+ return TargetVideoStream?.Profile;
}
var targetVideoCodecs = TargetVideoCodec;
@@ -710,7 +277,7 @@ namespace MediaBrowser.Model.Dlna
return GetOption(videoCodec, "profile");
}
- return TargetVideoStream == null ? null : TargetVideoStream.Profile;
+ return TargetVideoStream?.Profile;
}
}
@@ -725,12 +292,12 @@ namespace MediaBrowser.Model.Dlna
var stream = TargetVideoStream;
return !IsDirectStream
? null
- : stream == null ? null : stream.CodecTag;
+ : stream?.CodecTag;
}
}
/// <summary>
- /// Predicts the audio bitrate that will be in the output stream
+ /// Gets the audio bitrate that will be in the output stream.
/// </summary>
public int? TargetAudioBitrate
{
@@ -739,12 +306,12 @@ namespace MediaBrowser.Model.Dlna
var stream = TargetAudioStream;
return AudioBitrate.HasValue && !IsDirectStream
? AudioBitrate
- : stream == null ? null : stream.BitRate;
+ : stream?.BitRate;
}
}
/// <summary>
- /// Predicts the audio channels that will be in the output stream
+ /// Gets the audio channels that will be in the output stream.
/// </summary>
public int? TargetAudioChannels
{
@@ -752,7 +319,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetAudioStream == null ? (int?)null : TargetAudioStream.Channels;
+ return TargetAudioStream?.Channels;
}
var targetAudioCodecs = TargetAudioCodec;
@@ -762,30 +329,12 @@ namespace MediaBrowser.Model.Dlna
return GetTargetRefFrames(codec);
}
- return TargetAudioStream == null ? (int?)null : TargetAudioStream.Channels;
- }
- }
-
- public int? GetTargetAudioChannels(string codec)
- {
- var defaultValue = GlobalMaxAudioChannels;
-
- var value = GetOption(codec, "audiochannels");
- if (string.IsNullOrEmpty(value))
- {
- return defaultValue;
- }
-
- if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
- {
- return Math.Min(result, defaultValue ?? result);
+ return TargetAudioStream?.Channels;
}
-
- return defaultValue;
}
/// <summary>
- /// Predicts the audio codec that will be in the output stream
+ /// Gets the audio codec that will be in the output stream.
/// </summary>
public string[] TargetAudioCodec
{
@@ -793,18 +342,18 @@ namespace MediaBrowser.Model.Dlna
{
var stream = TargetAudioStream;
- string inputCodec = stream == null ? null : stream.Codec;
+ string inputCodec = stream?.Codec;
if (IsDirectStream)
{
- return string.IsNullOrEmpty(inputCodec) ? new string[] { } : new[] { inputCodec };
+ return string.IsNullOrEmpty(inputCodec) ? Array.Empty<string>() : new[] { inputCodec };
}
foreach (string codec in AudioCodecs)
{
- if (StringHelper.EqualsIgnoreCase(codec, inputCodec))
+ if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase))
{
- return string.IsNullOrEmpty(codec) ? new string[] { } : new[] { codec };
+ return string.IsNullOrEmpty(codec) ? Array.Empty<string>() : new[] { codec };
}
}
@@ -818,18 +367,18 @@ namespace MediaBrowser.Model.Dlna
{
var stream = TargetVideoStream;
- string inputCodec = stream == null ? null : stream.Codec;
+ string inputCodec = stream?.Codec;
if (IsDirectStream)
{
- return string.IsNullOrEmpty(inputCodec) ? new string[] { } : new[] { inputCodec };
+ return string.IsNullOrEmpty(inputCodec) ? Array.Empty<string>() : new[] { inputCodec };
}
foreach (string codec in VideoCodecs)
{
- if (StringHelper.EqualsIgnoreCase(codec, inputCodec))
+ if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase))
{
- return string.IsNullOrEmpty(codec) ? new string[] { } : new[] { codec };
+ return string.IsNullOrEmpty(codec) ? Array.Empty<string>() : new[] { codec };
}
}
@@ -838,7 +387,7 @@ namespace MediaBrowser.Model.Dlna
}
/// <summary>
- /// Predicts the audio channels that will be in the output stream
+ /// Gets the audio channels that will be in the output stream.
/// </summary>
public long? TargetSize
{
@@ -876,7 +425,7 @@ namespace MediaBrowser.Model.Dlna
return VideoBitrate.HasValue && !IsDirectStream
? VideoBitrate
- : stream == null ? null : stream.BitRate;
+ : stream?.BitRate;
}
}
@@ -884,7 +433,7 @@ namespace MediaBrowser.Model.Dlna
{
get
{
- var defaultValue = StringHelper.EqualsIgnoreCase(Container, "m2ts")
+ var defaultValue = string.Equals(Container, "m2ts", StringComparison.OrdinalIgnoreCase)
? TransportStreamTimestamp.Valid
: TransportStreamTimestamp.None;
@@ -902,7 +451,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? null : TargetVideoStream.IsAnamorphic;
+ return TargetVideoStream?.IsAnamorphic;
}
return false;
@@ -915,7 +464,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? (bool?)null : TargetVideoStream.IsInterlaced;
+ return TargetVideoStream?.IsInterlaced;
}
var targetVideoCodecs = TargetVideoCodec;
@@ -928,7 +477,7 @@ namespace MediaBrowser.Model.Dlna
}
}
- return TargetVideoStream == null ? (bool?)null : TargetVideoStream.IsInterlaced;
+ return TargetVideoStream?.IsInterlaced;
}
}
@@ -938,7 +487,7 @@ namespace MediaBrowser.Model.Dlna
{
if (IsDirectStream)
{
- return TargetVideoStream == null ? null : TargetVideoStream.IsAVC;
+ return TargetVideoStream?.IsAVC;
}
return true;
@@ -991,6 +540,7 @@ namespace MediaBrowser.Model.Dlna
{
return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
}
+
return GetMediaStreamCount(MediaStreamType.Video, 1);
}
}
@@ -1003,45 +553,476 @@ namespace MediaBrowser.Model.Dlna
{
return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
}
+
return GetMediaStreamCount(MediaStreamType.Audio, 1);
}
}
- private int? GetMediaStreamCount(MediaStreamType type, int limit)
+ public void SetOption(string qualifier, string name, string value)
{
- var count = MediaSource.GetStreamCount(type);
+ if (string.IsNullOrEmpty(qualifier))
+ {
+ SetOption(name, value);
+ }
+ else
+ {
+ SetOption(qualifier + "-" + name, value);
+ }
+ }
- if (count.HasValue)
+ public void SetOption(string name, string value)
+ {
+ StreamOptions[name] = value;
+ }
+
+ public string GetOption(string qualifier, string name)
+ {
+ var value = GetOption(qualifier + "-" + name);
+
+ if (string.IsNullOrEmpty(value))
{
- count = Math.Min(count.Value, limit);
+ value = GetOption(name);
}
- return count;
+ return value;
}
- public List<MediaStream> GetSelectableAudioStreams()
+ public string GetOption(string name)
{
- return GetSelectableStreams(MediaStreamType.Audio);
+ if (StreamOptions.TryGetValue(name, out var value))
+ {
+ return value;
+ }
+
+ return null;
}
- public List<MediaStream> GetSelectableSubtitleStreams()
+ public string ToUrl(string baseUrl, string accessToken)
{
- return GetSelectableStreams(MediaStreamType.Subtitle);
+ if (PlayMethod == PlayMethod.DirectPlay)
+ {
+ return MediaSource.Path;
+ }
+
+ if (string.IsNullOrEmpty(baseUrl))
+ {
+ throw new ArgumentNullException(nameof(baseUrl));
+ }
+
+ var list = new List<string>();
+ foreach (NameValuePair pair in BuildParams(this, accessToken))
+ {
+ if (string.IsNullOrEmpty(pair.Value))
+ {
+ continue;
+ }
+
+ // Try to keep the url clean by omitting defaults
+ if (string.Equals(pair.Name, "StartTimeTicks", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(pair.Value, "0", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ if (string.Equals(pair.Name, "SubtitleStreamIndex", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(pair.Value, "-1", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ var encodedValue = pair.Value.Replace(" ", "%20", StringComparison.Ordinal);
+
+ list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", pair.Name, encodedValue));
+ }
+
+ string queryString = string.Join('&', list);
+
+ return GetUrl(baseUrl, queryString);
+ }
+
+ private string GetUrl(string baseUrl, string queryString)
+ {
+ if (string.IsNullOrEmpty(baseUrl))
+ {
+ throw new ArgumentNullException(nameof(baseUrl));
+ }
+
+ string extension = string.IsNullOrEmpty(Container) ? string.Empty : "." + Container;
+
+ baseUrl = baseUrl.TrimEnd('/');
+
+ if (MediaType == DlnaProfileType.Audio)
+ {
+ if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
+ }
+
+ return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
+ }
+
+ if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
+ }
+
+ return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
}
- public List<MediaStream> GetSelectableStreams(MediaStreamType type)
+ private static List<NameValuePair> BuildParams(StreamInfo item, string accessToken)
{
- var list = new List<MediaStream>();
+ var list = new List<NameValuePair>();
+
+ string audioCodecs = item.AudioCodecs.Length == 0 ?
+ string.Empty :
+ string.Join(',', item.AudioCodecs);
+
+ string videoCodecs = item.VideoCodecs.Length == 0 ?
+ string.Empty :
+ string.Join(',', item.VideoCodecs);
+
+ list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty));
+ list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty));
+ list.Add(new NameValuePair("MediaSourceId", item.MediaSourceId ?? string.Empty));
+ list.Add(new NameValuePair("Static", item.IsDirectStream.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ 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("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));
+
+ list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+ list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+ list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? item.MaxHeight.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+
+ long startPositionTicks = item.StartPositionTicks;
+
+ var isHls = string.Equals(item.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase);
+
+ if (isHls)
+ {
+ list.Add(new NameValuePair("StartTimeTicks", string.Empty));
+ }
+ else
+ {
+ list.Add(new NameValuePair("StartTimeTicks", startPositionTicks.ToString(CultureInfo.InvariantCulture)));
+ }
+
+ list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty));
+ list.Add(new NameValuePair("api_key", accessToken ?? string.Empty));
- foreach (var stream in MediaSource.MediaStreams)
+ string liveStreamId = item.MediaSource?.LiveStreamId;
+ list.Add(new NameValuePair("LiveStreamId", liveStreamId ?? string.Empty));
+
+ list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
+
+ if (!item.IsDirectStream)
{
- if (type == stream.Type)
+ if (item.RequireNonAnamorphic)
{
- list.Add(stream);
+ list.Add(new NameValuePair("RequireNonAnamorphic", item.RequireNonAnamorphic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
}
+
+ list.Add(new NameValuePair("TranscodingMaxAudioChannels", item.TranscodingMaxAudioChannels.HasValue ? item.TranscodingMaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+
+ if (item.EnableSubtitlesInManifest)
+ {
+ list.Add(new NameValuePair("EnableSubtitlesInManifest", item.EnableSubtitlesInManifest.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ }
+
+ if (item.EnableMpegtsM2TsMode)
+ {
+ list.Add(new NameValuePair("EnableMpegtsM2TsMode", item.EnableMpegtsM2TsMode.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ }
+
+ if (item.EstimateContentLength)
+ {
+ list.Add(new NameValuePair("EstimateContentLength", item.EstimateContentLength.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ }
+
+ if (item.TranscodeSeekInfo != TranscodeSeekInfo.Auto)
+ {
+ list.Add(new NameValuePair("TranscodeSeekInfo", item.TranscodeSeekInfo.ToString().ToLowerInvariant()));
+ }
+
+ if (item.CopyTimestamps)
+ {
+ list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ }
+
+ list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
+ }
+
+ list.Add(new NameValuePair("Tag", item.MediaSource.ETag ?? string.Empty));
+
+ string subtitleCodecs = item.SubtitleCodecs.Length == 0 ?
+ string.Empty :
+ string.Join(",", item.SubtitleCodecs);
+
+ list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty));
+
+ if (isHls)
+ {
+ list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty));
+
+ if (item.SegmentLength.HasValue)
+ {
+ list.Add(new NameValuePair("SegmentLength", item.SegmentLength.Value.ToString(CultureInfo.InvariantCulture)));
+ }
+
+ if (item.MinSegments.HasValue)
+ {
+ list.Add(new NameValuePair("MinSegments", item.MinSegments.Value.ToString(CultureInfo.InvariantCulture)));
+ }
+
+ list.Add(new NameValuePair("BreakOnNonKeyFrames", item.BreakOnNonKeyFrames.ToString(CultureInfo.InvariantCulture)));
+ }
+
+ foreach (var pair in item.StreamOptions)
+ {
+ if (string.IsNullOrEmpty(pair.Value))
+ {
+ continue;
+ }
+
+ // strip spaces to avoid having to encode h264 profile names
+ list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty)));
+ }
+
+ if (!item.IsDirectStream)
+ {
+ list.Add(new NameValuePair("TranscodeReasons", string.Join(',', item.TranscodeReasons.Distinct())));
}
return list;
}
+
+ public List<SubtitleStreamInfo> GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken)
+ {
+ return GetExternalSubtitles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken);
+ }
+
+ public List<SubtitleStreamInfo> GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken)
+ {
+ var list = GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, enableAllProfiles, baseUrl, accessToken);
+ var newList = new List<SubtitleStreamInfo>();
+
+ // First add the selected track
+ foreach (SubtitleStreamInfo stream in list)
+ {
+ if (stream.DeliveryMethod == SubtitleDeliveryMethod.External)
+ {
+ newList.Add(stream);
+ }
+ }
+
+ return newList;
+ }
+
+ public List<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken)
+ {
+ return GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken);
+ }
+
+ public List<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken)
+ {
+ var list = new List<SubtitleStreamInfo>();
+
+ // HLS will preserve timestamps so we can just grab the full subtitle stream
+ long startPositionTicks = string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)
+ ? 0
+ : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0);
+
+ // First add the selected track
+ if (SubtitleStreamIndex.HasValue)
+ {
+ foreach (var stream in MediaSource.MediaStreams)
+ {
+ if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value)
+ {
+ AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
+ }
+ }
+ }
+
+ if (!includeSelectedTrackOnly)
+ {
+ foreach (var stream in MediaSource.MediaStreams)
+ {
+ if (stream.Type == MediaStreamType.Subtitle && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value))
+ {
+ AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
+ }
+ }
+ }
+
+ return list;
+ }
+
+ private void AddSubtitleProfiles(List<SubtitleStreamInfo> list, MediaStream stream, ITranscoderSupport transcoderSupport, bool enableAllProfiles, string baseUrl, string accessToken, long startPositionTicks)
+ {
+ if (enableAllProfiles)
+ {
+ foreach (var profile in DeviceProfile.SubtitleProfiles)
+ {
+ var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, new[] { profile }, transcoderSupport);
+
+ list.Add(info);
+ }
+ }
+ else
+ {
+ var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, DeviceProfile.SubtitleProfiles, transcoderSupport);
+
+ list.Add(info);
+ }
+ }
+
+ private SubtitleStreamInfo GetSubtitleStreamInfo(MediaStream stream, string baseUrl, string accessToken, long startPositionTicks, SubtitleProfile[] subtitleProfiles, ITranscoderSupport transcoderSupport)
+ {
+ var subtitleProfile = StreamBuilder.GetSubtitleProfile(MediaSource, stream, subtitleProfiles, PlayMethod, transcoderSupport, Container, SubProtocol);
+ var info = new SubtitleStreamInfo
+ {
+ IsForced = stream.IsForced,
+ Language = stream.Language,
+ Name = stream.Language ?? "Unknown",
+ Format = subtitleProfile.Format,
+ Index = stream.Index,
+ DeliveryMethod = subtitleProfile.Method,
+ DisplayTitle = stream.DisplayTitle
+ };
+
+ if (info.DeliveryMethod == SubtitleDeliveryMethod.External)
+ {
+ if (MediaSource.Protocol == MediaProtocol.File || !string.Equals(stream.Codec, subtitleProfile.Format, StringComparison.OrdinalIgnoreCase) || !stream.IsExternal)
+ {
+ info.Url = string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}",
+ baseUrl,
+ ItemId,
+ MediaSourceId,
+ stream.Index.ToString(CultureInfo.InvariantCulture),
+ startPositionTicks.ToString(CultureInfo.InvariantCulture),
+ subtitleProfile.Format);
+
+ if (!string.IsNullOrEmpty(accessToken))
+ {
+ info.Url += "?api_key=" + accessToken;
+ }
+
+ info.IsExternalUrl = false;
+ }
+ else
+ {
+ info.Url = stream.Path;
+ info.IsExternalUrl = true;
+ }
+ }
+
+ return info;
+ }
+
+ public int? GetTargetVideoBitDepth(string codec)
+ {
+ var value = GetOption(codec, "videobitdepth");
+ if (string.IsNullOrEmpty(value))
+ {
+ return null;
+ }
+
+ if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return null;
+ }
+
+ public int? GetTargetAudioBitDepth(string codec)
+ {
+ var value = GetOption(codec, "audiobitdepth");
+ if (string.IsNullOrEmpty(value))
+ {
+ return null;
+ }
+
+ if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return null;
+ }
+
+ public double? GetTargetVideoLevel(string codec)
+ {
+ var value = GetOption(codec, "level");
+ if (string.IsNullOrEmpty(value))
+ {
+ return null;
+ }
+
+ if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return null;
+ }
+
+ public int? GetTargetRefFrames(string codec)
+ {
+ var value = GetOption(codec, "maxrefframes");
+ if (string.IsNullOrEmpty(value))
+ {
+ return null;
+ }
+
+ if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result))
+ {
+ return result;
+ }
+
+ return null;
+ }
+
+ public int? GetTargetAudioChannels(string codec)
+ {
+ var defaultValue = GlobalMaxAudioChannels ?? TranscodingMaxAudioChannels;
+
+ var value = GetOption(codec, "audiochannels");
+ if (string.IsNullOrEmpty(value))
+ {
+ return defaultValue;
+ }
+
+ if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
+ {
+ return Math.Min(result, defaultValue ?? result);
+ }
+
+ return defaultValue;
+ }
+
+ private int? GetMediaStreamCount(MediaStreamType type, int limit)
+ {
+ var count = MediaSource.GetStreamCount(type);
+
+ if (count.HasValue)
+ {
+ count = Math.Min(count.Value, limit);
+ }
+
+ return count;
+ }
}
}
diff --git a/MediaBrowser.Model/Dlna/SubtitleDeliveryMethod.cs b/MediaBrowser.Model/Dlna/SubtitleDeliveryMethod.cs
index 925c1f9fc..9b39f9e11 100644
--- a/MediaBrowser.Model/Dlna/SubtitleDeliveryMethod.cs
+++ b/MediaBrowser.Model/Dlna/SubtitleDeliveryMethod.cs
@@ -1,21 +1,29 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
+ /// <summary>
+ /// Delivery method to use during playback of a specific subtitle format.
+ /// </summary>
public enum SubtitleDeliveryMethod
{
/// <summary>
- /// The encode
+ /// Burn the subtitles in the video track.
/// </summary>
Encode = 0,
+
/// <summary>
- /// The embed
+ /// Embed the subtitles in the file or stream.
/// </summary>
Embed = 1,
+
/// <summary>
- /// The external
+ /// Serve the subtitles as an external file.
/// </summary>
External = 2,
+
/// <summary>
- /// The HLS
+ /// Serve the subtitles as a separate HLS stream.
/// </summary>
Hls = 3
}
diff --git a/MediaBrowser.Model/Dlna/SubtitleProfile.cs b/MediaBrowser.Model/Dlna/SubtitleProfile.cs
index f950b6cb8..01e3c696b 100644
--- a/MediaBrowser.Model/Dlna/SubtitleProfile.cs
+++ b/MediaBrowser.Model/Dlna/SubtitleProfile.cs
@@ -1,5 +1,9 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Linq;
using System.Xml.Serialization;
-using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
@@ -38,7 +42,7 @@ namespace MediaBrowser.Model.Dlna
}
var languages = GetLanguages();
- return languages.Length == 0 || ListHelper.ContainsIgnoreCase(languages, subLanguage);
+ return languages.Length == 0 || languages.Contains(subLanguage, StringComparer.OrdinalIgnoreCase);
}
}
}
diff --git a/MediaBrowser.Model/Dlna/SubtitleStreamInfo.cs b/MediaBrowser.Model/Dlna/SubtitleStreamInfo.cs
index e81c26e69..2f01836bd 100644
--- a/MediaBrowser.Model/Dlna/SubtitleStreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/SubtitleStreamInfo.cs
@@ -1,15 +1,26 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public class SubtitleStreamInfo
{
public string Url { get; set; }
+
public string Language { get; set; }
+
public string Name { get; set; }
+
public bool IsForced { get; set; }
+
public string Format { get; set; }
+
public string DisplayTitle { get; set; }
+
public int Index { get; set; }
+
public SubtitleDeliveryMethod DeliveryMethod { get; set; }
+
public bool IsExternalUrl { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/TranscodeSeekInfo.cs b/MediaBrowser.Model/Dlna/TranscodeSeekInfo.cs
index eac5d4b36..cc0c6069b 100644
--- a/MediaBrowser.Model/Dlna/TranscodeSeekInfo.cs
+++ b/MediaBrowser.Model/Dlna/TranscodeSeekInfo.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
public enum TranscodeSeekInfo
diff --git a/MediaBrowser.Model/Dlna/TranscodingProfile.cs b/MediaBrowser.Model/Dlna/TranscodingProfile.cs
index dc2f0c90d..709bdad31 100644
--- a/MediaBrowser.Model/Dlna/TranscodingProfile.cs
+++ b/MediaBrowser.Model/Dlna/TranscodingProfile.cs
@@ -1,3 +1,6 @@
+#pragma warning disable CS1591
+
+using System.ComponentModel;
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
@@ -5,47 +8,56 @@ namespace MediaBrowser.Model.Dlna
public class TranscodingProfile
{
[XmlAttribute("container")]
- public string Container { get; set; }
+ public string Container { get; set; } = string.Empty;
[XmlAttribute("type")]
public DlnaProfileType Type { get; set; }
[XmlAttribute("videoCodec")]
- public string VideoCodec { get; set; }
+ public string VideoCodec { get; set; } = string.Empty;
[XmlAttribute("audioCodec")]
- public string AudioCodec { get; set; }
+ public string AudioCodec { get; set; } = string.Empty;
[XmlAttribute("protocol")]
- public string Protocol { get; set; }
+ public string Protocol { get; set; } = string.Empty;
+ [DefaultValue(false)]
[XmlAttribute("estimateContentLength")]
public bool EstimateContentLength { get; set; }
+ [DefaultValue(false)]
[XmlAttribute("enableMpegtsM2TsMode")]
public bool EnableMpegtsM2TsMode { get; set; }
+ [DefaultValue(TranscodeSeekInfo.Auto)]
[XmlAttribute("transcodeSeekInfo")]
public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
+ [DefaultValue(false)]
[XmlAttribute("copyTimestamps")]
public bool CopyTimestamps { get; set; }
+ [DefaultValue(EncodingContext.Streaming)]
[XmlAttribute("context")]
public EncodingContext Context { get; set; }
+ [DefaultValue(false)]
[XmlAttribute("enableSubtitlesInManifest")]
public bool EnableSubtitlesInManifest { get; set; }
[XmlAttribute("maxAudioChannels")]
- public string MaxAudioChannels { get; set; }
+ public string? MaxAudioChannels { get; set; }
+ [DefaultValue(0)]
[XmlAttribute("minSegments")]
public int MinSegments { get; set; }
+ [DefaultValue(0)]
[XmlAttribute("segmentLength")]
public int SegmentLength { get; set; }
+ [DefaultValue(false)]
[XmlAttribute("breakOnNonKeyFrames")]
public bool BreakOnNonKeyFrames { get; set; }
diff --git a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
index 4edbb503b..987a3a908 100644
--- a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
+++ b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
@@ -1,14 +1,22 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using MediaBrowser.Model.Net;
+using System.Net;
namespace MediaBrowser.Model.Dlna
{
public class UpnpDeviceInfo
{
public Uri Location { get; set; }
+
public Dictionary<string, string> Headers { get; set; }
- public IpAddressInfo LocalIpAddress { get; set; }
+
+ public IPAddress LocalIpAddress { get; set; }
+
public int LocalPort { get; set; }
+
+ public IPAddress RemoteIpAddress { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/VideoOptions.cs b/MediaBrowser.Model/Dlna/VideoOptions.cs
index 9c4a38292..4194f17c6 100644
--- a/MediaBrowser.Model/Dlna/VideoOptions.cs
+++ b/MediaBrowser.Model/Dlna/VideoOptions.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dlna
{
/// <summary>
@@ -6,6 +8,7 @@ namespace MediaBrowser.Model.Dlna
public class VideoOptions : AudioOptions
{
public int? AudioStreamIndex { get; set; }
+
public int? SubtitleStreamIndex { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/XmlAttribute.cs b/MediaBrowser.Model/Dlna/XmlAttribute.cs
index aa64177a8..03bb2e4b1 100644
--- a/MediaBrowser.Model/Dlna/XmlAttribute.cs
+++ b/MediaBrowser.Model/Dlna/XmlAttribute.cs
@@ -1,12 +1,24 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
{
+ /// <summary>
+ /// Defines the <see cref="XmlAttribute" />.
+ /// </summary>
public class XmlAttribute
{
+ /// <summary>
+ /// Gets or sets the name of the attribute.
+ /// </summary>
[XmlAttribute("name")]
public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets the value of the attribute.
+ /// </summary>
[XmlAttribute("value")]
public string Value { get; set; }
}
diff --git a/MediaBrowser.Model/Drawing/DrawingUtils.cs b/MediaBrowser.Model/Drawing/DrawingUtils.cs
index 9fe85512f..556792768 100644
--- a/MediaBrowser.Model/Drawing/DrawingUtils.cs
+++ b/MediaBrowser.Model/Drawing/DrawingUtils.cs
@@ -3,20 +3,21 @@ using System;
namespace MediaBrowser.Model.Drawing
{
/// <summary>
- /// Class DrawingUtils
+ /// Class DrawingUtils.
/// </summary>
public static class DrawingUtils
{
/// <summary>
- /// Resizes a set of dimensions
+ /// Resizes a set of dimensions.
/// </summary>
- /// <param name="size">The original size object</param>
- /// <param name="width">A new fixed width, if desired</param>
- /// <param name="height">A new fixed height, if desired</param>
- /// <param name="maxWidth">A max fixed width, if desired</param>
- /// <param name="maxHeight">A max fixed height, if desired</param>
- /// <returns>A new size object</returns>
- public static ImageDimensions Resize(ImageDimensions size,
+ /// <param name="size">The original size object.</param>
+ /// <param name="width">A new fixed width, if desired.</param>
+ /// <param name="height">A new fixed height, if desired.</param>
+ /// <param name="maxWidth">A max fixed width, if desired.</param>
+ /// <param name="maxHeight">A max fixed height, if desired.</param>
+ /// <returns>A new size object.</returns>
+ public static ImageDimensions Resize(
+ ImageDimensions size,
int width,
int height,
int maxWidth,
@@ -57,12 +58,58 @@ namespace MediaBrowser.Model.Drawing
}
/// <summary>
+ /// Scale down to fill box.
+ /// Returns original size if both width and height are null or zero.
+ /// </summary>
+ /// <param name="size">The original size object.</param>
+ /// <param name="fillWidth">A new fixed width, if desired.</param>
+ /// <param name="fillHeight">A new fixed height, if desired.</param>
+ /// <returns>A new size object or size.</returns>
+ public static ImageDimensions ResizeFill(
+ ImageDimensions size,
+ int? fillWidth,
+ int? fillHeight)
+ {
+ // Return original size if input is invalid.
+ if ((fillWidth == null || fillWidth == 0)
+ && (fillHeight == null || fillHeight == 0))
+ {
+ return size;
+ }
+
+ if (fillWidth == null || fillWidth == 0)
+ {
+ fillWidth = 1;
+ }
+
+ if (fillHeight == null || fillHeight == 0)
+ {
+ fillHeight = 1;
+ }
+
+ double widthRatio = size.Width / (double)fillWidth;
+ double heightRatio = size.Height / (double)fillHeight;
+ double scaleRatio = Math.Min(widthRatio, heightRatio);
+
+ // Clamp to current size.
+ if (scaleRatio < 1)
+ {
+ return size;
+ }
+
+ int newWidth = Convert.ToInt32(Math.Ceiling(size.Width / scaleRatio));
+ int newHeight = Convert.ToInt32(Math.Ceiling(size.Height / scaleRatio));
+
+ return new ImageDimensions(newWidth, newHeight);
+ }
+
+ /// <summary>
/// Gets the new width.
/// </summary>
/// <param name="currentHeight">Height of the current.</param>
/// <param name="currentWidth">Width of the current.</param>
/// <param name="newHeight">The new height.</param>
- /// <returns>the new width</returns>
+ /// <returns>The new width.</returns>
private static int GetNewWidth(int currentHeight, int currentWidth, int newHeight)
=> Convert.ToInt32((double)newHeight / currentHeight * currentWidth);
diff --git a/MediaBrowser.Model/Drawing/ImageDimensions.cs b/MediaBrowser.Model/Drawing/ImageDimensions.cs
index e7805ac49..f84fe6830 100644
--- a/MediaBrowser.Model/Drawing/ImageDimensions.cs
+++ b/MediaBrowser.Model/Drawing/ImageDimensions.cs
@@ -1,36 +1,45 @@
+#pragma warning disable CS1591
+
+using System.Globalization;
+
namespace MediaBrowser.Model.Drawing
{
/// <summary>
- /// Struct ImageDimensions
+ /// Struct ImageDimensions.
/// </summary>
- public struct ImageDimensions
+ public readonly struct ImageDimensions
{
+ public ImageDimensions(int width, int height)
+ {
+ Width = width;
+ Height = height;
+ }
+
/// <summary>
- /// Gets or sets the height.
+ /// Gets the height.
/// </summary>
/// <value>The height.</value>
- public int Height { get; set; }
+ public int Height { get; }
/// <summary>
- /// Gets or sets the width.
+ /// Gets the width.
/// </summary>
/// <value>The width.</value>
- public int Width { get; set; }
+ public int Width { get; }
public bool Equals(ImageDimensions size)
{
return Width.Equals(size.Width) && Height.Equals(size.Height);
}
+ /// <inheritdoc />
public override string ToString()
{
- return string.Format("{0}-{1}", Width, Height);
- }
-
- public ImageDimensions(int width, int height)
- {
- Width = width;
- Height = height;
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}-{1}",
+ Width,
+ Height);
}
}
}
diff --git a/MediaBrowser.Model/Drawing/ImageFormat.cs b/MediaBrowser.Model/Drawing/ImageFormat.cs
index 3639c1594..511c16a4e 100644
--- a/MediaBrowser.Model/Drawing/ImageFormat.cs
+++ b/MediaBrowser.Model/Drawing/ImageFormat.cs
@@ -1,28 +1,32 @@
namespace MediaBrowser.Model.Drawing
{
/// <summary>
- /// Enum ImageOutputFormat
+ /// Enum ImageOutputFormat.
/// </summary>
public enum ImageFormat
{
/// <summary>
- /// The BMP
+ /// The BMP.
/// </summary>
Bmp,
+
/// <summary>
- /// The GIF
+ /// The GIF.
/// </summary>
Gif,
+
/// <summary>
- /// The JPG
+ /// The JPG.
/// </summary>
Jpg,
+
/// <summary>
- /// The PNG
+ /// The PNG.
/// </summary>
Png,
+
/// <summary>
- /// The webp
+ /// The webp.
/// </summary>
Webp
}
diff --git a/MediaBrowser.Model/Drawing/ImageOrientation.cs b/MediaBrowser.Model/Drawing/ImageOrientation.cs
index 0fce8c3dc..5c78aea12 100644
--- a/MediaBrowser.Model/Drawing/ImageOrientation.cs
+++ b/MediaBrowser.Model/Drawing/ImageOrientation.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Drawing
{
public enum ImageOrientation
diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs
index b382d9d4a..a784025e3 100644
--- a/MediaBrowser.Model/Dto/BaseItemDto.cs
+++ b/MediaBrowser.Model/Dto/BaseItemDto.cs
@@ -1,5 +1,9 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using Jellyfin.Data.Enums;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Library;
@@ -59,17 +63,23 @@ namespace MediaBrowser.Model.Dto
public DateTime? DateCreated { get; set; }
public DateTime? DateLastMediaAdded { get; set; }
+
public string ExtraType { get; set; }
public int? AirsBeforeSeasonNumber { get; set; }
+
public int? AirsAfterSeasonNumber { get; set; }
+
public int? AirsBeforeEpisodeNumber { get; set; }
+
public bool? CanDelete { get; set; }
+
public bool? CanDownload { get; set; }
public bool? HasSubtitles { get; set; }
public string PreferredMetadataLanguage { get; set; }
+
public string PreferredMetadataCountryCode { get; set; }
/// <summary>
@@ -84,6 +94,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The name of the sort.</value>
public string SortName { get; set; }
+
public string ForcedSortName { get; set; }
/// <summary>
@@ -142,7 +153,8 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the channel identifier.
/// </summary>
/// <value>The channel identifier.</value>
- public Guid ChannelId { get; set; }
+ public Guid? ChannelId { get; set; }
+
public string ChannelName { get; set; }
/// <summary>
@@ -210,6 +222,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The number.</value>
public string Number { get; set; }
+
public string ChannelNumber { get; set; }
/// <summary>
@@ -234,7 +247,7 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the trailer urls.
/// </summary>
/// <value>The trailer urls.</value>
- public MediaUrl[] RemoteTrailers { get; set; }
+ public IReadOnlyCollection<MediaUrl> RemoteTrailers { get; set; }
/// <summary>
/// Gets or sets the provider ids.
@@ -258,13 +271,13 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the parent id.
/// </summary>
/// <value>The parent id.</value>
- public Guid ParentId { get; set; }
+ public Guid? ParentId { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
- public string Type { get; set; }
+ public BaseItemKind Type { get; set; }
/// <summary>
/// Gets or sets the people.
@@ -281,13 +294,13 @@ namespace MediaBrowser.Model.Dto
public NameGuidPair[] GenreItems { get; set; }
/// <summary>
- /// If the item does not have a logo, this will hold the Id of the Parent that has one.
+ /// Gets or sets wether the item has a logo, this will hold the Id of the Parent that has one.
/// </summary>
/// <value>The parent logo item id.</value>
public string ParentLogoItemId { get; set; }
/// <summary>
- /// If the item does not have any backdrops, this will hold the Id of the Parent that has one.
+ /// Gets or sets wether the item has any backdrops, this will hold the Id of the Parent that has one.
/// </summary>
/// <value>The parent backdrop item id.</value>
public string ParentBackdropItemId { get; set; }
@@ -305,7 +318,7 @@ namespace MediaBrowser.Model.Dto
public int? LocalTrailerCount { get; set; }
/// <summary>
- /// User data for this item based on the user it's being requested for
+ /// Gets or sets the user data for this item based on the user it's being requested for.
/// </summary>
/// <value>The user data.</value>
public UserItemDataDto UserData { get; set; }
@@ -332,13 +345,13 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the series id.
/// </summary>
/// <value>The series id.</value>
- public Guid SeriesId { get; set; }
+ public Guid? SeriesId { get; set; }
/// <summary>
/// Gets or sets the season identifier.
/// </summary>
/// <value>The season identifier.</value>
- public Guid SeasonId { get; set; }
+ public Guid? SeasonId { get; set; }
/// <summary>
/// Gets or sets the special feature count.
@@ -386,7 +399,7 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the artists.
/// </summary>
/// <value>The artists.</value>
- public string[] Artists { get; set; }
+ public IReadOnlyList<string> Artists { get; set; }
/// <summary>
/// Gets or sets the artist items.
@@ -416,7 +429,8 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the album id.
/// </summary>
/// <value>The album id.</value>
- public Guid AlbumId { get; set; }
+ public Guid? AlbumId { get; set; }
+
/// <summary>
/// Gets or sets the album image tag.
/// </summary>
@@ -464,6 +478,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The part count.</value>
public int? PartCount { get; set; }
+
public int? MediaSourceCount { get; set; }
/// <summary>
@@ -491,7 +506,7 @@ namespace MediaBrowser.Model.Dto
public string ParentLogoImageTag { get; set; }
/// <summary>
- /// If the item does not have a art, this will hold the Id of the Parent that has one.
+ /// Gets or sets wether the item has fan art, this will hold the Id of the Parent that has one.
/// </summary>
/// <value>The parent art item id.</value>
public string ParentArtItemId { get; set; }
@@ -509,6 +524,13 @@ namespace MediaBrowser.Model.Dto
public string SeriesThumbImageTag { get; set; }
/// <summary>
+ /// Gets or sets the blurhashes for the image tags.
+ /// Maps image type to dictionary mapping image tag to blurhash value.
+ /// </summary>
+ /// <value>The blurhashes.</value>
+ public Dictionary<ImageType, Dictionary<string, string>> ImageBlurHashes { get; set; }
+
+ /// <summary>
/// Gets or sets the series studio.
/// </summary>
/// <value>The series studio.</value>
@@ -572,40 +594,48 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the locked fields.
/// </summary>
/// <value>The locked fields.</value>
- public MetadataFields[] LockedFields { get; set; }
+ public MetadataField[] LockedFields { get; set; }
/// <summary>
/// Gets or sets the trailer count.
/// </summary>
/// <value>The trailer count.</value>
public int? TrailerCount { get; set; }
+
/// <summary>
/// Gets or sets the movie count.
/// </summary>
/// <value>The movie count.</value>
public int? MovieCount { get; set; }
+
/// <summary>
/// Gets or sets the series count.
/// </summary>
/// <value>The series count.</value>
public int? SeriesCount { get; set; }
+
public int? ProgramCount { get; set; }
+
/// <summary>
/// Gets or sets the episode count.
/// </summary>
/// <value>The episode count.</value>
public int? EpisodeCount { get; set; }
+
/// <summary>
/// Gets or sets the song count.
/// </summary>
/// <value>The song count.</value>
public int? SongCount { get; set; }
+
/// <summary>
/// Gets or sets the album count.
/// </summary>
/// <value>The album count.</value>
public int? AlbumCount { get; set; }
+
public int? ArtistCount { get; set; }
+
/// <summary>
/// Gets or sets the music video count.
/// </summary>
@@ -619,18 +649,31 @@ namespace MediaBrowser.Model.Dto
public bool? LockData { get; set; }
public int? Width { get; set; }
+
public int? Height { get; set; }
+
public string CameraMake { get; set; }
+
public string CameraModel { get; set; }
+
public string Software { get; set; }
+
public double? ExposureTime { get; set; }
+
public double? FocalLength { get; set; }
+
public ImageOrientation? ImageOrientation { get; set; }
+
public double? Aperture { get; set; }
+
public double? ShutterSpeed { get; set; }
+
public double? Latitude { get; set; }
+
public double? Longitude { get; set; }
+
public double? Altitude { get; set; }
+
public int? IsoSpeedRating { get; set; }
/// <summary>
@@ -652,7 +695,7 @@ namespace MediaBrowser.Model.Dto
public string ChannelPrimaryImageTag { get; set; }
/// <summary>
- /// The start date of the recording, in UTC.
+ /// Gets or sets the start date of the recording, in UTC.
/// </summary>
public DateTime? StartDate { get; set; }
@@ -733,6 +776,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The timer identifier.</value>
public string TimerId { get; set; }
+
/// <summary>
/// Gets or sets the current program.
/// </summary>
diff --git a/MediaBrowser.Model/Dto/BaseItemPerson.cs b/MediaBrowser.Model/Dto/BaseItemPerson.cs
index 7011ff8ea..ddd7667ef 100644
--- a/MediaBrowser.Model/Dto/BaseItemPerson.cs
+++ b/MediaBrowser.Model/Dto/BaseItemPerson.cs
@@ -1,9 +1,12 @@
-using MediaBrowser.Model.Serialization;
+#nullable disable
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// This is used by the api to get information about a Person within a BaseItem
+ /// This is used by the api to get information about a Person within a BaseItem.
/// </summary>
public class BaseItemPerson
{
@@ -38,10 +41,16 @@ namespace MediaBrowser.Model.Dto
public string PrimaryImageTag { get; set; }
/// <summary>
+ /// Gets or sets the primary image blurhash.
+ /// </summary>
+ /// <value>The primary image blurhash.</value>
+ public Dictionary<ImageType, Dictionary<string, string>> ImageBlurHashes { get; set; }
+
+ /// <summary>
/// Gets a value indicating whether this instance has primary image.
/// </summary>
/// <value><c>true</c> if this instance has primary image; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
+ [JsonIgnore]
public bool HasPrimaryImage => PrimaryImageTag != null;
}
}
diff --git a/MediaBrowser.Model/Dto/IHasServerId.cs b/MediaBrowser.Model/Dto/IHasServerId.cs
index 2cce5df62..c754d276c 100644
--- a/MediaBrowser.Model/Dto/IHasServerId.cs
+++ b/MediaBrowser.Model/Dto/IHasServerId.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dto
{
public interface IHasServerId
diff --git a/MediaBrowser.Model/Dto/IItemDto.cs b/MediaBrowser.Model/Dto/IItemDto.cs
index 0130adb6f..cb8808fb6 100644
--- a/MediaBrowser.Model/Dto/IItemDto.cs
+++ b/MediaBrowser.Model/Dto/IItemDto.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Interface IItemDto
+ /// Interface IItemDto.
/// </summary>
public interface IItemDto
{
diff --git a/MediaBrowser.Model/Dto/ImageByNameInfo.cs b/MediaBrowser.Model/Dto/ImageByNameInfo.cs
index 2bda8bf20..06cc3e73c 100644
--- a/MediaBrowser.Model/Dto/ImageByNameInfo.cs
+++ b/MediaBrowser.Model/Dto/ImageByNameInfo.cs
@@ -1,3 +1,5 @@
+#nullable disable
+#pragma warning disable CS1591
namespace MediaBrowser.Model.Dto
{
@@ -8,21 +10,25 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the theme.
/// </summary>
/// <value>The theme.</value>
public string Theme { get; set; }
+
/// <summary>
/// Gets or sets the context.
/// </summary>
/// <value>The context.</value>
public string Context { get; set; }
+
/// <summary>
/// Gets or sets the length of the file.
/// </summary>
/// <value>The length of the file.</value>
public long FileLength { get; set; }
+
/// <summary>
/// Gets or sets the format.
/// </summary>
diff --git a/MediaBrowser.Model/Dto/ImageInfo.cs b/MediaBrowser.Model/Dto/ImageInfo.cs
index 792eaff03..2e4b15a18 100644
--- a/MediaBrowser.Model/Dto/ImageInfo.cs
+++ b/MediaBrowser.Model/Dto/ImageInfo.cs
@@ -1,9 +1,10 @@
+#nullable disable
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Class ImageInfo
+ /// Class ImageInfo.
/// </summary>
public class ImageInfo
{
@@ -20,9 +21,9 @@ namespace MediaBrowser.Model.Dto
public int? ImageIndex { get; set; }
/// <summary>
- /// The image tag
+ /// Gets or sets the image tag.
/// </summary>
- public string ImageTag;
+ public string ImageTag { get; set; }
/// <summary>
/// Gets or sets the path.
@@ -31,6 +32,12 @@ namespace MediaBrowser.Model.Dto
public string Path { get; set; }
/// <summary>
+ /// Gets or sets the blurhash.
+ /// </summary>
+ /// <value>The blurhash.</value>
+ public string BlurHash { get; set; }
+
+ /// <summary>
/// Gets or sets the height.
/// </summary>
/// <value>The height.</value>
diff --git a/MediaBrowser.Model/Dto/ImageOptions.cs b/MediaBrowser.Model/Dto/ImageOptions.cs
index 1fd4a5383..3f4405f1e 100644
--- a/MediaBrowser.Model/Dto/ImageOptions.cs
+++ b/MediaBrowser.Model/Dto/ImageOptions.cs
@@ -1,14 +1,23 @@
+#nullable disable
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Class ImageOptions
+ /// Class ImageOptions.
/// </summary>
public class ImageOptions
{
/// <summary>
+ /// Initializes a new instance of the <see cref="ImageOptions" /> class.
+ /// </summary>
+ public ImageOptions()
+ {
+ EnableImageEnhancers = true;
+ }
+
+ /// <summary>
/// Gets or sets the type of the image.
/// </summary>
/// <value>The type of the image.</value>
@@ -52,7 +61,7 @@ namespace MediaBrowser.Model.Dto
/// <summary>
/// Gets or sets the image tag.
- /// If set this will result in strong, unconditional response caching
+ /// If set this will result in strong, unconditional response caching.
/// </summary>
/// <value>The hash.</value>
public string Tag { get; set; }
@@ -98,13 +107,5 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The color of the background.</value>
public string BackgroundColor { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImageOptions" /> class.
- /// </summary>
- public ImageOptions()
- {
- EnableImageEnhancers = true;
- }
}
}
diff --git a/MediaBrowser.Model/Dto/ItemCounts.cs b/MediaBrowser.Model/Dto/ItemCounts.cs
index ec5adab85..95f4a3d77 100644
--- a/MediaBrowser.Model/Dto/ItemCounts.cs
+++ b/MediaBrowser.Model/Dto/ItemCounts.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Class LibrarySummary
+ /// Class LibrarySummary.
/// </summary>
public class ItemCounts
{
@@ -10,48 +10,71 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The movie count.</value>
public int MovieCount { get; set; }
+
/// <summary>
/// Gets or sets the series count.
/// </summary>
/// <value>The series count.</value>
public int SeriesCount { get; set; }
+
/// <summary>
/// Gets or sets the episode count.
/// </summary>
/// <value>The episode count.</value>
public int EpisodeCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the artist count.
+ /// </summary>
+ /// <value>The artist count.</value>
public int ArtistCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the program count.
+ /// </summary>
+ /// <value>The program count.</value>
public int ProgramCount { get; set; }
+
/// <summary>
/// Gets or sets the trailer count.
/// </summary>
/// <value>The trailer count.</value>
public int TrailerCount { get; set; }
+
/// <summary>
/// Gets or sets the song count.
/// </summary>
/// <value>The song count.</value>
public int SongCount { get; set; }
+
/// <summary>
/// Gets or sets the album count.
/// </summary>
/// <value>The album count.</value>
public int AlbumCount { get; set; }
+
/// <summary>
/// Gets or sets the music video count.
/// </summary>
/// <value>The music video count.</value>
public int MusicVideoCount { get; set; }
+
/// <summary>
/// Gets or sets the box set count.
/// </summary>
/// <value>The box set count.</value>
public int BoxSetCount { get; set; }
+
/// <summary>
/// Gets or sets the book count.
/// </summary>
/// <value>The book count.</value>
public int BookCount { get; set; }
+
+ /// <summary>
+ /// Gets or sets the item count.
+ /// </summary>
+ /// <value>The item count.</value>
public int ItemCount { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dto/ItemIndex.cs b/MediaBrowser.Model/Dto/ItemIndex.cs
deleted file mode 100644
index 21e14c73e..000000000
--- a/MediaBrowser.Model/Dto/ItemIndex.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace MediaBrowser.Model.Dto
-{
- /// <summary>
- /// Class ItemIndex
- /// </summary>
- public class ItemIndex
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the item count.
- /// </summary>
- /// <value>The item count.</value>
- public int ItemCount { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
index 92e40fb01..ec3b37efa 100644
--- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
@@ -1,48 +1,81 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Text.Json.Serialization;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
namespace MediaBrowser.Model.Dto
{
public class MediaSourceInfo
{
+ public MediaSourceInfo()
+ {
+ Formats = Array.Empty<string>();
+ MediaStreams = new List<MediaStream>();
+ MediaAttachments = Array.Empty<MediaAttachment>();
+ RequiredHttpHeaders = new Dictionary<string, string>();
+ SupportsTranscoding = true;
+ SupportsDirectStream = true;
+ SupportsDirectPlay = true;
+ SupportsProbing = true;
+ }
+
public MediaProtocol Protocol { get; set; }
+
public string Id { get; set; }
public string Path { get; set; }
public string EncoderPath { get; set; }
+
public MediaProtocol? EncoderProtocol { get; set; }
public MediaSourceType Type { get; set; }
public string Container { get; set; }
+
public long? Size { get; set; }
public string Name { get; set; }
/// <summary>
- /// Differentiate internet url vs local network
+ /// Gets or sets a value indicating whether the media is remote.
+ /// Differentiate internet url vs local network.
/// </summary>
public bool IsRemote { get; set; }
public string ETag { get; set; }
+
public long? RunTimeTicks { get; set; }
+
public bool ReadAtNativeFramerate { get; set; }
+
public bool IgnoreDts { get; set; }
+
public bool IgnoreIndex { get; set; }
+
public bool GenPtsInput { get; set; }
+
public bool SupportsTranscoding { get; set; }
+
public bool SupportsDirectStream { get; set; }
+
public bool SupportsDirectPlay { get; set; }
+
public bool IsInfiniteStream { get; set; }
+
public bool RequiresOpening { get; set; }
+
public string OpenToken { get; set; }
+
public bool RequiresClosing { get; set; }
+
public string LiveStreamId { get; set; }
+
public int? BufferMs { get; set; }
public bool RequiresLooping { get; set; }
@@ -57,28 +90,46 @@ namespace MediaBrowser.Model.Dto
public List<MediaStream> MediaStreams { get; set; }
+ public IReadOnlyList<MediaAttachment> MediaAttachments { get; set; }
+
public string[] Formats { get; set; }
public int? Bitrate { get; set; }
public TransportStreamTimestamp? Timestamp { get; set; }
+
public Dictionary<string, string> RequiredHttpHeaders { get; set; }
public string TranscodingUrl { get; set; }
+
public string TranscodingSubProtocol { get; set; }
+
public string TranscodingContainer { get; set; }
public int? AnalyzeDurationMs { get; set; }
- public MediaSourceInfo()
+ [JsonIgnore]
+ public TranscodeReason[] TranscodeReasons { get; set; }
+
+ public int? DefaultAudioStreamIndex { get; set; }
+
+ public int? DefaultSubtitleStreamIndex { get; set; }
+
+ [JsonIgnore]
+ public MediaStream VideoStream
{
- Formats = Array.Empty<string>();
- MediaStreams = new List<MediaStream>();
- RequiredHttpHeaders = new Dictionary<string, string>();
- SupportsTranscoding = true;
- SupportsDirectStream = true;
- SupportsDirectPlay = true;
- SupportsProbing = true;
+ get
+ {
+ foreach (var i in MediaStreams)
+ {
+ if (i.Type == MediaStreamType.Video)
+ {
+ return i;
+ }
+ }
+
+ return null;
+ }
}
public void InferTotalBitrate(bool force = false)
@@ -108,12 +159,6 @@ namespace MediaBrowser.Model.Dto
}
}
- [IgnoreDataMember]
- public TranscodeReason[] TranscodeReasons { get; set; }
-
- public int? DefaultAudioStreamIndex { get; set; }
- public int? DefaultSubtitleStreamIndex { get; set; }
-
public MediaStream GetDefaultAudioStream(int? defaultIndex)
{
if (defaultIndex.HasValue)
@@ -148,23 +193,6 @@ namespace MediaBrowser.Model.Dto
return null;
}
- [IgnoreDataMember]
- public MediaStream VideoStream
- {
- get
- {
- foreach (var i in MediaStreams)
- {
- if (i.Type == MediaStreamType.Video)
- {
- return i;
- }
- }
-
- return null;
- }
- }
-
public MediaStream GetMediaStream(MediaStreamType type, int index)
{
foreach (var i in MediaStreams)
@@ -207,10 +235,7 @@ namespace MediaBrowser.Model.Dto
{
if (currentStream.Type == MediaStreamType.Audio && currentStream.IsDefault)
{
- if (currentStream.Index != stream.Index)
- {
- return true;
- }
+ return currentStream.Index != stream.Index;
}
}
diff --git a/MediaBrowser.Model/Dto/MediaSourceType.cs b/MediaBrowser.Model/Dto/MediaSourceType.cs
index b643cad9a..42314d519 100644
--- a/MediaBrowser.Model/Dto/MediaSourceType.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dto
{
public enum MediaSourceType
diff --git a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
index 46bcb62f4..e0e889f7d 100644
--- a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
+++ b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
@@ -7,14 +10,6 @@ namespace MediaBrowser.Model.Dto
{
public class MetadataEditorInfo
{
- public ParentalRating[] ParentalRatingOptions { get; set; }
- public CountryInfo[] Countries { get; set; }
- public CultureDto[] Cultures { get; set; }
- public ExternalIdInfo[] ExternalIdInfos { get; set; }
-
- public string ContentType { get; set; }
- public NameValuePair[] ContentTypeOptions { get; set; }
-
public MetadataEditorInfo()
{
ParentalRatingOptions = Array.Empty<ParentalRating>();
@@ -23,5 +18,17 @@ namespace MediaBrowser.Model.Dto
ExternalIdInfos = Array.Empty<ExternalIdInfo>();
ContentTypeOptions = Array.Empty<NameValuePair>();
}
+
+ public ParentalRating[] ParentalRatingOptions { get; set; }
+
+ public CountryInfo[] Countries { get; set; }
+
+ public CultureDto[] Cultures { get; set; }
+
+ public ExternalIdInfo[] ExternalIdInfos { get; set; }
+
+ public string ContentType { get; set; }
+
+ public NameValuePair[] ContentTypeOptions { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dto/NameGuidPair.cs b/MediaBrowser.Model/Dto/NameGuidPair.cs
new file mode 100644
index 000000000..71166df97
--- /dev/null
+++ b/MediaBrowser.Model/Dto/NameGuidPair.cs
@@ -0,0 +1,14 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Model.Dto
+{
+ public class NameGuidPair
+ {
+ public string Name { get; set; }
+
+ public Guid Id { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Dto/NameIdPair.cs b/MediaBrowser.Model/Dto/NameIdPair.cs
index ccd42f17f..31516947f 100644
--- a/MediaBrowser.Model/Dto/NameIdPair.cs
+++ b/MediaBrowser.Model/Dto/NameIdPair.cs
@@ -1,4 +1,5 @@
-using System;
+#nullable disable
+#pragma warning disable CS1591
namespace MediaBrowser.Model.Dto
{
@@ -9,16 +10,11 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public string Id { get; set; }
}
-
- public class NameGuidPair
- {
- public string Name { get; set; }
- public Guid Id { get; set; }
- }
}
diff --git a/MediaBrowser.Model/Dto/NameValuePair.cs b/MediaBrowser.Model/Dto/NameValuePair.cs
index 624763211..e71ff3c21 100644
--- a/MediaBrowser.Model/Dto/NameValuePair.cs
+++ b/MediaBrowser.Model/Dto/NameValuePair.cs
@@ -1,10 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dto
{
public class NameValuePair
{
public NameValuePair()
{
-
}
public NameValuePair(string name, string value)
@@ -18,6 +20,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the value.
/// </summary>
diff --git a/MediaBrowser.Model/Dto/RatingType.cs b/MediaBrowser.Model/Dto/RatingType.cs
index fc1f7ea0f..033776f9c 100644
--- a/MediaBrowser.Model/Dto/RatingType.cs
+++ b/MediaBrowser.Model/Dto/RatingType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dto
{
public enum RatingType
diff --git a/MediaBrowser.Model/Dto/RecommendationDto.cs b/MediaBrowser.Model/Dto/RecommendationDto.cs
index 0a890573b..107f41540 100644
--- a/MediaBrowser.Model/Dto/RecommendationDto.cs
+++ b/MediaBrowser.Model/Dto/RecommendationDto.cs
@@ -1,10 +1,14 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Model.Dto
{
public class RecommendationDto
{
- public BaseItemDto[] Items { get; set; }
+ public IReadOnlyCollection<BaseItemDto> Items { get; set; }
public RecommendationType RecommendationType { get; set; }
diff --git a/MediaBrowser.Model/Dto/RecommendationType.cs b/MediaBrowser.Model/Dto/RecommendationType.cs
index 55a0a8091..384f20c32 100644
--- a/MediaBrowser.Model/Dto/RecommendationType.cs
+++ b/MediaBrowser.Model/Dto/RecommendationType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Dto
{
public enum RecommendationType
diff --git a/MediaBrowser.Model/Dto/UserDto.cs b/MediaBrowser.Model/Dto/UserDto.cs
index 13da018a6..256d7b10f 100644
--- a/MediaBrowser.Model/Dto/UserDto.cs
+++ b/MediaBrowser.Model/Dto/UserDto.cs
@@ -1,3 +1,4 @@
+#nullable disable
using System;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Users;
@@ -5,11 +6,20 @@ using MediaBrowser.Model.Users;
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Class UserDto
+ /// Class UserDto.
/// </summary>
public class UserDto : IItemDto, IHasServerId
{
/// <summary>
+ /// Initializes a new instance of the <see cref="UserDto"/> class.
+ /// </summary>
+ public UserDto()
+ {
+ Configuration = new UserConfiguration();
+ Policy = new UserPolicy();
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
@@ -58,6 +68,9 @@ namespace MediaBrowser.Model.Dto
/// <value><c>true</c> if this instance has configured easy password; otherwise, <c>false</c>.</value>
public bool HasConfiguredEasyPassword { get; set; }
+ /// <summary>
+ /// Gets or sets whether async login is enabled or not.
+ /// </summary>
public bool? EnableAutoLogin { get; set; }
/// <summary>
@@ -90,15 +103,7 @@ namespace MediaBrowser.Model.Dto
/// <value>The primary image aspect ratio.</value>
public double? PrimaryImageAspectRatio { get; set; }
- /// <summary>
- /// Initializes a new instance of the <see cref="UserDto"/> class.
- /// </summary>
- public UserDto()
- {
- Configuration = new UserConfiguration();
- Policy = new UserPolicy();
- }
-
+ /// <inheritdoc />
public override string ToString()
{
return Name ?? base.ToString();
diff --git a/MediaBrowser.Model/Dto/UserItemDataDto.cs b/MediaBrowser.Model/Dto/UserItemDataDto.cs
index fa512e94c..adb2cd2ab 100644
--- a/MediaBrowser.Model/Dto/UserItemDataDto.cs
+++ b/MediaBrowser.Model/Dto/UserItemDataDto.cs
@@ -1,9 +1,10 @@
+#nullable disable
using System;
namespace MediaBrowser.Model.Dto
{
/// <summary>
- /// Class UserItemDataDto
+ /// Class UserItemDataDto.
/// </summary>
public class UserItemDataDto
{
diff --git a/MediaBrowser.Model/Entities/ChapterInfo.cs b/MediaBrowser.Model/Entities/ChapterInfo.cs
index dfd6fdf4a..45554c3dc 100644
--- a/MediaBrowser.Model/Entities/ChapterInfo.cs
+++ b/MediaBrowser.Model/Entities/ChapterInfo.cs
@@ -1,9 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class ChapterInfo
+ /// Class ChapterInfo.
/// </summary>
public class ChapterInfo
{
@@ -24,6 +27,7 @@ namespace MediaBrowser.Model.Entities
/// </summary>
/// <value>The image path.</value>
public string ImagePath { get; set; }
+
public DateTime ImageDateModified { get; set; }
public string ImageTag { get; set; }
diff --git a/MediaBrowser.Model/Entities/CollectionType.cs b/MediaBrowser.Model/Entities/CollectionType.cs
index e26d1b8c3..60b69d4b0 100644
--- a/MediaBrowser.Model/Entities/CollectionType.cs
+++ b/MediaBrowser.Model/Entities/CollectionType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
public static class CollectionType
@@ -22,36 +24,4 @@ namespace MediaBrowser.Model.Entities
public const string Playlists = "playlists";
public const string Folders = "folders";
}
-
- public static class SpecialFolder
- {
- public const string TvShowSeries = "TvShowSeries";
- public const string TvGenres = "TvGenres";
- public const string TvGenre = "TvGenre";
- public const string TvLatest = "TvLatest";
- public const string TvNextUp = "TvNextUp";
- public const string TvResume = "TvResume";
- public const string TvFavoriteSeries = "TvFavoriteSeries";
- public const string TvFavoriteEpisodes = "TvFavoriteEpisodes";
-
- public const string MovieLatest = "MovieLatest";
- public const string MovieResume = "MovieResume";
- public const string MovieMovies = "MovieMovies";
- public const string MovieCollections = "MovieCollections";
- public const string MovieFavorites = "MovieFavorites";
- public const string MovieGenres = "MovieGenres";
- public const string MovieGenre = "MovieGenre";
-
- public const string MusicArtists = "MusicArtists";
- public const string MusicAlbumArtists = "MusicAlbumArtists";
- public const string MusicAlbums = "MusicAlbums";
- public const string MusicGenres = "MusicGenres";
- public const string MusicLatest = "MusicLatest";
- public const string MusicPlaylists = "MusicPlaylists";
- public const string MusicSongs = "MusicSongs";
- public const string MusicFavorites = "MusicFavorites";
- public const string MusicFavoriteArtists = "MusicFavoriteArtists";
- public const string MusicFavoriteAlbums = "MusicFavoriteAlbums";
- public const string MusicFavoriteSongs = "MusicFavoriteSongs";
- }
}
diff --git a/MediaBrowser.Model/Entities/CollectionTypeOptions.cs b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs
new file mode 100644
index 000000000..e1894d84a
--- /dev/null
+++ b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs
@@ -0,0 +1,16 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Entities
+{
+ public enum CollectionTypeOptions
+ {
+ Movies = 0,
+ TvShows = 1,
+ Music = 2,
+ MusicVideos = 3,
+ HomeVideos = 4,
+ BoxSets = 5,
+ Books = 6,
+ Mixed = 7
+ }
+}
diff --git a/MediaBrowser.Model/Entities/DisplayPreferences.cs b/MediaBrowser.Model/Entities/DisplayPreferencesDto.cs
index f9b3ac7b3..1f7fe3030 100644
--- a/MediaBrowser.Model/Entities/DisplayPreferences.cs
+++ b/MediaBrowser.Model/Entities/DisplayPreferencesDto.cs
@@ -1,21 +1,18 @@
+#nullable disable
using System.Collections.Generic;
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Defines the display preferences for any item that supports them (usually Folders)
+ /// Defines the display preferences for any item that supports them (usually Folders).
/// </summary>
- public class DisplayPreferences
+ public class DisplayPreferencesDto
{
/// <summary>
- /// The image scale
+ /// Initializes a new instance of the <see cref="DisplayPreferencesDto" /> class.
/// </summary>
- private const double ImageScale = .9;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DisplayPreferences" /> class.
- /// </summary>
- public DisplayPreferences()
+ public DisplayPreferencesDto()
{
RememberIndexing = false;
PrimaryImageHeight = 250;
@@ -29,68 +26,81 @@ namespace MediaBrowser.Model.Entities
/// </summary>
/// <value>The user id.</value>
public string Id { get; set; }
+
/// <summary>
/// Gets or sets the type of the view.
/// </summary>
/// <value>The type of the view.</value>
public string ViewType { get; set; }
+
/// <summary>
/// Gets or sets the sort by.
/// </summary>
/// <value>The sort by.</value>
public string SortBy { get; set; }
+
/// <summary>
/// Gets or sets the index by.
/// </summary>
/// <value>The index by.</value>
public string IndexBy { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [remember indexing].
/// </summary>
/// <value><c>true</c> if [remember indexing]; otherwise, <c>false</c>.</value>
public bool RememberIndexing { get; set; }
+
/// <summary>
/// Gets or sets the height of the primary image.
/// </summary>
/// <value>The height of the primary image.</value>
public int PrimaryImageHeight { get; set; }
+
/// <summary>
/// Gets or sets the width of the primary image.
/// </summary>
/// <value>The width of the primary image.</value>
public int PrimaryImageWidth { get; set; }
+
/// <summary>
/// Gets or sets the custom prefs.
/// </summary>
/// <value>The custom prefs.</value>
public Dictionary<string, string> CustomPrefs { get; set; }
+
/// <summary>
/// Gets or sets the scroll direction.
/// </summary>
/// <value>The scroll direction.</value>
public ScrollDirection ScrollDirection { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether to show backdrops on this item.
/// </summary>
/// <value><c>true</c> if showing backdrops; otherwise, <c>false</c>.</value>
public bool ShowBackdrop { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [remember sorting].
/// </summary>
/// <value><c>true</c> if [remember sorting]; otherwise, <c>false</c>.</value>
public bool RememberSorting { get; set; }
+
/// <summary>
/// Gets or sets the sort order.
/// </summary>
/// <value>The sort order.</value>
public SortOrder SortOrder { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [show sidebar].
/// </summary>
/// <value><c>true</c> if [show sidebar]; otherwise, <c>false</c>.</value>
public bool ShowSidebar { get; set; }
+
/// <summary>
- /// Gets or sets the client
+ /// Gets or sets the client.
/// </summary>
public string Client { get; set; }
}
diff --git a/MediaBrowser.Model/Entities/EmptyRequestResult.cs b/MediaBrowser.Model/Entities/EmptyRequestResult.cs
deleted file mode 100644
index 5d29218e3..000000000
--- a/MediaBrowser.Model/Entities/EmptyRequestResult.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace MediaBrowser.Model.Entities
-{
- public class EmptyRequestResult
- {
- }
-}
diff --git a/MediaBrowser.Model/Entities/ExtraType.cs b/MediaBrowser.Model/Entities/ExtraType.cs
index 97350b955..aca4bd282 100644
--- a/MediaBrowser.Model/Entities/ExtraType.cs
+++ b/MediaBrowser.Model/Entities/ExtraType.cs
@@ -1,7 +1,10 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
public enum ExtraType
{
+ Unknown = 0,
Clip = 1,
Trailer = 2,
BehindTheScenes = 3,
diff --git a/MediaBrowser.Model/Entities/IHasProviderIds.cs b/MediaBrowser.Model/Entities/IHasProviderIds.cs
index 3b8d74cb4..1310f68ae 100644
--- a/MediaBrowser.Model/Entities/IHasProviderIds.cs
+++ b/MediaBrowser.Model/Entities/IHasProviderIds.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Since BaseItem and DTOBaseItem both have ProviderIds, this interface helps avoid code repition by using extension methods
+ /// Since BaseItem and DTOBaseItem both have ProviderIds, this interface helps avoid code repetition by using extension methods.
/// </summary>
public interface IHasProviderIds
{
diff --git a/MediaBrowser.Model/Entities/ImageType.cs b/MediaBrowser.Model/Entities/ImageType.cs
index ce3560e78..6ea9ee419 100644
--- a/MediaBrowser.Model/Entities/ImageType.cs
+++ b/MediaBrowser.Model/Entities/ImageType.cs
@@ -1,57 +1,73 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum ImageType
+ /// Enum ImageType.
/// </summary>
public enum ImageType
{
/// <summary>
- /// The primary
+ /// The primary.
/// </summary>
Primary = 0,
+
/// <summary>
- /// The art
+ /// The art.
/// </summary>
Art = 1,
+
/// <summary>
- /// The backdrop
+ /// The backdrop.
/// </summary>
Backdrop = 2,
+
/// <summary>
- /// The banner
+ /// The banner.
/// </summary>
Banner = 3,
+
/// <summary>
- /// The logo
+ /// The logo.
/// </summary>
Logo = 4,
+
/// <summary>
- /// The thumb
+ /// The thumb.
/// </summary>
Thumb = 5,
+
/// <summary>
- /// The disc
+ /// The disc.
/// </summary>
Disc = 6,
+
/// <summary>
- /// The box
+ /// The box.
/// </summary>
Box = 7,
+
/// <summary>
- /// The screenshot
+ /// The screenshot.
/// </summary>
Screenshot = 8,
+
/// <summary>
- /// The menu
+ /// The menu.
/// </summary>
Menu = 9,
+
/// <summary>
- /// The chapter image
+ /// The chapter image.
/// </summary>
Chapter = 10,
+
/// <summary>
- /// The box rear
+ /// The box rear.
/// </summary>
- BoxRear = 11
+ BoxRear = 11,
+
+ /// <summary>
+ /// The user profile image.
+ /// </summary>
+ Profile = 12
}
}
diff --git a/MediaBrowser.Model/Entities/IsoType.cs b/MediaBrowser.Model/Entities/IsoType.cs
index 8e4f0d63a..1aa29f31d 100644
--- a/MediaBrowser.Model/Entities/IsoType.cs
+++ b/MediaBrowser.Model/Entities/IsoType.cs
@@ -1,16 +1,17 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum IsoType
+ /// Enum IsoType.
/// </summary>
public enum IsoType
{
/// <summary>
- /// The DVD
+ /// The DVD.
/// </summary>
Dvd,
+
/// <summary>
- /// The blu ray
+ /// The blu ray.
/// </summary>
BluRay
}
diff --git a/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs b/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
index b83df87e2..6dd6653dc 100644
--- a/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
+++ b/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
@@ -1,17 +1,33 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class LibraryUpdateInfo
+ /// Class LibraryUpdateInfo.
/// </summary>
public class LibraryUpdateInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="LibraryUpdateInfo"/> class.
+ /// </summary>
+ public LibraryUpdateInfo()
+ {
+ FoldersAddedTo = Array.Empty<string>();
+ FoldersRemovedFrom = Array.Empty<string>();
+ ItemsAdded = Array.Empty<string>();
+ ItemsRemoved = Array.Empty<string>();
+ ItemsUpdated = Array.Empty<string>();
+ CollectionFolders = Array.Empty<string>();
+ }
+
+ /// <summary>
/// Gets or sets the folders added to.
/// </summary>
/// <value>The folders added to.</value>
public string[] FoldersAddedTo { get; set; }
+
/// <summary>
/// Gets or sets the folders removed from.
/// </summary>
@@ -39,18 +55,5 @@ namespace MediaBrowser.Model.Entities
public string[] CollectionFolders { get; set; }
public bool IsEmpty => FoldersAddedTo.Length == 0 && FoldersRemovedFrom.Length == 0 && ItemsAdded.Length == 0 && ItemsRemoved.Length == 0 && ItemsUpdated.Length == 0 && CollectionFolders.Length == 0;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LibraryUpdateInfo"/> class.
- /// </summary>
- public LibraryUpdateInfo()
- {
- FoldersAddedTo = Array.Empty<string>();
- FoldersRemovedFrom = Array.Empty<string>();
- ItemsAdded = Array.Empty<string>();
- ItemsRemoved = Array.Empty<string>();
- ItemsUpdated = Array.Empty<string>();
- CollectionFolders = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/Entities/LocationType.cs b/MediaBrowser.Model/Entities/LocationType.cs
index 52c08b28b..879b31c5c 100644
--- a/MediaBrowser.Model/Entities/LocationType.cs
+++ b/MediaBrowser.Model/Entities/LocationType.cs
@@ -1,24 +1,27 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum LocationType
+ /// Enum LocationType.
/// </summary>
public enum LocationType
{
/// <summary>
- /// The file system
+ /// The file system.
/// </summary>
FileSystem = 0,
+
/// <summary>
- /// The remote
+ /// The remote.
/// </summary>
Remote = 1,
+
/// <summary>
- /// The virtual
+ /// The virtual.
/// </summary>
Virtual = 2,
+
/// <summary>
- /// The offline
+ /// The offline.
/// </summary>
Offline = 3
}
diff --git a/MediaBrowser.Model/Entities/MediaAttachment.cs b/MediaBrowser.Model/Entities/MediaAttachment.cs
new file mode 100644
index 000000000..34e3eabc9
--- /dev/null
+++ b/MediaBrowser.Model/Entities/MediaAttachment.cs
@@ -0,0 +1,51 @@
+#nullable disable
+namespace MediaBrowser.Model.Entities
+{
+ /// <summary>
+ /// Class MediaAttachment.
+ /// </summary>
+ public class MediaAttachment
+ {
+ /// <summary>
+ /// Gets or sets the codec.
+ /// </summary>
+ /// <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 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 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 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 fc346df37..38ac44794 100644
--- a/MediaBrowser.Model/Entities/MediaStream.cs
+++ b/MediaBrowser.Model/Entities/MediaStream.cs
@@ -1,6 +1,11 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Linq;
+using System.Text;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
@@ -8,7 +13,7 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class MediaStream
+ /// Class MediaStream.
/// </summary>
public class MediaStream
{
@@ -30,9 +35,29 @@ namespace MediaBrowser.Model.Entities
/// <value>The language.</value>
public string Language { get; set; }
+ /// <summary>
+ /// Gets or sets the color range.
+ /// </summary>
+ /// <value>The color range.</value>
+ public string ColorRange { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color space.
+ /// </summary>
+ /// <value>The color space.</value>
+ public string ColorSpace { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color transfer.
+ /// </summary>
+ /// <value>The color transfer.</value>
public string ColorTransfer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the color primaries.
+ /// </summary>
+ /// <value>The color primaries.</value>
public string ColorPrimaries { get; set; }
- public string ColorSpace { get; set; }
/// <summary>
/// Gets or sets the comment.
@@ -40,11 +65,28 @@ namespace MediaBrowser.Model.Entities
/// <value>The comment.</value>
public string Comment { get; set; }
+ /// <summary>
+ /// Gets or sets the time base.
+ /// </summary>
+ /// <value>The time base.</value>
public string TimeBase { get; set; }
+
+ /// <summary>
+ /// Gets or sets the codec time base.
+ /// </summary>
+ /// <value>The codec time base.</value>
public string CodecTimeBase { get; set; }
+ /// <summary>
+ /// Gets or sets the title.
+ /// </summary>
+ /// <value>The title.</value>
public string Title { get; set; }
+ /// <summary>
+ /// Gets the video range.
+ /// </summary>
+ /// <value>The video range.</value>
public string VideoRange
{
get
@@ -56,190 +98,190 @@ namespace MediaBrowser.Model.Entities
var colorTransfer = ColorTransfer;
- if (string.Equals(colorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(colorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
{
return "HDR";
}
- return "SDR";
- }
- }
-
- public string DisplayTitle
- {
- get
- {
- if (Type == MediaStreamType.Audio)
- {
- //if (!string.IsNullOrEmpty(Title))
- //{
- // return AddLanguageIfNeeded(Title);
- //}
-
- var attributes = new List<string>();
-
- if (!string.IsNullOrEmpty(Language))
- {
- attributes.Add(StringHelper.FirstToUpper(Language));
- }
- if (!string.IsNullOrEmpty(Codec) && !StringHelper.EqualsIgnoreCase(Codec, "dca"))
- {
- attributes.Add(AudioCodec.GetFriendlyName(Codec));
- }
- else if (!string.IsNullOrEmpty(Profile) && !StringHelper.EqualsIgnoreCase(Profile, "lc"))
- {
- attributes.Add(Profile);
- }
-
- if (!string.IsNullOrEmpty(ChannelLayout))
- {
- attributes.Add(ChannelLayout);
- }
- else if (Channels.HasValue)
- {
- attributes.Add(Channels.Value.ToString(CultureInfo.InvariantCulture) + " ch");
- }
- if (IsDefault)
- {
- attributes.Add("Default");
- }
+ // For some Dolby Vision files, no color transfer is provided, so check the codec
- return string.Join(" ", attributes);
- }
+ var codecTag = CodecTag;
- if (Type == MediaStreamType.Video)
+ if (string.Equals(codecTag, "dva1", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codecTag, "dvav", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codecTag, "dvh1", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codecTag, "dvhe", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codecTag, "dav1", StringComparison.OrdinalIgnoreCase))
{
- var attributes = new List<string>();
-
- var resolutionText = GetResolutionText();
-
- if (!string.IsNullOrEmpty(resolutionText))
- {
- attributes.Add(resolutionText);
- }
-
- if (!string.IsNullOrEmpty(Codec))
- {
- attributes.Add(Codec.ToUpperInvariant());
- }
-
- return string.Join(" ", attributes);
+ return "HDR";
}
- if (Type == MediaStreamType.Subtitle)
- {
- //if (!string.IsNullOrEmpty(Title))
- //{
- // return AddLanguageIfNeeded(Title);
- //}
-
- var attributes = new List<string>();
-
- if (!string.IsNullOrEmpty(Language))
- {
- attributes.Add(StringHelper.FirstToUpper(Language));
- }
- else
- {
- attributes.Add("Und");
- }
-
- if (IsDefault)
- {
- attributes.Add("Default");
- }
-
- if (IsForced)
- {
- attributes.Add("Forced");
- }
-
- string name = string.Join(" ", attributes.ToArray());
-
- return name;
- }
+ return "SDR";
+ }
+ }
- if (Type == MediaStreamType.Video)
- {
+ public string LocalizedUndefined { get; set; }
- }
+ public string LocalizedDefault { get; set; }
- return null;
- }
- }
+ public string LocalizedForced { get; set; }
- private string GetResolutionText()
+ public string DisplayTitle
{
- var i = this;
-
- if (i.Width.HasValue && i.Height.HasValue)
+ get
{
- var width = i.Width.Value;
- var height = i.Height.Value;
-
- if (width >= 3800 || height >= 2000)
- {
- return "4K";
- }
- if (width >= 2500)
+ switch (Type)
{
- if (i.IsInterlaced)
+ case MediaStreamType.Audio:
{
- return "1440I";
+ var attributes = new List<string>();
+
+ 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.
+ string fullLanguage = CultureInfo
+ .GetCultures(CultureTypes.NeutralCultures)
+ .FirstOrDefault(r => r.ThreeLetterISOLanguageName.Equals(Language, StringComparison.OrdinalIgnoreCase))
+ ?.DisplayName;
+ attributes.Add(StringHelper.FirstToUpper(fullLanguage ?? Language));
+ }
+
+ if (!string.IsNullOrEmpty(Codec) && !string.Equals(Codec, "dca", StringComparison.OrdinalIgnoreCase))
+ {
+ attributes.Add(AudioCodec.GetFriendlyName(Codec));
+ }
+ else if (!string.IsNullOrEmpty(Profile) && !string.Equals(Profile, "lc", StringComparison.OrdinalIgnoreCase))
+ {
+ attributes.Add(Profile);
+ }
+
+ if (!string.IsNullOrEmpty(ChannelLayout))
+ {
+ attributes.Add(StringHelper.FirstToUpper(ChannelLayout));
+ }
+ else if (Channels.HasValue)
+ {
+ attributes.Add(Channels.Value.ToString(CultureInfo.InvariantCulture) + " ch");
+ }
+
+ if (IsDefault)
+ {
+ attributes.Add(string.IsNullOrEmpty(LocalizedDefault) ? "Default" : LocalizedDefault);
+ }
+
+ if (!string.IsNullOrEmpty(Title))
+ {
+ var result = new StringBuilder(Title);
+ foreach (var tag in attributes)
+ {
+ // Keep Tags that are not already in Title.
+ if (!Title.Contains(tag, StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(" - ").Append(tag);
+ }
+ }
+
+ return result.ToString();
+ }
+
+ return string.Join(" - ", attributes);
}
- return "1440P";
- }
- if (width >= 1900 || height >= 1000)
- {
- if (i.IsInterlaced)
- {
- return "1080I";
- }
- return "1080P";
- }
- if (width >= 1260 || height >= 700)
- {
- if (i.IsInterlaced)
+
+ case MediaStreamType.Video:
{
- return "720I";
+ var attributes = new List<string>();
+
+ var resolutionText = GetResolutionText();
+
+ if (!string.IsNullOrEmpty(resolutionText))
+ {
+ attributes.Add(resolutionText);
+ }
+
+ if (!string.IsNullOrEmpty(Codec))
+ {
+ attributes.Add(Codec.ToUpperInvariant());
+ }
+
+ if (!string.IsNullOrEmpty(VideoRange))
+ {
+ attributes.Add(VideoRange.ToUpperInvariant());
+ }
+
+ if (!string.IsNullOrEmpty(Title))
+ {
+ var result = new StringBuilder(Title);
+ foreach (var tag in attributes)
+ {
+ // Keep Tags that are not already in Title.
+ if (!Title.Contains(tag, StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(" - ").Append(tag);
+ }
+ }
+
+ return result.ToString();
+ }
+
+ return string.Join(' ', attributes);
}
- return "720P";
- }
- if (width >= 700 || height >= 440)
- {
- if (i.IsInterlaced)
+ case MediaStreamType.Subtitle:
{
- return "480I";
+ var attributes = new List<string>();
+
+ 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.
+ string fullLanguage = CultureInfo
+ .GetCultures(CultureTypes.NeutralCultures)
+ .FirstOrDefault(r => r.ThreeLetterISOLanguageName.Equals(Language, StringComparison.OrdinalIgnoreCase))
+ ?.DisplayName;
+ attributes.Add(StringHelper.FirstToUpper(fullLanguage ?? Language));
+ }
+ else
+ {
+ attributes.Add(string.IsNullOrEmpty(LocalizedUndefined) ? "Und" : LocalizedUndefined);
+ }
+
+ if (IsDefault)
+ {
+ attributes.Add(string.IsNullOrEmpty(LocalizedDefault) ? "Default" : LocalizedDefault);
+ }
+
+ if (IsForced)
+ {
+ attributes.Add(string.IsNullOrEmpty(LocalizedForced) ? "Forced" : LocalizedForced);
+ }
+
+ if (!string.IsNullOrEmpty(Codec))
+ {
+ attributes.Add(Codec.ToUpperInvariant());
+ }
+
+ if (!string.IsNullOrEmpty(Title))
+ {
+ var result = new StringBuilder(Title);
+ foreach (var tag in attributes)
+ {
+ // Keep Tags that are not already in Title.
+ if (!Title.Contains(tag, StringComparison.OrdinalIgnoreCase))
+ {
+ result.Append(" - ").Append(tag);
+ }
+ }
+
+ return result.ToString();
+ }
+
+ return string.Join(" - ", attributes);
}
- return "480P";
- }
-
- return "SD";
- }
- return null;
- }
-
- private string AddLanguageIfNeeded(string title)
- {
- if (!string.IsNullOrEmpty(Language) &&
- !string.Equals(Language, "und", StringComparison.OrdinalIgnoreCase) &&
- !IsLanguageInTitle(title, Language))
- {
- title = StringHelper.FirstToUpper(Language) + " " + title;
- }
- return title;
- }
-
- private bool IsLanguageInTitle(string title, string language)
- {
- if (title.IndexOf(Language, StringComparison.OrdinalIgnoreCase) != -1)
- {
- return true;
+ default:
+ return null;
+ }
}
-
- return false;
}
public string NalLengthSize { get; set; }
@@ -371,11 +413,13 @@ namespace MediaBrowser.Model.Entities
/// </summary>
/// <value>The method.</value>
public SubtitleDeliveryMethod? DeliveryMethod { get; set; }
+
/// <summary>
/// Gets or sets the delivery URL.
/// </summary>
/// <value>The delivery URL.</value>
public string DeliveryUrl { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is external URL.
/// </summary>
@@ -386,7 +430,10 @@ namespace MediaBrowser.Model.Entities
{
get
{
- if (Type != MediaStreamType.Subtitle) return false;
+ if (Type != MediaStreamType.Subtitle)
+ {
+ return false;
+ }
if (string.IsNullOrEmpty(Codec) && !IsExternal)
{
@@ -397,17 +444,73 @@ namespace MediaBrowser.Model.Entities
}
}
+ /// <summary>
+ /// Gets or sets a value indicating whether [supports external stream].
+ /// </summary>
+ /// <value><c>true</c> if [supports external stream]; otherwise, <c>false</c>.</value>
+ public bool SupportsExternalStream { get; set; }
+
+ /// <summary>
+ /// Gets or sets the filename.
+ /// </summary>
+ /// <value>The filename.</value>
+ public string Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the pixel format.
+ /// </summary>
+ /// <value>The pixel format.</value>
+ public string PixelFormat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the level.
+ /// </summary>
+ /// <value>The level.</value>
+ public double? Level { get; set; }
+
+ /// <summary>
+ /// Gets or sets whether this instance is anamorphic.
+ /// </summary>
+ /// <value><c>true</c> if this instance is anamorphic; otherwise, <c>false</c>.</value>
+ public bool? IsAnamorphic { get; set; }
+
+ internal string GetResolutionText()
+ {
+ if (!Width.HasValue || !Height.HasValue)
+ {
+ return null;
+ }
+
+ return Width switch
+ {
+ <= 720 when Height <= 480 => IsInterlaced ? "480i" : "480p",
+ // 720x576 (PAL) (768 when rescaled for square pixels)
+ <= 768 when Height <= 576 => IsInterlaced ? "576i" : "576p",
+ // 960x540 (sometimes 544 which is multiple of 16)
+ <= 960 when Height <= 544 => IsInterlaced ? "540i" : "540p",
+ // 1280x720
+ <= 1280 when Height <= 962 => IsInterlaced ? "720i" : "720p",
+ // 1920x1080
+ <= 1920 when Height <= 1440 => IsInterlaced ? "1080i" : "1080p",
+ // 4K
+ <= 4096 when Height <= 3072 => "4K",
+ // 8K
+ <= 8192 when Height <= 6144 => "8K",
+ _ => null
+ };
+ }
+
public static bool IsTextFormat(string format)
{
string codec = format ?? string.Empty;
// sub = external .sub file
- return codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) == -1 &&
- codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) == -1 &&
- codec.IndexOf("dvbsub", StringComparison.OrdinalIgnoreCase) == -1 &&
- !StringHelper.EqualsIgnoreCase(codec, "sub") &&
- !StringHelper.EqualsIgnoreCase(codec, "dvb_subtitle");
+ return !codec.Contains("pgs", StringComparison.OrdinalIgnoreCase) &&
+ !codec.Contains("dvd", StringComparison.OrdinalIgnoreCase) &&
+ !codec.Contains("dvbsub", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(codec, "sub", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase);
}
public bool SupportsSubtitleConversionTo(string toCodec)
@@ -420,56 +523,28 @@ namespace MediaBrowser.Model.Entities
var fromCodec = Codec;
// Can't convert from this
- if (StringHelper.EqualsIgnoreCase(fromCodec, "ass"))
+ if (string.Equals(fromCodec, "ass", StringComparison.OrdinalIgnoreCase))
{
return false;
}
- if (StringHelper.EqualsIgnoreCase(fromCodec, "ssa"))
+
+ if (string.Equals(fromCodec, "ssa", StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Can't convert to this
- if (StringHelper.EqualsIgnoreCase(toCodec, "ass"))
+ if (string.Equals(toCodec, "ass", StringComparison.OrdinalIgnoreCase))
{
return false;
}
- if (StringHelper.EqualsIgnoreCase(toCodec, "ssa"))
+
+ if (string.Equals(toCodec, "ssa", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
-
- /// <summary>
- /// Gets or sets a value indicating whether [supports external stream].
- /// </summary>
- /// <value><c>true</c> if [supports external stream]; otherwise, <c>false</c>.</value>
- public bool SupportsExternalStream { get; set; }
-
- /// <summary>
- /// Gets or sets the filename.
- /// </summary>
- /// <value>The filename.</value>
- public string Path { get; set; }
-
- /// <summary>
- /// Gets or sets the pixel format.
- /// </summary>
- /// <value>The pixel format.</value>
- public string PixelFormat { get; set; }
-
- /// <summary>
- /// Gets or sets the level.
- /// </summary>
- /// <value>The level.</value>
- public double? Level { get; set; }
-
- /// <summary>
- /// Gets a value indicating whether this instance is anamorphic.
- /// </summary>
- /// <value><c>true</c> if this instance is anamorphic; otherwise, <c>false</c>.</value>
- public bool? IsAnamorphic { get; set; }
}
}
diff --git a/MediaBrowser.Model/Entities/MediaStreamType.cs b/MediaBrowser.Model/Entities/MediaStreamType.cs
index 4fc1e5372..e09aaf6d0 100644
--- a/MediaBrowser.Model/Entities/MediaStreamType.cs
+++ b/MediaBrowser.Model/Entities/MediaStreamType.cs
@@ -1,24 +1,27 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum MediaStreamType
+ /// Enum MediaStreamType.
/// </summary>
public enum MediaStreamType
{
/// <summary>
- /// The audio
+ /// The audio.
/// </summary>
Audio,
+
/// <summary>
- /// The video
+ /// The video.
/// </summary>
Video,
+
/// <summary>
- /// The subtitle
+ /// The subtitle.
/// </summary>
Subtitle,
+
/// <summary>
- /// The embedded image
+ /// The embedded image.
/// </summary>
EmbeddedImage
}
diff --git a/MediaBrowser.Model/Entities/MediaType.cs b/MediaBrowser.Model/Entities/MediaType.cs
index c56c8f8f2..dd2ae810b 100644
--- a/MediaBrowser.Model/Entities/MediaType.cs
+++ b/MediaBrowser.Model/Entities/MediaType.cs
@@ -1,24 +1,27 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class MediaType
+ /// Class MediaType.
/// </summary>
- public class MediaType
+ public static class MediaType
{
/// <summary>
- /// The video
+ /// The video.
/// </summary>
public const string Video = "Video";
+
/// <summary>
- /// The audio
+ /// The audio.
/// </summary>
public const string Audio = "Audio";
+
/// <summary>
- /// The photo
+ /// The photo.
/// </summary>
public const string Photo = "Photo";
+
/// <summary>
- /// The book
+ /// The book.
/// </summary>
public const string Book = "Book";
}
diff --git a/MediaBrowser.Model/Entities/MediaUrl.cs b/MediaBrowser.Model/Entities/MediaUrl.cs
index 428c895b6..80ceaa765 100644
--- a/MediaBrowser.Model/Entities/MediaUrl.cs
+++ b/MediaBrowser.Model/Entities/MediaUrl.cs
@@ -1,8 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
public class MediaUrl
{
public string Url { get; set; }
+
public string Name { get; set; }
}
}
diff --git a/MediaBrowser.Model/Entities/MetadataFields.cs b/MediaBrowser.Model/Entities/MetadataFields.cs
index a7947a933..2cc6c8e33 100644
--- a/MediaBrowser.Model/Entities/MetadataFields.cs
+++ b/MediaBrowser.Model/Entities/MetadataFields.cs
@@ -1,44 +1,52 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum MetadataFields
+ /// Enum MetadataFields.
/// </summary>
- public enum MetadataFields
+ public enum MetadataField
{
/// <summary>
- /// The cast
+ /// The cast.
/// </summary>
Cast,
+
/// <summary>
- /// The genres
+ /// The genres.
/// </summary>
Genres,
+
/// <summary>
- /// The production locations
+ /// The production locations.
/// </summary>
ProductionLocations,
+
/// <summary>
- /// The studios
+ /// The studios.
/// </summary>
Studios,
+
/// <summary>
- /// The tags
+ /// The tags.
/// </summary>
Tags,
+
/// <summary>
- /// The name
+ /// The name.
/// </summary>
Name,
+
/// <summary>
- /// The overview
+ /// The overview.
/// </summary>
Overview,
+
/// <summary>
- /// The runtime
+ /// The runtime.
/// </summary>
Runtime,
+
/// <summary>
- /// The official rating
+ /// The official rating.
/// </summary>
OfficialRating
}
diff --git a/MediaBrowser.Model/Entities/MetadataProviders.cs b/MediaBrowser.Model/Entities/MetadataProvider.cs
index e9802cf46..e9c098021 100644
--- a/MediaBrowser.Model/Entities/MetadataProviders.cs
+++ b/MediaBrowser.Model/Entities/MetadataProvider.cs
@@ -1,28 +1,34 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum MetadataProviders
+ /// Enum MetadataProviders.
/// </summary>
- public enum MetadataProviders
+ public enum MetadataProvider
{
/// <summary>
- /// The imdb
+ /// The imdb.
/// </summary>
Imdb = 2,
+
/// <summary>
- /// The TMDB
+ /// The TMDB.
/// </summary>
Tmdb = 3,
+
/// <summary>
- /// The TVDB
+ /// The TVDB.
/// </summary>
Tvdb = 4,
+
/// <summary>
- /// The tvcom
+ /// The tvcom.
/// </summary>
Tvcom = 5,
+
/// <summary>
- /// Tmdb Collection Id
+ /// Tmdb Collection Id.
/// </summary>
TmdbCollection = 7,
MusicBrainzAlbum = 8,
diff --git a/MediaBrowser.Model/Entities/PackageReviewInfo.cs b/MediaBrowser.Model/Entities/PackageReviewInfo.cs
deleted file mode 100644
index b73ba8dd0..000000000
--- a/MediaBrowser.Model/Entities/PackageReviewInfo.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Entities
-{
- public class PackageReviewInfo
- {
- /// <summary>
- /// The package id (database key) for this review
- /// </summary>
- public int id { get; set; }
-
- /// <summary>
- /// The rating value
- /// </summary>
- public int rating { get; set; }
-
- /// <summary>
- /// Whether or not this review recommends this item
- /// </summary>
- public bool recommend { get; set; }
-
- /// <summary>
- /// A short description of the review
- /// </summary>
- public string title { get; set; }
-
- /// <summary>
- /// A full review
- /// </summary>
- public string review { get; set; }
-
- /// <summary>
- /// Time of review
- /// </summary>
- public DateTime timestamp { get; set; }
-
- }
-}
diff --git a/MediaBrowser.Model/Entities/ParentalRating.cs b/MediaBrowser.Model/Entities/ParentalRating.cs
index a22e119fa..17b2868a3 100644
--- a/MediaBrowser.Model/Entities/ParentalRating.cs
+++ b/MediaBrowser.Model/Entities/ParentalRating.cs
@@ -1,10 +1,23 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class ParentalRating
+ /// Class ParentalRating.
/// </summary>
public class ParentalRating
{
+ public ParentalRating()
+ {
+ }
+
+ public ParentalRating(string name, int value)
+ {
+ Name = name;
+ Value = value;
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
@@ -16,16 +29,5 @@ namespace MediaBrowser.Model.Entities
/// </summary>
/// <value>The value.</value>
public int Value { get; set; }
-
- public ParentalRating()
- {
-
- }
-
- public ParentalRating(string name, int value)
- {
- Name = name;
- Value = value;
- }
}
}
diff --git a/MediaBrowser.Model/Entities/PersonType.cs b/MediaBrowser.Model/Entities/PersonType.cs
index 72e3538fc..b985507f0 100644
--- a/MediaBrowser.Model/Entities/PersonType.cs
+++ b/MediaBrowser.Model/Entities/PersonType.cs
@@ -1,41 +1,68 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Struct PersonType
+ /// Types of persons.
/// </summary>
- public class PersonType
+ public static class PersonType
{
/// <summary>
- /// The actor
+ /// A person whose profession is acting on the stage, in films, or on television.
/// </summary>
public const string Actor = "Actor";
+
/// <summary>
- /// The director
+ /// A person who supervises the actors and other staff in a film, play, or similar production.
/// </summary>
public const string Director = "Director";
+
/// <summary>
- /// The composer
+ /// A person who writes music, especially as a professional occupation.
/// </summary>
public const string Composer = "Composer";
+
/// <summary>
- /// The writer
+ /// A writer of a book, article, or document. Can also be used as a generic term for music writer if there is a lack of specificity.
/// </summary>
public const string Writer = "Writer";
+
/// <summary>
- /// The guest star
+ /// A well-known actor or other performer who appears in a work in which they do not have a regular role.
/// </summary>
public const string GuestStar = "GuestStar";
+
/// <summary>
- /// The producer
+ /// A person responsible for the financial and managerial aspects of the making of a film or broadcast or for staging a play, opera, etc.
/// </summary>
public const string Producer = "Producer";
+
/// <summary>
- /// The conductor
+ /// A person who directs the performance of an orchestra or choir.
/// </summary>
public const string Conductor = "Conductor";
+
/// <summary>
- /// The lyricist
+ /// A person who writes the words to a song or musical.
/// </summary>
public const string Lyricist = "Lyricist";
+
+ /// <summary>
+ /// A person who adapts a musical composition for performance.
+ /// </summary>
+ public const string Arranger = "Arranger";
+
+ /// <summary>
+ /// An audio engineer who performed a general engineering role.
+ /// </summary>
+ public const string Engineer = "Engineer";
+
+ /// <summary>
+ /// An engineer responsible for using a mixing console to mix a recorded track into a single piece of music suitable for release.
+ /// </summary>
+ public const string Mixer = "Mixer";
+
+ /// <summary>
+ /// A person who remixed a recording by taking one or more other tracks, substantially altering them and mixing them together with other material.
+ /// </summary>
+ public const string Remixer = "Remixer";
}
}
diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
index a151bb3bb..ce4b0ec92 100644
--- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
+++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
@@ -1,42 +1,49 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Class ProviderIdsExtensions
+ /// Class ProviderIdsExtensions.
/// </summary>
public static class ProviderIdsExtensions
{
/// <summary>
- /// Determines whether [has provider identifier] [the specified instance].
+ /// Checks if this instance has an id for the given provider.
/// </summary>
/// <param name="instance">The instance.</param>
- /// <param name="provider">The provider.</param>
- /// <returns><c>true</c> if [has provider identifier] [the specified instance]; otherwise, <c>false</c>.</returns>
- public static bool HasProviderId(this IHasProviderIds instance, MetadataProviders provider)
+ /// <param name="name">The of the provider name.</param>
+ /// <returns><c>true</c> if a provider id with the given name was found; otherwise <c>false</c>.</returns>
+ public static bool HasProviderId(this IHasProviderIds instance, string name)
{
- return !string.IsNullOrEmpty(instance.GetProviderId(provider.ToString()));
+ if (instance == null)
+ {
+ throw new ArgumentNullException(nameof(instance));
+ }
+
+ return instance.TryGetProviderId(name, out _);
}
/// <summary>
- /// Gets a provider id
+ /// Checks if this instance has an id for the given provider.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="provider">The provider.</param>
- /// <returns>System.String.</returns>
- public static string GetProviderId(this IHasProviderIds instance, MetadataProviders provider)
+ /// <returns><c>true</c> if a provider id with the given name was found; otherwise <c>false</c>.</returns>
+ public static bool HasProviderId(this IHasProviderIds instance, MetadataProvider provider)
{
- return instance.GetProviderId(provider.ToString());
+ return instance.HasProviderId(provider.ToString());
}
/// <summary>
- /// Gets a provider id
+ /// Gets a provider id.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="name">The name.</param>
- /// <returns>System.String.</returns>
- public static string GetProviderId(this IHasProviderIds instance, string name)
+ /// <param name="id">The provider id.</param>
+ /// <returns><c>true</c> if a provider id with the given name was found; otherwise <c>false</c>.</returns>
+ public static bool TryGetProviderId(this IHasProviderIds instance, string name, [NotNullWhen(true)] out string? id)
{
if (instance == null)
{
@@ -45,15 +52,58 @@ namespace MediaBrowser.Model.Entities
if (instance.ProviderIds == null)
{
- return null;
+ id = null;
+ return false;
}
- instance.ProviderIds.TryGetValue(name, out string id);
+ var foundProviderId = instance.ProviderIds.TryGetValue(name, out id);
+ // This occurs when searching with Identify (and possibly in other places)
+ if (string.IsNullOrEmpty(id))
+ {
+ id = null;
+ foundProviderId = false;
+ }
+
+ return foundProviderId;
+ }
+
+ /// <summary>
+ /// Gets a provider id.
+ /// </summary>
+ /// <param name="instance">The instance.</param>
+ /// <param name="provider">The provider.</param>
+ /// <param name="id">The provider id.</param>
+ /// <returns><c>true</c> if a provider id with the given name was found; otherwise <c>false</c>.</returns>
+ public static bool TryGetProviderId(this IHasProviderIds instance, MetadataProvider provider, [NotNullWhen(true)] out string? id)
+ {
+ return instance.TryGetProviderId(provider.ToString(), out id);
+ }
+
+ /// <summary>
+ /// Gets a provider id.
+ /// </summary>
+ /// <param name="instance">The instance.</param>
+ /// <param name="name">The name.</param>
+ /// <returns>System.String.</returns>
+ public static string? GetProviderId(this IHasProviderIds instance, string name)
+ {
+ instance.TryGetProviderId(name, out string? id);
return id;
}
/// <summary>
- /// Sets a provider id
+ /// Gets a provider id.
+ /// </summary>
+ /// <param name="instance">The instance.</param>
+ /// <param name="provider">The provider.</param>
+ /// <returns>System.String.</returns>
+ public static string? GetProviderId(this IHasProviderIds instance, MetadataProvider provider)
+ {
+ return instance.GetProviderId(provider.ToString());
+ }
+
+ /// <summary>
+ /// Sets a provider id.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="name">The name.</param>
@@ -68,33 +118,24 @@ namespace MediaBrowser.Model.Entities
// If it's null remove the key from the dictionary
if (string.IsNullOrEmpty(value))
{
- if (instance.ProviderIds != null)
- {
- if (instance.ProviderIds.ContainsKey(name))
- {
- instance.ProviderIds.Remove(name);
- }
- }
+ instance.ProviderIds?.Remove(name);
}
else
{
// Ensure it exists
- if (instance.ProviderIds == null)
- {
- instance.ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
+ instance.ProviderIds ??= new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
instance.ProviderIds[name] = value;
}
}
/// <summary>
- /// Sets a provider id
+ /// Sets a provider id.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="provider">The provider.</param>
/// <param name="value">The value.</param>
- public static void SetProviderId(this IHasProviderIds instance, MetadataProviders provider, string value)
+ public static void SetProviderId(this IHasProviderIds instance, MetadataProvider provider, string value)
{
instance.SetProviderId(provider.ToString(), value);
}
diff --git a/MediaBrowser.Model/Entities/ScrollDirection.cs b/MediaBrowser.Model/Entities/ScrollDirection.cs
deleted file mode 100644
index bc66364f7..000000000
--- a/MediaBrowser.Model/Entities/ScrollDirection.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace MediaBrowser.Model.Entities
-{
- /// <summary>
- /// Enum ScrollDirection
- /// </summary>
- public enum ScrollDirection
- {
- /// <summary>
- /// The horizontal
- /// </summary>
- Horizontal,
- /// <summary>
- /// The vertical
- /// </summary>
- Vertical
- }
-}
diff --git a/MediaBrowser.Model/Entities/SeriesStatus.cs b/MediaBrowser.Model/Entities/SeriesStatus.cs
index cab6a83e8..c77c4a8ad 100644
--- a/MediaBrowser.Model/Entities/SeriesStatus.cs
+++ b/MediaBrowser.Model/Entities/SeriesStatus.cs
@@ -1,16 +1,17 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum SeriesStatus
+ /// Enum SeriesStatus.
/// </summary>
public enum SeriesStatus
{
/// <summary>
- /// The continuing
+ /// The continuing.
/// </summary>
Continuing,
+
/// <summary>
- /// The ended
+ /// The ended.
/// </summary>
Ended
}
diff --git a/MediaBrowser.Model/Entities/SortOrder.cs b/MediaBrowser.Model/Entities/SortOrder.cs
deleted file mode 100644
index 558ebeac2..000000000
--- a/MediaBrowser.Model/Entities/SortOrder.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace MediaBrowser.Model.Entities
-{
- /// <summary>
- /// Enum SortOrder
- /// </summary>
- public enum SortOrder
- {
- /// <summary>
- /// The ascending
- /// </summary>
- Ascending,
- /// <summary>
- /// The descending
- /// </summary>
- Descending
- }
-}
diff --git a/MediaBrowser.Model/Entities/SpecialFolder.cs b/MediaBrowser.Model/Entities/SpecialFolder.cs
new file mode 100644
index 000000000..2250c5dff
--- /dev/null
+++ b/MediaBrowser.Model/Entities/SpecialFolder.cs
@@ -0,0 +1,36 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Entities
+{
+ public static class SpecialFolder
+ {
+ public const string TvShowSeries = "TvShowSeries";
+ public const string TvGenres = "TvGenres";
+ public const string TvGenre = "TvGenre";
+ public const string TvLatest = "TvLatest";
+ public const string TvNextUp = "TvNextUp";
+ public const string TvResume = "TvResume";
+ public const string TvFavoriteSeries = "TvFavoriteSeries";
+ public const string TvFavoriteEpisodes = "TvFavoriteEpisodes";
+
+ public const string MovieLatest = "MovieLatest";
+ public const string MovieResume = "MovieResume";
+ public const string MovieMovies = "MovieMovies";
+ public const string MovieCollections = "MovieCollections";
+ public const string MovieFavorites = "MovieFavorites";
+ public const string MovieGenres = "MovieGenres";
+ public const string MovieGenre = "MovieGenre";
+
+ public const string MusicArtists = "MusicArtists";
+ public const string MusicAlbumArtists = "MusicAlbumArtists";
+ public const string MusicAlbums = "MusicAlbums";
+ public const string MusicGenres = "MusicGenres";
+ public const string MusicLatest = "MusicLatest";
+ public const string MusicPlaylists = "MusicPlaylists";
+ public const string MusicSongs = "MusicSongs";
+ public const string MusicFavorites = "MusicFavorites";
+ public const string MusicFavoriteArtists = "MusicFavoriteArtists";
+ public const string MusicFavoriteAlbums = "MusicFavoriteAlbums";
+ public const string MusicFavoriteSongs = "MusicFavoriteSongs";
+ }
+}
diff --git a/MediaBrowser.Model/Entities/TrailerType.cs b/MediaBrowser.Model/Entities/TrailerType.cs
index 73be5d7ca..68d992b0d 100644
--- a/MediaBrowser.Model/Entities/TrailerType.cs
+++ b/MediaBrowser.Model/Entities/TrailerType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
public enum TrailerType
diff --git a/MediaBrowser.Model/Entities/UserDataSaveReason.cs b/MediaBrowser.Model/Entities/UserDataSaveReason.cs
index bd7471682..20404e6f4 100644
--- a/MediaBrowser.Model/Entities/UserDataSaveReason.cs
+++ b/MediaBrowser.Model/Entities/UserDataSaveReason.cs
@@ -1,32 +1,37 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum UserDataSaveReason
+ /// Enum UserDataSaveReason.
/// </summary>
public enum UserDataSaveReason
{
/// <summary>
- /// The playback start
+ /// The playback start.
/// </summary>
PlaybackStart = 1,
+
/// <summary>
- /// The playback progress
+ /// The playback progress.
/// </summary>
PlaybackProgress = 2,
+
/// <summary>
- /// The playback finished
+ /// The playback finished.
/// </summary>
PlaybackFinished = 3,
+
/// <summary>
- /// The toggle played
+ /// The toggle played.
/// </summary>
TogglePlayed = 4,
+
/// <summary>
- /// The update user rating
+ /// The update user rating.
/// </summary>
UpdateUserRating = 5,
+
/// <summary>
- /// The import
+ /// The import.
/// </summary>
Import = 6
}
diff --git a/MediaBrowser.Model/Entities/Video3DFormat.cs b/MediaBrowser.Model/Entities/Video3DFormat.cs
index 89923ae52..a4f62e18b 100644
--- a/MediaBrowser.Model/Entities/Video3DFormat.cs
+++ b/MediaBrowser.Model/Entities/Video3DFormat.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Entities
{
public enum Video3DFormat
diff --git a/MediaBrowser.Model/Entities/VideoType.cs b/MediaBrowser.Model/Entities/VideoType.cs
index 95d69fb7b..172796301 100644
--- a/MediaBrowser.Model/Entities/VideoType.cs
+++ b/MediaBrowser.Model/Entities/VideoType.cs
@@ -1,24 +1,27 @@
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Enum VideoType
+ /// Enum VideoType.
/// </summary>
public enum VideoType
{
/// <summary>
- /// The video file
+ /// The video file.
/// </summary>
VideoFile,
+
/// <summary>
- /// The iso
+ /// The iso.
/// </summary>
Iso,
+
/// <summary>
- /// The DVD
+ /// The DVD.
/// </summary>
Dvd,
+
/// <summary>
- /// The blu ray
+ /// The blu ray.
/// </summary>
BluRay
}
diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
index 6bdbdb489..2b2bda12c 100644
--- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
+++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
@@ -1,14 +1,27 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
using MediaBrowser.Model.Configuration;
namespace MediaBrowser.Model.Entities
{
/// <summary>
- /// Used to hold information about a user's list of configured virtual folders
+ /// Used to hold information about a user's list of configured virtual folders.
/// </summary>
public class VirtualFolderInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="VirtualFolderInfo"/> class.
+ /// </summary>
+ public VirtualFolderInfo()
+ {
+ Locations = Array.Empty<string>();
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
@@ -24,19 +37,12 @@ namespace MediaBrowser.Model.Entities
/// Gets or sets the type of the collection.
/// </summary>
/// <value>The type of the collection.</value>
- public string CollectionType { get; set; }
+ [JsonConverter(typeof(JsonLowerCaseConverter<CollectionTypeOptions?>))]
+ public CollectionTypeOptions? CollectionType { get; set; }
public LibraryOptions LibraryOptions { get; set; }
/// <summary>
- /// Initializes a new instance of the <see cref="VirtualFolderInfo"/> class.
- /// </summary>
- public VirtualFolderInfo()
- {
- Locations = Array.Empty<string>();
- }
-
- /// <summary>
/// Gets or sets the item identifier.
/// </summary>
/// <value>The item identifier.</value>
@@ -49,6 +55,7 @@ namespace MediaBrowser.Model.Entities
public string PrimaryImageItemId { get; set; }
public double? RefreshProgress { get; set; }
+
public string RefreshStatus { get; set; }
}
}
diff --git a/MediaBrowser.Model/Extensions/EnumerableExtensions.cs b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
new file mode 100644
index 000000000..a5a6b18aa
--- /dev/null
+++ b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Model.Extensions
+{
+ /// <summary>
+ /// Extension methods for <see cref="IEnumerable{T}"/>.
+ /// </summary>
+ public static class EnumerableExtensions
+ {
+ /// <summary>
+ /// Orders <see cref="RemoteImageInfo"/> by requested language in descending order, prioritizing "en" over other non-matches.
+ /// </summary>
+ /// <param name="remoteImageInfos">The remote image infos.</param>
+ /// <param name="requestedLanguage">The requested language for the images.</param>
+ /// <returns>The ordered remote image infos.</returns>
+ public static IEnumerable<RemoteImageInfo> OrderByLanguageDescending(this IEnumerable<RemoteImageInfo> remoteImageInfos, string requestedLanguage)
+ {
+ if (string.IsNullOrWhiteSpace(requestedLanguage))
+ {
+ // Default to English if no requested language is specified.
+ requestedLanguage = "en";
+ }
+
+ var isRequestedLanguageEn = string.Equals(requestedLanguage, "en", StringComparison.OrdinalIgnoreCase);
+
+ return remoteImageInfos.OrderByDescending(i =>
+ {
+ if (string.Equals(requestedLanguage, i.Language, StringComparison.OrdinalIgnoreCase))
+ {
+ return 3;
+ }
+
+ if (string.IsNullOrEmpty(i.Language))
+ {
+ // Assume empty image language is likely to be English.
+ return isRequestedLanguageEn ? 3 : 2;
+ }
+
+ if (!isRequestedLanguageEn && string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase))
+ {
+ // Prioritize English over non-requested languages.
+ return 2;
+ }
+
+ return 0;
+ })
+ .ThenByDescending(i => i.CommunityRating ?? 0)
+ .ThenByDescending(i => i.VoteCount ?? 0);
+ }
+ }
+}
diff --git a/MediaBrowser.Model/Extensions/ListHelper.cs b/MediaBrowser.Model/Extensions/ListHelper.cs
deleted file mode 100644
index b5bd07702..000000000
--- a/MediaBrowser.Model/Extensions/ListHelper.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Extensions
-{
- public static class ListHelper
- {
- public static bool ContainsIgnoreCase(string[] list, string value)
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- foreach (var item in list)
- {
- if (string.Equals(item, value, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
- return false;
- }
- }
-}
diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs
index 75ba12a17..77cbef00f 100644
--- a/MediaBrowser.Model/Extensions/StringHelper.cs
+++ b/MediaBrowser.Model/Extensions/StringHelper.cs
@@ -1,57 +1,39 @@
-using System;
-using System.Text;
-
namespace MediaBrowser.Model.Extensions
{
/// <summary>
- /// Isolating these helpers allow this entire project to be easily converted to Java
+ /// Helper methods for manipulating strings.
/// </summary>
public static class StringHelper
{
/// <summary>
- /// Equalses the ignore case.
+ /// Returns the string with the first character as uppercase.
/// </summary>
- /// <param name="str1">The STR1.</param>
- /// <param name="str2">The STR2.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- public static bool EqualsIgnoreCase(string str1, string str2)
+ /// <param name="str">The input string.</param>
+ /// <returns>The string with the first character as uppercase.</returns>
+ public static string FirstToUpper(string str)
{
- return string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Replaces the specified STR.
- /// </summary>
- /// <param name="str">The STR.</param>
- /// <param name="oldValue">The old value.</param>
- /// <param name="newValue">The new value.</param>
- /// <param name="comparison">The comparison.</param>
- /// <returns>System.String.</returns>
- public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
- {
- var sb = new StringBuilder();
-
- var previousIndex = 0;
- var index = str.IndexOf(oldValue, comparison);
-
- while (index != -1)
+ if (str.Length == 0)
{
- sb.Append(str.Substring(previousIndex, index - previousIndex));
- sb.Append(newValue);
- index += oldValue.Length;
-
- previousIndex = index;
- index = str.IndexOf(oldValue, index, comparison);
+ return str;
}
- sb.Append(str.Substring(previousIndex));
-
- return sb.ToString();
- }
+ // We check IsLower instead of IsUpper because both return false for non-letters
+ if (!char.IsLower(str[0]))
+ {
+ return str;
+ }
- public static string FirstToUpper(this string str)
- {
- return string.IsNullOrEmpty(str) ? string.Empty : str.Substring(0, 1).ToUpperInvariant() + str.Substring(1);
+ return string.Create(
+ str.Length,
+ str,
+ (chars, buf) =>
+ {
+ chars[0] = char.ToUpperInvariant(buf[0]);
+ for (int i = 1; i < chars.Length; i++)
+ {
+ chars[i] = buf[i];
+ }
+ });
}
}
}
diff --git a/MediaBrowser.Model/Globalization/CountryInfo.cs b/MediaBrowser.Model/Globalization/CountryInfo.cs
index 3ae59494f..6f6979316 100644
--- a/MediaBrowser.Model/Globalization/CountryInfo.cs
+++ b/MediaBrowser.Model/Globalization/CountryInfo.cs
@@ -1,7 +1,8 @@
+#nullable disable
namespace MediaBrowser.Model.Globalization
{
/// <summary>
- /// Class CountryInfo
+ /// Class CountryInfo.
/// </summary>
public class CountryInfo
{
diff --git a/MediaBrowser.Model/Globalization/CultureDto.cs b/MediaBrowser.Model/Globalization/CultureDto.cs
index f229f2055..5246f87d9 100644
--- a/MediaBrowser.Model/Globalization/CultureDto.cs
+++ b/MediaBrowser.Model/Globalization/CultureDto.cs
@@ -1,12 +1,20 @@
-using global::System;
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
namespace MediaBrowser.Model.Globalization
{
/// <summary>
- /// Class CultureDto
+ /// Class CultureDto.
/// </summary>
public class CultureDto
{
+ public CultureDto()
+ {
+ ThreeLetterISOLanguageNames = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
@@ -26,7 +34,7 @@ namespace MediaBrowser.Model.Globalization
public string TwoLetterISOLanguageName { get; set; }
/// <summary>
- /// Gets or sets the name of the three letter ISO language.
+ /// Gets the name of the three letter ISO language.
/// </summary>
/// <value>The name of the three letter ISO language.</value>
public string ThreeLetterISOLanguageName
@@ -38,15 +46,11 @@ namespace MediaBrowser.Model.Globalization
{
return vals[0];
}
+
return null;
}
}
public string[] ThreeLetterISOLanguageNames { get; set; }
-
- public CultureDto()
- {
- ThreeLetterISOLanguageNames = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/Globalization/ILocalizationManager.cs b/MediaBrowser.Model/Globalization/ILocalizationManager.cs
index a9ce60a2a..e00157dce 100644
--- a/MediaBrowser.Model/Globalization/ILocalizationManager.cs
+++ b/MediaBrowser.Model/Globalization/ILocalizationManager.cs
@@ -1,35 +1,36 @@
using System.Collections.Generic;
-using System.Globalization;
-using System.Threading.Tasks;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Globalization
{
/// <summary>
- /// Interface ILocalizationManager
+ /// Interface ILocalizationManager.
/// </summary>
public interface ILocalizationManager
{
/// <summary>
/// Gets the cultures.
/// </summary>
- /// <returns>IEnumerable{CultureDto}.</returns>
- CultureDto[] GetCultures();
+ /// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
+ IEnumerable<CultureDto> GetCultures();
+
/// <summary>
/// Gets the countries.
/// </summary>
- /// <returns>IEnumerable{CountryInfo}.</returns>
- Task<CountryInfo[]> GetCountries();
+ /// <returns><see cref="IEnumerable{CountryInfo}" />.</returns>
+ IEnumerable<CountryInfo> GetCountries();
+
/// <summary>
/// Gets the parental ratings.
/// </summary>
- /// <returns>IEnumerable{ParentalRating}.</returns>
+ /// <returns><see cref="IEnumerable{ParentalRating}" />.</returns>
IEnumerable<ParentalRating> GetParentalRatings();
+
/// <summary>
/// Gets the rating level.
/// </summary>
/// <param name="rating">The rating.</param>
- /// <returns>System.Int32.</returns>
+ /// <returns><see cref="int" /> or <c>null</c>.</returns>
int? GetRatingLevel(string rating);
/// <summary>
@@ -37,7 +38,7 @@ namespace MediaBrowser.Model.Globalization
/// </summary>
/// <param name="phrase">The phrase.</param>
/// <param name="culture">The culture.</param>
- /// <returns>System.String.</returns>
+ /// <returns><see cref="string" />.</returns>
string GetLocalizedString(string phrase, string culture);
/// <summary>
@@ -50,13 +51,14 @@ namespace MediaBrowser.Model.Globalization
/// <summary>
/// Gets the localization options.
/// </summary>
- /// <returns>IEnumerable{LocalizatonOption}.</returns>
- LocalizationOption[] GetLocalizationOptions();
+ /// <returns><see cref="IEnumerable{LocalizatonOption}" />.</returns>
+ IEnumerable<LocalizationOption> GetLocalizationOptions();
- string NormalizeFormKD(string text);
-
- bool HasUnicodeCategory(string value, UnicodeCategory category);
-
- 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);
}
}
diff --git a/MediaBrowser.Model/Globalization/LocalizationOption.cs b/MediaBrowser.Model/Globalization/LocalizationOption.cs
index c4c9a8919..81f47d978 100644
--- a/MediaBrowser.Model/Globalization/LocalizationOption.cs
+++ b/MediaBrowser.Model/Globalization/LocalizationOption.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Globalization
{
public class LocalizationOption
@@ -9,6 +12,7 @@ namespace MediaBrowser.Model.Globalization
}
public string Name { get; set; }
+
public string Value { get; set; }
}
}
diff --git a/MediaBrowser.Model/IO/AsyncFile.cs b/MediaBrowser.Model/IO/AsyncFile.cs
new file mode 100644
index 000000000..3c8007d1c
--- /dev/null
+++ b/MediaBrowser.Model/IO/AsyncFile.cs
@@ -0,0 +1,45 @@
+using System.IO;
+
+namespace MediaBrowser.Model.IO
+{
+ /// <summary>
+ /// Helper class to create async <see cref="FileStream" />s.
+ /// </summary>
+ public static class AsyncFile
+ {
+ /// <summary>
+ /// Gets the default <see cref="FileStreamOptions"/> for reading files async.
+ /// </summary>
+ public static FileStreamOptions ReadOptions => new FileStreamOptions()
+ {
+ Options = FileOptions.Asynchronous
+ };
+
+ /// <summary>
+ /// Gets the default <see cref="FileStreamOptions"/> for writing files async.
+ /// </summary>
+ public static FileStreamOptions WriteOptions => new FileStreamOptions()
+ {
+ Mode = FileMode.OpenOrCreate,
+ Access = FileAccess.Write,
+ Share = FileShare.None,
+ Options = FileOptions.Asynchronous
+ };
+
+ /// <summary>
+ /// Opens an existing file for reading.
+ /// </summary>
+ /// <param name="path">The file to be opened for reading.</param>
+ /// <returns>A read-only <see cref="FileStream" /> on the specified path.</returns>
+ public static FileStream OpenRead(string path)
+ => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+
+ /// <summary>
+ /// Opens an existing file for writing.
+ /// </summary>
+ /// <param name="path">The file to be opened for writing.</param>
+ /// <returns>An unshared <see cref="FileStream" /> object on the specified path with Write access.</returns>
+ public static FileStream OpenWrite(string path)
+ => new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ }
+}
diff --git a/MediaBrowser.Model/IO/FileSystemEntryInfo.cs b/MediaBrowser.Model/IO/FileSystemEntryInfo.cs
index a197f0fbe..36ff5d041 100644
--- a/MediaBrowser.Model/IO/FileSystemEntryInfo.cs
+++ b/MediaBrowser.Model/IO/FileSystemEntryInfo.cs
@@ -1,26 +1,39 @@
namespace MediaBrowser.Model.IO
{
/// <summary>
- /// Class FileSystemEntryInfo
+ /// Class FileSystemEntryInfo.
/// </summary>
public class FileSystemEntryInfo
{
/// <summary>
- /// Gets or sets the name.
+ /// Initializes a new instance of the <see cref="FileSystemEntryInfo" /> class.
+ /// </summary>
+ /// <param name="name">The filename.</param>
+ /// <param name="path">The file path.</param>
+ /// <param name="type">The file type.</param>
+ public FileSystemEntryInfo(string name, string path, FileSystemEntryType type)
+ {
+ Name = name;
+ Path = path;
+ Type = type;
+ }
+
+ /// <summary>
+ /// Gets the name.
/// </summary>
/// <value>The name.</value>
- public string Name { get; set; }
+ public string Name { get; }
/// <summary>
- /// Gets or sets the path.
+ /// Gets the path.
/// </summary>
/// <value>The path.</value>
- public string Path { get; set; }
+ public string Path { get; }
/// <summary>
- /// Gets or sets the type.
+ /// Gets the type.
/// </summary>
/// <value>The type.</value>
- public FileSystemEntryType Type { get; set; }
+ public FileSystemEntryType Type { get; }
}
}
diff --git a/MediaBrowser.Model/IO/FileSystemEntryType.cs b/MediaBrowser.Model/IO/FileSystemEntryType.cs
index a4ed2334d..7780d6fcc 100644
--- a/MediaBrowser.Model/IO/FileSystemEntryType.cs
+++ b/MediaBrowser.Model/IO/FileSystemEntryType.cs
@@ -1,24 +1,27 @@
namespace MediaBrowser.Model.IO
{
/// <summary>
- /// Enum FileSystemEntryType
+ /// Enum FileSystemEntryType.
/// </summary>
public enum FileSystemEntryType
{
/// <summary>
- /// The file
+ /// The file.
/// </summary>
File,
+
/// <summary>
- /// The directory
+ /// The directory.
/// </summary>
Directory,
+
/// <summary>
- /// The network computer
+ /// The network computer.
/// </summary>
NetworkComputer,
+
/// <summary>
- /// The network share
+ /// The network share.
/// </summary>
NetworkShare
}
diff --git a/MediaBrowser.Model/IO/FileSystemMetadata.cs b/MediaBrowser.Model/IO/FileSystemMetadata.cs
index 2a6d13959..fb74886bf 100644
--- a/MediaBrowser.Model/IO/FileSystemMetadata.cs
+++ b/MediaBrowser.Model/IO/FileSystemMetadata.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.IO
@@ -9,44 +12,45 @@ namespace MediaBrowser.Model.IO
/// </summary>
/// <value><c>true</c> if exists; otherwise, <c>false</c>.</value>
public bool Exists { get; set; }
+
/// <summary>
/// Gets or sets the full name.
/// </summary>
/// <value>The full name.</value>
public string FullName { get; set; }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the extension.
/// </summary>
/// <value>The extension.</value>
public string Extension { get; set; }
+
/// <summary>
/// Gets or sets the length.
/// </summary>
/// <value>The length.</value>
public long Length { get; set; }
- /// <summary>
- /// Gets or sets the name of the directory.
- /// </summary>
- /// <value>The name of the directory.</value>
- public string DirectoryName { get; set; }
/// <summary>
/// Gets or sets the last write time UTC.
/// </summary>
/// <value>The last write time UTC.</value>
public DateTime LastWriteTimeUtc { get; set; }
+
/// <summary>
/// Gets or sets the creation time UTC.
/// </summary>
/// <value>The creation time UTC.</value>
public DateTime CreationTimeUtc { get; set; }
+
/// <summary>
- /// Gets a value indicating whether this instance is directory.
+ /// Gets or sets a value indicating whether this instance is directory.
/// </summary>
/// <value><c>true</c> if this instance is directory; otherwise, <c>false</c>.</value>
public bool IsDirectory { get; set; }
diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs
index e0771245f..0f77d6b5b 100644
--- a/MediaBrowser.Model/IO/IFileSystem.cs
+++ b/MediaBrowser.Model/IO/IFileSystem.cs
@@ -1,12 +1,12 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.IO;
-using System.Text;
namespace MediaBrowser.Model.IO
{
/// <summary>
- /// Interface IFileSystem
+ /// Interface IFileSystem.
/// </summary>
public interface IFileSystem
{
@@ -24,7 +24,7 @@ namespace MediaBrowser.Model.IO
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
- string ResolveShortcut(string filename);
+ string? ResolveShortcut(string filename);
/// <summary>
/// Creates the shortcut.
@@ -51,7 +51,7 @@ namespace MediaBrowser.Model.IO
/// <returns>A <see cref="FileSystemMetadata" /> object.</returns>
/// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata" /> object's
/// <see cref="FileSystemMetadata.IsDirectory" /> property and the <see cref="FileSystemMetadata.Exists" /> property will both be set to false.</para>
- /// <para>For automatic handling of files <b>and</b> directories, use <see cref="M:IFileSystem.GetFileSystemInfo(System.String)" />.</para></remarks>
+ /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo(string)" />.</para></remarks>
FileSystemMetadata GetFileInfo(string path);
/// <summary>
@@ -61,7 +61,7 @@ namespace MediaBrowser.Model.IO
/// <returns>A <see cref="FileSystemMetadata" /> object.</returns>
/// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata" /> object's
/// <see cref="FileSystemMetadata.IsDirectory" /> property will be set to true and the <see cref="FileSystemMetadata.Exists" /> property will be set to false.</para>
- /// <para>For automatic handling of files <b>and</b> directories, use <see cref="M:IFileSystem.GetFileSystemInfo(System.String)" />.</para></remarks>
+ /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo(string)" />.</para></remarks>
FileSystemMetadata GetDirectoryInfo(string path);
/// <summary>
@@ -100,20 +100,6 @@ namespace MediaBrowser.Model.IO
DateTime GetLastWriteTimeUtc(string path);
/// <summary>
- /// Gets the file stream.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="mode">The mode.</param>
- /// <param name="access">The access.</param>
- /// <param name="share">The share.</param>
- /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
- /// <returns>FileStream.</returns>
- Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false);
-
- Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share,
- FileOpenOptions fileOpenOptions);
-
- /// <summary>
/// Swaps the files.
/// </summary>
/// <param name="file1">The file1.</param>
@@ -131,13 +117,6 @@ namespace MediaBrowser.Model.IO
bool ContainsSubPath(string parentPath, string path);
/// <summary>
- /// Determines whether [is root path] [the specified path].
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns><c>true</c> if [is root path] [the specified path]; otherwise, <c>false</c>.</returns>
- bool IsRootPath(string path);
-
- /// <summary>
/// Normalizes the path.
/// </summary>
/// <param name="path">The path.</param>
@@ -168,16 +147,19 @@ namespace MediaBrowser.Model.IO
/// Gets the directories.
/// </summary>
/// <param name="path">The path.</param>
- /// <param name="recursive">if set to <c>true</c> [recursive].</param>
- /// <returns>IEnumerable&lt;DirectoryInfo&gt;.</returns>
+ /// <param name="recursive">If set to <c>true</c> also searches in subdirectiories.</param>
+ /// <returns>All found directories.</returns>
IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false);
/// <summary>
/// Gets the files.
/// </summary>
+ /// <param name="path">The path in which to search.</param>
+ /// <param name="recursive">If set to <c>true</c> also searches in subdirectiories.</param>
+ /// <returns>All found files.</returns>
IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false);
- IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive);
+ IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string>? extensions, bool enableCaseSensitiveExtensions, bool recursive);
/// <summary>
/// Gets the file system entries.
@@ -203,7 +185,7 @@ namespace MediaBrowser.Model.IO
/// <returns>IEnumerable&lt;System.String&gt;.</returns>
IEnumerable<string> GetFilePaths(string path, bool recursive = false);
- IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive);
+ IEnumerable<string> GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive);
/// <summary>
/// Gets the file system entry paths.
@@ -214,133 +196,9 @@ namespace MediaBrowser.Model.IO
IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false);
void SetHidden(string path, bool isHidden);
- void SetReadOnly(string path, bool readOnly);
- void SetAttributes(string path, bool isHidden, bool readOnly);
- List<FileSystemMetadata> GetDrives();
- void SetExecutable(string path);
- }
-
- //TODO Investigate if can be replaced by the one from System.IO ?
- public enum FileOpenMode
- {
- //
- // Summary:
- // Specifies that the operating system should create a new file. This requires System.Security.Permissions.FileIOPermissionAccess.Write
- // permission. If the file already exists, an System.IO.IOException exception is
- // thrown.
- CreateNew = 1,
- //
- // Summary:
- // Specifies that the operating system should create a new file. If the file already
- // exists, it will be overwritten. This requires System.Security.Permissions.FileIOPermissionAccess.Write
- // permission. FileMode.Create is equivalent to requesting that if the file does
- // not exist, use System.IO.FileMode.CreateNew; otherwise, use System.IO.FileMode.Truncate.
- // If the file already exists but is a hidden file, an System.UnauthorizedAccessException
- // exception is thrown.
- Create = 2,
- //
- // Summary:
- // Specifies that the operating system should open an existing file. The ability
- // to open the file is dependent on the value specified by the System.IO.FileAccess
- // enumeration. A System.IO.FileNotFoundException exception is thrown if the file
- // does not exist.
- Open = 3,
- //
- // Summary:
- // Specifies that the operating system should open a file if it exists; otherwise,
- // a new file should be created. If the file is opened with FileAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Read
- // permission is required. If the file access is FileAccess.Write, System.Security.Permissions.FileIOPermissionAccess.Write
- // permission is required. If the file is opened with FileAccess.ReadWrite, both
- // System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write
- // permissions are required.
- OpenOrCreate = 4
- }
-
- public enum FileAccessMode
- {
- //
- // Summary:
- // Read access to the file. Data can be read from the file. Combine with Write for
- // read/write access.
- Read = 1,
- //
- // Summary:
- // Write access to the file. Data can be written to the file. Combine with Read
- // for read/write access.
- Write = 2
- }
- public enum FileShareMode
- {
- //
- // Summary:
- // Declines sharing of the current file. Any request to open the file (by this process
- // or another process) will fail until the file is closed.
- None = 0,
- //
- // Summary:
- // Allows subsequent opening of the file for reading. If this flag is not specified,
- // any request to open the file for reading (by this process or another process)
- // will fail until the file is closed. However, even if this flag is specified,
- // additional permissions might still be needed to access the file.
- Read = 1,
- //
- // Summary:
- // Allows subsequent opening of the file for writing. If this flag is not specified,
- // any request to open the file for writing (by this process or another process)
- // will fail until the file is closed. However, even if this flag is specified,
- // additional permissions might still be needed to access the file.
- Write = 2,
- //
- // Summary:
- // Allows subsequent opening of the file for reading or writing. If this flag is
- // not specified, any request to open the file for reading or writing (by this process
- // or another process) will fail until the file is closed. However, even if this
- // flag is specified, additional permissions might still be needed to access the
- // file.
- ReadWrite = 3
- }
+ void SetAttributes(string path, bool isHidden, bool readOnly);
- //
- // Summary:
- // Represents advanced options for creating a System.IO.FileStream object.
- [Flags]
- public enum FileOpenOptions
- {
- //
- // Summary:
- // Indicates that the system should write through any intermediate cache and go
- // directly to disk.
- WriteThrough = int.MinValue,
- //
- // Summary:
- // Indicates that no additional options should be used when creating a System.IO.FileStream
- // object.
- None = 0,
- //
- // Summary:
- // Indicates that a file is encrypted and can be decrypted only by using the same
- // user account used for encryption.
- Encrypted = 16384,
- //
- // Summary:
- // Indicates that a file is automatically deleted when it is no longer in use.
- DeleteOnClose = 67108864,
- //
- // Summary:
- // Indicates that the file is to be accessed sequentially from beginning to end.
- // The system can use this as a hint to optimize file caching. If an application
- // moves the file pointer for random access, optimum caching may not occur; however,
- // correct operation is still guaranteed.
- SequentialScan = 134217728,
- //
- // Summary:
- // Indicates that the file is accessed randomly. The system can use this as a hint
- // to optimize file caching.
- RandomAccess = 268435456,
- //
- // Summary:
- // Indicates that a file can be used for asynchronous reading and writing.
- Asynchronous = 1073741824
+ List<FileSystemMetadata> GetDrives();
}
}
diff --git a/MediaBrowser.Model/IO/IIsoManager.cs b/MediaBrowser.Model/IO/IIsoManager.cs
deleted file mode 100644
index 24b6e5f05..000000000
--- a/MediaBrowser.Model/IO/IIsoManager.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.IO
-{
- public interface IIsoManager : IDisposable
- {
- /// <summary>
- /// Mounts the specified iso path.
- /// </summary>
- /// <param name="isoPath">The iso path.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>IsoMount.</returns>
- /// <exception cref="ArgumentNullException">isoPath</exception>
- /// <exception cref="IOException">Unable to create mount.</exception>
- Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken);
-
- /// <summary>
- /// Determines whether this instance can mount the specified path.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns>
- bool CanMount(string path);
-
- /// <summary>
- /// Adds the parts.
- /// </summary>
- /// <param name="mounters">The mounters.</param>
- void AddParts(IEnumerable<IIsoMounter> mounters);
- }
-}
diff --git a/MediaBrowser.Model/IO/IIsoMount.cs b/MediaBrowser.Model/IO/IIsoMount.cs
deleted file mode 100644
index 825c0c243..000000000
--- a/MediaBrowser.Model/IO/IIsoMount.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.IO
-{
- /// <summary>
- /// Interface IIsoMount
- /// </summary>
- public interface IIsoMount : IDisposable
- {
- /// <summary>
- /// Gets or sets the iso path.
- /// </summary>
- /// <value>The iso path.</value>
- string IsoPath { get; }
-
- /// <summary>
- /// Gets the mounted path.
- /// </summary>
- /// <value>The mounted path.</value>
- string MountedPath { get; }
- }
-}
diff --git a/MediaBrowser.Model/IO/IIsoMounter.cs b/MediaBrowser.Model/IO/IIsoMounter.cs
deleted file mode 100644
index f0153a928..000000000
--- a/MediaBrowser.Model/IO/IIsoMounter.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.IO
-{
- public interface IIsoMounter : IDisposable
- {
- /// <summary>
- /// Mounts the specified iso path.
- /// </summary>
- /// <param name="isoPath">The iso path.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>IsoMount.</returns>
- /// <exception cref="ArgumentNullException">isoPath</exception>
- /// <exception cref="IOException">Unable to create mount.</exception>
- Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken);
-
- /// <summary>
- /// Determines whether this instance can mount the specified path.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns>
- bool CanMount(string path);
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
- }
-}
diff --git a/MediaBrowser.Model/IO/IODefaults.cs b/MediaBrowser.Model/IO/IODefaults.cs
new file mode 100644
index 000000000..d9a1e6777
--- /dev/null
+++ b/MediaBrowser.Model/IO/IODefaults.cs
@@ -0,0 +1,25 @@
+using System.IO;
+
+namespace MediaBrowser.Model.IO
+{
+ /// <summary>
+ /// Class IODefaults.
+ /// </summary>
+ public static class IODefaults
+ {
+ /// <summary>
+ /// The default copy to buffer size.
+ /// </summary>
+ public const int CopyToBufferSize = 81920;
+
+ /// <summary>
+ /// The default file stream buffer size.
+ /// </summary>
+ public const int FileStreamBufferSize = 4096;
+
+ /// <summary>
+ /// The default <see cref="StreamWriter" /> buffer size.
+ /// </summary>
+ public const int StreamWriterBufferSize = 1024;
+ }
+}
diff --git a/MediaBrowser.Model/IO/IShortcutHandler.cs b/MediaBrowser.Model/IO/IShortcutHandler.cs
index 2cc18274b..2c364a962 100644
--- a/MediaBrowser.Model/IO/IShortcutHandler.cs
+++ b/MediaBrowser.Model/IO/IShortcutHandler.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.IO
{
public interface IShortcutHandler
@@ -7,18 +9,19 @@ namespace MediaBrowser.Model.IO
/// </summary>
/// <value>The extension.</value>
string Extension { get; }
+
/// <summary>
/// Resolves the specified shortcut path.
/// </summary>
/// <param name="shortcutPath">The shortcut path.</param>
/// <returns>System.String.</returns>
- string Resolve(string shortcutPath);
+ string? Resolve(string shortcutPath);
+
/// <summary>
/// Creates the specified shortcut path.
/// </summary>
/// <param name="shortcutPath">The shortcut path.</param>
/// <param name="targetPath">The target path.</param>
- /// <returns>System.String.</returns>
void Create(string shortcutPath, string targetPath);
}
}
diff --git a/MediaBrowser.Model/IO/IStreamHelper.cs b/MediaBrowser.Model/IO/IStreamHelper.cs
index 97d985df6..f900da556 100644
--- a/MediaBrowser.Model/IO/IStreamHelper.cs
+++ b/MediaBrowser.Model/IO/IStreamHelper.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Threading;
@@ -7,11 +9,10 @@ namespace MediaBrowser.Model.IO
{
public interface IStreamHelper
{
- Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken);
+ Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action? onStarted, CancellationToken cancellationToken);
Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken);
- Task<int> CopyToAsync(Stream source, Stream destination, CancellationToken cancellationToken);
Task CopyToAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken);
Task CopyUntilCancelled(Stream source, Stream target, int bufferSize, CancellationToken cancellationToken);
diff --git a/MediaBrowser.Model/IO/IZipClient.cs b/MediaBrowser.Model/IO/IZipClient.cs
index eaddd6df3..fca52ebae 100644
--- a/MediaBrowser.Model/IO/IZipClient.cs
+++ b/MediaBrowser.Model/IO/IZipClient.cs
@@ -1,9 +1,11 @@
+#pragma warning disable CS1591
+
using System.IO;
namespace MediaBrowser.Model.IO
{
/// <summary>
- /// Interface IZipClient
+ /// Interface IZipClient.
/// </summary>
public interface IZipClient
{
@@ -24,6 +26,7 @@ namespace MediaBrowser.Model.IO
void ExtractAll(Stream source, string targetPath, bool overwriteExistingFiles);
void ExtractAllFromGz(Stream source, string targetPath, bool overwriteExistingFiles);
+
void ExtractFirstFileFromGz(Stream source, string targetPath, string defaultFileName);
/// <summary>
diff --git a/MediaBrowser.Model/IO/StreamDefaults.cs b/MediaBrowser.Model/IO/StreamDefaults.cs
deleted file mode 100644
index bef20e74f..000000000
--- a/MediaBrowser.Model/IO/StreamDefaults.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace MediaBrowser.Model.IO
-{
- /// <summary>
- /// Class StreamDefaults
- /// </summary>
- public static class StreamDefaults
- {
- /// <summary>
- /// The default copy to buffer size
- /// </summary>
- public const int DefaultCopyToBufferSize = 81920;
-
- /// <summary>
- /// The default file stream buffer size
- /// </summary>
- public const int DefaultFileStreamBufferSize = 81920;
- }
-}
diff --git a/MediaBrowser.Model/Library/PlayAccess.cs b/MediaBrowser.Model/Library/PlayAccess.cs
index 2fd754f5e..a2f263ce5 100644
--- a/MediaBrowser.Model/Library/PlayAccess.cs
+++ b/MediaBrowser.Model/Library/PlayAccess.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Library
{
public enum PlayAccess
diff --git a/MediaBrowser.Model/Library/UserViewQuery.cs b/MediaBrowser.Model/Library/UserViewQuery.cs
index c2e189603..8a49b6863 100644
--- a/MediaBrowser.Model/Library/UserViewQuery.cs
+++ b/MediaBrowser.Model/Library/UserViewQuery.cs
@@ -1,9 +1,17 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Library
{
public class UserViewQuery
{
+ public UserViewQuery()
+ {
+ IncludeExternalContent = true;
+ PresetViews = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the user identifier.
/// </summary>
@@ -23,11 +31,5 @@ namespace MediaBrowser.Model.Library
public bool IncludeHidden { get; set; }
public string[] PresetViews { get; set; }
-
- public UserViewQuery()
- {
- IncludeExternalContent = true;
- PresetViews = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
index 311b5b0c5..c6de4c1ab 100644
--- a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dto;
@@ -6,7 +9,7 @@ namespace MediaBrowser.Model.LiveTv
public class BaseTimerInfoDto : IHasServerId
{
/// <summary>
- /// Id of the recording.
+ /// Gets or sets the Id of the recording.
/// </summary>
public string Id { get; set; }
@@ -25,7 +28,7 @@ namespace MediaBrowser.Model.LiveTv
public string ExternalId { get; set; }
/// <summary>
- /// ChannelId of the recording.
+ /// Gets or sets the channel id of the recording.
/// </summary>
public Guid ChannelId { get; set; }
@@ -36,7 +39,7 @@ namespace MediaBrowser.Model.LiveTv
public string ExternalChannelId { get; set; }
/// <summary>
- /// ChannelName of the recording.
+ /// Gets or sets the channel name of the recording.
/// </summary>
public string ChannelName { get; set; }
@@ -55,22 +58,22 @@ namespace MediaBrowser.Model.LiveTv
public string ExternalProgramId { get; set; }
/// <summary>
- /// Name of the recording.
+ /// Gets or sets the name of the recording.
/// </summary>
public string Name { get; set; }
/// <summary>
- /// Description of the recording.
+ /// Gets or sets the description of the recording.
/// </summary>
public string Overview { get; set; }
/// <summary>
- /// The start date of the recording, in UTC.
+ /// Gets or sets the start date of the recording, in UTC.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
- /// The end date of the recording, in UTC.
+ /// Gets or sets the end date of the recording, in UTC.
/// </summary>
public DateTime EndDate { get; set; }
@@ -105,7 +108,7 @@ namespace MediaBrowser.Model.LiveTv
public bool IsPrePaddingRequired { get; set; }
/// <summary>
- /// If the item does not have any backdrops, this will hold the Id of the Parent that has one.
+ /// Gets or sets the Id of the Parent that has a backdrop if the item does not have one.
/// </summary>
/// <value>The parent backdrop item id.</value>
public string ParentBackdropItemId { get; set; }
@@ -121,6 +124,7 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value><c>true</c> if this instance is post padding required; otherwise, <c>false</c>.</value>
public bool IsPostPaddingRequired { get; set; }
+
public KeepUntil KeepUntil { get; set; }
}
}
diff --git a/MediaBrowser.Model/LiveTv/ChannelType.cs b/MediaBrowser.Model/LiveTv/ChannelType.cs
index 8808aa6d2..f4c55cb6d 100644
--- a/MediaBrowser.Model/LiveTv/ChannelType.cs
+++ b/MediaBrowser.Model/LiveTv/ChannelType.cs
@@ -1,17 +1,17 @@
namespace MediaBrowser.Model.LiveTv
{
/// <summary>
- /// Enum ChannelType
+ /// Enum ChannelType.
/// </summary>
public enum ChannelType
{
/// <summary>
- /// The TV
+ /// The TV.
/// </summary>
TV,
/// <summary>
- /// The radio
+ /// The radio.
/// </summary>
Radio
}
diff --git a/MediaBrowser.Model/LiveTv/DayPattern.cs b/MediaBrowser.Model/LiveTv/DayPattern.cs
index 73b15507b..17efe3908 100644
--- a/MediaBrowser.Model/LiveTv/DayPattern.cs
+++ b/MediaBrowser.Model/LiveTv/DayPattern.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public enum DayPattern
diff --git a/MediaBrowser.Model/LiveTv/GuideInfo.cs b/MediaBrowser.Model/LiveTv/GuideInfo.cs
index 1303c278e..b1cc8cfdf 100644
--- a/MediaBrowser.Model/LiveTv/GuideInfo.cs
+++ b/MediaBrowser.Model/LiveTv/GuideInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.LiveTv
diff --git a/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs b/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs
new file mode 100644
index 000000000..082daeb51
--- /dev/null
+++ b/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs
@@ -0,0 +1,58 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using MediaBrowser.Model.Dto;
+
+namespace MediaBrowser.Model.LiveTv
+{
+ public class ListingsProviderInfo
+ {
+ public ListingsProviderInfo()
+ {
+ NewsCategories = new[] { "news", "journalism", "documentary", "current affairs" };
+ SportsCategories = new[] { "sports", "basketball", "baseball", "football" };
+ KidsCategories = new[] { "kids", "family", "children", "childrens", "disney" };
+ MovieCategories = new[] { "movie" };
+ EnabledTuners = Array.Empty<string>();
+ EnableAllTuners = true;
+ ChannelMappings = Array.Empty<NameValuePair>();
+ }
+
+ public string Id { get; set; }
+
+ public string Type { get; set; }
+
+ public string Username { get; set; }
+
+ public string Password { get; set; }
+
+ public string ListingsId { get; set; }
+
+ public string ZipCode { get; set; }
+
+ public string Country { get; set; }
+
+ public string Path { get; set; }
+
+ public string[] EnabledTuners { get; set; }
+
+ public bool EnableAllTuners { get; set; }
+
+ public string[] NewsCategories { get; set; }
+
+ public string[] SportsCategories { get; set; }
+
+ public string[] KidsCategories { get; set; }
+
+ public string[] MovieCategories { get; set; }
+
+ public NameValuePair[] ChannelMappings { get; set; }
+
+ public string MoviePrefix { get; set; }
+
+ public string PreferredLanguage { get; set; }
+
+ public string UserAgent { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
index eedf89db0..673d97a9e 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
@@ -1,5 +1,8 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Entities;
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.LiveTv
{
@@ -8,6 +11,12 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
public class LiveTvChannelQuery
{
+ public LiveTvChannelQuery()
+ {
+ EnableUserData = true;
+ SortBy = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the type of the channel.
/// </summary>
@@ -45,13 +54,13 @@ namespace MediaBrowser.Model.LiveTv
public Guid UserId { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Used for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
@@ -61,18 +70,19 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value><c>true</c> if [add current program]; otherwise, <c>false</c>.</value>
public bool AddCurrentProgram { get; set; }
+
public bool EnableUserData { get; set; }
/// <summary>
- /// Used to specific whether to return news or not
+ /// Gets or sets a value whether to return news or not.
/// </summary>
- /// <remarks>If set to null, all programs will be returned</remarks>
+ /// <remarks>If set to <c>null</c>, all programs will be returned.</remarks>
public bool? IsNews { get; set; }
/// <summary>
- /// Used to specific whether to return movies or not
+ /// Gets or sets a value whether to return movies or not.
/// </summary>
- /// <remarks>If set to null, all programs will be returned</remarks>
+ /// <remarks>If set to <c>null</c>, all programs will be returned.</remarks>
public bool? IsMovie { get; set; }
/// <summary>
@@ -80,25 +90,21 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value><c>null</c> if [is kids] contains no value, <c>true</c> if [is kids]; otherwise, <c>false</c>.</value>
public bool? IsKids { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is sports.
/// </summary>
/// <value><c>null</c> if [is sports] contains no value, <c>true</c> if [is sports]; otherwise, <c>false</c>.</value>
public bool? IsSports { get; set; }
+
public bool? IsSeries { get; set; }
public string[] SortBy { get; set; }
/// <summary>
- /// The sort order to return results with
+ /// Gets or sets the sort order to return results with.
/// </summary>
/// <value>The sort order.</value>
public SortOrder? SortOrder { get; set; }
-
- public LiveTvChannelQuery()
- {
- EnableUserData = true;
- SortBy = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvInfo.cs b/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
index 60cb27331..9767509d0 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
@@ -1,9 +1,17 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.LiveTv
{
public class LiveTvInfo
{
+ public LiveTvInfo()
+ {
+ Services = Array.Empty<LiveTvServiceInfo>();
+ EnabledUsers = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the services.
/// </summary>
@@ -21,11 +29,5 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value>The enabled users.</value>
public string[] EnabledUsers { get; set; }
-
- public LiveTvInfo()
- {
- Services = Array.Empty<LiveTvServiceInfo>();
- EnabledUsers = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
index 36fe0c3d2..4cece941c 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
@@ -1,88 +1,44 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.LiveTv
{
public class LiveTvOptions
{
+ public LiveTvOptions()
+ {
+ TunerHosts = Array.Empty<TunerHostInfo>();
+ ListingProviders = Array.Empty<ListingsProviderInfo>();
+ MediaLocationsCreated = Array.Empty<string>();
+ RecordingPostProcessorArguments = "\"{path}\"";
+ }
+
public int? GuideDays { get; set; }
+
public string RecordingPath { get; set; }
+
public string MovieRecordingPath { get; set; }
+
public string SeriesRecordingPath { get; set; }
+
public bool EnableRecordingSubfolders { get; set; }
+
public bool EnableOriginalAudioWithEncodedRecordings { get; set; }
public TunerHostInfo[] TunerHosts { get; set; }
+
public ListingsProviderInfo[] ListingProviders { get; set; }
public int PrePaddingSeconds { get; set; }
+
public int PostPaddingSeconds { get; set; }
public string[] MediaLocationsCreated { get; set; }
public string RecordingPostProcessor { get; set; }
- public string RecordingPostProcessorArguments { get; set; }
-
- public LiveTvOptions()
- {
- TunerHosts = Array.Empty<TunerHostInfo>();
- ListingProviders = Array.Empty<ListingsProviderInfo>();
- MediaLocationsCreated = Array.Empty<string>();
- RecordingPostProcessorArguments = "\"{path}\"";
- }
- }
- public class TunerHostInfo
- {
- public string Id { get; set; }
- public string Url { get; set; }
- public string Type { get; set; }
- public string DeviceId { get; set; }
- public string FriendlyName { get; set; }
- public bool ImportFavoritesOnly { get; set; }
- public bool AllowHWTranscoding { get; set; }
- public bool EnableStreamLooping { get; set; }
- public string Source { get; set; }
- public int TunerCount { get; set; }
- public string UserAgent { get; set; }
-
- public TunerHostInfo()
- {
- AllowHWTranscoding = true;
- }
- }
-
- public class ListingsProviderInfo
- {
- public string Id { get; set; }
- public string Type { get; set; }
- public string Username { get; set; }
- public string Password { get; set; }
- public string ListingsId { get; set; }
- public string ZipCode { get; set; }
- public string Country { get; set; }
- public string Path { get; set; }
-
- public string[] EnabledTuners { get; set; }
- public bool EnableAllTuners { get; set; }
- public string[] NewsCategories { get; set; }
- public string[] SportsCategories { get; set; }
- public string[] KidsCategories { get; set; }
- public string[] MovieCategories { get; set; }
- public NameValuePair[] ChannelMappings { get; set; }
- public string MoviePrefix { get; set; }
- public string PreferredLanguage { get; set; }
- public string UserAgent { get; set; }
-
- public ListingsProviderInfo()
- {
- NewsCategories = new[] { "news", "journalism", "documentary", "current affairs" };
- SportsCategories = new[] { "sports", "basketball", "baseball", "football" };
- KidsCategories = new[] { "kids", "family", "children", "childrens", "disney" };
- MovieCategories = new[] { "movie" };
- EnabledTuners = Array.Empty<string>();
- EnableAllTuners = true;
- ChannelMappings = Array.Empty<NameValuePair>();
- }
+ public string RecordingPostProcessorArguments { get; set; }
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
index 9ad13391a..ef5c5d2f3 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
@@ -1,12 +1,20 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.LiveTv
{
/// <summary>
- /// Class ServiceInfo
+ /// Class ServiceInfo.
/// </summary>
public class LiveTvServiceInfo
{
+ public LiveTvServiceInfo()
+ {
+ Tuners = Array.Empty<string>();
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
@@ -42,6 +50,7 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
public bool HasUpdateAvailable { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is visible.
/// </summary>
@@ -49,10 +58,5 @@ namespace MediaBrowser.Model.LiveTv
public bool IsVisible { get; set; }
public string[] Tuners { get; set; }
-
- public LiveTvServiceInfo()
- {
- Tuners = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvServiceStatus.cs b/MediaBrowser.Model/LiveTv/LiveTvServiceStatus.cs
index 7578f329a..72a0e2d7b 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvServiceStatus.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvServiceStatus.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public enum LiveTvServiceStatus
diff --git a/MediaBrowser.Model/LiveTv/LiveTvTunerStatus.cs b/MediaBrowser.Model/LiveTv/LiveTvTunerStatus.cs
index f7f521e43..80a646195 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvTunerStatus.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvTunerStatus.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public enum LiveTvTunerStatus
diff --git a/MediaBrowser.Model/LiveTv/ProgramAudio.cs b/MediaBrowser.Model/LiveTv/ProgramAudio.cs
index 158d67eb9..727d34695 100644
--- a/MediaBrowser.Model/LiveTv/ProgramAudio.cs
+++ b/MediaBrowser.Model/LiveTv/ProgramAudio.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public enum ProgramAudio
diff --git a/MediaBrowser.Model/LiveTv/RecordingQuery.cs b/MediaBrowser.Model/LiveTv/RecordingQuery.cs
index f98d7fe86..99bb1603c 100644
--- a/MediaBrowser.Model/LiveTv/RecordingQuery.cs
+++ b/MediaBrowser.Model/LiveTv/RecordingQuery.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
@@ -9,6 +12,11 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
public class RecordingQuery
{
+ public RecordingQuery()
+ {
+ EnableTotalRecordCount = true;
+ }
+
/// <summary>
/// Gets or sets the channel identifier.
/// </summary>
@@ -28,13 +36,13 @@ namespace MediaBrowser.Model.LiveTv
public string Id { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Use for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
@@ -58,25 +66,29 @@ namespace MediaBrowser.Model.LiveTv
public string SeriesTimerId { get; set; }
/// <summary>
- /// Fields to return within the items, in addition to basic information
+ /// Gets or sets the fields to return within the items, in addition to basic information.
/// </summary>
/// <value>The fields.</value>
public ItemFields[] Fields { get; set; }
+
public bool? EnableImages { get; set; }
+
public bool? IsLibraryItem { get; set; }
+
public bool? IsNews { get; set; }
+
public bool? IsMovie { get; set; }
+
public bool? IsSeries { get; set; }
+
public bool? IsKids { get; set; }
+
public bool? IsSports { get; set; }
+
public int? ImageTypeLimit { get; set; }
+
public ImageType[] EnableImageTypes { get; set; }
public bool EnableTotalRecordCount { get; set; }
-
- public RecordingQuery()
- {
- EnableTotalRecordCount = true;
- }
}
}
diff --git a/MediaBrowser.Model/LiveTv/RecordingStatus.cs b/MediaBrowser.Model/LiveTv/RecordingStatus.cs
index d3270c4d3..b0ba42d43 100644
--- a/MediaBrowser.Model/LiveTv/RecordingStatus.cs
+++ b/MediaBrowser.Model/LiveTv/RecordingStatus.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public enum RecordingStatus
diff --git a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
index 72c7a0c90..b26f5f45f 100644
--- a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
@@ -1,9 +1,20 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.LiveTv
{
+ public enum KeepUntil
+ {
+ UntilDeleted,
+ UntilSpaceNeeded,
+ UntilWatched,
+ UntilDate
+ }
+
/// <summary>
/// Class SeriesTimerInfoDto.
/// </summary>
@@ -12,7 +23,7 @@ namespace MediaBrowser.Model.LiveTv
public SeriesTimerInfoDto()
{
ImageTags = new Dictionary<ImageType, string>();
- Days = new DayOfWeek[] { };
+ Days = Array.Empty<DayOfWeek>();
Type = "SeriesTimer";
}
@@ -80,12 +91,4 @@ namespace MediaBrowser.Model.LiveTv
/// <value>The parent primary image tag.</value>
public string ParentPrimaryImageTag { get; set; }
}
-
- public enum KeepUntil
- {
- UntilDeleted,
- UntilSpaceNeeded,
- UntilWatched,
- UntilDate
- }
}
diff --git a/MediaBrowser.Model/LiveTv/SeriesTimerQuery.cs b/MediaBrowser.Model/LiveTv/SeriesTimerQuery.cs
index a15ba7a12..dae885775 100644
--- a/MediaBrowser.Model/LiveTv/SeriesTimerQuery.cs
+++ b/MediaBrowser.Model/LiveTv/SeriesTimerQuery.cs
@@ -1,14 +1,16 @@
-using MediaBrowser.Model.Entities;
+#pragma warning disable CS1591
+
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.LiveTv
{
public class SeriesTimerQuery
{
/// <summary>
- /// Gets or sets the sort by - SortName, Priority
+ /// Gets or sets the sort by - SortName, Priority.
/// </summary>
/// <value>The sort by.</value>
- public string SortBy { get; set; }
+ public string? SortBy { get; set; }
/// <summary>
/// Gets or sets the sort order.
diff --git a/MediaBrowser.Model/LiveTv/TimerInfoDto.cs b/MediaBrowser.Model/LiveTv/TimerInfoDto.cs
index 208f731c5..0b9b4141a 100644
--- a/MediaBrowser.Model/LiveTv/TimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/TimerInfoDto.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.LiveTv
@@ -38,6 +41,5 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value>The program information.</value>
public BaseItemDto ProgramInfo { get; set; }
-
}
}
diff --git a/MediaBrowser.Model/LiveTv/TimerQuery.cs b/MediaBrowser.Model/LiveTv/TimerQuery.cs
index 1478cc148..367c45b9d 100644
--- a/MediaBrowser.Model/LiveTv/TimerQuery.cs
+++ b/MediaBrowser.Model/LiveTv/TimerQuery.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.LiveTv
{
public class TimerQuery
diff --git a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs
new file mode 100644
index 000000000..05576a0f8
--- /dev/null
+++ b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs
@@ -0,0 +1,35 @@
+#nullable disable
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.LiveTv
+{
+ public class TunerHostInfo
+ {
+ public TunerHostInfo()
+ {
+ AllowHWTranscoding = true;
+ }
+
+ public string Id { get; set; }
+
+ public string Url { get; set; }
+
+ public string Type { get; set; }
+
+ public string DeviceId { get; set; }
+
+ public string FriendlyName { get; set; }
+
+ public bool ImportFavoritesOnly { get; set; }
+
+ public bool AllowHWTranscoding { get; set; }
+
+ public bool EnableStreamLooping { get; set; }
+
+ public string Source { get; set; }
+
+ public int TunerCount { get; set; }
+
+ public string UserAgent { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj
index f17fd7159..16bc4adf8 100644
--- a/MediaBrowser.Model/MediaBrowser.Model.csproj
+++ b/MediaBrowser.Model/MediaBrowser.Model.csproj
@@ -1,23 +1,53 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}</ProjectGuid>
+ </PropertyGroup>
<PropertyGroup>
<Authors>Jellyfin Contributors</Authors>
<PackageId>Jellyfin.Model</PackageId>
- <PackageLicenseUrl>https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt</PackageLicenseUrl>
+ <VersionPrefix>10.8.0</VersionPrefix>
<RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </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="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" />
+ <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="System.Globalization" Version="4.3.0" />
+ <PackageReference Include="System.Text.Json" Version="6.0.0-rc.2*" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="../Jellyfin.Data/Jellyfin.Data.csproj" />
+ <ProjectReference Include="../src/Jellyfin.Extensions/Jellyfin.Extensions.csproj" />
+ </ItemGroup>
+
</Project>
diff --git a/MediaBrowser.Model/MediaInfo/AudioCodec.cs b/MediaBrowser.Model/MediaInfo/AudioCodec.cs
index 5ebdb99cb..8b17757b8 100644
--- a/MediaBrowser.Model/MediaInfo/AudioCodec.cs
+++ b/MediaBrowser.Model/MediaInfo/AudioCodec.cs
@@ -1,6 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.MediaInfo
{
- public class AudioCodec
+ public static class AudioCodec
{
public const string AAC = "aac";
public const string MP3 = "mp3";
@@ -8,9 +10,9 @@ namespace MediaBrowser.Model.MediaInfo
public static string GetFriendlyName(string codec)
{
- if (string.IsNullOrEmpty(codec))
+ if (codec.Length == 0)
{
- return string.Empty;
+ return codec;
}
switch (codec.ToLowerInvariant())
diff --git a/MediaBrowser.Model/MediaInfo/BlurayDiscInfo.cs b/MediaBrowser.Model/MediaInfo/BlurayDiscInfo.cs
index e728ecdfd..83f982a5c 100644
--- a/MediaBrowser.Model/MediaInfo/BlurayDiscInfo.cs
+++ b/MediaBrowser.Model/MediaInfo/BlurayDiscInfo.cs
@@ -1,9 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.MediaInfo
{
/// <summary>
- /// Represents the result of BDInfo output
+ /// Represents the result of BDInfo output.
/// </summary>
public class BlurayDiscInfo
{
diff --git a/MediaBrowser.Model/MediaInfo/Container.cs b/MediaBrowser.Model/MediaInfo/Container.cs
deleted file mode 100644
index f8d56702d..000000000
--- a/MediaBrowser.Model/MediaInfo/Container.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace MediaBrowser.Model.MediaInfo
-{
- public class Container
- {
- public const string MP4 = "mp4";
- public const string MKV = "mkv";
- }
-}
diff --git a/MediaBrowser.Model/MediaInfo/IBlurayExaminer.cs b/MediaBrowser.Model/MediaInfo/IBlurayExaminer.cs
index 27137ab26..5b7d1d03c 100644
--- a/MediaBrowser.Model/MediaInfo/IBlurayExaminer.cs
+++ b/MediaBrowser.Model/MediaInfo/IBlurayExaminer.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Model.MediaInfo
{
/// <summary>
- /// Interface IBlurayExaminer
+ /// Interface IBlurayExaminer.
/// </summary>
public interface IBlurayExaminer
{
diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
index a5ae7c7a5..36a240706 100644
--- a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
+++ b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
@@ -1,25 +1,14 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dlna;
namespace MediaBrowser.Model.MediaInfo
{
public class LiveStreamRequest
{
- public string OpenToken { get; set; }
- public Guid UserId { get; set; }
- public string PlaySessionId { get; set; }
- public long? MaxStreamingBitrate { get; set; }
- public long? StartTimeTicks { get; set; }
- public int? AudioStreamIndex { get; set; }
- public int? SubtitleStreamIndex { get; set; }
- public int? MaxAudioChannels { get; set; }
- public Guid ItemId { get; set; }
- public DeviceProfile DeviceProfile { get; set; }
-
- public bool EnableDirectPlay { get; set; }
- public bool EnableDirectStream { get; set; }
- public MediaProtocol[] DirectPlayProtocols { get; set; }
-
public LiveStreamRequest()
{
EnableDirectPlay = true;
@@ -36,12 +25,37 @@ namespace MediaBrowser.Model.MediaInfo
DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http };
- var videoOptions = options as VideoOptions;
- if (videoOptions != null)
+ if (options is VideoOptions videoOptions)
{
AudioStreamIndex = videoOptions.AudioStreamIndex;
SubtitleStreamIndex = videoOptions.SubtitleStreamIndex;
}
}
+
+ public string OpenToken { get; set; }
+
+ public Guid UserId { get; set; }
+
+ public string PlaySessionId { get; set; }
+
+ public int? MaxStreamingBitrate { get; set; }
+
+ public long? StartTimeTicks { get; set; }
+
+ public int? AudioStreamIndex { get; set; }
+
+ public int? SubtitleStreamIndex { get; set; }
+
+ public int? MaxAudioChannels { get; set; }
+
+ public Guid ItemId { get; set; }
+
+ public DeviceProfile DeviceProfile { get; set; }
+
+ public bool EnableDirectPlay { get; set; }
+
+ public bool EnableDirectStream { get; set; }
+
+ public IReadOnlyList<MediaProtocol> DirectPlayProtocols { get; set; }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamResponse.cs b/MediaBrowser.Model/MediaInfo/LiveStreamResponse.cs
index dd4b69469..f017c1a11 100644
--- a/MediaBrowser.Model/MediaInfo/LiveStreamResponse.cs
+++ b/MediaBrowser.Model/MediaInfo/LiveStreamResponse.cs
@@ -1,9 +1,16 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.MediaInfo
{
public class LiveStreamResponse
{
- public MediaSourceInfo MediaSource { get; set; }
+ public LiveStreamResponse(MediaSourceInfo mediaSource)
+ {
+ MediaSource = mediaSource;
+ }
+
+ public MediaSourceInfo MediaSource { get; }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/MediaInfo.cs b/MediaBrowser.Model/MediaInfo/MediaInfo.cs
index 9d45a2af1..453aeb028 100644
--- a/MediaBrowser.Model/MediaInfo/MediaInfo.cs
+++ b/MediaBrowser.Model/MediaInfo/MediaInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Dto;
@@ -7,6 +10,17 @@ namespace MediaBrowser.Model.MediaInfo
{
public class MediaInfo : MediaSourceInfo, IHasProviderIds
{
+ public MediaInfo()
+ {
+ Chapters = Array.Empty<ChapterInfo>();
+ Artists = Array.Empty<string>();
+ AlbumArtists = Array.Empty<string>();
+ Studios = Array.Empty<string>();
+ Genres = Array.Empty<string>();
+ People = Array.Empty<BaseItemPerson>();
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
public ChapterInfo[] Chapters { get; set; }
/// <summary>
@@ -14,53 +28,59 @@ namespace MediaBrowser.Model.MediaInfo
/// </summary>
/// <value>The album.</value>
public string Album { get; set; }
+
/// <summary>
/// Gets or sets the artists.
/// </summary>
/// <value>The artists.</value>
public string[] Artists { get; set; }
+
/// <summary>
/// Gets or sets the album artists.
/// </summary>
/// <value>The album artists.</value>
public string[] AlbumArtists { get; set; }
+
/// <summary>
/// Gets or sets the studios.
/// </summary>
/// <value>The studios.</value>
public string[] Studios { get; set; }
+
public string[] Genres { get; set; }
+
+ public string ShowName { get; set; }
+
+ public string ForcedSortName { get; set; }
+
public int? IndexNumber { get; set; }
+
public int? ParentIndexNumber { get; set; }
+
public int? ProductionYear { get; set; }
+
public DateTime? PremiereDate { get; set; }
+
public BaseItemPerson[] People { get; set; }
+
public Dictionary<string, string> ProviderIds { get; set; }
+
/// <summary>
/// Gets or sets the official rating.
/// </summary>
/// <value>The official rating.</value>
public string OfficialRating { get; set; }
+
/// <summary>
/// Gets or sets the official rating description.
/// </summary>
/// <value>The official rating description.</value>
public string OfficialRatingDescription { get; set; }
+
/// <summary>
/// Gets or sets the overview.
/// </summary>
/// <value>The overview.</value>
public string Overview { get; set; }
-
- public MediaInfo()
- {
- Chapters = Array.Empty<ChapterInfo>();
- Artists = Array.Empty<string>();
- AlbumArtists = Array.Empty<string>();
- Studios = Array.Empty<string>();
- Genres = Array.Empty<string>();
- People = Array.Empty<BaseItemPerson>();
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/MediaProtocol.cs b/MediaBrowser.Model/MediaInfo/MediaProtocol.cs
index a993f6075..b9df01f27 100644
--- a/MediaBrowser.Model/MediaInfo/MediaProtocol.cs
+++ b/MediaBrowser.Model/MediaInfo/MediaProtocol.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.MediaInfo
{
public enum MediaProtocol
diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
index e5fad4e11..ecd9b8834 100644
--- a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
+++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dlna;
@@ -5,6 +8,17 @@ namespace MediaBrowser.Model.MediaInfo
{
public class PlaybackInfoRequest
{
+ public PlaybackInfoRequest()
+ {
+ EnableDirectPlay = true;
+ EnableDirectStream = true;
+ EnableTranscoding = true;
+ AllowVideoStreamCopy = true;
+ AllowAudioStreamCopy = true;
+ IsPlayback = true;
+ DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http };
+ }
+
public Guid Id { get; set; }
public Guid UserId { get; set; }
@@ -26,24 +40,19 @@ namespace MediaBrowser.Model.MediaInfo
public DeviceProfile DeviceProfile { get; set; }
public bool EnableDirectPlay { get; set; }
+
public bool EnableDirectStream { get; set; }
+
public bool EnableTranscoding { get; set; }
+
public bool AllowVideoStreamCopy { get; set; }
+
public bool AllowAudioStreamCopy { get; set; }
+
public bool IsPlayback { get; set; }
+
public bool AutoOpenLiveStream { get; set; }
public MediaProtocol[] DirectPlayProtocols { get; set; }
-
- public PlaybackInfoRequest()
- {
- EnableDirectPlay = true;
- EnableDirectStream = true;
- EnableTranscoding = true;
- AllowVideoStreamCopy = true;
- AllowAudioStreamCopy = true;
- IsPlayback = true;
- DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http };
- }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs
index 38638af42..32971b108 100644
--- a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs
+++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs
@@ -1,31 +1,39 @@
+using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.MediaInfo
{
+ /// <summary>
+ /// Class PlaybackInfoResponse.
+ /// </summary>
public class PlaybackInfoResponse
{
/// <summary>
+ /// Initializes a new instance of the <see cref="PlaybackInfoResponse" /> class.
+ /// </summary>
+ public PlaybackInfoResponse()
+ {
+ MediaSources = Array.Empty<MediaSourceInfo>();
+ }
+
+ /// <summary>
/// Gets or sets the media sources.
/// </summary>
/// <value>The media sources.</value>
- public MediaSourceInfo[] MediaSources { get; set; }
+ public IReadOnlyList<MediaSourceInfo> MediaSources { get; set; }
/// <summary>
/// Gets or sets the play session identifier.
/// </summary>
/// <value>The play session identifier.</value>
- public string PlaySessionId { get; set; }
+ public string? PlaySessionId { get; set; }
/// <summary>
/// Gets or sets the error code.
/// </summary>
/// <value>The error code.</value>
public PlaybackErrorCode? ErrorCode { get; set; }
-
- public PlaybackInfoResponse()
- {
- MediaSources = new MediaSourceInfo[] { };
- }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs b/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs
index 208e9bab9..2bd45695a 100644
--- a/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs
+++ b/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs
@@ -1,6 +1,8 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.MediaInfo
{
- public class SubtitleFormat
+ public static class SubtitleFormat
{
public const string SRT = "srt";
public const string SSA = "ssa";
diff --git a/MediaBrowser.Model/MediaInfo/SubtitleTrackEvent.cs b/MediaBrowser.Model/MediaInfo/SubtitleTrackEvent.cs
index 4eb000e58..88b00c166 100644
--- a/MediaBrowser.Model/MediaInfo/SubtitleTrackEvent.cs
+++ b/MediaBrowser.Model/MediaInfo/SubtitleTrackEvent.cs
@@ -1,10 +1,21 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.MediaInfo
{
public class SubtitleTrackEvent
{
+ public SubtitleTrackEvent(string id, string text)
+ {
+ Id = id;
+ Text = text;
+ }
+
public string Id { get; set; }
+
public string Text { get; set; }
+
public long StartPositionTicks { get; set; }
+
public long EndPositionTicks { get; set; }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs b/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs
index 962f4d2fe..d5c3a6aec 100644
--- a/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs
+++ b/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs
@@ -1,12 +1,17 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+
namespace MediaBrowser.Model.MediaInfo
{
public class SubtitleTrackInfo
{
- public SubtitleTrackEvent[] TrackEvents { get; set; }
-
public SubtitleTrackInfo()
{
- TrackEvents = new SubtitleTrackEvent[] { };
+ TrackEvents = Array.Empty<SubtitleTrackEvent>();
}
+
+ public IReadOnlyList<SubtitleTrackEvent> TrackEvents { get; set; }
}
}
diff --git a/MediaBrowser.Model/MediaInfo/TransportStreamTimestamp.cs b/MediaBrowser.Model/MediaInfo/TransportStreamTimestamp.cs
index 46ce2302e..b7ee5747a 100644
--- a/MediaBrowser.Model/MediaInfo/TransportStreamTimestamp.cs
+++ b/MediaBrowser.Model/MediaInfo/TransportStreamTimestamp.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.MediaInfo
{
public enum TransportStreamTimestamp
diff --git a/MediaBrowser.Model/MediaInfo/VideoCodec.cs b/MediaBrowser.Model/MediaInfo/VideoCodec.cs
deleted file mode 100644
index a26ce1b70..000000000
--- a/MediaBrowser.Model/MediaInfo/VideoCodec.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace MediaBrowser.Model.MediaInfo
-{
- public class VideoCodec
- {
- public const string H263 = "h263";
- public const string H264 = "h264";
- public const string H265 = "h265";
- public const string MPEG4 = "mpeg4";
- public const string MPEG1 = "mpeg1video";
- public const string MPEG2 = "mpeg2video";
- public const string MSMPEG4 = "msmpeg4";
- public const string VC1 = "vc1";
- }
-}
diff --git a/MediaBrowser.Model/Net/EndPointInfo.cs b/MediaBrowser.Model/Net/EndPointInfo.cs
index b73799ea8..034734a9e 100644
--- a/MediaBrowser.Model/Net/EndPointInfo.cs
+++ b/MediaBrowser.Model/Net/EndPointInfo.cs
@@ -1,8 +1,11 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Net
{
public class EndPointInfo
{
public bool IsLocal { get; set; }
+
public bool IsInNetwork { get; set; }
}
}
diff --git a/MediaBrowser.Model/Net/HttpException.cs b/MediaBrowser.Model/Net/HttpException.cs
deleted file mode 100644
index 16253ed6c..000000000
--- a/MediaBrowser.Model/Net/HttpException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Net;
-
-namespace MediaBrowser.Model.Net
-{
- /// <summary>
- /// Class HttpException
- /// </summary>
- public class HttpException : Exception
- {
- /// <summary>
- /// Gets or sets the status code.
- /// </summary>
- /// <value>The status code.</value>
- public HttpStatusCode? StatusCode { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is timed out.
- /// </summary>
- /// <value><c>true</c> if this instance is timed out; otherwise, <c>false</c>.</value>
- public bool IsTimedOut { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpException" /> class.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="innerException">The inner exception.</param>
- public HttpException(string message, Exception innerException)
- : base(message, innerException)
- {
-
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpException" /> class.
- /// </summary>
- /// <param name="message">The message.</param>
- public HttpException(string message)
- : base(message)
- {
- }
- }
-}
diff --git a/MediaBrowser.Model/Net/HttpResponse.cs b/MediaBrowser.Model/Net/HttpResponse.cs
deleted file mode 100644
index 286b1c0af..000000000
--- a/MediaBrowser.Model/Net/HttpResponse.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-
-namespace MediaBrowser.Model.Net
-{
- public class HttpResponse : IDisposable
- {
- /// <summary>
- /// Gets or sets the type of the content.
- /// </summary>
- /// <value>The type of the content.</value>
- public string ContentType { get; set; }
-
- /// <summary>
- /// Gets or sets the response URL.
- /// </summary>
- /// <value>The response URL.</value>
- public string ResponseUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the content.
- /// </summary>
- /// <value>The content.</value>
- public Stream Content { get; set; }
-
- /// <summary>
- /// Gets or sets the status code.
- /// </summary>
- /// <value>The status code.</value>
- public HttpStatusCode StatusCode { get; set; }
-
- /// <summary>
- /// Gets or sets the length of the content.
- /// </summary>
- /// <value>The length of the content.</value>
- public long? ContentLength { get; set; }
-
- /// <summary>
- /// Gets or sets the headers.
- /// </summary>
- /// <value>The headers.</value>
- public Dictionary<string, string> Headers { get; set; }
-
- private readonly IDisposable _disposable;
-
- public HttpResponse(IDisposable disposable)
- {
- _disposable = disposable;
- }
- public HttpResponse()
- {
- }
-
- public void Dispose()
- {
- if (_disposable != null)
- {
- _disposable.Dispose();
- }
- }
- }
-}
diff --git a/MediaBrowser.Model/Net/IAcceptSocket.cs b/MediaBrowser.Model/Net/IAcceptSocket.cs
deleted file mode 100644
index 2b21d3e66..000000000
--- a/MediaBrowser.Model/Net/IAcceptSocket.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Net
-{
- public class SocketCreateException : Exception
- {
- public SocketCreateException(string errorCode, Exception originalException)
- : base(errorCode, originalException)
- {
- ErrorCode = errorCode;
- }
-
- public string ErrorCode { get; private set; }
- }
-}
diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs
index 992ccb49b..3de41d565 100644
--- a/MediaBrowser.Model/Net/ISocket.cs
+++ b/MediaBrowser.Model/Net/ISocket.cs
@@ -1,4 +1,7 @@
+#pragma warning disable CS1591
+
using System;
+using System.Net;
using System.Threading;
using System.Threading.Tasks;
@@ -9,18 +12,23 @@ namespace MediaBrowser.Model.Net
/// </summary>
public interface ISocket : IDisposable
{
- IpAddressInfo LocalIPAddress { get; }
+ IPAddress LocalIPAddress { get; }
Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
- int Receive(byte[] buffer, int offset, int count);
-
IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback);
+
SocketReceiveResult EndReceive(IAsyncResult result);
/// <summary>
/// Sends a UDP message to a particular end point (uni or multicast).
/// </summary>
- Task SendToAsync(byte[] buffer, int offset, int bytes, IpEndPointInfo endPoint, CancellationToken cancellationToken);
+ /// <param name="buffer">An array of type <see cref="byte" /> that contains the data to send.</param>
+ /// <param name="offset">The zero-based position in buffer at which to begin sending data.</param>
+ /// <param name="bytes">The number of bytes to send.</param>
+ /// <param name="endPoint">An <see cref="IPEndPoint" /> that represents the remote device.</param>
+ /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
+ /// <returns>The task object representing the asynchronous operation.</returns>
+ Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs
index 69fe134bc..1527ef595 100644
--- a/MediaBrowser.Model/Net/ISocketFactory.cs
+++ b/MediaBrowser.Model/Net/ISocketFactory.cs
@@ -1,4 +1,6 @@
-using System.IO;
+#pragma warning disable CS1591
+
+using System.Net;
namespace MediaBrowser.Model.Net
{
@@ -7,41 +9,23 @@ namespace MediaBrowser.Model.Net
/// </summary>
public interface ISocketFactory
{
- /// <summary>
- /// Createa a new unicast socket using the specified local port number.
- /// </summary>
- /// <param name="localPort">The local port to bind to.</param>
- /// <returns>A <see cref="ISocket"/> implementation.</returns>
- ISocket CreateUdpSocket(int localPort);
-
ISocket CreateUdpBroadcastSocket(int localPort);
- ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort);
-
/// <summary>
- /// Createa a new unicast socket using the specified local port number.
+ /// Creates a new unicast socket using the specified local port number.
/// </summary>
- ISocket CreateSsdpUdpSocket(IpAddressInfo localIp, int localPort);
+ /// <param name="localIp">The local IP address to bind to.</param>
+ /// <param name="localPort">The local port to bind to.</param>
+ /// <returns>A new unicast socket using the specified local port number.</returns>
+ ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort);
/// <summary>
- /// Createa a new multicast socket using the specified multicast IP address, multicast time to live and local port.
+ /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port.
/// </summary>
/// <param name="ipAddress">The multicast IP address to bind to.</param>
/// <param name="multicastTimeToLive">The multicast time to live value. Actually a maximum number of network hops for UDP packets.</param>
/// <param name="localPort">The local port to bind to.</param>
/// <returns>A <see cref="ISocket"/> implementation.</returns>
ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort);
-
- Stream CreateNetworkStream(ISocket socket, bool ownsSocket);
- }
-
- public enum SocketType
- {
- Stream
- }
-
- public enum ProtocolType
- {
- Tcp
}
}
diff --git a/MediaBrowser.Model/Net/IpAddressInfo.cs b/MediaBrowser.Model/Net/IpAddressInfo.cs
deleted file mode 100644
index 7a278d4d4..000000000
--- a/MediaBrowser.Model/Net/IpAddressInfo.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Net
-{
- public class IpAddressInfo
- {
- public static IpAddressInfo Any = new IpAddressInfo("0.0.0.0", IpAddressFamily.InterNetwork);
- public static IpAddressInfo IPv6Any = new IpAddressInfo("00000000000000000000", IpAddressFamily.InterNetworkV6);
- public static IpAddressInfo Loopback = new IpAddressInfo("127.0.0.1", IpAddressFamily.InterNetwork);
- public static IpAddressInfo IPv6Loopback = new IpAddressInfo("::1", IpAddressFamily.InterNetworkV6);
-
- public string Address { get; set; }
- public IpAddressFamily AddressFamily { get; set; }
-
- public IpAddressInfo(string address, IpAddressFamily addressFamily)
- {
- Address = address;
- AddressFamily = addressFamily;
- }
-
- public bool Equals(IpAddressInfo address)
- {
- return string.Equals(address.Address, Address, StringComparison.OrdinalIgnoreCase);
- }
-
- public override string ToString()
- {
- return Address;
- }
- }
-
- public enum IpAddressFamily
- {
- InterNetwork,
- InterNetworkV6
- }
-}
diff --git a/MediaBrowser.Model/Net/IpEndPointInfo.cs b/MediaBrowser.Model/Net/IpEndPointInfo.cs
deleted file mode 100644
index f8c125144..000000000
--- a/MediaBrowser.Model/Net/IpEndPointInfo.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using System.Globalization;
-
-namespace MediaBrowser.Model.Net
-{
- public class IpEndPointInfo
- {
- public IpAddressInfo IpAddress { get; set; }
-
- public int Port { get; set; }
-
- public IpEndPointInfo()
- {
-
- }
-
- public IpEndPointInfo(IpAddressInfo address, int port)
- {
- IpAddress = address;
- Port = port;
- }
-
- public override string ToString()
- {
- var ipAddresString = IpAddress == null ? string.Empty : IpAddress.ToString();
-
- return ipAddresString + ":" + Port.ToString(CultureInfo.InvariantCulture);
- }
- }
-}
diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs
index 659abe84c..748170a0e 100644
--- a/MediaBrowser.Model/Net/MimeTypes.cs
+++ b/MediaBrowser.Model/Net/MimeTypes.cs
@@ -1,347 +1,236 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
-using MediaBrowser.Model.Extensions;
+using Jellyfin.Extensions;
namespace MediaBrowser.Model.Net
{
/// <summary>
- /// Class MimeTypes
+ /// Class MimeTypes.
/// </summary>
public static class MimeTypes
{
/// <summary>
- /// Any extension in this list is considered a video file - can be added to at runtime for extensibility
+ /// Any extension in this list is considered a video file.
/// </summary>
- private static readonly string[] VideoFileExtensions = new string[]
- {
- ".mkv",
- ".m2t",
- ".m2ts",
- ".img",
- ".iso",
- ".mk3d",
- ".ts",
- ".rmvb",
- ".mov",
- ".avi",
- ".mpg",
- ".mpeg",
- ".wmv",
- ".mp4",
- ".divx",
- ".dvr-ms",
- ".wtv",
- ".ogm",
- ".ogv",
- ".asf",
- ".m4v",
- ".flv",
- ".f4v",
- ".3gp",
- ".webm",
- ".mts",
- ".m2v",
- ".rec"
- };
-
- private static Dictionary<string, string> GetVideoFileExtensionsDictionary()
+ private static readonly HashSet<string> _videoFileExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
- var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- foreach (string ext in VideoFileExtensions)
- {
- dict[ext] = ext;
- }
-
- return dict;
- }
-
- private static readonly Dictionary<string, string> VideoFileExtensionsDictionary = GetVideoFileExtensionsDictionary();
+ ".3gp",
+ ".asf",
+ ".avi",
+ ".divx",
+ ".dvr-ms",
+ ".f4v",
+ ".flv",
+ ".img",
+ ".iso",
+ ".m2t",
+ ".m2ts",
+ ".m2v",
+ ".m4v",
+ ".mk3d",
+ ".mkv",
+ ".mov",
+ ".mp4",
+ ".mpg",
+ ".mpeg",
+ ".mts",
+ ".ogg",
+ ".ogm",
+ ".ogv",
+ ".rec",
+ ".ts",
+ ".rmvb",
+ ".webm",
+ ".wmv",
+ ".wtv",
+ };
// http://en.wikipedia.org/wiki/Internet_media_type
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
+ // http://www.iana.org/assignments/media-types/media-types.xhtml
// Add more as needed
-
- private static Dictionary<string, string> GetMimeTypeLookup()
+ private static readonly Dictionary<string, string> _mimeTypeLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
- var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- dict.Add(".jpg", "image/jpeg");
- dict.Add(".jpeg", "image/jpeg");
- dict.Add(".tbn", "image/jpeg");
- dict.Add(".png", "image/png");
- dict.Add(".gif", "image/gif");
- dict.Add(".tiff", "image/tiff");
- dict.Add(".webp", "image/webp");
- dict.Add(".ico", "image/vnd.microsoft.icon");
- dict.Add(".mpg", "video/mpeg");
- dict.Add(".mpeg", "video/mpeg");
- dict.Add(".ogv", "video/ogg");
- dict.Add(".mov", "video/quicktime");
- dict.Add(".webm", "video/webm");
- dict.Add(".mkv", "video/x-matroska");
- dict.Add(".wmv", "video/x-ms-wmv");
- dict.Add(".flv", "video/x-flv");
- dict.Add(".avi", "video/x-msvideo");
- dict.Add(".asf", "video/x-ms-asf");
- dict.Add(".m4v", "video/x-m4v");
- dict.Add(".m4s", "video/mp4");
- dict.Add(".cbz", "application/x-cbz");
- dict.Add(".cbr", "application/epub+zip");
- dict.Add(".epub", "application/epub+zip");
- dict.Add(".pdf", "application/pdf");
- dict.Add(".mobi", "application/x-mobipocket-ebook");
+ // Type application
+ { ".7z", "application/x-7z-compressed" },
+ { ".azw", "application/vnd.amazon.ebook" },
+ { ".azw3", "application/vnd.amazon.ebook" },
+ { ".cbz", "application/x-cbz" },
+ { ".cbr", "application/epub+zip" },
+ { ".eot", "application/vnd.ms-fontobject" },
+ { ".epub", "application/epub+zip" },
+ { ".js", "application/x-javascript" },
+ { ".json", "application/json" },
+ { ".m3u8", "application/x-mpegURL" },
+ { ".map", "application/x-javascript" },
+ { ".mobi", "application/x-mobipocket-ebook" },
+ { ".opf", "application/oebps-package+xml" },
+ { ".pdf", "application/pdf" },
+ { ".rar", "application/vnd.rar" },
+ { ".srt", "application/x-subrip" },
+ { ".ttml", "application/ttml+xml" },
+ { ".wasm", "application/wasm" },
+ { ".xml", "application/xml" },
+ { ".zip", "application/zip" },
+
+ // Type image
+ { ".bmp", "image/bmp" },
+ { ".gif", "image/gif" },
+ { ".ico", "image/vnd.microsoft.icon" },
+ { ".jpg", "image/jpeg" },
+ { ".jpeg", "image/jpeg" },
+ { ".png", "image/png" },
+ { ".svg", "image/svg+xml" },
+ { ".svgz", "image/svg+xml" },
+ { ".tbn", "image/jpeg" },
+ { ".tif", "image/tiff" },
+ { ".tiff", "image/tiff" },
+ { ".webp", "image/webp" },
+
+ // Type font
+ { ".ttf", "font/ttf" },
+ { ".woff", "font/woff" },
+ { ".woff2", "font/woff2" },
- dict.Add(".ass", "text/x-ssa");
- dict.Add(".ssa", "text/x-ssa");
+ // Type text
+ { ".ass", "text/x-ssa" },
+ { ".ssa", "text/x-ssa" },
+ { ".css", "text/css" },
+ { ".csv", "text/csv" },
+ { ".edl", "text/plain" },
+ { ".rtf", "text/rtf" },
+ { ".txt", "text/plain" },
+ { ".vtt", "text/vtt" },
- return dict;
- }
+ // Type video
+ { ".3gp", "video/3gpp" },
+ { ".3g2", "video/3gpp2" },
+ { ".asf", "video/x-ms-asf" },
+ { ".avi", "video/x-msvideo" },
+ { ".flv", "video/x-flv" },
+ { ".mp4", "video/mp4" },
+ { ".m4s", "video/mp4" },
+ { ".m4v", "video/x-m4v" },
+ { ".mpegts", "video/mp2t" },
+ { ".mpg", "video/mpeg" },
+ { ".mkv", "video/x-matroska" },
+ { ".mov", "video/quicktime" },
+ { ".mpd", "video/vnd.mpeg.dash.mpd" },
+ { ".ogv", "video/ogg" },
+ { ".ts", "video/mp2t" },
+ { ".webm", "video/webm" },
+ { ".wmv", "video/x-ms-wmv" },
- private static readonly Dictionary<string, string> MimeTypeLookup = GetMimeTypeLookup();
+ // Type audio
+ { ".aac", "audio/aac" },
+ { ".ac3", "audio/ac3" },
+ { ".ape", "audio/x-ape" },
+ { ".dsf", "audio/dsf" },
+ { ".dsp", "audio/dsp" },
+ { ".flac", "audio/flac" },
+ { ".m4a", "audio/mp4" },
+ { ".m4b", "audio/m4b" },
+ { ".mid", "audio/midi" },
+ { ".midi", "audio/midi" },
+ { ".mp3", "audio/mpeg" },
+ { ".oga", "audio/ogg" },
+ { ".ogg", "audio/ogg" },
+ { ".opus", "audio/ogg" },
+ { ".vorbis", "audio/vorbis" },
+ { ".wav", "audio/wav" },
+ { ".webma", "audio/webm" },
+ { ".wma", "audio/x-ms-wma" },
+ { ".wv", "audio/x-wavpack" },
+ { ".xsp", "audio/xsp" },
+ };
- private static readonly Dictionary<string, string> ExtensionLookup = CreateExtensionLookup();
+ private static readonly Dictionary<string, string> _extensionLookup = CreateExtensionLookup();
private static Dictionary<string, string> CreateExtensionLookup()
{
- var dict = MimeTypeLookup
+ var dict = _mimeTypeLookup
.GroupBy(i => i.Value)
.ToDictionary(x => x.Key, x => x.First().Key, StringComparer.OrdinalIgnoreCase);
dict["image/jpg"] = ".jpg";
dict["image/x-png"] = ".png";
+ dict["audio/x-aac"] = ".aac";
+
return dict;
}
- public static string GetMimeType(string path)
- {
- return GetMimeType(path, true);
- }
+ public static string GetMimeType(string path) => GetMimeType(path, "application/octet-stream");
/// <summary>
/// Gets the type of the MIME.
/// </summary>
- public static string GetMimeType(string path, bool enableStreamDefault)
+ /// <param name="filename">The filename to find the MIME type of.</param>
+ /// <param name="defaultValue">The default value to return if no fitting MIME type is found.</param>
+ /// <returns>The correct MIME type for the given filename, or <paramref name="defaultValue"/> if it wasn't found.</returns>
+ [return: NotNullIfNotNullAttribute("defaultValue")]
+ public static string? GetMimeType(string filename, string? defaultValue = null)
{
- if (string.IsNullOrEmpty(path))
+ if (filename.Length == 0)
{
- throw new ArgumentNullException(nameof(path));
+ throw new ArgumentException("String can't be empty.", nameof(filename));
}
- var ext = Path.GetExtension(path) ?? string.Empty;
+ var ext = Path.GetExtension(filename);
- if (MimeTypeLookup.TryGetValue(ext, out string result))
+ if (_mimeTypeLookup.TryGetValue(ext, out string? result))
{
return result;
}
- // Type video
- if (StringHelper.EqualsIgnoreCase(ext, ".3gp"))
- {
- return "video/3gpp";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".3g2"))
- {
- return "video/3gpp2";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".ts"))
- {
- return "video/mp2t";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".mpd"))
- {
- return "video/vnd.mpeg.dash.mpd";
- }
-
// Catch-all for all video types that don't require specific mime types
- if (VideoFileExtensionsDictionary.ContainsKey(ext))
+ if (_videoFileExtensions.Contains(ext))
{
- return "video/" + ext.TrimStart('.').ToLowerInvariant();
+ return "video/" + ext.Substring(1);
}
// Type text
- if (StringHelper.EqualsIgnoreCase(ext, ".css"))
- {
- return "text/css";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".csv"))
- {
- return "text/csv";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".html"))
+ if (string.Equals(ext, ".html", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(ext, ".htm", StringComparison.OrdinalIgnoreCase))
{
return "text/html; charset=UTF-8";
}
- if (StringHelper.EqualsIgnoreCase(ext, ".htm"))
- {
- return "text/html; charset=UTF-8";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".txt"))
- {
- return "text/plain";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".log"))
- {
- return "text/plain";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".xml"))
- {
- return "application/xml";
- }
-
- // Type audio
- if (StringHelper.EqualsIgnoreCase(ext, ".mp3"))
- {
- return "audio/mpeg";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".m4a"))
- {
- return "audio/mp4";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".aac"))
- {
- return "audio/mp4";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".webma"))
- {
- return "audio/webm";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".wav"))
- {
- return "audio/wav";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".wma"))
- {
- return "audio/x-ms-wma";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".flac"))
- {
- return "audio/flac";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".aac"))
- {
- return "audio/x-aac";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".ogg"))
- {
- return "audio/ogg";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".oga"))
- {
- return "audio/ogg";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".opus"))
- {
- return "audio/ogg";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".ac3"))
- {
- return "audio/ac3";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".dsf"))
- {
- return "audio/dsf";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".m4b"))
- {
- return "audio/m4b";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".xsp"))
- {
- return "audio/xsp";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".dsp"))
- {
- return "audio/dsp";
- }
- // Playlists
- if (StringHelper.EqualsIgnoreCase(ext, ".m3u8"))
- {
- return "application/x-mpegURL";
- }
-
- // Misc
- if (StringHelper.EqualsIgnoreCase(ext, ".dll"))
- {
- return "application/octet-stream";
- }
-
- // Web
- if (StringHelper.EqualsIgnoreCase(ext, ".js"))
- {
- return "application/x-javascript";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".json"))
- {
- return "application/json";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".map"))
- {
- return "application/x-javascript";
- }
-
- if (StringHelper.EqualsIgnoreCase(ext, ".woff"))
- {
- return "font/woff";
- }
-
- if (StringHelper.EqualsIgnoreCase(ext, ".ttf"))
- {
- return "font/ttf";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".eot"))
- {
- return "application/vnd.ms-fontobject";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".svg"))
- {
- return "image/svg+xml";
- }
- if (StringHelper.EqualsIgnoreCase(ext, ".svgz"))
- {
- return "image/svg+xml";
- }
-
- if (StringHelper.EqualsIgnoreCase(ext, ".srt"))
+ if (string.Equals(ext, ".log", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(ext, ".srt", StringComparison.OrdinalIgnoreCase))
{
return "text/plain";
}
- if (StringHelper.EqualsIgnoreCase(ext, ".vtt"))
- {
- return "text/vtt";
- }
-
- if (StringHelper.EqualsIgnoreCase(ext, ".ttml"))
- {
- return "application/ttml+xml";
- }
-
- if (enableStreamDefault)
+ // Misc
+ if (string.Equals(ext, ".dll", StringComparison.OrdinalIgnoreCase))
{
return "application/octet-stream";
}
- return null;
+ return defaultValue;
}
- public static string ToExtension(string mimeType)
+ public static string? ToExtension(string mimeType)
{
- if (string.IsNullOrEmpty(mimeType))
+ if (mimeType.Length == 0)
{
- throw new ArgumentNullException(nameof(mimeType));
+ throw new ArgumentException("String can't be empty.", nameof(mimeType));
}
// handle text/html; charset=UTF-8
- mimeType = mimeType.Split(';')[0];
+ mimeType = mimeType.AsSpan().LeftPart(';').ToString();
- if (ExtensionLookup.TryGetValue(mimeType, out string result))
+ if (_extensionLookup.TryGetValue(mimeType, out string? result))
{
return result;
}
+
return null;
}
}
diff --git a/MediaBrowser.Model/Net/NetworkShare.cs b/MediaBrowser.Model/Net/NetworkShare.cs
deleted file mode 100644
index 1f61414fc..000000000
--- a/MediaBrowser.Model/Net/NetworkShare.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-namespace MediaBrowser.Model.Net
-{
- public class NetworkShare
- {
- /// <summary>
- /// The name of the computer that this share belongs to
- /// </summary>
- public string Server { get; set; }
-
- /// <summary>
- /// Share name
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// Local path
- /// </summary>
- public string Path { get; set; }
-
- /// <summary>
- /// Share type
- /// </summary>
- public NetworkShareType ShareType { get; set; }
-
- /// <summary>
- /// Comment
- /// </summary>
- public string Remark { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Net/NetworkShareType.cs b/MediaBrowser.Model/Net/NetworkShareType.cs
index bf2d092a6..5d985f85d 100644
--- a/MediaBrowser.Model/Net/NetworkShareType.cs
+++ b/MediaBrowser.Model/Net/NetworkShareType.cs
@@ -1,28 +1,32 @@
namespace MediaBrowser.Model.Net
{
/// <summary>
- /// Enum NetworkShareType
+ /// Enum NetworkShareType.
/// </summary>
public enum NetworkShareType
{
/// <summary>
- /// Disk share
+ /// Disk share.
/// </summary>
Disk,
+
/// <summary>
- /// Printer share
+ /// Printer share.
/// </summary>
Printer,
+
/// <summary>
- /// Device share
+ /// Device share.
/// </summary>
Device,
+
/// <summary>
- /// IPC share
+ /// IPC share.
/// </summary>
Ipc,
+
/// <summary>
- /// Special share
+ /// Special share.
/// </summary>
Special
}
diff --git a/MediaBrowser.Model/Net/SocketReceiveResult.cs b/MediaBrowser.Model/Net/SocketReceiveResult.cs
index 8c394f7c7..1524786ea 100644
--- a/MediaBrowser.Model/Net/SocketReceiveResult.cs
+++ b/MediaBrowser.Model/Net/SocketReceiveResult.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+using System.Net;
+
namespace MediaBrowser.Model.Net
{
/// <summary>
@@ -6,19 +10,23 @@ namespace MediaBrowser.Model.Net
public sealed class SocketReceiveResult
{
/// <summary>
- /// The buffer to place received data into.
+ /// Gets or sets the buffer to place received data into.
/// </summary>
public byte[] Buffer { get; set; }
/// <summary>
- /// The number of bytes received.
+ /// Gets or sets the number of bytes received.
/// </summary>
public int ReceivedBytes { get; set; }
/// <summary>
- /// The <see cref="IpEndPointInfo"/> the data was received from.
+ /// Gets or sets the <see cref="IPEndPoint"/> the data was received from.
+ /// </summary>
+ public IPEndPoint RemoteEndPoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the local <see cref="IPAddress"/>.
/// </summary>
- public IpEndPointInfo RemoteEndPoint { get; set; }
- public IpAddressInfo LocalIPAddress { get; set; }
+ public IPAddress LocalIPAddress { get; set; }
}
}
diff --git a/MediaBrowser.Model/Net/WebSocketMessage.cs b/MediaBrowser.Model/Net/WebSocketMessage.cs
index c763216f1..b00158cb3 100644
--- a/MediaBrowser.Model/Net/WebSocketMessage.cs
+++ b/MediaBrowser.Model/Net/WebSocketMessage.cs
@@ -1,23 +1,31 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using MediaBrowser.Model.Session;
+
namespace MediaBrowser.Model.Net
{
/// <summary>
- /// Class WebSocketMessage
+ /// Class WebSocketMessage.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">The type of the data.</typeparam>
public class WebSocketMessage<T>
{
/// <summary>
/// Gets or sets the type of the message.
/// </summary>
/// <value>The type of the message.</value>
- public string MessageType { get; set; }
- public string MessageId { get; set; }
+ public SessionMessageType MessageType { get; set; }
+
+ public Guid MessageId { get; set; }
+
public string ServerId { get; set; }
+
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public T Data { get; set; }
}
-
}
diff --git a/MediaBrowser.Model/Notifications/NotificationLevel.cs b/MediaBrowser.Model/Notifications/NotificationLevel.cs
index 6a838b125..14fead3f0 100644
--- a/MediaBrowser.Model/Notifications/NotificationLevel.cs
+++ b/MediaBrowser.Model/Notifications/NotificationLevel.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Notifications
{
public enum NotificationLevel
diff --git a/MediaBrowser.Model/Notifications/NotificationOption.cs b/MediaBrowser.Model/Notifications/NotificationOption.cs
index 51a07370f..58aecb3d3 100644
--- a/MediaBrowser.Model/Notifications/NotificationOption.cs
+++ b/MediaBrowser.Model/Notifications/NotificationOption.cs
@@ -1,18 +1,36 @@
+#pragma warning disable CA1819 // Properties should not return arrays
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Notifications
{
public class NotificationOption
{
- public string Type { get; set; }
+ public NotificationOption(string type)
+ {
+ Type = type;
+ DisabledServices = Array.Empty<string>();
+ DisabledMonitorUsers = Array.Empty<string>();
+ SendToUsers = Array.Empty<string>();
+ }
+
+ public NotificationOption()
+ {
+ DisabledServices = Array.Empty<string>();
+ DisabledMonitorUsers = Array.Empty<string>();
+ SendToUsers = Array.Empty<string>();
+ }
+
+ public string? Type { get; set; }
/// <summary>
- /// User Ids to not monitor (it's opt out)
+ /// Gets or sets user Ids to not monitor (it's opt out).
/// </summary>
public string[] DisabledMonitorUsers { get; set; }
/// <summary>
- /// User Ids to send to (if SendToUserMode == Custom)
+ /// Gets or sets user Ids to send to (if SendToUserMode == Custom).
/// </summary>
public string[] SendToUsers { get; set; }
@@ -33,12 +51,5 @@ namespace MediaBrowser.Model.Notifications
/// </summary>
/// <value>The send to user mode.</value>
public SendToUserType SendToUserMode { get; set; }
-
- public NotificationOption()
- {
- DisabledServices = Array.Empty<string>();
- DisabledMonitorUsers = Array.Empty<string>();
- SendToUsers = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/Notifications/NotificationOptions.cs b/MediaBrowser.Model/Notifications/NotificationOptions.cs
index f48b5ee7f..09beb2ef7 100644
--- a/MediaBrowser.Model/Notifications/NotificationOptions.cs
+++ b/MediaBrowser.Model/Notifications/NotificationOptions.cs
@@ -1,86 +1,84 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Users;
+using System.Linq;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Notifications
{
public class NotificationOptions
{
- public NotificationOption[] Options { get; set; }
-
public NotificationOptions()
{
Options = new[]
{
- new NotificationOption
+ new NotificationOption(NotificationType.TaskFailed.ToString())
{
- Type = NotificationType.TaskFailed.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.ServerRestartRequired.ToString())
{
- Type = NotificationType.ServerRestartRequired.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.ApplicationUpdateAvailable.ToString())
{
- Type = NotificationType.ApplicationUpdateAvailable.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.ApplicationUpdateInstalled.ToString())
{
- Type = NotificationType.ApplicationUpdateInstalled.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.PluginUpdateInstalled.ToString())
{
- Type = NotificationType.PluginUpdateInstalled.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.PluginUninstalled.ToString())
{
- Type = NotificationType.PluginUninstalled.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.InstallationFailed.ToString())
{
- Type = NotificationType.InstallationFailed.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.PluginInstalled.ToString())
{
- Type = NotificationType.PluginInstalled.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.PluginError.ToString())
{
- Type = NotificationType.PluginError.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
},
- new NotificationOption
+ new NotificationOption(NotificationType.UserLockedOut.ToString())
{
- Type = NotificationType.UserLockedOut.ToString(),
Enabled = true,
SendToUserMode = SendToUserType.Admins
}
};
}
+ public NotificationOption[] Options { get; set; }
+
public NotificationOption GetOptions(string type)
{
foreach (NotificationOption i in Options)
{
- if (StringHelper.EqualsIgnoreCase(type, i.Type)) return i;
+ if (string.Equals(type, i.Type, StringComparison.OrdinalIgnoreCase))
+ {
+ return i;
+ }
}
+
return null;
}
@@ -95,19 +93,20 @@ namespace MediaBrowser.Model.Notifications
{
NotificationOption opt = GetOptions(notificationType);
- return opt == null ||
- !ListHelper.ContainsIgnoreCase(opt.DisabledServices, service);
+ return opt == null
+ || !opt.DisabledServices.Contains(service, StringComparer.OrdinalIgnoreCase);
}
public bool IsEnabledToMonitorUser(string type, Guid userId)
{
NotificationOption opt = GetOptions(type);
- return opt != null && opt.Enabled &&
- !ListHelper.ContainsIgnoreCase(opt.DisabledMonitorUsers, userId.ToString(""));
+ return opt != null
+ && opt.Enabled
+ && !opt.DisabledMonitorUsers.Contains(userId.ToString("N"), StringComparer.OrdinalIgnoreCase);
}
- public bool IsEnabledToSendToUser(string type, string userId, UserPolicy userPolicy)
+ public bool IsEnabledToSendToUser(string type, string userId, User user)
{
NotificationOption opt = GetOptions(type);
@@ -118,12 +117,12 @@ namespace MediaBrowser.Model.Notifications
return true;
}
- if (opt.SendToUserMode == SendToUserType.Admins && userPolicy.IsAdministrator)
+ if (opt.SendToUserMode == SendToUserType.Admins && user.HasPermission(PermissionKind.IsAdministrator))
{
return true;
}
- return ListHelper.ContainsIgnoreCase(opt.SendToUsers, userId);
+ return opt.SendToUsers.Contains(userId, StringComparer.OrdinalIgnoreCase);
}
return false;
diff --git a/MediaBrowser.Model/Notifications/NotificationRequest.cs b/MediaBrowser.Model/Notifications/NotificationRequest.cs
index 5a2634e73..622c50cd8 100644
--- a/MediaBrowser.Model/Notifications/NotificationRequest.cs
+++ b/MediaBrowser.Model/Notifications/NotificationRequest.cs
@@ -1,9 +1,18 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Notifications
{
public class NotificationRequest
{
+ public NotificationRequest()
+ {
+ UserIds = Array.Empty<Guid>();
+ Date = DateTime.UtcNow;
+ }
+
public string Name { get; set; }
public string Description { get; set; }
@@ -17,16 +26,10 @@ namespace MediaBrowser.Model.Notifications
public DateTime Date { get; set; }
/// <summary>
- /// The corresponding type name used in configuration. Not for display.
+ /// Gets or sets the corresponding type name used in configuration. Not for display.
/// </summary>
public string NotificationType { get; set; }
public SendToUserType? SendToUserMode { get; set; }
-
- public NotificationRequest()
- {
- UserIds = Array.Empty<Guid>();
- Date = DateTime.UtcNow;
- }
}
}
diff --git a/MediaBrowser.Model/Notifications/NotificationType.cs b/MediaBrowser.Model/Notifications/NotificationType.cs
index 38b519a14..a8b257b8d 100644
--- a/MediaBrowser.Model/Notifications/NotificationType.cs
+++ b/MediaBrowser.Model/Notifications/NotificationType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Notifications
{
public enum NotificationType
@@ -16,7 +18,6 @@ namespace MediaBrowser.Model.Notifications
NewLibraryContent,
ServerRestartRequired,
TaskFailed,
- CameraImageUploaded,
UserLockedOut
}
}
diff --git a/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs b/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
index ff957e644..402fbe81a 100644
--- a/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
+++ b/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Notifications
{
public class NotificationTypeInfo
diff --git a/MediaBrowser.Model/Notifications/SendToUserType.cs b/MediaBrowser.Model/Notifications/SendToUserType.cs
index 9f63d24bf..65fc4e1ab 100644
--- a/MediaBrowser.Model/Notifications/SendToUserType.cs
+++ b/MediaBrowser.Model/Notifications/SendToUserType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Notifications
{
public enum SendToUserType
diff --git a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
index 007965c0f..e8ee49403 100644
--- a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
+++ b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
@@ -1,4 +1,8 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Model.Playlists
{
@@ -6,15 +10,10 @@ namespace MediaBrowser.Model.Playlists
{
public string Name { get; set; }
- public Guid[] ItemIdList { get; set; }
+ public IReadOnlyList<Guid> ItemIdList { get; set; } = Array.Empty<Guid>();
public string MediaType { get; set; }
public Guid UserId { get; set; }
-
- public PlaylistCreationRequest()
- {
- ItemIdList = Array.Empty<Guid>();
- }
}
}
diff --git a/MediaBrowser.Model/Playlists/PlaylistCreationResult.cs b/MediaBrowser.Model/Playlists/PlaylistCreationResult.cs
index 301ae66a7..f3a1518ed 100644
--- a/MediaBrowser.Model/Playlists/PlaylistCreationResult.cs
+++ b/MediaBrowser.Model/Playlists/PlaylistCreationResult.cs
@@ -1,7 +1,14 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Playlists
{
public class PlaylistCreationResult
{
- public string Id { get; set; }
+ public PlaylistCreationResult(string id)
+ {
+ Id = id;
+ }
+
+ public string Id { get; }
}
}
diff --git a/MediaBrowser.Model/Playlists/PlaylistItemQuery.cs b/MediaBrowser.Model/Playlists/PlaylistItemQuery.cs
deleted file mode 100644
index 1f03c14d3..000000000
--- a/MediaBrowser.Model/Playlists/PlaylistItemQuery.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Model.Playlists
-{
- public class PlaylistItemQuery
- {
- /// <summary>
- /// Gets or sets the identifier.
- /// </summary>
- /// <value>The identifier.</value>
- public string Id { get; set; }
-
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the start index.
- /// </summary>
- /// <value>The start index.</value>
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// Gets or sets the limit.
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
-
- /// <summary>
- /// Gets or sets the fields.
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Plugins/BasePluginConfiguration.cs b/MediaBrowser.Model/Plugins/BasePluginConfiguration.cs
index 39db22133..ac540782c 100644
--- a/MediaBrowser.Model/Plugins/BasePluginConfiguration.cs
+++ b/MediaBrowser.Model/Plugins/BasePluginConfiguration.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Model.Plugins
{
/// <summary>
- /// Class BasePluginConfiguration
+ /// Class BasePluginConfiguration.
/// </summary>
public class BasePluginConfiguration
{
diff --git a/MediaBrowser.Model/Plugins/IHasWebPages.cs b/MediaBrowser.Model/Plugins/IHasWebPages.cs
index 5bda7e65e..765c2d373 100644
--- a/MediaBrowser.Model/Plugins/IHasWebPages.cs
+++ b/MediaBrowser.Model/Plugins/IHasWebPages.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
namespace MediaBrowser.Model.Plugins
diff --git a/MediaBrowser.Model/Plugins/PluginInfo.cs b/MediaBrowser.Model/Plugins/PluginInfo.cs
index 9ff9ea457..8eb90bdb0 100644
--- a/MediaBrowser.Model/Plugins/PluginInfo.cs
+++ b/MediaBrowser.Model/Plugins/PluginInfo.cs
@@ -1,3 +1,5 @@
+using System;
+
namespace MediaBrowser.Model.Plugins
{
/// <summary>
@@ -6,38 +8,60 @@ namespace MediaBrowser.Model.Plugins
public class PluginInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="PluginInfo"/> class.
+ /// </summary>
+ /// <param name="name">The plugin name.</param>
+ /// <param name="version">The plugin <see cref="Version"/>.</param>
+ /// <param name="description">The plugin description.</param>
+ /// <param name="id">The <see cref="Guid"/>.</param>
+ /// <param name="canUninstall">True if this plugin can be uninstalled.</param>
+ public PluginInfo(string name, Version version, string description, Guid id, bool canUninstall)
+ {
+ Name = name;
+ Version = version;
+ Description = description;
+ Id = id;
+ CanUninstall = canUninstall;
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
- /// <value>The name.</value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
- /// <value>The version.</value>
- public string Version { get; set; }
+ public Version Version { get; set; }
/// <summary>
/// Gets or sets the name of the configuration file.
/// </summary>
- /// <value>The name of the configuration file.</value>
- public string ConfigurationFileName { get; set; }
+ public string? ConfigurationFileName { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
- /// <value>The description.</value>
public string Description { get; set; }
/// <summary>
/// Gets or sets the unique id.
/// </summary>
- /// <value>The unique id.</value>
- public string Id { get; set; }
+ public Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the plugin can be uninstalled.
+ /// </summary>
+ public bool CanUninstall { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this plugin has a valid image.
+ /// </summary>
+ public bool HasImage { get; set; }
+
/// <summary>
- /// Gets or sets the image URL.
+ /// Gets or sets a value indicating the status of the plugin.
/// </summary>
- /// <value>The image URL.</value>
- public string ImageUrl { get; set; }
+ public PluginStatus Status { get; set; }
}
}
diff --git a/MediaBrowser.Model/Plugins/PluginPageInfo.cs b/MediaBrowser.Model/Plugins/PluginPageInfo.cs
index 8ed2064b9..f4d83c28b 100644
--- a/MediaBrowser.Model/Plugins/PluginPageInfo.cs
+++ b/MediaBrowser.Model/Plugins/PluginPageInfo.cs
@@ -1,17 +1,38 @@
namespace MediaBrowser.Model.Plugins
{
+ /// <summary>
+ /// Defines the <see cref="PluginPageInfo" />.
+ /// </summary>
public class PluginPageInfo
{
- public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ public string Name { get; set; } = string.Empty;
- public string DisplayName { get; set; }
+ /// <summary>
+ /// Gets or sets the display name.
+ /// </summary>
+ public string? DisplayName { get; set; }
- public string EmbeddedResourcePath { get; set; }
+ /// <summary>
+ /// Gets or sets the resource path.
+ /// </summary>
+ public string EmbeddedResourcePath { get; set; } = string.Empty;
+ /// <summary>
+ /// Gets or sets a value indicating whether this plugin should appear in the main menu.
+ /// </summary>
public bool EnableInMainMenu { get; set; }
- public string MenuSection { get; set; }
+ /// <summary>
+ /// Gets or sets the menu section.
+ /// </summary>
+ public string? MenuSection { get; set; }
- public string MenuIcon { get; set; }
+ /// <summary>
+ /// Gets or sets the menu icon.
+ /// </summary>
+ public string? MenuIcon { get; set; }
}
}
diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs
new file mode 100644
index 000000000..4b9b9bbee
--- /dev/null
+++ b/MediaBrowser.Model/Plugins/PluginStatus.cs
@@ -0,0 +1,47 @@
+namespace MediaBrowser.Model.Plugins
+{
+ /// <summary>
+ /// Plugin load status.
+ /// </summary>
+ public enum PluginStatus
+ {
+ /// <summary>
+ /// This plugin requires a restart in order for it to load. This is a memory only status.
+ /// The actual status of the plugin after reload is present in the manifest.
+ /// eg. A disabled plugin will still be active until the next restart, and so will have a memory status of Restart,
+ /// but a disk manifest status of Disabled.
+ /// </summary>
+ Restart = 1,
+
+ /// <summary>
+ /// This plugin is currently running.
+ /// </summary>
+ Active = 0,
+
+ /// <summary>
+ /// This plugin has been marked as disabled.
+ /// </summary>
+ Disabled = -1,
+
+ /// <summary>
+ /// This plugin does not meet the TargetAbi requirements.
+ /// </summary>
+ NotSupported = -2,
+
+ /// <summary>
+ /// This plugin caused an error when instantiated. (Either DI loop, or exception)
+ /// </summary>
+ Malfunctioned = -3,
+
+ /// <summary>
+ /// This plugin has been superceded by another version.
+ /// </summary>
+ Superceded = -4,
+
+ /// <summary>
+ /// An attempt to remove this plugin from disk will happen at every restart.
+ /// It will not be loaded, if unable to do so.
+ /// </summary>
+ Deleted = -5
+ }
+}
diff --git a/MediaBrowser.Model/Properties/AssemblyInfo.cs b/MediaBrowser.Model/Properties/AssemblyInfo.cs
index e78719e35..e50baf604 100644
--- a/MediaBrowser.Model/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.Model/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -9,11 +10,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.Model.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/MediaBrowser.Model/Providers/ExternalIdInfo.cs b/MediaBrowser.Model/Providers/ExternalIdInfo.cs
index bff84c553..d026d574f 100644
--- a/MediaBrowser.Model/Providers/ExternalIdInfo.cs
+++ b/MediaBrowser.Model/Providers/ExternalIdInfo.cs
@@ -1,23 +1,51 @@
namespace MediaBrowser.Model.Providers
{
+ /// <summary>
+ /// Represents the external id information for serialization to the client.
+ /// </summary>
public class ExternalIdInfo
{
/// <summary>
- /// Gets or sets the name.
+ /// Initializes a new instance of the <see cref="ExternalIdInfo"/> class.
/// </summary>
- /// <value>The name.</value>
+ /// <param name="name">Name of the external id provider (IE: IMDB, MusicBrainz, etc).</param>
+ /// <param name="key">Key for this id. This key should be unique across all providers.</param>
+ /// <param name="type">Specific media type for this id.</param>
+ /// <param name="urlFormatString">URL format string.</param>
+ public ExternalIdInfo(string name, string key, ExternalIdMediaType? type, string? urlFormatString)
+ {
+ Name = name;
+ Key = key;
+ Type = type;
+ UrlFormatString = urlFormatString;
+ }
+
+ /// <summary>
+ /// Gets or sets the display name of the external id provider (IE: IMDB, MusicBrainz, etc).
+ /// </summary>
+ // TODO: This should be renamed to ProviderName
public string Name { get; set; }
/// <summary>
- /// Gets or sets the key.
+ /// Gets or sets the unique key for this id. This key should be unique across all providers.
/// </summary>
- /// <value>The key.</value>
+ // TODO: This property is not actually unique across the concrete types at the moment. It should be updated to be unique.
public string Key { get; set; }
/// <summary>
+ /// Gets or sets the specific media type for this id. This is used to distinguish between the different
+ /// external id types for providers with multiple ids.
+ /// A null value indicates there is no specific media type associated with the external id, or this is the
+ /// default id for the external provider so there is no need to specify a type.
+ /// </summary>
+ /// <remarks>
+ /// This can be used along with the <see cref="Name"/> to localize the external id on the client.
+ /// </remarks>
+ public ExternalIdMediaType? Type { get; set; }
+
+ /// <summary>
/// Gets or sets the URL format string.
/// </summary>
- /// <value>The URL format string.</value>
- public string UrlFormatString { get; set; }
+ public string? UrlFormatString { get; set; }
}
}
diff --git a/MediaBrowser.Model/Providers/ExternalIdMediaType.cs b/MediaBrowser.Model/Providers/ExternalIdMediaType.cs
new file mode 100644
index 000000000..5303c8f58
--- /dev/null
+++ b/MediaBrowser.Model/Providers/ExternalIdMediaType.cs
@@ -0,0 +1,71 @@
+namespace MediaBrowser.Model.Providers
+{
+ /// <summary>
+ /// The specific media type of an <see cref="ExternalIdInfo"/>.
+ /// </summary>
+ /// <remarks>
+ /// Client applications may use this as a translation key.
+ /// </remarks>
+ public enum ExternalIdMediaType
+ {
+ /// <summary>
+ /// A music album.
+ /// </summary>
+ Album = 1,
+
+ /// <summary>
+ /// The artist of a music album.
+ /// </summary>
+ AlbumArtist = 2,
+
+ /// <summary>
+ /// The artist of a media item.
+ /// </summary>
+ Artist = 3,
+
+ /// <summary>
+ /// A boxed set of media.
+ /// </summary>
+ BoxSet = 4,
+
+ /// <summary>
+ /// A series episode.
+ /// </summary>
+ Episode = 5,
+
+ /// <summary>
+ /// A movie.
+ /// </summary>
+ Movie = 6,
+
+ /// <summary>
+ /// An alternative artist apart from the main artist.
+ /// </summary>
+ OtherArtist = 7,
+
+ /// <summary>
+ /// A person.
+ /// </summary>
+ Person = 8,
+
+ /// <summary>
+ /// A release group.
+ /// </summary>
+ ReleaseGroup = 9,
+
+ /// <summary>
+ /// A single season of a series.
+ /// </summary>
+ Season = 10,
+
+ /// <summary>
+ /// A series.
+ /// </summary>
+ Series = 11,
+
+ /// <summary>
+ /// A music track.
+ /// </summary>
+ Track = 12
+ }
+}
diff --git a/MediaBrowser.Model/Providers/ExternalUrl.cs b/MediaBrowser.Model/Providers/ExternalUrl.cs
index 69cead92a..9467a2b00 100644
--- a/MediaBrowser.Model/Providers/ExternalUrl.cs
+++ b/MediaBrowser.Model/Providers/ExternalUrl.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Providers
{
public class ExternalUrl
diff --git a/MediaBrowser.Model/Providers/ImageProviderInfo.cs b/MediaBrowser.Model/Providers/ImageProviderInfo.cs
index 1c4cff373..19af81c85 100644
--- a/MediaBrowser.Model/Providers/ImageProviderInfo.cs
+++ b/MediaBrowser.Model/Providers/ImageProviderInfo.cs
@@ -8,16 +8,25 @@ namespace MediaBrowser.Model.Providers
public class ImageProviderInfo
{
/// <summary>
- /// Gets or sets the name.
+ /// Initializes a new instance of the <see cref="ImageProviderInfo" /> class.
/// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- public ImageType[] SupportedImages { get; set; }
-
- public ImageProviderInfo()
+ /// <param name="name">The name of the image provider.</param>
+ /// <param name="supportedImages">The image types supported by the image provider.</param>
+ public ImageProviderInfo(string name, ImageType[] supportedImages)
{
- SupportedImages = new ImageType[] { };
+ Name = name;
+ SupportedImages = supportedImages;
}
+
+ /// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name { get; }
+
+ /// <summary>
+ /// Gets the supported image types.
+ /// </summary>
+ public ImageType[] SupportedImages { get; }
}
}
diff --git a/MediaBrowser.Model/Providers/RemoteImageInfo.cs b/MediaBrowser.Model/Providers/RemoteImageInfo.cs
index aacd108ec..48207d2d4 100644
--- a/MediaBrowser.Model/Providers/RemoteImageInfo.cs
+++ b/MediaBrowser.Model/Providers/RemoteImageInfo.cs
@@ -1,10 +1,11 @@
+#nullable disable
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Providers
{
/// <summary>
- /// Class RemoteImageInfo
+ /// Class RemoteImageInfo.
/// </summary>
public class RemoteImageInfo
{
@@ -21,7 +22,7 @@ namespace MediaBrowser.Model.Providers
public string Url { get; set; }
/// <summary>
- /// Gets a url used for previewing a smaller version
+ /// Gets or sets a url used for previewing a smaller version.
/// </summary>
public string ThumbnailUrl { get; set; }
@@ -67,5 +68,4 @@ namespace MediaBrowser.Model.Providers
/// <value>The type of the rating.</value>
public RatingType RatingType { get; set; }
}
-
}
diff --git a/MediaBrowser.Model/Providers/RemoteImageQuery.cs b/MediaBrowser.Model/Providers/RemoteImageQuery.cs
index 7c9216ce7..b7fad87ab 100644
--- a/MediaBrowser.Model/Providers/RemoteImageQuery.cs
+++ b/MediaBrowser.Model/Providers/RemoteImageQuery.cs
@@ -1,10 +1,17 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Providers
{
public class RemoteImageQuery
{
- public string ProviderName { get; set; }
+ public RemoteImageQuery(string providerName)
+ {
+ ProviderName = providerName;
+ }
+
+ public string ProviderName { get; }
public ImageType? ImageType { get; set; }
diff --git a/MediaBrowser.Model/Providers/RemoteImageResult.cs b/MediaBrowser.Model/Providers/RemoteImageResult.cs
index 5ca00f770..e6067ee6e 100644
--- a/MediaBrowser.Model/Providers/RemoteImageResult.cs
+++ b/MediaBrowser.Model/Providers/RemoteImageResult.cs
@@ -1,3 +1,4 @@
+#nullable disable
namespace MediaBrowser.Model.Providers
{
/// <summary>
diff --git a/MediaBrowser.Model/Providers/RemoteSearchResult.cs b/MediaBrowser.Model/Providers/RemoteSearchResult.cs
index 6e46b1556..a29e7ad1c 100644
--- a/MediaBrowser.Model/Providers/RemoteSearchResult.cs
+++ b/MediaBrowser.Model/Providers/RemoteSearchResult.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Entities;
@@ -6,23 +9,34 @@ namespace MediaBrowser.Model.Providers
{
public class RemoteSearchResult : IHasProviderIds
{
+ public RemoteSearchResult()
+ {
+ ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ Artists = Array.Empty<RemoteSearchResult>();
+ }
+
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
+
/// <summary>
/// Gets or sets the provider ids.
/// </summary>
/// <value>The provider ids.</value>
public Dictionary<string, string> ProviderIds { get; set; }
+
/// <summary>
/// Gets or sets the year.
/// </summary>
/// <value>The year.</value>
public int? ProductionYear { get; set; }
+
public int? IndexNumber { get; set; }
+
public int? IndexNumberEnd { get; set; }
+
public int? ParentIndexNumber { get; set; }
public DateTime? PremiereDate { get; set; }
@@ -30,15 +44,11 @@ namespace MediaBrowser.Model.Providers
public string ImageUrl { get; set; }
public string SearchProviderName { get; set; }
+
public string Overview { get; set; }
public RemoteSearchResult AlbumArtist { get; set; }
- public RemoteSearchResult[] Artists { get; set; }
- public RemoteSearchResult()
- {
- ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- Artists = new RemoteSearchResult[] { };
- }
+ public RemoteSearchResult[] Artists { get; set; }
}
}
diff --git a/MediaBrowser.Model/Providers/RemoteSubtitleInfo.cs b/MediaBrowser.Model/Providers/RemoteSubtitleInfo.cs
index 861aabf72..a8d88d8a1 100644
--- a/MediaBrowser.Model/Providers/RemoteSubtitleInfo.cs
+++ b/MediaBrowser.Model/Providers/RemoteSubtitleInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Providers
@@ -5,15 +8,25 @@ namespace MediaBrowser.Model.Providers
public class RemoteSubtitleInfo
{
public string ThreeLetterISOLanguageName { get; set; }
+
public string Id { get; set; }
+
public string ProviderName { get; set; }
+
public string Name { get; set; }
+
public string Format { get; set; }
+
public string Author { get; set; }
+
public string Comment { get; set; }
+
public DateTime? DateCreated { get; set; }
+
public float? CommunityRating { get; set; }
+
public int? DownloadCount { get; set; }
+
public bool? IsHashMatch { get; set; }
}
}
diff --git a/MediaBrowser.Model/Providers/SubtitleOptions.cs b/MediaBrowser.Model/Providers/SubtitleOptions.cs
index fde816dd3..6ea1e1486 100644
--- a/MediaBrowser.Model/Providers/SubtitleOptions.cs
+++ b/MediaBrowser.Model/Providers/SubtitleOptions.cs
@@ -1,27 +1,36 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Providers
{
public class SubtitleOptions
{
+ public SubtitleOptions()
+ {
+ DownloadLanguages = Array.Empty<string>();
+
+ SkipIfAudioTrackMatches = true;
+ RequirePerfectMatch = true;
+ }
+
public bool SkipIfEmbeddedSubtitlesPresent { get; set; }
+
public bool SkipIfAudioTrackMatches { get; set; }
+
public string[] DownloadLanguages { get; set; }
+
public bool DownloadMovieSubtitles { get; set; }
+
public bool DownloadEpisodeSubtitles { get; set; }
public string OpenSubtitlesUsername { get; set; }
+
public string OpenSubtitlesPasswordHash { get; set; }
+
public bool IsOpenSubtitleVipAccount { get; set; }
public bool RequirePerfectMatch { get; set; }
-
- public SubtitleOptions()
- {
- DownloadLanguages = Array.Empty<string>();
-
- SkipIfAudioTrackMatches = true;
- RequirePerfectMatch = true;
- }
}
}
diff --git a/MediaBrowser.Model/Providers/SubtitleProviderInfo.cs b/MediaBrowser.Model/Providers/SubtitleProviderInfo.cs
index 48a247818..7a7e7b9ec 100644
--- a/MediaBrowser.Model/Providers/SubtitleProviderInfo.cs
+++ b/MediaBrowser.Model/Providers/SubtitleProviderInfo.cs
@@ -1,8 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Providers
{
public class SubtitleProviderInfo
{
public string Name { get; set; }
+
public string Id { get; set; }
}
}
diff --git a/MediaBrowser.Model/Querying/AllThemeMediaResult.cs b/MediaBrowser.Model/Querying/AllThemeMediaResult.cs
index f843a33e6..6b503ba6b 100644
--- a/MediaBrowser.Model/Querying/AllThemeMediaResult.cs
+++ b/MediaBrowser.Model/Querying/AllThemeMediaResult.cs
@@ -1,13 +1,10 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Querying
{
public class AllThemeMediaResult
{
- public ThemeMediaResult ThemeVideosResult { get; set; }
-
- public ThemeMediaResult ThemeSongsResult { get; set; }
-
- public ThemeMediaResult SoundtrackSongsResult { get; set; }
-
public AllThemeMediaResult()
{
ThemeVideosResult = new ThemeMediaResult();
@@ -16,5 +13,11 @@ namespace MediaBrowser.Model.Querying
SoundtrackSongsResult = new ThemeMediaResult();
}
+
+ public ThemeMediaResult ThemeVideosResult { get; set; }
+
+ public ThemeMediaResult ThemeSongsResult { get; set; }
+
+ public ThemeMediaResult SoundtrackSongsResult { get; set; }
}
}
diff --git a/MediaBrowser.Model/Querying/EpisodeQuery.cs b/MediaBrowser.Model/Querying/EpisodeQuery.cs
deleted file mode 100644
index 0c8ea7ed4..000000000
--- a/MediaBrowser.Model/Querying/EpisodeQuery.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- public class EpisodeQuery
- {
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
- /// <summary>
- /// Gets or sets the season identifier.
- /// </summary>
- /// <value>The season identifier.</value>
- public string SeasonId { get; set; }
- /// <summary>
- /// Gets or sets the series identifier.
- /// </summary>
- /// <value>The series identifier.</value>
- public string SeriesId { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is missing.
- /// </summary>
- /// <value><c>null</c> if [is missing] contains no value, <c>true</c> if [is missing]; otherwise, <c>false</c>.</value>
- public bool? IsMissing { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is virtual unaired.
- /// </summary>
- /// <value><c>null</c> if [is virtual unaired] contains no value, <c>true</c> if [is virtual unaired]; otherwise, <c>false</c>.</value>
- public bool? IsVirtualUnaired { get; set; }
- /// <summary>
- /// Gets or sets the season number.
- /// </summary>
- /// <value>The season number.</value>
- public int? SeasonNumber { get; set; }
- /// <summary>
- /// Gets or sets the fields.
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- /// <summary>
- /// Gets or sets the start index.
- /// </summary>
- /// <value>The start index.</value>
- public int? StartIndex { get; set; }
- /// <summary>
- /// Gets or sets the limit.
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
- /// <summary>
- /// Gets or sets the start item identifier.
- /// </summary>
- /// <value>The start item identifier.</value>
- public string StartItemId { get; set; }
-
- public EpisodeQuery()
- {
- Fields = new ItemFields[] { };
- }
- }
-}
diff --git a/MediaBrowser.Model/Querying/ItemCountsQuery.cs b/MediaBrowser.Model/Querying/ItemCountsQuery.cs
deleted file mode 100644
index 02b809fa8..000000000
--- a/MediaBrowser.Model/Querying/ItemCountsQuery.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- /// <summary>
- /// Class ItemCountsQuery
- /// </summary>
- public class ItemCountsQuery
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is favorite.
- /// </summary>
- /// <value><c>null</c> if [is favorite] contains no value, <c>true</c> if [is favorite]; otherwise, <c>false</c>.</value>
- public bool? IsFavorite { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Querying/ItemFields.cs b/MediaBrowser.Model/Querying/ItemFields.cs
index af1aaf486..ef4698f3f 100644
--- a/MediaBrowser.Model/Querying/ItemFields.cs
+++ b/MediaBrowser.Model/Querying/ItemFields.cs
@@ -1,203 +1,206 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Querying
{
/// <summary>
- /// Used to control the data that gets attached to DtoBaseItems
+ /// Used to control the data that gets attached to DtoBaseItems.
/// </summary>
public enum ItemFields
{
/// <summary>
- /// The air time
+ /// The air time.
/// </summary>
AirTime,
/// <summary>
- /// The can delete
+ /// The can delete.
/// </summary>
CanDelete,
/// <summary>
- /// The can download
+ /// The can download.
/// </summary>
CanDownload,
/// <summary>
- /// The channel information
+ /// The channel information.
/// </summary>
ChannelInfo,
/// <summary>
- /// The chapters
+ /// The chapters.
/// </summary>
Chapters,
ChildCount,
/// <summary>
- /// The cumulative run time ticks
+ /// The cumulative run time ticks.
/// </summary>
CumulativeRunTimeTicks,
/// <summary>
- /// The custom rating
+ /// The custom rating.
/// </summary>
CustomRating,
/// <summary>
- /// The date created of the item
+ /// The date created of the item.
/// </summary>
DateCreated,
/// <summary>
- /// The date last media added
+ /// The date last media added.
/// </summary>
DateLastMediaAdded,
/// <summary>
- /// Item display preferences
+ /// Item display preferences.
/// </summary>
DisplayPreferencesId,
/// <summary>
- /// The etag
+ /// The etag.
/// </summary>
Etag,
/// <summary>
- /// The external urls
+ /// The external urls.
/// </summary>
ExternalUrls,
/// <summary>
- /// Genres
+ /// Genres.
/// </summary>
Genres,
/// <summary>
- /// The home page URL
+ /// The home page URL.
/// </summary>
HomePageUrl,
/// <summary>
- /// The item counts
+ /// The item counts.
/// </summary>
ItemCounts,
/// <summary>
- /// The media source count
+ /// The media source count.
/// </summary>
MediaSourceCount,
/// <summary>
- /// The media versions
+ /// The media versions.
/// </summary>
MediaSources,
OriginalTitle,
/// <summary>
- /// The item overview
+ /// The item overview.
/// </summary>
Overview,
/// <summary>
- /// The id of the item's parent
+ /// The id of the item's parent.
/// </summary>
ParentId,
/// <summary>
- /// The physical path of the item
+ /// The physical path of the item.
/// </summary>
Path,
/// <summary>
- /// The list of people for the item
+ /// The list of people for the item.
/// </summary>
People,
PlayAccess,
/// <summary>
- /// The production locations
+ /// The production locations.
/// </summary>
ProductionLocations,
/// <summary>
- /// Imdb, tmdb, etc
+ /// Imdb, tmdb, etc.
/// </summary>
ProviderIds,
/// <summary>
- /// The aspect ratio of the primary image
+ /// The aspect ratio of the primary image.
/// </summary>
PrimaryImageAspectRatio,
RecursiveItemCount,
/// <summary>
- /// The settings
+ /// The settings.
/// </summary>
Settings,
/// <summary>
- /// The screenshot image tags
+ /// The screenshot image tags.
/// </summary>
ScreenshotImageTags,
SeriesPrimaryImage,
/// <summary>
- /// The series studio
+ /// The series studio.
/// </summary>
SeriesStudio,
/// <summary>
- /// The sort name of the item
+ /// The sort name of the item.
/// </summary>
SortName,
/// <summary>
- /// The special episode numbers
+ /// The special episode numbers.
/// </summary>
SpecialEpisodeNumbers,
/// <summary>
- /// The studios of the item
+ /// The studios of the item.
/// </summary>
Studios,
BasicSyncInfo,
+
/// <summary>
- /// The synchronize information
+ /// The synchronize information.
/// </summary>
SyncInfo,
/// <summary>
- /// The taglines of the item
+ /// The taglines of the item.
/// </summary>
Taglines,
/// <summary>
- /// The tags
+ /// The tags.
/// </summary>
Tags,
/// <summary>
- /// The trailer url of the item
+ /// The trailer url of the item.
/// </summary>
RemoteTrailers,
/// <summary>
- /// The media streams
+ /// The media streams.
/// </summary>
MediaStreams,
/// <summary>
- /// The season user data
+ /// The season user data.
/// </summary>
SeasonUserData,
/// <summary>
- /// The service name
+ /// The service name.
/// </summary>
ServiceName,
ThemeSongIds,
diff --git a/MediaBrowser.Model/Querying/ItemFilter.cs b/MediaBrowser.Model/Querying/ItemFilter.cs
index b8dcfbdad..0ebb5185f 100644
--- a/MediaBrowser.Model/Querying/ItemFilter.cs
+++ b/MediaBrowser.Model/Querying/ItemFilter.cs
@@ -1,44 +1,52 @@
namespace MediaBrowser.Model.Querying
{
/// <summary>
- /// Enum ItemFilter
+ /// Enum ItemFilter.
/// </summary>
public enum ItemFilter
{
/// <summary>
- /// The item is a folder
+ /// The item is a folder.
/// </summary>
IsFolder = 1,
+
/// <summary>
- /// The item is not folder
+ /// The item is not folder.
/// </summary>
IsNotFolder = 2,
+
/// <summary>
- /// The item is unplayed
+ /// The item is unplayed.
/// </summary>
IsUnplayed = 3,
+
/// <summary>
- /// The item is played
+ /// The item is played.
/// </summary>
IsPlayed = 4,
+
/// <summary>
- /// The item is a favorite
+ /// The item is a favorite.
/// </summary>
IsFavorite = 5,
+
/// <summary>
- /// The item is resumable
+ /// The item is resumable.
/// </summary>
IsResumable = 7,
+
/// <summary>
- /// The likes
+ /// The likes.
/// </summary>
Likes = 8,
+
/// <summary>
- /// The dislikes
+ /// The dislikes.
/// </summary>
Dislikes = 9,
+
/// <summary>
- /// The is favorite or likes
+ /// The is favorite or likes.
/// </summary>
IsFavoriteOrLikes = 10
}
diff --git a/MediaBrowser.Model/Querying/ItemSortBy.cs b/MediaBrowser.Model/Querying/ItemSortBy.cs
index 6a71e3bb3..0b846bb96 100644
--- a/MediaBrowser.Model/Querying/ItemSortBy.cs
+++ b/MediaBrowser.Model/Querying/ItemSortBy.cs
@@ -1,78 +1,106 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Querying
{
/// <summary>
- /// These represent sort orders that are known by the core
+ /// These represent sort orders that are known by the core.
/// </summary>
public static class ItemSortBy
{
public const string AiredEpisodeOrder = "AiredEpisodeOrder";
+
/// <summary>
- /// The album
+ /// The album.
/// </summary>
public const string Album = "Album";
+
/// <summary>
- /// The album artist
+ /// The album artist.
/// </summary>
public const string AlbumArtist = "AlbumArtist";
+
/// <summary>
- /// The artist
+ /// The artist.
/// </summary>
public const string Artist = "Artist";
+
/// <summary>
- /// The date created
+ /// The date created.
/// </summary>
public const string DateCreated = "DateCreated";
+
/// <summary>
- /// The official rating
+ /// The official rating.
/// </summary>
public const string OfficialRating = "OfficialRating";
+
/// <summary>
- /// The date played
+ /// The date played.
/// </summary>
public const string DatePlayed = "DatePlayed";
+
/// <summary>
- /// The premiere date
+ /// The premiere date.
/// </summary>
public const string PremiereDate = "PremiereDate";
+
public const string StartDate = "StartDate";
+
/// <summary>
- /// The sort name
+ /// The sort name.
/// </summary>
public const string SortName = "SortName";
+
public const string Name = "Name";
+
/// <summary>
- /// The random
+ /// The random.
/// </summary>
public const string Random = "Random";
+
/// <summary>
- /// The runtime
+ /// The runtime.
/// </summary>
public const string Runtime = "Runtime";
+
/// <summary>
- /// The community rating
+ /// The community rating.
/// </summary>
public const string CommunityRating = "CommunityRating";
+
/// <summary>
- /// The production year
+ /// The production year.
/// </summary>
public const string ProductionYear = "ProductionYear";
+
/// <summary>
- /// The play count
+ /// The play count.
/// </summary>
public const string PlayCount = "PlayCount";
+
/// <summary>
- /// The critic rating
+ /// The critic rating.
/// </summary>
public const string CriticRating = "CriticRating";
+
public const string IsFolder = "IsFolder";
+
public const string IsUnplayed = "IsUnplayed";
+
public const string IsPlayed = "IsPlayed";
+
public const string SeriesSortName = "SeriesSortName";
+
public const string VideoBitRate = "VideoBitRate";
+
public const string AirTime = "AirTime";
+
public const string Studio = "Studio";
+
public const string IsFavoriteOrLiked = "IsFavoriteOrLiked";
+
public const string DateLastContentAdded = "DateLastContentAdded";
+
public const string SeriesDatePlayed = "SeriesDatePlayed";
}
}
diff --git a/MediaBrowser.Model/Querying/LatestItemsQuery.cs b/MediaBrowser.Model/Querying/LatestItemsQuery.cs
index 4a5818ac5..f555ffb36 100644
--- a/MediaBrowser.Model/Querying/LatestItemsQuery.cs
+++ b/MediaBrowser.Model/Querying/LatestItemsQuery.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
@@ -5,32 +8,38 @@ namespace MediaBrowser.Model.Querying
{
public class LatestItemsQuery
{
+ public LatestItemsQuery()
+ {
+ EnableImageTypes = Array.Empty<ImageType>();
+ }
+
/// <summary>
- /// The user to localize search results for
+ /// Gets or sets the user to localize search results for.
/// </summary>
/// <value>The user id.</value>
public Guid UserId { get; set; }
/// <summary>
+ /// Gets or sets the parent id.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
/// </summary>
/// <value>The parent id.</value>
public Guid ParentId { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Used for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
/// <summary>
- /// Fields to return within the items, in addition to basic information
+ /// Gets or sets the fields to return within the items, in addition to basic information.
/// </summary>
/// <value>The fields.</value>
public ItemFields[] Fields { get; set; }
@@ -52,25 +61,23 @@ namespace MediaBrowser.Model.Querying
/// </summary>
/// <value><c>true</c> if [group items]; otherwise, <c>false</c>.</value>
public bool GroupItems { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [enable images].
/// </summary>
/// <value><c>null</c> if [enable images] contains no value, <c>true</c> if [enable images]; otherwise, <c>false</c>.</value>
public bool? EnableImages { get; set; }
+
/// <summary>
/// Gets or sets the image type limit.
/// </summary>
/// <value>The image type limit.</value>
public int? ImageTypeLimit { get; set; }
+
/// <summary>
/// Gets or sets the enable image types.
/// </summary>
/// <value>The enable image types.</value>
public ImageType[] EnableImageTypes { get; set; }
-
- public LatestItemsQuery()
- {
- EnableImageTypes = new ImageType[] { };
- }
}
}
diff --git a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs b/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs
deleted file mode 100644
index 52c138355..000000000
--- a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- public class MovieRecommendationQuery
- {
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
- /// <summary>
- /// Gets or sets the parent identifier.
- /// </summary>
- /// <value>The parent identifier.</value>
- public string ParentId { get; set; }
- /// <summary>
- /// Gets or sets the item limit.
- /// </summary>
- /// <value>The item limit.</value>
- public int ItemLimit { get; set; }
- /// <summary>
- /// Gets or sets the category limit.
- /// </summary>
- /// <value>The category limit.</value>
- public int CategoryLimit { get; set; }
- /// <summary>
- /// Gets or sets the fields.
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
-
- public MovieRecommendationQuery()
- {
- ItemLimit = 10;
- CategoryLimit = 6;
- Fields = new ItemFields[] { };
- }
- }
-}
diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs
index ff146cede..fa8aa829d 100644
--- a/MediaBrowser.Model/Querying/NextUpQuery.cs
+++ b/MediaBrowser.Model/Querying/NextUpQuery.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Entities;
@@ -5,6 +8,14 @@ namespace MediaBrowser.Model.Querying
{
public class NextUpQuery
{
+ public NextUpQuery()
+ {
+ EnableImageTypes = Array.Empty<ImageType>();
+ EnableTotalRecordCount = true;
+ DisableFirstEpisode = false;
+ NextUpDateCutoff = DateTime.MinValue;
+ }
+
/// <summary>
/// Gets or sets the user id.
/// </summary>
@@ -15,7 +26,7 @@ namespace MediaBrowser.Model.Querying
/// Gets or sets the parent identifier.
/// </summary>
/// <value>The parent identifier.</value>
- public string ParentId { get; set; }
+ public Guid? ParentId { get; set; }
/// <summary>
/// Gets or sets the series id.
@@ -24,32 +35,35 @@ namespace MediaBrowser.Model.Querying
public string SeriesId { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Use for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
/// <summary>
- /// Fields to return within the items, in addition to basic information
+ /// gets or sets the fields to return within the items, in addition to basic information.
/// </summary>
/// <value>The fields.</value>
public ItemFields[] Fields { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [enable images].
/// </summary>
/// <value><c>null</c> if [enable images] contains no value, <c>true</c> if [enable images]; otherwise, <c>false</c>.</value>
public bool? EnableImages { get; set; }
+
/// <summary>
/// Gets or sets the image type limit.
/// </summary>
/// <value>The image type limit.</value>
public int? ImageTypeLimit { get; set; }
+
/// <summary>
/// Gets or sets the enable image types.
/// </summary>
@@ -58,10 +72,14 @@ namespace MediaBrowser.Model.Querying
public bool EnableTotalRecordCount { get; set; }
- public NextUpQuery()
- {
- EnableImageTypes = new ImageType[] { };
- EnableTotalRecordCount = true;
- }
+ /// <summary>
+ /// Gets or sets a value indicating whether do disable sending first episode as next up.
+ /// </summary>
+ public bool DisableFirstEpisode { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating the oldest date for a show to appear in Next Up.
+ /// </summary>
+ public DateTime NextUpDateCutoff { get; set; }
}
}
diff --git a/MediaBrowser.Model/Querying/QueryFilters.cs b/MediaBrowser.Model/Querying/QueryFilters.cs
index 2f38299db..73b27a7b0 100644
--- a/MediaBrowser.Model/Querying/QueryFilters.cs
+++ b/MediaBrowser.Model/Querying/QueryFilters.cs
@@ -1,32 +1,21 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.Querying
{
- public class QueryFiltersLegacy
- {
- public string[] Genres { get; set; }
- public string[] Tags { get; set; }
- public string[] OfficialRatings { get; set; }
- public int[] Years { get; set; }
-
- public QueryFiltersLegacy()
- {
- Genres = Array.Empty<string>();
- Tags = Array.Empty<string>();
- OfficialRatings = Array.Empty<string>();
- Years = Array.Empty<int>();
- }
- }
public class QueryFilters
{
- public NameGuidPair[] Genres { get; set; }
- public string[] Tags { get; set; }
-
public QueryFilters()
{
Tags = Array.Empty<string>();
Genres = Array.Empty<NameGuidPair>();
}
+
+ public NameGuidPair[] Genres { get; set; }
+
+ public string[] Tags { get; set; }
}
}
diff --git a/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs b/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs
new file mode 100644
index 000000000..fcb450ed3
--- /dev/null
+++ b/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs
@@ -0,0 +1,26 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Model.Querying
+{
+ public class QueryFiltersLegacy
+ {
+ public QueryFiltersLegacy()
+ {
+ Genres = Array.Empty<string>();
+ Tags = Array.Empty<string>();
+ OfficialRatings = Array.Empty<string>();
+ Years = Array.Empty<int>();
+ }
+
+ public string[] Genres { get; set; }
+
+ public string[] Tags { get; set; }
+
+ public string[] OfficialRatings { get; set; }
+
+ public int[] Years { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Querying/QueryResult.cs b/MediaBrowser.Model/Querying/QueryResult.cs
index e81f2b868..8ce794800 100644
--- a/MediaBrowser.Model/Querying/QueryResult.cs
+++ b/MediaBrowser.Model/Querying/QueryResult.cs
@@ -1,22 +1,40 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+
namespace MediaBrowser.Model.Querying
{
public class QueryResult<T>
{
+ public QueryResult()
+ {
+ Items = Array.Empty<T>();
+ }
+
+ public QueryResult(IReadOnlyList<T> items)
+ {
+ Items = items;
+ TotalRecordCount = items.Count;
+ }
+
/// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>The items.</value>
- public T[] Items { get; set; }
+ public IReadOnlyList<T> Items { get; set; }
/// <summary>
- /// The total number of records available
+ /// Gets or sets the total number of records available.
/// </summary>
/// <value>The total record count.</value>
public int TotalRecordCount { get; set; }
- public QueryResult()
- {
- Items = new T[] { };
- }
+ /// <summary>
+ /// Gets or sets the index of the first record in Items.
+ /// </summary>
+ /// <value>First record index.</value>
+ public int StartIndex { get; set; }
}
}
diff --git a/MediaBrowser.Model/Querying/SessionQuery.cs b/MediaBrowser.Model/Querying/SessionQuery.cs
deleted file mode 100644
index 1fac9d639..000000000
--- a/MediaBrowser.Model/Querying/SessionQuery.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- /// <summary>
- /// Class SessionQuery
- /// </summary>
- public class SessionQuery
- {
- /// <summary>
- /// Filter by sessions that are allowed to be controlled by a given user
- /// </summary>
- public string ControllableByUserId { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Querying/SimilarItemsQuery.cs b/MediaBrowser.Model/Querying/SimilarItemsQuery.cs
deleted file mode 100644
index 68f761bd4..000000000
--- a/MediaBrowser.Model/Querying/SimilarItemsQuery.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- public class SimilarItemsQuery
- {
- /// <summary>
- /// The user to localize search results for
- /// </summary>
- /// <value>The user id.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public string Id { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Querying/ThemeMediaResult.cs b/MediaBrowser.Model/Querying/ThemeMediaResult.cs
index bae954d78..5afedeeaf 100644
--- a/MediaBrowser.Model/Querying/ThemeMediaResult.cs
+++ b/MediaBrowser.Model/Querying/ThemeMediaResult.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.Querying
{
/// <summary>
- /// Class ThemeMediaResult
+ /// Class ThemeMediaResult.
/// </summary>
public class ThemeMediaResult : QueryResult<BaseItemDto>
{
diff --git a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs
deleted file mode 100644
index 5eac2860d..000000000
--- a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Model.Querying
-{
- public class UpcomingEpisodesQuery
- {
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the parent identifier.
- /// </summary>
- /// <value>The parent identifier.</value>
- public string ParentId { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether [enable images].
- /// </summary>
- /// <value><c>null</c> if [enable images] contains no value, <c>true</c> if [enable images]; otherwise, <c>false</c>.</value>
- public bool? EnableImages { get; set; }
- /// <summary>
- /// Gets or sets the image type limit.
- /// </summary>
- /// <value>The image type limit.</value>
- public int? ImageTypeLimit { get; set; }
- /// <summary>
- /// Gets or sets the enable image types.
- /// </summary>
- /// <value>The enable image types.</value>
- public ImageType[] EnableImageTypes { get; set; }
-
- public UpcomingEpisodesQuery()
- {
- EnableImageTypes = new ImageType[] { };
- }
- }
-}
diff --git a/MediaBrowser.Model/Querying/UserQuery.cs b/MediaBrowser.Model/Querying/UserQuery.cs
deleted file mode 100644
index 55cef664e..000000000
--- a/MediaBrowser.Model/Querying/UserQuery.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace MediaBrowser.Model.Querying
-{
- public class UserQuery
- {
- public bool? IsHidden { get; set; }
- public bool? IsDisabled { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/QuickConnect/QuickConnectResult.cs b/MediaBrowser.Model/QuickConnect/QuickConnectResult.cs
new file mode 100644
index 000000000..35a82f47c
--- /dev/null
+++ b/MediaBrowser.Model/QuickConnect/QuickConnectResult.cs
@@ -0,0 +1,78 @@
+using System;
+
+namespace MediaBrowser.Model.QuickConnect
+{
+ /// <summary>
+ /// Stores the state of an quick connect request.
+ /// </summary>
+ public class QuickConnectResult
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QuickConnectResult"/> class.
+ /// </summary>
+ /// <param name="secret">The secret used to query the request state.</param>
+ /// <param name="code">The code used to allow the request.</param>
+ /// <param name="dateAdded">The time when the request was created.</param>
+ /// <param name="deviceId">The requesting device id.</param>
+ /// <param name="deviceName">The requesting device name.</param>
+ /// <param name="appName">The requesting app name.</param>
+ /// <param name="appVersion">The requesting app version.</param>
+ public QuickConnectResult(
+ string secret,
+ string code,
+ DateTime dateAdded,
+ string deviceId,
+ string deviceName,
+ string appName,
+ string appVersion)
+ {
+ Secret = secret;
+ Code = code;
+ DateAdded = dateAdded;
+ DeviceId = deviceId;
+ DeviceName = deviceName;
+ AppName = appName;
+ AppVersion = appVersion;
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this request is authorized.
+ /// </summary>
+ public bool Authenticated { get; set; }
+
+ /// <summary>
+ /// Gets the secret value used to uniquely identify this request. Can be used to retrieve authentication information.
+ /// </summary>
+ public string Secret { get; }
+
+ /// <summary>
+ /// Gets the user facing code used so the user can quickly differentiate this request from others.
+ /// </summary>
+ public string Code { get; }
+
+ /// <summary>
+ /// Gets the requesting device id.
+ /// </summary>
+ public string DeviceId { get; }
+
+ /// <summary>
+ /// Gets the requesting device name.
+ /// </summary>
+ public string DeviceName { get; }
+
+ /// <summary>
+ /// Gets the requesting app name.
+ /// </summary>
+ public string AppName { get; }
+
+ /// <summary>
+ /// Gets the requesting app version.
+ /// </summary>
+ public string AppVersion { get; }
+
+ /// <summary>
+ /// Gets or sets the DateTime that this request was created.
+ /// </summary>
+ public DateTime DateAdded { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Reflection/IAssemblyInfo.cs b/MediaBrowser.Model/Reflection/IAssemblyInfo.cs
deleted file mode 100644
index 5c4536c1c..000000000
--- a/MediaBrowser.Model/Reflection/IAssemblyInfo.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-
-namespace MediaBrowser.Model.Reflection
-{
- public interface IAssemblyInfo
- {
- Stream GetManifestResourceStream(Type type, string resource);
- string[] GetManifestResourceNames(Type type);
-
- Assembly[] GetCurrentAssemblies();
- }
-}
diff --git a/MediaBrowser.Model/Search/SearchHint.cs b/MediaBrowser.Model/Search/SearchHint.cs
index 8a187f18e..983dbd2bc 100644
--- a/MediaBrowser.Model/Search/SearchHint.cs
+++ b/MediaBrowser.Model/Search/SearchHint.cs
@@ -1,9 +1,13 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Model.Search
{
/// <summary>
- /// Class SearchHintResult
+ /// Class SearchHintResult.
/// </summary>
public class SearchHint
{
@@ -96,6 +100,7 @@ namespace MediaBrowser.Model.Search
public string MediaType { get; set; }
public DateTime? StartDate { get; set; }
+
public DateTime? EndDate { get; set; }
/// <summary>
@@ -111,6 +116,7 @@ namespace MediaBrowser.Model.Search
/// </summary>
/// <value>The album.</value>
public string Album { get; set; }
+
public Guid AlbumId { get; set; }
/// <summary>
@@ -123,7 +129,7 @@ namespace MediaBrowser.Model.Search
/// Gets or sets the artists.
/// </summary>
/// <value>The artists.</value>
- public string[] Artists { get; set; }
+ public IReadOnlyList<string> Artists { get; set; }
/// <summary>
/// Gets or sets the song count.
diff --git a/MediaBrowser.Model/Search/SearchHintResult.cs b/MediaBrowser.Model/Search/SearchHintResult.cs
index 069e7e025..92ba4139e 100644
--- a/MediaBrowser.Model/Search/SearchHintResult.cs
+++ b/MediaBrowser.Model/Search/SearchHintResult.cs
@@ -1,7 +1,8 @@
+#nullable disable
namespace MediaBrowser.Model.Search
{
/// <summary>
- /// Class SearchHintResult
+ /// Class SearchHintResult.
/// </summary>
public class SearchHintResult
{
diff --git a/MediaBrowser.Model/Search/SearchQuery.cs b/MediaBrowser.Model/Search/SearchQuery.cs
index 96a8cb00c..aedfa4d36 100644
--- a/MediaBrowser.Model/Search/SearchQuery.cs
+++ b/MediaBrowser.Model/Search/SearchQuery.cs
@@ -1,11 +1,27 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Search
{
public class SearchQuery
{
+ public SearchQuery()
+ {
+ IncludeArtists = true;
+ IncludeGenres = true;
+ IncludeMedia = true;
+ IncludePeople = true;
+ IncludeStudios = true;
+
+ MediaTypes = Array.Empty<string>();
+ IncludeItemTypes = Array.Empty<string>();
+ ExcludeItemTypes = Array.Empty<string>();
+ }
+
/// <summary>
- /// The user to localize search results for
+ /// Gets or sets the user to localize search results for.
/// </summary>
/// <value>The user id.</value>
public Guid UserId { get; set; }
@@ -17,27 +33,34 @@ namespace MediaBrowser.Model.Search
public string SearchTerm { get; set; }
/// <summary>
- /// Skips over a given number of items within the results. Use for paging.
+ /// Gets or sets the start index. Used for paging.
/// </summary>
/// <value>The start index.</value>
public int? StartIndex { get; set; }
/// <summary>
- /// The maximum number of items to return
+ /// Gets or sets the maximum number of items to return.
/// </summary>
/// <value>The limit.</value>
public int? Limit { get; set; }
public bool IncludePeople { get; set; }
+
public bool IncludeMedia { get; set; }
+
public bool IncludeGenres { get; set; }
+
public bool IncludeStudios { get; set; }
+
public bool IncludeArtists { get; set; }
public string[] MediaTypes { get; set; }
+
public string[] IncludeItemTypes { get; set; }
+
public string[] ExcludeItemTypes { get; set; }
- public string ParentId { get; set; }
+
+ public Guid? ParentId { get; set; }
public bool? IsMovie { get; set; }
@@ -48,18 +71,5 @@ namespace MediaBrowser.Model.Search
public bool? IsKids { get; set; }
public bool? IsSports { get; set; }
-
- public SearchQuery()
- {
- IncludeArtists = true;
- IncludeGenres = true;
- IncludeMedia = true;
- IncludePeople = true;
- IncludeStudios = true;
-
- MediaTypes = Array.Empty<string>();
- IncludeItemTypes = Array.Empty<string>();
- ExcludeItemTypes = Array.Empty<string>();
- }
}
}
diff --git a/MediaBrowser.Model/Serialization/IJsonSerializer.cs b/MediaBrowser.Model/Serialization/IJsonSerializer.cs
deleted file mode 100644
index 18f51f652..000000000
--- a/MediaBrowser.Model/Serialization/IJsonSerializer.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.Serialization
-{
- public interface IJsonSerializer
- {
- /// <summary>
- /// Serializes to stream.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="stream">The stream.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- void SerializeToStream(object obj, Stream stream);
-
- /// <summary>
- /// Serializes to stream.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="stream">The stream.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- void SerializeToStream<T>(T obj, Stream stream);
-
- /// <summary>
- /// Serializes to file.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <param name="file">The file.</param>
- /// <exception cref="ArgumentNullException">obj</exception>
- void SerializeToFile(object obj, string file);
-
- /// <summary>
- /// Deserializes from file.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <param name="file">The file.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">type</exception>
- object DeserializeFromFile(Type type, string file);
-
- /// <summary>
- /// Deserializes from file.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="file">The file.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">file</exception>
- T DeserializeFromFile<T>(string file)
- where T : class;
-
- /// <summary>
- /// Deserializes from stream.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="stream">The stream.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">stream</exception>
- T DeserializeFromStream<T>(Stream stream);
-
- /// <summary>
- /// Deserializes from string.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="text">The text.</param>
- /// <returns>``0.</returns>
- /// <exception cref="ArgumentNullException">text</exception>
- T DeserializeFromString<T>(string text);
-
- /// <summary>
- /// Deserializes from stream.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">stream</exception>
- object DeserializeFromStream(Stream stream, Type type);
-
- /// <summary>
- /// Deserializes from string.
- /// </summary>
- /// <param name="json">The json.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- /// <exception cref="ArgumentNullException">json</exception>
- object DeserializeFromString(string json, Type type);
-
- /// <summary>
- /// Serializes to string.
- /// </summary>
- /// <param name="obj">The obj.</param>
- /// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">obj</exception>
- string SerializeToString(object obj);
-
- Task<object> DeserializeFromStreamAsync(Stream stream, Type type);
- Task<T> DeserializeFromStreamAsync<T>(Stream stream);
- }
-}
diff --git a/MediaBrowser.Model/Serialization/IXmlSerializer.cs b/MediaBrowser.Model/Serialization/IXmlSerializer.cs
index 902ebd4d1..16d126ac7 100644
--- a/MediaBrowser.Model/Serialization/IXmlSerializer.cs
+++ b/MediaBrowser.Model/Serialization/IXmlSerializer.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.IO;
diff --git a/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs b/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs
deleted file mode 100644
index b43949fe3..000000000
--- a/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Serialization
-{
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
- public sealed class IgnoreDataMemberAttribute : Attribute
- {
- public IgnoreDataMemberAttribute()
- {
- }
- }
-}
diff --git a/MediaBrowser.Model/Services/ApiMemberAttribute.cs b/MediaBrowser.Model/Services/ApiMemberAttribute.cs
deleted file mode 100644
index 8b155c8ab..000000000
--- a/MediaBrowser.Model/Services/ApiMemberAttribute.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Services
-{
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
- public class ApiMemberAttribute : Attribute
- {
- /// <summary>
- /// Gets or sets verb to which applies attribute. By default applies to all verbs.
- /// </summary>
- public string Verb { get; set; }
-
- /// <summary>
- /// Gets or sets parameter type: It can be only one of the following: path, query, body, form, or header.
- /// </summary>
- public string ParameterType { get; set; }
-
- /// <summary>
- /// Gets or sets unique name for the parameter. Each name must be unique, even if they are associated with different paramType values.
- /// </summary>
- /// <remarks>
- /// <para>
- /// Other notes on the name field:
- /// If paramType is body, the name is used only for UI and codegeneration.
- /// If paramType is path, the name field must correspond to the associated path segment from the path field in the api object.
- /// If paramType is query, the name field corresponds to the query param name.
- /// </para>
- /// </remarks>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the human-readable description for the parameter.
- /// </summary>
- public string Description { get; set; }
-
- /// <summary>
- /// For path, query, and header paramTypes, this field must be a primitive. For body, this can be a complex or container datatype.
- /// </summary>
- public string DataType { get; set; }
-
- /// <summary>
- /// For path, this is always true. Otherwise, this field tells the client whether or not the field must be supplied.
- /// </summary>
- public bool IsRequired { get; set; }
-
- /// <summary>
- /// For query params, this specifies that a comma-separated list of values can be passed to the API. For path and body types, this field cannot be true.
- /// </summary>
- public bool AllowMultiple { get; set; }
-
- /// <summary>
- /// Gets or sets route to which applies attribute, matches using StartsWith. By default applies to all routes.
- /// </summary>
- public string Route { get; set; }
-
- /// <summary>
- /// Whether to exclude this property from being included in the ModelSchema
- /// </summary>
- public bool ExcludeInSchema { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Services/HttpUtility.cs b/MediaBrowser.Model/Services/HttpUtility.cs
deleted file mode 100644
index be180334c..000000000
--- a/MediaBrowser.Model/Services/HttpUtility.cs
+++ /dev/null
@@ -1,691 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Text;
-
-namespace MediaBrowser.Model.Services
-{
- public static class MyHttpUtility
- {
- // Must be sorted
- static readonly long[] entities = new long[] {
- (long)'A' << 56 | (long)'E' << 48 | (long)'l' << 40 | (long)'i' << 32 | (long)'g' << 24,
- (long)'A' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'A' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'A' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'A' << 56 | (long)'l' << 48 | (long)'p' << 40 | (long)'h' << 32 | (long)'a' << 24,
- (long)'A' << 56 | (long)'r' << 48 | (long)'i' << 40 | (long)'n' << 32 | (long)'g' << 24,
- (long)'A' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'A' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'B' << 56 | (long)'e' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'C' << 56 | (long)'c' << 48 | (long)'e' << 40 | (long)'d' << 32 | (long)'i' << 24 | (long)'l' << 16,
- (long)'C' << 56 | (long)'h' << 48 | (long)'i' << 40,
- (long)'D' << 56 | (long)'a' << 48 | (long)'g' << 40 | (long)'g' << 32 | (long)'e' << 24 | (long)'r' << 16,
- (long)'D' << 56 | (long)'e' << 48 | (long)'l' << 40 | (long)'t' << 32 | (long)'a' << 24,
- (long)'E' << 56 | (long)'T' << 48 | (long)'H' << 40,
- (long)'E' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'E' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'E' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'E' << 56 | (long)'p' << 48 | (long)'s' << 40 | (long)'i' << 32 | (long)'l' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'E' << 56 | (long)'t' << 48 | (long)'a' << 40,
- (long)'E' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'G' << 56 | (long)'a' << 48 | (long)'m' << 40 | (long)'m' << 32 | (long)'a' << 24,
- (long)'I' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'I' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'I' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'I' << 56 | (long)'o' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'I' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'K' << 56 | (long)'a' << 48 | (long)'p' << 40 | (long)'p' << 32 | (long)'a' << 24,
- (long)'L' << 56 | (long)'a' << 48 | (long)'m' << 40 | (long)'b' << 32 | (long)'d' << 24 | (long)'a' << 16,
- (long)'M' << 56 | (long)'u' << 48,
- (long)'N' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'N' << 56 | (long)'u' << 48,
- (long)'O' << 56 | (long)'E' << 48 | (long)'l' << 40 | (long)'i' << 32 | (long)'g' << 24,
- (long)'O' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'O' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'O' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'O' << 56 | (long)'m' << 48 | (long)'e' << 40 | (long)'g' << 32 | (long)'a' << 24,
- (long)'O' << 56 | (long)'m' << 48 | (long)'i' << 40 | (long)'c' << 32 | (long)'r' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'O' << 56 | (long)'s' << 48 | (long)'l' << 40 | (long)'a' << 32 | (long)'s' << 24 | (long)'h' << 16,
- (long)'O' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'O' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'P' << 56 | (long)'h' << 48 | (long)'i' << 40,
- (long)'P' << 56 | (long)'i' << 48,
- (long)'P' << 56 | (long)'r' << 48 | (long)'i' << 40 | (long)'m' << 32 | (long)'e' << 24,
- (long)'P' << 56 | (long)'s' << 48 | (long)'i' << 40,
- (long)'R' << 56 | (long)'h' << 48 | (long)'o' << 40,
- (long)'S' << 56 | (long)'c' << 48 | (long)'a' << 40 | (long)'r' << 32 | (long)'o' << 24 | (long)'n' << 16,
- (long)'S' << 56 | (long)'i' << 48 | (long)'g' << 40 | (long)'m' << 32 | (long)'a' << 24,
- (long)'T' << 56 | (long)'H' << 48 | (long)'O' << 40 | (long)'R' << 32 | (long)'N' << 24,
- (long)'T' << 56 | (long)'a' << 48 | (long)'u' << 40,
- (long)'T' << 56 | (long)'h' << 48 | (long)'e' << 40 | (long)'t' << 32 | (long)'a' << 24,
- (long)'U' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'U' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'U' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'U' << 56 | (long)'p' << 48 | (long)'s' << 40 | (long)'i' << 32 | (long)'l' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'U' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'X' << 56 | (long)'i' << 48,
- (long)'Y' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'Y' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'Z' << 56 | (long)'e' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'a' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'a' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'a' << 56 | (long)'c' << 48 | (long)'u' << 40 | (long)'t' << 32 | (long)'e' << 24,
- (long)'a' << 56 | (long)'e' << 48 | (long)'l' << 40 | (long)'i' << 32 | (long)'g' << 24,
- (long)'a' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'a' << 56 | (long)'l' << 48 | (long)'e' << 40 | (long)'f' << 32 | (long)'s' << 24 | (long)'y' << 16 | (long)'m' << 8,
- (long)'a' << 56 | (long)'l' << 48 | (long)'p' << 40 | (long)'h' << 32 | (long)'a' << 24,
- (long)'a' << 56 | (long)'m' << 48 | (long)'p' << 40,
- (long)'a' << 56 | (long)'n' << 48 | (long)'d' << 40,
- (long)'a' << 56 | (long)'n' << 48 | (long)'g' << 40,
- (long)'a' << 56 | (long)'p' << 48 | (long)'o' << 40 | (long)'s' << 32,
- (long)'a' << 56 | (long)'r' << 48 | (long)'i' << 40 | (long)'n' << 32 | (long)'g' << 24,
- (long)'a' << 56 | (long)'s' << 48 | (long)'y' << 40 | (long)'m' << 32 | (long)'p' << 24,
- (long)'a' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'a' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'b' << 56 | (long)'d' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'b' << 56 | (long)'e' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'b' << 56 | (long)'r' << 48 | (long)'v' << 40 | (long)'b' << 32 | (long)'a' << 24 | (long)'r' << 16,
- (long)'b' << 56 | (long)'u' << 48 | (long)'l' << 40 | (long)'l' << 32,
- (long)'c' << 56 | (long)'a' << 48 | (long)'p' << 40,
- (long)'c' << 56 | (long)'c' << 48 | (long)'e' << 40 | (long)'d' << 32 | (long)'i' << 24 | (long)'l' << 16,
- (long)'c' << 56 | (long)'e' << 48 | (long)'d' << 40 | (long)'i' << 32 | (long)'l' << 24,
- (long)'c' << 56 | (long)'e' << 48 | (long)'n' << 40 | (long)'t' << 32,
- (long)'c' << 56 | (long)'h' << 48 | (long)'i' << 40,
- (long)'c' << 56 | (long)'i' << 48 | (long)'r' << 40 | (long)'c' << 32,
- (long)'c' << 56 | (long)'l' << 48 | (long)'u' << 40 | (long)'b' << 32 | (long)'s' << 24,
- (long)'c' << 56 | (long)'o' << 48 | (long)'n' << 40 | (long)'g' << 32,
- (long)'c' << 56 | (long)'o' << 48 | (long)'p' << 40 | (long)'y' << 32,
- (long)'c' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'r' << 32 | (long)'r' << 24,
- (long)'c' << 56 | (long)'u' << 48 | (long)'p' << 40,
- (long)'c' << 56 | (long)'u' << 48 | (long)'r' << 40 | (long)'r' << 32 | (long)'e' << 24 | (long)'n' << 16,
- (long)'d' << 56 | (long)'A' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'d' << 56 | (long)'a' << 48 | (long)'g' << 40 | (long)'g' << 32 | (long)'e' << 24 | (long)'r' << 16,
- (long)'d' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'d' << 56 | (long)'e' << 48 | (long)'g' << 40,
- (long)'d' << 56 | (long)'e' << 48 | (long)'l' << 40 | (long)'t' << 32 | (long)'a' << 24,
- (long)'d' << 56 | (long)'i' << 48 | (long)'a' << 40 | (long)'m' << 32 | (long)'s' << 24,
- (long)'d' << 56 | (long)'i' << 48 | (long)'v' << 40 | (long)'i' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'e' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'e' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'e' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'e' << 56 | (long)'m' << 48 | (long)'p' << 40 | (long)'t' << 32 | (long)'y' << 24,
- (long)'e' << 56 | (long)'m' << 48 | (long)'s' << 40 | (long)'p' << 32,
- (long)'e' << 56 | (long)'n' << 48 | (long)'s' << 40 | (long)'p' << 32,
- (long)'e' << 56 | (long)'p' << 48 | (long)'s' << 40 | (long)'i' << 32 | (long)'l' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'e' << 56 | (long)'q' << 48 | (long)'u' << 40 | (long)'i' << 32 | (long)'v' << 24,
- (long)'e' << 56 | (long)'t' << 48 | (long)'a' << 40,
- (long)'e' << 56 | (long)'t' << 48 | (long)'h' << 40,
- (long)'e' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'e' << 56 | (long)'u' << 48 | (long)'r' << 40 | (long)'o' << 32,
- (long)'e' << 56 | (long)'x' << 48 | (long)'i' << 40 | (long)'s' << 32 | (long)'t' << 24,
- (long)'f' << 56 | (long)'n' << 48 | (long)'o' << 40 | (long)'f' << 32,
- (long)'f' << 56 | (long)'o' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'l' << 24 | (long)'l' << 16,
- (long)'f' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'c' << 32 | (long)'1' << 24 | (long)'2' << 16,
- (long)'f' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'c' << 32 | (long)'1' << 24 | (long)'4' << 16,
- (long)'f' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'c' << 32 | (long)'3' << 24 | (long)'4' << 16,
- (long)'f' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'s' << 32 | (long)'l' << 24,
- (long)'g' << 56 | (long)'a' << 48 | (long)'m' << 40 | (long)'m' << 32 | (long)'a' << 24,
- (long)'g' << 56 | (long)'e' << 48,
- (long)'g' << 56 | (long)'t' << 48,
- (long)'h' << 56 | (long)'A' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'h' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'h' << 56 | (long)'e' << 48 | (long)'a' << 40 | (long)'r' << 32 | (long)'t' << 24 | (long)'s' << 16,
- (long)'h' << 56 | (long)'e' << 48 | (long)'l' << 40 | (long)'l' << 32 | (long)'i' << 24 | (long)'p' << 16,
- (long)'i' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'i' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'i' << 56 | (long)'e' << 48 | (long)'x' << 40 | (long)'c' << 32 | (long)'l' << 24,
- (long)'i' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'i' << 56 | (long)'m' << 48 | (long)'a' << 40 | (long)'g' << 32 | (long)'e' << 24,
- (long)'i' << 56 | (long)'n' << 48 | (long)'f' << 40 | (long)'i' << 32 | (long)'n' << 24,
- (long)'i' << 56 | (long)'n' << 48 | (long)'t' << 40,
- (long)'i' << 56 | (long)'o' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'i' << 56 | (long)'q' << 48 | (long)'u' << 40 | (long)'e' << 32 | (long)'s' << 24 | (long)'t' << 16,
- (long)'i' << 56 | (long)'s' << 48 | (long)'i' << 40 | (long)'n' << 32,
- (long)'i' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'k' << 56 | (long)'a' << 48 | (long)'p' << 40 | (long)'p' << 32 | (long)'a' << 24,
- (long)'l' << 56 | (long)'A' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'l' << 56 | (long)'a' << 48 | (long)'m' << 40 | (long)'b' << 32 | (long)'d' << 24 | (long)'a' << 16,
- (long)'l' << 56 | (long)'a' << 48 | (long)'n' << 40 | (long)'g' << 32,
- (long)'l' << 56 | (long)'a' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'l' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'l' << 56 | (long)'c' << 48 | (long)'e' << 40 | (long)'i' << 32 | (long)'l' << 24,
- (long)'l' << 56 | (long)'d' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'l' << 56 | (long)'e' << 48,
- (long)'l' << 56 | (long)'f' << 48 | (long)'l' << 40 | (long)'o' << 32 | (long)'o' << 24 | (long)'r' << 16,
- (long)'l' << 56 | (long)'o' << 48 | (long)'w' << 40 | (long)'a' << 32 | (long)'s' << 24 | (long)'t' << 16,
- (long)'l' << 56 | (long)'o' << 48 | (long)'z' << 40,
- (long)'l' << 56 | (long)'r' << 48 | (long)'m' << 40,
- (long)'l' << 56 | (long)'s' << 48 | (long)'a' << 40 | (long)'q' << 32 | (long)'u' << 24 | (long)'o' << 16,
- (long)'l' << 56 | (long)'s' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'l' << 56 | (long)'t' << 48,
- (long)'m' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'r' << 32,
- (long)'m' << 56 | (long)'d' << 48 | (long)'a' << 40 | (long)'s' << 32 | (long)'h' << 24,
- (long)'m' << 56 | (long)'i' << 48 | (long)'c' << 40 | (long)'r' << 32 | (long)'o' << 24,
- (long)'m' << 56 | (long)'i' << 48 | (long)'d' << 40 | (long)'d' << 32 | (long)'o' << 24 | (long)'t' << 16,
- (long)'m' << 56 | (long)'i' << 48 | (long)'n' << 40 | (long)'u' << 32 | (long)'s' << 24,
- (long)'m' << 56 | (long)'u' << 48,
- (long)'n' << 56 | (long)'a' << 48 | (long)'b' << 40 | (long)'l' << 32 | (long)'a' << 24,
- (long)'n' << 56 | (long)'b' << 48 | (long)'s' << 40 | (long)'p' << 32,
- (long)'n' << 56 | (long)'d' << 48 | (long)'a' << 40 | (long)'s' << 32 | (long)'h' << 24,
- (long)'n' << 56 | (long)'e' << 48,
- (long)'n' << 56 | (long)'i' << 48,
- (long)'n' << 56 | (long)'o' << 48 | (long)'t' << 40,
- (long)'n' << 56 | (long)'o' << 48 | (long)'t' << 40 | (long)'i' << 32 | (long)'n' << 24,
- (long)'n' << 56 | (long)'s' << 48 | (long)'u' << 40 | (long)'b' << 32,
- (long)'n' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'n' << 56 | (long)'u' << 48,
- (long)'o' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'o' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'o' << 56 | (long)'e' << 48 | (long)'l' << 40 | (long)'i' << 32 | (long)'g' << 24,
- (long)'o' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'o' << 56 | (long)'l' << 48 | (long)'i' << 40 | (long)'n' << 32 | (long)'e' << 24,
- (long)'o' << 56 | (long)'m' << 48 | (long)'e' << 40 | (long)'g' << 32 | (long)'a' << 24,
- (long)'o' << 56 | (long)'m' << 48 | (long)'i' << 40 | (long)'c' << 32 | (long)'r' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'o' << 56 | (long)'p' << 48 | (long)'l' << 40 | (long)'u' << 32 | (long)'s' << 24,
- (long)'o' << 56 | (long)'r' << 48,
- (long)'o' << 56 | (long)'r' << 48 | (long)'d' << 40 | (long)'f' << 32,
- (long)'o' << 56 | (long)'r' << 48 | (long)'d' << 40 | (long)'m' << 32,
- (long)'o' << 56 | (long)'s' << 48 | (long)'l' << 40 | (long)'a' << 32 | (long)'s' << 24 | (long)'h' << 16,
- (long)'o' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'l' << 32 | (long)'d' << 24 | (long)'e' << 16,
- (long)'o' << 56 | (long)'t' << 48 | (long)'i' << 40 | (long)'m' << 32 | (long)'e' << 24 | (long)'s' << 16,
- (long)'o' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'p' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'a' << 32,
- (long)'p' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'t' << 32,
- (long)'p' << 56 | (long)'e' << 48 | (long)'r' << 40 | (long)'m' << 32 | (long)'i' << 24 | (long)'l' << 16,
- (long)'p' << 56 | (long)'e' << 48 | (long)'r' << 40 | (long)'p' << 32,
- (long)'p' << 56 | (long)'h' << 48 | (long)'i' << 40,
- (long)'p' << 56 | (long)'i' << 48,
- (long)'p' << 56 | (long)'i' << 48 | (long)'v' << 40,
- (long)'p' << 56 | (long)'l' << 48 | (long)'u' << 40 | (long)'s' << 32 | (long)'m' << 24 | (long)'n' << 16,
- (long)'p' << 56 | (long)'o' << 48 | (long)'u' << 40 | (long)'n' << 32 | (long)'d' << 24,
- (long)'p' << 56 | (long)'r' << 48 | (long)'i' << 40 | (long)'m' << 32 | (long)'e' << 24,
- (long)'p' << 56 | (long)'r' << 48 | (long)'o' << 40 | (long)'d' << 32,
- (long)'p' << 56 | (long)'r' << 48 | (long)'o' << 40 | (long)'p' << 32,
- (long)'p' << 56 | (long)'s' << 48 | (long)'i' << 40,
- (long)'q' << 56 | (long)'u' << 48 | (long)'o' << 40 | (long)'t' << 32,
- (long)'r' << 56 | (long)'A' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'r' << 56 | (long)'a' << 48 | (long)'d' << 40 | (long)'i' << 32 | (long)'c' << 24,
- (long)'r' << 56 | (long)'a' << 48 | (long)'n' << 40 | (long)'g' << 32,
- (long)'r' << 56 | (long)'a' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'r' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'r' << 56 | (long)'c' << 48 | (long)'e' << 40 | (long)'i' << 32 | (long)'l' << 24,
- (long)'r' << 56 | (long)'d' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'r' << 56 | (long)'e' << 48 | (long)'a' << 40 | (long)'l' << 32,
- (long)'r' << 56 | (long)'e' << 48 | (long)'g' << 40,
- (long)'r' << 56 | (long)'f' << 48 | (long)'l' << 40 | (long)'o' << 32 | (long)'o' << 24 | (long)'r' << 16,
- (long)'r' << 56 | (long)'h' << 48 | (long)'o' << 40,
- (long)'r' << 56 | (long)'l' << 48 | (long)'m' << 40,
- (long)'r' << 56 | (long)'s' << 48 | (long)'a' << 40 | (long)'q' << 32 | (long)'u' << 24 | (long)'o' << 16,
- (long)'r' << 56 | (long)'s' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'s' << 56 | (long)'b' << 48 | (long)'q' << 40 | (long)'u' << 32 | (long)'o' << 24,
- (long)'s' << 56 | (long)'c' << 48 | (long)'a' << 40 | (long)'r' << 32 | (long)'o' << 24 | (long)'n' << 16,
- (long)'s' << 56 | (long)'d' << 48 | (long)'o' << 40 | (long)'t' << 32,
- (long)'s' << 56 | (long)'e' << 48 | (long)'c' << 40 | (long)'t' << 32,
- (long)'s' << 56 | (long)'h' << 48 | (long)'y' << 40,
- (long)'s' << 56 | (long)'i' << 48 | (long)'g' << 40 | (long)'m' << 32 | (long)'a' << 24,
- (long)'s' << 56 | (long)'i' << 48 | (long)'g' << 40 | (long)'m' << 32 | (long)'a' << 24 | (long)'f' << 16,
- (long)'s' << 56 | (long)'i' << 48 | (long)'m' << 40,
- (long)'s' << 56 | (long)'p' << 48 | (long)'a' << 40 | (long)'d' << 32 | (long)'e' << 24 | (long)'s' << 16,
- (long)'s' << 56 | (long)'u' << 48 | (long)'b' << 40,
- (long)'s' << 56 | (long)'u' << 48 | (long)'b' << 40 | (long)'e' << 32,
- (long)'s' << 56 | (long)'u' << 48 | (long)'m' << 40,
- (long)'s' << 56 | (long)'u' << 48 | (long)'p' << 40,
- (long)'s' << 56 | (long)'u' << 48 | (long)'p' << 40 | (long)'1' << 32,
- (long)'s' << 56 | (long)'u' << 48 | (long)'p' << 40 | (long)'2' << 32,
- (long)'s' << 56 | (long)'u' << 48 | (long)'p' << 40 | (long)'3' << 32,
- (long)'s' << 56 | (long)'u' << 48 | (long)'p' << 40 | (long)'e' << 32,
- (long)'s' << 56 | (long)'z' << 48 | (long)'l' << 40 | (long)'i' << 32 | (long)'g' << 24,
- (long)'t' << 56 | (long)'a' << 48 | (long)'u' << 40,
- (long)'t' << 56 | (long)'h' << 48 | (long)'e' << 40 | (long)'r' << 32 | (long)'e' << 24 | (long)'4' << 16,
- (long)'t' << 56 | (long)'h' << 48 | (long)'e' << 40 | (long)'t' << 32 | (long)'a' << 24,
- (long)'t' << 56 | (long)'h' << 48 | (long)'e' << 40 | (long)'t' << 32 | (long)'a' << 24 | (long)'s' << 16 | (long)'y' << 8 | (long)'m' << 0,
- (long)'t' << 56 | (long)'h' << 48 | (long)'i' << 40 | (long)'n' << 32 | (long)'s' << 24 | (long)'p' << 16,
- (long)'t' << 56 | (long)'h' << 48 | (long)'o' << 40 | (long)'r' << 32 | (long)'n' << 24,
- (long)'t' << 56 | (long)'i' << 48 | (long)'l' << 40 | (long)'d' << 32 | (long)'e' << 24,
- (long)'t' << 56 | (long)'i' << 48 | (long)'m' << 40 | (long)'e' << 32 | (long)'s' << 24,
- (long)'t' << 56 | (long)'r' << 48 | (long)'a' << 40 | (long)'d' << 32 | (long)'e' << 24,
- (long)'u' << 56 | (long)'A' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'u' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'u' << 56 | (long)'a' << 48 | (long)'r' << 40 | (long)'r' << 32,
- (long)'u' << 56 | (long)'c' << 48 | (long)'i' << 40 | (long)'r' << 32 | (long)'c' << 24,
- (long)'u' << 56 | (long)'g' << 48 | (long)'r' << 40 | (long)'a' << 32 | (long)'v' << 24 | (long)'e' << 16,
- (long)'u' << 56 | (long)'m' << 48 | (long)'l' << 40,
- (long)'u' << 56 | (long)'p' << 48 | (long)'s' << 40 | (long)'i' << 32 | (long)'h' << 24,
- (long)'u' << 56 | (long)'p' << 48 | (long)'s' << 40 | (long)'i' << 32 | (long)'l' << 24 | (long)'o' << 16 | (long)'n' << 8,
- (long)'u' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'w' << 56 | (long)'e' << 48 | (long)'i' << 40 | (long)'e' << 32 | (long)'r' << 24 | (long)'p' << 16,
- (long)'x' << 56 | (long)'i' << 48,
- (long)'y' << 56 | (long)'a' << 48 | (long)'c' << 40 | (long)'u' << 32 | (long)'t' << 24 | (long)'e' << 16,
- (long)'y' << 56 | (long)'e' << 48 | (long)'n' << 40,
- (long)'y' << 56 | (long)'u' << 48 | (long)'m' << 40 | (long)'l' << 32,
- (long)'z' << 56 | (long)'e' << 48 | (long)'t' << 40 | (long)'a' << 32,
- (long)'z' << 56 | (long)'w' << 48 | (long)'j' << 40,
- (long)'z' << 56 | (long)'w' << 48 | (long)'n' << 40 | (long)'j' << 32
- };
-
- static readonly char[] entities_values = new char[] {
- '\u00C6', '\u00C1', '\u00C2', '\u00C0', '\u0391', '\u00C5', '\u00C3', '\u00C4', '\u0392', '\u00C7', '\u03A7',
- '\u2021', '\u0394', '\u00D0', '\u00C9', '\u00CA', '\u00C8', '\u0395', '\u0397', '\u00CB', '\u0393', '\u00CD',
- '\u00CE', '\u00CC', '\u0399', '\u00CF', '\u039A', '\u039B', '\u039C', '\u00D1', '\u039D', '\u0152', '\u00D3',
- '\u00D4', '\u00D2', '\u03A9', '\u039F', '\u00D8', '\u00D5', '\u00D6', '\u03A6', '\u03A0', '\u2033', '\u03A8',
- '\u03A1', '\u0160', '\u03A3', '\u00DE', '\u03A4', '\u0398', '\u00DA', '\u00DB', '\u00D9', '\u03A5', '\u00DC',
- '\u039E', '\u00DD', '\u0178', '\u0396', '\u00E1', '\u00E2', '\u00B4', '\u00E6', '\u00E0', '\u2135', '\u03B1',
- '\u0026', '\u2227', '\u2220', '\u0027', '\u00E5', '\u2248', '\u00E3', '\u00E4', '\u201E', '\u03B2', '\u00A6',
- '\u2022', '\u2229', '\u00E7', '\u00B8', '\u00A2', '\u03C7', '\u02C6', '\u2663', '\u2245', '\u00A9', '\u21B5',
- '\u222A', '\u00A4', '\u21D3', '\u2020', '\u2193', '\u00B0', '\u03B4', '\u2666', '\u00F7', '\u00E9', '\u00EA',
- '\u00E8', '\u2205', '\u2003', '\u2002', '\u03B5', '\u2261', '\u03B7', '\u00F0', '\u00EB', '\u20AC', '\u2203',
- '\u0192', '\u2200', '\u00BD', '\u00BC', '\u00BE', '\u2044', '\u03B3', '\u2265', '\u003E', '\u21D4', '\u2194',
- '\u2665', '\u2026', '\u00ED', '\u00EE', '\u00A1', '\u00EC', '\u2111', '\u221E', '\u222B', '\u03B9', '\u00BF',
- '\u2208', '\u00EF', '\u03BA', '\u21D0', '\u03BB', '\u2329', '\u00AB', '\u2190', '\u2308', '\u201C', '\u2264',
- '\u230A', '\u2217', '\u25CA', '\u200E', '\u2039', '\u2018', '\u003C', '\u00AF', '\u2014', '\u00B5', '\u00B7',
- '\u2212', '\u03BC', '\u2207', '\u00A0', '\u2013', '\u2260', '\u220B', '\u00AC', '\u2209', '\u2284', '\u00F1',
- '\u03BD', '\u00F3', '\u00F4', '\u0153', '\u00F2', '\u203E', '\u03C9', '\u03BF', '\u2295', '\u2228', '\u00AA',
- '\u00BA', '\u00F8', '\u00F5', '\u2297', '\u00F6', '\u00B6', '\u2202', '\u2030', '\u22A5', '\u03C6', '\u03C0',
- '\u03D6', '\u00B1', '\u00A3', '\u2032', '\u220F', '\u221D', '\u03C8', '\u0022', '\u21D2', '\u221A', '\u232A',
- '\u00BB', '\u2192', '\u2309', '\u201D', '\u211C', '\u00AE', '\u230B', '\u03C1', '\u200F', '\u203A', '\u2019',
- '\u201A', '\u0161', '\u22C5', '\u00A7', '\u00AD', '\u03C3', '\u03C2', '\u223C', '\u2660', '\u2282', '\u2286',
- '\u2211', '\u2283', '\u00B9', '\u00B2', '\u00B3', '\u2287', '\u00DF', '\u03C4', '\u2234', '\u03B8', '\u03D1',
- '\u2009', '\u00FE', '\u02DC', '\u00D7', '\u2122', '\u21D1', '\u00FA', '\u2191', '\u00FB', '\u00F9', '\u00A8',
- '\u03D2', '\u03C5', '\u00FC', '\u2118', '\u03BE', '\u00FD', '\u00A5', '\u00FF', '\u03B6', '\u200D', '\u200C'
- };
-
- #region Methods
-
- static void WriteCharBytes(IList buf, char ch, Encoding e)
- {
- if (ch > 255)
- {
- foreach (byte b in e.GetBytes(new char[] { ch }))
- buf.Add(b);
- }
- else
- buf.Add((byte)ch);
- }
-
- public static string UrlDecode(string s, Encoding e)
- {
- if (null == s)
- return null;
-
- if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1)
- return s;
-
- if (e == null)
- e = Encoding.UTF8;
-
- long len = s.Length;
- var bytes = new List<byte>();
- int xchar;
- char ch;
-
- for (int i = 0; i < len; i++)
- {
- ch = s[i];
- if (ch == '%' && i + 2 < len && s[i + 1] != '%')
- {
- if (s[i + 1] == 'u' && i + 5 < len)
- {
- // unicode hex sequence
- xchar = GetChar(s, i + 2, 4);
- if (xchar != -1)
- {
- WriteCharBytes(bytes, (char)xchar, e);
- i += 5;
- }
- else
- WriteCharBytes(bytes, '%', e);
- }
- else if ((xchar = GetChar(s, i + 1, 2)) != -1)
- {
- WriteCharBytes(bytes, (char)xchar, e);
- i += 2;
- }
- else
- {
- WriteCharBytes(bytes, '%', e);
- }
- continue;
- }
-
- if (ch == '+')
- WriteCharBytes(bytes, ' ', e);
- else
- WriteCharBytes(bytes, ch, e);
- }
-
- byte[] buf = bytes.ToArray();
- bytes = null;
- return e.GetString(buf, 0, buf.Length);
-
- }
-
- static int GetInt(byte b)
- {
- char c = (char)b;
- if (c >= '0' && c <= '9')
- return c - '0';
-
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
-
- if (c >= 'A' && c <= 'F')
- return c - 'A' + 10;
-
- return -1;
- }
-
- static int GetChar(string str, int offset, int length)
- {
- int val = 0;
- int end = length + offset;
- for (int i = offset; i < end; i++)
- {
- char c = str[i];
- if (c > 127)
- return -1;
-
- int current = GetInt((byte)c);
- if (current == -1)
- return -1;
- val = (val << 4) + current;
- }
-
- return val;
- }
-
- static bool TryConvertKeyToEntity(string key, out char value)
- {
- var token = CalculateKeyValue(key);
- if (token == 0)
- {
- value = '\0';
- return false;
- }
-
- var idx = Array.BinarySearch(entities, token);
- if (idx < 0)
- {
- value = '\0';
- return false;
- }
-
- value = entities_values[idx];
- return true;
- }
-
- static long CalculateKeyValue(string s)
- {
- if (s.Length > 8)
- return 0;
-
- long key = 0;
- for (int i = 0; i < s.Length; ++i)
- {
- long ch = s[i];
- if (ch > 'z' || ch < '0')
- return 0;
-
- key |= ch << ((7 - i) * 8);
- }
-
- return key;
- }
-
- /// <summary>
- /// Decodes an HTML-encoded string and returns the decoded string.
- /// </summary>
- /// <param name="s">The HTML string to decode. </param>
- /// <returns>The decoded text.</returns>
- public static string HtmlDecode(string s)
- {
- if (s == null)
- throw new ArgumentNullException(nameof(s));
-
- if (s.IndexOf('&') == -1)
- return s;
-
- var entity = new StringBuilder();
- var output = new StringBuilder();
- int len = s.Length;
- // 0 -> nothing,
- // 1 -> right after '&'
- // 2 -> between '&' and ';' but no '#'
- // 3 -> '#' found after '&' and getting numbers
- int state = 0;
- int number = 0;
- int digit_start = 0;
- bool hex_number = false;
-
- for (int i = 0; i < len; i++)
- {
- char c = s[i];
- if (state == 0)
- {
- if (c == '&')
- {
- entity.Append(c);
- state = 1;
- }
- else
- {
- output.Append(c);
- }
- continue;
- }
-
- if (c == '&')
- {
- state = 1;
- if (digit_start > 0)
- {
- entity.Append(s, digit_start, i - digit_start);
- digit_start = 0;
- }
-
- output.Append(entity.ToString());
- entity.Length = 0;
- entity.Append('&');
- continue;
- }
-
- switch (state)
- {
- case 1:
- if (c == ';')
- {
- state = 0;
- output.Append(entity.ToString());
- output.Append(c);
- entity.Length = 0;
- break;
- }
-
- number = 0;
- hex_number = false;
- if (c != '#')
- {
- state = 2;
- }
- else
- {
- state = 3;
- }
- entity.Append(c);
-
- break;
- case 2:
- entity.Append(c);
- if (c == ';')
- {
- string key = entity.ToString();
- state = 0;
- entity.Length = 0;
-
- if (key.Length > 1)
- {
- var skey = key.Substring(1, key.Length - 2);
- if (TryConvertKeyToEntity(skey, out c))
- {
- output.Append(c);
- break;
- }
- }
-
- output.Append(key);
- }
-
- break;
- case 3:
- if (c == ';')
- {
- if (number < 0x10000)
- {
- output.Append((char)number);
- }
- else
- {
- output.Append((char)(0xd800 + ((number - 0x10000) >> 10)));
- output.Append((char)(0xdc00 + ((number - 0x10000) & 0x3ff)));
- }
- state = 0;
- entity.Length = 0;
- digit_start = 0;
- break;
- }
-
- if (c == 'x' || c == 'X' && !hex_number)
- {
- digit_start = i;
- hex_number = true;
- break;
- }
-
- if (char.IsDigit(c))
- {
- if (digit_start == 0)
- digit_start = i;
-
- number = number * (hex_number ? 16 : 10) + ((int)c - '0');
- break;
- }
-
- if (hex_number)
- {
- if (c >= 'a' && c <= 'f')
- {
- number = number * 16 + 10 + ((int)c - 'a');
- break;
- }
- if (c >= 'A' && c <= 'F')
- {
- number = number * 16 + 10 + ((int)c - 'A');
- break;
- }
- }
-
- state = 2;
- if (digit_start > 0)
- {
- entity.Append(s, digit_start, i - digit_start);
- digit_start = 0;
- }
-
- entity.Append(c);
- break;
- }
- }
-
- if (entity.Length > 0)
- {
- output.Append(entity);
- }
- else if (digit_start > 0)
- {
- output.Append(s, digit_start, s.Length - digit_start);
- }
- return output.ToString();
- }
-
- public static QueryParamCollection ParseQueryString(string query)
- {
- return ParseQueryString(query, Encoding.UTF8);
- }
-
- public static QueryParamCollection ParseQueryString(string query, Encoding encoding)
- {
- if (query == null)
- throw new ArgumentNullException(nameof(query));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
- return new QueryParamCollection();
- if (query[0] == '?')
- query = query.Substring(1);
-
- var result = new QueryParamCollection();
- ParseQueryString(query, encoding, result);
- return result;
- }
-
- internal static void ParseQueryString(string query, Encoding encoding, QueryParamCollection result)
- {
- if (query.Length == 0)
- return;
-
- string decoded = HtmlDecode(query);
- int decodedLength = decoded.Length;
- int namePos = 0;
- bool first = true;
- while (namePos <= decodedLength)
- {
- int valuePos = -1, valueEnd = -1;
- for (int q = namePos; q < decodedLength; q++)
- {
- if (valuePos == -1 && decoded[q] == '=')
- {
- valuePos = q + 1;
- }
- else if (decoded[q] == '&')
- {
- valueEnd = q;
- break;
- }
- }
-
- if (first)
- {
- first = false;
- if (decoded[namePos] == '?')
- namePos++;
- }
-
- string name, value;
- if (valuePos == -1)
- {
- name = null;
- valuePos = namePos;
- }
- else
- {
- name = UrlDecode(decoded.Substring(namePos, valuePos - namePos - 1), encoding);
- }
- if (valueEnd < 0)
- {
- namePos = -1;
- valueEnd = decoded.Length;
- }
- else
- {
- namePos = valueEnd + 1;
- }
- value = UrlDecode(decoded.Substring(valuePos, valueEnd - valuePos), encoding);
-
- result.Add(name, value);
- if (namePos == -1)
- break;
- }
- }
- #endregion // Methods
- }
-}
diff --git a/MediaBrowser.Model/Services/IAsyncStreamWriter.cs b/MediaBrowser.Model/Services/IAsyncStreamWriter.cs
deleted file mode 100644
index f16a877e6..000000000
--- a/MediaBrowser.Model/Services/IAsyncStreamWriter.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IAsyncStreamWriter
- {
- Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Model/Services/IHasHeaders.cs b/MediaBrowser.Model/Services/IHasHeaders.cs
deleted file mode 100644
index b2d413b70..000000000
--- a/MediaBrowser.Model/Services/IHasHeaders.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.Collections.Generic;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IHasHeaders
- {
- IDictionary<string, string> Headers { get; }
- }
-}
diff --git a/MediaBrowser.Model/Services/IHasRequestFilter.cs b/MediaBrowser.Model/Services/IHasRequestFilter.cs
deleted file mode 100644
index d4e6aa8e0..000000000
--- a/MediaBrowser.Model/Services/IHasRequestFilter.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace MediaBrowser.Model.Services
-{
- public interface IHasRequestFilter
- {
- /// <summary>
- /// Order in which Request Filters are executed.
- /// &lt;0 Executed before global request filters
- /// &gt;0 Executed after global request filters
- /// </summary>
- int Priority { get; }
-
- /// <summary>
- /// The request filter is executed before the service.
- /// </summary>
- /// <param name="req">The http request wrapper</param>
- /// <param name="res">The http response wrapper</param>
- /// <param name="requestDto">The request DTO</param>
- void RequestFilter(IRequest req, IResponse res, object requestDto);
- }
-}
diff --git a/MediaBrowser.Model/Services/IHttpRequest.cs b/MediaBrowser.Model/Services/IHttpRequest.cs
deleted file mode 100644
index 579f80c96..000000000
--- a/MediaBrowser.Model/Services/IHttpRequest.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-namespace MediaBrowser.Model.Services
-{
- public interface IHttpRequest : IRequest
- {
- /// <summary>
- /// The HttpResponse
- /// </summary>
- IHttpResponse HttpResponse { get; }
-
- /// <summary>
- /// The HTTP Verb
- /// </summary>
- string HttpMethod { get; }
-
- /// <summary>
- /// The IP Address of the X-Forwarded-For header, null if null or empty
- /// </summary>
- string XForwardedFor { get; }
-
- /// <summary>
- /// The Port number of the X-Forwarded-Port header, null if null or empty
- /// </summary>
- int? XForwardedPort { get; }
-
- /// <summary>
- /// The http or https scheme of the X-Forwarded-Proto header, null if null or empty
- /// </summary>
- string XForwardedProtocol { get; }
-
- /// <summary>
- /// The value of the X-Real-IP header, null if null or empty
- /// </summary>
- string XRealIp { get; }
-
- /// <summary>
- /// The value of the Accept HTTP Request Header
- /// </summary>
- string Accept { get; }
- }
-}
diff --git a/MediaBrowser.Model/Services/IHttpResponse.cs b/MediaBrowser.Model/Services/IHttpResponse.cs
deleted file mode 100644
index a8b79f394..000000000
--- a/MediaBrowser.Model/Services/IHttpResponse.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.Net;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IHttpResponse : IResponse
- {
- //ICookies Cookies { get; }
-
- /// <summary>
- /// Adds a new Set-Cookie instruction to Response
- /// </summary>
- /// <param name="cookie"></param>
- void SetCookie(Cookie cookie);
-
- /// <summary>
- /// Removes all pending Set-Cookie instructions
- /// </summary>
- void ClearCookies();
- }
-}
diff --git a/MediaBrowser.Model/Services/IHttpResult.cs b/MediaBrowser.Model/Services/IHttpResult.cs
deleted file mode 100644
index bfa30f60d..000000000
--- a/MediaBrowser.Model/Services/IHttpResult.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System.Net;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IHttpResult : IHasHeaders
- {
- /// <summary>
- /// The HTTP Response Status
- /// </summary>
- int Status { get; set; }
-
- /// <summary>
- /// The HTTP Response Status Code
- /// </summary>
- HttpStatusCode StatusCode { get; set; }
-
- /// <summary>
- /// The HTTP Response ContentType
- /// </summary>
- string ContentType { get; set; }
-
- /// <summary>
- /// Response DTO
- /// </summary>
- object Response { get; set; }
-
- /// <summary>
- /// Holds the request call context
- /// </summary>
- IRequest RequestContext { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Services/IRequest.cs b/MediaBrowser.Model/Services/IRequest.cs
deleted file mode 100644
index ac9b981b9..000000000
--- a/MediaBrowser.Model/Services/IRequest.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IRequest
- {
- /// <summary>
- /// The underlying ASP.NET or HttpListener HttpRequest
- /// </summary>
- object OriginalRequest { get; }
-
- IResponse Response { get; }
-
- /// <summary>
- /// The name of the service being called (e.g. Request DTO Name)
- /// </summary>
- string OperationName { get; set; }
-
- /// <summary>
- /// The Verb / HttpMethod or Action for this request
- /// </summary>
- string Verb { get; }
-
- /// <summary>
- /// The Request DTO, after it has been deserialized.
- /// </summary>
- object Dto { get; set; }
-
- /// <summary>
- /// The request ContentType
- /// </summary>
- string ContentType { get; }
-
- bool IsLocal { get; }
-
- string UserAgent { get; }
-
- IDictionary<string, Cookie> Cookies { get; }
-
- /// <summary>
- /// The expected Response ContentType for this request
- /// </summary>
- string ResponseContentType { get; set; }
-
- /// <summary>
- /// Attach any data to this request that all filters and services can access.
- /// </summary>
- Dictionary<string, object> Items { get; }
-
- QueryParamCollection Headers { get; }
-
- QueryParamCollection QueryString { get; }
-
- Task<QueryParamCollection> GetFormData();
-
- string RawUrl { get; }
-
- string AbsoluteUri { get; }
-
- /// <summary>
- /// The Remote Ip as reported by Request.UserHostAddress
- /// </summary>
- string UserHostAddress { get; }
-
- /// <summary>
- /// The Remote Ip as reported by X-Forwarded-For, X-Real-IP or Request.UserHostAddress
- /// </summary>
- string RemoteIp { get; }
-
- /// <summary>
- /// The value of the Authorization Header used to send the Api Key, null if not available
- /// </summary>
- string Authorization { get; }
-
- /// <summary>
- /// e.g. is https or not
- /// </summary>
- bool IsSecureConnection { get; }
-
- string[] AcceptTypes { get; }
-
- string PathInfo { get; }
-
- Stream InputStream { get; }
-
- long ContentLength { get; }
-
- /// <summary>
- /// Access to the multi-part/formdata files posted on this request
- /// </summary>
- IHttpFile[] Files { get; }
-
- /// <summary>
- /// The value of the Referrer, null if not available
- /// </summary>
- Uri UrlReferrer { get; }
- }
-
- public interface IHttpFile
- {
- string Name { get; }
- string FileName { get; }
- long ContentLength { get; }
- string ContentType { get; }
- Stream InputStream { get; }
- }
-
- public interface IRequiresRequest
- {
- IRequest Request { get; set; }
- }
-
- public interface IResponse
- {
- IRequest Request { get; }
-
- int StatusCode { get; set; }
-
- string StatusDescription { get; set; }
-
- string ContentType { get; set; }
-
- void AddHeader(string name, string value);
-
- string GetHeader(string name);
-
- void Redirect(string url);
-
- Stream OutputStream { get; }
-
- /// <summary>
- /// Signal that this response has been handled and no more processing should be done.
- /// When used in a request or response filter, no more filters or processing is done on this request.
- /// </summary>
- void Close();
-
- /// <summary>
- /// Gets a value indicating whether this instance is closed.
- /// </summary>
- bool IsClosed { get; }
-
- void SetContentLength(long contentLength);
-
- //Add Metadata to Response
- Dictionary<string, object> Items { get; }
-
- QueryParamCollection Headers { get; }
-
- Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken);
-
- bool SendChunked { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Services/IRequiresRequestStream.cs b/MediaBrowser.Model/Services/IRequiresRequestStream.cs
deleted file mode 100644
index 2f17c6a9a..000000000
--- a/MediaBrowser.Model/Services/IRequiresRequestStream.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.IO;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IRequiresRequestStream
- {
- /// <summary>
- /// The raw Http Request Input Stream
- /// </summary>
- Stream RequestStream { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Services/IService.cs b/MediaBrowser.Model/Services/IService.cs
deleted file mode 100644
index 8f2e63e98..000000000
--- a/MediaBrowser.Model/Services/IService.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace MediaBrowser.Model.Services
-{
- // marker interface
- public interface IService
- {
- }
-
- public interface IReturn { }
- public interface IReturn<T> : IReturn { }
- public interface IReturnVoid : IReturn { }
-}
diff --git a/MediaBrowser.Model/Services/IStreamWriter.cs b/MediaBrowser.Model/Services/IStreamWriter.cs
deleted file mode 100644
index 9d65cff63..000000000
--- a/MediaBrowser.Model/Services/IStreamWriter.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.IO;
-
-namespace MediaBrowser.Model.Services
-{
- public interface IStreamWriter
- {
- void WriteTo(Stream responseStream);
- }
-}
diff --git a/MediaBrowser.Model/Services/QueryParamCollection.cs b/MediaBrowser.Model/Services/QueryParamCollection.cs
deleted file mode 100644
index 4297b97c6..000000000
--- a/MediaBrowser.Model/Services/QueryParamCollection.cs
+++ /dev/null
@@ -1,196 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Model.Dto;
-
-namespace MediaBrowser.Model.Services
-{
- public class QueryParamCollection : List<NameValuePair>
- {
- public QueryParamCollection()
- {
-
- }
-
- public QueryParamCollection(IDictionary<string, string> headers)
- {
- foreach (var pair in headers)
- {
- Add(pair.Key, pair.Value);
- }
- }
-
- private static StringComparison GetStringComparison()
- {
- return StringComparison.OrdinalIgnoreCase;
- }
-
- private static StringComparer GetStringComparer()
- {
- return StringComparer.OrdinalIgnoreCase;
- }
-
- public string GetKey(int index)
- {
- return this[index].Name;
- }
-
- public string Get(int index)
- {
- return this[index].Value;
- }
-
- public virtual string[] GetValues(int index)
- {
- return new[] { Get(index) };
- }
-
- /// <summary>
- /// Adds a new query parameter.
- /// </summary>
- public virtual void Add(string key, string value)
- {
- Add(new NameValuePair(key, value));
- }
-
- public virtual void Set(string key, string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- var parameters = GetItems(key);
-
- foreach (var p in parameters)
- {
- Remove(p);
- }
-
- return;
- }
-
- foreach (var pair in this)
- {
- var stringComparison = GetStringComparison();
-
- if (string.Equals(key, pair.Name, stringComparison))
- {
- pair.Value = value;
- return;
- }
- }
-
- Add(key, value);
- }
-
- /// <summary>
- /// Removes all parameters of the given name.
- /// </summary>
- /// <returns>The number of parameters that were removed</returns>
- /// <exception cref="ArgumentNullException"><paramref name="name" /> is null.</exception>
- public virtual int Remove(string name)
- {
- return RemoveAll(p => p.Name == name);
- }
-
- public string Get(string name)
- {
- var stringComparison = GetStringComparison();
-
- foreach (var pair in this)
- {
- if (string.Equals(pair.Name, name, stringComparison))
- {
- return pair.Value;
- }
- }
-
- return null;
- }
-
- public virtual List<NameValuePair> GetItems(string name)
- {
- var stringComparison = GetStringComparison();
-
- var list = new List<NameValuePair>();
-
- foreach (var pair in this)
- {
- if (string.Equals(pair.Name, name, stringComparison))
- {
- list.Add(pair);
- }
- }
-
- return list;
- }
-
- public virtual List<string> GetValues(string name)
- {
- var stringComparison = GetStringComparison();
-
- var list = new List<string>();
-
- foreach (var pair in this)
- {
- if (string.Equals(pair.Name, name, stringComparison))
- {
- list.Add(pair.Value);
- }
- }
-
- return list;
- }
-
- public Dictionary<string, string> ToDictionary()
- {
- var stringComparer = GetStringComparer();
-
- var headers = new Dictionary<string, string>(stringComparer);
-
- foreach (var pair in this)
- {
- headers[pair.Name] = pair.Value;
- }
-
- return headers;
- }
-
- public IEnumerable<string> Keys
- {
- get
- {
- var keys = new string[this.Count];
-
- for (var i = 0; i < keys.Length; i++)
- {
- keys[i] = this[i].Name;
- }
-
- return keys;
- }
- }
-
- /// <summary>
- /// Gets or sets a query parameter value by name. A query may contain multiple values of the same name
- /// (i.e. "x=1&amp;x=2"), in which case the value is an array, which works for both getting and setting.
- /// </summary>
- /// <param name="name">The query parameter name</param>
- /// <returns>The query parameter value or array of values</returns>
- public string this[string name]
- {
- get => Get(name);
- set => Set(name, value);
- }
-
- private string GetQueryStringValue(NameValuePair pair)
- {
- return pair.Name + "=" + pair.Value;
- }
-
- public override string ToString()
- {
- var vals = this.Select(GetQueryStringValue).ToArray();
-
- return string.Join("&", vals);
- }
- }
-}
diff --git a/MediaBrowser.Model/Services/RouteAttribute.cs b/MediaBrowser.Model/Services/RouteAttribute.cs
deleted file mode 100644
index f6316e2b1..000000000
--- a/MediaBrowser.Model/Services/RouteAttribute.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Services
-{
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
- public class RouteAttribute : Attribute
- {
- /// <summary>
- /// <para>Initializes an instance of the <see cref="RouteAttribute"/> class.</para>
- /// </summary>
- /// <param name="path">
- /// <para>The path template to map to the request. See
- /// <see cref="Path">RouteAttribute.Path</see>
- /// for details on the correct format.</para>
- /// </param>
- public RouteAttribute(string path)
- : this(path, null)
- {
- }
-
- /// <summary>
- /// <para>Initializes an instance of the <see cref="RouteAttribute"/> class.</para>
- /// </summary>
- /// <param name="path">
- /// <para>The path template to map to the request. See
- /// <see cref="Path">RouteAttribute.Path</see>
- /// for details on the correct format.</para>
- /// </param>
- /// <param name="verbs">A comma-delimited list of HTTP verbs supported by the
- /// service. If unspecified, all verbs are assumed to be supported.</param>
- public RouteAttribute(string path, string verbs)
- {
- Path = path;
- Verbs = verbs;
- }
-
- /// <summary>
- /// Gets or sets the path template to be mapped to the request.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> value providing the path mapped to
- /// the request. Never <see langword="null"/>.
- /// </value>
- /// <remarks>
- /// <para>Some examples of valid paths are:</para>
- ///
- /// <list>
- /// <item>"/Inventory"</item>
- /// <item>"/Inventory/{Category}/{ItemId}"</item>
- /// <item>"/Inventory/{ItemPath*}"</item>
- /// </list>
- ///
- /// <para>Variables are specified within "{}"
- /// brackets. Each variable in the path is mapped to the same-named property
- /// on the request DTO. At runtime, ServiceStack will parse the
- /// request URL, extract the variable values, instantiate the request DTO,
- /// and assign the variable values into the corresponding request properties,
- /// prior to passing the request DTO to the service object for processing.</para>
- ///
- /// <para>It is not necessary to specify all request properties as
- /// variables in the path. For unspecified properties, callers may provide
- /// values in the query string. For example: the URL
- /// "http://services/Inventory?Category=Books&amp;ItemId=12345" causes the same
- /// request DTO to be processed as "http://services/Inventory/Books/12345",
- /// provided that the paths "/Inventory" (which supports the first URL) and
- /// "/Inventory/{Category}/{ItemId}" (which supports the second URL)
- /// are both mapped to the request DTO.</para>
- ///
- /// <para>Please note that while it is possible to specify property values
- /// in the query string, it is generally considered to be less RESTful and
- /// less desirable than to specify them as variables in the path. Using the
- /// query string to specify property values may also interfere with HTTP
- /// caching.</para>
- ///
- /// <para>The final variable in the path may contain a "*" suffix
- /// to grab all remaining segments in the path portion of the request URL and assign
- /// them to a single property on the request DTO.
- /// For example, if the path "/Inventory/{ItemPath*}" is mapped to the request DTO,
- /// then the request URL "http://services/Inventory/Books/12345" will result
- /// in a request DTO whose ItemPath property contains "Books/12345".
- /// You may only specify one such variable in the path, and it must be positioned at
- /// the end of the path.</para>
- /// </remarks>
- public string Path { get; set; }
-
- /// <summary>
- /// Gets or sets short summary of what the route does.
- /// </summary>
- public string Summary { get; set; }
-
- public string Description { get; set; }
-
- public bool IsHidden { get; set; }
-
- /// <summary>
- /// Gets or sets longer text to explain the behaviour of the route.
- /// </summary>
- public string Notes { get; set; }
-
- /// <summary>
- /// Gets or sets a comma-delimited list of HTTP verbs supported by the service, such as
- /// "GET,PUT,POST,DELETE".
- /// </summary>
- /// <value>
- /// A <see cref="String"/> providing a comma-delimited list of HTTP verbs supported
- /// by the service, <see langword="null"/> or empty if all verbs are supported.
- /// </value>
- public string Verbs { get; set; }
-
- /// <summary>
- /// Used to rank the precedences of route definitions in reverse routing.
- /// i.e. Priorities below 0 are auto-generated have less precedence.
- /// </summary>
- public int Priority { get; set; }
-
- protected bool Equals(RouteAttribute other)
- {
- return base.Equals(other)
- && string.Equals(Path, other.Path)
- && string.Equals(Summary, other.Summary)
- && string.Equals(Notes, other.Notes)
- && string.Equals(Verbs, other.Verbs)
- && Priority == other.Priority;
- }
-
- public override bool Equals(object obj)
- {
- if (ReferenceEquals(null, obj)) return false;
- if (ReferenceEquals(this, obj)) return true;
- if (obj.GetType() != this.GetType()) return false;
- return Equals((RouteAttribute)obj);
- }
-
- public override int GetHashCode()
- {
- unchecked
- {
- var hashCode = base.GetHashCode();
- hashCode = (hashCode * 397) ^ (Path != null ? Path.GetHashCode() : 0);
- hashCode = (hashCode * 397) ^ (Summary != null ? Summary.GetHashCode() : 0);
- hashCode = (hashCode * 397) ^ (Notes != null ? Notes.GetHashCode() : 0);
- hashCode = (hashCode * 397) ^ (Verbs != null ? Verbs.GetHashCode() : 0);
- hashCode = (hashCode * 397) ^ Priority;
- return hashCode;
- }
- }
- }
-}
diff --git a/MediaBrowser.Model/Session/BrowseRequest.cs b/MediaBrowser.Model/Session/BrowseRequest.cs
index 65d58501b..65afe5cf3 100644
--- a/MediaBrowser.Model/Session/BrowseRequest.cs
+++ b/MediaBrowser.Model/Session/BrowseRequest.cs
@@ -1,12 +1,14 @@
+#nullable disable
namespace MediaBrowser.Model.Session
{
/// <summary>
- /// Class BrowseRequest
+ /// Class BrowseRequest.
/// </summary>
public class BrowseRequest
{
/// <summary>
- /// Artist, Genre, Studio, Person, or any kind of BaseItem
+ /// Gets or sets the item type.
+ /// Artist, Genre, Studio, Person, or any kind of BaseItem.
/// </summary>
/// <value>The type of the item.</value>
public string ItemType { get; set; }
diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs
index fa74efb1b..d692906c6 100644
--- a/MediaBrowser.Model/Session/ClientCapabilities.cs
+++ b/MediaBrowser.Model/Session/ClientCapabilities.cs
@@ -1,31 +1,39 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dlna;
namespace MediaBrowser.Model.Session
{
public class ClientCapabilities
{
- public string[] PlayableMediaTypes { get; set; }
+ public ClientCapabilities()
+ {
+ PlayableMediaTypes = Array.Empty<string>();
+ SupportedCommands = Array.Empty<GeneralCommandType>();
+ SupportsPersistentIdentifier = true;
+ }
+
+ public IReadOnlyList<string> PlayableMediaTypes { get; set; }
- public string[] SupportedCommands { get; set; }
+ public IReadOnlyList<GeneralCommandType> SupportedCommands { get; set; }
public bool SupportsMediaControl { get; set; }
+
public bool SupportsContentUploading { get; set; }
+
public string MessageCallbackUrl { get; set; }
public bool SupportsPersistentIdentifier { get; set; }
+
public bool SupportsSync { get; set; }
public DeviceProfile DeviceProfile { get; set; }
public string AppStoreUrl { get; set; }
- public string IconUrl { get; set; }
- public ClientCapabilities()
- {
- PlayableMediaTypes = Array.Empty<string>();
- SupportedCommands = Array.Empty<string>();
- SupportsPersistentIdentifier = true;
- }
+ public string IconUrl { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/GeneralCommand.cs b/MediaBrowser.Model/Session/GeneralCommand.cs
index 74e58e678..29528c110 100644
--- a/MediaBrowser.Model/Session/GeneralCommand.cs
+++ b/MediaBrowser.Model/Session/GeneralCommand.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
@@ -5,15 +7,15 @@ namespace MediaBrowser.Model.Session
{
public class GeneralCommand
{
- public string Name { get; set; }
-
- public Guid ControllingUserId { get; set; }
-
- public Dictionary<string, string> Arguments { get; set; }
-
public GeneralCommand()
{
Arguments = new Dictionary<string, string>();
}
+
+ public GeneralCommandType Name { get; set; }
+
+ public Guid ControllingUserId { get; set; }
+
+ public Dictionary<string, string> Arguments { get; }
}
}
diff --git a/MediaBrowser.Model/Session/GeneralCommandType.cs b/MediaBrowser.Model/Session/GeneralCommandType.cs
index 4bb0c5cc5..c58fa9a6b 100644
--- a/MediaBrowser.Model/Session/GeneralCommandType.cs
+++ b/MediaBrowser.Model/Session/GeneralCommandType.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Session
{
/// <summary>
@@ -41,6 +43,11 @@ namespace MediaBrowser.Model.Session
Guide = 32,
ToggleStats = 33,
PlayMediaSource = 34,
- PlayTrailers = 35
+ PlayTrailers = 35,
+ SetShuffleQueue = 36,
+ PlayState = 37,
+ PlayNext = 38,
+ ToggleOsdMenu = 39,
+ Play = 40
}
}
diff --git a/MediaBrowser.Model/Session/HardwareEncodingType.cs b/MediaBrowser.Model/Session/HardwareEncodingType.cs
new file mode 100644
index 000000000..0e172f35f
--- /dev/null
+++ b/MediaBrowser.Model/Session/HardwareEncodingType.cs
@@ -0,0 +1,48 @@
+namespace MediaBrowser.Model.Session
+{
+ /// <summary>
+ /// Enum HardwareEncodingType.
+ /// </summary>
+ public enum HardwareEncodingType
+ {
+ /// <summary>
+ /// AMD AMF
+ /// </summary>
+ AMF = 0,
+
+ /// <summary>
+ /// Intel Quick Sync Video
+ /// </summary>
+ QSV = 1,
+
+ /// <summary>
+ /// NVIDIA NVENC
+ /// </summary>
+ NVENC = 2,
+
+ /// <summary>
+ /// OpenMax OMX
+ /// </summary>
+ OMX = 3,
+
+ /// <summary>
+ /// Exynos V4L2 MFC
+ /// </summary>
+ V4L2M2M = 4,
+
+ /// <summary>
+ /// MediaCodec Android
+ /// </summary>
+ MediaCodec = 5,
+
+ /// <summary>
+ /// Video Acceleration API (VAAPI)
+ /// </summary>
+ VAAPI = 6,
+
+ /// <summary>
+ /// Video ToolBox
+ /// </summary>
+ VideoToolBox = 7
+ }
+}
diff --git a/MediaBrowser.Model/Session/MessageCommand.cs b/MediaBrowser.Model/Session/MessageCommand.cs
index 1e558ef07..cc9db8e6c 100644
--- a/MediaBrowser.Model/Session/MessageCommand.cs
+++ b/MediaBrowser.Model/Session/MessageCommand.cs
@@ -1,9 +1,15 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System.ComponentModel.DataAnnotations;
+
namespace MediaBrowser.Model.Session
{
public class MessageCommand
{
public string Header { get; set; }
+ [Required(AllowEmptyStrings = false)]
public string Text { get; set; }
public long? TimeoutMs { get; set; }
diff --git a/MediaBrowser.Model/Session/PlayCommand.cs b/MediaBrowser.Model/Session/PlayCommand.cs
index b7a8f39ba..3ab049320 100644
--- a/MediaBrowser.Model/Session/PlayCommand.cs
+++ b/MediaBrowser.Model/Session/PlayCommand.cs
@@ -1,28 +1,32 @@
namespace MediaBrowser.Model.Session
{
/// <summary>
- /// Enum PlayCommand
+ /// Enum PlayCommand.
/// </summary>
public enum PlayCommand
{
/// <summary>
- /// The play now
+ /// The play now.
/// </summary>
PlayNow = 0,
+
/// <summary>
- /// The play next
+ /// The play next.
/// </summary>
PlayNext = 1,
+
/// <summary>
- /// The play last
+ /// The play last.
/// </summary>
PlayLast = 2,
+
/// <summary>
- /// The play instant mix
+ /// The play instant mix.
/// </summary>
PlayInstantMix = 3,
+
/// <summary>
- /// The play shuffle
+ /// The play shuffle.
/// </summary>
PlayShuffle = 4
}
diff --git a/MediaBrowser.Model/Session/PlayMethod.cs b/MediaBrowser.Model/Session/PlayMethod.cs
index 8daf8c953..806762784 100644
--- a/MediaBrowser.Model/Session/PlayMethod.cs
+++ b/MediaBrowser.Model/Session/PlayMethod.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Session
{
public enum PlayMethod
diff --git a/MediaBrowser.Model/Session/PlayRequest.cs b/MediaBrowser.Model/Session/PlayRequest.cs
index 075ae7730..6a66465a2 100644
--- a/MediaBrowser.Model/Session/PlayRequest.cs
+++ b/MediaBrowser.Model/Session/PlayRequest.cs
@@ -1,10 +1,12 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
-using MediaBrowser.Model.Services;
namespace MediaBrowser.Model.Session
{
/// <summary>
- /// Class PlayRequest
+ /// Class PlayRequest.
/// </summary>
public class PlayRequest
{
@@ -12,21 +14,18 @@ namespace MediaBrowser.Model.Session
/// Gets or sets the item ids.
/// </summary>
/// <value>The item ids.</value>
- [ApiMember(Name = "ItemIds", Description = "The ids of the items to play, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
public Guid[] ItemIds { get; set; }
/// <summary>
- /// Gets or sets the start position ticks that the first item should be played at
+ /// Gets or sets the start position ticks that the first item should be played at.
/// </summary>
/// <value>The start position ticks.</value>
- [ApiMember(Name = "StartPositionTicks", Description = "The starting position of the first item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public long? StartPositionTicks { get; set; }
/// <summary>
/// Gets or sets the play command.
/// </summary>
/// <value>The play command.</value>
- [ApiMember(Name = "PlayCommand", Description = "The type of play command to issue (PlayNow, PlayNext, PlayLast). Clients who have not yet implemented play next and play last may play now.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public PlayCommand PlayCommand { get; set; }
/// <summary>
@@ -36,8 +35,11 @@ namespace MediaBrowser.Model.Session
public Guid ControllingUserId { get; set; }
public int? SubtitleStreamIndex { get; set; }
+
public int? AudioStreamIndex { get; set; }
+
public string MediaSourceId { get; set; }
+
public int? StartIndex { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
index c1d630671..a6e7efcb0 100644
--- a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
+++ b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dto;
@@ -85,16 +88,19 @@ namespace MediaBrowser.Model.Session
/// </summary>
/// <value>The play method.</value>
public PlayMethod PlayMethod { get; set; }
+
/// <summary>
/// Gets or sets the live stream identifier.
/// </summary>
/// <value>The live stream identifier.</value>
public string LiveStreamId { get; set; }
+
/// <summary>
/// Gets or sets the play session identifier.
/// </summary>
/// <value>The play session identifier.</value>
public string PlaySessionId { get; set; }
+
/// <summary>
/// Gets or sets the repeat mode.
/// </summary>
@@ -102,19 +108,7 @@ namespace MediaBrowser.Model.Session
public RepeatMode RepeatMode { get; set; }
public QueueItem[] NowPlayingQueue { get; set; }
- public string PlaylistItemId { get; set; }
- }
- public enum RepeatMode
- {
- RepeatNone = 0,
- RepeatAll = 1,
- RepeatOne = 2
- }
-
- public class QueueItem
- {
- public Guid Id { get; set; }
public string PlaylistItemId { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/PlaybackStopInfo.cs b/MediaBrowser.Model/Session/PlaybackStopInfo.cs
index 8a85b1998..aa29bb249 100644
--- a/MediaBrowser.Model/Session/PlaybackStopInfo.cs
+++ b/MediaBrowser.Model/Session/PlaybackStopInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Model.Dto;
@@ -13,36 +16,43 @@ namespace MediaBrowser.Model.Session
/// </summary>
/// <value>The item.</value>
public BaseItemDto Item { get; set; }
+
/// <summary>
/// Gets or sets the item identifier.
/// </summary>
/// <value>The item identifier.</value>
public Guid ItemId { get; set; }
+
/// <summary>
/// Gets or sets the session id.
/// </summary>
/// <value>The session id.</value>
public string SessionId { get; set; }
+
/// <summary>
/// Gets or sets the media version identifier.
/// </summary>
/// <value>The media version identifier.</value>
public string MediaSourceId { get; set; }
+
/// <summary>
/// Gets or sets the position ticks.
/// </summary>
/// <value>The position ticks.</value>
public long? PositionTicks { get; set; }
+
/// <summary>
/// Gets or sets the live stream identifier.
/// </summary>
/// <value>The live stream identifier.</value>
public string LiveStreamId { get; set; }
+
/// <summary>
/// Gets or sets the play session identifier.
/// </summary>
/// <value>The play session identifier.</value>
public string PlaySessionId { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PlaybackStopInfo"/> is failed.
/// </summary>
@@ -52,6 +62,7 @@ namespace MediaBrowser.Model.Session
public string NextMediaType { get; set; }
public string PlaylistItemId { get; set; }
+
public QueueItem[] NowPlayingQueue { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/PlayerStateInfo.cs b/MediaBrowser.Model/Session/PlayerStateInfo.cs
index 7e54e16c8..0f10605ea 100644
--- a/MediaBrowser.Model/Session/PlayerStateInfo.cs
+++ b/MediaBrowser.Model/Session/PlayerStateInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Session
{
public class PlayerStateInfo
diff --git a/MediaBrowser.Model/Session/PlaystateCommand.cs b/MediaBrowser.Model/Session/PlaystateCommand.cs
index 6eb3e53c2..df47f3b73 100644
--- a/MediaBrowser.Model/Session/PlaystateCommand.cs
+++ b/MediaBrowser.Model/Session/PlaystateCommand.cs
@@ -1,42 +1,53 @@
namespace MediaBrowser.Model.Session
{
/// <summary>
- /// Enum PlaystateCommand
+ /// Enum PlaystateCommand.
/// </summary>
public enum PlaystateCommand
{
/// <summary>
- /// The stop
+ /// The stop.
/// </summary>
Stop,
+
/// <summary>
- /// The pause
+ /// The pause.
/// </summary>
Pause,
+
/// <summary>
- /// The unpause
+ /// The unpause.
/// </summary>
Unpause,
+
/// <summary>
- /// The next track
+ /// The next track.
/// </summary>
NextTrack,
+
/// <summary>
- /// The previous track
+ /// The previous track.
/// </summary>
PreviousTrack,
+
/// <summary>
- /// The seek
+ /// The seek.
/// </summary>
Seek,
+
/// <summary>
- /// The rewind
+ /// The rewind.
/// </summary>
Rewind,
+
/// <summary>
- /// The fast forward
+ /// The fast forward.
/// </summary>
FastForward,
+
+ /// <summary>
+ /// The play pause.
+ /// </summary>
PlayPause
}
}
diff --git a/MediaBrowser.Model/Session/PlaystateRequest.cs b/MediaBrowser.Model/Session/PlaystateRequest.cs
index 08d3f0072..ba2c024b7 100644
--- a/MediaBrowser.Model/Session/PlaystateRequest.cs
+++ b/MediaBrowser.Model/Session/PlaystateRequest.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Session
{
public class PlaystateRequest
@@ -10,6 +12,6 @@ namespace MediaBrowser.Model.Session
/// Gets or sets the controlling user identifier.
/// </summary>
/// <value>The controlling user identifier.</value>
- public string ControllingUserId { get; set; }
+ public string? ControllingUserId { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/QueueItem.cs b/MediaBrowser.Model/Session/QueueItem.cs
new file mode 100644
index 000000000..32b19101b
--- /dev/null
+++ b/MediaBrowser.Model/Session/QueueItem.cs
@@ -0,0 +1,14 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+
+namespace MediaBrowser.Model.Session
+{
+ public class QueueItem
+ {
+ public Guid Id { get; set; }
+
+ public string PlaylistItemId { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Session/RepeatMode.cs b/MediaBrowser.Model/Session/RepeatMode.cs
new file mode 100644
index 000000000..c6e173d6b
--- /dev/null
+++ b/MediaBrowser.Model/Session/RepeatMode.cs
@@ -0,0 +1,11 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Session
+{
+ public enum RepeatMode
+ {
+ RepeatNone = 0,
+ RepeatAll = 1,
+ RepeatOne = 2
+ }
+}
diff --git a/MediaBrowser.Model/Session/SessionMessageType.cs b/MediaBrowser.Model/Session/SessionMessageType.cs
new file mode 100644
index 000000000..84f4716b4
--- /dev/null
+++ b/MediaBrowser.Model/Session/SessionMessageType.cs
@@ -0,0 +1,50 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Session
+{
+ /// <summary>
+ /// The different kinds of messages that are used in the WebSocket api.
+ /// </summary>
+ public enum SessionMessageType
+ {
+ // Server -> Client
+ ForceKeepAlive,
+ GeneralCommand,
+ UserDataChanged,
+ Sessions,
+ Play,
+ SyncPlayCommand,
+ SyncPlayGroupUpdate,
+ Playstate,
+ RestartRequired,
+ ServerShuttingDown,
+ ServerRestarting,
+ LibraryChanged,
+ UserDeleted,
+ UserUpdated,
+ SeriesTimerCreated,
+ TimerCreated,
+ SeriesTimerCancelled,
+ TimerCancelled,
+ RefreshProgress,
+ ScheduledTaskEnded,
+ PackageInstallationCancelled,
+ PackageInstallationFailed,
+ PackageInstallationCompleted,
+ PackageInstalling,
+ PackageUninstalled,
+ ActivityLogEntry,
+ ScheduledTasksInfo,
+
+ // Client -> Server
+ ActivityLogEntryStart,
+ ActivityLogEntryStop,
+ SessionsStart,
+ SessionsStop,
+ ScheduledTasksInfoStart,
+ ScheduledTasksInfoStop,
+
+ // Shared
+ KeepAlive,
+ }
+}
diff --git a/MediaBrowser.Model/Session/SessionUserInfo.cs b/MediaBrowser.Model/Session/SessionUserInfo.cs
index 42a56b92b..4d6f35efc 100644
--- a/MediaBrowser.Model/Session/SessionUserInfo.cs
+++ b/MediaBrowser.Model/Session/SessionUserInfo.cs
@@ -1,3 +1,4 @@
+#nullable disable
using System;
namespace MediaBrowser.Model.Session
@@ -12,6 +13,7 @@ namespace MediaBrowser.Model.Session
/// </summary>
/// <value>The user identifier.</value>
public Guid UserId { get; set; }
+
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
diff --git a/MediaBrowser.Model/Session/TranscodeReason.cs b/MediaBrowser.Model/Session/TranscodeReason.cs
new file mode 100644
index 000000000..e93b5d288
--- /dev/null
+++ b/MediaBrowser.Model/Session/TranscodeReason.cs
@@ -0,0 +1,31 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Session
+{
+ public enum TranscodeReason
+ {
+ ContainerNotSupported = 0,
+ VideoCodecNotSupported = 1,
+ AudioCodecNotSupported = 2,
+ ContainerBitrateExceedsLimit = 3,
+ AudioBitrateNotSupported = 4,
+ AudioChannelsNotSupported = 5,
+ VideoResolutionNotSupported = 6,
+ UnknownVideoStreamInfo = 7,
+ UnknownAudioStreamInfo = 8,
+ AudioProfileNotSupported = 9,
+ AudioSampleRateNotSupported = 10,
+ AnamorphicVideoNotSupported = 11,
+ InterlacedVideoNotSupported = 12,
+ SecondaryAudioNotSupported = 13,
+ RefFramesNotSupported = 14,
+ VideoBitDepthNotSupported = 15,
+ VideoBitrateNotSupported = 16,
+ VideoFramerateNotSupported = 17,
+ VideoLevelNotSupported = 18,
+ VideoProfileNotSupported = 19,
+ AudioBitDepthNotSupported = 20,
+ SubtitleCodecNotSupported = 21,
+ DirectPlayError = 22
+ }
+}
diff --git a/MediaBrowser.Model/Session/TranscodingInfo.cs b/MediaBrowser.Model/Session/TranscodingInfo.cs
index 5161882fd..68ab691f8 100644
--- a/MediaBrowser.Model/Session/TranscodingInfo.cs
+++ b/MediaBrowser.Model/Session/TranscodingInfo.cs
@@ -1,53 +1,41 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+
namespace MediaBrowser.Model.Session
{
public class TranscodingInfo
{
+ public TranscodingInfo()
+ {
+ TranscodeReasons = Array.Empty<TranscodeReason>();
+ }
+
public string AudioCodec { get; set; }
+
public string VideoCodec { get; set; }
+
public string Container { get; set; }
+
public bool IsVideoDirect { get; set; }
+
public bool IsAudioDirect { get; set; }
+
public int? Bitrate { get; set; }
public float? Framerate { get; set; }
+
public double? CompletionPercentage { get; set; }
public int? Width { get; set; }
+
public int? Height { get; set; }
+
public int? AudioChannels { get; set; }
- public TranscodeReason[] TranscodeReasons { get; set; }
+ public HardwareEncodingType? HardwareAccelerationType { get; set; }
- public TranscodingInfo()
- {
- TranscodeReasons = new TranscodeReason[] { };
- }
- }
-
- public enum TranscodeReason
- {
- ContainerNotSupported = 0,
- VideoCodecNotSupported = 1,
- AudioCodecNotSupported = 2,
- ContainerBitrateExceedsLimit = 3,
- AudioBitrateNotSupported = 4,
- AudioChannelsNotSupported = 5,
- VideoResolutionNotSupported = 6,
- UnknownVideoStreamInfo = 7,
- UnknownAudioStreamInfo = 8,
- AudioProfileNotSupported = 9,
- AudioSampleRateNotSupported = 10,
- AnamorphicVideoNotSupported = 11,
- InterlacedVideoNotSupported = 12,
- SecondaryAudioNotSupported = 13,
- RefFramesNotSupported = 14,
- VideoBitDepthNotSupported = 15,
- VideoBitrateNotSupported = 16,
- VideoFramerateNotSupported = 17,
- VideoLevelNotSupported = 18,
- VideoProfileNotSupported = 19,
- AudioBitDepthNotSupported = 20,
- SubtitleCodecNotSupported = 21,
- DirectPlayError = 22
+ public TranscodeReason[] TranscodeReasons { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/UserDataChangeInfo.cs b/MediaBrowser.Model/Session/UserDataChangeInfo.cs
index ef0e2c89a..0fd24edcc 100644
--- a/MediaBrowser.Model/Session/UserDataChangeInfo.cs
+++ b/MediaBrowser.Model/Session/UserDataChangeInfo.cs
@@ -1,9 +1,10 @@
+#nullable disable
using MediaBrowser.Model.Dto;
namespace MediaBrowser.Model.Session
{
/// <summary>
- /// Class UserDataChangeInfo
+ /// Class UserDataChangeInfo.
/// </summary>
public class UserDataChangeInfo
{
diff --git a/MediaBrowser.Model/Subtitles/FontFile.cs b/MediaBrowser.Model/Subtitles/FontFile.cs
new file mode 100644
index 000000000..115c49295
--- /dev/null
+++ b/MediaBrowser.Model/Subtitles/FontFile.cs
@@ -0,0 +1,34 @@
+using System;
+
+namespace MediaBrowser.Model.Subtitles
+{
+ /// <summary>
+ /// Class FontFile.
+ /// </summary>
+ public class FontFile
+ {
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the size.
+ /// </summary>
+ /// <value>The size.</value>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date created.
+ /// </summary>
+ /// <value>The date created.</value>
+ public DateTime DateCreated { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date modified.
+ /// </summary>
+ /// <value>The date modified.</value>
+ public DateTime DateModified { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Sync/SyncCategory.cs b/MediaBrowser.Model/Sync/SyncCategory.cs
deleted file mode 100644
index 637c5ba74..000000000
--- a/MediaBrowser.Model/Sync/SyncCategory.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace MediaBrowser.Model.Sync
-{
- public enum SyncCategory
- {
- /// <summary>
- /// The latest
- /// </summary>
- Latest = 0,
- /// <summary>
- /// The next up
- /// </summary>
- NextUp = 1,
- /// <summary>
- /// The resume
- /// </summary>
- Resume = 2
- }
-}
diff --git a/MediaBrowser.Model/Sync/SyncJob.cs b/MediaBrowser.Model/Sync/SyncJob.cs
deleted file mode 100644
index 7a1f76fe9..000000000
--- a/MediaBrowser.Model/Sync/SyncJob.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Sync
-{
- public class SyncJob
- {
- /// <summary>
- /// Gets or sets the identifier.
- /// </summary>
- /// <value>The identifier.</value>
- public string Id { get; set; }
- /// <summary>
- /// Gets or sets the device identifier.
- /// </summary>
- /// <value>The device identifier.</value>
- public string TargetId { get; set; }
- /// <summary>
- /// Gets or sets the name of the target.
- /// </summary>
- /// <value>The name of the target.</value>
- public string TargetName { get; set; }
- /// <summary>
- /// Gets or sets the quality.
- /// </summary>
- /// <value>The quality.</value>
- public string Quality { get; set; }
- /// <summary>
- /// Gets or sets the bitrate.
- /// </summary>
- /// <value>The bitrate.</value>
- public int? Bitrate { get; set; }
- /// <summary>
- /// Gets or sets the profile.
- /// </summary>
- /// <value>The profile.</value>
- public string Profile { get; set; }
- /// <summary>
- /// Gets or sets the category.
- /// </summary>
- /// <value>The category.</value>
- public SyncCategory? Category { get; set; }
- /// <summary>
- /// Gets or sets the parent identifier.
- /// </summary>
- /// <value>The parent identifier.</value>
- public string ParentId { get; set; }
- /// <summary>
- /// Gets or sets the current progress.
- /// </summary>
- /// <value>The current progress.</value>
- public double? Progress { get; set; }
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets the status.
- /// </summary>
- /// <value>The status.</value>
- public SyncJobStatus Status { get; set; }
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether [unwatched only].
- /// </summary>
- /// <value><c>true</c> if [unwatched only]; otherwise, <c>false</c>.</value>
- public bool UnwatchedOnly { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether [synchronize new content].
- /// </summary>
- /// <value><c>true</c> if [synchronize new content]; otherwise, <c>false</c>.</value>
- public bool SyncNewContent { get; set; }
- /// <summary>
- /// Gets or sets the item limit.
- /// </summary>
- /// <value>The item limit.</value>
- public int? ItemLimit { get; set; }
- /// <summary>
- /// Gets or sets the requested item ids.
- /// </summary>
- /// <value>The requested item ids.</value>
- public Guid[] RequestedItemIds { get; set; }
- /// <summary>
- /// Gets or sets the date created.
- /// </summary>
- /// <value>The date created.</value>
- public DateTime DateCreated { get; set; }
- /// <summary>
- /// Gets or sets the date last modified.
- /// </summary>
- /// <value>The date last modified.</value>
- public DateTime DateLastModified { get; set; }
- /// <summary>
- /// Gets or sets the item count.
- /// </summary>
- /// <value>The item count.</value>
- public int ItemCount { get; set; }
-
- public string ParentName { get; set; }
- public string PrimaryImageItemId { get; set; }
- public string PrimaryImageTag { get; set; }
-
- public SyncJob()
- {
- RequestedItemIds = Array.Empty<Guid>();
- }
- }
-}
diff --git a/MediaBrowser.Model/Sync/SyncJobStatus.cs b/MediaBrowser.Model/Sync/SyncJobStatus.cs
deleted file mode 100644
index 4ea3d3fa5..000000000
--- a/MediaBrowser.Model/Sync/SyncJobStatus.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace MediaBrowser.Model.Sync
-{
- public enum SyncJobStatus
- {
- Queued = 0,
- Converting = 1,
- ReadyToTransfer = 2,
- Transferring = 3,
- Completed = 4,
- CompletedWithError = 5,
- Failed = 6
- }
-}
diff --git a/MediaBrowser.Model/Sync/SyncTarget.cs b/MediaBrowser.Model/Sync/SyncTarget.cs
deleted file mode 100644
index a94bf9a25..000000000
--- a/MediaBrowser.Model/Sync/SyncTarget.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace MediaBrowser.Model.Sync
-{
- public class SyncTarget
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets the identifier.
- /// </summary>
- /// <value>The identifier.</value>
- public string Id { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs
new file mode 100644
index 000000000..8c0960b83
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs
@@ -0,0 +1,58 @@
+using System;
+using System.Collections.Generic;
+
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class GroupInfoDto.
+ /// </summary>
+ public class GroupInfoDto
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GroupInfoDto"/> class.
+ /// </summary>
+ /// <param name="groupId">The group identifier.</param>
+ /// <param name="groupName">The group name.</param>
+ /// <param name="state">The group state.</param>
+ /// <param name="participants">The participants.</param>
+ /// <param name="lastUpdatedAt">The date when this DTO has been created.</param>
+ public GroupInfoDto(Guid groupId, string groupName, GroupStateType state, IReadOnlyList<string> participants, DateTime lastUpdatedAt)
+ {
+ GroupId = groupId;
+ GroupName = groupName;
+ State = state;
+ Participants = participants;
+ LastUpdatedAt = lastUpdatedAt;
+ }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ public Guid GroupId { get; }
+
+ /// <summary>
+ /// Gets the group name.
+ /// </summary>
+ /// <value>The group name.</value>
+ public string GroupName { get; }
+
+ /// <summary>
+ /// Gets the group state.
+ /// </summary>
+ /// <value>The group state.</value>
+ public GroupStateType State { get; }
+
+ /// <summary>
+ /// Gets the participants.
+ /// </summary>
+ /// <value>The participants.</value>
+ public IReadOnlyList<string> Participants { get; }
+
+ /// <summary>
+ /// Gets the date when this DTO has been created.
+ /// </summary>
+ /// <value>The date when this DTO has been created.</value>
+ public DateTime LastUpdatedAt { get; }
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs b/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs
new file mode 100644
index 000000000..5c9c2627b
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum GroupQueueMode.
+ /// </summary>
+ public enum GroupQueueMode
+ {
+ /// <summary>
+ /// Insert items at the end of the queue.
+ /// </summary>
+ Queue = 0,
+
+ /// <summary>
+ /// Insert items after the currently playing item.
+ /// </summary>
+ QueueNext = 1
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs b/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs
new file mode 100644
index 000000000..4895e57b7
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs
@@ -0,0 +1,23 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum GroupRepeatMode.
+ /// </summary>
+ public enum GroupRepeatMode
+ {
+ /// <summary>
+ /// Repeat one item only.
+ /// </summary>
+ RepeatOne = 0,
+
+ /// <summary>
+ /// Cycle the playlist.
+ /// </summary>
+ RepeatAll = 1,
+
+ /// <summary>
+ /// Do not repeat.
+ /// </summary>
+ RepeatNone = 2
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs b/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs
new file mode 100644
index 000000000..de860883c
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs
@@ -0,0 +1,18 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum GroupShuffleMode.
+ /// </summary>
+ public enum GroupShuffleMode
+ {
+ /// <summary>
+ /// Sorted playlist.
+ /// </summary>
+ Sorted = 0,
+
+ /// <summary>
+ /// Shuffled playlist.
+ /// </summary>
+ Shuffle = 1
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupStateType.cs b/MediaBrowser.Model/SyncPlay/GroupStateType.cs
new file mode 100644
index 000000000..7aa454f92
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupStateType.cs
@@ -0,0 +1,28 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum GroupState.
+ /// </summary>
+ public enum GroupStateType
+ {
+ /// <summary>
+ /// The group is in idle state. No media is playing.
+ /// </summary>
+ Idle = 0,
+
+ /// <summary>
+ /// The group is in wating state. Playback is paused. Will start playing when users are ready.
+ /// </summary>
+ Waiting = 1,
+
+ /// <summary>
+ /// The group is in paused state. Playback is paused. Will resume on play command.
+ /// </summary>
+ Paused = 2,
+
+ /// <summary>
+ /// The group is in playing state. Playback is advancing.
+ /// </summary>
+ Playing = 3
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs
new file mode 100644
index 000000000..7f7deb86b
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs
@@ -0,0 +1,31 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class GroupStateUpdate.
+ /// </summary>
+ public class GroupStateUpdate
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GroupStateUpdate"/> class.
+ /// </summary>
+ /// <param name="state">The state of the group.</param>
+ /// <param name="reason">The reason of the state change.</param>
+ public GroupStateUpdate(GroupStateType state, PlaybackRequestType reason)
+ {
+ State = state;
+ Reason = reason;
+ }
+
+ /// <summary>
+ /// Gets the state of the group.
+ /// </summary>
+ /// <value>The state of the group.</value>
+ public GroupStateType State { get; }
+
+ /// <summary>
+ /// Gets the reason of the state change.
+ /// </summary>
+ /// <value>The reason of the state change.</value>
+ public PlaybackRequestType Reason { get; }
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
new file mode 100644
index 000000000..6f159d653
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
@@ -0,0 +1,42 @@
+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>
+ {
+ /// <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)
+ {
+ GroupId = groupId;
+ Type = type;
+ Data = data;
+ }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ public Guid GroupId { get; }
+
+ /// <summary>
+ /// Gets the update type.
+ /// </summary>
+ /// <value>The update type.</value>
+ public GroupUpdateType Type { get; }
+
+ /// <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
new file mode 100644
index 000000000..907d1defe
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs
@@ -0,0 +1,63 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum GroupUpdateType.
+ /// </summary>
+ public enum GroupUpdateType
+ {
+ /// <summary>
+ /// The user-joined update. Tells members of a group about a new user.
+ /// </summary>
+ UserJoined,
+
+ /// <summary>
+ /// The user-left update. Tells members of a group that a user left.
+ /// </summary>
+ UserLeft,
+
+ /// <summary>
+ /// The group-joined update. Tells a user that the group has been joined.
+ /// </summary>
+ GroupJoined,
+
+ /// <summary>
+ /// The group-left update. Tells a user that the group has been left.
+ /// </summary>
+ GroupLeft,
+
+ /// <summary>
+ /// The group-state update. Tells members of the group that the state changed.
+ /// </summary>
+ StateUpdate,
+
+ /// <summary>
+ /// The play-queue update. Tells a user the playing queue of the group.
+ /// </summary>
+ PlayQueue,
+
+ /// <summary>
+ /// The not-in-group error. Tells a user that they don't belong to a group.
+ /// </summary>
+ NotInGroup,
+
+ /// <summary>
+ /// The group-does-not-exist error. Sent when trying to join a non-existing group.
+ /// </summary>
+ 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/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs
new file mode 100644
index 000000000..cce99c77d
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class PlayQueueUpdate.
+ /// </summary>
+ public class PlayQueueUpdate
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlayQueueUpdate"/> class.
+ /// </summary>
+ /// <param name="reason">The reason for the update.</param>
+ /// <param name="lastUpdate">The UTC time of the last change to the playing queue.</param>
+ /// <param name="playlist">The playlist.</param>
+ /// <param name="playingItemIndex">The playing item index in the playlist.</param>
+ /// <param name="startPositionTicks">The start position ticks.</param>
+ /// <param name="isPlaying">The playing item status.</param>
+ /// <param name="shuffleMode">The shuffle mode.</param>
+ /// <param name="repeatMode">The repeat mode.</param>
+ public PlayQueueUpdate(PlayQueueUpdateReason reason, DateTime lastUpdate, IReadOnlyList<QueueItem> playlist, int playingItemIndex, long startPositionTicks, bool isPlaying, GroupShuffleMode shuffleMode, GroupRepeatMode repeatMode)
+ {
+ Reason = reason;
+ LastUpdate = lastUpdate;
+ Playlist = playlist;
+ PlayingItemIndex = playingItemIndex;
+ StartPositionTicks = startPositionTicks;
+ IsPlaying = isPlaying;
+ ShuffleMode = shuffleMode;
+ RepeatMode = repeatMode;
+ }
+
+ /// <summary>
+ /// Gets the request type that originated this update.
+ /// </summary>
+ /// <value>The reason for the update.</value>
+ public PlayQueueUpdateReason Reason { get; }
+
+ /// <summary>
+ /// Gets the UTC time of the last change to the playing queue.
+ /// </summary>
+ /// <value>The UTC time of the last change to the playing queue.</value>
+ public DateTime LastUpdate { get; }
+
+ /// <summary>
+ /// Gets the playlist.
+ /// </summary>
+ /// <value>The playlist.</value>
+ public IReadOnlyList<QueueItem> Playlist { get; }
+
+ /// <summary>
+ /// Gets the playing item index in the playlist.
+ /// </summary>
+ /// <value>The playing item index in the playlist.</value>
+ public int PlayingItemIndex { get; }
+
+ /// <summary>
+ /// Gets the start position ticks.
+ /// </summary>
+ /// <value>The start position ticks.</value>
+ public long StartPositionTicks { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the current item is playing.
+ /// </summary>
+ /// <value>The playing item status.</value>
+ public bool IsPlaying { get; }
+
+ /// <summary>
+ /// Gets the shuffle mode.
+ /// </summary>
+ /// <value>The shuffle mode.</value>
+ public GroupShuffleMode ShuffleMode { get; }
+
+ /// <summary>
+ /// Gets the repeat mode.
+ /// </summary>
+ /// <value>The repeat mode.</value>
+ public GroupRepeatMode RepeatMode { get; }
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs
new file mode 100644
index 000000000..b609f4b1b
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs
@@ -0,0 +1,58 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum PlayQueueUpdateReason.
+ /// </summary>
+ public enum PlayQueueUpdateReason
+ {
+ /// <summary>
+ /// A user is requesting to play a new playlist.
+ /// </summary>
+ NewPlaylist = 0,
+
+ /// <summary>
+ /// A user is changing the playing item.
+ /// </summary>
+ SetCurrentItem = 1,
+
+ /// <summary>
+ /// A user is removing items from the playlist.
+ /// </summary>
+ RemoveItems = 2,
+
+ /// <summary>
+ /// A user is moving an item in the playlist.
+ /// </summary>
+ MoveItem = 3,
+
+ /// <summary>
+ /// A user is adding items the queue.
+ /// </summary>
+ Queue = 4,
+
+ /// <summary>
+ /// A user is adding items to the queue, after the currently playing item.
+ /// </summary>
+ QueueNext = 5,
+
+ /// <summary>
+ /// A user is requesting the next item in queue.
+ /// </summary>
+ NextItem = 6,
+
+ /// <summary>
+ /// A user is requesting the previous item in queue.
+ /// </summary>
+ PreviousItem = 7,
+
+ /// <summary>
+ /// A user is changing repeat mode.
+ /// </summary>
+ RepeatMode = 8,
+
+ /// <summary>
+ /// A user is changing shuffle mode.
+ /// </summary>
+ ShuffleMode = 9
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs
new file mode 100644
index 000000000..4429623dd
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs
@@ -0,0 +1,93 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum PlaybackRequestType.
+ /// </summary>
+ public enum PlaybackRequestType
+ {
+ /// <summary>
+ /// A user is setting a new playlist.
+ /// </summary>
+ Play = 0,
+
+ /// <summary>
+ /// A user is changing the playlist item.
+ /// </summary>
+ SetPlaylistItem = 1,
+
+ /// <summary>
+ /// A user is removing items from the playlist.
+ /// </summary>
+ RemoveFromPlaylist = 2,
+
+ /// <summary>
+ /// A user is moving an item in the playlist.
+ /// </summary>
+ MovePlaylistItem = 3,
+
+ /// <summary>
+ /// A user is adding items to the playlist.
+ /// </summary>
+ Queue = 4,
+
+ /// <summary>
+ /// A user is requesting an unpause command for the group.
+ /// </summary>
+ Unpause = 5,
+
+ /// <summary>
+ /// A user is requesting a pause command for the group.
+ /// </summary>
+ Pause = 6,
+
+ /// <summary>
+ /// A user is requesting a stop command for the group.
+ /// </summary>
+ Stop = 7,
+
+ /// <summary>
+ /// A user is requesting a seek command for the group.
+ /// </summary>
+ Seek = 8,
+
+ /// <summary>
+ /// A user is signaling that playback is buffering.
+ /// </summary>
+ Buffer = 9,
+
+ /// <summary>
+ /// A user is signaling that playback resumed.
+ /// </summary>
+ Ready = 10,
+
+ /// <summary>
+ /// A user is requesting next item in playlist.
+ /// </summary>
+ NextItem = 11,
+
+ /// <summary>
+ /// A user is requesting previous item in playlist.
+ /// </summary>
+ PreviousItem = 12,
+
+ /// <summary>
+ /// A user is setting the repeat mode.
+ /// </summary>
+ SetRepeatMode = 13,
+
+ /// <summary>
+ /// A user is setting the shuffle mode.
+ /// </summary>
+ SetShuffleMode = 14,
+
+ /// <summary>
+ /// A user is reporting their ping.
+ /// </summary>
+ Ping = 15,
+
+ /// <summary>
+ /// A user is requesting to be ignored on group wait.
+ /// </summary>
+ IgnoreWait = 16
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/QueueItem.cs
new file mode 100644
index 000000000..a6dcc109e
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/QueueItem.cs
@@ -0,0 +1,31 @@
+using System;
+
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class QueueItem.
+ /// </summary>
+ public class QueueItem
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="QueueItem"/> class.
+ /// </summary>
+ /// <param name="itemId">The item identifier.</param>
+ public QueueItem(Guid itemId)
+ {
+ ItemId = itemId;
+ }
+
+ /// <summary>
+ /// Gets the item identifier.
+ /// </summary>
+ /// <value>The item identifier.</value>
+ public Guid ItemId { get; }
+
+ /// <summary>
+ /// Gets the playlist identifier of the item.
+ /// </summary>
+ /// <value>The playlist identifier of the item.</value>
+ public Guid PlaylistItemId { get; } = Guid.NewGuid();
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/RequestType.cs b/MediaBrowser.Model/SyncPlay/RequestType.cs
new file mode 100644
index 000000000..a6e397dcd
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/RequestType.cs
@@ -0,0 +1,33 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum RequestType.
+ /// </summary>
+ public enum RequestType
+ {
+ /// <summary>
+ /// A user is requesting to create a new group.
+ /// </summary>
+ NewGroup = 0,
+
+ /// <summary>
+ /// A user is requesting to join a group.
+ /// </summary>
+ JoinGroup = 1,
+
+ /// <summary>
+ /// A user is requesting to leave a group.
+ /// </summary>
+ LeaveGroup = 2,
+
+ /// <summary>
+ /// A user is requesting the list of available groups.
+ /// </summary>
+ ListGroups = 3,
+
+ /// <summary>
+ /// A user is sending a playback command to a group.
+ /// </summary>
+ Playback = 4
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs
new file mode 100644
index 000000000..73cb50876
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs
@@ -0,0 +1,65 @@
+using System;
+
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class SendCommand.
+ /// </summary>
+ public class SendCommand
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SendCommand"/> class.
+ /// </summary>
+ /// <param name="groupId">The group identifier.</param>
+ /// <param name="playlistItemId">The playlist identifier of the playing item.</param>
+ /// <param name="when">The UTC time when to execute the command.</param>
+ /// <param name="command">The command.</param>
+ /// <param name="positionTicks">The position ticks, for commands that require it.</param>
+ /// <param name="emittedAt">The UTC time when this command has been emitted.</param>
+ public SendCommand(Guid groupId, Guid playlistItemId, DateTime when, SendCommandType command, long? positionTicks, DateTime emittedAt)
+ {
+ GroupId = groupId;
+ PlaylistItemId = playlistItemId;
+ When = when;
+ Command = command;
+ PositionTicks = positionTicks;
+ EmittedAt = emittedAt;
+ }
+
+ /// <summary>
+ /// Gets the group identifier.
+ /// </summary>
+ /// <value>The group identifier.</value>
+ public Guid GroupId { get; }
+
+ /// <summary>
+ /// Gets the playlist identifier of the playing item.
+ /// </summary>
+ /// <value>The playlist identifier of the playing item.</value>
+ public Guid PlaylistItemId { get; }
+
+ /// <summary>
+ /// Gets or sets the UTC time when to execute the command.
+ /// </summary>
+ /// <value>The UTC time when to execute the command.</value>
+ public DateTime When { get; set; }
+
+ /// <summary>
+ /// Gets the position ticks.
+ /// </summary>
+ /// <value>The position ticks.</value>
+ public long? PositionTicks { get; }
+
+ /// <summary>
+ /// Gets the command.
+ /// </summary>
+ /// <value>The command.</value>
+ public SendCommandType Command { get; }
+
+ /// <summary>
+ /// Gets the UTC time when this command has been emitted.
+ /// </summary>
+ /// <value>The UTC time when this command has been emitted.</value>
+ public DateTime EmittedAt { get; }
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/SendCommandType.cs b/MediaBrowser.Model/SyncPlay/SendCommandType.cs
new file mode 100644
index 000000000..e6b17c60a
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SendCommandType.cs
@@ -0,0 +1,28 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Enum SendCommandType.
+ /// </summary>
+ public enum SendCommandType
+ {
+ /// <summary>
+ /// The unpause command. Instructs users to unpause playback.
+ /// </summary>
+ Unpause = 0,
+
+ /// <summary>
+ /// The pause command. Instructs users to pause playback.
+ /// </summary>
+ Pause = 1,
+
+ /// <summary>
+ /// The stop command. Instructs users to stop playback.
+ /// </summary>
+ Stop = 2,
+
+ /// <summary>
+ /// The seek command. Instructs users to seek to a specified time.
+ /// </summary>
+ Seek = 3
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs b/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs
new file mode 100644
index 000000000..29dbb11b3
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs
@@ -0,0 +1,28 @@
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Used to filter the sessions of a group.
+ /// </summary>
+ public enum SyncPlayBroadcastType
+ {
+ /// <summary>
+ /// All sessions will receive the message.
+ /// </summary>
+ AllGroup = 0,
+
+ /// <summary>
+ /// Only the specified session will receive the message.
+ /// </summary>
+ CurrentSession = 1,
+
+ /// <summary>
+ /// All sessions, except the current one, will receive the message.
+ /// </summary>
+ AllExceptCurrentSession = 2,
+
+ /// <summary>
+ /// Only sessions that are not buffering will receive the message.
+ /// </summary>
+ AllReady = 3
+ }
+}
diff --git a/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs b/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs
new file mode 100644
index 000000000..219e7b1e0
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs
@@ -0,0 +1,33 @@
+using System;
+
+namespace MediaBrowser.Model.SyncPlay
+{
+ /// <summary>
+ /// Class UtcTimeResponse.
+ /// </summary>
+ public class UtcTimeResponse
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UtcTimeResponse"/> class.
+ /// </summary>
+ /// <param name="requestReceptionTime">The UTC time when request has been received.</param>
+ /// <param name="responseTransmissionTime">The UTC time when response has been sent.</param>
+ public UtcTimeResponse(DateTime requestReceptionTime, DateTime responseTransmissionTime)
+ {
+ RequestReceptionTime = requestReceptionTime;
+ ResponseTransmissionTime = responseTransmissionTime;
+ }
+
+ /// <summary>
+ /// Gets the UTC time when request has been received.
+ /// </summary>
+ /// <value>The UTC time when request has been received.</value>
+ public DateTime RequestReceptionTime { get; }
+
+ /// <summary>
+ /// Gets the UTC time when response has been sent.
+ /// </summary>
+ /// <value>The UTC time when response has been sent.</value>
+ public DateTime ResponseTransmissionTime { get; }
+ }
+}
diff --git a/MediaBrowser.Model/System/IEnvironmentInfo.cs b/MediaBrowser.Model/System/IEnvironmentInfo.cs
deleted file mode 100644
index 3ffcc7de1..000000000
--- a/MediaBrowser.Model/System/IEnvironmentInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace MediaBrowser.Model.System
-{
- public interface IEnvironmentInfo
- {
- OperatingSystem OperatingSystem { get; }
- string OperatingSystemName { get; }
- string OperatingSystemVersion { get; }
- Architecture SystemArchitecture { get; }
- }
-
- public enum OperatingSystem
- {
- Windows,
- Linux,
- OSX,
- BSD,
- Android
- }
-}
diff --git a/MediaBrowser.Model/System/LogFile.cs b/MediaBrowser.Model/System/LogFile.cs
index 913e8e1ea..aec910c92 100644
--- a/MediaBrowser.Model/System/LogFile.cs
+++ b/MediaBrowser.Model/System/LogFile.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.System
diff --git a/MediaBrowser.Model/System/OperatingSystemId.cs b/MediaBrowser.Model/System/OperatingSystemId.cs
new file mode 100644
index 000000000..2e417f6b5
--- /dev/null
+++ b/MediaBrowser.Model/System/OperatingSystemId.cs
@@ -0,0 +1,12 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.System
+{
+ public enum OperatingSystemId
+ {
+ Windows,
+ Linux,
+ Darwin,
+ BSD
+ }
+}
diff --git a/MediaBrowser.Model/System/PublicSystemInfo.cs b/MediaBrowser.Model/System/PublicSystemInfo.cs
index d97eda352..53030843a 100644
--- a/MediaBrowser.Model/System/PublicSystemInfo.cs
+++ b/MediaBrowser.Model/System/PublicSystemInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.System
{
public class PublicSystemInfo
@@ -9,12 +12,6 @@ namespace MediaBrowser.Model.System
public string LocalAddress { get; set; }
/// <summary>
- /// Gets or sets the wan address.
- /// </summary>
- /// <value>The wan address.</value>
- public string WanAddress { get; set; }
-
- /// <summary>
/// Gets or sets the name of the server.
/// </summary>
/// <value>The name of the server.</value>
@@ -27,6 +24,11 @@ namespace MediaBrowser.Model.System
public string Version { get; set; }
/// <summary>
+ /// Gets or sets the product name. This is the AssemblyProduct name.
+ /// </summary>
+ public string ProductName { get; set; }
+
+ /// <summary>
/// Gets or sets the operating system.
/// </summary>
/// <value>The operating system.</value>
@@ -37,5 +39,14 @@ namespace MediaBrowser.Model.System
/// </summary>
/// <value>The id.</value>
public string Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the startup wizard is completed.
+ /// </summary>
+ /// <remarks>
+ /// Nullable for OpenAPI specification only to retain backwards compatibility in apiclients.
+ /// </remarks>
+ /// <value>The startup completion status.</value>]
+ public bool? StartupWizardCompleted { get; set; }
}
}
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index 581a1069c..a82c1c8c0 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
using System.Runtime.InteropServices;
using MediaBrowser.Model.Updates;
@@ -5,11 +8,35 @@ using MediaBrowser.Model.Updates;
namespace MediaBrowser.Model.System
{
/// <summary>
- /// Class SystemInfo
+ /// Enum describing the location of the FFmpeg tool.
+ /// </summary>
+ public enum FFmpegLocation
+ {
+ /// <summary>No path to FFmpeg found.</summary>
+ NotFound,
+
+ /// <summary>Path supplied via command line using switch --ffmpeg.</summary>
+ SetByArgument,
+
+ /// <summary>User has supplied path via Transcoding UI page.</summary>
+ Custom,
+
+ /// <summary>FFmpeg tool found on system $PATH.</summary>
+ System
+ }
+
+ /// <summary>
+ /// Class SystemInfo.
/// </summary>
public class SystemInfo : PublicSystemInfo
{
- public PackageVersionClass SystemUpdateLevel { get; set; }
+ /// <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.
@@ -18,12 +45,7 @@ namespace MediaBrowser.Model.System
public string OperatingSystemDisplayName { get; set; }
/// <summary>
- /// The product name. This is the AssemblyProduct name.
- /// </summary>
- public string ProductName { get; set; }
-
- /// <summary>
- /// Get or sets the package name.
+ /// Gets or sets the package name.
/// </summary>
/// <value>The value of the '-package' command line argument.</value>
public string PackageName { get; set; }
@@ -69,6 +91,12 @@ namespace MediaBrowser.Model.System
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>
@@ -93,45 +121,21 @@ namespace MediaBrowser.Model.System
public string InternalMetadataPath { get; set; }
/// <summary>
- /// Gets or sets the transcoding temporary path.
+ /// Gets or sets the transcode path.
/// </summary>
- /// <value>The transcoding temporary path.</value>
+ /// <value>The transcode path.</value>
public string TranscodingTempPath { get; set; }
/// <summary>
- /// Gets or sets the HTTP server port number.
- /// </summary>
- /// <value>The HTTP server port number.</value>
- public int HttpServerPortNumber { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [enable HTTPS].
- /// </summary>
- /// <value><c>true</c> if [enable HTTPS]; otherwise, <c>false</c>.</value>
- public bool SupportsHttps { get; set; }
-
- /// <summary>
- /// Gets or sets the HTTPS server port number.
- /// </summary>
- /// <value>The HTTPS server port number.</value>
- public int HttpsPortNumber { 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")]
public bool HasUpdateAvailable { get; set; }
- public string EncoderLocationType { get; set; }
+ [Obsolete("This isn't set correctly anymore")]
+ public FFmpegLocation EncoderLocation { get; set; }
public Architecture SystemArchitecture { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SystemInfo" /> class.
- /// </summary>
- public SystemInfo()
- {
- CompletedInstallations = Array.Empty<InstallationInfo>();
- }
}
}
diff --git a/MediaBrowser.Model/System/WakeOnLanInfo.cs b/MediaBrowser.Model/System/WakeOnLanInfo.cs
index 031458735..aba19a6ba 100644
--- a/MediaBrowser.Model/System/WakeOnLanInfo.cs
+++ b/MediaBrowser.Model/System/WakeOnLanInfo.cs
@@ -1,13 +1,47 @@
+using System.Net.NetworkInformation;
+
namespace MediaBrowser.Model.System
{
+ /// <summary>
+ /// Provides the MAC address and port for wake-on-LAN functionality.
+ /// </summary>
public class WakeOnLanInfo
{
- public string MacAddress { get; set; }
- public int Port { get; set; }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WakeOnLanInfo" /> class.
+ /// </summary>
+ /// <param name="macAddress">The MAC address.</param>
+ public WakeOnLanInfo(PhysicalAddress macAddress) : this(macAddress.ToString())
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WakeOnLanInfo" /> class.
+ /// </summary>
+ /// <param name="macAddress">The MAC address.</param>
+ public WakeOnLanInfo(string macAddress) : this()
+ {
+ MacAddress = macAddress;
+ }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WakeOnLanInfo" /> class.
+ /// </summary>
public WakeOnLanInfo()
{
Port = 9;
}
+
+ /// <summary>
+ /// Gets the MAC address of the device.
+ /// </summary>
+ /// <value>The MAC address.</value>
+ public string? MacAddress { get; }
+
+ /// <summary>
+ /// Gets or sets the wake-on-LAN port.
+ /// </summary>
+ /// <value>The wake-on-LAN port.</value>
+ public int Port { get; set; }
}
}
diff --git a/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs b/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
index 9c4b75c54..6212d76f7 100644
--- a/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
+++ b/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Tasks
{
public interface IConfigurableScheduledTask
@@ -7,6 +9,7 @@ namespace MediaBrowser.Model.Tasks
/// </summary>
/// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
bool IsHidden { get; }
+
/// <summary>
/// Gets a value indicating whether this instance is enabled.
/// </summary>
diff --git a/MediaBrowser.Model/Tasks/IScheduledTask.cs b/MediaBrowser.Model/Tasks/IScheduledTask.cs
index a615ebb07..bf87088e4 100644
--- a/MediaBrowser.Model/Tasks/IScheduledTask.cs
+++ b/MediaBrowser.Model/Tasks/IScheduledTask.cs
@@ -6,16 +6,19 @@ using System.Threading.Tasks;
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Interface IScheduledTaskWorker
+ /// Interface IScheduledTaskWorker.
/// </summary>
public interface IScheduledTask
{
/// <summary>
- /// Gets the name of the task
+ /// Gets the name of the task.
/// </summary>
/// <value>The name.</value>
string Name { get; }
+ /// <summary>
+ /// Gets the key of the task.
+ /// </summary>
string Key { get; }
/// <summary>
@@ -31,7 +34,7 @@ namespace MediaBrowser.Model.Tasks
string Category { get; }
/// <summary>
- /// Executes the task
+ /// Executes the task.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
@@ -39,9 +42,9 @@ namespace MediaBrowser.Model.Tasks
Task Execute(CancellationToken cancellationToken, IProgress<double> progress);
/// <summary>
- /// Gets the default triggers.
+ /// Gets the default triggers that define when the task will run.
/// </summary>
- /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
+ /// <returns>The default triggers that define when the task will run.</returns>
IEnumerable<TaskTriggerInfo> GetDefaultTriggers();
}
}
diff --git a/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs b/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs
index 61e3a65eb..ca769e26b 100644
--- a/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs
+++ b/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs
@@ -1,10 +1,11 @@
+#nullable disable
using System;
-using MediaBrowser.Model.Events;
+using Jellyfin.Data.Events;
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Interface IScheduledTaskWorker
+ /// Interface IScheduledTaskWorker.
/// </summary>
public interface IScheduledTaskWorker : IDisposable
{
@@ -14,7 +15,7 @@ namespace MediaBrowser.Model.Tasks
event EventHandler<GenericEventArgs<double>> TaskProgress;
/// <summary>
- /// Gets or sets the scheduled task.
+ /// Gets the scheduled task.
/// </summary>
/// <value>The scheduled task.</value>
IScheduledTask ScheduledTask { get; }
@@ -56,10 +57,9 @@ namespace MediaBrowser.Model.Tasks
double? CurrentProgress { get; }
/// <summary>
- /// Gets the triggers that define when the task will run
+ /// Gets or sets the triggers that define when the task will run.
/// </summary>
/// <value>The triggers.</value>
- /// <exception cref="ArgumentNullException">value</exception>
TaskTriggerInfo[] Triggers { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/Tasks/ITaskManager.cs b/MediaBrowser.Model/Tasks/ITaskManager.cs
index 57b8d1af8..a86bf2a1c 100644
--- a/MediaBrowser.Model/Tasks/ITaskManager.cs
+++ b/MediaBrowser.Model/Tasks/ITaskManager.cs
@@ -1,14 +1,20 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
-using MediaBrowser.Model.Events;
+using Jellyfin.Data.Events;
namespace MediaBrowser.Model.Tasks
{
public interface ITaskManager : IDisposable
{
+ event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
+
+ event EventHandler<TaskCompletionEventArgs> TaskCompleted;
+
/// <summary>
- /// Gets the list of Scheduled Tasks
+ /// Gets the list of Scheduled Tasks.
/// </summary>
/// <value>The scheduled tasks.</value>
IScheduledTaskWorker[] ScheduledTasks { get; }
@@ -16,7 +22,7 @@ namespace MediaBrowser.Model.Tasks
/// <summary>
/// Cancels if running and queue.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">An implementatin of <see cref="IScheduledTask" />.</typeparam>
/// <param name="options">Task options.</param>
void CancelIfRunningAndQueue<T>(TaskOptions options)
where T : IScheduledTask;
@@ -24,21 +30,21 @@ namespace MediaBrowser.Model.Tasks
/// <summary>
/// Cancels if running and queue.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">An implementatin of <see cref="IScheduledTask" />.</typeparam>
void CancelIfRunningAndQueue<T>()
where T : IScheduledTask;
/// <summary>
/// Cancels if running.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">An implementatin of <see cref="IScheduledTask" />.</typeparam>
void CancelIfRunning<T>()
where T : IScheduledTask;
/// <summary>
/// Queues the scheduled task.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">An implementatin of <see cref="IScheduledTask" />.</typeparam>
/// <param name="options">Task options.</param>
void QueueScheduledTask<T>(TaskOptions options)
where T : IScheduledTask;
@@ -46,7 +52,7 @@ namespace MediaBrowser.Model.Tasks
/// <summary>
/// Queues the scheduled task.
/// </summary>
- /// <typeparam name="T"></typeparam>
+ /// <typeparam name="T">An implementatin of <see cref="IScheduledTask" />.</typeparam>
void QueueScheduledTask<T>()
where T : IScheduledTask;
@@ -56,6 +62,8 @@ namespace MediaBrowser.Model.Tasks
/// <summary>
/// Queues the scheduled task.
/// </summary>
+ /// <param name="task">The <see cref="IScheduledTask" /> to queue.</param>
+ /// <param name="options">The <see cref="TaskOptions" /> to use.</param>
void QueueScheduledTask(IScheduledTask task, TaskOptions options);
/// <summary>
@@ -65,12 +73,10 @@ namespace MediaBrowser.Model.Tasks
void AddTasks(IEnumerable<IScheduledTask> tasks);
void Cancel(IScheduledTaskWorker task);
+
Task Execute(IScheduledTaskWorker task, TaskOptions options);
void Execute<T>()
where T : IScheduledTask;
-
- event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
- event EventHandler<TaskCompletionEventArgs> TaskCompleted;
}
}
diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
index c8433ed21..999db9605 100644
--- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs
+++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
@@ -4,27 +4,31 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Interface ITaskTrigger
+ /// Interface ITaskTrigger.
/// </summary>
public interface ITaskTrigger
{
/// <summary>
- /// Fires when the trigger condition is satisfied and the task should run
+ /// Fires when the trigger condition is satisfied and the task should run.
/// </summary>
- event EventHandler<EventArgs> Triggered;
+ event EventHandler<EventArgs>? Triggered;
/// <summary>
- /// Gets or sets the options of this task.
+ /// Gets the options of this task.
/// </summary>
- TaskOptions TaskOptions { get; set; }
+ TaskOptions TaskOptions { get; }
/// <summary>
- /// Stars waiting for the trigger action
+ /// Stars waiting for the trigger action.
/// </summary>
+ /// <param name="lastResult">Result of the last run triggerd task.</param>
+ /// <param name="logger">The <see cref="ILogger"/>.</param>
+ /// <param name="taskName">The name of the task.</param>
+ /// <param name="isApplicationStartup">Wheter or not this is is fired during startup.</param>
void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup);
/// <summary>
- /// Stops waiting for the trigger action
+ /// Stops waiting for the trigger action.
/// </summary>
void Stop();
}
diff --git a/MediaBrowser.Model/Tasks/ScheduledTaskHelpers.cs b/MediaBrowser.Model/Tasks/ScheduledTaskHelpers.cs
index e461e4a4b..9063903ae 100644
--- a/MediaBrowser.Model/Tasks/ScheduledTaskHelpers.cs
+++ b/MediaBrowser.Model/Tasks/ScheduledTaskHelpers.cs
@@ -1,7 +1,7 @@
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Class ScheduledTaskHelpers
+ /// Class ScheduledTaskHelpers.
/// </summary>
public static class ScheduledTaskHelpers
{
@@ -14,9 +14,7 @@ namespace MediaBrowser.Model.Tasks
{
var isHidden = false;
- var configurableTask = task.ScheduledTask as IConfigurableScheduledTask;
-
- if (configurableTask != null)
+ if (task.ScheduledTask is IConfigurableScheduledTask configurableTask)
{
isHidden = configurableTask.IsHidden;
}
diff --git a/MediaBrowser.Model/Tasks/TaskCompletionEventArgs.cs b/MediaBrowser.Model/Tasks/TaskCompletionEventArgs.cs
index 05eaff8da..48950667e 100644
--- a/MediaBrowser.Model/Tasks/TaskCompletionEventArgs.cs
+++ b/MediaBrowser.Model/Tasks/TaskCompletionEventArgs.cs
@@ -1,11 +1,19 @@
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Tasks
{
public class TaskCompletionEventArgs : EventArgs
{
- public IScheduledTaskWorker Task { get; set; }
+ public TaskCompletionEventArgs(IScheduledTaskWorker task, TaskResult result)
+ {
+ Task = task;
+ Result = result;
+ }
+
+ public IScheduledTaskWorker Task { get; }
- public TaskResult Result { get; set; }
+ public TaskResult Result { get; }
}
}
diff --git a/MediaBrowser.Model/Tasks/TaskCompletionStatus.cs b/MediaBrowser.Model/Tasks/TaskCompletionStatus.cs
index 4d7ff523d..5c8b5f223 100644
--- a/MediaBrowser.Model/Tasks/TaskCompletionStatus.cs
+++ b/MediaBrowser.Model/Tasks/TaskCompletionStatus.cs
@@ -1,27 +1,27 @@
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Enum TaskCompletionStatus
+ /// Enum TaskCompletionStatus.
/// </summary>
public enum TaskCompletionStatus
{
/// <summary>
- /// The completed
+ /// The completed.
/// </summary>
Completed,
/// <summary>
- /// The failed
+ /// The failed.
/// </summary>
Failed,
/// <summary>
- /// Manually cancelled by the user
+ /// Manually cancelled by the user.
/// </summary>
Cancelled,
/// <summary>
- /// Aborted due to a system failure or shutdown
+ /// Aborted due to a system failure or shutdown.
/// </summary>
Aborted
}
diff --git a/MediaBrowser.Model/Tasks/TaskInfo.cs b/MediaBrowser.Model/Tasks/TaskInfo.cs
index 8d80e68cf..16de0b121 100644
--- a/MediaBrowser.Model/Tasks/TaskInfo.cs
+++ b/MediaBrowser.Model/Tasks/TaskInfo.cs
@@ -1,11 +1,22 @@
+#nullable disable
+using System;
+
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Class TaskInfo
+ /// Class TaskInfo.
/// </summary>
public class TaskInfo
{
/// <summary>
+ /// Initializes a new instance of the <see cref="TaskInfo"/> class.
+ /// </summary>
+ public TaskInfo()
+ {
+ Triggers = Array.Empty<TaskTriggerInfo>();
+ }
+
+ /// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
@@ -64,13 +75,5 @@ namespace MediaBrowser.Model.Tasks
/// </summary>
/// <value>The key.</value>
public string Key { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="TaskInfo"/> class.
- /// </summary>
- public TaskInfo()
- {
- Triggers = new TaskTriggerInfo[] { };
- }
}
}
diff --git a/MediaBrowser.Model/Tasks/TaskOptions.cs b/MediaBrowser.Model/Tasks/TaskOptions.cs
index a9f03303a..3a221b878 100644
--- a/MediaBrowser.Model/Tasks/TaskOptions.cs
+++ b/MediaBrowser.Model/Tasks/TaskOptions.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Tasks
{
public class TaskOptions
diff --git a/MediaBrowser.Model/Tasks/TaskResult.cs b/MediaBrowser.Model/Tasks/TaskResult.cs
index eede9069f..31001aeb2 100644
--- a/MediaBrowser.Model/Tasks/TaskResult.cs
+++ b/MediaBrowser.Model/Tasks/TaskResult.cs
@@ -1,9 +1,10 @@
+#nullable disable
using System;
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Class TaskExecutionInfo
+ /// Class TaskExecutionInfo.
/// </summary>
public class TaskResult
{
diff --git a/MediaBrowser.Model/Tasks/TaskState.cs b/MediaBrowser.Model/Tasks/TaskState.cs
index 91bc7f682..619dedb70 100644
--- a/MediaBrowser.Model/Tasks/TaskState.cs
+++ b/MediaBrowser.Model/Tasks/TaskState.cs
@@ -1,20 +1,22 @@
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Enum TaskState
+ /// Enum TaskState.
/// </summary>
public enum TaskState
{
/// <summary>
- /// The idle
+ /// The idle.
/// </summary>
Idle,
+
/// <summary>
- /// The cancelling
+ /// The cancelling.
/// </summary>
Cancelling,
+
/// <summary>
- /// The running
+ /// The running.
/// </summary>
Running
}
diff --git a/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs b/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs
index 714f11872..f8a8c727e 100644
--- a/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs
+++ b/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs
@@ -1,12 +1,21 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Tasks
{
/// <summary>
- /// Class TaskTriggerInfo
+ /// Class TaskTriggerInfo.
/// </summary>
public class TaskTriggerInfo
{
+ public const string TriggerDaily = "DailyTrigger";
+ public const string TriggerWeekly = "WeeklyTrigger";
+ public const string TriggerInterval = "IntervalTrigger";
+ public const string TriggerSystemEvent = "SystemEventTrigger";
+ public const string TriggerStartup = "StartupTrigger";
+
/// <summary>
/// Gets or sets the type.
/// </summary>
@@ -36,11 +45,5 @@ namespace MediaBrowser.Model.Tasks
/// </summary>
/// <value>The maximum runtime ticks.</value>
public long? MaxRuntimeTicks { get; set; }
-
- public const string TriggerDaily = "DailyTrigger";
- public const string TriggerWeekly = "WeeklyTrigger";
- public const string TriggerInterval = "IntervalTrigger";
- public const string TriggerSystemEvent = "SystemEventTrigger";
- public const string TriggerStartup = "StartupTrigger";
}
}
diff --git a/MediaBrowser.Model/Updates/CheckForUpdateResult.cs b/MediaBrowser.Model/Updates/CheckForUpdateResult.cs
deleted file mode 100644
index 4c66c6d49..000000000
--- a/MediaBrowser.Model/Updates/CheckForUpdateResult.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-namespace MediaBrowser.Model.Updates
-{
- /// <summary>
- /// Class CheckForUpdateResult
- /// </summary>
- public class CheckForUpdateResult
- {
- /// <summary>
- /// Gets or sets a value indicating whether this instance is update available.
- /// </summary>
- /// <value><c>true</c> if this instance is update available; otherwise, <c>false</c>.</value>
- public bool IsUpdateAvailable { get; set; }
-
- /// <summary>
- /// Gets or sets the available version.
- /// </summary>
- /// <value>The available version.</value>
- public string AvailableVersion
- {
- get => Package != null ? Package.versionStr : "0.0.0.1";
- set { } // need this for the serializer
- }
-
- /// <summary>
- /// Get or sets package information for an available update
- /// </summary>
- public PackageVersionInfo Package { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Updates/InstallationInfo.cs b/MediaBrowser.Model/Updates/InstallationInfo.cs
index a3f19e236..cc600de9d 100644
--- a/MediaBrowser.Model/Updates/InstallationInfo.cs
+++ b/MediaBrowser.Model/Updates/InstallationInfo.cs
@@ -1,16 +1,20 @@
+#nullable disable
+
using System;
+using System.Text.Json.Serialization;
namespace MediaBrowser.Model.Updates
{
/// <summary>
- /// Class InstallationInfo
+ /// Class InstallationInfo.
/// </summary>
public class InstallationInfo
{
/// <summary>
- /// Gets or sets the id.
+ /// Gets or sets the Id.
/// </summary>
- /// <value>The id.</value>
+ /// <value>The Id.</value>
+ [JsonPropertyName("Guid")]
public Guid Id { get; set; }
/// <summary>
@@ -20,27 +24,33 @@ namespace MediaBrowser.Model.Updates
public string Name { get; set; }
/// <summary>
- /// Gets or sets the assembly guid.
+ /// Gets or sets the version.
/// </summary>
- /// <value>The guid of the assembly.</value>
- public string AssemblyGuid { get; set; }
+ /// <value>The version.</value>
+ public Version Version { get; set; }
/// <summary>
- /// Gets or sets the version.
+ /// Gets or sets the changelog for this version.
/// </summary>
- /// <value>The version.</value>
- public string Version { get; set; }
+ /// <value>The changelog.</value>
+ public string Changelog { get; set; }
+
+ /// <summary>
+ /// Gets or sets the source URL.
+ /// </summary>
+ /// <value>The source URL.</value>
+ public string SourceUrl { get; set; }
/// <summary>
- /// Gets or sets the update class.
+ /// Gets or sets a checksum for the binary.
/// </summary>
- /// <value>The update class.</value>
- public PackageVersionClass UpdateClass { get; set; }
+ /// <value>The checksum.</value>
+ public string Checksum { get; set; }
/// <summary>
- /// Gets or sets the percent complete.
+ /// Gets or sets package information for the installation.
/// </summary>
- /// <value>The percent complete.</value>
- public double? PercentComplete { get; set; }
+ /// <value>The package information.</value>
+ public PackageInfo PackageInfo { get; set; }
}
}
diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs
index ff4ed26d3..aeaaa8b35 100644
--- a/MediaBrowser.Model/Updates/PackageInfo.cs
+++ b/MediaBrowser.Model/Updates/PackageInfo.cs
@@ -1,175 +1,83 @@
using System;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
namespace MediaBrowser.Model.Updates
{
/// <summary>
- /// Class PackageInfo
+ /// Class PackageInfo.
/// </summary>
public class PackageInfo
{
/// <summary>
- /// The internal id of this package.
+ /// Initializes a new instance of the <see cref="PackageInfo"/> class.
/// </summary>
- /// <value>The id.</value>
- public string id { get; set; }
+ public PackageInfo()
+ {
+ Versions = Array.Empty<VersionInfo>();
+ Category = string.Empty;
+ Name = string.Empty;
+ Overview = string.Empty;
+ Owner = string.Empty;
+ Description = string.Empty;
+ }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
- public string name { get; set; }
+ [JsonPropertyName("name")]
+ public string Name { get; set; }
/// <summary>
- /// Gets or sets the short description.
+ /// Gets or sets a long description of the plugin containing features or helpful explanations.
/// </summary>
- /// <value>The short description.</value>
- public string shortDescription { get; set; }
+ /// <value>The description.</value>
+ [JsonPropertyName("description")]
+ public string Description { get; set; }
/// <summary>
- /// Gets or sets the overview.
+ /// Gets or sets a short overview of what the plugin does.
/// </summary>
/// <value>The overview.</value>
- public string overview { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is premium.
- /// </summary>
- /// <value><c>true</c> if this instance is premium; otherwise, <c>false</c>.</value>
- public bool isPremium { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is adult only content.
- /// </summary>
- /// <value><c>true</c> if this instance is adult; otherwise, <c>false</c>.</value>
- public bool adult { get; set; }
-
- /// <summary>
- /// Gets or sets the rich desc URL.
- /// </summary>
- /// <value>The rich desc URL.</value>
- public string richDescUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the thumb image.
- /// </summary>
- /// <value>The thumb image.</value>
- public string thumbImage { get; set; }
-
- /// <summary>
- /// Gets or sets the preview image.
- /// </summary>
- /// <value>The preview image.</value>
- public string previewImage { get; set; }
-
- /// <summary>
- /// Gets or sets the type.
- /// </summary>
- /// <value>The type.</value>
- public string type { get; set; }
-
- /// <summary>
- /// Gets or sets the target filename.
- /// </summary>
- /// <value>The target filename.</value>
- public string targetFilename { get; set; }
+ [JsonPropertyName("overview")]
+ public string Overview { get; set; }
/// <summary>
/// Gets or sets the owner.
/// </summary>
/// <value>The owner.</value>
- public string owner { get; set; }
+ [JsonPropertyName("owner")]
+ public string Owner { get; set; }
/// <summary>
/// Gets or sets the category.
/// </summary>
/// <value>The category.</value>
- public string category { get; set; }
-
- /// <summary>
- /// Gets or sets the catalog tile color.
- /// </summary>
- /// <value>The owner.</value>
- public string tileColor { get; set; }
-
- /// <summary>
- /// Gets or sets the feature id of this package (if premium).
- /// </summary>
- /// <value>The feature id.</value>
- public string featureId { get; set; }
+ [JsonPropertyName("category")]
+ public string Category { get; set; }
/// <summary>
- /// Gets or sets the registration info for this package (if premium).
- /// </summary>
- /// <value>The registration info.</value>
- public string regInfo { get; set; }
-
- /// <summary>
- /// Gets or sets the price for this package (if premium).
- /// </summary>
- /// <value>The price.</value>
- public float price { get; set; }
-
- /// <summary>
- /// Gets or sets the target system for this plug-in (Server, MBTheater, MBClassic).
- /// </summary>
- /// <value>The target system.</value>
- public PackageTargetSystem targetSystem { get; set; }
-
- /// <summary>
- /// The guid of the assembly associated with this package (if a plug-in).
+ /// Gets or sets the guid of the assembly associated with this plugin.
/// This is used to identify the proper item for automatic updates.
/// </summary>
/// <value>The name.</value>
- public string guid { get; set; }
-
- /// <summary>
- /// Gets or sets the total number of ratings for this package.
- /// </summary>
- /// <value>The total ratings.</value>
- public int? totalRatings { get; set; }
-
- /// <summary>
- /// Gets or sets the average rating for this package .
- /// </summary>
- /// <value>The rating.</value>
- public float avgRating { get; set; }
-
- /// <summary>
- /// Gets or sets whether or not this package is registered.
- /// </summary>
- /// <value>True if registered.</value>
- public bool isRegistered { get; set; }
-
- /// <summary>
- /// Gets or sets the expiration date for this package.
- /// </summary>
- /// <value>Expiration Date.</value>
- public DateTime expDate { get; set; }
+ [JsonPropertyName("guid")]
+ public Guid Id { get; set; }
/// <summary>
/// Gets or sets the versions.
/// </summary>
/// <value>The versions.</value>
- public PackageVersionInfo[] versions { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [enable in application store].
- /// </summary>
- /// <value><c>true</c> if [enable in application store]; otherwise, <c>false</c>.</value>
- public bool enableInAppStore { get; set; }
+ [JsonPropertyName("versions")]
+#pragma warning disable CA2227 // Collection properties should be read only
+ public IList<VersionInfo> Versions { get; set; }
+#pragma warning restore CA2227 // Collection properties should be read only
/// <summary>
- /// Gets or sets the installs.
+ /// Gets or sets the image url for the package.
/// </summary>
- /// <value>The installs.</value>
- public int installs { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PackageInfo"/> class.
- /// </summary>
- public PackageInfo()
- {
- versions = new PackageVersionInfo[] { };
- }
+ [JsonPropertyName("imageUrl")]
+ public string? ImageUrl { get; set; }
}
}
diff --git a/MediaBrowser.Model/Updates/PackageTargetSystem.cs b/MediaBrowser.Model/Updates/PackageTargetSystem.cs
deleted file mode 100644
index a0646f959..000000000
--- a/MediaBrowser.Model/Updates/PackageTargetSystem.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace MediaBrowser.Model.Updates
-{
- /// <summary>
- /// Enum PackageType
- /// </summary>
- public enum PackageTargetSystem
- {
- /// <summary>
- /// Server
- /// </summary>
- Server,
- /// <summary>
- /// MB Theater
- /// </summary>
- MBTheater,
- /// <summary>
- /// MB Classic
- /// </summary>
- MBClassic
- }
-}
diff --git a/MediaBrowser.Model/Updates/PackageVersionClass.cs b/MediaBrowser.Model/Updates/PackageVersionClass.cs
deleted file mode 100644
index 52f08b73b..000000000
--- a/MediaBrowser.Model/Updates/PackageVersionClass.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace MediaBrowser.Model.Updates
-{
- /// <summary>
- /// Enum PackageVersionClass
- /// </summary>
- public enum PackageVersionClass
- {
- /// <summary>
- /// The release
- /// </summary>
- Release = 0,
- /// <summary>
- /// The beta
- /// </summary>
- Beta = 1,
- /// <summary>
- /// The dev
- /// </summary>
- Dev = 2
- }
-}
diff --git a/MediaBrowser.Model/Updates/PackageVersionInfo.cs b/MediaBrowser.Model/Updates/PackageVersionInfo.cs
deleted file mode 100644
index be531770d..000000000
--- a/MediaBrowser.Model/Updates/PackageVersionInfo.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using MediaBrowser.Model.Serialization;
-
-namespace MediaBrowser.Model.Updates
-{
- /// <summary>
- /// Class PackageVersionInfo
- /// </summary>
- public class PackageVersionInfo
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string name { get; set; }
-
- /// <summary>
- /// Gets or sets the guid.
- /// </summary>
- /// <value>The guid.</value>
- public string guid { get; set; }
-
- /// <summary>
- /// Gets or sets the version STR.
- /// </summary>
- /// <value>The version STR.</value>
- public string versionStr { get; set; }
-
- /// <summary>
- /// The _version
- /// </summary>
- private Version _version;
- /// <summary>
- /// Gets or sets the version.
- /// Had to make this an interpreted property since Protobuf can't handle Version
- /// </summary>
- /// <value>The version.</value>
- [IgnoreDataMember]
- public Version version => _version ?? (_version = new Version(ValueOrDefault(versionStr, "0.0.0.1")));
-
- /// <summary>
- /// Values the or default.
- /// </summary>
- /// <param name="str">The STR.</param>
- /// <param name="def">The def.</param>
- /// <returns>System.String.</returns>
- private static string ValueOrDefault(string str, string def)
- {
- return string.IsNullOrEmpty(str) ? def : str;
- }
-
- /// <summary>
- /// Gets or sets the classification.
- /// </summary>
- /// <value>The classification.</value>
- public PackageVersionClass classification { get; set; }
-
- /// <summary>
- /// Gets or sets the description.
- /// </summary>
- /// <value>The description.</value>
- public string description { get; set; }
-
- /// <summary>
- /// Gets or sets the required version STR.
- /// </summary>
- /// <value>The required version STR.</value>
- public string requiredVersionStr { get; set; }
-
- /// <summary>
- /// Gets or sets the source URL.
- /// </summary>
- /// <value>The source URL.</value>
- public string sourceUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the source URL.
- /// </summary>
- /// <value>The source URL.</value>
- public string checksum { get; set; }
-
- /// <summary>
- /// Gets or sets the target filename.
- /// </summary>
- /// <value>The target filename.</value>
- public string targetFilename { get; set; }
-
- public string infoUrl { get; set; }
-
- public string runtimes { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Updates/RepositoryInfo.cs b/MediaBrowser.Model/Updates/RepositoryInfo.cs
new file mode 100644
index 000000000..705d3b33c
--- /dev/null
+++ b/MediaBrowser.Model/Updates/RepositoryInfo.cs
@@ -0,0 +1,26 @@
+namespace MediaBrowser.Model.Updates
+{
+ /// <summary>
+ /// Class RepositoryInfo.
+ /// </summary>
+ public class RepositoryInfo
+ {
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string? Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the URL.
+ /// </summary>
+ /// <value>The URL.</value>
+ public string? Url { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the repository is enabled.
+ /// </summary>
+ /// <value><c>true</c> if enabled.</value>
+ public bool Enabled { get; set; } = true;
+ }
+}
diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs
new file mode 100644
index 000000000..03a540dde
--- /dev/null
+++ b/MediaBrowser.Model/Updates/VersionInfo.cs
@@ -0,0 +1,77 @@
+using System.Text.Json.Serialization;
+using SysVersion = System.Version;
+
+namespace MediaBrowser.Model.Updates
+{
+ /// <summary>
+ /// Defines the <see cref="VersionInfo"/> class.
+ /// </summary>
+ public class VersionInfo
+ {
+ private SysVersion? _version;
+
+ /// <summary>
+ /// Gets or sets the version.
+ /// </summary>
+ /// <value>The version.</value>
+ [JsonPropertyName("version")]
+ public string Version
+ {
+ get => _version == null ? string.Empty : _version.ToString();
+
+ set => _version = SysVersion.Parse(value);
+ }
+
+ /// <summary>
+ /// Gets the version as a <see cref="SysVersion"/>.
+ /// </summary>
+ public SysVersion VersionNumber => _version ?? new SysVersion(0, 0, 0);
+
+ /// <summary>
+ /// Gets or sets the changelog for this version.
+ /// </summary>
+ /// <value>The changelog.</value>
+ [JsonPropertyName("changelog")]
+ public string? Changelog { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ABI that this version was built against.
+ /// </summary>
+ /// <value>The target ABI version.</value>
+ [JsonPropertyName("targetAbi")]
+ public string? TargetAbi { get; set; }
+
+ /// <summary>
+ /// Gets or sets the source URL.
+ /// </summary>
+ /// <value>The source URL.</value>
+ [JsonPropertyName("sourceUrl")]
+ public string? SourceUrl { get; set; }
+
+ /// <summary>
+ /// Gets or sets a checksum for the binary.
+ /// </summary>
+ /// <value>The checksum.</value>
+ [JsonPropertyName("checksum")]
+ public string? Checksum { get; set; }
+
+ /// <summary>
+ /// Gets or sets a timestamp of when the binary was built.
+ /// </summary>
+ /// <value>The timestamp.</value>
+ [JsonPropertyName("timestamp")]
+ public string? Timestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the repository name.
+ /// </summary>
+ [JsonPropertyName("repositoryName")]
+ public string RepositoryName { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the repository url.
+ /// </summary>
+ [JsonPropertyName("repositoryUrl")]
+ public string RepositoryUrl { get; set; } = string.Empty;
+ }
+}
diff --git a/MediaBrowser.Model/Users/ForgotPasswordAction.cs b/MediaBrowser.Model/Users/ForgotPasswordAction.cs
index 2124126c1..f198476e3 100644
--- a/MediaBrowser.Model/Users/ForgotPasswordAction.cs
+++ b/MediaBrowser.Model/Users/ForgotPasswordAction.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
namespace MediaBrowser.Model.Users
{
public enum ForgotPasswordAction
diff --git a/MediaBrowser.Model/Users/ForgotPasswordResult.cs b/MediaBrowser.Model/Users/ForgotPasswordResult.cs
index 2f9b4cf48..6bb13d4c9 100644
--- a/MediaBrowser.Model/Users/ForgotPasswordResult.cs
+++ b/MediaBrowser.Model/Users/ForgotPasswordResult.cs
@@ -1,3 +1,6 @@
+#nullable disable
+#pragma warning disable CS1591
+
using System;
namespace MediaBrowser.Model.Users
@@ -9,11 +12,13 @@ namespace MediaBrowser.Model.Users
/// </summary>
/// <value>The action.</value>
public ForgotPasswordAction Action { get; set; }
+
/// <summary>
/// Gets or sets the pin file.
/// </summary>
/// <value>The pin file.</value>
public string PinFile { get; set; }
+
/// <summary>
/// Gets or sets the pin expiration date.
/// </summary>
diff --git a/MediaBrowser.Model/Users/PinRedeemResult.cs b/MediaBrowser.Model/Users/PinRedeemResult.cs
index 35663ba57..23fa631e8 100644
--- a/MediaBrowser.Model/Users/PinRedeemResult.cs
+++ b/MediaBrowser.Model/Users/PinRedeemResult.cs
@@ -1,3 +1,7 @@
+#pragma warning disable CS1591
+
+using System;
+
namespace MediaBrowser.Model.Users
{
public class PinRedeemResult
@@ -7,10 +11,11 @@ namespace MediaBrowser.Model.Users
/// </summary>
/// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
public bool Success { get; set; }
+
/// <summary>
/// Gets or sets the users reset.
/// </summary>
/// <value>The users reset.</value>
- public string[] UsersReset { get; set; }
+ public string[] UsersReset { get; set; } = Array.Empty<string>();
}
}
diff --git a/MediaBrowser.Model/Users/UserAction.cs b/MediaBrowser.Model/Users/UserAction.cs
deleted file mode 100644
index 48b5bbef1..000000000
--- a/MediaBrowser.Model/Users/UserAction.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Users
-{
- public class UserAction
- {
- public string Id { get; set; }
- public string ServerId { get; set; }
- public Guid UserId { get; set; }
- public Guid ItemId { get; set; }
- public UserActionType Type { get; set; }
- public DateTime Date { get; set; }
- public long? PositionTicks { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Users/UserActionType.cs b/MediaBrowser.Model/Users/UserActionType.cs
deleted file mode 100644
index 5d843a738..000000000
--- a/MediaBrowser.Model/Users/UserActionType.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MediaBrowser.Model.Users
-{
- public enum UserActionType
- {
- PlayedItem = 0
- }
-}
diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs
index 23805b79f..3634d0705 100644
--- a/MediaBrowser.Model/Users/UserPolicy.cs
+++ b/MediaBrowser.Model/Users/UserPolicy.cs
@@ -1,10 +1,65 @@
+#nullable disable
+#pragma warning disable CS1591, CA1819
+
using System;
-using MediaBrowser.Model.Configuration;
+using System.Xml.Serialization;
+using Jellyfin.Data.Enums;
+using AccessSchedule = Jellyfin.Data.Entities.AccessSchedule;
namespace MediaBrowser.Model.Users
{
public class UserPolicy
{
+ public UserPolicy()
+ {
+ IsHidden = true;
+
+ EnableContentDeletion = false;
+ EnableContentDeletionFromFolders = Array.Empty<string>();
+
+ EnableSyncTranscoding = true;
+ EnableMediaConversion = true;
+
+ EnableMediaPlayback = true;
+ EnableAudioPlaybackTranscoding = true;
+ EnableVideoPlaybackTranscoding = true;
+ EnablePlaybackRemuxing = true;
+ ForceRemoteSourceTranscoding = false;
+ EnableLiveTvManagement = true;
+ EnableLiveTvAccess = true;
+
+ // Without this on by default, admins won't be able to do this
+ // Improve in the future
+ EnableLiveTvManagement = true;
+
+ EnableSharedDeviceControl = true;
+
+ BlockedTags = Array.Empty<string>();
+ BlockUnratedItems = Array.Empty<UnratedItem>();
+
+ EnableUserPreferenceAccess = true;
+
+ AccessSchedules = Array.Empty<AccessSchedule>();
+
+ LoginAttemptsBeforeLockout = -1;
+
+ MaxActiveSessions = 0;
+
+ EnableAllChannels = true;
+ EnabledChannels = Array.Empty<Guid>();
+
+ EnableAllFolders = true;
+ EnabledFolders = Array.Empty<Guid>();
+
+ EnabledDevices = Array.Empty<string>();
+ EnableAllDevices = true;
+
+ EnableContentDownloading = true;
+ EnablePublicSharing = true;
+ EnableRemoteAccess = true;
+ SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups;
+ }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is administrator.
/// </summary>
@@ -30,23 +85,37 @@ namespace MediaBrowser.Model.Users
public int? MaxParentalRating { get; set; }
public string[] BlockedTags { get; set; }
+
public bool EnableUserPreferenceAccess { get; set; }
+
public AccessSchedule[] AccessSchedules { get; set; }
+
public UnratedItem[] BlockUnratedItems { get; set; }
+
public bool EnableRemoteControlOfOtherUsers { get; set; }
+
public bool EnableSharedDeviceControl { get; set; }
+
public bool EnableRemoteAccess { get; set; }
public bool EnableLiveTvManagement { get; set; }
+
public bool EnableLiveTvAccess { get; set; }
public bool EnableMediaPlayback { get; set; }
+
public bool EnableAudioPlaybackTranscoding { get; set; }
+
public bool EnableVideoPlaybackTranscoding { get; set; }
+
public bool EnablePlaybackRemuxing { get; set; }
+ public bool ForceRemoteSourceTranscoding { get; set; }
+
public bool EnableContentDeletion { get; set; }
+
public string[] EnableContentDeletionFromFolders { get; set; }
+
public bool EnableContentDownloading { get; set; }
/// <summary>
@@ -54,68 +123,44 @@ namespace MediaBrowser.Model.Users
/// </summary>
/// <value><c>true</c> if [enable synchronize]; otherwise, <c>false</c>.</value>
public bool EnableSyncTranscoding { get; set; }
+
public bool EnableMediaConversion { get; set; }
public string[] EnabledDevices { get; set; }
+
public bool EnableAllDevices { get; set; }
- public string[] EnabledChannels { get; set; }
+ public Guid[] EnabledChannels { get; set; }
+
public bool EnableAllChannels { get; set; }
- public string[] EnabledFolders { get; set; }
+ public Guid[] EnabledFolders { get; set; }
+
public bool EnableAllFolders { get; set; }
public int InvalidLoginAttemptCount { get; set; }
- public bool EnablePublicSharing { get; set; }
-
- public string[] BlockedMediaFolders { get; set; }
- public string[] BlockedChannels { get; set; }
-
- public int RemoteClientBitrateLimit { get; set; }
- public string AuthenticationProviderId { get; set; }
-
- public UserPolicy()
- {
- EnableContentDeletion = true;
- EnableContentDeletionFromFolders = Array.Empty<string>();
+ public int LoginAttemptsBeforeLockout { get; set; }
- EnableSyncTranscoding = true;
- EnableMediaConversion = true;
+ public int MaxActiveSessions { get; set; }
- EnableMediaPlayback = true;
- EnableAudioPlaybackTranscoding = true;
- EnableVideoPlaybackTranscoding = true;
- EnablePlaybackRemuxing = true;
-
- EnableLiveTvManagement = true;
- EnableLiveTvAccess = true;
-
- // Without this on by default, admins won't be able to do this
- // Improve in the future
- EnableLiveTvManagement = true;
-
- EnableSharedDeviceControl = true;
-
- BlockedTags = Array.Empty<string>();
- BlockUnratedItems = Array.Empty<UnratedItem>();
+ public bool EnablePublicSharing { get; set; }
- EnableUserPreferenceAccess = true;
+ public Guid[] BlockedMediaFolders { get; set; }
- AccessSchedules = Array.Empty<AccessSchedule>();
+ public Guid[] BlockedChannels { get; set; }
- EnableAllChannels = true;
- EnabledChannels = Array.Empty<string>();
+ public int RemoteClientBitrateLimit { get; set; }
- EnableAllFolders = true;
- EnabledFolders = Array.Empty<string>();
+ [XmlElement(ElementName = "AuthenticationProviderId")]
+ public string AuthenticationProviderId { get; set; }
- EnabledDevices = Array.Empty<string>();
- EnableAllDevices = true;
+ public string PasswordResetProviderId { get; set; }
- EnableContentDownloading = true;
- EnablePublicSharing = true;
- EnableRemoteAccess = true;
- }
+ /// <summary>
+ /// Gets or sets a value indicating what SyncPlay features the user can access.
+ /// </summary>
+ /// <value>Access level to SyncPlay features.</value>
+ public SyncPlayUserAccessType SyncPlayAccess { get; set; }
}
}
diff --git a/MediaBrowser.Model/Xml/IXmlReaderSettingsFactory.cs b/MediaBrowser.Model/Xml/IXmlReaderSettingsFactory.cs
deleted file mode 100644
index b39325958..000000000
--- a/MediaBrowser.Model/Xml/IXmlReaderSettingsFactory.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.Xml;
-
-namespace MediaBrowser.Model.Xml
-{
- public interface IXmlReaderSettingsFactory
- {
- XmlReaderSettings Create(bool enableValidation);
- }
-}
diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
index 4820e12ab..eabc66c6b 100644
--- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,14 +13,30 @@ namespace MediaBrowser.Providers.Books
{
public class AudioBookMetadataService : MetadataService<AudioBook, SongInfo>
{
- protected override void MergeData(MetadataResult<AudioBook> source, MetadataResult<AudioBook> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ 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)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
var sourceItem = source.Item;
var targetItem = target.Item;
- if (replaceData || targetItem.Artists.Length == 0)
+ if (replaceData || targetItem.Artists.Count == 0)
{
targetItem.Artists = sourceItem.Artists;
}
@@ -28,9 +46,5 @@ namespace MediaBrowser.Providers.Books
targetItem.Album = sourceItem.Album;
}
}
-
- public AudioBookMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs
index 358f87a0f..3f3782dfb 100644
--- a/MediaBrowser.Providers/Books/BookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/BookMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,7 +13,18 @@ namespace MediaBrowser.Providers.Books
{
public class BookMetadataService : MetadataService<Book, BookInfo>
{
- protected override void MergeData(MetadataResult<Book> source, MetadataResult<Book> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ 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)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -20,9 +33,5 @@ namespace MediaBrowser.Providers.Books
target.Item.SeriesName = source.Item.SeriesName;
}
}
-
- public BookMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
index 693edb143..88ce8d087 100644
--- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
+++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Controller.Configuration;
@@ -14,12 +16,36 @@ namespace MediaBrowser.Providers.BoxSets
{
public class BoxSetMetadataService : MetadataService<BoxSet, BoxSetInfo>
{
+ 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 EnableUpdatingOfficialRatingFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingPremiereDateFromChildren => true;
+
+ /// <inheritdoc />
protected override IList<BaseItem> GetChildrenForMetadataUpdates(BoxSet item)
{
return item.GetLinkedChildren();
}
- protected override void MergeData(MetadataResult<BoxSet> source, MetadataResult<BoxSet> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<BoxSet> source, MetadataResult<BoxSet> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -32,9 +58,10 @@ namespace MediaBrowser.Providers.BoxSets
}
}
- protected override ItemUpdateType BeforeSaveInternal(BoxSet item, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ /// <inheritdoc />
+ protected override ItemUpdateType BeforeSaveInternal(BoxSet item, bool isFullRefresh, ItemUpdateType updateType)
{
- var updateType = base.BeforeSaveInternal(item, isFullRefresh, currentUpdateType);
+ var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
var libraryFolderIds = item.GetLibraryFolderIds();
@@ -42,22 +69,10 @@ namespace MediaBrowser.Providers.BoxSets
if (itemLibraryFolderIds == null || !libraryFolderIds.SequenceEqual(itemLibraryFolderIds))
{
item.LibraryFolderIds = libraryFolderIds;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- return updateType;
+ return updatedType;
}
-
- public BoxSetMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
-
- protected override bool EnableUpdatingGenresFromChildren => true;
-
- protected override bool EnableUpdatingOfficialRatingFromChildren => true;
-
- protected override bool EnableUpdatingStudiosFromChildren => true;
-
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
}
}
diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetImageProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetImageProvider.cs
deleted file mode 100644
index 4d12b2f4a..000000000
--- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetImageProvider.cs
+++ /dev/null
@@ -1,158 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.Movies;
-
-namespace MediaBrowser.Providers.BoxSets
-{
- public class MovieDbBoxSetImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IHttpClient _httpClient;
-
- public MovieDbBoxSetImageProvider(IHttpClient httpClient)
- {
- _httpClient = httpClient;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheMovieDb";
-
- public bool Supports(BaseItem item)
- {
- return item is BoxSet;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- var language = item.GetPreferredMetadataLanguage();
-
- var mainResult = await MovieDbBoxSetProvider.Current.GetMovieDbResult(tmdbId, null, cancellationToken).ConfigureAwait(false);
-
- if (mainResult != null)
- {
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- return GetImages(mainResult, language, tmdbImageUrl);
- }
- }
-
- return new List<RemoteImageInfo>();
- }
-
- private IEnumerable<RemoteImageInfo> GetImages(MovieDbBoxSetProvider.RootObject obj, string language, string baseUrl)
- {
- var list = new List<RemoteImageInfo>();
-
- var images = obj.images ?? new MovieDbBoxSetProvider.Images();
-
- list.AddRange(GetPosters(images).Select(i => new RemoteImageInfo
- {
- Url = baseUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- Language = MovieDbProvider.AdjustImageLanguage(i.iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
-
- list.AddRange(GetBackdrops(images).Select(i => new RemoteImageInfo
- {
- Url = baseUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- ProviderName = Name,
- Type = ImageType.Backdrop,
- RatingType = RatingType.Score
- }));
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- /// <summary>
- /// Gets the posters.
- /// </summary>
- /// <param name="images">The images.</param>
- /// <returns>IEnumerable{MovieDbProvider.Poster}.</returns>
- private IEnumerable<MovieDbBoxSetProvider.Poster> GetPosters(MovieDbBoxSetProvider.Images images)
- {
- return images.posters ?? new List<MovieDbBoxSetProvider.Poster>();
- }
-
- /// <summary>
- /// Gets the backdrops.
- /// </summary>
- /// <param name="images">The images.</param>
- /// <returns>IEnumerable{MovieDbProvider.Backdrop}.</returns>
- private IEnumerable<MovieDbBoxSetProvider.Backdrop> GetBackdrops(MovieDbBoxSetProvider.Images images)
- {
- var eligibleBackdrops = images.backdrops == null ? new List<MovieDbBoxSetProvider.Backdrop>() :
- images.backdrops;
-
- return eligibleBackdrops.OrderByDescending(i => i.vote_average)
- .ThenByDescending(i => i.vote_count);
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs
deleted file mode 100644
index 4e41694c4..000000000
--- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs
+++ /dev/null
@@ -1,326 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.BoxSets
-{
- public class MovieDbBoxSetProvider : IRemoteMetadataProvider<BoxSet, BoxSetInfo>
- {
- private const string GetCollectionInfo3 = MovieDbProvider.BaseMovieDbUrl + @"3/collection/{0}?api_key={1}&append_to_response=images";
-
- internal static MovieDbBoxSetProvider Current;
-
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
- private readonly IServerConfigurationManager _config;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
- private readonly IHttpClient _httpClient;
- private readonly ILibraryManager _libraryManager;
-
- public MovieDbBoxSetProvider(ILogger logger, IJsonSerializer json, IServerConfigurationManager config, IFileSystem fileSystem, ILocalizationManager localization, IHttpClient httpClient, ILibraryManager libraryManager)
- {
- _logger = logger;
- _json = json;
- _config = config;
- _fileSystem = fileSystem;
- _localization = localization;
- _httpClient = httpClient;
- _libraryManager = libraryManager;
- Current = this;
- }
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
- {
- var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- await EnsureInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, searchInfo.MetadataLanguage);
- var info = _json.DeserializeFromFile<RootObject>(dataFilePath);
-
- var images = (info.images ?? new Images()).posters ?? new List<Poster>();
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var result = new RemoteSearchResult
- {
- Name = info.name,
-
- SearchProviderName = Name,
-
- ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
- };
-
- result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
-
- return new[] { result };
- }
-
- return await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
- }
-
- public async Task<MetadataResult<BoxSet>> GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
- {
- var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
-
- // We don't already have an Id, need to fetch it
- if (string.IsNullOrEmpty(tmdbId))
- {
- var searchResults = await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(id, cancellationToken).ConfigureAwait(false);
-
- var searchResult = searchResults.FirstOrDefault();
-
- if (searchResult != null)
- {
- tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
- }
- }
-
- var result = new MetadataResult<BoxSet>();
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- var mainResult = await GetMovieDbResult(tmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult != null)
- {
- result.HasMetadata = true;
- result.Item = GetItem(mainResult);
- }
- }
-
- return result;
- }
-
- internal async Task<RootObject> GetMovieDbResult(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- await EnsureInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, language);
-
- if (!string.IsNullOrEmpty(dataFilePath))
- {
- return _json.DeserializeFromFile<RootObject>(dataFilePath);
- }
-
- return null;
- }
-
- private BoxSet GetItem(RootObject obj)
- {
- var item = new BoxSet
- {
- Name = obj.name,
- Overview = obj.overview
- };
-
- item.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
-
- return item;
- }
-
- private async Task DownloadInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null) return;
-
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _json.SerializeToFile(mainResult, dataFilePath);
- }
-
- private async Task<RootObject> FetchMainResult(string id, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(GetCollectionInfo3, id, MovieDbProvider.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format("&language={0}", MovieDbProvider.NormalizeLanguage(language));
-
- // Get images in english and with no language
- url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- RootObject mainResult = null;
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbSearch.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- mainResult = await _json.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
- }
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- if (mainResult != null && string.IsNullOrEmpty(mainResult.name))
- {
- if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- url = string.Format(GetCollectionInfo3, id, MovieDbSearch.ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
- }
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbSearch.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- mainResult = await _json.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
- }
- }
- }
- }
- return mainResult;
- }
-
- internal Task EnsureInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var path = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadInfo(tmdbId, preferredMetadataLanguage, cancellationToken);
- }
-
- public string Name => "TheMovieDb";
-
- private static string GetDataFilePath(IApplicationPaths appPaths, string tmdbId, string preferredLanguage)
- {
- var path = GetDataPath(appPaths, tmdbId);
-
- var filename = string.Format("all-{0}.json", preferredLanguage ?? string.Empty);
-
- return Path.Combine(path, filename);
- }
-
- private static string GetDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetCollectionsDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- private static string GetCollectionsDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-collections");
-
- return dataPath;
- }
-
- internal class Part
- {
- public string title { get; set; }
- public int id { get; set; }
- public string release_date { get; set; }
- public string poster_path { get; set; }
- public string backdrop_path { get; set; }
- }
-
- internal class Backdrop
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- internal class Poster
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- internal class Images
- {
- public List<Backdrop> backdrops { get; set; }
- public List<Poster> posters { get; set; }
- }
-
- internal class RootObject
- {
- public int id { get; set; }
- public string name { get; set; }
- public string overview { get; set; }
- public string poster_path { get; set; }
- public string backdrop_path { get; set; }
- public List<Part> parts { get; set; }
- public Images images { get; set; }
- }
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
index 0763a0163..db2213bad 100644
--- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
+++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Channels
{
public class ChannelMetadataService : MetadataService<Channel, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<Channel> source, MetadataResult<Channel> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public ChannelMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<ChannelMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public ChannelMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Channel> source, MetadataResult<Channel> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Chapters/ChapterManager.cs b/MediaBrowser.Providers/Chapters/ChapterManager.cs
index 45e87f137..3cbfe7d4d 100644
--- a/MediaBrowser.Providers/Chapters/ChapterManager.cs
+++ b/MediaBrowser.Providers/Chapters/ChapterManager.cs
@@ -1,36 +1,26 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.Chapters;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Chapters
{
public class ChapterManager : IChapterManager
{
- private readonly ILibraryManager _libraryManager;
- private readonly ILogger _logger;
- private readonly IServerConfigurationManager _config;
private readonly IItemRepository _itemRepo;
- public ChapterManager(
- ILibraryManager libraryManager,
- ILoggerFactory loggerFactory,
- IServerConfigurationManager config,
- IItemRepository itemRepo)
+ public ChapterManager(IItemRepository itemRepo)
{
- _libraryManager = libraryManager;
- _logger = loggerFactory.CreateLogger(nameof(ChapterManager));
- _config = config;
_itemRepo = itemRepo;
}
- public void SaveChapters(string itemId, List<ChapterInfo> chapters)
+ /// <inheritdoc />
+ public void SaveChapters(Guid itemId, IReadOnlyList<ChapterInfo> chapters)
{
- _itemRepo.SaveChapters(new Guid(itemId), chapters);
+ _itemRepo.SaveChapters(itemId, chapters);
}
}
}
diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
index 2c28b3e35..e0f3131fd 100644
--- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
@@ -1,3 +1,4 @@
+#pragma warning disable CS1591
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -12,13 +13,20 @@ namespace MediaBrowser.Providers.Folders
{
public class CollectionFolderMetadataService : MetadataService<CollectionFolder, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<CollectionFolder> source, MetadataResult<CollectionFolder> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public CollectionFolderMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<CollectionFolderMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public CollectionFolderMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<CollectionFolder> source, MetadataResult<CollectionFolder> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
index bb1634422..998bf4c6a 100644
--- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,16 +13,24 @@ namespace MediaBrowser.Providers.Folders
{
public class FolderMetadataService : MetadataService<Folder, ItemLookupInfo>
{
+ 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;
- protected override void MergeData(MetadataResult<Folder> source, MetadataResult<Folder> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Folder> source, MetadataResult<Folder> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
-
- public FolderMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
index 8d6e77aeb..2d536f12e 100644
--- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Folders
{
public class UserViewMetadataService : MetadataService<UserView, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<UserView> source, MetadataResult<UserView> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public UserViewMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<UserViewMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public UserViewMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<UserView> source, MetadataResult<UserView> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
index 28a46b008..f7ea767e7 100644
--- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs
+++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Genres
{
public class GenreMetadataService : MetadataService<Genre, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<Genre> source, MetadataResult<Genre> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public GenreMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<GenreMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public GenreMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Genre> source, MetadataResult<Genre> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs b/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs
index 6009d3a58..2e6cf4530 100644
--- a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs
+++ b/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.LiveTv
{
public class LiveTvMetadataService : MetadataService<LiveTvChannel, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<LiveTvChannel> source, MetadataResult<LiveTvChannel> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public LiveTvMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<LiveTvMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public LiveTvMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<LiveTvChannel> source, MetadataResult<LiveTvChannel> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs
index ab906809f..8ded2d144 100644
--- a/MediaBrowser.Providers/Manager/ImageSaver.cs
+++ b/MediaBrowser.Providers/Manager/ImageSaver.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -9,30 +13,31 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Person = MediaBrowser.Controller.Entities.Person;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
namespace MediaBrowser.Providers.Manager
{
/// <summary>
- /// Class ImageSaver
+ /// Class ImageSaver.
/// </summary>
public class ImageSaver
{
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
/// <summary>
- /// The _config
+ /// The _config.
/// </summary>
private readonly IServerConfigurationManager _config;
/// <summary>
- /// The _directory watchers
+ /// The _directory watchers.
/// </summary>
private readonly ILibraryMonitor _libraryMonitor;
private readonly IFileSystem _fileSystem;
@@ -53,6 +58,16 @@ namespace MediaBrowser.Providers.Manager
_logger = logger;
}
+ private bool EnableExtraThumbsDuplication
+ {
+ get
+ {
+ var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
+
+ return config.EnableExtraThumbsDuplication;
+ }
+ }
+
/// <summary>
/// Saves the image.
/// </summary>
@@ -63,7 +78,7 @@ namespace MediaBrowser.Providers.Manager
/// <param name="imageIndex">Index of the image.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- /// <exception cref="ArgumentNullException">mimeType</exception>
+ /// <exception cref="ArgumentNullException">mimeType.</exception>
public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
return SaveImage(item, source, mimeType, type, imageIndex, null, cancellationToken);
@@ -76,12 +91,7 @@ namespace MediaBrowser.Providers.Manager
throw new ArgumentNullException(nameof(mimeType));
}
- var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && !(item is Audio);
-
- if (item is User)
- {
- saveLocally = true;
- }
+ var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && item is not Audio;
if (type != ImageType.Primary && item is Episode)
{
@@ -92,10 +102,8 @@ namespace MediaBrowser.Providers.Manager
{
saveLocally = false;
- var season = item as Season;
-
// If season is virtual under a physical series, save locally if using compatible convention
- if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
+ if (item is Season season && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
{
var series = season.Series;
@@ -105,6 +113,7 @@ namespace MediaBrowser.Providers.Manager
}
}
}
+
if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
{
saveLocally = saveLocallyWithMedia.Value;
@@ -122,35 +131,40 @@ namespace MediaBrowser.Providers.Manager
var retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);
// If there are more than one output paths, the stream will need to be seekable
- var memoryStream = new MemoryStream();
- using (source)
+ if (paths.Length > 1 && !source.CanSeek)
{
- await source.CopyToAsync(memoryStream).ConfigureAwait(false);
- }
+ var memoryStream = new MemoryStream();
+ await using (source.ConfigureAwait(false))
+ {
+ await source.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
+ }
- source = memoryStream;
+ source = memoryStream;
+ }
var currentImage = GetCurrentImage(item, type, index);
var currentImageIsLocalFile = currentImage != null && currentImage.IsLocalFile;
- var currentImagePath = currentImage == null ? null : currentImage.Path;
+ var currentImagePath = currentImage?.Path;
var savedPaths = new List<string>();
- using (source)
+ await using (source.ConfigureAwait(false))
{
- var currentPathIndex = 0;
-
- foreach (var path in paths)
+ for (int i = 0; i < paths.Length; i++)
{
- source.Position = 0;
+ if (i != 0)
+ {
+ source.Position = 0;
+ }
+
string retryPath = null;
if (paths.Length == retryPaths.Length)
{
- retryPath = retryPaths[currentPathIndex];
+ retryPath = retryPaths[i];
}
- var savedPath = await SaveImageToLocation(source, path, retryPath, cancellationToken).ConfigureAwait(false);
+
+ var savedPath = await SaveImageToLocation(source, paths[i], retryPath, cancellationToken).ConfigureAwait(false);
savedPaths.Add(savedPath);
- currentPathIndex++;
}
}
@@ -158,7 +172,9 @@ namespace MediaBrowser.Providers.Manager
SetImagePath(item, type, imageIndex, savedPaths[0]);
// Delete the current path
- if (currentImageIsLocalFile && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase))
+ if (currentImageIsLocalFile
+ && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase)
+ && (saveLocally || currentImagePath.Contains(_config.ApplicationPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase)))
{
var currentPath = currentImagePath;
@@ -172,7 +188,6 @@ namespace MediaBrowser.Providers.Manager
}
catch (FileNotFoundException)
{
-
}
finally
{
@@ -181,6 +196,11 @@ namespace MediaBrowser.Providers.Manager
}
}
+ public async Task SaveImage(Stream source, string path)
+ {
+ await SaveImageToLocation(source, path, path, CancellationToken.None).ConfigureAwait(false);
+ }
+
private async Task<string> SaveImageToLocation(Stream source, string path, string retryPath, CancellationToken cancellationToken)
{
try
@@ -217,7 +237,6 @@ namespace MediaBrowser.Providers.Manager
}
}
- source.Position = 0;
await SaveImageToLocation(source, retryPath, cancellationToken).ConfigureAwait(false);
return retryPath;
}
@@ -244,9 +263,12 @@ namespace MediaBrowser.Providers.Manager
_fileSystem.SetAttributes(path, false, false);
- using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.Asynchronous))
+ var fileStreamOptions = AsyncFile.WriteOptions;
+ fileStreamOptions.Mode = FileMode.Create;
+ fileStreamOptions.PreallocationSize = source.Length;
+ await using (var fs = new FileStream(path, fileStreamOptions))
{
- await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
+ await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
}
if (_config.Configuration.SaveMetadataHidden)
@@ -302,7 +324,7 @@ namespace MediaBrowser.Providers.Manager
/// <exception cref="ArgumentNullException">
/// imageIndex
/// or
- /// imageIndex
+ /// imageIndex.
/// </exception>
private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
{
@@ -318,7 +340,8 @@ namespace MediaBrowser.Providers.Manager
/// <param name="path">The path.</param>
/// <exception cref="ArgumentNullException">imageIndex
/// or
- /// imageIndex</exception>
+ /// imageIndex.
+ /// </exception>
private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
{
item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
@@ -336,7 +359,7 @@ namespace MediaBrowser.Providers.Manager
/// <exception cref="ArgumentNullException">
/// imageIndex
/// or
- /// imageIndex
+ /// imageIndex.
/// </exception>
private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
{
@@ -345,7 +368,7 @@ namespace MediaBrowser.Providers.Manager
if (string.IsNullOrWhiteSpace(extension))
{
- throw new ArgumentException(string.Format("Unable to determine image file extension from mime type {0}", mimeType));
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to determine image file extension from mime type {0}", mimeType));
}
if (type == ImageType.Thumb && saveLocally)
@@ -356,7 +379,7 @@ namespace MediaBrowser.Providers.Manager
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
- : season.IndexNumber.Value.ToString("00", UsCulture);
+ : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
var imageFilename = "season" + seasonMarker + "-landscape" + extension;
@@ -379,7 +402,7 @@ namespace MediaBrowser.Providers.Manager
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
- : season.IndexNumber.Value.ToString("00", UsCulture);
+ : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
var imageFilename = "season" + seasonMarker + "-banner" + extension;
@@ -439,7 +462,6 @@ namespace MediaBrowser.Providers.Manager
{
path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
}
-
else if (item.IsInMixedFolder)
{
path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
@@ -458,6 +480,7 @@ namespace MediaBrowser.Providers.Manager
{
filename = folderName;
}
+
path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
}
@@ -474,12 +497,12 @@ namespace MediaBrowser.Providers.Manager
var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
var current = 1;
- while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
+ while (filenames.Contains(numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase))
{
current++;
}
- return numberedIndexPrefix + current.ToString(UsCulture);
+ return numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
@@ -490,7 +513,7 @@ namespace MediaBrowser.Providers.Manager
/// <param name="imageIndex">Index of the image.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <returns>IEnumerable{System.String}.</returns>
- /// <exception cref="ArgumentNullException">imageIndex</exception>
+ /// <exception cref="ArgumentNullException">imageIndex.</exception>
private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
{
var season = item as Season;
@@ -518,7 +541,7 @@ namespace MediaBrowser.Providers.Manager
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
- : season.IndexNumber.Value.ToString("00", UsCulture);
+ : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
var imageFilename = "season" + seasonMarker + "-fanart" + extension;
@@ -535,7 +558,7 @@ namespace MediaBrowser.Providers.Manager
if (item.IsInMixedFolder)
{
- return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
+ return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(CultureInfo.InvariantCulture), extension) };
}
var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
@@ -547,8 +570,9 @@ namespace MediaBrowser.Providers.Manager
if (EnableExtraThumbsDuplication)
{
- list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
+ list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(CultureInfo.InvariantCulture) + extension));
}
+
return list.ToArray();
}
@@ -560,7 +584,7 @@ namespace MediaBrowser.Providers.Manager
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
- : season.IndexNumber.Value.ToString("00", UsCulture);
+ : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
var imageFilename = "season" + seasonMarker + "-poster" + extension;
@@ -593,16 +617,6 @@ namespace MediaBrowser.Providers.Manager
return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
}
- private bool EnableExtraThumbsDuplication
- {
- get
- {
- var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
-
- return config.EnableExtraThumbsDuplication;
- }
- }
-
/// <summary>
/// Gets the save path for item in mixed folder.
/// </summary>
@@ -617,6 +631,7 @@ namespace MediaBrowser.Providers.Manager
{
imageFilename = "poster";
}
+
var folder = Path.GetDirectoryName(item.Path);
return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
index 033aea146..39372acb9 100644
--- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs
+++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
@@ -1,11 +1,15 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
@@ -25,14 +29,28 @@ namespace MediaBrowser.Providers.Manager
{
private readonly ILogger _logger;
private readonly IProviderManager _providerManager;
- private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
- public ItemImageProvider(ILogger logger, IProviderManager providerManager, IServerConfigurationManager config, IFileSystem fileSystem)
+ /// <summary>
+ /// Image types that are only one per item.
+ /// </summary>
+ private static readonly ImageType[] _singularImages =
+ {
+ ImageType.Primary,
+ ImageType.Art,
+ ImageType.Banner,
+ ImageType.Box,
+ ImageType.BoxRear,
+ ImageType.Disc,
+ ImageType.Logo,
+ ImageType.Menu,
+ ImageType.Thumb
+ };
+
+ public ItemImageProvider(ILogger logger, IProviderManager providerManager, IFileSystem fileSystem)
{
_logger = logger;
_providerManager = providerManager;
- _config = config;
_fileSystem = fileSystem;
}
@@ -40,9 +58,9 @@ namespace MediaBrowser.Providers.Manager
{
var hasChanges = false;
- if (!(item is Photo))
+ if (item is not Photo)
{
- var images = providers.OfType<ILocalImageFileProvider>()
+ var images = providers.OfType<ILocalImageProvider>()
.SelectMany(i => i.GetImages(item, directoryService))
.ToList();
@@ -55,12 +73,18 @@ namespace MediaBrowser.Providers.Manager
return hasChanges;
}
- public async Task<RefreshResult> RefreshImages(BaseItem item, LibraryOptions libraryOptions, List<IImageProvider> providers, ImageRefreshOptions refreshOptions, MetadataOptions savedOptions, CancellationToken cancellationToken)
+ public async Task<RefreshResult> RefreshImages(
+ BaseItem item,
+ LibraryOptions libraryOptions,
+ List<IImageProvider> providers,
+ ImageRefreshOptions refreshOptions,
+ CancellationToken cancellationToken)
{
if (refreshOptions.IsReplacingImage(ImageType.Backdrop))
{
ClearImages(item, ImageType.Backdrop);
}
+
if (refreshOptions.IsReplacingImage(ImageType.Screenshot))
{
ClearImages(item, ImageType.Screenshot);
@@ -78,19 +102,15 @@ namespace MediaBrowser.Providers.Manager
foreach (var provider in providers)
{
- var remoteProvider = provider as IRemoteImageProvider;
-
- if (remoteProvider != null)
+ if (provider is IRemoteImageProvider remoteProvider)
{
- await RefreshFromProvider(item, libraryOptions, remoteProvider, refreshOptions, typeOptions, backdropLimit, screenshotLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false);
+ await RefreshFromProvider(item, remoteProvider, refreshOptions, typeOptions, backdropLimit, screenshotLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false);
continue;
}
- var dynamicImageProvider = provider as IDynamicImageProvider;
-
- if (dynamicImageProvider != null)
+ if (provider is IDynamicImageProvider dynamicImageProvider)
{
- await RefreshFromProvider(item, dynamicImageProvider, refreshOptions, typeOptions, libraryOptions, downloadedImages, result, cancellationToken).ConfigureAwait(false);
+ await RefreshFromProvider(item, dynamicImageProvider, refreshOptions, typeOptions, downloadedImages, result, cancellationToken).ConfigureAwait(false);
}
}
@@ -100,11 +120,11 @@ namespace MediaBrowser.Providers.Manager
/// <summary>
/// Refreshes from provider.
/// </summary>
- private async Task RefreshFromProvider(BaseItem item,
+ private async Task RefreshFromProvider(
+ BaseItem item,
IDynamicImageProvider provider,
ImageRefreshOptions refreshOptions,
TypeOptions savedOptions,
- LibraryOptions libraryOptions,
ICollection<ImageType> downloadedImages,
RefreshResult result,
CancellationToken cancellationToken)
@@ -115,7 +135,10 @@ namespace MediaBrowser.Providers.Manager
foreach (var imageType in images)
{
- if (!IsEnabled(savedOptions, imageType, item)) continue;
+ if (!IsEnabled(savedOptions, imageType))
+ {
+ continue;
+ }
if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
{
@@ -130,18 +153,19 @@ namespace MediaBrowser.Providers.Manager
if (response.Protocol == MediaProtocol.Http)
{
_logger.LogDebug("Setting image url into item {0}", item.Id);
- item.SetImage(new ItemImageInfo
- {
- Path = response.Path,
- Type = imageType
-
- }, 0);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = response.Path,
+ Type = imageType
+ },
+ 0);
}
else
{
var mimeType = MimeTypes.GetMimeType(response.Path);
- var stream = _fileSystem.GetFileStream(response.Path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
+ var stream = AsyncFile.OpenRead(response.Path);
await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
}
@@ -154,7 +178,7 @@ namespace MediaBrowser.Providers.Manager
}
downloadedImages.Add(imageType);
- result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
+ result.UpdateType |= ItemUpdateType.ImageUpdate;
}
}
}
@@ -170,29 +194,13 @@ namespace MediaBrowser.Providers.Manager
}
}
- /// <summary>
- /// Image types that are only one per item
- /// </summary>
- private readonly ImageType[] _singularImages =
- {
- ImageType.Primary,
- ImageType.Art,
- ImageType.Banner,
- ImageType.Box,
- ImageType.BoxRear,
- ImageType.Disc,
- ImageType.Logo,
- ImageType.Menu,
- ImageType.Thumb
- };
-
private bool HasImage(BaseItem item, ImageType type)
{
return item.HasImage(type);
}
/// <summary>
- /// Determines if an item already contains the given images
+ /// Determines if an item already contains the given images.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="images">The images.</param>
@@ -202,9 +210,14 @@ namespace MediaBrowser.Providers.Manager
/// <returns><c>true</c> if the specified item contains images; otherwise, <c>false</c>.</returns>
private bool ContainsImages(BaseItem item, List<ImageType> images, TypeOptions savedOptions, int backdropLimit, int screenshotLimit)
{
- if (_singularImages.Any(i => images.Contains(i) && !HasImage(item, i) && savedOptions.GetLimit(i) > 0))
+ // Using .Any causes the creation of a DisplayClass aka. variable capture
+ for (var i = 0; i < _singularImages.Length; i++)
{
- return false;
+ var type = _singularImages[i];
+ if (images.Contains(type) && !HasImage(item, type) && savedOptions.GetLimit(type) > 0)
+ {
+ return false;
+ }
}
if (images.Contains(ImageType.Backdrop) && item.GetImages(ImageType.Backdrop).Count() < backdropLimit)
@@ -233,7 +246,8 @@ namespace MediaBrowser.Providers.Manager
/// <param name="result">The result.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- private async Task RefreshFromProvider(BaseItem item, LibraryOptions libraryOptions,
+ private async Task RefreshFromProvider(
+ BaseItem item,
IRemoteImageProvider provider,
ImageRefreshOptions refreshOptions,
TypeOptions savedOptions,
@@ -259,25 +273,29 @@ namespace MediaBrowser.Providers.Manager
_logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
- var images = await _providerManager.GetAvailableRemoteImages(item, new RemoteImageQuery
- {
- ProviderName = provider.Name,
- IncludeAllLanguages = false,
- IncludeDisabledProviders = false,
-
- }, cancellationToken).ConfigureAwait(false);
+ var images = await _providerManager.GetAvailableRemoteImages(
+ item,
+ new RemoteImageQuery(provider.Name)
+ {
+ IncludeAllLanguages = true,
+ IncludeDisabledProviders = false,
+ },
+ cancellationToken).ConfigureAwait(false);
var list = images.ToList();
int minWidth;
foreach (var imageType in _singularImages)
{
- if (!IsEnabled(savedOptions, imageType, item)) continue;
+ if (!IsEnabled(savedOptions, imageType))
+ {
+ continue;
+ }
if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
{
minWidth = savedOptions.GetMinWidth(imageType);
- var downloaded = await DownloadImage(item, libraryOptions, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);
+ var downloaded = await DownloadImage(item, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);
if (downloaded)
{
@@ -287,13 +305,12 @@ namespace MediaBrowser.Providers.Manager
}
minWidth = savedOptions.GetMinWidth(ImageType.Backdrop);
- await DownloadBackdrops(item, libraryOptions, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
+ await DownloadBackdrops(item, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
- var hasScreenshots = item as IHasScreenshots;
- if (hasScreenshots != null)
+ if (item is IHasScreenshots hasScreenshots)
{
minWidth = savedOptions.GetMinWidth(ImageType.Screenshot);
- await DownloadBackdrops(item, libraryOptions, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
+ await DownloadBackdrops(item, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -307,7 +324,7 @@ namespace MediaBrowser.Providers.Manager
}
}
- private bool IsEnabled(TypeOptions options, ImageType type, BaseItem item)
+ private bool IsEnabled(TypeOptions options, ImageType type)
{
return options.IsEnabled(type);
}
@@ -317,7 +334,7 @@ namespace MediaBrowser.Providers.Manager
var deleted = false;
var deletedImages = new List<ItemImageInfo>();
- foreach (var image in item.GetImages(type).ToList())
+ foreach (var image in item.GetImages(type))
{
if (!image.IsLocalFile)
{
@@ -332,7 +349,6 @@ namespace MediaBrowser.Providers.Manager
}
catch (FileNotFoundException)
{
-
}
}
@@ -340,17 +356,18 @@ namespace MediaBrowser.Providers.Manager
if (deleted)
{
- item.ValidateImages(new DirectoryService(_logger, _fileSystem));
+ item.ValidateImages(new DirectoryService(_fileSystem));
}
}
- public bool MergeImages(BaseItem item, List<LocalImageInfo> images)
+ public bool MergeImages(BaseItem item, IReadOnlyList<LocalImageInfo> images)
{
var changed = false;
- foreach (var type in _singularImages)
+ for (var i = 0; i < _singularImages.Length; i++)
{
- var image = images.FirstOrDefault(i => i.Type == type);
+ var type = _singularImages[i];
+ var image = GetFirstLocalImageInfoByType(images, type);
if (image != null)
{
@@ -368,7 +385,6 @@ namespace MediaBrowser.Providers.Manager
}
else
{
-
var newDateModified = _fileSystem.GetLastWriteTimeUtc(image.FileInfo);
// If date changed then we need to reset saved image dimensions
@@ -413,15 +429,29 @@ namespace MediaBrowser.Providers.Manager
return changed;
}
- private bool UpdateMultiImages(BaseItem item, List<LocalImageInfo> images, ImageType type)
+ private static LocalImageInfo GetFirstLocalImageInfoByType(IReadOnlyList<LocalImageInfo> images, ImageType type)
{
- var changed = false;
+ var len = images.Count;
+ for (var i = 0; i < len; i++)
+ {
+ var image = images[i];
+ if (image.Type == type)
+ {
+ return image;
+ }
+ }
- var newImages = images.Where(i => i.Type == type).ToList();
+ return null;
+ }
- var newImageFileInfos = newImages
- .Select(i => i.FileInfo)
- .ToList();
+ private bool UpdateMultiImages(BaseItem item, IReadOnlyList<LocalImageInfo> images, ImageType type)
+ {
+ var changed = false;
+
+ var newImageFileInfos = images
+ .Where(i => i.Type == type)
+ .Select(i => i.FileInfo)
+ .ToList();
if (item.AddImages(type, newImageFileInfos))
{
@@ -431,7 +461,8 @@ namespace MediaBrowser.Providers.Manager
return changed;
}
- private async Task<bool> DownloadImage(BaseItem item, LibraryOptions libraryOptions,
+ private async Task<bool> DownloadImage(
+ BaseItem item,
IRemoteImageProvider provider,
RefreshResult result,
IEnumerable<RemoteImageInfo> images,
@@ -440,13 +471,13 @@ namespace MediaBrowser.Providers.Manager
CancellationToken cancellationToken)
{
var eligibleImages = images
- .Where(i => i.Type == type && !(i.Width.HasValue && i.Width.Value < minWidth))
+ .Where(i => i.Type == type && i.Width >= minWidth)
.ToList();
- if (EnableImageStub(item, type, libraryOptions) && eligibleImages.Count > 0)
+ if (EnableImageStub(item) && eligibleImages.Count > 0)
{
SaveImageStub(item, type, eligibleImages.Select(i => i.Url));
- result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
+ result.UpdateType |= ItemUpdateType.ImageUpdate;
return true;
}
@@ -456,20 +487,36 @@ namespace MediaBrowser.Providers.Manager
try
{
- var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
+ using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
+
+ // Sometimes providers send back bad urls. Just move to the next image
+ if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Forbidden)
+ {
+ _logger.LogDebug("{Url} returned {StatusCode}, ignoring", url, response.StatusCode);
+ continue;
+ }
+
+ if (!response.IsSuccessStatusCode)
+ {
+ _logger.LogWarning("{Url} returned {StatusCode}, skipping all remaining requests", url, response.StatusCode);
+ break;
+ }
- await _providerManager.SaveImage(item, response.Content, response.ContentType, type, null, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
+ await _providerManager.SaveImage(
+ item,
+ stream,
+ response.Content.Headers.ContentType.MediaType,
+ type,
+ null,
+ cancellationToken).ConfigureAwait(false);
+
+ result.UpdateType |= ItemUpdateType.ImageUpdate;
return true;
}
- catch (HttpException ex)
+ catch (HttpRequestException)
{
- // Sometimes providers send back bad url's. Just move to the next image
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- continue;
- }
break;
}
}
@@ -477,7 +524,7 @@ namespace MediaBrowser.Providers.Manager
return false;
}
- private bool EnableImageStub(BaseItem item, ImageType type, LibraryOptions libraryOptions)
+ private bool EnableImageStub(BaseItem item)
{
if (item is LiveTvProgram)
{
@@ -489,7 +536,7 @@ namespace MediaBrowser.Providers.Manager
return true;
}
- if (item is IItemByName && !(item is MusicArtist))
+ if (item is IItemByName && item is not MusicArtist)
{
var hasDualAccess = item as IHasDualAccess;
if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
@@ -498,17 +545,8 @@ namespace MediaBrowser.Providers.Manager
}
}
- if (libraryOptions.DownloadImagesInAdvance)
- {
- return false;
- }
-
- //if (!item.IsSaveLocalMetadataEnabled())
- //{
- // return true;
- //}
-
- return true;
+ // We always want to use prefetched images
+ return false;
}
private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable<string> urls)
@@ -520,17 +558,18 @@ namespace MediaBrowser.Providers.Manager
private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable<string> urls, int newIndex)
{
- var path = string.Join("|", urls.Take(1).ToArray());
-
- item.SetImage(new ItemImageInfo
- {
- Path = path,
- Type = imageType
+ var path = string.Join('|', urls.Take(1));
- }, newIndex);
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = path,
+ Type = imageType
+ },
+ newIndex);
}
- private async Task DownloadBackdrops(BaseItem item, LibraryOptions libraryOptions, ImageType imageType, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken)
+ private async Task DownloadBackdrops(BaseItem item, ImageType imageType, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken)
{
foreach (var image in images.Where(i => i.Type == imageType))
{
@@ -546,23 +585,36 @@ namespace MediaBrowser.Providers.Manager
var url = image.Url;
- if (EnableImageStub(item, imageType, libraryOptions))
+ if (EnableImageStub(item))
{
SaveImageStub(item, imageType, new[] { url });
- result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
+ result.UpdateType |= ItemUpdateType.ImageUpdate;
continue;
}
try
{
- var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
+ using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
+
+ // Sometimes providers send back bad urls. Just move to the next image
+ if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Forbidden)
+ {
+ _logger.LogDebug("{Url} returned {StatusCode}, ignoring", url, response.StatusCode);
+ continue;
+ }
+
+ if (!response.IsSuccessStatusCode)
+ {
+ _logger.LogWarning("{Url} returned {StatusCode}, skipping all remaining requests", url, response.StatusCode);
+ break;
+ }
// If there's already an image of the same size, skip it
- if (response.ContentLength.HasValue)
+ if (response.Content.Headers.ContentLength.HasValue)
{
try
{
- if (item.GetImages(imageType).Any(i => _fileSystem.GetFileInfo(i.Path).Length == response.ContentLength.Value))
+ if (item.GetImages(imageType).Any(i => _fileSystem.GetFileInfo(i.Path).Length == response.Content.Headers.ContentLength.Value))
{
response.Content.Dispose();
continue;
@@ -574,16 +626,18 @@ namespace MediaBrowser.Providers.Manager
}
}
- await _providerManager.SaveImage(item, response.Content, response.ContentType, imageType, null, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await _providerManager.SaveImage(
+ item,
+ stream,
+ response.Content.Headers.ContentType.MediaType,
+ imageType,
+ null,
+ cancellationToken).ConfigureAwait(false);
result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
}
- catch (HttpException ex)
+ catch (HttpRequestException)
{
- // Sometimes providers send back bad urls. Just move onto the next image
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- continue;
- }
break;
}
}
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index 77028e526..ffb3baeb1 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -19,23 +23,38 @@ namespace MediaBrowser.Providers.Manager
where TItemType : BaseItem, IHasLookupInfo<TIdType>, new()
where TIdType : ItemLookupInfo, new()
{
- protected readonly IServerConfigurationManager ServerConfigurationManager;
- protected readonly ILogger Logger;
- protected readonly IProviderManager ProviderManager;
- protected readonly IFileSystem FileSystem;
- protected readonly IUserDataManager UserDataManager;
- protected readonly ILibraryManager LibraryManager;
-
- protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager)
+ protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger<MetadataService<TItemType, TIdType>> logger, IProviderManager providerManager, IFileSystem fileSystem, ILibraryManager libraryManager)
{
ServerConfigurationManager = serverConfigurationManager;
Logger = logger;
ProviderManager = providerManager;
FileSystem = fileSystem;
- UserDataManager = userDataManager;
LibraryManager = libraryManager;
+ ImageProvider = new ItemImageProvider(Logger, ProviderManager, FileSystem);
}
+ protected ItemImageProvider ImageProvider { get; }
+
+ protected IServerConfigurationManager ServerConfigurationManager { get; }
+
+ protected ILogger<MetadataService<TItemType, TIdType>> Logger { get; }
+
+ protected IProviderManager ProviderManager { get; }
+
+ protected IFileSystem FileSystem { get; }
+
+ protected ILibraryManager LibraryManager { get; }
+
+ protected virtual bool EnableUpdatingPremiereDateFromChildren => false;
+
+ protected virtual bool EnableUpdatingGenresFromChildren => false;
+
+ protected virtual bool EnableUpdatingStudiosFromChildren => false;
+
+ protected virtual bool EnableUpdatingOfficialRatingFromChildren => false;
+
+ public virtual int Order => 0;
+
private FileSystemMetadata TryGetFile(string path, IDirectoryService directoryService)
{
try
@@ -44,7 +63,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error getting file {path}", path);
+ Logger.LogError(ex, "Error getting file {Path}", path);
return null;
}
}
@@ -52,7 +71,6 @@ namespace MediaBrowser.Providers.Manager
public async Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
{
var itemOfType = (TItemType)item;
- var config = ProviderManager.GetMetadataOptions(item);
var updateType = ItemUpdateType.None;
var requiresRefresh = false;
@@ -75,7 +93,6 @@ namespace MediaBrowser.Providers.Manager
}
}
- var itemImageProvider = new ItemImageProvider(Logger, ProviderManager, ServerConfigurationManager, FileSystem);
var localImagesFailed = false;
var allImageProviders = ((ProviderManager)ProviderManager).GetImageProviders(item, refreshOptions).ToList();
@@ -84,18 +101,15 @@ namespace MediaBrowser.Providers.Manager
try
{
// Always validate images and check for new locally stored ones.
- if (itemImageProvider.ValidateImages(item, allImageProviders.OfType<ILocalImageProvider>(), refreshOptions.DirectoryService))
+ if (ImageProvider.ValidateImages(item, allImageProviders.OfType<ILocalImageProvider>(), refreshOptions.DirectoryService))
{
- updateType = updateType | ItemUpdateType.ImageUpdate;
+ updateType |= ItemUpdateType.ImageUpdate;
}
}
catch (Exception ex)
{
localImagesFailed = true;
- if (!(item is IItemByName))
- {
- Logger.LogError(ex, "Error validating images for {0}", item.Path ?? item.Name ?? "Unknown name");
- }
+ Logger.LogError(ex, "Error validating images for {0}", item.Path ?? item.Name ?? "Unknown name");
}
var metadataResult = new MetadataResult<TItemType>
@@ -105,7 +119,7 @@ namespace MediaBrowser.Providers.Manager
bool hasRefreshedMetadata = true;
bool hasRefreshedImages = true;
- var isFirstRefresh = item.DateLastRefreshed == default(DateTime);
+ var isFirstRefresh = item.DateLastRefreshed == default;
// Next run metadata providers
if (refreshOptions.MetadataRefreshMode != MetadataRefreshMode.None)
@@ -117,7 +131,7 @@ namespace MediaBrowser.Providers.Manager
{
if (item.BeforeMetadataRefresh(refreshOptions.ReplaceAllMetadata))
{
- updateType = updateType | ItemUpdateType.MetadataImport;
+ updateType |= ItemUpdateType.MetadataImport;
}
}
@@ -130,12 +144,12 @@ namespace MediaBrowser.Providers.Manager
ApplySearchResult(id, refreshOptions.SearchResult);
}
- //await FindIdentities(id, cancellationToken).ConfigureAwait(false);
+ // await FindIdentities(id, cancellationToken).ConfigureAwait(false);
id.IsAutomated = refreshOptions.IsAutomated;
- var result = await RefreshWithProviders(metadataResult, id, refreshOptions, providers, itemImageProvider, cancellationToken).ConfigureAwait(false);
+ var result = await RefreshWithProviders(metadataResult, id, refreshOptions, providers, ImageProvider, cancellationToken).ConfigureAwait(false);
- updateType = updateType | result.UpdateType;
+ updateType |= result.UpdateType;
if (result.Failures > 0)
{
hasRefreshedMetadata = false;
@@ -150,9 +164,9 @@ namespace MediaBrowser.Providers.Manager
if (providers.Count > 0)
{
- var result = await itemImageProvider.RefreshImages(itemOfType, libraryOptions, providers, refreshOptions, config, cancellationToken).ConfigureAwait(false);
+ var result = await ImageProvider.RefreshImages(itemOfType, libraryOptions, providers, refreshOptions, cancellationToken).ConfigureAwait(false);
- updateType = updateType | result.UpdateType;
+ updateType |= result.UpdateType;
if (result.Failures > 0)
{
hasRefreshedImages = false;
@@ -161,7 +175,7 @@ namespace MediaBrowser.Providers.Manager
}
var beforeSaveResult = BeforeSave(itemOfType, isFirstRefresh || refreshOptions.ReplaceAllMetadata || refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || requiresRefresh || refreshOptions.ForceSave, updateType);
- updateType = updateType | beforeSaveResult;
+ updateType |= beforeSaveResult;
// Save if changes were made, or it's never been saved before
if (refreshOptions.ForceSave || updateType > ItemUpdateType.None || isFirstRefresh || refreshOptions.ReplaceAllMetadata || requiresRefresh)
@@ -178,7 +192,7 @@ namespace MediaBrowser.Providers.Manager
// If any of these properties are set then make sure the updateType is not None, just to force everything to save
if (refreshOptions.ForceSave || refreshOptions.ReplaceAllMetadata)
{
- updateType = updateType | ItemUpdateType.MetadataDownload;
+ updateType |= ItemUpdateType.MetadataDownload;
}
if (hasRefreshedMetadata && hasRefreshedImages)
@@ -187,11 +201,11 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- item.DateLastRefreshed = default(DateTime);
+ item.DateLastRefreshed = default;
}
// Save to database
- SaveItem(metadataResult, libraryOptions, updateType, cancellationToken);
+ await SaveItemAsync(metadataResult, updateType, cancellationToken).ConfigureAwait(false);
}
await AfterMetadataRefresh(itemOfType, refreshOptions, cancellationToken).ConfigureAwait(false);
@@ -201,80 +215,35 @@ namespace MediaBrowser.Providers.Manager
private void ApplySearchResult(ItemLookupInfo lookupInfo, RemoteSearchResult result)
{
- lookupInfo.ProviderIds = result.ProviderIds;
- lookupInfo.Name = result.Name;
- lookupInfo.Year = result.ProductionYear;
+ // Episode and Season do not support Identify, so the search results are the Series'
+ switch (lookupInfo)
+ {
+ case EpisodeInfo episodeInfo:
+ episodeInfo.SeriesProviderIds = result.ProviderIds;
+ episodeInfo.ProviderIds.Clear();
+ break;
+ case SeasonInfo seasonInfo:
+ seasonInfo.SeriesProviderIds = result.ProviderIds;
+ seasonInfo.ProviderIds.Clear();
+ break;
+ default:
+ lookupInfo.ProviderIds = result.ProviderIds;
+ lookupInfo.Name = result.Name;
+ lookupInfo.Year = result.ProductionYear;
+ break;
+ }
}
- protected void SaveItem(MetadataResult<TItemType> result, LibraryOptions libraryOptions, ItemUpdateType reason, CancellationToken cancellationToken)
+ protected async Task SaveItemAsync(MetadataResult<TItemType> result, ItemUpdateType reason, CancellationToken cancellationToken)
{
if (result.Item.SupportsPeople && result.People != null)
{
var baseItem = result.Item;
- LibraryManager.UpdatePeople(baseItem, result.People);
- SavePeopleMetadata(result.People, libraryOptions, cancellationToken);
+ await LibraryManager.UpdatePeopleAsync(baseItem, result.People, cancellationToken).ConfigureAwait(false);
}
- result.Item.UpdateToRepository(reason, cancellationToken);
- }
-
- private void SavePeopleMetadata(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken)
- {
- foreach (var person in people)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (person.ProviderIds.Any() || !string.IsNullOrWhiteSpace(person.ImageUrl))
- {
- var updateType = ItemUpdateType.MetadataDownload;
- var saveEntity = false;
- var personEntity = LibraryManager.GetPerson(person.Name);
- foreach (var id in person.ProviderIds)
- {
- if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase))
- {
- personEntity.SetProviderId(id.Key, id.Value);
- saveEntity = true;
- }
- }
-
- if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
- {
- AddPersonImage(personEntity, libraryOptions, person.ImageUrl, cancellationToken);
-
- saveEntity = true;
- updateType = updateType | ItemUpdateType.ImageUpdate;
- }
-
- if (saveEntity)
- {
- personEntity.UpdateToRepository(updateType, cancellationToken);
- }
- }
- }
- }
-
- private void AddPersonImage(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken)
- {
- //if (libraryOptions.DownloadImagesInAdvance)
- //{
- // try
- // {
- // await ProviderManager.SaveImage(personEntity, imageUrl, ImageType.Primary, null, cancellationToken).ConfigureAwait(false);
- // return;
- // }
- // catch (Exception ex)
- // {
- // Logger.LogError(ex, "Error in AddPersonImage");
- // }
- //}
-
- personEntity.SetImage(new ItemImageInfo
- {
- Path = imageUrl,
- Type = ImageType.Primary
- }, 0);
+ await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false);
}
protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
@@ -284,7 +253,7 @@ namespace MediaBrowser.Providers.Manager
}
/// <summary>
- /// Befores the save.
+ /// Before the save.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="isFullRefresh">if set to <c>true</c> [is full refresh].</param>
@@ -329,8 +298,8 @@ namespace MediaBrowser.Providers.Manager
{
return true;
}
- var folder = item as Folder;
- if (folder != null)
+
+ if (item is Folder folder)
{
return folder.SupportsDateLastMediaAdded || folder.SupportsCumulativeRunTimeTicks;
}
@@ -341,13 +310,12 @@ namespace MediaBrowser.Providers.Manager
protected virtual IList<BaseItem> GetChildrenForMetadataUpdates(TItemType item)
{
- var folder = item as Folder;
- if (folder != null)
+ if (item is Folder folder)
{
return folder.GetRecursiveChildren();
}
- return new List<BaseItem>();
+ return Array.Empty<BaseItem>();
}
protected virtual ItemUpdateType UpdateMetadataFromChildren(TItemType item, IList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
@@ -385,8 +353,7 @@ namespace MediaBrowser.Providers.Manager
private ItemUpdateType UpdateCumulativeRunTimeTicks(TItemType item, IList<BaseItem> children)
{
- var folder = item as Folder;
- if (folder != null && folder.SupportsCumulativeRunTimeTicks)
+ if (item is Folder folder && folder.SupportsCumulativeRunTimeTicks)
{
long ticks = 0;
@@ -394,7 +361,7 @@ namespace MediaBrowser.Providers.Manager
{
if (!child.IsFolder)
{
- ticks += (child.RunTimeTicks ?? 0);
+ ticks += child.RunTimeTicks ?? 0;
}
}
@@ -427,6 +394,7 @@ namespace MediaBrowser.Providers.Manager
{
dateLastMediaAdded = childDateCreated;
}
+
any = true;
}
}
@@ -441,14 +409,6 @@ namespace MediaBrowser.Providers.Manager
return updateType;
}
- protected virtual bool EnableUpdatingPremiereDateFromChildren => false;
-
- protected virtual bool EnableUpdatingGenresFromChildren => false;
-
- protected virtual bool EnableUpdatingStudiosFromChildren => false;
-
- protected virtual bool EnableUpdatingOfficialRatingFromChildren => false;
-
private ItemUpdateType UpdatePremiereDate(TItemType item, IList<BaseItem> children)
{
var updateType = ItemUpdateType.None;
@@ -481,7 +441,7 @@ namespace MediaBrowser.Providers.Manager
if ((originalPremiereDate ?? DateTime.MinValue) != (item.PremiereDate ?? DateTime.MinValue) ||
(originalProductionYear ?? -1) != (item.ProductionYear ?? -1))
{
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
return updateType;
@@ -491,7 +451,7 @@ namespace MediaBrowser.Providers.Manager
{
var updateType = ItemUpdateType.None;
- if (!item.LockedFields.Contains(MetadataFields.Genres))
+ if (!item.LockedFields.Contains(MetadataField.Genres))
{
var currentList = item.Genres;
@@ -501,7 +461,7 @@ namespace MediaBrowser.Providers.Manager
if (currentList.Length != item.Genres.Length || !currentList.OrderBy(i => i).SequenceEqual(item.Genres.OrderBy(i => i), StringComparer.OrdinalIgnoreCase))
{
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
}
@@ -512,7 +472,7 @@ namespace MediaBrowser.Providers.Manager
{
var updateType = ItemUpdateType.None;
- if (!item.LockedFields.Contains(MetadataFields.Studios))
+ if (!item.LockedFields.Contains(MetadataField.Studios))
{
var currentList = item.Studios;
@@ -522,7 +482,7 @@ namespace MediaBrowser.Providers.Manager
if (currentList.Length != item.Studios.Length || !currentList.OrderBy(i => i).SequenceEqual(item.Studios.OrderBy(i => i), StringComparer.OrdinalIgnoreCase))
{
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
}
@@ -533,11 +493,11 @@ namespace MediaBrowser.Providers.Manager
{
var updateType = ItemUpdateType.None;
- if (!item.LockedFields.Contains(MetadataFields.OfficialRating))
+ if (!item.LockedFields.Contains(MetadataField.OfficialRating))
{
if (item.UpdateRatingToItems(children))
{
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
}
@@ -547,6 +507,11 @@ namespace MediaBrowser.Providers.Manager
/// <summary>
/// Gets the providers.
/// </summary>
+ /// <param name="item">A media item.</param>
+ /// <param name="libraryOptions">The LibraryOptions to use.</param>
+ /// <param name="options">The MetadataRefreshOptions to use.</param>
+ /// <param name="isFirstRefresh">Specifies first refresh mode.</param>
+ /// <param name="requiresRefresh">Specifies refresh mode.</param>
/// <returns>IEnumerable{`0}.</returns>
protected IEnumerable<IMetadataProvider> GetProviders(BaseItem item, LibraryOptions libraryOptions, MetadataRefreshOptions options, bool isFirstRefresh, bool requiresRefresh)
{
@@ -611,7 +576,6 @@ namespace MediaBrowser.Providers.Manager
// Run custom refresh providers if they report a change or any remote providers change
return anyRemoteProvidersChanged || providersWithChanges.Contains(i);
-
}).ToList();
}
}
@@ -622,7 +586,7 @@ namespace MediaBrowser.Providers.Manager
protected virtual IEnumerable<IImageProvider> GetNonLocalImageProviders(BaseItem item, IEnumerable<IImageProvider> allImageProviders, ImageRefreshOptions options)
{
// Get providers to refresh
- var providers = allImageProviders.Where(i => !(i is ILocalImageProvider)).ToList();
+ var providers = allImageProviders.Where(i => i is not ILocalImageProvider);
var dateLastImageRefresh = item.DateLastRefreshed;
@@ -634,15 +598,13 @@ namespace MediaBrowser.Providers.Manager
providers = providers
.Where(i =>
{
- var hasFileChangeMonitor = i as IHasItemChangeMonitor;
- if (hasFileChangeMonitor != null)
+ if (i is IHasItemChangeMonitor hasFileChangeMonitor)
{
return HasChanged(item, hasFileChangeMonitor, options.DirectoryService);
}
return false;
- })
- .ToList();
+ });
}
return providers;
@@ -658,10 +620,11 @@ namespace MediaBrowser.Providers.Manager
return type == typeof(TItemType);
}
- protected virtual async Task<RefreshResult> RefreshWithProviders(MetadataResult<TItemType> metadata,
+ protected virtual async Task<RefreshResult> RefreshWithProviders(
+ MetadataResult<TItemType> metadata,
TIdType id,
MetadataRefreshOptions options,
- List<IMetadataProvider> providers,
+ ICollection<IMetadataProvider> providers,
ItemImageProvider imageService,
CancellationToken cancellationToken)
{
@@ -694,7 +657,7 @@ namespace MediaBrowser.Providers.Manager
var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType<IRemoteMetadataProvider<TItemType, TIdType>>(), cancellationToken)
.ConfigureAwait(false);
- refreshResult.UpdateType = refreshResult.UpdateType | remoteResult.UpdateType;
+ refreshResult.UpdateType |= remoteResult.UpdateType;
refreshResult.ErrorMessage = remoteResult.ErrorMessage;
refreshResult.Failures += remoteResult.Failures;
}
@@ -714,9 +677,15 @@ namespace MediaBrowser.Providers.Manager
if (localItem.HasMetadata)
{
+ foreach (var remoteImage in localItem.RemoteImages)
+ {
+ await ProviderManager.SaveImage(item, remoteImage.url, remoteImage.type, null, cancellationToken).ConfigureAwait(false);
+ refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
+ }
+
if (imageService.MergeImages(item, localItem.Images))
{
- refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.ImageUpdate;
+ refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
}
if (localItem.UserDataList != null)
@@ -724,14 +693,15 @@ namespace MediaBrowser.Providers.Manager
userDataList.AddRange(localItem.UserDataList);
}
- MergeData(localItem, temp, new MetadataFields[] { }, !options.ReplaceAllMetadata, true);
- refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataImport;
+ MergeData(localItem, temp, Array.Empty<MetadataField>(), !options.ReplaceAllMetadata, true);
+ refreshResult.UpdateType |= ItemUpdateType.MetadataImport;
// Only one local provider allowed per item
if (item.IsLocked || localItem.Item.IsLocked || IsFullLocalMetadata(localItem.Item))
{
hasLocalMetadata = true;
}
+
break;
}
@@ -756,12 +726,12 @@ namespace MediaBrowser.Providers.Manager
var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType<IRemoteMetadataProvider<TItemType, TIdType>>(), cancellationToken)
.ConfigureAwait(false);
- refreshResult.UpdateType = refreshResult.UpdateType | remoteResult.UpdateType;
+ refreshResult.UpdateType |= remoteResult.UpdateType;
refreshResult.ErrorMessage = remoteResult.ErrorMessage;
refreshResult.Failures += remoteResult.Failures;
}
- if (providers.Any(i => !(i is ICustomMetadataProvider)))
+ if (providers.Any(i => i is not ICustomMetadataProvider))
{
if (refreshResult.UpdateType > ItemUpdateType.None)
{
@@ -772,20 +742,20 @@ namespace MediaBrowser.Providers.Manager
else
{
// TODO: If the new metadata from above has some blank data, this can cause old data to get filled into those empty fields
- MergeData(metadata, temp, new MetadataFields[] { }, false, false);
+ MergeData(metadata, temp, Array.Empty<MetadataField>(), false, false);
MergeData(temp, metadata, item.LockedFields, true, false);
}
}
}
- //var isUnidentified = failedProviderCount > 0 && successfulProviderCount == 0;
+ // var isUnidentified = failedProviderCount > 0 && successfulProviderCount == 0;
- foreach (var provider in customProviders.Where(i => !(i is IPreRefreshProvider)))
+ foreach (var provider in customProviders.Where(i => i is not IPreRefreshProvider))
{
await RunCustomProvider(provider, item, logName, options, refreshResult, cancellationToken).ConfigureAwait(false);
}
- //ImportUserData(item, userDataList, cancellationToken);
+ // ImportUserData(item, userDataList, cancellationToken);
return refreshResult;
}
@@ -806,7 +776,7 @@ namespace MediaBrowser.Providers.Manager
try
{
- refreshResult.UpdateType = refreshResult.UpdateType | await provider.FetchAsync(item, options, cancellationToken).ConfigureAwait(false);
+ refreshResult.UpdateType |= await provider.FetchAsync(item, options, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -849,10 +819,10 @@ namespace MediaBrowser.Providers.Manager
{
result.Provider = provider.Name;
- MergeData(result, temp, new MetadataFields[] { }, false, false);
+ MergeData(result, temp, Array.Empty<MetadataField>(), false, false);
MergeNewData(temp.Item, id);
- refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataDownload;
+ refreshResult.UpdateType |= ItemUpdateType.MetadataDownload;
}
else
{
@@ -874,15 +844,6 @@ namespace MediaBrowser.Providers.Manager
return refreshResult;
}
- private string NormalizeLanguage(string language)
- {
- if (string.IsNullOrWhiteSpace(language))
- {
- return "en";
- }
- return language;
- }
-
private void MergeNewData(TItemType source, TIdType lookupInfo)
{
// Copy new provider id's that may have been obtained
@@ -898,24 +859,23 @@ namespace MediaBrowser.Providers.Manager
}
}
- protected abstract void MergeData(MetadataResult<TItemType> source,
+ protected abstract void MergeData(
+ MetadataResult<TItemType> source,
MetadataResult<TItemType> target,
- MetadataFields[] lockedFields,
+ MetadataField[] lockedFields,
bool replaceData,
bool mergeMetadataSettings);
- public virtual int Order => 0;
-
private bool HasChanged(BaseItem item, IHasItemChangeMonitor changeMonitor, IDirectoryService directoryService)
{
try
{
var hasChanged = changeMonitor.HasChanged(item, directoryService);
- //if (hasChanged)
- //{
- // logger.LogDebug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name);
- //}
+ if (hasChanged)
+ {
+ Logger.LogDebug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name);
+ }
return hasChanged;
}
@@ -926,11 +886,4 @@ namespace MediaBrowser.Providers.Manager
}
}
}
-
- public class RefreshResult
- {
- public ItemUpdateType UpdateType { get; set; }
- public string ErrorMessage { get; set; }
- public int Failures { get; set; }
- }
}
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index f26087fda..ca557f6d6 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -1,129 +1,142 @@
+#nullable disable
+
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.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Events;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
+using MediaBrowser.Controller.BaseItemManager;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Events;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using Priority_Queue;
+using Book = MediaBrowser.Controller.Entities.Book;
+using Episode = MediaBrowser.Controller.Entities.TV.Episode;
+using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
+using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
+using Season = MediaBrowser.Controller.Entities.TV.Season;
+using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace MediaBrowser.Providers.Manager
{
/// <summary>
- /// Class ProviderManager
+ /// Class ProviderManager.
/// </summary>
public class ProviderManager : IProviderManager, IDisposable
{
- /// <summary>
- /// The _logger
- /// </summary>
- private readonly ILogger _logger;
-
- /// <summary>
- /// The _HTTP client
- /// </summary>
- private readonly IHttpClient _httpClient;
-
- /// <summary>
- /// The _directory watchers
- /// </summary>
+ private readonly object _refreshQueueLock = new object();
+ private readonly ILogger<ProviderManager> _logger;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly ILibraryMonitor _libraryMonitor;
-
- /// <summary>
- /// Gets or sets the configuration manager.
- /// </summary>
- /// <value>The configuration manager.</value>
- private IServerConfigurationManager ConfigurationManager { get; set; }
-
- private IImageProvider[] ImageProviders { get; set; }
-
private readonly IFileSystem _fileSystem;
-
- private IMetadataService[] _metadataServices = { };
- private IMetadataProvider[] _metadataProviders = { };
- private IEnumerable<IMetadataSaver> _savers;
private readonly IServerApplicationPaths _appPaths;
- private readonly IJsonSerializer _json;
-
- private IExternalId[] _externalIds;
-
- private readonly Func<ILibraryManager> _libraryManagerFactory;
- private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
-
- public event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted;
- public event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted;
- public event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ISubtitleManager _subtitleManager;
+ private readonly IServerConfigurationManager _configurationManager;
+ private readonly IBaseItemManager _baseItemManager;
+ private readonly ConcurrentDictionary<Guid, double> _activeRefreshes = new ConcurrentDictionary<Guid, double>();
+ private readonly CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
+ private readonly SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>> _refreshQueue =
+ new SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>>();
- private ISubtitleManager _subtitleManager;
+ private IMetadataService[] _metadataServices = Array.Empty<IMetadataService>();
+ private IMetadataProvider[] _metadataProviders = Array.Empty<IMetadataProvider>();
+ private IMetadataSaver[] _savers = Array.Empty<IMetadataSaver>();
+ private IExternalId[] _externalIds = Array.Empty<IExternalId>();
+ private bool _isProcessingRefreshQueue;
+ private bool _disposed;
/// <summary>
- /// Initializes a new instance of the <see cref="ProviderManager" /> class.
+ /// Initializes a new instance of the <see cref="ProviderManager"/> class.
/// </summary>
- public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILoggerFactory loggerFactory, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func<ILibraryManager> libraryManagerFactory, IJsonSerializer json)
+ /// <param name="httpClientFactory">The Http client factory.</param>
+ /// <param name="subtitleManager">The subtitle manager.</param>
+ /// <param name="configurationManager">The configuration manager.</param>
+ /// <param name="libraryMonitor">The library monitor.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="fileSystem">The filesystem.</param>
+ /// <param name="appPaths">The server application paths.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="baseItemManager">The BaseItem manager.</param>
+ public ProviderManager(
+ IHttpClientFactory httpClientFactory,
+ ISubtitleManager subtitleManager,
+ IServerConfigurationManager configurationManager,
+ ILibraryMonitor libraryMonitor,
+ ILogger<ProviderManager> logger,
+ IFileSystem fileSystem,
+ IServerApplicationPaths appPaths,
+ ILibraryManager libraryManager,
+ IBaseItemManager baseItemManager)
{
- _logger = loggerFactory.CreateLogger("ProviderManager");
- _httpClient = httpClient;
- ConfigurationManager = configurationManager;
+ _logger = logger;
+ _httpClientFactory = httpClientFactory;
+ _configurationManager = configurationManager;
_libraryMonitor = libraryMonitor;
_fileSystem = fileSystem;
_appPaths = appPaths;
- _libraryManagerFactory = libraryManagerFactory;
- _json = json;
+ _libraryManager = libraryManager;
_subtitleManager = subtitleManager;
+ _baseItemManager = baseItemManager;
}
- /// <summary>
- /// Adds the metadata providers.
- /// </summary>
- public void AddParts(IEnumerable<IImageProvider> imageProviders, IEnumerable<IMetadataService> metadataServices,
- IEnumerable<IMetadataProvider> metadataProviders, IEnumerable<IMetadataSaver> metadataSavers,
- IEnumerable<IExternalId> externalIds)
+ /// <inheritdoc/>
+ public event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted;
+
+ /// <inheritdoc/>
+ public event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted;
+
+ /// <inheritdoc/>
+ public event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress;
+
+ private IImageProvider[] ImageProviders { get; set; }
+
+ /// <inheritdoc/>
+ public void AddParts(
+ IEnumerable<IImageProvider> imageProviders,
+ IEnumerable<IMetadataService> metadataServices,
+ IEnumerable<IMetadataProvider> metadataProviders,
+ IEnumerable<IMetadataSaver> metadataSavers,
+ IEnumerable<IExternalId> externalIds)
{
ImageProviders = imageProviders.ToArray();
_metadataServices = metadataServices.OrderBy(i => i.Order).ToArray();
_metadataProviders = metadataProviders.ToArray();
- _externalIds = externalIds.OrderBy(i => i.Name).ToArray();
-
- _savers = metadataSavers.Where(i =>
- {
- var configurable = i as IConfigurableProvider;
+ _externalIds = externalIds.OrderBy(i => i.ProviderName).ToArray();
- return configurable == null || configurable.IsEnabled;
- }).ToArray();
+ _savers = metadataSavers
+ .Where(i => i is not IConfigurableProvider configurable || configurable.IsEnabled)
+ .ToArray();
}
+ /// <inheritdoc/>
public Task<ItemUpdateType> RefreshSingleItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
- IMetadataService service = null;
var type = item.GetType();
- foreach (var current in _metadataServices)
- {
- if (current.CanRefreshPrimary(type))
- {
- service = current;
- break;
- }
- }
+ var service = _metadataServices.FirstOrDefault(current => current.CanRefreshPrimary(type));
if (service == null)
{
@@ -146,35 +159,52 @@ namespace MediaBrowser.Providers.Manager
return Task.FromResult(ItemUpdateType.None);
}
+ /// <inheritdoc/>
public async Task SaveImage(BaseItem item, string url, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
- using (var response = await _httpClient.GetResponse(new HttpRequestOptions
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
+
+ if (response.StatusCode != HttpStatusCode.OK)
{
- CancellationToken = cancellationToken,
- Url = url,
- BufferContent = false
+ throw new HttpRequestException("Invalid image received.", null, response.StatusCode);
+ }
+
+ var contentType = response.Content.Headers.ContentType?.MediaType;
- }).ConfigureAwait(false))
+ // Workaround for tvheadend channel icons
+ // TODO: Isolate this hack into the tvh plugin
+ if (string.IsNullOrEmpty(contentType))
{
- // Workaround for tvheadend channel icons
- // TODO: Isolate this hack into the tvh plugin
- if (string.IsNullOrEmpty(response.ContentType))
+ if (url.IndexOf("/imagecache/", StringComparison.OrdinalIgnoreCase) != -1)
{
- if (url.IndexOf("/imagecache/", StringComparison.OrdinalIgnoreCase) != -1)
- {
- response.ContentType = "image/png";
- }
+ contentType = "image/png";
}
+ }
- await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken).ConfigureAwait(false);
+ // thetvdb will sometimes serve a rubbish 404 html page with a 200 OK code, because reasons...
+ if (contentType.Equals(MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound);
}
+
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await SaveImage(
+ item,
+ stream,
+ contentType,
+ type,
+ imageIndex,
+ cancellationToken).ConfigureAwait(false);
}
+ /// <inheritdoc/>
public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
- return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
+ return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
}
+ /// <inheritdoc/>
public Task SaveImage(BaseItem item, string source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(source))
@@ -182,11 +212,18 @@ namespace MediaBrowser.Providers.Manager
throw new ArgumentNullException(nameof(source));
}
- var fileStream = _fileSystem.GetFileStream(source, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
+ var fileStream = AsyncFile.OpenRead(source);
+ return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, saveLocallyWithMedia, cancellationToken);
+ }
- return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, saveLocallyWithMedia, cancellationToken);
+ /// <inheritdoc/>
+ public Task SaveImage(Stream source, string mimeType, string path)
+ {
+ return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger)
+ .SaveImage(source, path);
}
+ /// <inheritdoc/>
public async Task<IEnumerable<RemoteImageInfo>> GetAvailableRemoteImages(BaseItem item, RemoteImageQuery query, CancellationToken cancellationToken)
{
var providers = GetRemoteImageProviders(item, query.IncludeDisabledProviders);
@@ -200,13 +237,7 @@ namespace MediaBrowser.Providers.Manager
var preferredLanguage = item.GetPreferredMetadataLanguage();
- var languages = new List<string>();
- if (!query.IncludeAllLanguages && !string.IsNullOrWhiteSpace(preferredLanguage))
- {
- languages.Add(preferredLanguage);
- }
-
- var tasks = providers.Select(i => GetImages(item, cancellationToken, i, languages, query.ImageType));
+ var tasks = providers.Select(i => GetImages(item, i, preferredLanguage, query.IncludeAllLanguages, cancellationToken, query.ImageType));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
@@ -217,13 +248,22 @@ namespace MediaBrowser.Providers.Manager
/// Gets the images.
/// </summary>
/// <param name="item">The item.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="provider">The provider.</param>
- /// <param name="preferredLanguages">The preferred languages.</param>
+ /// <param name="preferredLanguage">The preferred language.</param>
+ /// <param name="includeAllLanguages">Whether to include all languages in results.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="type">The type.</param>
/// <returns>Task{IEnumerable{RemoteImageInfo}}.</returns>
- private async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken, IRemoteImageProvider provider, List<string> preferredLanguages, ImageType? type = null)
+ private async Task<IEnumerable<RemoteImageInfo>> GetImages(
+ BaseItem item,
+ IRemoteImageProvider provider,
+ string preferredLanguage,
+ bool includeAllLanguages,
+ CancellationToken cancellationToken,
+ ImageType? type = null)
{
+ bool hasPreferredLanguage = !string.IsNullOrWhiteSpace(preferredLanguage);
+
try
{
var result = await provider.GetImages(item, cancellationToken).ConfigureAwait(false);
@@ -233,14 +273,17 @@ namespace MediaBrowser.Providers.Manager
result = result.Where(i => i.Type == type.Value);
}
- if (preferredLanguages.Count > 0)
+ if (!includeAllLanguages && hasPreferredLanguage)
{
- result = result.Where(i => string.IsNullOrEmpty(i.Language) ||
- preferredLanguages.Contains(i.Language, StringComparer.OrdinalIgnoreCase) ||
+ // Filter out languages that do not match the preferred languages.
+ //
+ // TODO: should exception case of "en" (English) eventually be removed?
+ result = result.Where(i => string.IsNullOrWhiteSpace(i.Language) ||
+ string.Equals(preferredLanguage, i.Language, StringComparison.OrdinalIgnoreCase) ||
string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
}
- return result;
+ return result.OrderByLanguageDescending(preferredLanguage);
}
catch (OperationCanceledException)
{
@@ -248,28 +291,26 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.LogError(ex, "{0} failed in GetImageInfos for type {1}", provider.GetType().Name, item.GetType().Name);
+ _logger.LogError(ex, "{ProviderName} failed in GetImageInfos for type {ItemType} at {ItemPath}", provider.GetType().Name, item.GetType().Name, item.Path);
return new List<RemoteImageInfo>();
}
}
- /// <summary>
- /// Gets the supported image providers.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>IEnumerable{IImageProvider}.</returns>
+ /// <inheritdoc/>
public IEnumerable<ImageProviderInfo> GetRemoteImageProviderInfo(BaseItem item)
{
- return GetRemoteImageProviders(item, true).Select(i => new ImageProviderInfo
- {
- Name = i.Name,
- SupportedImages = i.GetSupportedImages(item).ToArray()
- });
+ return GetRemoteImageProviders(item, true).Select(i => new ImageProviderInfo(i.Name, i.GetSupportedImages(item).ToArray()));
}
+ /// <summary>
+ /// Gets the image providers for the provided item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="refreshOptions">The image refresh options.</param>
+ /// <returns>The image providers for the item.</returns>
public IEnumerable<IImageProvider> GetImageProviders(BaseItem item, ImageRefreshOptions refreshOptions)
{
- return GetImageProviders(item, _libraryManagerFactory().GetLibraryOptions(item), GetMetadataOptions(item), refreshOptions, false);
+ return GetImageProviders(item, _libraryManager.GetLibraryOptions(item), GetMetadataOptions(item), refreshOptions, false);
}
private IEnumerable<IImageProvider> GetImageProviders(BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
@@ -278,16 +319,15 @@ namespace MediaBrowser.Providers.Manager
var currentOptions = options;
var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
- var typeFetcherOrder = typeOptions == null ? null : typeOptions.ImageFetcherOrder;
+ var typeFetcherOrder = typeOptions?.ImageFetcherOrder;
- return ImageProviders.Where(i => CanRefresh(i, item, libraryOptions, options, refreshOptions, includeDisabled))
+ return ImageProviders.Where(i => CanRefresh(i, item, libraryOptions, refreshOptions, includeDisabled))
.OrderBy(i =>
{
// See if there's a user-defined order
- if (!(i is ILocalImageProvider))
+ if (i is not ILocalImageProvider)
{
var fetcherOrder = typeFetcherOrder ?? currentOptions.ImageFetcherOrder;
-
var index = Array.IndexOf(fetcherOrder, i.Name);
if (index != -1)
@@ -302,6 +342,13 @@ namespace MediaBrowser.Providers.Manager
.ThenBy(GetOrder);
}
+ /// <summary>
+ /// Gets the metadata providers for the provided item.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="libraryOptions">The library options.</param>
+ /// <typeparam name="T">The type of metadata provider.</typeparam>
+ /// <returns>The metadata providers.</returns>
public IEnumerable<IMetadataProvider<T>> GetMetadataProviders<T>(BaseItem item, LibraryOptions libraryOptions)
where T : BaseItem
{
@@ -317,7 +364,7 @@ namespace MediaBrowser.Providers.Manager
var currentOptions = globalMetadataOptions;
return _metadataProviders.OfType<IMetadataProvider<T>>()
- .Where(i => CanRefresh(i, item, libraryOptions, currentOptions, includeDisabled, forceEnableInternetMetadata))
+ .Where(i => CanRefresh(i, item, libraryOptions, includeDisabled, forceEnableInternetMetadata))
.OrderBy(i => GetConfiguredOrder(item, i, libraryOptions, globalMetadataOptions))
.ThenBy(GetDefaultOrder);
}
@@ -325,28 +372,34 @@ namespace MediaBrowser.Providers.Manager
private IEnumerable<IRemoteImageProvider> GetRemoteImageProviders(BaseItem item, bool includeDisabled)
{
var options = GetMetadataOptions(item);
- var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item);
-
- return GetImageProviders(item, libraryOptions, options,
- new ImageRefreshOptions(
- new DirectoryService(_logger, _fileSystem)),
- includeDisabled)
- .OfType<IRemoteImageProvider>();
+ var libraryOptions = _libraryManager.GetLibraryOptions(item);
+
+ return GetImageProviders(
+ item,
+ libraryOptions,
+ options,
+ new ImageRefreshOptions(new DirectoryService(_fileSystem)),
+ includeDisabled).OfType<IRemoteImageProvider>();
}
- private bool CanRefresh(IMetadataProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, bool includeDisabled, bool forceEnableInternetMetadata)
+ private bool CanRefresh(
+ IMetadataProvider provider,
+ BaseItem item,
+ LibraryOptions libraryOptions,
+ bool includeDisabled,
+ bool forceEnableInternetMetadata)
{
if (!includeDisabled)
{
// If locked only allow local providers
- if (item.IsLocked && !(provider is ILocalMetadataProvider) && !(provider is IForcedProvider))
+ if (item.IsLocked && provider is not ILocalMetadataProvider && provider is not IForcedProvider)
{
return false;
}
if (provider is IRemoteMetadataProvider)
{
- if (!forceEnableInternetMetadata && !item.IsMetadataFetcherEnabled(libraryOptions, provider.Name))
+ if (!forceEnableInternetMetadata && !_baseItemManager.IsMetadataFetcherEnabled(item, libraryOptions, provider.Name))
{
return false;
}
@@ -370,12 +423,17 @@ namespace MediaBrowser.Providers.Manager
return true;
}
- private bool CanRefresh(IImageProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
+ private bool CanRefresh(
+ IImageProvider provider,
+ BaseItem item,
+ LibraryOptions libraryOptions,
+ ImageRefreshOptions refreshOptions,
+ bool includeDisabled)
{
if (!includeDisabled)
{
// If locked only allow local providers
- if (item.IsLocked && !(provider is ILocalImageProvider))
+ if (item.IsLocked && provider is not ILocalImageProvider)
{
if (refreshOptions.ImageRefreshMode != MetadataRefreshMode.FullRefresh)
{
@@ -385,7 +443,7 @@ namespace MediaBrowser.Providers.Manager
if (provider is IRemoteImageProvider || provider is IDynamicImageProvider)
{
- if (!item.IsImageFetcherEnabled(libraryOptions, provider.Name))
+ if (!_baseItemManager.IsImageFetcherEnabled(item, libraryOptions, provider.Name))
{
return false;
}
@@ -398,7 +456,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.LogError(ex, "{0} failed in Supports for type {1}", provider.GetType().Name, item.GetType().Name);
+ _logger.LogError(ex, "{ProviderName} failed in Supports for type {ItemType} at {ItemPath}", provider.GetType().Name, item.GetType().Name, item.Path);
return false;
}
}
@@ -410,9 +468,7 @@ namespace MediaBrowser.Providers.Manager
/// <returns>System.Int32.</returns>
private int GetOrder(IImageProvider provider)
{
- var hasOrder = provider as IHasOrder;
-
- if (hasOrder == null)
+ if (provider is not IHasOrder hasOrder)
{
return 0;
}
@@ -439,7 +495,7 @@ namespace MediaBrowser.Providers.Manager
if (provider is IRemoteMetadataProvider)
{
var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
- var typeFetcherOrder = typeOptions == null ? null : typeOptions.MetadataFetcherOrder;
+ var typeFetcherOrder = typeOptions?.MetadataFetcherOrder;
var fetcherOrder = typeFetcherOrder ?? globalMetadataOptions.MetadataFetcherOrder;
@@ -457,9 +513,7 @@ namespace MediaBrowser.Providers.Manager
private int GetDefaultOrder(IMetadataProvider provider)
{
- var hasOrder = provider as IHasOrder;
-
- if (hasOrder != null)
+ if (provider is IHasOrder hasOrder)
{
return hasOrder.Order;
}
@@ -467,9 +521,10 @@ namespace MediaBrowser.Providers.Manager
return 0;
}
+ /// <inheritdoc/>
public MetadataPluginSummary[] GetAllMetadataPlugins()
{
- return new MetadataPluginSummary[]
+ return new[]
{
GetPluginSummary<Movie>(),
GetPluginSummary<BoxSet>(),
@@ -491,7 +546,7 @@ namespace MediaBrowser.Providers.Manager
where T : BaseItem, new()
{
// Give it a dummy path just so that it looks like a file system item
- var dummy = new T()
+ var dummy = new T
{
Path = Path.Combine(_appPaths.InternalMetadataPath, "dummy"),
ParentId = Guid.NewGuid()
@@ -506,16 +561,17 @@ namespace MediaBrowser.Providers.Manager
var libraryOptions = new LibraryOptions();
- var imageProviders = GetImageProviders(dummy, libraryOptions, options,
- new ImageRefreshOptions(
- new DirectoryService(_logger, _fileSystem)),
- true)
- .ToList();
+ var imageProviders = GetImageProviders(
+ dummy,
+ libraryOptions,
+ options,
+ new ImageRefreshOptions(new DirectoryService(_fileSystem)),
+ true).ToList();
var pluginList = summary.Plugins.ToList();
AddMetadataPlugins(pluginList, dummy, libraryOptions, options);
- AddImagePlugins(pluginList, dummy, imageProviders);
+ AddImagePlugins(pluginList, imageProviders);
var subtitleProviders = _subtitleManager.GetSupportedProviders(dummy);
@@ -546,14 +602,14 @@ namespace MediaBrowser.Providers.Manager
var providers = GetMetadataProvidersInternal<T>(item, libraryOptions, options, true, true).ToList();
// Locals
- list.AddRange(providers.Where(i => (i is ILocalMetadataProvider)).Select(i => new MetadataPlugin
+ list.AddRange(providers.Where(i => i is ILocalMetadataProvider).Select(i => new MetadataPlugin
{
Name = i.Name,
Type = MetadataPluginType.LocalMetadataProvider
}));
// Fetchers
- list.AddRange(providers.Where(i => (i is IRemoteMetadataProvider)).Select(i => new MetadataPlugin
+ list.AddRange(providers.Where(i => i is IRemoteMetadataProvider).Select(i => new MetadataPlugin
{
Name = i.Name,
Type = MetadataPluginType.MetadataFetcher
@@ -567,12 +623,10 @@ namespace MediaBrowser.Providers.Manager
}));
}
- private void AddImagePlugins<T>(List<MetadataPlugin> list, T item, List<IImageProvider> imageProviders)
- where T : BaseItem
+ private void AddImagePlugins(List<MetadataPlugin> list, List<IImageProvider> imageProviders)
{
-
// Locals
- list.AddRange(imageProviders.Where(i => (i is ILocalImageProvider)).Select(i => new MetadataPlugin
+ list.AddRange(imageProviders.Where(i => i is ILocalImageProvider).Select(i => new MetadataPlugin
{
Name = i.Name,
Type = MetadataPluginType.LocalImageProvider
@@ -586,26 +640,23 @@ namespace MediaBrowser.Providers.Manager
}));
}
+ /// <inheritdoc/>
public MetadataOptions GetMetadataOptions(BaseItem item)
{
var type = item.GetType().Name;
- return ConfigurationManager.Configuration.MetadataOptions
+ return _configurationManager.Configuration.MetadataOptions
.FirstOrDefault(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase)) ??
new MetadataOptions();
}
- /// <summary>
- /// Saves the metadata.
- /// </summary>
+ /// <inheritdoc/>
public void SaveMetadata(BaseItem item, ItemUpdateType updateType)
{
SaveMetadata(item, updateType, _savers);
}
- /// <summary>
- /// Saves the metadata.
- /// </summary>
+ /// <inheritdoc/>
public void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<string> savers)
{
SaveMetadata(item, updateType, _savers.Where(i => savers.Contains(i.Name, StringComparer.OrdinalIgnoreCase)));
@@ -617,20 +668,17 @@ namespace MediaBrowser.Providers.Manager
/// <param name="item">The item.</param>
/// <param name="updateType">Type of the update.</param>
/// <param name="savers">The savers.</param>
- /// <returns>Task.</returns>
private void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<IMetadataSaver> savers)
{
- var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item);
+ var libraryOptions = _libraryManager.GetLibraryOptions(item);
foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, updateType, false)))
{
_logger.LogDebug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name);
- var fileSaver = saver as IMetadataFileSaver;
-
- if (fileSaver != null)
+ if (saver is IMetadataFileSaver fileSaver)
{
- string path = null;
+ string path;
try
{
@@ -697,11 +745,9 @@ namespace MediaBrowser.Providers.Manager
{
if (updateType >= ItemUpdateType.MetadataEdit)
{
- var fileSaver = saver as IMetadataFileSaver;
-
// Manual edit occurred
// Even if save local is off, save locally anyway if the metadata file already exists
- if (fileSaver == null || !File.Exists(fileSaver.GetSavePath(item)))
+ if (saver is not IMetadataFileSaver fileSaver || !File.Exists(fileSaver.GetSavePath(item)))
{
return false;
}
@@ -732,6 +778,7 @@ namespace MediaBrowser.Providers.Manager
}
}
+ /// <inheritdoc/>
public Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo, CancellationToken cancellationToken)
where TItemType : BaseItem, new()
where TLookupType : ItemLookupInfo
@@ -740,13 +787,13 @@ namespace MediaBrowser.Providers.Manager
if (!searchInfo.ItemId.Equals(Guid.Empty))
{
- referenceItem = _libraryManagerFactory().GetItemById(searchInfo.ItemId);
+ referenceItem = _libraryManager.GetItemById(searchInfo.ItemId);
}
return GetRemoteSearchResults<TItemType, TLookupType>(searchInfo, referenceItem, cancellationToken);
}
- public async Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo, BaseItem referenceItem, CancellationToken cancellationToken)
+ private async Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo, BaseItem referenceItem, CancellationToken cancellationToken)
where TItemType : BaseItem, new()
where TLookupType : ItemLookupInfo
{
@@ -768,7 +815,7 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- libraryOptions = _libraryManagerFactory().GetLibraryOptions(referenceItem);
+ libraryOptions = _libraryManager.GetLibraryOptions(referenceItem);
}
var options = GetMetadataOptions(referenceItem);
@@ -783,11 +830,12 @@ namespace MediaBrowser.Providers.Manager
if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataLanguage))
{
- searchInfo.SearchInfo.MetadataLanguage = ConfigurationManager.Configuration.PreferredMetadataLanguage;
+ searchInfo.SearchInfo.MetadataLanguage = _configurationManager.Configuration.PreferredMetadataLanguage;
}
+
if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataCountryCode))
{
- searchInfo.SearchInfo.MetadataCountryCode = ConfigurationManager.Configuration.MetadataCountryCode;
+ searchInfo.SearchInfo.MetadataCountryCode = _configurationManager.Configuration.MetadataCountryCode;
}
var resultList = new List<RemoteSearchResult>();
@@ -823,18 +871,20 @@ namespace MediaBrowser.Providers.Manager
}
}
}
- catch (Exception)
+#pragma warning disable CA1031 // do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // do not catch general exception types
{
- // Logged at lower levels
+ _logger.LogError(ex, "Provider {ProviderName} failed to retrieve search results", provider.Name);
}
}
- //_logger.LogDebug("Returning search results {0}", _json.SerializeToString(resultList));
-
return resultList;
}
- private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults<TLookupType>(IRemoteSearchProvider<TLookupType> provider, TLookupType searchInfo,
+ private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults<TLookupType>(
+ IRemoteSearchProvider<TLookupType> provider,
+ TLookupType searchInfo,
CancellationToken cancellationToken)
where TLookupType : ItemLookupInfo
{
@@ -850,7 +900,8 @@ namespace MediaBrowser.Providers.Manager
return list;
}
- public Task<HttpResponseInfo> GetSearchImage(string providerName, string url, CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public Task<HttpResponseMessage> GetSearchImage(string providerName, string url, CancellationToken cancellationToken)
{
var provider = _metadataProviders.OfType<IRemoteSearchProvider>().FirstOrDefault(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
@@ -862,7 +913,7 @@ namespace MediaBrowser.Providers.Manager
return provider.GetImageResponse(url, cancellationToken);
}
- public IEnumerable<IExternalId> GetExternalIds(IHasProviderIds item)
+ private IEnumerable<IExternalId> GetExternalIds(IHasProviderIds item)
{
return _externalIds.Where(i =>
{
@@ -878,6 +929,7 @@ namespace MediaBrowser.Providers.Manager
});
}
+ /// <inheritdoc/>
public IEnumerable<ExternalUrl> GetExternalUrls(BaseItem item)
{
return GetExternalIds(item)
@@ -897,27 +949,27 @@ namespace MediaBrowser.Providers.Manager
return new ExternalUrl
{
- Name = i.Name,
- Url = string.Format(i.UrlFormatString, value)
+ Name = i.ProviderName,
+ Url = string.Format(
+ CultureInfo.InvariantCulture,
+ i.UrlFormatString,
+ value)
};
-
}).Where(i => i != null).Concat(item.GetRelatedUrls());
}
+ /// <inheritdoc/>
public IEnumerable<ExternalIdInfo> GetExternalIdInfos(IHasProviderIds item)
{
return GetExternalIds(item)
- .Select(i => new ExternalIdInfo
- {
- Name = i.Name,
- Key = i.Key,
- UrlFormatString = i.UrlFormatString
-
- });
+ .Select(i => new ExternalIdInfo(
+ name: i.ProviderName,
+ key: i.Key,
+ type: i.Type,
+ urlFormatString: i.UrlFormatString));
}
- private Dictionary<Guid, double> _activeRefreshes = new Dictionary<Guid, double>();
-
+ /// <inheritdoc/>
public Dictionary<Guid, Guid> GetRefreshQueue()
{
lock (_refreshQueueLock)
@@ -928,91 +980,69 @@ namespace MediaBrowser.Providers.Manager
{
dict[item.Item1] = item.Item1;
}
+
return dict;
}
}
+ /// <inheritdoc/>
public void OnRefreshStart(BaseItem item)
{
- //_logger.LogInformation("OnRefreshStart {0}", item.Id.ToString("N"));
- var id = item.Id;
-
- lock (_activeRefreshes)
- {
- _activeRefreshes[id] = 0;
- }
-
- if (RefreshStarted != null)
- {
- RefreshStarted(this, new GenericEventArgs<BaseItem>(item));
- }
+ _logger.LogDebug("OnRefreshStart {0}", item.Id.ToString("N", CultureInfo.InvariantCulture));
+ _activeRefreshes[item.Id] = 0;
+ RefreshStarted?.Invoke(this, new GenericEventArgs<BaseItem>(item));
}
+ /// <inheritdoc/>
public void OnRefreshComplete(BaseItem item)
{
- //_logger.LogInformation("OnRefreshComplete {0}", item.Id.ToString("N"));
- lock (_activeRefreshes)
- {
- _activeRefreshes.Remove(item.Id);
- }
+ _logger.LogDebug("OnRefreshComplete {0}", item.Id.ToString("N", CultureInfo.InvariantCulture));
- if (RefreshCompleted != null)
- {
- RefreshCompleted(this, new GenericEventArgs<BaseItem>(item));
- }
+ _activeRefreshes.Remove(item.Id, out _);
+
+ RefreshCompleted?.Invoke(this, new GenericEventArgs<BaseItem>(item));
}
+ /// <inheritdoc/>
public double? GetRefreshProgress(Guid id)
{
- lock (_activeRefreshes)
+ if (_activeRefreshes.TryGetValue(id, out double value))
{
- if (_activeRefreshes.TryGetValue(id, out double value))
- {
- return value;
- }
-
- return null;
+ return value;
}
+
+ return null;
}
+ /// <inheritdoc/>
public void OnRefreshProgress(BaseItem item, double progress)
{
- //_logger.LogInformation("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress);
var id = item.Id;
-
- lock (_activeRefreshes)
- {
- if (_activeRefreshes.ContainsKey(id))
- {
- _activeRefreshes[id] = progress;
-
- if (RefreshProgress != null)
- {
- RefreshProgress(this, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(item, progress)));
- }
- }
- else
- {
- // TODO: Need to hunt down the conditions for this happening
- //throw new Exception(string.Format("Refresh for item {0} {1} is not in progress", item.GetType().Name, item.Id.ToString("N")));
- }
- }
+ _logger.LogDebug("OnRefreshProgress {0} {1}", id.ToString("N", CultureInfo.InvariantCulture), progress);
+
+ // TODO: Need to hunt down the conditions for this happening
+ _activeRefreshes.AddOrUpdate(
+ id,
+ (_) => throw new InvalidOperationException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Cannot update refresh progress of item '{0}' ({1}) because a refresh for this item is not running",
+ item.GetType().Name,
+ item.Id.ToString("N", CultureInfo.InvariantCulture))),
+ (_, _) => progress);
+
+ RefreshProgress?.Invoke(this, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(item, progress)));
}
- private readonly SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>> _refreshQueue =
- new SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>>();
-
- private readonly object _refreshQueueLock = new object();
- private bool _isProcessingRefreshQueue;
-
- public void QueueRefresh(Guid id, MetadataRefreshOptions options, RefreshPriority priority)
+ /// <inheritdoc/>
+ public void QueueRefresh(Guid itemId, MetadataRefreshOptions options, RefreshPriority priority)
{
if (_disposed)
{
return;
}
- _refreshQueue.Enqueue(new Tuple<Guid, MetadataRefreshOptions>(id, options), (int)priority);
+ _refreshQueue.Enqueue(new Tuple<Guid, MetadataRefreshOptions>(itemId, options), (int)priority);
lock (_refreshQueueLock)
{
@@ -1026,7 +1056,7 @@ namespace MediaBrowser.Providers.Manager
private async Task StartProcessingRefreshQueue()
{
- var libraryManager = _libraryManagerFactory();
+ var libraryManager = _libraryManager;
if (_disposed)
{
@@ -1045,18 +1075,16 @@ namespace MediaBrowser.Providers.Manager
try
{
var item = libraryManager.GetItemById(refreshItem.Item1);
- if (item != null)
+ if (item == null)
{
- // Try to throttle this a little bit.
- await Task.Delay(100).ConfigureAwait(false);
+ continue;
+ }
- var artist = item as MusicArtist;
- var task = artist == null
- ? RefreshItem(item, refreshItem.Item2, cancellationToken)
- : RefreshArtist(artist, refreshItem.Item2, cancellationToken);
+ var task = item is MusicArtist artist
+ ? RefreshArtist(artist, refreshItem.Item2, cancellationToken)
+ : RefreshItem(item, refreshItem.Item2, cancellationToken);
- await task.ConfigureAwait(false);
- }
+ await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -1079,59 +1107,46 @@ namespace MediaBrowser.Providers.Manager
await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
// Collection folders don't validate their children so we'll have to simulate that here
- var collectionFolder = item as CollectionFolder;
-
- if (collectionFolder != null)
+ switch (item)
{
- await RefreshCollectionFolderChildren(options, collectionFolder, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- var folder = item as Folder;
-
- if (folder != null)
- {
- await folder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options).ConfigureAwait(false);
- }
+ case CollectionFolder collectionFolder:
+ await RefreshCollectionFolderChildren(options, collectionFolder, cancellationToken).ConfigureAwait(false);
+ break;
+ case Folder folder:
+ await folder.ValidateChildren(new SimpleProgress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
+ break;
}
}
private async Task RefreshCollectionFolderChildren(MetadataRefreshOptions options, CollectionFolder collectionFolder, CancellationToken cancellationToken)
{
- foreach (var child in collectionFolder.GetPhysicalFolders().ToList())
+ foreach (var child in collectionFolder.GetPhysicalFolders())
{
await child.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
- if (child.IsFolder)
- {
- var folder = (Folder)child;
-
- await folder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options, true).ConfigureAwait(false);
- }
+ await child.ValidateChildren(new SimpleProgress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
private async Task RefreshArtist(MusicArtist item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
- var albums = _libraryManagerFactory()
+ var albums = _libraryManager
.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
ArtistIds = new[] { item.Id },
DtoOptions = new DtoOptions(false)
{
EnableImages = false
}
})
- .OfType<MusicAlbum>()
- .ToList();
+ .OfType<MusicAlbum>();
var musicArtists = albums
.Select(i => i.MusicArtist)
- .Where(i => i != null)
- .ToList();
+ .Where(i => i != null);
- var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options, true));
+ var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new SimpleProgress<double>(), options, true, cancellationToken));
await Task.WhenAll(musicArtistRefreshTasks).ConfigureAwait(false);
@@ -1145,21 +1160,64 @@ namespace MediaBrowser.Providers.Manager
}
}
- public Task RefreshFullItem(BaseItem item, MetadataRefreshOptions options,
- CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public Task RefreshFullItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
return RefreshItem(item, options, cancellationToken);
}
- private bool _disposed;
+ /// <summary>
+ /// Runs multiple metadata refreshes concurrently.
+ /// </summary>
+ /// <param name="action">The action to run.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
+ public async Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken)
+ {
+ // create a variable for this since it is possible MetadataRefreshThrottler could change due to a config update during a scan
+ var metadataRefreshThrottler = _baseItemManager.MetadataRefreshThrottler;
+
+ await metadataRefreshThrottler.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ await action().ConfigureAwait(false);
+ }
+ finally
+ {
+ metadataRefreshThrottler.Release();
+ }
+ }
+
+ /// <inheritdoc/>
public void Dispose()
{
- _disposed = true;
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and optionally managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
if (!_disposeCancellationTokenSource.IsCancellationRequested)
{
_disposeCancellationTokenSource.Cancel();
}
+
+ if (disposing)
+ {
+ _disposeCancellationTokenSource.Dispose();
+ }
+
+ _disposed = true;
}
}
}
diff --git a/MediaBrowser.Providers/Manager/ProviderUtils.cs b/MediaBrowser.Providers/Manager/ProviderUtils.cs
index 2031449d9..b90136d50 100644
--- a/MediaBrowser.Providers/Manager/ProviderUtils.cs
+++ b/MediaBrowser.Providers/Manager/ProviderUtils.cs
@@ -1,9 +1,13 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
+using Diacritics.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Extensions;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -11,9 +15,10 @@ namespace MediaBrowser.Providers.Manager
{
public static class ProviderUtils
{
- public static void MergeBaseItemData<T>(MetadataResult<T> sourceResult,
+ public static void MergeBaseItemData<T>(
+ MetadataResult<T> sourceResult,
MetadataResult<T> targetResult,
- MetadataFields[] lockedFields,
+ MetadataField[] lockedFields,
bool replaceData,
bool mergeMetadataSettings)
where T : BaseItem
@@ -23,18 +28,19 @@ namespace MediaBrowser.Providers.Manager
if (source == null)
{
- throw new ArgumentNullException(nameof(source));
+ throw new ArgumentException("Item cannot be null.", nameof(sourceResult));
}
+
if (target == null)
{
- throw new ArgumentNullException(nameof(target));
+ throw new ArgumentException("Item cannot be null.", nameof(targetResult));
}
- if (!lockedFields.Contains(MetadataFields.Name))
+ if (!lockedFields.Contains(MetadataField.Name))
{
if (replaceData || string.IsNullOrEmpty(target.Name))
{
- // Safeguard against incoming data having an emtpy name
+ // Safeguard against incoming data having an empty name
if (!string.IsNullOrWhiteSpace(source.Name))
{
target.Name = source.Name;
@@ -44,14 +50,14 @@ namespace MediaBrowser.Providers.Manager
if (replaceData || string.IsNullOrEmpty(target.OriginalTitle))
{
- // Safeguard against incoming data having an emtpy name
+ // Safeguard against incoming data having an empty name
if (!string.IsNullOrWhiteSpace(source.OriginalTitle))
{
target.OriginalTitle = source.OriginalTitle;
}
}
- if (replaceData || !target.CommunityRating.HasValue || (source.CommunityRating.HasValue && string.Equals(sourceResult.Provider, "The Open Movie Database", StringComparison.OrdinalIgnoreCase)))
+ if (replaceData || !target.CommunityRating.HasValue)
{
target.CommunityRating = source.CommunityRating;
}
@@ -61,7 +67,7 @@ namespace MediaBrowser.Providers.Manager
target.EndDate = source.EndDate;
}
- if (!lockedFields.Contains(MetadataFields.Genres))
+ if (!lockedFields.Contains(MetadataField.Genres))
{
if (replaceData || target.Genres.Length == 0)
{
@@ -74,7 +80,7 @@ namespace MediaBrowser.Providers.Manager
target.IndexNumber = source.IndexNumber;
}
- if (!lockedFields.Contains(MetadataFields.OfficialRating))
+ if (!lockedFields.Contains(MetadataField.OfficialRating))
{
if (replaceData || string.IsNullOrEmpty(target.OfficialRating))
{
@@ -92,7 +98,7 @@ namespace MediaBrowser.Providers.Manager
target.Tagline = source.Tagline;
}
- if (!lockedFields.Contains(MetadataFields.Overview))
+ if (!lockedFields.Contains(MetadataField.Overview))
{
if (replaceData || string.IsNullOrEmpty(target.Overview))
{
@@ -105,12 +111,11 @@ namespace MediaBrowser.Providers.Manager
target.ParentIndexNumber = source.ParentIndexNumber;
}
- if (!lockedFields.Contains(MetadataFields.Cast))
+ if (!lockedFields.Contains(MetadataField.Cast))
{
if (replaceData || targetResult.People == null || targetResult.People.Count == 0)
{
targetResult.People = sourceResult.People;
-
}
else if (targetResult.People != null && sourceResult.People != null)
{
@@ -128,18 +133,18 @@ namespace MediaBrowser.Providers.Manager
target.ProductionYear = source.ProductionYear;
}
- if (!lockedFields.Contains(MetadataFields.Runtime))
+ if (!lockedFields.Contains(MetadataField.Runtime))
{
if (replaceData || !target.RunTimeTicks.HasValue)
{
- if (!(target is Audio) && !(target is Video))
+ if (target is not Audio && target is not Video)
{
target.RunTimeTicks = source.RunTimeTicks;
}
}
}
- if (!lockedFields.Contains(MetadataFields.Studios))
+ if (!lockedFields.Contains(MetadataField.Studios))
{
if (replaceData || target.Studios.Length == 0)
{
@@ -147,7 +152,7 @@ namespace MediaBrowser.Providers.Manager
}
}
- if (!lockedFields.Contains(MetadataFields.Tags))
+ if (!lockedFields.Contains(MetadataField.Tags))
{
if (replaceData || target.Tags.Length == 0)
{
@@ -155,7 +160,7 @@ namespace MediaBrowser.Providers.Manager
}
}
- if (!lockedFields.Contains(MetadataFields.ProductionLocations))
+ if (!lockedFields.Contains(MetadataField.ProductionLocations))
{
if (replaceData || target.ProductionLocations.Length == 0)
{
@@ -174,11 +179,11 @@ namespace MediaBrowser.Providers.Manager
}
}
- MergeAlbumArtist(source, target, lockedFields, replaceData);
- MergeCriticRating(source, target, lockedFields, replaceData);
- MergeTrailers(source, target, lockedFields, replaceData);
- MergeVideoInfo(source, target, lockedFields, replaceData);
- MergeDisplayOrder(source, target, lockedFields, replaceData);
+ MergeAlbumArtist(source, target, replaceData);
+ MergeCriticRating(source, target, replaceData);
+ MergeTrailers(source, target, replaceData);
+ MergeVideoInfo(source, target, replaceData);
+ MergeDisplayOrder(source, target, replaceData);
if (replaceData || string.IsNullOrEmpty(target.ForcedSortName))
{
@@ -196,7 +201,7 @@ namespace MediaBrowser.Providers.Manager
target.IsLocked = source.IsLocked;
// Grab the value if it's there, but if not then don't overwrite the default
- if (source.DateCreated != default(DateTime))
+ if (source.DateCreated != default)
{
target.DateCreated = source.DateCreated;
}
@@ -231,12 +236,10 @@ namespace MediaBrowser.Providers.Manager
}
}
- private static void MergeDisplayOrder(BaseItem source, BaseItem target, MetadataFields[] lockedFields, bool replaceData)
+ private static void MergeDisplayOrder(BaseItem source, BaseItem target, bool replaceData)
{
- var sourceHasDisplayOrder = source as IHasDisplayOrder;
- var targetHasDisplayOrder = target as IHasDisplayOrder;
-
- if (sourceHasDisplayOrder != null && targetHasDisplayOrder != null)
+ if (source is IHasDisplayOrder sourceHasDisplayOrder
+ && target is IHasDisplayOrder targetHasDisplayOrder)
{
if (replaceData || string.IsNullOrEmpty(targetHasDisplayOrder.DisplayOrder))
{
@@ -250,21 +253,19 @@ namespace MediaBrowser.Providers.Manager
}
}
- private static void MergeAlbumArtist(BaseItem source, BaseItem target, MetadataFields[] lockedFields, bool replaceData)
+ private static void MergeAlbumArtist(BaseItem source, BaseItem target, bool replaceData)
{
- var sourceHasAlbumArtist = source as IHasAlbumArtist;
- var targetHasAlbumArtist = target as IHasAlbumArtist;
-
- if (sourceHasAlbumArtist != null && targetHasAlbumArtist != null)
+ if (source is IHasAlbumArtist sourceHasAlbumArtist
+ && target is IHasAlbumArtist targetHasAlbumArtist)
{
- if (replaceData || targetHasAlbumArtist.AlbumArtists.Length == 0)
+ if (replaceData || targetHasAlbumArtist.AlbumArtists.Count == 0)
{
targetHasAlbumArtist.AlbumArtists = sourceHasAlbumArtist.AlbumArtists;
}
}
}
- private static void MergeCriticRating(BaseItem source, BaseItem target, MetadataFields[] lockedFields, bool replaceData)
+ private static void MergeCriticRating(BaseItem source, BaseItem target, bool replaceData)
{
if (replaceData || !target.CriticRating.HasValue)
{
@@ -272,20 +273,17 @@ namespace MediaBrowser.Providers.Manager
}
}
- private static void MergeTrailers(BaseItem source, BaseItem target, MetadataFields[] lockedFields, bool replaceData)
+ private static void MergeTrailers(BaseItem source, BaseItem target, bool replaceData)
{
- if (replaceData || target.RemoteTrailers.Length == 0)
+ if (replaceData || target.RemoteTrailers.Count == 0)
{
target.RemoteTrailers = source.RemoteTrailers;
}
}
- private static void MergeVideoInfo(BaseItem source, BaseItem target, MetadataFields[] lockedFields, bool replaceData)
+ private static void MergeVideoInfo(BaseItem source, BaseItem target, bool replaceData)
{
- var sourceCast = source as Video;
- var targetCast = target as Video;
-
- if (sourceCast != null && targetCast != null)
+ if (source is Video sourceCast && target is Video targetCast)
{
if (replaceData || targetCast.Video3DFormat == null)
{
diff --git a/MediaBrowser.Providers/Manager/RefreshResult.cs b/MediaBrowser.Providers/Manager/RefreshResult.cs
new file mode 100644
index 000000000..663ffc524
--- /dev/null
+++ b/MediaBrowser.Providers/Manager/RefreshResult.cs
@@ -0,0 +1,15 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Library;
+
+namespace MediaBrowser.Providers.Manager
+{
+ public class RefreshResult
+ {
+ public ItemUpdateType UpdateType { get; set; }
+
+ public string? ErrorMessage { get; set; }
+
+ public int Failures { get; set; }
+ }
+}
diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
index 52a52efdc..9d0a6944b 100644
--- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj
+++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
@@ -1,5 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{442B5058-DCAF-4263-BB6A-F21E31120A1B}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
@@ -11,15 +16,37 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
- <PackageReference Include="OptimizedPriorityQueue" Version="4.2.0" />
- <PackageReference Include="PlaylistsNET" Version="1.0.2" />
- <PackageReference Include="TvDbSharper" Version="2.0.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
+ <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" />
+ <PackageReference Include="PlaylistsNET" Version="1.1.3" />
+ <PackageReference Include="TMDbLib" Version="1.8.1" />
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <None Remove="Plugins\AudioDb\Configuration\config.html" />
+ <EmbeddedResource Include="Plugins\AudioDb\Configuration\config.html" />
+ <None Remove="Plugins\Omdb\Configuration\config.html" />
+ <EmbeddedResource Include="Plugins\Omdb\Configuration\config.html" />
+ <None Remove="Plugins\MusicBrainz\Configuration\config.html" />
+ <EmbeddedResource Include="Plugins\MusicBrainz\Configuration\config.html" />
+ <None Remove="Plugins\Tmdb\Configuration\config.html" />
+ <EmbeddedResource Include="Plugins\Tmdb\Configuration\config.html" />
+ </ItemGroup>
</Project>
diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs
index 61a8a122b..8c81b08db 100644
--- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs
@@ -1,5 +1,10 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -16,7 +21,7 @@ using MediaBrowser.Model.IO;
namespace MediaBrowser.Providers.MediaInfo
{
/// <summary>
- /// Uses ffmpeg to create video images
+ /// Uses ffmpeg to create video images.
/// </summary>
public class AudioImageProvider : IDynamicImageProvider
{
@@ -31,6 +36,10 @@ namespace MediaBrowser.Providers.MediaInfo
_fileSystem = fileSystem;
}
+ public string AudioImagesPath => Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images");
+
+ public string Name => "Image Extractor";
+
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType> { ImageType.Primary };
@@ -78,7 +87,6 @@ namespace MediaBrowser.Providers.MediaInfo
}
catch
{
-
}
}
@@ -91,19 +99,19 @@ namespace MediaBrowser.Providers.MediaInfo
private string GetAudioImagePath(Audio item)
{
- string filename = null;
+ string filename;
if (item.GetType() == typeof(Audio))
{
- var albumArtist = item.AlbumArtists.FirstOrDefault();
-
- if (!string.IsNullOrWhiteSpace(item.Album) && !string.IsNullOrWhiteSpace(albumArtist))
+ if (item.AlbumArtists.Count > 0
+ && !string.IsNullOrWhiteSpace(item.Album)
+ && !string.IsNullOrWhiteSpace(item.AlbumArtists[0]))
{
- filename = (item.Album + "-" + albumArtist).GetMD5().ToString("N");
+ filename = (item.Album + "-" + item.AlbumArtists[0]).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
else
{
- filename = item.Id.ToString("N");
+ filename = item.Id.ToString("N", CultureInfo.InvariantCulture);
}
filename += ".jpg";
@@ -111,32 +119,27 @@ namespace MediaBrowser.Providers.MediaInfo
else
{
// If it's an audio book or audio podcast, allow unique image per item
- filename = item.Id.ToString("N") + ".jpg";
+ filename = item.Id.ToString("N", CultureInfo.InvariantCulture) + ".jpg";
}
- var prefix = filename.Substring(0, 1);
+ var prefix = filename.AsSpan().Slice(0, 1);
- return Path.Combine(AudioImagesPath, prefix, filename);
+ return Path.Join(AudioImagesPath, prefix, filename);
}
- public string AudioImagesPath => Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images");
-
- public string Name => "Image Extractor";
-
public bool Supports(BaseItem item)
{
if (item.IsShortcut)
{
return false;
}
+
if (!item.IsFileProtocol)
{
return false;
}
- var audio = item as Audio;
-
- return audio != null;
+ return item is Audio;
}
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs b/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs
new file mode 100644
index 000000000..c41d36d76
--- /dev/null
+++ b/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs
@@ -0,0 +1,222 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Net;
+
+namespace MediaBrowser.Providers.MediaInfo
+{
+ /// <summary>
+ /// Uses <see cref="IMediaEncoder"/> to extract embedded images.
+ /// </summary>
+ public class EmbeddedImageProvider : IDynamicImageProvider, IHasOrder
+ {
+ private static readonly string[] _primaryImageFileNames =
+ {
+ "poster",
+ "folder",
+ "cover",
+ "default"
+ };
+
+ private static readonly string[] _backdropImageFileNames =
+ {
+ "backdrop",
+ "fanart",
+ "background",
+ "art"
+ };
+
+ private static readonly string[] _logoImageFileNames =
+ {
+ "logo",
+ };
+
+ private readonly IMediaEncoder _mediaEncoder;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EmbeddedImageProvider"/> class.
+ /// </summary>
+ /// <param name="mediaEncoder">The media encoder for extracting attached/embedded images.</param>
+ public EmbeddedImageProvider(IMediaEncoder mediaEncoder)
+ {
+ _mediaEncoder = mediaEncoder;
+ }
+
+ /// <inheritdoc />
+ public string Name => "Embedded Image Extractor";
+
+ /// <inheritdoc />
+ // Default to after internet image providers but before Screen Grabber
+ public int Order => 99;
+
+ /// <inheritdoc />
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ if (item is Video)
+ {
+ if (item is Episode)
+ {
+ return new[]
+ {
+ ImageType.Primary,
+ };
+ }
+
+ return new[]
+ {
+ ImageType.Primary,
+ ImageType.Backdrop,
+ ImageType.Logo,
+ };
+ }
+
+ return Array.Empty<ImageType>();
+ }
+
+ /// <inheritdoc />
+ public Task<DynamicImageResponse> GetImage(BaseItem item, ImageType type, CancellationToken cancellationToken)
+ {
+ var video = (Video)item;
+
+ // No support for these
+ if (video.IsPlaceHolder || video.VideoType == VideoType.Dvd)
+ {
+ return Task.FromResult(new DynamicImageResponse { HasImage = false });
+ }
+
+ return GetEmbeddedImage(video, type, cancellationToken);
+ }
+
+ private async Task<DynamicImageResponse> GetEmbeddedImage(Video item, ImageType type, CancellationToken cancellationToken)
+ {
+ MediaSourceInfo mediaSource = new MediaSourceInfo
+ {
+ VideoType = item.VideoType,
+ IsoType = item.IsoType,
+ Protocol = item.PathProtocol ?? MediaProtocol.File,
+ };
+
+ string[] imageFileNames = type switch
+ {
+ ImageType.Primary => _primaryImageFileNames,
+ ImageType.Backdrop => _backdropImageFileNames,
+ ImageType.Logo => _logoImageFileNames,
+ _ => _primaryImageFileNames
+ };
+
+ // Try attachments first
+ var attachmentStream = item.GetMediaSources(false)
+ .SelectMany(source => source.MediaAttachments)
+ .FirstOrDefault(attachment => !string.IsNullOrEmpty(attachment.FileName)
+ && imageFileNames.Any(name => attachment.FileName.Contains(name, StringComparison.OrdinalIgnoreCase)));
+
+ if (attachmentStream != null)
+ {
+ return await ExtractAttachment(item, cancellationToken, attachmentStream, mediaSource);
+ }
+
+ // Fall back to EmbeddedImage streams
+ var imageStreams = item.GetMediaStreams().FindAll(i => i.Type == MediaStreamType.EmbeddedImage);
+
+ if (imageStreams.Count == 0)
+ {
+ // Can't extract if we don't have any EmbeddedImage streams
+ return new DynamicImageResponse { HasImage = false };
+ }
+
+ // Extract first stream containing an element of imageFileNames
+ var imageStream = imageStreams
+ .FirstOrDefault(stream => !string.IsNullOrEmpty(stream.Comment)
+ && imageFileNames.Any(name => stream.Comment.Contains(name, StringComparison.OrdinalIgnoreCase)));
+
+ // Primary type only: default to first image if none found by label
+ if (imageStream == null)
+ {
+ if (type == ImageType.Primary)
+ {
+ imageStream = imageStreams[0];
+ }
+ else
+ {
+ // No streams matched, abort
+ return new DynamicImageResponse { HasImage = false };
+ }
+ }
+
+ string extractedImagePath =
+ await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, imageStream, imageStream.Index, ".jpg", cancellationToken)
+ .ConfigureAwait(false);
+
+ return new DynamicImageResponse
+ {
+ Format = ImageFormat.Jpg,
+ HasImage = true,
+ Path = extractedImagePath,
+ Protocol = MediaProtocol.File
+ };
+ }
+
+ private async Task<DynamicImageResponse> ExtractAttachment(Video item, CancellationToken cancellationToken, MediaAttachment attachmentStream, MediaSourceInfo mediaSource)
+ {
+ var extension = string.IsNullOrEmpty(attachmentStream.MimeType)
+ ? Path.GetExtension(attachmentStream.FileName)
+ : MimeTypes.ToExtension(attachmentStream.MimeType);
+
+ if (string.IsNullOrEmpty(extension))
+ {
+ extension = ".jpg";
+ }
+
+ string extractedAttachmentPath =
+ await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, null, attachmentStream.Index, extension, cancellationToken)
+ .ConfigureAwait(false);
+
+ ImageFormat format = extension switch
+ {
+ ".bmp" => ImageFormat.Bmp,
+ ".gif" => ImageFormat.Gif,
+ ".jpg" => ImageFormat.Jpg,
+ ".png" => ImageFormat.Png,
+ ".webp" => ImageFormat.Webp,
+ _ => ImageFormat.Jpg
+ };
+
+ return new DynamicImageResponse
+ {
+ Format = format,
+ HasImage = true,
+ Path = extractedAttachmentPath,
+ Protocol = MediaProtocol.File
+ };
+ }
+
+ /// <inheritdoc />
+ public bool Supports(BaseItem item)
+ {
+ if (item.IsShortcut)
+ {
+ return false;
+ }
+
+ if (!item.IsFileProtocol)
+ {
+ return false;
+ }
+
+ return item is Video video && !video.IsPlaceHolder && video.IsCompleteMedia;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs
index 207d75524..9eb79c39d 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs
@@ -1,10 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
-using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
@@ -15,32 +17,31 @@ using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Providers.MediaInfo
{
- class FFProbeAudioInfo
+ public class FFProbeAudioInfo
{
private readonly IMediaEncoder _mediaEncoder;
private readonly IItemRepository _itemRepo;
- private readonly IApplicationPaths _appPaths;
- private readonly IJsonSerializer _json;
private readonly ILibraryManager _libraryManager;
private readonly IMediaSourceManager _mediaSourceManager;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public FFProbeAudioInfo(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IApplicationPaths appPaths, IJsonSerializer json, ILibraryManager libraryManager)
+ public FFProbeAudioInfo(
+ IMediaSourceManager mediaSourceManager,
+ IMediaEncoder mediaEncoder,
+ IItemRepository itemRepo,
+ ILibraryManager libraryManager)
{
_mediaEncoder = mediaEncoder;
_itemRepo = itemRepo;
- _appPaths = appPaths;
- _json = json;
_libraryManager = libraryManager;
_mediaSourceManager = mediaSourceManager;
}
- public async Task<ItemUpdateType> Probe<T>(T item, MetadataRefreshOptions options,
+ public async Task<ItemUpdateType> Probe<T>(
+ T item,
+ MetadataRefreshOptions options,
CancellationToken cancellationToken)
where T : Audio
{
@@ -55,20 +56,21 @@ namespace MediaBrowser.Providers.MediaInfo
protocol = _mediaSourceManager.GetPathProtocol(path);
}
- var result = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
- {
- MediaType = DlnaProfileType.Audio,
- MediaSource = new MediaSourceInfo
+ var result = await _mediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
{
- Path = path,
- Protocol = protocol
- }
-
- }, cancellationToken).ConfigureAwait(false);
+ MediaType = DlnaProfileType.Audio,
+ MediaSource = new MediaSourceInfo
+ {
+ Path = path,
+ Protocol = protocol
+ }
+ },
+ cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
- Fetch(item, cancellationToken, result);
+ Fetch(item, result, cancellationToken);
}
return ItemUpdateType.MetadataImport;
@@ -78,10 +80,9 @@ namespace MediaBrowser.Providers.MediaInfo
/// Fetches the specified audio.
/// </summary>
/// <param name="audio">The audio.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="mediaInfo">The media information.</param>
- /// <returns>Task.</returns>
- protected void Fetch(Audio audio, CancellationToken cancellationToken, Model.MediaInfo.MediaInfo mediaInfo)
+ /// <param name="cancellationToken">The cancellation token.</param>
+ protected void Fetch(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, CancellationToken cancellationToken)
{
var mediaStreams = mediaInfo.MediaStreams;
@@ -91,8 +92,8 @@ namespace MediaBrowser.Providers.MediaInfo
audio.RunTimeTicks = mediaInfo.RunTimeTicks;
audio.Size = mediaInfo.Size;
- //var extension = (Path.GetExtension(audio.Path) ?? string.Empty).TrimStart('.');
- //audio.Container = extension;
+ // var extension = (Path.GetExtension(audio.Path) ?? string.Empty).TrimStart('.');
+ // audio.Container = extension;
FetchDataFromTags(audio, mediaInfo);
@@ -100,7 +101,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
/// <summary>
- /// Fetches data from the tags dictionary
+ /// Fetches data from the tags dictionary.
/// </summary>
/// <param name="audio">The audio.</param>
/// <param name="data">The data.</param>
@@ -112,7 +113,12 @@ namespace MediaBrowser.Providers.MediaInfo
audio.Name = data.Name;
}
- if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataFields.Cast))
+ if (!string.IsNullOrEmpty(data.ForcedSortName))
+ {
+ audio.ForcedSortName = data.ForcedSortName;
+ }
+
+ if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
{
var people = new List<PersonInfo>();
@@ -143,7 +149,7 @@ namespace MediaBrowser.Providers.MediaInfo
audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
}
- if (!audio.LockedFields.Contains(MetadataFields.Genres))
+ if (!audio.LockedFields.Contains(MetadataField.Genres))
{
audio.Genres = Array.Empty<string>();
@@ -153,16 +159,16 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (!audio.LockedFields.Contains(MetadataFields.Studios))
+ if (!audio.LockedFields.Contains(MetadataField.Studios))
{
audio.SetStudios(data.Studios);
}
- audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, data.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist));
- audio.SetProviderId(MetadataProviders.MusicBrainzArtist, data.GetProviderId(MetadataProviders.MusicBrainzArtist));
- audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, data.GetProviderId(MetadataProviders.MusicBrainzAlbum));
- audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, data.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup));
- audio.SetProviderId(MetadataProviders.MusicBrainzTrack, data.GetProviderId(MetadataProviders.MusicBrainzTrack));
+ audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, data.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist));
+ audio.SetProviderId(MetadataProvider.MusicBrainzArtist, data.GetProviderId(MetadataProvider.MusicBrainzArtist));
+ audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, data.GetProviderId(MetadataProvider.MusicBrainzAlbum));
+ audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, data.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup));
+ audio.SetProviderId(MetadataProvider.MusicBrainzTrack, data.GetProviderId(MetadataProvider.MusicBrainzTrack));
}
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
index 4e11fcbb2..d4b5d8655 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
@@ -1,10 +1,12 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -18,9 +20,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.MediaInfo
@@ -37,25 +37,54 @@ namespace MediaBrowser.Providers.MediaInfo
IPreRefreshProvider,
IHasItemChangeMonitor
{
- private readonly ILogger _logger;
- private readonly IIsoManager _isoManager;
+ private readonly ILogger<FFProbeProvider> _logger;
private readonly IMediaEncoder _mediaEncoder;
private readonly IItemRepository _itemRepo;
private readonly IBlurayExaminer _blurayExaminer;
private readonly ILocalizationManager _localization;
- private readonly IApplicationPaths _appPaths;
- private readonly IJsonSerializer _json;
private readonly IEncodingManager _encodingManager;
- private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _config;
private readonly ISubtitleManager _subtitleManager;
private readonly IChapterManager _chapterManager;
private readonly ILibraryManager _libraryManager;
- private readonly IChannelManager _channelManager;
private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly SubtitleResolver _subtitleResolver;
+
+ private readonly Task<ItemUpdateType> _cachedTask = Task.FromResult(ItemUpdateType.None);
+
+ public FFProbeProvider(
+ ILogger<FFProbeProvider> logger,
+ IMediaSourceManager mediaSourceManager,
+ IMediaEncoder mediaEncoder,
+ IItemRepository itemRepo,
+ IBlurayExaminer blurayExaminer,
+ ILocalizationManager localization,
+ IEncodingManager encodingManager,
+ IServerConfigurationManager config,
+ ISubtitleManager subtitleManager,
+ IChapterManager chapterManager,
+ ILibraryManager libraryManager)
+ {
+ _logger = logger;
+ _mediaEncoder = mediaEncoder;
+ _itemRepo = itemRepo;
+ _blurayExaminer = blurayExaminer;
+ _localization = localization;
+ _encodingManager = encodingManager;
+ _config = config;
+ _subtitleManager = subtitleManager;
+ _chapterManager = chapterManager;
+ _libraryManager = libraryManager;
+ _mediaSourceManager = mediaSourceManager;
+
+ _subtitleResolver = new SubtitleResolver(BaseItem.LocalizationManager);
+ }
public string Name => "ffprobe";
+ // Run last
+ public int Order => 100;
+
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
var video = item as Video;
@@ -120,38 +149,9 @@ namespace MediaBrowser.Providers.MediaInfo
return FetchAudioInfo(item, options, cancellationToken);
}
- private SubtitleResolver _subtitleResolver;
- public FFProbeProvider(ILogger logger, IMediaSourceManager mediaSourceManager, IChannelManager channelManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IBlurayExaminer blurayExaminer, ILocalizationManager localization, IApplicationPaths appPaths, IJsonSerializer json, IEncodingManager encodingManager, IFileSystem fileSystem, IServerConfigurationManager config, ISubtitleManager subtitleManager, IChapterManager chapterManager, ILibraryManager libraryManager)
- {
- _logger = logger;
- _isoManager = isoManager;
- _mediaEncoder = mediaEncoder;
- _itemRepo = itemRepo;
- _blurayExaminer = blurayExaminer;
- _localization = localization;
- _appPaths = appPaths;
- _json = json;
- _encodingManager = encodingManager;
- _fileSystem = fileSystem;
- _config = config;
- _subtitleManager = subtitleManager;
- _chapterManager = chapterManager;
- _libraryManager = libraryManager;
- _channelManager = channelManager;
- _mediaSourceManager = mediaSourceManager;
-
- _subtitleResolver = new SubtitleResolver(BaseItem.LocalizationManager, fileSystem);
- }
-
- private readonly Task<ItemUpdateType> _cachedTask = Task.FromResult(ItemUpdateType.None);
public Task<ItemUpdateType> FetchVideoInfo<T>(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
where T : Video
{
- if (item.VideoType == VideoType.Iso)
- {
- return _cachedTask;
- }
-
if (item.IsPlaceHolder)
{
return _cachedTask;
@@ -177,16 +177,27 @@ namespace MediaBrowser.Providers.MediaInfo
FetchShortcutInfo(item);
}
- var prober = new FFProbeVideoInfo(_logger, _mediaSourceManager, _isoManager, _mediaEncoder, _itemRepo, _blurayExaminer, _localization, _appPaths, _json, _encodingManager, _fileSystem, _config, _subtitleManager, _chapterManager, _libraryManager);
+ var prober = new FFProbeVideoInfo(
+ _logger,
+ _mediaSourceManager,
+ _mediaEncoder,
+ _itemRepo,
+ _blurayExaminer,
+ _localization,
+ _encodingManager,
+ _config,
+ _subtitleManager,
+ _chapterManager,
+ _libraryManager);
return prober.ProbeVideo(item, options, cancellationToken);
}
private string NormalizeStrmLine(string line)
{
- return line.Replace("\t", string.Empty)
- .Replace("\r", string.Empty)
- .Replace("\n", string.Empty)
+ return line.Replace("\t", string.Empty, StringComparison.Ordinal)
+ .Replace("\r", string.Empty, StringComparison.Ordinal)
+ .Replace("\n", string.Empty, StringComparison.Ordinal)
.Trim();
}
@@ -194,7 +205,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
item.ShortcutPath = File.ReadAllLines(item.Path)
.Select(NormalizeStrmLine)
- .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i) && !i.StartsWith("#", StringComparison.OrdinalIgnoreCase));
+ .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i) && !i.StartsWith('#'));
}
public Task<ItemUpdateType> FetchAudioInfo<T>(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
@@ -215,11 +226,9 @@ namespace MediaBrowser.Providers.MediaInfo
FetchShortcutInfo(item);
}
- var prober = new FFProbeAudioInfo(_mediaSourceManager, _mediaEncoder, _itemRepo, _appPaths, _json, _libraryManager);
+ var prober = new FFProbeAudioInfo(_mediaSourceManager, _mediaEncoder, _itemRepo, _libraryManager);
return prober.Probe(item, options, cancellationToken);
}
- // Run last
- public int Order => 100;
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
index d2abd2a63..4ab15f60e 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1068, CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -22,10 +26,8 @@ using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.MediaInfo
@@ -33,33 +35,38 @@ namespace MediaBrowser.Providers.MediaInfo
public class FFProbeVideoInfo
{
private readonly ILogger _logger;
- private readonly IIsoManager _isoManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IItemRepository _itemRepo;
private readonly IBlurayExaminer _blurayExaminer;
private readonly ILocalizationManager _localization;
- private readonly IApplicationPaths _appPaths;
- private readonly IJsonSerializer _json;
private readonly IEncodingManager _encodingManager;
- private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _config;
private readonly ISubtitleManager _subtitleManager;
private readonly IChapterManager _chapterManager;
private readonly ILibraryManager _libraryManager;
private readonly IMediaSourceManager _mediaSourceManager;
- public FFProbeVideoInfo(ILogger logger, IMediaSourceManager mediaSourceManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IBlurayExaminer blurayExaminer, ILocalizationManager localization, IApplicationPaths appPaths, IJsonSerializer json, IEncodingManager encodingManager, IFileSystem fileSystem, IServerConfigurationManager config, ISubtitleManager subtitleManager, IChapterManager chapterManager, ILibraryManager libraryManager)
+ private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
+
+ public FFProbeVideoInfo(
+ ILogger logger,
+ IMediaSourceManager mediaSourceManager,
+ IMediaEncoder mediaEncoder,
+ IItemRepository itemRepo,
+ IBlurayExaminer blurayExaminer,
+ ILocalizationManager localization,
+ IEncodingManager encodingManager,
+ IServerConfigurationManager config,
+ ISubtitleManager subtitleManager,
+ IChapterManager chapterManager,
+ ILibraryManager libraryManager)
{
_logger = logger;
- _isoManager = isoManager;
_mediaEncoder = mediaEncoder;
_itemRepo = itemRepo;
_blurayExaminer = blurayExaminer;
_localization = localization;
- _appPaths = appPaths;
- _json = json;
_encodingManager = encodingManager;
- _fileSystem = fileSystem;
_config = config;
_subtitleManager = subtitleManager;
_chapterManager = chapterManager;
@@ -67,7 +74,8 @@ namespace MediaBrowser.Providers.MediaInfo
_mediaSourceManager = mediaSourceManager;
}
- public async Task<ItemUpdateType> ProbeVideo<T>(T item,
+ public async Task<ItemUpdateType> ProbeVideo<T>(
+ T item,
MetadataRefreshOptions options,
CancellationToken cancellationToken)
where T : Video
@@ -90,7 +98,6 @@ namespace MediaBrowser.Providers.MediaInfo
return ItemUpdateType.MetadataImport;
}
}
-
else if (item.VideoType == VideoType.BluRay)
{
var inputPath = item.Path;
@@ -106,12 +113,9 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (streamFileNames == null)
- {
- streamFileNames = Array.Empty<string>();
- }
+ streamFileNames ??= Array.Empty<string>();
- mediaInfoResult = await GetMediaInfo(item, streamFileNames, cancellationToken).ConfigureAwait(false);
+ mediaInfoResult = await GetMediaInfo(item, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
}
@@ -121,8 +125,8 @@ namespace MediaBrowser.Providers.MediaInfo
return ItemUpdateType.MetadataImport;
}
- private Task<Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
- string[] streamFileNames,
+ private Task<Model.MediaInfo.MediaInfo> GetMediaInfo(
+ Video item,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -136,36 +140,40 @@ namespace MediaBrowser.Providers.MediaInfo
protocol = _mediaSourceManager.GetPathProtocol(path);
}
- return _mediaEncoder.GetMediaInfo(new MediaInfoRequest
- {
- PlayableStreamFileNames = streamFileNames,
- ExtractChapters = true,
- MediaType = DlnaProfileType.Video,
- MediaSource = new MediaSourceInfo
+ return _mediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
{
- Path = path,
- Protocol = protocol,
- VideoType = item.VideoType
- }
-
- }, cancellationToken);
+ ExtractChapters = true,
+ MediaType = DlnaProfileType.Video,
+ MediaSource = new MediaSourceInfo
+ {
+ Path = path,
+ Protocol = protocol,
+ VideoType = item.VideoType,
+ IsoType = item.IsoType
+ }
+ },
+ cancellationToken);
}
- protected async Task Fetch(Video video,
+ protected async Task Fetch(
+ Video video,
CancellationToken cancellationToken,
Model.MediaInfo.MediaInfo mediaInfo,
BlurayDiscInfo blurayInfo,
MetadataRefreshOptions options)
{
List<MediaStream> mediaStreams;
- List<ChapterInfo> chapters;
+ IReadOnlyList<MediaAttachment> mediaAttachments;
+ ChapterInfo[] chapters;
if (mediaInfo != null)
{
mediaStreams = mediaInfo.MediaStreams;
+ mediaAttachments = mediaInfo.MediaAttachments;
video.TotalBitrate = mediaInfo.Bitrate;
- //video.FormatName = (mediaInfo.Container ?? string.Empty)
+ // video.FormatName = (mediaInfo.Container ?? string.Empty)
// .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
// For dvd's this may not always be accurate, so don't set the runtime if the item already has one
@@ -175,6 +183,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
video.RunTimeTicks = mediaInfo.RunTimeTicks;
}
+
video.Size = mediaInfo.Size;
if (video.VideoType == VideoType.VideoFile)
@@ -187,18 +196,20 @@ namespace MediaBrowser.Providers.MediaInfo
{
video.Container = null;
}
+
video.Container = mediaInfo.Container;
- chapters = mediaInfo.Chapters == null ? new List<ChapterInfo>() : mediaInfo.Chapters.ToList();
+ chapters = mediaInfo.Chapters == null ? Array.Empty<ChapterInfo>() : mediaInfo.Chapters;
if (blurayInfo != null)
{
- FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
+ FetchBdInfo(video, ref chapters, mediaStreams, blurayInfo);
}
}
else
{
mediaStreams = new List<MediaStream>();
- chapters = new List<ChapterInfo>();
+ mediaAttachments = Array.Empty<MediaAttachment>();
+ chapters = Array.Empty<ChapterInfo>();
}
await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
@@ -210,26 +221,27 @@ namespace MediaBrowser.Providers.MediaInfo
FetchEmbeddedInfo(video, mediaInfo, options, libraryOptions);
FetchPeople(video, mediaInfo, options);
video.Timestamp = mediaInfo.Timestamp;
- video.Video3DFormat = video.Video3DFormat ?? mediaInfo.Video3DFormat;
+ video.Video3DFormat ??= mediaInfo.Video3DFormat;
}
var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
- video.Height = videoStream == null ? 0 : videoStream.Height ?? 0;
- video.Width = videoStream == null ? 0 : videoStream.Width ?? 0;
+ video.Height = videoStream?.Height ?? 0;
+ video.Width = videoStream?.Width ?? 0;
video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
_itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken);
+ _itemRepo.SaveMediaAttachments(video.Id, mediaAttachments, cancellationToken);
if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
options.MetadataRefreshMode == MetadataRefreshMode.Default)
{
- if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
+ if (chapters.Length == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
{
- AddDummyChapters(video, chapters);
+ chapters = CreateDummyChapters(video);
}
NormalizeChapterNames(chapters);
@@ -242,32 +254,33 @@ namespace MediaBrowser.Providers.MediaInfo
await _encodingManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
- _chapterManager.SaveChapters(video.Id.ToString(), chapters);
+ _chapterManager.SaveChapters(video.Id, chapters);
}
}
- private void NormalizeChapterNames(List<ChapterInfo> chapters)
+ private void NormalizeChapterNames(ChapterInfo[] chapters)
{
- var index = 1;
-
- foreach (var chapter in chapters)
+ for (int i = 0; i < chapters.Length; i++)
{
+ string name = chapters[i].Name;
// Check if the name is empty and/or if the name is a time
// Some ripping programs do that.
- if (string.IsNullOrWhiteSpace(chapter.Name) ||
- TimeSpan.TryParse(chapter.Name, out var time))
+ if (string.IsNullOrWhiteSpace(name) ||
+ TimeSpan.TryParse(name, out _))
{
- chapter.Name = string.Format(_localization.GetLocalizedString("ChapterNameValue"), index.ToString(CultureInfo.InvariantCulture));
+ chapters[i].Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("ChapterNameValue"),
+ (i + 1).ToString(CultureInfo.InvariantCulture));
}
- index++;
}
}
- private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
+ private void FetchBdInfo(BaseItem item, ref ChapterInfo[] chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
{
var video = (Video)item;
- //video.PlayableStreamFileNames = blurayInfo.Files.ToList();
+ // video.PlayableStreamFileNames = blurayInfo.Files.ToList();
// Use BD Info if it has multiple m2ts. Otherwise, treat it like a video file and rely more on ffprobe output
if (blurayInfo.Files.Length > 1)
@@ -297,13 +310,15 @@ namespace MediaBrowser.Providers.MediaInfo
if (blurayInfo.Chapters != null)
{
- chapters.Clear();
-
- chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
+ double[] brChapter = blurayInfo.Chapters;
+ chapters = new ChapterInfo[brChapter.Length];
+ for (int i = 0; i < brChapter.Length; i++)
{
- StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
-
- }));
+ chapters[i] = new ChapterInfo
+ {
+ StartPositionTicks = TimeSpan.FromSeconds(brChapter[i]).Ticks
+ };
+ }
}
videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
@@ -324,7 +339,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
/// <summary>
- /// Gets information about the longest playlist on a bdrom
+ /// Gets information about the longest playlist on a bdrom.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>VideoStream.</returns>
@@ -350,7 +365,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
var isFullRefresh = refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.OfficialRating))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.OfficialRating))
{
if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
{
@@ -358,7 +373,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Genres))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Genres))
{
if (video.Genres.Length == 0 || isFullRefresh)
{
@@ -371,7 +386,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Studios))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Studios))
{
if (video.Studios.Length == 0 || isFullRefresh)
{
@@ -379,6 +394,12 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
+ if (video is MusicVideo musicVideo)
+ {
+ musicVideo.Album = data.Album;
+ musicVideo.Artists = data.Artists;
+ }
+
if (data.ProductionYear.HasValue)
{
if (!video.ProductionYear.HasValue || isFullRefresh)
@@ -386,6 +407,7 @@ namespace MediaBrowser.Providers.MediaInfo
video.ProductionYear = data.ProductionYear;
}
}
+
if (data.PremiereDate.HasValue)
{
if (!video.PremiereDate.HasValue || isFullRefresh)
@@ -393,6 +415,7 @@ namespace MediaBrowser.Providers.MediaInfo
video.PremiereDate = data.PremiereDate;
}
}
+
if (data.IndexNumber.HasValue)
{
if (!video.IndexNumber.HasValue || isFullRefresh)
@@ -400,6 +423,7 @@ namespace MediaBrowser.Providers.MediaInfo
video.IndexNumber = data.IndexNumber;
}
}
+
if (data.ParentIndexNumber.HasValue)
{
if (!video.ParentIndexNumber.HasValue || isFullRefresh)
@@ -408,7 +432,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Name))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Name))
{
if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
{
@@ -418,6 +442,11 @@ namespace MediaBrowser.Providers.MediaInfo
video.Name = data.Name;
}
}
+
+ if (!string.IsNullOrWhiteSpace(data.ForcedSortName))
+ {
+ video.ForcedSortName = data.ForcedSortName;
+ }
}
// If we don't have a ProductionYear try and get it from PremiereDate
@@ -426,7 +455,7 @@ namespace MediaBrowser.Providers.MediaInfo
video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
}
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Overview))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Overview))
{
if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
{
@@ -439,7 +468,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
- if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Cast))
+ if (!video.IsLocked && !video.LockedFields.Contains(MetadataField.Cast))
{
if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
{
@@ -473,12 +502,13 @@ namespace MediaBrowser.Providers.MediaInfo
/// <param name="options">The refreshOptions.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- private async Task AddExternalSubtitles(Video video,
+ private async Task AddExternalSubtitles(
+ Video video,
List<MediaStream> currentStreams,
MetadataRefreshOptions options,
CancellationToken cancellationToken)
{
- var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
+ var subtitleResolver = new SubtitleResolver(_localization);
var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false);
@@ -491,17 +521,17 @@ namespace MediaBrowser.Providers.MediaInfo
var libraryOptions = _libraryManager.GetLibraryOptions(video);
string[] subtitleDownloadLanguages;
- bool SkipIfEmbeddedSubtitlesPresent;
- bool SkipIfAudioTrackMatches;
- bool RequirePerfectMatch;
+ bool skipIfEmbeddedSubtitlesPresent;
+ bool skipIfAudioTrackMatches;
+ bool requirePerfectMatch;
bool enabled;
if (libraryOptions.SubtitleDownloadLanguages == null)
{
subtitleDownloadLanguages = subtitleOptions.DownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = subtitleOptions.SkipIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = subtitleOptions.SkipIfAudioTrackMatches;
- RequirePerfectMatch = subtitleOptions.RequirePerfectMatch;
+ skipIfEmbeddedSubtitlesPresent = subtitleOptions.SkipIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = subtitleOptions.SkipIfAudioTrackMatches;
+ requirePerfectMatch = subtitleOptions.RequirePerfectMatch;
enabled = (subtitleOptions.DownloadEpisodeSubtitles &&
video is Episode) ||
(subtitleOptions.DownloadMovieSubtitles &&
@@ -510,25 +540,27 @@ namespace MediaBrowser.Providers.MediaInfo
else
{
subtitleDownloadLanguages = libraryOptions.SubtitleDownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
- RequirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
+ skipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
+ requirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
enabled = true;
}
if (enableSubtitleDownloading && enabled)
{
- var downloadedLanguages = await new SubtitleDownloader(_logger,
- _subtitleManager)
- .DownloadSubtitles(video,
- currentStreams.Concat(externalSubtitleStreams).ToList(),
- SkipIfEmbeddedSubtitlesPresent,
- SkipIfAudioTrackMatches,
- RequirePerfectMatch,
- subtitleDownloadLanguages,
- libraryOptions.DisabledSubtitleFetchers,
- libraryOptions.SubtitleFetcherOrder,
- cancellationToken).ConfigureAwait(false);
+ var downloadedLanguages = await new SubtitleDownloader(
+ _logger,
+ _subtitleManager).DownloadSubtitles(
+ video,
+ currentStreams.Concat(externalSubtitleStreams).ToList(),
+ skipIfEmbeddedSubtitlesPresent,
+ skipIfAudioTrackMatches,
+ requirePerfectMatch,
+ subtitleDownloadLanguages,
+ libraryOptions.DisabledSubtitleFetchers,
+ libraryOptions.SubtitleFetcherOrder,
+ true,
+ cancellationToken).ConfigureAwait(false);
// Rescan
if (downloadedLanguages.Count > 0)
@@ -543,49 +575,51 @@ namespace MediaBrowser.Providers.MediaInfo
}
/// <summary>
- /// The dummy chapter duration
- /// </summary>
- private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
-
- /// <summary>
- /// Adds the dummy chapters.
+ /// Creates dummy chapters.
/// </summary>
/// <param name="video">The video.</param>
- /// <param name="chapters">The chapters.</param>
- private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
+ /// <returns>An array of dummy chapters.</returns>
+ private ChapterInfo[] CreateDummyChapters(Video video)
{
var runtime = video.RunTimeTicks ?? 0;
if (runtime < 0)
{
- throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
+ throw new ArgumentException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} has invalid runtime of {1}",
+ video.Name,
+ runtime));
}
if (runtime < _dummyChapterDuration)
{
- return;
+ return Array.Empty<ChapterInfo>();
}
- long currentChapterTicks = 0;
- var index = 1;
-
// Limit to 100 chapters just in case there's some incorrect metadata here
- while (currentChapterTicks < runtime && index < 100)
+ int chapterCount = (int)Math.Min(runtime / _dummyChapterDuration, 100);
+ var chapters = new ChapterInfo[chapterCount];
+
+ long currentChapterTicks = 0;
+ for (int i = 0; i < chapterCount; i++)
{
- chapters.Add(new ChapterInfo
+ chapters[i] = new ChapterInfo
{
StartPositionTicks = currentChapterTicks
- });
+ };
- index++;
currentChapterTicks += _dummyChapterDuration;
}
+
+ return chapters;
}
private string[] FetchFromDvdLib(Video item)
{
var path = item.Path;
- var dvd = new Dvd(path, _fileSystem);
+ var dvd = new Dvd(path);
var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
@@ -597,7 +631,7 @@ namespace MediaBrowser.Providers.MediaInfo
item.RunTimeTicks = GetRuntime(primaryTitle);
}
- return _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, null, titleNumber)
+ return _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, titleNumber)
.Select(Path.GetFileName)
.ToArray();
}
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
index 77c0e9b4e..b2b93940a 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -25,7 +29,8 @@ namespace MediaBrowser.Providers.MediaInfo
_subtitleManager = subtitleManager;
}
- public async Task<List<string>> DownloadSubtitles(Video video,
+ public async Task<List<string>> DownloadSubtitles(
+ Video video,
List<MediaStream> mediaStreams,
bool skipIfEmbeddedSubtitlesPresent,
bool skipIfAudioTrackMatches,
@@ -33,14 +38,24 @@ namespace MediaBrowser.Providers.MediaInfo
IEnumerable<string> languages,
string[] disabledSubtitleFetchers,
string[] subtitleFetcherOrder,
+ bool isAutomated,
CancellationToken cancellationToken)
{
var downloadedLanguages = new List<string>();
foreach (var lang in languages)
{
- var downloaded = await DownloadSubtitles(video, mediaStreams, skipIfEmbeddedSubtitlesPresent,
- skipIfAudioTrackMatches, requirePerfectMatch, lang, disabledSubtitleFetchers, subtitleFetcherOrder, cancellationToken).ConfigureAwait(false);
+ var downloaded = await DownloadSubtitles(
+ video,
+ mediaStreams,
+ skipIfEmbeddedSubtitlesPresent,
+ skipIfAudioTrackMatches,
+ requirePerfectMatch,
+ lang,
+ disabledSubtitleFetchers,
+ subtitleFetcherOrder,
+ isAutomated,
+ cancellationToken).ConfigureAwait(false);
if (downloaded)
{
@@ -51,7 +66,8 @@ namespace MediaBrowser.Providers.MediaInfo
return downloadedLanguages;
}
- public Task<bool> DownloadSubtitles(Video video,
+ public Task<bool> DownloadSubtitles(
+ Video video,
List<MediaStream> mediaStreams,
bool skipIfEmbeddedSubtitlesPresent,
bool skipIfAudioTrackMatches,
@@ -59,6 +75,7 @@ namespace MediaBrowser.Providers.MediaInfo
string lang,
string[] disabledSubtitleFetchers,
string[] subtitleFetcherOrder,
+ bool isAutomated,
CancellationToken cancellationToken)
{
if (video.VideoType != VideoType.VideoFile)
@@ -87,11 +104,22 @@ namespace MediaBrowser.Providers.MediaInfo
return Task.FromResult(false);
}
- return DownloadSubtitles(video, mediaStreams, skipIfEmbeddedSubtitlesPresent, skipIfAudioTrackMatches,
- requirePerfectMatch, lang, disabledSubtitleFetchers, subtitleFetcherOrder, mediaType, cancellationToken);
+ return DownloadSubtitles(
+ video,
+ mediaStreams,
+ skipIfEmbeddedSubtitlesPresent,
+ skipIfAudioTrackMatches,
+ requirePerfectMatch,
+ lang,
+ disabledSubtitleFetchers,
+ subtitleFetcherOrder,
+ mediaType,
+ isAutomated,
+ cancellationToken);
}
- private async Task<bool> DownloadSubtitles(Video video,
+ private async Task<bool> DownloadSubtitles(
+ Video video,
List<MediaStream> mediaStreams,
bool skipIfEmbeddedSubtitlesPresent,
bool skipIfAudioTrackMatches,
@@ -100,6 +128,7 @@ namespace MediaBrowser.Providers.MediaInfo
string[] disabledSubtitleFetchers,
string[] subtitleFetcherOrder,
VideoContentType mediaType,
+ bool isAutomated,
CancellationToken cancellationToken)
{
// There's already subtitles for this language
@@ -147,12 +176,11 @@ namespace MediaBrowser.Providers.MediaInfo
IsPerfectMatch = requirePerfectMatch,
DisabledSubtitleFetchers = disabledSubtitleFetchers,
- SubtitleFetcherOrder = subtitleFetcherOrder
+ SubtitleFetcherOrder = subtitleFetcherOrder,
+ IsAutomated = isAutomated
};
- var episode = video as Episode;
-
- if (episode != null)
+ if (video is Episode episode)
{
request.IndexNumberEnd = episode.IndexNumberEnd;
request.SeriesName = episode.SeriesName;
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
index cd026b39b..dd4a5f061 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
@@ -1,42 +1,31 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
namespace MediaBrowser.Providers.MediaInfo
{
public class SubtitleResolver
{
private readonly ILocalizationManager _localization;
- private readonly IFileSystem _fileSystem;
- private string[] SubtitleExtensions = new[]
- {
- ".srt",
- ".ssa",
- ".ass",
- ".sub",
- ".smi",
- ".sami",
- ".vtt"
- };
-
- public SubtitleResolver(ILocalizationManager localization, IFileSystem fileSystem)
+ public SubtitleResolver(ILocalizationManager localization)
{
_localization = localization;
- _fileSystem = fileSystem;
}
- public List<MediaStream> GetExternalSubtitleStreams(Video video,
- int startIndex,
- IDirectoryService directoryService,
- bool clearCache)
+ public List<MediaStream> GetExternalSubtitleStreams(
+ Video video,
+ int startIndex,
+ IDirectoryService directoryService,
+ bool clearCache)
{
var streams = new List<MediaStream>();
@@ -49,146 +38,160 @@ namespace MediaBrowser.Providers.MediaInfo
startIndex += streams.Count;
+ string folder = video.GetInternalMetadataPath();
+
+ if (!Directory.Exists(folder))
+ {
+ return streams;
+ }
+
try
{
- AddExternalSubtitleStreams(streams, video.GetInternalMetadataPath(), video.Path, startIndex, directoryService, clearCache);
+ AddExternalSubtitleStreams(streams, folder, video.Path, startIndex, directoryService, clearCache);
}
catch (IOException)
{
-
}
return streams;
}
- public List<string> GetExternalSubtitleFiles(Video video,
- IDirectoryService directoryService,
- bool clearCache)
+ public IEnumerable<string> GetExternalSubtitleFiles(
+ Video video,
+ IDirectoryService directoryService,
+ bool clearCache)
{
- var list = new List<string>();
-
if (!video.IsFileProtocol)
{
- return list;
+ yield break;
}
var streams = GetExternalSubtitleStreams(video, 0, directoryService, clearCache);
foreach (var stream in streams)
{
- list.Add(stream.Path);
+ yield return stream.Path;
}
-
- return list;
}
- private void AddExternalSubtitleStreams(List<MediaStream> streams, string folder,
+ public void AddExternalSubtitleStreams(
+ List<MediaStream> streams,
string videoPath,
int startIndex,
- IDirectoryService directoryService,
- bool clearCache)
+ IReadOnlyList<string> files)
{
- var files = directoryService.GetFilePaths(folder, clearCache).OrderBy(i => i).ToArray();
-
- AddExternalSubtitleStreams(streams, videoPath, startIndex, files);
- }
+ var videoFileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(videoPath);
- public void AddExternalSubtitleStreams(List<MediaStream> streams,
- string videoPath,
- int startIndex,
- string[] files)
- {
- var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(videoPath);
- videoFileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(videoFileNameWithoutExtension);
-
- foreach (var fullName in files)
+ for (var i = 0; i < files.Count; i++)
{
- var extension = Path.GetExtension(fullName);
-
- if (!SubtitleExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
-
- var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
- fileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(fileNameWithoutExtension);
-
- if (!string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase) &&
- !fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
+ var fullName = files[i];
+ var extension = Path.GetExtension(fullName.AsSpan());
+ if (!IsSubtitleExtension(extension))
{
continue;
}
- var codec = Path.GetExtension(fullName).ToLowerInvariant().TrimStart('.');
+ var fileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(fullName);
- if (string.Equals(codec, "txt", StringComparison.OrdinalIgnoreCase))
- {
- codec = "srt";
- }
+ MediaStream mediaStream;
- // If the subtitle file matches the video file name
- if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
+ // The subtitle filename must either be equal to the video filename or start with the video filename followed by a dot
+ if (videoFileNameWithoutExtension.Equals(fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
{
- streams.Add(new MediaStream
+ mediaStream = new MediaStream
{
Index = startIndex++,
Type = MediaStreamType.Subtitle,
IsExternal = true,
- Path = fullName,
- Codec = codec
- });
+ Path = fullName
+ };
}
- else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
+ else if (fileNameWithoutExtension.Length > videoFileNameWithoutExtension.Length
+ && fileNameWithoutExtension[videoFileNameWithoutExtension.Length] == '.'
+ && fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
{
- var isForced = fullName.IndexOf(".forced.", StringComparison.OrdinalIgnoreCase) != -1 ||
- fullName.IndexOf(".foreign.", StringComparison.OrdinalIgnoreCase) != -1;
+ var isForced = fullName.Contains(".forced.", StringComparison.OrdinalIgnoreCase)
+ || fullName.Contains(".foreign.", StringComparison.OrdinalIgnoreCase);
- var isDefault = fullName.IndexOf(".default.", StringComparison.OrdinalIgnoreCase) != -1;
+ var isDefault = fullName.Contains(".default.", StringComparison.OrdinalIgnoreCase);
// Support xbmc naming conventions - 300.spanish.srt
- var language = fileNameWithoutExtension
- .Replace(".forced", string.Empty, StringComparison.OrdinalIgnoreCase)
- .Replace(".foreign", string.Empty, StringComparison.OrdinalIgnoreCase)
- .Replace(".default", string.Empty, StringComparison.OrdinalIgnoreCase)
- .Split('.')
- .LastOrDefault();
+ var languageSpan = fileNameWithoutExtension;
+ while (languageSpan.Length > 0)
+ {
+ var lastDot = languageSpan.LastIndexOf('.');
+ var currentSlice = languageSpan[lastDot..];
+ if (currentSlice.Equals(".default", StringComparison.OrdinalIgnoreCase)
+ || currentSlice.Equals(".forced", StringComparison.OrdinalIgnoreCase)
+ || currentSlice.Equals(".foreign", StringComparison.OrdinalIgnoreCase))
+ {
+ languageSpan = languageSpan[..lastDot];
+ continue;
+ }
+
+ languageSpan = languageSpan[(lastDot + 1)..];
+ break;
+ }
// Try to translate to three character code
// Be flexible and check against both the full and three character versions
+ var language = languageSpan.ToString();
var culture = _localization.FindLanguageInfo(language);
- if (culture != null)
- {
- language = culture.ThreeLetterISOLanguageName;
- }
+ language = culture == null ? language : culture.ThreeLetterISOLanguageName;
- streams.Add(new MediaStream
+ mediaStream = new MediaStream
{
Index = startIndex++,
Type = MediaStreamType.Subtitle,
IsExternal = true,
Path = fullName,
- Codec = codec,
Language = language,
IsForced = isForced,
IsDefault = isDefault
- });
+ };
+ }
+ else
+ {
+ continue;
}
+
+ mediaStream.Codec = extension.TrimStart('.').ToString().ToLowerInvariant();
+
+ streams.Add(mediaStream);
}
}
- private string NormalizeFilenameForSubtitleComparison(string filename)
+ private static bool IsSubtitleExtension(ReadOnlySpan<char> extension)
{
- // Try to account for sloppy file naming
- filename = filename.Replace("_", string.Empty);
- filename = filename.Replace(" ", string.Empty);
+ return extension.Equals(".srt", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".ssa", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".ass", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".sub", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".vtt", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".smi", StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(".sami", StringComparison.OrdinalIgnoreCase);
+ }
- // can't normalize this due to languages such as pt-br
- //filename = filename.Replace("-", string.Empty);
+ private static ReadOnlySpan<char> NormalizeFilenameForSubtitleComparison(string filename)
+ {
+ // Try to account for sloppy file naming
+ filename = filename.Replace("_", string.Empty, StringComparison.Ordinal);
+ filename = filename.Replace(" ", string.Empty, StringComparison.Ordinal);
+ return Path.GetFileNameWithoutExtension(filename.AsSpan());
+ }
- //filename = filename.Replace(".", string.Empty);
+ private void AddExternalSubtitleStreams(
+ List<MediaStream> streams,
+ string folder,
+ string videoPath,
+ int startIndex,
+ IDirectoryService directoryService,
+ bool clearCache)
+ {
+ var files = directoryService.GetFilePaths(folder, clearCache, true);
- return filename;
+ AddExternalSubtitleStreams(streams, videoPath, startIndex, files);
}
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
index 74f41f9df..1eacbf1e1 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,8 +14,8 @@ 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.Serialization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@@ -22,20 +26,37 @@ namespace MediaBrowser.Providers.MediaInfo
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _config;
private readonly ISubtitleManager _subtitleManager;
- private readonly IMediaSourceManager _mediaSourceManager;
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
-
- public SubtitleScheduledTask(ILibraryManager libraryManager, IJsonSerializer json, IServerConfigurationManager config, ISubtitleManager subtitleManager, ILogger logger, IMediaSourceManager mediaSourceManager)
+ private readonly ILogger<SubtitleScheduledTask> _logger;
+ private readonly ILocalizationManager _localization;
+
+ public SubtitleScheduledTask(
+ ILibraryManager libraryManager,
+ IServerConfigurationManager config,
+ ISubtitleManager subtitleManager,
+ ILogger<SubtitleScheduledTask> logger,
+ ILocalizationManager localization)
{
_libraryManager = libraryManager;
_config = config;
_subtitleManager = subtitleManager;
_logger = logger;
- _mediaSourceManager = mediaSourceManager;
- _json = json;
+ _localization = localization;
}
+ public string Name => _localization.GetLocalizedString("TaskDownloadMissingSubtitles");
+
+ public string Description => _localization.GetLocalizedString("TaskDownloadMissingSubtitlesDescription");
+
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+
+ public string Key => "DownloadSubtitles";
+
+ public bool IsHidden => false;
+
+ public bool IsEnabled => true;
+
+ public bool IsLogged => true;
+
private SubtitleOptions GetOptions()
{
return _config.GetConfiguration<SubtitleOptions>("subtitles");
@@ -54,23 +75,23 @@ namespace MediaBrowser.Providers.MediaInfo
var libraryOptions = _libraryManager.GetLibraryOptions(library);
string[] subtitleDownloadLanguages;
- bool SkipIfEmbeddedSubtitlesPresent;
- bool SkipIfAudioTrackMatches;
- bool RequirePerfectMatch;
+ bool skipIfEmbeddedSubtitlesPresent;
+ bool skipIfAudioTrackMatches;
+ bool requirePerfectMatch;
if (libraryOptions.SubtitleDownloadLanguages == null)
{
subtitleDownloadLanguages = options.DownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = options.SkipIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = options.SkipIfAudioTrackMatches;
- RequirePerfectMatch = options.RequirePerfectMatch;
+ skipIfEmbeddedSubtitlesPresent = options.SkipIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = options.SkipIfAudioTrackMatches;
+ requirePerfectMatch = options.RequirePerfectMatch;
}
else
{
subtitleDownloadLanguages = libraryOptions.SubtitleDownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
- RequirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
+ skipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
+ requirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
}
foreach (var lang in subtitleDownloadLanguages)
@@ -86,12 +107,12 @@ namespace MediaBrowser.Providers.MediaInfo
Recursive = true
};
- if (SkipIfAudioTrackMatches)
+ if (skipIfAudioTrackMatches)
{
query.HasNoAudioTrackWithLanguage = lang;
}
- if (SkipIfEmbeddedSubtitlesPresent)
+ if (skipIfEmbeddedSubtitlesPresent)
{
// Exclude if it already has any subtitles of the same language
query.HasNoSubtitleTrackWithLanguage = lang;
@@ -148,36 +169,38 @@ namespace MediaBrowser.Providers.MediaInfo
var libraryOptions = _libraryManager.GetLibraryOptions(video);
string[] subtitleDownloadLanguages;
- bool SkipIfEmbeddedSubtitlesPresent;
- bool SkipIfAudioTrackMatches;
- bool RequirePerfectMatch;
+ bool skipIfEmbeddedSubtitlesPresent;
+ bool skipIfAudioTrackMatches;
+ bool requirePerfectMatch;
if (libraryOptions.SubtitleDownloadLanguages == null)
{
subtitleDownloadLanguages = options.DownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = options.SkipIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = options.SkipIfAudioTrackMatches;
- RequirePerfectMatch = options.RequirePerfectMatch;
+ skipIfEmbeddedSubtitlesPresent = options.SkipIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = options.SkipIfAudioTrackMatches;
+ requirePerfectMatch = options.RequirePerfectMatch;
}
else
{
subtitleDownloadLanguages = libraryOptions.SubtitleDownloadLanguages;
- SkipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
- SkipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
- RequirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
+ skipIfEmbeddedSubtitlesPresent = libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent;
+ skipIfAudioTrackMatches = libraryOptions.SkipSubtitlesIfAudioTrackMatches;
+ requirePerfectMatch = libraryOptions.RequirePerfectSubtitleMatch;
}
- var downloadedLanguages = await new SubtitleDownloader(_logger,
- _subtitleManager)
- .DownloadSubtitles(video,
- mediaStreams,
- SkipIfEmbeddedSubtitlesPresent,
- SkipIfAudioTrackMatches,
- RequirePerfectMatch,
- subtitleDownloadLanguages,
- libraryOptions.DisabledSubtitleFetchers,
- libraryOptions.SubtitleFetcherOrder,
- cancellationToken).ConfigureAwait(false);
+ var downloadedLanguages = await new SubtitleDownloader(
+ _logger,
+ _subtitleManager).DownloadSubtitles(
+ video,
+ mediaStreams,
+ skipIfEmbeddedSubtitlesPresent,
+ skipIfAudioTrackMatches,
+ requirePerfectMatch,
+ subtitleDownloadLanguages,
+ libraryOptions.DisabledSubtitleFetchers,
+ libraryOptions.SubtitleFetcherOrder,
+ true,
+ cancellationToken).ConfigureAwait(false);
// Rescan
if (downloadedLanguages.Count > 0)
@@ -191,25 +214,11 @@ namespace MediaBrowser.Providers.MediaInfo
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[] {
-
+ return new[]
+ {
// Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
};
}
-
- public string Name => "Download missing subtitles";
-
- public string Description => "Searches the internet for missing subtitles based on metadata configuration.";
-
- public string Category => "Library";
-
- public string Key => "DownloadSubtitles";
-
- public bool IsHidden => false;
-
- public bool IsEnabled => true;
-
- public bool IsLogged => true;
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
index d80084acf..d226182c0 100644
--- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
@@ -7,43 +7,52 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.MediaInfo
{
+ /// <summary>
+ /// Uses <see cref="IMediaEncoder"/> to create still images from the main video.
+ /// </summary>
public class VideoImageProvider : IDynamicImageProvider, IHasOrder
{
private readonly IMediaEncoder _mediaEncoder;
- private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
-
- public VideoImageProvider(IMediaEncoder mediaEncoder, ILogger logger, IFileSystem fileSystem)
+ private readonly ILogger<VideoImageProvider> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideoImageProvider"/> class.
+ /// </summary>
+ /// <param name="mediaEncoder">The media encoder for capturing images.</param>
+ /// <param name="logger">The logger.</param>
+ public VideoImageProvider(IMediaEncoder mediaEncoder, ILogger<VideoImageProvider> logger)
{
_mediaEncoder = mediaEncoder;
_logger = logger;
- _fileSystem = fileSystem;
}
+ /// <inheritdoc />
+ public string Name => "Screen Grabber";
+
+ /// <inheritdoc />
+ // Make sure this comes after internet image providers
+ public int Order => 100;
+
+ /// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
- return new List<ImageType> { ImageType.Primary };
+ return new[] { ImageType.Primary };
}
+ /// <inheritdoc />
public Task<DynamicImageResponse> GetImage(BaseItem item, ImageType type, CancellationToken cancellationToken)
{
var video = (Video)item;
- // No support for this
- if (video.IsPlaceHolder)
- {
- return Task.FromResult(new DynamicImageResponse { HasImage = false });
- }
-
- // No support for this
- if (video.VideoType == VideoType.Iso || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay)
+ // No support for these
+ if (video.IsPlaceHolder || video.VideoType == VideoType.Dvd)
{
return Task.FromResult(new DynamicImageResponse { HasImage = false });
}
@@ -51,65 +60,38 @@ namespace MediaBrowser.Providers.MediaInfo
// Can't extract if we didn't find a video stream in the file
if (!video.DefaultVideoStreamIndex.HasValue)
{
- _logger.LogInformation("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty);
+ _logger.LogInformation("Skipping image extraction due to missing DefaultVideoStreamIndex for {Path}.", video.Path ?? string.Empty);
return Task.FromResult(new DynamicImageResponse { HasImage = false });
}
return GetVideoImage(video, cancellationToken);
}
- public async Task<DynamicImageResponse> GetVideoImage(Video item, CancellationToken cancellationToken)
+ private async Task<DynamicImageResponse> GetVideoImage(Video item, CancellationToken cancellationToken)
{
- var protocol = item.PathProtocol ?? MediaProtocol.File;
-
- var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, item.Path, protocol, null, item.GetPlayableStreamFileNames(_mediaEncoder));
-
- var mediaStreams =
- item.GetMediaStreams();
-
- var imageStreams =
- mediaStreams
- .Where(i => i.Type == MediaStreamType.EmbeddedImage)
- .ToList();
+ MediaSourceInfo mediaSource = new MediaSourceInfo
+ {
+ VideoType = item.VideoType,
+ IsoType = item.IsoType,
+ Protocol = item.PathProtocol ?? MediaProtocol.File,
+ };
- var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ??
- imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ??
- imageStreams.FirstOrDefault();
+ // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
+ // Always use 10 seconds for dvd because our duration could be out of whack
+ var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue &&
+ item.RunTimeTicks.Value > 0
+ ? TimeSpan.FromTicks(item.RunTimeTicks.Value / 10)
+ : TimeSpan.FromSeconds(10);
- string extractedImagePath;
+ var videoStream = item.GetDefaultVideoStream() ?? item.GetMediaStreams().FirstOrDefault(i => i.Type == MediaStreamType.Video);
- if (imageStream != null)
+ if (videoStream == null)
{
- // Instead of using the raw stream index, we need to use nth video/embedded image stream
- var videoIndex = -1;
- foreach (var mediaStream in mediaStreams)
- {
- if (mediaStream.Type == MediaStreamType.Video ||
- mediaStream.Type == MediaStreamType.EmbeddedImage)
- {
- videoIndex++;
- }
- if (mediaStream == imageStream)
- {
- break;
- }
- }
-
- extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, imageStream, videoIndex, cancellationToken).ConfigureAwait(false);
+ _logger.LogInformation("Skipping image extraction: no video stream found for {Path}.", item.Path ?? string.Empty);
+ return new DynamicImageResponse { HasImage = false };
}
- else
- {
- // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
- // Always use 10 seconds for dvd because our duration could be out of whack
- var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue &&
- item.RunTimeTicks.Value > 0
- ? TimeSpan.FromTicks(Convert.ToInt64(item.RunTimeTicks.Value * .1))
- : TimeSpan.FromSeconds(10);
- var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
-
- extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, videoStream, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
- }
+ string extractedImagePath = await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, videoStream, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
return new DynamicImageResponse
{
@@ -120,29 +102,20 @@ namespace MediaBrowser.Providers.MediaInfo
};
}
- public string Name => "Screen Grabber";
-
+ /// <inheritdoc />
public bool Supports(BaseItem item)
{
if (item.IsShortcut)
{
return false;
}
+
if (!item.IsFileProtocol)
{
return false;
}
- var video = item as Video;
-
- if (video != null && !video.IsPlaceHolder && video.IsCompleteMedia)
- {
- return true;
- }
-
- return false;
+ return item is Video video && !video.IsPlaceHolder && video.IsCompleteMedia;
}
- // Make sure this comes after internet image providers
- public int Order => 100;
}
}
diff --git a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs b/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs
deleted file mode 100644
index 70d187bf5..000000000
--- a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs
+++ /dev/null
@@ -1,334 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Music;
-using MediaBrowser.Providers.TV;
-using MediaBrowser.Providers.TV.FanArt;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class FanartMovieImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _json;
-
- private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3/movies/{1}?api_key={0}";
-
- internal static FanartMovieImageProvider Current;
-
- public FanartMovieImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
- {
- _config = config;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _json = json;
-
- Current = this;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "FanArt";
-
- public bool Supports(BaseItem item)
- {
- return item is Movie || item is BoxSet || item is MusicVideo;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Thumb,
- ImageType.Art,
- ImageType.Logo,
- ImageType.Disc,
- ImageType.Banner,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var baseItem = item;
- var list = new List<RemoteImageInfo>();
-
- var movieId = baseItem.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(movieId))
- {
- // Bad id entered
- try
- {
- await EnsureMovieJson(movieId, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
- {
- throw;
- }
- }
-
- var path = GetFanartJsonPath(movieId);
-
- try
- {
- AddImages(list, path, cancellationToken);
- }
- catch (FileNotFoundException)
- {
- // No biggie. Don't blow up
- }
- catch (IOException)
- {
- // No biggie. Don't blow up
- }
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- // Sort first by width to prioritize HD versions
- return list.OrderByDescending(i => i.Width ?? 0)
- .ThenByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0);
- }
-
- private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
- {
- var root = _json.DeserializeFromFile<RootObject>(path);
-
- AddImages(list, root, cancellationToken);
- }
-
- private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
- {
- PopulateImages(list, obj.hdmovieclearart, ImageType.Art, 1000, 562);
- PopulateImages(list, obj.hdmovielogo, ImageType.Logo, 800, 310);
- PopulateImages(list, obj.moviedisc, ImageType.Disc, 1000, 1000);
- PopulateImages(list, obj.movieposter, ImageType.Primary, 1000, 1426);
- PopulateImages(list, obj.movielogo, ImageType.Logo, 400, 155);
- PopulateImages(list, obj.movieart, ImageType.Art, 500, 281);
- PopulateImages(list, obj.moviethumb, ImageType.Thumb, 1000, 562);
- PopulateImages(list, obj.moviebanner, ImageType.Banner, 1000, 185);
- PopulateImages(list, obj.moviebackground, ImageType.Backdrop, 1920, 1080);
- }
-
- private void PopulateImages(List<RemoteImageInfo> list, List<Image> images, ImageType type, int width, int height)
- {
- if (images == null)
- {
- return;
- }
-
- list.AddRange(images.Select(i =>
- {
- var url = i.url;
-
- if (!string.IsNullOrEmpty(url))
- {
- var likesString = i.likes;
-
- var info = new RemoteImageInfo
- {
- RatingType = RatingType.Likes,
- Type = type,
- Width = width,
- Height = height,
- ProviderName = Name,
- Url = url,
- Language = i.lang
- };
-
- if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
- {
- info.CommunityRating = likes;
- }
-
- return info;
- }
-
- return null;
- }).Where(i => i != null));
- }
-
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- /// <summary>
- /// Gets the movie data path.
- /// </summary>
- /// <param name="appPaths">The application paths.</param>
- /// <param name="id">The identifier.</param>
- /// <returns>System.String.</returns>
- internal static string GetMovieDataPath(IApplicationPaths appPaths, string id)
- {
- var dataPath = Path.Combine(GetMoviesDataPath(appPaths), id);
-
- return dataPath;
- }
-
- /// <summary>
- /// Gets the movie data path.
- /// </summary>
- /// <param name="appPaths">The app paths.</param>
- /// <returns>System.String.</returns>
- internal static string GetMoviesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "fanart-movies");
-
- return dataPath;
- }
-
- public string GetFanartJsonPath(string id)
- {
- var movieDataPath = GetMovieDataPath(_config.ApplicationPaths, id);
- return Path.Combine(movieDataPath, "fanart.json");
- }
-
- /// <summary>
- /// Downloads the movie json.
- /// </summary>
- /// <param name="id">The identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- internal async Task DownloadMovieJson(string id, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, id);
-
- var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
- if (!string.IsNullOrWhiteSpace(clientKey))
- {
- url += "&client_key=" + clientKey;
- }
-
- var path = GetFanartJsonPath(id);
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- try
- {
- using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = true
-
- }, "GET").ConfigureAwait(false))
- {
- using (var response = httpResponse.Content)
- {
- using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await response.CopyToAsync(fileStream).ConfigureAwait(false);
- }
- }
- }
- }
- catch (HttpException exception)
- {
- if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
- {
- // If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
- _json.SerializeToFile(new RootObject(), path);
-
- return;
- }
-
- throw;
- }
- }
-
- internal Task EnsureMovieJson(string id, CancellationToken cancellationToken)
- {
- var path = GetFanartJsonPath(id);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadMovieJson(id, cancellationToken);
- }
-
- public class Image
- {
- public string id { get; set; }
- public string url { get; set; }
- public string lang { get; set; }
- public string likes { get; set; }
- }
-
- public class RootObject
- {
- public string name { get; set; }
- public string tmdb_id { get; set; }
- public string imdb_id { get; set; }
- public List<Image> hdmovielogo { get; set; }
- public List<Image> moviedisc { get; set; }
- public List<Image> movielogo { get; set; }
- public List<Image> movieposter { get; set; }
- public List<Image> hdmovieclearart { get; set; }
- public List<Image> movieart { get; set; }
- public List<Image> moviebackground { get; set; }
- public List<Image> moviebanner { get; set; }
- public List<Image> moviethumb { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
deleted file mode 100644
index 4300b84a9..000000000
--- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
+++ /dev/null
@@ -1,315 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class GenericMovieDbInfo<T>
- where T : BaseItem, new()
- {
- private readonly ILogger _logger;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly ILibraryManager _libraryManager;
- private readonly IFileSystem _fileSystem;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public GenericMovieDbInfo(ILogger logger, IJsonSerializer jsonSerializer, ILibraryManager libraryManager, IFileSystem fileSystem)
- {
- _logger = logger;
- _jsonSerializer = jsonSerializer;
- _libraryManager = libraryManager;
- _fileSystem = fileSystem;
- }
-
- public async Task<MetadataResult<T>> GetMetadata(ItemLookupInfo itemId, CancellationToken cancellationToken)
- {
- var tmdbId = itemId.GetProviderId(MetadataProviders.Tmdb);
- var imdbId = itemId.GetProviderId(MetadataProviders.Imdb);
-
- // Don't search for music video id's because it is very easy to misidentify.
- if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId) && typeof(T) != typeof(MusicVideo))
- {
- var searchResults = await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetMovieSearchResults(itemId, cancellationToken).ConfigureAwait(false);
-
- var searchResult = searchResults.FirstOrDefault();
-
- if (searchResult != null)
- {
- tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
- }
- }
-
- if (!string.IsNullOrEmpty(tmdbId) || !string.IsNullOrEmpty(imdbId))
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- return await FetchMovieData(tmdbId, imdbId, itemId.MetadataLanguage, itemId.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
- }
-
- return new MetadataResult<T>();
- }
-
- /// <summary>
- /// Fetches the movie data.
- /// </summary>
- /// <param name="tmdbId">The TMDB identifier.</param>
- /// <param name="imdbId">The imdb identifier.</param>
- /// <param name="language">The language.</param>
- /// <param name="preferredCountryCode">The preferred country code.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{`0}.</returns>
- private async Task<MetadataResult<T>> FetchMovieData(string tmdbId, string imdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
- {
- var item = new MetadataResult<T>
- {
- Item = new T()
- };
-
- string dataFilePath = null;
- MovieDbProvider.CompleteMovieData movieInfo = null;
-
- // Id could be ImdbId or TmdbId
- if (string.IsNullOrEmpty(tmdbId))
- {
- movieInfo = await MovieDbProvider.Current.FetchMainResult(imdbId, false, language, cancellationToken).ConfigureAwait(false);
- if (movieInfo != null)
- {
- tmdbId = movieInfo.id.ToString(_usCulture);
-
- dataFilePath = MovieDbProvider.Current.GetDataFilePath(tmdbId, language);
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(movieInfo, dataFilePath);
- }
- }
-
- if (!string.IsNullOrWhiteSpace(tmdbId))
- {
- await MovieDbProvider.Current.EnsureMovieInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- dataFilePath = dataFilePath ?? MovieDbProvider.Current.GetDataFilePath(tmdbId, language);
- movieInfo = movieInfo ?? _jsonSerializer.DeserializeFromFile<MovieDbProvider.CompleteMovieData>(dataFilePath);
-
- var settings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- ProcessMainInfo(item, settings, preferredCountryCode, movieInfo);
- item.HasMetadata = true;
- }
-
- return item;
- }
-
- /// <summary>
- /// Processes the main info.
- /// </summary>
- /// <param name="resultItem">The result item.</param>
- /// <param name="settings">The settings.</param>
- /// <param name="preferredCountryCode">The preferred country code.</param>
- /// <param name="movieData">The movie data.</param>
- private void ProcessMainInfo(MetadataResult<T> resultItem, TmdbSettingsResult settings, string preferredCountryCode, MovieDbProvider.CompleteMovieData movieData)
- {
- var movie = resultItem.Item;
-
- movie.Name = movieData.GetTitle() ?? movie.Name;
-
- movie.OriginalTitle = movieData.GetOriginalTitle();
-
- movie.Overview = string.IsNullOrWhiteSpace(movieData.overview) ? null : WebUtility.HtmlDecode(movieData.overview);
- movie.Overview = movie.Overview != null ? movie.Overview.Replace("\n\n", "\n") : null;
-
- //movie.HomePageUrl = movieData.homepage;
-
- if (!string.IsNullOrEmpty(movieData.tagline))
- {
- movie.Tagline = movieData.tagline;
- }
-
- if (movieData.production_countries != null)
- {
- movie.ProductionLocations = movieData
- .production_countries
- .Select(i => i.name)
- .ToArray();
- }
-
- movie.SetProviderId(MetadataProviders.Tmdb, movieData.id.ToString(_usCulture));
- movie.SetProviderId(MetadataProviders.Imdb, movieData.imdb_id);
-
- if (movieData.belongs_to_collection != null)
- {
- movie.SetProviderId(MetadataProviders.TmdbCollection,
- movieData.belongs_to_collection.id.ToString(CultureInfo.InvariantCulture));
-
- var movieItem = movie as Movie;
-
- if (movieItem != null)
- {
- movieItem.CollectionName = movieData.belongs_to_collection.name;
- }
- }
-
- string voteAvg = movieData.vote_average.ToString(CultureInfo.InvariantCulture);
-
- if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rating))
- {
- movie.CommunityRating = rating;
- }
-
- //movie.VoteCount = movieData.vote_count;
-
- if (movieData.releases != null && movieData.releases.countries != null)
- {
- var releases = movieData.releases.countries.Where(i => !string.IsNullOrWhiteSpace(i.certification)).ToList();
-
- var ourRelease = releases.FirstOrDefault(c => string.Equals(c.iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
- var usRelease = releases.FirstOrDefault(c => string.Equals(c.iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
-
- if (ourRelease != null)
- {
- var ratingPrefix = string.Equals(preferredCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? "" : preferredCountryCode + "-";
- var newRating = ratingPrefix + ourRelease.certification;
-
- newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);
-
- movie.OfficialRating = newRating;
- }
- else if (usRelease != null)
- {
- movie.OfficialRating = usRelease.certification;
- }
- }
-
- if (!string.IsNullOrWhiteSpace(movieData.release_date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParse(movieData.release_date, _usCulture, DateTimeStyles.None, out var r))
- {
- movie.PremiereDate = r.ToUniversalTime();
- movie.ProductionYear = movie.PremiereDate.Value.Year;
- }
- }
-
- //studios
- if (movieData.production_companies != null)
- {
- movie.SetStudios(movieData.production_companies.Select(c => c.name));
- }
-
- // genres
- // Movies get this from imdb
- var genres = movieData.genres ?? new List<MovieDbProvider.GenreItem>();
-
- foreach (var genre in genres.Select(g => g.name))
- {
- movie.AddGenre(genre);
- }
-
- resultItem.ResetPeople();
- var tmdbImageUrl = settings.images.GetImageUrl("original");
-
- //Actors, Directors, Writers - all in People
- //actors come from cast
- if (movieData.casts != null && movieData.casts.cast != null)
- {
- foreach (var actor in movieData.casts.cast.OrderBy(a => a.order))
- {
- var personInfo = new PersonInfo
- {
- Name = actor.name.Trim(),
- Role = actor.character,
- Type = PersonType.Actor,
- SortOrder = actor.order
- };
-
- if (!string.IsNullOrWhiteSpace(actor.profile_path))
- {
- personInfo.ImageUrl = tmdbImageUrl + actor.profile_path;
- }
-
- if (actor.id > 0)
- {
- personInfo.SetProviderId(MetadataProviders.Tmdb, actor.id.ToString(CultureInfo.InvariantCulture));
- }
-
- resultItem.AddPerson(personInfo);
- }
- }
-
- //and the rest from crew
- if (movieData.casts != null && movieData.casts.crew != null)
- {
- var keepTypes = new[]
- {
- PersonType.Director,
- //PersonType.Writer,
- //PersonType.Producer
- };
-
- foreach (var person in movieData.casts.crew)
- {
- // Normalize this
- var type = person.department;
- if (string.Equals(type, "writing", StringComparison.OrdinalIgnoreCase))
- {
- type = PersonType.Writer;
- }
-
- if (!keepTypes.Contains(type ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
- !keepTypes.Contains(person.job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
-
- var personInfo = new PersonInfo
- {
- Name = person.name.Trim(),
- Role = person.job,
- Type = type
- };
-
- if (!string.IsNullOrWhiteSpace(person.profile_path))
- {
- personInfo.ImageUrl = tmdbImageUrl + person.profile_path;
- }
-
- if (person.id > 0)
- {
- personInfo.SetProviderId(MetadataProviders.Tmdb, person.id.ToString(CultureInfo.InvariantCulture));
- }
-
- resultItem.AddPerson(personInfo);
- }
- }
-
- //if (movieData.keywords != null && movieData.keywords.keywords != null)
- //{
- // movie.Keywords = movieData.keywords.keywords.Select(i => i.name).ToList();
- //}
-
- if (movieData.trailers != null && movieData.trailers.youtube != null)
- {
- movie.RemoteTrailers = movieData.trailers.youtube.Select(i => new MediaUrl
- {
- Url = string.Format("https://www.youtube.com/watch?v={0}", i.source),
- Name = i.name
-
- }).ToArray();
- }
- }
-
- }
-}
diff --git a/MediaBrowser.Providers/Movies/ImdbExternalId.cs b/MediaBrowser.Providers/Movies/ImdbExternalId.cs
new file mode 100644
index 000000000..d00f37db5
--- /dev/null
+++ b/MediaBrowser.Providers/Movies/ImdbExternalId.cs
@@ -0,0 +1,39 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Movies
+{
+ public class ImdbExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "IMDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Imdb.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => null;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.imdb.com/title/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ {
+ // Supports images for tv movies
+ if (item is LiveTvProgram tvProgram && tvProgram.IsMovie)
+ {
+ return true;
+ }
+
+ return item is Movie || item is MusicVideo || item is Series || item is Episode || item is Trailer;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Movies/ImdbPersonExternalId.cs b/MediaBrowser.Providers/Movies/ImdbPersonExternalId.cs
new file mode 100644
index 000000000..1bb5e1ea8
--- /dev/null
+++ b/MediaBrowser.Providers/Movies/ImdbPersonExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Movies
+{
+ public class ImdbPersonExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "IMDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Imdb.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Person;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.imdb.com/name/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Person;
+ }
+}
diff --git a/MediaBrowser.Providers/Movies/MovieDbImageProvider.cs b/MediaBrowser.Providers/Movies/MovieDbImageProvider.cs
deleted file mode 100644
index 20b53d58a..000000000
--- a/MediaBrowser.Providers/Movies/MovieDbImageProvider.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class MovieDbImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
-
- public MovieDbImageProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem)
- {
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheMovieDb";
-
- public bool Supports(BaseItem item)
- {
- return item is Movie || item is MusicVideo || item is Trailer;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var list = new List<RemoteImageInfo>();
-
- var language = item.GetPreferredMetadataLanguage();
-
- var results = await FetchImages(item, null, _jsonSerializer, cancellationToken).ConfigureAwait(false);
-
- if (results == null)
- {
- return list;
- }
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var supportedImages = GetSupportedImages(item).ToList();
-
- if (supportedImages.Contains(ImageType.Primary))
- {
- list.AddRange(GetPosters(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- Language = MovieDbProvider.AdjustImageLanguage(i.iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
- }
-
- if (supportedImages.Contains(ImageType.Backdrop))
- {
- list.AddRange(GetBackdrops(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- ProviderName = Name,
- Type = ImageType.Backdrop,
- RatingType = RatingType.Score
- }));
- }
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- /// <summary>
- /// Gets the posters.
- /// </summary>
- /// <param name="images">The images.</param>
- /// <returns>IEnumerable{MovieDbProvider.Poster}.</returns>
- private IEnumerable<MovieDbProvider.Poster> GetPosters(MovieDbProvider.Images images)
- {
- return images.posters ?? new List<MovieDbProvider.Poster>();
- }
-
- /// <summary>
- /// Gets the backdrops.
- /// </summary>
- /// <param name="images">The images.</param>
- /// <returns>IEnumerable{MovieDbProvider.Backdrop}.</returns>
- private IEnumerable<MovieDbProvider.Backdrop> GetBackdrops(MovieDbProvider.Images images)
- {
- var eligibleBackdrops = images.backdrops == null ? new List<MovieDbProvider.Backdrop>() :
- images.backdrops;
-
- return eligibleBackdrops.OrderByDescending(i => i.vote_average)
- .ThenByDescending(i => i.vote_count);
- }
-
- /// <summary>
- /// Fetches the images.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="language">The language.</param>
- /// <param name="jsonSerializer">The json serializer.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{MovieImages}.</returns>
- private async Task<MovieDbProvider.Images> FetchImages(BaseItem item, string language, IJsonSerializer jsonSerializer, CancellationToken cancellationToken)
- {
- var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);
-
- if (string.IsNullOrWhiteSpace(tmdbId))
- {
- var imdbId = item.GetProviderId(MetadataProviders.Imdb);
- if (!string.IsNullOrWhiteSpace(imdbId))
- {
- var movieInfo = await MovieDbProvider.Current.FetchMainResult(imdbId, false, language, cancellationToken).ConfigureAwait(false);
- if (movieInfo != null)
- {
- tmdbId = movieInfo.id.ToString(CultureInfo.InvariantCulture);
- }
- }
- }
-
- if (string.IsNullOrWhiteSpace(tmdbId))
- {
- return null;
- }
-
- await MovieDbProvider.Current.EnsureMovieInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var path = MovieDbProvider.Current.GetDataFilePath(tmdbId, language);
-
- if (!string.IsNullOrEmpty(path))
- {
- var fileInfo = _fileSystem.GetFileInfo(path);
-
- if (fileInfo.Exists)
- {
- return jsonSerializer.DeserializeFromFile<MovieDbProvider.CompleteMovieData>(path).images;
- }
- }
-
- return null;
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs
deleted file mode 100644
index 3ff63a4bf..000000000
--- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs
+++ /dev/null
@@ -1,642 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Movies
-{
- /// <summary>
- /// Class MovieDbProvider
- /// </summary>
- public class MovieDbProvider : IRemoteMetadataProvider<Movie, MovieInfo>, IHasOrder
- {
- internal static MovieDbProvider Current { get; private set; }
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly ILogger _logger;
- private readonly ILocalizationManager _localization;
- private readonly ILibraryManager _libraryManager;
- private readonly IApplicationHost _appHost;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public MovieDbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILogger logger, ILocalizationManager localization, ILibraryManager libraryManager, IApplicationHost appHost)
- {
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _logger = logger;
- _localization = localization;
- _libraryManager = libraryManager;
- _appHost = appHost;
- Current = this;
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
- {
- return GetMovieSearchResults(searchInfo, cancellationToken);
- }
-
- public async Task<IEnumerable<RemoteSearchResult>> GetMovieSearchResults(ItemLookupInfo searchInfo, CancellationToken cancellationToken)
- {
- var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- await EnsureMovieInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);
-
- var obj = _jsonSerializer.DeserializeFromFile<CompleteMovieData>(dataFilePath);
-
- var tmdbSettings = await GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var remoteResult = new RemoteSearchResult
- {
- Name = obj.GetTitle(),
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(obj.poster_path) ? null : tmdbImageUrl + obj.poster_path
- };
-
- if (!string.IsNullOrWhiteSpace(obj.release_date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParse(obj.release_date, _usCulture, DateTimeStyles.None, out var r))
- {
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
- }
- }
-
- remoteResult.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
-
- if (!string.IsNullOrWhiteSpace(obj.imdb_id))
- {
- remoteResult.SetProviderId(MetadataProviders.Imdb, obj.imdb_id);
- }
-
- return new[] { remoteResult };
- }
-
- return await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetMovieSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
- }
-
- public Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
- {
- return GetItemMetadata<Movie>(info, cancellationToken);
- }
-
- public Task<MetadataResult<T>> GetItemMetadata<T>(ItemLookupInfo id, CancellationToken cancellationToken)
- where T : BaseItem, new()
- {
- var movieDb = new GenericMovieDbInfo<T>(_logger, _jsonSerializer, _libraryManager, _fileSystem);
-
- return movieDb.GetMetadata(id, cancellationToken);
- }
-
- public string Name => "TheMovieDb";
-
- /// <summary>
- /// The _TMDB settings task
- /// </summary>
- private TmdbSettingsResult _tmdbSettings;
-
- /// <summary>
- /// Gets the TMDB settings.
- /// </summary>
- /// <returns>Task{TmdbSettingsResult}.</returns>
- internal async Task<TmdbSettingsResult> GetTmdbSettings(CancellationToken cancellationToken)
- {
- if (_tmdbSettings != null)
- {
- return _tmdbSettings;
- }
-
- using (HttpResponseInfo response = await GetMovieDbResponse(new HttpRequestOptions
- {
- Url = string.Format(TmdbConfigUrl, ApiKey),
- CancellationToken = cancellationToken,
- AcceptHeader = AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (Stream json = response.Content)
- {
- _tmdbSettings = await _jsonSerializer.DeserializeFromStreamAsync<TmdbSettingsResult>(json).ConfigureAwait(false);
-
- return _tmdbSettings;
- }
- }
- }
-
- public const string BaseMovieDbUrl = "https://api.themoviedb.org/";
-
- private const string TmdbConfigUrl = BaseMovieDbUrl + "3/configuration?api_key={0}";
- private const string GetMovieInfo3 = BaseMovieDbUrl + @"3/movie/{0}?api_key={1}&append_to_response=casts,releases,images,keywords,trailers";
-
- internal static string ApiKey = "4219e299c89411838049ab0dab19ebd5";
- internal static string AcceptHeader = "application/json,image/*";
-
- /// <summary>
- /// Gets the movie data path.
- /// </summary>
- /// <param name="appPaths">The app paths.</param>
- /// <param name="tmdbId">The TMDB id.</param>
- /// <returns>System.String.</returns>
- internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetMoviesDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- internal static string GetMoviesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-movies2");
-
- return dataPath;
- }
-
- /// <summary>
- /// Downloads the movie info.
- /// </summary>
- /// <param name="id">The id.</param>
- /// <param name="preferredMetadataLanguage">The preferred metadata language.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- internal async Task DownloadMovieInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(id, true, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null) return;
-
- var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal Task EnsureMovieInfo(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetDataFilePath(tmdbId, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadMovieInfo(tmdbId, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetMovieDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- if (string.IsNullOrWhiteSpace(preferredLanguage))
- {
- preferredLanguage = "alllang";
- }
-
- var filename = string.Format("all-{0}.json", preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- public static string GetImageLanguagesParam(string preferredLanguage)
- {
- var languages = new List<string>();
-
- if (!string.IsNullOrEmpty(preferredLanguage))
- {
- preferredLanguage = NormalizeLanguage(preferredLanguage);
-
- languages.Add(preferredLanguage);
-
- if (preferredLanguage.Length == 5) // like en-US
- {
- // Currenty, TMDB supports 2-letter language codes only
- // They are planning to change this in the future, thus we're
- // supplying both codes if we're having a 5-letter code.
- languages.Add(preferredLanguage.Substring(0, 2));
- }
- }
-
- languages.Add("null");
-
- if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
- {
- languages.Add("en");
- }
-
- return string.Join(",", languages.ToArray());
- }
-
- public static string NormalizeLanguage(string language)
- {
- if (!string.IsNullOrEmpty(language))
- {
- // They require this to be uppercase
- // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api.
- // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
- var parts = language.Split('-');
-
- if (parts.Length == 2)
- {
- language = parts[0] + "-" + parts[1].ToUpperInvariant();
- }
- }
-
- return language;
- }
-
- public static string AdjustImageLanguage(string imageLanguage, string requestLanguage)
- {
- if (!string.IsNullOrEmpty(imageLanguage)
- && !string.IsNullOrEmpty(requestLanguage)
- && requestLanguage.Length > 2
- && imageLanguage.Length == 2
- && requestLanguage.StartsWith(imageLanguage, StringComparison.OrdinalIgnoreCase))
- {
- return requestLanguage;
- }
-
- return imageLanguage;
- }
-
- /// <summary>
- /// Fetches the main result.
- /// </summary>
- /// <param name="id">The id.</param>
- /// <param name="isTmdbId">if set to <c>true</c> [is TMDB identifier].</param>
- /// <param name="language">The language.</param>
- /// <param name="cancellationToken">The cancellation token</param>
- /// <returns>Task{CompleteMovieData}.</returns>
- internal async Task<CompleteMovieData> FetchMainResult(string id, bool isTmdbId, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(GetMovieInfo3, id, ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format("&language={0}", NormalizeLanguage(language));
-
- // Get images in english and with no language
- url += "&include_image_language=" + GetImageLanguagesParam(language);
- }
-
- CompleteMovieData mainResult;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // Cache if not using a tmdbId because we won't have the tmdb cache directory structure. So use the lower level cache.
- var cacheMode = isTmdbId ? CacheMode.None : CacheMode.Unconditional;
- var cacheLength = TimeSpan.FromDays(3);
-
- try
- {
- using (var response = await GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = AcceptHeader,
- CacheMode = cacheMode,
- CacheLength = cacheLength
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- mainResult = await _jsonSerializer.DeserializeFromStreamAsync<CompleteMovieData>(json).ConfigureAwait(false);
- }
- }
- }
- catch (HttpException ex)
- {
- // Return null so that callers know there is no metadata for this id
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return null;
- }
-
- throw;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // If the language preference isn't english, then have the overview fallback to english if it's blank
- if (mainResult != null &&
- string.IsNullOrEmpty(mainResult.overview) &&
- !string.IsNullOrEmpty(language) &&
- !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogInformation("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
-
- url = string.Format(GetMovieInfo3, id, ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + GetImageLanguagesParam(language);
- }
-
- using (var response = await GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = AcceptHeader,
- CacheMode = cacheMode,
- CacheLength = cacheLength
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var englishResult = await _jsonSerializer.DeserializeFromStreamAsync<CompleteMovieData>(json).ConfigureAwait(false);
-
- mainResult.overview = englishResult.overview;
- }
- }
- }
-
- return mainResult;
- }
-
- private static long _lastRequestTicks;
- // The limit is 40 requests per 10 seconds
- private static int requestIntervalMs = 300;
-
- /// <summary>
- /// Gets the movie db response.
- /// </summary>
- internal async Task<HttpResponseInfo> GetMovieDbResponse(HttpRequestOptions options)
- {
- var delayTicks = (requestIntervalMs * 10000) - (DateTime.UtcNow.Ticks - _lastRequestTicks);
- var delayMs = Math.Min(delayTicks / 10000, requestIntervalMs);
-
- if (delayMs > 0)
- {
- _logger.LogDebug("Throttling Tmdb by {0} ms", delayMs);
- await Task.Delay(Convert.ToInt32(delayMs)).ConfigureAwait(false);
- }
-
- _lastRequestTicks = DateTime.UtcNow.Ticks;
-
- options.BufferContent = true;
- options.UserAgent = _appHost.ApplicationUserAgent;
-
- return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false);
- }
-
- /// <summary>
- /// Class TmdbTitle
- /// </summary>
- internal class TmdbTitle
- {
- /// <summary>
- /// Gets or sets the iso_3166_1.
- /// </summary>
- /// <value>The iso_3166_1.</value>
- public string iso_3166_1 { get; set; }
- /// <summary>
- /// Gets or sets the title.
- /// </summary>
- /// <value>The title.</value>
- public string title { get; set; }
- }
-
- /// <summary>
- /// Class TmdbAltTitleResults
- /// </summary>
- internal class TmdbAltTitleResults
- {
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public int id { get; set; }
- /// <summary>
- /// Gets or sets the titles.
- /// </summary>
- /// <value>The titles.</value>
- public List<TmdbTitle> titles { get; set; }
- }
-
- internal class BelongsToCollection
- {
- public int id { get; set; }
- public string name { get; set; }
- public string poster_path { get; set; }
- public string backdrop_path { get; set; }
- }
-
- internal class GenreItem
- {
- public int id { get; set; }
- public string name { get; set; }
- }
-
- internal class ProductionCompany
- {
- public string name { get; set; }
- public int id { get; set; }
- }
-
- internal class ProductionCountry
- {
- public string iso_3166_1 { get; set; }
- public string name { get; set; }
- }
-
- internal class SpokenLanguage
- {
- public string iso_639_1 { get; set; }
- public string name { get; set; }
- }
-
- internal class Cast
- {
- public int id { get; set; }
- public string name { get; set; }
- public string character { get; set; }
- public int order { get; set; }
- public int cast_id { get; set; }
- public string profile_path { get; set; }
- }
-
- internal class Crew
- {
- public int id { get; set; }
- public string name { get; set; }
- public string department { get; set; }
- public string job { get; set; }
- public string profile_path { get; set; }
- }
-
- internal class Casts
- {
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- }
-
- internal class Country
- {
- public string iso_3166_1 { get; set; }
- public string certification { get; set; }
- public DateTime release_date { get; set; }
- }
-
- internal class Releases
- {
- public List<Country> countries { get; set; }
- }
-
- internal class Backdrop
- {
- public string file_path { get; set; }
- public int width { get; set; }
- public int height { get; set; }
- public object iso_639_1 { get; set; }
- public double aspect_ratio { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- }
-
- internal class Poster
- {
- public string file_path { get; set; }
- public int width { get; set; }
- public int height { get; set; }
- public string iso_639_1 { get; set; }
- public double aspect_ratio { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- }
-
- internal class Images
- {
- public List<Backdrop> backdrops { get; set; }
- public List<Poster> posters { get; set; }
- }
-
- internal class Keyword
- {
- public int id { get; set; }
- public string name { get; set; }
- }
-
- internal class Keywords
- {
- public List<Keyword> keywords { get; set; }
- }
-
- internal class Youtube
- {
- public string name { get; set; }
- public string size { get; set; }
- public string source { get; set; }
- }
-
- internal class Trailers
- {
- public List<object> quicktime { get; set; }
- public List<Youtube> youtube { get; set; }
- }
-
- internal class CompleteMovieData
- {
- public bool adult { get; set; }
- public string backdrop_path { get; set; }
- public BelongsToCollection belongs_to_collection { get; set; }
- public int budget { get; set; }
- public List<GenreItem> genres { get; set; }
- public string homepage { get; set; }
- public int id { get; set; }
- public string imdb_id { get; set; }
- public string original_title { get; set; }
- public string original_name { get; set; }
- public string overview { get; set; }
- public double popularity { get; set; }
- public string poster_path { get; set; }
- public List<ProductionCompany> production_companies { get; set; }
- public List<ProductionCountry> production_countries { get; set; }
- public string release_date { get; set; }
- public int revenue { get; set; }
- public int runtime { get; set; }
- public List<SpokenLanguage> spoken_languages { get; set; }
- public string status { get; set; }
- public string tagline { get; set; }
- public string title { get; set; }
- public string name { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public Casts casts { get; set; }
- public Releases releases { get; set; }
- public Images images { get; set; }
- public Keywords keywords { get; set; }
- public Trailers trailers { get; set; }
-
- public string GetOriginalTitle()
- {
- return original_name ?? original_title;
- }
-
- public string GetTitle()
- {
- return name ?? title ?? GetOriginalTitle();
- }
- }
-
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/MovieDbSearch.cs b/MediaBrowser.Providers/Movies/MovieDbSearch.cs
deleted file mode 100644
index e466d40a0..000000000
--- a/MediaBrowser.Providers/Movies/MovieDbSearch.cs
+++ /dev/null
@@ -1,394 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class MovieDbSearch
- {
- private static readonly CultureInfo EnUs = new CultureInfo("en-US");
- private const string Search3 = MovieDbProvider.BaseMovieDbUrl + @"3/search/{3}?api_key={1}&query={0}&language={2}";
-
- internal static string ApiKey = "4219e299c89411838049ab0dab19ebd5";
- internal static string AcceptHeader = "application/json,image/*";
-
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
- private readonly ILibraryManager _libraryManager;
-
- public MovieDbSearch(ILogger logger, IJsonSerializer json, ILibraryManager libraryManager)
- {
- _logger = logger;
- _json = json;
- _libraryManager = libraryManager;
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "tv", cancellationToken);
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetMovieSearchResults(ItemLookupInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "movie", cancellationToken);
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "collection", cancellationToken);
- }
-
- private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ItemLookupInfo idInfo, string searchType, CancellationToken cancellationToken)
- {
- var name = idInfo.Name;
- var year = idInfo.Year;
-
- if (string.IsNullOrWhiteSpace(name))
- {
- return new List<RemoteSearchResult>();
- }
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- if (!string.IsNullOrWhiteSpace(name))
- {
- var parsedName = _libraryManager.ParseName(name);
- var yearInName = parsedName.Year;
- name = parsedName.Name;
- year = year ?? yearInName;
- }
-
- _logger.LogInformation("MovieDbProvider: Finding id for item: " + name);
- var language = idInfo.MetadataLanguage.ToLowerInvariant();
-
- //nope - search for it
- //var searchType = item is BoxSet ? "collection" : "movie";
-
- var results = await GetSearchResults(name, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
-
- if (results.Count == 0)
- {
- //try in english if wasn't before
- if (!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- results = await GetSearchResults(name, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
- }
- }
-
- if (results.Count == 0)
- {
- // try with dot and _ turned to space
- var originalName = name;
-
- name = name.Replace(",", " ");
- name = name.Replace(".", " ");
- name = name.Replace("_", " ");
- name = name.Replace("-", " ");
- name = name.Replace("!", " ");
- name = name.Replace("?", " ");
-
- var parenthIndex = name.IndexOf('(');
- if (parenthIndex != -1)
- {
- name = name.Substring(0, parenthIndex);
- }
-
- name = name.Trim();
-
- // Search again if the new name is different
- if (!string.Equals(name, originalName))
- {
- results = await GetSearchResults(name, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
-
- if (results.Count == 0 && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- //one more time, in english
- results = await GetSearchResults(name, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
-
- }
- }
- }
-
- return results.Where(i =>
- {
- if (year.HasValue && i.ProductionYear.HasValue)
- {
- // Allow one year tolerance
- return Math.Abs(year.Value - i.ProductionYear.Value) <= 1;
- }
-
- return true;
- });
- }
-
- private Task<List<RemoteSearchResult>> GetSearchResults(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- switch (type)
- {
- case "tv":
- return GetSearchResultsTv(name, year, language, baseImageUrl, cancellationToken);
- default:
- return GetSearchResultsGeneric(name, type, year, language, baseImageUrl, cancellationToken);
- }
- }
-
- private async Task<List<RemoteSearchResult>> GetSearchResultsGeneric(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentException("name");
- }
-
- var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, type);
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url3,
- CancellationToken = cancellationToken,
- AcceptHeader = AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var searchResults = await _json.DeserializeFromStreamAsync<TmdbMovieSearchResults>(json).ConfigureAwait(false);
-
- var results = searchResults.results ?? new List<TmdbMovieSearchResult>();
-
- return results
- .Select(i =>
- {
- var remoteResult = new RemoteSearchResult
- {
- SearchProviderName = MovieDbProvider.Current.Name,
- Name = i.title ?? i.name ?? i.original_title,
- ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path
- };
-
- if (!string.IsNullOrWhiteSpace(i.release_date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParseExact(i.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out var r))
- {
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
- }
- }
-
- remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs));
-
- return remoteResult;
-
- })
- .ToList();
- }
- }
- }
-
- private async Task<List<RemoteSearchResult>> GetSearchResultsTv(string name, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentException("name");
- }
-
- var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, "tv");
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url3,
- CancellationToken = cancellationToken,
- AcceptHeader = AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var searchResults = await _json.DeserializeFromStreamAsync<TmdbTvSearchResults>(json).ConfigureAwait(false);
-
- var results = searchResults.results ?? new List<TvResult>();
-
- return results
- .Select(i =>
- {
- var remoteResult = new RemoteSearchResult
- {
- SearchProviderName = MovieDbProvider.Current.Name,
- Name = i.name ?? i.original_name,
- ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path
- };
-
- if (!string.IsNullOrWhiteSpace(i.first_air_date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParseExact(i.first_air_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out var r))
- {
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
- }
- }
-
- remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs));
-
- return remoteResult;
-
- })
- .ToList();
- }
- }
- }
-
- /// <summary>
- /// Class TmdbMovieSearchResult
- /// </summary>
- public class TmdbMovieSearchResult
- {
- /// <summary>
- /// Gets or sets a value indicating whether this <see cref="TmdbMovieSearchResult" /> is adult.
- /// </summary>
- /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
- public bool adult { get; set; }
- /// <summary>
- /// Gets or sets the backdrop_path.
- /// </summary>
- /// <value>The backdrop_path.</value>
- public string backdrop_path { get; set; }
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public int id { get; set; }
- /// <summary>
- /// Gets or sets the original_title.
- /// </summary>
- /// <value>The original_title.</value>
- public string original_title { get; set; }
- /// <summary>
- /// Gets or sets the original_name.
- /// </summary>
- /// <value>The original_name.</value>
- public string original_name { get; set; }
- /// <summary>
- /// Gets or sets the release_date.
- /// </summary>
- /// <value>The release_date.</value>
- public string release_date { get; set; }
- /// <summary>
- /// Gets or sets the poster_path.
- /// </summary>
- /// <value>The poster_path.</value>
- public string poster_path { get; set; }
- /// <summary>
- /// Gets or sets the popularity.
- /// </summary>
- /// <value>The popularity.</value>
- public double popularity { get; set; }
- /// <summary>
- /// Gets or sets the title.
- /// </summary>
- /// <value>The title.</value>
- public string title { get; set; }
- /// <summary>
- /// Gets or sets the vote_average.
- /// </summary>
- /// <value>The vote_average.</value>
- public double vote_average { get; set; }
- /// <summary>
- /// For collection search results
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// Gets or sets the vote_count.
- /// </summary>
- /// <value>The vote_count.</value>
- public int vote_count { get; set; }
- }
-
- /// <summary>
- /// Class TmdbMovieSearchResults
- /// </summary>
- private class TmdbMovieSearchResults
- {
- /// <summary>
- /// Gets or sets the page.
- /// </summary>
- /// <value>The page.</value>
- public int page { get; set; }
- /// <summary>
- /// Gets or sets the results.
- /// </summary>
- /// <value>The results.</value>
- public List<TmdbMovieSearchResult> results { get; set; }
- /// <summary>
- /// Gets or sets the total_pages.
- /// </summary>
- /// <value>The total_pages.</value>
- public int total_pages { get; set; }
- /// <summary>
- /// Gets or sets the total_results.
- /// </summary>
- /// <value>The total_results.</value>
- public int total_results { get; set; }
- }
-
- public class TvResult
- {
- public string backdrop_path { get; set; }
- public string first_air_date { get; set; }
- public int id { get; set; }
- public string original_name { get; set; }
- public string poster_path { get; set; }
- public double popularity { get; set; }
- public string name { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- }
-
- /// <summary>
- /// Class TmdbTvSearchResults
- /// </summary>
- private class TmdbTvSearchResults
- {
- /// <summary>
- /// Gets or sets the page.
- /// </summary>
- /// <value>The page.</value>
- public int page { get; set; }
- /// <summary>
- /// Gets or sets the results.
- /// </summary>
- /// <value>The results.</value>
- public List<TvResult> results { get; set; }
- /// <summary>
- /// Gets or sets the total_pages.
- /// </summary>
- /// <value>The total_pages.</value>
- public int total_pages { get; set; }
- /// <summary>
- /// Gets or sets the total_results.
- /// </summary>
- /// <value>The total_results.</value>
- public int total_results { get; set; }
- }
-
- public class ExternalIdLookupResult
- {
- public List<object> movie_results { get; set; }
- public List<object> person_results { get; set; }
- public List<TvResult> tv_results { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/MovieDbTrailerProvider.cs b/MediaBrowser.Providers/Movies/MovieDbTrailerProvider.cs
deleted file mode 100644
index 2a3cdf097..000000000
--- a/MediaBrowser.Providers/Movies/MovieDbTrailerProvider.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Providers;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class MovieDbTrailerProvider : IHasOrder, IRemoteMetadataProvider<Trailer, TrailerInfo>
- {
- private readonly IHttpClient _httpClient;
-
- public MovieDbTrailerProvider(IHttpClient httpClient)
- {
- _httpClient = httpClient;
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(TrailerInfo searchInfo, CancellationToken cancellationToken)
- {
- return MovieDbProvider.Current.GetMovieSearchResults(searchInfo, cancellationToken);
- }
-
- public Task<MetadataResult<Trailer>> GetMetadata(TrailerInfo info, CancellationToken cancellationToken)
- {
- return MovieDbProvider.Current.GetItemMetadata<Trailer>(info, cancellationToken);
- }
-
- public string Name => MovieDbProvider.Current.Name;
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/MovieExternalIds.cs b/MediaBrowser.Providers/Movies/MovieExternalIds.cs
deleted file mode 100644
index 3783c5032..000000000
--- a/MediaBrowser.Providers/Movies/MovieExternalIds.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Providers.Movies
-{
- public class MovieDbMovieExternalId : IExternalId
- {
- public const string BaseMovieDbUrl = "https://www.themoviedb.org/";
-
- public string Name => "TheMovieDb";
-
- public string Key => MetadataProviders.Tmdb.ToString();
-
- public string UrlFormatString => BaseMovieDbUrl + "movie/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- // Supports images for tv movies
- var tvProgram = item as LiveTvProgram;
- if (tvProgram != null && tvProgram.IsMovie)
- {
- return true;
- }
-
- return item is Movie || item is MusicVideo || item is Trailer;
- }
- }
-
- public class MovieDbSeriesExternalId : IExternalId
- {
- public string Name => "TheMovieDb";
-
- public string Key => MetadataProviders.Tmdb.ToString();
-
- public string UrlFormatString => MovieDbMovieExternalId.BaseMovieDbUrl + "tv/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Series;
- }
- }
-
- public class MovieDbMovieCollectionExternalId : IExternalId
- {
- public string Name => "TheMovieDb Collection";
-
- public string Key => MetadataProviders.TmdbCollection.ToString();
-
- public string UrlFormatString => MovieDbMovieExternalId.BaseMovieDbUrl + "collection/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Movie || item is MusicVideo || item is Trailer;
- }
- }
-
- public class MovieDbPersonExternalId : IExternalId
- {
- public string Name => "TheMovieDb";
-
- public string Key => MetadataProviders.Tmdb.ToString();
-
- public string UrlFormatString => MovieDbMovieExternalId.BaseMovieDbUrl + "person/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Person;
- }
- }
-
- public class MovieDbCollectionExternalId : IExternalId
- {
- public string Name => "TheMovieDb";
-
- public string Key => MetadataProviders.Tmdb.ToString();
-
- public string UrlFormatString => MovieDbMovieExternalId.BaseMovieDbUrl + "collection/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is BoxSet;
- }
- }
-
- public class ImdbExternalId : IExternalId
- {
- public string Name => "IMDb";
-
- public string Key => MetadataProviders.Imdb.ToString();
-
- public string UrlFormatString => "https://www.imdb.com/title/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- // Supports images for tv movies
- var tvProgram = item as LiveTvProgram;
- if (tvProgram != null && tvProgram.IsMovie)
- {
- return true;
- }
-
- return item is Movie || item is MusicVideo || item is Series || item is Episode || item is Trailer;
- }
- }
-
-
- public class ImdbPersonExternalId : IExternalId
- {
- public string Name => "IMDb";
-
- public string Key => MetadataProviders.Imdb.ToString();
-
- public string UrlFormatString => "https://www.imdb.com/name/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Person;
- }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
index 41806e49b..c477fb70f 100644
--- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs
+++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
@@ -1,5 +1,6 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
@@ -12,20 +13,34 @@ namespace MediaBrowser.Providers.Movies
{
public class MovieMetadataService : MetadataService<Movie, MovieInfo>
{
+ public MovieMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MovieMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ {
+ }
+
+ /// <inheritdoc />
protected override bool IsFullLocalMetadata(Movie item)
{
if (string.IsNullOrWhiteSpace(item.Overview))
{
return false;
}
+
if (!item.ProductionYear.HasValue)
{
return false;
}
+
return base.IsFullLocalMetadata(item);
}
- protected override void MergeData(MetadataResult<Movie> source, MetadataResult<Movie> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Movie> source, MetadataResult<Movie> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -37,40 +52,5 @@ namespace MediaBrowser.Providers.Movies
targetItem.CollectionName = sourceItem.CollectionName;
}
}
-
- public MovieMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
- }
-
- public class TrailerMetadataService : MetadataService<Trailer, TrailerInfo>
- {
- protected override bool IsFullLocalMetadata(Trailer item)
- {
- if (string.IsNullOrWhiteSpace(item.Overview))
- {
- return false;
- }
- if (!item.ProductionYear.HasValue)
- {
- return false;
- }
- return base.IsFullLocalMetadata(item);
- }
-
- protected override void MergeData(MetadataResult<Trailer> source, MetadataResult<Trailer> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
-
- if (replaceData || target.Item.TrailerTypes.Length == 0)
- {
- target.Item.TrailerTypes = source.Item.TrailerTypes;
- }
- }
-
- public TrailerMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
-
}
diff --git a/MediaBrowser.Providers/Movies/TmdbSettings.cs b/MediaBrowser.Providers/Movies/TmdbSettings.cs
deleted file mode 100644
index 119bbfca6..000000000
--- a/MediaBrowser.Providers/Movies/TmdbSettings.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Movies
-{
- internal class TmdbImageSettings
- {
- public List<string> backdrop_sizes { get; set; }
- public string secure_base_url { get; set; }
- public List<string> poster_sizes { get; set; }
- public List<string> profile_sizes { get; set; }
-
- public string GetImageUrl(string image)
- {
- return secure_base_url + image;
- }
- }
-
- internal class TmdbSettingsResult
- {
- public TmdbImageSettings images { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Movies/TrailerMetadataService.cs b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs
new file mode 100644
index 000000000..f32d9ec0a
--- /dev/null
+++ b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs
@@ -0,0 +1,53 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Providers.Manager;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.Providers.Movies
+{
+ public class TrailerMetadataService : MetadataService<Trailer, TrailerInfo>
+ {
+ public TrailerMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<TrailerMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override bool IsFullLocalMetadata(Trailer item)
+ {
+ if (string.IsNullOrWhiteSpace(item.Overview))
+ {
+ return false;
+ }
+
+ if (!item.ProductionYear.HasValue)
+ {
+ return false;
+ }
+
+ return base.IsFullLocalMetadata(item);
+ }
+
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Trailer> source, MetadataResult<Trailer> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+
+ if (replaceData || target.Item.TrailerTypes.Length == 0)
+ {
+ target.Item.TrailerTypes = source.Item.TrailerTypes;
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Music/Extensions.cs b/MediaBrowser.Providers/Music/AlbumInfoExtensions.cs
index ea1efe266..d3fce37c7 100644
--- a/MediaBrowser.Providers/Music/Extensions.cs
+++ b/MediaBrowser.Providers/Music/AlbumInfoExtensions.cs
@@ -1,12 +1,14 @@
+#pragma warning disable CS1591
+
using System.Linq;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Providers.Music
{
- public static class Extensions
+ public static class AlbumInfoExtensions
{
- public static string GetAlbumArtist(this AlbumInfo info)
+ public static string? GetAlbumArtist(this AlbumInfo info)
{
var id = info.SongInfos.SelectMany(i => i.AlbumArtists)
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
@@ -16,60 +18,60 @@ namespace MediaBrowser.Providers.Music
return id;
}
- return info.AlbumArtists.FirstOrDefault();
+ return info.AlbumArtists.Count > 0 ? info.AlbumArtists[0] : default;
}
- public static string GetReleaseGroupId(this AlbumInfo info)
+ public static string? GetReleaseGroupId(this AlbumInfo info)
{
- var id = info.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
+ var id = info.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup);
if (string.IsNullOrEmpty(id))
{
- return info.SongInfos.Select(i => i.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup))
+ return info.SongInfos.Select(i => i.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup))
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
return id;
}
- public static string GetReleaseId(this AlbumInfo info)
+ public static string? GetReleaseId(this AlbumInfo info)
{
- var id = info.GetProviderId(MetadataProviders.MusicBrainzAlbum);
+ var id = info.GetProviderId(MetadataProvider.MusicBrainzAlbum);
if (string.IsNullOrEmpty(id))
{
- return info.SongInfos.Select(i => i.GetProviderId(MetadataProviders.MusicBrainzAlbum))
+ return info.SongInfos.Select(i => i.GetProviderId(MetadataProvider.MusicBrainzAlbum))
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
return id;
}
- public static string GetMusicBrainzArtistId(this AlbumInfo info)
+ public static string? GetMusicBrainzArtistId(this AlbumInfo info)
{
- info.ProviderIds.TryGetValue(MetadataProviders.MusicBrainzAlbumArtist.ToString(), out string id);
+ info.ProviderIds.TryGetValue(MetadataProvider.MusicBrainzAlbumArtist.ToString(), out string? id);
if (string.IsNullOrEmpty(id))
{
- info.ArtistProviderIds.TryGetValue(MetadataProviders.MusicBrainzArtist.ToString(), out id);
+ info.ArtistProviderIds.TryGetValue(MetadataProvider.MusicBrainzArtist.ToString(), out id);
}
if (string.IsNullOrEmpty(id))
{
- return info.SongInfos.Select(i => i.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist))
+ return info.SongInfos.Select(i => i.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist))
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
return id;
}
- public static string GetMusicBrainzArtistId(this ArtistInfo info)
+ public static string? GetMusicBrainzArtistId(this ArtistInfo info)
{
- info.ProviderIds.TryGetValue(MetadataProviders.MusicBrainzArtist.ToString(), out var id);
+ info.ProviderIds.TryGetValue(MetadataProvider.MusicBrainzArtist.ToString(), out var id);
if (string.IsNullOrEmpty(id))
{
- return info.SongInfos.Select(i => i.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist))
+ return info.SongInfos.Select(i => i.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist))
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
index 33a6c2fa3..7c5b80e1e 100644
--- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,47 +17,57 @@ namespace MediaBrowser.Providers.Music
{
public class AlbumMetadataService : MetadataService<MusicAlbum, AlbumInfo>
{
- protected override IList<BaseItem> GetChildrenForMetadataUpdates(MusicAlbum item)
+ public AlbumMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<AlbumMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- return item.GetRecursiveChildren(i => i is Audio)
- .ToList();
}
+ /// <inheritdoc />
+ protected override bool EnableUpdatingPremiereDateFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
+
+ /// <inheritdoc />
+ protected override IList<BaseItem> GetChildrenForMetadataUpdates(MusicAlbum item)
+ => item.GetRecursiveChildren(i => i is Audio);
+
+ /// <inheritdoc />
protected override ItemUpdateType UpdateMetadataFromChildren(MusicAlbum item, IList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
{
var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
{
- if (!item.LockedFields.Contains(MetadataFields.Name))
+ if (!item.LockedFields.Contains(MetadataField.Name))
{
var name = children.Select(i => i.Album).FirstOrDefault(i => !string.IsNullOrEmpty(i));
- if (!string.IsNullOrEmpty(name))
+ if (!string.IsNullOrEmpty(name)
+ && !string.Equals(item.Name, name, StringComparison.Ordinal))
{
- if (!string.Equals(item.Name, name, StringComparison.Ordinal))
- {
- item.Name = name;
- updateType = updateType | ItemUpdateType.MetadataEdit;
- }
+ item.Name = name;
+ updateType |= ItemUpdateType.MetadataEdit;
}
}
var songs = children.Cast<Audio>().ToArray();
- updateType = updateType | SetAlbumArtistFromSongs(item, songs);
- updateType = updateType | SetArtistsFromSongs(item, songs);
+ updateType |= SetAlbumArtistFromSongs(item, songs);
+ updateType |= SetArtistsFromSongs(item, songs);
}
return updateType;
}
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
-
- protected override bool EnableUpdatingGenresFromChildren => true;
-
- protected override bool EnableUpdatingStudiosFromChildren => true;
-
private ItemUpdateType SetAlbumArtistFromSongs(MusicAlbum item, IEnumerable<Audio> songs)
{
var updateType = ItemUpdateType.None;
@@ -69,7 +81,7 @@ namespace MediaBrowser.Providers.Music
if (!item.AlbumArtists.SequenceEqual(artists, StringComparer.OrdinalIgnoreCase))
{
item.AlbumArtists = artists;
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
return updateType;
@@ -88,27 +100,29 @@ namespace MediaBrowser.Providers.Music
if (!item.Artists.SequenceEqual(artists, StringComparer.OrdinalIgnoreCase))
{
item.Artists = artists;
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updateType |= ItemUpdateType.MetadataEdit;
}
return updateType;
}
- protected override void MergeData(MetadataResult<MusicAlbum> source, MetadataResult<MusicAlbum> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(
+ MetadataResult<MusicAlbum> source,
+ MetadataResult<MusicAlbum> target,
+ MetadataField[] lockedFields,
+ bool replaceData,
+ bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
var sourceItem = source.Item;
var targetItem = target.Item;
- if (replaceData || targetItem.Artists.Length == 0)
+ if (replaceData || targetItem.Artists.Count == 0)
{
targetItem.Artists = sourceItem.Artists;
}
}
-
- public AlbumMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Music/ArtistMetadataService.cs b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
index 5b8782554..e29475dd7 100644
--- a/MediaBrowser.Providers/Music/ArtistMetadataService.cs
+++ b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -13,26 +15,35 @@ namespace MediaBrowser.Providers.Music
{
public class ArtistMetadataService : MetadataService<MusicArtist, ArtistInfo>
{
- protected override IList<BaseItem> GetChildrenForMetadataUpdates(MusicArtist item)
+ public ArtistMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<ArtistMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- return item.IsAccessedByName ?
- item.GetTaggedItems(new InternalItemsQuery
- {
- Recursive = true,
- IsFolder = false
- }) :
- item.GetRecursiveChildren(i => i is IHasArtist && !i.IsFolder);
}
+ /// <inheritdoc />
protected override bool EnableUpdatingGenresFromChildren => true;
- protected override void MergeData(MetadataResult<MusicArtist> source, MetadataResult<MusicArtist> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override IList<BaseItem> GetChildrenForMetadataUpdates(MusicArtist item)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ return item.IsAccessedByName
+ ? item.GetTaggedItems(new InternalItemsQuery
+ {
+ Recursive = true,
+ IsFolder = false
+ })
+ : item.GetRecursiveChildren(i => i is IHasArtist && !i.IsFolder);
}
- public ArtistMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<MusicArtist> source, MetadataResult<MusicArtist> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Music/AudioDbExternalIds.cs b/MediaBrowser.Providers/Music/AudioDbExternalIds.cs
deleted file mode 100644
index 3e1022d7d..000000000
--- a/MediaBrowser.Providers/Music/AudioDbExternalIds.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Providers.Music
-{
- public class AudioDbAlbumExternalId : IExternalId
- {
- public string Name => "TheAudioDb";
-
- public string Key => MetadataProviders.AudioDbAlbum.ToString();
-
- public string UrlFormatString => "https://www.theaudiodb.com/album/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is MusicAlbum;
- }
- }
-
- public class AudioDbOtherAlbumExternalId : IExternalId
- {
- public string Name => "TheAudioDb Album";
-
- public string Key => MetadataProviders.AudioDbAlbum.ToString();
-
- public string UrlFormatString => "https://www.theaudiodb.com/album/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio;
- }
- }
-
- public class AudioDbArtistExternalId : IExternalId
- {
- public string Name => "TheAudioDb";
-
- public string Key => MetadataProviders.AudioDbArtist.ToString();
-
- public string UrlFormatString => "https://www.theaudiodb.com/artist/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is MusicArtist;
- }
- }
-
- public class AudioDbOtherArtistExternalId : IExternalId
- {
- public string Name => "TheAudioDb Artist";
-
- public string Key => MetadataProviders.AudioDbArtist.ToString();
-
- public string UrlFormatString => "https://www.theaudiodb.com/artist/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio || item is MusicAlbum;
- }
- }
-
-}
diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs
index 1422a4eaa..8b9fc8a08 100644
--- a/MediaBrowser.Providers/Music/AudioMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
@@ -11,14 +13,25 @@ namespace MediaBrowser.Providers.Music
{
public class AudioMetadataService : MetadataService<Audio, SongInfo>
{
- protected override void MergeData(MetadataResult<Audio> source, MetadataResult<Audio> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public AudioMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<AudioMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Audio> source, MetadataResult<Audio> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
var sourceItem = source.Item;
var targetItem = target.Item;
- if (replaceData || targetItem.Artists.Length == 0)
+ if (replaceData || targetItem.Artists.Count == 0)
{
targetItem.Artists = sourceItem.Artists;
}
@@ -28,9 +41,5 @@ namespace MediaBrowser.Providers.Music
targetItem.Album = sourceItem.Album;
}
}
-
- public AudioMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Music/FanArtAlbumProvider.cs b/MediaBrowser.Providers/Music/FanArtAlbumProvider.cs
deleted file mode 100644
index ebb740ffe..000000000
--- a/MediaBrowser.Providers/Music/FanArtAlbumProvider.cs
+++ /dev/null
@@ -1,201 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-
-namespace MediaBrowser.Providers.Music
-{
- public class FanartAlbumProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _jsonSerializer;
-
- public FanartAlbumProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
- {
- _config = config;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _jsonSerializer = jsonSerializer;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "FanArt";
-
- public bool Supports(BaseItem item)
- {
- return item is MusicAlbum;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Disc
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var album = (MusicAlbum)item;
-
- var list = new List<RemoteImageInfo>();
-
- var musicArtist = album.MusicArtist;
-
- if (musicArtist == null)
- {
- return list;
- }
-
- var artistMusicBrainzId = musicArtist.GetProviderId(MetadataProviders.MusicBrainzArtist);
-
- if (!string.IsNullOrEmpty(artistMusicBrainzId))
- {
- await FanartArtistProvider.Current.EnsureArtistJson(artistMusicBrainzId, cancellationToken).ConfigureAwait(false);
-
- var artistJsonPath = FanartArtistProvider.GetArtistJsonPath(_config.CommonApplicationPaths, artistMusicBrainzId);
-
- var musicBrainzReleaseGroupId = album.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
-
- var musicBrainzId = album.GetProviderId(MetadataProviders.MusicBrainzAlbum);
-
- try
- {
- AddImages(list, artistJsonPath, musicBrainzId, musicBrainzReleaseGroupId, cancellationToken);
- }
- catch (FileNotFoundException)
- {
-
- }
- catch (IOException)
- {
-
- }
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- // Sort first by width to prioritize HD versions
- return list.OrderByDescending(i => i.Width ?? 0)
- .ThenByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- /// <summary>
- /// Adds the images.
- /// </summary>
- /// <param name="list">The list.</param>
- /// <param name="path">The path.</param>
- /// <param name="releaseId">The release identifier.</param>
- /// <param name="releaseGroupId">The release group identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- private void AddImages(List<RemoteImageInfo> list, string path, string releaseId, string releaseGroupId, CancellationToken cancellationToken)
- {
- var obj = _jsonSerializer.DeserializeFromFile<FanartArtistProvider.FanartArtistResponse>(path);
-
- if (obj.albums != null)
- {
- var album = obj.albums.FirstOrDefault(i => string.Equals(i.release_group_id, releaseGroupId, StringComparison.OrdinalIgnoreCase));
-
- if (album != null)
- {
- PopulateImages(list, album.albumcover, ImageType.Primary, 1000, 1000);
- PopulateImages(list, album.cdart, ImageType.Disc, 1000, 1000);
- }
- }
- }
-
- private void PopulateImages(List<RemoteImageInfo> list,
- List<FanartArtistProvider.FanartArtistImage> images,
- ImageType type,
- int width,
- int height)
- {
- if (images == null)
- {
- return;
- }
-
- list.AddRange(images.Select(i =>
- {
- var url = i.url;
-
- if (!string.IsNullOrEmpty(url))
- {
- var likesString = i.likes;
-
- var info = new RemoteImageInfo
- {
- RatingType = RatingType.Likes,
- Type = type,
- Width = width,
- Height = height,
- ProviderName = Name,
- Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
- Language = i.lang
- };
-
- if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
- {
- info.CommunityRating = likes;
- }
-
- return info;
- }
-
- return null;
- }).Where(i => i != null));
- }
- // After embedded provider
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Music/FanArtArtistProvider.cs b/MediaBrowser.Providers/Music/FanArtArtistProvider.cs
deleted file mode 100644
index 75b4213c5..000000000
--- a/MediaBrowser.Providers/Music/FanArtArtistProvider.cs
+++ /dev/null
@@ -1,335 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.TV;
-using MediaBrowser.Providers.TV.FanArt;
-
-namespace MediaBrowser.Providers.Music
-{
- public class FanartArtistProvider : IRemoteImageProvider, IHasOrder
- {
- internal const string ApiKey = "184e1a2b1fe3b94935365411f919f638";
- private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3.1/music/{1}?api_key={0}";
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _jsonSerializer;
-
- internal static FanartArtistProvider Current;
-
- public FanartArtistProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
- {
- _config = config;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _jsonSerializer = jsonSerializer;
-
- Current = this;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "FanArt";
-
- public bool Supports(BaseItem item)
- {
- return item is MusicArtist;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Logo,
- ImageType.Art,
- ImageType.Banner,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var artist = (MusicArtist)item;
-
- var list = new List<RemoteImageInfo>();
-
- var artistMusicBrainzId = artist.GetProviderId(MetadataProviders.MusicBrainzArtist);
-
- if (!string.IsNullOrEmpty(artistMusicBrainzId))
- {
- await EnsureArtistJson(artistMusicBrainzId, cancellationToken).ConfigureAwait(false);
-
- var artistJsonPath = GetArtistJsonPath(_config.CommonApplicationPaths, artistMusicBrainzId);
-
- try
- {
- AddImages(list, artistJsonPath, cancellationToken);
- }
- catch (FileNotFoundException)
- {
-
- }
- catch (IOException)
- {
-
- }
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- // Sort first by width to prioritize HD versions
- return list.OrderByDescending(i => i.Width ?? 0)
- .ThenByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- /// <summary>
- /// Adds the images.
- /// </summary>
- /// <param name="list">The list.</param>
- /// <param name="path">The path.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
- {
- var obj = _jsonSerializer.DeserializeFromFile<FanartArtistResponse>(path);
-
- PopulateImages(list, obj.artistbackground, ImageType.Backdrop, 1920, 1080);
- PopulateImages(list, obj.artistthumb, ImageType.Primary, 500, 281);
- PopulateImages(list, obj.hdmusiclogo, ImageType.Logo, 800, 310);
- PopulateImages(list, obj.musicbanner, ImageType.Banner, 1000, 185);
- PopulateImages(list, obj.musiclogo, ImageType.Logo, 400, 155);
- PopulateImages(list, obj.hdmusicarts, ImageType.Art, 1000, 562);
- PopulateImages(list, obj.musicarts, ImageType.Art, 500, 281);
- }
-
- private void PopulateImages(List<RemoteImageInfo> list,
- List<FanartArtistImage> images,
- ImageType type,
- int width,
- int height)
- {
- if (images == null)
- {
- return;
- }
-
- list.AddRange(images.Select(i =>
- {
- var url = i.url;
-
- if (!string.IsNullOrEmpty(url))
- {
- var likesString = i.likes;
-
- var info = new RemoteImageInfo
- {
- RatingType = RatingType.Likes,
- Type = type,
- Width = width,
- Height = height,
- ProviderName = Name,
- Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
- Language = i.lang
- };
-
- if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
- {
- info.CommunityRating = likes;
- }
-
- return info;
- }
-
- return null;
- }).Where(i => i != null));
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- internal Task EnsureArtistJson(string musicBrainzId, CancellationToken cancellationToken)
- {
- var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(jsonPath);
-
- if (fileInfo.Exists)
- {
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadArtistJson(musicBrainzId, cancellationToken);
- }
-
- /// <summary>
- /// Downloads the artist data.
- /// </summary>
- /// <param name="musicBrainzId">The music brainz id.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.Boolean}.</returns>
- internal async Task DownloadArtistJson(string musicBrainzId, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
-
- var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
- if (!string.IsNullOrWhiteSpace(clientKey))
- {
- url += "&client_key=" + clientKey;
- }
-
- var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
-
- Directory.CreateDirectory(Path.GetDirectoryName(jsonPath));
-
- try
- {
- using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = true
-
- }, "GET").ConfigureAwait(false))
- {
- using (var response = httpResponse.Content)
- {
- using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await response.CopyToAsync(saveFileStream).ConfigureAwait(false);
- }
- }
- }
- }
- catch (HttpException ex)
- {
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- _jsonSerializer.SerializeToFile(new FanartArtistResponse(), jsonPath);
- }
- else
- {
- throw;
- }
- }
- }
-
- /// <summary>
- /// Gets the artist data path.
- /// </summary>
- /// <param name="appPaths">The application paths.</param>
- /// <param name="musicBrainzArtistId">The music brainz artist identifier.</param>
- /// <returns>System.String.</returns>
- private static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
- {
- var dataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
-
- return dataPath;
- }
-
- /// <summary>
- /// Gets the artist data path.
- /// </summary>
- /// <param name="appPaths">The application paths.</param>
- /// <returns>System.String.</returns>
- internal static string GetArtistDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "fanart-music");
-
- return dataPath;
- }
-
- internal static string GetArtistJsonPath(IApplicationPaths appPaths, string musicBrainzArtistId)
- {
- var dataPath = GetArtistDataPath(appPaths, musicBrainzArtistId);
-
- return Path.Combine(dataPath, "fanart.json");
- }
-
-
- public class FanartArtistImage
- {
- public string id { get; set; }
- public string url { get; set; }
- public string likes { get; set; }
- public string disc { get; set; }
- public string size { get; set; }
- public string lang { get; set; }
- }
-
- public class Album
- {
- public string release_group_id { get; set; }
- public List<FanartArtistImage> cdart { get; set; }
- public List<FanartArtistImage> albumcover { get; set; }
- }
-
- public class FanartArtistResponse
- {
- public string name { get; set; }
- public string mbid_id { get; set; }
- public List<FanartArtistImage> artistthumb { get; set; }
- public List<FanartArtistImage> artistbackground { get; set; }
- public List<FanartArtistImage> hdmusiclogo { get; set; }
- public List<FanartArtistImage> musicbanner { get; set; }
- public List<FanartArtistImage> musiclogo { get; set; }
- public List<FanartArtistImage> musicarts { get; set; }
- public List<FanartArtistImage> hdmusicarts { get; set; }
- public List<Album> albums { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Providers/Music/ImvdbId.cs b/MediaBrowser.Providers/Music/ImvdbId.cs
new file mode 100644
index 000000000..ed69f369c
--- /dev/null
+++ b/MediaBrowser.Providers/Music/ImvdbId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class ImvdbId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "IMVDb";
+
+ /// <inheritdoc />
+ public string Key => "IMVDb";
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => null;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => null;
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ => item is MusicVideo;
+ }
+}
diff --git a/MediaBrowser.Providers/Music/MovieDbMusicVideoProvider.cs b/MediaBrowser.Providers/Music/MovieDbMusicVideoProvider.cs
deleted file mode 100644
index 506cbfb89..000000000
--- a/MediaBrowser.Providers/Music/MovieDbMusicVideoProvider.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.Movies;
-
-namespace MediaBrowser.Providers.Music
-{
- public class MovieDbMusicVideoProvider : IRemoteMetadataProvider<MusicVideo, MusicVideoInfo>
- {
- public Task<MetadataResult<MusicVideo>> GetMetadata(MusicVideoInfo info, CancellationToken cancellationToken)
- {
- return MovieDbProvider.Current.GetItemMetadata<MusicVideo>(info, cancellationToken);
- }
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MusicVideoInfo searchInfo, CancellationToken cancellationToken)
- {
- return Task.FromResult((IEnumerable<RemoteSearchResult>)new List<RemoteSearchResult>());
- }
-
- public string Name => MovieDbProvider.Current.Name;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/MediaBrowser.Providers/Music/MusicExternalIds.cs b/MediaBrowser.Providers/Music/MusicExternalIds.cs
deleted file mode 100644
index 614de11ca..000000000
--- a/MediaBrowser.Providers/Music/MusicExternalIds.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Providers.Music
-{
- public class MusicBrainzReleaseGroupExternalId : IExternalId
- {
- public string Name => "MusicBrainz Release Group";
-
- public string Key => MetadataProviders.MusicBrainzReleaseGroup.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/release-group/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio || item is MusicAlbum;
- }
- }
-
- public class MusicBrainzAlbumArtistExternalId : IExternalId
- {
- public string Name => "MusicBrainz Album Artist";
-
- public string Key => MetadataProviders.MusicBrainzAlbumArtist.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/artist/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio;
- }
- }
-
- public class MusicBrainzAlbumExternalId : IExternalId
- {
- public string Name => "MusicBrainz Album";
-
- public string Key => MetadataProviders.MusicBrainzAlbum.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/release/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio || item is MusicAlbum;
- }
- }
-
- public class MusicBrainzArtistExternalId : IExternalId
- {
- public string Name => "MusicBrainz";
-
- public string Key => MetadataProviders.MusicBrainzArtist.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/artist/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is MusicArtist;
- }
- }
-
- public class MusicBrainzOtherArtistExternalId : IExternalId
- {
- public string Name => "MusicBrainz Artist";
-
- public string Key => MetadataProviders.MusicBrainzArtist.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/artist/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio || item is MusicAlbum;
- }
- }
-
- public class MusicBrainzTrackId : IExternalId
- {
- public string Name => "MusicBrainz Track";
-
- public string Key => MetadataProviders.MusicBrainzTrack.ToString();
-
- public string UrlFormatString => "https://musicbrainz.org/track/{0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Audio;
- }
- }
-
- public class ImvdbId : IExternalId
- {
- public string Name => "IMVDb";
-
- public string Key => "IMVDb";
-
- public string UrlFormatString => null;
-
- public bool Supports(IHasProviderIds item)
- {
- return item is MusicVideo;
- }
- }
-}
diff --git a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
index 93412306f..1d611a746 100644
--- a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
+++ b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,7 +13,23 @@ namespace MediaBrowser.Providers.Music
{
public class MusicVideoMetadataService : MetadataService<MusicVideo, MusicVideoInfo>
{
- protected override void MergeData(MetadataResult<MusicVideo> source, MetadataResult<MusicVideo> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ 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)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -23,14 +41,10 @@ namespace MediaBrowser.Providers.Music
targetItem.Album = sourceItem.Album;
}
- if (replaceData || targetItem.Artists.Length == 0)
+ if (replaceData || targetItem.Artists.Count == 0)
{
targetItem.Artists = sourceItem.Artists;
}
}
-
- public MusicVideoMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
index d25ddb220..7dda7e9bf 100644
--- a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
+++ b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.MusicGenres
{
public class MusicGenreMetadataService : MetadataService<MusicGenre, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<MusicGenre> source, MetadataResult<MusicGenre> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public MusicGenreMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MusicGenreMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public MusicGenreMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<MusicGenre> source, MetadataResult<MusicGenre> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/People/MovieDbPersonImageProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonImageProvider.cs
deleted file mode 100644
index 3019ee506..000000000
--- a/MediaBrowser.Providers/People/MovieDbPersonImageProvider.cs
+++ /dev/null
@@ -1,132 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-
-namespace MediaBrowser.Providers.People
-{
- public class MovieDbPersonImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IServerConfigurationManager _config;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
-
- public MovieDbPersonImageProvider(IServerConfigurationManager config, IJsonSerializer jsonSerializer, IHttpClient httpClient)
- {
- _config = config;
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheMovieDb";
-
- public bool Supports(BaseItem item)
- {
- return item is Person;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var person = (Person)item;
- var id = person.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(id))
- {
- await MovieDbPersonProvider.Current.EnsurePersonInfo(id, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = MovieDbPersonProvider.GetPersonDataFilePath(_config.ApplicationPaths, id);
-
- var result = _jsonSerializer.DeserializeFromFile<MovieDbPersonProvider.PersonResult>(dataFilePath);
-
- var images = result.images ?? new MovieDbPersonProvider.Images();
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- return GetImages(images, item.GetPreferredMetadataLanguage(), tmdbImageUrl);
- }
-
- return new List<RemoteImageInfo>();
- }
-
- private IEnumerable<RemoteImageInfo> GetImages(MovieDbPersonProvider.Images images, string preferredLanguage, string baseImageUrl)
- {
- var list = new List<RemoteImageInfo>();
-
- if (images.profiles != null)
- {
- list.AddRange(images.profiles.Select(i => new RemoteImageInfo
- {
- ProviderName = Name,
- Type = ImageType.Primary,
- Width = i.width,
- Height = i.height,
- Language = GetLanguage(i),
- Url = baseImageUrl + i.file_path
- }));
- }
-
- var language = preferredLanguage;
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private string GetLanguage(MovieDbPersonProvider.Profile profile)
- {
- return profile.iso_639_1 == null ? null : profile.iso_639_1.ToString();
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs
deleted file mode 100644
index 6d9d66f80..000000000
--- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs
+++ /dev/null
@@ -1,395 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.People
-{
- public class MovieDbPersonProvider : IRemoteMetadataProvider<Person, PersonLookupInfo>
- {
- const string DataFileName = "info.json";
-
- internal static MovieDbPersonProvider Current { get; private set; }
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
-
- public MovieDbPersonProvider(IFileSystem fileSystem, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogger logger)
- {
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _logger = logger;
- Current = this;
- }
-
- public string Name => "TheMovieDb";
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
- {
- var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
- var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
-
- var images = (info.images ?? new Images()).profiles ?? new List<Profile>();
-
- var result = new RemoteSearchResult
- {
- Name = info.name,
-
- SearchProviderName = Name,
-
- ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
- };
-
- result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
- result.SetProviderId(MetadataProviders.Imdb, info.imdb_id);
-
- return new[] { result };
- }
-
- if (searchInfo.IsAutomated)
- {
- // Don't hammer moviedb searching by name
- return new List<RemoteSearchResult>();
- }
-
- var url = string.Format(MovieDbProvider.BaseMovieDbUrl + @"3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), MovieDbProvider.ApiKey);
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var result = await _jsonSerializer.DeserializeFromStreamAsync<PersonSearchResults>(json).ConfigureAwait(false) ??
- new PersonSearchResults();
-
- return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
- }
- }
- }
-
- private RemoteSearchResult GetSearchResult(PersonSearchResult i, string baseImageUrl)
- {
- var result = new RemoteSearchResult
- {
- SearchProviderName = Name,
-
- Name = i.Name,
-
- ImageUrl = string.IsNullOrEmpty(i.Profile_Path) ? null : (baseImageUrl + i.Profile_Path)
- };
-
- result.SetProviderId(MetadataProviders.Tmdb, i.Id.ToString(_usCulture));
-
- return result;
- }
-
- public async Task<MetadataResult<Person>> GetMetadata(PersonLookupInfo id, CancellationToken cancellationToken)
- {
- var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
-
- // We don't already have an Id, need to fetch it
- if (string.IsNullOrEmpty(tmdbId))
- {
- tmdbId = await GetTmdbId(id, cancellationToken).ConfigureAwait(false);
- }
-
- var result = new MetadataResult<Person>();
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- try
- {
- await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
-
- throw;
- }
-
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
-
- var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
-
- var item = new Person();
- result.HasMetadata = true;
-
- // Take name from incoming info, don't rename the person
- // TODO: This should go in PersonMetadataService, not each person provider
- item.Name = id.Name;
-
- //item.HomePageUrl = info.homepage;
-
- if (!string.IsNullOrWhiteSpace(info.place_of_birth))
- {
- item.ProductionLocations = new string[] { info.place_of_birth };
- }
- item.Overview = info.biography;
-
- if (DateTime.TryParseExact(info.birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out var date))
- {
- item.PremiereDate = date.ToUniversalTime();
- }
-
- if (DateTime.TryParseExact(info.deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
- {
- item.EndDate = date.ToUniversalTime();
- }
-
- item.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
-
- if (!string.IsNullOrEmpty(info.imdb_id))
- {
- item.SetProviderId(MetadataProviders.Imdb, info.imdb_id);
- }
-
- result.HasMetadata = true;
- result.Item = item;
- }
-
- return result;
- }
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- /// <summary>
- /// Gets the TMDB id.
- /// </summary>
- /// <param name="info">The information.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.String}.</returns>
- private async Task<string> GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
- {
- var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
-
- return results.Select(i => i.GetProviderId(MetadataProviders.Tmdb)).FirstOrDefault();
- }
-
- internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
- {
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
-
- if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return;
- }
-
- var url = string.Format(MovieDbProvider.BaseMovieDbUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", MovieDbProvider.ApiKey, id);
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- using (var fs = _fileSystem.GetFileStream(dataFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await json.CopyToAsync(fs).ConfigureAwait(false);
- }
- }
- }
- }
-
- private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var letter = tmdbId.GetMD5().ToString().Substring(0, 1);
-
- return Path.Combine(GetPersonsDataPath(appPaths), letter, tmdbId);
- }
-
- internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
- {
- return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
- }
-
- private static string GetPersonsDataPath(IApplicationPaths appPaths)
- {
- return Path.Combine(appPaths.CachePath, "tmdb-people");
- }
-
- #region Result Objects
- /// <summary>
- /// Class PersonSearchResult
- /// </summary>
- public class PersonSearchResult
- {
- /// <summary>
- /// Gets or sets a value indicating whether this <see cref="PersonSearchResult" /> is adult.
- /// </summary>
- /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
- public bool Adult { get; set; }
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public int Id { get; set; }
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- /// <summary>
- /// Gets or sets the profile_ path.
- /// </summary>
- /// <value>The profile_ path.</value>
- public string Profile_Path { get; set; }
- }
-
- /// <summary>
- /// Class PersonSearchResults
- /// </summary>
- public class PersonSearchResults
- {
- /// <summary>
- /// Gets or sets the page.
- /// </summary>
- /// <value>The page.</value>
- public int Page { get; set; }
- /// <summary>
- /// Gets or sets the results.
- /// </summary>
- /// <value>The results.</value>
- public List<PersonSearchResult> Results { get; set; }
- /// <summary>
- /// Gets or sets the total_ pages.
- /// </summary>
- /// <value>The total_ pages.</value>
- public int Total_Pages { get; set; }
- /// <summary>
- /// Gets or sets the total_ results.
- /// </summary>
- /// <value>The total_ results.</value>
- public int Total_Results { get; set; }
- }
-
- public class Cast
- {
- public int id { get; set; }
- public string title { get; set; }
- public string character { get; set; }
- public string original_title { get; set; }
- public string poster_path { get; set; }
- public string release_date { get; set; }
- public bool adult { get; set; }
- }
-
- public class Crew
- {
- public int id { get; set; }
- public string title { get; set; }
- public string original_title { get; set; }
- public string department { get; set; }
- public string job { get; set; }
- public string poster_path { get; set; }
- public string release_date { get; set; }
- public bool adult { get; set; }
- }
-
- public class Credits
- {
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- }
-
- public class Profile
- {
- public string file_path { get; set; }
- public int width { get; set; }
- public int height { get; set; }
- public object iso_639_1 { get; set; }
- public double aspect_ratio { get; set; }
- }
-
- public class Images
- {
- public List<Profile> profiles { get; set; }
- }
-
- public class ExternalIds
- {
- public string imdb_id { get; set; }
- public string freebase_mid { get; set; }
- public string freebase_id { get; set; }
- public int tvrage_id { get; set; }
- }
-
- public class PersonResult
- {
- public bool adult { get; set; }
- public List<object> also_known_as { get; set; }
- public string biography { get; set; }
- public string birthday { get; set; }
- public string deathday { get; set; }
- public string homepage { get; set; }
- public int id { get; set; }
- public string imdb_id { get; set; }
- public string name { get; set; }
- public string place_of_birth { get; set; }
- public double popularity { get; set; }
- public string profile_path { get; set; }
- public Credits credits { get; set; }
- public Images images { get; set; }
- public ExternalIds external_ids { get; set; }
- }
-
- #endregion
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/People/PersonMetadataService.cs b/MediaBrowser.Providers/People/PersonMetadataService.cs
index adbeb94ea..fe6d1d4d3 100644
--- a/MediaBrowser.Providers/People/PersonMetadataService.cs
+++ b/MediaBrowser.Providers/People/PersonMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.People
{
public class PersonMetadataService : MetadataService<Person, PersonLookupInfo>
{
- protected override void MergeData(MetadataResult<Person> source, MetadataResult<Person> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public PersonMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PersonMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public PersonMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Person> source, MetadataResult<Person> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/People/TvdbPersonImageProvider.cs b/MediaBrowser.Providers/People/TvdbPersonImageProvider.cs
deleted file mode 100644
index 8c8b99e89..000000000
--- a/MediaBrowser.Providers/People/TvdbPersonImageProvider.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.TV.TheTVDB;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-
-namespace MediaBrowser.Providers.People
-{
- public class TvdbPersonImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbPersonImageProvider(ILibraryManager libraryManager, IHttpClient httpClient, ILogger<TvdbPersonImageProvider> logger, TvDbClientManager tvDbClientManager)
- {
- _libraryManager = libraryManager;
- _httpClient = httpClient;
- _logger = logger;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheTVDB";
-
- public bool Supports(BaseItem item)
- {
- return item is Person;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var seriesWithPerson = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { typeof(Series).Name },
- PersonIds = new[] { item.Id },
- DtoOptions = new DtoOptions(false)
- {
- EnableImages = false
- }
-
- }).Cast<Series>()
- .Where(i => TvdbSeriesProvider.IsValidSeries(i.ProviderIds))
- .ToList();
-
- var infos = (await Task.WhenAll(seriesWithPerson.Select(async i =>
- await GetImageFromSeriesData(i, item.Name, cancellationToken).ConfigureAwait(false)))
- .ConfigureAwait(false))
- .Where(i => i != null)
- .Take(1);
-
- return infos;
- }
-
- private async Task<RemoteImageInfo> GetImageFromSeriesData(Series series, string personName, CancellationToken cancellationToken)
- {
- var tvdbId = Convert.ToInt32(series.GetProviderId(MetadataProviders.Tvdb));
-
- try
- {
- var actorsResult = await _tvDbClientManager
- .GetActorsAsync(tvdbId, series.GetPreferredMetadataLanguage(), cancellationToken)
- .ConfigureAwait(false);
- var actor = actorsResult.Data.FirstOrDefault(a =>
- string.Equals(a.Name, personName, StringComparison.OrdinalIgnoreCase) &&
- !string.IsNullOrEmpty(a.Image));
- if (actor == null)
- {
- return null;
- }
-
- return new RemoteImageInfo
- {
- Url = TvdbUtils.BannerUrl + actor.Image,
- Type = ImageType.Primary,
- ProviderName = Name
- };
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve actor {ActorName} from series {SeriesTvdbId}", personName, tvdbId);
- return null;
- }
- }
-
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
index 993581cca..60ed96452 100644
--- a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Photos
{
public class PhotoAlbumMetadataService : MetadataService<PhotoAlbum, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<PhotoAlbum> source, MetadataResult<PhotoAlbum> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public PhotoAlbumMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PhotoAlbumMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public PhotoAlbumMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<PhotoAlbum> source, MetadataResult<PhotoAlbum> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
index b739c5765..cbbb433c0 100644
--- a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Photos
{
public class PhotoMetadataService : MetadataService<Photo, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<Photo> source, MetadataResult<Photo> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public PhotoMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PhotoMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public PhotoMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Photo> source, MetadataResult<Photo> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
index dacb63f84..8baca30c6 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
@@ -1,3 +1,7 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -8,7 +12,6 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
using PlaylistsNET.Content;
@@ -20,17 +23,18 @@ namespace MediaBrowser.Providers.Playlists
IPreRefreshProvider,
IHasItemChangeMonitor
{
- private ILogger _logger;
- private IFileSystem _fileSystem;
+ private readonly ILogger<PlaylistItemsProvider> _logger;
- public PlaylistItemsProvider(IFileSystem fileSystem, ILogger logger)
+ public PlaylistItemsProvider(ILogger<PlaylistItemsProvider> logger)
{
- _fileSystem = fileSystem;
_logger = logger;
}
public string Name => "Playlist Reader";
+ // Run last
+ public int Order => 100;
+
public Task<ItemUpdateType> FetchAsync(Playlist item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
var path = item.Path;
@@ -61,18 +65,22 @@ namespace MediaBrowser.Providers.Playlists
{
return GetWplItems(stream);
}
+
if (string.Equals(".zpl", extension, StringComparison.OrdinalIgnoreCase))
{
return GetZplItems(stream);
}
+
if (string.Equals(".m3u", extension, StringComparison.OrdinalIgnoreCase))
{
return GetM3uItems(stream);
}
+
if (string.Equals(".m3u8", extension, StringComparison.OrdinalIgnoreCase))
{
return GetM3u8Items(stream);
}
+
if (string.Equals(".pls", extension, StringComparison.OrdinalIgnoreCase))
{
return GetPlsItems(stream);
@@ -95,7 +103,7 @@ namespace MediaBrowser.Providers.Playlists
private IEnumerable<LinkedChild> GetM3u8Items(Stream stream)
{
- var content = new M3u8Content();
+ var content = new M3uContent();
var playlist = content.GetFromStream(stream);
return playlist.PlaylistEntries.Select(i => new LinkedChild
@@ -157,7 +165,5 @@ namespace MediaBrowser.Providers.Playlists
return false;
}
- // Run last
- public int Order => 100;
}
}
diff --git a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
index 30ce5c64c..5262919d5 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -13,12 +15,31 @@ namespace MediaBrowser.Providers.Playlists
{
public class PlaylistMetadataService : MetadataService<Playlist, ItemLookupInfo>
{
- protected override IList<BaseItem> GetChildrenForMetadataUpdates(Playlist item)
+ public PlaylistMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PlaylistMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- return item.GetLinkedChildren();
}
- protected override void MergeData(MetadataResult<Playlist> source, MetadataResult<Playlist> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingOfficialRatingFromChildren => true;
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
+
+ /// <inheritdoc />
+ protected override IList<BaseItem> GetChildrenForMetadataUpdates(Playlist item)
+ => item.GetLinkedChildren();
+
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Playlist> source, MetadataResult<Playlist> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -32,15 +53,5 @@ namespace MediaBrowser.Providers.Playlists
targetItem.Shares = sourceItem.Shares;
}
}
-
- public PlaylistMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
-
- protected override bool EnableUpdatingGenresFromChildren => true;
-
- protected override bool EnableUpdatingOfficialRatingFromChildren => true;
-
- protected override bool EnableUpdatingStudiosFromChildren => true;
}
}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumExternalId.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumExternalId.cs
new file mode 100644
index 000000000..3a400575b
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class AudioDbAlbumExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "TheAudioDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.AudioDbAlbum.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => null;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.theaudiodb.com/album/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is MusicAlbum;
+ }
+}
diff --git a/MediaBrowser.Providers/Music/AudioDbAlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumImageProvider.cs
index c2a8431cd..ad0247fb2 100644
--- a/MediaBrowser.Providers/Music/AudioDbAlbumImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumImageProvider.cs
@@ -1,30 +1,45 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
+using System.IO;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Plugins.AudioDb
{
public class AudioDbAlbumImageProvider : IRemoteImageProvider, IHasOrder
{
private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IJsonSerializer json)
+ public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory)
{
_config = config;
- _httpClient = httpClient;
- _json = json;
+ _httpClientFactory = httpClientFactory;
}
+ /// <inheritdoc />
+ public string Name => "TheAudioDB";
+
+ /// <inheritdoc />
+ // After embedded and fanart
+ public int Order => 2;
+
+ /// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType>
@@ -34,9 +49,10 @@ namespace MediaBrowser.Providers.Music
};
}
+ /// <inheritdoc />
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
- var id = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
+ var id = item.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup);
if (!string.IsNullOrWhiteSpace(id))
{
@@ -44,7 +60,8 @@ namespace MediaBrowser.Providers.Music
var path = AudioDbAlbumProvider.GetAlbumInfoPath(_config.ApplicationPaths, id);
- var obj = _json.DeserializeFromFile<AudioDbAlbumProvider.RootObject>(path);
+ await using FileStream jsonStream = AsyncFile.OpenRead(path);
+ var obj = await JsonSerializer.DeserializeAsync<AudioDbAlbumProvider.RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (obj != null && obj.album != null && obj.album.Count > 0)
{
@@ -82,22 +99,15 @@ namespace MediaBrowser.Providers.Music
return list;
}
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ return httpClient.GetAsync(url, cancellationToken);
}
- public string Name => "TheAudioDB";
- // After embedded and fanart
- public int Order => 2;
-
+ /// <inheritdoc />
public bool Supports(BaseItem item)
- {
- return item is MusicAlbum;
- }
+ => item is MusicAlbum;
}
}
diff --git a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumProvider.cs
index 7ccf7cffa..43f30824b 100644
--- a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumProvider.cs
@@ -1,9 +1,17 @@
+#nullable disable
+
+#pragma warning disable CA1002, CS1591, SA1300
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
@@ -13,40 +21,45 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
+using MediaBrowser.Providers.Music;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Plugins.AudioDb
{
public class AudioDbAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
{
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+#pragma warning disable SA1401, CA2211
public static AudioDbAlbumProvider Current;
+#pragma warning restore SA1401, CA2211
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public AudioDbAlbumProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClient httpClient, IJsonSerializer json)
+ public AudioDbAlbumProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory)
{
_config = config;
_fileSystem = fileSystem;
- _httpClient = httpClient;
- _json = json;
+ _httpClientFactory = httpClientFactory;
Current = this;
}
+ /// <inheritdoc />
+ public string Name => "TheAudioDB";
+
+ /// <inheritdoc />
+ // After music brainz
+ public int Order => 1;
+
+ /// <inheritdoc />
public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
- {
- return Task.FromResult((IEnumerable<RemoteSearchResult>)new List<RemoteSearchResult>());
- }
+ => Task.FromResult(Enumerable.Empty<RemoteSearchResult>());
+ /// <inheritdoc />
public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<MusicAlbum>();
-
var id = info.GetReleaseGroupId();
if (!string.IsNullOrWhiteSpace(id))
@@ -55,7 +68,8 @@ namespace MediaBrowser.Providers.Music
var path = GetAlbumInfoPath(_config.ApplicationPaths, id);
- var obj = _json.DeserializeFromFile<RootObject>(path);
+ await using FileStream jsonStream = AsyncFile.OpenRead(path);
+ var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (obj != null && obj.album != null && obj.album.Count > 0)
{
@@ -70,6 +84,11 @@ namespace MediaBrowser.Providers.Music
private void ProcessResult(MusicAlbum item, Album result, string preferredLanguage)
{
+ if (Plugin.Instance.Configuration.ReplaceAlbumName && !string.IsNullOrWhiteSpace(result.strAlbum))
+ {
+ item.Album = result.strAlbum;
+ }
+
if (!string.IsNullOrWhiteSpace(result.strArtist))
{
item.AlbumArtists = new string[] { result.strArtist };
@@ -77,7 +96,7 @@ namespace MediaBrowser.Providers.Music
if (!string.IsNullOrEmpty(result.intYearReleased))
{
- item.ProductionYear = int.Parse(result.intYearReleased, _usCulture);
+ item.ProductionYear = int.Parse(result.intYearReleased, CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(result.strGenre))
@@ -85,11 +104,11 @@ namespace MediaBrowser.Providers.Music
item.Genres = new[] { result.strGenre };
}
- item.SetProviderId(MetadataProviders.AudioDbArtist, result.idArtist);
- item.SetProviderId(MetadataProviders.AudioDbAlbum, result.idAlbum);
+ item.SetProviderId(MetadataProvider.AudioDbArtist, result.idArtist);
+ item.SetProviderId(MetadataProvider.AudioDbAlbum, result.idAlbum);
- item.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, result.strMusicBrainzArtistID);
- item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, result.strMusicBrainzID);
+ item.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, result.strMusicBrainzArtistID);
+ item.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, result.strMusicBrainzID);
string overview = null;
@@ -126,8 +145,6 @@ namespace MediaBrowser.Providers.Music
item.Overview = (overview ?? string.Empty).StripHtml();
}
- public string Name => "TheAudioDB";
-
internal Task EnsureInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
var xmlPath = GetAlbumInfoPath(_config.ApplicationPaths, musicBrainzReleaseGroupId);
@@ -155,21 +172,14 @@ namespace MediaBrowser.Providers.Music
Directory.CreateDirectory(Path.GetDirectoryName(path));
- using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- }, "GET").ConfigureAwait(false))
- {
- using (var response = httpResponse.Content)
- {
- using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
- }
- }
- }
+ var fileStreamOptions = AsyncFile.WriteOptions;
+ fileStreamOptions.Mode = FileMode.Create;
+ fileStreamOptions.PreallocationSize = stream.Length;
+ await using var xmlFileStream = new FileStream(path, fileStreamOptions);
+ await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false);
}
private static string GetAlbumDataPath(IApplicationPaths appPaths, string musicBrainzReleaseGroupId)
@@ -192,48 +202,90 @@ namespace MediaBrowser.Providers.Music
return Path.Combine(dataPath, "album.json");
}
- // After music brainz
- public int Order => 1;
+ /// <inheritdoc />
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ throw new NotImplementedException();
+ }
+
+#pragma warning disable CA1034, CA2227
public class Album
{
public string idAlbum { get; set; }
+
public string idArtist { get; set; }
+
public string strAlbum { get; set; }
+
public string strArtist { get; set; }
+
public string intYearReleased { get; set; }
+
public string strGenre { get; set; }
+
public string strSubGenre { get; set; }
+
public string strReleaseFormat { get; set; }
+
public string intSales { get; set; }
+
public string strAlbumThumb { get; set; }
+
public string strAlbumCDart { get; set; }
+
public string strDescriptionEN { get; set; }
+
public string strDescriptionDE { get; set; }
+
public string strDescriptionFR { get; set; }
+
public string strDescriptionCN { get; set; }
+
public string strDescriptionIT { get; set; }
+
public string strDescriptionJP { get; set; }
+
public string strDescriptionRU { get; set; }
+
public string strDescriptionES { get; set; }
+
public string strDescriptionPT { get; set; }
+
public string strDescriptionSE { get; set; }
+
public string strDescriptionNL { get; set; }
+
public string strDescriptionHU { get; set; }
+
public string strDescriptionNO { get; set; }
+
public string strDescriptionIL { get; set; }
+
public string strDescriptionPL { get; set; }
+
public object intLoved { get; set; }
+
public object intScore { get; set; }
+
public string strReview { get; set; }
+
public object strMood { get; set; }
+
public object strTheme { get; set; }
+
public object strSpeed { get; set; }
+
public object strLocation { get; set; }
+
public string strMusicBrainzID { get; set; }
+
public string strMusicBrainzArtistID { get; set; }
+
public object strItunesID { get; set; }
+
public object strAmazonID { get; set; }
+
public string strLocked { get; set; }
}
@@ -241,10 +293,5 @@ namespace MediaBrowser.Providers.Music
{
public List<Album> album { get; set; }
}
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- throw new NotImplementedException();
- }
}
}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistExternalId.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistExternalId.cs
new file mode 100644
index 000000000..b9e57eb26
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class AudioDbArtistExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "TheAudioDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.AudioDbArtist.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Artist;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.theaudiodb.com/artist/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is MusicArtist;
+ }
+}
diff --git a/MediaBrowser.Providers/Music/AudioDbArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistImageProvider.cs
index c59e9551c..9c2447660 100644
--- a/MediaBrowser.Providers/Music/AudioDbArtistImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistImageProvider.cs
@@ -1,30 +1,45 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
+using System.IO;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Plugins.AudioDb
{
public class AudioDbArtistImageProvider : IRemoteImageProvider, IHasOrder
{
private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- public AudioDbArtistImageProvider(IServerConfigurationManager config, IJsonSerializer json, IHttpClient httpClient)
+ public AudioDbArtistImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory)
{
_config = config;
- _json = json;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
}
+ /// <inheritdoc />
+ public string Name => "TheAudioDB";
+
+ /// <inheritdoc />
+ // After fanart
+ public int Order => 1;
+
+ /// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType>
@@ -36,9 +51,10 @@ namespace MediaBrowser.Providers.Music
};
}
+ /// <inheritdoc />
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
- var id = item.GetProviderId(MetadataProviders.MusicBrainzArtist);
+ var id = item.GetProviderId(MetadataProvider.MusicBrainzArtist);
if (!string.IsNullOrWhiteSpace(id))
{
@@ -46,7 +62,8 @@ namespace MediaBrowser.Providers.Music
var path = AudioDbArtistProvider.GetArtistInfoPath(_config.ApplicationPaths, id);
- var obj = _json.DeserializeFromFile<AudioDbArtistProvider.RootObject>(path);
+ await using FileStream jsonStream = AsyncFile.OpenRead(path);
+ var obj = await JsonSerializer.DeserializeAsync<AudioDbArtistProvider.RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (obj != null && obj.artists != null && obj.artists.Count > 0)
{
@@ -124,22 +141,14 @@ namespace MediaBrowser.Providers.Music
return list;
}
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ return httpClient.GetAsync(url, cancellationToken);
}
- public string Name => "TheAudioDB";
-
+ /// <inheritdoc />
public bool Supports(BaseItem item)
- {
- return item is MusicArtist;
- }
- // After fanart
- public int Order => 1;
+ => item is MusicArtist;
}
}
diff --git a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistProvider.cs
index 2540a6047..538dc67c4 100644
--- a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbArtistProvider.cs
@@ -1,8 +1,16 @@
+#nullable disable
+
+#pragma warning disable CA1034, CS1591, CA1002, SA1028, SA1300
+
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
@@ -12,40 +20,45 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
+using MediaBrowser.Providers.Music;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Plugins.AudioDb
{
public class AudioDbArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>, IHasOrder
{
- private readonly IServerConfigurationManager _config;
- private readonly IFileSystem _fileSystem;
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
-
- public static AudioDbArtistProvider Current;
-
private const string ApiKey = "195003";
public const string BaseUrl = "https://www.theaudiodb.com/api/v1/json/" + ApiKey;
- public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClient httpClient, IJsonSerializer json)
+ private readonly IServerConfigurationManager _config;
+ private readonly IFileSystem _fileSystem;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+
+ public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory)
{
_config = config;
_fileSystem = fileSystem;
- _httpClient = httpClient;
- _json = json;
+ _httpClientFactory = httpClientFactory;
Current = this;
}
+ public static AudioDbArtistProvider Current { get; private set; }
+
+ /// <inheritdoc />
+ public string Name => "TheAudioDB";
+
+ /// <inheritdoc />
+ // After musicbrainz
+ public int Order => 1;
+
+ /// <inheritdoc />
public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
- {
- return Task.FromResult((IEnumerable<RemoteSearchResult>)new List<RemoteSearchResult>());
- }
+ => Task.FromResult(Enumerable.Empty<RemoteSearchResult>());
+ /// <inheritdoc />
public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<MusicArtist>();
-
var id = info.GetMusicBrainzArtistId();
if (!string.IsNullOrWhiteSpace(id))
@@ -54,7 +67,8 @@ namespace MediaBrowser.Providers.Music
var path = GetArtistInfoPath(_config.ApplicationPaths, id);
- var obj = _json.DeserializeFromFile<RootObject>(path);
+ await using FileStream jsonStream = AsyncFile.OpenRead(path);
+ var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
if (obj != null && obj.artists != null && obj.artists.Count > 0)
{
@@ -69,15 +83,15 @@ namespace MediaBrowser.Providers.Music
private void ProcessResult(MusicArtist item, Artist result, string preferredLanguage)
{
- //item.HomePageUrl = result.strWebsite;
+ // item.HomePageUrl = result.strWebsite;
if (!string.IsNullOrEmpty(result.strGenre))
{
item.Genres = new[] { result.strGenre };
}
- item.SetProviderId(MetadataProviders.AudioDbArtist, result.idArtist);
- item.SetProviderId(MetadataProviders.MusicBrainzArtist, result.strMusicBrainzID);
+ item.SetProviderId(MetadataProvider.AudioDbArtist, result.idArtist);
+ item.SetProviderId(MetadataProvider.MusicBrainzArtist, result.strMusicBrainzID);
string overview = null;
@@ -114,20 +128,16 @@ namespace MediaBrowser.Providers.Music
item.Overview = (overview ?? string.Empty).StripHtml();
}
- public string Name => "TheAudioDB";
-
internal Task EnsureArtistInfo(string musicBrainzId, CancellationToken cancellationToken)
{
var xmlPath = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId);
var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath);
- if (fileInfo.Exists)
+ if (fileInfo.Exists
+ && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
{
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
+ return Task.CompletedTask;
}
return DownloadArtistInfo(musicBrainzId, cancellationToken);
@@ -141,24 +151,16 @@ namespace MediaBrowser.Providers.Music
var path = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId);
- using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = true
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- }, "GET").ConfigureAwait(false))
- {
- using (var response = httpResponse.Content)
- {
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
- using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
- }
- }
- }
+ var fileStreamOptions = AsyncFile.WriteOptions;
+ fileStreamOptions.Mode = FileMode.Create;
+ fileStreamOptions.PreallocationSize = stream.Length;
+ await using var xmlFileStream = new FileStream(path, fileStreamOptions);
+ await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -168,11 +170,7 @@ namespace MediaBrowser.Providers.Music
/// <param name="musicBrainzArtistId">The music brainz artist identifier.</param>
/// <returns>System.String.</returns>
private static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
- {
- var dataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
-
- return dataPath;
- }
+ => Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
/// <summary>
/// Gets the artist data path.
@@ -180,11 +178,7 @@ namespace MediaBrowser.Providers.Music
/// <param name="appPaths">The application paths.</param>
/// <returns>System.String.</returns>
private static string GetArtistDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "audiodb-artist");
-
- return dataPath;
- }
+ => Path.Combine(appPaths.CachePath, "audiodb-artist");
internal static string GetArtistInfoPath(IApplicationPaths appPaths, string musicBrainzArtistId)
{
@@ -193,61 +187,101 @@ namespace MediaBrowser.Providers.Music
return Path.Combine(dataPath, "artist.json");
}
+ /// <inheritdoc />
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ throw new NotImplementedException();
+ }
+
public class Artist
{
public string idArtist { get; set; }
+
public string strArtist { get; set; }
+
public string strArtistAlternate { get; set; }
+
public object idLabel { get; set; }
+
public string intFormedYear { get; set; }
+
public string intBornYear { get; set; }
+
public object intDiedYear { get; set; }
+
public object strDisbanded { get; set; }
+
public string strGenre { get; set; }
+
public string strSubGenre { get; set; }
+
public string strWebsite { get; set; }
+
public string strFacebook { get; set; }
+
public string strTwitter { get; set; }
+
public string strBiographyEN { get; set; }
+
public string strBiographyDE { get; set; }
+
public string strBiographyFR { get; set; }
+
public string strBiographyCN { get; set; }
+
public string strBiographyIT { get; set; }
+
public string strBiographyJP { get; set; }
+
public string strBiographyRU { get; set; }
+
public string strBiographyES { get; set; }
+
public string strBiographyPT { get; set; }
+
public string strBiographySE { get; set; }
+
public string strBiographyNL { get; set; }
+
public string strBiographyHU { get; set; }
+
public string strBiographyNO { get; set; }
+
public string strBiographyIL { get; set; }
+
public string strBiographyPL { get; set; }
+
public string strGender { get; set; }
+
public string intMembers { get; set; }
+
public string strCountry { get; set; }
+
public string strCountryCode { get; set; }
+
public string strArtistThumb { get; set; }
+
public string strArtistLogo { get; set; }
+
public string strArtistFanart { get; set; }
+
public string strArtistFanart2 { get; set; }
+
public string strArtistFanart3 { get; set; }
+
public string strArtistBanner { get; set; }
+
public string strMusicBrainzID { get; set; }
+
public object strLastFMChart { get; set; }
+
public string strLocked { get; set; }
}
+#pragma warning disable CA2227
public class RootObject
{
public List<Artist> artists { get; set; }
}
- // After musicbrainz
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- throw new NotImplementedException();
- }
}
}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherAlbumExternalId.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherAlbumExternalId.cs
new file mode 100644
index 000000000..f8f6253ff
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherAlbumExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class AudioDbOtherAlbumExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "TheAudioDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.AudioDbAlbum.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Album;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.theaudiodb.com/album/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherArtistExternalId.cs b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherArtistExternalId.cs
new file mode 100644
index 000000000..fd598c918
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AudioDbOtherArtistExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class AudioDbOtherArtistExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "TheAudioDb";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.AudioDbArtist.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.OtherArtist;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "https://www.theaudiodb.com/artist/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs
new file mode 100644
index 000000000..d61ec6cb1
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs
@@ -0,0 +1,11 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class PluginConfiguration : BasePluginConfiguration
+ {
+ public bool ReplaceAlbumName { get; set; }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html
new file mode 100644
index 000000000..eab252005
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>AudioDB</title>
+</head>
+<body>
+ <div data-role="page" class="page type-interior pluginConfigurationPage configPage" data-require="emby-input,emby-button,emby-checkbox">
+ <div data-role="content">
+ <div class="content-primary">
+ <form class="configForm">
+ <label class="checkboxContainer">
+ <input is="emby-checkbox" type="checkbox" id="replaceAlbumName" />
+ <span>When an album is found during a metadata search, replace the name with the value on the server.</span>
+ </label>
+ <br />
+ <div>
+ <button is="emby-button" type="submit" class="raised button-submit block"><span>Save</span></button>
+ </div>
+ </form>
+ </div>
+ </div>
+ <script type="text/javascript">
+ var PluginConfig = {
+ pluginId: "a629c0da-fac5-4c7e-931a-7174223f14c8"
+ };
+
+ document.querySelector('.configPage')
+ .addEventListener('pageshow', function () {
+ Dashboard.showLoadingMsg();
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ document.querySelector('#replaceAlbumName').checked = config.ReplaceAlbumName;
+
+ Dashboard.hideLoadingMsg();
+ });
+ });
+
+ document.querySelector('.configForm')
+ .addEventListener('submit', function (e) {
+ Dashboard.showLoadingMsg();
+
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ config.ReplaceAlbumName = document.querySelector('#replaceAlbumName').checked;
+
+ ApiClient.updatePluginConfiguration(PluginConfig.pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult);
+ });
+
+ e.preventDefault();
+ return false;
+ });
+ </script>
+ </div>
+</body>
+</html>
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs b/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs
new file mode 100644
index 000000000..6c2ad0573
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs
@@ -0,0 +1,41 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.AudioDb
+{
+ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
+ {
+ public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ public static Plugin Instance { get; private set; }
+
+ public override Guid Id => new Guid("a629c0da-fac5-4c7e-931a-7174223f14c8");
+
+ public override string Name => "AudioDB";
+
+ public override string Description => "Get artist and album metadata or images from AudioDB.";
+
+ // TODO remove when plugin removed from server.
+ public override string ConfigurationFileName => "Jellyfin.Plugin.AudioDb.xml";
+
+ public IEnumerable<PluginPageInfo> GetPages()
+ {
+ yield return new PluginPageInfo
+ {
+ Name = Name,
+ EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs
new file mode 100644
index 000000000..9c27bd7d3
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs
@@ -0,0 +1,37 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Providers.Plugins.MusicBrainz
+{
+ public class PluginConfiguration : BasePluginConfiguration
+ {
+ private string _server = Plugin.DefaultServer;
+
+ private long _rateLimit = Plugin.DefaultRateLimit;
+
+ public string Server
+ {
+ get => _server;
+ set => _server = value.TrimEnd('/');
+ }
+
+ public long RateLimit
+ {
+ get => _rateLimit;
+ set
+ {
+ if (value < Plugin.DefaultRateLimit && _server == Plugin.DefaultServer)
+ {
+ _rateLimit = Plugin.DefaultRateLimit;
+ }
+ else
+ {
+ _rateLimit = value;
+ }
+ }
+ }
+
+ public bool ReplaceArtistName { get; set; }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html
new file mode 100644
index 000000000..6f1296bb7
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html
@@ -0,0 +1,77 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>MusicBrainz</title>
+</head>
+<body>
+ <div data-role="page" class="page type-interior pluginConfigurationPage musicBrainzConfigPage" data-require="emby-input,emby-button,emby-checkbox">
+ <div data-role="content">
+ <div class="content-primary">
+ <form class="musicBrainzConfigForm">
+ <div class="inputContainer">
+ <input is="emby-input" type="text" id="server" required label="Server" />
+ <div class="fieldDescription">This can be a mirror of the official server or even a custom server.</div>
+ </div>
+ <div class="inputContainer">
+ <input is="emby-input" type="number" id="rateLimit" pattern="[0-9]*" required min="0" max="10000" label="Rate Limit" />
+ <div class="fieldDescription">Span of time between requests in milliseconds. The official server is limited to one request every two seconds.</div>
+ </div>
+ <label class="checkboxContainer">
+ <input is="emby-checkbox" type="checkbox" id="replaceArtistName" />
+ <span>When an artist is found during a metadata search, replace the artist name with the value on the server.</span>
+ </label>
+ <br />
+ <div>
+ <button is="emby-button" type="submit" class="raised button-submit block"><span>Save</span></button>
+ </div>
+ </form>
+ </div>
+ </div>
+ <script type="text/javascript">
+ var MusicBrainzPluginConfig = {
+ uniquePluginId: "8c95c4d2-e50c-4fb0-a4f3-6c06ff0f9a1a"
+ };
+
+ document.querySelector('.musicBrainzConfigPage')
+ .addEventListener('pageshow', function () {
+ Dashboard.showLoadingMsg();
+ ApiClient.getPluginConfiguration(MusicBrainzPluginConfig.uniquePluginId).then(function (config) {
+ var server = document.querySelector('#server');
+ server.value = config.Server;
+ server.dispatchEvent(new Event('change', {
+ bubbles: true,
+ cancelable: false
+ }));
+
+ var rateLimit = document.querySelector('#rateLimit');
+ rateLimit.value = config.RateLimit;
+ rateLimit.dispatchEvent(new Event('change', {
+ bubbles: true,
+ cancelable: false
+ }));
+
+ document.querySelector('#replaceArtistName').checked = config.ReplaceArtistName;
+
+ Dashboard.hideLoadingMsg();
+ });
+ });
+
+ document.querySelector('.musicBrainzConfigForm')
+ .addEventListener('submit', function (e) {
+ Dashboard.showLoadingMsg();
+
+ ApiClient.getPluginConfiguration(MusicBrainzPluginConfig.uniquePluginId).then(function (config) {
+ config.Server = document.querySelector('#server').value;
+ config.RateLimit = document.querySelector('#rateLimit').value;
+ config.ReplaceArtistName = document.querySelector('#replaceArtistName').checked;
+
+ ApiClient.updatePluginConfiguration(MusicBrainzPluginConfig.uniquePluginId, config).then(Dashboard.processPluginConfigurationUpdateResult);
+ });
+
+ e.preventDefault();
+ return false;
+ });
+ </script>
+ </div>
+</body>
+</html>
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumArtistExternalId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumArtistExternalId.cs
new file mode 100644
index 000000000..c54cdda3d
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumArtistExternalId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzAlbumArtistExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzAlbumArtist.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.AlbumArtist;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumExternalId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumExternalId.cs
new file mode 100644
index 000000000..8f7fadd06
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumExternalId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzAlbumExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzAlbum.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Album;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/release/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum;
+ }
+}
diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs
index e4bb52217..5559b9db6 100644
--- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs
@@ -1,64 +1,93 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1401
+
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
-using MediaBrowser.Common;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Xml;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Music
{
- public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
+ public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder, IDisposable
{
- internal static MusicBrainzAlbumProvider Current;
+ /// <summary>
+ /// For each single MB lookup/search, this is the maximum number of
+ /// attempts that shall be made whilst receiving a 503 Server
+ /// Unavailable (indicating throttled) response.
+ /// </summary>
+ private const uint MusicBrainzQueryAttempts = 5u;
+
+ /// <summary>
+ /// The Jellyfin user-agent is unrestricted but source IP must not exceed
+ /// one request per second, therefore we rate limit to avoid throttling.
+ /// Be prudent, use a value slightly above the minimun required.
+ /// https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting.
+ /// </summary>
+ private readonly long _musicBrainzQueryIntervalMs;
+
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILogger<MusicBrainzAlbumProvider> _logger;
- private readonly IHttpClient _httpClient;
- private readonly IApplicationHost _appHost;
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
- private readonly IXmlReaderSettingsFactory _xmlSettings;
+ private readonly string _musicBrainzBaseUrl;
- public static string MusicBrainzBaseUrl = "https://www.musicbrainz.org";
+ private SemaphoreSlim _apiRequestLock = new SemaphoreSlim(1, 1);
+ private Stopwatch _stopWatchMusicBrainz = new Stopwatch();
- public MusicBrainzAlbumProvider(IHttpClient httpClient, IApplicationHost appHost, ILogger logger, IJsonSerializer json, IXmlReaderSettingsFactory xmlSettings)
+ public MusicBrainzAlbumProvider(
+ IHttpClientFactory httpClientFactory,
+ ILogger<MusicBrainzAlbumProvider> logger)
{
- _httpClient = httpClient;
- _appHost = appHost;
+ _httpClientFactory = httpClientFactory;
_logger = logger;
- _json = json;
- _xmlSettings = xmlSettings;
+
+ _musicBrainzBaseUrl = Plugin.Instance.Configuration.Server;
+ _musicBrainzQueryIntervalMs = Plugin.Instance.Configuration.RateLimit;
+
+ // Use a stopwatch to ensure we don't exceed the MusicBrainz rate limit
+ _stopWatchMusicBrainz.Start();
+
Current = this;
}
+ internal static MusicBrainzAlbumProvider Current { get; private set; }
+
+ /// <inheritdoc />
+ public string Name => "MusicBrainz";
+
+ /// <inheritdoc />
+ public int Order => 0;
+
+ /// <inheritdoc />
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
{
var releaseId = searchInfo.GetReleaseId();
var releaseGroupId = searchInfo.GetReleaseGroupId();
- string url = null;
- var isNameSearch = false;
- bool forceMusicBrainzProper = false;
+ string url;
if (!string.IsNullOrEmpty(releaseId))
{
- url = string.Format("/ws/2/release/?query=reid:{0}", releaseId);
+ url = "/ws/2/release/?query=reid:" + releaseId.ToString(CultureInfo.InvariantCulture);
}
else if (!string.IsNullOrEmpty(releaseGroupId))
{
- url = string.Format("/ws/2/release?release-group={0}", releaseGroupId);
- forceMusicBrainzProper = true;
+ url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
}
else
{
@@ -66,90 +95,87 @@ namespace MediaBrowser.Providers.Music
if (!string.IsNullOrWhiteSpace(artistMusicBrainzId))
{
- url = string.Format("/ws/2/release/?query=\"{0}\" AND arid:{1}",
+ url = string.Format(
+ CultureInfo.InvariantCulture,
+ "/ws/2/release/?query=\"{0}\" AND arid:{1}",
WebUtility.UrlEncode(searchInfo.Name),
artistMusicBrainzId);
}
else
{
- isNameSearch = true;
-
// I'm sure there is a better way but for now it resolves search for 12" Mixes
- var queryName = searchInfo.Name.Replace("\"", string.Empty);
+ var queryName = searchInfo.Name.Replace("\"", string.Empty, StringComparison.Ordinal);
- url = string.Format("/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
- WebUtility.UrlEncode(queryName),
- WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
+ url = string.Format(
+ CultureInfo.InvariantCulture,
+ "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
+ WebUtility.UrlEncode(queryName),
+ WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
}
}
if (!string.IsNullOrWhiteSpace(url))
{
- using (var response = await GetMusicBrainzResponse(url, isNameSearch, forceMusicBrainzProper, cancellationToken).ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- return GetResultsFromResponse(stream);
- }
- }
+ using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ return GetResultsFromResponse(stream);
}
- return new List<RemoteSearchResult>();
+ return Enumerable.Empty<RemoteSearchResult>();
}
- private List<RemoteSearchResult> GetResultsFromResponse(Stream stream)
+ private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream)
{
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings()
{
- var settings = _xmlSettings.Create(false);
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ using var reader = XmlReader.Create(oReader, settings);
+ var results = ReleaseResult.Parse(reader);
- using (var reader = XmlReader.Create(oReader, settings))
+ return results.Select(i =>
+ {
+ var result = new RemoteSearchResult
{
- var results = ReleaseResult.Parse(reader);
+ Name = i.Title,
+ ProductionYear = i.Year
+ };
- return results.Select(i =>
+ if (i.Artists.Count > 0)
+ {
+ result.AlbumArtist = new RemoteSearchResult
{
- var result = new RemoteSearchResult
- {
- Name = i.Title,
- ProductionYear = i.Year
- };
-
- if (i.Artists.Count > 0)
- {
- result.AlbumArtist = new RemoteSearchResult
- {
- SearchProviderName = Name,
- Name = i.Artists[0].Item1
- };
+ SearchProviderName = Name,
+ Name = i.Artists[0].Item1
+ };
- result.AlbumArtist.SetProviderId(MetadataProviders.MusicBrainzArtist, i.Artists[0].Item2);
- }
-
- if (!string.IsNullOrWhiteSpace(i.ReleaseId))
- {
- result.SetProviderId(MetadataProviders.MusicBrainzAlbum, i.ReleaseId);
- }
- if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId))
- {
- result.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, i.ReleaseGroupId);
- }
+ result.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, i.Artists[0].Item2);
+ }
- return result;
+ if (!string.IsNullOrWhiteSpace(i.ReleaseId))
+ {
+ result.SetProviderId(MetadataProvider.MusicBrainzAlbum, i.ReleaseId);
+ }
- }).ToList();
+ if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId))
+ {
+ result.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, i.ReleaseGroupId);
}
- }
+
+ return result;
+ });
}
- public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo id, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
{
- var releaseId = id.GetReleaseId();
- var releaseGroupId = id.GetReleaseGroupId();
+ var releaseId = info.GetReleaseId();
+ var releaseGroupId = info.GetReleaseGroupId();
var result = new MetadataResult<MusicAlbum>
{
@@ -165,9 +191,9 @@ namespace MediaBrowser.Providers.Music
if (string.IsNullOrWhiteSpace(releaseId))
{
- var artistMusicBrainzId = id.GetMusicBrainzArtistId();
+ var artistMusicBrainzId = info.GetMusicBrainzArtistId();
- var releaseResult = await GetReleaseResult(artistMusicBrainzId, id.GetAlbumArtist(), id.Name, cancellationToken).ConfigureAwait(false);
+ var releaseResult = await GetReleaseResult(artistMusicBrainzId, info.GetAlbumArtist(), info.Name, cancellationToken).ConfigureAwait(false);
if (releaseResult != null)
{
@@ -204,20 +230,18 @@ namespace MediaBrowser.Providers.Music
{
if (!string.IsNullOrEmpty(releaseId))
{
- result.Item.SetProviderId(MetadataProviders.MusicBrainzAlbum, releaseId);
+ result.Item.SetProviderId(MetadataProvider.MusicBrainzAlbum, releaseId);
}
if (!string.IsNullOrEmpty(releaseGroupId))
{
- result.Item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, releaseGroupId);
+ result.Item.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, releaseGroupId);
}
}
return result;
}
- public string Name => "MusicBrainz";
-
private Task<ReleaseResult> GetReleaseResult(string artistMusicBrainId, string artistName, string albumName, CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(artistMusicBrainId))
@@ -235,245 +259,51 @@ namespace MediaBrowser.Providers.Music
private async Task<ReleaseResult> GetReleaseResult(string albumName, string artistId, CancellationToken cancellationToken)
{
- var url = string.Format("/ws/2/release/?query=\"{0}\" AND arid:{1}",
+ var url = string.Format(
+ CultureInfo.InvariantCulture,
+ "/ws/2/release/?query=\"{0}\" AND arid:{1}",
WebUtility.UrlEncode(albumName),
artistId);
- using (var response = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false))
+ using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings
{
- using (var stream = response.Content)
- {
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
- {
- var settings = _xmlSettings.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- using (var reader = XmlReader.Create(oReader, settings))
- {
- return ReleaseResult.Parse(reader).FirstOrDefault();
- }
- }
- }
- }
+ using var reader = XmlReader.Create(oReader, settings);
+ return ReleaseResult.Parse(reader).FirstOrDefault();
}
private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
{
- var url = string.Format("/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
+ var url = string.Format(
+ CultureInfo.InvariantCulture,
+ "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
WebUtility.UrlEncode(albumName),
WebUtility.UrlEncode(artistName));
- using (var response = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
- {
- var settings = _xmlSettings.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
-
- using (var reader = XmlReader.Create(oReader, settings))
- {
- return ReleaseResult.Parse(reader).FirstOrDefault();
- }
- }
- }
- }
- }
-
- private class ReleaseResult
- {
- public string ReleaseId;
- public string ReleaseGroupId;
- public string Title;
- public string Overview;
- public int? Year;
-
- public List<ValueTuple<string, string>> Artists = new List<ValueTuple<string, string>>();
-
- public static List<ReleaseResult> Parse(XmlReader reader)
- {
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "release-list":
- {
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- using (var subReader = reader.ReadSubtree())
- {
- return ParseReleaseList(subReader);
- }
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- return new List<ReleaseResult>();
- }
-
- private static List<ReleaseResult> ParseReleaseList(XmlReader reader)
+ using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings()
{
- var list = new List<ReleaseResult>();
-
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "release":
- {
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- var releaseId = reader.GetAttribute("id");
-
- using (var subReader = reader.ReadSubtree())
- {
- var release = ParseRelease(subReader, releaseId);
- if (release != null)
- {
- list.Add(release);
- }
- }
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- return list;
- }
-
- private static ReleaseResult ParseRelease(XmlReader reader, string releaseId)
- {
- var result = new ReleaseResult
- {
- ReleaseId = releaseId
- };
-
- reader.MoveToContent();
- reader.Read();
-
- // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "title":
- {
- result.Title = reader.ReadElementContentAsString();
- break;
- }
- case "date":
- {
- var val = reader.ReadElementContentAsString();
- if (DateTime.TryParse(val, out var date))
- {
- result.Year = date.Year;
- }
- break;
- }
- case "annotation":
- {
- result.Overview = reader.ReadElementContentAsString();
- break;
- }
- case "release-group":
- {
- result.ReleaseGroupId = reader.GetAttribute("id");
- reader.Skip();
- break;
- }
- case "artist-credit":
- {
- // TODO
-
- /*
- * <artist-credit>
-<name-credit>
-<artist id="e225cda5-882d-4b80-b8a3-b36d7175b1ea">
-<name>SARCASTIC+ZOOKEEPER</name>
-<sort-name>SARCASTIC+ZOOKEEPER</sort-name>
-</artist>
-</name-credit>
-</artist-credit>
- */
- using (var subReader = reader.ReadSubtree())
- {
- var artist = ParseArtistCredit(subReader);
-
- if (!string.IsNullOrEmpty(artist.Item1))
- {
- result.Artists.Add(artist);
- }
- }
-
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- return result;
- }
+ using var reader = XmlReader.Create(oReader, settings);
+ return ReleaseResult.Parse(reader).FirstOrDefault();
}
- private static ValueTuple<string, string> ParseArtistCredit(XmlReader reader)
+ private static (string, string) ParseArtistCredit(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
@@ -488,17 +318,16 @@ namespace MediaBrowser.Providers.Music
switch (reader.Name)
{
case "name-credit":
- {
- using (var subReader = reader.ReadSubtree())
- {
- return ParseArtistNameCredit(subReader);
- }
- }
+ {
+ using var subReader = reader.ReadSubtree();
+ return ParseArtistNameCredit(subReader);
+ }
+
default:
- {
- reader.Skip();
- break;
- }
+ {
+ reader.Skip();
+ break;
+ }
}
}
else
@@ -507,7 +336,7 @@ namespace MediaBrowser.Providers.Music
}
}
- return new ValueTuple<string, string>();
+ return default;
}
private static (string, string) ParseArtistNameCredit(XmlReader reader)
@@ -527,11 +356,10 @@ namespace MediaBrowser.Providers.Music
case "artist":
{
var id = reader.GetAttribute("id");
- using (var subReader = reader.ReadSubtree())
- {
- return ParseArtistArtistCredit(subReader, id);
- }
+ using var subReader = reader.ReadSubtree();
+ return ParseArtistArtistCredit(subReader, id);
}
+
default:
{
reader.Skip();
@@ -548,7 +376,7 @@ namespace MediaBrowser.Providers.Music
return (null, null);
}
- private static ValueTuple<string, string> ParseArtistArtistCredit(XmlReader reader, string artistId)
+ private static (string name, string id) ParseArtistArtistCredit(XmlReader reader, string artistId)
{
reader.MoveToContent();
reader.Read();
@@ -569,6 +397,7 @@ namespace MediaBrowser.Providers.Music
name = reader.ReadElementContentAsString();
break;
}
+
default:
{
reader.Skip();
@@ -582,39 +411,28 @@ namespace MediaBrowser.Providers.Music
}
}
- return new ValueTuple<string, string>(name, artistId);
+ return (name, artistId);
}
private async Task<string> GetReleaseIdFromReleaseGroupId(string releaseGroupId, CancellationToken cancellationToken)
{
- var url = string.Format("/ws/2/release?release-group={0}", releaseGroupId);
+ var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
- using (var response = await GetMusicBrainzResponse(url, true, true, cancellationToken).ConfigureAwait(false))
+ using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings
{
- using (var stream = response.Content)
- {
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
- {
- var settings = _xmlSettings.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
-
- using (var reader = XmlReader.Create(oReader, settings))
- {
- var result = ReleaseResult.Parse(reader).FirstOrDefault();
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- if (result != null)
- {
- return result.ReleaseId;
- }
- }
- }
- }
- }
+ using var reader = XmlReader.Create(oReader, settings);
+ var result = ReleaseResult.Parse(reader).FirstOrDefault();
- return null;
+ return result?.ReleaseId;
}
/// <summary>
@@ -625,61 +443,56 @@ namespace MediaBrowser.Providers.Music
/// <returns>Task{System.String}.</returns>
private async Task<string> GetReleaseGroupFromReleaseId(string releaseEntryId, CancellationToken cancellationToken)
{
- var url = string.Format("/ws/2/release-group/?query=reid:{0}", releaseEntryId);
+ var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture);
- using (var response = await GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false))
+ using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings
{
- using (var stream = response.Content)
- {
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
- {
- var settings = _xmlSettings.Create(false);
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ using var reader = XmlReader.Create(oReader, settings);
+ reader.MoveToContent();
+ reader.Read();
- using (var reader = XmlReader.Create(oReader, settings))
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "release-group-list":
{
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ if (reader.IsEmptyElement)
{
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "release-group-list":
- {
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- using (var subReader = reader.ReadSubtree())
- {
- return GetFirstReleaseGroupId(subReader);
- }
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
+ reader.Read();
+ continue;
}
- return null;
+
+ using var subReader = reader.ReadSubtree();
+ return GetFirstReleaseGroupId(subReader);
+ }
+
+ default:
+ {
+ reader.Skip();
+ break;
}
}
}
+ else
+ {
+ reader.Read();
+ }
}
+
+ return null;
}
private string GetFirstReleaseGroupId(XmlReader reader)
@@ -698,6 +511,7 @@ namespace MediaBrowser.Providers.Music
{
return reader.GetAttribute("id");
}
+
default:
{
reader.Skip();
@@ -714,56 +528,259 @@ namespace MediaBrowser.Providers.Music
return null;
}
- internal Task<HttpResponseInfo> GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken)
- {
- return GetMusicBrainzResponse(url, isSearch, false, cancellationToken);
- }
-
/// <summary>
- /// Gets the music brainz response.
+ /// Makes request to MusicBrainz server and awaits a response.
+ /// A 503 Service Unavailable response indicates throttling to maintain a rate limit.
+ /// A number of retries shall be made in order to try and satisfy the request before
+ /// giving up and returning null.
/// </summary>
- internal async Task<HttpResponseInfo> GetMusicBrainzResponse(string url, bool isSearch, bool forceMusicBrainzProper, CancellationToken cancellationToken)
+ /// <param name="url">Address of MusicBrainz server.</param>
+ /// <param name="cancellationToken">CancellationToken to use for method.</param>
+ /// <returns>Returns response from MusicBrainz service.</returns>
+ internal async Task<HttpResponseMessage> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
{
- var urlInfo = new MbzUrl(MusicBrainzBaseUrl, 1000);
- var throttleMs = urlInfo.throttleMs;
+ await _apiRequestLock.WaitAsync(cancellationToken).ConfigureAwait(false);
- if (throttleMs > 0)
+ try
{
- // MusicBrainz is extremely adamant about limiting to one request per second
- _logger.LogDebug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture));
- await Task.Delay(throttleMs, cancellationToken).ConfigureAwait(false);
- }
+ HttpResponseMessage response;
+ var attempts = 0u;
+ var requestUrl = _musicBrainzBaseUrl.TrimEnd('/') + url;
- url = urlInfo.url.TrimEnd('/') + url;
+ do
+ {
+ attempts++;
+
+ if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
+ {
+ // MusicBrainz is extremely adamant about limiting to one request per second.
+ var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
+ await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
+ }
- var options = new HttpRequestOptions
+ // Write time since last request to debug log as evidence we're meeting rate limit
+ // requirement, before resetting stopwatch back to zero.
+ _logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
+ _stopWatchMusicBrainz.Restart();
+
+ using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
+ response = await _httpClientFactory
+ .CreateClient(NamedClient.MusicBrainz)
+ .SendAsync(request, cancellationToken)
+ .ConfigureAwait(false);
+
+ // We retry a finite number of times, and only whilst MB is indicating 503 (throttling).
+ }
+ while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
+
+ // Log error if unable to query MB database due to throttling.
+ if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
+ {
+ _logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, requestUrl);
+ }
+
+ return response;
+ }
+ finally
{
- Url = url,
- CancellationToken = cancellationToken,
- UserAgent = _appHost.ApplicationUserAgent,
- BufferContent = throttleMs > 0
- };
+ _apiRequestLock.Release();
+ }
+ }
- return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false);
+ /// <inheritdoc />
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ throw new NotImplementedException();
}
- public int Order => 0;
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _apiRequestLock?.Dispose();
+ }
+ }
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public void Dispose()
{
- throw new NotImplementedException();
+ Dispose(true);
+ GC.SuppressFinalize(this);
}
- internal class MbzUrl
+ private class ReleaseResult
{
- internal MbzUrl(string url, int throttleMs)
+ public string ReleaseId;
+ public string ReleaseGroupId;
+ public string Title;
+ public string Overview;
+ public int? Year;
+
+ public List<ValueTuple<string, string>> Artists = new List<ValueTuple<string, string>>();
+
+ public static IEnumerable<ReleaseResult> Parse(XmlReader reader)
+ {
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "release-list":
+ {
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ continue;
+ }
+
+ using var subReader = reader.ReadSubtree();
+ return ParseReleaseList(subReader).ToList();
+ }
+
+ default:
+ {
+ reader.Skip();
+ break;
+ }
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
+
+ return Enumerable.Empty<ReleaseResult>();
+ }
+
+ private static IEnumerable<ReleaseResult> ParseReleaseList(XmlReader reader)
{
- this.url = url;
- this.throttleMs = throttleMs;
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "release":
+ {
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ continue;
+ }
+
+ var releaseId = reader.GetAttribute("id");
+
+ using var subReader = reader.ReadSubtree();
+ var release = ParseRelease(subReader, releaseId);
+ if (release != null)
+ {
+ yield return release;
+ }
+
+ break;
+ }
+
+ default:
+ {
+ reader.Skip();
+ break;
+ }
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
}
- public string url { get; set; }
- public int throttleMs { get; set; }
+ private static ReleaseResult ParseRelease(XmlReader reader, string releaseId)
+ {
+ var result = new ReleaseResult
+ {
+ ReleaseId = releaseId
+ };
+
+ reader.MoveToContent();
+ reader.Read();
+
+ // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "title":
+ {
+ result.Title = reader.ReadElementContentAsString();
+ break;
+ }
+
+ case "date":
+ {
+ var val = reader.ReadElementContentAsString();
+ if (DateTime.TryParse(val, out var date))
+ {
+ result.Year = date.Year;
+ }
+
+ break;
+ }
+
+ case "annotation":
+ {
+ result.Overview = reader.ReadElementContentAsString();
+ break;
+ }
+
+ case "release-group":
+ {
+ result.ReleaseGroupId = reader.GetAttribute("id");
+ reader.Skip();
+ break;
+ }
+
+ case "artist-credit":
+ {
+ using var subReader = reader.ReadSubtree();
+ var artist = ParseArtistCredit(subReader);
+
+ if (!string.IsNullOrEmpty(artist.Item1))
+ {
+ result.Artists.Add(artist);
+ }
+
+ break;
+ }
+
+ default:
+ {
+ reader.Skip();
+ break;
+ }
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
+
+ return result;
+ }
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistExternalId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistExternalId.cs
new file mode 100644
index 000000000..941ffea72
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistExternalId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzArtistExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzArtist.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Artist;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is MusicArtist;
+ }
+}
diff --git a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistProvider.cs
index 8d10834c3..1feb7f4ea 100644
--- a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzArtistProvider.cs
@@ -1,141 +1,128 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
-using MediaBrowser.Common.Net;
+using Diacritics.Extensions;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Extensions;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Xml;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music
{
public class MusicBrainzArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>
{
- private readonly IXmlReaderSettingsFactory _xmlSettings;
-
- public MusicBrainzArtistProvider(IXmlReaderSettingsFactory xmlSettings)
- {
- _xmlSettings = xmlSettings;
- }
+ public string Name => "MusicBrainz";
+ /// <inheritdoc />
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
{
var musicBrainzId = searchInfo.GetMusicBrainzArtistId();
if (!string.IsNullOrWhiteSpace(musicBrainzId))
{
- var url = string.Format("/ws/2/artist/?query=arid:{0}", musicBrainzId);
+ var url = "/ws/2/artist/?query=arid:{0}" + musicBrainzId.ToString(CultureInfo.InvariantCulture);
- using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- return GetResultsFromResponse(stream);
- }
- }
+ using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ return GetResultsFromResponse(stream);
}
else
{
// They seem to throw bad request failures on any term with a slash
var nameToSearch = searchInfo.Name.Replace('/', ' ');
- var url = string.Format("/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch));
+ var url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch));
- using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false))
+ using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
+ await using (var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false))
{
- using (var stream = response.Content)
- {
- var results = GetResultsFromResponse(stream);
+ var results = GetResultsFromResponse(stream).ToList();
- if (results.Count > 0)
- {
- return results;
- }
+ if (results.Count > 0)
+ {
+ return results;
}
}
- if (HasDiacritics(searchInfo.Name))
+ if (searchInfo.Name.HasDiacritics())
{
// Try again using the search with accent characters url
- url = string.Format("/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch));
+ url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch));
- using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- return GetResultsFromResponse(stream);
- }
- }
+ using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ return GetResultsFromResponse(stream);
}
}
- return new List<RemoteSearchResult>();
+ return Enumerable.Empty<RemoteSearchResult>();
}
- private List<RemoteSearchResult> GetResultsFromResponse(Stream stream)
+ private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream)
{
- using (var oReader = new StreamReader(stream, Encoding.UTF8))
+ using var oReader = new StreamReader(stream, Encoding.UTF8);
+ var settings = new XmlReaderSettings()
{
- var settings = _xmlSettings.Create(false);
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ using var reader = XmlReader.Create(oReader, settings);
+ reader.MoveToContent();
+ reader.Read();
- using (var reader = XmlReader.Create(oReader, settings))
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
{
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ switch (reader.Name)
{
- if (reader.NodeType == XmlNodeType.Element)
+ case "artist-list":
{
- switch (reader.Name)
+ if (reader.IsEmptyElement)
{
- case "artist-list":
- {
- if (reader.IsEmptyElement)
- {
- reader.Read();
- continue;
- }
- using (var subReader = reader.ReadSubtree())
- {
- return ParseArtistList(subReader);
- }
- }
- default:
- {
- reader.Skip();
- break;
- }
+ reader.Read();
+ continue;
}
+
+ using var subReader = reader.ReadSubtree();
+ return ParseArtistList(subReader).ToList();
}
- else
+
+ default:
{
- reader.Read();
+ reader.Skip();
+ break;
}
}
-
- return new List<RemoteSearchResult>();
+ }
+ else
+ {
+ reader.Read();
}
}
+
+ return Enumerable.Empty<RemoteSearchResult>();
}
- private List<RemoteSearchResult> ParseArtistList(XmlReader reader)
+ private IEnumerable<RemoteSearchResult> ParseArtistList(XmlReader reader)
{
- var list = new List<RemoteSearchResult>();
-
reader.MoveToContent();
reader.Read();
@@ -153,18 +140,19 @@ namespace MediaBrowser.Providers.Music
reader.Read();
continue;
}
+
var mbzId = reader.GetAttribute("id");
- using (var subReader = reader.ReadSubtree())
+ using var subReader = reader.ReadSubtree();
+ var artist = ParseArtist(subReader, mbzId);
+ if (artist != null)
{
- var artist = ParseArtist(subReader, mbzId);
- if (artist != null)
- {
- list.Add(artist);
- }
+ yield return artist;
}
+
break;
}
+
default:
{
reader.Skip();
@@ -177,8 +165,6 @@ namespace MediaBrowser.Providers.Music
reader.Read();
}
}
-
- return list;
}
private RemoteSearchResult ParseArtist(XmlReader reader, string artistId)
@@ -202,11 +188,13 @@ namespace MediaBrowser.Providers.Music
result.Name = reader.ReadElementContentAsString();
break;
}
+
case "annotation":
{
result.Overview = reader.ReadElementContentAsString();
break;
}
+
default:
{
// there is sort-name if ever needed
@@ -221,7 +209,7 @@ namespace MediaBrowser.Providers.Music
}
}
- result.SetProviderId(MetadataProviders.MusicBrainzArtist, artistId);
+ result.SetProviderId(MetadataProvider.MusicBrainzArtist, artistId);
if (string.IsNullOrWhiteSpace(artistId) || string.IsNullOrWhiteSpace(result.Name))
{
@@ -231,61 +219,54 @@ namespace MediaBrowser.Providers.Music
return result;
}
- public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo id, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<MusicArtist>
{
Item = new MusicArtist()
};
- var musicBrainzId = id.GetMusicBrainzArtistId();
+ var musicBrainzId = info.GetMusicBrainzArtistId();
if (string.IsNullOrWhiteSpace(musicBrainzId))
{
- var searchResults = await GetSearchResults(id, cancellationToken).ConfigureAwait(false);
+ var searchResults = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
var singleResult = searchResults.FirstOrDefault();
if (singleResult != null)
{
- musicBrainzId = singleResult.GetProviderId(MetadataProviders.MusicBrainzArtist);
- //result.Item.Name = singleResult.Name;
+ musicBrainzId = singleResult.GetProviderId(MetadataProvider.MusicBrainzArtist);
result.Item.Overview = singleResult.Overview;
+
+ if (Plugin.Instance.Configuration.ReplaceArtistName)
+ {
+ result.Item.Name = singleResult.Name;
+ }
}
}
if (!string.IsNullOrWhiteSpace(musicBrainzId))
{
result.HasMetadata = true;
- result.Item.SetProviderId(MetadataProviders.MusicBrainzArtist, musicBrainzId);
+ result.Item.SetProviderId(MetadataProvider.MusicBrainzArtist, musicBrainzId);
}
return result;
}
/// <summary>
- /// Determines whether the specified text has diacritics.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
- private bool HasDiacritics(string text)
- {
- return !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
- }
-
- /// <summary>
/// Encodes an URL.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>System.String.</returns>
- private string UrlEncode(string name)
+ private static string UrlEncode(string name)
{
return WebUtility.UrlEncode(name);
}
- public string Name => "MusicBrainz";
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzOtherArtistExternalId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzOtherArtistExternalId.cs
new file mode 100644
index 000000000..05db2d98f
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzOtherArtistExternalId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzOtherArtistExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzArtist.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.OtherArtist;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzReleaseGroupExternalId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzReleaseGroupExternalId.cs
new file mode 100644
index 000000000..acb652fe0
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzReleaseGroupExternalId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzReleaseGroupExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzReleaseGroup.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.ReleaseGroup;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/release-group/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzTrackId.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzTrackId.cs
new file mode 100644
index 000000000..14805b9b7
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzTrackId.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.MusicBrainz;
+
+namespace MediaBrowser.Providers.Music
+{
+ public class MusicBrainzTrackId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "MusicBrainz";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.MusicBrainzTrack.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Track;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/track/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Audio;
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs
new file mode 100644
index 000000000..cfa10dd64
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs
@@ -0,0 +1,45 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.MusicBrainz
+{
+ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
+ {
+ public const string DefaultServer = "https://musicbrainz.org";
+
+ public const long DefaultRateLimit = 2000u;
+
+ public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ public static Plugin Instance { get; private set; }
+
+ public override Guid Id => new Guid("8c95c4d2-e50c-4fb0-a4f3-6c06ff0f9a1a");
+
+ public override string Name => "MusicBrainz";
+
+ public override string Description => "Get artist and album metadata from any MusicBrainz server.";
+
+ // TODO remove when plugin removed from server.
+ public override string ConfigurationFileName => "Jellyfin.Plugin.MusicBrainz.xml";
+
+ public IEnumerable<PluginPageInfo> GetPages()
+ {
+ yield return new PluginPageInfo
+ {
+ Name = Name,
+ EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Omdb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/Omdb/Configuration/PluginConfiguration.cs
new file mode 100644
index 000000000..099547005
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Omdb/Configuration/PluginConfiguration.cs
@@ -0,0 +1,11 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Providers.Plugins.Omdb
+{
+ public class PluginConfiguration : BasePluginConfiguration
+ {
+ public bool CastAndCrew { get; set; }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Omdb/Configuration/config.html b/MediaBrowser.Providers/Plugins/Omdb/Configuration/config.html
new file mode 100644
index 000000000..f4375b3cb
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Omdb/Configuration/config.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>OMDb</title>
+</head>
+<body>
+ <div data-role="page" class="page type-interior pluginConfigurationPage configPage" data-require="emby-input,emby-button,emby-checkbox">
+ <div data-role="content">
+ <div class="content-primary">
+ <form class="configForm">
+ <label class="checkboxContainer">
+ <input is="emby-checkbox" type="checkbox" id="castAndCrew" />
+ <span>Collect information about the cast and other crew members from OMDb.</span>
+ </label>
+ <br />
+ <div>
+ <button is="emby-button" type="submit" class="raised button-submit block"><span>Save</span></button>
+ </div>
+ </form>
+ </div>
+ </div>
+ <script type="text/javascript">
+ var PluginConfig = {
+ pluginId: "a628c0da-fac5-4c7e-9d1a-7134223f14c8"
+ };
+
+ document.querySelector('.configPage')
+ .addEventListener('pageshow', function () {
+ Dashboard.showLoadingMsg();
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ document.querySelector('#castAndCrew').checked = config.CastAndCrew;
+ Dashboard.hideLoadingMsg();
+ });
+ });
+
+
+ document.querySelector('.configForm')
+ .addEventListener('submit', function (e) {
+ Dashboard.showLoadingMsg();
+
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ config.CastAndCrew = document.querySelector('#castAndCrew').checked;
+ ApiClient.updatePluginConfiguration(PluginConfig.pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult);
+ });
+
+ e.preventDefault();
+ return false;
+ });
+ </script>
+ </div>
+</body>
+</html>
diff --git a/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableInt32Converter.cs b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableInt32Converter.cs
new file mode 100644
index 000000000..8bfdc461e
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableInt32Converter.cs
@@ -0,0 +1,44 @@
+using System;
+using System.ComponentModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.Omdb
+{
+ /// <summary>
+ /// Converts a string <c>N/A</c> to <c>string.Empty</c>.
+ /// </summary>
+ public class JsonOmdbNotAvailableInt32Converter : JsonConverter<int?>
+ {
+ /// <inheritdoc />
+ public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ var str = reader.GetString();
+ if (str == null || str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
+ var converter = TypeDescriptor.GetConverter(typeToConvert);
+ return (int?)converter.ConvertFromString(str);
+ }
+
+ return JsonSerializer.Deserialize<int>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
+ {
+ if (value.HasValue)
+ {
+ writer.WriteNumberValue(value.Value);
+ }
+ else
+ {
+ writer.WriteNullValue();
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs
new file mode 100644
index 000000000..f35880a04
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.Omdb
+{
+ /// <summary>
+ /// Converts a string <c>N/A</c> to <c>string.Empty</c>.
+ /// </summary>
+ public class JsonOmdbNotAvailableStringConverter : JsonConverter<string?>
+ {
+ /// <inheritdoc />
+ public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.Null)
+ {
+ return null;
+ }
+
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ // GetString can't return null here because we already handled it above
+ var str = reader.GetString()!;
+ if (str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
+ return str;
+ }
+
+ return JsonSerializer.Deserialize<string?>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs
index dee3030af..f67ac6ede 100644
--- a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs
@@ -1,8 +1,10 @@
+#pragma warning disable CS1591
+
using System.Collections.Generic;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common;
-using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
@@ -10,33 +12,36 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Omdb;
-using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.TV.Omdb
+namespace MediaBrowser.Providers.Plugins.Omdb
{
- public class OmdbEpisodeProvider :
- IRemoteMetadataProvider<Episode, EpisodeInfo>,
- IHasOrder
+ public class OmdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder
{
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly OmdbItemProvider _itemProvider;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
private readonly IApplicationHost _appHost;
- public OmdbEpisodeProvider(IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClient httpClient, ILogger logger, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
+ public OmdbEpisodeProvider(
+ IApplicationHost appHost,
+ IHttpClientFactory httpClientFactory,
+ ILibraryManager libraryManager,
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager)
{
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_appHost = appHost;
- _itemProvider = new OmdbItemProvider(jsonSerializer, _appHost, httpClient, logger, libraryManager, fileSystem, configurationManager);
+ _itemProvider = new OmdbItemProvider(_appHost, httpClientFactory, libraryManager, fileSystem, configurationManager);
}
+ // After TheTvDb
+ public int Order => 1;
+
+ public string Name => "The Open Movie Database";
+
public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
{
return _itemProvider.GetSearchResults(searchInfo, "episode", cancellationToken);
@@ -56,23 +61,19 @@ namespace MediaBrowser.Providers.TV.Omdb
return result;
}
- if (info.SeriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out string seriesImdbId) && !string.IsNullOrEmpty(seriesImdbId))
+ if (info.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string? seriesImdbId) && !string.IsNullOrEmpty(seriesImdbId))
{
if (info.IndexNumber.HasValue && info.ParentIndexNumber.HasValue)
{
- result.HasMetadata = await new OmdbProvider(_jsonSerializer, _httpClient, _fileSystem, _appHost, _configurationManager)
- .FetchEpisodeData(result, info.IndexNumber.Value, info.ParentIndexNumber.Value, info.GetProviderId(MetadataProviders.Imdb), seriesImdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
+ result.HasMetadata = await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager)
+ .FetchEpisodeData(result, info.IndexNumber.Value, info.ParentIndexNumber.Value, info.GetProviderId(MetadataProvider.Imdb), seriesImdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
}
}
return result;
}
- // After TheTvDb
- public int Order => 1;
-
- public string Name => "The Open Movie Database";
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _itemProvider.GetImageResponse(url, cancellationToken);
}
diff --git a/MediaBrowser.Providers/Omdb/OmdbImageProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs
index 1e0bcacf2..fa82089c8 100644
--- a/MediaBrowser.Providers/Omdb/OmdbImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs
@@ -1,4 +1,10 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System.Collections.Generic;
+using System.Globalization;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common;
@@ -11,27 +17,30 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-namespace MediaBrowser.Providers.Omdb
+namespace MediaBrowser.Providers.Plugins.Omdb
{
public class OmdbImageProvider : IRemoteImageProvider, IHasOrder
{
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _jsonSerializer;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
private readonly IApplicationHost _appHost;
- public OmdbImageProvider(IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
+ public OmdbImageProvider(IApplicationHost appHost, IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
{
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_appHost = appHost;
}
+ public string Name => "The Open Movie Database";
+
+ // After other internet providers, because they're better
+ // But before fallback providers like screengrab
+ public int Order => 90;
+
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType>
@@ -42,11 +51,11 @@ namespace MediaBrowser.Providers.Omdb
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
- var imdbId = item.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = item.GetProviderId(MetadataProvider.Imdb);
var list = new List<RemoteImageInfo>();
- var provider = new OmdbProvider(_jsonSerializer, _httpClient, _fileSystem, _appHost, _configurationManager);
+ var provider = new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager);
if (!string.IsNullOrWhiteSpace(imdbId))
{
@@ -68,7 +77,7 @@ namespace MediaBrowser.Providers.Omdb
list.Add(new RemoteImageInfo
{
ProviderName = Name,
- Url = string.Format("https://img.omdbapi.com/?i={0}&apikey=2c9d9507", imdbId)
+ Url = string.Format(CultureInfo.InvariantCulture, "https://img.omdbapi.com/?i={0}&apikey=2c9d9507", imdbId)
});
}
}
@@ -77,23 +86,14 @@ namespace MediaBrowser.Providers.Omdb
return list;
}
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
- public string Name => "The Open Movie Database";
-
public bool Supports(BaseItem item)
{
return item is Movie || item is Trailer || item is Episode;
}
- // After other internet providers, because they're better
- // But before fallback providers like screengrab
- public int Order => 90;
}
}
diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs
index 44b9dcca1..2409993a2 100644
--- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs
@@ -1,10 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591, SA1300
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
@@ -16,32 +23,39 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Omdb
+namespace MediaBrowser.Providers.Plugins.Omdb
{
public class OmdbItemProvider : IRemoteMetadataProvider<Series, SeriesInfo>,
IRemoteMetadataProvider<Movie, MovieInfo>, IRemoteMetadataProvider<Trailer, TrailerInfo>, IHasOrder
{
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly ILibraryManager _libraryManager;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
private readonly IApplicationHost _appHost;
-
- public OmdbItemProvider(IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClient httpClient, ILogger logger, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
+ private readonly JsonSerializerOptions _jsonOptions;
+
+ public OmdbItemProvider(
+ IApplicationHost appHost,
+ IHttpClientFactory httpClientFactory,
+ ILibraryManager libraryManager,
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager)
{
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _logger = logger;
+ _httpClientFactory = httpClientFactory;
_libraryManager = libraryManager;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_appHost = appHost;
+
+ _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options);
+ _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter());
+ _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter());
}
+
+ public string Name => "The Open Movie Database";
+
// After primary option
public int Order => 2;
@@ -64,12 +78,12 @@ namespace MediaBrowser.Providers.Omdb
{
var episodeSearchInfo = searchInfo as EpisodeInfo;
- var imdbId = searchInfo.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = searchInfo.GetProviderId(MetadataProvider.Imdb);
var urlQuery = "plot=full&r=json";
if (type == "episode" && episodeSearchInfo != null)
{
- episodeSearchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out imdbId);
+ episodeSearchInfo.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out imdbId);
}
var name = searchInfo.Name;
@@ -80,7 +94,7 @@ namespace MediaBrowser.Providers.Omdb
var parsedName = _libraryManager.ParseName(name);
var yearInName = parsedName.Year;
name = parsedName.Name;
- year = year ?? yearInName;
+ year ??= yearInName;
}
if (string.IsNullOrWhiteSpace(imdbId))
@@ -99,6 +113,7 @@ namespace MediaBrowser.Providers.Omdb
{
urlQuery += "&t=" + WebUtility.UrlEncode(name);
}
+
urlQuery += "&type=" + type;
}
else
@@ -113,75 +128,72 @@ namespace MediaBrowser.Providers.Omdb
{
urlQuery += string.Format(CultureInfo.InvariantCulture, "&Episode={0}", searchInfo.IndexNumber);
}
+
if (searchInfo.ParentIndexNumber.HasValue)
{
urlQuery += string.Format(CultureInfo.InvariantCulture, "&Season={0}", searchInfo.ParentIndexNumber);
}
}
- var url = OmdbProvider.GetOmdbUrl(urlQuery, _appHost, cancellationToken);
+ var url = OmdbProvider.GetOmdbUrl(urlQuery);
+
+ using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ var resultList = new List<SearchResult>();
- using (var response = await OmdbProvider.GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
+ if (isSearch)
+ {
+ var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (searchResultList != null && searchResultList.Search != null)
+ {
+ resultList.AddRange(searchResultList.Search);
+ }
+ }
+ else
{
- using (var stream = response.Content)
+ var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase))
{
- var resultList = new List<SearchResult>();
-
- if (isSearch)
- {
- var searchResultList = await _jsonSerializer.DeserializeFromStreamAsync<SearchResultList>(stream).ConfigureAwait(false);
- if (searchResultList != null && searchResultList.Search != null)
- {
- resultList.AddRange(searchResultList.Search);
- }
- }
- else
- {
- var result = await _jsonSerializer.DeserializeFromStreamAsync<SearchResult>(stream).ConfigureAwait(false);
- if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase))
- {
- resultList.Add(result);
- }
- }
-
- return resultList.Select(result =>
- {
- var item = new RemoteSearchResult
- {
- IndexNumber = searchInfo.IndexNumber,
- Name = result.Title,
- ParentIndexNumber = searchInfo.ParentIndexNumber,
- SearchProviderName = Name
- };
-
- if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue)
- {
- item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value;
- }
-
- item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
-
- if (result.Year.Length > 0
- && int.TryParse(result.Year.Substring(0, Math.Min(result.Year.Length, 4)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
- {
- item.ProductionYear = parsedYear;
- }
-
- if (!string.IsNullOrEmpty(result.Released)
- && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var released))
- {
- item.PremiereDate = released;
- }
-
- if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase))
- {
- item.ImageUrl = result.Poster;
- }
-
- return item;
- });
+ resultList.Add(result);
}
}
+
+ return resultList.Select(result =>
+ {
+ var item = new RemoteSearchResult
+ {
+ IndexNumber = searchInfo.IndexNumber,
+ Name = result.Title,
+ ParentIndexNumber = searchInfo.ParentIndexNumber,
+ SearchProviderName = Name
+ };
+
+ if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue)
+ {
+ item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value;
+ }
+
+ item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
+
+ if (result.Year.Length > 0
+ && int.TryParse(result.Year.AsSpan().Slice(0, Math.Min(result.Year.Length, 4)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
+ {
+ item.ProductionYear = parsedYear;
+ }
+
+ if (!string.IsNullOrEmpty(result.Released)
+ && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var released))
+ {
+ item.PremiereDate = released;
+ }
+
+ if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase))
+ {
+ item.ImageUrl = result.Poster;
+ }
+
+ return item;
+ });
}
public Task<MetadataResult<Trailer>> GetMetadata(TrailerInfo info, CancellationToken cancellationToken)
@@ -194,8 +206,6 @@ namespace MediaBrowser.Providers.Omdb
return GetSearchResults(searchInfo, "movie", cancellationToken);
}
- public string Name => "The Open Movie Database";
-
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<Series>
@@ -204,7 +214,7 @@ namespace MediaBrowser.Providers.Omdb
QueriedById = true
};
- var imdbId = info.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = info.GetProviderId(MetadataProvider.Imdb);
if (string.IsNullOrWhiteSpace(imdbId))
{
imdbId = await GetSeriesImdbId(info, cancellationToken).ConfigureAwait(false);
@@ -213,10 +223,10 @@ namespace MediaBrowser.Providers.Omdb
if (!string.IsNullOrEmpty(imdbId))
{
- result.Item.SetProviderId(MetadataProviders.Imdb, imdbId);
+ result.Item.SetProviderId(MetadataProvider.Imdb, imdbId);
result.HasMetadata = true;
- await new OmdbProvider(_jsonSerializer, _httpClient, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
+ await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
}
return result;
@@ -236,7 +246,7 @@ namespace MediaBrowser.Providers.Omdb
QueriedById = true
};
- var imdbId = info.GetProviderId(MetadataProviders.Imdb);
+ var imdbId = info.GetProviderId(MetadataProvider.Imdb);
if (string.IsNullOrWhiteSpace(imdbId))
{
imdbId = await GetMovieImdbId(info, cancellationToken).ConfigureAwait(false);
@@ -245,10 +255,10 @@ namespace MediaBrowser.Providers.Omdb
if (!string.IsNullOrEmpty(imdbId))
{
- result.Item.SetProviderId(MetadataProviders.Imdb, imdbId);
+ result.Item.SetProviderId(MetadataProvider.Imdb, imdbId);
result.HasMetadata = true;
- await new OmdbProvider(_jsonSerializer, _httpClient, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
+ await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
}
return result;
@@ -258,49 +268,67 @@ namespace MediaBrowser.Providers.Omdb
{
var results = await GetSearchResultsInternal(info, "movie", false, cancellationToken).ConfigureAwait(false);
var first = results.FirstOrDefault();
- return first == null ? null : first.GetProviderId(MetadataProviders.Imdb);
+ return first?.GetProviderId(MetadataProvider.Imdb);
}
private async Task<string> GetSeriesImdbId(SeriesInfo info, CancellationToken cancellationToken)
{
var results = await GetSearchResultsInternal(info, "series", false, cancellationToken).ConfigureAwait(false);
var first = results.FirstOrDefault();
- return first == null ? null : first.GetProviderId(MetadataProviders.Imdb);
+ return first?.GetProviderId(MetadataProvider.Imdb);
}
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
- class SearchResult
+ private class SearchResult
{
public string Title { get; set; }
+
public string Year { get; set; }
+
public string Rated { get; set; }
+
public string Released { get; set; }
+
public string Season { get; set; }
+
public string Episode { get; set; }
+
public string Runtime { get; set; }
+
public string Genre { get; set; }
+
public string Director { get; set; }
+
public string Writer { get; set; }
+
public string Actors { get; set; }
+
public string Plot { get; set; }
+
public string Language { get; set; }
+
public string Country { get; set; }
+
public string Awards { get; set; }
+
public string Poster { get; set; }
+
public string Metascore { get; set; }
+
public string imdbRating { get; set; }
+
public string imdbVotes { get; set; }
+
public string imdbID { get; set; }
+
public string seriesID { get; set; }
+
public string Type { get; set; }
+
public string Response { get; set; }
}
@@ -312,6 +340,5 @@ namespace MediaBrowser.Providers.Omdb
/// <value>The results.</value>
public List<SearchResult> Search { get; set; }
}
-
}
}
diff --git a/MediaBrowser.Providers/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs
index 19dce34d6..816a882b4 100644
--- a/MediaBrowser.Providers/Omdb/OmdbProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs
@@ -1,11 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS159, SA1300
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Text;
+using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
using MediaBrowser.Common;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
@@ -13,28 +19,43 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-namespace MediaBrowser.Providers.Omdb
+namespace MediaBrowser.Providers.Plugins.Omdb
{
+ /// <summary>Provider for OMDB service.</summary>
public class OmdbProvider
{
- private readonly IJsonSerializer _jsonSerializer;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
- private readonly IHttpClient _httpClient;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IApplicationHost _appHost;
-
- public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager)
+ private readonly JsonSerializerOptions _jsonOptions;
+
+ /// <summary>Initializes a new instance of the <see cref="OmdbProvider"/> class.</summary>
+ /// <param name="httpClientFactory">HttpClientFactory to use for calls to OMDB service.</param>
+ /// <param name="fileSystem">IFileSystem to use for store OMDB data.</param>
+ /// <param name="appHost">IApplicationHost to use.</param>
+ /// <param name="configurationManager">IServerConfigurationManager to use.</param>
+ public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager)
{
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_appHost = appHost;
+
+ _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options);
+ _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter());
+ _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter());
}
+ /// <summary>Fetches data from OMDB service.</summary>
+ /// <param name="itemResult">Metadata about media item.</param>
+ /// <param name="imdbId">IMDB ID for media.</param>
+ /// <param name="language">Media language.</param>
+ /// <param name="country">Country of origin.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <typeparam name="T">The first generic type parameter.</typeparam>
+ /// <returns>Returns a Task object that can be awaited.</returns>
public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken)
where T : BaseItem
{
@@ -47,7 +68,7 @@ namespace MediaBrowser.Providers.Omdb
var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
- // Only take the name and rating if the user's language is set to english, since Omdb has no localization
+ // Only take the name and rating if the user's language is set to English, since Omdb has no localization
if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
{
item.Name = result.Title;
@@ -59,7 +80,7 @@ namespace MediaBrowser.Providers.Omdb
}
if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
- && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out var year)
+ && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, CultureInfo.InvariantCulture, out var year)
&& year >= 0)
{
item.ProductionYear = year;
@@ -73,32 +94,43 @@ namespace MediaBrowser.Providers.Omdb
}
if (!string.IsNullOrEmpty(result.imdbVotes)
- && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
+ && int.TryParse(result.imdbVotes, NumberStyles.Number, CultureInfo.InvariantCulture, out var voteCount)
&& voteCount >= 0)
{
- //item.VoteCount = voteCount;
+ // item.VoteCount = voteCount;
}
if (!string.IsNullOrEmpty(result.imdbRating)
- && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
+ && float.TryParse(result.imdbRating, NumberStyles.Any, CultureInfo.InvariantCulture, out var imdbRating)
&& imdbRating >= 0)
{
item.CommunityRating = imdbRating;
}
- //if (!string.IsNullOrEmpty(result.Website))
- //{
- // item.HomePageUrl = result.Website;
- //}
+ if (!string.IsNullOrEmpty(result.Website))
+ {
+ item.HomePageUrl = result.Website;
+ }
if (!string.IsNullOrWhiteSpace(result.imdbID))
{
- item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
+ item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
}
ParseAdditionalMetadata(itemResult, result);
}
+ /// <summary>Gets data about an episode.</summary>
+ /// <param name="itemResult">Metadata about episode.</param>
+ /// <param name="episodeNumber">Episode number.</param>
+ /// <param name="seasonNumber">Season number.</param>
+ /// <param name="episodeImdbId">Episode ID.</param>
+ /// <param name="seriesImdbId">Season ID.</param>
+ /// <param name="language">Episode language.</param>
+ /// <param name="country">Country of origin.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <typeparam name="T">The first generic type parameter.</typeparam>
+ /// <returns>Whether operation was successful.</returns>
public async Task<bool> FetchEpisodeData<T>(MetadataResult<T> itemResult, int episodeNumber, int seasonNumber, string episodeImdbId, string seriesImdbId, string language, string country, CancellationToken cancellationToken)
where T : BaseItem
{
@@ -111,7 +143,7 @@ namespace MediaBrowser.Providers.Omdb
var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false);
- if (seasonResult == null)
+ if (seasonResult?.Episodes == null)
{
return false;
}
@@ -120,7 +152,7 @@ namespace MediaBrowser.Providers.Omdb
if (!string.IsNullOrWhiteSpace(episodeImdbId))
{
- foreach (var episode in (seasonResult.Episodes ?? new RootObject[] { }))
+ foreach (var episode in seasonResult.Episodes)
{
if (string.Equals(episodeImdbId, episode.imdbID, StringComparison.OrdinalIgnoreCase))
{
@@ -133,7 +165,7 @@ namespace MediaBrowser.Providers.Omdb
// finally, search by numbers
if (result == null)
{
- foreach (var episode in (seasonResult.Episodes ?? new RootObject[] { }))
+ foreach (var episode in seasonResult.Episodes)
{
if (episode.Episode == episodeNumber)
{
@@ -148,7 +180,7 @@ namespace MediaBrowser.Providers.Omdb
return false;
}
- // Only take the name and rating if the user's language is set to english, since Omdb has no localization
+ // Only take the name and rating if the user's language is set to English, since Omdb has no localization
if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
{
item.Name = result.Title;
@@ -160,7 +192,7 @@ namespace MediaBrowser.Providers.Omdb
}
if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
- && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out var year)
+ && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, CultureInfo.InvariantCulture, out var year)
&& year >= 0)
{
item.ProductionYear = year;
@@ -174,27 +206,27 @@ namespace MediaBrowser.Providers.Omdb
}
if (!string.IsNullOrEmpty(result.imdbVotes)
- && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
+ && int.TryParse(result.imdbVotes, NumberStyles.Number, CultureInfo.InvariantCulture, out var voteCount)
&& voteCount >= 0)
{
- //item.VoteCount = voteCount;
+ // item.VoteCount = voteCount;
}
if (!string.IsNullOrEmpty(result.imdbRating)
- && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
+ && float.TryParse(result.imdbRating, NumberStyles.Any, CultureInfo.InvariantCulture, out var imdbRating)
&& imdbRating >= 0)
{
item.CommunityRating = imdbRating;
}
- //if (!string.IsNullOrEmpty(result.Website))
- //{
- // item.HomePageUrl = result.Website;
- //}
+ if (!string.IsNullOrEmpty(result.Website))
+ {
+ item.HomePageUrl = result.Website;
+ }
if (!string.IsNullOrWhiteSpace(result.imdbID))
{
- item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
+ item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
}
ParseAdditionalMetadata(itemResult, result);
@@ -205,64 +237,30 @@ namespace MediaBrowser.Providers.Omdb
internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
{
var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false);
-
- string resultString;
-
- using (var stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
- {
- using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
- {
- resultString = reader.ReadToEnd();
- resultString = resultString.Replace("\"N/A\"", "\"\"");
- }
- }
-
- var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString);
- return result;
+ await using var stream = AsyncFile.OpenRead(path);
+ return await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
}
internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
{
var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false);
-
- string resultString;
-
- using (var stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
- {
- using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
- {
- resultString = reader.ReadToEnd();
- resultString = resultString.Replace("\"N/A\"", "\"\"");
- }
- }
-
- var result = _jsonSerializer.DeserializeFromString<SeasonRootObject>(resultString);
- return result;
+ await using var stream = AsyncFile.OpenRead(path);
+ return await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
}
- internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
+ /// <summary>Gets OMDB URL.</summary>
+ /// <param name="query">Appends query string to URL.</param>
+ /// <returns>OMDB URL with optional query string.</returns>
+ public static string GetOmdbUrl(string query)
{
- if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out string id) && !string.IsNullOrEmpty(id))
- {
- // This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
- if (!string.IsNullOrWhiteSpace(id))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static string GetOmdbUrl(string query, IApplicationHost appHost, CancellationToken cancellationToken)
- {
- const string url = "https://www.omdbapi.com?apikey=2c9d9507";
+ const string Url = "https://www.omdbapi.com?apikey=2c9d9507";
if (string.IsNullOrWhiteSpace(query))
{
- return url;
+ return Url;
}
- return url + "&" + query;
+
+ return Url + "&" + query;
}
private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
@@ -286,19 +284,21 @@ namespace MediaBrowser.Providers.Omdb
return path;
}
}
-
- var url = GetOmdbUrl(string.Format("i={0}&plot=short&tomatoes=true&r=json", imdbParam), _appHost, cancellationToken);
-
- using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
+ else
{
- using (var stream = response.Content)
- {
- var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(stream).ConfigureAwait(false);
- Directory.CreateDirectory(Path.GetDirectoryName(path));
- _jsonSerializer.SerializeToFile(rootObject, path);
- }
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
}
+ var url = GetOmdbUrl(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "i={0}&plot=short&tomatoes=true&r=json",
+ imdbParam));
+
+ var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
+ await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
+
return path;
}
@@ -323,31 +323,47 @@ namespace MediaBrowser.Providers.Omdb
return path;
}
}
-
- var url = GetOmdbUrl(string.Format("i={0}&season={1}&detail=full", imdbParam, seasonId), _appHost, cancellationToken);
-
- using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
+ else
{
- using (var stream = response.Content)
- {
- var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<SeasonRootObject>(stream).ConfigureAwait(false);
- Directory.CreateDirectory(Path.GetDirectoryName(path));
- _jsonSerializer.SerializeToFile(rootObject, path);
- }
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
}
+ var url = GetOmdbUrl(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "i={0}&season={1}&detail=full",
+ imdbParam,
+ seasonId));
+
+ var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
+ await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
+
return path;
}
- public static Task<HttpResponseInfo> GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken)
+ /// <summary>Gets response from OMDB service as type T.</summary>
+ /// <param name="httpClient">HttpClient instance to use for service call.</param>
+ /// <param name="url">Http URL to use for service call.</param>
+ /// <param name="cancellationToken">CancellationToken to use for service call.</param>
+ /// <typeparam name="T">The first generic type parameter.</typeparam>
+ /// <returns>OMDB service response as type T.</returns>
+ public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken)
{
- return httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = true,
- EnableDefaultUserAgent = true
- }, "GET");
+ using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false);
+ await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+
+ return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <summary>Gets response from OMDB service.</summary>
+ /// <param name="httpClient">HttpClient instance to use for service call.</param>
+ /// <param name="url">Http URL to use for service call.</param>
+ /// <param name="cancellationToken">CancellationToken to use for service call.</param>
+ /// <returns>OMDB service response as HttpResponseMessage.</returns>
+ public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken)
+ {
+ return httpClient.GetAsync(url, cancellationToken);
}
internal string GetDataFilePath(string imdbId)
@@ -359,7 +375,7 @@ namespace MediaBrowser.Providers.Omdb
var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
- var filename = string.Format("{0}.json", imdbId);
+ var filename = string.Format(CultureInfo.InvariantCulture, "{0}.json", imdbId);
return Path.Combine(dataPath, filename);
}
@@ -373,7 +389,7 @@ namespace MediaBrowser.Providers.Omdb
var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
- var filename = string.Format("{0}_season_{1}.json", imdbId, seasonId);
+ var filename = string.Format(CultureInfo.InvariantCulture, "{0}_season_{1}.json", imdbId, seasonId);
return Path.Combine(dataPath, filename);
}
@@ -385,14 +401,14 @@ namespace MediaBrowser.Providers.Omdb
var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;
- // Grab series genres because imdb data is better than tvdb. Leave movies alone
- // But only do it if english is the preferred language because this data will not be localized
+ // Grab series genres because IMDb data is better than TVDB. Leave movies alone
+ // But only do it if English is the preferred language because this data will not be localized
if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
{
item.Genres = Array.Empty<string>();
foreach (var genre in result.Genre
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
+ .Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.Where(i => !string.IsNullOrWhiteSpace(i)))
{
@@ -402,97 +418,132 @@ namespace MediaBrowser.Providers.Omdb
if (isConfiguredForEnglish)
{
- // Omdb is currently english only, so for other languages skip this and let secondary providers fill it in
+ // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in
item.Overview = result.Plot;
}
- //if (!string.IsNullOrWhiteSpace(result.Director))
- //{
- // var person = new PersonInfo
- // {
- // Name = result.Director.Trim(),
- // Type = PersonType.Director
- // };
-
- // itemResult.AddPerson(person);
- //}
-
- //if (!string.IsNullOrWhiteSpace(result.Writer))
- //{
- // var person = new PersonInfo
- // {
- // Name = result.Director.Trim(),
- // Type = PersonType.Writer
- // };
-
- // itemResult.AddPerson(person);
- //}
-
- //if (!string.IsNullOrWhiteSpace(result.Actors))
- //{
- // var actorList = result.Actors.Split(',');
- // foreach (var actor in actorList)
- // {
- // if (!string.IsNullOrWhiteSpace(actor))
- // {
- // var person = new PersonInfo
- // {
- // Name = actor.Trim(),
- // Type = PersonType.Actor
- // };
-
- // itemResult.AddPerson(person);
- // }
- // }
- //}
+ if (!Plugin.Instance.Configuration.CastAndCrew)
+ {
+ return;
+ }
+
+ if (!string.IsNullOrWhiteSpace(result.Director))
+ {
+ var person = new PersonInfo
+ {
+ Name = result.Director.Trim(),
+ Type = PersonType.Director
+ };
+
+ itemResult.AddPerson(person);
+ }
+
+ if (!string.IsNullOrWhiteSpace(result.Writer))
+ {
+ var person = new PersonInfo
+ {
+ Name = result.Writer.Trim(),
+ Type = PersonType.Writer
+ };
+
+ itemResult.AddPerson(person);
+ }
+
+ if (!string.IsNullOrWhiteSpace(result.Actors))
+ {
+ var actorList = result.Actors.Split(',');
+ foreach (var actor in actorList)
+ {
+ if (!string.IsNullOrWhiteSpace(actor))
+ {
+ var person = new PersonInfo
+ {
+ Name = actor.Trim(),
+ Type = PersonType.Actor
+ };
+
+ itemResult.AddPerson(person);
+ }
+ }
+ }
}
private bool IsConfiguredForEnglish(BaseItem item)
{
var lang = item.GetPreferredMetadataLanguage();
- // The data isn't localized and so can only be used for english users
+ // The data isn't localized and so can only be used for English users
return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
}
internal class SeasonRootObject
{
public string Title { get; set; }
+
public string seriesID { get; set; }
- public int Season { get; set; }
+
+ public int? Season { get; set; }
+
public int? totalSeasons { get; set; }
+
public RootObject[] Episodes { get; set; }
+
public string Response { get; set; }
}
internal class RootObject
{
public string Title { get; set; }
+
public string Year { get; set; }
+
public string Rated { get; set; }
+
public string Released { get; set; }
+
public string Runtime { get; set; }
+
public string Genre { get; set; }
+
public string Director { get; set; }
+
public string Writer { get; set; }
+
public string Actors { get; set; }
+
public string Plot { get; set; }
+
public string Language { get; set; }
+
public string Country { get; set; }
+
public string Awards { get; set; }
+
public string Poster { get; set; }
+
public List<OmdbRating> Ratings { get; set; }
+
public string Metascore { get; set; }
+
public string imdbRating { get; set; }
+
public string imdbVotes { get; set; }
+
public string imdbID { get; set; }
+
public string Type { get; set; }
+
public string DVD { get; set; }
+
public string BoxOffice { get; set; }
+
public string Production { get; set; }
+
public string Website { get; set; }
+
public string Response { get; set; }
- public int Episode { get; set; }
+
+ public int? Episode { get; set; }
public float? GetRottenTomatoScore()
{
@@ -508,12 +559,19 @@ namespace MediaBrowser.Providers.Omdb
}
}
}
+
return null;
}
}
+
+#pragma warning disable CA1034
+ /// <summary>Describes OMDB rating.</summary>
public class OmdbRating
{
+ /// <summary>Gets or sets rating source.</summary>
public string Source { get; set; }
+
+ /// <summary>Gets or sets rating value.</summary>
public string Value { get; set; }
}
}
diff --git a/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs b/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs
new file mode 100644
index 000000000..a0fba48f0
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs
@@ -0,0 +1,41 @@
+#nullable disable
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.Omdb
+{
+ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
+ {
+ public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ public static Plugin Instance { get; private set; }
+
+ public override Guid Id => new Guid("a628c0da-fac5-4c7e-9d1a-7134223f14c8");
+
+ public override string Name => "OMDb";
+
+ public override string Description => "Get metadata for movies and other video content from OMDb.";
+
+ // TODO remove when plugin removed from server.
+ public override string ConfigurationFileName => "Jellyfin.Plugin.Omdb.xml";
+
+ public IEnumerable<PluginPageInfo> GetPages()
+ {
+ yield return new PluginPageInfo
+ {
+ Name = Name,
+ EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetExternalId.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetExternalId.cs
new file mode 100644
index 000000000..3217ac2f1
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetExternalId.cs
@@ -0,0 +1,32 @@
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
+{
+ /// <summary>
+ /// External ID for a TMDB box set.
+ /// </summary>
+ public class TmdbBoxSetExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.TmdbCollection.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.BoxSet;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => TmdbUtils.BaseTmdbUrl + "collection/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ {
+ return item is Movie || item is MusicVideo || item is Trailer;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs
new file mode 100644
index 000000000..35dc36811
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs
@@ -0,0 +1,113 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
+{
+ public class TmdbBoxSetImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbBoxSetImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public int Order => 0;
+
+ public bool Supports(BaseItem item)
+ {
+ return item is BoxSet;
+ }
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary,
+ ImageType.Backdrop
+ };
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var tmdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+
+ if (tmdbId <= 0)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var language = item.GetPreferredMetadataLanguage();
+
+ // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, null, null, cancellationToken).ConfigureAwait(false);
+
+ if (collection?.Images == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var remoteImages = new List<RemoteImageInfo>();
+
+ for (var i = 0; i < collection.Images.Posters.Count; i++)
+ {
+ var poster = collection.Images.Posters[i];
+ remoteImages.Add(new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(poster.FilePath),
+ CommunityRating = poster.VoteAverage,
+ VoteCount = poster.VoteCount,
+ Width = poster.Width,
+ Height = poster.Height,
+ Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ });
+ }
+
+ for (var i = 0; i < collection.Images.Backdrops.Count; i++)
+ {
+ var backdrop = collection.Images.Backdrops[i];
+ remoteImages.Add(new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
+ CommunityRating = backdrop.VoteAverage,
+ VoteCount = backdrop.VoteCount,
+ Width = backdrop.Width,
+ Height = backdrop.Height,
+ ProviderName = Name,
+ Type = ImageType.Backdrop,
+ RatingType = RatingType.Score
+ });
+ }
+
+ return remoteImages;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs
new file mode 100644
index 000000000..62bc9c65f
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs
@@ -0,0 +1,132 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
+{
+ public class TmdbBoxSetProvider : IRemoteMetadataProvider<BoxSet, BoxSetInfo>
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+ private readonly ILibraryManager _libraryManager;
+
+ public TmdbBoxSetProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager, ILibraryManager libraryManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ _libraryManager = libraryManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
+ {
+ var tmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+ var language = searchInfo.MetadataLanguage;
+
+ if (tmdbId > 0)
+ {
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);
+
+ if (collection == null)
+ {
+ return Enumerable.Empty<RemoteSearchResult>();
+ }
+
+ var result = new RemoteSearchResult
+ {
+ Name = collection.Name,
+ SearchProviderName = Name
+ };
+
+ if (collection.Images != null)
+ {
+ result.ImageUrl = _tmdbClientManager.GetPosterUrl(collection.PosterPath);
+ }
+
+ result.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));
+
+ return new[] { result };
+ }
+
+ var collectionSearchResults = await _tmdbClientManager.SearchCollectionAsync(searchInfo.Name, language, cancellationToken).ConfigureAwait(false);
+
+ var collections = new List<RemoteSearchResult>();
+ for (var i = 0; i < collectionSearchResults.Count; i++)
+ {
+ var collection = new RemoteSearchResult
+ {
+ Name = collectionSearchResults[i].Name,
+ SearchProviderName = Name
+ };
+ collection.SetProviderId(MetadataProvider.Tmdb, collectionSearchResults[i].Id.ToString(CultureInfo.InvariantCulture));
+
+ collections.Add(collection);
+ }
+
+ return collections;
+ }
+
+ public async Task<MetadataResult<BoxSet>> GetMetadata(BoxSetInfo info, CancellationToken cancellationToken)
+ {
+ var tmdbId = Convert.ToInt32(info.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+ var language = info.MetadataLanguage;
+ // We don't already have an Id, need to fetch it
+ if (tmdbId <= 0)
+ {
+ // ParseName is required here.
+ // Caller provides the filename with extension stripped and NOT the parsed filename
+ var parsedName = _libraryManager.ParseName(info.Name);
+ var cleanedName = TmdbUtils.CleanName(parsedName.Name);
+ var searchResults = await _tmdbClientManager.SearchCollectionAsync(cleanedName, language, cancellationToken).ConfigureAwait(false);
+
+ if (searchResults != null && searchResults.Count > 0)
+ {
+ tmdbId = searchResults[0].Id;
+ }
+ }
+
+ var result = new MetadataResult<BoxSet>();
+
+ if (tmdbId > 0)
+ {
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);
+
+ if (collection != null)
+ {
+ var item = new BoxSet
+ {
+ Name = collection.Name,
+ Overview = collection.Overview
+ };
+
+ item.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));
+
+ result.HasMetadata = true;
+ result.Item = item;
+ }
+ }
+
+ return result;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs
new file mode 100644
index 000000000..907f0160d
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs
@@ -0,0 +1,15 @@
+using MediaBrowser.Model.Plugins;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb
+{
+ /// <summary>
+ /// Plugin configuration class for TMDb library.
+ /// </summary>
+ public class PluginConfiguration : BasePluginConfiguration
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether include adult content when searching with TMDb.
+ /// </summary>
+ public bool IncludeAdult { get; set; }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html
new file mode 100644
index 000000000..6f42549d7
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>TMDb</title>
+</head>
+<body>
+ <div data-role="page" class="page type-interior pluginConfigurationPage configPage" data-require="emby-input,emby-button,emby-checkbox">
+ <div data-role="content">
+ <div class="content-primary">
+ <form class="configForm">
+ <label class="checkboxContainer">
+ <input is="emby-checkbox" type="checkbox" id="includeAdult" />
+ <span>Include adult content in search results.</span>
+ </label>
+ <br />
+ <div>
+ <button is="emby-button" type="submit" class="raised button-submit block"><span>Save</span></button>
+ </div>
+ </form>
+ </div>
+ </div>
+ <script type="text/javascript">
+ var PluginConfig = {
+ pluginId: "b8715ed1-6c47-4528-9ad3-f72deb539cd4"
+ };
+
+ document.querySelector('.configPage')
+ .addEventListener('pageshow', function () {
+ Dashboard.showLoadingMsg();
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ document.querySelector('#includeAdult').checked = config.IncludeAdult;
+ Dashboard.hideLoadingMsg();
+ });
+ });
+
+
+ document.querySelector('.configForm')
+ .addEventListener('submit', function (e) {
+ Dashboard.showLoadingMsg();
+
+ ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) {
+ config.IncludeAdult = document.querySelector('#includeAdult').checked;
+ ApiClient.updatePluginConfiguration(PluginConfig.pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult);
+ });
+
+ e.preventDefault();
+ return false;
+ });
+ </script>
+ </div>
+</body>
+</html>
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieExternalId.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieExternalId.cs
new file mode 100644
index 000000000..31310a8d4
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieExternalId.cs
@@ -0,0 +1,38 @@
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
+{
+ /// <summary>
+ /// External ID for a TMBD movie.
+ /// </summary>
+ public class TmdbMovieExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Tmdb.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Movie;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => TmdbUtils.BaseTmdbUrl + "movie/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ {
+ // Supports images for tv movies
+ if (item is LiveTvProgram tvProgram && tvProgram.IsMovie)
+ {
+ return true;
+ }
+
+ return item is Movie;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs
new file mode 100644
index 000000000..015eddc1a
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs
@@ -0,0 +1,130 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using TMDbLib.Objects.Find;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
+{
+ public class TmdbMovieImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbMovieImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public int Order => 0;
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public bool Supports(BaseItem item)
+ {
+ return item is Movie || item is Trailer;
+ }
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary,
+ ImageType.Backdrop
+ };
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var language = item.GetPreferredMetadataLanguage();
+
+ var movieTmdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+ if (movieTmdbId <= 0)
+ {
+ var movieImdbId = item.GetProviderId(MetadataProvider.Imdb);
+ if (string.IsNullOrEmpty(movieImdbId))
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var movieResult = await _tmdbClientManager.FindByExternalIdAsync(movieImdbId, FindExternalSource.Imdb, language, cancellationToken).ConfigureAwait(false);
+ if (movieResult?.MovieResults != null && movieResult.MovieResults.Count > 0)
+ {
+ movieTmdbId = movieResult.MovieResults[0].Id;
+ }
+ }
+
+ if (movieTmdbId <= 0)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
+ var movie = await _tmdbClientManager
+ .GetMovieAsync(movieTmdbId, null, null, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (movie?.Images == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var remoteImages = new List<RemoteImageInfo>();
+
+ for (var i = 0; i < movie.Images.Posters.Count; i++)
+ {
+ var poster = movie.Images.Posters[i];
+ remoteImages.Add(new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(poster.FilePath),
+ CommunityRating = poster.VoteAverage,
+ VoteCount = poster.VoteCount,
+ Width = poster.Width,
+ Height = poster.Height,
+ Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ });
+ }
+
+ for (var i = 0; i < movie.Images.Backdrops.Count; i++)
+ {
+ var backdrop = movie.Images.Backdrops[i];
+ remoteImages.Add(new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(backdrop.FilePath),
+ CommunityRating = backdrop.VoteAverage,
+ VoteCount = backdrop.VoteCount,
+ Width = backdrop.Width,
+ Height = backdrop.Height,
+ ProviderName = Name,
+ Type = ImageType.Backdrop,
+ RatingType = RatingType.Score
+ });
+ }
+
+ return remoteImages;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
new file mode 100644
index 000000000..9dd067856
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
@@ -0,0 +1,340 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using TMDbLib.Objects.Find;
+using TMDbLib.Objects.Search;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
+{
+ /// <summary>
+ /// Class MovieDbProvider.
+ /// </summary>
+ public class TmdbMovieProvider : IRemoteMetadataProvider<Movie, MovieInfo>, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILibraryManager _libraryManager;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbMovieProvider(
+ ILibraryManager libraryManager,
+ TmdbClientManager tmdbClientManager,
+ IHttpClientFactory httpClientFactory)
+ {
+ _libraryManager = libraryManager;
+ _tmdbClientManager = tmdbClientManager;
+ _httpClientFactory = httpClientFactory;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public int Order => 1;
+
+ public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
+ {
+ if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var id))
+ {
+ var movie = await _tmdbClientManager
+ .GetMovieAsync(
+ int.Parse(id, CultureInfo.InvariantCulture),
+ searchInfo.MetadataLanguage,
+ TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
+ cancellationToken)
+ .ConfigureAwait(false);
+
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = movie.Title ?? movie.OriginalTitle,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
+ Overview = movie.Overview
+ };
+
+ if (movie.ReleaseDate != null)
+ {
+ var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
+ remoteResult.PremiereDate = releaseDate;
+ remoteResult.ProductionYear = releaseDate.Year;
+ }
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));
+
+ if (!string.IsNullOrWhiteSpace(movie.ImdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId);
+ }
+
+ return new[] { remoteResult };
+ }
+
+ IReadOnlyList<SearchMovie> movieResults;
+ if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out id))
+ {
+ var result = await _tmdbClientManager.FindByExternalIdAsync(
+ id,
+ FindExternalSource.Imdb,
+ TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
+ cancellationToken).ConfigureAwait(false);
+ movieResults = result.MovieResults;
+ }
+ else if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out id))
+ {
+ var result = await _tmdbClientManager.FindByExternalIdAsync(
+ id,
+ FindExternalSource.TvDb,
+ TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
+ cancellationToken).ConfigureAwait(false);
+ movieResults = result.MovieResults;
+ }
+ else
+ {
+ movieResults = await _tmdbClientManager
+ .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ var len = movieResults.Count;
+ var remoteSearchResults = new RemoteSearchResult[len];
+ for (var i = 0; i < len; i++)
+ {
+ var movieResult = movieResults[i];
+ var remoteSearchResult = new RemoteSearchResult
+ {
+ Name = movieResult.Title ?? movieResult.OriginalTitle,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
+ Overview = movieResult.Overview,
+ SearchProviderName = Name
+ };
+
+ var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
+ remoteSearchResult.PremiereDate = releaseDate;
+ remoteSearchResult.ProductionYear = releaseDate?.Year;
+
+ remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture));
+ remoteSearchResults[i] = remoteSearchResult;
+ }
+
+ return remoteSearchResults;
+ }
+
+ public async Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
+ {
+ var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
+ var imdbId = info.GetProviderId(MetadataProvider.Imdb);
+
+ if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
+ {
+ // ParseName is required here.
+ // Caller provides the filename with extension stripped and NOT the parsed filename
+ var parsedName = _libraryManager.ParseName(info.Name);
+ var cleanedName = TmdbUtils.CleanName(parsedName.Name);
+ var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+
+ if (searchResults.Count > 0)
+ {
+ tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId))
+ {
+ var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+ if (movieResultFromImdbId?.MovieResults.Count > 0)
+ {
+ tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId))
+ {
+ return new MetadataResult<Movie>();
+ }
+
+ var movieResult = await _tmdbClientManager
+ .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ if (movieResult == null)
+ {
+ return new MetadataResult<Movie>();
+ }
+
+ var movie = new Movie
+ {
+ Name = movieResult.Title ?? movieResult.OriginalTitle,
+ OriginalTitle = movieResult.OriginalTitle,
+ Overview = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
+ Tagline = movieResult.Tagline,
+ ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
+ };
+ var metadataResult = new MetadataResult<Movie>
+ {
+ HasMetadata = true,
+ ResultLanguage = info.MetadataLanguage,
+ Item = movie
+ };
+
+ movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
+ movie.SetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
+ if (movieResult.BelongsToCollection != null)
+ {
+ movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(CultureInfo.InvariantCulture));
+ movie.CollectionName = movieResult.BelongsToCollection.Name;
+ }
+
+ movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);
+
+ if (movieResult.Releases?.Countries != null)
+ {
+ var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
+
+ var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
+ var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
+
+ if (ourRelease != null)
+ {
+ movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification);
+ }
+ else if (usRelease != null)
+ {
+ movie.OfficialRating = usRelease.Certification;
+ }
+ }
+
+ movie.PremiereDate = movieResult.ReleaseDate;
+ movie.ProductionYear = movieResult.ReleaseDate?.Year;
+
+ if (movieResult.ProductionCompanies != null)
+ {
+ movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
+ }
+
+ var genres = movieResult.Genres;
+
+ foreach (var genre in genres.Select(g => g.Name))
+ {
+ movie.AddGenre(genre);
+ }
+
+ if (movieResult.Keywords?.Keywords != null)
+ {
+ for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
+ {
+ movie.AddTag(movieResult.Keywords.Keywords[i].Name);
+ }
+ }
+
+ if (movieResult.Credits?.Cast != null)
+ {
+ // TODO configurable
+ foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ var personInfo = new PersonInfo
+ {
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order
+ };
+
+ if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
+ {
+ personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
+ }
+
+ if (actor.Id > 0)
+ {
+ personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
+ }
+
+ metadataResult.AddPerson(personInfo);
+ }
+ }
+
+ if (movieResult.Credits?.Crew != null)
+ {
+ var keepTypes = new[]
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
+ };
+
+ foreach (var person in movieResult.Credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
+ !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ var personInfo = new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ };
+
+ if (!string.IsNullOrWhiteSpace(person.ProfilePath))
+ {
+ personInfo.ImageUrl = _tmdbClientManager.GetPosterUrl(person.ProfilePath);
+ }
+
+ if (person.Id > 0)
+ {
+ personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
+ }
+
+ metadataResult.AddPerson(personInfo);
+ }
+ }
+
+ if (movieResult.Videos?.Results != null)
+ {
+ var trailers = new List<MediaUrl>();
+ for (var i = 0; i < movieResult.Videos.Results.Count; i++)
+ {
+ var video = movieResult.Videos.Results[0];
+ if (!TmdbUtils.IsTrailerType(video))
+ {
+ continue;
+ }
+
+ trailers.Add(new MediaUrl
+ {
+ Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.Key),
+ Name = video.Name
+ });
+ }
+
+ movie.RemoteTrailers = trailers;
+ }
+
+ return metadataResult;
+ }
+
+ /// <inheritdoc />
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonExternalId.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonExternalId.cs
new file mode 100644
index 000000000..9804d60bd
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonExternalId.cs
@@ -0,0 +1,31 @@
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.People
+{
+ /// <summary>
+ /// External ID for a TMDB person.
+ /// </summary>
+ public class TmdbPersonExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Tmdb.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Person;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => TmdbUtils.BaseTmdbUrl + "person/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ {
+ return item is Person;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs
new file mode 100644
index 000000000..1fc5ccba5
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs
@@ -0,0 +1,87 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.People
+{
+ public class TmdbPersonImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbPersonImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ /// <inheritdoc />
+ public string Name => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public int Order => 0;
+
+ public bool Supports(BaseItem item)
+ {
+ return item is Person;
+ }
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary
+ };
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var person = (Person)item;
+
+ if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId))
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var language = item.GetPreferredMetadataLanguage();
+ var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), language, cancellationToken).ConfigureAwait(false);
+ if (personResult?.Images?.Profiles == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var remoteImages = new RemoteImageInfo[personResult.Images.Profiles.Count];
+
+ for (var i = 0; i < personResult.Images.Profiles.Count; i++)
+ {
+ var image = personResult.Images.Profiles[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ Url = _tmdbClientManager.GetProfileUrl(image.FilePath)
+ };
+ }
+
+ return remoteImages;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs
new file mode 100644
index 000000000..8790e3759
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs
@@ -0,0 +1,139 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.People
+{
+ public class TmdbPersonProvider : IRemoteMetadataProvider<Person, PersonLookupInfo>
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbPersonProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
+ {
+ if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId))
+ {
+ var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+
+ if (personResult != null)
+ {
+ var result = new RemoteSearchResult
+ {
+ Name = personResult.Name,
+ SearchProviderName = Name,
+ Overview = personResult.Biography
+ };
+
+ if (personResult.Images?.Profiles != null && personResult.Images.Profiles.Count > 0)
+ {
+ result.ImageUrl = _tmdbClientManager.GetProfileUrl(personResult.Images.Profiles[0].FilePath);
+ }
+
+ result.SetProviderId(MetadataProvider.Tmdb, personResult.Id.ToString(CultureInfo.InvariantCulture));
+ if (!string.IsNullOrEmpty(personResult.ExternalIds.ImdbId))
+ {
+ result.SetProviderId(MetadataProvider.Imdb, personResult.ExternalIds.ImdbId);
+ }
+
+ return new[] { result };
+ }
+ }
+
+ var personSearchResult = await _tmdbClientManager.SearchPersonAsync(searchInfo.Name, cancellationToken).ConfigureAwait(false);
+
+ var remoteSearchResults = new List<RemoteSearchResult>();
+ for (var i = 0; i < personSearchResult.Count; i++)
+ {
+ var person = personSearchResult[i];
+ var remoteSearchResult = new RemoteSearchResult
+ {
+ SearchProviderName = Name,
+ Name = person.Name,
+ ImageUrl = _tmdbClientManager.GetProfileUrl(person.ProfilePath)
+ };
+
+ remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
+ remoteSearchResults.Add(remoteSearchResult);
+ }
+
+ return remoteSearchResults;
+ }
+
+ public async Task<MetadataResult<Person>> GetMetadata(PersonLookupInfo info, CancellationToken cancellationToken)
+ {
+ var personTmdbId = Convert.ToInt32(info.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+
+ // We don't already have an Id, need to fetch it
+ if (personTmdbId <= 0)
+ {
+ var personSearchResults = await _tmdbClientManager.SearchPersonAsync(info.Name, cancellationToken).ConfigureAwait(false);
+ if (personSearchResults.Count > 0)
+ {
+ personTmdbId = personSearchResults[0].Id;
+ }
+ }
+
+ var result = new MetadataResult<Person>();
+
+ if (personTmdbId > 0)
+ {
+ var person = await _tmdbClientManager.GetPersonAsync(personTmdbId, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+
+ result.HasMetadata = true;
+
+ var item = new Person
+ {
+ // Take name from incoming info, don't rename the person
+ // TODO: This should go in PersonMetadataService, not each person provider
+ Name = info.Name,
+ HomePageUrl = person.Homepage,
+ Overview = person.Biography,
+ PremiereDate = person.Birthday?.ToUniversalTime(),
+ EndDate = person.Deathday?.ToUniversalTime()
+ };
+
+ if (!string.IsNullOrWhiteSpace(person.PlaceOfBirth))
+ {
+ item.ProductionLocations = new[] { person.PlaceOfBirth };
+ }
+
+ item.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
+
+ if (!string.IsNullOrEmpty(person.ImdbId))
+ {
+ item.SetProviderId(MetadataProvider.Imdb, person.ImdbId);
+ }
+
+ result.HasMetadata = true;
+ result.Item = item;
+ }
+
+ return result;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Plugin.cs b/MediaBrowser.Providers/Plugins/Tmdb/Plugin.cs
new file mode 100644
index 000000000..4adde8366
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Plugin.cs
@@ -0,0 +1,60 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb
+{
+ /// <summary>
+ /// Plugin class for the TMDb library.
+ /// </summary>
+ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Plugin"/> class.
+ /// </summary>
+ /// <param name="applicationPaths">application paths.</param>
+ /// <param name="xmlSerializer">xml serializer.</param>
+ public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ /// <summary>
+ /// Gets the instance of TMDb plugin.
+ /// </summary>
+ public static Plugin Instance { get; private set; }
+
+ /// <inheritdoc/>
+ public override Guid Id => new Guid("b8715ed1-6c47-4528-9ad3-f72deb539cd4");
+
+ /// <inheritdoc/>
+ public override string Name => "TMDb";
+
+ /// <inheritdoc/>
+ public override string Description => "Get metadata for movies and other video content from TheMovieDb.";
+
+ // TODO remove when plugin removed from server.
+
+ /// <inheritdoc/>
+ public override string ConfigurationFileName => "Jellyfin.Plugin.Tmdb.xml";
+
+ /// <summary>
+ /// Return the plugin configuration page.
+ /// </summary>
+ /// <returns>PluginPageInfo.</returns>
+ public IEnumerable<PluginPageInfo> GetPages()
+ {
+ yield return new PluginPageInfo
+ {
+ Name = Name,
+ EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs
new file mode 100644
index 000000000..eb75e9405
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs
@@ -0,0 +1,109 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbEpisodeImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbEpisodeImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ // After TheTvDb
+ public int Order => 1;
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary
+ };
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var episode = (Controller.Entities.TV.Episode)item;
+ var series = episode.Series;
+
+ var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+
+ if (seriesTmdbId <= 0)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var seasonNumber = episode.ParentIndexNumber;
+ var episodeNumber = episode.IndexNumber;
+
+ if (!seasonNumber.HasValue || !episodeNumber.HasValue)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var language = item.GetPreferredMetadataLanguage();
+
+ // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
+ var episodeResult = await _tmdbClientManager
+ .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, series.DisplayOrder, null, null, cancellationToken)
+ .ConfigureAwait(false);
+
+ var stills = episodeResult?.Images?.Stills;
+ if (stills == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var remoteImages = new RemoteImageInfo[stills.Count];
+ for (var i = 0; i < stills.Count; i++)
+ {
+ var image = stills[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetStillUrl(image.FilePath),
+ CommunityRating = image.VoteAverage,
+ VoteCount = image.VoteCount,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
+
+ return remoteImages;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+
+ public bool Supports(BaseItem item)
+ {
+ return item is Controller.Entities.TV.Episode;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs
new file mode 100644
index 000000000..3f826843a
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs
@@ -0,0 +1,216 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbEpisodeProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ // After TheTvDb
+ public int Order => 1;
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
+ {
+ // The search query must either provide an episode number or date
+ if (!searchInfo.IndexNumber.HasValue || !searchInfo.ParentIndexNumber.HasValue)
+ {
+ return Enumerable.Empty<RemoteSearchResult>();
+ }
+
+ var metadataResult = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false);
+
+ if (!metadataResult.HasMetadata)
+ {
+ return Enumerable.Empty<RemoteSearchResult>();
+ }
+
+ var item = metadataResult.Item;
+
+ return new[]
+ {
+ new RemoteSearchResult
+ {
+ IndexNumber = item.IndexNumber,
+ Name = item.Name,
+ ParentIndexNumber = item.ParentIndexNumber,
+ PremiereDate = item.PremiereDate,
+ ProductionYear = item.ProductionYear,
+ ProviderIds = item.ProviderIds,
+ SearchProviderName = Name,
+ IndexNumberEnd = item.IndexNumberEnd
+ }
+ };
+ }
+
+ public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
+ {
+ var metadataResult = new MetadataResult<Episode>();
+
+ // Allowing this will dramatically increase scan times
+ if (info.IsMissingEpisode)
+ {
+ return metadataResult;
+ }
+
+ info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string tmdbId);
+
+ var seriesTmdbId = Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture);
+ if (seriesTmdbId <= 0)
+ {
+ return metadataResult;
+ }
+
+ var seasonNumber = info.ParentIndexNumber;
+ var episodeNumber = info.IndexNumber;
+
+ if (!seasonNumber.HasValue || !episodeNumber.HasValue)
+ {
+ return metadataResult;
+ }
+
+ var episodeResult = await _tmdbClientManager
+ .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.SeriesDisplayOrder, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ if (episodeResult == null)
+ {
+ return metadataResult;
+ }
+
+ metadataResult.HasMetadata = true;
+ metadataResult.QueriedById = true;
+
+ if (!string.IsNullOrEmpty(episodeResult.Overview))
+ {
+ // if overview is non-empty, we can assume that localized data was returned
+ metadataResult.ResultLanguage = info.MetadataLanguage;
+ }
+
+ var item = new Episode
+ {
+ IndexNumber = info.IndexNumber,
+ ParentIndexNumber = info.ParentIndexNumber,
+ IndexNumberEnd = info.IndexNumberEnd,
+ Name = episodeResult.Name,
+ PremiereDate = episodeResult.AirDate,
+ ProductionYear = episodeResult.AirDate?.Year,
+ Overview = episodeResult.Overview,
+ CommunityRating = Convert.ToSingle(episodeResult.VoteAverage)
+ };
+
+ var externalIds = episodeResult.ExternalIds;
+ if (!string.IsNullOrEmpty(externalIds?.TvdbId))
+ {
+ item.SetProviderId(MetadataProvider.Tvdb, externalIds.TvdbId);
+ }
+
+ if (!string.IsNullOrEmpty(externalIds?.ImdbId))
+ {
+ item.SetProviderId(MetadataProvider.Imdb, externalIds.ImdbId);
+ }
+
+ if (!string.IsNullOrEmpty(externalIds?.TvrageId))
+ {
+ item.SetProviderId(MetadataProvider.TvRage, externalIds.TvrageId);
+ }
+
+ if (episodeResult.Videos?.Results != null)
+ {
+ foreach (var video in episodeResult.Videos.Results)
+ {
+ if (TmdbUtils.IsTrailerType(video))
+ {
+ item.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
+ }
+ }
+ }
+
+ var credits = episodeResult.Credits;
+
+ if (credits?.Cast != null)
+ {
+ foreach (var actor in credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order
+ });
+ }
+ }
+
+ if (credits?.GuestStars != null)
+ {
+ foreach (var guest in credits.GuestStars.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = guest.Name.Trim(),
+ Role = guest.Character,
+ Type = PersonType.GuestStar,
+ SortOrder = guest.Order
+ });
+ }
+ }
+
+ // and the rest from crew
+ if (credits?.Crew != null)
+ {
+ foreach (var person in credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ });
+ }
+ }
+
+ metadataResult.Item = item;
+
+ return metadataResult;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs
new file mode 100644
index 000000000..ca44c9bbc
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs
@@ -0,0 +1,99 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbSeasonImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbSeasonImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public int Order => 1;
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var season = (Season)item;
+ var series = season?.Series;
+
+ var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+
+ if (seriesTmdbId <= 0 || season?.IndexNumber == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var language = item.GetPreferredMetadataLanguage();
+
+ // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
+ var seasonResult = await _tmdbClientManager
+ .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, null, null, cancellationToken)
+ .ConfigureAwait(false);
+
+ var posters = seasonResult?.Images?.Posters;
+ if (posters == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var remoteImages = new RemoteImageInfo[posters.Count];
+ for (var i = 0; i < posters.Count; i++)
+ {
+ var image = posters[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(image.FilePath),
+ CommunityRating = image.VoteAverage,
+ VoteCount = image.VoteCount,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
+
+ return remoteImages;
+ }
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary
+ };
+ }
+
+ public bool Supports(BaseItem item)
+ {
+ return item is Season;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs
new file mode 100644
index 000000000..4ac889680
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs
@@ -0,0 +1,121 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbSeasonProvider : IRemoteMetadataProvider<Season, SeasonInfo>
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbSeasonProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ public async Task<MetadataResult<Season>> GetMetadata(SeasonInfo info, CancellationToken cancellationToken)
+ {
+ var result = new MetadataResult<Season>();
+
+ info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string? seriesTmdbId);
+
+ var seasonNumber = info.IndexNumber;
+
+ if (string.IsNullOrWhiteSpace(seriesTmdbId) || !seasonNumber.HasValue)
+ {
+ return result;
+ }
+
+ var seasonResult = await _tmdbClientManager
+ .GetSeasonAsync(Convert.ToInt32(seriesTmdbId, CultureInfo.InvariantCulture), seasonNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ if (seasonResult == null)
+ {
+ return result;
+ }
+
+ result.HasMetadata = true;
+ result.Item = new Season
+ {
+ IndexNumber = seasonNumber,
+ Overview = seasonResult.Overview
+ };
+
+ if (!string.IsNullOrEmpty(seasonResult.ExternalIds?.TvdbId))
+ {
+ result.Item.SetProviderId(MetadataProvider.Tvdb, seasonResult.ExternalIds.TvdbId);
+ }
+
+ // TODO why was this disabled?
+ var credits = seasonResult.Credits;
+ if (credits?.Cast != null)
+ {
+ var cast = credits.Cast.OrderBy(c => c.Order).Take(TmdbUtils.MaxCastMembers).ToList();
+ for (var i = 0; i < cast.Count; i++)
+ {
+ result.AddPerson(new PersonInfo
+ {
+ Name = cast[i].Name.Trim(),
+ Role = cast[i].Character,
+ Type = PersonType.Actor,
+ SortOrder = cast[i].Order
+ });
+ }
+ }
+
+ if (credits?.Crew != null)
+ {
+ foreach (var person in credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ result.AddPerson(new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ });
+ }
+ }
+
+ result.Item.PremiereDate = seasonResult.AirDate;
+ result.Item.ProductionYear = seasonResult.AirDate?.Year;
+
+ return result;
+ }
+
+ public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeasonInfo searchInfo, CancellationToken cancellationToken)
+ {
+ return Task.FromResult(Enumerable.Empty<RemoteSearchResult>());
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesExternalId.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesExternalId.cs
new file mode 100644
index 000000000..8a2be80cd
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesExternalId.cs
@@ -0,0 +1,31 @@
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ /// <summary>
+ /// External ID for a TMDB series.
+ /// </summary>
+ public class TmdbSeriesExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => TmdbUtils.ProviderName;
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Tmdb.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => ExternalIdMediaType.Series;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => TmdbUtils.BaseTmdbUrl + "tv/{0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item)
+ {
+ return item is Series;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs
new file mode 100644
index 000000000..f3f340378
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs
@@ -0,0 +1,117 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbSeriesImageProvider : IRemoteImageProvider, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbSeriesImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ // After tvdb and fanart
+ public int Order => 2;
+
+ public bool Supports(BaseItem item)
+ {
+ return item is Series;
+ }
+
+ public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary,
+ ImageType.Backdrop
+ };
+ }
+
+ public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
+ {
+ var tmdbId = item.GetProviderId(MetadataProvider.Tmdb);
+
+ if (string.IsNullOrEmpty(tmdbId))
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var language = item.GetPreferredMetadataLanguage();
+
+ // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
+ var series = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), null, null, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (series?.Images == null)
+ {
+ return Enumerable.Empty<RemoteImageInfo>();
+ }
+
+ var posters = series.Images.Posters;
+ var backdrops = series.Images.Backdrops;
+
+ var remoteImages = new RemoteImageInfo[posters.Count + backdrops.Count];
+
+ for (var i = 0; i < posters.Count; i++)
+ {
+ var poster = posters[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(poster.FilePath),
+ CommunityRating = poster.VoteAverage,
+ VoteCount = poster.VoteCount,
+ Width = poster.Width,
+ Height = poster.Height,
+ Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
+
+ for (var i = 0; i < backdrops.Count; i++)
+ {
+ var backdrop = series.Images.Backdrops[i];
+ remoteImages[posters.Count + i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
+ CommunityRating = backdrop.VoteAverage,
+ VoteCount = backdrop.VoteCount,
+ Width = backdrop.Width,
+ Height = backdrop.Height,
+ ProviderName = Name,
+ Type = ImageType.Backdrop,
+ RatingType = RatingType.Score
+ };
+ }
+
+ return remoteImages;
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
new file mode 100644
index 000000000..feda15cf7
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
@@ -0,0 +1,389 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using TMDbLib.Objects.Find;
+using TMDbLib.Objects.Search;
+using TMDbLib.Objects.TvShows;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb.TV
+{
+ public class TmdbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
+ {
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILibraryManager _libraryManager;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbSeriesProvider(
+ ILibraryManager libraryManager,
+ IHttpClientFactory httpClientFactory,
+ TmdbClientManager tmdbClientManager)
+ {
+ _libraryManager = libraryManager;
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
+
+ public string Name => TmdbUtils.ProviderName;
+
+ // After TheTVDB
+ public int Order => 1;
+
+ public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
+ {
+ if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var tmdbId))
+ {
+ var series = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (series != null)
+ {
+ var remoteResult = MapTvShowToRemoteSearchResult(series);
+
+ return new[] { remoteResult };
+ }
+ }
+
+ if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
+ {
+ var findResult = await _tmdbClientManager
+ .FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+
+ var tvResults = findResult?.TvResults;
+ if (tvResults != null)
+ {
+ var imdbIdResults = new RemoteSearchResult[tvResults.Count];
+ for (var i = 0; i < tvResults.Count; i++)
+ {
+ var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
+ remoteResult.SetProviderId(MetadataProvider.Imdb, imdbId);
+ imdbIdResults[i] = remoteResult;
+ }
+
+ return imdbIdResults;
+ }
+ }
+
+ if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
+ {
+ var findResult = await _tmdbClientManager
+ .FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+
+ var tvResults = findResult?.TvResults;
+ if (tvResults != null)
+ {
+ var tvIdResults = new RemoteSearchResult[tvResults.Count];
+ for (var i = 0; i < tvResults.Count; i++)
+ {
+ var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
+ remoteResult.SetProviderId(MetadataProvider.Tvdb, tvdbId);
+ tvIdResults[i] = remoteResult;
+ }
+
+ return tvIdResults;
+ }
+ }
+
+ var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ var remoteResults = new RemoteSearchResult[tvSearchResults.Count];
+ for (var i = 0; i < tvSearchResults.Count; i++)
+ {
+ remoteResults[i] = MapSearchTvToRemoteSearchResult(tvSearchResults[i]);
+ }
+
+ return remoteResults;
+ }
+
+ private RemoteSearchResult MapTvShowToRemoteSearchResult(TvShow series)
+ {
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = series.Name ?? series.OriginalName,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
+ Overview = series.Overview
+ };
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
+ if (series.ExternalIds != null)
+ {
+ if (!string.IsNullOrEmpty(series.ExternalIds.ImdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Imdb, series.ExternalIds.ImdbId);
+ }
+
+ if (!string.IsNullOrEmpty(series.ExternalIds.TvdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Tvdb, series.ExternalIds.TvdbId);
+ }
+ }
+
+ remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
+
+ return remoteResult;
+ }
+
+ private RemoteSearchResult MapSearchTvToRemoteSearchResult(SearchTv series)
+ {
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = series.Name ?? series.OriginalName,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
+ Overview = series.Overview
+ };
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
+ remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
+
+ return remoteResult;
+ }
+
+ public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
+ {
+ var result = new MetadataResult<Series>
+ {
+ QueriedById = true
+ };
+
+ var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
+
+ if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
+ {
+ var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+ if (searchResult?.TvResults.Count > 0)
+ {
+ tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
+ {
+ var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+ if (searchResult?.TvResults.Count > 0)
+ {
+ tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId))
+ {
+ result.QueriedById = false;
+ // ParseName is required here.
+ // Caller provides the filename with extension stripped and NOT the parsed filename
+ var parsedName = _libraryManager.ParseName(info.Name);
+ var cleanedName = TmdbUtils.CleanName(parsedName.Name);
+ var searchResults = await _tmdbClientManager.SearchSeriesAsync(cleanedName, info.MetadataLanguage, info.Year ?? parsedName.Year ?? 0, cancellationToken).ConfigureAwait(false);
+
+ if (searchResults.Count > 0)
+ {
+ tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId))
+ {
+ return result;
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tvShow = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ result = new MetadataResult<Series>
+ {
+ Item = MapTvShowToSeries(tvShow, info.MetadataCountryCode),
+ ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage
+ };
+
+ foreach (var person in GetPersons(tvShow))
+ {
+ result.AddPerson(person);
+ }
+
+ result.HasMetadata = result.Item != null;
+
+ return result;
+ }
+
+ private static Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode)
+ {
+ var series = new Series
+ {
+ Name = seriesResult.Name,
+ OriginalTitle = seriesResult.OriginalName
+ };
+
+ series.SetProviderId(MetadataProvider.Tmdb, seriesResult.Id.ToString(CultureInfo.InvariantCulture));
+
+ series.CommunityRating = Convert.ToSingle(seriesResult.VoteAverage);
+
+ series.Overview = seriesResult.Overview;
+
+ if (seriesResult.Networks != null)
+ {
+ series.Studios = seriesResult.Networks.Select(i => i.Name).ToArray();
+ }
+
+ if (seriesResult.Genres != null)
+ {
+ series.Genres = seriesResult.Genres.Select(i => i.Name).ToArray();
+ }
+
+ if (seriesResult.Keywords?.Results != null)
+ {
+ for (var i = 0; i < seriesResult.Keywords.Results.Count; i++)
+ {
+ series.AddTag(seriesResult.Keywords.Results[i].Name);
+ }
+ }
+
+ series.HomePageUrl = seriesResult.Homepage;
+
+ series.RunTimeTicks = seriesResult.EpisodeRunTime.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();
+
+ if (string.Equals(seriesResult.Status, "Ended", StringComparison.OrdinalIgnoreCase))
+ {
+ series.Status = SeriesStatus.Ended;
+ series.EndDate = seriesResult.LastAirDate;
+ }
+ else
+ {
+ series.Status = SeriesStatus.Continuing;
+ }
+
+ series.PremiereDate = seriesResult.FirstAirDate;
+
+ var ids = seriesResult.ExternalIds;
+ if (ids != null)
+ {
+ if (!string.IsNullOrWhiteSpace(ids.ImdbId))
+ {
+ series.SetProviderId(MetadataProvider.Imdb, ids.ImdbId);
+ }
+
+ if (!string.IsNullOrEmpty(ids.TvrageId))
+ {
+ series.SetProviderId(MetadataProvider.TvRage, ids.TvrageId);
+ }
+
+ if (!string.IsNullOrEmpty(ids.TvdbId))
+ {
+ series.SetProviderId(MetadataProvider.Tvdb, ids.TvdbId);
+ }
+ }
+
+ var contentRatings = seriesResult.ContentRatings.Results ?? new List<ContentRating>();
+
+ var ourRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
+ var usRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
+ var minimumRelease = contentRatings.FirstOrDefault();
+
+ if (ourRelease != null)
+ {
+ series.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Rating);
+ }
+ else if (usRelease != null)
+ {
+ series.OfficialRating = usRelease.Rating;
+ }
+ else if (minimumRelease != null)
+ {
+ series.OfficialRating = minimumRelease.Rating;
+ }
+
+ if (seriesResult.Videos?.Results != null)
+ {
+ foreach (var video in seriesResult.Videos.Results)
+ {
+ if (TmdbUtils.IsTrailerType(video))
+ {
+ series.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
+ }
+ }
+ }
+
+ return series;
+ }
+
+ private IEnumerable<PersonInfo> GetPersons(TvShow seriesResult)
+ {
+ if (seriesResult.Credits?.Cast != null)
+ {
+ foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ var personInfo = new PersonInfo
+ {
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(actor.ProfilePath)
+ };
+
+ if (actor.Id > 0)
+ {
+ personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
+ }
+
+ yield return personInfo;
+ }
+ }
+
+ if (seriesResult.Credits?.Crew != null)
+ {
+ var keepTypes = new[]
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
+ };
+
+ foreach (var person in seriesResult.Credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ yield return new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ };
+ }
+ }
+ }
+
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
+ {
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
new file mode 100644
index 000000000..74be4c793
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
@@ -0,0 +1,558 @@
+#nullable disable
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Caching.Memory;
+using TMDbLib.Client;
+using TMDbLib.Objects.Collections;
+using TMDbLib.Objects.Find;
+using TMDbLib.Objects.General;
+using TMDbLib.Objects.Movies;
+using TMDbLib.Objects.People;
+using TMDbLib.Objects.Search;
+using TMDbLib.Objects.TvShows;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb
+{
+ /// <summary>
+ /// Manager class for abstracting the TMDb API client library.
+ /// </summary>
+ public class TmdbClientManager : IDisposable
+ {
+ private const int CacheDurationInHours = 1;
+
+ private readonly IMemoryCache _memoryCache;
+ private readonly TMDbClient _tmDbClient;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TmdbClientManager"/> class.
+ /// </summary>
+ /// <param name="memoryCache">An instance of <see cref="IMemoryCache"/>.</param>
+ public TmdbClientManager(IMemoryCache memoryCache)
+ {
+ _memoryCache = memoryCache;
+ _tmDbClient = new TMDbClient(TmdbUtils.ApiKey);
+ // Not really interested in NotFoundException
+ _tmDbClient.ThrowApiExceptions = false;
+ }
+
+ /// <summary>
+ /// Gets a movie from the TMDb API based on its TMDb id.
+ /// </summary>
+ /// <param name="tmdbId">The movie's TMDb id.</param>
+ /// <param name="language">The movie's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb movie or null if not found.</returns>
+ public async Task<Movie> GetMovieAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out Movie movie))
+ {
+ return movie;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ movie = await _tmDbClient.GetMovieAsync(
+ tmdbId,
+ TmdbUtils.NormalizeLanguage(language),
+ imageLanguages,
+ MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Keywords | MovieMethods.Videos,
+ cancellationToken).ConfigureAwait(false);
+
+ if (movie != null)
+ {
+ _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return movie;
+ }
+
+ /// <summary>
+ /// Gets a collection from the TMDb API based on its TMDb id.
+ /// </summary>
+ /// <param name="tmdbId">The collection's TMDb id.</param>
+ /// <param name="language">The collection's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb collection or null if not found.</returns>
+ public async Task<Collection> GetCollectionAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out Collection collection))
+ {
+ return collection;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ collection = await _tmDbClient.GetCollectionAsync(
+ tmdbId,
+ TmdbUtils.NormalizeLanguage(language),
+ imageLanguages,
+ CollectionMethods.Images,
+ cancellationToken).ConfigureAwait(false);
+
+ if (collection != null)
+ {
+ _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return collection;
+ }
+
+ /// <summary>
+ /// Gets a tv show from the TMDb API based on its TMDb id.
+ /// </summary>
+ /// <param name="tmdbId">The tv show's TMDb id.</param>
+ /// <param name="language">The tv show's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb tv show information or null if not found.</returns>
+ public async Task<TvShow> GetSeriesAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvShow series))
+ {
+ return series;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ series = await _tmDbClient.GetTvShowAsync(
+ tmdbId,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings | TvShowMethods.EpisodeGroups,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (series != null)
+ {
+ _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return series;
+ }
+
+ /// <summary>
+ /// Gets a tv show episode group from the TMDb API based on the show id and the display order.
+ /// </summary>
+ /// <param name="tvShowId">The tv show's TMDb id.</param>
+ /// <param name="displayOrder">The display order.</param>
+ /// <param name="language">The tv show's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb tv show episode group information or null if not found.</returns>
+ private async Task<TvGroupCollection> GetSeriesGroupAsync(int tvShowId, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ TvGroupType? groupType =
+ string.Equals(displayOrder, "absolute", StringComparison.Ordinal) ? TvGroupType.Absolute :
+ string.Equals(displayOrder, "dvd", StringComparison.Ordinal) ? TvGroupType.DVD :
+ null;
+
+ if (groupType == null)
+ {
+ return null;
+ }
+
+ var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvGroupCollection group))
+ {
+ return group;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var series = await GetSeriesAsync(tvShowId, language, imageLanguages, cancellationToken).ConfigureAwait(false);
+ var episodeGroupId = series?.EpisodeGroups.Results.Find(g => g.Type == groupType)?.Id;
+
+ if (episodeGroupId == null)
+ {
+ return null;
+ }
+
+ group = await _tmDbClient.GetTvEpisodeGroupsAsync(
+ episodeGroupId,
+ language: TmdbUtils.NormalizeLanguage(language),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (group != null)
+ {
+ _memoryCache.Set(key, group, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return group;
+ }
+
+ /// <summary>
+ /// Gets a tv season from the TMDb API based on the tv show's TMDb id.
+ /// </summary>
+ /// <param name="tvShowId">The tv season's TMDb id.</param>
+ /// <param name="seasonNumber">The season number.</param>
+ /// <param name="language">The tv season's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb tv season information or null if not found.</returns>
+ public async Task<TvSeason> GetSeasonAsync(int tvShowId, int seasonNumber, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvSeason season))
+ {
+ return season;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ season = await _tmDbClient.GetTvSeasonAsync(
+ tvShowId,
+ seasonNumber,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonMethods.Videos,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (season != null)
+ {
+ _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return season;
+ }
+
+ /// <summary>
+ /// Gets a movie from the TMDb API based on the tv show's TMDb id.
+ /// </summary>
+ /// <param name="tvShowId">The tv show's TMDb id.</param>
+ /// <param name="seasonNumber">The season number.</param>
+ /// <param name="episodeNumber">The episode number.</param>
+ /// <param name="displayOrder">The display order.</param>
+ /// <param name="language">The episode's language.</param>
+ /// <param name="imageLanguages">A comma-separated list of image languages.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb tv episode information or null if not found.</returns>
+ public async Task<TvEpisode> GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvEpisode episode))
+ {
+ return episode;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var group = await GetSeriesGroupAsync(tvShowId, displayOrder, language, imageLanguages, cancellationToken).ConfigureAwait(false);
+ if (group != null)
+ {
+ var season = group.Groups.Find(s => s.Order == seasonNumber);
+ // Episode order starts at 0
+ var ep = season?.Episodes.Find(e => e.Order == episodeNumber - 1);
+ if (ep != null)
+ {
+ seasonNumber = ep.SeasonNumber;
+ episodeNumber = ep.EpisodeNumber;
+ }
+ }
+
+ episode = await _tmDbClient.GetTvEpisodeAsync(
+ tvShowId,
+ seasonNumber,
+ episodeNumber,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpisodeMethods.Videos,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (episode != null)
+ {
+ _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return episode;
+ }
+
+ /// <summary>
+ /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id.
+ /// </summary>
+ /// <param name="personTmdbId">The person's TMDb id.</param>
+ /// <param name="language">The episode's language.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb person information or null if not found.</returns>
+ public async Task<Person> GetPersonAsync(int personTmdbId, string language, CancellationToken cancellationToken)
+ {
+ var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out Person person))
+ {
+ return person;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ person = await _tmDbClient.GetPersonAsync(
+ personTmdbId,
+ TmdbUtils.NormalizeLanguage(language),
+ PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
+ cancellationToken).ConfigureAwait(false);
+
+ if (person != null)
+ {
+ _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return person;
+ }
+
+ /// <summary>
+ /// Gets an item from the TMDb API based on its id from an external service eg. IMDb id, TvDb id.
+ /// </summary>
+ /// <param name="externalId">The item's external id.</param>
+ /// <param name="source">The source of the id eg. IMDb.</param>
+ /// <param name="language">The item's language.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb item or null if not found.</returns>
+ public async Task<FindContainer> FindByExternalIdAsync(
+ string externalId,
+ FindExternalSource source,
+ string language,
+ CancellationToken cancellationToken)
+ {
+ var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out FindContainer result))
+ {
+ return result;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ result = await _tmDbClient.FindAsync(
+ source,
+ externalId,
+ TmdbUtils.NormalizeLanguage(language),
+ cancellationToken).ConfigureAwait(false);
+
+ if (result != null)
+ {
+ _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Searches for a tv show using the TMDb API based on its name.
+ /// </summary>
+ /// <param name="name">The name of the tv show.</param>
+ /// <param name="language">The tv show's language.</param>
+ /// <param name="year">The year the tv show first aired.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <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}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv> series))
+ {
+ return series.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), includeAdult: Plugin.Instance.Configuration.IncludeAdult, firstAirDateYear: year, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ /// <summary>
+ /// Searches for a person based on their name using the TMDb API.
+ /// </summary>
+ /// <param name="name">The name of the person.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb person information.</returns>
+ public async Task<IReadOnlyList<SearchPerson>> SearchPersonAsync(string name, CancellationToken cancellationToken)
+ {
+ var key = $"searchperson-{name}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer<SearchPerson> person))
+ {
+ return person.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchPersonAsync(name, includeAdult: Plugin.Instance.Configuration.IncludeAdult, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ /// <summary>
+ /// Searches for a movie based on its name using the TMDb API.
+ /// </summary>
+ /// <param name="name">The name of the movie.</param>
+ /// <param name="language">The movie's language.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb movie information.</returns>
+ public Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, string language, CancellationToken cancellationToken)
+ {
+ return SearchMovieAsync(name, 0, language, cancellationToken);
+ }
+
+ /// <summary>
+ /// Searches for a movie based on its name using the TMDb API.
+ /// </summary>
+ /// <param name="name">The name of the movie.</param>
+ /// <param name="year">The release year of the movie.</param>
+ /// <param name="language">The movie's language.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb movie information.</returns>
+ public async Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, int year, string language, CancellationToken cancellationToken)
+ {
+ var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer<SearchMovie> movies))
+ {
+ return movies.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language), includeAdult: Plugin.Instance.Configuration.IncludeAdult, year: year, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ /// <summary>
+ /// Searches for a collection based on its name using the TMDb API.
+ /// </summary>
+ /// <param name="name">The name of the collection.</param>
+ /// <param name="language">The collection's language.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The TMDb collection information.</returns>
+ public async Task<IReadOnlyList<SearchCollection>> SearchCollectionAsync(string name, string language, CancellationToken cancellationToken)
+ {
+ var key = $"collectionsearch-{name}-{language}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer<SearchCollection> collections))
+ {
+ return collections.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ /// <summary>
+ /// Gets the absolute URL of the poster.
+ /// </summary>
+ /// <param name="posterPath">The relative URL of the poster.</param>
+ /// <returns>The absolute URL.</returns>
+ public string GetPosterUrl(string posterPath)
+ {
+ if (string.IsNullOrEmpty(posterPath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.PosterSizes[^1], posterPath).ToString();
+ }
+
+ /// <summary>
+ /// Gets the absolute URL of the backdrop image.
+ /// </summary>
+ /// <param name="posterPath">The relative URL of the backdrop image.</param>
+ /// <returns>The absolute URL.</returns>
+ public string GetBackdropUrl(string posterPath)
+ {
+ if (string.IsNullOrEmpty(posterPath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.BackdropSizes[^1], posterPath).ToString();
+ }
+
+ /// <summary>
+ /// Gets the absolute URL of the profile image.
+ /// </summary>
+ /// <param name="actorProfilePath">The relative URL of the profile image.</param>
+ /// <returns>The absolute URL.</returns>
+ public string GetProfileUrl(string actorProfilePath)
+ {
+ if (string.IsNullOrEmpty(actorProfilePath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.ProfileSizes[^1], actorProfilePath).ToString();
+ }
+
+ /// <summary>
+ /// Gets the absolute URL of the still image.
+ /// </summary>
+ /// <param name="filePath">The relative URL of the still image.</param>
+ /// <returns>The absolute URL.</returns>
+ public string GetStillUrl(string filePath)
+ {
+ if (string.IsNullOrEmpty(filePath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.StillSizes[^1], filePath).ToString();
+ }
+
+ private Task EnsureClientConfigAsync()
+ {
+ return !_tmDbClient.HasConfig ? _tmDbClient.GetConfigAsync() : Task.CompletedTask;
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+/// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _memoryCache?.Dispose();
+ _tmDbClient?.Dispose();
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
new file mode 100644
index 000000000..58ab9f547
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
@@ -0,0 +1,196 @@
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+using MediaBrowser.Model.Entities;
+using TMDbLib.Objects.General;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb
+{
+ /// <summary>
+ /// Utilities for the TMDb provider.
+ /// </summary>
+ public static class TmdbUtils
+ {
+ private static readonly Regex _nonWords = new (@"[\W_]+", RegexOptions.Compiled);
+
+ /// <summary>
+ /// URL of the TMDB instance to use.
+ /// </summary>
+ public const string BaseTmdbUrl = "https://www.themoviedb.org/";
+
+ /// <summary>
+ /// Name of the provider.
+ /// </summary>
+ public const string ProviderName = "TheMovieDb";
+
+ /// <summary>
+ /// API key to use when performing an API call.
+ /// </summary>
+ public const string ApiKey = "4219e299c89411838049ab0dab19ebd5";
+
+ /// <summary>
+ /// Maximum number of cast members to pull.
+ /// </summary>
+ public const int MaxCastMembers = 15;
+
+ /// <summary>
+ /// The crew types to keep.
+ /// </summary>
+ public static readonly string[] WantedCrewTypes =
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
+ };
+
+ /// <summary>
+ /// Cleans the name according to TMDb requirements.
+ /// </summary>
+ /// <param name="name">The name of the entity.</param>
+ /// <returns>The cleaned name.</returns>
+ public static string CleanName(string name)
+ {
+ // TMDb expects a space separated list of words make sure that is the case
+ return _nonWords.Replace(name, " ");
+ }
+
+ /// <summary>
+ /// Maps the TMDB provided roles for crew members to Jellyfin roles.
+ /// </summary>
+ /// <param name="crew">Crew member to map against the Jellyfin person types.</param>
+ /// <returns>The Jellyfin person type.</returns>
+ public static string MapCrewToPersonType(Crew crew)
+ {
+ if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase)
+ && crew.Job.Contains("director", StringComparison.OrdinalIgnoreCase))
+ {
+ return PersonType.Director;
+ }
+
+ if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase)
+ && crew.Job.Contains("producer", StringComparison.OrdinalIgnoreCase))
+ {
+ return PersonType.Producer;
+ }
+
+ if (crew.Department.Equals("writing", StringComparison.OrdinalIgnoreCase))
+ {
+ return PersonType.Writer;
+ }
+
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Determines whether a video is a trailer.
+ /// </summary>
+ /// <param name="video">The TMDb video.</param>
+ /// <returns>A boolean indicating whether the video is a trailer.</returns>
+ public static bool IsTrailerType(Video video)
+ {
+ return video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase)
+ && (!video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase)
+ || !video.Type.Equals("teaser", StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// <summary>
+ /// Normalizes a language string for use with TMDb's include image language parameter.
+ /// </summary>
+ /// <param name="preferredLanguage">The preferred language as either a 2 letter code with or without country code.</param>
+ /// <returns>The comma separated language string.</returns>
+ public static string GetImageLanguagesParam(string preferredLanguage)
+ {
+ var languages = new List<string>();
+
+ if (!string.IsNullOrEmpty(preferredLanguage))
+ {
+ preferredLanguage = NormalizeLanguage(preferredLanguage);
+
+ languages.Add(preferredLanguage);
+
+ if (preferredLanguage.Length == 5) // like en-US
+ {
+ // Currently, TMDB supports 2-letter language codes only
+ // They are planning to change this in the future, thus we're
+ // supplying both codes if we're having a 5-letter code.
+ languages.Add(preferredLanguage.Substring(0, 2));
+ }
+ }
+
+ languages.Add("null");
+
+ if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
+ {
+ languages.Add("en");
+ }
+
+ return string.Join(',', languages);
+ }
+
+ /// <summary>
+ /// Normalizes a language string for use with TMDb's language parameter.
+ /// </summary>
+ /// <param name="language">The language code.</param>
+ /// <returns>The normalized language code.</returns>
+ public static string NormalizeLanguage(string language)
+ {
+ if (string.IsNullOrEmpty(language))
+ {
+ return language;
+ }
+
+ // They require this to be uppercase
+ // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api.
+ // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
+ var parts = language.Split('-');
+
+ if (parts.Length == 2)
+ {
+ // TMDB doesn't support Switzerland (de-CH, it-CH or fr-CH) so use the language (de, it or fr) without country code
+ if (string.Equals(parts[1], "CH", StringComparison.OrdinalIgnoreCase))
+ {
+ return parts[0];
+ }
+
+ language = parts[0] + "-" + parts[1].ToUpperInvariant();
+ }
+
+ return language;
+ }
+
+ /// <summary>
+ /// Adjusts the image's language code preferring the 5 letter language code eg. en-US.
+ /// </summary>
+ /// <param name="imageLanguage">The image's actual language code.</param>
+ /// <param name="requestLanguage">The requested language code.</param>
+ /// <returns>The language code.</returns>
+ public static string AdjustImageLanguage(string imageLanguage, string requestLanguage)
+ {
+ if (!string.IsNullOrEmpty(imageLanguage)
+ && !string.IsNullOrEmpty(requestLanguage)
+ && requestLanguage.Length > 2
+ && imageLanguage.Length == 2
+ && requestLanguage.StartsWith(imageLanguage, StringComparison.OrdinalIgnoreCase))
+ {
+ return requestLanguage;
+ }
+
+ return imageLanguage;
+ }
+
+ /// <summary>
+ /// Combines the metadata country code and the parental rating from the Api into the value we store in our database.
+ /// </summary>
+ /// <param name="countryCode">The Iso 3166-1 country code of the rating country.</param>
+ /// <param name="ratingValue">The rating value returned by the Tmdb Api.</param>
+ /// <returns>The combined parental rating of country code+rating value.</returns>
+ public static string BuildParentalRating(string countryCode, string ratingValue)
+ {
+ // exclude US because we store us values as TV-14 without the country code.
+ var ratingPrefix = string.Equals(countryCode, "US", StringComparison.OrdinalIgnoreCase) ? string.Empty : countryCode + "-";
+ var newRating = ratingPrefix + ratingValue;
+
+ return newRating.Replace("DE-", "FSK-", StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Properties/AssemblyInfo.cs b/MediaBrowser.Providers/Properties/AssemblyInfo.cs
index d2b13fc89..bd301b5f0 100644
--- a/MediaBrowser.Providers/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.Providers/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -9,11 +10,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.Providers.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/MediaBrowser.Providers/Studios/StudioMetadataService.cs b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
index 78204dccf..091b33ce0 100644
--- a/MediaBrowser.Providers/Studios/StudioMetadataService.cs
+++ b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Studios
{
public class StudioMetadataService : MetadataService<Studio, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<Studio> source, MetadataResult<Studio> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public StudioMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<StudioMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public StudioMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Studio> source, MetadataResult<Studio> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs
index 4b41589f1..7f1665532 100644
--- a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs
+++ b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs
@@ -1,11 +1,17 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
@@ -18,18 +24,20 @@ namespace MediaBrowser.Providers.Studios
public class StudiosImageProvider : IRemoteImageProvider
{
private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
+ private readonly IHttpClientFactory _httpClientFactory;
private readonly IFileSystem _fileSystem;
- public StudiosImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem)
+ public StudiosImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory, IFileSystem fileSystem)
{
_config = config;
- _httpClient = httpClient;
+ _httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
}
public string Name => "Emby Designs";
+ public int Order => 0;
+
public bool Supports(BaseItem item)
{
return item is Studio;
@@ -78,7 +86,7 @@ namespace MediaBrowser.Providers.Studios
private RemoteImageInfo GetImage(BaseItem item, string filename, ImageType type, string remoteFilename)
{
- var list = GetAvailableImages(filename, _fileSystem);
+ var list = GetAvailableImages(filename);
var match = FindMatch(item, list);
@@ -99,33 +107,27 @@ namespace MediaBrowser.Providers.Studios
private string GetUrl(string image, string filename)
{
- return string.Format("https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname/studios/{0}/{1}.jpg", image, filename);
+ return string.Format(CultureInfo.InvariantCulture, "https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname/studios/{0}/{1}.jpg", image, filename);
}
private Task<string> EnsureThumbsList(string file, CancellationToken cancellationToken)
{
const string url = "https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname/studiothumbs.txt";
- return EnsureList(url, file, _httpClient, _fileSystem, cancellationToken);
+ return EnsureList(url, file, _fileSystem, cancellationToken);
}
private Task<string> EnsurePosterList(string file, CancellationToken cancellationToken)
{
const string url = "https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname/studioposters.txt";
- return EnsureList(url, file, _httpClient, _fileSystem, cancellationToken);
+ return EnsureList(url, file, _fileSystem, cancellationToken);
}
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
+ public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url,
- BufferContent = false
- });
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ return httpClient.GetAsync(url, cancellationToken);
}
/// <summary>
@@ -133,36 +135,21 @@ namespace MediaBrowser.Providers.Studios
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="file">The file.</param>
- /// <param name="httpClient">The HTTP client.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- public async Task<string> EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, CancellationToken cancellationToken)
+ public async Task<string> EnsureList(string url, string file, IFileSystem fileSystem, CancellationToken cancellationToken)
{
var fileInfo = fileSystem.GetFileInfo(file);
if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
{
- var temp = await httpClient.GetTempFile(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Progress = new SimpleProgress<double>(),
- Url = url
-
- }).ConfigureAwait(false);
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
Directory.CreateDirectory(Path.GetDirectoryName(file));
-
- try
- {
- File.Copy(temp, file, true);
- }
- catch
- {
-
- }
-
- return temp;
+ await using var response = await httpClient.GetStreamAsync(url, cancellationToken).ConfigureAwait(false);
+ await using var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+ await response.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
}
return file;
@@ -177,36 +164,26 @@ namespace MediaBrowser.Providers.Studios
private string GetComparableName(string name)
{
- return name.Replace(" ", string.Empty)
- .Replace(".", string.Empty)
- .Replace("&", string.Empty)
- .Replace("!", string.Empty)
- .Replace(",", string.Empty)
- .Replace("/", string.Empty);
+ return name.Replace(" ", string.Empty, StringComparison.Ordinal)
+ .Replace(".", string.Empty, StringComparison.Ordinal)
+ .Replace("&", string.Empty, StringComparison.Ordinal)
+ .Replace("!", string.Empty, StringComparison.Ordinal)
+ .Replace(",", string.Empty, StringComparison.Ordinal)
+ .Replace("/", string.Empty, StringComparison.Ordinal);
}
- public IEnumerable<string> GetAvailableImages(string file, IFileSystem fileSystem)
+ public IEnumerable<string> GetAvailableImages(string file)
{
- using (var fileStream = fileSystem.GetFileStream(file, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
+ using var fileStream = File.OpenRead(file);
+ using var reader = new StreamReader(fileStream);
+
+ foreach (var line in reader.ReadAllLines())
{
- using (var reader = new StreamReader(fileStream))
+ if (!string.IsNullOrWhiteSpace(line))
{
- var lines = new List<string>();
-
- while (!reader.EndOfStream)
- {
- var text = reader.ReadLine();
-
- if (!string.IsNullOrWhiteSpace(text))
- {
- lines.Add(text);
- }
- }
-
- return lines;
+ yield return line;
}
}
}
-
}
}
diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
index 7fc6909f5..c2b420c33 100644
--- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
+++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
@@ -1,12 +1,15 @@
+#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 MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
@@ -25,41 +28,40 @@ namespace MediaBrowser.Providers.Subtitles
{
public class SubtitleManager : ISubtitleManager
{
- private ISubtitleProvider[] _subtitleProviders;
- private readonly ILogger _logger;
+ private readonly ILogger<SubtitleManager> _logger;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _monitor;
private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly ILocalizationManager _localization;
- public event EventHandler<SubtitleDownloadFailureEventArgs> SubtitleDownloadFailure;
-
- private ILocalizationManager _localization;
+ private ISubtitleProvider[] _subtitleProviders;
public SubtitleManager(
- ILoggerFactory loggerFactory,
+ ILogger<SubtitleManager> logger,
IFileSystem fileSystem,
ILibraryMonitor monitor,
IMediaSourceManager mediaSourceManager,
ILocalizationManager localizationManager)
{
- _logger = loggerFactory.CreateLogger(nameof(SubtitleManager));
+ _logger = logger;
_fileSystem = fileSystem;
_monitor = monitor;
_mediaSourceManager = mediaSourceManager;
_localization = localizationManager;
}
+ /// <inheritdoc />
+ public event EventHandler<SubtitleDownloadFailureEventArgs> SubtitleDownloadFailure;
+
+ /// <inheritdoc />
public void AddParts(IEnumerable<ISubtitleProvider> subtitleProviders)
{
_subtitleProviders = subtitleProviders
- .OrderBy(i =>
- {
- var hasOrder = i as IHasOrder;
- return hasOrder == null ? 0 : hasOrder.Order;
- })
+ .OrderBy(i => i is IHasOrder hasOrder ? hasOrder.Order : 0)
.ToArray();
}
+ /// <inheritdoc />
public async Task<RemoteSubtitleInfo[]> SearchSubtitles(SubtitleSearchRequest request, CancellationToken cancellationToken)
{
if (request.Language != null)
@@ -105,7 +107,8 @@ namespace MediaBrowser.Providers.Subtitles
_logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name);
}
}
- return new RemoteSubtitleInfo[] { };
+
+ return Array.Empty<RemoteSubtitleInfo>();
}
var tasks = providers.Select(async i =>
@@ -121,7 +124,7 @@ namespace MediaBrowser.Providers.Subtitles
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading subtitles from {0}", i.Name);
- return new RemoteSubtitleInfo[] { };
+ return Array.Empty<RemoteSubtitleInfo>();
}
});
@@ -130,6 +133,7 @@ namespace MediaBrowser.Providers.Subtitles
return results.SelectMany(i => i).ToArray();
}
+ /// <inheritdoc />
public Task DownloadSubtitles(Video video, string subtitleId, CancellationToken cancellationToken)
{
var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video);
@@ -137,47 +141,21 @@ namespace MediaBrowser.Providers.Subtitles
return DownloadSubtitles(video, libraryOptions, subtitleId, cancellationToken);
}
- public async Task DownloadSubtitles(Video video,
+ /// <inheritdoc />
+ public async Task DownloadSubtitles(
+ Video video,
LibraryOptions libraryOptions,
string subtitleId,
CancellationToken cancellationToken)
{
- var parts = subtitleId.Split(new[] { '_' }, 2);
- var provider = GetProvider(parts.First());
-
- var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;
+ var parts = subtitleId.Split('_', 2);
+ var provider = GetProvider(parts[0]);
try
{
var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false);
- using (var stream = response.Stream)
- {
- using (var memoryStream = new MemoryStream())
- {
- await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
- memoryStream.Position = 0;
-
- var savePaths = new List<string>();
- var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant();
-
- if (response.IsForced)
- {
- saveFileName += ".forced";
- }
-
- saveFileName += "." + response.Format.ToLowerInvariant();
-
- if (saveInMediaFolder)
- {
- savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName));
- }
-
- savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName));
-
- await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
- }
- }
+ await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false);
}
catch (RateLimitExceededException)
{
@@ -196,13 +174,70 @@ namespace MediaBrowser.Providers.Subtitles
}
}
+ /// <inheritdoc />
+ public Task UploadSubtitle(Video video, SubtitleResponse response)
+ {
+ var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video);
+ return TrySaveSubtitle(video, libraryOptions, response);
+ }
+
+ private async Task TrySaveSubtitle(
+ Video video,
+ LibraryOptions libraryOptions,
+ SubtitleResponse response)
+ {
+ var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;
+
+ await using var stream = response.Stream;
+ await using var memoryStream = new MemoryStream();
+ await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
+ memoryStream.Position = 0;
+
+ var savePaths = new List<string>();
+ var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant();
+
+ if (response.IsForced)
+ {
+ saveFileName += ".forced";
+ }
+
+ saveFileName += "." + response.Format.ToLowerInvariant();
+
+ if (saveInMediaFolder)
+ {
+ var mediaFolderPath = Path.GetFullPath(Path.Combine(video.ContainingFolderPath, saveFileName));
+ // TODO: Add some error handling to the API user: return BadRequest("Could not save subtitle, bad path.");
+ if (mediaFolderPath.StartsWith(video.ContainingFolderPath, StringComparison.Ordinal))
+ {
+ savePaths.Add(mediaFolderPath);
+ }
+ }
+
+ var internalPath = Path.GetFullPath(Path.Combine(video.GetInternalMetadataPath(), saveFileName));
+
+ // TODO: Add some error to the user: return BadRequest("Could not save subtitle, bad path.");
+ if (internalPath.StartsWith(video.GetInternalMetadataPath(), StringComparison.Ordinal))
+ {
+ savePaths.Add(internalPath);
+ }
+
+ if (savePaths.Count > 0)
+ {
+ await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
+ }
+ else
+ {
+ _logger.LogError("An uploaded subtitle could not be saved because the resulting paths were invalid.");
+ }
+ }
+
private async Task TrySaveToFiles(Stream stream, List<string> savePaths)
{
- Exception exceptionToThrow = null;
+ List<Exception> exs = null;
foreach (var savePath in savePaths)
{
- _logger.LogInformation("Saving subtitles to {0}", savePath);
+ _logger.LogInformation("Saving subtitles to {SavePath}", savePath);
_monitor.ReportFileSystemChangeBeginning(savePath);
@@ -210,19 +245,20 @@ namespace MediaBrowser.Providers.Subtitles
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
- using (var fs = _fileSystem.GetFileStream(savePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(fs).ConfigureAwait(false);
- }
+ var fileOptions = AsyncFile.WriteOptions;
+ fileOptions.Mode = FileMode.CreateNew;
+ fileOptions.PreallocationSize = stream.Length;
+ using var fs = new FileStream(savePath, fileOptions);
+ await stream.CopyToAsync(fs).ConfigureAwait(false);
return;
}
catch (Exception ex)
{
- if (exceptionToThrow == null)
- {
- exceptionToThrow = ex;
- }
+// Bug in analyzer -- https://github.com/dotnet/roslyn-analyzers/issues/5160
+#pragma warning disable CA1508
+ (exs ??= new List<Exception>()).Add(ex);
+#pragma warning restore CA1508
}
finally
{
@@ -232,17 +268,18 @@ namespace MediaBrowser.Providers.Subtitles
stream.Position = 0;
}
- if (exceptionToThrow != null)
+ if (exs != null)
{
- throw exceptionToThrow;
+ throw new AggregateException(exs);
}
}
- public Task<RemoteSubtitleInfo[]> SearchSubtitles(Video video, string language, bool? isPerfectMatch, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task<RemoteSubtitleInfo[]> SearchSubtitles(Video video, string language, bool? isPerfectMatch, bool isAutomated, CancellationToken cancellationToken)
{
if (video.VideoType != VideoType.VideoFile)
{
- return Task.FromResult(new RemoteSubtitleInfo[] { });
+ return Task.FromResult(Array.Empty<RemoteSubtitleInfo>());
}
VideoContentType mediaType;
@@ -258,7 +295,7 @@ namespace MediaBrowser.Providers.Subtitles
else
{
// These are the only supported types
- return Task.FromResult(new RemoteSubtitleInfo[] { });
+ return Task.FromResult(Array.Empty<RemoteSubtitleInfo>());
}
var request = new SubtitleSearchRequest
@@ -272,12 +309,11 @@ namespace MediaBrowser.Providers.Subtitles
ProductionYear = video.ProductionYear,
ProviderIds = video.ProviderIds,
RuntimeTicks = video.RunTimeTicks,
- IsPerfectMatch = isPerfectMatch ?? false
+ IsPerfectMatch = isPerfectMatch ?? false,
+ IsAutomated = isAutomated
};
- var episode = video as Episode;
-
- if (episode != null)
+ if (video is Episode episode)
{
request.IndexNumberEnd = episode.IndexNumberEnd;
request.SeriesName = episode.SeriesName;
@@ -296,14 +332,15 @@ namespace MediaBrowser.Providers.Subtitles
private string GetProviderId(string name)
{
- return name.ToLowerInvariant().GetMD5().ToString("N");
+ return name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
private ISubtitleProvider GetProvider(string id)
{
- return _subtitleProviders.First(i => string.Equals(id, GetProviderId(i.Name)));
+ return _subtitleProviders.First(i => string.Equals(id, GetProviderId(i.Name), StringComparison.Ordinal));
}
+ /// <inheritdoc />
public Task DeleteSubtitles(BaseItem item, int index)
{
var stream = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery
@@ -311,8 +348,7 @@ namespace MediaBrowser.Providers.Subtitles
Index = index,
ItemId = item.Id,
Type = MediaStreamType.Subtitle
-
- }).First();
+ })[0];
var path = stream.Path;
_monitor.ReportFileSystemChangeBeginning(path);
@@ -329,32 +365,34 @@ namespace MediaBrowser.Providers.Subtitles
return item.RefreshMetadata(CancellationToken.None);
}
+ /// <inheritdoc />
public Task<SubtitleResponse> GetRemoteSubtitles(string id, CancellationToken cancellationToken)
{
- var parts = id.Split(new[] { '_' }, 2);
+ var parts = id.Split('_', 2);
- var provider = GetProvider(parts.First());
- id = parts.Last();
+ var provider = GetProvider(parts[0]);
+ id = parts[^1];
return provider.GetSubtitles(id, cancellationToken);
}
- public SubtitleProviderInfo[] GetSupportedProviders(BaseItem video)
+ /// <inheritdoc />
+ public SubtitleProviderInfo[] GetSupportedProviders(BaseItem item)
{
VideoContentType mediaType;
- if (video is Episode)
+ if (item is Episode)
{
mediaType = VideoContentType.Episode;
}
- else if (video is Movie)
+ else if (item is Movie)
{
mediaType = VideoContentType.Movie;
}
else
{
// These are the only supported types
- return new SubtitleProviderInfo[] { };
+ return Array.Empty<SubtitleProviderInfo>();
}
return _subtitleProviders
@@ -363,9 +401,7 @@ namespace MediaBrowser.Providers.Subtitles
{
Name = i.Name,
Id = GetProviderId(i.Name)
-
}).ToArray();
}
-
}
}
diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs
deleted file mode 100644
index bd58fc5de..000000000
--- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs
+++ /dev/null
@@ -1,209 +0,0 @@
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV
-{
- public class DummySeasonProvider
- {
- private readonly IServerConfigurationManager _config;
- private readonly ILogger _logger;
- private readonly ILocalizationManager _localization;
- private readonly ILibraryManager _libraryManager;
- private readonly IFileSystem _fileSystem;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public DummySeasonProvider(IServerConfigurationManager config, ILogger logger, ILocalizationManager localization, ILibraryManager libraryManager, IFileSystem fileSystem)
- {
- _config = config;
- _logger = logger;
- _localization = localization;
- _libraryManager = libraryManager;
- _fileSystem = fileSystem;
- }
-
- public async Task<bool> Run(Series series, CancellationToken cancellationToken)
- {
- var seasonsRemoved = RemoveObsoleteSeasons(series);
-
- var hasNewSeasons = await AddDummySeasonFolders(series, cancellationToken).ConfigureAwait(false);
-
- if (hasNewSeasons)
- {
- //var directoryService = new DirectoryService(_fileSystem);
-
- //await series.RefreshMetadata(new MetadataRefreshOptions(directoryService), cancellationToken).ConfigureAwait(false);
-
- //await series.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(directoryService))
- // .ConfigureAwait(false);
- }
-
- return seasonsRemoved || hasNewSeasons;
- }
-
- private async Task<bool> AddDummySeasonFolders(Series series, CancellationToken cancellationToken)
- {
- var episodesInSeriesFolder = series.GetRecursiveChildren(i => i is Episode)
- .Cast<Episode>()
- .Where(i => !i.IsInSeasonFolder)
- .ToList();
-
- var hasChanges = false;
-
- List<Season> seasons = null;
-
- // Loop through the unique season numbers
- foreach (var seasonNumber in episodesInSeriesFolder.Select(i => i.ParentIndexNumber ?? -1)
- .Where(i => i >= 0)
- .Distinct()
- .ToList())
- {
- if (seasons == null)
- {
- seasons = series.Children.OfType<Season>().ToList();
- }
- var existingSeason = seasons
- .FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
-
- if (existingSeason == null)
- {
- await AddSeason(series, seasonNumber, false, cancellationToken).ConfigureAwait(false);
- hasChanges = true;
- seasons = null;
- }
- else if (existingSeason.IsVirtualItem)
- {
- existingSeason.IsVirtualItem = false;
- existingSeason.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken);
- seasons = null;
- }
- }
-
- // Unknown season - create a dummy season to put these under
- if (episodesInSeriesFolder.Any(i => !i.ParentIndexNumber.HasValue))
- {
- if (seasons == null)
- {
- seasons = series.Children.OfType<Season>().ToList();
- }
-
- var existingSeason = seasons
- .FirstOrDefault(i => !i.IndexNumber.HasValue);
-
- if (existingSeason == null)
- {
- await AddSeason(series, null, false, cancellationToken).ConfigureAwait(false);
-
- hasChanges = true;
- seasons = null;
- }
- else if (existingSeason.IsVirtualItem)
- {
- existingSeason.IsVirtualItem = false;
- existingSeason.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken);
- seasons = null;
- }
- }
-
- return hasChanges;
- }
-
- /// <summary>
- /// Adds the season.
- /// </summary>
- public async Task<Season> AddSeason(Series series,
- int? seasonNumber,
- bool isVirtualItem,
- CancellationToken cancellationToken)
- {
- var seasonName = seasonNumber == 0 ?
- _libraryManager.GetLibraryOptions(series).SeasonZeroDisplayName :
- (seasonNumber.HasValue ? string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value.ToString(_usCulture)) : _localization.GetLocalizedString("NameSeasonUnknown"));
-
- _logger.LogInformation("Creating Season {0} entry for {1}", seasonName, series.Name);
-
- var season = new Season
- {
- Name = seasonName,
- IndexNumber = seasonNumber,
- Id = _libraryManager.GetNewItemId((series.Id + (seasonNumber ?? -1).ToString(_usCulture) + seasonName), typeof(Season)),
- IsVirtualItem = isVirtualItem,
- SeriesId = series.Id,
- SeriesName = series.Name
- };
-
- season.SetParent(series);
-
- series.AddChild(season, cancellationToken);
-
- await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
-
- return season;
- }
-
- private bool RemoveObsoleteSeasons(Series series)
- {
- var existingSeasons = series.Children.OfType<Season>().ToList();
-
- var physicalSeasons = existingSeasons
- .Where(i => i.LocationType != LocationType.Virtual)
- .ToList();
-
- var virtualSeasons = existingSeasons
- .Where(i => i.LocationType == LocationType.Virtual)
- .ToList();
-
- var seasonsToRemove = virtualSeasons
- .Where(i =>
- {
- if (i.IndexNumber.HasValue)
- {
- var seasonNumber = i.IndexNumber.Value;
-
- // If there's a physical season with the same number, delete it
- if (physicalSeasons.Any(p => p.IndexNumber.HasValue && (p.IndexNumber.Value == seasonNumber)))
- {
- return true;
- }
- }
-
- // If there are no episodes with this season number, delete it
- if (!i.GetEpisodes().Any())
- {
- return true;
- }
-
- return false;
- })
- .ToList();
-
- var hasChanges = false;
-
- foreach (var seasonToRemove in seasonsToRemove)
- {
- _logger.LogInformation("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber);
-
- _libraryManager.DeleteItem(seasonToRemove, new DeleteOptions
- {
- DeleteFileLocation = true
-
- }, false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
index 5993f615a..08cb6ced9 100644
--- a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
+++ b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
@@ -12,49 +14,61 @@ namespace MediaBrowser.Providers.TV
{
public class EpisodeMetadataService : MetadataService<Episode, EpisodeInfo>
{
- protected override ItemUpdateType BeforeSaveInternal(Episode item, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ public EpisodeMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<EpisodeMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override ItemUpdateType BeforeSaveInternal(Episode item, bool isFullRefresh, ItemUpdateType updateType)
{
- var updateType = base.BeforeSaveInternal(item, isFullRefresh, currentUpdateType);
+ var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
var seriesName = item.FindSeriesName();
if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
{
item.SeriesName = seriesName;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seasonName = item.FindSeasonName();
if (!string.Equals(item.SeasonName, seasonName, StringComparison.Ordinal))
{
item.SeasonName = seasonName;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seriesId = item.FindSeriesId();
if (!item.SeriesId.Equals(seriesId))
{
item.SeriesId = seriesId;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seasonId = item.FindSeasonId();
if (!item.SeasonId.Equals(seasonId))
{
item.SeasonId = seasonId;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
{
item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- return updateType;
+ return updatedType;
}
- protected override void MergeData(MetadataResult<Episode> source, MetadataResult<Episode> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Episode> source, MetadataResult<Episode> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -81,9 +95,5 @@ namespace MediaBrowser.Providers.TV
targetItem.IndexNumberEnd = sourceItem.IndexNumberEnd;
}
}
-
- public EpisodeMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/TV/FanArt/FanArtSeasonProvider.cs b/MediaBrowser.Providers/TV/FanArt/FanArtSeasonProvider.cs
deleted file mode 100644
index 58356910f..000000000
--- a/MediaBrowser.Providers/TV/FanArt/FanArtSeasonProvider.cs
+++ /dev/null
@@ -1,205 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-
-namespace MediaBrowser.Providers.TV.FanArt
-{
- public class FanArtSeasonProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _json;
-
- public FanArtSeasonProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
- {
- _config = config;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _json = json;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "FanArt";
-
- public bool Supports(BaseItem item)
- {
- return item is Season;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Backdrop,
- ImageType.Thumb,
- ImageType.Banner,
- ImageType.Primary
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var list = new List<RemoteImageInfo>();
-
- var season = (Season)item;
- var series = season.Series;
-
- if (series != null)
- {
- var id = series.GetProviderId(MetadataProviders.Tvdb);
-
- if (!string.IsNullOrEmpty(id) && season.IndexNumber.HasValue)
- {
- // Bad id entered
- try
- {
- await FanartSeriesProvider.Current.EnsureSeriesJson(id, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
- {
- throw;
- }
- }
-
- var path = FanartSeriesProvider.Current.GetFanartJsonPath(id);
-
- try
- {
- AddImages(list, season.IndexNumber.Value, path, cancellationToken);
- }
- catch (FileNotFoundException)
- {
- // No biggie. Don't blow up
- }
- catch (IOException)
- {
- // No biggie. Don't blow up
- }
- }
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- // Sort first by width to prioritize HD versions
- return list.OrderByDescending(i => i.Width ?? 0)
- .ThenByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private void AddImages(List<RemoteImageInfo> list, int seasonNumber, string path, CancellationToken cancellationToken)
- {
- var root = _json.DeserializeFromFile<FanartSeriesProvider.RootObject>(path);
-
- AddImages(list, root, seasonNumber, cancellationToken);
- }
-
- private void AddImages(List<RemoteImageInfo> list, FanartSeriesProvider.RootObject obj, int seasonNumber, CancellationToken cancellationToken)
- {
- PopulateImages(list, obj.seasonposter, ImageType.Primary, 1000, 1426, seasonNumber);
- PopulateImages(list, obj.seasonbanner, ImageType.Banner, 1000, 185, seasonNumber);
- PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281, seasonNumber);
- PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, seasonNumber);
- }
-
- private void PopulateImages(List<RemoteImageInfo> list,
- List<FanartSeriesProvider.Image> images,
- ImageType type,
- int width,
- int height,
- int seasonNumber)
- {
- if (images == null)
- {
- return;
- }
-
- list.AddRange(images.Select(i =>
- {
- var url = i.url;
- var season = i.season;
-
- if (!string.IsNullOrEmpty(url) &&
- !string.IsNullOrEmpty(season) &&
- int.TryParse(season, NumberStyles.Integer, _usCulture, out var imageSeasonNumber) &&
- seasonNumber == imageSeasonNumber)
- {
- var likesString = i.likes;
-
- var info = new RemoteImageInfo
- {
- RatingType = RatingType.Likes,
- Type = type,
- Width = width,
- Height = height,
- ProviderName = Name,
- Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
- Language = i.lang
- };
-
- if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
- {
- info.CommunityRating = likes;
- }
-
- return info;
- }
-
- return null;
- }).Where(i => i != null));
- }
-
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs b/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs
deleted file mode 100644
index 49cd9596e..000000000
--- a/MediaBrowser.Providers/TV/FanArt/FanartSeriesProvider.cs
+++ /dev/null
@@ -1,378 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Music;
-
-namespace MediaBrowser.Providers.TV.FanArt
-{
- public class FanartSeriesProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IServerConfigurationManager _config;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
- private readonly IJsonSerializer _json;
-
- private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3/tv/{1}?api_key={0}";
-
- internal static FanartSeriesProvider Current { get; private set; }
-
- public FanartSeriesProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
- {
- _config = config;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- _json = json;
-
- Current = this;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "FanArt";
-
- public bool Supports(BaseItem item)
- {
- return item is Series;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Thumb,
- ImageType.Art,
- ImageType.Logo,
- ImageType.Backdrop,
- ImageType.Banner
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var list = new List<RemoteImageInfo>();
-
- var series = (Series)item;
-
- var id = series.GetProviderId(MetadataProviders.Tvdb);
-
- if (!string.IsNullOrEmpty(id))
- {
- // Bad id entered
- try
- {
- await EnsureSeriesJson(id, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
- {
- throw;
- }
- }
-
- var path = GetFanartJsonPath(id);
-
- try
- {
- AddImages(list, path, cancellationToken);
- }
- catch (FileNotFoundException)
- {
- // No biggie. Don't blow up
- }
- catch (IOException)
- {
- // No biggie. Don't blow up
- }
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- // Sort first by width to prioritize HD versions
- return list.OrderByDescending(i => i.Width ?? 0)
- .ThenByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
- {
- var root = _json.DeserializeFromFile<RootObject>(path);
-
- AddImages(list, root, cancellationToken);
- }
-
- private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
- {
- PopulateImages(list, obj.hdtvlogo, ImageType.Logo, 800, 310);
- PopulateImages(list, obj.hdclearart, ImageType.Art, 1000, 562);
- PopulateImages(list, obj.clearlogo, ImageType.Logo, 400, 155);
- PopulateImages(list, obj.clearart, ImageType.Art, 500, 281);
- PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, true);
- PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281);
- PopulateImages(list, obj.tvthumb, ImageType.Thumb, 500, 281);
- PopulateImages(list, obj.tvbanner, ImageType.Banner, 1000, 185);
- PopulateImages(list, obj.tvposter, ImageType.Primary, 1000, 1426);
- }
-
- private void PopulateImages(List<RemoteImageInfo> list,
- List<Image> images,
- ImageType type,
- int width,
- int height,
- bool allowSeasonAll = false)
- {
- if (images == null)
- {
- return;
- }
-
- list.AddRange(images.Select(i =>
- {
- var url = i.url;
- var season = i.season;
-
- var isSeasonValid = string.IsNullOrEmpty(season) ||
- (allowSeasonAll && string.Equals(season, "all", StringComparison.OrdinalIgnoreCase));
-
- if (!string.IsNullOrEmpty(url) && isSeasonValid)
- {
- var likesString = i.likes;
-
- var info = new RemoteImageInfo
- {
- RatingType = RatingType.Likes,
- Type = type,
- Width = width,
- Height = height,
- ProviderName = Name,
- Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
- Language = i.lang
- };
-
- if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
- {
- info.CommunityRating = likes;
- }
-
- return info;
- }
-
- return null;
- }).Where(i => i != null));
- }
-
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- /// <summary>
- /// Gets the series data path.
- /// </summary>
- /// <param name="appPaths">The app paths.</param>
- /// <param name="seriesId">The series id.</param>
- /// <returns>System.String.</returns>
- internal static string GetSeriesDataPath(IApplicationPaths appPaths, string seriesId)
- {
- var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
-
- return seriesDataPath;
- }
-
- /// <summary>
- /// Gets the series data path.
- /// </summary>
- /// <param name="appPaths">The app paths.</param>
- /// <returns>System.String.</returns>
- internal static string GetSeriesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "fanart-tv");
-
- return dataPath;
- }
-
- public string GetFanartJsonPath(string tvdbId)
- {
- var dataPath = GetSeriesDataPath(_config.ApplicationPaths, tvdbId);
- return Path.Combine(dataPath, "fanart.json");
- }
-
- private readonly SemaphoreSlim _ensureSemaphore = new SemaphoreSlim(1, 1);
- internal async Task EnsureSeriesJson(string tvdbId, CancellationToken cancellationToken)
- {
- var path = GetFanartJsonPath(tvdbId);
-
- // Only allow one thread in here at a time since every season will be calling this method, possibly concurrently
- await _ensureSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
- {
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return;
- }
- }
-
- await DownloadSeriesJson(tvdbId, cancellationToken).ConfigureAwait(false);
- }
- finally
- {
- _ensureSemaphore.Release();
- }
- }
-
- public FanartOptions GetFanartOptions()
- {
- return _config.GetConfiguration<FanartOptions>("fanart");
- }
-
- /// <summary>
- /// Downloads the series json.
- /// </summary>
- /// <param name="tvdbId">The TVDB identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- internal async Task DownloadSeriesJson(string tvdbId, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, tvdbId);
-
- var clientKey = GetFanartOptions().UserApiKey;
- if (!string.IsNullOrWhiteSpace(clientKey))
- {
- url += "&client_key=" + clientKey;
- }
-
- var path = GetFanartJsonPath(tvdbId);
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- try
- {
- using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- BufferContent = true
-
- }, "GET").ConfigureAwait(false))
- {
- using (var response = httpResponse.Content)
- {
- using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await response.CopyToAsync(fileStream).ConfigureAwait(false);
- }
- }
- }
- }
- catch (HttpException exception)
- {
- if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
- {
- // If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
- _json.SerializeToFile(new RootObject(), path);
-
- return;
- }
-
- throw;
- }
- }
-
- public class Image
- {
- public string id { get; set; }
- public string url { get; set; }
- public string lang { get; set; }
- public string likes { get; set; }
- public string season { get; set; }
- }
-
- public class RootObject
- {
- public string name { get; set; }
- public string thetvdb_id { get; set; }
- public List<Image> clearlogo { get; set; }
- public List<Image> hdtvlogo { get; set; }
- public List<Image> clearart { get; set; }
- public List<Image> showbackground { get; set; }
- public List<Image> tvthumb { get; set; }
- public List<Image> seasonposter { get; set; }
- public List<Image> seasonthumb { get; set; }
- public List<Image> hdclearart { get; set; }
- public List<Image> tvbanner { get; set; }
- public List<Image> characterart { get; set; }
- public List<Image> tvposter { get; set; }
- public List<Image> seasonbanner { get; set; }
- }
- }
-
- public class FanartConfigStore : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new ConfigurationStore[]
- {
- new ConfigurationStore
- {
- Key = "fanart",
- ConfigurationType = typeof(FanartOptions)
- }
- };
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
deleted file mode 100644
index 0a2975e0f..000000000
--- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
+++ /dev/null
@@ -1,391 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Providers.TV.TheTVDB;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV
-{
- public class MissingEpisodeProvider
- {
- private readonly IServerConfigurationManager _config;
- private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localization;
- private readonly IFileSystem _fileSystem;
- private readonly TvDbClientManager _tvDbClientManager;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private const double UnairedEpisodeThresholdDays = 2;
-
- public MissingEpisodeProvider(
- ILogger logger,
- IServerConfigurationManager config,
- ILibraryManager libraryManager,
- ILocalizationManager localization,
- IFileSystem fileSystem,
- TvDbClientManager tvDbClientManager)
- {
- _logger = logger;
- _config = config;
- _libraryManager = libraryManager;
- _localization = localization;
- _fileSystem = fileSystem;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public async Task<bool> Run(Series series, bool addNewItems, CancellationToken cancellationToken)
- {
- var tvdbId = series.GetProviderId(MetadataProviders.Tvdb);
- if (string.IsNullOrEmpty(tvdbId))
- {
- return false;
- }
-
- var episodes = await _tvDbClientManager.GetAllEpisodesAsync(Convert.ToInt32(tvdbId), series.GetPreferredMetadataLanguage(), cancellationToken);
-
- var episodeLookup = episodes
- .Select(i =>
- {
- DateTime.TryParse(i.FirstAired, out var firstAired);
- var seasonNumber = i.AiredSeason.GetValueOrDefault(-1);
- var episodeNumber = i.AiredEpisodeNumber.GetValueOrDefault(-1);
- return (seasonNumber: seasonNumber, episodeNumber: episodeNumber, firstAired: firstAired);
- })
- .Where(i => i.seasonNumber != -1 && i.episodeNumber != -1)
- .OrderBy(i => i.seasonNumber)
- .ThenBy(i => i.episodeNumber)
- .ToList();
-
- var allRecursiveChildren = series.GetRecursiveChildren();
-
- var hasBadData = HasInvalidContent(allRecursiveChildren);
-
- // Be conservative here to avoid creating missing episodes for ones they already have
- var addMissingEpisodes = !hasBadData && _libraryManager.GetLibraryOptions(series).ImportMissingEpisodes;
-
- var anySeasonsRemoved = RemoveObsoleteOrMissingSeasons(allRecursiveChildren, episodeLookup);
-
- if (anySeasonsRemoved)
- {
- // refresh this
- allRecursiveChildren = series.GetRecursiveChildren();
- }
-
- var anyEpisodesRemoved = RemoveObsoleteOrMissingEpisodes(allRecursiveChildren, episodeLookup, addMissingEpisodes);
-
- if (anyEpisodesRemoved)
- {
- // refresh this
- allRecursiveChildren = series.GetRecursiveChildren();
- }
-
- var hasNewEpisodes = false;
-
- if (addNewItems && series.IsMetadataFetcherEnabled(_libraryManager.GetLibraryOptions(series), TvdbSeriesProvider.Current.Name))
- {
- hasNewEpisodes = await AddMissingEpisodes(series, allRecursiveChildren, addMissingEpisodes, episodeLookup, cancellationToken)
- .ConfigureAwait(false);
- }
-
- if (hasNewEpisodes || anySeasonsRemoved || anyEpisodesRemoved)
- {
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Returns true if a series has any seasons or episodes without season or episode numbers
- /// If this data is missing no virtual items will be added in order to prevent possible duplicates
- /// </summary>
- private bool HasInvalidContent(IList<BaseItem> allItems)
- {
- return allItems.OfType<Season>().Any(i => !i.IndexNumber.HasValue) ||
- allItems.OfType<Episode>().Any(i =>
- {
- if (!i.ParentIndexNumber.HasValue)
- {
- return true;
- }
-
- // You could have episodes under season 0 with no number
- return false;
- });
- }
-
- private async Task<bool> AddMissingEpisodes(
- Series series,
- IEnumerable<BaseItem> allItems,
- bool addMissingEpisodes,
- IReadOnlyCollection<(int seasonNumber, int episodenumber, DateTime firstAired)> episodeLookup,
- CancellationToken cancellationToken)
- {
- var existingEpisodes = allItems.OfType<Episode>().ToList();
-
- var seasonCounts = episodeLookup.GroupBy(e => e.seasonNumber).ToDictionary(g => g.Key, g => g.Count());
-
- var hasChanges = false;
-
- foreach (var tuple in episodeLookup)
- {
- if (tuple.seasonNumber <= 0 || tuple.episodenumber <= 0)
- {
- // Ignore episode/season zeros
- continue;
- }
-
- var existingEpisode = GetExistingEpisode(existingEpisodes, seasonCounts, tuple);
-
- if (existingEpisode != null)
- {
- continue;
- }
-
- var airDate = tuple.firstAired;
-
- var now = DateTime.UtcNow.AddDays(-UnairedEpisodeThresholdDays);
-
- if (airDate < now && addMissingEpisodes || airDate > now)
- {
- // tvdb has a lot of nearly blank episodes
- _logger.LogInformation("Creating virtual missing/unaired episode {0} {1}x{2}", series.Name, tuple.seasonNumber, tuple.episodenumber);
- await AddEpisode(series, tuple.seasonNumber, tuple.episodenumber, cancellationToken).ConfigureAwait(false);
-
- hasChanges = true;
- }
- }
-
- return hasChanges;
- }
-
- /// <summary>
- /// Removes the virtual entry after a corresponding physical version has been added
- /// </summary>
- private bool RemoveObsoleteOrMissingEpisodes(
- IEnumerable<BaseItem> allRecursiveChildren,
- IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup,
- bool allowMissingEpisodes)
- {
- var existingEpisodes = allRecursiveChildren.OfType<Episode>();
-
- var physicalEpisodes = new List<Episode>();
- var virtualEpisodes = new List<Episode>();
- foreach (var episode in existingEpisodes)
- {
- if (episode.LocationType == LocationType.Virtual)
- {
- virtualEpisodes.Add(episode);
- }
- else
- {
- physicalEpisodes.Add(episode);
- }
- }
-
- var episodesToRemove = virtualEpisodes
- .Where(i =>
- {
- if (!i.IndexNumber.HasValue || !i.ParentIndexNumber.HasValue)
- {
- return true;
- }
-
- var seasonNumber = i.ParentIndexNumber.Value;
- var episodeNumber = i.IndexNumber.Value;
-
- // If there's a physical episode with the same season and episode number, delete it
- if (physicalEpisodes.Any(p =>
- p.ParentIndexNumber.HasValue && p.ParentIndexNumber.Value == seasonNumber &&
- p.ContainsEpisodeNumber(episodeNumber)))
- {
- return true;
- }
-
- // If the episode no longer exists in the remote lookup, delete it
- if (!episodeLookup.Any(e => e.seasonNumber == seasonNumber && e.episodeNumber == episodeNumber))
- {
- return true;
- }
-
- // If it's missing, but not unaired, remove it
- return !allowMissingEpisodes && i.IsMissingEpisode &&
- (!i.PremiereDate.HasValue ||
- i.PremiereDate.Value.ToLocalTime().Date.AddDays(UnairedEpisodeThresholdDays) <
- DateTime.Now.Date);
- });
-
- var hasChanges = false;
-
- foreach (var episodeToRemove in episodesToRemove)
- {
- _libraryManager.DeleteItem(episodeToRemove, new DeleteOptions
- {
- DeleteFileLocation = true
- }, false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
-
- /// <summary>
- /// Removes the obsolete or missing seasons.
- /// </summary>
- /// <param name="allRecursiveChildren"></param>
- /// <param name="episodeLookup">The episode lookup.</param>
- /// <returns>Task{System.Boolean}.</returns>
- private bool RemoveObsoleteOrMissingSeasons(IList<BaseItem> allRecursiveChildren,
- IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup)
- {
- var existingSeasons = allRecursiveChildren.OfType<Season>().ToList();
-
- var physicalSeasons = new List<Season>();
- var virtualSeasons = new List<Season>();
- foreach (var season in existingSeasons)
- {
- if (season.LocationType == LocationType.Virtual)
- {
- virtualSeasons.Add(season);
- }
- else
- {
- physicalSeasons.Add(season);
- }
- }
-
- var allEpisodes = allRecursiveChildren.OfType<Episode>().ToList();
-
- var seasonsToRemove = virtualSeasons
- .Where(i =>
- {
- if (i.IndexNumber.HasValue)
- {
- var seasonNumber = i.IndexNumber.Value;
-
- // If there's a physical season with the same number, delete it
- if (physicalSeasons.Any(p => p.IndexNumber.HasValue && p.IndexNumber.Value == seasonNumber && string.Equals(p.Series.PresentationUniqueKey, i.Series.PresentationUniqueKey, StringComparison.Ordinal)))
- {
- return true;
- }
-
- // If the season no longer exists in the remote lookup, delete it, but only if an existing episode doesn't require it
- return episodeLookup.All(e => e.seasonNumber != seasonNumber) && allEpisodes.All(s => s.ParentIndexNumber != seasonNumber || s.IsInSeasonFolder);
- }
-
- // Season does not have a number
- // Remove if there are no episodes directly in series without a season number
- return allEpisodes.All(s => s.ParentIndexNumber.HasValue || s.IsInSeasonFolder);
- });
-
- var hasChanges = false;
-
- foreach (var seasonToRemove in seasonsToRemove)
- {
- _libraryManager.DeleteItem(seasonToRemove, new DeleteOptions
- {
- DeleteFileLocation = true
-
- }, false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
-
- /// <summary>
- /// Adds the episode.
- /// </summary>
- /// <param name="series">The series.</param>
- /// <param name="seasonNumber">The season number.</param>
- /// <param name="episodeNumber">The episode number.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- private async Task AddEpisode(Series series, int seasonNumber, int episodeNumber, CancellationToken cancellationToken)
- {
- var season = series.Children.OfType<Season>()
- .FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
-
- if (season == null)
- {
- var provider = new DummySeasonProvider(_config, _logger, _localization, _libraryManager, _fileSystem);
- season = await provider.AddSeason(series, seasonNumber, true, cancellationToken).ConfigureAwait(false);
- }
-
- var name = $"Episode {episodeNumber.ToString(_usCulture)}";
-
- var episode = new Episode
- {
- Name = name,
- IndexNumber = episodeNumber,
- ParentIndexNumber = seasonNumber,
- Id = _libraryManager.GetNewItemId(series.Id + seasonNumber.ToString(_usCulture) + name, typeof(Episode)),
- IsVirtualItem = true,
- SeasonId = season?.Id ?? Guid.Empty,
- SeriesId = series.Id
- };
-
- season.AddChild(episode, cancellationToken);
-
- await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Gets the existing episode.
- /// </summary>
- /// <param name="existingEpisodes">The existing episodes.</param>
- /// <param name="seasonCounts"></param>
- /// <param name="episodeTuple"></param>
- /// <returns>Episode.</returns>
- private Episode GetExistingEpisode(IList<Episode> existingEpisodes, IReadOnlyDictionary<int, int> seasonCounts, (int seasonNumber, int episodeNumber, DateTime firstAired) episodeTuple)
- {
- var seasonNumber = episodeTuple.seasonNumber;
- var episodeNumber = episodeTuple.episodeNumber;
-
- while (true)
- {
- var episode = GetExistingEpisode(existingEpisodes, seasonNumber, episodeNumber);
- if (episode != null)
- {
- return episode;
- }
-
- seasonNumber--;
-
- if (seasonCounts.ContainsKey(seasonNumber))
- {
- episodeNumber += seasonCounts[seasonNumber];
- }
- else
- {
- break;
- }
- }
-
- return null;
- }
-
- private Episode GetExistingEpisode(IEnumerable<Episode> existingEpisodes, int season, int episode)
- {
- return existingEpisodes
- .FirstOrDefault(i => i.ParentIndexNumber == season && i.ContainsEpisodeNumber(episode));
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/SeasonMetadataService.cs b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
index c575057de..b173fc7a3 100644
--- a/MediaBrowser.Providers/TV/SeasonMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,9 +17,23 @@ namespace MediaBrowser.Providers.TV
{
public class SeasonMetadataService : MetadataService<Season, SeasonInfo>
{
- protected override ItemUpdateType BeforeSaveInternal(Season item, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ public SeasonMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<SeasonMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- var updateType = base.BeforeSaveInternal(item, isFullRefresh, currentUpdateType);
+ }
+
+ /// <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.HasValue && item.IndexNumber.Value == 0)
{
@@ -26,7 +42,7 @@ namespace MediaBrowser.Providers.TV
if (!string.Equals(item.Name, seasonZeroDisplayName, StringComparison.OrdinalIgnoreCase))
{
item.Name = seasonZeroDisplayName;
- updateType = updateType | ItemUpdateType.MetadataEdit;
+ updatedType |= ItemUpdateType.MetadataEdit;
}
}
@@ -34,33 +50,31 @@ namespace MediaBrowser.Providers.TV
if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
{
item.SeriesName = seriesName;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
{
item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
var seriesId = item.FindSeriesId();
if (!item.SeriesId.Equals(seriesId))
{
item.SeriesId = seriesId;
- updateType |= ItemUpdateType.MetadataImport;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- return updateType;
+ return updatedType;
}
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
-
+ /// <inheritdoc />
protected override IList<BaseItem> GetChildrenForMetadataUpdates(Season item)
- {
- return item.GetEpisodes();
- }
+ => item.GetEpisodes();
+ /// <inheritdoc />
protected override ItemUpdateType UpdateMetadataFromChildren(Season item, IList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
{
var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
@@ -73,7 +87,8 @@ namespace MediaBrowser.Providers.TV
return updateType;
}
- protected override void MergeData(MetadataResult<Season> source, MetadataResult<Season> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Season> source, MetadataResult<Season> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
@@ -90,9 +105,5 @@ namespace MediaBrowser.Providers.TV
return ItemUpdateType.None;
}
-
- public SeasonMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index afbd838e4..9d223b4b6 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -1,4 +1,10 @@
-using System;
+#nullable disable
+
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
@@ -8,76 +14,54 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.Providers.Manager;
-using MediaBrowser.Providers.TV.TheTVDB;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.TV
{
public class SeriesMetadataService : MetadataService<Series, SeriesInfo>
{
- private readonly ILocalizationManager _localization;
- private readonly IXmlReaderSettingsFactory _xmlSettings;
- private readonly TvDbClientManager _tvDbClientManager;
+ private readonly ILocalizationManager _localizationManager;
public SeriesMetadataService(
IServerConfigurationManager serverConfigurationManager,
- ILogger logger,
+ ILogger<SeriesMetadataService> logger,
IProviderManager providerManager,
IFileSystem fileSystem,
- IUserDataManager userDataManager,
ILibraryManager libraryManager,
- ILocalizationManager localization,
- IXmlReaderSettingsFactory xmlSettings,
- TvDbClientManager tvDbClientManager
- )
- : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ ILocalizationManager localizationManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- _localization = localization;
- _xmlSettings = xmlSettings;
- _tvDbClientManager = tvDbClientManager;
+ _localizationManager = localizationManager;
}
+ /// <inheritdoc />
protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
{
await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false);
- var seasonProvider = new DummySeasonProvider(ServerConfigurationManager, Logger, _localization, LibraryManager, FileSystem);
- await seasonProvider.Run(item, cancellationToken).ConfigureAwait(false);
-
- // TODO why does it not register this itself omg
- var provider = new MissingEpisodeProvider(Logger,
- ServerConfigurationManager,
- LibraryManager,
- _localization,
- FileSystem,
- _tvDbClientManager);
-
- try
- {
- await provider.Run(item, true, CancellationToken.None).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error in DummySeasonProvider");
- }
+ RemoveObsoleteSeasons(item);
+ await FillInMissingSeasonsAsync(item, cancellationToken).ConfigureAwait(false);
}
+ /// <inheritdoc />
protected override bool IsFullLocalMetadata(Series item)
{
if (string.IsNullOrWhiteSpace(item.Overview))
{
return false;
}
+
if (!item.ProductionYear.HasValue)
{
return false;
}
+
return base.IsFullLocalMetadata(item);
}
- protected override void MergeData(MetadataResult<Series> source, MetadataResult<Series> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Series> source, MetadataResult<Series> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
@@ -99,5 +83,117 @@ namespace MediaBrowser.Providers.TV
targetItem.AirDays = sourceItem.AirDays;
}
}
+
+ private void RemoveObsoleteSeasons(Series series)
+ {
+ // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in FillInMissingSeasonsAsync.
+ 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)
+ {
+ physicalSeasonNumbers.Add(existingSeason.IndexNumber.Value);
+ }
+ else if (existingSeason.LocationType == LocationType.Virtual)
+ {
+ virtualSeasons.Add(existingSeason);
+ }
+ }
+
+ 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().Any())
+ {
+ Logger.LogInformation("Removing virtual season {SeasonNumber} in series {SeriesName}", virtualSeason.IndexNumber, series.Name);
+
+ LibraryManager.DeleteItem(
+ virtualSeason,
+ new DeleteOptions
+ {
+ DeleteFileLocation = true
+ },
+ false);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Creates seasons for all episodes that aren't in a season folder.
+ /// 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 FillInMissingSeasonsAsync(Series series, CancellationToken cancellationToken)
+ {
+ var episodesInSeriesFolder = series.GetRecursiveChildren(i => i is Episode)
+ .Cast<Episode>()
+ .Where(i => !i.IsInSeasonFolder);
+
+ List<Season> seasons = series.Children.OfType<Season>().ToList();
+
+ // Loop through the unique season numbers
+ foreach (var episode in episodesInSeriesFolder)
+ {
+ // Null season numbers will have a 'dummy' season created because seasons are always required.
+ var seasonNumber = episode.ParentIndexNumber >= 0 ? episode.ParentIndexNumber : null;
+ var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber);
+
+ if (existingSeason == null)
+ {
+ var season = await CreateSeasonAsync(series, seasonNumber, cancellationToken).ConfigureAwait(false);
+ seasons.Add(season);
+ }
+ else if (existingSeason.IsVirtualItem)
+ {
+ existingSeason.IsVirtualItem = false;
+ await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, 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="seasonNumber">The season number.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The newly created season.</returns>
+ private async Task<Season> CreateSeasonAsync(
+ Series series,
+ int? seasonNumber,
+ CancellationToken cancellationToken)
+ {
+ string seasonName = seasonNumber switch
+ {
+ null => _localizationManager.GetLocalizedString("NameSeasonUnknown"),
+ 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName,
+ _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value)
+ };
+
+ Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name);
+
+ var season = new Season
+ {
+ 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
+ };
+
+ series.AddChild(season);
+
+ await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken).ConfigureAwait(false);
+
+ return season;
+ }
}
}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs
deleted file mode 100644
index e4248afe1..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public class MovieDbEpisodeImageProvider :
- MovieDbProviderBase,
- IRemoteImageProvider,
- IHasOrder
- {
- public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
- { }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var episode = (Controller.Entities.TV.Episode)item;
- var series = episode.Series;
-
- var seriesId = series != null ? series.GetProviderId(MetadataProviders.Tmdb) : null;
-
- var list = new List<RemoteImageInfo>();
-
- if (string.IsNullOrEmpty(seriesId))
- {
- return list;
- }
-
- var seasonNumber = episode.ParentIndexNumber;
- var episodeNumber = episode.IndexNumber;
-
- if (!seasonNumber.HasValue || !episodeNumber.HasValue)
- {
- return list;
- }
-
- var language = item.GetPreferredMetadataLanguage();
-
- var response = await GetEpisodeInfo(seriesId, seasonNumber.Value, episodeNumber.Value,
- language, cancellationToken).ConfigureAwait(false);
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- list.AddRange(GetPosters(response.images).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- Language = MovieDbProvider.AdjustImageLanguage(i.iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
-
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
-
- }
-
- private IEnumerable<Still> GetPosters(Images images)
- {
- return images.stills ?? new List<Still>();
- }
-
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return GetResponse(url, cancellationToken);
- }
-
- public string Name => "TheMovieDb";
-
- public bool Supports(BaseItem item)
- {
- return item is Controller.Entities.TV.Episode;
- }
- // After TheTvDb
- public int Order => 1;
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
deleted file mode 100644
index 3d7745085..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
+++ /dev/null
@@ -1,216 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public class MovieDbEpisodeProvider :
- MovieDbProviderBase,
- IRemoteMetadataProvider<Episode, EpisodeInfo>,
- IHasOrder
- {
- public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
- { }
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
- {
- var list = new List<RemoteSearchResult>();
-
- // The search query must either provide an episode number or date
- if (!searchInfo.IndexNumber.HasValue || !searchInfo.ParentIndexNumber.HasValue)
- {
- return list;
- }
-
- var metadataResult = await GetMetadata(searchInfo, cancellationToken);
-
- if (metadataResult.HasMetadata)
- {
- var item = metadataResult.Item;
-
- list.Add(new RemoteSearchResult
- {
- IndexNumber = item.IndexNumber,
- Name = item.Name,
- ParentIndexNumber = item.ParentIndexNumber,
- PremiereDate = item.PremiereDate,
- ProductionYear = item.ProductionYear,
- ProviderIds = item.ProviderIds,
- SearchProviderName = Name,
- IndexNumberEnd = item.IndexNumberEnd
- });
- }
-
- return list;
- }
-
- public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
- {
- var result = new MetadataResult<Episode>();
-
- // Allowing this will dramatically increase scan times
- if (info.IsMissingEpisode)
- {
- return result;
- }
-
- info.SeriesProviderIds.TryGetValue(MetadataProviders.Tmdb.ToString(), out string seriesTmdbId);
-
- if (string.IsNullOrEmpty(seriesTmdbId))
- {
- return result;
- }
-
- var seasonNumber = info.ParentIndexNumber;
- var episodeNumber = info.IndexNumber;
-
- if (!seasonNumber.HasValue || !episodeNumber.HasValue)
- {
- return result;
- }
-
- try
- {
- var response = await GetEpisodeInfo(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- result.HasMetadata = true;
- result.QueriedById = true;
-
- if (!string.IsNullOrEmpty(response.overview))
- {
- // if overview is non-empty, we can assume that localized data was returned
- result.ResultLanguage = info.MetadataLanguage;
- }
-
- var item = new Episode();
- result.Item = item;
-
- item.Name = info.Name;
- item.IndexNumber = info.IndexNumber;
- item.ParentIndexNumber = info.ParentIndexNumber;
- item.IndexNumberEnd = info.IndexNumberEnd;
-
- if (response.external_ids.tvdb_id > 0)
- {
- item.SetProviderId(MetadataProviders.Tvdb, response.external_ids.tvdb_id.ToString(CultureInfo.InvariantCulture));
- }
-
- item.PremiereDate = response.air_date;
- item.ProductionYear = result.Item.PremiereDate.Value.Year;
-
- item.Name = response.name;
- item.Overview = response.overview;
-
- item.CommunityRating = (float)response.vote_average;
- //item.VoteCount = response.vote_count;
-
- if (response.videos != null && response.videos.results != null)
- {
- foreach (var video in response.videos.results)
- {
- if (video.type.Equals("trailer", System.StringComparison.OrdinalIgnoreCase)
- || video.type.Equals("clip", System.StringComparison.OrdinalIgnoreCase))
- {
- if (video.site.Equals("youtube", System.StringComparison.OrdinalIgnoreCase))
- {
- var videoUrl = string.Format("http://www.youtube.com/watch?v={0}", video.key);
- item.AddTrailerUrl(videoUrl);
- }
- }
- }
- }
-
- result.ResetPeople();
-
- var credits = response.credits;
- if (credits != null)
- {
- //Actors, Directors, Writers - all in People
- //actors come from cast
- if (credits.cast != null)
- {
- foreach (var actor in credits.cast.OrderBy(a => a.order))
- {
- result.AddPerson(new PersonInfo { Name = actor.name.Trim(), Role = actor.character, Type = PersonType.Actor, SortOrder = actor.order });
- }
- }
-
- // guest stars
- if (credits.guest_stars != null)
- {
- foreach (var guest in credits.guest_stars.OrderBy(a => a.order))
- {
- result.AddPerson(new PersonInfo { Name = guest.name.Trim(), Role = guest.character, Type = PersonType.GuestStar, SortOrder = guest.order });
- }
- }
-
- //and the rest from crew
- if (credits.crew != null)
- {
- var keepTypes = new[]
- {
- PersonType.Director,
- //PersonType.Writer,
- //PersonType.Producer
- };
-
- foreach (var person in credits.crew)
- {
- // Normalize this
- var type = person.department;
- if (string.Equals(type, "writing", StringComparison.OrdinalIgnoreCase))
- {
- type = PersonType.Writer;
- }
-
- if (!keepTypes.Contains(type ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
- !keepTypes.Contains(person.job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
-
- result.AddPerson(new PersonInfo { Name = person.name.Trim(), Role = person.job, Type = type });
- }
- }
- }
- }
- catch (HttpException ex)
- {
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
-
- throw;
- }
-
- return result;
- }
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return GetResponse(url, cancellationToken);
- }
- // After TheTvDb
- public int Order => 1;
-
- public string Name => "TheMovieDb";
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs
deleted file mode 100644
index 6e438ebd8..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs
+++ /dev/null
@@ -1,245 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public abstract class MovieDbProviderBase
- {
- private const string EpisodeUrlPattern = MovieDbProvider.BaseMovieDbUrl + @"3/tv/{0}/season/{1}/episode/{2}?api_key={3}&append_to_response=images,external_ids,credits,videos";
- private readonly IHttpClient _httpClient;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
- private readonly ILogger _logger;
-
- public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- {
- _httpClient = httpClient;
- _configurationManager = configurationManager;
- _jsonSerializer = jsonSerializer;
- _fileSystem = fileSystem;
- _localization = localization;
- _logger = loggerFactory.CreateLogger(GetType().Name);
- }
-
- protected ILogger Logger => _logger;
-
- protected async Task<RootObject> GetEpisodeInfo(string seriesTmdbId, int season, int episodeNumber, string preferredMetadataLanguage,
- CancellationToken cancellationToken)
- {
- await EnsureEpisodeInfo(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage);
-
- return _jsonSerializer.DeserializeFromFile<RootObject>(dataFilePath);
- }
-
- internal Task EnsureEpisodeInfo(string tmdbId, int seasonNumber, int episodeNumber, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
- if (string.IsNullOrEmpty(language))
- {
- throw new ArgumentNullException(nameof(language));
- }
-
- var path = GetDataFilePath(tmdbId, seasonNumber, episodeNumber, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadEpisodeInfo(tmdbId, seasonNumber, episodeNumber, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, int seasonNumber, int episodeNumber, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
- if (string.IsNullOrEmpty(preferredLanguage))
- {
- throw new ArgumentNullException(nameof(preferredLanguage));
- }
-
- var path = MovieDbSeriesProvider.GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format("season-{0}-episode-{1}-{2}.json",
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- episodeNumber.ToString(CultureInfo.InvariantCulture),
- preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- internal async Task DownloadEpisodeInfo(string id, int seasonNumber, int episodeNumber, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(EpisodeUrlPattern, id, seasonNumber, episodeNumber, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(id, seasonNumber, episodeNumber, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task<RootObject> FetchMainResult(string urlPattern, string id, int seasonNumber, int episodeNumber, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(urlPattern, id, seasonNumber.ToString(CultureInfo.InvariantCulture), episodeNumber, MovieDbProvider.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format("&language={0}", language);
- }
-
- var includeImageLanguageParam = MovieDbProvider.GetImageLanguagesParam(language);
- // Get images in english and with no language
- url += "&include_image_language=" + includeImageLanguageParam;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- return await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
- }
- }
- }
-
- protected Task<HttpResponseInfo> GetResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- public class Still
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string id { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- public class Images
- {
- public List<Still> stills { get; set; }
- }
-
- public class ExternalIds
- {
- public string imdb_id { get; set; }
- public object freebase_id { get; set; }
- public string freebase_mid { get; set; }
- public int tvdb_id { get; set; }
- public int tvrage_id { get; set; }
- }
-
- public class Cast
- {
- public string character { get; set; }
- public string credit_id { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string profile_path { get; set; }
- public int order { get; set; }
- }
-
- public class Crew
- {
- public int id { get; set; }
- public string credit_id { get; set; }
- public string name { get; set; }
- public string department { get; set; }
- public string job { get; set; }
- public string profile_path { get; set; }
- }
-
- public class GuestStar
- {
- public int id { get; set; }
- public string name { get; set; }
- public string credit_id { get; set; }
- public string character { get; set; }
- public int order { get; set; }
- public string profile_path { get; set; }
- }
-
- public class Credits
- {
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- public List<GuestStar> guest_stars { get; set; }
- }
-
- public class Videos
- {
- public List<Video> results { get; set; }
- }
-
- public class Video
- {
- public string id { get; set; }
- public string iso_639_1 { get; set; }
- public string iso_3166_1 { get; set; }
- public string key { get; set; }
- public string name { get; set; }
- public string site { get; set; }
- public string size { get; set; }
- public string type { get; set; }
- }
-
- public class RootObject
- {
- public DateTime air_date { get; set; }
- public int episode_number { get; set; }
- public string name { get; set; }
- public string overview { get; set; }
- public int id { get; set; }
- public object production_code { get; set; }
- public int season_number { get; set; }
- public string still_path { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public Images images { get; set; }
- public ExternalIds external_ids { get; set; }
- public Credits credits { get; set; }
- public Videos videos { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs
deleted file mode 100644
index 6be1b101d..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs
+++ /dev/null
@@ -1,308 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public class MovieDbSeasonProvider : IRemoteMetadataProvider<Season, SeasonInfo>
- {
- private const string GetTvInfo3 = MovieDbProvider.BaseMovieDbUrl + @"3/tv/{0}/season/{1}?api_key={2}&append_to_response=images,keywords,external_ids,credits,videos";
- private readonly IHttpClient _httpClient;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
- private readonly ILogger _logger;
-
- public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory)
- {
- _httpClient = httpClient;
- _configurationManager = configurationManager;
- _fileSystem = fileSystem;
- _localization = localization;
- _jsonSerializer = jsonSerializer;
- _logger = loggerFactory.CreateLogger(GetType().Name);
- }
-
- public async Task<MetadataResult<Season>> GetMetadata(SeasonInfo info, CancellationToken cancellationToken)
- {
- var result = new MetadataResult<Season>();
-
- info.SeriesProviderIds.TryGetValue(MetadataProviders.Tmdb.ToString(), out string seriesTmdbId);
-
- var seasonNumber = info.IndexNumber;
-
- if (!string.IsNullOrWhiteSpace(seriesTmdbId) && seasonNumber.HasValue)
- {
- try
- {
- var seasonInfo = await GetSeasonInfo(seriesTmdbId, seasonNumber.Value, info.MetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- result.HasMetadata = true;
- result.Item = new Season();
-
- // Don't use moviedb season names for now until if/when we have field-level configuration
- //result.Item.Name = seasonInfo.name;
-
- result.Item.Name = info.Name;
-
- result.Item.IndexNumber = seasonNumber;
-
- result.Item.Overview = seasonInfo.overview;
-
- if (seasonInfo.external_ids.tvdb_id > 0)
- {
- result.Item.SetProviderId(MetadataProviders.Tvdb, seasonInfo.external_ids.tvdb_id.ToString(CultureInfo.InvariantCulture));
- }
-
- var credits = seasonInfo.credits;
- if (credits != null)
- {
- //Actors, Directors, Writers - all in People
- //actors come from cast
- if (credits.cast != null)
- {
- //foreach (var actor in credits.cast.OrderBy(a => a.order)) result.Item.AddPerson(new PersonInfo { Name = actor.name.Trim(), Role = actor.character, Type = PersonType.Actor, SortOrder = actor.order });
- }
-
- //and the rest from crew
- if (credits.crew != null)
- {
- //foreach (var person in credits.crew) result.Item.AddPerson(new PersonInfo { Name = person.name.Trim(), Role = person.job, Type = person.department });
- }
- }
-
- result.Item.PremiereDate = seasonInfo.air_date;
- result.Item.ProductionYear = result.Item.PremiereDate.Value.Year;
- }
- catch (HttpException ex)
- {
- _logger.LogError(ex, "No metadata found for {0}", seasonNumber.Value);
-
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
-
- throw;
- }
- }
-
- return result;
- }
-
- public string Name => "TheMovieDb";
-
- public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeasonInfo searchInfo, CancellationToken cancellationToken)
- {
- return Task.FromResult<IEnumerable<RemoteSearchResult>>(new List<RemoteSearchResult>());
- }
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- private async Task<RootObject> GetSeasonInfo(string seriesTmdbId, int season, string preferredMetadataLanguage,
- CancellationToken cancellationToken)
- {
- await EnsureSeasonInfo(seriesTmdbId, season, preferredMetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(seriesTmdbId, season, preferredMetadataLanguage);
-
- return _jsonSerializer.DeserializeFromFile<RootObject>(dataFilePath);
- }
-
- internal Task EnsureSeasonInfo(string tmdbId, int seasonNumber, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
- if (string.IsNullOrEmpty(language))
- {
- throw new ArgumentNullException(nameof(language));
- }
-
- var path = GetDataFilePath(tmdbId, seasonNumber, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadSeasonInfo(tmdbId, seasonNumber, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, int seasonNumber, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
- if (string.IsNullOrEmpty(preferredLanguage))
- {
- throw new ArgumentNullException(nameof(preferredLanguage));
- }
-
- var path = MovieDbSeriesProvider.GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format("season-{0}-{1}.json",
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- internal async Task DownloadSeasonInfo(string id, int seasonNumber, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(id, seasonNumber, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(id, seasonNumber, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task<RootObject> FetchMainResult(string id, int seasonNumber, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(GetTvInfo3, id, seasonNumber.ToString(CultureInfo.InvariantCulture), MovieDbProvider.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format("&language={0}", MovieDbProvider.NormalizeLanguage(language));
- }
-
- var includeImageLanguageParam = MovieDbProvider.GetImageLanguagesParam(language);
- // Get images in english and with no language
- url += "&include_image_language=" + includeImageLanguageParam;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- return await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
- }
- }
- }
-
- public class Episode
- {
- public string air_date { get; set; }
- public int episode_number { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string overview { get; set; }
- public string still_path { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- }
-
- public class Cast
- {
- public string character { get; set; }
- public string credit_id { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string profile_path { get; set; }
- public int order { get; set; }
- }
-
- public class Crew
- {
- public string credit_id { get; set; }
- public string department { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string job { get; set; }
- public string profile_path { get; set; }
- }
-
- public class Credits
- {
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- }
-
- public class Poster
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string id { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- public class Images
- {
- public List<Poster> posters { get; set; }
- }
-
- public class ExternalIds
- {
- public string freebase_id { get; set; }
- public string freebase_mid { get; set; }
- public int tvdb_id { get; set; }
- public object tvrage_id { get; set; }
- }
-
- public class Videos
- {
- public List<object> results { get; set; }
- }
-
- public class RootObject
- {
- public DateTime air_date { get; set; }
- public List<Episode> episodes { get; set; }
- public string name { get; set; }
- public string overview { get; set; }
- public int id { get; set; }
- public string poster_path { get; set; }
- public int season_number { get; set; }
- public Credits credits { get; set; }
- public Images images { get; set; }
- public ExternalIds external_ids { get; set; }
- public Videos videos { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesImageProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesImageProvider.cs
deleted file mode 100644
index 26686356f..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesImageProvider.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public class MovieDbSeriesImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IHttpClient _httpClient;
- private readonly IFileSystem _fileSystem;
-
- public MovieDbSeriesImageProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem)
- {
- _jsonSerializer = jsonSerializer;
- _httpClient = httpClient;
- _fileSystem = fileSystem;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheMovieDb";
-
- public bool Supports(BaseItem item)
- {
- return item is Series;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var list = new List<RemoteImageInfo>();
-
- var results = await FetchImages(item, null, _jsonSerializer, cancellationToken).ConfigureAwait(false);
-
- if (results == null)
- {
- return list;
- }
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var language = item.GetPreferredMetadataLanguage();
-
- list.AddRange(GetPosters(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- Language = MovieDbProvider.AdjustImageLanguage(i.iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
-
- list.AddRange(GetBackdrops(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.file_path,
- CommunityRating = i.vote_average,
- VoteCount = i.vote_count,
- Width = i.width,
- Height = i.height,
- ProviderName = Name,
- Type = ImageType.Backdrop,
- RatingType = RatingType.Score
- }));
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- /// <summary>
- /// Gets the posters.
- /// </summary>
- /// <param name="images">The images.</param>
- private IEnumerable<MovieDbSeriesProvider.Poster> GetPosters(MovieDbSeriesProvider.Images images)
- {
- return images.posters ?? new List<MovieDbSeriesProvider.Poster>();
- }
-
- /// <summary>
- /// Gets the backdrops.
- /// </summary>
- /// <param name="images">The images.</param>
- private IEnumerable<MovieDbSeriesProvider.Backdrop> GetBackdrops(MovieDbSeriesProvider.Images images)
- {
- var eligibleBackdrops = images.backdrops == null ? new List<MovieDbSeriesProvider.Backdrop>() :
- images.backdrops;
-
- return eligibleBackdrops.OrderByDescending(i => i.vote_average)
- .ThenByDescending(i => i.vote_count);
- }
-
- /// <summary>
- /// Fetches the images.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="language">The language.</param>
- /// <param name="jsonSerializer">The json serializer.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{MovieImages}.</returns>
- private async Task<MovieDbSeriesProvider.Images> FetchImages(BaseItem item, string language, IJsonSerializer jsonSerializer,
- CancellationToken cancellationToken)
- {
- var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);
-
- if (string.IsNullOrEmpty(tmdbId))
- {
- return null;
- }
-
- await MovieDbSeriesProvider.Current.EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var path = MovieDbSeriesProvider.Current.GetDataFilePath(tmdbId, language);
-
- if (!string.IsNullOrEmpty(path))
- {
- var fileInfo = _fileSystem.GetFileInfo(path);
-
- if (fileInfo.Exists)
- {
- return jsonSerializer.DeserializeFromFile<MovieDbSeriesProvider.RootObject>(path).images;
- }
- }
-
- return null;
- }
- // After tvdb and fanart
- public int Order => 2;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
deleted file mode 100644
index b51fb6af8..000000000
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
+++ /dev/null
@@ -1,683 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV.TheMovieDb
-{
- public class MovieDbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
- {
- private const string GetTvInfo3 = MovieDbProvider.BaseMovieDbUrl + @"3/tv/{0}?api_key={1}&append_to_response=credits,images,keywords,external_ids,videos,content_ratings";
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- internal static MovieDbSeriesProvider Current { get; private set; }
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly ILogger _logger;
- private readonly ILocalizationManager _localization;
- private readonly IHttpClient _httpClient;
- private readonly ILibraryManager _libraryManager;
-
- public MovieDbSeriesProvider(IJsonSerializer jsonSerializer, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILogger logger, ILocalizationManager localization, IHttpClient httpClient, ILibraryManager libraryManager)
- {
- _jsonSerializer = jsonSerializer;
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _logger = logger;
- _localization = localization;
- _httpClient = httpClient;
- _libraryManager = libraryManager;
- Current = this;
- }
-
- public string Name => "TheMovieDb";
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
- {
- var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- await EnsureSeriesInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);
-
- var obj = _jsonSerializer.DeserializeFromFile<RootObject>(dataFilePath);
-
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var remoteResult = new RemoteSearchResult
- {
- Name = obj.name,
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(obj.poster_path) ? null : tmdbImageUrl + obj.poster_path
- };
-
- remoteResult.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
- remoteResult.SetProviderId(MetadataProviders.Imdb, obj.external_ids.imdb_id);
-
- if (obj.external_ids.tvdb_id > 0)
- {
- remoteResult.SetProviderId(MetadataProviders.Tvdb, obj.external_ids.tvdb_id.ToString(_usCulture));
- }
-
- return new[] { remoteResult };
- }
-
- var imdbId = searchInfo.GetProviderId(MetadataProviders.Imdb);
-
- if (!string.IsNullOrEmpty(imdbId))
- {
- var searchResult = await FindByExternalId(imdbId, "imdb_id", cancellationToken).ConfigureAwait(false);
-
- if (searchResult != null)
- {
- return new[] { searchResult };
- }
- }
-
- var tvdbId = searchInfo.GetProviderId(MetadataProviders.Tvdb);
-
- if (!string.IsNullOrEmpty(tvdbId))
- {
- var searchResult = await FindByExternalId(tvdbId, "tvdb_id", cancellationToken).ConfigureAwait(false);
-
- if (searchResult != null)
- {
- return new[] { searchResult };
- }
- }
-
- return await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
- }
-
- public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
- {
- var result = new MetadataResult<Series>();
- result.QueriedById = true;
-
- var tmdbId = info.GetProviderId(MetadataProviders.Tmdb);
-
- if (string.IsNullOrEmpty(tmdbId))
- {
- var imdbId = info.GetProviderId(MetadataProviders.Imdb);
-
- if (!string.IsNullOrEmpty(imdbId))
- {
- var searchResult = await FindByExternalId(imdbId, "imdb_id", cancellationToken).ConfigureAwait(false);
-
- if (searchResult != null)
- {
- tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
- }
- }
- }
-
- if (string.IsNullOrEmpty(tmdbId))
- {
- var tvdbId = info.GetProviderId(MetadataProviders.Tvdb);
-
- if (!string.IsNullOrEmpty(tvdbId))
- {
- var searchResult = await FindByExternalId(tvdbId, "tvdb_id", cancellationToken).ConfigureAwait(false);
-
- if (searchResult != null)
- {
- tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
- }
- }
- }
-
- if (string.IsNullOrEmpty(tmdbId))
- {
- result.QueriedById = false;
- var searchResults = await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetSearchResults(info, cancellationToken).ConfigureAwait(false);
-
- var searchResult = searchResults.FirstOrDefault();
-
- if (searchResult != null)
- {
- tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
- }
- }
-
- if (!string.IsNullOrEmpty(tmdbId))
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- result = await FetchMovieData(tmdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
-
- result.HasMetadata = result.Item != null;
- }
-
- return result;
- }
-
- private async Task<MetadataResult<Series>> FetchMovieData(string tmdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
- {
- RootObject seriesInfo = await FetchMainResult(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- if (seriesInfo == null)
- {
- return null;
- }
-
- tmdbId = seriesInfo.id.ToString(_usCulture);
-
- string dataFilePath = GetDataFilePath(tmdbId, language);
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(seriesInfo, dataFilePath);
-
- await EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var result = new MetadataResult<Series>();
- result.Item = new Series();
- result.ResultLanguage = seriesInfo.ResultLanguage;
-
- var settings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- ProcessMainInfo(result, seriesInfo, preferredCountryCode, settings);
-
- return result;
- }
-
- private void ProcessMainInfo(MetadataResult<Series> seriesResult, RootObject seriesInfo, string preferredCountryCode, TmdbSettingsResult settings)
- {
- var series = seriesResult.Item;
-
- series.Name = seriesInfo.name;
- series.SetProviderId(MetadataProviders.Tmdb, seriesInfo.id.ToString(_usCulture));
-
- //series.VoteCount = seriesInfo.vote_count;
-
- string voteAvg = seriesInfo.vote_average.ToString(CultureInfo.InvariantCulture);
-
- if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out float rating))
- {
- series.CommunityRating = rating;
- }
-
- series.Overview = seriesInfo.overview;
-
- if (seriesInfo.networks != null)
- {
- series.Studios = seriesInfo.networks.Select(i => i.name).ToArray();
- }
-
- if (seriesInfo.genres != null)
- {
- series.Genres = seriesInfo.genres.Select(i => i.name).ToArray();
- }
-
- //series.HomePageUrl = seriesInfo.homepage;
-
- series.RunTimeTicks = seriesInfo.episode_run_time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();
-
- if (string.Equals(seriesInfo.status, "Ended", StringComparison.OrdinalIgnoreCase))
- {
- series.Status = SeriesStatus.Ended;
- series.EndDate = seriesInfo.last_air_date;
- }
- else
- {
- series.Status = SeriesStatus.Continuing;
- }
-
- series.PremiereDate = seriesInfo.first_air_date;
-
- var ids = seriesInfo.external_ids;
- if (ids != null)
- {
- if (!string.IsNullOrWhiteSpace(ids.imdb_id))
- {
- series.SetProviderId(MetadataProviders.Imdb, ids.imdb_id);
- }
- if (ids.tvrage_id > 0)
- {
- series.SetProviderId(MetadataProviders.TvRage, ids.tvrage_id.ToString(_usCulture));
- }
- if (ids.tvdb_id > 0)
- {
- series.SetProviderId(MetadataProviders.Tvdb, ids.tvdb_id.ToString(_usCulture));
- }
- }
-
- var contentRatings = (seriesInfo.content_ratings ?? new ContentRatings()).results ?? new List<ContentRating>();
-
- var ourRelease = contentRatings.FirstOrDefault(c => string.Equals(c.iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
- var usRelease = contentRatings.FirstOrDefault(c => string.Equals(c.iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
- var minimumRelease = contentRatings.FirstOrDefault();
-
- if (ourRelease != null)
- {
- series.OfficialRating = ourRelease.rating;
- }
- else if (usRelease != null)
- {
- series.OfficialRating = usRelease.rating;
- }
- else if (minimumRelease != null)
- {
- series.OfficialRating = minimumRelease.rating;
- }
-
- if (seriesInfo.videos != null && seriesInfo.videos.results != null)
- {
- foreach (var video in seriesInfo.videos.results)
- {
- if ((video.type.Equals("trailer", StringComparison.OrdinalIgnoreCase)
- || video.type.Equals("clip", StringComparison.OrdinalIgnoreCase))
- && video.site.Equals("youtube", StringComparison.OrdinalIgnoreCase))
- {
- series.AddTrailerUrl($"http://www.youtube.com/watch?v={video.key}");
- }
- }
- }
-
- seriesResult.ResetPeople();
- var tmdbImageUrl = settings.images.GetImageUrl("original");
-
- if (seriesInfo.credits != null && seriesInfo.credits.cast != null)
- {
- foreach (var actor in seriesInfo.credits.cast.OrderBy(a => a.order))
- {
- var personInfo = new PersonInfo
- {
- Name = actor.name.Trim(),
- Role = actor.character,
- Type = PersonType.Actor,
- SortOrder = actor.order
- };
-
- if (!string.IsNullOrWhiteSpace(actor.profile_path))
- {
- personInfo.ImageUrl = tmdbImageUrl + actor.profile_path;
- }
-
- if (actor.id > 0)
- {
- personInfo.SetProviderId(MetadataProviders.Tmdb, actor.id.ToString(CultureInfo.InvariantCulture));
- }
-
- seriesResult.AddPerson(personInfo);
- }
- }
- }
-
- internal static string GetSeriesDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetSeriesDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- internal static string GetSeriesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-tv");
-
- return dataPath;
- }
-
- internal async Task DownloadSeriesInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- RootObject mainResult = await FetchMainResult(id, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null)
- {
- return;
- }
-
- var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task<RootObject> FetchMainResult(string id, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(GetTvInfo3, id, MovieDbProvider.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += "&language=" + MovieDbProvider.NormalizeLanguage(language)
- + "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language); // Get images in english and with no language
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- RootObject mainResult;
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- mainResult = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
-
- if (!string.IsNullOrEmpty(language))
- {
- mainResult.ResultLanguage = language;
- }
- }
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // If the language preference isn't english, then have the overview fallback to english if it's blank
- if (mainResult != null &&
- string.IsNullOrEmpty(mainResult.overview) &&
- !string.IsNullOrEmpty(language) &&
- !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogInformation("MovieDbSeriesProvider couldn't find meta for language {Language}. Trying English...", language);
-
- url = string.Format(GetTvInfo3, id, MovieDbProvider.ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
- }
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var englishResult = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
-
- mainResult.overview = englishResult.overview;
- mainResult.ResultLanguage = "en";
- }
- }
- }
-
- return mainResult;
- }
-
- internal Task EnsureSeriesInfo(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetDataFilePath(tmdbId, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadSeriesInfo(tmdbId, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format("series-{0}.json", preferredLanguage ?? string.Empty);
-
- return Path.Combine(path, filename);
- }
-
- private async Task<RemoteSearchResult> FindByExternalId(string id, string externalSource, CancellationToken cancellationToken)
- {
- var url = string.Format(MovieDbProvider.BaseMovieDbUrl + @"3/find/{0}?api_key={1}&external_source={2}",
- id,
- MovieDbProvider.ApiKey,
- externalSource);
-
- using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
- {
- Url = url,
- CancellationToken = cancellationToken,
- AcceptHeader = MovieDbProvider.AcceptHeader
-
- }).ConfigureAwait(false))
- {
- using (var json = response.Content)
- {
- var result = await _jsonSerializer.DeserializeFromStreamAsync<MovieDbSearch.ExternalIdLookupResult>(json).ConfigureAwait(false);
-
- if (result != null && result.tv_results != null)
- {
- var tv = result.tv_results.FirstOrDefault();
-
- if (tv != null)
- {
- var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var remoteResult = new RemoteSearchResult
- {
- Name = tv.name,
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(tv.poster_path) ? null : tmdbImageUrl + tv.poster_path
- };
-
- remoteResult.SetProviderId(MetadataProviders.Tmdb, tv.id.ToString(_usCulture));
-
- return remoteResult;
- }
- }
- }
- }
-
- return null;
- }
-
- public class CreatedBy
- {
- public int id { get; set; }
- public string name { get; set; }
- public string profile_path { get; set; }
- }
-
- public class Genre
- {
- public int id { get; set; }
- public string name { get; set; }
- }
-
- public class Network
- {
- public int id { get; set; }
- public string name { get; set; }
- }
-
- public class Season
- {
- public string air_date { get; set; }
- public int episode_count { get; set; }
- public int id { get; set; }
- public string poster_path { get; set; }
- public int season_number { get; set; }
- }
-
- public class Cast
- {
- public string character { get; set; }
- public string credit_id { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string profile_path { get; set; }
- public int order { get; set; }
- }
-
- public class Crew
- {
- public string credit_id { get; set; }
- public string department { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public string job { get; set; }
- public string profile_path { get; set; }
- }
-
- public class Credits
- {
- public List<Cast> cast { get; set; }
- public List<Crew> crew { get; set; }
- }
-
- public class Backdrop
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- public class Poster
- {
- public double aspect_ratio { get; set; }
- public string file_path { get; set; }
- public int height { get; set; }
- public string iso_639_1 { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public int width { get; set; }
- }
-
- public class Images
- {
- public List<Backdrop> backdrops { get; set; }
- public List<Poster> posters { get; set; }
- }
-
- public class Keywords
- {
- public List<object> results { get; set; }
- }
-
- public class ExternalIds
- {
- public string imdb_id { get; set; }
- public string freebase_id { get; set; }
- public string freebase_mid { get; set; }
- public int tvdb_id { get; set; }
- public int tvrage_id { get; set; }
- }
-
- public class Videos
- {
- public List<Video> results { get; set; }
- }
-
- public class Video
- {
- public string id { get; set; }
- public string iso_639_1 { get; set; }
- public string iso_3166_1 { get; set; }
- public string key { get; set; }
- public string name { get; set; }
- public string site { get; set; }
- public string size { get; set; }
- public string type { get; set; }
- }
-
- public class ContentRating
- {
- public string iso_3166_1 { get; set; }
- public string rating { get; set; }
- }
-
- public class ContentRatings
- {
- public List<ContentRating> results { get; set; }
- }
-
- public class RootObject
- {
- public string backdrop_path { get; set; }
- public List<CreatedBy> created_by { get; set; }
- public List<int> episode_run_time { get; set; }
- public DateTime first_air_date { get; set; }
- public List<Genre> genres { get; set; }
- public string homepage { get; set; }
- public int id { get; set; }
- public bool in_production { get; set; }
- public List<string> languages { get; set; }
- public DateTime last_air_date { get; set; }
- public string name { get; set; }
- public List<Network> networks { get; set; }
- public int number_of_episodes { get; set; }
- public int number_of_seasons { get; set; }
- public string original_name { get; set; }
- public List<string> origin_country { get; set; }
- public string overview { get; set; }
- public string popularity { get; set; }
- public string poster_path { get; set; }
- public List<Season> seasons { get; set; }
- public string status { get; set; }
- public double vote_average { get; set; }
- public int vote_count { get; set; }
- public Credits credits { get; set; }
- public Images images { get; set; }
- public Keywords keywords { get; set; }
- public ExternalIds external_ids { get; set; }
- public Videos videos { get; set; }
- public ContentRatings content_ratings { get; set; }
- public string ResultLanguage { get; set; }
- }
- // After TheTVDB
- public int Order => 1;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvDbClientManager.cs b/MediaBrowser.Providers/TV/TheTVDB/TvDbClientManager.cs
deleted file mode 100644
index efb8a0fe8..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvDbClientManager.cs
+++ /dev/null
@@ -1,244 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using Microsoft.Extensions.Caching.Memory;
-using TvDbSharper;
-using TvDbSharper.Dto;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public class TvDbClientManager
- {
- private readonly SemaphoreSlim _cacheWriteLock = new SemaphoreSlim(1, 1);
- private readonly IMemoryCache _cache;
- private readonly TvDbClient _tvDbClient;
- private DateTime _tokenCreatedAt;
- private const string DefaultLanguage = "en";
-
- public TvDbClientManager(IMemoryCache memoryCache)
- {
- _cache = memoryCache;
- _tvDbClient = new TvDbClient();
- _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey);
- _tokenCreatedAt = DateTime.Now;
- }
-
- public TvDbClient TvDbClient
- {
- get
- {
- // Refresh if necessary
- if (_tokenCreatedAt > DateTime.Now.Subtract(TimeSpan.FromHours(20)))
- {
- try
- {
- _tvDbClient.Authentication.RefreshTokenAsync();
- }
- catch
- {
- _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey);
- }
-
- _tokenCreatedAt = DateTime.Now;
- }
-
- return _tvDbClient;
- }
- }
-
- public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByNameAsync(string name, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("series", name, language);
- return TryGetValue(cacheKey, language,() => TvDbClient.Search.SearchSeriesByNameAsync(name, cancellationToken));
- }
-
- public Task<TvDbResponse<Series>> GetSeriesByIdAsync(int tvdbId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("series", tvdbId, language);
- return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetAsync(tvdbId, cancellationToken));
- }
-
- public Task<TvDbResponse<EpisodeRecord>> GetEpisodesAsync(int episodeTvdbId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("episode", episodeTvdbId, language);
- return TryGetValue(cacheKey, language,() => TvDbClient.Episodes.GetAsync(episodeTvdbId, cancellationToken));
- }
-
- public async Task<List<EpisodeRecord>> GetAllEpisodesAsync(int tvdbId, string language,
- CancellationToken cancellationToken)
- {
- // Traverse all episode pages and join them together
- var episodes = new List<EpisodeRecord>();
- var episodePage = await GetEpisodesPageAsync(tvdbId, new EpisodeQuery(), language, cancellationToken)
- .ConfigureAwait(false);
- episodes.AddRange(episodePage.Data);
- if (!episodePage.Links.Next.HasValue || !episodePage.Links.Last.HasValue)
- {
- return episodes;
- }
-
- int next = episodePage.Links.Next.Value;
- int last = episodePage.Links.Last.Value;
-
- for (var page = next; page <= last; ++page)
- {
- episodePage = await GetEpisodesPageAsync(tvdbId, page, new EpisodeQuery(), language, cancellationToken)
- .ConfigureAwait(false);
- episodes.AddRange(episodePage.Data);
- }
-
- return episodes;
- }
-
- public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByImdbIdAsync(string imdbId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("series", imdbId, language);
- return TryGetValue(cacheKey, language,() => TvDbClient.Search.SearchSeriesByImdbIdAsync(imdbId, cancellationToken));
- }
-
- public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByZap2ItIdAsync(string zap2ItId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("series", zap2ItId, language);
- return TryGetValue( cacheKey, language,() => TvDbClient.Search.SearchSeriesByZap2ItIdAsync(zap2ItId, cancellationToken));
- }
- public Task<TvDbResponse<Actor[]>> GetActorsAsync(int tvdbId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("actors", tvdbId, language);
- return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetActorsAsync(tvdbId, cancellationToken));
- }
-
- public Task<TvDbResponse<Image[]>> GetImagesAsync(int tvdbId, ImagesQuery imageQuery, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("images", tvdbId, language, imageQuery);
- return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetImagesAsync(tvdbId, imageQuery, cancellationToken));
- }
-
- public Task<TvDbResponse<Language[]>> GetLanguagesAsync(CancellationToken cancellationToken)
- {
- return TryGetValue("languages", null,() => TvDbClient.Languages.GetAllAsync(cancellationToken));
- }
-
- public Task<TvDbResponse<EpisodesSummary>> GetSeriesEpisodeSummaryAsync(int tvdbId, string language,
- CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey("seriesepisodesummary", tvdbId, language);
- return TryGetValue(cacheKey, language,
- () => TvDbClient.Series.GetEpisodesSummaryAsync(tvdbId, cancellationToken));
- }
-
- public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, int page, EpisodeQuery episodeQuery,
- string language, CancellationToken cancellationToken)
- {
- var cacheKey = GenerateKey(language, tvdbId, episodeQuery);
-
- return TryGetValue(cacheKey, language,
- () => TvDbClient.Series.GetEpisodesAsync(tvdbId, page, episodeQuery, cancellationToken));
- }
-
- public Task<string> GetEpisodeTvdbId(EpisodeInfo searchInfo, string language,
- CancellationToken cancellationToken)
- {
- searchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(),
- out var seriesTvdbId);
-
- var episodeQuery = new EpisodeQuery();
-
- // Prefer SxE over premiere date as it is more robust
- if (searchInfo.IndexNumber.HasValue && searchInfo.ParentIndexNumber.HasValue)
- {
- episodeQuery.AiredEpisode = searchInfo.IndexNumber.Value;
- episodeQuery.AiredSeason = searchInfo.ParentIndexNumber.Value;
- }
- else if (searchInfo.PremiereDate.HasValue)
- {
- // tvdb expects yyyy-mm-dd format
- episodeQuery.FirstAired = searchInfo.PremiereDate.Value.ToString("yyyy-MM-dd");
- }
-
- return GetEpisodeTvdbId(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken);
- }
-
- public async Task<string> GetEpisodeTvdbId(int seriesTvdbId, EpisodeQuery episodeQuery,
- string language,
- CancellationToken cancellationToken)
- {
- var episodePage =
- await GetEpisodesPageAsync(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken)
- .ConfigureAwait(false);
- return episodePage.Data.FirstOrDefault()?.Id.ToString();
- }
-
- public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, EpisodeQuery episodeQuery,
- string language, CancellationToken cancellationToken)
- {
- return GetEpisodesPageAsync(tvdbId, 1, episodeQuery, language, cancellationToken);
- }
-
- private async Task<T> TryGetValue<T>(string key, string language, Func<Task<T>> resultFactory)
- {
- if (_cache.TryGetValue(key, out T cachedValue))
- {
- return cachedValue;
- }
-
- await _cacheWriteLock.WaitAsync().ConfigureAwait(false);
- try
- {
- if (_cache.TryGetValue(key, out cachedValue))
- {
- return cachedValue;
- }
-
- _tvDbClient.AcceptedLanguage = TvdbUtils.NormalizeLanguage(language) ?? DefaultLanguage;
- var result = await resultFactory.Invoke().ConfigureAwait(false);
- _cache.Set(key, result, TimeSpan.FromHours(1));
- return result;
- }
- finally
- {
- _cacheWriteLock.Release();
- }
- }
-
- private static string GenerateKey(params object[] objects)
- {
- var key = string.Empty;
-
- foreach (var obj in objects)
- {
- var objType = obj.GetType();
- if (objType.IsPrimitive || objType == typeof(string))
- {
- key += obj + ";";
- }
- else
- {
- foreach (PropertyInfo propertyInfo in objType.GetProperties())
- {
- var currentValue = propertyInfo.GetValue(obj, null);
- if (currentValue == null)
- {
- continue;
- }
-
- key += propertyInfo.Name + "=" + currentValue + ";";
- }
- }
- }
-
- return key;
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeImageProvider.cs
deleted file mode 100644
index c04e98e64..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeImageProvider.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-using TvDbSharper.Dto;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public class TvdbEpisodeImageProvider : IRemoteImageProvider
- {
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbEpisodeImageProvider(IHttpClient httpClient, ILogger<TvdbEpisodeImageProvider> logger, TvDbClientManager tvDbClientManager)
- {
- _httpClient = httpClient;
- _logger = logger;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public string Name => "TheTVDB";
-
- public bool Supports(BaseItem item)
- {
- return item is Episode;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var episode = (Episode)item;
- var series = episode.Series;
- var imageResult = new List<RemoteImageInfo>();
- var language = item.GetPreferredMetadataLanguage();
- if (series != null && TvdbSeriesProvider.IsValidSeries(series.ProviderIds))
- {
- var episodeTvdbId = episode.GetProviderId(MetadataProviders.Tvdb);
-
- // Process images
- try
- {
- if (string.IsNullOrEmpty(episodeTvdbId))
- {
- var episodeInfo = new EpisodeInfo
- {
- IndexNumber = episode.IndexNumber.Value,
- ParentIndexNumber = episode.ParentIndexNumber.Value,
- SeriesProviderIds = series.ProviderIds
- };
- episodeTvdbId = await _tvDbClientManager
- .GetEpisodeTvdbId(episodeInfo, language, cancellationToken).ConfigureAwait(false);
- if (string.IsNullOrEmpty(episodeTvdbId))
- {
- _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
- episodeInfo.ParentIndexNumber, episodeInfo.IndexNumber, series.GetProviderId(MetadataProviders.Tvdb));
- return imageResult;
- }
- }
-
- var episodeResult =
- await _tvDbClientManager
- .GetEpisodesAsync(Convert.ToInt32(episodeTvdbId), language, cancellationToken)
- .ConfigureAwait(false);
-
- var image = GetImageInfo(episodeResult.Data);
- if (image != null)
- {
- imageResult.Add(image);
- }
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve episode images for {TvDbId}", episodeTvdbId);
- }
- }
-
- return imageResult;
- }
-
- private RemoteImageInfo GetImageInfo(EpisodeRecord episode)
- {
- if (string.IsNullOrEmpty(episode.Filename))
- {
- return null;
- }
-
- return new RemoteImageInfo
- {
- Width = Convert.ToInt32(episode.ThumbWidth),
- Height = Convert.ToInt32(episode.ThumbHeight),
- ProviderName = Name,
- Url = TvdbUtils.BannerUrl + episode.Filename,
- Type = ImageType.Primary
- };
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
deleted file mode 100644
index b256f2667..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
+++ /dev/null
@@ -1,239 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-using TvDbSharper.Dto;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
-
- /// <summary>
- /// Class RemoteEpisodeProvider
- /// </summary>
- class TvdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder
- {
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbEpisodeProvider(IHttpClient httpClient, ILogger<TvdbEpisodeProvider> logger, TvDbClientManager tvDbClientManager)
- {
- _httpClient = httpClient;
- _logger = logger;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
- {
- var list = new List<RemoteSearchResult>();
-
- // The search query must either provide an episode number or date
- if (!searchInfo.IndexNumber.HasValue || !searchInfo.PremiereDate.HasValue)
- {
- return list;
- }
-
- if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds))
- {
- try
- {
- var episodeTvdbId = searchInfo.GetProviderId(MetadataProviders.Tvdb);
- if (string.IsNullOrEmpty(episodeTvdbId))
- {
- searchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(),
- out var seriesTvdbId);
- episodeTvdbId = await _tvDbClientManager
- .GetEpisodeTvdbId(searchInfo, searchInfo.MetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
- if (string.IsNullOrEmpty(episodeTvdbId))
- {
- _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
- searchInfo.ParentIndexNumber, searchInfo.IndexNumber, seriesTvdbId);
- return list;
- }
- }
-
- var episodeResult = await _tvDbClientManager.GetEpisodesAsync(Convert.ToInt32(episodeTvdbId),
- searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
- var metadataResult = MapEpisodeToResult(searchInfo, episodeResult.Data);
-
- if (metadataResult.HasMetadata)
- {
- var item = metadataResult.Item;
-
- list.Add(new RemoteSearchResult
- {
- IndexNumber = item.IndexNumber,
- Name = item.Name,
- ParentIndexNumber = item.ParentIndexNumber,
- PremiereDate = item.PremiereDate,
- ProductionYear = item.ProductionYear,
- ProviderIds = item.ProviderIds,
- SearchProviderName = Name,
- IndexNumberEnd = item.IndexNumberEnd
- });
- }
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve episode with id {TvDbId}", searchInfo.IndexNumber);
- }
- }
-
- return list;
- }
-
- public string Name => "TheTVDB";
-
- public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo searchInfo, CancellationToken cancellationToken)
- {
- var result = new MetadataResult<Episode>
- {
- QueriedById = true
- };
-
- if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds) &&
- (searchInfo.IndexNumber.HasValue || searchInfo.PremiereDate.HasValue))
- {
- var tvdbId = searchInfo.GetProviderId(MetadataProviders.Tvdb);
- try
- {
- if (string.IsNullOrEmpty(tvdbId))
- {
- tvdbId = await _tvDbClientManager
- .GetEpisodeTvdbId(searchInfo, searchInfo.MetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
- if (string.IsNullOrEmpty(tvdbId))
- {
- _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
- searchInfo.ParentIndexNumber, searchInfo.IndexNumber, tvdbId);
- return result;
- }
- }
-
- var episodeResult = await _tvDbClientManager.GetEpisodesAsync(
- Convert.ToInt32(tvdbId), searchInfo.MetadataLanguage,
- cancellationToken).ConfigureAwait(false);
-
- result = MapEpisodeToResult(searchInfo, episodeResult.Data);
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve episode with id {TvDbId}", tvdbId);
- }
- }
- else
- {
- _logger.LogDebug("No series identity found for {EpisodeName}", searchInfo.Name);
- }
-
- return result;
- }
-
- private static MetadataResult<Episode> MapEpisodeToResult(EpisodeInfo id, EpisodeRecord episode)
- {
- var result = new MetadataResult<Episode>
- {
- HasMetadata = true,
- Item = new Episode
- {
- IndexNumber = id.IndexNumber,
- ParentIndexNumber = id.ParentIndexNumber,
- IndexNumberEnd = id.IndexNumberEnd,
- AirsBeforeEpisodeNumber = episode.AirsBeforeEpisode,
- AirsAfterSeasonNumber = episode.AirsAfterSeason,
- AirsBeforeSeasonNumber = episode.AirsBeforeSeason,
- Name = episode.EpisodeName,
- Overview = episode.Overview,
- CommunityRating = (float?)episode.SiteRating,
-
- }
- };
- result.ResetPeople();
-
- var item = result.Item;
- item.SetProviderId(MetadataProviders.Tvdb, episode.Id.ToString());
- item.SetProviderId(MetadataProviders.Imdb, episode.ImdbId);
-
- if (string.Equals(id.SeriesDisplayOrder, "dvd", StringComparison.OrdinalIgnoreCase))
- {
- item.IndexNumber = Convert.ToInt32(episode.DvdEpisodeNumber ?? episode.AiredEpisodeNumber);
- item.ParentIndexNumber = episode.DvdSeason ?? episode.AiredSeason;
- }
- else if (episode.AiredEpisodeNumber.HasValue)
- {
- item.IndexNumber = episode.AiredEpisodeNumber;
- }
- else if (episode.AiredSeason.HasValue)
- {
- item.ParentIndexNumber = episode.AiredSeason;
- }
-
- if (DateTime.TryParse(episode.FirstAired, out var date))
- {
- // dates from tvdb are UTC but without offset or Z
- item.PremiereDate = date;
- item.ProductionYear = date.Year;
- }
-
- foreach (var director in episode.Directors)
- {
- result.AddPerson(new PersonInfo
- {
- Name = director,
- Type = PersonType.Director
- });
- }
- foreach (var person in episode.GuestStars)
- {
- var index = person.IndexOf('(');
- string role = null;
- var name = person;
-
- if (index != -1)
- {
- role = person.Substring(index + 1).Trim().TrimEnd(')');
-
- name = person.Substring(0, index).Trim();
- }
-
- result.AddPerson(new PersonInfo
- {
- Type = PersonType.GuestStar,
- Name = name,
- Role = role
- });
- }
- foreach (var writer in episode.Writers)
- {
- result.AddPerson(new PersonInfo
- {
- Name = writer,
- Type = PersonType.Writer
- });
- }
-
- result.ResultLanguage = episode.Language.EpisodeName;
- return result;
- }
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
-
- public int Order => 0;
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeasonImageProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeasonImageProvider.cs
deleted file mode 100644
index 94ca603f2..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeasonImageProvider.cs
+++ /dev/null
@@ -1,155 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-using TvDbSharper.Dto;
-using RatingType = MediaBrowser.Model.Dto.RatingType;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public class TvdbSeasonImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbSeasonImageProvider(IHttpClient httpClient, ILogger<TvdbSeasonImageProvider> logger, TvDbClientManager tvDbClientManager)
- {
- _httpClient = httpClient;
- _logger = logger;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheTVDB";
-
- public bool Supports(BaseItem item)
- {
- return item is Season;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Banner,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var season = (Season)item;
- var series = season.Series;
-
- if (series == null || !season.IndexNumber.HasValue || !TvdbSeriesProvider.IsValidSeries(series.ProviderIds))
- {
- return new RemoteImageInfo[] { };
- }
-
- var tvdbId = Convert.ToInt32(series.GetProviderId(MetadataProviders.Tvdb));
- var seasonNumber = season.IndexNumber.Value;
- var language = item.GetPreferredMetadataLanguage();
- var remoteImages = new List<RemoteImageInfo>();
-
- var keyTypes = new[] { KeyType.Season, KeyType.Seasonwide, KeyType.Fanart };
- foreach (var keyType in keyTypes)
- {
- var imageQuery = new ImagesQuery
- {
- KeyType = keyType,
- SubKey = seasonNumber.ToString()
- };
- try
- {
- var imageResults = await _tvDbClientManager
- .GetImagesAsync(tvdbId, imageQuery, language, cancellationToken).ConfigureAwait(false);
- remoteImages.AddRange(GetImages(imageResults.Data, language));
- }
- catch (TvDbServerException)
- {
- _logger.LogDebug("No images of type {KeyType} found for series {TvdbId}", keyType, tvdbId);
- }
- }
-
- return remoteImages;
- }
-
- private IEnumerable<RemoteImageInfo> GetImages(Image[] images, string preferredLanguage)
- {
- var list = new List<RemoteImageInfo>();
- var languages = _tvDbClientManager.GetLanguagesAsync(CancellationToken.None).Result.Data;
- foreach (Image image in images)
- {
- var imageInfo = new RemoteImageInfo
- {
- RatingType = RatingType.Score,
- CommunityRating = (double?)image.RatingsInfo.Average,
- VoteCount = image.RatingsInfo.Count,
- Url = TvdbUtils.BannerUrl + image.FileName,
- ProviderName = ProviderName,
- Language = languages.FirstOrDefault(lang => lang.Id == image.LanguageId)?.Abbreviation,
- ThumbnailUrl = TvdbUtils.BannerUrl + image.Thumbnail
- };
-
- var resolution = image.Resolution.Split('x');
- if (resolution.Length == 2)
- {
- imageInfo.Width = Convert.ToInt32(resolution[0]);
- imageInfo.Height = Convert.ToInt32(resolution[1]);
- }
-
- imageInfo.Type = TvdbUtils.GetImageTypeFromKeyType(image.KeyType);
- list.Add(imageInfo);
- }
- var isLanguageEn = string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(preferredLanguage, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs
deleted file mode 100644
index 365f49fb7..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs
+++ /dev/null
@@ -1,152 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-using TvDbSharper.Dto;
-using RatingType = MediaBrowser.Model.Dto.RatingType;
-using Series = MediaBrowser.Controller.Entities.TV.Series;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public class TvdbSeriesImageProvider : IRemoteImageProvider, IHasOrder
- {
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbSeriesImageProvider(IHttpClient httpClient, ILogger<TvdbSeriesImageProvider> logger, TvDbClientManager tvDbClientManager)
- {
- _httpClient = httpClient;
- _logger = logger;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public string Name => ProviderName;
-
- public static string ProviderName => "TheTVDB";
-
- public bool Supports(BaseItem item)
- {
- return item is Series;
- }
-
- public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
- {
- return new List<ImageType>
- {
- ImageType.Primary,
- ImageType.Banner,
- ImageType.Backdrop
- };
- }
-
- public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- if (!TvdbSeriesProvider.IsValidSeries(item.ProviderIds))
- {
- return Array.Empty<RemoteImageInfo>();
- }
-
- var language = item.GetPreferredMetadataLanguage();
- var remoteImages = new List<RemoteImageInfo>();
- var keyTypes = new[] { KeyType.Poster, KeyType.Series, KeyType.Fanart };
- var tvdbId = Convert.ToInt32(item.GetProviderId(MetadataProviders.Tvdb));
- foreach (KeyType keyType in keyTypes)
- {
- var imageQuery = new ImagesQuery
- {
- KeyType = keyType
- };
- try
- {
- var imageResults =
- await _tvDbClientManager.GetImagesAsync(tvdbId, imageQuery, language, cancellationToken)
- .ConfigureAwait(false);
-
- remoteImages.AddRange(GetImages(imageResults.Data, language));
- }
- catch (TvDbServerException)
- {
- _logger.LogDebug("No images of type {KeyType} exist for series {TvDbId}", keyType,
- tvdbId);
- }
- }
- return remoteImages;
- }
-
- private IEnumerable<RemoteImageInfo> GetImages(Image[] images, string preferredLanguage)
- {
- var list = new List<RemoteImageInfo>();
- var languages = _tvDbClientManager.GetLanguagesAsync(CancellationToken.None).Result.Data;
-
- foreach (Image image in images)
- {
- var imageInfo = new RemoteImageInfo
- {
- RatingType = RatingType.Score,
- CommunityRating = (double?)image.RatingsInfo.Average,
- VoteCount = image.RatingsInfo.Count,
- Url = TvdbUtils.BannerUrl + image.FileName,
- ProviderName = Name,
- Language = languages.FirstOrDefault(lang => lang.Id == image.LanguageId)?.Abbreviation,
- ThumbnailUrl = TvdbUtils.BannerUrl + image.Thumbnail
- };
-
- var resolution = image.Resolution.Split('x');
- if (resolution.Length == 2)
- {
- imageInfo.Width = Convert.ToInt32(resolution[0]);
- imageInfo.Height = Convert.ToInt32(resolution[1]);
- }
-
- imageInfo.Type = TvdbUtils.GetImageTypeFromKeyType(image.KeyType);
- list.Add(imageInfo);
- }
- var isLanguageEn = string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(preferredLanguage, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
deleted file mode 100644
index 9c24e4c98..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
+++ /dev/null
@@ -1,440 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Providers;
-using Microsoft.Extensions.Logging;
-using TvDbSharper;
-using TvDbSharper.Dto;
-using Series = MediaBrowser.Controller.Entities.TV.Series;
-
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public class TvdbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
- {
- internal static TvdbSeriesProvider Current { get; private set; }
- private readonly IHttpClient _httpClient;
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localizationManager;
- private readonly TvDbClientManager _tvDbClientManager;
-
- public TvdbSeriesProvider(IHttpClient httpClient, ILogger<TvdbSeriesProvider> logger, ILibraryManager libraryManager, ILocalizationManager localizationManager, TvDbClientManager tvDbClientManager)
- {
- _httpClient = httpClient;
- _logger = logger;
- _libraryManager = libraryManager;
- _localizationManager = localizationManager;
- Current = this;
- _tvDbClientManager = tvDbClientManager;
- }
-
- public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
- {
- if (IsValidSeries(searchInfo.ProviderIds))
- {
- var metadata = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false);
-
- if (metadata.HasMetadata)
- {
- return new List<RemoteSearchResult>
- {
- new RemoteSearchResult
- {
- Name = metadata.Item.Name,
- PremiereDate = metadata.Item.PremiereDate,
- ProductionYear = metadata.Item.ProductionYear,
- ProviderIds = metadata.Item.ProviderIds,
- SearchProviderName = Name
- }
- };
- }
- }
-
- return await FindSeries(searchInfo.Name, searchInfo.Year, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
- }
-
- public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo itemId, CancellationToken cancellationToken)
- {
- var result = new MetadataResult<Series>
- {
- QueriedById = true
- };
-
- if (!IsValidSeries(itemId.ProviderIds))
- {
- result.QueriedById = false;
- await Identify(itemId).ConfigureAwait(false);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- if (IsValidSeries(itemId.ProviderIds))
- {
- result.Item = new Series();
- result.HasMetadata = true;
-
- await FetchSeriesData(result, itemId.MetadataLanguage, itemId.ProviderIds, cancellationToken)
- .ConfigureAwait(false);
- }
-
- return result;
- }
-
- private async Task FetchSeriesData(MetadataResult<Series> result, string metadataLanguage, Dictionary<string, string> seriesProviderIds, CancellationToken cancellationToken)
- {
- var series = result.Item;
-
- if (seriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out var tvdbId) && !string.IsNullOrEmpty(tvdbId))
- {
- series.SetProviderId(MetadataProviders.Tvdb, tvdbId);
- }
-
- if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out var imdbId) && !string.IsNullOrEmpty(imdbId))
- {
- series.SetProviderId(MetadataProviders.Imdb, imdbId);
- tvdbId = await GetSeriesByRemoteId(imdbId, MetadataProviders.Imdb.ToString(), metadataLanguage,
- cancellationToken).ConfigureAwait(false);
- }
-
- if (seriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out var zap2It) && !string.IsNullOrEmpty(zap2It))
- {
- series.SetProviderId(MetadataProviders.Zap2It, zap2It);
- tvdbId = await GetSeriesByRemoteId(zap2It, MetadataProviders.Zap2It.ToString(), metadataLanguage,
- cancellationToken).ConfigureAwait(false);
- }
-
- try
- {
- var seriesResult =
- await _tvDbClientManager
- .GetSeriesByIdAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken)
- .ConfigureAwait(false);
- MapSeriesToResult(result, seriesResult.Data, metadataLanguage);
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve series with id {TvdbId}", tvdbId);
- return;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- result.ResetPeople();
-
- try
- {
- var actorsResult = await _tvDbClientManager
- .GetActorsAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken).ConfigureAwait(false);
- MapActorsToResult(result, actorsResult.Data);
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve actors for series {TvdbId}", tvdbId);
- }
- }
-
- private async Task<string> GetSeriesByRemoteId(string id, string idType, string language, CancellationToken cancellationToken)
- {
- TvDbResponse<SeriesSearchResult[]> result = null;
-
- try
- {
- if (string.Equals(idType, MetadataProviders.Zap2It.ToString(), StringComparison.OrdinalIgnoreCase))
- {
- result = await _tvDbClientManager.GetSeriesByZap2ItIdAsync(id, language, cancellationToken)
- .ConfigureAwait(false);
- }
- else
- {
- result = await _tvDbClientManager.GetSeriesByImdbIdAsync(id, language, cancellationToken)
- .ConfigureAwait(false);
- }
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to retrieve series with remote id {RemoteId}", id);
- }
-
- return result?.Data.First().Id.ToString();
- }
-
- internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
- {
- return seriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out _) ||
- seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out _) ||
- seriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out _);
- }
-
- /// <summary>
- /// Finds the series.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="year">The year.</param>
- /// <param name="language">The language.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.String}.</returns>
- private async Task<IEnumerable<RemoteSearchResult>> FindSeries(string name, int? year, string language, CancellationToken cancellationToken)
- {
- var results = await FindSeriesInternal(name, language, cancellationToken).ConfigureAwait(false);
-
- if (results.Count == 0)
- {
- var parsedName = _libraryManager.ParseName(name);
- var nameWithoutYear = parsedName.Name;
-
- if (!string.IsNullOrWhiteSpace(nameWithoutYear) && !string.Equals(nameWithoutYear, name, StringComparison.OrdinalIgnoreCase))
- {
- results = await FindSeriesInternal(nameWithoutYear, language, cancellationToken).ConfigureAwait(false);
- }
- }
-
- return results.Where(i =>
- {
- if (year.HasValue && i.ProductionYear.HasValue)
- {
- // Allow one year tolerance
- return Math.Abs(year.Value - i.ProductionYear.Value) <= 1;
- }
-
- return true;
- });
- }
-
- private async Task<List<RemoteSearchResult>> FindSeriesInternal(string name, string language, CancellationToken cancellationToken)
- {
- var comparableName = GetComparableName(name);
- var list = new List<Tuple<List<string>, RemoteSearchResult>>();
- TvDbResponse<SeriesSearchResult[]> result;
- try
- {
- result = await _tvDbClientManager.GetSeriesByNameAsync(comparableName, language, cancellationToken)
- .ConfigureAwait(false);
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "No series results found for {Name}", comparableName);
- return new List<RemoteSearchResult>();
- }
-
- foreach (var seriesSearchResult in result.Data)
- {
- var tvdbTitles = new List<string>
- {
- GetComparableName(seriesSearchResult.SeriesName)
- };
- tvdbTitles.AddRange(seriesSearchResult.Aliases.Select(GetComparableName));
-
- DateTime.TryParse(seriesSearchResult.FirstAired, out var firstAired);
- var remoteSearchResult = new RemoteSearchResult
- {
- Name = tvdbTitles.FirstOrDefault(),
- ProductionYear = firstAired.Year,
- SearchProviderName = Name,
- ImageUrl = TvdbUtils.BannerUrl + seriesSearchResult.Banner
-
- };
- try
- {
- var seriesSesult =
- await _tvDbClientManager.GetSeriesByIdAsync(seriesSearchResult.Id, language, cancellationToken)
- .ConfigureAwait(false);
- remoteSearchResult.SetProviderId(MetadataProviders.Imdb, seriesSesult.Data.ImdbId);
- remoteSearchResult.SetProviderId(MetadataProviders.Zap2It, seriesSesult.Data.Zap2itId);
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Unable to retrieve series with id {TvdbId}", seriesSearchResult.Id);
- }
-
- remoteSearchResult.SetProviderId(MetadataProviders.Tvdb, seriesSearchResult.Id.ToString());
- list.Add(new Tuple<List<string>, RemoteSearchResult>(tvdbTitles, remoteSearchResult));
- }
-
- return list
- .OrderBy(i => i.Item1.Contains(comparableName, StringComparer.OrdinalIgnoreCase) ? 0 : 1)
- .ThenBy(i => list.IndexOf(i))
- .Select(i => i.Item2)
- .ToList();
- }
-
- /// <summary>
- /// The remove
- /// </summary>
- const string remove = "\"'!`?";
- /// <summary>
- /// The spacers
- /// </summary>
- const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are two types of dashes, short and long)
-
- /// <summary>
- /// Gets the name of the comparable.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <returns>System.String.</returns>
- private string GetComparableName(string name)
- {
- name = name.ToLowerInvariant();
- name = _localizationManager.NormalizeFormKD(name);
- var sb = new StringBuilder();
- foreach (var c in name)
- {
- if (c >= 0x2B0 && c <= 0x0333)
- {
- // skip char modifier and diacritics
- }
- else if (remove.IndexOf(c) > -1)
- {
- // skip chars we are removing
- }
- else if (spacers.IndexOf(c) > -1)
- {
- sb.Append(" ");
- }
- else if (c == '&')
- {
- sb.Append(" and ");
- }
- else
- {
- sb.Append(c);
- }
- }
- name = sb.ToString();
- name = name.Replace(", the", "");
- name = name.Replace("the ", " ");
- name = name.Replace(" the ", " ");
-
- string prevName;
- do
- {
- prevName = name;
- name = name.Replace(" ", " ");
- } while (name.Length != prevName.Length);
-
- return name.Trim();
- }
-
- private void MapSeriesToResult(MetadataResult<Series> result, TvDbSharper.Dto.Series tvdbSeries, string metadataLanguage)
- {
- Series series = result.Item;
- series.SetProviderId(MetadataProviders.Tvdb, tvdbSeries.Id.ToString());
- series.Name = tvdbSeries.SeriesName;
- series.Overview = (tvdbSeries.Overview ?? string.Empty).Trim();
- result.ResultLanguage = metadataLanguage;
- series.AirDays = TVUtils.GetAirDays(tvdbSeries.AirsDayOfWeek);
- series.AirTime = tvdbSeries.AirsTime;
-
- series.CommunityRating = (float?)tvdbSeries.SiteRating;
- series.SetProviderId(MetadataProviders.Imdb, tvdbSeries.ImdbId);
- series.SetProviderId(MetadataProviders.Zap2It, tvdbSeries.Zap2itId);
- if (Enum.TryParse(tvdbSeries.Status, true, out SeriesStatus seriesStatus))
- {
- series.Status = seriesStatus;
- }
-
- if (DateTime.TryParse(tvdbSeries.FirstAired, out var date))
- {
- // dates from tvdb are UTC but without offset or Z
- series.PremiereDate = date;
- series.ProductionYear = date.Year;
- }
-
- series.RunTimeTicks = TimeSpan.FromMinutes(Convert.ToDouble(tvdbSeries.Runtime)).Ticks;
- foreach (var genre in tvdbSeries.Genre)
- {
- series.AddGenre(genre);
- }
-
- series.AddStudio(tvdbSeries.Network);
-
- if (result.Item.Status.HasValue && result.Item.Status.Value == SeriesStatus.Ended)
- {
- try
- {
- var episodeSummary = _tvDbClientManager
- .GetSeriesEpisodeSummaryAsync(tvdbSeries.Id, metadataLanguage, CancellationToken.None).Result.Data;
- var maxSeasonNumber = episodeSummary.AiredSeasons.Select(s => Convert.ToInt32(s)).Max();
- var episodeQuery = new EpisodeQuery
- {
- AiredSeason = maxSeasonNumber
- };
- var episodesPage =
- _tvDbClientManager.GetEpisodesPageAsync(tvdbSeries.Id, episodeQuery, metadataLanguage, CancellationToken.None).Result.Data;
- result.Item.EndDate = episodesPage.Select(e =>
- {
- DateTime.TryParse(e.FirstAired, out var firstAired);
- return firstAired;
- }).Max();
- }
- catch (TvDbServerException e)
- {
- _logger.LogError(e, "Failed to find series end date for series {TvdbId}", tvdbSeries.Id);
- }
- }
- }
-
- private static void MapActorsToResult(MetadataResult<Series> result, IEnumerable<Actor> actors)
- {
- foreach (Actor actor in actors)
- {
- var personInfo = new PersonInfo
- {
- Type = PersonType.Actor,
- Name = (actor.Name ?? string.Empty).Trim(),
- Role = actor.Role,
- ImageUrl = TvdbUtils.BannerUrl + actor.Image,
- SortOrder = actor.SortOrder
- };
-
- if (!string.IsNullOrWhiteSpace(personInfo.Name))
- {
- result.AddPerson(personInfo);
- }
- }
- }
-
- public string Name => "TheTVDB";
-
- public async Task Identify(SeriesInfo info)
- {
- if (!string.IsNullOrWhiteSpace(info.GetProviderId(MetadataProviders.Tvdb)))
- {
- return;
- }
-
- var srch = await FindSeries(info.Name, info.Year, info.MetadataLanguage, CancellationToken.None)
- .ConfigureAwait(false);
-
- var entry = srch.FirstOrDefault();
-
- if (entry != null)
- {
- var id = entry.GetProviderId(MetadataProviders.Tvdb);
- info.SetProviderId(MetadataProviders.Tvdb, id);
- }
- }
-
- public int Order => 0;
-
- public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClient.GetResponse(new HttpRequestOptions
- {
- CancellationToken = cancellationToken,
- Url = url,
- BufferContent = false
- });
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbUtils.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbUtils.cs
deleted file mode 100644
index 112cbf800..000000000
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbUtils.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-using System.ComponentModel;
-using MediaBrowser.Model.Entities;
-namespace MediaBrowser.Providers.TV.TheTVDB
-{
- public static class TvdbUtils
- {
- public const string TvdbApiKey = "OG4V3YJ3FAP7FP2K";
- public const string TvdbBaseUrl = "https://www.thetvdb.com/";
- public const string BannerUrl = TvdbBaseUrl + "banners/";
-
- public static ImageType GetImageTypeFromKeyType(string keyType)
- {
- switch (keyType.ToLowerInvariant())
- {
- case "poster":
- case "season": return ImageType.Primary;
- case "series":
- case "seasonwide": return ImageType.Banner;
- case "fanart": return ImageType.Backdrop;
- default: throw new ArgumentException($"Invalid or unknown keytype: {keyType}", nameof(keyType));
- }
- }
-
- public static string NormalizeLanguage(string language)
- {
- if (string.IsNullOrWhiteSpace(language))
- {
- return null;
- }
-
- // pt-br is just pt to tvdb
- return language.Split('-')[0].ToLowerInvariant();
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/TvExternalIds.cs b/MediaBrowser.Providers/TV/TvExternalIds.cs
deleted file mode 100644
index 3f889fbbe..000000000
--- a/MediaBrowser.Providers/TV/TvExternalIds.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Providers.TV.TheTVDB;
-
-namespace MediaBrowser.Providers.TV
-{
- public class Zap2ItExternalId : IExternalId
- {
- public string Name => "Zap2It";
-
- public string Key => MetadataProviders.Zap2It.ToString();
-
- public string UrlFormatString => "http://tvlistings.zap2it.com/overview.html?programSeriesId={0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Series;
- }
- }
-
- public class TvdbExternalId : IExternalId
- {
- public string Name => "TheTVDB";
-
- public string Key => MetadataProviders.Tvdb.ToString();
-
- public string UrlFormatString => TvdbUtils.TvdbBaseUrl + "?tab=series&id={0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Series;
- }
- }
-
- public class TvdbSeasonExternalId : IExternalId
- {
- public string Name => "TheTVDB";
-
- public string Key => MetadataProviders.Tvdb.ToString();
-
- public string UrlFormatString => null;
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Season;
- }
- }
-
- public class TvdbEpisodeExternalId : IExternalId
- {
- public string Name => "TheTVDB";
-
- public string Key => MetadataProviders.Tvdb.ToString();
-
- public string UrlFormatString => TvdbUtils.TvdbBaseUrl + "?tab=episode&id={0}";
-
- public bool Supports(IHasProviderIds item)
- {
- return item is Episode;
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/Zap2ItExternalId.cs b/MediaBrowser.Providers/TV/Zap2ItExternalId.cs
new file mode 100644
index 000000000..087e4036a
--- /dev/null
+++ b/MediaBrowser.Providers/TV/Zap2ItExternalId.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Providers.TV
+{
+ public class Zap2ItExternalId : IExternalId
+ {
+ /// <inheritdoc />
+ public string ProviderName => "Zap2It";
+
+ /// <inheritdoc />
+ public string Key => MetadataProvider.Zap2It.ToString();
+
+ /// <inheritdoc />
+ public ExternalIdMediaType? Type => null;
+
+ /// <inheritdoc />
+ public string? UrlFormatString => "http://tvlistings.zap2it.com/overview.html?programSeriesId={0}";
+
+ /// <inheritdoc />
+ public bool Supports(IHasProviderIds item) => item is Series;
+ }
+}
diff --git a/MediaBrowser.Providers/Users/UserMetadataService.cs b/MediaBrowser.Providers/Users/UserMetadataService.cs
deleted file mode 100644
index 024c2f959..000000000
--- a/MediaBrowser.Providers/Users/UserMetadataService.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Providers.Manager;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Users
-{
- public class UserMetadataService : MetadataService<User, ItemLookupInfo>
- {
- protected override void MergeData(MetadataResult<User> source, MetadataResult<User> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- }
-
- public UserMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
- }
-}
diff --git a/MediaBrowser.Providers/Videos/VideoMetadataService.cs b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
index f5f5b8971..31c7eaac4 100644
--- a/MediaBrowser.Providers/Videos/VideoMetadataService.cs
+++ b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,16 +13,24 @@ namespace MediaBrowser.Providers.Videos
{
public class VideoMetadataService : MetadataService<Video, ItemLookupInfo>
{
+ 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;
- protected override void MergeData(MetadataResult<Video> source, MetadataResult<Video> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Video> source, MetadataResult<Video> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
-
- public VideoMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Years/YearMetadataService.cs b/MediaBrowser.Providers/Years/YearMetadataService.cs
index b94494253..6151d12e9 100644
--- a/MediaBrowser.Providers/Years/YearMetadataService.cs
+++ b/MediaBrowser.Providers/Years/YearMetadataService.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -11,13 +13,20 @@ namespace MediaBrowser.Providers.Years
{
public class YearMetadataService : MetadataService<Year, ItemLookupInfo>
{
- protected override void MergeData(MetadataResult<Year> source, MetadataResult<Year> target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ public YearMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<YearMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
- public YearMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Year> source, MetadataResult<Year> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
}
}
}
diff --git a/MediaBrowser.Tests/ConsistencyTests/Resources/SampleTransformed.htm b/MediaBrowser.Tests/ConsistencyTests/Resources/SampleTransformed.htm
deleted file mode 100644
index f36652468..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/Resources/SampleTransformed.htm
+++ /dev/null
@@ -1,1277 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>String Usage Report</title>
- <style>
-body {
- background: #F3F3F4;
- color: #1E1E1F;
- font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
- padding: 0;
- margin: 0;
-}
-h1 {
- padding: 10px 0px 10px 10px;
- font-size: 21pt;
- background-color: #E2E2E2;
- border-bottom: 1px #C1C1C2 solid;
- color: #201F20;
- margin: 0;
- font-weight: normal;
-}
-h2 {
- font-size: 18pt;
- font-weight: normal;
- padding: 15px 0 5px 0;
- margin: 0;
-}
-h3 {
- font-weight: normal;
- font-size: 15pt;
- margin: 0;
- padding: 15px 0 5px 0;
- background-color: transparent;
-}
-/* Color all hyperlinks one color */
-a {
- color: #1382CE;
-}
-/* Table styles */
-table {
- border-spacing: 0 0;
- border-collapse: collapse;
- font-size: 10pt;
-}
-table th {
- background: #E7E7E8;
- text-align: left;
- text-decoration: none;
- font-weight: normal;
- padding: 3px 6px 3px 6px;
- border: 1px solid #CBCBCB;
-}
-table td {
- vertical-align: top;
- padding: 3px 6px 5px 5px;
- margin: 0px;
- border: 1px solid #CBCBCB;
- background: #F7F7F8;
-}
-/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
-.localLink {
- color: #1E1E1F;
- background: #EEEEED;
- text-decoration: none;
-}
-.localLink:hover {
- color: #1382CE;
- background: #FFFF99;
- text-decoration: none;
-}
-.baseCell {
- width: 100%;
- color: #427A9F;
-}
-.stringCell {
- display: table;
-}
-.tokenCell {
- white-space: nowrap;
-}
-.occurrence {
- padding-left: 40px;
-}
-.block {
- display: table-cell;
-}
-/* Padding around the content after the h1 */
-#content {
- padding: 0px 12px 12px 12px;
-}
-#messages table {
- width: 97%;
-}
- </style>
- </head>
- <body>
- <h1>String Usage Report</h1>
- <div id="content">
- <h2>Strings</h2>
- <div id="messages">
- <table>
- <tbody>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelExit</strong>: "</div>
- <div class="block">Exit"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelVisitCommunity</strong>: "</div>
- <div class="block">Visit Community"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelGithub</strong>: "</div>
- <div class="block">Github"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelSwagger</strong>: "</div>
- <div class="block">Swagger"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelStandard</strong>: "</div>
- <div class="block">Standard"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelApiDocumentation</strong>: "</div>
- <div class="block">Api Documentation"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelDeveloperResources</strong>: "</div>
- <div class="block">Developer Resources"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelBrowseLibrary</strong>: "</div>
- <div class="block">Browse Library"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelConfigureServer</strong>: "</div>
- <div class="block">Configure Emby"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelOpenLibraryViewer</strong>: "</div>
- <div class="block">Open Library Viewer"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelRestartServer</strong>: "</div>
- <div class="block">Restart Server"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelShowLogWindow</strong>: "</div>
- <div class="block">Show Log Window"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelPrevious</strong>: "</div>
- <div class="block">Previous"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardcomponents.html">\wizardcomponents.html:54</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html">\wizardfinish.html:40</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlibrary.html">\wizardlibrary.html:19</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvguide.html">\wizardlivetvguide.html:30</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvtuner.html">\wizardlivetvtuner.html:31</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:17</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html">\wizardsettings.html:32</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:27</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelFinish</strong>: "</div>
- <div class="block">Finish"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html">\wizardfinish.html:41</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelNext</strong>: "</div>
- <div class="block">Next"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardcomponents.html">\wizardcomponents.html:55</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlibrary.html">\wizardlibrary.html:20</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvguide.html">\wizardlivetvguide.html:31</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvtuner.html">\wizardlivetvtuner.html:32</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:18</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html">\wizardsettings.html:33</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html">\wizardstart.html:25</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:28</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelYoureDone</strong>: "</div>
- <div class="block">You're Done!"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html">\wizardfinish.html:7</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>WelcomeToProject</strong>: "</div>
- <div class="block">Welcome to Emby!"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html">\wizardstart.html:10</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ThisWizardWillGuideYou</strong>: "</div>
- <div class="block">This wizard will help guide you through the setup process. To begin, please select your preferred language."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html">\wizardstart.html:16</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>TellUsAboutYourself</strong>: "</div>
- <div class="block">Tell us about yourself"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:8</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonQuickStartGuide</strong>: "</div>
- <div class="block">Quick start guide"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html">\wizardstart.html:12</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelYourFirstName</strong>: "</div>
- <div class="block">Your first name:"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:14</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>MoreUsersCanBeAddedLater</strong>: "</div>
- <div class="block">More users can be added later within the Dashboard."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:15</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>UserProfilesIntro</strong>: "</div>
- <div class="block">Emby includes built-in support for user profiles, enabling each user to have their own display settings, playstate and parental controls."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html">\wizarduser.html:11</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelWindowsService</strong>: "</div>
- <div class="block">Windows Service"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:7</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>AWindowsServiceHasBeenInstalled</strong>: "</div>
- <div class="block">A Windows Service has been installed."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:10</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>WindowsServiceIntro1</strong>: "</div>
- <div class="block">Emby Server normally runs as a desktop application with a tray icon, but if you prefer to run it as a background service, it can be started from the windows services control panel instead."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:12</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>WindowsServiceIntro2</strong>: "</div>
- <div class="block">If using the windows service, please note that it cannot be run at the same time as the tray icon, so you'll need to exit the tray in order to run the service. The service will also need to be configured with administrative privileges via the control panel. When running as a service, you will need to ensure that the service account has access to your media folders."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html">\wizardservice.html:14</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>WizardCompleted</strong>: "</div>
- <div class="block">That's all we need for now. Emby has begun collecting information about your media library. Check out some of our apps, and then click &lt;b&gt;Finish&lt;/b&gt; to view the &lt;b&gt;Server Dashboard&lt;/b&gt;."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html">\wizardfinish.html:10</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelConfigureSettings</strong>: "</div>
- <div class="block">Configure settings"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html">\wizardsettings.html:8</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelEnableVideoImageExtraction</strong>: "</div>
- <div class="block">Enable video image extraction"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>VideoImageExtractionHelp</strong>: "</div>
- <div class="block">For videos that don't already have images, and that we're unable to find internet images for. This will add some additional time to the initial library scan but will result in a more pleasing presentation."</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelEnableChapterImageExtractionForMovies</strong>: "</div>
- <div class="block">Extract chapter image extraction for Movies"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelChapterImageExtractionForMoviesHelp</strong>: "</div>
- <div class="block">Extracting chapter images will allow clients to display graphical scene selection menus. The process can be slow, cpu-intensive and may require several gigabytes of space. It runs as a nightly scheduled task, although this is configurable in the scheduled tasks area. It is not recommended to run this task during peak usage hours."</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelEnableAutomaticPortMapping</strong>: "</div>
- <div class="block">Enable automatic port mapping"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelEnableAutomaticPortMappingHelp</strong>: "</div>
- <div class="block">UPnP allows automated router configuration for easy remote access. This may not work with some router models."</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderTermsOfService</strong>: "</div>
- <div class="block">Emby Terms of Service"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderDeveloperOptions</strong>: "</div>
- <div class="block">Developer Options"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:108</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>OptionEnableWebClientResponseCache</strong>: "</div>
- <div class="block">Enable web response caching"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:112</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>OptionDisableForDevelopmentHelp</strong>: "</div>
- <div class="block">Configure these as needed for web development purposes."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:119</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>OptionEnableWebClientResourceMinification</strong>: "</div>
- <div class="block">Enable web resource minification"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:116</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelDashboardSourcePath</strong>: "</div>
- <div class="block">Web client source path:"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:124</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelDashboardSourcePathHelp</strong>: "</div>
- <div class="block">If running the server from source, specify the path to the dashboard-ui folder. All web client files will be served from this location."</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html">\dashboardgeneral.html:126</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonConvertMedia</strong>: "</div>
- <div class="block">Convert media"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\syncactivity.html">\syncactivity.html:22</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonOrganize</strong>: "</div>
- <div class="block">Organize"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\autoorganizelog.html">\autoorganizelog.html:8</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js">\scripts\autoorganizelog.js:293</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js">\scripts\autoorganizelog.js:294</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js">\scripts\autoorganizelog.js:296</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LinkedToEmbyConnect</strong>: "</div>
- <div class="block">Linked to Emby Connect"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderSupporterBenefits</strong>: "</div>
- <div class="block">Emby Premiere Benefits"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderAddUser</strong>: "</div>
- <div class="block">Add User"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelAddConnectSupporterHelp</strong>: "</div>
- <div class="block">To add a user who isn't listed, you'll need to first link their account to Emby Connect from their user profile page."</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>LabelPinCode</strong>: "</div>
- <div class="block">Pin code:"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>OptionHideWatchedContentFromLatestMedia</strong>: "</div>
- <div class="block">Hide watched content from latest media"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\mypreferenceshome.html">\mypreferenceshome.html:114</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderSync</strong>: "</div>
- <div class="block">Sync"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\mysyncsettings.html">\mysyncsettings.html:7</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\registrationservices.js">\scripts\registrationservices.js:175</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\useredit.html">\useredit.html:82</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonOk</strong>: "</div>
- <div class="block">Ok"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\directorybrowser\directorybrowser.js">\components\directorybrowser\directorybrowser.js:147</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\fileorganizer\fileorganizer.template.html">\components\fileorganizer\fileorganizer.template.html:45</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\medialibrarycreator\medialibrarycreator.template.html">\components\medialibrarycreator\medialibrarycreator.template.html:30</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\metadataeditor\personeditor.template.html">\components\metadataeditor\personeditor.template.html:33</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:372</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:453</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:504</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:542</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:590</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:630</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:661</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:706</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\nowplaying.html">\nowplaying.html:113</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\ratingdialog.js">\scripts\ratingdialog.js:42</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonCancel</strong>: "</div>
- <div class="block">Cancel"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\tvproviders\schedulesdirect.template.html">\components\tvproviders\schedulesdirect.template.html:68</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\tvproviders\xmltv.template.html">\components\tvproviders\xmltv.template.html:48</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\connectlogin.html">\connectlogin.html:74</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\connectlogin.html">\connectlogin.html:108</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:325</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:375</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:456</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:507</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:545</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:593</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:633</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:664</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:709</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\forgotpassword.html">\forgotpassword.html:23</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\forgotpasswordpin.html">\forgotpasswordpin.html:22</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvseriestimer.html">\livetvseriestimer.html:62</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-hdhomerun.html">\livetvtunerprovider-hdhomerun.html:35</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-m3u.html">\livetvtunerprovider-m3u.html:19</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-satip.html">\livetvtunerprovider-satip.html:65</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\login.html">\login.html:27</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\notificationsetting.html">\notificationsetting.html:64</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scheduledtask.html">\scheduledtask.html:85</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\librarylist.js">\scripts\librarylist.js:349</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\mediacontroller.js">\scripts\mediacontroller.js:167</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\mediacontroller.js">\scripts\mediacontroller.js:436</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\ratingdialog.js">\scripts\ratingdialog.js:43</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\site.js">\scripts\site.js:1025</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\userprofilespage.js">\scripts\userprofilespage.js:198</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\syncsettings.html">\syncsettings.html:43</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\useredit.html">\useredit.html:111</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userlibraryaccess.html">\userlibraryaccess.html:57</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\usernew.html">\usernew.html:45</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userparentalcontrol.html">\userparentalcontrol.html:101</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonExit</strong>: "</div>
- <div class="block">Exit"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>ButtonNew</strong>: "</div>
- <div class="block">New"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\fileorganizer\fileorganizer.template.html">\components\fileorganizer\fileorganizer.template.html:18</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:107</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:278</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:290</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:296</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:302</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:308</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html">\dlnaprofile.html:314</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofiles.html">\dlnaprofiles.html:14</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\serversecurity.html">\serversecurity.html:8</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderTaskTriggers</strong>: "</div>
- <div class="block">Task Triggers"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scheduledtask.html">\scheduledtask.html:11</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderTV</strong>: "</div>
- <div class="block">TV"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html">\librarysettings.html:113</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderAudio</strong>: "</div>
- <div class="block">Audio"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html">\librarysettings.html:39</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderVideo</strong>: "</div>
- <div class="block">Video"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html">\librarysettings.html:50</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderPaths</strong>: "</div>
- <div class="block">Paths"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboard.html">\dashboard.html:92</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>CategorySync</strong>: "</div>
- <div class="block">Sync"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>TabPlaylist</strong>: "</div>
- <div class="block">Playlist"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\nowplaying.html">\nowplaying.html:20</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderEasyPinCode</strong>: "</div>
- <div class="block">Easy Pin Code"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\myprofile.html">\myprofile.html:69</a>
- </td>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userpassword.html">\userpassword.html:42</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderGrownupsOnly</strong>: "</div>
- <div class="block">Grown-ups Only!"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>DividerOr</strong>: "</div>
- <div class="block">-- or --"</div>
- </div>
- </th>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderInstalledServices</strong>: "</div>
- <div class="block">Installed Services"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\appservices.html">\appservices.html:6</a>
- </td>
- </tr>
- <tr>
- <th class="baseCell">
- <div class="stringCell">
- <div class="block tokenCell">
- <strong>HeaderAvailableServices</strong>: "</div>
- <div class="block">Available Services"</div>
- </div>
- </th>
- </tr>
- <tr>
- <td class="baseCell occurrence">
- <a href="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\appservices.html">\appservices.html:11</a>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </body>
-</html>
diff --git a/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheck.xslt b/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheck.xslt
deleted file mode 100644
index 39586022b..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheck.xslt
+++ /dev/null
@@ -1,145 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- DWXMLSource="StringCheckSample.xml" -->
-<!DOCTYPE xsl:stylesheet [
- <!ENTITY nbsp "&#160;">
- <!ENTITY copy "&#169;">
- <!ENTITY reg "&#174;">
- <!ENTITY trade "&#8482;">
- <!ENTITY mdash "&#8212;">
- <!ENTITY ldquo "&#8220;">
- <!ENTITY rdquo "&#8221;">
- <!ENTITY pound "&#163;">
- <!ENTITY yen "&#165;">
- <!ENTITY euro "&#8364;">
-]>
-<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:output method="html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
- <xsl:template match="/">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <title>
- <xsl:value-of select="StringUsages/@ReportTitle"/>
- </title>
- <style>
-body {
- background: #F3F3F4;
- color: #1E1E1F;
- font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
- padding: 0;
- margin: 0;
-}
-h1 {
- padding: 10px 0px 10px 10px;
- font-size: 21pt;
- background-color: #E2E2E2;
- border-bottom: 1px #C1C1C2 solid;
- color: #201F20;
- margin: 0;
- font-weight: normal;
-}
-h2 {
- font-size: 18pt;
- font-weight: normal;
- padding: 15px 0 5px 0;
- margin: 0;
-}
-h3 {
- font-weight: normal;
- font-size: 15pt;
- margin: 0;
- padding: 15px 0 5px 0;
- background-color: transparent;
-}
-/* Color all hyperlinks one color */
-a {
- color: #1382CE;
-}
-/* Table styles */
-table {
- border-spacing: 0 0;
- border-collapse: collapse;
- font-size: 10pt;
-}
-table th {
- background: #E7E7E8;
- text-align: left;
- text-decoration: none;
- font-weight: normal;
- padding: 3px 6px 3px 6px;
- border: 1px solid #CBCBCB;
-}
-table td {
- vertical-align: top;
- padding: 3px 6px 5px 5px;
- margin: 0px;
- border: 1px solid #CBCBCB;
- background: #F7F7F8;
-}
-/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
-.localLink {
- color: #1E1E1F;
- background: #EEEEED;
- text-decoration: none;
-}
-.localLink:hover {
- color: #1382CE;
- background: #FFFF99;
- text-decoration: none;
-}
-.baseCell {
- width: 100%;
- color: #427A9F;
-}
-.stringCell {
- display: table;
-}
-.tokenCell {
- white-space: nowrap;
-}
-.occurrence {
- padding-left: 40px;
-}
-.block {
- display: table-cell;
-}
-/* Padding around the content after the h1 */
-#content {
- padding: 0px 12px 12px 12px;
-}
-#messages table {
- width: 97%;
-}
- </style>
- </head>
- <body>
- <h1>
- <xsl:value-of select="StringUsages/@ReportTitle"/>
- </h1>
- <div id="content">
- <h2>Strings</h2>
- <div id="messages">
- <table>
- <tbody>
- <xsl:for-each select="StringUsages/Dictionary">
- <tr>
- <th class="baseCell"> <div class="stringCell">
- <div class="block tokenCell"><strong><xsl:value-of select="@Token"/></strong>: "</div>
- <div class="block"><xsl:value-of select="@Text"/>"</div>
- </div></th>
- </tr>
- <xsl:for-each select="Occurence">
- <xsl:variable name="hyperlink"><xsl:value-of select="@FullPath" /></xsl:variable>
- <tr>
- <td class="baseCell occurrence"><a href="{@FullPath}"><xsl:value-of select="@FileName"/>:<xsl:value-of select="@LineNumber"/></a></td>
- </tr>
- </xsl:for-each>
- </xsl:for-each>
- </tbody>
- </table>
- </div>
- </div>
- </body>
- </html>
- </xsl:template>
-</xsl:stylesheet> \ No newline at end of file
diff --git a/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheckSample.xml b/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheckSample.xml
deleted file mode 100644
index 9c65bddcd..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/Resources/StringCheckSample.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" encoding="utf-8" standalone="yes"?>
-<?xml-stylesheet type="text/xsl" href="StringCheck.xslt"?>
-<StringUsages Mode="All">
- <Dictionary Token="LabelExit" Text="Exit" />
- <Dictionary Token="LabelVisitCommunity" Text="Visit Community" />
- <Dictionary Token="LabelGithub" Text="Github" />
- <Dictionary Token="LabelSwagger" Text="Swagger" />
- <Dictionary Token="LabelStandard" Text="Standard" />
- <Dictionary Token="LabelApiDocumentation" Text="Api Documentation" />
- <Dictionary Token="LabelDeveloperResources" Text="Developer Resources" />
- <Dictionary Token="LabelBrowseLibrary" Text="Browse Library" />
- <Dictionary Token="LabelConfigureServer" Text="Configure Emby" />
- <Dictionary Token="LabelOpenLibraryViewer" Text="Open Library Viewer" />
- <Dictionary Token="LabelRestartServer" Text="Restart Server" />
- <Dictionary Token="LabelShowLogWindow" Text="Show Log Window" />
- <Dictionary Token="LabelPrevious" Text="Previous">
- <Occurence FileName="\wizardcomponents.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardcomponents.html" LineNumber="54" />
- <Occurence FileName="\wizardfinish.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html" LineNumber="40" />
- <Occurence FileName="\wizardlibrary.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlibrary.html" LineNumber="19" />
- <Occurence FileName="\wizardlivetvguide.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvguide.html" LineNumber="30" />
- <Occurence FileName="\wizardlivetvtuner.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvtuner.html" LineNumber="31" />
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="17" />
- <Occurence FileName="\wizardsettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html" LineNumber="32" />
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="27" />
- </Dictionary>
- <Dictionary Token="LabelFinish" Text="Finish">
- <Occurence FileName="\wizardfinish.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html" LineNumber="41" />
- </Dictionary>
- <Dictionary Token="LabelNext" Text="Next">
- <Occurence FileName="\wizardcomponents.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardcomponents.html" LineNumber="55" />
- <Occurence FileName="\wizardlibrary.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlibrary.html" LineNumber="20" />
- <Occurence FileName="\wizardlivetvguide.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvguide.html" LineNumber="31" />
- <Occurence FileName="\wizardlivetvtuner.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardlivetvtuner.html" LineNumber="32" />
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="18" />
- <Occurence FileName="\wizardsettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html" LineNumber="33" />
- <Occurence FileName="\wizardstart.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html" LineNumber="25" />
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="28" />
- </Dictionary>
- <Dictionary Token="LabelYoureDone" Text="You're Done!">
- <Occurence FileName="\wizardfinish.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html" LineNumber="7" />
- </Dictionary>
- <Dictionary Token="WelcomeToProject" Text="Welcome to Emby!">
- <Occurence FileName="\wizardstart.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html" LineNumber="10" />
- </Dictionary>
- <Dictionary Token="ThisWizardWillGuideYou" Text="This wizard will help guide you through the setup process. To begin, please select your preferred language.">
- <Occurence FileName="\wizardstart.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html" LineNumber="16" />
- </Dictionary>
- <Dictionary Token="TellUsAboutYourself" Text="Tell us about yourself">
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="8" />
- </Dictionary>
- <Dictionary Token="ButtonQuickStartGuide" Text="Quick start guide">
- <Occurence FileName="\wizardstart.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardstart.html" LineNumber="12" />
- </Dictionary>
- <Dictionary Token="LabelYourFirstName" Text="Your first name:">
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="14" />
- </Dictionary>
- <Dictionary Token="MoreUsersCanBeAddedLater" Text="More users can be added later within the Dashboard.">
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="15" />
- </Dictionary>
- <Dictionary Token="UserProfilesIntro" Text="Emby includes built-in support for user profiles, enabling each user to have their own display settings, playstate and parental controls.">
- <Occurence FileName="\wizarduser.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizarduser.html" LineNumber="11" />
- </Dictionary>
- <Dictionary Token="LabelWindowsService" Text="Windows Service">
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="7" />
- </Dictionary>
- <Dictionary Token="AWindowsServiceHasBeenInstalled" Text="A Windows Service has been installed.">
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="10" />
- </Dictionary>
- <Dictionary Token="WindowsServiceIntro1" Text="Emby Server normally runs as a desktop application with a tray icon, but if you prefer to run it as a background service, it can be started from the windows services control panel instead.">
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="12" />
- </Dictionary>
- <Dictionary Token="WindowsServiceIntro2" Text="If using the windows service, please note that it cannot be run at the same time as the tray icon, so you'll need to exit the tray in order to run the service. The service will also need to be configured with administrative privileges via the control panel. When running as a service, you will need to ensure that the service account has access to your media folders.">
- <Occurence FileName="\wizardservice.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardservice.html" LineNumber="14" />
- </Dictionary>
- <Dictionary Token="WizardCompleted" Text="That's all we need for now. Emby has begun collecting information about your media library. Check out some of our apps, and then click &lt;b&gt;Finish&lt;/b&gt; to view the &lt;b&gt;Server Dashboard&lt;/b&gt;.">
- <Occurence FileName="\wizardfinish.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardfinish.html" LineNumber="10" />
- </Dictionary>
- <Dictionary Token="LabelConfigureSettings" Text="Configure settings">
- <Occurence FileName="\wizardsettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\wizardsettings.html" LineNumber="8" />
- </Dictionary>
- <Dictionary Token="LabelEnableVideoImageExtraction" Text="Enable video image extraction" />
- <Dictionary Token="VideoImageExtractionHelp" Text="For videos that don't already have images, and that we're unable to find internet images for. This will add some additional time to the initial library scan but will result in a more pleasing presentation." />
- <Dictionary Token="LabelEnableChapterImageExtractionForMovies" Text="Extract chapter image extraction for Movies" />
- <Dictionary Token="LabelChapterImageExtractionForMoviesHelp" Text="Extracting chapter images will allow clients to display graphical scene selection menus. The process can be slow, cpu-intensive and may require several gigabytes of space. It runs as a nightly scheduled task, although this is configurable in the scheduled tasks area. It is not recommended to run this task during peak usage hours." />
- <Dictionary Token="LabelEnableAutomaticPortMapping" Text="Enable automatic port mapping" />
- <Dictionary Token="LabelEnableAutomaticPortMappingHelp" Text="UPnP allows automated router configuration for easy remote access. This may not work with some router models." />
- <Dictionary Token="HeaderDeveloperOptions" Text="Developer Options">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="108" />
- </Dictionary>
- <Dictionary Token="OptionEnableWebClientResponseCache" Text="Enable web response caching">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="112" />
- </Dictionary>
- <Dictionary Token="OptionDisableForDevelopmentHelp" Text="Configure these as needed for web development purposes.">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="119" />
- </Dictionary>
- <Dictionary Token="OptionEnableWebClientResourceMinification" Text="Enable web resource minification">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="116" />
- </Dictionary>
- <Dictionary Token="LabelDashboardSourcePath" Text="Web client source path:">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="124" />
- </Dictionary>
- <Dictionary Token="LabelDashboardSourcePathHelp" Text="If running the server from source, specify the path to the dashboard-ui folder. All web client files will be served from this location.">
- <Occurence FileName="\dashboardgeneral.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboardgeneral.html" LineNumber="126" />
- </Dictionary>
- <Dictionary Token="ButtonConvertMedia" Text="Convert media">
- <Occurence FileName="\syncactivity.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\syncactivity.html" LineNumber="22" />
- </Dictionary>
- <Dictionary Token="ButtonOrganize" Text="Organize">
- <Occurence FileName="\autoorganizelog.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\autoorganizelog.html" LineNumber="8" />
- <Occurence FileName="\scripts\autoorganizelog.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js" LineNumber="293" />
- <Occurence FileName="\scripts\autoorganizelog.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js" LineNumber="294" />
- <Occurence FileName="\scripts\autoorganizelog.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\autoorganizelog.js" LineNumber="296" />
- </Dictionary>
- <Dictionary Token="LinkedToEmbyConnect" Text="Linked to Emby Connect" />
- <Dictionary Token="HeaderSupporterBenefits" Text="Emby Premiere Benefits" />
- <Dictionary Token="HeaderAddUser" Text="Add User" />
- <Dictionary Token="LabelAddConnectSupporterHelp" Text="To add a user who isn't listed, you'll need to first link their account to Emby Connect from their user profile page." />
- <Dictionary Token="LabelPinCode" Text="Pin code:" />
- <Dictionary Token="OptionHideWatchedContentFromLatestMedia" Text="Hide watched content from latest media">
- <Occurence FileName="\mypreferenceshome.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\mypreferenceshome.html" LineNumber="114" />
- </Dictionary>
- <Dictionary Token="HeaderSync" Text="Sync">
- <Occurence FileName="\mysyncsettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\mysyncsettings.html" LineNumber="7" />
- <Occurence FileName="\scripts\registrationservices.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\registrationservices.js" LineNumber="175" />
- <Occurence FileName="\useredit.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\useredit.html" LineNumber="82" />
- </Dictionary>
- <Dictionary Token="ButtonOk" Text="Ok">
- <Occurence FileName="\components\directorybrowser\directorybrowser.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\directorybrowser\directorybrowser.js" LineNumber="147" />
- <Occurence FileName="\components\fileorganizer\fileorganizer.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\fileorganizer\fileorganizer.template.html" LineNumber="45" />
- <Occurence FileName="\components\medialibrarycreator\medialibrarycreator.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\medialibrarycreator\medialibrarycreator.template.html" LineNumber="30" />
- <Occurence FileName="\components\metadataeditor\personeditor.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\metadataeditor\personeditor.template.html" LineNumber="33" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="372" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="453" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="504" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="542" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="590" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="630" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="661" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="706" />
- <Occurence FileName="\nowplaying.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\nowplaying.html" LineNumber="113" />
- <Occurence FileName="\scripts\ratingdialog.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\ratingdialog.js" LineNumber="42" />
- </Dictionary>
- <Dictionary Token="ButtonCancel" Text="Cancel">
- <Occurence FileName="\components\tvproviders\schedulesdirect.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\tvproviders\schedulesdirect.template.html" LineNumber="68" />
- <Occurence FileName="\components\tvproviders\xmltv.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\tvproviders\xmltv.template.html" LineNumber="48" />
- <Occurence FileName="\connectlogin.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\connectlogin.html" LineNumber="74" />
- <Occurence FileName="\connectlogin.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\connectlogin.html" LineNumber="108" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="325" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="375" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="456" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="507" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="545" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="593" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="633" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="664" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="709" />
- <Occurence FileName="\forgotpassword.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\forgotpassword.html" LineNumber="23" />
- <Occurence FileName="\forgotpasswordpin.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\forgotpasswordpin.html" LineNumber="22" />
- <Occurence FileName="\livetvseriestimer.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvseriestimer.html" LineNumber="62" />
- <Occurence FileName="\livetvtunerprovider-hdhomerun.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-hdhomerun.html" LineNumber="35" />
- <Occurence FileName="\livetvtunerprovider-m3u.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-m3u.html" LineNumber="19" />
- <Occurence FileName="\livetvtunerprovider-satip.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\livetvtunerprovider-satip.html" LineNumber="65" />
- <Occurence FileName="\login.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\login.html" LineNumber="27" />
- <Occurence FileName="\notificationsetting.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\notificationsetting.html" LineNumber="64" />
- <Occurence FileName="\scheduledtask.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scheduledtask.html" LineNumber="85" />
- <Occurence FileName="\scripts\librarylist.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\librarylist.js" LineNumber="349" />
- <Occurence FileName="\scripts\mediacontroller.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\mediacontroller.js" LineNumber="167" />
- <Occurence FileName="\scripts\mediacontroller.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\mediacontroller.js" LineNumber="436" />
- <Occurence FileName="\scripts\ratingdialog.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\ratingdialog.js" LineNumber="43" />
- <Occurence FileName="\scripts\site.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\site.js" LineNumber="1025" />
- <Occurence FileName="\scripts\userprofilespage.js" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scripts\userprofilespage.js" LineNumber="198" />
- <Occurence FileName="\syncsettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\syncsettings.html" LineNumber="43" />
- <Occurence FileName="\useredit.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\useredit.html" LineNumber="111" />
- <Occurence FileName="\userlibraryaccess.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userlibraryaccess.html" LineNumber="57" />
- <Occurence FileName="\usernew.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\usernew.html" LineNumber="45" />
- <Occurence FileName="\userparentalcontrol.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userparentalcontrol.html" LineNumber="101" />
- </Dictionary>
- <Dictionary Token="ButtonExit" Text="Exit" />
- <Dictionary Token="ButtonNew" Text="New">
- <Occurence FileName="\components\fileorganizer\fileorganizer.template.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\components\fileorganizer\fileorganizer.template.html" LineNumber="18" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="107" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="278" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="290" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="296" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="302" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="308" />
- <Occurence FileName="\dlnaprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofile.html" LineNumber="314" />
- <Occurence FileName="\dlnaprofiles.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dlnaprofiles.html" LineNumber="14" />
- <Occurence FileName="\serversecurity.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\serversecurity.html" LineNumber="8" />
- </Dictionary>
- <Dictionary Token="HeaderTaskTriggers" Text="Task Triggers">
- <Occurence FileName="\scheduledtask.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\scheduledtask.html" LineNumber="11" />
- </Dictionary>
- <Dictionary Token="HeaderTV" Text="TV">
- <Occurence FileName="\librarysettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html" LineNumber="113" />
- </Dictionary>
- <Dictionary Token="HeaderAudio" Text="Audio">
- <Occurence FileName="\librarysettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html" LineNumber="39" />
- </Dictionary>
- <Dictionary Token="HeaderVideo" Text="Video">
- <Occurence FileName="\librarysettings.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\librarysettings.html" LineNumber="50" />
- </Dictionary>
- <Dictionary Token="HeaderPaths" Text="Paths">
- <Occurence FileName="\dashboard.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\dashboard.html" LineNumber="92" />
- </Dictionary>
- <Dictionary Token="CategorySync" Text="Sync" />
- <Dictionary Token="TabPlaylist" Text="Playlist">
- <Occurence FileName="\nowplaying.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\nowplaying.html" LineNumber="20" />
- </Dictionary>
- <Dictionary Token="HeaderEasyPinCode" Text="Easy Pin Code">
- <Occurence FileName="\myprofile.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\myprofile.html" LineNumber="69" />
- <Occurence FileName="\userpassword.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\userpassword.html" LineNumber="42" />
- </Dictionary>
- <Dictionary Token="HeaderGrownupsOnly" Text="Grown-ups Only!" />
- <Dictionary Token="DividerOr" Text="-- or --" />
- <Dictionary Token="HeaderInstalledServices" Text="Installed Services">
- <Occurence FileName="\appservices.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\appservices.html" LineNumber="6" />
- </Dictionary>
- <Dictionary Token="HeaderAvailableServices" Text="Available Services">
- <Occurence FileName="\appservices.html" FullPath="F:\Projects\Softworkz_Emby\Emby\MediaBrowser.WebDashboard\dashboard-ui\appservices.html" LineNumber="11" />
- </Dictionary>
-</StringUsages>
diff --git a/MediaBrowser.Tests/ConsistencyTests/StringUsageReporter.cs b/MediaBrowser.Tests/ConsistencyTests/StringUsageReporter.cs
deleted file mode 100644
index 1fd511e86..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/StringUsageReporter.cs
+++ /dev/null
@@ -1,259 +0,0 @@
-using MediaBrowser.Tests.ConsistencyTests.TextIndexing;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml;
-
-namespace MediaBrowser.Tests.ConsistencyTests
-{
- /// <summary>
- /// This class contains tests for reporting the usage of localization string tokens
- /// in the dashboard-ui or similar.
- /// </summary>
- /// <remarks>
- /// <para>Run one of the two tests using Visual Studio's "Test Explorer":</para>
- /// <para>
- /// <list type="bullet">
- /// <item><see cref="ReportStringUsage"/></item>
- /// <item><see cref="ReportUnusedStrings"/></item>
- /// </list>
- /// </para>
- /// <para>
- /// On successful run, the bottom section of the test explorer will contain a link "Output".
- /// This link will open the test results, displaying the trace and two attachment links.
- /// One link will open the output folder, the other link will open the output xml file.
- /// </para>
- /// <para>
- /// The output xml file contains a stylesheet link to render the results as html.
- /// How that works depends on the default application configured for XML files:
- /// </para>
- /// <para><list type="bullet">
- /// <item><term>Visual Studio</term>
- /// <description>Will open in XML source view. To view the html result, click menu
- /// 'XML' => 'Start XSLT without debugging'</description></item>
- /// <item><term>Internet Explorer</term>
- /// <description>XSL transform will be applied automatically.</description></item>
- /// <item><term>Firefox</term>
- /// <description>XSL transform will be applied automatically.</description></item>
- /// <item><term>Chrome</term>
- /// <description>Does not work. Chrome is unable/unwilling to apply xslt transforms from local files.</description></item>
- /// </list></para>
- /// </remarks>
- [TestClass]
- public class StringUsageReporter
- {
- /// <summary>
- /// Root path of the web application
- /// </summary>
- /// <remarks>
- /// Can be an absolute path or a path relative to the binaries folder (bin\Debug).
- /// </remarks>
- public const string WebFolder = @"..\..\..\MediaBrowser.WebDashboard\dashboard-ui";
-
- /// <summary>
- /// Path to the strings file, relative to <see cref="WebFolder"/>.
- /// </summary>
- public const string StringsFile = @"strings\en-US.json";
-
- /// <summary>
- /// Path to the output folder
- /// </summary>
- /// <remarks>
- /// Can be an absolute path or a path relative to the binaries folder (bin\Debug).
- /// Important: When changing the output path, make sure that "StringCheck.xslt" is present
- /// to make the XML transform work.
- /// </remarks>
- public const string OutputPath = @".";
-
- /// <summary>
- /// List of file extension to search.
- /// </summary>
- public static string[] TargetExtensions = new[] { ".js", ".html" };
-
- /// <summary>
- /// List of paths to exclude from search.
- /// </summary>
- public static string[] ExcludePaths = new[] { @"\bower_components\", @"\thirdparty\" };
-
- private TestContext testContextInstance;
-
- /// <summary>
- ///Gets or sets the test context which provides
- ///information about and functionality for the current test run.
- ///</summary>
- public TestContext TestContext
- {
- get
- {
- return testContextInstance;
- }
- set
- {
- testContextInstance = value;
- }
- }
-
- //[TestMethod]
- //public void ReportStringUsage()
- //{
- // this.CheckDashboardStrings(false);
- //}
-
- [TestMethod]
- public void ReportUnusedStrings()
- {
- this.CheckDashboardStrings(true);
- }
-
- private void CheckDashboardStrings(Boolean unusedOnly)
- {
- // Init Folders
- var currentDir = System.IO.Directory.GetCurrentDirectory();
- Trace("CurrentDir: {0}", currentDir);
-
- var rootFolderInfo = ResolveFolder(currentDir, WebFolder);
- Trace("Web Root: {0}", rootFolderInfo.FullName);
-
- var outputFolderInfo = ResolveFolder(currentDir, OutputPath);
- Trace("Output Path: {0}", outputFolderInfo.FullName);
-
- // Load Strings
- var stringsFileName = Path.Combine(rootFolderInfo.FullName, StringsFile);
-
- if (!File.Exists(stringsFileName))
- {
- throw new Exception(string.Format("Strings file not found: {0}", stringsFileName));
- }
-
- int lineNumbers;
- var stringsDic = this.CreateStringsDictionary(new FileInfo(stringsFileName), out lineNumbers);
-
- Trace("Loaded {0} strings from strings file containing {1} lines", stringsDic.Count, lineNumbers);
-
- var allFiles = rootFolderInfo.GetFiles("*", SearchOption.AllDirectories);
-
- var filteredFiles1 = allFiles.Where(f => TargetExtensions.Any(e => string.Equals(e, f.Extension, StringComparison.OrdinalIgnoreCase)));
- var filteredFiles2 = filteredFiles1.Where(f => !ExcludePaths.Any(p => f.FullName.Contains(p)));
-
- var selectedFiles = filteredFiles2.OrderBy(f => f.FullName).ToList();
-
- var wordIndex = IndexBuilder.BuildIndexFromFiles(selectedFiles, rootFolderInfo.FullName);
-
- Trace("Created word index from {0} files containing {1} individual words", selectedFiles.Count, wordIndex.Keys.Count);
-
- var outputFileName = Path.Combine(outputFolderInfo.FullName, string.Format("StringCheck_{0:yyyyMMddHHmmss}.xml", DateTime.Now));
- var settings = new XmlWriterSettings
- {
- Indent = true,
- Encoding = Encoding.UTF8,
- WriteEndDocumentOnClose = true
- };
-
- Trace("Output file: {0}", outputFileName);
-
- using (XmlWriter writer = XmlWriter.Create(outputFileName, settings))
- {
- writer.WriteStartDocument(true);
-
- // Write the Processing Instruction node.
- string xslText = "type=\"text/xsl\" href=\"StringCheck.xslt\"";
- writer.WriteProcessingInstruction("xml-stylesheet", xslText);
-
- writer.WriteStartElement("StringUsages");
- writer.WriteAttributeString("ReportTitle", unusedOnly ? "Unused Strings Report" : "String Usage Report");
- writer.WriteAttributeString("Mode", unusedOnly ? "UnusedOnly" : "All");
-
- foreach (var kvp in stringsDic)
- {
- var occurences = wordIndex.Find(kvp.Key);
-
- if (occurences == null || !unusedOnly)
- {
- ////Trace("{0}: {1}", kvp.Key, kvp.Value);
- writer.WriteStartElement("Dictionary");
- writer.WriteAttributeString("Token", kvp.Key);
- writer.WriteAttributeString("Text", kvp.Value);
-
- if (occurences != null && !unusedOnly)
- {
- foreach (var occurence in occurences)
- {
- writer.WriteStartElement("Occurence");
- writer.WriteAttributeString("FileName", occurence.FileName);
- writer.WriteAttributeString("FullPath", occurence.FullPath);
- writer.WriteAttributeString("LineNumber", occurence.LineNumber.ToString());
- writer.WriteEndElement();
- ////Trace(" {0}:{1}", occurence.FileName, occurence.LineNumber);
- }
- }
-
- writer.WriteEndElement();
- }
- }
- }
-
- TestContext.AddResultFile(outputFileName);
- TestContext.AddResultFile(outputFolderInfo.FullName);
- }
-
- private SortedDictionary<string, string> CreateStringsDictionary(FileInfo file, out int lineNumbers)
- {
- var dic = new SortedDictionary<string, string>();
- lineNumbers = 0;
-
- using (var reader = file.OpenText())
- {
- while (!reader.EndOfStream)
- {
- lineNumbers++;
- var words = reader
- .ReadLine()
- .Split(new[] { "\":" }, StringSplitOptions.RemoveEmptyEntries);
-
-
- if (words.Length == 2)
- {
- var token = words[0].Replace("\"", string.Empty).Trim();
- var text = words[1].Replace("\",", string.Empty).Replace("\"", string.Empty).Trim();
-
- if (dic.Keys.Contains(token))
- {
- throw new Exception(string.Format("Double string entry found: {0}", token));
- }
-
- dic.Add(token, text);
- }
- }
- }
-
- return dic;
- }
-
- private DirectoryInfo ResolveFolder(string currentDir, string folderPath)
- {
- if (folderPath.IndexOf(@"\:") != 1)
- {
- folderPath = Path.Combine(currentDir, folderPath);
- }
-
- var folderInfo = new DirectoryInfo(folderPath);
-
- if (!folderInfo.Exists)
- {
- throw new Exception(string.Format("Folder not found: {0}", folderInfo.FullName));
- }
-
- return folderInfo;
- }
-
-
- private void Trace(string message, params object[] parameters)
- {
- var formatted = string.Format(message, parameters);
- System.Diagnostics.Trace.WriteLine(formatted);
- }
- }
-}
diff --git a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/IndexBuilder.cs b/MediaBrowser.Tests/ConsistencyTests/TextIndexing/IndexBuilder.cs
deleted file mode 100644
index 4c46f4793..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/IndexBuilder.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-
-namespace MediaBrowser.Tests.ConsistencyTests.TextIndexing
-{
- public class IndexBuilder
- {
- public const int MinumumWordLength = 4;
-
- public static char[] WordChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
-
- public static WordIndex BuildIndexFromFiles(IEnumerable<FileInfo> wordFiles, string rootFolderPath)
- {
- var index = new WordIndex();
-
- var wordSeparators = Enumerable.Range(32, 127).Select(e => Convert.ToChar(e)).Where(c => !WordChars.Contains(c)).ToArray();
- wordSeparators = wordSeparators.Concat(new[] { '\t' }).ToArray(); // add tab
-
- foreach (var file in wordFiles)
- {
- var lineNumber = 1;
- var displayFileName = file.FullName.Replace(rootFolderPath, string.Empty);
- using (var reader = file.OpenText())
- {
- while (!reader.EndOfStream)
- {
- var words = reader
- .ReadLine()
- .Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries);
- ////.Select(f => f.Trim());
-
- var wordIndex = 1;
- foreach (var word in words)
- {
- if (word.Length >= MinumumWordLength)
- {
- index.AddWordOccurrence(word, displayFileName, file.FullName, lineNumber, wordIndex++);
- }
- }
-
- lineNumber++;
- }
- }
- }
-
- return index;
- }
-
- }
-}
diff --git a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordIndex.cs b/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordIndex.cs
deleted file mode 100644
index e0af08792..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordIndex.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace MediaBrowser.Tests.ConsistencyTests.TextIndexing
-{
- public class WordIndex : Dictionary<string, WordOccurrences>
- {
- public WordIndex() : base(StringComparer.InvariantCultureIgnoreCase)
- {
- }
-
- public void AddWordOccurrence(string word, string fileName, string fullPath, int lineNumber, int wordIndex)
- {
- WordOccurrences current;
- if (!this.TryGetValue(word, out current))
- {
- current = new WordOccurrences();
- this[word] = current;
- }
-
- current.AddOccurrence(fileName, fullPath, lineNumber, wordIndex);
- }
-
- public WordOccurrences Find(string word)
- {
- WordOccurrences found;
- if (this.TryGetValue(word, out found))
- {
- return found;
- }
-
- return null;
- }
-
- }
-}
diff --git a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrence.cs b/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrence.cs
deleted file mode 100644
index b30e58624..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrence.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace MediaBrowser.Tests.ConsistencyTests.TextIndexing
-{
- public struct WordOccurrence
- {
- public readonly string FileName; // file containing the word.
- public readonly string FullPath; // file containing the word.
- public readonly int LineNumber; // line within the file.
- public readonly int WordIndex; // index within the line.
-
- public WordOccurrence(string fileName, string fullPath, int lineNumber, int wordIndex)
- {
- FileName = fileName;
- FullPath = fullPath;
- LineNumber = lineNumber;
- WordIndex = wordIndex;
- }
- }
-}
diff --git a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrences.cs b/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrences.cs
deleted file mode 100644
index a6388ab54..000000000
--- a/MediaBrowser.Tests/ConsistencyTests/TextIndexing/WordOccurrences.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System.Collections.Generic;
-
-namespace MediaBrowser.Tests.ConsistencyTests.TextIndexing
-{
- public class WordOccurrences : List<WordOccurrence>
- {
- public void AddOccurrence(string fileName, string fullPath, int lineNumber, int wordIndex)
- {
- this.Add(new WordOccurrence(fileName, fullPath, lineNumber, wordIndex));
- }
-
- }
-}
diff --git a/MediaBrowser.Tests/M3uParserTest.cs b/MediaBrowser.Tests/M3uParserTest.cs
deleted file mode 100644
index 583f5f5f0..000000000
--- a/MediaBrowser.Tests/M3uParserTest.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Cryptography;
-using Emby.Server.Implementations.LiveTv.TunerHosts;
-using MediaBrowser.Common.Extensions;
-using Microsoft.Extensions.Logging;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace MediaBrowser.Tests
-{
- [TestClass]
- public class M3uParserTest
- {
- [TestMethod]
- public void TestFormat1()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString("#EXTINF:0,84. VOX Schweiz\nhttp://mystream", "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.AreEqual("VOX Schweiz", result[0].Name);
- Assert.AreEqual("84", result[0].Number);
- }
- [TestMethod]
- public void TestFormat2()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var input = "#EXTINF:-1 tvg-id=\"\" tvg-name=\"ABC News 04\" tvg-logo=\"\" group-title=\"ABC Group\",ABC News 04";
- input += "\n";
- input += "http://mystream";
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString(input, "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.AreEqual("ABC News 04", result[0].Name);
- Assert.IsNull(result[0].Number);
- }
-
- [TestMethod]
- public void TestFormat3()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString("#EXTINF:0, 3.2 - Movies!\nhttp://mystream", "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.AreEqual("Movies!", result[0].Name);
- Assert.AreEqual("3.2", result[0].Number);
- }
-
- [TestMethod]
- public void TestFormat4()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString("#EXTINF:0 tvg-id=\"abckabclosangeles.path.to\" tvg-logo=\"path.to / channel_logos / abckabclosangeles.png\", ABC KABC Los Angeles\nhttp://mystream", "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.IsNull(result[0].Number);
- Assert.AreEqual("ABC KABC Los Angeles", result[0].Name);
- }
-
- [TestMethod]
- public void TestFormat5()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString("#EXTINF:-1 channel-id=\"2101\" tvg-id=\"I69387.json.schedulesdirect.org\" group-title=\"Entertainment\",BBC 1 HD\nhttp://mystream", "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.AreEqual("BBC 1 HD", result[0].Name);
- Assert.AreEqual("2101", result[0].Number);
- }
-
- [TestMethod]
- public void TestFormat6()
- {
- BaseExtensions.CryptographyProvider = new CryptographyProvider();
-
- var result = new M3uParser(new NullLogger(), null, null, null).ParseString("#EXTINF:-1 tvg-id=\"2101\" group-title=\"Entertainment\",BBC 1 HD\nhttp://mystream", "-", "-");
- Assert.AreEqual(1, result.Count);
-
- Assert.AreEqual("BBC 1 HD", result[0].Name);
- Assert.AreEqual("2101", result[0].Number);
- }
- }
-}
diff --git a/MediaBrowser.Tests/MediaBrowser.Tests.csproj b/MediaBrowser.Tests/MediaBrowser.Tests.csproj
deleted file mode 100644
index 6415d4211..000000000
--- a/MediaBrowser.Tests/MediaBrowser.Tests.csproj
+++ /dev/null
@@ -1,139 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build"
- xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProjectGuid>{E22BFD35-0FCD-4A85-978A-C22DCD73A081}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>MediaBrowser.Tests</RootNamespace>
- <AssemblyName>MediaBrowser.Tests</AssemblyName>
- <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
- <FileAlignment>512</FileAlignment>
- <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
- <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
- <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
- <IsCodedUITest>False</IsCodedUITest>
- <TestProjectType>UnitTest</TestProjectType>
- <TargetFrameworkProfile />
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
- <OutputPath>bin\Debug\</OutputPath>
- <DefineConstants>DEBUG;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <DocumentationFile>bin\Debug\MediaBrowser.Tests.XML</DocumentationFile>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>none</DebugType>
- <Optimize>true</Optimize>
- <OutputPath>bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="Emby.Server.MediaEncoding">
- <HintPath>..\ThirdParty\emby\Emby.Server.MediaEncoding.dll</HintPath>
- </Reference>
- <Reference Include="System" />
- <Reference Include="System.XML" />
- </ItemGroup>
- <Choose>
- <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
- </ItemGroup>
- </When>
- <Otherwise>
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
- </ItemGroup>
- </Otherwise>
- </Choose>
- <ItemGroup>
- <Compile Include="ConsistencyTests\StringUsageReporter.cs" />
- <Compile Include="ConsistencyTests\TextIndexing\IndexBuilder.cs" />
- <Compile Include="ConsistencyTests\TextIndexing\WordIndex.cs" />
- <Compile Include="ConsistencyTests\TextIndexing\WordOccurrence.cs" />
- <Compile Include="ConsistencyTests\TextIndexing\WordOccurrences.cs" />
- <Compile Include="M3uParserTest.cs" />
- <Compile Include="MediaEncoding\Subtitles\AssParserTests.cs" />
- <Compile Include="MediaEncoding\Subtitles\SrtParserTests.cs" />
- <Compile Include="MediaEncoding\Subtitles\VttWriterTest.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj">
- <Project>{e383961b-9356-4d5d-8233-9a1079d03055}</Project>
- <Name>Emby.Server.Implementations</Name>
- </ProjectReference>
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj">
- <Project>{9142eefa-7570-41e1-bfcc-468bb571af2f}</Project>
- <Name>MediaBrowser.Common</Name>
- </ProjectReference>
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj">
- <Project>{17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2}</Project>
- <Name>MediaBrowser.Controller</Name>
- </ProjectReference>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj">
- <Project>{7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}</Project>
- <Name>MediaBrowser.Model</Name>
- </ProjectReference>
- <ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj">
- <Project>{442B5058-DCAF-4263-BB6A-F21E31120A1B}</Project>
- <Name>MediaBrowser.Providers</Name>
- </ProjectReference>
- <ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj">
- <Project>{23499896-b135-4527-8574-c26e926ea99e}</Project>
- <Name>MediaBrowser.XbmcMetadata</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
- <None Include="app.config" />
- <None Include="MediaEncoding\Subtitles\TestSubtitles\data.ass" />
- <None Include="MediaEncoding\Subtitles\TestSubtitles\data2.ass" />
- <None Include="MediaEncoding\Subtitles\TestSubtitles\expected.vtt" />
- <None Include="MediaEncoding\Subtitles\TestSubtitles\unit.srt" />
- </ItemGroup>
- <ItemGroup>
- <ContentWithTargetPath Include="ConsistencyTests\Resources\StringCheck.xslt">
- <CopyToOutputDirectory>Always</CopyToOutputDirectory>
- <TargetPath>StringCheck.xslt</TargetPath>
- </ContentWithTargetPath>
- <None Include="ConsistencyTests\Resources\SampleTransformed.htm" />
- <None Include="ConsistencyTests\Resources\StringCheckSample.xml" />
- </ItemGroup>
- <Choose>
- <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
- <ItemGroup>
- <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <Private>False</Private>
- </Reference>
- </ItemGroup>
- </When>
- </Choose>
- <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
- Other similar extension points exist, see Microsoft.Common.targets.
- <Target Name="BeforeBuild">
- </Target>
- <Target Name="AfterBuild">
- </Target>
- -->
-</Project>
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/AssParserTests.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/AssParserTests.cs
deleted file mode 100644
index b69faab11..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/AssParserTests.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using System.Text;
-using MediaBrowser.MediaEncoding.Subtitles;
-using MediaBrowser.Model.MediaInfo;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using Emby.Server.MediaEncoding.Subtitles;
-
-namespace MediaBrowser.Tests.MediaEncoding.Subtitles {
-
- [TestClass]
- public class AssParserTests {
-
- [TestMethod]
- public void TestParse() {
-
- var expectedSubs =
- new SubtitleTrackInfo {
- TrackEvents = new SubtitleTrackEvent[] {
- new SubtitleTrackEvent {
- Id = "1",
- StartPositionTicks = 24000000,
- EndPositionTicks = 72000000,
- Text =
- "Senator, we're "+ParserValues.NewLine+"making our final "+ParserValues.NewLine+"approach into Coruscant."
- },
- new SubtitleTrackEvent {
- Id = "2",
- StartPositionTicks = 97100000,
- EndPositionTicks = 133900000,
- Text =
- "Very good, Lieutenant."
- },
- new SubtitleTrackEvent {
- Id = "3",
- StartPositionTicks = 150400000,
- EndPositionTicks = 180400000,
- Text = "It's "+ParserValues.NewLine+"a "+ParserValues.NewLine+"trap!"
- }
- }
- };
-
- var sut = new AssParser();
-
- var stream = File.OpenRead(@"MediaEncoding\Subtitles\TestSubtitles\data.ass");
-
- var result = sut.Parse(stream, CancellationToken.None);
-
- Assert.IsNotNull(result);
- Assert.AreEqual(expectedSubs.TrackEvents.Length,result.TrackEvents.Length);
- for (int i = 0; i < expectedSubs.TrackEvents.Length; i++)
- {
- Assert.AreEqual(expectedSubs.TrackEvents[i].Id, result.TrackEvents[i].Id);
- Assert.AreEqual(expectedSubs.TrackEvents[i].StartPositionTicks, result.TrackEvents[i].StartPositionTicks);
- Assert.AreEqual(expectedSubs.TrackEvents[i].EndPositionTicks, result.TrackEvents[i].EndPositionTicks);
- Assert.AreEqual(expectedSubs.TrackEvents[i].Text, result.TrackEvents[i].Text);
- }
-
- }
-
- [TestMethod]
- public void TestParse2()
- {
-
- var sut = new AssParser();
-
- var stream = File.OpenRead(@"MediaEncoding\Subtitles\TestSubtitles\data2.ass");
-
- var result = sut.Parse(stream, CancellationToken.None);
-
- Assert.IsNotNull(result);
-
- using (var ms = new MemoryStream())
- {
- var writer = new SrtWriter();
- writer.Write(result, ms, CancellationToken.None);
-
- ms.Position = 0;
- var text = Encoding.UTF8.GetString(ms.ToArray());
- var b = text;
- }
-
- }
- }
-}
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs
deleted file mode 100644
index aae96b382..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using Emby.Server.MediaEncoding.Subtitles;
-using Microsoft.Extensions.Logging;
-using MediaBrowser.Model.MediaInfo;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace MediaBrowser.Tests.MediaEncoding.Subtitles
-{
-
- [TestClass]
- public class SrtParserTests
- {
-
- [TestMethod]
- public void TestParse()
- {
-
- var expectedSubs =
- new SubtitleTrackInfo
- {
- TrackEvents = new SubtitleTrackEvent[] {
- new SubtitleTrackEvent {
- Id = "1",
- StartPositionTicks = 24000000,
- EndPositionTicks = 52000000,
- Text =
- "[Background Music Playing]"
- },
- new SubtitleTrackEvent {
- Id = "2",
- StartPositionTicks = 157120000,
- EndPositionTicks = 173990000,
- Text =
- "Oh my god, Watch out!"+ParserValues.NewLine+"It's coming!!"
- },
- new SubtitleTrackEvent {
- Id = "3",
- StartPositionTicks = 257120000,
- EndPositionTicks = 303990000,
- Text = "[Bird noises]"
- },
- new SubtitleTrackEvent {
- Id = "4",
- StartPositionTicks = 310000000,
- EndPositionTicks = 319990000,
- Text =
- "This text is <font color=\"red\">RED</font> and has not been positioned."
- },
- new SubtitleTrackEvent {
- Id = "5",
- StartPositionTicks = 320000000,
- EndPositionTicks = 329990000,
- Text =
- "This is a"+ParserValues.NewLine+"new line, as is"+ParserValues.NewLine+"this"
- },
- new SubtitleTrackEvent {
- Id = "6",
- StartPositionTicks = 330000000,
- EndPositionTicks = 339990000,
- Text =
- "This contains nested <b>bold, <i>italic, <u>underline</u> and <s>strike-through</s></u></i></b> HTML tags"
- },
- new SubtitleTrackEvent {
- Id = "7",
- StartPositionTicks = 340000000,
- EndPositionTicks = 349990000,
- Text =
- "Unclosed but <b>supported HTML tags are left in, SSA italics aren't"
- },
- new SubtitleTrackEvent {
- Id = "8",
- StartPositionTicks = 350000000,
- EndPositionTicks = 359990000,
- Text =
- "&lt;ggg&gt;Unsupported&lt;/ggg&gt; HTML tags are escaped and left in, even if &lt;hhh&gt;not closed."
- },
- new SubtitleTrackEvent {
- Id = "9",
- StartPositionTicks = 360000000,
- EndPositionTicks = 369990000,
- Text =
- "Multiple SSA tags are stripped"
- },
- new SubtitleTrackEvent {
- Id = "10",
- StartPositionTicks = 370000000,
- EndPositionTicks = 379990000,
- Text =
- "Greater than (&lt;) and less than (&gt;) are shown"
- }
- }
- };
-
- var sut = new SrtParser(new NullLogger());
-
- var stream = File.OpenRead(@"MediaEncoding\Subtitles\TestSubtitles\unit.srt");
-
- var result = sut.Parse(stream, CancellationToken.None);
-
- Assert.IsNotNull(result);
- Assert.AreEqual(expectedSubs.TrackEvents.Length, result.TrackEvents.Length);
- for (int i = 0; i < expectedSubs.TrackEvents.Length; i++)
- {
- Assert.AreEqual(expectedSubs.TrackEvents[i].Id, result.TrackEvents[i].Id);
- Assert.AreEqual(expectedSubs.TrackEvents[i].StartPositionTicks, result.TrackEvents[i].StartPositionTicks);
- Assert.AreEqual(expectedSubs.TrackEvents[i].EndPositionTicks, result.TrackEvents[i].EndPositionTicks);
- Assert.AreEqual(expectedSubs.TrackEvents[i].Text, result.TrackEvents[i].Text);
- }
-
- }
- }
-}
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data.ass b/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data.ass
deleted file mode 100644
index 3114a844a..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data.ass
+++ /dev/null
@@ -1,23 +0,0 @@
-[Script Info]
-Title: Testing subtitles for the SSA Format
-
-[V4 Styles]
-Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
-Style: Default,Arial,20,65535,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0
-Style: Titre_episode,Akbar,140,15724527,65535,65535,986895,-1,0,1,1,0,3,30,30,30,0,0
-Style: Wolf main,Wolf_Rain,56,15724527,15724527,15724527,4144959,0,0,1,1,2,2,5,5,30,0,0
-
-
-
-[Events]
-Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
-Dialogue: 0,0:00:02.40,0:00:07.20,Default,,0000,0000,0000,,Senator, {\kf89}we're \Nmaking our final \napproach into Coruscant.
-Dialogue: 0,0:00:09.71,0:00:13.39,Default,,0000,0000,0000,,{\pos(400,570)}Very good, Lieutenant.
-Dialogue: 0,0:00:15.04,0:00:18.04,Default,,0000,0000,0000,,It's \Na \ntrap!
-
-
-[Pictures]
-This section will be ignored
-
-[Fonts]
-This section will be ignored \ No newline at end of file
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data2.ass b/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data2.ass
deleted file mode 100644
index 98585f636..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/data2.ass
+++ /dev/null
@@ -1,391 +0,0 @@
-[Script Info]
-Title: English (US)
-ScriptType: v4.00+
-WrapStyle: 0
-PlayResX: 640
-PlayResY: 360
-
-[V4+ Styles]
-Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
-Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,0010,0010,0010,1
-Style: para-main,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,0020,0020,0015,0
-Style: para-main-top,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H001E0200,&H00000000,0,0,0,0,100,100,0,0,1,2,1,8,0010,0010,0017,0
-Style: para-internal,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H001E0200,&H00000000,0,1,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-internal-top,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H001E0200,&H00000000,0,1,0,0,100,100,0,0,1,2,1,8,0010,0010,0017,0
-Style: para-overlap,Trebuchet MS,25,&H00BAFCF3,&H000000FF,&H001E0200,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-narration,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H00000137,&H00000137,0,1,0,0,100,100,0,0,1,2,1,8,0020,0020,0015,0
-Style: para-internaloverlap,Trebuchet MS,25,&H00BAFCF3,&H000000FF,&H001E0200,&H00000000,0,1,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-flashback,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H004D0000,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-flashbackinternal,Trebuchet MS,25,&H00FFFFFF,&H000000FF,&H004D0701,&H00000000,0,1,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-flashbackoverlap,Trebuchet MS,25,&H00BAFCF3,&H000000FF,&H004D0701,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,0010,0010,0015,0
-Style: para-title,arial,35,&H001F00C1,&H000000FF,&H00050058,&H00000137,1,0,0,0,100,100,0,0,1,1,0,7,0050,0020,0050,0
-Style: para-title-maxim,Times New Roman,25,&H00FFF3F3,&H000000FF,&H003B264A,&H00000137,0,0,0,0,100,100,0,0,1,1,0,4,0050,0020,0050,0
-Style: para-ep-title,Times New Roman,25,&H00F8FDFF,&H000000FF,&H005C5C5C,&H00273024,0,0,0,0,100,100,0,0,1,0,1,1,0056,0058,0060,0
-Style: para-next-ep,Trebuchet MS,22,&H009A8D94,&H000000FF,&H00000000,&H00273024,0,0,0,0,100,100,0,0,1,0,0,8,0000,0000,0135,0
-Style: tiny sign,Times New Roman,14,&H002C2F23,&H000000FF,&H00060600,&H00000000,1,0,0,0,100,100,0,0,1,2,0,8,0140,0010,0015,1
-Style: writing1,Verdana,16,&H00292C29,&H000000FF,&H002D241D,&H00000000,0,0,0,0,100,100,0,0,1,0,0,8,0080,0010,0025,1
-Style: writing2,Verdana,12,&H00292C29,&H000000FF,&H002D241D,&H00000000,0,0,0,0,100,100,0,0,1,0,0,3,0080,0090,0085,1
-Style: writing3,Verdana,16,&H00292C29,&H000000FF,&H002D241D,&H00000000,0,0,0,0,100,100,0,0,1,0,0,8,0010,0130,0080,1
-Style: recept,Trebuchet MS,12,&H00AFB2AC,&H000000FF,&H004C4D49,&H00000000,1,0,0,0,100,100,0,0,1,4,0,8,0010,0010,0020,1
-Style: food,Times New Roman,23,&H0056886C,&H000000FF,&H0083E5F9,&H00000000,1,0,0,0,100,100,0,0,1,4,0,7,0020,0010,0070,1
-Style: pad,Times New Roman,12,&H00445F6A,&H000000FF,&H007D6A4F,&H00000000,0,0,0,0,100,100,0,25,1,0,0,2,0040,0010,0105,1
-Style: chalk,Times New Roman,24,&H007B867F,&H000000FF,&H008EE3E9,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0050,0050,0055,1
-Style: fortune,Times New Roman,18,&H00153249,&H000000FF,&H00727FA4,&H00000000,0,0,0,0,100,100,0,0,1,4,0,7,0060,0010,0030,1
-Style: fortune2,Times New Roman,24,&H003277AB,&H000000FF,&H00D0FFFF,&H00000000,1,0,0,0,100,100,0,0,1,4,0,8,0080,0000,0020,1
-
-[Events]
-Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
-
-Dialogue: 0,0:00:06.89,0:00:10.62,para-main,M,0000,0000,0000,,I'm sorry to sour the mood, Shinichi, but...
-Dialogue: 0,0:00:10.62,0:00:11.80,para-main,S,0000,0000,0000,,No way.
-Dialogue: 0,0:00:11.80,0:00:12.49,para-main,S,0000,0000,0000,,You must be kidding.
-Dialogue: 0,0:00:13.00,0:00:14.61,para-main,M,0000,0000,0000,,We need to start running right now.
-Dialogue: 0,0:00:15.20,0:00:16.74,para-main,S,0000,0000,0000,,Are you sure it's him?
-Dialogue: 0,0:00:17.25,0:00:20.06,para-main,M,0000,0000,0000,,These wavelengths are too \Npowerful to come from some lackey.
-Dialogue: 0,0:00:20.06,0:00:22.81,para-main,M,0000,0000,0000,,And given the speed of his \Napproach, I'd say he's in a car.
-Dialogue: 0,0:00:23.49,0:00:25.29,para-main,M,0000,0000,0000,,Take a right at that corner.
-Dialogue: 0,0:00:25.76,0:00:26.72,para-main,S,0000,0000,0000,,Shit!
-Dialogue: 0,0:00:26.72,0:00:28.43,para-main,S,0000,0000,0000,,Now I'm a thief.
-Dialogue: 0,0:00:28.43,0:00:30.17,para-main,M,0000,0000,0000,,Is this the time to whine about it?
-Dialogue: 0,0:00:31.10,0:00:34.25,para-main,S,0000,0000,0000,,When'd you learn to drive, anyway?
-Dialogue: 0,0:00:34.70,0:00:37.80,para-main,M,0000,0000,0000,,I mastered Japanese in \Na single day, you know.
-Dialogue: 0,0:00:39.72,0:00:41.46,para-main,S,0000,0000,0000,,Migi, I have a favor to ask.
-Dialogue: 0,0:00:42.68,0:00:45.23,para-main,S,0000,0000,0000,,Please go somewhere with \Nas few people as possible.
-Dialogue: 0,0:00:45.23,0:00:47.94,para-main,S,0000,0000,0000,,If we fight him in a city, \Nmany people will die.
-Dialogue: 0,0:00:49.63,0:00:50.94,para-main,M,0000,0000,0000,,Very well.
-Dialogue: 0,0:00:52.20,0:00:55.81,para-main,M,0000,0000,0000,,I've thought of something \Nthat's worth a gamble.
-Dialogue: 0,0:01:35.53,0:01:42.66,para-title,,0000,0000,0000,,Parasyte
-Dialogue: 0,0:01:37.74,0:01:42.66,para-title-maxim,,0000,0000,0000,,{\fad(2000,1)}The Maxim
-Dialogue: 0,0:02:42.01,0:02:46.54,para-ep-title,Sign 0245,0000,0000,0000,,{\fad(350,500)\an3}Quiescence and Awakening
-Dialogue: 0,0:02:48.95,0:02:49.69,para-main,S,0000,0000,0000,,Well?
-Dialogue: 0,0:02:50.56,0:02:51.55,para-main,M,0000,0000,0000,,It didn't work.
-Dialogue: 0,0:02:52.05,0:02:52.99,para-main,M,0000,0000,0000,,He's alive.
-Dialogue: 0,0:02:53.89,0:02:55.55,para-main,M,0000,0000,0000,,He's tough.
-Dialogue: 0,0:02:56.76,0:02:57.48,para-main,M,0000,0000,0000,,Let's go.
-Dialogue: 0,0:02:58.00,0:02:58.82,para-main,S,0000,0000,0000,,Go where?
-Dialogue: 0,0:03:00.01,0:03:00.87,para-main,M,0000,0000,0000,,Let's run.
-Dialogue: 0,0:03:11.71,0:03:13.13,para-main,M,0000,0000,0000,,All right, stop.
-Dialogue: 0,0:03:16.59,0:03:18.09,para-main,S,0000,0000,0000,,Why are we stopping?
-Dialogue: 0,0:03:18.09,0:03:20.38,para-main,S,0000,0000,0000,,We can't afford to waste time here!
-Dialogue: 0,0:03:20.38,0:03:21.47,para-main,M,0000,0000,0000,,Calm down.
-Dialogue: 0,0:03:21.47,0:03:23.97,para-main,M,0000,0000,0000,,Let's strategize until he shows up.
-Dialogue: 0,0:03:24.33,0:03:25.85,para-main,S,0000,0000,0000,,Strategize?!
-Dialogue: 0,0:03:25.85,0:03:28.21,para-main,S,0000,0000,0000,,We might be minutes away \Nfrom being chopped up!
-Dialogue: 0,0:03:28.21,0:03:29.24,para-main,M,0000,0000,0000,,Shinichi.
-Dialogue: 0,0:03:29.24,0:03:30.69,para-main,M,0000,0000,0000,,I understand how you feel.
-Dialogue: 0,0:03:30.69,0:03:32.48,para-main,M,0000,0000,0000,,Anyone would fear death.
-Dialogue: 0,0:03:32.83,0:03:34.48,para-main,M,0000,0000,0000,,I'm afraid, as well.
-Dialogue: 0,0:03:34.95,0:03:37.51,para-main,M,0000,0000,0000,,However, this is our moment of truth!
-Dialogue: 0,0:03:39.54,0:03:43.25,para-main,M,0000,0000,0000,,You have a strength normal \Nhumans don't have.
-Dialogue: 0,0:03:43.25,0:03:46.23,para-main,M,0000,0000,0000,,You can be calm, no matter \Nwhat the circumstance.
-Dialogue: 0,0:03:46.85,0:03:48.89,para-main,M,0000,0000,0000,,Now, put your hand on your chest
-Dialogue: 0,0:03:48.89,0:03:51.02,para-main,M,0000,0000,0000,,and breathe deeply like you always do.
-Dialogue: 0,0:04:00.56,0:04:02.84,para-main,M,0000,0000,0000,,Good, well done.
-Dialogue: 0,0:04:03.54,0:04:04.44,para-main,M,0000,0000,0000,,Listen.
-Dialogue: 0,0:04:04.44,0:04:08.50,para-main,M,0000,0000,0000,,When it comes to ability, \NGotou surpasses us in every way.
-Dialogue: 0,0:04:08.93,0:04:12.85,para-main,M,0000,0000,0000,,By simple calculations, our odds of \Nvictory might be zero percent.
-Dialogue: 0,0:04:12.85,0:04:16.22,para-main,M,0000,0000,0000,,But that just means we should approach \Nthis from a different angle.
-Dialogue: 0,0:04:16.79,0:04:20.18,para-main,M,0000,0000,0000,,If we can't win even by working together,
-Dialogue: 0,0:04:20.85,0:04:23.36,para-main,M,0000,0000,0000,,maybe we should try {\i1}not{\i0} working together.
-Dialogue: 0,0:04:23.63,0:04:24.24,para-main,S,0000,0000,0000,,What?
-Dialogue: 0,0:04:25.01,0:04:28.12,para-main,M,0000,0000,0000,,In war, what matters is \Nopportunity, not numbers.
-Dialogue: 0,0:04:28.12,0:04:29.27,para-main,S,0000,0000,0000,,Opportunity?
-Dialogue: 0,0:04:29.86,0:04:33.16,para-main,M,0000,0000,0000,,In your pocket is a lighter I found in the car.
-Dialogue: 0,0:04:42.79,0:04:44.01,para-main,Goto,0000,0000,0000,,They're above...
-Dialogue: 0,0:04:44.31,0:04:48.01,para-main,Goto,0000,0000,0000,,They've spread out among \Nthe tree branches to hide.
-Dialogue: 0,0:04:48.29,0:04:49.89,para-main,Goto,0000,0000,0000,,How unoriginal.
-Dialogue: 0,0:04:50.90,0:04:52.68,para-flashbackinternal,M,0000,0000,0000,,This will be a race against time.
-Dialogue: 0,0:04:53.27,0:04:57.40,para-flashbackinternal,M,0000,0000,0000,,To a parasite, the body is our lifeline \Nas well as our greatest weakness.
-Dialogue: 0,0:04:58.18,0:05:01.39,para-flashbackinternal,M,0000,0000,0000,,My cells that have dispersed in your body
-Dialogue: 0,0:05:01.39,0:05:05.21,para-flashbackinternal,M,0000,0000,0000,,have been completely integrated, \Nand are altered,
-Dialogue: 0,0:05:05.21,0:05:06.91,para-flashbackinternal,M,0000,0000,0000,,so Gotou can't detect them.
-Dialogue: 0,0:05:07.43,0:05:09.72,para-flashbackinternal,M,0000,0000,0000,,He will come straight for me
-Dialogue: 0,0:05:09.72,0:05:11.66,para-flashbackinternal,M,0000,0000,0000,,without noticing your presence.
-Dialogue: 0,0:05:12.17,0:05:15.50,para-flashbackinternal,M,0000,0000,0000,,If there is a protracted fight, \NI will shrivel up and die.
-Dialogue: 0,0:05:15.50,0:05:17.67,para-flashbackinternal,M,0000,0000,0000,,This is an extremely reckless strategy.
-Dialogue: 0,0:05:17.67,0:05:21.67,para-flashbackinternal,M,0000,0000,0000,,But that means even Gotou is \Nunlikely to anticipate our strategy.
-Dialogue: 0,0:05:39.54,0:05:43.16,para-internal,Gotou,0000,0000,0000,,What, no counterattack?
-Dialogue: 0,0:05:46.10,0:05:48.69,para-internal,Gotou,0000,0000,0000,,Where is the human boy?
-Dialogue: 0,0:05:48.69,0:05:51.95,para-internal,Gotou,0000,0000,0000,,If only I can find and destroy the body, I'll win.
-Dialogue: 0,0:05:53.56,0:05:54.58,para-flashbackinternal,M,0000,0000,0000,,His body
-Dialogue: 0,0:05:55.03,0:05:58.58,para-flashbackinternal,M,0000,0000,0000,,is protected by semi-hardened parasite cells.
-Dialogue: 0,0:05:59.12,0:06:02.59,para-flashbackinternal,M,0000,0000,0000,,It's unlikely that his entire body is armored,
-Dialogue: 0,0:06:02.59,0:06:06.28,para-flashbackinternal,M,0000,0000,0000,,but there's no time to find where \Nthe chinks are in his armor.
-Dialogue: 0,0:06:06.28,0:06:08.95,para-flashbackinternal,M,0000,0000,0000,,The part least likely to be armored
-Dialogue: 0,0:06:08.95,0:06:12.47,para-flashbackinternal,M,0000,0000,0000,,and thus most suitable as a target...
-Dialogue: 0,0:06:13.05,0:06:14.12,para-flashbackinternal,M,0000,0000,0000,,is his head.
-Dialogue: 0,0:06:16.41,0:06:19.93,para-flashbackinternal,M,0000,0000,0000,,Unifying the multiple parasites \Nin his torso and limbs must
-Dialogue: 0,0:06:19.93,0:06:22.95,para-flashbackinternal,M,0000,0000,0000,,require a tremendous amount of energy.
-Dialogue: 0,0:06:22.95,0:06:25.96,para-flashbackinternal,M,0000,0000,0000,,Thus, the "head" has its hands \Nfull acting as the control tower.
-Dialogue: 0,0:06:26.53,0:06:29.63,para-flashbackinternal,M,0000,0000,0000,,If we lop the head off,
-Dialogue: 0,0:06:29.63,0:06:31.93,para-flashbackinternal,M,0000,0000,0000,,unity will be lost along with his armor,
-Dialogue: 0,0:06:31.93,0:06:34.12,para-flashbackinternal,M,0000,0000,0000,,which should allow us to destroy his body.
-Dialogue: 0,0:06:34.76,0:06:36.28,para-internal,S,0000,0000,0000,,Any time now, Migi!
-Dialogue: 0,0:06:36.74,0:06:39.12,para-internal,S,0000,0000,0000,,If you don't hurry, you'll...
-Dialogue: 0,0:06:39.64,0:06:41.33,para-internal,M,0000,0000,0000,,I will only have one chance!
-Dialogue: 0,0:06:41.33,0:06:45.88,para-internal,M,0000,0000,0000,,If I am to decapitate Gotou when his \Npower and speed far surpasses my own...
-Dialogue: 0,0:06:47.02,0:06:48.51,para-internal,M,0000,0000,0000,,What is this?
-Dialogue: 0,0:06:48.51,0:06:50.73,para-internal,M,0000,0000,0000,,My consciousness is already fading...
-Dialogue: 0,0:06:51.25,0:06:52.74,para-internal,M,0000,0000,0000,,I must hurry!
-Dialogue: 0,0:06:52.74,0:06:54.89,para-internal,M,0000,0000,0000,,But the angle of attack is still poor.
-Dialogue: 0,0:06:55.51,0:06:57.09,para-main,Gotou,0000,0000,0000,,Hey! Listen up!
-Dialogue: 0,0:06:57.09,0:06:59.12,para-main,Gotou,0000,0000,0000,,Are you that scared of me?!
-Dialogue: 0,0:06:59.12,0:07:03.19,para-main,Gotou,0000,0000,0000,,Spreading out in all directions \Nisn't much of a camouflage!
-Dialogue: 0,0:07:03.51,0:07:06.69,para-main,Gotou,0000,0000,0000,,Use your brains to fight, not run!
-Dialogue: 0,0:07:06.69,0:07:08.11,para-main,M,0000,0000,0000,,Now! Do it!
-Dialogue: 0,0:07:08.62,0:07:09.49,para-internal,S,0000,0000,0000,,Was that my voice?
-Dialogue: 0,0:07:09.88,0:07:11.24,para-main,G,0000,0000,0000,,There!
-Dialogue: 0,0:07:17.41,0:07:20.29,para-flashbackinternal,M,0000,0000,0000,,The surface cells will instinctively disengage
-Dialogue: 0,0:07:20.29,0:07:22.58,para-flashbackinternal,M,0000,0000,0000,,from Gotou's command upon exposure to fire,
-Dialogue: 0,0:07:22.92,0:07:23.72,para-flashbackinternal,M,0000,0000,0000,,and as a result...
-Dialogue: 0,0:07:28.94,0:07:29.67,para-internal,M,0000,0000,0000,,Damn!
-Dialogue: 0,0:07:29.67,0:07:30.38,para-internal,M,0000,0000,0000,,Not deep enough!
-Dialogue: 0,0:07:34.70,0:07:35.55,para-main,M,0000,0000,0000,,Did we fail?
-Dialogue: 0,0:07:35.55,0:07:36.84,para-main,S,0000,0000,0000,,Migi!
-Dialogue: 0,0:07:36.84,0:07:38.08,para-main,M,0000,0000,0000,,Stay back, Shinichi!
-Dialogue: 0,0:07:39.79,0:07:40.77,para-main,M,0000,0000,0000,,We failed!
-Dialogue: 0,0:07:41.31,0:07:43.43,para-main,Gotou,0000,0000,0000,,Well, this is a surprise.
-Dialogue: 0,0:07:43.43,0:07:44.31,para-main,Gotou,0000,0000,0000,,Well done.
-Dialogue: 0,0:07:44.52,0:07:45.52,para-main,M,0000,0000,0000,,Run! Now!
-Dialogue: 0,0:07:45.52,0:07:46.33,para-main,S,0000,0000,0000,,But...
-Dialogue: 0,0:07:46.33,0:07:47.36,para-main,M,0000,0000,0000,,Don't come any closer!
-Dialogue: 0,0:07:47.61,0:07:48.98,para-main,M,0000,0000,0000,,We don't both need to die!
-Dialogue: 0,0:07:52.43,0:07:54.11,para-main,S,0000,0000,0000,,But, Migi...
-Dialogue: 0,0:07:59.77,0:08:00.83,para-main,M,0000,0000,0000,,What are you doing?!
-Dialogue: 0,0:08:00.83,0:08:01.62,para-main,M,0000,0000,0000,,Hurry up and go!
-Dialogue: 0,0:08:10.76,0:08:12.38,para-internal,M,0000,0000,0000,,Goodbye, Shinichi.
-Dialogue: 0,0:08:13.06,0:08:15.48,para-internal,M,0000,0000,0000,,This is farewell, Shinichi.
-Dialogue: 0,0:08:16.52,0:08:21.88,para-internal,M,0000,0000,0000,,I'm glad I didn't take over \Nyour brain when we first met.
-Dialogue: 0,0:08:22.86,0:08:27.24,para-internal,M,0000,0000,0000,,Thanks to that, we made many \Ngood memories as friends...
-Dialogue: 0,0:08:33.43,0:08:35.48,para-internal,M,0000,0000,0000,,I'm fading...
-Dialogue: 0,0:08:35.91,0:08:37.32,para-internal,M,0000,0000,0000,,I feel oddly sleepy,
-Dialogue: 0,0:08:38.47,0:08:42.85,para-internal,M,0000,0000,0000,,yet it's all eclipsed by the \Nfeeling that I'm so alone.
-Dialogue: 0,0:08:45.37,0:08:46.44,para-internal,M,0000,0000,0000,,So this...
-Dialogue: 0,0:08:47.45,0:08:48.37,para-internal,M,0000,0000,0000,,is death...
-Dialogue: 0,0:09:48.98,0:09:49.91,para-main,Mitsu,0000,0000,0000,,Who's there?!
-Dialogue: 0,0:09:53.90,0:09:55.91,para-main,S,0000,0000,0000,,Oh, sorry.
-Dialogue: 0,0:09:55.91,0:09:57.35,para-main,Mitsu,0000,0000,0000,,A... A burglar?!
-Dialogue: 0,0:09:57.35,0:09:58.41,para-main,S,0000,0000,0000,,No!
-Dialogue: 0,0:09:59.03,0:10:00.66,para-main,S,0000,0000,0000,,I'm not... But...
-Dialogue: 0,0:10:00.66,0:10:02.82,para-main,S,0000,0000,0000,,Sure. You can call me that.
-Dialogue: 0,0:10:02.82,0:10:03.70,para-main,Mitsu,0000,0000,0000,,Huh?
-Dialogue: 0,0:10:04.52,0:10:07.71,para-main,S,0000,0000,0000,,I did try to drink some water \Nwithout permission, after all.
-Dialogue: 0,0:10:07.71,0:10:09.55,para-main,Mitsu,0000,0000,0000,,I see.
-Dialogue: 0,0:10:09.55,0:10:11.97,para-main,Mitsu,0000,0000,0000,,Water isn't free, either.
-Dialogue: 0,0:10:12.55,0:10:14.19,para-main,S,0000,0000,0000,,S-Sorry...
-Dialogue: 0,0:10:14.82,0:10:16.39,para-main,S,0000,0000,0000,,Well, uh...
-Dialogue: 0,0:10:16.87,0:10:18.19,para-main,S,0000,0000,0000,,I should go.
-Dialogue: 0,0:10:18.19,0:10:19.75,para-main,S,0000,0000,0000,,I'm sorry for the trouble.
-Dialogue: 0,0:10:23.35,0:10:24.99,para-main,Mitsu,0000,0000,0000,,Hang on a second.
-Dialogue: 0,0:10:24.99,0:10:25.87,para-main,S,0000,0000,0000,,Yes?
-Dialogue: 0,0:10:25.87,0:10:27.39,para-main,Mitsu,0000,0000,0000,,You're hurt.
-Dialogue: 0,0:10:27.67,0:10:28.31,para-main,S,0000,0000,0000,,Oh...
-Dialogue: 0,0:10:28.88,0:10:30.54,para-main,S,0000,0000,0000,,Well, no, uh...
-Dialogue: 0,0:10:30.54,0:10:33.07,para-main,Mitsu,0000,0000,0000,,No, your head.
-Dialogue: 0,0:10:33.07,0:10:36.03,para-main,Mitsu,0000,0000,0000,,You lost your right arm a long \Ntime ago, from the looks of it.
-Dialogue: 0,0:10:37.39,0:10:38.44,para-main,S,0000,0000,0000,,I'm fine.
-Dialogue: 0,0:10:38.93,0:10:40.77,para-main,S,0000,0000,0000,,I think the bleeding's already stopped.
-Dialogue: 0,0:10:40.77,0:10:43.40,para-main,Mitsu,0000,0000,0000,,Just come in and let me take a look.
-Dialogue: 0,0:10:43.81,0:10:44.41,para-main,S,0000,0000,0000,,But...
-Dialogue: 0,0:10:44.41,0:10:45.74,para-main,Mitsu,0000,0000,0000,,Hurry up!
-Dialogue: 0,0:10:45.74,0:10:48.69,para-main,Mitsu,0000,0000,0000,,A burglar wouldn't be this polite.
-Dialogue: 0,0:10:48.69,0:10:51.29,para-main,Mitsu,0000,0000,0000,,Besides, you look like you've been crying.
-Dialogue: 0,0:10:54.13,0:10:57.55,para-main,Mitsu,0000,0000,0000,,I worked in retail for a long time.
-Dialogue: 0,0:10:57.55,0:11:01.89,para-main,Mitsu,0000,0000,0000,,I can tell a lot about a person from just one look.
-Dialogue: 0,0:11:03.49,0:11:09.26,para-main,Mitsu,0000,0000,0000,,This injury wasn't from a fair fight, \Nwas it? You were bullied.
-Dialogue: 0,0:11:09.26,0:11:10.39,para-main,S,0000,0000,0000,,Uh...
-Dialogue: 0,0:11:11.56,0:11:14.15,para-main,Mitsu,0000,0000,0000,,The cut's pretty deep.
-Dialogue: 0,0:11:14.70,0:11:18.14,para-main,Mitsu,0000,0000,0000,,Some people in this world do terrible things.
-Dialogue: 0,0:11:30.20,0:11:33.22,para-main,S,0000,0000,0000,,I didn't expect so much kindness \Nfrom a complete stranger.
-Dialogue: 0,0:11:34.82,0:11:36.92,para-main,S,0000,0000,0000,,Thank you for everything.
-Dialogue: 0,0:11:37.35,0:11:39.76,para-main,Mitsu,0000,0000,0000,,Stay the night.
-Dialogue: 0,0:11:39.76,0:11:40.48,para-main,S,0000,0000,0000,,What?
-Dialogue: 0,0:11:40.48,0:11:42.34,para-main,S,0000,0000,0000,,I couldn't possibly...
-Dialogue: 0,0:11:43.32,0:11:45.73,para-main,Mitsu,0000,0000,0000,,Where do you expect to go this late at night?
-Dialogue: 0,0:11:45.73,0:11:48.05,para-main,Mitsu,0000,0000,0000,,There are no hotels around here!
-Dialogue: 0,0:11:48.79,0:11:52.32,para-main,S,0000,0000,0000,,Um, do you live here by yourself, Granny?
-Dialogue: 0,0:11:52.74,0:11:54.89,para-main,Mitsu,0000,0000,0000,,I don't have any grandchildren your age.
-Dialogue: 0,0:11:55.41,0:11:56.91,para-main,S,0000,0000,0000,,Erm, Auntie?
-Dialogue: 0,0:11:56.91,0:11:58.40,para-main,Mitsu,0000,0000,0000,,I don't have any nephews, either.
-Dialogue: 0,0:11:59.38,0:12:01.40,para-main,Mitsu,0000,0000,0000,,My name is Mitsuyo.
-Dialogue: 0,0:12:02.65,0:12:03.80,para-main,S,0000,0000,0000,,I'm sorry.
-Dialogue: 0,0:12:04.31,0:12:06.91,para-main,S,0000,0000,0000,,I'm Izumi Shinichi.
-Dialogue: 0,0:12:07.72,0:12:09.24,para-main,Mitsu,0000,0000,0000,,Shinichi, eh?
-Dialogue: 0,0:12:09.86,0:12:11.22,para-main,Mitsu,0000,0000,0000,,Shin-chan, then.
-Dialogue: 0,0:12:13.27,0:12:16.75,para-main,Mitsu,0000,0000,0000,,Sorry for making you help with the shopping.
-Dialogue: 0,0:12:16.75,0:12:18.20,para-main,S,0000,0000,0000,,Oh, no problem.
-Dialogue: 0,0:12:18.75,0:12:20.10,para-main,S,0000,0000,0000,,I can at least do that much.
-Dialogue: 0,0:12:22.76,0:12:26.09,para-main,Mitsu,0000,0000,0000,,Let's just say you're my nephew.
-Dialogue: 0,0:12:26.09,0:12:26.84,para-main,S,0000,0000,0000,,Nephew?
-Dialogue: 0,0:12:26.84,0:12:29.39,para-main,Mitsu,0000,0000,0000,,Strange things have been \Nhappening around here lately.
-Dialogue: 0,0:12:29.39,0:12:31.48,para-main,Mitsu,0000,0000,0000,,They're suspicious of outsiders.
-Dialogue: 0,0:12:31.87,0:12:33.17,para-main,S,0000,0000,0000,,Strange things?
-Dialogue: 0,0:12:36.59,0:12:38.12,para-main,Mitsu,0000,0000,0000,,This is what I was talking about.
-Dialogue: 0,0:12:38.98,0:12:43.54,para-main,Mitsu,0000,0000,0000,,Someone keeps dumping truckloads \Nof garbage without permission.
-Dialogue: 0,0:12:43.54,0:12:48.49,para-main,Mitsu,0000,0000,0000,,One time, it caught fire and nearly \Nset the entire mountain ablaze.
-Dialogue: 0,0:12:48.85,0:12:52.74,para-main,Mitsu,0000,0000,0000,,I know they say big cities \Nare running out of landfills,
-Dialogue: 0,0:12:52.74,0:12:55.11,para-main,Mitsu,0000,0000,0000,,but this is a bit much, don't you think?
-Dialogue: 0,0:12:55.11,0:12:55.93,para-main,S,0000,0000,0000,,Yes...
-Dialogue: 0,0:12:56.36,0:12:58.27,para-main,Mitsu,0000,0000,0000,,Those of us who live around here
-Dialogue: 0,0:12:58.27,0:13:00.84,para-main,Mitsu,0000,0000,0000,,have been keeping watch day and night,
-Dialogue: 0,0:13:01.16,0:13:03.50,para-main,Mitsu,0000,0000,0000,,but they're no-shows when we do keep watch
-Dialogue: 0,0:13:03.50,0:13:06.49,para-main,Mitsu,0000,0000,0000,,and come the one day we sleep.
-Dialogue: 0,0:13:06.49,0:13:09.38,para-internal,S,0000,0000,0000,,Mitsuyo-san had a sharp tongue,
-Dialogue: 0,0:13:09.38,0:13:10.86,para-internal,S,0000,0000,0000,,but she was kindhearted.
-Dialogue: 0,0:13:11.78,0:13:14.98,para-internal,S,0000,0000,0000,,Whenever I tried to thank her and leave,
-Dialogue: 0,0:13:14.98,0:13:18.73,para-internal,S,0000,0000,0000,,she'd stop me with a machine gun \Nbarrage of conversation.
-Dialogue: 0,0:13:19.43,0:13:20.86,para-internal,S,0000,0000,0000,,With Migi gone,
-Dialogue: 0,0:13:20.86,0:13:23.55,para-internal,S,0000,0000,0000,,I had no idea what to do next.
-Dialogue: 0,0:13:23.55,0:13:27.06,para-internal,S,0000,0000,0000,,I ended up staying several days.
-Dialogue: 0,0:13:28.68,0:13:31.83,para-internal,S,0000,0000,0000,,But I can't impose on her forever.
-Dialogue: 0,0:13:32.36,0:13:36.87,para-internal,S,0000,0000,0000,,I should go home tomorrow \Nand tell Dad everything.
-Dialogue: 0,0:13:37.52,0:13:39.30,para-internal,S,0000,0000,0000,,About why I lost my right arm...
-Dialogue: 0,0:13:39.93,0:13:42.39,para-internal,S,0000,0000,0000,,About how I had a friend named Migi...
-Dialogue: 0,0:13:43.11,0:13:45.54,para-internal,S,0000,0000,0000,,About the day Migi first showed up in my life.
-Dialogue: 0,0:13:46.48,0:13:48.39,para-internal,S,0000,0000,0000,,About the days we spent together.
-Dialogue: 0,0:13:49.08,0:13:52.73,para-internal,S,0000,0000,0000,,And about how great a guy he was.
-Dialogue: 0,0:13:53.94,0:13:55.77,para-internal,S,0000,0000,0000,,To save my life, he...
-Dialogue: 0,0:13:55.77,0:13:58.14,para-internal,S,0000,0000,0000,,His intelligence, his courage...
-Dialogue: 0,0:13:58.87,0:14:01.43,para-internal,S,0000,0000,0000,,I can't even hope to come \Nclose to him in any way.
-Dialogue: 0,0:14:03.01,0:14:06.65,para-internal,S,0000,0000,0000,,He is a true hero!
-Dialogue: 0,0:14:11.44,0:14:12.87,para-internal,S,0000,0000,0000,,Where am I?
-Dialogue: 0,0:14:12.87,0:14:15.31,para-internal,S,0000,0000,0000,,I think I've been here before.
-Dialogue: 0,0:14:16.02,0:14:17.22,para-internal,S,0000,0000,0000,,What's that?
-Dialogue: 0,0:14:17.67,0:14:19.70,para-internal,S,0000,0000,0000,,Uh, who're you?
-Dialogue: 0,0:14:19.70,0:14:20.63,para-internal,M,0000,0000,0000,,What is it?
-Dialogue: 0,0:14:20.63,0:14:22.21,para-internal,M,0000,0000,0000,,Are you looking for something?
-Dialogue: 0,0:14:22.21,0:14:24.08,para-internal,S,0000,0000,0000,,Looking?
-Dialogue: 0,0:14:24.08,0:14:26.42,para-internal,S,0000,0000,0000,,Yeah, I'm looking for a friend.
-Dialogue: 0,0:14:26.42,0:14:27.75,para-internal,M,0000,0000,0000,,A friend?
-Dialogue: 0,0:14:28.17,0:14:30.27,para-internal,M,0000,0000,0000,,What does this friend look like?
-Dialogue: 0,0:14:30.27,0:14:31.09,para-internal,S,0000,0000,0000,,Look like?
-Dialogue: 0,0:14:31.72,0:14:34.12,para-internal,S,0000,0000,0000,,I don't really remember.
-Dialogue: 0,0:14:34.12,0:14:35.43,para-internal,M,0000,0000,0000,,Then I can't help you.
-Dialogue: 0,0:14:35.43,0:14:37.58,para-internal,S,0000,0000,0000,,Hey, wait.
-Dialogue: 0,0:14:37.58,0:14:39.22,para-internal,S,0000,0000,0000,,I think he looked like you...
-Dialogue: 0,0:14:39.76,0:14:41.81,para-internal,S,0000,0000,0000,,Right! I remember now!
-Dialogue: 0,0:14:41.81,0:14:42.95,para-internal,S,0000,0000,0000,,He...
-Dialogue: 0,0:14:42.95,0:14:44.86,para-internal,S,0000,0000,0000,,He died.
-Dialogue: 0,0:14:44.86,0:14:46.83,para-internal,M,0000,0000,0000,,What? He's dead?
-Dialogue: 0,0:14:46.83,0:14:47.69,para-internal,S,0000,0000,0000,,Yeah...
-Dialogue: 0,0:14:48.28,0:14:51.43,para-internal,M,0000,0000,0000,,No, he's alive.
-Dialogue: 0,0:14:51.43,0:14:52.07,para-internal,S,0000,0000,0000,,What?!
-Dialogue: 0,0:14:52.16,0:14:53.97,para-internal,M,0000,0000,0000,,I can tell.
-Dialogue: 0,0:14:53.97,0:14:56.60,para-internal,M,0000,0000,0000,,I actually know his name, too.
-Dialogue: 0,0:14:56.60,0:14:58.55,para-internal,S,0000,0000,0000,,His... name?
-Dialogue: 0,0:14:58.55,0:15:00.30,para-internal,S,0000,0000,0000,,His name...
-Dialogue: 0,0:15:01.27,0:15:02.26,para-main,S,0000,0000,0000,,Migi?!
-Dialogue: 0,0:15:07.49,0:15:08.26,para-main,S,0000,0000,0000,,Huh?!
-Dialogue: 0,0:15:09.76,0:15:10.46,para-main,S,0000,0000,0000,,M...
-Dialogue: 0,0:15:10.88,0:15:11.64,para-main,S,0000,0000,0000,,Migi!
-Dialogue: 0,0:15:12.60,0:15:14.76,para-internal,S,0000,0000,0000,,Some of his cells are still here!
-Dialogue: 0,0:15:15.68,0:15:17.37,para-main,S,0000,0000,0000,,Hey! It's me!
-Dialogue: 0,0:15:17.37,0:15:18.50,para-main,S,0000,0000,0000,,Do you recognize me?!
-Dialogue: 0,0:15:18.50,0:15:20.85,para-main,Mitsu,0000,0000,0000,,Keep it down.
-Dialogue: 0,0:15:21.30,0:15:23.62,para-main,Mitsu,0000,0000,0000,,Go back to sleep.
-Dialogue: 0,0:15:28.12,0:15:29.25,para-internal,S,0000,0000,0000,,It won't work.
-Dialogue: 0,0:15:29.74,0:15:31.75,para-internal,S,0000,0000,0000,,Even if he can make a small eye,
-Dialogue: 0,0:15:31.75,0:15:34.21,para-internal,S,0000,0000,0000,,it's not enough to be capable \Nof thought or speech.
-Dialogue: 0,0:15:36.08,0:15:36.93,para-internal,S,0000,0000,0000,,Migi...
-Dialogue: 0,0:15:38.42,0:15:39.24,para-internal,S,0000,0000,0000,,Migi!
-Dialogue: 0,0:15:54.23,0:15:55.45,para-main,Mitsu,0000,0000,0000,,I see.
-Dialogue: 0,0:15:55.45,0:15:57.42,para-main,Mitsu,0000,0000,0000,,I guess I don't have a choice.
-Dialogue: 0,0:15:57.42,0:16:00.75,para-main,Mitsu,0000,0000,0000,,I can't keep you here forever.
-Dialogue: 0,0:16:00.75,0:16:03.48,para-main,S,0000,0000,0000,,I don't know how I can ever repay you.
-Dialogue: 0,0:16:08.17,0:16:09.58,para-main,Mitsu,0000,0000,0000,,What's the matter?
-Dialogue: 0,0:16:09.58,0:16:11.49,para-main,Mitsu,0000,0000,0000,,Why're you here so early in the morning?
-Dialogue: 0,0:16:11.49,0:16:13.00,para-main,Taoka,0000,0000,0000,,Hey, you!
-Dialogue: 0,0:16:13.00,0:16:15.28,para-main,Taoka,0000,0000,0000,,Are you really Mitsuyo-san's nephew?
-Dialogue: 0,0:16:15.89,0:16:18.16,para-main,Mitsu,0000,0000,0000,,What does it matter?
-Dialogue: 0,0:16:18.16,0:16:20.54,para-main,Mitsu,0000,0000,0000,,He's about to leave.
-Dialogue: 0,0:16:20.54,0:16:22.05,para-main,Taoka,0000,0000,0000,,Not so fast.
-Dialogue: 0,0:16:22.05,0:16:24.79,para-main,Taoka,0000,0000,0000,,There are way too many strange \Nthings happening lately.
-Dialogue: 0,0:16:24.79,0:16:26.70,para-main,Taoka,0000,0000,0000,,The illegal trash dumping,
-Dialogue: 0,0:16:26.70,0:16:29.05,para-main,Taoka,0000,0000,0000,,the car crash between two \Ndriver-less vehicles,
-Dialogue: 0,0:16:30.29,0:16:32.30,para-main,Taoka,0000,0000,0000,,and now, murder.
-Dialogue: 0,0:16:32.65,0:16:33.88,para-main,Mitsu,0000,0000,0000,,What?!
-Dialogue: 0,0:16:34.09,0:16:37.24,para-main,Taoka,0000,0000,0000,,Isn't it always outsiders who commit crimes?
-Dialogue: 0,0:16:37.24,0:16:38.85,para-main,Taoka,0000,0000,0000,,Outsiders like him?
-Dialogue: 0,0:16:41.62,0:16:45.50,para-main,Nakano,0000,0000,0000,,I told you, that thing was \Nbeyond being an outsider.
-Dialogue: 0,0:16:45.50,0:16:47.74,para-main,Mitsu,0000,0000,0000,,He's been with me the entire time—
-Dialogue: 0,0:16:47.15,0:16:49.19,para-overlap,Nakano,0000,0000,0000,,It wasn't human!
-Dialogue: 0,0:16:49.59,0:16:51.40,para-main,Nakano,0000,0000,0000,,I wasn't just seeing things!
-Dialogue: 0,0:16:51.40,0:16:53.24,para-main,Nakano,0000,0000,0000,,It was at least three meters tall!
-Dialogue: 0,0:16:53.78,0:16:54.45,para-main,Nakano,0000,0000,0000,,And its legs!
-Dialogue: 0,0:16:54.45,0:16:56.70,para-main,Nakano,0000,0000,0000,,Yeah, it had four front legs alone!
-Dialogue: 0,0:16:56.98,0:16:59.49,para-main,Nakano,0000,0000,0000,,It had more than three eyes, too!
-Dialogue: 0,0:17:00.45,0:17:01.79,para-internal,S,0000,0000,0000,,It's Gotou...
-Dialogue: 0,0:17:01.79,0:17:03.20,para-internal,S,0000,0000,0000,,It has to be!
-Dialogue: 0,0:17:03.20,0:17:06.23,para-main,Nakano,0000,0000,0000,,Yeah, laugh at me all you want.
-Dialogue: 0,0:17:06.23,0:17:09.75,para-main,Nakano,0000,0000,0000,,But see this blood? It's all Kitayama's!
-Dialogue: 0,0:17:10.19,0:17:14.85,para-main,Nakano,0000,0000,0000,,Kitayama was killed and eaten \Nby a monster right close by!
-Dialogue: 0,0:17:19.80,0:17:22.29,para-main,Det,0000,0000,0000,,So it happened around here?
-Dialogue: 0,0:17:22.29,0:17:24.43,para-main,Nakano,0000,0000,0000,,Th-That's right.
-Dialogue: 0,0:17:29.90,0:17:31.64,para-main,Naitou,0000,0000,0000,,This is horrible.
-Dialogue: 0,0:17:31.64,0:17:34.65,para-main,Cop,0000,0000,0000,,Wait, something similar's happened before...
-Dialogue: 0,0:17:35.46,0:17:37.08,para-main,Det,0000,0000,0000,,The Mincemeat Murders?
-Dialogue: 0,0:17:38.54,0:17:40.10,para-main,Mitsu,0000,0000,0000,,I see.
-Dialogue: 0,0:17:40.10,0:17:42.04,para-main,Mitsu,0000,0000,0000,,Okay, got it.
-Dialogue: 0,0:17:46.32,0:17:49.76,para-main,Mitsu,0000,0000,0000,,A bunch of hunters are going \Nto get together tomorrow,
-Dialogue: 0,0:17:49.76,0:17:53.05,para-main,Mitsu,0000,0000,0000,,so they should be able to take \Ndown this "monster" then.
-Dialogue: 0,0:17:55.04,0:17:58.12,para-main,S,0000,0000,0000,,Hunting rifles won't be \Nenough to take him down.
-Dialogue: 0,0:17:58.12,0:17:58.90,para-main,Mitsu,0000,0000,0000,,Huh?
-Dialogue: 0,0:17:58.90,0:18:00.05,para-main,Mitsu,0000,0000,0000,,"Him"?
-Dialogue: 0,0:18:00.73,0:18:03.31,para-main,Mitsu,0000,0000,0000,,You know the monster?
-Dialogue: 0,0:18:04.05,0:18:06.09,para-main,S,0000,0000,0000,,He's here because he's after me.
-Dialogue: 0,0:18:06.57,0:18:08.01,para-main,S,0000,0000,0000,,To kill me.
-Dialogue: 0,0:18:08.42,0:18:09.39,para-main,Mitsu,0000,0000,0000,,Huh?
-Dialogue: 0,0:18:09.39,0:18:10.94,para-main,Mitsu,0000,0000,0000,,Stop talking nonsense.
-Dialogue: 0,0:18:11.26,0:18:13.24,para-main,S,0000,0000,0000,,This is my fault!
-Dialogue: 0,0:18:13.24,0:18:14.73,para-main,S,0000,0000,0000,,I brought him here!
-Dialogue: 0,0:18:14.73,0:18:16.36,para-main,S,0000,0000,0000,,And someone was killed!
-Dialogue: 0,0:18:17.15,0:18:20.18,para-main,S,0000,0000,0000,,Many more will die tomorrow \Nif I don't do something!
-Dialogue: 0,0:18:21.02,0:18:22.41,para-main,Mitsu,0000,0000,0000,,Shin-chan...
-Dialogue: 0,0:18:23.25,0:18:24.87,para-main,S,0000,0000,0000,,I just wanted to keep myself alive.
-Dialogue: 0,0:18:25.38,0:18:26.85,para-main,S,0000,0000,0000,,Whatever it took.
-Dialogue: 0,0:18:27.54,0:18:30.15,para-main,S,0000,0000,0000,,Friends have died for me, too.
-Dialogue: 0,0:18:30.71,0:18:35.20,para-main,S,0000,0000,0000,,But I can't just keep running away on my own.
-Dialogue: 0,0:18:36.07,0:18:37.43,para-main,Mitsu,0000,0000,0000,,Why not?
-Dialogue: 0,0:18:41.97,0:18:43.90,para-main,Mitsu,0000,0000,0000,,Why not live?
-Dialogue: 0,0:18:43.90,0:18:45.81,para-main,Mitsu,0000,0000,0000,,Why not run?
-Dialogue: 0,0:18:45.81,0:18:48.98,para-main,Mitsu,0000,0000,0000,,Run if it's only to save your own life.
-Dialogue: 0,0:18:49.27,0:18:51.68,para-main,Mitsu,0000,0000,0000,,It's nothing to be ashamed of.
-Dialogue: 0,0:18:52.39,0:18:57.15,para-main,S,0000,0000,0000,,Mitsuyo-san, I haven't done \Neverything I can just yet!
-Dialogue: 0,0:18:57.80,0:19:00.79,para-main,S,0000,0000,0000,,I have to make use of my life \Nbefore a group of people
-Dialogue: 0,0:19:00.79,0:19:03.28,para-main,S,0000,0000,0000,,come face-to-face with \Nthat monster tomorrow!
-Dialogue: 0,0:19:04.33,0:19:05.22,para-main,Mitsu,0000,0000,0000,,You idiot!
-Dialogue: 0,0:19:05.22,0:19:06.45,para-main,Mitsu,0000,0000,0000,,Cut the bullshit!
-Dialogue: 0,0:19:06.45,0:19:08.99,para-main,Mitsu,0000,0000,0000,,Make use of your life?
-Dialogue: 0,0:19:08.99,0:19:10.96,para-main,Mitsu,0000,0000,0000,,How dare you speak so \Nlightly of your own life?!
-Dialogue: 0,0:19:11.33,0:19:13.14,para-main,Mitsu,0000,0000,0000,,Who do you think you are?!
-Dialogue: 0,0:19:13.14,0:19:14.88,para-main,Mitsu,0000,0000,0000,,Use your life?
-Dialogue: 0,0:19:14.88,0:19:16.40,para-main,Mitsu,0000,0000,0000,,Don't make me laugh!
-Dialogue: 0,0:19:16.40,0:19:19.47,para-main,Mitsu,0000,0000,0000,,What does a snot-nosed brat \Nlike you expect to do?!
-Dialogue: 0,0:19:24.99,0:19:27.65,para-main,Mitsu,0000,0000,0000,,Look, I don't know your story,
-Dialogue: 0,0:19:27.65,0:19:31.42,para-main,Mitsu,0000,0000,0000,,but you should just let adults \Nhandle this sort of thing.
-Dialogue: 0,0:19:40.56,0:19:42.61,para-main,Mitsu,0000,0000,0000,,You're still leaving?
-Dialogue: 0,0:19:43.78,0:19:48.70,para-main,Mitsu,0000,0000,0000,,Don't you have someone \Nin your life you care about?
-Dialogue: 0,0:19:48.70,0:19:50.98,para-main,Mitsu,0000,0000,0000,,Even if it's a stranger,
-Dialogue: 0,0:19:50.98,0:19:53.08,para-main,Mitsu,0000,0000,0000,,once I come to know them,
-Dialogue: 0,0:19:53.08,0:19:54.66,para-main,Mitsu,0000,0000,0000,,I can't just abandon them.
-Dialogue: 0,0:19:54.66,0:19:57.20,para-main,Mitsu,0000,0000,0000,,That's what it means to be human.
-Dialogue: 0,0:19:57.20,0:19:58.73,para-main,Mitsu,0000,0000,0000,,But you...
-Dialogue: 0,0:20:00.87,0:20:05.52,para-main,Mitsu,0000,0000,0000,,I don't know how much time you have left,
-Dialogue: 0,0:20:05.52,0:20:11.89,para-main,Mitsu,0000,0000,0000,,but give some thought to as many things, \Nas many ideas, as you can come up with.
-Dialogue: 0,0:20:12.80,0:20:16.47,para-main,Mitsu,0000,0000,0000,,If you throw everything away, that's the end.
-Dialogue: 0,0:20:17.05,0:20:20.10,para-main,Mitsu,0000,0000,0000,,Don't give up, no matter what,
-Dialogue: 0,0:20:20.10,0:20:21.78,para-main,Mitsu,0000,0000,0000,,and be flexible.
-Dialogue: 0,0:20:31.45,0:20:32.36,para-main,Mitsu,0000,0000,0000,,Wait.
-Dialogue: 0,0:20:32.90,0:20:35.81,para-main,Mitsu,0000,0000,0000,,Isn't there something useful \Nyou can take with you?
-Dialogue: 0,0:20:35.81,0:20:37.09,para-main,Mitsu,0000,0000,0000,,Like a weapon?
-Dialogue: 0,0:20:41.43,0:20:42.84,para-main,S,0000,0000,0000,,This, then.
-Dialogue: 0,0:20:42.84,0:20:46.42,para-main,Mitsu,0000,0000,0000,,What, that? It's all rusty.
-Dialogue: 0,0:20:46.42,0:20:48.60,para-main,Mitsu,0000,0000,0000,,But I guess it's better than nothing.
-Dialogue: 0,0:21:02.69,0:21:03.88,para-internal,Mitsu,0000,0000,0000,,Dear...
-Dialogue: 0,0:21:04.62,0:21:06.32,para-internal,Mitsu,0000,0000,0000,,Please keep him safe.
-Dialogue: 0,0:21:15.06,0:21:19.51,para-internal,S,0000,0000,0000,,If Gotou's adopted a totally \Ndifferent human appearance,
-Dialogue: 0,0:21:19.51,0:21:21.48,para-internal,S,0000,0000,0000,,there'll be no way for me to recognize him.
-Dialogue: 0,0:21:21.96,0:21:25.53,para-internal,S,0000,0000,0000,,But I'll cross that bridge when I come to it!
-Dialogue: 0,0:22:46.84,0:22:51.03,para-next-ep,Sign 2248,0000,0000,0000,,{\fad(700,1)}Life and Oath
-Dialogue: 0,0:22:46.93,0:22:47.67,para-main,S,0000,0000,0000,,Next time:
-Dialogue: 0,0:22:48.64,0:22:49.81,para-main,S,0000,0000,0000,,"Life and Oath."
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/expected.vtt b/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/expected.vtt
deleted file mode 100644
index b6352e7b5..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/expected.vtt
+++ /dev/null
@@ -1,32 +0,0 @@
-WEBVTT
-
-00:00:02.400 --> 00:00:05.200
-[Background Music Playing]
-
-00:00:15.712 --> 00:00:17.399
-Oh my god, Watch out!<br />It's coming!!
-
-00:00:25.712 --> 00:00:30.399
-[Bird noises]
-
-00:00:31.000 --> 00:00:31.999
-This text is <font color="red">RED</font> and has not been positioned.
-
-00:00:32.000 --> 00:00:32.999
-This is a<br />new line, as is<br />this
-
-00:00:33.000 --> 00:00:33.999
-This contains nested <b>bold, <i>italic, <u>underline</u> and <s>strike-through</s></u></i></b> HTML tags
-
-00:00:34.000 --> 00:00:34.999
-Unclosed but <b>supported HTML tags are left in, SSA italics aren't
-
-00:00:35.000 --> 00:00:35.999
-&lt;ggg&gt;Unsupported&lt;/ggg&gt; HTML tags are escaped and left in, even if &lt;hhh&gt;not closed.
-
-00:00:36.000 --> 00:00:36.999
-Multiple SSA tags are stripped
-
-00:00:37.000 --> 00:00:37.999
-Greater than (&lt;) and less than (&gt;) are shown
-
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/unit.srt b/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/unit.srt
deleted file mode 100644
index 1ce811bcb..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/TestSubtitles/unit.srt
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-1
-00:00:02.400 --> 00:00:05.200
-[Background Music Playing]
-
-2
-00:00:15,712 --> 00:00:17,399 X1:000 X2:000 Y1:050 Y2:100
-Oh my god, Watch out!
-It's coming!!
-
-3
-00:00:25,712 --> 00:00:30,399
-[Bird noises]
-
-4
-00:00:31,000 --> 00:00:31,999
-This text is <font color="red">RED</font> and has not been {\pos(142,120)}positioned.
-
-5
-00:00:32,000 --> 00:00:32,999
-This is a\nnew line, as is\Nthis
-
-6
-00:00:33,000 --> 00:00:33,999
-This contains nested <b>bold, <i>italic, <u>underline</u> and <s>strike-through</s></u></i></b> HTML tags
-
-7
-00:00:34,000 --> 00:00:34,999
-Unclosed but <b>supported HTML tags are left in, {\i1} SSA italics aren't
-
-8
-00:00:35,000 --> 00:00:35,999
-<ggg>Unsupported</ggg> HTML tags are escaped and left in, even if <hhh>not closed.
-
-9
-00:00:36,000 --> 00:00:36,999
-Multiple {\bord-3.7\clip(1,m 50 0 b 100 0 100 100 50 100 b 0 100 0 0 50 0)\pos(142,120)\t(0,500,\fscx100\fscy100)\b1\c&H000000&}SSA tags are stripped
-
-10
-00:00:37,000 --> 00:00:37,999
-Greater than (<) and less than (>) are shown
-
-
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/VttWriterTest.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/VttWriterTest.cs
deleted file mode 100644
index 2d25bcb14..000000000
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/VttWriterTest.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using Emby.Server.MediaEncoding.Subtitles;
-using MediaBrowser.Model.MediaInfo;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace MediaBrowser.Tests.MediaEncoding.Subtitles {
-
- [TestClass]
- public class VttWriterTest {
- [TestMethod]
- public void TestWrite() {
- var infoSubs =
- new SubtitleTrackInfo
- {
- TrackEvents = new SubtitleTrackEvent[] {
- new SubtitleTrackEvent {
- Id = "1",
- StartPositionTicks = 24000000,
- EndPositionTicks = 52000000,
- Text =
- "[Background Music Playing]"
- },
- new SubtitleTrackEvent {
- Id = "2",
- StartPositionTicks = 157120000,
- EndPositionTicks = 173990000,
- Text =
- "Oh my god, Watch out!<br />It's coming!!"
- },
- new SubtitleTrackEvent {
- Id = "3",
- StartPositionTicks = 257120000,
- EndPositionTicks = 303990000,
- Text = "[Bird noises]"
- },
- new SubtitleTrackEvent {
- Id = "4",
- StartPositionTicks = 310000000,
- EndPositionTicks = 319990000,
- Text =
- "This text is <font color=\"red\">RED</font> and has not been positioned."
- },
- new SubtitleTrackEvent {
- Id = "5",
- StartPositionTicks = 320000000,
- EndPositionTicks = 329990000,
- Text =
- "This is a<br />new line, as is<br />this"
- },
- new SubtitleTrackEvent {
- Id = "6",
- StartPositionTicks = 330000000,
- EndPositionTicks = 339990000,
- Text =
- "This contains nested <b>bold, <i>italic, <u>underline</u> and <s>strike-through</s></u></i></b> HTML tags"
- },
- new SubtitleTrackEvent {
- Id = "7",
- StartPositionTicks = 340000000,
- EndPositionTicks = 349990000,
- Text =
- "Unclosed but <b>supported HTML tags are left in, SSA italics aren't"
- },
- new SubtitleTrackEvent {
- Id = "8",
- StartPositionTicks = 350000000,
- EndPositionTicks = 359990000,
- Text =
- "&lt;ggg&gt;Unsupported&lt;/ggg&gt; HTML tags are escaped and left in, even if &lt;hhh&gt;not closed."
- },
- new SubtitleTrackEvent {
- Id = "9",
- StartPositionTicks = 360000000,
- EndPositionTicks = 369990000,
- Text =
- "Multiple SSA tags are stripped"
- },
- new SubtitleTrackEvent {
- Id = "10",
- StartPositionTicks = 370000000,
- EndPositionTicks = 379990000,
- Text =
- "Greater than (&lt;) and less than (&gt;) are shown"
- }
- }
- };
-
- var sut = new VttWriter();
-
- if(File.Exists("testVTT.vtt"))
- File.Delete("testVTT.vtt");
- using (var file = File.OpenWrite("testVTT.vtt"))
- {
- sut.Write(infoSubs, file, CancellationToken.None);
- }
-
- var result = File.ReadAllText("testVTT.vtt");
- var expectedText = File.ReadAllText(@"MediaEncoding\Subtitles\TestSubtitles\expected.vtt");
-
- Assert.AreEqual(expectedText, result);
- }
- }
-}
diff --git a/MediaBrowser.Tests/Properties/AssemblyInfo.cs b/MediaBrowser.Tests/Properties/AssemblyInfo.cs
deleted file mode 100644
index 9bc2a19f2..000000000
--- a/MediaBrowser.Tests/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MediaBrowser.Tests")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/MediaBrowser.Tests/app.config b/MediaBrowser.Tests/app.config
deleted file mode 100644
index 5c79b167f..000000000
--- a/MediaBrowser.Tests/app.config
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<configuration>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral"/>
- <bindingRedirect oldVersion="0.0.0.0-1.0.94.0" newVersion="1.0.94.0"/>
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
-<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/></startup></configuration>
diff --git a/MediaBrowser.WebDashboard/Api/ConfigurationPageInfo.cs b/MediaBrowser.WebDashboard/Api/ConfigurationPageInfo.cs
deleted file mode 100644
index b8f9e09b5..000000000
--- a/MediaBrowser.WebDashboard/Api/ConfigurationPageInfo.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Plugins;
-
-namespace MediaBrowser.WebDashboard.Api
-{
- public class ConfigurationPageInfo
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- public bool EnableInMainMenu { get; set; }
- public string MenuSection { get; set; }
- public string MenuIcon { get; set; }
-
- public string DisplayName { get; set; }
-
- /// <summary>
- /// Gets the type of the configuration page.
- /// </summary>
- /// <value>The type of the configuration page.</value>
- public ConfigurationPageType ConfigurationPageType { get; set; }
-
- /// <summary>
- /// Gets or sets the plugin id.
- /// </summary>
- /// <value>The plugin id.</value>
- public string PluginId { get; set; }
-
- public ConfigurationPageInfo(IPluginConfigurationPage page)
- {
- Name = page.Name;
-
- ConfigurationPageType = page.ConfigurationPageType;
-
- if (page.Plugin != null)
- {
- DisplayName = page.Plugin.Name;
- // Don't use "N" because it needs to match Plugin.Id
- PluginId = page.Plugin.Id.ToString();
- }
- }
-
- public ConfigurationPageInfo(IPlugin plugin, PluginPageInfo page)
- {
- Name = page.Name;
- EnableInMainMenu = page.EnableInMainMenu;
- MenuSection = page.MenuSection;
- MenuIcon = page.MenuIcon;
- DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin.Name : page.DisplayName;
-
- // Don't use "N" because it needs to match Plugin.Id
- PluginId = plugin.Id.ToString();
- }
- }
-}
diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs
deleted file mode 100644
index 531978e1d..000000000
--- a/MediaBrowser.WebDashboard/Api/DashboardService.cs
+++ /dev/null
@@ -1,448 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Plugins;
-using MediaBrowser.Model.Reflection;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.WebDashboard.Api
-{
- /// <summary>
- /// Class GetDashboardConfigurationPages
- /// </summary>
- [Route("/web/ConfigurationPages", "GET")]
- public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
- {
- /// <summary>
- /// Gets or sets the type of the page.
- /// </summary>
- /// <value>The type of the page.</value>
- public ConfigurationPageType? PageType { get; set; }
- public bool? EnableInMainMenu { get; set; }
- }
-
- /// <summary>
- /// Class GetDashboardConfigurationPage
- /// </summary>
- [Route("/web/ConfigurationPage", "GET")]
- public class GetDashboardConfigurationPage
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
- }
-
- [Route("/web/Package", "GET", IsHidden = true)]
- public class GetDashboardPackage
- {
- public string Mode { get; set; }
- }
-
- [Route("/robots.txt", "GET", IsHidden = true)]
- public class GetRobotsTxt
- {
- }
-
- /// <summary>
- /// Class GetDashboardResource
- /// </summary>
- [Route("/web/{ResourceName*}", "GET", IsHidden = true)]
- public class GetDashboardResource
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string ResourceName { get; set; }
- /// <summary>
- /// Gets or sets the V.
- /// </summary>
- /// <value>The V.</value>
- public string V { get; set; }
- }
-
- [Route("/favicon.ico", "GET", IsHidden = true)]
- public class GetFavIcon
- {
- }
-
- /// <summary>
- /// Class DashboardService
- /// </summary>
- public class DashboardService : IService, IRequiresRequest
- {
- /// <summary>
- /// Gets or sets the logger.
- /// </summary>
- /// <value>The logger.</value>
- private readonly ILogger _logger;
-
- /// <summary>
- /// Gets or sets the HTTP result factory.
- /// </summary>
- /// <value>The HTTP result factory.</value>
- private readonly IHttpResultFactory _resultFactory;
-
- /// <summary>
- /// Gets or sets the request context.
- /// </summary>
- /// <value>The request context.</value>
- public IRequest Request { get; set; }
-
- /// <summary>
- /// The _app host
- /// </summary>
- private readonly IServerApplicationHost _appHost;
-
- /// <summary>
- /// The _server configuration manager
- /// </summary>
- private readonly IServerConfigurationManager _serverConfigurationManager;
-
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IAssemblyInfo _assemblyInfo;
- private IResourceFileManager _resourceFileManager;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DashboardService" /> class.
- /// </summary>
- public DashboardService(IServerApplicationHost appHost, IResourceFileManager resourceFileManager, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, IAssemblyInfo assemblyInfo, ILogger logger, IHttpResultFactory resultFactory)
- {
- _appHost = appHost;
- _serverConfigurationManager = serverConfigurationManager;
- _fileSystem = fileSystem;
- _localization = localization;
- _jsonSerializer = jsonSerializer;
- _assemblyInfo = assemblyInfo;
- _logger = logger;
- _resultFactory = resultFactory;
- _resourceFileManager = resourceFileManager;
- }
-
- /// <summary>
- /// Gets the path for the web interface.
- /// </summary>
- /// <value>The path for the web interface.</value>
- public string DashboardUIPath
- {
- get
- {
- if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
- {
- return _serverConfigurationManager.Configuration.DashboardSourcePath;
- }
-
- return Path.Combine(_serverConfigurationManager.ApplicationPaths.ApplicationResourcesPath, "jellyfin-web", "src");
- }
- }
-
- public object Get(GetFavIcon request)
- {
- return Get(new GetDashboardResource
- {
- ResourceName = "favicon.ico"
- });
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public Task<object> Get(GetDashboardConfigurationPage request)
- {
- IPlugin plugin = null;
- Stream stream = null;
-
- var isJs = false;
- var isTemplate = false;
-
- var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
- if (page != null)
- {
- plugin = page.Plugin;
- stream = page.GetHtmlStream();
- }
-
- if (plugin == null)
- {
- var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
- if (altPage != null)
- {
- plugin = altPage.Item2;
- stream = _assemblyInfo.GetManifestResourceStream(plugin.GetType(), altPage.Item1.EmbeddedResourcePath);
-
- isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
- isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html");
- }
- }
-
- if (plugin != null && stream != null)
- {
- if (isJs)
- {
- return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream));
- }
- if (isTemplate)
- {
- return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
- }
-
- return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator(DashboardUIPath).ModifyHtml("dummy.html", stream, null, _appHost.ApplicationVersion, null));
- }
-
- throw new ResourceNotFoundException();
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public object Get(GetDashboardConfigurationPages request)
- {
- const string unavailableMessage = "The server is still loading. Please try again momentarily.";
-
- var instance = ServerEntryPoint.Instance;
-
- if (instance == null)
- {
- throw new InvalidOperationException(unavailableMessage);
- }
-
- var pages = instance.PluginConfigurationPages;
-
- if (pages == null)
- {
- throw new InvalidOperationException(unavailableMessage);
- }
-
- // Don't allow a failing plugin to fail them all
- var configPages = pages.Select(p =>
- {
-
- try
- {
- return new ConfigurationPageInfo(p);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name);
- return null;
- }
- })
- .Where(i => i != null)
- .ToList();
-
- configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
-
- if (request.PageType.HasValue)
- {
- configPages = configPages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
- }
-
- if (request.EnableInMainMenu.HasValue)
- {
- configPages = configPages.Where(p => p.EnableInMainMenu == request.EnableInMainMenu.Value).ToList();
- }
-
- return configPages;
- }
-
- private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
- {
- return _appHost.Plugins.SelectMany(GetPluginPages);
- }
-
- private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
- {
- var hasConfig = plugin as IHasWebPages;
-
- if (hasConfig == null)
- {
- return new List<Tuple<PluginPageInfo, IPlugin>>();
- }
-
- return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
- }
-
- private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
- {
- return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
- }
-
- public object Get(GetRobotsTxt request)
- {
- return Get(new GetDashboardResource
- {
- ResourceName = "robots.txt"
- });
- }
-
- /// <summary>
- /// Gets the specified request.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <returns>System.Object.</returns>
- public async Task<object> Get(GetDashboardResource request)
- {
- var path = request.ResourceName;
-
- var contentType = MimeTypes.GetMimeType(path);
- var basePath = DashboardUIPath;
-
- // Bounce them to the startup wizard if it hasn't been completed yet
- if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted &&
- Request.RawUrl.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 &&
- GetPackageCreator(basePath).IsCoreHtml(path))
- {
- // But don't redirect if an html import is being requested.
- if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
- {
- Request.Response.Redirect("index.html?start=wizard#!/wizardstart.html");
- return null;
- }
- }
-
- var localizationCulture = GetLocalizationCulture();
-
- // Don't cache if not configured to do so
- // But always cache images to simulate production
- if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
- !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
- !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
- {
- var stream = await GetResourceStream(basePath, path, localizationCulture).ConfigureAwait(false);
- return _resultFactory.GetResult(Request, stream, contentType);
- }
-
- TimeSpan? cacheDuration = null;
-
- // Cache images unconditionally - updates to image files will require new filename
- // If there's a version number in the query string we can cache this unconditionally
- if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
- {
- cacheDuration = TimeSpan.FromDays(365);
- }
-
- var cacheKey = (_appHost.ApplicationVersion + (localizationCulture ?? string.Empty) + path).GetMD5();
-
- // html gets modified on the fly
- if (contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
- {
- return await _resultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(basePath, path, localizationCulture)).ConfigureAwait(false);
- }
-
- return await _resourceFileManager.GetStaticFileResult(Request, basePath, path, contentType, cacheDuration);
- }
-
- private string GetLocalizationCulture()
- {
- return _serverConfigurationManager.Configuration.UICulture;
- }
-
- /// <summary>
- /// Gets the resource stream.
- /// </summary>
- private Task<Stream> GetResourceStream(string basePath, string virtualPath, string localizationCulture)
- {
- return GetPackageCreator(basePath)
- .GetResource(virtualPath, null, localizationCulture, _appHost.ApplicationVersion);
- }
-
- private PackageCreator GetPackageCreator(string basePath)
- {
- return new PackageCreator(basePath, _fileSystem, _logger, _serverConfigurationManager, _resourceFileManager);
- }
-
- public async Task<object> Get(GetDashboardPackage request)
- {
- var mode = request.Mode;
-
- var inputPath = string.IsNullOrWhiteSpace(mode) ?
- DashboardUIPath
- : "C:\\dev\\emby-web-mobile-master\\dist";
-
- var targetPath = !string.IsNullOrWhiteSpace(mode) ?
- inputPath
- : "C:\\dev\\emby-web-mobile\\src";
-
- var packageCreator = GetPackageCreator(inputPath);
-
- if (!string.Equals(inputPath, targetPath, StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- Directory.Delete(targetPath, true);
- }
- catch (IOException)
- {
-
- }
-
- CopyDirectory(inputPath, targetPath);
- }
-
- var appVersion = _appHost.ApplicationVersion;
-
- await DumpHtml(packageCreator, inputPath, targetPath, mode, appVersion);
-
- return "";
- }
-
- private async Task DumpHtml(PackageCreator packageCreator, string source, string destination, string mode, string appVersion)
- {
- foreach (var file in _fileSystem.GetFiles(source))
- {
- var filename = file.Name;
-
- if (!string.Equals(file.Extension, ".html", StringComparison.OrdinalIgnoreCase))
- {
- continue;
- }
-
- await DumpFile(packageCreator, filename, Path.Combine(destination, filename), mode, appVersion).ConfigureAwait(false);
- }
- }
-
- private async Task DumpFile(PackageCreator packageCreator, string resourceVirtualPath, string destinationFilePath, string mode, string appVersion)
- {
- using (var stream = await packageCreator.GetResource(resourceVirtualPath, mode, null, appVersion).ConfigureAwait(false))
- using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
- {
- await stream.CopyToAsync(fs);
- }
- }
-
- private void CopyDirectory(string source, string destination)
- {
- Directory.CreateDirectory(destination);
-
- //Now Create all of the directories
- foreach (var dirPath in _fileSystem.GetDirectories(source, true))
- Directory.CreateDirectory(dirPath.FullName.Replace(source, destination));
-
- //Copy all the files & Replaces any files with the same name
- foreach (var newPath in _fileSystem.GetFiles(source, true))
- File.Copy(newPath.FullName, newPath.FullName.Replace(source, destination), true);
- }
- }
-
-}
diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs
deleted file mode 100644
index 2d0e0e188..000000000
--- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs
+++ /dev/null
@@ -1,194 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.IO;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.WebDashboard.Api
-{
- public class PackageCreator
- {
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
- private readonly IServerConfigurationManager _config;
- private readonly string _basePath;
- private IResourceFileManager _resourceFileManager;
-
- public PackageCreator(string basePath, IFileSystem fileSystem, ILogger logger, IServerConfigurationManager config, IResourceFileManager resourceFileManager)
- {
- _fileSystem = fileSystem;
- _logger = logger;
- _config = config;
- _basePath = basePath;
- _resourceFileManager = resourceFileManager;
- }
-
- public async Task<Stream> GetResource(string virtualPath,
- string mode,
- string localizationCulture,
- string appVersion)
- {
- var resourceStream = GetRawResourceStream(virtualPath);
-
- if (resourceStream != null)
- {
- if (IsFormat(virtualPath, "html"))
- {
- if (IsCoreHtml(virtualPath))
- {
- resourceStream = await ModifyHtml(virtualPath, resourceStream, mode, appVersion, localizationCulture).ConfigureAwait(false);
- }
- }
- }
-
- return resourceStream;
- }
-
- /// <summary>
- /// Determines whether the specified path is HTML.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="format">The format.</param>
- /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
- private static bool IsFormat(string path, string format)
- {
- return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
- }
-
- public bool IsCoreHtml(string path)
- {
- if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
- {
- return false;
- }
-
- return IsFormat(path, "html");
- }
-
- /// <summary>
- /// Modifies the HTML by adding common meta tags, css and js.
- /// </summary>
- /// <returns>Task{Stream}.</returns>
- public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture)
- {
- var isMainIndexPage = string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase);
-
- using (sourceStream)
- {
- string html;
-
- using (var memoryStream = new MemoryStream())
- {
- await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
-
- var originalBytes = memoryStream.ToArray();
-
- html = Encoding.UTF8.GetString(originalBytes, 0, originalBytes.Length);
-
- if (isMainIndexPage)
- {
- if (!string.IsNullOrWhiteSpace(localizationCulture))
- {
- var lang = localizationCulture.Split('-').FirstOrDefault();
-
- html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
- }
- }
- }
-
- if (isMainIndexPage)
- {
- html = html.Replace("<head>", "<head>" + GetMetaTags(mode));
- }
-
- // Disable embedded scripts from plugins. We'll run them later once resources have loaded
- if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
- {
- html = html.Replace("<script", "<!--<script");
- html = html.Replace("</script>", "</script>-->");
- }
-
- if (isMainIndexPage)
- {
- html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
- }
-
- var bytes = Encoding.UTF8.GetBytes(html);
-
- return new MemoryStream(bytes);
- }
- }
-
- /// <summary>
- /// Gets the meta tags.
- /// </summary>
- /// <returns>System.String.</returns>
- private string GetMetaTags(string mode)
- {
- var sb = new StringBuilder();
-
- if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(mode, "android", StringComparison.OrdinalIgnoreCase))
- {
- sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem: ws: wss:;\">");
- }
-
- return sb.ToString();
- }
-
- /// <summary>
- /// Gets the common javascript.
- /// </summary>
- /// <param name="mode">The mode.</param>
- /// <param name="version">The version.</param>
- /// <returns>System.String.</returns>
- private string GetCommonJavascript(string mode, string version)
- {
- var builder = new StringBuilder();
-
- builder.Append("<script>");
- if (!string.IsNullOrWhiteSpace(mode))
- {
- builder.AppendFormat("window.appMode='{0}';", mode);
- }
-
- else
- {
- builder.AppendFormat("window.dashboardVersion='{0}';", version);
- }
-
- builder.Append("</script>");
-
- var versionString = string.IsNullOrWhiteSpace(mode) ? "?v=" + version : string.Empty;
-
- var files = new List<string>();
-
- files.Add("scripts/apploader.js" + versionString);
-
- if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
- {
- files.Insert(0, "cordova.js");
- }
-
- var tags = files.Select(s => string.Format("<script src=\"{0}\" defer></script>", s)).ToArray();
-
- builder.Append(string.Join(string.Empty, tags));
-
- return builder.ToString();
- }
-
- /// <summary>
- /// Gets the raw resource stream.
- /// </summary>
- private Stream GetRawResourceStream(string virtualPath)
- {
- return _resourceFileManager.GetResourceFileStream(_basePath, virtualPath);
- }
-
- }
-}
diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
deleted file mode 100644
index c099e77d6..000000000
--- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
+++ /dev/null
@@ -1,23 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
- <ItemGroup>
- <None Include="jellyfin-web\src\**\*.*">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </None>
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/MediaBrowser.WebDashboard/Properties/AssemblyInfo.cs b/MediaBrowser.WebDashboard/Properties/AssemblyInfo.cs
deleted file mode 100644
index 416ce4826..000000000
--- a/MediaBrowser.WebDashboard/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("MediaBrowser.WebDashboard")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/MediaBrowser.WebDashboard/ServerEntryPoint.cs b/MediaBrowser.WebDashboard/ServerEntryPoint.cs
deleted file mode 100644
index 18ed54a78..000000000
--- a/MediaBrowser.WebDashboard/ServerEntryPoint.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using MediaBrowser.Common;
-using MediaBrowser.Controller.Plugins;
-
-namespace MediaBrowser.WebDashboard
-{
- public class ServerEntryPoint : IServerEntryPoint
- {
- /// <summary>
- /// Gets the list of plugin configuration pages
- /// </summary>
- /// <value>The configuration pages.</value>
- public List<IPluginConfigurationPage> PluginConfigurationPages { get; private set; }
-
- private readonly IApplicationHost _appHost;
-
- public static ServerEntryPoint Instance { get; private set; }
-
- public ServerEntryPoint(IApplicationHost appHost)
- {
- _appHost = appHost;
- Instance = this;
- }
-
- public Task RunAsync()
- {
- PluginConfigurationPages = _appHost.GetExports<IPluginConfigurationPage>().ToList();
-
- return Task.CompletedTask;
- }
-
- public void Dispose()
- {
- }
- }
-}
diff --git a/MediaBrowser.WebDashboard/jellyfin-web b/MediaBrowser.WebDashboard/jellyfin-web
deleted file mode 160000
-Subproject b4842e325e9d7d708193b4a27060cfe4c978df5
diff --git a/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationExtension.cs b/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationExtension.cs
new file mode 100644
index 000000000..fe3bc3cd3
--- /dev/null
+++ b/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationExtension.cs
@@ -0,0 +1,15 @@
+#pragma warning disable CS1591
+
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.XbmcMetadata.Configuration
+{
+ public static class NfoConfigurationExtension
+ {
+ public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
+ {
+ return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
+ }
+ }
+}
diff --git a/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationFactory.cs b/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationFactory.cs
new file mode 100644
index 000000000..c73989e76
--- /dev/null
+++ b/MediaBrowser.XbmcMetadata/Configuration/NfoConfigurationFactory.cs
@@ -0,0 +1,24 @@
+#pragma warning disable CS1591
+
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.Configuration;
+
+namespace MediaBrowser.XbmcMetadata.Configuration
+{
+ public class NfoConfigurationFactory : IConfigurationFactory
+ {
+ /// <inheritdoc />
+ public IEnumerable<ConfigurationStore> GetConfigurations()
+ {
+ return new[]
+ {
+ new ConfigurationStore
+ {
+ ConfigurationType = typeof(XbmcMetadataOptions),
+ Key = "xbmcmetadata"
+ }
+ };
+ }
+ }
+}
diff --git a/MediaBrowser.XbmcMetadata/Configuration/NfoOptions.cs b/MediaBrowser.XbmcMetadata/Configuration/NfoOptions.cs
deleted file mode 100644
index f631439de..000000000
--- a/MediaBrowser.XbmcMetadata/Configuration/NfoOptions.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Configuration;
-
-namespace MediaBrowser.XbmcMetadata.Configuration
-{
- public class ConfigurationFactory : IConfigurationFactory
- {
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new[]
- {
- new ConfigurationStore
- {
- ConfigurationType = typeof(XbmcMetadataOptions),
- Key = "xbmcmetadata"
- }
- };
- }
- }
-
- public static class ConfigurationExtension
- {
- public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
- {
- return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
- }
- }
-}
diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs
index 992991a7e..d02aea556 100644
--- a/MediaBrowser.XbmcMetadata/EntryPoint.cs
+++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
@@ -12,31 +14,34 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata
{
- public class EntryPoint : IServerEntryPoint
+ public sealed class EntryPoint : IServerEntryPoint
{
private readonly IUserDataManager _userDataManager;
- private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<EntryPoint> _logger;
private readonly IProviderManager _providerManager;
private readonly IConfigurationManager _config;
- public EntryPoint(IUserDataManager userDataManager, ILibraryManager libraryManager, ILogger logger, IProviderManager providerManager, IConfigurationManager config)
+ public EntryPoint(
+ IUserDataManager userDataManager,
+ ILogger<EntryPoint> logger,
+ IProviderManager providerManager,
+ IConfigurationManager config)
{
_userDataManager = userDataManager;
- _libraryManager = libraryManager;
_logger = logger;
_providerManager = providerManager;
_config = config;
}
+ /// <inheritdoc />
public Task RunAsync()
{
- _userDataManager.UserDataSaved += _userDataManager_UserDataSaved;
+ _userDataManager.UserDataSaved += OnUserDataSaved;
return Task.CompletedTask;
}
- void _userDataManager_UserDataSaved(object sender, UserDataSaveEventArgs e)
+ private void OnUserDataSaved(object? sender, UserDataSaveEventArgs e)
{
if (e.SaveReason == UserDataSaveReason.PlaybackFinished || e.SaveReason == UserDataSaveReason.TogglePlayed || e.SaveReason == UserDataSaveReason.UpdateUserRating)
{
@@ -47,24 +52,15 @@ namespace MediaBrowser.XbmcMetadata
}
}
+ /// <inheritdoc />
public void Dispose()
{
- _userDataManager.UserDataSaved -= _userDataManager_UserDataSaved;
+ _userDataManager.UserDataSaved -= OnUserDataSaved;
}
private void SaveMetadataForItem(BaseItem item, ItemUpdateType updateReason)
{
- if (!item.IsFileProtocol)
- {
- return;
- }
-
- if (!item.SupportsLocalMetadata)
- {
- return;
- }
-
- if (!item.IsSaveLocalMetadataEnabled())
+ if (!item.IsFileProtocol || !item.SupportsLocalMetadata)
{
return;
}
diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
index ba29c656b..926be5a92 100644
--- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
+++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
@@ -1,5 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{23499896-B135-4527-8574-C26E926EA99E}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
@@ -10,8 +15,16 @@
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
index f20dbbb6e..9d558b6ce 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
@@ -1,20 +1,22 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
-using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Providers;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Configuration;
using MediaBrowser.XbmcMetadata.Savers;
using Microsoft.Extensions.Logging;
@@ -24,57 +26,68 @@ namespace MediaBrowser.XbmcMetadata.Parsers
public class BaseNfoParser<T>
where T : BaseItem
{
- /// <summary>
- /// The logger
- /// </summary>
- protected ILogger Logger { get; private set; }
- protected IFileSystem FileSystem { get; private set; }
- protected IProviderManager ProviderManager { get; private set; }
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IConfigurationManager _config;
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
private Dictionary<string, string> _validProviderIds;
/// <summary>
/// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
/// </summary>
- public BaseNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public BaseNfoParser(
+ ILogger logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
{
Logger = logger;
_config = config;
ProviderManager = providerManager;
- FileSystem = fileSystem;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _validProviderIds = new Dictionary<string, string>();
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
/// <summary>
- /// Fetches metadata for an item from one xml file
+ /// Gets the logger.
+ /// </summary>
+ protected ILogger Logger { get; }
+
+ protected IProviderManager ProviderManager { get; }
+
+ protected virtual bool SupportsUrlAfterClosingXmlTag => false;
+
+ /// <summary>
+ /// Fetches metadata for an item from one xml file.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="metadataFile">The metadata file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <exception cref="ArgumentNullException">
- /// </exception>
+ /// <exception cref="ArgumentNullException"><c>item</c> is <c>null</c>.</exception>
+ /// <exception cref="ArgumentException"><c>metadataFile</c> is <c>null</c> or empty.</exception>
public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
{
- if (item == null)
+ if (item.Item == null)
{
- throw new ArgumentNullException(nameof(item));
+ throw new ArgumentException("Item can't be null.", nameof(item));
}
if (string.IsNullOrEmpty(metadataFile))
{
- throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile));
+ throw new ArgumentException("The metadata filepath was empty.", nameof(metadataFile));
}
- var settings = XmlReaderSettingsFactory.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
-
- _validProviderIds = _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var idInfos = ProviderManager.GetExternalIdInfos(item.Item);
@@ -87,16 +100,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers
}
}
- //Additional Mappings
+ // Additional Mappings
_validProviderIds.Add("collectionnumber", "TmdbCollection");
_validProviderIds.Add("tmdbcolid", "TmdbCollection");
_validProviderIds.Add("imdb_id", "Imdb");
- Fetch(item, metadataFile, settings, cancellationToken);
+ Fetch(item, metadataFile, GetXmlReaderSettings(), cancellationToken);
}
- protected virtual bool SupportsUrlAfterClosingXmlTag => false;
-
/// <summary>
/// Fetches the specified item.
/// </summary>
@@ -109,155 +120,127 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!SupportsUrlAfterClosingXmlTag)
{
using (var fileStream = File.OpenRead(metadataFile))
+ using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
+ using (var reader = XmlReader.Create(streamReader, settings))
{
- using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
- {
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(streamReader, settings))
- {
- item.ResetPeople();
+ item.ResetPeople();
- reader.MoveToContent();
- reader.Read();
+ reader.MoveToContent();
+ reader.Read();
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- else
- {
- reader.Read();
- }
- }
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ FetchDataFromXmlNode(reader, item);
+ }
+ else
+ {
+ reader.Read();
}
}
}
+
return;
}
- using (var fileStream = File.OpenRead(metadataFile))
- {
- using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
- {
- item.ResetPeople();
+ item.ResetPeople();
- // Need to handle a url after the xml data
- // http://kodi.wiki/view/NFO_files/movies
+ // Need to handle a url after the xml data
+ // http://kodi.wiki/view/NFO_files/movies
- var xml = streamReader.ReadToEnd();
+ var xml = File.ReadAllText(metadataFile);
- // Find last closing Tag
- // Need to do this in two steps to account for random > characters after the closing xml
- var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
+ // Find last closing Tag
+ // Need to do this in two steps to account for random > characters after the closing xml
+ var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
- // If closing tag exists, move to end of Tag
- if (index != -1)
- {
- index = xml.IndexOf('>', index);
- }
+ // If closing tag exists, move to end of Tag
+ if (index != -1)
+ {
+ index = xml.IndexOf('>', index);
+ }
- if (index != -1)
- {
- var endingXml = xml.Substring(index);
+ if (index != -1)
+ {
+ var endingXml = xml.AsSpan().Slice(index);
- ParseProviderLinks(item.Item, endingXml);
+ ParseProviderLinks(item.Item, endingXml);
- // If the file is just an imdb url, don't go any further
- if (index == 0)
- {
- return;
- }
+ // If the file is just an imdb url, don't go any further
+ if (index == 0)
+ {
+ return;
+ }
- xml = xml.Substring(0, index + 1);
- }
- else
- {
- // If the file is just an Imdb url, handle that
+ xml = xml.Substring(0, index + 1);
+ }
+ else
+ {
+ // If the file is just provider urls, handle that
+ ParseProviderLinks(item.Item, xml);
- ParseProviderLinks(item.Item, xml);
+ return;
+ }
- return;
- }
+ // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
+ try
+ {
+ using (var stringReader = new StringReader(xml))
+ using (var reader = XmlReader.Create(stringReader, settings))
+ {
+ reader.MoveToContent();
+ reader.Read();
- // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
- try
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
- using (var stringReader = new StringReader(xml))
- {
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(stringReader, settings))
- {
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ cancellationToken.ThrowIfCancellationRequested();
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- else
- {
- reader.Read();
- }
- }
- }
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ FetchDataFromXmlNode(reader, item);
+ }
+ else
+ {
+ reader.Read();
}
- }
- catch (XmlException)
- {
-
}
}
}
+ catch (XmlException)
+ {
+ }
}
- protected virtual string MovieDbParserSearchString => "themoviedb.org/movie/";
-
- protected void ParseProviderLinks(T item, string xml)
+ protected void ParseProviderLinks(T item, ReadOnlySpan<char> xml)
{
- //Look for a match for the Regex pattern "tt" followed by 7 digits
- var m = Regex.Match(xml, @"tt([0-9]{7})", RegexOptions.IgnoreCase);
- if (m.Success)
+ if (ProviderIdParsers.TryFindImdbId(xml, out var imdbId))
{
- item.SetProviderId(MetadataProviders.Imdb, m.Value);
+ item.SetProviderId(MetadataProvider.Imdb, imdbId.ToString());
}
- // Support Tmdb
- // https://www.themoviedb.org/movie/30287-fallo
- var srch = MovieDbParserSearchString;
- var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
-
- if (index != -1)
+ if (item is Movie)
{
- var tmdbId = xml.Substring(index + srch.Length).TrimEnd('/').Split('-')[0];
- if (!string.IsNullOrWhiteSpace(tmdbId) && int.TryParse(tmdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
+ if (ProviderIdParsers.TryFindTmdbMovieId(xml, out var tmdbId))
{
- item.SetProviderId(MetadataProviders.Tmdb, value.ToString(_usCulture));
+ item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString());
}
}
if (item is Series)
{
- srch = "thetvdb.com/?tab=series&id=";
-
- index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
+ if (ProviderIdParsers.TryFindTmdbSeriesId(xml, out var tmdbId))
+ {
+ item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString());
+ }
- if (index != -1)
+ if (ProviderIdParsers.TryFindTvdbId(xml, out var tvdbId))
{
- var tvdbId = xml.Substring(index + srch.Length).TrimEnd('/');
- if (!string.IsNullOrWhiteSpace(tvdbId) && int.TryParse(tvdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
- {
- item.SetProviderId(MetadataProviders.Tvdb, value.ToString(_usCulture));
- }
+ item.SetProviderId(MetadataProvider.Tvdb, tvdbId.ToString());
}
}
}
@@ -266,6 +249,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
var item = itemResult.Item;
+ var nfoConfiguration = _config.GetNfoConfiguration();
+ UserItemData? userData = null;
+ if (!string.IsNullOrWhiteSpace(nfoConfiguration.UserId))
+ {
+ var user = _userManager.GetUserById(Guid.Parse(nfoConfiguration.UserId));
+ userData = _userDataManager.GetUserData(user, item);
+ }
+
switch (reader.Name)
{
// DateCreated
@@ -275,19 +266,16 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var added))
+ if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var added))
{
- item.DateCreated = added.ToUniversalTime();
- }
- else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
- {
- item.DateCreated = added.ToUniversalTime();
+ item.DateCreated = added;
}
else
{
- Logger.LogWarning("Invalid Added value found: " + val);
+ Logger.LogWarning("Invalid Added value found: {Value}", val);
}
}
+
break;
}
@@ -299,21 +287,27 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.OriginalTitle = val;
}
+
break;
}
+ case "name":
case "title":
case "localtitle":
item.Name = reader.ReadElementContentAsString();
break;
+ case "sortname":
+ item.SortName = reader.ReadElementContentAsString();
+ break;
+
case "criticrating":
{
var text = reader.ReadElementContentAsString();
if (!string.IsNullOrEmpty(text))
{
- if (float.TryParse(text, NumberStyles.Any, _usCulture, out var value))
+ if (float.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var value))
{
item.CriticRating = value;
}
@@ -330,6 +324,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.ForcedSortName = val;
}
+
break;
}
@@ -356,6 +351,50 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
+ case "watched":
+ {
+ var val = reader.ReadElementContentAsBoolean();
+
+ if (userData != null)
+ {
+ userData.Played = val;
+ }
+
+ break;
+ }
+
+ case "playcount":
+ {
+ var val = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(val) && userData != null)
+ {
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var count))
+ {
+ userData.PlayCount = count;
+ }
+ }
+
+ break;
+ }
+
+ case "lastplayed":
+ {
+ var val = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(val) && userData != null)
+ {
+ if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var added))
+ {
+ userData.LastPlayedDate = added;
+ }
+ else
+ {
+ Logger.LogWarning("Invalid lastplayed value found: {Value}", val);
+ }
+ }
+
+ break;
+ }
+
case "countrycode":
{
var val = reader.ReadElementContentAsString();
@@ -373,29 +412,21 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.LockedFields = val.Split('|').Select(i =>
{
- if (Enum.TryParse(i, true, out MetadataFields field))
+ if (Enum.TryParse(i, true, out MetadataField field))
{
- return (MetadataFields?)field;
+ return (MetadataField?)field;
}
return null;
-
- }).Where(i => i.HasValue).Select(i => i.Value).ToArray();
+ }).OfType<MetadataField>().ToArray();
}
break;
}
case "tagline":
- {
- var val = reader.ReadElementContentAsString();
-
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.Tagline = val;
- }
- break;
- }
+ item.Tagline = reader.ReadElementContentAsString();
+ break;
case "country":
{
@@ -408,6 +439,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
.Where(i => !string.IsNullOrWhiteSpace(i))
.ToArray();
}
+
break;
}
@@ -419,6 +451,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.OfficialRating = rating;
}
+
break;
}
@@ -430,6 +463,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.CustomRating = val;
}
+
break;
}
@@ -439,11 +473,12 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(text))
{
- if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out var runtime))
+ if (int.TryParse(text.AsSpan().LeftPart(' '), NumberStyles.Integer, CultureInfo.InvariantCulture, out var runtime))
{
item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
}
}
+
break;
}
@@ -451,11 +486,12 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
var val = reader.ReadElementContentAsString();
- var hasAspectRatio = item as IHasAspectRatio;
- if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
+ if (!string.IsNullOrWhiteSpace(val)
+ && item is IHasAspectRatio hasAspectRatio)
{
hasAspectRatio.AspectRatio = val;
}
+
break;
}
@@ -467,6 +503,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
+
break;
}
@@ -476,16 +513,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- //var parts = val.Split('/')
- // .Select(i => i.Trim())
- // .Where(i => !string.IsNullOrWhiteSpace(i));
-
- //foreach (var p in parts)
- //{
- // item.AddStudio(p);
- //}
item.AddStudio(val);
}
+
break;
}
@@ -498,10 +528,13 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
continue;
}
+
itemResult.AddPerson(p);
}
+
break;
}
+
case "credits":
{
var val = reader.ReadElementContentAsString();
@@ -517,9 +550,11 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
continue;
}
+
itemResult.AddPerson(p);
}
}
+
break;
}
@@ -532,8 +567,10 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
continue;
}
+
itemResult.AddPerson(p);
}
+
break;
}
@@ -555,6 +592,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
reader.Read();
}
+
break;
}
@@ -568,6 +606,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.AddTrailerUrl(val);
}
+
break;
}
@@ -583,6 +622,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
hasDisplayOrder.DisplayOrder = val;
}
}
+
break;
}
@@ -603,7 +643,6 @@ namespace MediaBrowser.XbmcMetadata.Parsers
case "rating":
{
-
var rating = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(rating))
@@ -614,6 +653,22 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.CommunityRating = val;
}
}
+
+ break;
+ }
+
+ case "ratings":
+ {
+ if (!reader.IsEmptyElement)
+ {
+ using var subtree = reader.ReadSubtree();
+ FetchFromRatingsNode(subtree, item);
+ }
+ else
+ {
+ reader.Read();
+ }
+
break;
}
@@ -622,15 +677,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers
case "premiered":
case "releasedate":
{
- var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
+ var formatString = nfoConfiguration.ReleaseDateFormat;
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
- if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
+ if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var date) && date.Year > 1850)
{
- item.PremiereDate = date.ToUniversalTime();
+ item.PremiereDate = date;
item.ProductionYear = date.Year;
}
}
@@ -640,15 +695,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers
case "enddate":
{
- var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
+ var formatString = nfoConfiguration.ReleaseDateFormat;
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
- if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
+ if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var date) && date.Year > 1850)
{
- item.EndDate = date.ToUniversalTime();
+ item.EndDate = date;
}
}
@@ -670,6 +725,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.AddGenre(p);
}
}
+
break;
}
@@ -681,6 +737,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.AddTag(val);
}
+
break;
}
@@ -697,15 +754,48 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
reader.Read();
}
+
+ break;
+ }
+
+ case "uniqueid":
+ {
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ break;
+ }
+
+ var provider = reader.GetAttribute("type");
+ var id = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(provider) && !string.IsNullOrWhiteSpace(id))
+ {
+ item.SetProviderId(provider, id);
+ }
+
+ break;
+ }
+
+ case "thumb":
+ {
+ FetchThumbNode(reader, itemResult);
+ break;
+ }
+
+ case "fanart":
+ {
+ var subtree = reader.ReadSubtree();
+ subtree.ReadToDescendant("thumb");
+ FetchThumbNode(subtree, itemResult);
break;
}
default:
string readerName = reader.Name;
- if (_validProviderIds.TryGetValue(readerName, out string providerIdValue))
+ if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
{
var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
+ if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
{
item.SetProviderId(providerIdValue, id);
}
@@ -714,10 +804,73 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
reader.Skip();
}
+
break;
}
}
+ private void FetchThumbNode(XmlReader reader, MetadataResult<T> itemResult)
+ {
+ var artType = reader.GetAttribute("aspect");
+ var val = reader.ReadElementContentAsString();
+
+ // artType is null if the thumb node is a child of the fanart tag
+ // -> set image type to fanart
+ if (string.IsNullOrWhiteSpace(artType))
+ {
+ artType = "fanart";
+ }
+
+ // skip:
+ // - empty uri
+ // - tag containing '.' because we can't set images for seasons, episodes or movie sets within series or movies
+ if (string.IsNullOrEmpty(val) || artType.Contains('.', StringComparison.Ordinal))
+ {
+ return;
+ }
+
+ ImageType imageType = GetImageType(artType);
+
+ if (!Uri.TryCreate(val, UriKind.Absolute, out var uri))
+ {
+ Logger.LogError("Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file path.", val, itemResult.Item.Name);
+ return;
+ }
+
+ if (uri.IsFile)
+ {
+ // only allow one item of each type
+ if (itemResult.Images.Any(x => x.Type == imageType))
+ {
+ return;
+ }
+
+ var fileSystemMetadata = _directoryService.GetFile(val);
+ // non existing file returns null
+ if (fileSystemMetadata == null || !fileSystemMetadata.Exists)
+ {
+ Logger.LogWarning("Artwork file {Path} specified in nfo file for {ItemName} does not exist.", uri, itemResult.Item.Name);
+ return;
+ }
+
+ itemResult.Images.Add(new LocalImageInfo()
+ {
+ FileInfo = fileSystemMetadata,
+ Type = imageType
+ });
+ }
+ else
+ {
+ // only allow one item of each type
+ if (itemResult.RemoteImages.Any(x => x.type == imageType))
+ {
+ return;
+ }
+
+ itemResult.RemoteImages.Add((uri.ToString(), imageType));
+ }
+ }
+
private void FetchFromFileInfoNode(XmlReader reader, T item)
{
reader.MoveToContent();
@@ -737,10 +890,12 @@ namespace MediaBrowser.XbmcMetadata.Parsers
reader.Read();
continue;
}
+
using (var subtree = reader.ReadSubtree())
{
FetchFromStreamDetailsNode(subtree, item);
}
+
break;
}
@@ -775,10 +930,28 @@ namespace MediaBrowser.XbmcMetadata.Parsers
reader.Read();
continue;
}
+
using (var subtree = reader.ReadSubtree())
{
FetchFromVideoNode(subtree, item);
}
+
+ break;
+ }
+
+ case "subtitle":
+ {
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ continue;
+ }
+
+ using (var subtree = reader.ReadSubtree())
+ {
+ FetchFromSubtitleNode(subtree, item);
+ }
+
break;
}
@@ -835,6 +1008,91 @@ namespace MediaBrowser.XbmcMetadata.Parsers
video.Video3DFormat = Video3DFormat.MVC;
}
}
+
+ break;
+ }
+
+ case "aspect":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (item is Video video)
+ {
+ video.AspectRatio = val;
+ }
+
+ break;
+ }
+
+ case "width":
+ {
+ var val = reader.ReadElementContentAsInt();
+
+ if (item is Video video)
+ {
+ video.Width = val;
+ }
+
+ break;
+ }
+
+ case "height":
+ {
+ var val = reader.ReadElementContentAsInt();
+
+ if (item is Video video)
+ {
+ video.Height = val;
+ }
+
+ break;
+ }
+
+ case "durationinseconds":
+ {
+ var val = reader.ReadElementContentAsInt();
+
+ if (item is Video video)
+ {
+ video.RunTimeTicks = new TimeSpan(0, 0, val).Ticks;
+ }
+
+ break;
+ }
+
+ default:
+ reader.Skip();
+ break;
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
+ }
+
+ private void FetchFromSubtitleNode(XmlReader reader, T item)
+ {
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "language":
+ {
+ _ = reader.ReadElementContentAsString();
+
+ if (item is Video video)
+ {
+ video.HasSubtitles = true;
+ }
+
break;
}
@@ -850,6 +1108,92 @@ namespace MediaBrowser.XbmcMetadata.Parsers
}
}
+ private void FetchFromRatingsNode(XmlReader reader, T item)
+ {
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "rating":
+ {
+ if (reader.IsEmptyElement)
+ {
+ reader.Read();
+ continue;
+ }
+
+ var ratingName = reader.GetAttribute("name");
+
+ using var subtree = reader.ReadSubtree();
+ FetchFromRatingNode(subtree, item, ratingName);
+
+ break;
+ }
+
+ default:
+ reader.Skip();
+ break;
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
+ }
+
+ private void FetchFromRatingNode(XmlReader reader, T item, string? ratingName)
+ {
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ switch (reader.Name)
+ {
+ case "value":
+ var val = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ if (float.TryParse(val, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue))
+ {
+ // if ratingName contains tomato --> assume critic rating
+ if (ratingName != null &&
+ ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase) &&
+ !ratingName.Contains("audience", StringComparison.OrdinalIgnoreCase))
+ {
+ item.CriticRating = ratingValue;
+ }
+ else
+ {
+ item.CommunityRating = ratingValue;
+ }
+ }
+ }
+
+ break;
+ default:
+ reader.Skip();
+ break;
+ }
+ }
+ else
+ {
+ reader.Read();
+ }
+ }
+ }
+
/// <summary>
/// Gets the persons from XML node.
/// </summary>
@@ -861,6 +1205,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
var type = PersonType.Actor; // If type is not specified assume actor
var role = string.Empty;
int? sortOrder = null;
+ string? imageUrl = null;
reader.MoveToContent();
reader.Read();
@@ -873,7 +1218,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
switch (reader.Name)
{
case "name":
- name = reader.ReadElementContentAsString() ?? string.Empty;
+ name = reader.ReadElementContentAsString();
break;
case "role":
@@ -884,19 +1229,58 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
role = val;
}
+
break;
}
+
+ case "type":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ type = val switch
+ {
+ PersonType.Composer => PersonType.Composer,
+ PersonType.Conductor => PersonType.Conductor,
+ PersonType.Director => PersonType.Director,
+ PersonType.Lyricist => PersonType.Lyricist,
+ PersonType.Producer => PersonType.Producer,
+ PersonType.Writer => PersonType.Writer,
+ PersonType.GuestStar => PersonType.GuestStar,
+ // unknown type --> actor
+ _ => PersonType.Actor
+ };
+ }
+
+ break;
+ }
+
+ case "order":
case "sortorder":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
- if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var intVal))
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intVal))
{
sortOrder = intVal;
}
}
+
+ break;
+ }
+
+ case "thumb":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ imageUrl = val;
+ }
+
break;
}
@@ -916,38 +1300,56 @@ namespace MediaBrowser.XbmcMetadata.Parsers
Name = name.Trim(),
Role = role,
Type = type,
- SortOrder = sortOrder
+ SortOrder = sortOrder,
+ ImageUrl = imageUrl
};
}
+ internal XmlReaderSettings GetXmlReaderSettings()
+ => new XmlReaderSettings()
+ {
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
+
/// <summary>
- /// Used to split names of comma or pipe delimeted genres and people
+ /// Used to split names of comma or pipe delimeted genres and people.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>IEnumerable{System.String}.</returns>
private IEnumerable<string> SplitNames(string value)
{
- value = value ?? string.Empty;
-
// Only split by comma if there is no pipe in the string
// We have to be careful to not split names like Matthew, Jr.
- var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
+ var separator = !value.Contains('|', StringComparison.Ordinal) && !value.Contains(';', StringComparison.Ordinal)
+ ? new[] { ',' }
+ : new[] { '|', ';' };
value = value.Trim().Trim(separator);
- return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
+ return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
- /// Provides an additional overload for string.split
+ /// Parses the ImageType from the nfo aspect property.
/// </summary>
- /// <param name="val">The val.</param>
- /// <param name="separators">The separators.</param>
- /// <param name="options">The options.</param>
- /// <returns>System.String[][].</returns>
- private string[] Split(string val, char[] separators, StringSplitOptions options)
+ /// <param name="aspect">The nfo aspect property.</param>
+ /// <returns>The image type.</returns>
+ private static ImageType GetImageType(string aspect)
{
- return val.Split(separators, options);
+ return aspect switch
+ {
+ "banner" => ImageType.Banner,
+ "clearlogo" => ImageType.Logo,
+ "discart" => ImageType.Disc,
+ "landscape" => ImageType.Thumb,
+ "clearart" => ImageType.Art,
+ "fanart" => ImageType.Backdrop,
+ // unknown type (including "poster") --> primary
+ _ => ImageType.Primary,
+ };
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
index a8cb6ac40..d2f349ad7 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
@@ -1,90 +1,110 @@
using System;
-using System.Collections.Generic;
using System.Globalization;
using System.IO;
-using System.Text;
using System.Threading;
using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Parsers
{
+ /// <summary>
+ /// Nfo parser for episodes.
+ /// </summary>
public class EpisodeNfoParser : BaseNfoParser<Episode>
{
- public void Fetch(MetadataResult<Episode> item,
- List<LocalImageInfo> images,
- string metadataFile,
- CancellationToken cancellationToken)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeNfoParser"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{BaseNfoParser}"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public EpisodeNfoParser(
+ ILogger logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, config, providerManager, userManager, userDataManager, directoryService)
{
- Fetch(item, metadataFile, cancellationToken);
}
- private readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<Episode> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
{
- using (var fileStream = File.OpenRead(metadataFile))
- {
- using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
- {
- item.ResetPeople();
+ item.ResetPeople();
- var xml = streamReader.ReadToEnd();
+ var xmlFile = File.ReadAllText(metadataFile);
- var srch = "</episodedetails>";
- var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
+ var srch = "</episodedetails>";
+ var index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
- if (index != -1)
- {
- xml = xml.Substring(0, index + srch.Length);
- }
+ var xml = xmlFile;
- // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
- try
+ if (index != -1)
+ {
+ xml = xmlFile.Substring(0, index + srch.Length);
+ xmlFile = xmlFile.Substring(index + srch.Length);
+ }
+
+ // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
+ try
+ {
+ // Extract episode details from the first episodedetails block
+ using (var stringReader = new StringReader(xml))
+ using (var reader = XmlReader.Create(stringReader, settings))
+ {
+ reader.MoveToContent();
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
- using (var stringReader = new StringReader(xml))
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (reader.NodeType == XmlNodeType.Element)
{
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(stringReader, settings))
- {
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- else
- {
- reader.Read();
- }
- }
- }
+ FetchDataFromXmlNode(reader, item);
+ }
+ else
+ {
+ reader.Read();
}
}
- catch (XmlException)
+ }
+
+ // Extract the last episode number from nfo
+ // This is needed because XBMC metadata uses multiple episodedetails blocks instead of episodenumberend tag
+ while ((index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase)) != -1)
+ {
+ xml = xmlFile.Substring(0, index + srch.Length);
+ xmlFile = xmlFile.Substring(index + srch.Length);
+
+ using (var stringReader = new StringReader(xml))
+ using (var reader = XmlReader.Create(stringReader, settings))
{
+ reader.MoveToContent();
+ if (reader.ReadToDescendant("episode") && int.TryParse(reader.ReadElementContentAsString(), out var num))
+ {
+ item.Item.IndexNumberEnd = Math.Max(num, item.Item.IndexNumberEnd ?? num);
+ }
}
}
}
+ catch (XmlException)
+ {
+ }
}
- /// <summary>
- /// Fetches the data from XML node.
- /// </summary>
- /// <param name="reader">The reader.</param>
- /// <param name="itemResult">The item result.</param>
+ /// <inheritdoc />
protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Episode> itemResult)
{
var item = itemResult.Item;
@@ -102,6 +122,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.ParentIndexNumber = num;
}
}
+
break;
}
@@ -116,6 +137,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.IndexNumber = num;
}
}
+
break;
}
@@ -130,6 +152,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.IndexNumberEnd = num;
}
}
+
break;
}
@@ -139,8 +162,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- // int.TryParse is local aware, so it can be probamatic, force us culture
- if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval))
+ // int.TryParse is local aware, so it can be problematic, force us culture
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var rval))
{
item.AirsBeforeEpisodeNumber = rval;
}
@@ -155,8 +178,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- // int.TryParse is local aware, so it can be probamatic, force us culture
- if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval))
+ // int.TryParse is local aware, so it can be problematic, force us culture
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var rval))
{
item.AirsAfterSeasonNumber = rval;
}
@@ -171,8 +194,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- // int.TryParse is local aware, so it can be probamatic, force us culture
- if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval))
+ // int.TryParse is local aware, so it can be problematic, force us culture
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var rval))
{
item.AirsBeforeSeasonNumber = rval;
}
@@ -187,8 +210,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- // int.TryParse is local aware, so it can be probamatic, force us culture
- if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval))
+ // int.TryParse is local aware, so it can be problematic, force us culture
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var rval))
{
item.AirsBeforeSeasonNumber = rval;
}
@@ -203,8 +226,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val))
{
- // int.TryParse is local aware, so it can be probamatic, force us culture
- if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval))
+ // int.TryParse is local aware, so it can be problematic, force us culture
+ if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out var rval))
{
item.AirsBeforeEpisodeNumber = rval;
}
@@ -213,15 +236,22 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
+ case "showtitle":
+ {
+ var showtitle = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(showtitle))
+ {
+ item.SeriesName = showtitle;
+ }
+
+ break;
+ }
default:
base.FetchDataFromXmlNode(reader, itemResult);
break;
}
}
-
- public EpisodeNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(logger, config, providerManager, fileSystem, xmlReaderSettingsFactory)
- {
- }
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
index a3e48d30d..e51055725 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
@@ -5,23 +5,42 @@ using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Parsers
{
+ /// <summary>
+ /// Nfo parser for movies.
+ /// </summary>
public class MovieNfoParser : BaseNfoParser<Video>
{
- protected override bool SupportsUrlAfterClosingXmlTag => true;
-
/// <summary>
- /// Fetches the data from XML node.
+ /// Initializes a new instance of the <see cref="MovieNfoParser"/> class.
/// </summary>
- /// <param name="reader">The reader.</param>
- /// <param name="itemResult">The item result.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="DirectoryService"/> interface.</param>
+ public MovieNfoParser(
+ ILogger logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, config, providerManager, userManager, userDataManager, directoryService)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override bool SupportsUrlAfterClosingXmlTag => true;
+
+ /// <inheritdoc />
protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Video> itemResult)
{
var item = itemResult.Item;
@@ -30,23 +49,34 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
case "id":
{
- string imdbId = reader.GetAttribute("IMDB");
- string tmdbId = reader.GetAttribute("TMDB");
+ // get ids from attributes
+ string? imdbId = reader.GetAttribute("IMDB");
+ string? tmdbId = reader.GetAttribute("TMDB");
- if (string.IsNullOrWhiteSpace(imdbId))
+ // read id from content
+ var contentId = reader.ReadElementContentAsString();
+ if (contentId.Contains("tt", StringComparison.Ordinal) && string.IsNullOrEmpty(imdbId))
+ {
+ imdbId = contentId;
+ }
+ else if (string.IsNullOrEmpty(tmdbId))
{
- imdbId = reader.ReadElementContentAsString();
+ tmdbId = contentId;
}
+
if (!string.IsNullOrWhiteSpace(imdbId))
{
- item.SetProviderId(MetadataProviders.Imdb, imdbId);
+ item.SetProviderId(MetadataProvider.Imdb, imdbId);
}
+
if (!string.IsNullOrWhiteSpace(tmdbId))
{
- item.SetProviderId(MetadataProviders.Tmdb, tmdbId);
+ item.SetProviderId(MetadataProvider.Tmdb, tmdbId);
}
+
break;
}
+
case "set":
{
var movie = item as Movie;
@@ -54,7 +84,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
var tmdbcolid = reader.GetAttribute("tmdbcolid");
if (!string.IsNullOrWhiteSpace(tmdbcolid) && movie != null)
{
- movie.SetProviderId(MetadataProviders.TmdbCollection, tmdbcolid);
+ movie.SetProviderId(MetadataProvider.TmdbCollection, tmdbcolid);
}
var val = reader.ReadInnerXml();
@@ -62,7 +92,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
if (!string.IsNullOrWhiteSpace(val) && movie != null)
{
// TODO Handle this better later
- if (val.IndexOf('<') == -1)
+ if (!val.Contains('<', StringComparison.Ordinal))
{
movie.CollectionName = val;
}
@@ -85,9 +115,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
case "artist":
{
var val = reader.ReadElementContentAsString();
- var movie = item as MusicVideo;
- if (!string.IsNullOrWhiteSpace(val) && movie != null)
+ if (!string.IsNullOrWhiteSpace(val) && item is MusicVideo movie)
{
var list = movie.Artists.ToList();
list.Add(val);
@@ -100,9 +129,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
case "album":
{
var val = reader.ReadElementContentAsString();
- var movie = item as MusicVideo;
- if (!string.IsNullOrWhiteSpace(val) && movie != null)
+ if (!string.IsNullOrWhiteSpace(val) && item is MusicVideo movie)
{
movie.Album = val;
}
@@ -118,57 +146,40 @@ namespace MediaBrowser.XbmcMetadata.Parsers
private void ParseSetXml(string xml, Movie movie)
{
- //xml = xml.Substring(xml.IndexOf('<'));
- //xml = xml.Substring(0, xml.LastIndexOf('>'));
-
- using (var stringReader = new StringReader("<set>" + xml + "</set>"))
+ // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
+ try
{
- // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
- try
+ using (var stringReader = new StringReader("<set>" + xml + "</set>"))
+ using (var reader = XmlReader.Create(stringReader, GetXmlReaderSettings()))
{
- var settings = XmlReaderSettingsFactory.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ reader.MoveToContent();
+ reader.Read();
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(stringReader, settings))
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
- reader.MoveToContent();
- reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ if (reader.NodeType == XmlNodeType.Element)
{
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "name":
- movie.CollectionName = reader.ReadElementContentAsString();
- break;
- default:
- reader.Skip();
- break;
- }
- }
- else
+ switch (reader.Name)
{
- reader.Read();
+ case "name":
+ movie.CollectionName = reader.ReadElementContentAsString();
+ break;
+ default:
+ reader.Skip();
+ break;
}
}
+ else
+ {
+ reader.Read();
+ }
}
}
- catch (XmlException)
- {
-
- }
}
- }
-
- public MovieNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(logger, config, providerManager, fileSystem, xmlReaderSettingsFactory)
- {
+ catch (XmlException)
+ {
+ }
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
index 17f36d82d..2f5fd40e2 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
@@ -2,20 +2,38 @@ using System.Globalization;
using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Parsers
{
+ /// <summary>
+ /// Nfo parser for seasons.
+ /// </summary>
public class SeasonNfoParser : BaseNfoParser<Season>
{
/// <summary>
- /// Fetches the data from XML node.
+ /// Initializes a new instance of the <see cref="SeasonNfoParser"/> class.
/// </summary>
- /// <param name="reader">The reader.</param>
- /// <param name="itemResult">The item result.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="DirectoryService"/> interface.</param>
+ public SeasonNfoParser(
+ ILogger logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, config, providerManager, userManager, userDataManager, directoryService)
+ {
+ }
+
+ /// <inheritdoc />
protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Season> itemResult)
{
var item = itemResult.Item;
@@ -33,6 +51,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
item.IndexNumber = num;
}
}
+
break;
}
@@ -41,9 +60,5 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
}
-
- public SeasonNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(logger, config, providerManager, fileSystem, xmlReaderSettingsFactory)
- {
- }
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
index 700656b65..2c893ac9f 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
@@ -5,23 +5,39 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Parsers
{
+ /// <summary>
+ /// Nfo parser for series.
+ /// </summary>
public class SeriesNfoParser : BaseNfoParser<Series>
{
- protected override bool SupportsUrlAfterClosingXmlTag => true;
-
- protected override string MovieDbParserSearchString => "themoviedb.org/tv/";
-
/// <summary>
- /// Fetches the data from XML node.
+ /// Initializes a new instance of the <see cref="SeriesNfoParser"/> class.
/// </summary>
- /// <param name="reader">The reader.</param>
- /// <param name="itemResult">The item result.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public SeriesNfoParser(
+ ILogger logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, config, providerManager, userManager, userDataManager, directoryService)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override bool SupportsUrlAfterClosingXmlTag => true;
+
+ /// <inheritdoc />
protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Series> itemResult)
{
var item = itemResult.Item;
@@ -30,28 +46,33 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
case "id":
{
- string imdbId = reader.GetAttribute("IMDB");
- string tmdbId = reader.GetAttribute("TMDB");
- string tvdbId = reader.GetAttribute("TVDB");
+ string? imdbId = reader.GetAttribute("IMDB");
+ string? tmdbId = reader.GetAttribute("TMDB");
+ string? tvdbId = reader.GetAttribute("TVDB");
if (string.IsNullOrWhiteSpace(tvdbId))
{
tvdbId = reader.ReadElementContentAsString();
}
+
if (!string.IsNullOrWhiteSpace(imdbId))
{
- item.SetProviderId(MetadataProviders.Imdb, imdbId);
+ item.SetProviderId(MetadataProvider.Imdb, imdbId);
}
+
if (!string.IsNullOrWhiteSpace(tmdbId))
{
- item.SetProviderId(MetadataProviders.Tmdb, tmdbId);
+ item.SetProviderId(MetadataProvider.Tmdb, tmdbId);
}
+
if (!string.IsNullOrWhiteSpace(tvdbId))
{
- item.SetProviderId(MetadataProviders.Tvdb, tvdbId);
+ item.SetProviderId(MetadataProvider.Tvdb, tvdbId);
}
+
break;
}
+
case "airs_dayofweek":
{
item.AirDays = TVUtils.GetAirDays(reader.ReadElementContentAsString());
@@ -66,6 +87,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
{
item.AirTime = val;
}
+
break;
}
@@ -93,9 +115,5 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
}
-
- public SeriesNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(logger, config, providerManager, fileSystem, xmlReaderSettingsFactory)
- {
- }
}
}
diff --git a/MediaBrowser.XbmcMetadata/Properties/AssemblyInfo.cs b/MediaBrowser.XbmcMetadata/Properties/AssemblyInfo.cs
index 11e513f1b..cfe06b940 100644
--- a/MediaBrowser.XbmcMetadata/Properties/AssemblyInfo.cs
+++ b/MediaBrowser.XbmcMetadata/Properties/AssemblyInfo.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Resources;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -9,11 +10,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
+[assembly: InternalsVisibleTo("Jellyfin.XbmcMetadata.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
index 1e22bf358..f7a85a07e 100644
--- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
@@ -2,38 +2,62 @@ using System.IO;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for albums.
+ /// </summary>
public class AlbumNfoProvider : BaseNfoProvider<MusicAlbum>
{
- private readonly ILogger _logger;
+ private readonly ILogger<AlbumNfoProvider> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public AlbumNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AlbumNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{AlbumNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public AlbumNfoProvider(
+ ILogger<AlbumNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<MusicAlbum> result, string path, CancellationToken cancellationToken)
{
- new BaseNfoParser<MusicAlbum>(_logger, _config, _providerManager, FileSystem, XmlReaderSettingsFactory).Fetch(result, path, cancellationToken);
+ new BaseNfoParser<MusicAlbum>(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
- {
- return directoryService.GetFile(Path.Combine(info.Path, "album.nfo"));
- }
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ => directoryService.GetFile(Path.Combine(info.Path, "album.nfo"));
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
index ad811b475..2b563b7fa 100644
--- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
@@ -2,38 +2,62 @@ using System.IO;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for artists.
+ /// </summary>
public class ArtistNfoProvider : BaseNfoProvider<MusicArtist>
{
- private readonly ILogger _logger;
+ private readonly ILogger<ArtistNfoProvider> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public ArtistNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{ArtistNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public ArtistNfoProvider(
+ IFileSystem fileSystem,
+ ILogger<ArtistNfoProvider> logger,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<MusicArtist> result, string path, CancellationToken cancellationToken)
{
- new BaseNfoParser<MusicArtist>(_logger, _config, _providerManager, FileSystem, XmlReaderSettingsFactory).Fetch(result, path, cancellationToken);
+ new BaseNfoParser<MusicArtist>(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
- {
- return directoryService.GetFile(Path.Combine(info.Path, "artist.nfo"));
- }
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ => directoryService.GetFile(Path.Combine(info.Path, "artist.nfo"));
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
index 0a47ac8e1..abd3e78d7 100644
--- a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -11,9 +13,19 @@ namespace MediaBrowser.XbmcMetadata.Providers
public abstract class BaseNfoProvider<T> : ILocalMetadataProvider<T>, IHasItemChangeMonitor
where T : BaseItem, new()
{
- protected IFileSystem FileSystem;
+ private IFileSystem _fileSystem;
+
+ protected BaseNfoProvider(IFileSystem fileSystem)
+ {
+ _fileSystem = fileSystem;
+ }
- public Task<MetadataResult<T>> GetMetadata(ItemInfo info,
+ /// <inheritdoc />
+ public string Name => BaseNfoSaver.SaverName;
+
+ /// <inheritdoc />
+ public Task<MetadataResult<T>> GetMetadata(
+ ItemInfo info,
IDirectoryService directoryService,
CancellationToken cancellationToken)
{
@@ -47,15 +59,7 @@ namespace MediaBrowser.XbmcMetadata.Providers
return Task.FromResult(result);
}
- protected abstract void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken);
-
- protected BaseNfoProvider(IFileSystem fileSystem)
- {
- FileSystem = fileSystem;
- }
-
- protected abstract FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService);
-
+ /// <inheritdoc />
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
var file = GetXmlFile(new ItemInfo(item), directoryService);
@@ -65,9 +69,11 @@ namespace MediaBrowser.XbmcMetadata.Providers
return false;
}
- return file.Exists && FileSystem.GetLastWriteTimeUtc(file) > item.DateLastSaved;
+ return file.Exists && _fileSystem.GetLastWriteTimeUtc(file) > item.DateLastSaved;
}
- public string Name => BaseNfoSaver.SaverName;
+ protected abstract void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken);
+
+ protected abstract FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService);
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
index 94f104f61..8574be3f3 100644
--- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
@@ -1,43 +1,59 @@
+#pragma warning disable CS1591
+
using System.Linq;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using MediaBrowser.XbmcMetadata.Savers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
- public class BaseVideoNfoProvider<T> : BaseNfoProvider<T>
+ public abstract class BaseVideoNfoProvider<T> : BaseNfoProvider<T>
where T : Video, new()
{
- private readonly ILogger _logger;
+ private readonly ILogger<BaseVideoNfoProvider<T>> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public BaseVideoNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ protected BaseVideoNfoProvider(
+ ILogger<BaseVideoNfoProvider<T>> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken)
{
var tmpItem = new MetadataResult<Video>
{
Item = result.Item
};
- new MovieNfoParser(_logger, _config, _providerManager, FileSystem, XmlReaderSettingsFactory).Fetch(tmpItem, path, cancellationToken);
+ new MovieNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(tmpItem, path, cancellationToken);
result.Item = (T)tmpItem.Item;
result.People = tmpItem.People;
+ result.Images = tmpItem.Images;
+ result.RemoteImages = tmpItem.RemoteImages;
if (tmpItem.UserDataList != null)
{
@@ -45,9 +61,10 @@ namespace MediaBrowser.XbmcMetadata.Providers
}
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
{
- return MovieNfoSaver.GetMovieSavePaths(info, FileSystem)
+ return MovieNfoSaver.GetMovieSavePaths(info)
.Select(directoryService.GetFile)
.FirstOrDefault(i => i != null);
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
index bf05f0f38..f6c5877b4 100644
--- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
@@ -1,42 +1,63 @@
-using System.Collections.Generic;
using System.IO;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for episodes.
+ /// </summary>
public class EpisodeNfoProvider : BaseNfoProvider<Episode>
{
- private readonly ILogger _logger;
+ private readonly ILogger<EpisodeNfoProvider> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public EpisodeNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{EpisodeNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public EpisodeNfoProvider(
+ ILogger<EpisodeNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<Episode> result, string path, CancellationToken cancellationToken)
{
- var images = new List<LocalImageInfo>();
-
- new EpisodeNfoParser(_logger, _config, _providerManager, FileSystem, XmlReaderSettingsFactory).Fetch(result, images, path, cancellationToken);
-
- result.Images = images;
+ new EpisodeNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
{
var path = Path.ChangeExtension(info.Path, ".nfo");
diff --git a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
index 77b3b3781..cdbc5a918 100644
--- a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
@@ -1,30 +1,36 @@
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for movies.
+ /// </summary>
public class MovieNfoProvider : BaseVideoNfoProvider<Movie>
{
- public MovieNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, logger, config, providerManager, xmlReaderSettingsFactory)
- {
- }
- }
-
- public class MusicVideoNfoProvider : BaseVideoNfoProvider<MusicVideo>
- {
- public MusicVideoNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, logger, config, providerManager, xmlReaderSettingsFactory)
- {
- }
- }
-
- public class VideoNfoProvider : BaseVideoNfoProvider<Video>
- {
- public VideoNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, logger, config, providerManager, xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovieNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{MovieNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public MovieNfoProvider(
+ ILogger<MovieNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService)
{
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs
new file mode 100644
index 000000000..9d1f3e61d
--- /dev/null
+++ b/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs
@@ -0,0 +1,37 @@
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.XbmcMetadata.Providers
+{
+ /// <summary>
+ /// Nfo provider for music videos.
+ /// </summary>
+ public class MusicVideoNfoProvider : BaseVideoNfoProvider<MusicVideo>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicVideoNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{SeasonNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public MusicVideoNfoProvider(
+ ILogger<MusicVideoNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
index e669a86a3..d01abadf6 100644
--- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
@@ -2,39 +2,62 @@ using System.IO;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for seasons.
+ /// </summary>
public class SeasonNfoProvider : BaseNfoProvider<Season>
{
- private readonly ILogger _logger;
+ private readonly ILogger<SeasonNfoProvider> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public SeasonNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeasonNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{SeasonNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public SeasonNfoProvider(
+ ILogger<SeasonNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<Season> result, string path, CancellationToken cancellationToken)
{
- new SeasonNfoParser(_logger, _config, _providerManager, FileSystem, XmlReaderSettingsFactory).Fetch(result, path, cancellationToken);
+ new SeasonNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
- {
- return directoryService.GetFile(Path.Combine(info.Path, "season.nfo"));
- }
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ => directoryService.GetFile(Path.Combine(info.Path, "season.nfo"));
}
}
-
diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
index d90a65535..002b94463 100644
--- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
@@ -2,40 +2,62 @@ using System.IO;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Providers
{
+ /// <summary>
+ /// Nfo provider for series.
+ /// </summary>
public class SeriesNfoProvider : BaseNfoProvider<Series>
{
- private readonly ILogger _logger;
+ private readonly ILogger<SeriesNfoProvider> _logger;
private readonly IConfigurationManager _config;
private readonly IProviderManager _providerManager;
- private readonly IFileSystem _fileSystem;
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IDirectoryService _directoryService;
- public SeriesNfoProvider(IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem1, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeriesNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{SeriesNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public SeriesNfoProvider(
+ ILogger<SeriesNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
: base(fileSystem)
{
_logger = logger;
_config = config;
_providerManager = providerManager;
- _fileSystem = fileSystem1;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
+ _userManager = userManager;
+ _userDataManager = userDataManager;
+ _directoryService = directoryService;
}
+ /// <inheritdoc />
protected override void Fetch(MetadataResult<Series> result, string path, CancellationToken cancellationToken)
{
- new SeriesNfoParser(_logger, _config, _providerManager, _fileSystem, XmlReaderSettingsFactory).Fetch(result, path, cancellationToken);
+ new SeriesNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken);
}
- protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
- {
- return directoryService.GetFile(Path.Combine(info.Path, "tvshow.nfo"));
- }
+ /// <inheritdoc />
+ protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService)
+ => directoryService.GetFile(Path.Combine(info.Path, "tvshow.nfo"));
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs
new file mode 100644
index 000000000..93b1be62f
--- /dev/null
+++ b/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs
@@ -0,0 +1,37 @@
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.XbmcMetadata.Providers
+{
+ /// <summary>
+ /// Nfo provider for videos.
+ /// </summary>
+ public class VideoNfoProvider : BaseVideoNfoProvider<Video>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideoNfoProvider"/> class.
+ /// </summary>
+ /// <param name="logger">Instance of the <see cref="ILogger{VideoNfoProvider}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+ /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
+ /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
+ public VideoNfoProvider(
+ ILogger<VideoNfoProvider> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager config,
+ IProviderManager providerManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ IDirectoryService directoryService)
+ : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService)
+ {
+ }
+ }
+}
diff --git a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
index 79f119d7f..2385e7048 100644
--- a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
@@ -9,33 +9,48 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for albums.
+ /// </summary>
public class AlbumNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AlbumNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public AlbumNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<AlbumNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- return Path.Combine(item.Path, "album.nfo");
}
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => Path.Combine(item.Path, "album.nfo");
+
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return "album";
- }
+ => "album";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
- {
- if (!item.SupportsLocalMetadata)
- {
- return false;
- }
-
- return item is MusicAlbum && updateType >= MinimumUpdateType;
- }
+ => item.SupportsLocalMetadata && item is MusicAlbum && updateType >= MinimumUpdateType;
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var album = (MusicAlbum)item;
@@ -53,8 +68,6 @@ namespace MediaBrowser.XbmcMetadata.Savers
AddTracks(album.Tracks, writer);
}
- private readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
private void AddTracks(IEnumerable<BaseItem> tracks, XmlWriter writer)
{
foreach (var track in tracks.OrderBy(i => i.ParentIndexNumber ?? 0).ThenBy(i => i.IndexNumber ?? 0))
@@ -63,7 +76,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (track.IndexNumber.HasValue)
{
- writer.WriteElementString("position", track.IndexNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("position", track.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(track.Name))
@@ -73,7 +86,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (track.RunTimeTicks.HasValue)
{
- var time = TimeSpan.FromTicks(track.RunTimeTicks.Value).ToString(@"mm\:ss");
+ var time = TimeSpan.FromTicks(track.RunTimeTicks.Value).ToString(@"mm\:ss", CultureInfo.InvariantCulture);
writer.WriteElementString("duration", time);
}
@@ -82,20 +95,17 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "track",
- "artist",
- "albumartist"
- });
- return list;
- }
+ yield return tag;
+ }
- public AlbumNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "track";
+ yield return "artist";
+ yield return "albumartist";
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
index f01132fd9..71b58cddb 100644
--- a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
@@ -7,34 +7,49 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Configuration;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for artsist.
+ /// </summary>
public class ArtistNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public ArtistNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<ArtistNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- return Path.Combine(item.Path, "artist.nfo");
}
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => Path.Combine(item.Path, "artist.nfo");
+
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return "artist";
- }
+ => "artist";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
- {
- if (!item.SupportsLocalMetadata)
- {
- return false;
- }
-
- return item is MusicArtist && updateType >= MinimumUpdateType;
- }
+ => item.SupportsLocalMetadata && item is MusicArtist && updateType >= MinimumUpdateType;
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var artist = (MusicArtist)item;
@@ -43,7 +58,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
var formatString = ConfigurationManager.GetNfoConfiguration().ReleaseDateFormat;
- writer.WriteElementString("disbanded", artist.EndDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString("disbanded", artist.EndDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
var albums = artist
@@ -52,8 +67,6 @@ namespace MediaBrowser.XbmcMetadata.Savers
AddAlbums(albums, writer);
}
- private readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
private void AddAlbums(IList<BaseItem> albums, XmlWriter writer)
{
foreach (var album in albums)
@@ -67,26 +80,23 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (album.ProductionYear.HasValue)
{
- writer.WriteElementString("year", album.ProductionYear.Value.ToString(UsCulture));
+ writer.WriteElementString("year", album.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
}
writer.WriteEndElement();
}
}
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "album",
- "disbanded"
- });
- return list;
- }
+ yield return tag;
+ }
- public ArtistNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "album";
+ yield return "disbanded";
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
index 4925c7cd1..594402258 100644
--- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -16,9 +18,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Configuration;
using Microsoft.Extensions.Logging;
@@ -26,81 +26,88 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
public abstract class BaseNfoSaver : IMetadataFileSaver
{
- public static readonly string YouTubeWatchUrl = "https://www.youtube.com/watch?v=";
-
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- private static readonly Dictionary<string, string> CommonTags = new[] {
-
- "plot",
- "customrating",
- "lockdata",
- "dateadded",
- "title",
- "rating",
- "year",
- "sorttitle",
- "mpaa",
- "aspectratio",
- "collectionnumber",
- "tmdbid",
- "rottentomatoesid",
- "language",
- "tvcomid",
- "tagline",
- "studio",
- "genre",
- "tag",
- "runtime",
- "actor",
- "criticrating",
- "fileinfo",
- "director",
- "writer",
- "trailer",
- "premiered",
- "releasedate",
- "outline",
- "id",
- "credits",
- "originaltitle",
- "watched",
- "playcount",
- "lastplayed",
- "art",
- "resume",
- "biography",
- "formed",
- "review",
- "style",
- "imdbid",
- "imdb_id",
- "country",
- "audiodbalbumid",
- "audiodbartistid",
- "enddate",
- "lockedfields",
- "zap2itid",
- "tvrageid",
-
- "musicbrainzartistid",
- "musicbrainzalbumartistid",
- "musicbrainzalbumid",
- "musicbrainzreleasegroupid",
- "tvdbid",
- "collectionitem",
-
- "isuserfavorite",
- "userrating",
+ public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
- "countrycode"
+ public const string YouTubeWatchUrl = "https://www.youtube.com/watch?v=";
- }.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
+ // filters control characters but allows only properly-formed surrogate sequences
+ private const string _invalidXMLCharsRegex = @"(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]";
- protected BaseNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+ private static readonly HashSet<string> _commonTags = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ "plot",
+ "customrating",
+ "lockdata",
+ "dateadded",
+ "title",
+ "rating",
+ "year",
+ "sorttitle",
+ "mpaa",
+ "aspectratio",
+ "collectionnumber",
+ "tmdbid",
+ "rottentomatoesid",
+ "language",
+ "tvcomid",
+ "tagline",
+ "studio",
+ "genre",
+ "tag",
+ "runtime",
+ "actor",
+ "criticrating",
+ "fileinfo",
+ "director",
+ "writer",
+ "trailer",
+ "premiered",
+ "releasedate",
+ "outline",
+ "id",
+ "credits",
+ "originaltitle",
+ "watched",
+ "playcount",
+ "lastplayed",
+ "art",
+ "resume",
+ "biography",
+ "formed",
+ "review",
+ "style",
+ "imdbid",
+ "imdb_id",
+ "country",
+ "audiodbalbumid",
+ "audiodbartistid",
+ "enddate",
+ "lockedfields",
+ "zap2itid",
+ "tvrageid",
+
+ "musicbrainzartistid",
+ "musicbrainzalbumartistid",
+ "musicbrainzalbumid",
+ "musicbrainzreleasegroupid",
+ "tvdbid",
+ "collectionitem",
+
+ "isuserfavorite",
+ "userrating",
+
+ "countrycode"
+ };
+
+ protected BaseNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<BaseNfoSaver> logger)
{
Logger = logger;
- XmlReaderSettingsFactory = xmlReaderSettingsFactory;
UserDataManager = userDataManager;
UserManager = userManager;
LibraryManager = libraryManager;
@@ -108,13 +115,17 @@ namespace MediaBrowser.XbmcMetadata.Savers
FileSystem = fileSystem;
}
- protected IFileSystem FileSystem { get; private set; }
- protected IServerConfigurationManager ConfigurationManager { get; private set; }
- protected ILibraryManager LibraryManager { get; private set; }
- protected IUserManager UserManager { get; private set; }
- protected IUserDataManager UserDataManager { get; private set; }
- protected ILogger Logger { get; private set; }
- protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
+ protected IFileSystem FileSystem { get; }
+
+ protected IServerConfigurationManager ConfigurationManager { get; }
+
+ protected ILibraryManager LibraryManager { get; }
+
+ protected IUserManager UserManager { get; }
+
+ protected IUserDataManager UserDataManager { get; }
+
+ protected ILogger<BaseNfoSaver> Logger { get; }
protected ItemUpdateType MinimumUpdateType
{
@@ -129,51 +140,45 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
+ /// <inheritdoc />
public string Name => SaverName;
public static string SaverName => "Nfo";
+ /// <inheritdoc />
public string GetSavePath(BaseItem item)
- {
- return GetLocalSavePath(item);
- }
+ => GetLocalSavePath(item);
/// <summary>
/// Gets the save path.
/// </summary>
/// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
+ /// <returns><see cref="string" />.</returns>
protected abstract string GetLocalSavePath(BaseItem item);
/// <summary>
/// Gets the name of the root element.
/// </summary>
/// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
+ /// <returns><see cref="string" />.</returns>
protected abstract string GetRootElementName(BaseItem item);
- /// <summary>
- /// Determines whether [is enabled for] [the specified item].
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="updateType">Type of the update.</param>
- /// <returns><c>true</c> if [is enabled for] [the specified item]; otherwise, <c>false</c>.</returns>
+ /// <inheritdoc />
public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType);
- protected virtual List<string> GetTagsUsed(BaseItem item)
+ protected virtual IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = new List<string>();
foreach (var providerKey in item.ProviderIds.Keys)
{
var providerIdTagName = GetTagForProviderKey(providerKey);
- if (!CommonTags.ContainsKey(providerIdTagName))
+ if (!_commonTags.Contains(providerIdTagName))
{
- list.Add(providerIdTagName);
+ yield return providerIdTagName;
}
}
- return list;
}
+ /// <inheritdoc />
public void Save(BaseItem item, CancellationToken cancellationToken)
{
var path = GetSavePath(item);
@@ -192,11 +197,21 @@ namespace MediaBrowser.XbmcMetadata.Savers
private void SaveToFile(Stream stream, string path)
{
- Directory.CreateDirectory(Path.GetDirectoryName(path));
- // On Windows, savint the file will fail if the file is hidden or readonly
+ var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
+ Directory.CreateDirectory(directory);
+
+ // On Windows, saving the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false);
- using (var filestream = FileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ var fileStreamOptions = new FileStreamOptions()
+ {
+ Mode = FileMode.Create,
+ Access = FileAccess.Write,
+ Share = FileShare.None,
+ PreallocationSize = stream.Length
+ };
+
+ using (var filestream = new FileStream(path, fileStreamOptions))
{
stream.CopyTo(filestream);
}
@@ -213,9 +228,9 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
FileSystem.SetHidden(path, hidden);
}
- catch (Exception ex)
+ catch (IOException ex)
{
- Logger.LogError(ex, "Error setting hidden attribute on {path}", path);
+ Logger.LogError(ex, "Error setting hidden attribute on {Path}", path);
}
}
@@ -240,31 +255,27 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (baseItem != null)
{
- AddCommonNodes(baseItem, writer, LibraryManager, UserManager, UserDataManager, FileSystem, ConfigurationManager);
+ AddCommonNodes(baseItem, writer, LibraryManager, UserManager, UserDataManager, ConfigurationManager);
}
WriteCustomElements(item, writer);
- var hasMediaSources = baseItem as IHasMediaSources;
-
- if (hasMediaSources != null)
+ if (baseItem is IHasMediaSources hasMediaSources)
{
AddMediaInfo(hasMediaSources, writer);
}
- var tagsUsed = GetTagsUsed(item);
+ var tagsUsed = GetTagsUsed(item).ToList();
try
{
- AddCustomTags(xmlPath, tagsUsed, writer, Logger, FileSystem);
+ AddCustomTags(xmlPath, tagsUsed, writer, Logger);
}
catch (FileNotFoundException)
{
-
}
catch (IOException)
{
-
}
catch (XmlException ex)
{
@@ -280,7 +291,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
protected abstract void WriteCustomElements(BaseItem item, XmlWriter writer);
public static void AddMediaInfo<T>(T item, XmlWriter writer)
- where T : IHasMediaSources
+ where T : IHasMediaSources
{
writer.WriteStartElement("fileinfo");
writer.WriteStartElement("streamdetails");
@@ -310,17 +321,17 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (stream.BitRate.HasValue)
{
- writer.WriteElementString("bitrate", stream.BitRate.Value.ToString(UsCulture));
+ writer.WriteElementString("bitrate", stream.BitRate.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.Width.HasValue)
{
- writer.WriteElementString("width", stream.Width.Value.ToString(UsCulture));
+ writer.WriteElementString("width", stream.Width.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.Height.HasValue)
{
- writer.WriteElementString("height", stream.Height.Value.ToString(UsCulture));
+ writer.WriteElementString("height", stream.Height.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(stream.AspectRatio))
@@ -333,34 +344,31 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (framerate.HasValue)
{
- writer.WriteElementString("framerate", framerate.Value.ToString(UsCulture));
+ writer.WriteElementString("framerate", framerate.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(stream.Language))
{
// http://web.archive.org/web/20181230211547/https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify
// Web Archive version of link since it's not really explained in the thread.
- writer.WriteElementString("language", RemoveInvalidXMLChars(stream.Language));
+ writer.WriteElementString("language", Regex.Replace(stream.Language, _invalidXMLCharsRegex, string.Empty));
}
var scanType = stream.IsInterlaced ? "interlaced" : "progressive";
- if (!string.IsNullOrEmpty(scanType))
- {
- writer.WriteElementString("scantype", scanType);
- }
+ writer.WriteElementString("scantype", scanType);
if (stream.Channels.HasValue)
{
- writer.WriteElementString("channels", stream.Channels.Value.ToString(UsCulture));
+ writer.WriteElementString("channels", stream.Channels.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.SampleRate.HasValue)
{
- writer.WriteElementString("samplingrate", stream.SampleRate.Value.ToString(UsCulture));
+ writer.WriteElementString("samplingrate", stream.SampleRate.Value.ToString(CultureInfo.InvariantCulture));
}
- writer.WriteElementString("default", stream.IsDefault.ToString());
- writer.WriteElementString("forced", stream.IsForced.ToString());
+ writer.WriteElementString("default", stream.IsDefault.ToString(CultureInfo.InvariantCulture));
+ writer.WriteElementString("forced", stream.IsForced.ToString(CultureInfo.InvariantCulture));
if (stream.Type == MediaStreamType.Video)
{
@@ -369,15 +377,17 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
var timespan = TimeSpan.FromTicks(runtimeTicks.Value);
- writer.WriteElementString("duration", Math.Floor(timespan.TotalMinutes).ToString(UsCulture));
- writer.WriteElementString("durationinseconds", Math.Floor(timespan.TotalSeconds).ToString(UsCulture));
+ writer.WriteElementString(
+ "duration",
+ Math.Floor(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture));
+ writer.WriteElementString(
+ "durationinseconds",
+ Math.Floor(timespan.TotalSeconds).ToString(CultureInfo.InvariantCulture));
}
- var video = item as Video;
-
- if (video != null)
+ if (item is Video video)
{
- //AddChapters(video, builder, itemRepository);
+ // AddChapters(video, builder, itemRepository);
if (video.Video3DFormat.HasValue)
{
@@ -410,32 +420,22 @@ namespace MediaBrowser.XbmcMetadata.Savers
writer.WriteEndElement();
}
- // filters control characters but allows only properly-formed surrogate sequences
- private static Regex _invalidXMLChars = new Regex(
- @"(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]");
-
- /// <summary>
- /// removes any unusual unicode characters that can't be encoded into XML
- /// </summary>
- public static string RemoveInvalidXMLChars(string text)
- {
- if (string.IsNullOrEmpty(text)) return string.Empty;
- return _invalidXMLChars.Replace(text, string.Empty);
- }
-
- public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
-
/// <summary>
/// Adds the common nodes.
/// </summary>
- /// <returns>Task.</returns>
- private void AddCommonNodes(BaseItem item, XmlWriter writer, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepo, IFileSystem fileSystem, IServerConfigurationManager config)
+ private void AddCommonNodes(
+ BaseItem item,
+ XmlWriter writer,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataRepo,
+ IServerConfigurationManager config)
{
var writtenProviderIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var overview = (item.Overview ?? string.Empty)
.StripHtml()
- .Replace("&quot;", "'");
+ .Replace("&quot;", "'", StringComparison.Ordinal);
var options = config.GetNfoConfiguration();
@@ -452,15 +452,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
writer.WriteElementString("plot", overview);
}
- if (item is Video)
- {
- var outline = (item.Tagline ?? string.Empty)
- .StripHtml()
- .Replace("&quot;", "'");
-
- writer.WriteElementString("outline", outline);
- }
- else
+ if (item is not Video)
{
writer.WriteElementString("outline", overview);
}
@@ -474,10 +466,10 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (item.LockedFields.Length > 0)
{
- writer.WriteElementString("lockedfields", string.Join("|", item.LockedFields));
+ writer.WriteElementString("lockedfields", string.Join('|', item.LockedFields));
}
- writer.WriteElementString("dateadded", item.DateCreated.ToLocalTime().ToString(DateAddedFormat));
+ writer.WriteElementString("dateadded", item.DateCreated.ToLocalTime().ToString(DateAddedFormat, CultureInfo.InvariantCulture));
writer.WriteElementString("title", item.Name ?? string.Empty);
@@ -521,12 +513,12 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (item.CommunityRating.HasValue)
{
- writer.WriteElementString("rating", item.CommunityRating.Value.ToString(UsCulture));
+ writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
}
if (item.ProductionYear.HasValue)
{
- writer.WriteElementString("year", item.ProductionYear.Value.ToString(UsCulture));
+ writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
}
var forcedSortName = item.ForcedSortName;
@@ -540,24 +532,21 @@ namespace MediaBrowser.XbmcMetadata.Savers
writer.WriteElementString("mpaa", item.OfficialRating);
}
- var hasAspectRatio = item as IHasAspectRatio;
- if (hasAspectRatio != null)
+ if (item is IHasAspectRatio hasAspectRatio
+ && !string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
{
- if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
- {
- writer.WriteElementString("aspectratio", hasAspectRatio.AspectRatio);
- }
+ writer.WriteElementString("aspectratio", hasAspectRatio.AspectRatio);
}
- var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
+ var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
if (!string.IsNullOrEmpty(tmdbCollection))
{
writer.WriteElementString("collectionnumber", tmdbCollection);
- writtenProviderIds.Add(MetadataProviders.TmdbCollection.ToString());
+ writtenProviderIds.Add(MetadataProvider.TmdbCollection.ToString());
}
- var imdb = item.GetProviderId(MetadataProviders.Imdb);
+ var imdb = item.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdb))
{
if (item is Series)
@@ -568,69 +557,79 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
writer.WriteElementString("imdbid", imdb);
}
- writtenProviderIds.Add(MetadataProviders.Imdb.ToString());
+
+ writtenProviderIds.Add(MetadataProvider.Imdb.ToString());
}
// Series xml saver already saves this
- if (!(item is Series))
+ if (item is not Series)
{
- var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
+ var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
if (!string.IsNullOrEmpty(tvdb))
{
writer.WriteElementString("tvdbid", tvdb);
- writtenProviderIds.Add(MetadataProviders.Tvdb.ToString());
+ writtenProviderIds.Add(MetadataProvider.Tvdb.ToString());
}
}
- var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
+ var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(tmdb))
{
writer.WriteElementString("tmdbid", tmdb);
- writtenProviderIds.Add(MetadataProviders.Tmdb.ToString());
+ writtenProviderIds.Add(MetadataProvider.Tmdb.ToString());
}
if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
{
writer.WriteElementString("language", item.PreferredMetadataLanguage);
}
+
if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
{
writer.WriteElementString("countrycode", item.PreferredMetadataCountryCode);
}
- if (item.PremiereDate.HasValue && !(item is Episode))
+ if (item.PremiereDate.HasValue && item is not Episode)
{
var formatString = options.ReleaseDateFormat;
if (item is MusicArtist)
{
- writer.WriteElementString("formed", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString(
+ "formed",
+ item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
else
{
- writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
- writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString(
+ "premiered",
+ item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
+ writer.WriteElementString(
+ "releasedate",
+ item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
}
if (item.EndDate.HasValue)
{
- if (!(item is Episode))
+ if (item is not Episode)
{
var formatString = options.ReleaseDateFormat;
- writer.WriteElementString("enddate", item.EndDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString(
+ "enddate",
+ item.EndDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
}
if (item.CriticRating.HasValue)
{
- writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(UsCulture));
+ writer.WriteElementString(
+ "criticrating",
+ item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
}
- var hasDisplayOrder = item as IHasDisplayOrder;
-
- if (hasDisplayOrder != null)
+ if (item is IHasDisplayOrder hasDisplayOrder)
{
if (!string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
{
@@ -645,7 +644,9 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
- writer.WriteElementString("runtime", Convert.ToInt64(timespan.TotalMinutes).ToString(UsCulture));
+ writer.WriteElementString(
+ "runtime",
+ Convert.ToInt64(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrWhiteSpace(item.Tagline))
@@ -680,67 +681,67 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- var externalId = item.GetProviderId(MetadataProviders.AudioDbArtist);
+ var externalId = item.GetProviderId(MetadataProvider.AudioDbArtist);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("audiodbartistid", externalId);
- writtenProviderIds.Add(MetadataProviders.AudioDbArtist.ToString());
+ writtenProviderIds.Add(MetadataProvider.AudioDbArtist.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.AudioDbAlbum);
+ externalId = item.GetProviderId(MetadataProvider.AudioDbAlbum);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("audiodbalbumid", externalId);
- writtenProviderIds.Add(MetadataProviders.AudioDbAlbum.ToString());
+ writtenProviderIds.Add(MetadataProvider.AudioDbAlbum.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.Zap2It);
+ externalId = item.GetProviderId(MetadataProvider.Zap2It);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("zap2itid", externalId);
- writtenProviderIds.Add(MetadataProviders.Zap2It.ToString());
+ writtenProviderIds.Add(MetadataProvider.Zap2It.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbum);
+ externalId = item.GetProviderId(MetadataProvider.MusicBrainzAlbum);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("musicbrainzalbumid", externalId);
- writtenProviderIds.Add(MetadataProviders.MusicBrainzAlbum.ToString());
+ writtenProviderIds.Add(MetadataProvider.MusicBrainzAlbum.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist);
+ externalId = item.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("musicbrainzalbumartistid", externalId);
- writtenProviderIds.Add(MetadataProviders.MusicBrainzAlbumArtist.ToString());
+ writtenProviderIds.Add(MetadataProvider.MusicBrainzAlbumArtist.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.MusicBrainzArtist);
+ externalId = item.GetProviderId(MetadataProvider.MusicBrainzArtist);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("musicbrainzartistid", externalId);
- writtenProviderIds.Add(MetadataProviders.MusicBrainzArtist.ToString());
+ writtenProviderIds.Add(MetadataProvider.MusicBrainzArtist.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
+ externalId = item.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("musicbrainzreleasegroupid", externalId);
- writtenProviderIds.Add(MetadataProviders.MusicBrainzReleaseGroup.ToString());
+ writtenProviderIds.Add(MetadataProvider.MusicBrainzReleaseGroup.ToString());
}
- externalId = item.GetProviderId(MetadataProviders.TvRage);
+ externalId = item.GetProviderId(MetadataProvider.TvRage);
if (!string.IsNullOrEmpty(externalId))
{
writer.WriteElementString("tvrageid", externalId);
- writtenProviderIds.Add(MetadataProviders.TvRage.ToString());
+ writtenProviderIds.Add(MetadataProvider.TvRage.ToString());
}
if (item.ProviderIds != null)
@@ -753,9 +754,9 @@ namespace MediaBrowser.XbmcMetadata.Savers
try
{
var tagName = GetTagForProviderKey(providerKey);
- //logger.LogDebug("Verifying custom provider tagname {0}", tagName);
+ Logger.LogDebug("Verifying custom provider tagname {0}", tagName);
XmlConvert.VerifyName(tagName);
- //logger.LogDebug("Saving custom provider tagname {0}", tagName);
+ Logger.LogDebug("Saving custom provider tagname {0}", tagName);
writer.WriteElementString(GetTagForProviderKey(providerKey), providerId);
}
@@ -773,15 +774,14 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (options.SaveImagePathsInNfo)
{
- AddImages(item, writer, libraryManager, config);
+ AddImages(item, writer, libraryManager);
}
AddUserData(item, writer, userManager, userDataRepo, options);
- AddActors(people, writer, libraryManager, fileSystem, config, options.SaveImagePathsInNfo);
+ AddActors(people, writer, libraryManager, options.SaveImagePathsInNfo);
- var folder = item as BoxSet;
- if (folder != null)
+ if (item is BoxSet folder)
{
AddCollectionItems(folder, writer);
}
@@ -822,7 +822,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
return url.Replace(YouTubeWatchUrl, "plugin://plugin.video.youtube/?action=play_video&videoid=", StringComparison.OrdinalIgnoreCase);
}
- private void AddImages(BaseItem item, XmlWriter writer, ILibraryManager libraryManager, IServerConfigurationManager config)
+ private void AddImages(BaseItem item, XmlWriter writer, ILibraryManager libraryManager)
{
writer.WriteStartElement("art");
@@ -830,12 +830,12 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (image != null)
{
- writer.WriteElementString("poster", GetImagePathToSave(image, libraryManager, config));
+ writer.WriteElementString("poster", GetImagePathToSave(image, libraryManager));
}
foreach (var backdrop in item.GetImages(ImageType.Backdrop))
{
- writer.WriteElementString("fanart", GetImagePathToSave(backdrop, libraryManager, config));
+ writer.WriteElementString("fanart", GetImagePathToSave(backdrop, libraryManager));
}
writer.WriteEndElement();
@@ -849,7 +849,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
return;
}
- var user = userManager.GetUserById(userId);
+ var user = userManager.GetUserById(Guid.Parse(userId));
if (user == null)
{
@@ -863,35 +863,49 @@ namespace MediaBrowser.XbmcMetadata.Savers
var userdata = userDataRepo.GetUserData(user, item);
- writer.WriteElementString("isuserfavorite", userdata.IsFavorite.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
+ writer.WriteElementString(
+ "isuserfavorite",
+ userdata.IsFavorite.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (userdata.Rating.HasValue)
{
- writer.WriteElementString("userrating", userdata.Rating.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
+ writer.WriteElementString(
+ "userrating",
+ userdata.Rating.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
}
if (!item.IsFolder)
{
- writer.WriteElementString("playcount", userdata.PlayCount.ToString(UsCulture));
- writer.WriteElementString("watched", userdata.Played.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
+ writer.WriteElementString(
+ "playcount",
+ userdata.PlayCount.ToString(CultureInfo.InvariantCulture));
+ writer.WriteElementString(
+ "watched",
+ userdata.Played.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (userdata.LastPlayedDate.HasValue)
{
- writer.WriteElementString("lastplayed", userdata.LastPlayedDate.Value.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss").ToLowerInvariant());
+ writer.WriteElementString(
+ "lastplayed",
+ userdata.LastPlayedDate.Value.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).ToLowerInvariant());
}
writer.WriteStartElement("resume");
var runTimeTicks = item.RunTimeTicks ?? 0;
- writer.WriteElementString("position", TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds.ToString(UsCulture));
- writer.WriteElementString("total", TimeSpan.FromTicks(runTimeTicks).TotalSeconds.ToString(UsCulture));
+ writer.WriteElementString(
+ "position",
+ TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture));
+ writer.WriteElementString(
+ "total",
+ TimeSpan.FromTicks(runTimeTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture));
}
writer.WriteEndElement();
}
- private void AddActors(List<PersonInfo> people, XmlWriter writer, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager config, bool saveImagePath)
+ private void AddActors(List<PersonInfo> people, XmlWriter writer, ILibraryManager libraryManager, bool saveImagePath)
{
foreach (var person in people)
{
@@ -919,24 +933,21 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (person.SortOrder.HasValue)
{
- writer.WriteElementString("sortorder", person.SortOrder.Value.ToString(UsCulture));
+ writer.WriteElementString(
+ "sortorder",
+ person.SortOrder.Value.ToString(CultureInfo.InvariantCulture));
}
if (saveImagePath)
{
- try
- {
- var personEntity = libraryManager.GetPerson(person.Name);
- var image = personEntity.GetImageInfo(ImageType.Primary, 0);
+ var personEntity = libraryManager.GetPerson(person.Name);
+ var image = personEntity.GetImageInfo(ImageType.Primary, 0);
- if (image != null)
- {
- writer.WriteElementString("thumb", GetImagePathToSave(image, libraryManager, config));
- }
- }
- catch (Exception)
+ if (image != null)
{
- // Already logged in core
+ writer.WriteElementString(
+ "thumb",
+ GetImagePathToSave(image, libraryManager));
}
}
@@ -944,7 +955,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- private string GetImagePathToSave(ItemImageInfo image, ILibraryManager libraryManager, IServerConfigurationManager config)
+ private string GetImagePathToSave(ItemImageInfo image, ILibraryManager libraryManager)
{
if (!image.IsLocalFile)
{
@@ -955,66 +966,61 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
private bool IsPersonType(PersonInfo person, string type)
- {
- return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
- }
+ => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
- private void AddCustomTags(string path, List<string> xmlTagsUsed, XmlWriter writer, ILogger logger, IFileSystem fileSystem)
+ private void AddCustomTags(string path, IReadOnlyCollection<string> xmlTagsUsed, XmlWriter writer, ILogger<BaseNfoSaver> logger)
{
- var settings = XmlReaderSettingsFactory.Create(false);
-
- settings.CheckCharacters = false;
- settings.IgnoreProcessingInstructions = true;
- settings.IgnoreComments = true;
+ var settings = new XmlReaderSettings()
+ {
+ ValidationType = ValidationType.None,
+ CheckCharacters = false,
+ IgnoreProcessingInstructions = true,
+ IgnoreComments = true
+ };
using (var fileStream = File.OpenRead(path))
+ using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
+ using (var reader = XmlReader.Create(streamReader, settings))
{
- using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
+ try
+ {
+ reader.MoveToContent();
+ }
+ catch (Exception ex)
{
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(streamReader, settings))
+ logger.LogError(ex, "Error reading existing xml tags from {Path}.", path);
+ return;
+ }
+
+ reader.Read();
+
+ // Loop through each element
+ while (!reader.EOF && reader.ReadState == ReadState.Interactive)
+ {
+ if (reader.NodeType == XmlNodeType.Element)
{
- try
+ var name = reader.Name;
+
+ if (!_commonTags.Contains(name)
+ && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
{
- reader.MoveToContent();
+ writer.WriteNode(reader, false);
}
- catch (Exception ex)
+ else
{
- logger.LogError(ex, "Error reading existing xml tags from {path}.", path);
- return;
+ reader.Skip();
}
-
+ }
+ else
+ {
reader.Read();
-
- // Loop through each element
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- var name = reader.Name;
-
- if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
- {
- writer.WriteNode(reader, false);
- }
- else
- {
- reader.Skip();
- }
- }
- else
- {
- reader.Read();
- }
- }
}
}
}
}
private string GetTagForProviderKey(string providerKey)
- {
- return providerKey.ToLowerInvariant() + "id";
- }
+ => providerKey.ToLowerInvariant() + "id";
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
index 05a7a44f9..2cd3fdf02 100644
--- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
@@ -7,110 +7,125 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using MediaBrowser.XbmcMetadata.Configuration;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for episodes.
+ /// </summary>
public class EpisodeNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EpisodeNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public EpisodeNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<EpisodeNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- return Path.ChangeExtension(item.Path, ".nfo");
}
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => Path.ChangeExtension(item.Path, ".nfo");
+
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return "episodedetails";
- }
+ => "episodedetails";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
- {
- if (!item.SupportsLocalMetadata)
- {
- return false;
- }
-
- return item is Episode && updateType >= MinimumUpdateType;
- }
+ => item.SupportsLocalMetadata && item is Episode && updateType >= MinimumUpdateType;
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var episode = (Episode)item;
+ writer.WriteElementString("showtitle", episode.SeriesName);
+
if (episode.IndexNumber.HasValue)
{
- writer.WriteElementString("episode", episode.IndexNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("episode", episode.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
}
if (episode.IndexNumberEnd.HasValue)
{
- writer.WriteElementString("episodenumberend", episode.IndexNumberEnd.Value.ToString(UsCulture));
+ writer.WriteElementString("episodenumberend", episode.IndexNumberEnd.Value.ToString(CultureInfo.InvariantCulture));
}
if (episode.ParentIndexNumber.HasValue)
{
- writer.WriteElementString("season", episode.ParentIndexNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("season", episode.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
}
if (episode.PremiereDate.HasValue)
{
var formatString = ConfigurationManager.GetNfoConfiguration().ReleaseDateFormat;
- writer.WriteElementString("aired", episode.PremiereDate.Value.ToLocalTime().ToString(formatString));
+ writer.WriteElementString("aired", episode.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
if (!episode.ParentIndexNumber.HasValue || episode.ParentIndexNumber.Value == 0)
{
if (episode.AirsAfterSeasonNumber.HasValue && episode.AirsAfterSeasonNumber.Value != -1)
{
- writer.WriteElementString("airsafter_season", episode.AirsAfterSeasonNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("airsafter_season", episode.AirsAfterSeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
}
+
if (episode.AirsBeforeEpisodeNumber.HasValue && episode.AirsBeforeEpisodeNumber.Value != -1)
{
- writer.WriteElementString("airsbefore_episode", episode.AirsBeforeEpisodeNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("airsbefore_episode", episode.AirsBeforeEpisodeNumber.Value.ToString(CultureInfo.InvariantCulture));
}
+
if (episode.AirsBeforeSeasonNumber.HasValue && episode.AirsBeforeSeasonNumber.Value != -1)
{
- writer.WriteElementString("airsbefore_season", episode.AirsBeforeSeasonNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("airsbefore_season", episode.AirsBeforeSeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
}
if (episode.AirsBeforeEpisodeNumber.HasValue && episode.AirsBeforeEpisodeNumber.Value != -1)
{
- writer.WriteElementString("displayepisode", episode.AirsBeforeEpisodeNumber.Value.ToString(UsCulture));
+ writer.WriteElementString("displayepisode", episode.AirsBeforeEpisodeNumber.Value.ToString(CultureInfo.InvariantCulture));
}
var specialSeason = episode.AiredSeasonNumber;
if (specialSeason.HasValue && specialSeason.Value != -1)
{
- writer.WriteElementString("displayseason", specialSeason.Value.ToString(UsCulture));
+ writer.WriteElementString("displayseason", specialSeason.Value.ToString(CultureInfo.InvariantCulture));
}
}
}
- private readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "aired",
- "season",
- "episode",
- "episodenumberend",
- "airsafter_season",
- "airsbefore_episode",
- "airsbefore_season",
- "displayseason",
- "displayepisode"
- });
- return list;
- }
+ yield return tag;
+ }
- public EpisodeNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "aired";
+ yield return "season";
+ yield return "episode";
+ yield return "episodenumberend";
+ yield return "airsafter_season";
+ yield return "airsbefore_episode";
+ yield return "airsbefore_season";
+ yield return "displayseason";
+ yield return "displayepisode";
+ yield return "showtitle";
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
index b3bbe539a..21e7e2335 100644
--- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Xml;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -9,61 +10,70 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for movies.
+ /// </summary>
public class MovieNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovieNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public MovieNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<MovieNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- var paths = GetMovieSavePaths(new ItemInfo(item), FileSystem);
- return paths.Count == 0 ? null : paths[0];
}
- public static List<string> GetMovieSavePaths(ItemInfo item, IFileSystem fileSystem)
- {
- var list = new List<string>();
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => GetMovieSavePaths(new ItemInfo(item)).FirstOrDefault() ?? Path.ChangeExtension(item.Path, ".nfo");
+ internal static IEnumerable<string> GetMovieSavePaths(ItemInfo item)
+ {
if (item.VideoType == VideoType.Dvd && !item.IsPlaceHolder)
{
var path = item.ContainingFolderPath;
- list.Add(Path.Combine(path, "VIDEO_TS", "VIDEO_TS.nfo"));
+ yield return Path.Combine(path, "VIDEO_TS", "VIDEO_TS.nfo");
}
if (!item.IsPlaceHolder && (item.VideoType == VideoType.Dvd || item.VideoType == VideoType.BluRay))
{
var path = item.ContainingFolderPath;
- list.Add(Path.Combine(path, Path.GetFileName(path) + ".nfo"));
+ yield return Path.Combine(path, Path.GetFileName(path) + ".nfo");
}
else
{
- // http://kodi.wiki/view/NFO_files/Movies
- // movie.nfo will override all and any .nfo files in the same folder as the media files if you use the "Use foldernames for lookups" setting. If you don't, then moviename.nfo is used
- //if (!item.IsInMixedFolder && item.ItemType == typeof(Movie))
- //{
- // list.Add(Path.Combine(item.ContainingFolderPath, "movie.nfo"));
- //}
-
- list.Add(Path.ChangeExtension(item.Path, ".nfo"));
+ yield return Path.ChangeExtension(item.Path, ".nfo");
if (!item.IsInMixedFolder)
{
- list.Add(Path.Combine(item.ContainingFolderPath, "movie.nfo"));
+ yield return Path.Combine(item.ContainingFolderPath, "movie.nfo");
}
}
-
- return list;
}
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return item is MusicVideo ? "musicvideo" : "movie";
- }
+ => item is MusicVideo ? "musicvideo" : "movie";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
{
if (!item.SupportsLocalMetadata)
@@ -71,10 +81,8 @@ namespace MediaBrowser.XbmcMetadata.Savers
return false;
}
- var video = item as Video;
-
// Check parent for null to avoid running this against things like video backdrops
- if (video != null && !(item is Episode) && !video.ExtraType.HasValue)
+ if (item is Video video && item is not Episode && !video.ExtraType.HasValue)
{
return updateType >= MinimumUpdateType;
}
@@ -82,32 +90,30 @@ namespace MediaBrowser.XbmcMetadata.Savers
return false;
}
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
- var imdb = item.GetProviderId(MetadataProviders.Imdb);
+ var imdb = item.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdb))
{
writer.WriteElementString("id", imdb);
}
- var musicVideo = item as MusicVideo;
-
- if (musicVideo != null)
+ if (item is MusicVideo musicVideo)
{
foreach (var artist in musicVideo.Artists)
{
writer.WriteElementString("artist", artist);
}
+
if (!string.IsNullOrEmpty(musicVideo.Album))
{
writer.WriteElementString("album", musicVideo.Album);
}
}
- var movie = item as Movie;
-
- if (movie != null)
+ if (item is Movie movie)
{
if (!string.IsNullOrEmpty(movie.CollectionName))
{
@@ -116,21 +122,18 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "album",
- "artist",
- "set",
- "id"
- });
- return list;
- }
+ yield return tag;
+ }
- public MovieNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "album";
+ yield return "artist";
+ yield return "set";
+ yield return "id";
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
index 5246bec02..e97550630 100644
--- a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
@@ -7,23 +7,44 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for seasons.
+ /// </summary>
public class SeasonNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeasonNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public SeasonNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<SeasonNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- return Path.Combine(item.Path, "season.nfo");
}
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => Path.Combine(item.Path, "season.nfo");
+
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return "season";
- }
+ => "season";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
{
if (!item.SupportsLocalMetadata)
@@ -31,7 +52,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
return false;
}
- if (!(item is Season))
+ if (item is not Season)
{
return false;
}
@@ -39,6 +60,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
return updateType >= MinimumUpdateType || (updateType >= ItemUpdateType.MetadataImport && File.Exists(GetSavePath(item)));
}
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var season = (Season)item;
@@ -49,27 +71,15 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "seasonnumber"
- });
-
- return list;
- }
+ yield return tag;
+ }
- public SeasonNfoSaver(
- IFileSystem fileSystem,
- IServerConfigurationManager configurationManager,
- ILibraryManager libraryManager,
- IUserManager userManager,
- IUserDataManager userDataManager,
- ILogger logger,
- IXmlReaderSettingsFactory xmlReaderSettingsFactory)
- : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "seasonnumber";
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
index 0ef267a1d..083f22e5d 100644
--- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Xml;
using MediaBrowser.Controller.Configuration;
@@ -7,38 +8,53 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
+ /// <summary>
+ /// Nfo saver for series.
+ /// </summary>
public class SeriesNfoSaver : BaseNfoSaver
{
- protected override string GetLocalSavePath(BaseItem item)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SeriesNfoSaver"/> class.
+ /// </summary>
+ /// <param name="fileSystem">The file system.</param>
+ /// <param name="configurationManager">the server configuration manager.</param>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="userManager">The user manager.</param>
+ /// <param name="userDataManager">The user data manager.</param>
+ /// <param name="logger">The logger.</param>
+ public SeriesNfoSaver(
+ IFileSystem fileSystem,
+ IServerConfigurationManager configurationManager,
+ ILibraryManager libraryManager,
+ IUserManager userManager,
+ IUserDataManager userDataManager,
+ ILogger<SeriesNfoSaver> logger)
+ : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger)
{
- return Path.Combine(item.Path, "tvshow.nfo");
}
+ /// <inheritdoc />
+ protected override string GetLocalSavePath(BaseItem item)
+ => Path.Combine(item.Path, "tvshow.nfo");
+
+ /// <inheritdoc />
protected override string GetRootElementName(BaseItem item)
- {
- return "tvshow";
- }
+ => "tvshow";
+ /// <inheritdoc />
public override bool IsEnabledFor(BaseItem item, ItemUpdateType updateType)
- {
- if (!item.SupportsLocalMetadata)
- {
- return false;
- }
-
- return item is Series && updateType >= MinimumUpdateType;
- }
+ => item.SupportsLocalMetadata && item is Series && updateType >= MinimumUpdateType;
+ /// <inheritdoc />
protected override void WriteCustomElements(BaseItem item, XmlWriter writer)
{
var series = (Series)item;
- var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
+ var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
if (!string.IsNullOrEmpty(tvdb))
{
@@ -52,8 +68,13 @@ namespace MediaBrowser.XbmcMetadata.Savers
: language;
writer.WriteStartElement("url");
- writer.WriteAttributeString("cache", string.Format("{0}.xml", tvdb));
- writer.WriteString(string.Format("http://www.thetvdb.com/api/1D62F2F90030C444/series/{0}/all/{1}.zip", tvdb, language));
+ writer.WriteAttributeString("cache", tvdb + ".xml");
+ writer.WriteString(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "http://www.thetvdb.com/api/1D62F2F90030C444/series/{0}/all/{1}.zip",
+ tvdb,
+ language));
writer.WriteEndElement();
writer.WriteEndElement();
@@ -68,23 +89,20 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
}
- protected override List<string> GetTagsUsed(BaseItem item)
+ /// <inheritdoc />
+ protected override IEnumerable<string> GetTagsUsed(BaseItem item)
{
- var list = base.GetTagsUsed(item);
- list.AddRange(new string[]
+ foreach (var tag in base.GetTagsUsed(item))
{
- "id",
- "episodeguide",
- "season",
- "episode",
- "status",
- "displayorder"
- });
- return list;
- }
+ yield return tag;
+ }
- public SeriesNfoSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) : base(fileSystem, configurationManager, libraryManager, userManager, userDataManager, logger, xmlReaderSettingsFactory)
- {
+ yield return "id";
+ yield return "episodeguide";
+ yield return "season";
+ yield return "episode";
+ yield return "status";
+ yield return "displayorder";
}
}
}
diff --git a/MediaBrowser.sln b/MediaBrowser.sln
deleted file mode 100644
index 62ae58d73..000000000
--- a/MediaBrowser.sln
+++ /dev/null
@@ -1,192 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.26730.3
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Controller", "MediaBrowser.Controller\MediaBrowser.Controller.csproj", "{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Api", "MediaBrowser.Api\MediaBrowser.Api.csproj", "{4FD51AC5-2C16-4308-A993-C3A84F3B4582}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Common", "MediaBrowser.Common\MediaBrowser.Common.csproj", "{9142EEFA-7570-41E1-BFCC-468BB571AF2F}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Model", "MediaBrowser.Model\MediaBrowser.Model.csproj", "{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.WebDashboard", "MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj", "{5624B7B5-B5A7-41D8-9F10-CC5611109619}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Providers", "MediaBrowser.Providers\MediaBrowser.Providers.csproj", "{442B5058-DCAF-4263-BB6A-F21E31120A1B}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenSubtitlesHandler", "OpenSubtitlesHandler\OpenSubtitlesHandler.csproj", "{4A4402D4-E910-443B-B8FC-2C18286A2CA0}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.XbmcMetadata", "MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj", "{23499896-B135-4527-8574-C26E926EA99E}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.LocalMetadata", "MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj", "{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Photos", "Emby.Photos\Emby.Photos.csproj", "{89AB4548-770D-41FD-A891-8DAFF44F452C}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DvdLib", "DvdLib\DvdLib.csproj", "{713F42B5-878E-499D-A878-E4C652B1D5E8}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BDInfo", "BDInfo\BDInfo.csproj", "{88AE38DF-19D7-406F-A6A9-09527719A21E}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Server.Implementations", "Emby.Server.Implementations\Emby.Server.Implementations.csproj", "{E383961B-9356-4D5D-8233-9A1079D03055}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RSSDP", "RSSDP\RSSDP.csproj", "{21002819-C39A-4D3E-BE83-2A276A77FB1F}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Dlna", "Emby.Dlna\Emby.Dlna.csproj", "{805844AB-E92F-45E6-9D99-4F6D48D129A5}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.Nat", "Mono.Nat\Mono.Nat.csproj", "{CB7F2326-6497-4A3D-BA03-48513B17A7BE}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SocketHttpListener", "SocketHttpListener\SocketHttpListener.csproj", "{1D74413B-E7CF-455B-B021-F52BDF881542}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Notifications", "Emby.Notifications\Emby.Notifications.csproj", "{2E030C33-6923-4530-9E54-FA29FA6AD1A9}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Naming", "Emby.Naming\Emby.Naming.csproj", "{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj", "{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IsoMounter", "Emby.IsoMounting\IsoMounter\IsoMounter.csproj", "{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}"
- ProjectSection(SolutionItems) = preProject
- .editorconfig = .editorconfig
- SharedVersion.cs = SharedVersion.cs
- EndProjectSection
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Drawing.Skia", "Jellyfin.Drawing.Skia\Jellyfin.Drawing.Skia.csproj", "{154872D9-6C12-4007-96E3-8F70A58386CE}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.Build.0 = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.Build.0 = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.Build.0 = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.Build.0 = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.Build.0 = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.Build.0 = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.Build.0 = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.Build.0 = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.Build.0 = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.Build.0 = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.Build.0 = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.Build.0 = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.Build.0 = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.Build.0 = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.Build.0 = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.Build.0 = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.Build.0 = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.Build.0 = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.Build.0 = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.Build.0 = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.Build.0 = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.Build.0 = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU
- {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE}
- EndGlobalSection
- GlobalSection(AutomaticVersions) = postSolution
- UpdateAssemblyVersion = True
- UpdateAssemblyFileVersion = True
- UpdateAssemblyInfoVersion = True
- AssemblyVersionSettings = None.None.None.None
- AssemblyFileVersionSettings = None.None.None.None
- AssemblyInfoVersionSettings = None.None.None.None
- UpdatePackageVersion = False
- AssemblyInfoVersionType = SettingsVersion
- InheritWinAppVersionFrom = None
- EndGlobalSection
- GlobalSection(MonoDevelopProperties) = preSolution
- Policies = $0
- $0.StandardHeader = $1
- $1.Text = @### This header should be used to start new files.\n### It provides an explicit per-file license reference that should be present on all new files.\n### To use this header, delete these lines and the following empty line, modify <filename> to\n### the proper full path, and then add new code following the header and a single empty line.\n\n// ${FileName}\n// Part of the Jellyfin project (https://jellyfin.media)\n//\n// All copyright belongs to the Jellyfin contributors; a full list can\n// be found in the file CONTRIBUTORS.md\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, version 2.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n
- $0.DotNetNamingPolicy = $2
- $2.DirectoryNamespaceAssociation = PrefixedHierarchical
- EndGlobalSection
-EndGlobal
diff --git a/MediaBrowser.sln.GhostDoc.xml b/MediaBrowser.sln.GhostDoc.xml
deleted file mode 100644
index eafee0bf5..000000000
--- a/MediaBrowser.sln.GhostDoc.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<GhostDoc>
- <SpellChecker>
- <IncludeExtensions>
- </IncludeExtensions>
- <IgnoreExtensions>
- </IgnoreExtensions>
- <IgnoreFiles>
- </IgnoreFiles>
- </SpellChecker>
- <HelpConfigurations selected="HelpFile">
- <HelpConfiguration name="HelpFile">
- <OutputPath>D:\Development\MediaBrowser\Help</OutputPath>
- <ImageFolderPath />
- <HtmlFormats>
- <HtmlHelp>true</HtmlHelp>
- <MSHelpViewer>false</MSHelpViewer>
- <MSHelp2>false</MSHelp2>
- <Website>false</Website>
- </HtmlFormats>
- <IncludeScopes>
- <Public>true</Public>
- <Internal>false</Internal>
- <Protected>false</Protected>
- <Private>false</Private>
- <Inherited>true</Inherited>
- <EnableTags>false</EnableTags>
- <TagList />
- </IncludeScopes>
- <ResolveCrefLinks>true</ResolveCrefLinks>
- <HeaderText />
- <FooterText />
- <SelectedProjects />
- </HelpConfiguration>
- </HelpConfigurations>
-</GhostDoc>
diff --git a/Mono.Nat/AbstractNatDevice.cs b/Mono.Nat/AbstractNatDevice.cs
deleted file mode 100644
index 1241170c1..000000000
--- a/Mono.Nat/AbstractNatDevice.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Net;
-using System.Threading.Tasks;
-
-namespace Mono.Nat
-{
- public abstract class AbstractNatDevice : INatDevice
- {
- private DateTime lastSeen;
-
- protected AbstractNatDevice()
- {
- }
-
- public abstract IPAddress LocalAddress { get; }
-
- public DateTime LastSeen
- {
- get { return lastSeen; }
- set { lastSeen = value; }
- }
-
- public abstract Task CreatePortMap(Mapping mapping);
- }
-}
diff --git a/Mono.Nat/Enums/ProtocolType.cs b/Mono.Nat/Enums/ProtocolType.cs
deleted file mode 100644
index 54480598d..000000000
--- a/Mono.Nat/Enums/ProtocolType.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Nat
-{
- public enum Protocol
- {
- Tcp,
- Udp
- }
-}
diff --git a/Mono.Nat/EventArgs/DeviceEventArgs.cs b/Mono.Nat/EventArgs/DeviceEventArgs.cs
deleted file mode 100644
index 6358a0c29..000000000
--- a/Mono.Nat/EventArgs/DeviceEventArgs.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Nat
-{
- public class DeviceEventArgs : EventArgs
- {
- private INatDevice device;
-
- public DeviceEventArgs(INatDevice device)
- {
- this.device = device;
- }
-
- public INatDevice Device
- {
- get { return this.device; }
- }
- }
-}
diff --git a/Mono.Nat/INatDevice.cs b/Mono.Nat/INatDevice.cs
deleted file mode 100644
index 6a1509071..000000000
--- a/Mono.Nat/INatDevice.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Net;
-using System.Threading.Tasks;
-
-namespace Mono.Nat
-{
- public interface INatDevice
- {
- Task CreatePortMap (Mapping mapping);
-
- IPAddress LocalAddress { get; }
-
- DateTime LastSeen { get; set; }
- }
-}
diff --git a/Mono.Nat/ISearcher.cs b/Mono.Nat/ISearcher.cs
deleted file mode 100644
index 95c2f2aa9..000000000
--- a/Mono.Nat/ISearcher.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-// Nicholas Terry <nick.i.terry@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-// Copyright (C) 2014 Nicholas Terry
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Net.Sockets;
-using System.Net;
-
-namespace Mono.Nat
-{
- internal interface ISearcher
- {
- event EventHandler<DeviceEventArgs> DeviceFound;
-
- void Search();
- void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint);
- }
-}
diff --git a/Mono.Nat/Mapping.cs b/Mono.Nat/Mapping.cs
deleted file mode 100644
index 5b15d4e14..000000000
--- a/Mono.Nat/Mapping.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Nat
-{
- public class Mapping
- {
- private string description;
- private DateTime expiration;
- private int lifetime;
- private int privatePort;
- private Protocol protocol;
- private int publicPort;
-
- public Mapping(Protocol protocol, int privatePort, int publicPort)
- : this (protocol, privatePort, publicPort, 0)
- {
- }
-
- public Mapping(Protocol protocol, int privatePort, int publicPort, int lifetime)
- {
- this.protocol = protocol;
- this.privatePort = privatePort;
- this.publicPort = publicPort;
- this.lifetime = lifetime;
-
- if (lifetime == int.MaxValue)
- this.expiration = DateTime.MaxValue;
- else if (lifetime == 0)
- this.expiration = DateTime.Now;
- else
- this.expiration = DateTime.Now.AddSeconds (lifetime);
- }
-
- public string Description
- {
- get { return description; }
- set { description = value; }
- }
-
- public Protocol Protocol
- {
- get { return protocol; }
- internal set { protocol = value; }
- }
-
- public int PrivatePort
- {
- get { return privatePort; }
- internal set { privatePort = value; }
- }
-
- public int PublicPort
- {
- get { return publicPort; }
- internal set { publicPort = value; }
- }
-
- public int Lifetime
- {
- get { return lifetime; }
- internal set { lifetime = value; }
- }
-
- public DateTime Expiration
- {
- get { return expiration; }
- internal set { expiration = value; }
- }
-
- public bool IsExpired()
- {
- return expiration < DateTime.Now;
- }
-
- public override bool Equals(object obj)
- {
- var other = obj as Mapping;
- return other == null ? false : this.protocol == other.protocol &&
- this.privatePort == other.privatePort && this.publicPort == other.publicPort;
- }
-
- public override int GetHashCode()
- {
- return this.protocol.GetHashCode() ^ this.privatePort.GetHashCode() ^ this.publicPort.GetHashCode();
- }
-
- public override string ToString()
- {
- return String.Format( "Protocol: {0}, Public Port: {1}, Private Port: {2}, Description: {3}, Expiration: {4}, Lifetime: {5}",
- this.protocol, this.publicPort, this.privatePort, this.description, this.expiration, this.lifetime );
- }
- }
-}
diff --git a/Mono.Nat/Mono.Nat.csproj b/Mono.Nat/Mono.Nat.csproj
deleted file mode 100644
index edfd5c9bb..000000000
--- a/Mono.Nat/Mono.Nat.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/Mono.Nat/NatManager.cs b/Mono.Nat/NatManager.cs
deleted file mode 100644
index 3ed01a6b3..000000000
--- a/Mono.Nat/NatManager.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using System;
-using System.Net;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Dlna;
-using Microsoft.Extensions.Logging;
-using System.Linq;
-
-namespace Mono.Nat
-{
- public class NatManager : IDisposable
- {
- public event EventHandler<DeviceEventArgs> DeviceFound;
-
- private List<ISearcher> controllers = new List<ISearcher>();
-
- private ILogger Logger;
- private IHttpClient HttpClient;
-
- public NatManager(ILogger logger, IHttpClient httpClient)
- {
- Logger = logger;
- HttpClient = httpClient;
- }
-
- private object _runSyncLock = new object();
- public void StartDiscovery()
- {
- lock (_runSyncLock)
- {
- if (controllers.Count > 0)
- {
- return;
- }
-
- controllers.Add(new PmpSearcher(Logger));
-
- foreach (var searcher in controllers)
- {
- searcher.DeviceFound += Searcher_DeviceFound;
- }
- }
- }
-
- public void StopDiscovery()
- {
- lock (_runSyncLock)
- {
- var disposables = controllers.OfType<IDisposable>().ToList();
- controllers.Clear();
-
- foreach (var disposable in disposables)
- {
- disposable.Dispose();
- }
- }
- }
-
- public void Dispose()
- {
- StopDiscovery();
- }
-
- public Task Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint, NatProtocol protocol)
- {
- switch (protocol)
- {
- case NatProtocol.Upnp:
- var searcher = new UpnpSearcher(Logger, HttpClient);
- searcher.DeviceFound += Searcher_DeviceFound;
- return searcher.Handle(localAddress, deviceInfo, endpoint);
- default:
- throw new ArgumentException("Unexpected protocol: " + protocol);
- }
- }
-
- private void Searcher_DeviceFound(object sender, DeviceEventArgs e)
- {
- if (DeviceFound != null)
- {
- DeviceFound(sender, e);
- }
- }
- }
-}
diff --git a/Mono.Nat/NatProtocol.cs b/Mono.Nat/NatProtocol.cs
deleted file mode 100644
index 2768f133c..000000000
--- a/Mono.Nat/NatProtocol.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace Mono.Nat
-{
- public enum NatProtocol
- {
- Upnp = 0,
- Pmp = 1
- }
-}
diff --git a/Mono.Nat/Pmp/PmpConstants.cs b/Mono.Nat/Pmp/PmpConstants.cs
deleted file mode 100644
index 83fa8e07c..000000000
--- a/Mono.Nat/Pmp/PmpConstants.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-//
-// Authors:
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Nat.Pmp
-{
- internal static class PmpConstants
- {
- public const byte Version = (byte)0;
-
- public const byte OperationCode = (byte)0;
- public const byte OperationCodeUdp = (byte)1;
- public const byte OperationCodeTcp = (byte)2;
- public const byte ServerNoop = (byte)128;
-
- public const int ClientPort = 5350;
- public const int ServerPort = 5351;
-
- public const int RetryDelay = 250;
- public const int RetryAttempts = 9;
-
- public const int RecommendedLeaseTime = 60 * 60;
- public const int DefaultLeaseTime = RecommendedLeaseTime;
-
- public const short ResultCodeSuccess = 0;
- public const short ResultCodeUnsupportedVersion = 1;
- public const short ResultCodeNotAuthorized = 2;
- public const short ResultCodeNetworkFailure = 3;
- public const short ResultCodeOutOfResources = 4;
- public const short ResultCodeUnsupportedOperationCode = 5;
- }
-}
diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs
deleted file mode 100644
index 95bd72a6c..000000000
--- a/Mono.Nat/Pmp/PmpNatDevice.cs
+++ /dev/null
@@ -1,217 +0,0 @@
-//
-// Authors:
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Extensions;
-using Microsoft.Extensions.Logging;
-
-namespace Mono.Nat.Pmp
-{
- internal sealed class PmpNatDevice : AbstractNatDevice, IEquatable<PmpNatDevice>
- {
- private IPAddress localAddress;
- private IPAddress publicAddress;
- private ILogger _logger;
-
- internal PmpNatDevice(IPAddress localAddress, IPAddress publicAddress, ILogger logger)
- {
- if (localAddress == null)
- {
- throw new ArgumentNullException(nameof(localAddress));
- }
-
- this.localAddress = localAddress;
- this.publicAddress = publicAddress;
- _logger = logger;
- }
-
- public override IPAddress LocalAddress
- {
- get { return localAddress; }
- }
-
- public override Task CreatePortMap(Mapping mapping)
- {
- return InternalCreatePortMapAsync(mapping, true);
- }
-
- public override bool Equals(object obj)
- {
- var device = obj as PmpNatDevice;
- return (device == null) ? false : this.Equals(device);
- }
-
- public override int GetHashCode()
- {
- return this.publicAddress.GetHashCode();
- }
-
- public bool Equals(PmpNatDevice other)
- {
- return (other == null) ? false : this.publicAddress.Equals(other.publicAddress);
- }
-
- private async Task<Mapping> InternalCreatePortMapAsync(Mapping mapping, bool create)
- {
- var package = new List<byte>();
-
- package.Add(PmpConstants.Version);
- package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
- package.Add(0); //reserved
- package.Add(0); //reserved
- package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)mapping.PrivatePort)));
- package.AddRange(
- BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0));
- package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime)));
-
- try
- {
- byte[] buffer = package.ToArray();
- int attempt = 0;
- int delay = PmpConstants.RetryDelay;
-
- using (var udpClient = new UdpClient())
- {
- var cancellationTokenSource = new CancellationTokenSource();
-
- while (attempt < PmpConstants.RetryAttempts)
- {
- await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(LocalAddress, PmpConstants.ServerPort));
-
- if (attempt == 0)
- {
- await Task.Run(() => CreatePortMapListen(udpClient, mapping, cancellationTokenSource.Token));
- }
-
- attempt++;
- delay *= 2;
- await Task.Delay(delay).ConfigureAwait(false);
- }
-
- cancellationTokenSource.Cancel();
- }
- }
- catch (OperationCanceledException)
- {
-
- }
- catch (Exception e)
- {
- string type = create ? "create" : "delete";
- string message = String.Format("Failed to {0} portmap (protocol={1}, private port={2}) {3}",
- type,
- mapping.Protocol,
- mapping.PrivatePort,
- e.Message);
- _logger.LogDebug(message);
- throw e;
- }
-
- return mapping;
- }
-
- private async void CreatePortMapListen(UdpClient udpClient, Mapping mapping, CancellationToken cancellationToken)
- {
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- var result = await udpClient.ReceiveAsync().ConfigureAwait(false);
- var endPoint = result.RemoteEndPoint;
- byte[] data = data = result.Buffer;
-
- if (data.Length < 16)
- continue;
-
- if (data[0] != PmpConstants.Version)
- continue;
-
- var opCode = (byte)(data[1] & 127);
-
- var protocol = Protocol.Tcp;
- if (opCode == PmpConstants.OperationCodeUdp)
- protocol = Protocol.Udp;
-
- short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2));
- int epoch = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4));
-
- short privatePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8));
- short publicPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10));
-
- var lifetime = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12));
-
- if (privatePort < 0 || publicPort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
- {
- var errors = new[]
- {
- "Success",
- "Unsupported Version",
- "Not Authorized/Refused (e.g. box supports mapping, but user has turned feature off)"
- ,
- "Network Failure (e.g. NAT box itself has not obtained a DHCP lease)",
- "Out of resources (NAT box cannot create any more mappings at this time)",
- "Unsupported opcode"
- };
-
- var errorMsg = errors[resultCode];
- _logger.LogDebug("Error in CreatePortMapListen: " + errorMsg);
- return;
- }
-
- if (lifetime == 0) return; //mapping was deleted
-
- //mapping was created
- //TODO: verify that the private port+protocol are a match
- mapping.PublicPort = publicPort;
- mapping.Protocol = protocol;
- mapping.Expiration = DateTime.Now.AddSeconds(lifetime);
- return;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in CreatePortMapListen");
- return;
- }
- }
- }
-
- /// <summary>
- /// Overridden.
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return String.Format("PmpNatDevice - Local Address: {0}, Public IP: {1}, Last Seen: {2}",
- this.localAddress, this.publicAddress, this.LastSeen);
- }
- }
-}
diff --git a/Mono.Nat/Pmp/PmpSearcher.cs b/Mono.Nat/Pmp/PmpSearcher.cs
deleted file mode 100644
index 46c2e9d80..000000000
--- a/Mono.Nat/Pmp/PmpSearcher.cs
+++ /dev/null
@@ -1,235 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-// Nicholas Terry <nick.i.terry@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-// Copyright (C) 2014 Nicholas Terry
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Net;
-using Mono.Nat.Pmp;
-using System.Net.NetworkInformation;
-using System.Net.Sockets;
-using System.Threading.Tasks;
-using Microsoft.Extensions.Logging;
-using System.Linq;
-
-namespace Mono.Nat
-{
- internal class PmpSearcher : ISearcher, IDisposable
- {
- private ILogger _logger;
-
- private int timeout = 250;
- private DateTime nextSearch;
- public event EventHandler<DeviceEventArgs> DeviceFound;
-
- public PmpSearcher(ILogger logger)
- {
- _logger = logger;
-
- CreateSocketsAndAddGateways();
- }
-
- public void Dispose()
- {
- var list = sockets.ToList();
- sockets.Clear();
-
- foreach (var s in list)
- {
- using (s)
- {
- s.Close();
- }
- }
- }
-
- private List<UdpClient> sockets;
- private Dictionary<UdpClient, List<IPEndPoint>> gatewayLists;
-
- private void CreateSocketsAndAddGateways()
- {
- sockets = new List<UdpClient>();
- gatewayLists = new Dictionary<UdpClient, List<IPEndPoint>>();
-
- try
- {
- foreach (var n in NetworkInterface.GetAllNetworkInterfaces())
- {
- if (n.OperationalStatus != OperationalStatus.Up && n.OperationalStatus != OperationalStatus.Unknown)
- continue;
- IPInterfaceProperties properties = n.GetIPProperties();
- var gatewayList = new List<IPEndPoint>();
-
- foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
- {
- if (gateway.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- gatewayList.Add(new IPEndPoint(gateway.Address, PmpConstants.ServerPort));
- }
- }
- if (gatewayList.Count == 0)
- {
- /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
- foreach (var gw2 in properties.DnsAddresses)
- {
- if (gw2.AddressFamily == AddressFamily.InterNetwork)
- {
- gatewayList.Add(new IPEndPoint(gw2, PmpConstants.ServerPort));
- }
- }
- foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
- {
- if (/*unicast.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
- && unicast.AddressPreferredLifetime != UInt32.MaxValue
- && */unicast.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- var bytes = unicast.Address.GetAddressBytes();
- bytes[3] = 1;
- gatewayList.Add(new IPEndPoint(new IPAddress(bytes), PmpConstants.ServerPort));
- }
- }
- }
-
- if (gatewayList.Count > 0)
- {
- foreach (var address in properties.UnicastAddresses)
- {
- if (address.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- UdpClient client;
-
- try
- {
- client = new UdpClient(new IPEndPoint(address.Address, 0));
- }
- catch (SocketException)
- {
- continue; // Move on to the next address.
- }
-
- gatewayLists.Add(client, gatewayList);
- sockets.Add(client);
- }
- }
- }
- }
- }
- catch (Exception)
- {
- // NAT-PMP does not use multicast, so there isn't really a good fallback.
- }
- }
-
- public async void Search()
- {
- foreach (UdpClient s in sockets)
- {
- try
- {
- await Search(s).ConfigureAwait(false);
- }
- catch
- {
- // Ignore any search errors
- }
- }
- }
-
- async Task Search(UdpClient client)
- {
- // Sort out the time for the next search first. The spec says the
- // timeout should double after each attempt. Once it reaches 64 seconds
- // (and that attempt fails), assume no devices available
- nextSearch = DateTime.Now.AddMilliseconds(timeout);
- timeout *= 2;
-
- // We've tried 9 times as per spec, try searching again in 5 minutes
- if (timeout == 128 * 1000)
- {
- timeout = 250;
- nextSearch = DateTime.Now.AddMinutes(10);
- return;
- }
-
- // The nat-pmp search message. Must be sent to GatewayIP:53531
- byte[] buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
- foreach (IPEndPoint gatewayEndpoint in gatewayLists[client])
- {
- await client.SendAsync(buffer, buffer.Length, gatewayEndpoint).ConfigureAwait(false);
- }
- }
-
- bool IsSearchAddress(IPAddress address)
- {
- foreach (var gatewayList in gatewayLists.Values)
- foreach (var gatewayEndpoint in gatewayList)
- if (gatewayEndpoint.Address.Equals(address))
- return true;
- return false;
- }
-
- public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
- {
- if (!IsSearchAddress(endpoint.Address))
- return;
- if (response.Length != 12)
- return;
- if (response[0] != PmpConstants.Version)
- return;
- if (response[1] != PmpConstants.ServerNoop)
- return;
- int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
- if (errorcode != 0)
- _logger.LogDebug("Non zero error: {0}", errorcode);
-
- var publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
- nextSearch = DateTime.Now.AddMinutes(5);
- timeout = 250;
-
- OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(endpoint.Address, publicIp, _logger)));
- }
-
- public DateTime NextSearch
- {
- get { return nextSearch; }
- }
- private void OnDeviceFound(DeviceEventArgs args)
- {
- if (DeviceFound != null)
- DeviceFound(this, args);
- }
-
- public NatProtocol Protocol
- {
- get { return NatProtocol.Pmp; }
- }
- }
-}
diff --git a/Mono.Nat/Properties/AssemblyInfo.cs b/Mono.Nat/Properties/AssemblyInfo.cs
deleted file mode 100644
index ea1c9dee6..000000000
--- a/Mono.Nat/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Mono.Nat")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2006 Alan McGovern. Copyright © 2007 Ben Motmans. Code releases unde the MIT license. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
deleted file mode 100644
index 72b4c2b25..000000000
--- a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Diagnostics;
-using System.Net;
-using MediaBrowser.Common.Net;
-using Microsoft.Extensions.Logging;
-
-namespace Mono.Nat.Upnp
-{
- internal class GetServicesMessage : MessageBase
- {
- private string servicesDescriptionUrl;
- private EndPoint hostAddress;
- private readonly ILogger _logger;
-
- public GetServicesMessage(string description, EndPoint hostAddress, ILogger logger)
- : base(null)
- {
- if (string.IsNullOrEmpty(description))
- _logger.LogWarning("Description is null");
-
- if (hostAddress == null)
- _logger.LogWarning("hostaddress is null");
-
- this.servicesDescriptionUrl = description;
- this.hostAddress = hostAddress;
- _logger = logger;
- }
-
- public override string Method
- {
- get
- {
- return "GET";
- }
- }
-
- public override HttpRequestOptions Encode()
- {
- var req = new HttpRequestOptions();
-
- // The periodic request logging may keep some devices awake
- req.LogRequestAsDebug = true;
- req.LogErrors = false;
-
- req.Url = "http://" + this.hostAddress.ToString() + this.servicesDescriptionUrl;
- req.RequestHeaders.Add("ACCEPT-LANGUAGE", "en");
-
- return req;
- }
- }
-}
diff --git a/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs b/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs
deleted file mode 100644
index 7d6844e32..000000000
--- a/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System.Net;
-using System.IO;
-using System.Globalization;
-using System.Text;
-using System.Xml;
-using MediaBrowser.Common.Net;
-
-namespace Mono.Nat.Upnp
-{
- internal class CreatePortMappingMessage : MessageBase
- {
- #region Private Fields
-
- private IPAddress localIpAddress;
- private Mapping mapping;
-
- #endregion
-
-
- #region Constructors
- public CreatePortMappingMessage(Mapping mapping, IPAddress localIpAddress, UpnpNatDevice device)
- : base(device)
- {
- this.mapping = mapping;
- this.localIpAddress = localIpAddress;
- }
- #endregion
-
- public override HttpRequestOptions Encode()
- {
- var culture = CultureInfo.InvariantCulture;
-
- var builder = new StringBuilder(256);
- XmlWriter writer = CreateWriter(builder);
-
- WriteFullElement(writer, "NewRemoteHost", string.Empty);
- WriteFullElement(writer, "NewExternalPort", this.mapping.PublicPort.ToString(culture));
- WriteFullElement(writer, "NewProtocol", this.mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP");
- WriteFullElement(writer, "NewInternalPort", this.mapping.PrivatePort.ToString(culture));
- WriteFullElement(writer, "NewInternalClient", this.localIpAddress.ToString());
- WriteFullElement(writer, "NewEnabled", "1");
- WriteFullElement(writer, "NewPortMappingDescription", string.IsNullOrEmpty(mapping.Description) ? "Mono.Nat" : mapping.Description);
- WriteFullElement(writer, "NewLeaseDuration", mapping.Lifetime.ToString());
-
- writer.Flush();
- return CreateRequest("AddPortMapping", builder.ToString());
- }
- }
-}
diff --git a/Mono.Nat/Upnp/Messages/UpnpMessage.cs b/Mono.Nat/Upnp/Messages/UpnpMessage.cs
deleted file mode 100644
index 1151dd997..000000000
--- a/Mono.Nat/Upnp/Messages/UpnpMessage.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-//
-// Copyright (C) 2006 Alan McGovern
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Diagnostics;
-using System.Xml;
-using System.Net;
-using System.IO;
-using System.Text;
-using System.Globalization;
-using MediaBrowser.Common.Net;
-
-namespace Mono.Nat.Upnp
-{
- internal abstract class MessageBase
- {
- protected UpnpNatDevice device;
-
- protected MessageBase(UpnpNatDevice device)
- {
- this.device = device;
- }
-
- protected HttpRequestOptions CreateRequest(string upnpMethod, string methodParameters)
- {
- string ss = "http://" + this.device.HostEndPoint.ToString() + this.device.ControlUrl;
-
- var req = new HttpRequestOptions();
- req.LogErrors = false;
-
- // The periodic request logging may keep some devices awake
- req.LogRequestAsDebug = true;
-
- req.Url = ss;
- req.EnableKeepAlive = false;
- req.RequestContentType = "text/xml";
- req.AppendCharsetToMimeType = true;
- req.RequestHeaders.Add("SOAPACTION", "\"" + device.ServiceType + "#" + upnpMethod + "\"");
-
- string bodyString = "<s:Envelope "
- + "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
- + "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>"
- + "<u:" + upnpMethod + " "
- + "xmlns:u=\"" + device.ServiceType + "\">"
- + methodParameters
- + "</u:" + upnpMethod + ">"
- + "</s:Body>"
- + "</s:Envelope>\r\n\r\n";
-
- req.RequestContentBytes = System.Text.Encoding.UTF8.GetBytes(bodyString);
- return req;
- }
-
- public abstract HttpRequestOptions Encode();
-
- public virtual string Method
- {
- get { return "POST"; }
- }
-
- protected void WriteFullElement(XmlWriter writer, string element, string value)
- {
- writer.WriteStartElement(element);
- writer.WriteString(value);
- writer.WriteEndElement();
- }
-
- protected XmlWriter CreateWriter(StringBuilder sb)
- {
- var settings = new XmlWriterSettings();
- settings.ConformanceLevel = ConformanceLevel.Fragment;
- return XmlWriter.Create(sb, settings);
- }
- }
-}
diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
deleted file mode 100644
index 3b54c4680..000000000
--- a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-// Nicholas Terry <nick.i.terry@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-// Copyright (C) 2014 Nicholas Terry
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Net;
-using Mono.Nat.Upnp;
-using System.Diagnostics;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using MediaBrowser.Common.Net;
-using Microsoft.Extensions.Logging;
-using MediaBrowser.Model.Dlna;
-using System.Threading.Tasks;
-
-namespace Mono.Nat
-{
- internal class UpnpSearcher : ISearcher
- {
- public event EventHandler<DeviceEventArgs> DeviceFound;
-
- private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
-
- public UpnpSearcher(ILogger logger, IHttpClient httpClient)
- {
- _logger = logger;
- _httpClient = httpClient;
- }
-
- public void Search()
- {
- }
-
- public async Task Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint)
- {
- if (localAddress == null)
- {
- throw new ArgumentNullException(nameof(localAddress));
- }
-
- try
- {
- /* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection.
- * Any other device type is no good to us for this purpose. See the IGP overview paper
- * page 5 for an overview of device types and their hierarchy.
- * http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */
-
- /* TODO: Currently we are assuming version 1 of the protocol. We should figure out which
- * version it is and apply the correct URN. */
-
- /* Some routers don't correctly implement the version ID on the URN, so we only search for the type
- * prefix. */
-
- // We have an internet gateway device now
- var d = new UpnpNatDevice(localAddress, deviceInfo, endpoint, string.Empty, _logger, _httpClient);
-
- await d.GetServicesList().ConfigureAwait(false);
-
- OnDeviceFound(new DeviceEventArgs(d));
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error decoding device response");
- }
- }
-
- public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
- {
- }
-
- private void OnDeviceFound(DeviceEventArgs args)
- {
- if (DeviceFound != null)
- DeviceFound(this, args);
- }
-
- public NatProtocol Protocol
- {
- get { return NatProtocol.Upnp; }
- }
- }
-}
diff --git a/Mono.Nat/Upnp/UpnpNatDevice.cs b/Mono.Nat/Upnp/UpnpNatDevice.cs
deleted file mode 100644
index fd408ee63..000000000
--- a/Mono.Nat/Upnp/UpnpNatDevice.cs
+++ /dev/null
@@ -1,269 +0,0 @@
-//
-// Authors:
-// Alan McGovern alan.mcgovern@gmail.com
-// Ben Motmans <ben.motmans@gmail.com>
-//
-// Copyright (C) 2006 Alan McGovern
-// Copyright (C) 2007 Ben Motmans
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Net;
-using System.Xml;
-using System.Text;
-using System.Diagnostics;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using Microsoft.Extensions.Logging;
-using MediaBrowser.Model.Dlna;
-
-namespace Mono.Nat.Upnp
-{
- public sealed class UpnpNatDevice : AbstractNatDevice, IEquatable<UpnpNatDevice>
- {
- private EndPoint hostEndPoint;
- private IPAddress localAddress;
- private string serviceDescriptionUrl;
- private string controlUrl;
- private string serviceType;
- private readonly ILogger _logger;
- private readonly IHttpClient _httpClient;
-
- public override IPAddress LocalAddress
- {
- get { return localAddress; }
- }
-
- internal UpnpNatDevice(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint hostEndPoint, string serviceType, ILogger logger, IHttpClient httpClient)
- {
- if (localAddress == null)
- {
- throw new ArgumentNullException(nameof(localAddress));
- }
-
- this.LastSeen = DateTime.Now;
- this.localAddress = localAddress;
-
- // Split the string at the "location" section so i can extract the ipaddress and service description url
- string locationDetails = deviceInfo.Location.ToString();
- this.serviceType = serviceType;
- _logger = logger;
- _httpClient = httpClient;
-
- // Make sure we have no excess whitespace
- locationDetails = locationDetails.Trim();
-
- // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
- // Are we going to get addresses with the "http://" attached?
- if (locationDetails.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogDebug("Found device at: {0}", locationDetails);
- // This bit strings out the "http://" from the string
- locationDetails = locationDetails.Substring(7);
-
- this.hostEndPoint = hostEndPoint;
-
- // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
- // and port information
- this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
- }
- else
- {
- _logger.LogDebug("Couldn't decode address. Please send following string to the developer: ");
- }
- }
-
- public async Task GetServicesList()
- {
- // Create a HTTPWebRequest to download the list of services the device offers
- var message = new GetServicesMessage(this.serviceDescriptionUrl, this.hostEndPoint, _logger);
-
- using (var response = await _httpClient.SendAsync(message.Encode(), message.Method).ConfigureAwait(false))
- {
- OnServicesReceived(response);
- }
- }
-
- private void OnServicesReceived(HttpResponseInfo response)
- {
- int abortCount = 0;
- int bytesRead = 0;
- byte[] buffer = new byte[10240];
- var servicesXml = new StringBuilder();
- var xmldoc = new XmlDocument();
-
- using (var s = response.Content)
- {
- if (response.StatusCode != HttpStatusCode.OK)
- {
- _logger.LogDebug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
- return; // FIXME: This the best thing to do??
- }
-
- while (true)
- {
- bytesRead = s.Read(buffer, 0, buffer.Length);
- servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
- try
- {
- xmldoc.LoadXml(servicesXml.ToString());
- break;
- }
- catch (XmlException)
- {
- // If we can't receive the entire XML within 500ms, then drop the connection
- // Unfortunately not all routers supply a valid ContentLength (mine doesn't)
- // so this hack is needed to keep testing our recieved data until it gets successfully
- // parsed by the xmldoc. Without this, the code will never pick up my router.
- if (abortCount++ > 50)
- {
- return;
- }
- _logger.LogDebug("{0}: Couldn't parse services list", HostEndPoint);
- System.Threading.Thread.Sleep(10);
- }
- }
-
- var ns = new XmlNamespaceManager(xmldoc.NameTable);
- ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
- XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns);
-
- foreach (XmlNode node in nodes)
- {
- //Go through each service there
- foreach (XmlNode service in node.ChildNodes)
- {
- //If the service is a WANIPConnection, then we have what we want
- string type = service["serviceType"].InnerText;
- _logger.LogDebug("{0}: Found service: {1}", HostEndPoint, type);
-
- // TODO: Add support for version 2 of UPnP.
- if (string.Equals(type, "urn:schemas-upnp-org:service:WANPPPConnection:1", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(type, "urn:schemas-upnp-org:service:WANIPConnection:1", StringComparison.OrdinalIgnoreCase))
- {
- this.controlUrl = service["controlURL"].InnerText;
- _logger.LogDebug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
-
- Uri u;
- if (Uri.TryCreate(controlUrl, UriKind.RelativeOrAbsolute, out u))
- {
- if (u.IsAbsoluteUri)
- {
- var old = hostEndPoint;
- IPAddress parsedHostIpAddress;
- if (IPAddress.TryParse(u.Host, out parsedHostIpAddress))
- {
- this.hostEndPoint = new IPEndPoint(parsedHostIpAddress, u.Port);
- //_logger.LogDebug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
- this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
- //_logger.LogDebug("{0}: New control url: {1}", HostEndPoint, controlUrl);
- }
- }
- }
- else
- {
- _logger.LogDebug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
- }
- return;
- }
- }
- }
-
- //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding
- //So we don't invoke the callback, so this device is never added to our lists
- }
- }
-
- /// <summary>
- /// The EndPoint that the device is at
- /// </summary>
- internal EndPoint HostEndPoint
- {
- get { return this.hostEndPoint; }
- }
-
- /// <summary>
- /// The relative url of the xml file that describes the list of services is at
- /// </summary>
- internal string ServiceDescriptionUrl
- {
- get { return this.serviceDescriptionUrl; }
- }
-
- /// <summary>
- /// The relative url that we can use to control the port forwarding
- /// </summary>
- internal string ControlUrl
- {
- get { return this.controlUrl; }
- }
-
- /// <summary>
- /// The service type we're using on the device
- /// </summary>
- public string ServiceType
- {
- get { return serviceType; }
- }
-
- public override async Task CreatePortMap(Mapping mapping)
- {
- var message = new CreatePortMappingMessage(mapping, localAddress, this);
- using (await _httpClient.SendAsync(message.Encode(), message.Method).ConfigureAwait(false))
- {
-
- }
- }
-
- public override bool Equals(object obj)
- {
- var device = obj as UpnpNatDevice;
- return (device == null) ? false : this.Equals((device));
- }
-
-
- public bool Equals(UpnpNatDevice other)
- {
- return (other == null) ? false : (this.hostEndPoint.Equals(other.hostEndPoint)
- //&& this.controlUrl == other.controlUrl
- && this.serviceDescriptionUrl == other.serviceDescriptionUrl);
- }
-
- public override int GetHashCode()
- {
- return (this.hostEndPoint.GetHashCode() ^ this.controlUrl.GetHashCode() ^ this.serviceDescriptionUrl.GetHashCode());
- }
-
- /// <summary>
- /// Overridden.
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- //GetExternalIP is blocking and can throw exceptions, can't use it here.
- return String.Format(
- "UpnpNatDevice - EndPoint: {0}, External IP: {1}, Control Url: {2}, Service Description Url: {3}, Service Type: {4}, Last Seen: {5}",
- this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen);
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Console/OSHConsole.cs b/OpenSubtitlesHandler/Console/OSHConsole.cs
deleted file mode 100644
index 396b28cbc..000000000
--- a/OpenSubtitlesHandler/Console/OSHConsole.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System;
-
-namespace OpenSubtitlesHandler.Console
-{
- public class OSHConsole
- {
- /// <summary>
- /// Write line to the console and raise the "LineWritten" event
- /// </summary>
- ///
- /// <param name="text">The debug line</param>
- /// <param name="code">The status</param>
- public static void WriteLine(string text, DebugCode code = DebugCode.None)
- {
- if (LineWritten != null)
- LineWritten(null, new DebugEventArgs(text, code));
- }
- /// <summary>
- /// Update the last written line
- /// </summary>
- /// <param name="text">The debug line</param>
- /// <param name="code">The status</param>
- public static void UpdateLine(string text, DebugCode code = DebugCode.None)
- {
- if (UpdateLastLine != null)
- UpdateLastLine(null, new DebugEventArgs(text, code));
- }
-
- public static event EventHandler<DebugEventArgs> LineWritten;
- public static event EventHandler<DebugEventArgs> UpdateLastLine;
- }
- public enum DebugCode
- {
- None,
- Good,
- Warning,
- Error
- }
- /// <summary>
- /// Console Debug Args
- /// </summary>
- public class DebugEventArgs : EventArgs
- {
- public DebugCode Code { get; private set; }
- public string Text { get; private set; }
-
- /// <summary>
- /// Console Debug Args
- /// </summary>
- /// <param name="text">The debug line</param>
- /// <param name="code">The status</param>
- public DebugEventArgs(string text, DebugCode code)
- {
- this.Text = text;
- this.Code = code;
- }
- }
- public struct DebugLine
- {
- public DebugLine(string debugLine, DebugCode status)
- {
- this.debugLine = debugLine;
- this.status = status;
- }
- string debugLine;
- DebugCode status;
-
- public string Text
- { get { return debugLine; } set { debugLine = value; } }
- public DebugCode Code
- { get { return status; } set { status = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Interfaces/IMethodResponse.cs b/OpenSubtitlesHandler/Interfaces/IMethodResponse.cs
deleted file mode 100644
index 3450beff5..000000000
--- a/OpenSubtitlesHandler/Interfaces/IMethodResponse.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// When you call a method to communicate with OpenSubtitles server, that method should return this response with the reuired information.
- /// </summary>
- public abstract class IMethodResponse
- {
- public IMethodResponse() { LoadAttributes(); }
- public IMethodResponse(string name, string message)
- {
- this.name = name;
- this.message = message;
- }
- protected string name;
- protected string message;
- protected double seconds;
- protected string status;
-
- protected void LoadAttributes()
- {
- //foreach (Attribute attr in Attribute.GetCustomAttributes(this.GetType()))
- //{
- // if (attr.GetType() == typeof(MethodResponseDescription))
- // {
- // this.name = ((MethodResponseDescription)attr).Name;
- // this.message = ((MethodResponseDescription)attr).Message;
- // break;
- // }
- //}
- }
-
- [Description("The name of this response"), Category("MethodResponse")]
- public virtual string Name { get { return name; } set { name = value; } }
- [Description("The message about this response"), Category("MethodResponse")]
- public virtual string Message { get { return message; } set { message = value; } }
- [Description("Time taken to execute this command on server"), Category("MethodResponse")]
- public double Seconds { get { return seconds; } set { seconds = value; } }
- [Description("The status"), Category("MethodResponse")]
- public string Status { get { return status; } set { status = value; } }
- }
-
- public class DescriptionAttribute : Attribute
- {
- public DescriptionAttribute(string text) { }
- }
-
- public class CategoryAttribute : Attribute
- {
- public CategoryAttribute(string text) { }
- }
-}
diff --git a/OpenSubtitlesHandler/Interfaces/MethodResponseAttr.cs b/OpenSubtitlesHandler/Interfaces/MethodResponseAttr.cs
deleted file mode 100644
index a7e49032d..000000000
--- a/OpenSubtitlesHandler/Interfaces/MethodResponseAttr.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Attributes to describe a method response object.
- /// </summary>
- public class MethodResponseDescription : Attribute
- {
- public MethodResponseDescription(string name, string message)
- {
- this.name = name;
- this.message = message;
- }
-
- private string name;
- private string message;
-
- public string Name { get { return name; } set { name = value; } }
- public string Message { get { return message; } set { message = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Languages/DetectLanguageResult.cs b/OpenSubtitlesHandler/Languages/DetectLanguageResult.cs
deleted file mode 100644
index 3e72dc65c..000000000
--- a/OpenSubtitlesHandler/Languages/DetectLanguageResult.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- public struct DetectLanguageResult
- {
- private string inputSample;
- private string languageID;
-
- public string LanguageID
- { get { return languageID; } set { languageID = value; } }
- public string InputSample
- { get { return inputSample; } set { inputSample = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseAddComment.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseAddComment.cs
deleted file mode 100644
index 03d0337d4..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseAddComment.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("AddComment method response",
- "AddComment method response hold all expected values from server.")]
- public class MethodResponseAddComment : IMethodResponse
- {
- public MethodResponseAddComment()
- : base()
- { }
- public MethodResponseAddComment(string name, string message)
- : base(name, message)
- { }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseAddRequest.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseAddRequest.cs
deleted file mode 100644
index b996043c2..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseAddRequest.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("AddRequest method response",
- "AddRequest method response hold all expected values from server.")]
- public class MethodResponseAddRequest : IMethodResponse
- {
- public MethodResponseAddRequest()
- : base()
- { }
- public MethodResponseAddRequest(string name, string message)
- : base(name, message)
- { }
- private string _request_url;
-
- public string request_url { get { return _request_url; } set { _request_url = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseAutoUpdate.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseAutoUpdate.cs
deleted file mode 100644
index 6ee14f1f8..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseAutoUpdate.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("AutoUpdate method response",
- "AutoUpdate method response hold all expected values from server.")]
- public class MethodResponseAutoUpdate : IMethodResponse
- {
- public MethodResponseAutoUpdate()
- : base()
- { }
- public MethodResponseAutoUpdate(string name, string message)
- : base(name, message)
- { }
-
- private string _version;
- private string _url_windows;
- private string _comments;
- private string _url_linux;
- /// <summary>
- /// Latest application version
- /// </summary>
- [Description("Latest application version"), Category("AutoUpdate")]
- public string version { get { return _version; } set { _version = value; } }
- /// <summary>
- /// Download URL for Windows version
- /// </summary>
- [Description("Download URL for Windows version"), Category("AutoUpdate")]
- public string url_windows { get { return _url_windows; } set { _url_windows = value; } }
- /// <summary>
- /// Application changelog and other comments
- /// </summary>
- [Description("Application changelog and other comments"), Category("AutoUpdate")]
- public string comments { get { return _comments; } set { _comments = value; } }
- /// <summary>
- /// Download URL for Linux version
- /// </summary>
- [Description("Download URL for Linux version"), Category("AutoUpdate")]
- public string url_linux { get { return _url_linux; } set { _url_linux = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash.cs
deleted file mode 100644
index 4bb326244..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("CheckMovieHash method response",
- "CheckMovieHash method response hold all expected values from server.")]
- public class MethodResponseCheckMovieHash : IMethodResponse
- {
- public MethodResponseCheckMovieHash()
- : base()
- { }
- public MethodResponseCheckMovieHash(string name, string message)
- : base(name, message)
- { }
- private List<CheckMovieHashResult> results = new List<CheckMovieHashResult>();
- public List<CheckMovieHashResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash2.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash2.cs
deleted file mode 100644
index 72b4c3b15..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckMovieHash2.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("CheckMovieHash2 method response",
- "CheckMovieHash2 method response hold all expected values from server.")]
- public class MethodResponseCheckMovieHash2 : IMethodResponse
- {
- public MethodResponseCheckMovieHash2()
- : base()
- { }
- public MethodResponseCheckMovieHash2(string name, string message)
- : base(name, message)
- { }
- private List<CheckMovieHash2Result> results = new List<CheckMovieHash2Result>();
- public List<CheckMovieHash2Result> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckSubHash.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckSubHash.cs
deleted file mode 100644
index 04e287ea7..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseCheckSubHash.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("CheckSubHash method response",
- "CheckSubHash method response hold all expected values from server.")]
- public class MethodResponseCheckSubHash : IMethodResponse
- {
- public MethodResponseCheckSubHash()
- : base()
- { }
- public MethodResponseCheckSubHash(string name, string message)
- : base(name, message)
- { }
- private List<CheckSubHashResult> results = new List<CheckSubHashResult>();
-
- public List<CheckSubHashResult> Results { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseDetectLanguage.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseDetectLanguage.cs
deleted file mode 100644
index 6bf21d50e..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseDetectLanguage.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("DetectLanguage method response",
- "DetectLanguage method response hold all expected values from server.")]
- public class MethodResponseDetectLanguage : IMethodResponse
- {
- public MethodResponseDetectLanguage()
- : base()
- { }
- public MethodResponseDetectLanguage(string name, string message)
- : base(name, message)
- { }
- private List<DetectLanguageResult> results = new List<DetectLanguageResult>();
-
- public List<DetectLanguageResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseError.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseError.cs
deleted file mode 100644
index 7ed807067..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseError.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Response that can be used for general error like internet connection fail.
- /// </summary>
- [MethodResponseDescription("Error method response",
- "Error method response that describes error that occured")]
- public class MethodResponseError : IMethodResponse
- {
- public MethodResponseError()
- : base()
- { }
- public MethodResponseError(string name, string message)
- : base(name, message)
- { }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetAvailableTranslations.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseGetAvailableTranslations.cs
deleted file mode 100644
index 91803f4b3..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetAvailableTranslations.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("GetAvailableTranslations method response",
- "GetAvailableTranslations method response hold all expected values from server.")]
- public class MethodResponseGetAvailableTranslations : IMethodResponse
- {
- public MethodResponseGetAvailableTranslations()
- : base()
- { }
- public MethodResponseGetAvailableTranslations(string name, string message)
- : base(name, message)
- { }
- private List<GetAvailableTranslationsResult> results = new List<GetAvailableTranslationsResult>();
- public List<GetAvailableTranslationsResult> Results { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetComments.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseGetComments.cs
deleted file mode 100644
index 421e1783b..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetComments.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("GetComments method response",
- "GetComments method response hold all expected values from server.")]
- public class MethodResponseGetComments : IMethodResponse
- {
- public MethodResponseGetComments()
- : base()
- { }
- public MethodResponseGetComments(string name, string message)
- : base(name, message)
- { }
- private List<GetCommentsResult> results = new List<GetCommentsResult>();
-
- public List<GetCommentsResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetSubLanguages.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseGetSubLanguages.cs
deleted file mode 100644
index 905b87c91..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetSubLanguages.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("GetSubLanguages method response",
- "GetSubLanguages method response hold all expected values from server.")]
- public class MethodResponseGetSubLanguages : IMethodResponse
- {
- public MethodResponseGetSubLanguages()
- : base()
- { }
- public MethodResponseGetSubLanguages(string name, string message)
- : base(name, message)
- { }
- private List<SubtitleLanguage> languages = new List<SubtitleLanguage>();
-
- public List<SubtitleLanguage> Languages
- { get { return languages; } set { languages = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetTranslation.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseGetTranslation.cs
deleted file mode 100644
index f008f7711..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseGetTranslation.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("GetTranslation method response",
- "GetTranslation method response hold all expected values from server.")]
- public class MethodResponseGetTranslation : IMethodResponse
- {
- public MethodResponseGetTranslation()
- : base()
- { }
- public MethodResponseGetTranslation(string name, string message)
- : base(name, message)
- { }
- private string data;
-
- public string ContentData { get { return data; } set { data = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovie.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovie.cs
deleted file mode 100644
index 1148b5f47..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovie.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("InsertMovie method response",
- "InsertMovie method response hold all expected values from server.")]
- public class MethodResponseInsertMovie : IMethodResponse
- {
- public MethodResponseInsertMovie()
- : base()
- { }
- public MethodResponseInsertMovie(string name, string message)
- : base(name, message)
- { }
- private string _ID;
- public string ID
- { get { return _ID; } set { _ID = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovieHash.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovieHash.cs
deleted file mode 100644
index 74f52837c..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseInsertMovieHash.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("InsertMovieHash method response",
- "InsertMovieHash method response hold all expected values from server.")]
- public class MethodResponseInsertMovieHash : IMethodResponse
- {
- public MethodResponseInsertMovieHash()
- : base()
- { }
- public MethodResponseInsertMovieHash(string name, string message)
- : base(name, message)
- { }
- private List<string> _accepted_moviehashes = new List<string>();
- private List<string> _new_imdbs = new List<string>();
-
- public List<string> accepted_moviehashes { get { return _accepted_moviehashes; } set { _accepted_moviehashes = value; } }
- public List<string> new_imdbs { get { return _new_imdbs; } set { _new_imdbs = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseLogIn.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseLogIn.cs
deleted file mode 100644
index 44d294382..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseLogIn.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Response can be used for log in/out operation.
- /// </summary>
- [MethodResponseDescription("LogIn method response",
- "LogIn method response hold all expected values from server.")]
- public class MethodResponseLogIn : IMethodResponse
- {
- public MethodResponseLogIn()
- : base()
- { }
- public MethodResponseLogIn(string name, string message)
- : base(name, message)
- { }
- private string token;
-
- public string Token { get { return token; } set { token = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieDetails.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieDetails.cs
deleted file mode 100644
index 6126c0053..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieDetails.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("MovieDetails method response",
- "MovieDetails method response hold all expected values from server.")]
- public class MethodResponseMovieDetails : IMethodResponse
- {
- public MethodResponseMovieDetails()
- : base()
- { }
- public MethodResponseMovieDetails(string name, string message)
- : base(name, message)
- { }
- // Details
- private string id;
- private string title;
- private string year;
- private string coverLink;
-
- private string duration;
- private string tagline;
- private string plot;
- private string goofs;
- private string trivia;
- private List<string> cast = new List<string>();
- private List<string> directors = new List<string>();
- private List<string> writers = new List<string>();
- private List<string> awards = new List<string>();
- private List<string> genres = new List<string>();
- private List<string> country = new List<string>();
- private List<string> language = new List<string>();
- private List<string> certification = new List<string>();
-
- // Details
- public string ID { get { return id; } set { id = value; } }
- public string Title { get { return title; } set { title = value; } }
- public string Year { get { return year; } set { year = value; } }
- public string CoverLink { get { return coverLink; } set { coverLink = value; } }
- public string Duration { get { return duration; } set { duration = value; } }
- public string Tagline { get { return tagline; } set { tagline = value; } }
- public string Plot { get { return plot; } set { plot = value; } }
- public string Goofs { get { return goofs; } set { goofs = value; } }
- public string Trivia { get { return trivia; } set { trivia = value; } }
- public List<string> Cast { get { return cast; } set { cast = value; } }
- public List<string> Directors { get { return directors; } set { directors = value; } }
- public List<string> Writers { get { return writers; } set { writers = value; } }
- public List<string> Genres { get { return genres; } set { genres = value; } }
- public List<string> Awards { get { return awards; } set { awards = value; } }
- public List<string> Country { get { return country; } set { country = value; } }
- public List<string> Language { get { return language; } set { language = value; } }
- public List<string> Certification { get { return certification; } set { certification = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieSearch.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieSearch.cs
deleted file mode 100644
index 93cd70346..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseMovieSearch.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("MovieSearch method response",
- "MovieSearch method response hold all expected values from server.")]
- public class MethodResponseMovieSearch : IMethodResponse
- {
- public MethodResponseMovieSearch()
- : base()
- {
- results = new List<MovieSearchResult>();
- }
- public MethodResponseMovieSearch(string name, string message)
- : base(name, message)
- {
- results = new List<MovieSearchResult>();
- }
- private List<MovieSearchResult> results;
-
- public List<MovieSearchResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseNoOperation.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseNoOperation.cs
deleted file mode 100644
index 02a9993cb..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseNoOperation.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("NoOperation method response",
- "NoOperation method response hold all expected values from server.")]
- public class MethodResponseNoOperation : IMethodResponse
- {
- public MethodResponseNoOperation()
- : base() { }
- public MethodResponseNoOperation(string name, string message)
- : base(name, message)
- { }
-
- private string _global_wrh_download_limit;
- private string _client_ip;
- private string _limit_check_by;
- private string _client_24h_download_count;
- private string _client_downlaod_quota;
- private string _client_24h_download_limit;
-
- public string global_wrh_download_limit
- { get { return _global_wrh_download_limit; } set { _global_wrh_download_limit = value; } }
- public string client_ip
- { get { return _client_ip; } set { _client_ip = value; } }
- public string limit_check_by
- { get { return _limit_check_by; } set { _limit_check_by = value; } }
- public string client_24h_download_count
- { get { return _client_24h_download_count; } set { _client_24h_download_count = value; } }
- public string client_downlaod_quota
- { get { return _client_downlaod_quota; } set { _client_downlaod_quota = value; } }
- public string client_24h_download_limit
- { get { return _client_24h_download_limit; } set { _client_24h_download_limit = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongImdbMovie.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongImdbMovie.cs
deleted file mode 100644
index 391fec58a..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongImdbMovie.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("ReportWrongImdbMovie method response",
- "ReportWrongImdbMovie method response hold all expected values from server.")]
- public class MethodResponseReportWrongImdbMovie : IMethodResponse
- {
- public MethodResponseReportWrongImdbMovie()
- : base()
- { }
- public MethodResponseReportWrongImdbMovie(string name, string message)
- : base(name, message)
- { }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongMovieHash.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongMovieHash.cs
deleted file mode 100644
index 5696e7084..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseReportWrongMovieHash.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("ReportWrongMovieHash method response",
- "ReportWrongMovieHash method response hold all expected values from server.")]
- public class MethodResponseReportWrongMovieHash : IMethodResponse
- {
- public MethodResponseReportWrongMovieHash()
- : base()
- { }
- public MethodResponseReportWrongMovieHash(string name, string message)
- : base(name, message)
- { }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseSearchToMail.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseSearchToMail.cs
deleted file mode 100644
index ea248bc22..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseSearchToMail.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("SearchToMail method response",
- "SearchToMail method response hold all expected values from server.")]
- public class MethodResponseSearchToMail : IMethodResponse
- {
- public MethodResponseSearchToMail()
- : base()
- { }
- public MethodResponseSearchToMail(string name, string message)
- : base(name, message)
- { }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseServerInfo.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseServerInfo.cs
deleted file mode 100644
index 973550e9f..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseServerInfo.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("ServerInfo method response",
- "ServerInfo method response hold all expected values from server.")]
- public class MethodResponseServerInfo : IMethodResponse
- {
- public MethodResponseServerInfo()
- : base()
- { }
- public MethodResponseServerInfo(string name, string message)
- : base(name, message)
- { }
- private string _xmlrpc_version;
- private string _xmlrpc_url;
- private string _application;
- private string _contact;
- private string _website_url;
- private int _users_online_total;
- private int _users_online_program;
- private int _users_loggedin;
- private string _users_max_alltime;
- private string _users_registered;
- private string _subs_downloads;
- private string _subs_subtitle_files;
- private string _movies_total;
- private string _movies_aka;
- private string _total_subtitles_languages;
- private List<string> _last_update_strings = new List<string>();
-
- /// <summary>
- /// Version of server's XML-RPC API implementation
- /// </summary>
- [Description("Version of server's XML-RPC API implementation"), Category("OS")]
- public string xmlrpc_version { get { return _xmlrpc_version; } set { _xmlrpc_version = value; } }
- /// <summary>
- /// XML-RPC interface URL
- /// </summary>
- [Description("XML-RPC interface URL"), Category("OS")]
- public string xmlrpc_url { get { return _xmlrpc_url; } set { _xmlrpc_url = value; } }
- /// <summary>
- /// Server's application name and version
- /// </summary>
- [Description("Server's application name and version"), Category("OS")]
- public string application { get { return _application; } set { _application = value; } }
- /// <summary>
- /// Contact e-mail address for server related quuestions and problems
- /// </summary>
- [Description("Contact e-mail address for server related quuestions and problems"), Category("OS")]
- public string contact { get { return _contact; } set { _contact = value; } }
- /// <summary>
- /// Main server URL
- /// </summary>
- [Description("Main server URL"), Category("OS")]
- public string website_url { get { return _website_url; } set { _website_url = value; } }
- /// <summary>
- /// Number of users currently online
- /// </summary>
- [Description("Number of users currently online"), Category("OS")]
- public int users_online_total { get { return _users_online_total; } set { _users_online_total = value; } }
- /// <summary>
- /// Number of users currently online using a client application (XML-RPC API)
- /// </summary>
- [Description("Number of users currently online using a client application (XML-RPC API)"), Category("OS")]
- public int users_online_program { get { return _users_online_program; } set { _users_online_program = value; } }
- /// <summary>
- /// Number of currently logged-in users
- /// </summary>
- [Description("Number of currently logged-in users"), Category("OS")]
- public int users_loggedin { get { return _users_loggedin; } set { _users_loggedin = value; } }
- /// <summary>
- /// Maximum number of users throughout the history
- /// </summary>
- [Description("Maximum number of users throughout the history"), Category("OS")]
- public string users_max_alltime { get { return _users_max_alltime; } set { _users_max_alltime = value; } }
- /// <summary>
- /// Number of registered users
- /// </summary>
- [Description("Number of registered users"), Category("OS")]
- public string users_registered { get { return _users_registered; } set { _users_registered = value; } }
- /// <summary>
- /// Total number of subtitle downloads
- /// </summary>
- [Description("Total number of subtitle downloads"), Category("OS")]
- public string subs_downloads { get { return _subs_downloads; } set { _subs_downloads = value; } }
- /// <summary>
- /// Total number of subtitle files stored on the server
- /// </summary>
- [Description("Total number of subtitle files stored on the server"), Category("OS")]
- public string subs_subtitle_files { get { return _subs_subtitle_files; } set { _subs_subtitle_files = value; } }
- /// <summary>
- /// Total number of movies in the database
- /// </summary>
- [Description("Total number of movies in the database"), Category("OS")]
- public string movies_total { get { return _movies_total; } set { _movies_total = value; } }
- /// <summary>
- /// Total number of movie A.K.A. titles in the database
- /// </summary>
- [Description("Total number of movie A.K.A. titles in the database"), Category("OS")]
- public string movies_aka { get { return _movies_aka; } set { _movies_aka = value; } }
- /// <summary>
- /// Total number of subtitle languages supported
- /// </summary>
- [Description("Total number of subtitle languages supported"), Category("OS")]
- public string total_subtitles_languages { get { return _total_subtitles_languages; } set { _total_subtitles_languages = value; } }
- /// <summary>
- /// Structure containing information about last updates of translations.
- /// </summary>
- [Description("Structure containing information about last updates of translations"), Category("OS")]
- public List<string> last_update_strings { get { return _last_update_strings; } set { _last_update_strings = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleDownload.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleDownload.cs
deleted file mode 100644
index 6a5d57d19..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleDownload.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// The response that should be used by subtitle download methods.
- /// </summary>
- [MethodResponseDescription("SubtitleDownload method response",
- "SubtitleDownload method response hold all expected values from server.")]
- public class MethodResponseSubtitleDownload : IMethodResponse
- {
- public MethodResponseSubtitleDownload()
- : base()
- {
- results = new List<SubtitleDownloadResult>();
- }
- public MethodResponseSubtitleDownload(string name, string message)
- : base(name, message)
- {
- results = new List<SubtitleDownloadResult>();
- }
- private List<SubtitleDownloadResult> results;
- public List<SubtitleDownloadResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleSearch.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleSearch.cs
deleted file mode 100644
index 0dce20349..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitleSearch.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Response to SearchSubtitle successed call.
- /// </summary>
- [MethodResponseDescription("SubtitleSearch method response",
- "SubtitleSearch method response hold all expected values from server.")]
- public class MethodResponseSubtitleSearch : IMethodResponse
- {
- public MethodResponseSubtitleSearch()
- : base()
- {
- results = new List<SubtitleSearchResult>();
- }
- public MethodResponseSubtitleSearch(string name, string message)
- : base(name, message)
- {
- results = new List<SubtitleSearchResult>();
- }
-
- private List<SubtitleSearchResult> results;
- public List<SubtitleSearchResult> Results
- { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitlesVote.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitlesVote.cs
deleted file mode 100644
index f02f822f0..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseSubtitlesVote.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("SubtitlesVote method response",
- "SubtitlesVote method response hold all expected values from server.")]
- public class MethodResponseSubtitlesVote : IMethodResponse
- {
- public MethodResponseSubtitlesVote()
- : base()
- { }
- public MethodResponseSubtitlesVote(string name, string message)
- : base(name, message)
- { }
- private string _SubRating;
- private string _SubSumVotes;
- private string _IDSubtitle;
-
- public string SubRating
- { get { return _SubRating; } set { _SubRating = value; } }
- public string SubSumVotes
- { get { return _SubSumVotes; } set { _SubSumVotes = value; } }
- public string IDSubtitle
- { get { return _IDSubtitle; } set { _IDSubtitle = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseTryUploadSubtitles.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseTryUploadSubtitles.cs
deleted file mode 100644
index cb3866a62..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseTryUploadSubtitles.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("TryUploadSubtitles method response",
- "TryUploadSubtitles method response hold all expected values from server.")]
- public class MethodResponseTryUploadSubtitles : IMethodResponse
- {
- public MethodResponseTryUploadSubtitles()
- : base()
- { }
- public MethodResponseTryUploadSubtitles(string name, string message)
- : base(name, message)
- { }
- private int alreadyindb;
- private List<SubtitleSearchResult> results = new List<SubtitleSearchResult>();
-
- public int AlreadyInDB { get { return alreadyindb; } set { alreadyindb = value; } }
- public List<SubtitleSearchResult> Results { get { return results; } set { results = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/MethodResponses/MethodResponseUploadSubtitles.cs b/OpenSubtitlesHandler/MethodResponses/MethodResponseUploadSubtitles.cs
deleted file mode 100644
index bda950bef..000000000
--- a/OpenSubtitlesHandler/MethodResponses/MethodResponseUploadSubtitles.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- [MethodResponseDescription("UploadSubtitles method response",
- "UploadSubtitles method response hold all expected values from server.")]
- public class MethodResponseUploadSubtitles : IMethodResponse
- {
- public MethodResponseUploadSubtitles()
- : base()
- { }
- public MethodResponseUploadSubtitles(string name, string message)
- : base(name, message)
- { }
- private string _data;
- private bool _subtitles;
-
- public string Data { get { return _data; } set { _data = value; } }
- public bool SubTitles { get { return _subtitles; } set { _subtitles = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Methods Implemeted.txt b/OpenSubtitlesHandler/Methods Implemeted.txt
deleted file mode 100644
index e3493d9a2..000000000
--- a/OpenSubtitlesHandler/Methods Implemeted.txt
+++ /dev/null
@@ -1,39 +0,0 @@
-List of available OpenSubtitles.org server XML-RPC methods.
-==========================================================
-Legends:
-* OK: this method is fully implemented, tested and works fine.
-* TODO: this method is in the plan to be added.
-* NOT TESTED: this method added and expected to work fine but never tested.
-* NOT WORK (x): this method added but not work. x= Description of the error.
-
---------------------------------------------
-Method name | Status
--------------------------|------------------
-LogIn | OK
-LogOut | OK
-NoOperation | OK
-SearchSubtitles | OK
-DownloadSubtitles | OK
-SearchToMail | OK
-TryUploadSubtitles | OK
-UploadSubtitles | OK
-SearchMoviesOnIMDB | OK
-GetIMDBMovieDetails | OK
-InsertMovie | OK
-InsertMovieHash | OK
-ServerInfo | OK
-ReportWrongMovieHash | OK
-ReportWrongImdbMovie | OK
-SubtitlesVote | OK
-AddComment | OK
-AddRequest | OK
-GetComments | OK
-GetSubLanguages | OK
-DetectLanguage | OK
-GetAvailableTranslations | OK
-GetTranslation | NOT WORK (Returns status of error 410 'Other or unknown error')
-AutoUpdate | NOT WORK (Returns status: 'parse error. not well formed')
-CheckMovieHash | OK
-CheckMovieHash2 | OK
-CheckSubHash | OK
---------------------------------------------
diff --git a/OpenSubtitlesHandler/MovieHasher.cs b/OpenSubtitlesHandler/MovieHasher.cs
deleted file mode 100644
index 25d91c1ac..000000000
--- a/OpenSubtitlesHandler/MovieHasher.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace OpenSubtitlesHandler
-{
- public class MovieHasher
- {
- public static byte[] ComputeMovieHash(Stream input)
- {
- using (input)
- {
- long lhash, streamsize;
- streamsize = input.Length;
- lhash = streamsize;
-
- long i = 0;
- byte[] buffer = new byte[sizeof(long)];
- while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
- {
- i++;
- lhash += BitConverter.ToInt64(buffer, 0);
- }
-
- input.Position = Math.Max(0, streamsize - 65536);
- i = 0;
- while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
- {
- i++;
- lhash += BitConverter.ToInt64(buffer, 0);
- }
- byte[] result = BitConverter.GetBytes(lhash);
- Array.Reverse(result);
- return result;
- }
- }
-
- public static string ToHexadecimal(byte[] bytes)
- {
- var hexBuilder = new StringBuilder();
- for (int i = 0; i < bytes.Length; i++)
- {
- hexBuilder.Append(bytes[i].ToString("x2"));
- }
- return hexBuilder.ToString();
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/CheckMovieHash2Data.cs b/OpenSubtitlesHandler/Movies/CheckMovieHash2Data.cs
deleted file mode 100644
index 953590137..000000000
--- a/OpenSubtitlesHandler/Movies/CheckMovieHash2Data.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct CheckMovieHash2Data
- {
- private string _MovieHash;
- private string _MovieImdbID;
- private string _MovieName;
- private string _MovieYear;
- private string _MovieKind;
- private string _SeriesSeason;
- private string _SeriesEpisode;
- private string _SeenCount;
-
- public string MovieHash { get { return _MovieHash; } set { _MovieHash = value; } }
- public string MovieImdbID { get { return _MovieImdbID; } set { _MovieImdbID = value; } }
- public string MovieName { get { return _MovieName; } set { _MovieName = value; } }
- public string MovieYear { get { return _MovieYear; } set { _MovieYear = value; } }
- public string MovieKind { get { return _MovieKind; } set { _MovieKind = value; } }
- public string SeriesSeason { get { return _SeriesSeason; } set { _SeriesSeason = value; } }
- public string SeriesEpisode { get { return _SeriesEpisode; } set { _SeriesEpisode = value; } }
- public string SeenCount { get { return _SeenCount; } set { _SeenCount = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/CheckMovieHash2Result.cs b/OpenSubtitlesHandler/Movies/CheckMovieHash2Result.cs
deleted file mode 100644
index 96652fae7..000000000
--- a/OpenSubtitlesHandler/Movies/CheckMovieHash2Result.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- public class CheckMovieHash2Result
- {
- private string name;
- private List<CheckMovieHash2Data> data = new List<CheckMovieHash2Data>();
-
- public string Name { get { return name; } set { name = value; } }
- public List<CheckMovieHash2Data> Items { get { return data; } set { data = value; } }
-
- public override string ToString()
- {
- return name;
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/CheckMovieHashResult.cs b/OpenSubtitlesHandler/Movies/CheckMovieHashResult.cs
deleted file mode 100644
index 0d6c79f80..000000000
--- a/OpenSubtitlesHandler/Movies/CheckMovieHashResult.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct CheckMovieHashResult
- {
- private string name;
- private string _MovieHash;
- private string _MovieImdbID;
- private string _MovieName;
- private string _MovieYear;
-
- public string MovieHash { get { return _MovieHash; } set { _MovieHash = value; } }
- public string MovieImdbID { get { return _MovieImdbID; } set { _MovieImdbID = value; } }
- public string MovieName { get { return _MovieName; } set { _MovieName = value; } }
- public string MovieYear { get { return _MovieYear; } set { _MovieYear = value; } }
- public string Name { get { return name; } set { name = value; } }
-
- public override string ToString()
- {
- return name;
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/InsertMovieHashParameters.cs b/OpenSubtitlesHandler/Movies/InsertMovieHashParameters.cs
deleted file mode 100644
index d0de7f8c6..000000000
--- a/OpenSubtitlesHandler/Movies/InsertMovieHashParameters.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public class InsertMovieHashParameters
- {
- private string _moviehash = "";
- private string _moviebytesize = "";
- private string _imdbid = "";
- private string _movietimems = "";
- private string _moviefps = "";
- private string _moviefilename = "";
-
- public string moviehash { get { return _moviehash; } set { _moviehash = value; } }
- public string moviebytesize { get { return _moviebytesize; } set { _moviebytesize = value; } }
- public string imdbid { get { return _imdbid; } set { _imdbid = value; } }
- public string movietimems { get { return _movietimems; } set { _movietimems = value; } }
- public string moviefps { get { return _moviefps; } set { _moviefps = value; } }
- public string moviefilename { get { return _moviefilename; } set { _moviefilename = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/MovieSearchResult.cs b/OpenSubtitlesHandler/Movies/MovieSearchResult.cs
deleted file mode 100644
index d77116583..000000000
--- a/OpenSubtitlesHandler/Movies/MovieSearchResult.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct MovieSearchResult
- {
- private string id;
- private string title;
-
- public string ID
- { get { return id; } set { id = value; } }
- public string Title
- { get { return title; } set { title = value; } }
- /// <summary>
- /// Title
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return title;
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Movies/SearchToMailMovieParameter.cs b/OpenSubtitlesHandler/Movies/SearchToMailMovieParameter.cs
deleted file mode 100644
index a0ecc87f8..000000000
--- a/OpenSubtitlesHandler/Movies/SearchToMailMovieParameter.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct SearchToMailMovieParameter
- {
- private string _moviehash;
- private double _moviesize;
-
- public string moviehash { get { return _moviehash; } set { _moviehash = value; } }
- public double moviesize { get { return _moviesize; } set { _moviesize = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/OpenSubtitles.cs b/OpenSubtitlesHandler/OpenSubtitles.cs
deleted file mode 100644
index 76f70dc07..000000000
--- a/OpenSubtitlesHandler/OpenSubtitles.cs
+++ /dev/null
@@ -1,2744 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using OpenSubtitlesHandler.Console;
-using XmlRpcHandler;
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// The core of the OpenSubtitles Handler library. All members are static.
- /// </summary>
- public sealed class OpenSubtitles
- {
- private static string XML_PRC_USERAGENT = "";
- // This is session id after log in, important value and MUST be set by LogIn before any other call.
- private static string TOKEN = "";
-
- /// <summary>
- /// Set the useragent value. This must be called before doing anything else.
- /// </summary>
- /// <param name="agent">The useragent value</param>
- public static void SetUserAgent(string agent)
- {
- XML_PRC_USERAGENT = agent;
- }
-
- /*Session handling*/
- /// <summary>
- /// Send a LogIn request, this must be called before anything else in this class.
- /// </summary>
- /// <param name="userName">The user name of OpenSubtitles</param>
- /// <param name="password">The password</param>
- /// <param name="language">The language, usally en</param>
- /// <returns>Status of the login operation</returns>
- public static IMethodResponse LogIn(string userName, string password, string language)
- {
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(userName));
- parms.Add(new XmlRpcValueBasic(password));
- parms.Add(new XmlRpcValueBasic(language));
- parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT));
- var call = new XmlRpcMethodCall("LogIn", parms);
- OSHConsole.WriteLine("Sending LogIn request to the server ...", DebugCode.Good);
-
- //File.WriteAllText(".\\request.txt", Encoding.UTF8.GetString(XmlRpcGenerator.Generate(call)));
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
-
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response. We expect Struct here.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- var re = new MethodResponseLogIn("Success", "Log in successful.");
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "token": re.Token = TOKEN = MEMBER.Data.Data.ToString(); OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": re.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "status": re.Status = MEMBER.Data.Data.ToString(); OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- return re;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "Log in failed !");
- }
-
- public static async Task<IMethodResponse> LogInAsync(string userName, string password, string language, CancellationToken cancellationToken)
- {
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(userName));
- parms.Add(new XmlRpcValueBasic(password));
- parms.Add(new XmlRpcValueBasic(language));
- parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT));
- var call = new XmlRpcMethodCall("LogIn", parms);
- OSHConsole.WriteLine("Sending LogIn request to the server ...", DebugCode.Good);
-
- //File.WriteAllText(".\\request.txt", Encoding.UTF8.GetString(XmlRpcGenerator.Generate(call)));
- // Send the request to the server
- var stream = await Utilities.SendRequestAsync(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT, cancellationToken)
- .ConfigureAwait(false);
-
- string response = Utilities.GetStreamString(stream);
-
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response. We expect Struct here.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- var re = new MethodResponseLogIn("Success", "Log in successful.");
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "token":
- re.Token = TOKEN = MEMBER.Data.Data.ToString();
- OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "seconds":
- re.Seconds = double.Parse(MEMBER.Data.Data.ToString(), CultureInfo.InvariantCulture);
- OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "status":
- re.Status = MEMBER.Data.Data.ToString();
- OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- }
- }
- return re;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "Log in failed !");
- }
-
- /// <summary>
- /// Log out from the server. Call this to terminate the session.
- /// </summary>
- /// <returns></returns>
- public static IMethodResponse LogOut()
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var call = new XmlRpcMethodCall("LogOut", parms);
-
- OSHConsole.WriteLine("Sending LogOut request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response. We expect Struct here.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var strct = (XmlRpcValueStruct)calls[0].Parameters[0];
- OSHConsole.WriteLine("STATUS=" + ((XmlRpcValueBasic)strct.Members[0].Data).Data.ToString());
- OSHConsole.WriteLine("SECONDS=" + ((XmlRpcValueBasic)strct.Members[1].Data).Data.ToString());
- var re = new MethodResponseLogIn("Success", "Log out successful.");
- re.Status = ((XmlRpcValueBasic)strct.Members[0].Data).Data.ToString();
- re.Seconds = (double)((XmlRpcValueBasic)strct.Members[1].Data).Data;
- return re;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "Log out failed !");
- }
- /// <summary>
- /// keep-alive user's session, verify token/session validity
- /// </summary>
- /// <returns>Status of the call operation</returns>
- public static IMethodResponse NoOperation()
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT, XmlRpcBasicValueType.String));
- var call = new XmlRpcMethodCall("NoOperation", parms);
-
- OSHConsole.WriteLine("Sending NoOperation request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response. We expect Struct here.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var R = new MethodResponseNoOperation();
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(MEMBER.Name + "= " + MEMBER.Data.Data); break;
- case "download_limits":
- var dlStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dlmember in dlStruct.Members)
- {
- OSHConsole.WriteLine(" >" + dlmember.Name + "= " + dlmember.Data.Data.ToString());
- switch (dlmember.Name)
- {
- case "global_wrh_download_limit": R.global_wrh_download_limit = dlmember.Data.Data.ToString(); break;
- case "client_ip": R.client_ip = dlmember.Data.Data.ToString(); break;
- case "limit_check_by": R.limit_check_by = dlmember.Data.Data.ToString(); break;
- case "client_24h_download_count": R.client_24h_download_count = dlmember.Data.Data.ToString(); break;
- case "client_downlaod_quota": R.client_downlaod_quota = dlmember.Data.Data.ToString(); break;
- case "client_24h_download_limit": R.client_24h_download_limit = dlmember.Data.Data.ToString(); break;
- }
- }
- break;
- }
- }
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "NoOperation call failed !");
- }
- /*Search and download*/
- /// <summary>
- /// Search for subtitle files matching your videos using either video file hashes or IMDb IDs.
- /// </summary>
- /// <param name="parameters">List of search subtitle parameters which each one represents 'struct parameter' as descriped at http://trac.opensubtitles.org/projects/opensubtitles/wiki/XmlRpcSearchSubtitles </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseSubtitleSearch'</returns>
- public static IMethodResponse SearchSubtitles(SubtitleSearchParameters[] parameters)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- if (parameters == null)
- {
- OSHConsole.UpdateLine("No subtitle search parameter passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle search parameter passed");
- }
- if (parameters.Length == 0)
- {
- OSHConsole.UpdateLine("No subtitle search parameter passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle search parameter passed");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add subtitle search parameters. Each one will be like 'array' of structs.
- var array = new XmlRpcValueArray();
- foreach (SubtitleSearchParameters param in parameters)
- {
- var strct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- // sublanguageid member
- var member = new XmlRpcStructMember("sublanguageid",
- new XmlRpcValueBasic(param.SubLangaugeID, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- // moviehash member
- if (param.MovieHash.Length > 0 && param.MovieByteSize > 0)
- {
- member = new XmlRpcStructMember("moviehash",
- new XmlRpcValueBasic(param.MovieHash, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- // moviehash member
- member = new XmlRpcStructMember("moviebytesize",
- new XmlRpcValueBasic(param.MovieByteSize, XmlRpcBasicValueType.Int));
- strct.Members.Add(member);
- }
- if (param.Query.Length > 0)
- {
- member = new XmlRpcStructMember("query",
- new XmlRpcValueBasic(param.Query, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
-
- if (param.Episode.Length > 0 && param.Season.Length > 0)
- {
- member = new XmlRpcStructMember("season",
- new XmlRpcValueBasic(param.Season, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- member = new XmlRpcStructMember("episode",
- new XmlRpcValueBasic(param.Episode, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
-
- // imdbid member
- if (param.IMDbID.Length > 0)
- {
- member = new XmlRpcStructMember("imdbid",
- new XmlRpcValueBasic(param.IMDbID, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
- // Add the struct to the array
- array.Values.Add(strct);
- }
- // Add the array to the parameters
- parms.Add(array);
- // Call !
- var call = new XmlRpcMethodCall("SearchSubtitles", parms);
- OSHConsole.WriteLine("Sending SearchSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
-
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- // We expect Struct of 3 members:
- //* the first is status
- //* the second is [array of structs, each one includes subtitle file].
- //* the third is [double basic value] represent seconds token by server.
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSubtitleSearch();
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Search results: ");
-
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new SubtitleSearchResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "IDMovie": result.IDMovie = submember.Data.Data.ToString(); break;
- case "IDMovieImdb": result.IDMovieImdb = submember.Data.Data.ToString(); break;
- case "IDSubMovieFile": result.IDSubMovieFile = submember.Data.Data.ToString(); break;
- case "IDSubtitle": result.IDSubtitle = submember.Data.Data.ToString(); break;
- case "IDSubtitleFile": result.IDSubtitleFile = submember.Data.Data.ToString(); break;
- case "ISO639": result.ISO639 = submember.Data.Data.ToString(); break;
- case "LanguageName": result.LanguageName = submember.Data.Data.ToString(); break;
- case "MovieByteSize": result.MovieByteSize = submember.Data.Data.ToString(); break;
- case "MovieHash": result.MovieHash = submember.Data.Data.ToString(); break;
- case "MovieImdbRating": result.MovieImdbRating = submember.Data.Data.ToString(); break;
- case "MovieName": result.MovieName = submember.Data.Data.ToString(); break;
- case "MovieNameEng": result.MovieNameEng = submember.Data.Data.ToString(); break;
- case "MovieReleaseName": result.MovieReleaseName = submember.Data.Data.ToString(); break;
- case "MovieTimeMS": result.MovieTimeMS = submember.Data.Data.ToString(); break;
- case "MovieYear": result.MovieYear = submember.Data.Data.ToString(); break;
- case "SubActualCD": result.SubActualCD = submember.Data.Data.ToString(); break;
- case "SubAddDate": result.SubAddDate = submember.Data.Data.ToString(); break;
- case "SubAuthorComment": result.SubAuthorComment = submember.Data.Data.ToString(); break;
- case "SubBad": result.SubBad = submember.Data.Data.ToString(); break;
- case "SubDownloadLink": result.SubDownloadLink = submember.Data.Data.ToString(); break;
- case "SubDownloadsCnt": result.SubDownloadsCnt = submember.Data.Data.ToString(); break;
- case "SeriesEpisode": result.SeriesEpisode = submember.Data.Data.ToString(); break;
- case "SeriesSeason": result.SeriesSeason = submember.Data.Data.ToString(); break;
- case "SubFileName": result.SubFileName = submember.Data.Data.ToString(); break;
- case "SubFormat": result.SubFormat = submember.Data.Data.ToString(); break;
- case "SubHash": result.SubHash = submember.Data.Data.ToString(); break;
- case "SubLanguageID": result.SubLanguageID = submember.Data.Data.ToString(); break;
- case "SubRating": result.SubRating = submember.Data.Data.ToString(); break;
- case "SubSize": result.SubSize = submember.Data.Data.ToString(); break;
- case "SubSumCD": result.SubSumCD = submember.Data.Data.ToString(); break;
- case "UserID": result.UserID = submember.Data.Data.ToString(); break;
- case "UserNickName": result.UserNickName = submember.Data.Data.ToString(); break;
- case "ZipDownloadLink": result.ZipDownloadLink = submember.Data.Data.ToString(); break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine(">" + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "Search Subtitles call failed !");
- }
-
- public static async Task<IMethodResponse> SearchSubtitlesAsync(SubtitleSearchParameters[] parameters, CancellationToken cancellationToken)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- if (parameters == null)
- {
- OSHConsole.UpdateLine("No subtitle search parameter passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle search parameter passed");
- }
- if (parameters.Length == 0)
- {
- OSHConsole.UpdateLine("No subtitle search parameter passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle search parameter passed");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add subtitle search parameters. Each one will be like 'array' of structs.
- var array = new XmlRpcValueArray();
- foreach (SubtitleSearchParameters param in parameters)
- {
- var strct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- // sublanguageid member
- var member = new XmlRpcStructMember("sublanguageid",
- new XmlRpcValueBasic(param.SubLangaugeID, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- // moviehash member
- if (param.MovieHash.Length > 0 && param.MovieByteSize > 0)
- {
- member = new XmlRpcStructMember("moviehash",
- new XmlRpcValueBasic(param.MovieHash, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- // moviehash member
- member = new XmlRpcStructMember("moviebytesize",
- new XmlRpcValueBasic(param.MovieByteSize, XmlRpcBasicValueType.Int));
- strct.Members.Add(member);
- }
- if (param.Query.Length > 0)
- {
- member = new XmlRpcStructMember("query",
- new XmlRpcValueBasic(param.Query, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
-
- if (param.Episode.Length > 0 && param.Season.Length > 0)
- {
- member = new XmlRpcStructMember("season",
- new XmlRpcValueBasic(param.Season, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- member = new XmlRpcStructMember("episode",
- new XmlRpcValueBasic(param.Episode, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
-
- // imdbid member
- if (param.IMDbID.Length > 0)
- {
- member = new XmlRpcStructMember("imdbid",
- new XmlRpcValueBasic(param.IMDbID, XmlRpcBasicValueType.String));
- strct.Members.Add(member);
- }
- // Add the struct to the array
- array.Values.Add(strct);
- }
- // Add the array to the parameters
- parms.Add(array);
- // Call !
- var call = new XmlRpcMethodCall("SearchSubtitles", parms);
- OSHConsole.WriteLine("Sending SearchSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(await Utilities.SendRequestAsync(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT, cancellationToken).ConfigureAwait(false));
-
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- // We expect Struct of 3 members:
- //* the first is status
- //* the second is [array of structs, each one includes subtitle file].
- //* the third is [double basic value] represent seconds token by server.
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSubtitleSearch();
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Search results: ");
-
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new SubtitleSearchResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "IDMovie": result.IDMovie = submember.Data.Data.ToString(); break;
- case "IDMovieImdb": result.IDMovieImdb = submember.Data.Data.ToString(); break;
- case "IDSubMovieFile": result.IDSubMovieFile = submember.Data.Data.ToString(); break;
- case "IDSubtitle": result.IDSubtitle = submember.Data.Data.ToString(); break;
- case "IDSubtitleFile": result.IDSubtitleFile = submember.Data.Data.ToString(); break;
- case "ISO639": result.ISO639 = submember.Data.Data.ToString(); break;
- case "LanguageName": result.LanguageName = submember.Data.Data.ToString(); break;
- case "MovieByteSize": result.MovieByteSize = submember.Data.Data.ToString(); break;
- case "MovieHash": result.MovieHash = submember.Data.Data.ToString(); break;
- case "MovieImdbRating": result.MovieImdbRating = submember.Data.Data.ToString(); break;
- case "MovieName": result.MovieName = submember.Data.Data.ToString(); break;
- case "MovieNameEng": result.MovieNameEng = submember.Data.Data.ToString(); break;
- case "MovieReleaseName": result.MovieReleaseName = submember.Data.Data.ToString(); break;
- case "MovieTimeMS": result.MovieTimeMS = submember.Data.Data.ToString(); break;
- case "MovieYear": result.MovieYear = submember.Data.Data.ToString(); break;
- case "SubActualCD": result.SubActualCD = submember.Data.Data.ToString(); break;
- case "SubAddDate": result.SubAddDate = submember.Data.Data.ToString(); break;
- case "SubAuthorComment": result.SubAuthorComment = submember.Data.Data.ToString(); break;
- case "SubBad": result.SubBad = submember.Data.Data.ToString(); break;
- case "SubDownloadLink": result.SubDownloadLink = submember.Data.Data.ToString(); break;
- case "SubDownloadsCnt": result.SubDownloadsCnt = submember.Data.Data.ToString(); break;
- case "SeriesEpisode": result.SeriesEpisode = submember.Data.Data.ToString(); break;
- case "SeriesSeason": result.SeriesSeason = submember.Data.Data.ToString(); break;
- case "SubFileName": result.SubFileName = submember.Data.Data.ToString(); break;
- case "SubFormat": result.SubFormat = submember.Data.Data.ToString(); break;
- case "SubHash": result.SubHash = submember.Data.Data.ToString(); break;
- case "SubLanguageID": result.SubLanguageID = submember.Data.Data.ToString(); break;
- case "SubRating": result.SubRating = submember.Data.Data.ToString(); break;
- case "SubSize": result.SubSize = submember.Data.Data.ToString(); break;
- case "SubSumCD": result.SubSumCD = submember.Data.Data.ToString(); break;
- case "UserID": result.UserID = submember.Data.Data.ToString(); break;
- case "UserNickName": result.UserNickName = submember.Data.Data.ToString(); break;
- case "ZipDownloadLink": result.ZipDownloadLink = submember.Data.Data.ToString(); break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine(">" + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "Search Subtitles call failed !");
- }
-
- /// <summary>
- /// Download subtitle file(s)
- /// </summary>
- /// <param name="subIDS">The subtitle IDS (an array of IDSubtitleFile value that given by server as SearchSubtiles results)</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseSubtitleDownload' which will hold downloaded subtitles</returns>
- public static IMethodResponse DownloadSubtitles(int[] subIDS)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- if (subIDS == null)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- if (subIDS.Length == 0)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add subtitle search parameters. Each one will be like 'array' of structs.
- var array = new XmlRpcValueArray();
- foreach (int id in subIDS)
- {
- array.Values.Add(new XmlRpcValueBasic(id, XmlRpcBasicValueType.Int));
- }
- // Add the array to the parameters
- parms.Add(array);
- // Call !
- var call = new XmlRpcMethodCall("DownloadSubtitles", parms);
- OSHConsole.WriteLine("Sending DownloadSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- // We expect Struct of 3 members:
- //* the first is status
- //* the second is [array of structs, each one includes subtitle file].
- //* the third is [double basic value] represent seconds token by server.
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSubtitleDownload();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Download results:");
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new SubtitleDownloadResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "idsubtitlefile": result.IdSubtitleFile = (string)submember.Data.Data; break;
- case "data": result.Data = (string)submember.Data.Data; break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine("> IDSubtilteFile= " + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "DownloadSubtitles call failed !");
- }
-
- public static async Task<IMethodResponse> DownloadSubtitlesAsync(int[] subIDS, CancellationToken cancellationToken)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- if (subIDS == null)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- if (subIDS.Length == 0)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add subtitle search parameters. Each one will be like 'array' of structs.
- var array = new XmlRpcValueArray();
- foreach (int id in subIDS)
- {
- array.Values.Add(new XmlRpcValueBasic(id, XmlRpcBasicValueType.Int));
- }
- // Add the array to the parameters
- parms.Add(array);
- // Call !
- var call = new XmlRpcMethodCall("DownloadSubtitles", parms);
- OSHConsole.WriteLine("Sending DownloadSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
-
- var httpResponse = await Utilities.SendRequestAsync(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT, cancellationToken).ConfigureAwait(false);
-
- string response = Utilities.GetStreamString(httpResponse);
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- // We expect Struct of 3 members:
- //* the first is status
- //* the second is [array of structs, each one includes subtitle file].
- //* the third is [double basic value] represent seconds token by server.
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSubtitleDownload();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Download results:");
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new SubtitleDownloadResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "idsubtitlefile": result.IdSubtitleFile = (string)submember.Data.Data; break;
- case "data": result.Data = (string)submember.Data.Data; break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine("> IDSubtilteFile= " + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "DownloadSubtitles call failed !");
- }
-
- /// <summary>
- /// Returns comments for subtitles
- /// </summary>
- /// <param name="subIDS">The subtitle IDS (an array of IDSubtitleFile value that given by server as SearchSubtiles results)</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseGetComments'</returns>
- public static IMethodResponse GetComments(int[] subIDS)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- if (subIDS == null)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- if (subIDS.Length == 0)
- {
- OSHConsole.UpdateLine("No subtitle id passed !!", DebugCode.Error);
- return new MethodResponseError("Fail", "No subtitle id passed");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN));
- // Add subtitle search parameters. Each one will be like 'array' of structs.
- var array = new XmlRpcValueArray(subIDS);
- // Add the array to the parameters
- parms.Add(array);
- // Call !
- var call = new XmlRpcMethodCall("GetComments", parms);
- OSHConsole.WriteLine("Sending GetComments request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseGetComments();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Comments results:");
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue commentStruct in rarray.Values)
- {
- if (commentStruct == null) continue;
- if (!(commentStruct is XmlRpcValueStruct)) continue;
-
- var result = new GetCommentsResult();
- foreach (XmlRpcStructMember commentmember in ((XmlRpcValueStruct)commentStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (commentmember.Name)
- {
- case "IDSubtitle": result.IDSubtitle = (string)commentmember.Data.Data; break;
- case "UserID": result.UserID = (string)commentmember.Data.Data; break;
- case "UserNickName": result.UserNickName = (string)commentmember.Data.Data; break;
- case "Comment": result.Comment = (string)commentmember.Data.Data; break;
- case "Created": result.Created = (string)commentmember.Data.Data; break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine("> IDSubtitle= " + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "GetComments call failed !");
- }
-
- /// <summary>
- /// Schedule a periodical search for subtitles matching given video files, send results to user's e-mail address.
- /// </summary>
- /// <param name="languageIDS">The language 3 lenght ids array</param>
- /// <param name="movies">The movies parameters</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseSearchToMail'</returns>
- public static IMethodResponse SearchToMail(string[] languageIDS, SearchToMailMovieParameter[] movies)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Array of sub langs
- var a = new XmlRpcValueArray(languageIDS);
- parms.Add(a);
- // Array of video parameters
- a = new XmlRpcValueArray();
- foreach (SearchToMailMovieParameter p in movies)
- {
- var str = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- str.Members.Add(new XmlRpcStructMember("moviehash", new XmlRpcValueBasic(p.moviehash)));
- str.Members.Add(new XmlRpcStructMember("moviesize", new XmlRpcValueBasic(p.moviesize)));
- a.Values.Add(str);
- }
- parms.Add(a);
- var call = new XmlRpcMethodCall("SearchToMail", parms);
-
- OSHConsole.WriteLine("Sending SearchToMail request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSearchToMail();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "SearchToMail call failed !");
- }
- /*Movies*/
- /// <summary>
- /// Search for a movie (using movie title)
- /// </summary>
- /// <param name="query">Movie title user is searching for, this is cleaned-up a bit (remove dvdrip, etc.) before searching </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseSubtitleSearch'</returns>
- public static IMethodResponse SearchMoviesOnIMDB(string query)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add query param
- parms.Add(new XmlRpcValueBasic(query, XmlRpcBasicValueType.String));
- // Call !
- var call = new XmlRpcMethodCall("SearchMoviesOnIMDB", parms);
- OSHConsole.WriteLine("Sending SearchMoviesOnIMDB request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseMovieSearch();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Search results:");
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new MovieSearchResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "id": result.ID = (string)submember.Data.Data; break;
- case "title": result.Title = (string)submember.Data.Data; break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine(">" + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "SearchMoviesOnIMDB call failed !");
- }
- /// <summary>
- /// Get movie details for given IMDb ID
- /// </summary>
- /// <param name="imdbid">http://www.imdb.com/</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseMovieDetails'</returns>
- public static IMethodResponse GetIMDBMovieDetails(string imdbid)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN));
- // Add query param
- parms.Add(new XmlRpcValueBasic(imdbid));
- // Call !
- var call = new XmlRpcMethodCall("GetIMDBMovieDetails", parms);
- OSHConsole.WriteLine("Sending GetIMDBMovieDetails request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseMovieDetails();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "data")
- {
- // We expect struct with details...
- if (MEMBER.Data is XmlRpcValueStruct)
- {
- OSHConsole.WriteLine("Details result:");
- var detailsStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dmem in detailsStruct.Members)
- {
- switch (dmem.Name)
- {
- case "id": R.ID = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "title": R.Title = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "year": R.Year = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "cover": R.CoverLink = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "duration": R.Duration = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "tagline": R.Tagline = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "plot": R.Plot = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "goofs": R.Goofs = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "trivia": R.Trivia = dmem.Data.Data.ToString(); OSHConsole.WriteLine(">" + dmem.Name + "= " + dmem.Data.Data.ToString()); break;
- case "cast":
- // this is another struct with cast members...
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- var castStruct = (XmlRpcValueStruct)dmem.Data;
- foreach (XmlRpcStructMember castMemeber in castStruct.Members)
- {
- R.Cast.Add(castMemeber.Data.Data.ToString());
- OSHConsole.WriteLine(" >" + castMemeber.Data.Data.ToString());
- }
- break;
- case "directors":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is another struct with directors members...
- var directorsStruct = (XmlRpcValueStruct)dmem.Data;
- foreach (XmlRpcStructMember directorsMember in directorsStruct.Members)
- {
- R.Directors.Add(directorsMember.Data.Data.ToString());
- OSHConsole.WriteLine(" >" + directorsMember.Data.Data.ToString());
- }
- break;
- case "writers":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is another struct with writers members...
- var writersStruct = (XmlRpcValueStruct)dmem.Data;
- foreach (XmlRpcStructMember writersMember in writersStruct.Members)
- {
- R.Writers.Add(writersMember.Data.Data.ToString());
- OSHConsole.WriteLine("+->" + writersMember.Data.Data.ToString());
- }
- break;
- case "awards":
- // this is an array of genres...
- var awardsArray = (XmlRpcValueArray)dmem.Data;
- foreach (XmlRpcValueBasic award in awardsArray.Values)
- {
- R.Awards.Add(award.Data.ToString());
- OSHConsole.WriteLine(" >" + award.Data.ToString());
- }
- break;
- case "genres":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is an array of genres...
- var genresArray = (XmlRpcValueArray)dmem.Data;
- foreach (XmlRpcValueBasic genre in genresArray.Values)
- {
- R.Genres.Add(genre.Data.ToString());
- OSHConsole.WriteLine(" >" + genre.Data.ToString());
- }
- break;
- case "country":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is an array of country...
- var countryArray = (XmlRpcValueArray)dmem.Data;
- foreach (XmlRpcValueBasic country in countryArray.Values)
- {
- R.Country.Add(country.Data.ToString());
- OSHConsole.WriteLine(" >" + country.Data.ToString());
- }
- break;
- case "language":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is an array of language...
- var languageArray = (XmlRpcValueArray)dmem.Data;
- foreach (XmlRpcValueBasic language in languageArray.Values)
- {
- R.Language.Add(language.Data.ToString());
- OSHConsole.WriteLine(" >" + language.Data.ToString());
- }
- break;
- case "certification":
- OSHConsole.WriteLine(">" + dmem.Name + "= ");
- // this is an array of certification...
- var certificationArray = (XmlRpcValueArray)dmem.Data;
- foreach (XmlRpcValueBasic certification in certificationArray.Values)
- {
- R.Certification.Add(certification.Data.ToString());
- OSHConsole.WriteLine(" >" + certification.Data.ToString());
- }
- break;
- }
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "GetIMDBMovieDetails call failed !");
- }
- /// <summary>
- /// Allows registered users to insert new movies (not stored in IMDb) to the database.
- /// </summary>
- /// <param name="movieName">Movie title </param>
- /// <param name="movieyear">Release year </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseInsertMovie'</returns>
- public static IMethodResponse InsertMovie(string movieName, string movieyear)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // Add token param
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // Add movieinfo struct
- var movieinfo = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- movieinfo.Members.Add(new XmlRpcStructMember("moviename", new XmlRpcValueBasic(movieName)));
- movieinfo.Members.Add(new XmlRpcStructMember("movieyear", new XmlRpcValueBasic(movieyear)));
- parms.Add(movieinfo);
- // Call !
- var call = new XmlRpcMethodCall("InsertMovie", parms);
- OSHConsole.WriteLine("Sending InsertMovie request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseInsertMovie();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- if (MEMBER.Name == "status")
- {
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("Status= " + R.Status);
- }
- else if (MEMBER.Name == "seconds")
- {
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine("Seconds= " + R.Seconds);
- }
- else if (MEMBER.Name == "id")
- {
- R.ID = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine("ID= " + R.Seconds);
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "InsertMovie call failed !");
- }
- /// <summary>
- /// Inserts or updates data to tables, which are used for CheckMovieHash() and !CheckMovieHash2().
- /// </summary>
- /// <param name="parameters">The parameters</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseInsertMovieHash'</returns>
- public static IMethodResponse InsertMovieHash(InsertMovieHashParameters[] parameters)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- foreach (InsertMovieHashParameters p in parameters)
- {
- var pstruct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- pstruct.Members.Add(new XmlRpcStructMember("moviehash", new XmlRpcValueBasic(p.moviehash)));
- pstruct.Members.Add(new XmlRpcStructMember("moviebytesize", new XmlRpcValueBasic(p.moviebytesize)));
- pstruct.Members.Add(new XmlRpcStructMember("imdbid", new XmlRpcValueBasic(p.imdbid)));
- pstruct.Members.Add(new XmlRpcStructMember("movietimems", new XmlRpcValueBasic(p.movietimems)));
- pstruct.Members.Add(new XmlRpcStructMember("moviefps", new XmlRpcValueBasic(p.moviefps)));
- pstruct.Members.Add(new XmlRpcStructMember("moviefilename", new XmlRpcValueBasic(p.moviefilename)));
- parms.Add(pstruct);
- }
- var call = new XmlRpcMethodCall("InsertMovieHash", parms);
-
- OSHConsole.WriteLine("Sending InsertMovieHash request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseInsertMovieHash();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status":
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "seconds":
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- switch (dataMember.Name)
- {
- case "accepted_moviehashes":
- var mh = (XmlRpcValueArray)dataMember.Data;
- foreach (IXmlRpcValue val in mh.Values)
- {
- if (val is XmlRpcValueBasic)
- {
- R.accepted_moviehashes.Add(val.Data.ToString());
- }
- }
- break;
- case "new_imdbs":
- var mi = (XmlRpcValueArray)dataMember.Data;
- foreach (IXmlRpcValue val in mi.Values)
- {
- if (val is XmlRpcValueBasic)
- {
- R.new_imdbs.Add(val.Data.ToString());
- }
- }
- break;
- }
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "InsertMovieHash call failed !");
- }
- /*Reporting and rating*/
- /// <summary>
- /// Get basic server information and statistics
- /// </summary>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseServerInfo'</returns>
- public static IMethodResponse ServerInfo()
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT, XmlRpcBasicValueType.String));
- var call = new XmlRpcMethodCall("ServerInfo", parms);
-
- OSHConsole.WriteLine("Sending ServerInfo request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseServerInfo();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status":
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "seconds":
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "xmlrpc_version":
- R.xmlrpc_version = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "xmlrpc_url":
- R.xmlrpc_url = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "application":
- R.application = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "contact":
- R.contact = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "website_url":
- R.website_url = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "users_online_total":
- R.users_online_total = (int)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "users_online_program":
- R.users_online_program = (int)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "users_loggedin":
- R.users_loggedin = (int)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "users_max_alltime":
- R.users_max_alltime = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "users_registered":
- R.users_registered = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "subs_downloads":
- R.subs_downloads = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "subs_subtitle_files":
- R.subs_subtitle_files = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "movies_total":
- R.movies_total = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "movies_aka":
- R.movies_aka = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "total_subtitles_languages":
- R.total_subtitles_languages = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "last_update_strings":
- //R.total_subtitles_languages = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + ":");
- var luStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember luMemeber in luStruct.Members)
- {
- R.last_update_strings.Add(luMemeber.Name + " [" + luMemeber.Data.Data.ToString() + "]");
- OSHConsole.WriteLine(" >" + luMemeber.Name + "= " + luMemeber.Data.Data.ToString());
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "ServerInfo call failed !");
- }
- /// <summary>
- /// Report wrong subtitle file <--> video file combination
- /// </summary>
- /// <param name="IDSubMovieFile">Identifier of the subtitle file <--> video file combination </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseReportWrongMovieHash'</returns>
- public static IMethodResponse ReportWrongMovieHash(string IDSubMovieFile)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- parms.Add(new XmlRpcValueBasic(IDSubMovieFile, XmlRpcBasicValueType.String));
- var call = new XmlRpcMethodCall("ReportWrongMovieHash", parms);
-
- OSHConsole.WriteLine("Sending ReportWrongMovieHash request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseReportWrongMovieHash();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status":
- R.Status = (string)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- case "seconds":
- R.Seconds = (double)MEMBER.Data.Data;
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString());
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "ReportWrongMovieHash call failed !");
- }
- /// <summary>
- /// This method is needed to report bad movie hash for imdbid. This method should be used for correcting wrong entries,
- /// when using CheckMovieHash2. Pass moviehash and moviebytesize for file, and imdbid as new, corrected one IMDBID
- /// (id number without trailing zeroes). After some reports, moviehash will be linked to new imdbid.
- /// </summary>
- /// <param name="moviehash">The movie hash</param>
- /// <param name="moviebytesize">The movie size in bytes</param>
- /// <param name="imdbid">The movie imbid</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseReportWrongImdbMovie'</returns>
- public static IMethodResponse ReportWrongImdbMovie(string moviehash, string moviebytesize, string imdbid)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- s.Members.Add(new XmlRpcStructMember("moviehash", new XmlRpcValueBasic(moviehash)));
- s.Members.Add(new XmlRpcStructMember("moviebytesize", new XmlRpcValueBasic(moviebytesize)));
- s.Members.Add(new XmlRpcStructMember("imdbid", new XmlRpcValueBasic(imdbid)));
- parms.Add(s);
- var call = new XmlRpcMethodCall("ReportWrongImdbMovie", parms);
-
- OSHConsole.WriteLine("Sending ReportWrongImdbMovie request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseAddComment();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "ReportWrongImdbMovie call failed !");
- }
- /// <summary>
- /// Rate subtitles
- /// </summary>
- /// <param name="idsubtitle">Id of subtitle (NOT subtitle file) user wants to rate </param>
- /// <param name="score">Subtitle rating, must be in interval 1 (worst) to 10 (best). </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseSubtitlesVote'</returns>
- public static IMethodResponse SubtitlesVote(int idsubtitle, int score)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- s.Members.Add(new XmlRpcStructMember("idsubtitle", new XmlRpcValueBasic(idsubtitle)));
- s.Members.Add(new XmlRpcStructMember("score", new XmlRpcValueBasic(score)));
- parms.Add(s);
- var call = new XmlRpcMethodCall("SubtitlesVote", parms);
-
- OSHConsole.WriteLine("Sending SubtitlesVote request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseSubtitlesVote();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dataMemeber in dataStruct.Members)
- {
- OSHConsole.WriteLine(" >" + dataMemeber.Name + "= " + dataMemeber.Data.Data.ToString());
- switch (dataMemeber.Name)
- {
- case "SubRating": R.SubRating = dataMemeber.Data.Data.ToString(); break;
- case "SubSumVotes": R.SubSumVotes = dataMemeber.Data.Data.ToString(); break;
- case "IDSubtitle": R.IDSubtitle = dataMemeber.Data.Data.ToString(); break;
- }
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "SubtitlesVote call failed !");
- }
- /// <summary>
- /// Add comment to a subtitle
- /// </summary>
- /// <param name="idsubtitle">Subtitle identifier (BEWARE! this is not the ID of subtitle file but of the whole subtitle (a subtitle can contain multiple subtitle files))</param>
- /// <param name="comment">User's comment</param>
- /// <param name="badsubtitle">Optional parameter. If set to 1, subtitles are marked as bad.</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseAddComment'</returns>
- public static IMethodResponse AddComment(int idsubtitle, string comment, int badsubtitle)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- s.Members.Add(new XmlRpcStructMember("idsubtitle", new XmlRpcValueBasic(idsubtitle)));
- s.Members.Add(new XmlRpcStructMember("comment", new XmlRpcValueBasic(comment)));
- s.Members.Add(new XmlRpcStructMember("badsubtitle", new XmlRpcValueBasic(badsubtitle)));
- parms.Add(s);
- var call = new XmlRpcMethodCall("AddComment", parms);
-
- OSHConsole.WriteLine("Sending AddComment request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseAddComment();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (var MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "AddComment call failed !");
- }
- /// <summary>
- /// Add new request for subtitles, user must be logged in
- /// </summary>
- /// <param name="sublanguageid">The subtitle language id 3 length</param>
- /// <param name="idmovieimdb">http://www.imdb.com/</param>
- /// <param name="comment">The comment</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseAddRequest'</returns>
- public static IMethodResponse AddRequest(string sublanguageid, string idmovieimdb, string comment)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- s.Members.Add(new XmlRpcStructMember("sublanguageid", new XmlRpcValueBasic(sublanguageid)));
- s.Members.Add(new XmlRpcStructMember("idmovieimdb", new XmlRpcValueBasic(idmovieimdb)));
- s.Members.Add(new XmlRpcStructMember("comment", new XmlRpcValueBasic(comment)));
- parms.Add(s);
- var call = new XmlRpcMethodCall("AddRequest", parms);
-
- OSHConsole.WriteLine("Sending AddRequest request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseAddRequest();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dataMemeber in dataStruct.Members)
- {
- switch (dataMemeber.Name)
- {
- case "request_url": R.request_url = dataMemeber.Data.Data.ToString(); OSHConsole.WriteLine(">" + dataMemeber.Name + "= " + dataMemeber.Data.Data.ToString()); break;
- }
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "AddRequest call failed !");
- }
- /*User interface*/
- /// <summary>
- /// Get list of supported subtitle languages
- /// </summary>
- /// <param name="language">ISO639-1 2-letter language code of user's interface language. </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseGetSubLanguages'</returns>
- public static IMethodResponse GetSubLanguages(string language)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueBasic(language));
- var call = new XmlRpcMethodCall("GetSubLanguages", parms);
-
- OSHConsole.WriteLine("Sending GetSubLanguages request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseGetSubLanguages();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":// array of structs
- var array = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue value in array.Values)
- {
- if (value is XmlRpcValueStruct)
- {
- var valueStruct = (XmlRpcValueStruct)value;
- var lang = new SubtitleLanguage();
- OSHConsole.WriteLine(">SubLanguage:");
- foreach (XmlRpcStructMember langMemeber in valueStruct.Members)
- {
- OSHConsole.WriteLine(" >" + langMemeber.Name + "= " + langMemeber.Data.Data.ToString());
- switch (langMemeber.Name)
- {
- case "SubLanguageID": lang.SubLanguageID = langMemeber.Data.Data.ToString(); break;
- case "LanguageName": lang.LanguageName = langMemeber.Data.Data.ToString(); break;
- case "ISO639": lang.ISO639 = langMemeber.Data.Data.ToString(); break;
- }
- }
- R.Languages.Add(lang);
- }
- else
- {
- OSHConsole.WriteLine(">" + MEMBER.Name + "= " +
- MEMBER.Data.Data.ToString() + " [Struct expected !]", DebugCode.Warning);
- }
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "GetSubLanguages call failed !");
- }
- /// <summary>
- /// Detect language for given strings
- /// </summary>
- /// <param name="texts">Array of strings you want language detected for</param>
- /// <param name="encodingUsed">The encoding that will be used to get buffer of given strings. (this is not OS official parameter)</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseDetectLanguage'</returns>
- public static IMethodResponse DetectLanguage(string[] texts, Encoding encodingUsed)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- // We need to gzip texts then code them with base 24
- var decodedTexts = new List<string>();
- foreach (string text in texts)
- {
- // compress
- Stream str = new MemoryStream();
- byte[] stringData = encodingUsed.GetBytes(text);
- str.Write(stringData, 0, stringData.Length);
- str.Position = 0;
- byte[] data = Utilities.Compress(str);
- //base 64
- decodedTexts.Add(Convert.ToBase64String(data));
- }
- parms.Add(new XmlRpcValueArray(decodedTexts.ToArray()));
- var call = new XmlRpcMethodCall("DetectLanguage", parms);
-
- OSHConsole.WriteLine("Sending DetectLanguage request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseDetectLanguage();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- if (MEMBER.Data is XmlRpcValueStruct)
- {
- OSHConsole.WriteLine(">Languages:");
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- var lang = new DetectLanguageResult();
- lang.InputSample = dataMember.Name;
- lang.LanguageID = dataMember.Data.Data.ToString();
- R.Results.Add(lang);
- OSHConsole.WriteLine(" >" + dataMember.Name + " (" + dataMember.Data.Data.ToString() + ")");
- }
- }
- else
- {
- OSHConsole.WriteLine(">Languages ?? Struct expected but server return another type!!", DebugCode.Warning);
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "DetectLanguage call failed !");
- }
- /// <summary>
- /// Get available translations for given program
- /// </summary>
- /// <param name="program">Name of the program/client application you want translations for. Currently supported values: subdownloader, oscar</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseGetAvailableTranslations'</returns>
- public static IMethodResponse GetAvailableTranslations(string program)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueBasic(program));
- var call = new XmlRpcMethodCall("GetAvailableTranslations", parms);
-
- OSHConsole.WriteLine("Sending GetAvailableTranslations request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseGetAvailableTranslations();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- OSHConsole.WriteLine(">data:");
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- if (dataMember.Data is XmlRpcValueStruct)
- {
- var resStruct = (XmlRpcValueStruct)dataMember.Data;
- var res = new GetAvailableTranslationsResult();
- res.LanguageID = dataMember.Name;
- OSHConsole.WriteLine(" >LanguageID: " + dataMember.Name);
- foreach (XmlRpcStructMember resMember in resStruct.Members)
- {
- switch (resMember.Name)
- {
- case "LastCreated": res.LastCreated = resMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + resMember.Name + "= " + resMember.Data.Data.ToString()); break;
- case "StringsNo": res.StringsNo = resMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + resMember.Name + "= " + resMember.Data.Data.ToString()); break;
- }
- R.Results.Add(res);
- }
- }
- else
- {
- OSHConsole.WriteLine(" >Struct expected !!", DebugCode.Warning);
- }
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "GetAvailableTranslations call failed !");
- }
- /// <summary>
- /// Get a translation for given program and language
- /// </summary>
- /// <param name="iso639">language ​ISO639-1 2-letter code </param>
- /// <param name="format">available formats: [gnugettext compatible: mo, po] and [additional: txt, xml]</param>
- /// <param name="program">Name of the program/client application you want translations for. (currently supported values: subdownloader, oscar)</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseGetTranslation'</returns>
- public static IMethodResponse GetTranslation(string iso639, string format, string program)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueBasic(iso639));
- parms.Add(new XmlRpcValueBasic(format));
- parms.Add(new XmlRpcValueBasic(program));
- var call = new XmlRpcMethodCall("GetTranslation", parms);
-
- OSHConsole.WriteLine("Sending GetTranslation request to the server ...", DebugCode.Good);
- // Send the request to the server
- //File.WriteAllText(".\\REQUEST_GetTranslation.xml", Encoding.ASCII.GetString(XmlRpcGenerator.Generate(call)));
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseGetTranslation();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data": R.ContentData = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "GetTranslation call failed !");
- }
- /// <summary>
- /// Check for the latest version of given application
- /// </summary>
- /// <param name="program">name of the program/client application you want to check. (Currently supported values: subdownloader, oscar)</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseAutoUpdate'</returns>
- public static IMethodResponse AutoUpdate(string program)
- {
- /*if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }*/
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- // parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueBasic(program));
- // parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT));
-
- var call = new XmlRpcMethodCall("AutoUpdate", parms);
- OSHConsole.WriteLine("Sending AutoUpdate request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseAutoUpdate();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "version": R.version = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "url_windows": R.url_windows = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "url_linux": R.url_linux = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "comments": R.comments = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "AutoUpdate call failed !");
- }
- /*Checking*/
- /// <summary>
- /// Check if video file hashes are already stored in the database
- /// </summary>
- /// <param name="hashes">Array of video file hashes</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseCheckMovieHash'</returns>
- public static IMethodResponse CheckMovieHash(string[] hashes)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueArray(hashes));
- var call = new XmlRpcMethodCall("CheckMovieHash", parms);
-
- OSHConsole.WriteLine("Sending CheckMovieHash request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseCheckMovieHash();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- OSHConsole.WriteLine(">Data:");
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- var res = new CheckMovieHashResult();
- res.Name = dataMember.Name;
- OSHConsole.WriteLine(" >" + res.Name + ":");
- var movieStruct = (XmlRpcValueStruct)dataMember.Data;
- foreach (XmlRpcStructMember movieMember in movieStruct.Members)
- {
- switch (movieMember.Name)
- {
- case "MovieHash": res.MovieHash = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieImdbID": res.MovieImdbID = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieName": res.MovieName = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieYear": res.MovieYear = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- }
- }
- R.Results.Add(res);
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "CheckMovieHash call failed !");
- }
- /// <summary>
- /// Check if video file hashes are already stored in the database. This method returns matching !MovieImdbID, MovieName, MovieYear, SeriesSeason, SeriesEpisode,
- /// MovieKind if available for each $moviehash, always sorted by SeenCount DESC.
- /// </summary>
- /// <param name="hashes">Array of video file hashes</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseCheckMovieHash2'</returns>
- public static IMethodResponse CheckMovieHash2(string[] hashes)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueArray(hashes));
- var call = new XmlRpcMethodCall("CheckMovieHash2", parms);
-
- OSHConsole.WriteLine("Sending CheckMovieHash2 request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseCheckMovieHash2();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- OSHConsole.WriteLine(">Data:");
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- var res = new CheckMovieHash2Result();
- res.Name = dataMember.Name;
- OSHConsole.WriteLine(" >" + res.Name + ":");
-
- var dataArray = (XmlRpcValueArray)dataMember.Data;
- foreach (XmlRpcValueStruct movieStruct in dataArray.Values)
- {
- var d = new CheckMovieHash2Data();
- foreach (XmlRpcStructMember movieMember in movieStruct.Members)
- {
- switch (movieMember.Name)
- {
- case "MovieHash": d.MovieHash = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieImdbID": d.MovieImdbID = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieName": d.MovieName = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieYear": d.MovieYear = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "MovieKind": d.MovieKind = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "SeriesSeason": d.SeriesSeason = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "SeriesEpisode": d.SeriesEpisode = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- case "SeenCount": d.MovieYear = movieMember.Data.Data.ToString(); OSHConsole.WriteLine(" >" + movieMember.Name + "= " + movieMember.Data.Data.ToString()); break;
- }
- }
- res.Items.Add(d);
- }
- R.Results.Add(res);
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "CheckMovieHash2 call failed !");
- }
- /// <summary>
- /// Check if given subtitle files are already stored in the database
- /// </summary>
- /// <param name="hashes">Array of subtitle file hashes (MD5 hashes of subtitle file contents) </param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseCheckSubHash'</returns>
- public static IMethodResponse CheckSubHash(string[] hashes)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- parms.Add(new XmlRpcValueArray(hashes));
- var call = new XmlRpcMethodCall("CheckSubHash", parms);
-
- OSHConsole.WriteLine("Sending CheckSubHash request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseCheckSubHash();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- OSHConsole.WriteLine(">Data:");
- var dataStruct = (XmlRpcValueStruct)MEMBER.Data;
- foreach (XmlRpcStructMember dataMember in dataStruct.Members)
- {
- OSHConsole.WriteLine(" >" + dataMember.Name + "= " + dataMember.Data.Data.ToString());
- var r = new CheckSubHashResult();
- r.Hash = dataMember.Name;
- r.SubID = dataMember.Data.Data.ToString();
- R.Results.Add(r);
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "CheckSubHash call failed !");
- }
- /*Upload*/
- /// <summary>
- /// Try to upload subtitles, perform pre-upload checking (i.e. check if subtitles already exist on server)
- /// </summary>
- /// <param name="subs">The subtitle parameters collection to try to upload</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseTryUploadSubtitles'</returns>
- public static IMethodResponse TryUploadSubtitles(TryUploadSubtitlesParameters[] subs)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN, XmlRpcBasicValueType.String));
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- int i = 1;
- foreach (var cd in subs)
- {
- var member = new XmlRpcStructMember("cd" + i, null);
- var memberStruct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- memberStruct.Members.Add(new XmlRpcStructMember("subhash", new XmlRpcValueBasic(cd.subhash)));
- memberStruct.Members.Add(new XmlRpcStructMember("subfilename", new XmlRpcValueBasic(cd.subfilename)));
- memberStruct.Members.Add(new XmlRpcStructMember("moviehash", new XmlRpcValueBasic(cd.moviehash)));
- memberStruct.Members.Add(new XmlRpcStructMember("moviebytesize", new XmlRpcValueBasic(cd.moviebytesize)));
- memberStruct.Members.Add(new XmlRpcStructMember("moviefps", new XmlRpcValueBasic(cd.moviefps)));
- memberStruct.Members.Add(new XmlRpcStructMember("movietimems", new XmlRpcValueBasic(cd.movietimems)));
- memberStruct.Members.Add(new XmlRpcStructMember("movieframes", new XmlRpcValueBasic(cd.movieframes)));
- memberStruct.Members.Add(new XmlRpcStructMember("moviefilename", new XmlRpcValueBasic(cd.moviefilename)));
- member.Data = memberStruct;
- s.Members.Add(member);
- i++;
- }
- parms.Add(s);
- var call = new XmlRpcMethodCall("TryUploadSubtitles", parms);
-
- OSHConsole.WriteLine("Sending TryUploadSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseTryUploadSubtitles();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "alreadyindb": R.AlreadyInDB = (int)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data":
- if (MEMBER.Data is XmlRpcValueArray)
- {
- OSHConsole.WriteLine("Results: ");
-
- var rarray = (XmlRpcValueArray)MEMBER.Data;
- foreach (IXmlRpcValue subStruct in rarray.Values)
- {
- if (subStruct == null) continue;
- if (!(subStruct is XmlRpcValueStruct)) continue;
-
- var result = new SubtitleSearchResult();
- foreach (XmlRpcStructMember submember in ((XmlRpcValueStruct)subStruct).Members)
- {
- // To avoid errors of arranged info or missing ones, let's do it with switch..
- switch (submember.Name)
- {
- case "IDMovie": result.IDMovie = submember.Data.Data.ToString(); break;
- case "IDMovieImdb": result.IDMovieImdb = submember.Data.Data.ToString(); break;
- case "IDSubMovieFile": result.IDSubMovieFile = submember.Data.Data.ToString(); break;
- case "IDSubtitle": result.IDSubtitle = submember.Data.Data.ToString(); break;
- case "IDSubtitleFile": result.IDSubtitleFile = submember.Data.Data.ToString(); break;
- case "ISO639": result.ISO639 = submember.Data.Data.ToString(); break;
- case "LanguageName": result.LanguageName = submember.Data.Data.ToString(); break;
- case "MovieByteSize": result.MovieByteSize = submember.Data.Data.ToString(); break;
- case "MovieHash": result.MovieHash = submember.Data.Data.ToString(); break;
- case "MovieImdbRating": result.MovieImdbRating = submember.Data.Data.ToString(); break;
- case "MovieName": result.MovieName = submember.Data.Data.ToString(); break;
- case "MovieNameEng": result.MovieNameEng = submember.Data.Data.ToString(); break;
- case "MovieReleaseName": result.MovieReleaseName = submember.Data.Data.ToString(); break;
- case "MovieTimeMS": result.MovieTimeMS = submember.Data.Data.ToString(); break;
- case "MovieYear": result.MovieYear = submember.Data.Data.ToString(); break;
- case "SubActualCD": result.SubActualCD = submember.Data.Data.ToString(); break;
- case "SubAddDate": result.SubAddDate = submember.Data.Data.ToString(); break;
- case "SubAuthorComment": result.SubAuthorComment = submember.Data.Data.ToString(); break;
- case "SubBad": result.SubBad = submember.Data.Data.ToString(); break;
- case "SubDownloadLink": result.SubDownloadLink = submember.Data.Data.ToString(); break;
- case "SubDownloadsCnt": result.SubDownloadsCnt = submember.Data.Data.ToString(); break;
- case "SubFileName": result.SubFileName = submember.Data.Data.ToString(); break;
- case "SubFormat": result.SubFormat = submember.Data.Data.ToString(); break;
- case "SubHash": result.SubHash = submember.Data.Data.ToString(); break;
- case "SubLanguageID": result.SubLanguageID = submember.Data.Data.ToString(); break;
- case "SubRating": result.SubRating = submember.Data.Data.ToString(); break;
- case "SubSize": result.SubSize = submember.Data.Data.ToString(); break;
- case "SubSumCD": result.SubSumCD = submember.Data.Data.ToString(); break;
- case "UserID": result.UserID = submember.Data.Data.ToString(); break;
- case "UserNickName": result.UserNickName = submember.Data.Data.ToString(); break;
- case "ZipDownloadLink": result.ZipDownloadLink = submember.Data.Data.ToString(); break;
- }
- }
- R.Results.Add(result);
- OSHConsole.WriteLine(">" + result.ToString());
- }
- }
- else// Unknown data ?
- {
- OSHConsole.WriteLine("Data= " + MEMBER.Data.Data.ToString(), DebugCode.Warning);
- }
- break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "TryUploadSubtitles call failed !");
- }
- /// <summary>
- /// Upload given subtitles to OSDb server
- /// </summary>
- /// <param name="info">The pamaters of upload method</param>
- /// <returns>Status of the call operation. If the call success the response will be 'MethodResponseUploadSubtitles'</returns>
- public static IMethodResponse UploadSubtitles(UploadSubtitleInfoParameters info)
- {
- if (TOKEN == "")
- {
- OSHConsole.WriteLine("Can't do this call, 'token' value not set. Please use Log In method first.", DebugCode.Error);
- return new MethodResponseError("Fail", "Can't do this call, 'token' value not set. Please use Log In method first.");
- }
- // Method call ..
- var parms = new List<IXmlRpcValue>();
- parms.Add(new XmlRpcValueBasic(TOKEN));
- // Main struct
- var s = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
-
- // Base info member as struct
- var member = new XmlRpcStructMember("baseinfo", null);
- var memberStruct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- memberStruct.Members.Add(new XmlRpcStructMember("idmovieimdb", new XmlRpcValueBasic(info.idmovieimdb)));
- memberStruct.Members.Add(new XmlRpcStructMember("sublanguageid", new XmlRpcValueBasic(info.sublanguageid)));
- memberStruct.Members.Add(new XmlRpcStructMember("moviereleasename", new XmlRpcValueBasic(info.moviereleasename)));
- memberStruct.Members.Add(new XmlRpcStructMember("movieaka", new XmlRpcValueBasic(info.movieaka)));
- memberStruct.Members.Add(new XmlRpcStructMember("subauthorcomment", new XmlRpcValueBasic(info.subauthorcomment)));
- // memberStruct.Members.Add(new XmlRpcStructMember("hearingimpaired", new XmlRpcValueBasic(info.hearingimpaired)));
- // memberStruct.Members.Add(new XmlRpcStructMember("highdefinition", new XmlRpcValueBasic(info.highdefinition)));
- // memberStruct.Members.Add(new XmlRpcStructMember("automatictranslation", new XmlRpcValueBasic(info.automatictranslation)));
- member.Data = memberStruct;
- s.Members.Add(member);
-
- // CDS members
- int i = 1;
- foreach (UploadSubtitleParameters cd in info.CDS)
- {
- var member2 = new XmlRpcStructMember("cd" + i, null);
- var memberStruct2 = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- memberStruct2.Members.Add(new XmlRpcStructMember("subhash", new XmlRpcValueBasic(cd.subhash)));
- memberStruct2.Members.Add(new XmlRpcStructMember("subfilename", new XmlRpcValueBasic(cd.subfilename)));
- memberStruct2.Members.Add(new XmlRpcStructMember("moviehash", new XmlRpcValueBasic(cd.moviehash)));
- memberStruct2.Members.Add(new XmlRpcStructMember("moviebytesize", new XmlRpcValueBasic(cd.moviebytesize)));
- memberStruct2.Members.Add(new XmlRpcStructMember("moviefps", new XmlRpcValueBasic(cd.moviefps)));
- memberStruct2.Members.Add(new XmlRpcStructMember("movietimems", new XmlRpcValueBasic(cd.movietimems)));
- memberStruct2.Members.Add(new XmlRpcStructMember("movieframes", new XmlRpcValueBasic(cd.movieframes)));
- memberStruct2.Members.Add(new XmlRpcStructMember("moviefilename", new XmlRpcValueBasic(cd.moviefilename)));
- memberStruct2.Members.Add(new XmlRpcStructMember("subcontent", new XmlRpcValueBasic(cd.subcontent)));
- member2.Data = memberStruct2;
- s.Members.Add(member2);
- i++;
- }
-
- // add main struct to parameters
- parms.Add(s);
- // add user agent
- //parms.Add(new XmlRpcValueBasic(XML_PRC_USERAGENT));
- var call = new XmlRpcMethodCall("UploadSubtitles", parms);
- OSHConsole.WriteLine("Sending UploadSubtitles request to the server ...", DebugCode.Good);
- // Send the request to the server
- string response = Utilities.GetStreamString(Utilities.SendRequest(XmlRpcGenerator.Generate(call), XML_PRC_USERAGENT));
- if (!response.Contains("ERROR:"))
- {
- // No error occur, get and decode the response.
- XmlRpcMethodCall[] calls = XmlRpcGenerator.DecodeMethodResponse(response);
- if (calls.Length > 0)
- {
- if (calls[0].Parameters.Count > 0)
- {
- var mainStruct = (XmlRpcValueStruct)calls[0].Parameters[0];
- // Create the response, we'll need it later
- var R = new MethodResponseUploadSubtitles();
-
- // To make sure response is not currepted by server, do it in loop
- foreach (XmlRpcStructMember MEMBER in mainStruct.Members)
- {
- switch (MEMBER.Name)
- {
- case "status": R.Status = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "seconds": R.Seconds = (double)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "data": R.Data = (string)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- case "subtitles": R.SubTitles = (bool)MEMBER.Data.Data; OSHConsole.WriteLine(">" + MEMBER.Name + "= " + MEMBER.Data.Data.ToString()); break;
- }
- }
- // Return the response to user !!
- return R;
- }
- }
- }
- else
- {
- OSHConsole.WriteLine(response, DebugCode.Error);
- return new MethodResponseError("Fail", response);
- }
- return new MethodResponseError("Fail", "UploadSubtitles call failed !");
- }
- }
-}
diff --git a/OpenSubtitlesHandler/OpenSubtitlesHandler.csproj b/OpenSubtitlesHandler/OpenSubtitlesHandler.csproj
deleted file mode 100644
index eabd3e070..000000000
--- a/OpenSubtitlesHandler/OpenSubtitlesHandler.csproj
+++ /dev/null
@@ -1,13 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/OpenSubtitlesHandler/OtherTypes/GetAvailableTranslationsResult.cs b/OpenSubtitlesHandler/OtherTypes/GetAvailableTranslationsResult.cs
deleted file mode 100644
index 39d048545..000000000
--- a/OpenSubtitlesHandler/OtherTypes/GetAvailableTranslationsResult.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- public struct GetAvailableTranslationsResult
- {
- private string _language;
- private string _LastCreated;
- private string _StringsNo;
-
- public string LanguageID { get { return _language; } set { _language = value; } }
- public string LastCreated { get { return _LastCreated; } set { _LastCreated = value; } }
- public string StringsNo { get { return _StringsNo; } set { _StringsNo = value; } }
- /// <summary>
- /// LanguageID (LastCreated)
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return _language + " (" + _LastCreated + ")";
- }
- }
-}
diff --git a/OpenSubtitlesHandler/OtherTypes/GetCommentsResult.cs b/OpenSubtitlesHandler/OtherTypes/GetCommentsResult.cs
deleted file mode 100644
index 8f4aa9db4..000000000
--- a/OpenSubtitlesHandler/OtherTypes/GetCommentsResult.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct GetCommentsResult
- {
- private string _IDSubtitle;
- private string _UserID;
- private string _UserNickName;
- private string _Comment;
- private string _Created;
-
- public string IDSubtitle { get { return _IDSubtitle; } set { _IDSubtitle = value; } }
- public string UserID { get { return _UserID; } set { _UserID = value; } }
- public string UserNickName { get { return _UserNickName; } set { _UserNickName = value; } }
- public string Comment { get { return _Comment; } set { _Comment = value; } }
- public string Created { get { return _Created; } set { _Created = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/Properties/AssemblyInfo.cs b/OpenSubtitlesHandler/Properties/AssemblyInfo.cs
deleted file mode 100644
index b5ae23021..000000000
--- a/OpenSubtitlesHandler/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("OpenSubtitlesHandler")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2013 Ala Ibrahim Hadid. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-[assembly: AssemblyVersion("1.0.3.0")]
-[assembly: AssemblyFileVersion("2019.1.20.3")]
diff --git a/OpenSubtitlesHandler/Readme.txt b/OpenSubtitlesHandler/Readme.txt
deleted file mode 100644
index d5814aec1..000000000
--- a/OpenSubtitlesHandler/Readme.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-OpenSubtitlesHandler
-====================
-This project is for OpenSubtitles.org integration‏. The point is to allow user to access OpenSubtitles.org database directly
-within ASM without the need to open internet browser.
-The plan: Implement the "OSDb protocol" http://trac.opensubtitles.org/projects/opensubtitles/wiki/OSDb
-
-Copyright:
-=========
-This library ann all its content are written by Ala Ibrahim Hadid.
-Copyright © Ala Ibrahim Hadid 2013
-mailto:ahdsoftwares@hotmail.com
-
-Resources:
-==========
-* GetHash.dll: this dll is used to compute hash for movie.
- For more information please visit http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#C2
-
-XML_RPC:
-========
-This class is created to generate XML-RPC requests as XML String. All you need is to call XML_RPC.Generate() method.
diff --git a/OpenSubtitlesHandler/SubtitleTypes/CheckSubHashResult.cs b/OpenSubtitlesHandler/SubtitleTypes/CheckSubHashResult.cs
deleted file mode 100644
index a2fbe8773..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/CheckSubHashResult.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct CheckSubHashResult
- {
- private string _hash;
- private string _id;
-
- public string Hash { get { return _hash; } set { _hash = value; } }
- public string SubID { get { return _id; } set { _id = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/SubtitleDownloadResult.cs b/OpenSubtitlesHandler/SubtitleTypes/SubtitleDownloadResult.cs
deleted file mode 100644
index e4194994c..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/SubtitleDownloadResult.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct SubtitleDownloadResult
- {
- private string idsubtitlefile;
- private string data;
-
- public string IdSubtitleFile
- { get { return idsubtitlefile; } set { idsubtitlefile = value; } }
- /// <summary>
- /// Get or set the data of subtitle file. To decode, decode the string to base64 and then decompress with GZIP.
- /// </summary>
- public string Data
- { get { return data; } set { data = value; } }
- /// <summary>
- /// IdSubtitleFile
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return idsubtitlefile.ToString();
- }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/SubtitleLanguage.cs b/OpenSubtitlesHandler/SubtitleTypes/SubtitleLanguage.cs
deleted file mode 100644
index b2dc15413..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/SubtitleLanguage.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace OpenSubtitlesHandler
-{
- public struct SubtitleLanguage
- {
- private string _SubLanguageID;
- private string _LanguageName;
- private string _ISO639;
-
- public string SubLanguageID { get { return _SubLanguageID; } set { _SubLanguageID = value; } }
- public string LanguageName { get { return _LanguageName; } set { _LanguageName = value; } }
- public string ISO639 { get { return _ISO639; } set { _ISO639 = value; } }
- /// <summary>
- /// LanguageName [SubLanguageID]
- /// </summary>
- /// <returns>LanguageName [SubLanguageID]</returns>
- public override string ToString()
- {
- return _LanguageName + " [" + _SubLanguageID + "]";
- }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchParameters.cs b/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchParameters.cs
deleted file mode 100644
index 5c8f8c01a..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchParameters.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Paramaters for subtitle search call
- /// </summary>
- public struct SubtitleSearchParameters
- {
- public SubtitleSearchParameters(string subLanguageId, string query = "", string season = "", string episode = "", string movieHash = "", long movieByteSize = 0, string imdbid = "")
- {
- this.subLanguageId = subLanguageId;
- this.movieHash = movieHash;
- this.movieByteSize = movieByteSize;
- this.imdbid = imdbid;
- this._episode = episode;
- this._season = season;
- this._query = query;
- }
-
- private string subLanguageId;
- private string movieHash;
- private long movieByteSize;
- private string imdbid;
- private string _query;
- private string _episode;
-
- public string Episode
- {
- get { return _episode; }
- set { _episode = value; }
- }
-
- public string Season
- {
- get { return _season; }
- set { _season = value; }
- }
-
- private string _season;
-
- public string Query
- {
- get { return _query; }
- set { _query = value; }
- }
-
- /// <summary>
- /// List of language ISO639-3 language codes to search for, divided by ',' (e.g. 'cze,eng,slo')
- /// </summary>
- public string SubLangaugeID { get { return subLanguageId; } set { subLanguageId = value; } }
- /// <summary>
- /// Video file hash as calculated by one of the implementation functions as seen on http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes
- /// </summary>
- public string MovieHash { get { return movieHash; } set { movieHash = value; } }
- /// <summary>
- /// Size of video file in bytes
- /// </summary>
- public long MovieByteSize { get { return movieByteSize; } set { movieByteSize = value; } }
- /// <summary>
- /// ​IMDb ID of movie this video is part of, belongs to.
- /// </summary>
- public string IMDbID { get { return imdbid; } set { imdbid = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchResult.cs b/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchResult.cs
deleted file mode 100644
index a4a8dd3e6..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/SubtitleSearchResult.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// The subtitle search result that comes with server response on SearchSubtitles successed call
- /// </summary>
- public struct SubtitleSearchResult
- {
- private string _IDSubMovieFile;
- private string _MovieHash;
- private string _MovieByteSize;
- private string _MovieTimeMS;
- private string _IDSubtitleFile;
- private string _SubFileName;
- private string _SubActualCD;
- private string _SubSize;
- private string _SubHash;
- private string _IDSubtitle;
- private string _UserID;
- private string _SubLanguageID;
- private string _SubFormat;
- private string _SeriesSeason;
- private string _SeriesEpisode;
- private string _SubSumCD;
- private string _SubAuthorComment;
- private string _SubAddDate;
- private string _SubBad;
- private string _SubRating;
- private string _SubDownloadsCnt;
- private string _MovieReleaseName;
- private string _IDMovie;
- private string _IDMovieImdb;
- private string _MovieName;
- private string _MovieNameEng;
- private string _MovieYear;
- private string _MovieImdbRating;
- private string _UserNickName;
- private string _ISO639;
- private string _LanguageName;
- private string _SubDownloadLink;
- private string _ZipDownloadLink;
-
- public string IDSubMovieFile
- { get { return _IDSubMovieFile; } set { _IDSubMovieFile = value; } }
- public string MovieHash
- { get { return _MovieHash; } set { _MovieHash = value; } }
- public string MovieByteSize
- { get { return _MovieByteSize; } set { _MovieByteSize = value; } }
- public string MovieTimeMS
- { get { return _MovieTimeMS; } set { _MovieTimeMS = value; } }
- public string IDSubtitleFile
- { get { return _IDSubtitleFile; } set { _IDSubtitleFile = value; } }
- public string SubFileName
- { get { return _SubFileName; } set { _SubFileName = value; } }
- public string SubActualCD
- { get { return _SubActualCD; } set { _SubActualCD = value; } }
- public string SubSize
- { get { return _SubSize; } set { _SubSize = value; } }
- public string SubHash
- { get { return _SubHash; } set { _SubHash = value; } }
- public string IDSubtitle
- { get { return _IDSubtitle; } set { _IDSubtitle = value; } }
- public string UserID
- { get { return _UserID; } set { _UserID = value; } }
- public string SubLanguageID
- { get { return _SubLanguageID; } set { _SubLanguageID = value; } }
- public string SubFormat
- { get { return _SubFormat; } set { _SubFormat = value; } }
- public string SubSumCD
- { get { return _SubSumCD; } set { _SubSumCD = value; } }
- public string SubAuthorComment
- { get { return _SubAuthorComment; } set { _SubAuthorComment = value; } }
- public string SubAddDate
- { get { return _SubAddDate; } set { _SubAddDate = value; } }
- public string SubBad
- { get { return _SubBad; } set { _SubBad = value; } }
- public string SubRating
- { get { return _SubRating; } set { _SubRating = value; } }
- public string SubDownloadsCnt
- { get { return _SubDownloadsCnt; } set { _SubDownloadsCnt = value; } }
- public string MovieReleaseName
- { get { return _MovieReleaseName; } set { _MovieReleaseName = value; } }
- public string IDMovie
- { get { return _IDMovie; } set { _IDMovie = value; } }
- public string IDMovieImdb
- { get { return _IDMovieImdb; } set { _IDMovieImdb = value; } }
- public string MovieName
- { get { return _MovieName; } set { _MovieName = value; } }
- public string MovieNameEng
- { get { return _MovieNameEng; } set { _MovieNameEng = value; } }
- public string MovieYear
- { get { return _MovieYear; } set { _MovieYear = value; } }
- public string MovieImdbRating
- { get { return _MovieImdbRating; } set { _MovieImdbRating = value; } }
- public string UserNickName
- { get { return _UserNickName; } set { _UserNickName = value; } }
- public string ISO639
- { get { return _ISO639; } set { _ISO639 = value; } }
- public string LanguageName
- { get { return _LanguageName; } set { _LanguageName = value; } }
- public string SubDownloadLink
- { get { return _SubDownloadLink; } set { _SubDownloadLink = value; } }
- public string ZipDownloadLink
- { get { return _ZipDownloadLink; } set { _ZipDownloadLink = value; } }
- public string SeriesSeason
- { get { return _SeriesSeason; } set { _SeriesSeason = value; } }
- public string SeriesEpisode
- { get { return _SeriesEpisode; } set { _SeriesEpisode = value; } }
- /// <summary>
- /// SubFileName + " (" + SubFormat + ")"
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return _SubFileName + " (" + _SubFormat + ")";
- }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/TryUploadSubtitlesParameters.cs b/OpenSubtitlesHandler/SubtitleTypes/TryUploadSubtitlesParameters.cs
deleted file mode 100644
index 11f3a706c..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/TryUploadSubtitlesParameters.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public class TryUploadSubtitlesParameters
- {
- private string _subhash = "";
- private string _subfilename = "";
- private string _moviehash = "";
- private string _moviebytesize = "";
- private int _movietimems = 0;
- private int _movieframes = 0;
- private double _moviefps = 0;
- private string _moviefilename = "";
-
- public string subhash { get { return _subhash; } set { _subhash = value; } }
- public string subfilename { get { return _subfilename; } set { _subfilename = value; } }
- public string moviehash { get { return _moviehash; } set { _moviehash = value; } }
- public string moviebytesize { get { return _moviebytesize; } set { _moviebytesize = value; } }
- public int movietimems { get { return _movietimems; } set { _movietimems = value; } }
- public int movieframes { get { return _movieframes; } set { _movieframes = value; } }
- public double moviefps { get { return _moviefps; } set { _moviefps = value; } }
- public string moviefilename { get { return _moviefilename; } set { _moviefilename = value; } }
-
- public override string ToString()
- {
- return _subfilename + " (" + _subhash + ")";
- }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleInfoParameter.cs b/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleInfoParameter.cs
deleted file mode 100644
index 133cc1d23..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleInfoParameter.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace OpenSubtitlesHandler
-{
- public class UploadSubtitleInfoParameters
- {
- private string _idmovieimdb;
- private string _moviereleasename;
- private string _movieaka;
- private string _sublanguageid;
- private string _subauthorcomment;
- private bool _hearingimpaired;
- private bool _highdefinition;
- private bool _automatictranslation;
- private List<UploadSubtitleParameters> cds;
-
- public string idmovieimdb { get { return _idmovieimdb; } set { _idmovieimdb = value; } }
- public string moviereleasename { get { return _moviereleasename; } set { _moviereleasename = value; } }
- public string movieaka { get { return _movieaka; } set { _movieaka = value; } }
- public string sublanguageid { get { return _sublanguageid; } set { _sublanguageid = value; } }
- public string subauthorcomment { get { return _subauthorcomment; } set { _subauthorcomment = value; } }
- public bool hearingimpaired { get { return _hearingimpaired; } set { _hearingimpaired = value; } }
- public bool highdefinition { get { return _highdefinition; } set { _highdefinition = value; } }
- public bool automatictranslation { get { return _automatictranslation; } set { _automatictranslation = value; } }
- public List<UploadSubtitleParameters> CDS { get { return cds; } set { cds = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleParameters.cs b/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleParameters.cs
deleted file mode 100644
index 9910dadc5..000000000
--- a/OpenSubtitlesHandler/SubtitleTypes/UploadSubtitleParameters.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace OpenSubtitlesHandler
-{
- public struct UploadSubtitleParameters
- {
- private string _subhash;
- private string _subfilename;
- private string _moviehash;
- private double _moviebytesize;
- private int _movietimems;
- private int _movieframes;
- private double _moviefps;
- private string _moviefilename;
- private string _subcontent;
-
- public string subhash { get { return _subhash; } set { _subhash = value; } }
- public string subfilename { get { return _subfilename; } set { _subfilename = value; } }
- public string moviehash { get { return _moviehash; } set { _moviehash = value; } }
- public double moviebytesize { get { return _moviebytesize; } set { _moviebytesize = value; } }
- public int movietimems { get { return _movietimems; } set { _movietimems = value; } }
- public int movieframes { get { return _movieframes; } set { _movieframes = value; } }
- public double moviefps { get { return _moviefps; } set { _moviefps = value; } }
- public string moviefilename { get { return _moviefilename; } set { _moviefilename = value; } }
- /// <summary>
- /// Sub content. Note: this value must be the subtitle file gziped and then base64 decoded.
- /// </summary>
- public string subcontent { get { return _subcontent; } set { _subcontent = value; } }
-
- public override string ToString()
- {
- return _subfilename + " (" + _subhash + ")";
- }
- }
-}
diff --git a/OpenSubtitlesHandler/Utilities.cs b/OpenSubtitlesHandler/Utilities.cs
deleted file mode 100644
index 429e28a8f..000000000
--- a/OpenSubtitlesHandler/Utilities.cs
+++ /dev/null
@@ -1,174 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Cryptography;
-
-namespace OpenSubtitlesHandler
-{
- /// <summary>
- /// Include helper methods. All member are statics.
- /// </summary>
- public sealed class Utilities
- {
- public static ICryptoProvider CryptographyProvider { get; set; }
- public static IHttpClient HttpClient { get; set; }
- private static string XML_RPC_SERVER = "https://api.opensubtitles.org/xml-rpc";
- //private static string XML_RPC_SERVER = "https://92.240.234.122/xml-rpc";
- private static string HostHeader = "api.opensubtitles.org:443";
-
- /// <summary>
- /// Compute movie hash
- /// </summary>
- /// <returns>The hash as Hexadecimal string</returns>
- public static string ComputeHash(Stream stream)
- {
- byte[] hash = MovieHasher.ComputeMovieHash(stream);
- return MovieHasher.ToHexadecimal(hash);
- }
- /// <summary>
- /// Decompress data using GZip
- /// </summary>
- /// <param name="dataToDecompress">The stream that hold the data</param>
- /// <returns>Bytes array of decompressed data</returns>
- public static byte[] Decompress(Stream dataToDecompress)
- {
- using (var target = new MemoryStream())
- {
- using (var decompressionStream = new System.IO.Compression.GZipStream(dataToDecompress, System.IO.Compression.CompressionMode.Decompress))
- {
- decompressionStream.CopyTo(target);
- }
- return target.ToArray();
- }
- }
-
- /// <summary>
- /// Compress data using GZip (the retunred buffer will be WITHOUT HEADER)
- /// </summary>
- /// <param name="dataToCompress">The stream that hold the data</param>
- /// <returns>Bytes array of compressed data WITHOUT HEADER bytes</returns>
- public static byte[] Compress(Stream dataToCompress)
- {
- /*using (var compressed = new MemoryStream())
- {
- using (var compressor = new System.IO.Compression.GZipStream(compressed,
- System.IO.Compression.CompressionMode.Compress))
- {
- dataToCompress.CopyTo(compressor);
- }
- // Get the compressed bytes only after closing the GZipStream
- return compressed.ToArray();
- }*/
- //using (var compressedOutput = new MemoryStream())
- //{
- // using (var compressedStream = new ZlibStream(compressedOutput,
- // Ionic.Zlib.CompressionMode.Compress,
- // CompressionLevel.Default, false))
- // {
- // var buffer = new byte[4096];
- // int byteCount;
- // do
- // {
- // byteCount = dataToCompress.Read(buffer, 0, buffer.Length);
-
- // if (byteCount > 0)
- // {
- // compressedStream.Write(buffer, 0, byteCount);
- // }
- // } while (byteCount > 0);
- // }
- // return compressedOutput.ToArray();
- //}
-
- throw new NotImplementedException();
- }
-
- /// <summary>
- /// Handle server response stream and decode it as given encoding string.
- /// </summary>
- /// <returns>The string of the stream after decode using given encoding</returns>
- public static string GetStreamString(Stream responseStream)
- {
- using (responseStream)
- {
- // Handle response, should be XML text.
- var data = new List<byte>();
- while (true)
- {
- int r = responseStream.ReadByte();
- if (r < 0)
- break;
- data.Add((byte)r);
- }
- var bytes = data.ToArray();
- return Encoding.ASCII.GetString(bytes, 0, bytes.Length);
- }
- }
-
- public static byte[] GetASCIIBytes(string text)
- {
- return Encoding.ASCII.GetBytes(text);
- }
-
- /// <summary>
- /// Send a request to the server
- /// </summary>
- /// <param name="request">The request buffer to send as bytes array.</param>
- /// <param name="userAgent">The user agent value.</param>
- /// <returns>Response of the server or stream of error message as string started with 'ERROR:' keyword.</returns>
- public static Stream SendRequest(byte[] request, string userAgent)
- {
- return SendRequestAsync(request, userAgent, CancellationToken.None).Result;
- }
-
- public static async Task<Stream> SendRequestAsync(byte[] request, string userAgent, CancellationToken cancellationToken)
- {
- var options = new HttpRequestOptions
- {
- RequestContentBytes = request,
- RequestContentType = "text/xml",
- UserAgent = userAgent,
- Host = HostHeader,
- Url = XML_RPC_SERVER,
-
- // Response parsing will fail with this enabled
- EnableHttpCompression = false,
-
- CancellationToken = cancellationToken,
- BufferContent = false
- };
-
- if (string.IsNullOrEmpty(options.UserAgent))
- {
- options.UserAgent = "xmlrpc-epi-php/0.2 (PHP)";
- }
-
- var result = await HttpClient.Post(options).ConfigureAwait(false);
-
- return result.Content;
- }
-
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Docs/XML-RPC.txt b/OpenSubtitlesHandler/XML-RPC/Docs/XML-RPC.txt
deleted file mode 100644
index a4de38cde..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Docs/XML-RPC.txt
+++ /dev/null
@@ -1,225 +0,0 @@
-XML-RPC Specification
-
-Tue, Jun 15, 1999; by Dave Winer.
-
-Updated 6/30/03 DW
-
-Updated 10/16/99 DW
-
-Updated 1/21/99 DW
-
-This specification documents the XML-RPC protocol implemented in UserLand Frontier 5.1.
-
-For a non-technical explanation, see XML-RPC for Newbies.
-
-This page provides all the information that an implementor needs.
-
-Overview
-
-XML-RPC is a Remote Procedure Calling protocol that works over the Internet.
-
-An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.
-
-Procedure parameters can be scalars, numbers, strings, dates, etc.; and can also be complex record and list structures.
-
-Request example
-
-Here's an example of an XML-RPC request:
-
-POST /RPC2 HTTP/1.0
-User-Agent: Frontier/5.1.2 (WinNT)
-Host: betty.userland.com
-Content-Type: text/xml
-Content-length: 181
-
-<?xml version="1.0"?>
- <methodCall>
- <methodName>examples.getStateName</methodName>
- <params>
- <param>
- <value>
- <i4>41</i4>
- </value>
- </param>
- </params>
- </methodCall>
-
-Header requirements
-
-The format of the URI in the first line of the header is not specified. For example, it could be empty, a single slash, if the server is only handling XML-RPC calls. However, if the server is handling a mix of incoming HTTP requests, we allow the URI to help route the request to the code that handles XML-RPC requests. (In the example, the URI is /RPC2, telling the server to route the request to the "RPC2" responder.)
-
-A User-Agent and Host must be specified.
-
-The Content-Type is text/xml.
-
-The Content-Length must be specified and must be correct.
-
-Payload format
-
-The payload is in XML, a single <methodCall> structure.
-
-The <methodCall> must contain a <methodName> sub-item, a string, containing the name of the method to be called. The string may only contain identifier characters, upper and lower-case A-Z, the numeric characters, 0-9, underscore, dot, colon and slash. It's entirely up to the server to decide how to interpret the characters in a methodName.
-
-For example, the methodName could be the name of a file containing a script that executes on an incoming request. It could be the name of a cell in a database table. Or it could be a path to a file contained within a hierarchy of folders and files.
-
-If the procedure call has parameters, the <methodCall> must contain a <params> sub-item. The <params> sub-item can contain any number of <param>s, each of which has a <value>.
-
-Scalar <value>s
-
-<value>s can be scalars, type is indicated by nesting the value inside one of the tags listed in this table:
-
-Tag Type Example
-<i4> or <int> four-byte signed integer -12
-<boolean> 0 (false) or 1 (true) 1
-<string> string hello world
-<double> double-precision signed floating point number -12.214
-<dateTime.iso8601> date/time 19980717T14:08:55
-<base64> base64-encoded binary eW91IGNhbid0IHJlYWQgdGhpcyE=
-
-If no type is indicated, the type is string.
-
-<struct>s
-
-A value can also be of type <struct>.
-
-A <struct> contains <member>s and each <member> contains a <name> and a <value>.
-
-Here's an example of a two-element <struct>:
-
-<struct>
- <member>
- <name>lowerBound</name>
- <value><i4>18</i4></value>
- </member>
- <member>
- <name>upperBound</name>
- <value><i4>139</i4></value>
- </member>
- </struct>
-
-<struct>s can be recursive, any <value> may contain a <struct> or any other type, including an <array>, described below.
-
-<array>s
-
-A value can also be of type <array>.
-
-An <array> contains a single <data> element, which can contain any number of <value>s.
-
-Here's an example of a four-element array:
-
-<array>
- <data>
- <value><i4>12</i4></value>
- <value><string>Egypt</string></value>
- <value><boolean>0</boolean></value>
- <value><i4>-31</i4></value>
- </data>
- </array>
-
-<array> elements do not have names.
-
-You can mix types as the example above illustrates.
-
-<arrays>s can be recursive, any value may contain an <array> or any other type, including a <struct>, described above.
-
-Response example
-
-Here's an example of a response to an XML-RPC request:
-
-HTTP/1.1 200 OK
-Connection: close
-Content-Length: 158
-Content-Type: text/xml
-Date: Fri, 17 Jul 1998 19:55:08 GMT
-Server: UserLand Frontier/5.1.2-WinNT
-
-<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>South Dakota</string></value> </param> </params> </methodResponse>
-
-Response format
-
-Unless there's a lower-level error, always return 200 OK.
-
-The Content-Type is text/xml. Content-Length must be present and correct.
-
-The body of the response is a single XML structure, a <methodResponse>, which can contain a single <params> which contains a single <param> which contains a single <value>.
-
-The <methodResponse> could also contain a <fault> which contains a <value> which is a <struct> containing two elements, one named <faultCode>, an <int> and one named <faultString>, a <string>.
-
-A <methodResponse> can not contain both a <fault> and a <params>.
-
-Fault example
-
-HTTP/1.1 200 OK
-Connection: close
-Content-Length: 426
-Content-Type: text/xml
-Date: Fri, 17 Jul 1998 19:55:02 GMT
-Server: UserLand Frontier/5.1.2-WinNT
-
-<?xml version="1.0"?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>4</int></value> </member> <member> <name>faultString</name> <value><string>Too many parameters.</string></value> </member> </struct> </value> </fault> </methodResponse>
-
-Strategies/Goals
-
-Firewalls. The goal of this protocol is to lay a compatible foundation across different environments, no new power is provided beyond the capabilities of the CGI interface. Firewall software can watch for POSTs whose Content-Type is text/xml.
-
-Discoverability. We wanted a clean, extensible format that's very simple. It should be possible for an HTML coder to be able to look at a file containing an XML-RPC procedure call, understand what it's doing, and be able to modify it and have it work on the first or second try.
-
-Easy to implement. We also wanted it to be an easy to implement protocol that could quickly be adapted to run in other environments or on other operating systems.
-
-Updated 1/21/99 DW
-
-The following questions came up on the UserLand discussion group as XML-RPC was being implemented in Python.
-
- The Response Format section says "The body of the response is a single XML structure, a <methodResponse>, which can contain a single <params>..." This is confusing. Can we leave out the <params>?
-
- No you cannot leave it out if the procedure executed successfully. There are only two options, either a response contains a <params> structure or it contains a <fault> structure. That's why we used the word "can" in that sentence.
-
- Is "boolean" a distinct data type, or can boolean values be interchanged with integers (e.g. zero=false, non-zero=true)?
-
- Yes, boolean is a distinct data type. Some languages/environments allow for an easy coercion from zero to false and one to true, but if you mean true, send a boolean type with the value true, so your intent can't possibly be misunderstood.
-
- What is the legal syntax (and range) for integers? How to deal with leading zeros? Is a leading plus sign allowed? How to deal with whitespace?
-
- An integer is a 32-bit signed number. You can include a plus or minus at the beginning of a string of numeric characters. Leading zeros are collapsed. Whitespace is not permitted. Just numeric characters preceeded by a plus or minus.
-
- What is the legal syntax (and range) for floating point values (doubles)? How is the exponent represented? How to deal with whitespace? Can infinity and "not a number" be represented?
-
- There is no representation for infinity or negative infinity or "not a number". At this time, only decimal point notation is allowed, a plus or a minus, followed by any number of numeric characters, followed by a period and any number of numeric characters. Whitespace is not allowed. The range of allowable values is implementation-dependent, is not specified.
-
- What characters are allowed in strings? Non-printable characters? Null characters? Can a "string" be used to hold an arbitrary chunk of binary data?
-
- Any characters are allowed in a string except < and &, which are encoded as &lt; and &amp;. A string can be used to encode binary data.
-
- Does the "struct" element keep the order of keys. Or in other words, is the struct "foo=1, bar=2" equivalent to "bar=2, foo=1" or not?
-
- The struct element does not preserve the order of the keys. The two structs are equivalent.
-
- Can the <fault> struct contain other members than <faultCode> and <faultString>? Is there a global list of faultCodes? (so they can be mapped to distinct exceptions for languages like Python and Java)?
-
- A <fault> struct may not contain members other than those specified. This is true for all other structures. We believe the specification is flexible enough so that all reasonable data-transfer needs can be accomodated within the specified structures. If you believe strongly that this is not true, please post a message on the discussion group.
-
- There is no global list of fault codes. It is up to the server implementer, or higher-level standards to specify fault codes.
-
- What timezone should be assumed for the dateTime.iso8601 type? UTC? localtime?
-
- Don't assume a timezone. It should be specified by the server in its documentation what assumptions it makes about timezones.
-
-Additions
-
- <base64> type. 1/21/99 DW.
-
-Updated 6/30/03 DW
-
-Removed "ASCII" from definition of string.
-
-Changed copyright dates, below, to 1999-2003 from 1998-99.
-
-Copyright and disclaimer
-
-© Copyright 1998-2003 UserLand Software. All Rights Reserved.
-
-This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and these paragraphs are included on all such copies and derivative works.
-
-This document may not be modified in any way, such as by removing the copyright notice or references to UserLand or other organizations. Further, while these copyright restrictions apply to the written XML-RPC specification, no claim of ownership is made by UserLand to the protocol it describes. Any party may, for commercial or non-commercial purposes, implement this protocol without royalty or license fee to UserLand. The limited permissions granted herein are perpetual and will not be revoked by UserLand or its successors or assigns.
-
-This document and the information contained herein is provided on an "AS IS" basis and USERLAND DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/OpenSubtitlesHandler/XML-RPC/Enums/XmlRpcValueType.cs b/OpenSubtitlesHandler/XML-RPC/Enums/XmlRpcValueType.cs
deleted file mode 100644
index 51e0ee98f..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Enums/XmlRpcValueType.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-namespace XmlRpcHandler
-{
- public enum XmlRpcBasicValueType
- {
- String, Int, Boolean, Double, dateTime_iso8601, base64
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Types/XmlRpcMethodCall.cs b/OpenSubtitlesHandler/XML-RPC/Types/XmlRpcMethodCall.cs
deleted file mode 100644
index 7cc1a164f..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Types/XmlRpcMethodCall.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace XmlRpcHandler
-{
- /// <summary>
- /// A method call
- /// </summary>
- public struct XmlRpcMethodCall
- {
- /// <summary>
- /// A method call
- /// </summary>
- /// <param name="name">The name of this method</param>
- public XmlRpcMethodCall(string name)
- {
- this.name = name;
- this.parameters = new List<IXmlRpcValue>();
- }
- /// <summary>
- /// A method call
- /// </summary>
- /// <param name="name">The name of this method</param>
- /// <param name="parameters">A list of parameters</param>
- public XmlRpcMethodCall(string name, List<IXmlRpcValue> parameters)
- {
- this.name = name;
- this.parameters = parameters;
- }
-
- private string name;
- private List<IXmlRpcValue> parameters;
-
- /// <summary>
- /// Get or set the name of this method
- /// </summary>
- public string Name
- { get { return name; } set { name = value; } }
- /// <summary>
- /// Get or set the parameters to be sent
- /// </summary>
- public List<IXmlRpcValue> Parameters
- { get { return parameters; } set { parameters = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Values/IXmlRpcValue.cs b/OpenSubtitlesHandler/XML-RPC/Values/IXmlRpcValue.cs
deleted file mode 100644
index c918790cb..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Values/IXmlRpcValue.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace XmlRpcHandler
-{
- public abstract class IXmlRpcValue
- {
- public IXmlRpcValue()
- { }
- public IXmlRpcValue(object data)
- {
- this.data = data;
- }
- private object data;
- /// <summary>
- /// Get or set the data of this value
- /// </summary>
- public virtual object Data { get { return data; } set { data = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcStructMember.cs b/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcStructMember.cs
deleted file mode 100644
index 2aad7ebff..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcStructMember.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-namespace XmlRpcHandler
-{
- public class XmlRpcStructMember
- {
- public XmlRpcStructMember(string name, IXmlRpcValue data)
- {
- this.name = name;
- this.data = data;
- }
- private string name;
- private IXmlRpcValue data;
-
- /// <summary>
- /// Get or set the name of this member
- /// </summary>
- public string Name
- { get { return name; } set { name = value; } }
- /// <summary>
- /// Get or set the data of this member
- /// </summary>
- public IXmlRpcValue Data
- { get { return data; } set { data = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueArray.cs b/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueArray.cs
deleted file mode 100644
index d10a80175..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueArray.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-using System.Collections.Generic;
-
-namespace XmlRpcHandler
-{
- public class XmlRpcValueArray : IXmlRpcValue
- {
- public XmlRpcValueArray() :
- base()
- {
- values = new List<IXmlRpcValue>();
- }
- public XmlRpcValueArray(object data) :
- base(data)
- {
- values = new List<IXmlRpcValue>();
- }
- public XmlRpcValueArray(string[] texts) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (string val in texts)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(int[] ints) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (int val in ints)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(double[] doubles) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (double val in doubles)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(bool[] bools) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (bool val in bools)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(long[] base24s) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (long val in base24s)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(DateTime[] dates) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (var val in dates)
- {
- values.Add(new XmlRpcValueBasic(val));
- }
- }
- public XmlRpcValueArray(XmlRpcValueBasic[] basicValues) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (var val in basicValues)
- {
- values.Add(val);
- }
- }
- public XmlRpcValueArray(XmlRpcValueStruct[] structs) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (var val in structs)
- {
- values.Add(val);
- }
- }
- public XmlRpcValueArray(XmlRpcValueArray[] arrays) :
- base()
- {
- values = new List<IXmlRpcValue>();
- foreach (var val in arrays)
- {
- values.Add(val);
- }
- }
- private List<IXmlRpcValue> values;
-
- public List<IXmlRpcValue> Values { get { return values; } set { values = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueBasic.cs b/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueBasic.cs
deleted file mode 100644
index f2811b988..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueBasic.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-
-namespace XmlRpcHandler
-{
- public class XmlRpcValueBasic : IXmlRpcValue
- {
- public XmlRpcValueBasic()
- : base()
- { }
- public XmlRpcValueBasic(string data)
- : base(data)
- { this.type = XmlRpcBasicValueType.String; }
- public XmlRpcValueBasic(int data)
- : base(data)
- { this.type = XmlRpcBasicValueType.Int; }
- public XmlRpcValueBasic(double data)
- : base(data)
- { this.type = XmlRpcBasicValueType.Double; }
- public XmlRpcValueBasic(DateTime data)
- : base(data)
- { this.type = XmlRpcBasicValueType.dateTime_iso8601; }
- public XmlRpcValueBasic(bool data)
- : base(data)
- { this.type = XmlRpcBasicValueType.Boolean; }
- public XmlRpcValueBasic(long data)
- : base(data)
- { this.type = XmlRpcBasicValueType.base64; }
- public XmlRpcValueBasic(object data, XmlRpcBasicValueType type)
- : base(data)
- { this.type = type; }
-
- private XmlRpcBasicValueType type = XmlRpcBasicValueType.String;
- /// <summary>
- /// Get or set the type of this basic value
- /// </summary>
- public XmlRpcBasicValueType ValueType { get { return type; } set { type = value; } }
- /*Oprators. help a lot.*/
- public static implicit operator string(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return f.Data.ToString();
- else
- throw new Exception("Unable to convert, this value is not string type.");
- }
- public static implicit operator int(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return (int)f.Data;
- else
- throw new Exception("Unable to convert, this value is not int type.");
- }
- public static implicit operator double(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return (double)f.Data;
- else
- throw new Exception("Unable to convert, this value is not double type.");
- }
- public static implicit operator bool(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return (bool)f.Data;
- else
- throw new Exception("Unable to convert, this value is not bool type.");
- }
- public static implicit operator long(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return (long)f.Data;
- else
- throw new Exception("Unable to convert, this value is not long type.");
- }
- public static implicit operator DateTime(XmlRpcValueBasic f)
- {
- if (f.type == XmlRpcBasicValueType.String)
- return (DateTime)f.Data;
- else
- throw new Exception("Unable to convert, this value is not DateTime type.");
- }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueStruct.cs b/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueStruct.cs
deleted file mode 100644
index 4863e38e8..000000000
--- a/OpenSubtitlesHandler/XML-RPC/Values/XmlRpcValueStruct.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-using System.Collections.Generic;
-
-namespace XmlRpcHandler
-{
- /// <summary>
- /// Represents XML-RPC struct
- /// </summary>
- public class XmlRpcValueStruct : IXmlRpcValue
- {
- /// <summary>
- /// Represents XML-RPC struct
- /// </summary>
- /// <param name="members"></param>
- public XmlRpcValueStruct(List<XmlRpcStructMember> members)
- { this.members = members; }
-
- private List<XmlRpcStructMember> members;
- /// <summary>
- /// Get or set the members collection
- /// </summary>
- public List<XmlRpcStructMember> Members
- { get { return members; } set { members = value; } }
- }
-}
diff --git a/OpenSubtitlesHandler/XML-RPC/XmlRpcGenerator.cs b/OpenSubtitlesHandler/XML-RPC/XmlRpcGenerator.cs
deleted file mode 100644
index a79a278fa..000000000
--- a/OpenSubtitlesHandler/XML-RPC/XmlRpcGenerator.cs
+++ /dev/null
@@ -1,350 +0,0 @@
-/* This file is part of OpenSubtitles Handler
- A library that handle OpenSubtitles.org XML-RPC methods.
-
- Copyright © Ala Ibrahim Hadid 2013
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Xml;
-using OpenSubtitlesHandler;
-
-namespace XmlRpcHandler
-{
- /// <summary>
- /// A class for making XML-RPC requests. The requests then can be sent directly as http request.
- /// </summary>
- public class XmlRpcGenerator
- {
- /// <summary>
- /// Generate XML-RPC request using method call.
- /// </summary>
- /// <param name="method">The method call</param>
- /// <returns>The request in xml.</returns>
- public static byte[] Generate(XmlRpcMethodCall method)
- { return Generate(new XmlRpcMethodCall[] { method }); }
- /// <summary>
- /// Generate XML-RPC request using method calls array.
- /// </summary>
- /// <param name="methods">The method calls array</param>
- /// <returns>The request in utf8 xml string as buffer</returns>
- public static byte[] Generate(XmlRpcMethodCall[] methods)
- {
- if (methods == null)
- throw new Exception("No method to write !");
- if (methods.Length == 0)
- throw new Exception("No method to write !");
- // Create xml
- var sett = new XmlWriterSettings();
- sett.Indent = true;
-
- sett.Encoding = Encoding.UTF8;
-
- using (var ms = new MemoryStream())
- {
- using (var XMLwrt = XmlWriter.Create(ms, sett))
- {
- // Let's write the methods
- foreach (XmlRpcMethodCall method in methods)
- {
- XMLwrt.WriteStartElement("methodCall");//methodCall
- XMLwrt.WriteStartElement("methodName");//methodName
- XMLwrt.WriteString(method.Name);
- XMLwrt.WriteEndElement();//methodName
- XMLwrt.WriteStartElement("params");//params
- // Write values
- foreach (IXmlRpcValue p in method.Parameters)
- {
- XMLwrt.WriteStartElement("param");//param
- if (p is XmlRpcValueBasic)
- {
- WriteBasicValue(XMLwrt, (XmlRpcValueBasic)p);
- }
- else if (p is XmlRpcValueStruct)
- {
- WriteStructValue(XMLwrt, (XmlRpcValueStruct)p);
- }
- else if (p is XmlRpcValueArray)
- {
- WriteArrayValue(XMLwrt, (XmlRpcValueArray)p);
- }
- XMLwrt.WriteEndElement();//param
- }
-
- XMLwrt.WriteEndElement();//params
- XMLwrt.WriteEndElement();//methodCall
- }
- XMLwrt.Flush();
- return ms.ToArray();
- }
- }
- }
- /// <summary>
- /// Decode response then return the values
- /// </summary>
- /// <param name="xmlResponse">The response xml string as provided by server as methodResponse</param>
- /// <returns></returns>
- public static XmlRpcMethodCall[] DecodeMethodResponse(string xmlResponse)
- {
- var methods = new List<XmlRpcMethodCall>();
- var sett = new XmlReaderSettings();
- sett.DtdProcessing = DtdProcessing.Ignore;
- sett.IgnoreWhitespace = true;
- MemoryStream str;
- if (xmlResponse.Contains(@"encoding=""utf-8"""))
- {
- str = new MemoryStream(Encoding.UTF8.GetBytes(xmlResponse));
- }
- else
- {
- str = new MemoryStream(Utilities.GetASCIIBytes(xmlResponse));
- }
- using (str)
- {
- using (var XMLread = XmlReader.Create(str, sett))
- {
- var call = new XmlRpcMethodCall("methodResponse");
- // Read parameters
- while (XMLread.Read())
- {
- if (XMLread.Name == "param" && XMLread.IsStartElement())
- {
- IXmlRpcValue val = ReadValue(XMLread);
- if (val != null)
- call.Parameters.Add(val);
- }
- }
- methods.Add(call);
- return methods.ToArray();
- }
- }
- }
-
- private static void WriteBasicValue(XmlWriter XMLwrt, XmlRpcValueBasic val)
- {
- XMLwrt.WriteStartElement("value");//value
- switch (val.ValueType)
- {
- case XmlRpcBasicValueType.String:
- XMLwrt.WriteStartElement("string");
- if (val.Data != null)
- XMLwrt.WriteString(val.Data.ToString());
- XMLwrt.WriteEndElement();
- break;
- case XmlRpcBasicValueType.Int:
- XMLwrt.WriteStartElement("int");
- if (val.Data != null)
- XMLwrt.WriteString(val.Data.ToString());
- XMLwrt.WriteEndElement();
- break;
- case XmlRpcBasicValueType.Boolean:
- XMLwrt.WriteStartElement("boolean");
- if (val.Data != null)
- XMLwrt.WriteString(((bool)val.Data) ? "1" : "0");
- XMLwrt.WriteEndElement();
- break;
- case XmlRpcBasicValueType.Double:
- XMLwrt.WriteStartElement("double");
- if (val.Data != null)
- XMLwrt.WriteString(val.Data.ToString());
- XMLwrt.WriteEndElement();
- break;
- case XmlRpcBasicValueType.dateTime_iso8601:
- XMLwrt.WriteStartElement("dateTime.iso8601");
- // Get date time format
- if (val.Data != null)
- {
- var time = (DateTime)val.Data;
- string dt = time.Year + time.Month.ToString("D2") + time.Day.ToString("D2") +
- "T" + time.Hour.ToString("D2") + ":" + time.Minute.ToString("D2") + ":" +
- time.Second.ToString("D2");
- XMLwrt.WriteString(dt);
- }
- XMLwrt.WriteEndElement();
- break;
- case XmlRpcBasicValueType.base64:
- XMLwrt.WriteStartElement("base64");
- if (val.Data != null)
- XMLwrt.WriteString(Convert.ToBase64String(BitConverter.GetBytes((long)val.Data)));
- XMLwrt.WriteEndElement();
- break;
- }
- XMLwrt.WriteEndElement();//value
- }
- private static void WriteStructValue(XmlWriter XMLwrt, XmlRpcValueStruct val)
- {
- XMLwrt.WriteStartElement("value");//value
- XMLwrt.WriteStartElement("struct");//struct
- foreach (XmlRpcStructMember member in val.Members)
- {
- XMLwrt.WriteStartElement("member");//member
-
- XMLwrt.WriteStartElement("name");//name
- XMLwrt.WriteString(member.Name);
- XMLwrt.WriteEndElement();//name
-
- if (member.Data is XmlRpcValueBasic)
- {
- WriteBasicValue(XMLwrt, (XmlRpcValueBasic)member.Data);
- }
- else if (member.Data is XmlRpcValueStruct)
- {
- WriteStructValue(XMLwrt, (XmlRpcValueStruct)member.Data);
- }
- else if (member.Data is XmlRpcValueArray)
- {
- WriteArrayValue(XMLwrt, (XmlRpcValueArray)member.Data);
- }
-
- XMLwrt.WriteEndElement();//member
- }
- XMLwrt.WriteEndElement();//struct
- XMLwrt.WriteEndElement();//value
- }
- private static void WriteArrayValue(XmlWriter XMLwrt, XmlRpcValueArray val)
- {
- XMLwrt.WriteStartElement("value");//value
- XMLwrt.WriteStartElement("array");//array
- XMLwrt.WriteStartElement("data");//data
- foreach (IXmlRpcValue o in val.Values)
- {
- if (o is XmlRpcValueBasic)
- {
- WriteBasicValue(XMLwrt, (XmlRpcValueBasic)o);
- }
- else if (o is XmlRpcValueStruct)
- {
- WriteStructValue(XMLwrt, (XmlRpcValueStruct)o);
- }
- else if (o is XmlRpcValueArray)
- {
- WriteArrayValue(XMLwrt, (XmlRpcValueArray)o);
- }
- }
- XMLwrt.WriteEndElement();//data
- XMLwrt.WriteEndElement();//array
- XMLwrt.WriteEndElement();//value
- }
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
- private static string ReadString(XmlReader reader)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- return reader.ReadElementContentAsString();
- }
- return reader.ReadContentAsString();
- }
-
- private static IXmlRpcValue ReadValue(XmlReader xmlReader, bool skipRead = false)
- {
- while (skipRead || xmlReader.Read())
- {
- if (xmlReader.Name == "value" && xmlReader.IsStartElement())
- {
- xmlReader.Read();
- if (xmlReader.Name == "string" && xmlReader.IsStartElement())
- {
- return new XmlRpcValueBasic(ReadString(xmlReader), XmlRpcBasicValueType.String);
- }
- else if (xmlReader.Name == "int" && xmlReader.IsStartElement())
- {
- return new XmlRpcValueBasic(int.Parse(ReadString(xmlReader), UsCulture), XmlRpcBasicValueType.Int);
- }
- else if (xmlReader.Name == "boolean" && xmlReader.IsStartElement())
- {
- return new XmlRpcValueBasic(ReadString(xmlReader) == "1", XmlRpcBasicValueType.Boolean);
- }
- else if (xmlReader.Name == "double" && xmlReader.IsStartElement())
- {
- return new XmlRpcValueBasic(double.Parse(ReadString(xmlReader), UsCulture), XmlRpcBasicValueType.Double);
- }
- else if (xmlReader.Name == "dateTime.iso8601" && xmlReader.IsStartElement())
- {
- string date = ReadString(xmlReader);
- int year = int.Parse(date.Substring(0, 4), UsCulture);
- int month = int.Parse(date.Substring(4, 2), UsCulture);
- int day = int.Parse(date.Substring(6, 2), UsCulture);
- int hour = int.Parse(date.Substring(9, 2), UsCulture);
- int minute = int.Parse(date.Substring(12, 2), UsCulture);//19980717T14:08:55
- int sec = int.Parse(date.Substring(15, 2), UsCulture);
- var time = new DateTime(year, month, day, hour, minute, sec);
- return new XmlRpcValueBasic(time, XmlRpcBasicValueType.dateTime_iso8601);
- }
- else if (xmlReader.Name == "base64" && xmlReader.IsStartElement())
- {
- return new XmlRpcValueBasic(BitConverter.ToInt64(Convert.FromBase64String(ReadString(xmlReader)), 0)
- , XmlRpcBasicValueType.Double);
- }
- else if (xmlReader.Name == "struct" && xmlReader.IsStartElement())
- {
- var strct = new XmlRpcValueStruct(new List<XmlRpcStructMember>());
- // Read members...
- while (xmlReader.Read())
- {
- if (xmlReader.Name == "member" && xmlReader.IsStartElement())
- {
- var member = new XmlRpcStructMember("", null);
- xmlReader.Read();// read name
- member.Name = ReadString(xmlReader);
-
- IXmlRpcValue val = ReadValue(xmlReader, true);
- if (val != null)
- {
- member.Data = val;
- strct.Members.Add(member);
- }
- }
- else if (xmlReader.Name == "struct" && !xmlReader.IsStartElement())
- {
- return strct;
- }
- }
- return strct;
- }
- else if (xmlReader.Name == "array" && xmlReader.IsStartElement())
- {
- var array = new XmlRpcValueArray();
- // Read members...
- while (xmlReader.Read())
- {
- if (xmlReader.Name == "array" && !xmlReader.IsStartElement())
- {
- return array;
- }
- else
- {
- IXmlRpcValue val = ReadValue(xmlReader);
- if (val != null)
- array.Values.Add(val);
- }
- }
- return array;
- }
- }
- else break;
-
- if (skipRead)
- {
- return null;
- }
- }
- return null;
- }
- }
-}
diff --git a/README.md b/README.md
index d869c8978..6653bff11 100644
--- a/README.md
+++ b/README.md
@@ -4,37 +4,176 @@
---
<p align="center">
-<img alt="Logo banner" src="https://raw.githubusercontent.com/jellyfin/jellyfin-ux/master/branding/SVG/banner-logo-solid.svg?sanitize=true"/>
-<br/><br/>
-<a href="https://github.com/jellyfin/jellyfin"><img alt="GPL 2.0 License" src="https://img.shields.io/github/license/jellyfin/jellyfin.svg"/></a>
-<a href="https://github.com/jellyfin/jellyfin/releases"><img alt="Current Release" src="https://img.shields.io/github/release/jellyfin/jellyfin.svg"/></a>
-<a href="https://translate.jellyfin.org/engage/jellyfin/?utm_source=widget"><img alt="Translations" src="https://translate.jellyfin.org/widgets/jellyfin/-/svg-badge.svg"/></a>
-<a href="https://cloud.drone.io/jellyfin/jellyfin"><img alt="Build Status" src="https://cloud.drone.io/api/badges/jellyfin/jellyfin/status.svg"/></a>
-<a href="https://hub.docker.com/r/jellyfin/jellyfin"><img alt="Docker Pull Count" src="https://img.shields.io/docker/pulls/jellyfin/jellyfin.svg"/></a>
+<img alt="Logo Banner" src="https://raw.githubusercontent.com/jellyfin/jellyfin-ux/master/branding/SVG/banner-logo-solid.svg?sanitize=true"/>
+<br/>
+<br/>
+<a href="https://github.com/jellyfin/jellyfin">
+<img alt="GPL 2.0 License" src="https://img.shields.io/github/license/jellyfin/jellyfin.svg"/>
+</a>
+<a href="https://github.com/jellyfin/jellyfin/releases">
+<img alt="Current Release" src="https://img.shields.io/github/release/jellyfin/jellyfin.svg"/>
+</a>
+<a href="https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/?utm_source=widget">
+<img alt="Translation Status" src="https://translate.jellyfin.org/widgets/jellyfin/-/jellyfin-core/svg-badge.svg"/>
+</a>
+<a href="https://dev.azure.com/jellyfin-project/jellyfin/_build?definitionId=29">
+<img alt="Azure Builds" src="https://dev.azure.com/jellyfin-project/jellyfin/_apis/build/status/Jellyfin%20Server"/>
+</a>
+<a href="https://hub.docker.com/r/jellyfin/jellyfin">
+<img alt="Docker Pull Count" src="https://img.shields.io/docker/pulls/jellyfin/jellyfin.svg"/>
+</a>
</br>
-<a href="https://opencollective.com/jellyfin"><img alt="Donate" src="https://img.shields.io/opencollective/all/jellyfin.svg?label=backers"/></a>
-<a href="https://forum.jellyfin.org"/><img alt="Discuss on our Forum" src="https://img.shields.io/discourse/https/forum.jellyfin.org/users.svg"/></a>
-<a href="https://matrix.to/#/+jellyfin:matrix.org"><img alt="Chat on Matrix" src="https://img.shields.io/matrix/jellyfin:matrix.org.svg?logo=matrix"/></a>
-<a href="https://www.reddit.com/r/jellyfin/"><img alt="Join our Subreddit" src="https://img.shields.io/badge/reddit-r%2Fjellyfin-%23FF5700.svg"/></a>
+<a href="https://opencollective.com/jellyfin">
+<img alt="Donate" src="https://img.shields.io/opencollective/all/jellyfin.svg?label=backers"/>
+</a>
+<a href="https://features.jellyfin.org">
+<img alt="Submit Feature Requests" src="https://img.shields.io/badge/fider-vote%20on%20features-success.svg"/>
+</a>
+<a href="https://matrix.to/#/+jellyfin:matrix.org">
+<img alt="Chat on Matrix" src="https://img.shields.io/matrix/jellyfin:matrix.org.svg?logo=matrix"/>
+</a>
+<a href="https://www.reddit.com/r/jellyfin">
+<img alt="Join our Subreddit" src="https://img.shields.io/badge/reddit-r%2Fjellyfin-%23FF5700.svg"/>
+</a>
+<a href="https://github.com/jellyfin/jellyfin/releases.atom">
+<img alt="Release RSS Feed"" src="https://img.shields.io/badge/rss-releases-ffa500?logo=rss" />
+</a>
+<a href="https://github.com/jellyfin/jellyfin/commits/master.atom">
+<img alt="Master Commits RSS Feed"" src="https://img.shields.io/badge/rss-commits-ffa500?logo=rss" />
+</a>
+<a href="https://lgtm.com/projects/g/jellyfin/jellyfin/alerts/">
+<img alt="Total LGTM alerts" src="https://img.shields.io/lgtm/alerts/g/jellyfin/jellyfin.svg?logo=lgtm&logoWidth=18"/>
+</a>
</p>
---
Jellyfin is a Free Software Media System that puts you in control of managing and streaming your media. It is an alternative to the proprietary Emby and Plex, to provide media from a dedicated server to end-user devices via multiple apps. Jellyfin is descended from Emby's 3.5.2 release and ported to the .NET Core framework to enable full cross-platform support. There are no strings attached, no premium licenses or features, and no hidden agendas: just a team who want to build something better and work together to achieve it. We welcome anyone who is interested in joining us in our quest!
-For further details, please see [our documentation page](https://jellyfin.readthedocs.io). To receive the latest updates, get help with Jellyfin, and join the community, please visit [one of our communication channels on Matrix/Riot or social media](https://jellyfin.readthedocs.io/en/latest/user-docs/getting-help).
+For further details, please see [our documentation page](https://docs.jellyfin.org/). To receive the latest updates, get help with Jellyfin, and join the community, please visit [one of our communication channels](https://docs.jellyfin.org/general/getting-help.html). For more information about the project, please see our [about page](https://docs.jellyfin.org/general/about.html).
-For more information about the project, please see our [about page](https://jellyfin.readthedocs.io/en/latest/about/).
+<strong>Want to get started?</strong><br/>
+Check out our <a href="https://jellyfin.org/downloads">downloads page</a> or our <a href="https://docs.jellyfin.org/general/administration/installing.html">installation guide</a>, then see our <a href="https://docs.jellyfin.org/general/quick-start.html">quick start guide</a>. You can also <a href="https://docs.jellyfin.org/general/administration/building.html">build from source</a>.<br/>
+<strong>Something not working right?</strong><br/>
+Open an <a href="https://docs.jellyfin.org/general/contributing/issues.html">Issue</a> on GitHub.<br/>
+
+<strong>Want to contribute?</strong><br/>
+Check out our <a href="https://jellyfin.org/contribute">contributing choose-your-own-adventure</a> to see where you can help, then see our <a href="https://docs.jellyfin.org/general/contributing/index.html">contributing guide</a> and our <a href="https://jellyfin.org/docs/general/community-standards">community standards</a>.<br/>
+
+<strong>New idea or improvement?</strong><br/>
+Check out our <a href="https://features.jellyfin.org/?view=most-wanted">feature request hub</a>.<br/>
+
+<strong>Don't see Jellyfin in your language?</strong><br/>
+Check out our <a href="https://translate.jellyfin.org">Weblate instance</a> to help translate Jellyfin and its subprojects.<br/>
+
+<a href="https://translate.jellyfin.org/engage/jellyfin/?utm_source=widget">
+<img src="https://translate.jellyfin.org/widgets/jellyfin/-/jellyfin-web/multi-auto.svg" alt="Detailed Translation Status"/>
+</a>
+
+---
+
+## Jellyfin Server
+
+This repository contains the code for Jellyfin's backend server. Note that this is only one of many projects under the Jellyfin GitHub [organization](https://github.com/jellyfin/) on GitHub. If you want to contribute, you can start by checking out our [documentation](https://jellyfin.org/docs/general/contributing/index.html) to see what to work on.
+
+## Server Development
+
+These instructions will help you get set up with a local development environment in order to contribute to this repository. Before you start, please be sure to completely read our [guidelines on development contributions](https://jellyfin.org/docs/general/contributing/development.html). Note that this project is supported on all major operating systems except FreeBSD, which is still incompatible.
+
+### Prerequisites
+
+Before the project can be built, you must first install the [.NET 6.0 SDK](https://dotnet.microsoft.com/download/dotnet) on your system.
+
+Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download).
+
+[ffmpeg](https://github.com/jellyfin/jellyfin-ffmpeg) will also need to be installed.
+
+### Cloning the Repository
+
+After dependencies are installed you will need to clone a local copy of this repository. If you just want to run the server from source you can clone this repository directly, but if you are intending to contribute code changes to the project, you should [set up your own fork](https://jellyfin.org/docs/general/contributing/development.html#set-up-your-copy-of-the-repo) of the repository. The following example shows how you can clone the repository directly over HTTPS.
+
+```bash
+git clone https://github.com/jellyfin/jellyfin.git
+```
+
+### Installing the Web Client
+
+The server is configured to host the static files required for the [web client](https://github.com/jellyfin/jellyfin-web) in addition to serving the backend by default. Before you can run the server, you will need to get a copy of the web client since they are not included in this repository directly.
+
+Note that it is also possible to [host the web client separately](#hosting-the-web-client-separately) from the web server with some additional configuration, in which case you can skip this step.
+
+There are three options to get the files for the web client.
+
+1. Download one of the finished builds from the [Azure DevOps pipeline](https://dev.azure.com/jellyfin-project/jellyfin/_build?definitionId=27). You can download the build for a specific release by looking at the [branches tab](https://dev.azure.com/jellyfin-project/jellyfin/_build?definitionId=27&_a=summary&repositoryFilter=6&view=branches) of the pipelines page.
+2. Build them from source following the instructions on the [jellyfin-web repository](https://github.com/jellyfin/jellyfin-web)
+3. Get the pre-built files from an existing installation of the server. For example, with a Windows server installation the client files are located at `C:\Program Files\Jellyfin\Server\jellyfin-web`
+
+### Running The Server
+
+The following instructions will help you get the project up and running via the command line, or your preferred IDE.
+
+#### Running With Visual Studio
+
+To run the project with Visual Studio you can open the Solution (`.sln`) file and then press `F5` to run the server.
+
+#### Running With Visual Studio Code
+
+To run the project with Visual Studio Code you will first need to open the repository directory with Visual Studio Code using the `Open Folder...` option.
+
+Second, you need to [install the recommended extensions for the workspace](https://code.visualstudio.com/docs/editor/extension-gallery#_recommended-extensions). Note that extension recommendations are classified as either "Workspace Recommendations" or "Other Recommendations", but only the "Workspace Recommendations" are required.
+
+After the required extensions are installed, you can run the server by pressing `F5`.
+
+#### Running From The Command Line
+
+To run the server from the command line you can use the `dotnet run` command. The example below shows how to do this if you have cloned the repository into a directory named `jellyfin` (the default directory name) and should work on all operating systems.
+
+```bash
+cd jellyfin # Move into the repository directory
+dotnet run --project Jellyfin.Server --webdir /absolute/path/to/jellyfin-web/dist # Run the server startup project
+```
+
+A second option is to build the project and then run the resulting executable file directly. When running the executable directly you can easily add command line options. Add the `--help` flag to list details on all the supported command line options.
+
+1. Build the project
+
+ ```bash
+ dotnet build # Build the project
+ cd bin/Debug/net5.0 # Change into the build output directory
+ ```
+
+2. Execute the build output. On Linux, Mac, etc. use `./jellyfin` and on Windows use `jellyfin.exe`.
+
+### Running The Tests
+
+This repository also includes unit tests that are used to validate functionality as part of a CI pipeline on Azure. There are several ways to run these tests.
+
+1. Run tests from the command line using `dotnet test`
+2. Run tests in Visual Studio using the [Test Explorer](https://docs.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer)
+3. Run individual tests in Visual Studio Code using the associated [CodeLens annotation](https://github.com/OmniSharp/omnisharp-vscode/wiki/How-to-run-and-debug-unit-tests)
+
+### Advanced Configuration
+
+The following sections describe some more advanced scenarios for running the server from source that build upon the standard instructions above.
+
+#### Hosting The Web Client Separately
+
+It is not necessary to host the frontend web client as part of the backend server. Hosting these two components separately may be useful for frontend developers who would prefer to host the client in a separate webpack development server for a tighter development loop. See the [jellyfin-web](https://github.com/jellyfin/jellyfin-web#getting-started) repo for instructions on how to do this.
+
+To instruct the server not to host the web content, there is a `nowebclient` configuration flag that must be set. This can specified using the command line
+switch `--nowebclient` or the environment variable `JELLYFIN_NOWEBCONTENT=true`.
+
+Since this is a common scenario, there is also a separate launch profile defined for Visual Studio called `Jellyfin.Server (nowebcontent)` that can be selected from the 'Start Debugging' dropdown in the main toolbar.
+
+**NOTE:** The setup wizard can not be run if the web client is hosted separately.
+
+---
<p align="center">
-<strong>Want to get started?</strong>
-<em>Choose from <a href="https://jellyfin.readthedocs.io/en/latest/administrator-docs/installing/">Prebuilt Packages</a> or <a href="https://jellyfin.readthedocs.io/en/latest/administrator-docs/building/">Build from Source</a>, then see our <a href="https://jellyfin.readthedocs.io/en/latest/administrator-docs/first-time/">first-time setup guide</a>.</em>
-</p>
-<p align="center">
-<strong>Want to contribute?</strong>
-<em>Check out <a href="https://jellyfin.readthedocs.io/en/latest/contributor-docs/contributing/">our documentation for guidelines</a>.</em>
-</p>
-<p align="center">
-<strong>New idea or improvement? Something not working right?</strong>
-<em>Open an <a href="https://jellyfin.readthedocs.io/en/latest/contributor-docs/issues/">Issue</a>.</em>
+This project is supported by:
+<br/>
+<br/>
+<a href="https://www.digitalocean.com"><img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_horizontal_blue.svg" height="50px" alt="DigitalOcean"></a>
+ &nbsp;
+<a href="https://www.jetbrains.com"><img src="https://gist.githubusercontent.com/anthonylavado/e8b2403deee9581e0b4cb8cd675af7db/raw/fa104b7d73f759d7262794b94569f1b89df41c0b/jetbrains.svg" height="50px" alt="JetBrains logo"></a>
</p>
diff --git a/RSSDP/DeviceAvailableEventArgs.cs b/RSSDP/DeviceAvailableEventArgs.cs
index 9106e27e5..04b14c4dc 100644
--- a/RSSDP/DeviceAvailableEventArgs.cs
+++ b/RSSDP/DeviceAvailableEventArgs.cs
@@ -1,8 +1,5 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
+using System.Net;
namespace Rssdp
{
@@ -11,16 +8,11 @@ namespace Rssdp
/// </summary>
public sealed class DeviceAvailableEventArgs : EventArgs
{
- public IpAddressInfo LocalIpAddress { get; set; }
-
- #region Fields
+ public IPAddress RemoteIpAddress { get; set; }
private readonly DiscoveredSsdpDevice _DiscoveredDevice;
- private readonly bool _IsNewlyDiscovered;
-
- #endregion
- #region Constructors
+ private readonly bool _IsNewlyDiscovered;
/// <summary>
/// Full constructor.
@@ -29,34 +21,30 @@ namespace Rssdp
/// <param name="isNewlyDiscovered">A boolean value indicating whether or not this device came from the cache. See <see cref="IsNewlyDiscovered"/> for more detail.</param>
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception>
public DeviceAvailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool isNewlyDiscovered)
- {
- if (discoveredDevice == null) throw new ArgumentNullException(nameof(discoveredDevice));
-
- _DiscoveredDevice = discoveredDevice;
- _IsNewlyDiscovered = isNewlyDiscovered;
- }
-
- #endregion
+ {
+ if (discoveredDevice == null)
+ {
+ throw new ArgumentNullException(nameof(discoveredDevice));
+ }
- #region Public Properties
+ _DiscoveredDevice = discoveredDevice;
+ _IsNewlyDiscovered = isNewlyDiscovered;
+ }
- /// <summary>
- /// Returns true if the device was discovered due to an alive notification, or a search and was not already in the cache. Returns false if the item came from the cache but matched the current search request.
- /// </summary>
- public bool IsNewlyDiscovered
- {
- get { return _IsNewlyDiscovered; }
- }
+ /// <summary>
+ /// Returns true if the device was discovered due to an alive notification, or a search and was not already in the cache. Returns false if the item came from the cache but matched the current search request.
+ /// </summary>
+ public bool IsNewlyDiscovered
+ {
+ get { return _IsNewlyDiscovered; }
+ }
/// <summary>
/// A reference to a <see cref="DiscoveredSsdpDevice"/> instance containing the discovered details and allowing access to the full device description.
/// </summary>
public DiscoveredSsdpDevice DiscoveredDevice
- {
- get { return _DiscoveredDevice; }
- }
-
- #endregion
-
- }
-} \ No newline at end of file
+ {
+ get { return _DiscoveredDevice; }
+ }
+ }
+}
diff --git a/RSSDP/DeviceEventArgs.cs b/RSSDP/DeviceEventArgs.cs
index 3925ba248..2455ccbfa 100644
--- a/RSSDP/DeviceEventArgs.cs
+++ b/RSSDP/DeviceEventArgs.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Text;
namespace Rssdp
{
@@ -9,15 +7,8 @@ namespace Rssdp
/// </summary>
public sealed class DeviceEventArgs : EventArgs
{
-
- #region Fields
-
private readonly SsdpDevice _Device;
- #endregion
-
- #region Constructors
-
/// <summary>
/// Constructs a new instance for the specified <see cref="SsdpDevice"/>.
/// </summary>
@@ -25,15 +16,14 @@ namespace Rssdp
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
public DeviceEventArgs(SsdpDevice device)
{
- if (device == null) throw new ArgumentNullException(nameof(device));
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
_Device = device;
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Returns the <see cref="SsdpDevice"/> instance the event being raised for.
/// </summary>
@@ -41,8 +31,5 @@ namespace Rssdp
{
get { return _Device; }
}
-
- #endregion
-
}
}
diff --git a/RSSDP/DeviceUnavailableEventArgs.cs b/RSSDP/DeviceUnavailableEventArgs.cs
index d90ddfb60..94248f39f 100644
--- a/RSSDP/DeviceUnavailableEventArgs.cs
+++ b/RSSDP/DeviceUnavailableEventArgs.cs
@@ -1,7 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
namespace Rssdp
{
@@ -10,15 +7,9 @@ namespace Rssdp
/// </summary>
public sealed class DeviceUnavailableEventArgs : EventArgs
{
-
- #region Fields
-
private readonly DiscoveredSsdpDevice _DiscoveredDevice;
- private readonly bool _Expired;
-
- #endregion
- #region Constructors
+ private readonly bool _Expired;
/// <summary>
/// Full constructor.
@@ -28,16 +19,15 @@ namespace Rssdp
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception>
public DeviceUnavailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool expired)
{
- if (discoveredDevice == null) throw new ArgumentNullException(nameof(discoveredDevice));
+ if (discoveredDevice == null)
+ {
+ throw new ArgumentNullException(nameof(discoveredDevice));
+ }
_DiscoveredDevice = discoveredDevice;
_Expired = expired;
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Returns true if the device is considered unavailable because it's cached information expired before a new alive notification or search result was received. Returns false if the device is unavailable because it sent an explicit notification of it's unavailability.
/// </summary>
@@ -53,7 +43,5 @@ namespace Rssdp
{
get { return _DiscoveredDevice; }
}
-
- #endregion
}
}
diff --git a/RSSDP/DiscoveredSsdpDevice.cs b/RSSDP/DiscoveredSsdpDevice.cs
index f42e7c674..322bd55e5 100644
--- a/RSSDP/DiscoveredSsdpDevice.cs
+++ b/RSSDP/DiscoveredSsdpDevice.cs
@@ -1,8 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace Rssdp
@@ -14,15 +10,8 @@ namespace Rssdp
/// <seealso cref="Infrastructure.ISsdpDeviceLocator"/>
public sealed class DiscoveredSsdpDevice
{
-
- #region Fields
-
private DateTimeOffset _AsAt;
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Sets or returns the type of notification, being either a uuid, device type, service type or upnp:rootdevice.
/// </summary>
@@ -49,6 +38,7 @@ namespace Rssdp
public DateTimeOffset AsAt
{
get { return _AsAt; }
+
set
{
if (_AsAt != value)
@@ -59,14 +49,10 @@ namespace Rssdp
}
/// <summary>
- /// Returns the headers from the SSDP device response message
+ /// Returns the headers from the SSDP device response message.
/// </summary>
public HttpHeaders ResponseHeaders { get; set; }
- #endregion
-
- #region Public Methods
-
/// <summary>
/// Returns true if this device information has expired, based on the current date/time, and the <see cref="CacheLifetime"/> &amp; <see cref="AsAt"/> properties.
/// </summary>
@@ -76,10 +62,6 @@ namespace Rssdp
return this.CacheLifetime == TimeSpan.Zero || this.AsAt.Add(this.CacheLifetime) <= DateTimeOffset.Now;
}
- #endregion
-
- #region Overrides
-
/// <summary>
/// Returns the device's <see cref="Usn"/> value.
/// </summary>
@@ -88,7 +70,5 @@ namespace Rssdp
{
return this.Usn;
}
-
- #endregion
}
}
diff --git a/RSSDP/DisposableManagedObjectBase.cs b/RSSDP/DisposableManagedObjectBase.cs
index 0f656fb46..5d7da4124 100644
--- a/RSSDP/DisposableManagedObjectBase.cs
+++ b/RSSDP/DisposableManagedObjectBase.cs
@@ -1,18 +1,15 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Text;
-using System.Threading.Tasks;
namespace Rssdp.Infrastructure
{
/// <summary>
- /// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
+ /// Correctly implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceties not on the interface such as an <see cref="IsDisposed"/> property.
/// </summary>
public abstract class DisposableManagedObjectBase : IDisposable
{
-
- #region Public Methods
-
/// <summary>
/// Override this method and dispose any objects you own the lifetime of if disposing is true;
/// </summary>
@@ -27,13 +24,12 @@ namespace Rssdp.Infrastructure
/// <seealso cref="Dispose()"/>
protected virtual void ThrowIfDisposed()
{
- if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().FullName);
+ if (this.IsDisposed)
+ {
+ throw new ObjectDisposedException(this.GetType().FullName);
+ }
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Sets or returns a boolean indicating whether or not this instance has been disposed.
/// </summary>
@@ -44,19 +40,17 @@ namespace Rssdp.Infrastructure
private set;
}
- #endregion
-
public string BuildMessage(string header, Dictionary<string, string> values)
{
var builder = new StringBuilder();
- const string argFormat = "{0}: {1}\r\n";
+ const string ArgFormat = "{0}: {1}\r\n";
- builder.AppendFormat("{0}\r\n", header);
+ builder.AppendFormat(CultureInfo.InvariantCulture, "{0}\r\n", header);
foreach (var pair in values)
{
- builder.AppendFormat(argFormat, pair.Key, pair.Value);
+ builder.AppendFormat(CultureInfo.InvariantCulture, ArgFormat, pair.Key, pair.Value);
}
builder.Append("\r\n");
@@ -64,23 +58,19 @@ namespace Rssdp.Infrastructure
return builder.ToString();
}
- #region IDisposable Members
-
/// <summary>
/// Disposes this object instance and all internally managed resources.
/// </summary>
/// <remarks>
- /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
+ /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behavior of derived classes.</para>
/// </remarks>
/// <seealso cref="IsDisposed"/>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification="We do exactly as asked, but CA doesn't seem to like us also setting the IsDisposed property. Too bad, it's a good idea and shouldn't cause an exception or anything likely to interfer with the dispose process.")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "We do exactly as asked, but CA doesn't seem to like us also setting the IsDisposed property. Too bad, it's a good idea and shouldn't cause an exception or anything likely to interfere with the dispose process.")]
public void Dispose()
{
IsDisposed = true;
Dispose(true);
}
-
- #endregion
}
}
diff --git a/RSSDP/HttpParserBase.cs b/RSSDP/HttpParserBase.cs
index 18712470d..c56249523 100644
--- a/RSSDP/HttpParserBase.cs
+++ b/RSSDP/HttpParserBase.cs
@@ -2,8 +2,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
-using System.Text;
-using System.IO;
namespace Rssdp.Infrastructure
{
@@ -13,18 +11,9 @@ namespace Rssdp.Infrastructure
/// <typeparam name="T"></typeparam>
public abstract class HttpParserBase<T> where T : new()
{
-
- #region Fields
-
private readonly string[] LineTerminators = new string[] { "\r\n", "\n" };
private readonly char[] SeparatorCharacters = new char[] { ',', ';' };
- #endregion
-
- #region Public Methods
-
- private static byte[] EmptyByteArray = new byte[]{};
-
/// <summary>
/// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
/// </summary>
@@ -42,15 +31,26 @@ namespace Rssdp.Infrastructure
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Honestly, it's fine. MemoryStream doesn't mind.")]
protected virtual void Parse(T message, System.Net.Http.Headers.HttpHeaders headers, string data)
{
- if (data == null) throw new ArgumentNullException(nameof(data));
- if (data.Length == 0) throw new ArgumentException("data cannot be an empty string.", nameof(data));
- if (!LineTerminators.Any(data.Contains)) throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data));
+ if (data == null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
+ if (data.Length == 0)
+ {
+ throw new ArgumentException("data cannot be an empty string.", nameof(data));
+ }
- using (var retVal = new ByteArrayContent(EmptyByteArray))
+ if (!LineTerminators.Any(data.Contains))
+ {
+ throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data));
+ }
+
+ using (var retVal = new ByteArrayContent(Array.Empty<byte>()))
{
var lines = data.Split(LineTerminators, StringSplitOptions.None);
- //First line is the 'request' line containing http protocol details like method, uri, http version etc.
+ // First line is the 'request' line containing http protocol details like method, uri, http version etc.
ParseStatusLine(lines[0], message);
ParseHeaders(headers, retVal.Headers, lines);
@@ -77,18 +77,20 @@ namespace Rssdp.Infrastructure
/// <returns>A <see cref="Version"/> object containing the parsed version data.</returns>
protected Version ParseHttpVersion(string versionData)
{
- if (versionData == null) throw new ArgumentNullException(nameof(versionData));
+ if (versionData == null)
+ {
+ throw new ArgumentNullException(nameof(versionData));
+ }
var versionSeparatorIndex = versionData.IndexOf('/');
- if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length) throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData));
+ if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length)
+ {
+ throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData));
+ }
return Version.Parse(versionData.Substring(versionSeparatorIndex + 1));
}
- #endregion
-
- #region Private Methods
-
/// <summary>
/// Parses a line from an HTTP request or response message containing a header name and value pair.
/// </summary>
@@ -97,35 +99,39 @@ namespace Rssdp.Infrastructure
/// <param name="contentHeaders">A reference to a <see cref="System.Net.Http.Headers.HttpHeaders"/> collection for the message content, to which the parsed header will be added.</param>
private void ParseHeader(string line, System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders)
{
- //Header format is
- //name: value
+ // Header format is
+ // name: value
var headerKeySeparatorIndex = line.IndexOf(":", StringComparison.OrdinalIgnoreCase);
var headerName = line.Substring(0, headerKeySeparatorIndex).Trim();
var headerValue = line.Substring(headerKeySeparatorIndex + 1).Trim();
- //Not sure how to determine where request headers and and content headers begin,
- //at least not without a known set of headers (general headers first the content headers)
- //which seems like a bad way of doing it. So we'll assume if it's a known content header put it there
- //else use request headers.
+ // Not sure how to determine where request headers and content headers begin,
+ // at least not without a known set of headers (general headers first the content headers)
+ // which seems like a bad way of doing it. So we'll assume if it's a known content header put it there
+ // else use request headers.
var values = ParseValues(headerValue);
var headersToAddTo = IsContentHeader(headerName) ? contentHeaders : headers;
if (values.Count > 1)
+ {
headersToAddTo.TryAddWithoutValidation(headerName, values);
+ }
else
- headersToAddTo.TryAddWithoutValidation(headerName, values.First());
+ {
+ headersToAddTo.TryAddWithoutValidation(headerName, values[0]);
+ }
}
private int ParseHeaders(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders, string[] lines)
{
- //Blank line separates headers from content, so read headers until we find blank line.
+ // Blank line separates headers from content, so read headers until we find blank line.
int lineIndex = 1;
string line = null, nextLine = null;
while (lineIndex + 1 < lines.Length && !String.IsNullOrEmpty((line = lines[lineIndex++])))
{
- //If the following line starts with space or tab (or any whitespace), it is really part of this header but split for human readability.
- //Combine these lines into a single comma separated style header for easier parsing.
+ // If the following line starts with space or tab (or any whitespace), it is really part of this header but split for human readability.
+ // Combine these lines into a single comma separated style header for easier parsing.
while (lineIndex < lines.Length && !String.IsNullOrEmpty((nextLine = lines[lineIndex])))
{
if (nextLine.Length > 0 && Char.IsWhiteSpace(nextLine[0]))
@@ -134,15 +140,18 @@ namespace Rssdp.Infrastructure
lineIndex++;
}
else
+ {
break;
+ }
}
ParseHeader(line, headers, contentHeaders);
}
+
return lineIndex;
}
- private IList<string> ParseValues(string headerValue)
+ private List<string> ParseValues(string headerValue)
{
// This really should be better and match the HTTP 1.1 spec,
// but this should actually be good enough for SSDP implementations
@@ -151,29 +160,35 @@ namespace Rssdp.Infrastructure
if (headerValue == "\"\"")
{
- values.Add(String.Empty);
+ values.Add(string.Empty);
return values;
}
var indexOfSeparator = headerValue.IndexOfAny(SeparatorCharacters);
if (indexOfSeparator <= 0)
+ {
values.Add(headerValue);
+ }
else
{
var segments = headerValue.Split(SeparatorCharacters);
- if (headerValue.Contains("\""))
+ if (headerValue.Contains('"'))
{
for (int segmentIndex = 0; segmentIndex < segments.Length; segmentIndex++)
{
var segment = segments[segmentIndex];
if (segment.Trim().StartsWith("\"", StringComparison.OrdinalIgnoreCase))
+ {
segment = CombineQuotedSegments(segments, ref segmentIndex, segment);
+ }
values.Add(segment);
}
}
else
+ {
values.AddRange(segments);
+ }
}
return values;
@@ -196,17 +211,20 @@ namespace Rssdp.Infrastructure
}
if (index + 1 < segments.Length)
+ {
trimmedSegment += "," + segments[index + 1].TrimEnd();
+ }
}
segmentIndex = segments.Length;
if (trimmedSegment.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && trimmedSegment.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
+ {
return trimmedSegment.Substring(1, trimmedSegment.Length - 2);
+ }
else
+ {
return trimmedSegment;
+ }
}
-
- #endregion
-
}
-} \ No newline at end of file
+}
diff --git a/RSSDP/HttpRequestParser.cs b/RSSDP/HttpRequestParser.cs
index d4505b8ad..4114195a6 100644
--- a/RSSDP/HttpRequestParser.cs
+++ b/RSSDP/HttpRequestParser.cs
@@ -1,10 +1,6 @@
using System;
-using System.Collections.Generic;
using System.Linq;
-using System.Net;
using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
namespace Rssdp.Infrastructure
{
@@ -13,17 +9,10 @@ namespace Rssdp.Infrastructure
/// </summary>
public sealed class HttpRequestParser : HttpParserBase<HttpRequestMessage>
{
-
- #region Fields & Constants
-
private readonly string[] ContentHeaderNames = new string[]
- {
- "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
- };
-
- #endregion
-
- #region Public Methods
+ {
+ "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
+ };
/// <summary>
/// Parses the specified data into a <see cref="HttpRequestMessage"/> instance.
@@ -45,14 +34,12 @@ namespace Rssdp.Infrastructure
finally
{
if (retVal != null)
+ {
retVal.Dispose();
+ }
}
}
- #endregion
-
- #region Overrides
-
/// <summary>
/// Used to parse the first line of an HTTP request or response and assign the values to the appropriate properties on the <paramref name="message"/>.
/// </summary>
@@ -60,18 +47,32 @@ namespace Rssdp.Infrastructure
/// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param>
protected override void ParseStatusLine(string data, HttpRequestMessage message)
{
- if (data == null) throw new ArgumentNullException(nameof(data));
- if (message == null) throw new ArgumentNullException(nameof(message));
+ if (data == null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
+ if (message == null)
+ {
+ throw new ArgumentNullException(nameof(message));
+ }
var parts = data.Split(' ');
- if (parts.Length < 2) throw new ArgumentException("Status line is invalid. Insufficient status parts.", nameof(data));
+ if (parts.Length < 2)
+ {
+ throw new ArgumentException("Status line is invalid. Insufficient status parts.", nameof(data));
+ }
message.Method = new HttpMethod(parts[0].Trim());
Uri requestUri;
if (Uri.TryCreate(parts[1].Trim(), UriKind.RelativeOrAbsolute, out requestUri))
+ {
message.RequestUri = requestUri;
+ }
else
+ {
System.Diagnostics.Debug.WriteLine(parts[1]);
+ }
if (parts.Length >= 3)
{
@@ -87,8 +88,5 @@ namespace Rssdp.Infrastructure
{
return ContentHeaderNames.Contains(headerName, StringComparer.OrdinalIgnoreCase);
}
-
- #endregion
-
}
}
diff --git a/RSSDP/HttpResponseParser.cs b/RSSDP/HttpResponseParser.cs
index a77c898ff..0dd4bb45a 100644
--- a/RSSDP/HttpResponseParser.cs
+++ b/RSSDP/HttpResponseParser.cs
@@ -1,10 +1,7 @@
using System;
-using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
namespace Rssdp.Infrastructure
{
@@ -13,17 +10,10 @@ namespace Rssdp.Infrastructure
/// </summary>
public sealed class HttpResponseParser : HttpParserBase<HttpResponseMessage>
{
-
- #region Fields & Constants
-
private readonly string[] ContentHeaderNames = new string[]
- {
- "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
- };
-
- #endregion
-
- #region Public Methods
+ {
+ "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
+ };
/// <summary>
/// Parses the specified data into a <see cref="HttpResponseMessage"/> instance.
@@ -44,16 +34,14 @@ namespace Rssdp.Infrastructure
catch
{
if (retVal != null)
+ {
retVal.Dispose();
+ }
throw;
}
}
- #endregion
-
- #region Overrides Methods
-
/// <summary>
/// Returns a boolean indicating whether the specified HTTP header name represents a content header (true), or a message header (false).
/// </summary>
@@ -71,17 +59,29 @@ namespace Rssdp.Infrastructure
/// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param>
protected override void ParseStatusLine(string data, HttpResponseMessage message)
{
- if (data == null) throw new ArgumentNullException(nameof(data));
- if (message == null) throw new ArgumentNullException(nameof(message));
+ if (data == null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
+ if (message == null)
+ {
+ throw new ArgumentNullException(nameof(message));
+ }
var parts = data.Split(' ');
- if (parts.Length < 2) throw new ArgumentException("data status line is invalid. Insufficient status parts.", nameof(data));
+ if (parts.Length < 2)
+ {
+ throw new ArgumentException("data status line is invalid. Insufficient status parts.", nameof(data));
+ }
message.Version = ParseHttpVersion(parts[0].Trim());
int statusCode = -1;
if (!Int32.TryParse(parts[1].Trim(), out statusCode))
+ {
throw new ArgumentException("data status line is invalid. Status code is not a valid integer.", nameof(data));
+ }
message.StatusCode = (HttpStatusCode)statusCode;
@@ -90,7 +90,5 @@ namespace Rssdp.Infrastructure
message.ReasonPhrase = parts[2].Trim();
}
}
-
- #endregion
}
}
diff --git a/RSSDP/IEnumerableExtensions.cs b/RSSDP/IEnumerableExtensions.cs
index c96542dca..1f0daad3e 100644
--- a/RSSDP/IEnumerableExtensions.cs
+++ b/RSSDP/IEnumerableExtensions.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
namespace Rssdp.Infrastructure
{
@@ -9,8 +8,15 @@ namespace Rssdp.Infrastructure
{
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
- if (source == null) throw new ArgumentNullException(nameof(source));
- if (selector == null) throw new ArgumentNullException(nameof(selector));
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (selector == null)
+ {
+ throw new ArgumentNullException(nameof(selector));
+ }
return !source.Any() ? source :
source.Concat(
diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs
index ef75f997f..aa35811ef 100644
--- a/RSSDP/ISsdpCommunicationsServer.cs
+++ b/RSSDP/ISsdpCommunicationsServer.cs
@@ -1,7 +1,7 @@
using System;
+using System.Net;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
{
@@ -10,9 +10,6 @@ namespace Rssdp.Infrastructure
/// </summary>
public interface ISsdpCommunicationsServer : IDisposable
{
-
- #region Events
-
/// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary>
@@ -23,10 +20,6 @@ namespace Rssdp.Infrastructure
/// </summary>
event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
- #endregion
-
- #region Methods
-
/// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
@@ -40,17 +33,13 @@ namespace Rssdp.Infrastructure
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </summary>
- Task SendMessage(byte[] messageData, IpEndPointInfo destination, IpAddressInfo fromLocalIpAddress, CancellationToken cancellationToken);
+ Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
/// <summary>
/// Sends a message to the SSDP multicast address and port.
/// </summary>
- Task SendMulticastMessage(string message, CancellationToken cancellationToken);
- Task SendMulticastMessage(string message, int sendCount, CancellationToken cancellationToken);
-
- #endregion
-
- #region Properties
+ Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
+ Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
/// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
@@ -59,8 +48,5 @@ namespace Rssdp.Infrastructure
/// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
/// </remarks>
bool IsShared { get; set; }
-
- #endregion
-
}
-} \ No newline at end of file
+}
diff --git a/RSSDP/ISsdpDeviceLocator.cs b/RSSDP/ISsdpDeviceLocator.cs
index 8f0d39e75..4df166cd2 100644
--- a/RSSDP/ISsdpDeviceLocator.cs
+++ b/RSSDP/ISsdpDeviceLocator.cs
@@ -13,9 +13,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="ISsdpDevicePublisher"/>
public interface ISsdpDeviceLocator
{
-
- #region Events
-
/// <summary>
/// Event raised when a device becomes available or is found by a search request.
/// </summary>
@@ -34,10 +31,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="StopListeningForNotifications"/>
event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable;
- #endregion
-
- #region Properties
-
/// <summary>
/// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="DeviceAvailable"/> or <see cref="DeviceUnavailable"/> events.
/// </summary>
@@ -58,14 +51,8 @@ namespace Rssdp.Infrastructure
set;
}
- #endregion
-
- #region Methods
-
- #region SearchAsync Overloads
-
/// <summary>
- /// Aynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results.
+ /// Asynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results.
/// </summary>
/// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns>
System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync();
@@ -96,7 +83,7 @@ namespace Rssdp.Infrastructure
/// </param>
/// <param name="searchWaitTime">The amount of time to wait for network responses to the search request. Longer values will likely return more devices, but increase search time. A value between 1 and 5 is recommended by the UPnP 1.1 specification. Specify TimeSpan.Zero to return only devices already in the cache.</param>
/// <remarks>
- /// <para>By design RSSDP does not support 'publishing services' as it is intended for use with non-standard UPnP devices that don't publish UPnP style services. However, it is still possible to use RSSDP to search for devices implemetning these services if you know the service type.</para>
+ /// <para>By design RSSDP does not support 'publishing services' as it is intended for use with non-standard UPnP devices that don't publish UPnP style services. However, it is still possible to use RSSDP to search for devices implementing these services if you know the service type.</para>
/// </remarks>
/// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns>
System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(string searchTarget, TimeSpan searchWaitTime);
@@ -108,8 +95,6 @@ namespace Rssdp.Infrastructure
/// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns>
System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(TimeSpan searchWaitTime);
- #endregion
-
/// <summary>
/// Starts listening for broadcast notifications of service availability.
/// </summary>
@@ -134,8 +119,5 @@ namespace Rssdp.Infrastructure
/// <seealso cref="DeviceUnavailable"/>
/// <seealso cref="NotificationFilter"/>
void StopListeningForNotifications();
-
- #endregion
-
}
}
diff --git a/RSSDP/ISsdpDevicePublisher.cs b/RSSDP/ISsdpDevicePublisher.cs
index 7e914c109..96c15443d 100644
--- a/RSSDP/ISsdpDevicePublisher.cs
+++ b/RSSDP/ISsdpDevicePublisher.cs
@@ -1,4 +1,3 @@
-using System;
using System.Threading.Tasks;
namespace Rssdp.Infrastructure
diff --git a/RSSDP/Properties/AssemblyInfo.cs b/RSSDP/Properties/AssemblyInfo.cs
index d2bb7c6f3..55f7b6a83 100644
--- a/RSSDP/Properties/AssemblyInfo.cs
+++ b/RSSDP/Properties/AssemblyInfo.cs
@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2015 Troy Willmot. Code released under the MIT license. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright © 2015 Troy Willmot. Code released under the MIT license. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
diff --git a/RSSDP/RSSDP.csproj b/RSSDP/RSSDP.csproj
index f06d4687b..77130983b 100644
--- a/RSSDP/RSSDP.csproj
+++ b/RSSDP/RSSDP.csproj
@@ -1,13 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{21002819-C39A-4D3E-BE83-2A276A77FB1F}</ProjectGuid>
+ </PropertyGroup>
+
<ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
+ <ProjectReference Include="..\Jellyfin.Networking\Jellyfin.Networking.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
<PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <AnalysisMode>AllDisabledByDefault</AnalysisMode>
+ <Nullable>disable</Nullable>
+ <NoWarn>CA2016</NoWarn>
</PropertyGroup>
</Project>
diff --git a/RSSDP/RequestReceivedEventArgs.cs b/RSSDP/RequestReceivedEventArgs.cs
index fd3cd9e3a..025c4d2e0 100644
--- a/RSSDP/RequestReceivedEventArgs.cs
+++ b/RSSDP/RequestReceivedEventArgs.cs
@@ -1,10 +1,6 @@
using System;
-using System.Collections.Generic;
using System.Net;
using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
{
@@ -13,31 +9,22 @@ namespace Rssdp.Infrastructure
/// </summary>
public sealed class RequestReceivedEventArgs : EventArgs
{
- #region Fields
-
private readonly HttpRequestMessage _Message;
- private readonly IpEndPointInfo _ReceivedFrom;
-
- #endregion
- public IpAddressInfo LocalIpAddress { get; private set; }
+ private readonly IPEndPoint _ReceivedFrom;
- #region Constructors
+ public IPAddress LocalIpAddress { get; private set; }
/// <summary>
/// Full constructor.
/// </summary>
- public RequestReceivedEventArgs(HttpRequestMessage message, IpEndPointInfo receivedFrom, IpAddressInfo localIpAddress)
+ public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIpAddress)
{
_Message = message;
_ReceivedFrom = receivedFrom;
LocalIpAddress = localIpAddress;
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// The <see cref="HttpRequestMessage"/> that was received.
/// </summary>
@@ -49,11 +36,9 @@ namespace Rssdp.Infrastructure
/// <summary>
/// The <see cref="UdpEndPoint"/> the request came from.
/// </summary>
- public IpEndPointInfo ReceivedFrom
+ public IPEndPoint ReceivedFrom
{
get { return _ReceivedFrom; }
}
-
- #endregion
}
}
diff --git a/RSSDP/ResponseReceivedEventArgs.cs b/RSSDP/ResponseReceivedEventArgs.cs
index 5ed9664ed..708113da1 100644
--- a/RSSDP/ResponseReceivedEventArgs.cs
+++ b/RSSDP/ResponseReceivedEventArgs.cs
@@ -1,10 +1,6 @@
using System;
-using System.Collections.Generic;
using System.Net;
using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
{
@@ -13,31 +9,21 @@ namespace Rssdp.Infrastructure
/// </summary>
public sealed class ResponseReceivedEventArgs : EventArgs
{
-
- public IpAddressInfo LocalIpAddress { get; set; }
-
- #region Fields
+ public IPAddress LocalIpAddress { get; set; }
private readonly HttpResponseMessage _Message;
- private readonly IpEndPointInfo _ReceivedFrom;
-
- #endregion
- #region Constructors
+ private readonly IPEndPoint _ReceivedFrom;
/// <summary>
/// Full constructor.
/// </summary>
- public ResponseReceivedEventArgs(HttpResponseMessage message, IpEndPointInfo receivedFrom)
+ public ResponseReceivedEventArgs(HttpResponseMessage message, IPEndPoint receivedFrom)
{
_Message = message;
_ReceivedFrom = receivedFrom;
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// The <see cref="HttpResponseMessage"/> that was received.
/// </summary>
@@ -49,11 +35,9 @@ namespace Rssdp.Infrastructure
/// <summary>
/// The <see cref="UdpEndPoint"/> the response came from.
/// </summary>
- public IpEndPointInfo ReceivedFrom
+ public IPEndPoint ReceivedFrom
{
get { return _ReceivedFrom; }
}
-
- #endregion
}
}
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs
index 04e76ef59..58dabc628 100644
--- a/RSSDP/SsdpCommunicationsServer.cs
+++ b/RSSDP/SsdpCommunicationsServer.cs
@@ -1,14 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
-using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
+using Microsoft.Extensions.Logging;
namespace Rssdp.Infrastructure
{
@@ -17,9 +18,6 @@ namespace Rssdp.Infrastructure
/// </summary>
public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
{
-
- #region Fields
-
/* We could technically use one socket listening on port 1900 for everything.
* This should get both multicast (notifications) and unicast (search response) messages, however
* this often doesn't work under Windows because the MS SSDP service is running. If that service
@@ -52,10 +50,6 @@ namespace Rssdp.Infrastructure
private bool _IsShared;
private readonly bool _enableMultiSocketBinding;
- #endregion
-
- #region Events
-
/// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary>
@@ -66,17 +60,15 @@ namespace Rssdp.Infrastructure
/// </summary>
public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
- #endregion
-
- #region Constructors
-
/// <summary>
/// Minimum constructor.
/// </summary>
/// <exception cref="ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
- public SsdpCommunicationsServer(ISocketFactory socketFactory, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
+ public SsdpCommunicationsServer(ISocketFactory socketFactory,
+ INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
: this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger, enableMultiSocketBinding)
{
+
}
/// <summary>
@@ -86,8 +78,15 @@ namespace Rssdp.Infrastructure
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
{
- if (socketFactory == null) throw new ArgumentNullException(nameof(socketFactory));
- if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero.");
+ if (socketFactory == null)
+ {
+ throw new ArgumentNullException(nameof(socketFactory));
+ }
+
+ if (multicastTimeToLive <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero.");
+ }
_BroadcastListenSocketSynchroniser = new object();
_SendSocketSynchroniser = new object();
@@ -104,10 +103,6 @@ namespace Rssdp.Infrastructure
_enableMultiSocketBinding = enableMultiSocketBinding;
}
- #endregion
-
- #region Public Methods
-
/// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
@@ -159,9 +154,12 @@ namespace Rssdp.Infrastructure
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </summary>
- public async Task SendMessage(byte[] messageData, IpEndPointInfo destination, IpAddressInfo fromLocalIpAddress, CancellationToken cancellationToken)
+ public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{
- if (messageData == null) throw new ArgumentNullException(nameof(messageData));
+ if (messageData == null)
+ {
+ throw new ArgumentNullException(nameof(messageData));
+ }
ThrowIfDisposed();
@@ -182,7 +180,7 @@ namespace Rssdp.Infrastructure
}
}
- private async Task SendFromSocket(ISocket socket, byte[] messageData, IpEndPointInfo destination, CancellationToken cancellationToken)
+ private async Task SendFromSocket(ISocket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken)
{
try
{
@@ -190,11 +188,9 @@ namespace Rssdp.Infrastructure
}
catch (ObjectDisposedException)
{
-
}
catch (OperationCanceledException)
{
-
}
catch (Exception ex)
{
@@ -202,7 +198,7 @@ namespace Rssdp.Infrastructure
}
}
- private List<ISocket> GetSendSockets(IpAddressInfo fromLocalIpAddress, IpEndPointInfo destination)
+ private List<ISocket> GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination)
{
EnsureSendSocketCreated();
@@ -211,24 +207,24 @@ namespace Rssdp.Infrastructure
var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily);
// Send from the Any socket and the socket with the matching address
- if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetwork)
+ if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork)
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
+ sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
// If sending to the loopback address, filter the socket list as well
- if (destination.IpAddress.Equals(IpAddressInfo.Loopback))
+ if (destination.Address.Equals(IPAddress.Loopback))
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || i.LocalIPAddress.Equals(IpAddressInfo.Loopback));
+ sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || i.LocalIPAddress.Equals(IPAddress.Loopback));
}
}
- else if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
+ else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
+ sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
// If sending to the loopback address, filter the socket list as well
- if (destination.IpAddress.Equals(IpAddressInfo.IPv6Loopback))
+ if (destination.Address.Equals(IPAddress.IPv6Loopback))
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || i.LocalIPAddress.Equals(IpAddressInfo.IPv6Loopback));
+ sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || i.LocalIPAddress.Equals(IPAddress.IPv6Loopback));
}
}
@@ -236,17 +232,20 @@ namespace Rssdp.Infrastructure
}
}
- public Task SendMulticastMessage(string message, CancellationToken cancellationToken)
+ public Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{
- return SendMulticastMessage(message, SsdpConstants.UdpResendCount, cancellationToken);
+ return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromLocalIpAddress, cancellationToken);
}
/// <summary>
/// Sends a message to the SSDP multicast address and port.
/// </summary>
- public async Task SendMulticastMessage(string message, int sendCount, CancellationToken cancellationToken)
+ public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{
- if (message == null) throw new ArgumentNullException(nameof(message));
+ if (message == null)
+ {
+ throw new ArgumentNullException(nameof(message));
+ }
byte[] messageData = Encoding.UTF8.GetBytes(message);
@@ -259,12 +258,13 @@ namespace Rssdp.Infrastructure
// SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
for (var i = 0; i < sendCount; i++)
{
- await SendMessageIfSocketNotDisposed(messageData, new IpEndPointInfo
- {
- IpAddress = new IpAddressInfo(SsdpConstants.MulticastLocalAdminAddress, IpAddressFamily.InterNetwork),
- Port = SsdpConstants.MulticastPort
-
- }, cancellationToken).ConfigureAwait(false);
+ await SendMessageIfSocketNotDisposed(
+ messageData,
+ new IPEndPoint(
+ IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress),
+ SsdpConstants.MulticastPort),
+ fromLocalIpAddress,
+ cancellationToken).ConfigureAwait(false);
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
@@ -294,10 +294,6 @@ namespace Rssdp.Infrastructure
}
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
/// </summary>
@@ -307,13 +303,10 @@ namespace Rssdp.Infrastructure
public bool IsShared
{
get { return _IsShared; }
+
set { _IsShared = value; }
}
- #endregion
-
- #region Overrides
-
/// <summary>
/// Stops listening for requests, disposes this instance and all internal resources.
/// </summary>
@@ -328,18 +321,15 @@ namespace Rssdp.Infrastructure
}
}
- #endregion
-
- #region Private Methods
-
- private Task SendMessageIfSocketNotDisposed(byte[] messageData, IpEndPointInfo destination, CancellationToken cancellationToken)
+ private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{
var sockets = _sendSockets;
if (sockets != null)
{
sockets = sockets.ToList();
- var tasks = sockets.Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
+ var tasks = sockets.Where(s => (fromLocalIpAddress == null || fromLocalIpAddress.Equals(s.LocalIPAddress)))
+ .Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
return Task.WhenAll(tasks);
}
@@ -349,8 +339,7 @@ namespace Rssdp.Infrastructure
private ISocket ListenForBroadcastsAsync()
{
var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
-
- ListenToSocket(socket);
+ _ = ListenToSocketInternal(socket);
return socket;
}
@@ -359,21 +348,21 @@ namespace Rssdp.Infrastructure
{
var sockets = new List<ISocket>();
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IpAddressInfo.Any, _LocalPort));
+ sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort));
if (_enableMultiSocketBinding)
{
- foreach (var address in _networkManager.GetLocalIpAddresses())
+ foreach (var address in _networkManager.GetInternalBindAddresses())
{
- if (address.AddressFamily == IpAddressFamily.InterNetworkV6)
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
- // Not supported ?
+ // Not support IPv6 right now
continue;
}
try
{
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address, _LocalPort));
+ sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort));
}
catch (Exception ex)
{
@@ -384,19 +373,12 @@ namespace Rssdp.Infrastructure
foreach (var socket in sockets)
{
- ListenToSocket(socket);
+ _ = ListenToSocketInternal(socket);
}
return sockets;
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
- private void ListenToSocket(ISocket socket)
- {
- // Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
- var t = Task.Run(() => ListenToSocketInternal(socket));
- }
-
private async Task ListenToSocketInternal(ISocket socket)
{
var cancelled = false;
@@ -413,7 +395,7 @@ namespace Rssdp.Infrastructure
// Strange cannot convert compiler error here if I don't explicitly
// assign or cast to Action first. Assignment is easier to read,
// so went with that.
- ProcessMessage(System.Text.UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress);
+ ProcessMessage(UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress);
}
}
catch (ObjectDisposedException)
@@ -433,20 +415,17 @@ namespace Rssdp.Infrastructure
{
lock (_SendSocketSynchroniser)
{
- if (_sendSockets == null)
- {
- _sendSockets = CreateSocketAndListenForResponsesAsync();
- }
+ _sendSockets ??= CreateSocketAndListenForResponsesAsync();
}
}
}
- private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress)
+ private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnLocalIpAddress)
{
- //Responses start with the HTTP version, prefixed with HTTP/ while
- //requests start with a method which can vary and might be one we haven't
- //seen/don't know. We'll check if this message is a request or a response
- //by checking for the HTTP/ prefix on the start of the message.
+ // Responses start with the HTTP version, prefixed with HTTP/ while
+ // requests start with a method which can vary and might be one we haven't
+ // seen/don't know. We'll check if this message is a request or a response
+ // by checking for the HTTP/ prefix on the start of the message.
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage responseMessage = null;
@@ -460,7 +439,9 @@ namespace Rssdp.Infrastructure
}
if (responseMessage != null)
+ {
OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
+ }
}
else
{
@@ -481,11 +462,11 @@ namespace Rssdp.Infrastructure
}
}
- private void OnRequestReceived(HttpRequestMessage data, IpEndPointInfo remoteEndPoint, IpAddressInfo receivedOnLocalIpAddress)
+ private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnLocalIpAddress)
{
- //SSDP specification says only * is currently used but other uri's might
- //be implemented in the future and should be ignored unless understood.
- //Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
+ // SSDP specification says only * is currently used but other uri's might
+ // be implemented in the future and should be ignored unless understood.
+ // Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
if (data.RequestUri.ToString() != "*")
{
return;
@@ -493,20 +474,21 @@ namespace Rssdp.Infrastructure
var handlers = this.RequestReceived;
if (handlers != null)
+ {
handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
+ }
}
- private void OnResponseReceived(HttpResponseMessage data, IpEndPointInfo endPoint, IpAddressInfo localIpAddress)
+ private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress)
{
var handlers = this.ResponseReceived;
if (handlers != null)
+ {
handlers(this, new ResponseReceivedEventArgs(data, endPoint)
{
LocalIpAddress = localIpAddress
});
+ }
}
-
- #endregion
-
}
}
diff --git a/RSSDP/SsdpConstants.cs b/RSSDP/SsdpConstants.cs
index 8372d1cb3..798f050e1 100644
--- a/RSSDP/SsdpConstants.cs
+++ b/RSSDP/SsdpConstants.cs
@@ -1,8 +1,3 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-
namespace Rssdp.Infrastructure
{
/// <summary>
@@ -62,6 +57,5 @@ namespace Rssdp.Infrastructure
internal const string SsdpByeByeNotification = "ssdp:byebye";
internal const int UdpResendCount = 3;
-
}
}
diff --git a/RSSDP/SsdpDevice.cs b/RSSDP/SsdpDevice.cs
index b4c4a88fd..c826830f1 100644
--- a/RSSDP/SsdpDevice.cs
+++ b/RSSDP/SsdpDevice.cs
@@ -1,9 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using System.Text;
-using System.Threading.Tasks;
-using System.Xml;
+using System.Globalization;
using Rssdp.Infrastructure;
namespace Rssdp
@@ -18,9 +16,6 @@ namespace Rssdp
/// <seealso cref="SsdpEmbeddedDevice"/>
public abstract class SsdpDevice
{
-
- #region Fields
-
private string _Udn;
private string _DeviceType;
private string _DeviceTypeNamespace;
@@ -28,10 +23,6 @@ namespace Rssdp
private IList<SsdpDevice> _Devices;
- #endregion
-
- #region Events
-
/// <summary>
/// Raised when a new child device is added.
/// </summary>
@@ -46,10 +37,6 @@ namespace Rssdp
/// <seealso cref="DeviceRemoved"/>
public event EventHandler<DeviceEventArgs> DeviceRemoved;
- #endregion
-
- #region Constructors
-
/// <summary>
/// Derived type constructor, allows constructing a device with no parent. Should only be used from derived types that are or inherit from <see cref="SsdpRootDevice"/>.
/// </summary>
@@ -63,23 +50,19 @@ namespace Rssdp
this.Devices = new ReadOnlyCollection<SsdpDevice>(_Devices);
}
- #endregion
-
public SsdpRootDevice ToRootDevice()
{
var device = this;
var rootDevice = device as SsdpRootDevice;
if (rootDevice == null)
+ {
rootDevice = ((SsdpEmbeddedDevice)device).RootDevice;
+ }
return rootDevice;
}
- #region Public Properties
-
- #region UPnP Device Description Properties
-
/// <summary>
/// Sets or returns the core device type (not including namespace, version etc.). Required.
/// </summary>
@@ -93,6 +76,7 @@ namespace Rssdp
{
return _DeviceType;
}
+
set
{
_DeviceType = value;
@@ -114,6 +98,7 @@ namespace Rssdp
{
return _DeviceTypeNamespace;
}
+
set
{
_DeviceTypeNamespace = value;
@@ -133,6 +118,7 @@ namespace Rssdp
{
return _DeviceVersion;
}
+
set
{
_DeviceVersion = value;
@@ -149,11 +135,13 @@ namespace Rssdp
{
get
{
- return String.Format("urn:{0}:{3}:{1}:{2}",
- this.DeviceTypeNamespace ?? String.Empty,
- this.DeviceType ?? String.Empty,
- this.DeviceVersion,
- this.DeviceClass ?? "device");
+ return String.Format(
+ CultureInfo.InvariantCulture,
+ "urn:{0}:{3}:{1}:{2}",
+ this.DeviceTypeNamespace ?? String.Empty,
+ this.DeviceType ?? String.Empty,
+ this.DeviceVersion,
+ this.DeviceClass ?? "device");
}
}
@@ -180,10 +168,15 @@ namespace Rssdp
get
{
if (String.IsNullOrEmpty(_Udn) && !String.IsNullOrEmpty(this.Uuid))
+ {
return "uuid:" + this.Uuid;
+ }
else
+ {
return _Udn;
+ }
}
+
set
{
_Udn = value;
@@ -251,8 +244,6 @@ namespace Rssdp
/// </remarks>
public Uri PresentationUrl { get; set; }
- #endregion
-
/// <summary>
/// Returns a read-only enumerable set of <see cref="SsdpDevice"/> objects representing children of this device. Child devices are optional.
/// </summary>
@@ -264,10 +255,6 @@ namespace Rssdp
private set;
}
- #endregion
-
- #region Public Methods
-
/// <summary>
/// Adds a child device to the <see cref="Devices"/> collection.
/// </summary>
@@ -281,9 +268,20 @@ namespace Rssdp
/// <seealso cref="DeviceAdded"/>
public void AddDevice(SsdpEmbeddedDevice device)
{
- if (device == null) throw new ArgumentNullException(nameof(device));
- if (device.RootDevice != null && device.RootDevice != this.ToRootDevice()) throw new InvalidOperationException("This device is already associated with a different root device (has been added as a child in another branch).");
- if (device == this) throw new InvalidOperationException("Can't add device to itself.");
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
+
+ if (device.RootDevice != null && device.RootDevice != this.ToRootDevice())
+ {
+ throw new InvalidOperationException("This device is already associated with a different root device (has been added as a child in another branch).");
+ }
+
+ if (device == this)
+ {
+ throw new InvalidOperationException("Can't add device to itself.");
+ }
bool wasAdded = false;
lock (_Devices)
@@ -294,7 +292,9 @@ namespace Rssdp
}
if (wasAdded)
+ {
OnDeviceAdded(device);
+ }
}
/// <summary>
@@ -309,7 +309,10 @@ namespace Rssdp
/// <seealso cref="DeviceRemoved"/>
public void RemoveDevice(SsdpEmbeddedDevice device)
{
- if (device == null) throw new ArgumentNullException(nameof(device));
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
bool wasRemoved = false;
lock (_Devices)
@@ -322,7 +325,9 @@ namespace Rssdp
}
if (wasRemoved)
+ {
OnDeviceRemoved(device);
+ }
}
/// <summary>
@@ -335,7 +340,9 @@ namespace Rssdp
{
var handlers = this.DeviceAdded;
if (handlers != null)
+ {
handlers(this, new DeviceEventArgs(device));
+ }
}
/// <summary>
@@ -348,10 +355,9 @@ namespace Rssdp
{
var handlers = this.DeviceRemoved;
if (handlers != null)
+ {
handlers(this, new DeviceEventArgs(device));
+ }
}
-
- #endregion
-
}
}
diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs
index 128bdfcbb..3a52b2a3e 100644
--- a/RSSDP/SsdpDeviceLocator.cs
+++ b/RSSDP/SsdpDeviceLocator.cs
@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.IO;
using System.Linq;
+using System.Net;
using System.Net.Http;
-using System.Text;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
{
@@ -16,9 +13,6 @@ namespace Rssdp.Infrastructure
/// </summary>
public class SsdpDeviceLocator : DisposableManagedObjectBase
{
-
- #region Fields & Constants
-
private List<DiscoveredSsdpDevice> _Devices;
private ISsdpCommunicationsServer _CommunicationsServer;
@@ -28,16 +22,15 @@ namespace Rssdp.Infrastructure
private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4);
private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
- #endregion
-
- #region Constructors
-
/// <summary>
/// Default constructor.
/// </summary>
public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer)
{
- if (communicationsServer == null) throw new ArgumentNullException(nameof(communicationsServer));
+ if (communicationsServer == null)
+ {
+ throw new ArgumentNullException(nameof(communicationsServer));
+ }
_CommunicationsServer = communicationsServer;
_CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived;
@@ -45,10 +38,6 @@ namespace Rssdp.Infrastructure
_Devices = new List<DiscoveredSsdpDevice>();
}
- #endregion
-
- #region Events
-
/// <summary>
/// Raised for when
/// <list type="bullet">
@@ -79,12 +68,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="StopListeningForNotifications"/>
public event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable;
- #endregion
-
- #region Public Methods
-
- #region Search Overloads
-
public void RestartBroadcastTimer(TimeSpan dueTime, TimeSpan period)
{
lock (_timerLock)
@@ -114,6 +97,11 @@ namespace Rssdp.Infrastructure
private async void OnBroadcastTimerCallback(object state)
{
+ if (IsDisposed)
+ {
+ return;
+ }
+
StartListeningForNotifications();
RemoveExpiredDevicesFromCache();
@@ -123,7 +111,6 @@ namespace Rssdp.Infrastructure
}
catch (Exception)
{
-
}
}
@@ -161,18 +148,31 @@ namespace Rssdp.Infrastructure
private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken)
{
- if (searchTarget == null) throw new ArgumentNullException(nameof(searchTarget));
- if (searchTarget.Length == 0) throw new ArgumentException("searchTarget cannot be an empty string.", nameof(searchTarget));
- if (searchWaitTime.TotalSeconds < 0) throw new ArgumentException("searchWaitTime must be a positive time.");
- if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1) throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second.");
+ if (searchTarget == null)
+ {
+ throw new ArgumentNullException(nameof(searchTarget));
+ }
+
+ if (searchTarget.Length == 0)
+ {
+ throw new ArgumentException("searchTarget cannot be an empty string.", nameof(searchTarget));
+ }
+
+ if (searchWaitTime.TotalSeconds < 0)
+ {
+ throw new ArgumentException("searchWaitTime must be a positive time.");
+ }
+
+ if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1)
+ {
+ throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second.");
+ }
ThrowIfDisposed();
return BroadcastDiscoverMessage(searchTarget, SearchTimeToMXValue(searchWaitTime), cancellationToken);
}
- #endregion
-
/// <summary>
/// Starts listening for broadcast notifications of service availability.
/// </summary>
@@ -185,8 +185,6 @@ namespace Rssdp.Infrastructure
/// <exception cref="ObjectDisposedException">Throw if the <see cref="DisposableManagedObjectBase.IsDisposed"/> ty is true.</exception>
public void StartListeningForNotifications()
{
- ThrowIfDisposed();
-
_CommunicationsServer.RequestReceived -= CommsServer_RequestReceived;
_CommunicationsServer.RequestReceived += CommsServer_RequestReceived;
_CommunicationsServer.BeginListeningForBroadcasts();
@@ -213,16 +211,21 @@ namespace Rssdp.Infrastructure
/// Raises the <see cref="DeviceAvailable"/> event.
/// </summary>
/// <seealso cref="DeviceAvailable"/>
- protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
+ protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress)
{
- if (this.IsDisposed) return;
+ if (this.IsDisposed)
+ {
+ return;
+ }
var handlers = this.DeviceAvailable;
if (handlers != null)
+ {
handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
{
- LocalIpAddress = localIpAddress
+ RemoteIpAddress = IpAddress
});
+ }
}
/// <summary>
@@ -233,17 +236,18 @@ namespace Rssdp.Infrastructure
/// <seealso cref="DeviceUnavailable"/>
protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired)
{
- if (this.IsDisposed) return;
+ if (this.IsDisposed)
+ {
+ return;
+ }
var handlers = this.DeviceUnavailable;
if (handlers != null)
+ {
handlers(this, new DeviceUnavailableEventArgs(device, expired));
+ }
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="ISsdpDeviceLocator.DeviceAvailable"/> or <see cref="ISsdpDeviceLocator.DeviceUnavailable"/> events.
/// </summary>
@@ -265,10 +269,6 @@ namespace Rssdp.Infrastructure
set;
}
- #endregion
-
- #region Overrides
-
/// <summary>
/// Disposes this object and all internal resources. Stops listening for all network messages.
/// </summary>
@@ -289,13 +289,7 @@ namespace Rssdp.Infrastructure
}
}
- #endregion
-
- #region Private Methods
-
- #region Discovery/Device Add
-
- private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IpAddressInfo localIpAddress)
+ private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IpAddress)
{
bool isNewDevice = false;
lock (_Devices)
@@ -313,14 +307,17 @@ namespace Rssdp.Infrastructure
}
}
- DeviceFound(device, isNewDevice, localIpAddress);
+ DeviceFound(device, isNewDevice, IpAddress);
}
- private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
+ private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress)
{
- if (!NotificationTypeMatchesFilter(device)) return;
+ if (!NotificationTypeMatchesFilter(device))
+ {
+ return;
+ }
- OnDeviceAvailable(device, isNewDevice, localIpAddress);
+ OnDeviceAvailable(device, isNewDevice, IpAddress);
}
private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
@@ -330,17 +327,13 @@ namespace Rssdp.Infrastructure
|| device.NotificationType == this.NotificationFilter;
}
- #endregion
-
- #region Network Message Processing
-
private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken)
{
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
values["HOST"] = "239.255.255.250:1900";
values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
- //values["X-EMBY-SERVERID"] = _appHost.SystemId;
+ // values["X-EMBY-SERVERID"] = _appHost.SystemId;
values["MAN"] = "\"ssdp:discover\"";
@@ -354,12 +347,15 @@ namespace Rssdp.Infrastructure
var message = BuildMessage(header, values);
- return _CommunicationsServer.SendMulticastMessage(message, cancellationToken);
+ return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken);
}
- private void ProcessSearchResponseMessage(HttpResponseMessage message, IpAddressInfo localIpAddress)
+ private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress)
{
- if (!message.IsSuccessStatusCode) return;
+ if (!message.IsSuccessStatusCode)
+ {
+ return;
+ }
var location = GetFirstHeaderUriValue("Location", message);
if (location != null)
@@ -374,22 +370,29 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers
};
- AddOrUpdateDiscoveredDevice(device, localIpAddress);
+ AddOrUpdateDiscoveredDevice(device, IpAddress);
}
}
- private void ProcessNotificationMessage(HttpRequestMessage message, IpAddressInfo localIpAddress)
+ private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IpAddress)
{
- if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) return;
+ if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0)
+ {
+ return;
+ }
var notificationType = GetFirstHeaderStringValue("NTS", message);
if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
- ProcessAliveNotification(message, localIpAddress);
+ {
+ ProcessAliveNotification(message, IpAddress);
+ }
else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
+ {
ProcessByeByeNotification(message);
+ }
}
- private void ProcessAliveNotification(HttpRequestMessage message, IpAddressInfo localIpAddress)
+ private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress)
{
var location = GetFirstHeaderUriValue("Location", message);
if (location != null)
@@ -404,7 +407,7 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers
};
- AddOrUpdateDiscoveredDevice(device, localIpAddress);
+ AddOrUpdateDiscoveredDevice(device, IpAddress);
}
}
@@ -428,13 +431,13 @@ namespace Rssdp.Infrastructure
};
if (NotificationTypeMatchesFilter(deadDevice))
+ {
OnDeviceUnavailable(deadDevice, false);
+ }
}
}
}
- #region Header/Message Processing Utilities
-
private string GetFirstHeaderStringValue(string headerName, HttpResponseMessage message)
{
string retVal = null;
@@ -443,7 +446,9 @@ namespace Rssdp.Infrastructure
{
message.Headers.TryGetValues(headerName, out values);
if (values != null)
+ {
retVal = values.FirstOrDefault();
+ }
}
return retVal;
@@ -457,7 +462,9 @@ namespace Rssdp.Infrastructure
{
message.Headers.TryGetValues(headerName, out values);
if (values != null)
+ {
retVal = values.FirstOrDefault();
+ }
}
return retVal;
@@ -471,7 +478,9 @@ namespace Rssdp.Infrastructure
{
request.Headers.TryGetValues(headerName, out values);
if (values != null)
+ {
value = values.FirstOrDefault();
+ }
}
Uri retVal;
@@ -487,7 +496,9 @@ namespace Rssdp.Infrastructure
{
response.Headers.TryGetValues(headerName, out values);
if (values != null)
+ {
value = values.FirstOrDefault();
+ }
}
Uri retVal;
@@ -497,21 +508,16 @@ namespace Rssdp.Infrastructure
private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue)
{
- if (headerValue == null) return TimeSpan.Zero;
+ if (headerValue == null)
+ {
+ return TimeSpan.Zero;
+ }
- return (TimeSpan)(headerValue.MaxAge ?? headerValue.SharedMaxAge ?? TimeSpan.Zero);
+ return headerValue.MaxAge ?? headerValue.SharedMaxAge ?? TimeSpan.Zero;
}
- #endregion
-
- #endregion
-
- #region Expiry and Device Removal
-
private void RemoveExpiredDevicesFromCache()
{
- if (this.IsDisposed) return;
-
DiscoveredSsdpDevice[] expiredDevices = null;
lock (_Devices)
{
@@ -519,7 +525,10 @@ namespace Rssdp.Infrastructure
foreach (var device in expiredDevices)
{
- if (this.IsDisposed) return;
+ if (this.IsDisposed)
+ {
+ return;
+ }
_Devices.Remove(device);
}
@@ -530,7 +539,10 @@ namespace Rssdp.Infrastructure
// problems.
foreach (var expiredUsn in (from expiredDevice in expiredDevices select expiredDevice.Usn).Distinct())
{
- if (this.IsDisposed) return;
+ if (this.IsDisposed)
+ {
+ return;
+ }
DeviceDied(expiredUsn, true);
}
@@ -544,7 +556,10 @@ namespace Rssdp.Infrastructure
existingDevices = FindExistingDeviceNotifications(_Devices, deviceUsn);
foreach (var existingDevice in existingDevices)
{
- if (this.IsDisposed) return true;
+ if (this.IsDisposed)
+ {
+ return true;
+ }
_Devices.Remove(existingDevice);
}
@@ -555,7 +570,9 @@ namespace Rssdp.Infrastructure
foreach (var removedDevice in existingDevices)
{
if (NotificationTypeMatchesFilter(removedDevice))
+ {
OnDeviceUnavailable(removedDevice, expired);
+ }
}
return true;
@@ -564,14 +581,16 @@ namespace Rssdp.Infrastructure
return false;
}
- #endregion
-
private TimeSpan SearchTimeToMXValue(TimeSpan searchWaitTime)
{
if (searchWaitTime.TotalSeconds < 2 || searchWaitTime == TimeSpan.Zero)
+ {
return OneSecond;
+ }
else
+ {
return searchWaitTime.Subtract(OneSecond);
+ }
}
private DiscoveredSsdpDevice FindExistingDeviceNotification(IEnumerable<DiscoveredSsdpDevice> devices, string notificationType, string usn)
@@ -583,6 +602,7 @@ namespace Rssdp.Infrastructure
return d;
}
}
+
return null;
}
@@ -601,10 +621,6 @@ namespace Rssdp.Infrastructure
return list;
}
- #endregion
-
- #region Event Handlers
-
private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
{
ProcessSearchResponseMessage(e.Message, e.LocalIpAddress);
@@ -612,10 +628,7 @@ namespace Rssdp.Infrastructure
private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
{
- ProcessNotificationMessage(e.Message, e.LocalIpAddress);
+ ProcessNotificationMessage(e.Message, e.ReceivedFrom.Address);
}
-
- #endregion
-
}
}
diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs
index ce64ba117..64d19803d 100644
--- a/RSSDP/SsdpDevicePublisher.cs
+++ b/RSSDP/SsdpDevicePublisher.cs
@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Globalization;
using System.Linq;
-using System.Net.Http;
-using System.Text;
+using System.Net;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
-using Rssdp;
+using MediaBrowser.Common.Net;
namespace Rssdp.Infrastructure
{
@@ -16,10 +15,12 @@ namespace Rssdp.Infrastructure
/// </summary>
public class SsdpDevicePublisher : DisposableManagedObjectBase, ISsdpDevicePublisher
{
+ private readonly INetworkManager _networkManager;
private ISsdpCommunicationsServer _CommsServer;
private string _OSName;
private string _OSVersion;
+ private bool _sendOnlyMatchedHost;
private bool _SupportPnpRootDevice;
@@ -37,13 +38,38 @@ namespace Rssdp.Infrastructure
/// <summary>
/// Default constructor.
/// </summary>
- public SsdpDevicePublisher(ISsdpCommunicationsServer communicationsServer, string osName, string osVersion)
+ public SsdpDevicePublisher(ISsdpCommunicationsServer communicationsServer, INetworkManager networkManager,
+ string osName, string osVersion, bool sendOnlyMatchedHost)
{
- if (communicationsServer == null) throw new ArgumentNullException(nameof(communicationsServer));
- if (osName == null) throw new ArgumentNullException(nameof(osName));
- if (osName.Length == 0) throw new ArgumentException("osName cannot be an empty string.", nameof(osName));
- if (osVersion == null) throw new ArgumentNullException(nameof(osVersion));
- if (osVersion.Length == 0) throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName));
+ if (communicationsServer == null)
+ {
+ throw new ArgumentNullException(nameof(communicationsServer));
+ }
+
+ if (networkManager == null)
+ {
+ throw new ArgumentNullException(nameof(networkManager));
+ }
+
+ if (osName == null)
+ {
+ throw new ArgumentNullException(nameof(osName));
+ }
+
+ if (osName.Length == 0)
+ {
+ throw new ArgumentException("osName cannot be an empty string.", nameof(osName));
+ }
+
+ if (osVersion == null)
+ {
+ throw new ArgumentNullException(nameof(osVersion));
+ }
+
+ if (osVersion.Length == 0)
+ {
+ throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName));
+ }
_SupportPnpRootDevice = true;
_Devices = new List<SsdpRootDevice>();
@@ -51,10 +77,12 @@ namespace Rssdp.Infrastructure
_RecentSearchRequests = new Dictionary<string, SearchRequest>(StringComparer.OrdinalIgnoreCase);
_Random = new Random();
+ _networkManager = networkManager;
_CommsServer = communicationsServer;
_CommsServer.RequestReceived += CommsServer_RequestReceived;
_OSName = osName;
_OSVersion = osVersion;
+ _sendOnlyMatchedHost = sendOnlyMatchedHost;
_CommsServer.BeginListeningForBroadcasts();
}
@@ -75,14 +103,16 @@ namespace Rssdp.Infrastructure
/// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param>
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
/// <exception cref="InvalidOperationException">Thrown if the <paramref name="device"/> contains property values that are not acceptable to the UPnP 1.0 specification.</exception>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable suppresses compiler warning, but task is not really needed.")]
public void AddDevice(SsdpRootDevice device)
{
- if (device == null) throw new ArgumentNullException(nameof(device));
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
ThrowIfDisposed();
- var minCacheTime = TimeSpan.Zero;
bool wasAdded = false;
lock (_Devices)
{
@@ -90,7 +120,6 @@ namespace Rssdp.Infrastructure
{
_Devices.Add(device);
wasAdded = true;
- minCacheTime = GetMinimumNonZeroCacheLifetime();
}
}
@@ -113,17 +142,18 @@ namespace Rssdp.Infrastructure
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
public async Task RemoveDevice(SsdpRootDevice device)
{
- if (device == null) throw new ArgumentNullException(nameof(device));
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
bool wasRemoved = false;
- var minCacheTime = TimeSpan.Zero;
lock (_Devices)
{
if (_Devices.Contains(device))
{
_Devices.Remove(device);
wasRemoved = true;
- minCacheTime = GetMinimumNonZeroCacheLifetime();
}
}
@@ -151,11 +181,12 @@ namespace Rssdp.Infrastructure
/// </summary>
/// <remarks>
/// <para>Enabling this option will cause devices to show up in Microsoft Windows Explorer's network screens (if discovery is enabled etc.). Windows Explorer appears to search only for pnp:rootdeivce and not upnp:rootdevice.</para>
- /// <para>If false, the system will only use upnp:rootdevice for notifiation broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para>
+ /// <para>If false, the system will only use upnp:rootdevice for notification broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para>
/// </remarks>
public bool SupportPnpRootDevice
{
get { return _SupportPnpRootDevice; }
+
set
{
_SupportPnpRootDevice = value;
@@ -185,78 +216,100 @@ namespace Rssdp.Infrastructure
if (commsServer != null)
{
if (!commsServer.IsShared)
+ {
commsServer.Dispose();
+ }
}
_RecentSearchRequests = null;
}
}
- private void ProcessSearchRequest(string mx, string searchTarget, IpEndPointInfo remoteEndPoint, IpAddressInfo receivedOnlocalIpAddress, CancellationToken cancellationToken)
+ private void ProcessSearchRequest(
+ string mx,
+ string searchTarget,
+ IPEndPoint remoteEndPoint,
+ IPAddress receivedOnlocalIpAddress,
+ CancellationToken cancellationToken)
{
if (String.IsNullOrEmpty(searchTarget))
{
- WriteTrace(String.Format("Invalid search request received From {0}, Target is null/empty.", remoteEndPoint.ToString()));
+ WriteTrace(String.Format(CultureInfo.InvariantCulture, "Invalid search request received From {0}, Target is null/empty.", remoteEndPoint.ToString()));
return;
}
- //WriteTrace(String.Format("Search Request Received From {0}, Target = {1}", remoteEndPoint.ToString(), searchTarget));
+ // WriteTrace(String.Format("Search Request Received From {0}, Target = {1}", remoteEndPoint.ToString(), searchTarget));
if (IsDuplicateSearchRequest(searchTarget, remoteEndPoint))
{
- //WriteTrace("Search Request is Duplicate, ignoring.");
+ // WriteTrace("Search Request is Duplicate, ignoring.");
return;
}
- //Wait on random interval up to MX, as per SSDP spec.
- //Also, as per UPnP 1.1/SSDP spec ignore missing/bank MX header. If over 120, assume random value between 0 and 120.
- //Using 16 as minimum as that's often the minimum system clock frequency anyway.
+ // Wait on random interval up to MX, as per SSDP spec.
+ // Also, as per UPnP 1.1/SSDP spec ignore missing/bank MX header. If over 120, assume random value between 0 and 120.
+ // Using 16 as minimum as that's often the minimum system clock frequency anyway.
int maxWaitInterval = 0;
if (String.IsNullOrEmpty(mx))
{
- //Windows Explorer is poorly behaved and doesn't supply an MX header value.
- //if (this.SupportPnpRootDevice)
+ // Windows Explorer is poorly behaved and doesn't supply an MX header value.
+ // if (this.SupportPnpRootDevice)
mx = "1";
- //else
- //return;
+ // else
+ // return;
}
- if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0) return;
+ if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0)
+ {
+ return;
+ }
if (maxWaitInterval > 120)
+ {
maxWaitInterval = _Random.Next(0, 120);
+ }
- //Do not block synchronously as that may tie up a threadpool thread for several seconds.
+ // Do not block synchronously as that may tie up a threadpool thread for several seconds.
Task.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
{
- //Copying devices to local array here to avoid threading issues/enumerator exceptions.
+ // Copying devices to local array here to avoid threading issues/enumerator exceptions.
IEnumerable<SsdpDevice> devices = null;
lock (_Devices)
{
if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
+ {
devices = GetAllDevicesAsFlatEnumerable().ToArray();
+ }
else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
+ {
devices = _Devices.ToArray();
+ }
else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
+ {
devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
+ }
else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
+ {
devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
+ }
}
if (devices != null)
{
var deviceList = devices.ToList();
- //WriteTrace(String.Format("Sending {0} search responses", deviceList.Count));
+ // WriteTrace(String.Format("Sending {0} search responses", deviceList.Count));
foreach (var device in deviceList)
{
- SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken);
+ var root = device.ToRootDevice();
+ var source = new IPNetAddress(root.Address, root.PrefixLength);
+ var destination = new IPNetAddress(remoteEndPoint.Address, root.PrefixLength);
+ if (!_sendOnlyMatchedHost || source.NetworkAddress.Equals(destination.NetworkAddress))
+ {
+ SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken);
+ }
}
}
- else
- {
- //WriteTrace(String.Format("Sending 0 search responses."));
- }
});
}
@@ -265,14 +318,20 @@ namespace Rssdp.Infrastructure
return _Devices.Union(_Devices.SelectManyRecursive<SsdpDevice>((d) => d.Devices));
}
- private void SendDeviceSearchResponses(SsdpDevice device, IpEndPointInfo endPoint, IpAddressInfo receivedOnlocalIpAddress, CancellationToken cancellationToken)
+ private void SendDeviceSearchResponses(
+ SsdpDevice device,
+ IPEndPoint endPoint,
+ IPAddress receivedOnlocalIpAddress,
+ CancellationToken cancellationToken)
{
bool isRootDevice = (device as SsdpRootDevice) != null;
if (isRootDevice)
{
SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
if (this.SupportPnpRootDevice)
+ {
SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
+ }
}
SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken);
@@ -282,14 +341,20 @@ namespace Rssdp.Infrastructure
private string GetUsn(string udn, string fullDeviceType)
{
- return String.Format("{0}::{1}", udn, fullDeviceType);
+ return String.Format(CultureInfo.InvariantCulture, "{0}::{1}", udn, fullDeviceType);
}
- private async void SendSearchResponse(string searchTarget, SsdpDevice device, string uniqueServiceName, IpEndPointInfo endPoint, IpAddressInfo receivedOnlocalIpAddress, CancellationToken cancellationToken)
+ private async void SendSearchResponse(
+ string searchTarget,
+ SsdpDevice device,
+ string uniqueServiceName,
+ IPEndPoint endPoint,
+ IPAddress receivedOnlocalIpAddress,
+ CancellationToken cancellationToken)
{
var rootDevice = device.ToRootDevice();
- //var additionalheaders = FormatCustomHeadersForResponse(device);
+ // var additionalheaders = FormatCustomHeadersForResponse(device);
const string header = "HTTP/1.1 200 OK";
@@ -299,7 +364,7 @@ namespace Rssdp.Infrastructure
values["DATE"] = DateTime.UtcNow.ToString("r");
values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
values["ST"] = searchTarget;
- values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
values["USN"] = uniqueServiceName;
values["LOCATION"] = rootDevice.Location.ToString();
@@ -316,13 +381,12 @@ namespace Rssdp.Infrastructure
}
catch (Exception)
{
-
}
- //WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
+ // WriteTrace(String.Format("Sent search response to " + endPoint.ToString()), device);
}
- private bool IsDuplicateSearchRequest(string searchTarget, IpEndPointInfo endPoint)
+ private bool IsDuplicateSearchRequest(string searchTarget, IPEndPoint endPoint)
{
var isDuplicateRequest = false;
@@ -333,15 +397,21 @@ namespace Rssdp.Infrastructure
{
var lastRequest = _RecentSearchRequests[newRequest.Key];
if (lastRequest.IsOld())
+ {
_RecentSearchRequests[newRequest.Key] = newRequest;
+ }
else
+ {
isDuplicateRequest = true;
+ }
}
else
{
_RecentSearchRequests.Add(newRequest.Key, newRequest);
if (_RecentSearchRequests.Count > 10)
+ {
CleanUpRecentSearchRequestsAsync();
+ }
}
}
@@ -363,9 +433,12 @@ namespace Rssdp.Infrastructure
{
try
{
- if (IsDisposed) return;
+ if (IsDisposed)
+ {
+ return;
+ }
- //WriteTrace("Begin Sending Alive Notifications For All Devices");
+ // WriteTrace("Begin Sending Alive Notifications For All Devices");
SsdpRootDevice[] devices;
lock (_Devices)
@@ -375,12 +448,15 @@ namespace Rssdp.Infrastructure
foreach (var device in devices)
{
- if (IsDisposed) return;
+ if (IsDisposed)
+ {
+ return;
+ }
SendAliveNotifications(device, true, CancellationToken.None);
}
- //WriteTrace("Completed Sending Alive Notifications For All Devices");
+ // WriteTrace("Completed Sending Alive Notifications For All Devices");
}
catch (ObjectDisposedException ex)
{
@@ -395,7 +471,9 @@ namespace Rssdp.Infrastructure
{
SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken);
if (this.SupportPnpRootDevice)
+ {
SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken);
+ }
}
SendAliveNotification(device, device.Udn, device.Udn, cancellationToken);
@@ -420,16 +498,16 @@ namespace Rssdp.Infrastructure
values["DATE"] = DateTime.UtcNow.ToString("r");
values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
values["LOCATION"] = rootDevice.Location.ToString();
- values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
values["NTS"] = "ssdp:alive";
values["NT"] = notificationType;
values["USN"] = uniqueServiceName;
var message = BuildMessage(header, values);
- _CommsServer.SendMulticastMessage(message, cancellationToken);
+ _CommsServer.SendMulticastMessage(message, _sendOnlyMatchedHost ? rootDevice.Address : null, cancellationToken);
- //WriteTrace(String.Format("Sent alive notification"), device);
+ // WriteTrace(String.Format("Sent alive notification"), device);
}
private Task SendByeByeNotifications(SsdpDevice device, bool isRoot, CancellationToken cancellationToken)
@@ -439,11 +517,13 @@ namespace Rssdp.Infrastructure
{
tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken));
if (this.SupportPnpRootDevice)
+ {
tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken));
+ }
}
tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken));
- tasks.Add(SendByeByeNotification(device, String.Format("urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType), cancellationToken));
+ tasks.Add(SendByeByeNotification(device, String.Format(CultureInfo.InvariantCulture, "urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType), cancellationToken));
foreach (var childDevice in device.Devices)
{
@@ -463,7 +543,7 @@ namespace Rssdp.Infrastructure
// If needed later for non-server devices, these headers will need to be dynamic
values["HOST"] = "239.255.255.250:1900";
values["DATE"] = DateTime.UtcNow.ToString("r");
- values["SERVER"] = string.Format("{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
values["NTS"] = "ssdp:byebye";
values["NT"] = notificationType;
values["USN"] = uniqueServiceName;
@@ -471,8 +551,8 @@ namespace Rssdp.Infrastructure
var message = BuildMessage(header, values);
var sendCount = IsDisposed ? 1 : 3;
- WriteTrace(String.Format("Sent byebye notification"), device);
- return _CommsServer.SendMulticastMessage(message, sendCount, cancellationToken);
+ WriteTrace(String.Format(CultureInfo.InvariantCulture, "Sent byebye notification"), device);
+ return _CommsServer.SendMulticastMessage(message, sendCount, _sendOnlyMatchedHost ? device.ToRootDevice().Address : null, cancellationToken);
}
private void DisposeRebroadcastTimer()
@@ -480,20 +560,27 @@ namespace Rssdp.Infrastructure
var timer = _RebroadcastAliveNotificationsTimer;
_RebroadcastAliveNotificationsTimer = null;
if (timer != null)
+ {
timer.Dispose();
+ }
}
private TimeSpan GetMinimumNonZeroCacheLifetime()
{
- var nonzeroCacheLifetimesQuery = (from device
- in _Devices
- where device.CacheLifetime != TimeSpan.Zero
- select device.CacheLifetime).ToList();
+ var nonzeroCacheLifetimesQuery = (
+ from device
+ in _Devices
+ where device.CacheLifetime != TimeSpan.Zero
+ select device.CacheLifetime).ToList();
if (nonzeroCacheLifetimesQuery.Any())
+ {
return nonzeroCacheLifetimesQuery.Min();
+ }
else
+ {
return TimeSpan.Zero;
+ }
}
private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
@@ -501,7 +588,9 @@ namespace Rssdp.Infrastructure
string retVal = null;
IEnumerable<String> values = null;
if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
+ {
retVal = values.FirstOrDefault();
+ }
return retVal;
}
@@ -514,39 +603,48 @@ namespace Rssdp.Infrastructure
{
LogFunction(text);
}
- //System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
+ // System.Diagnostics.Debug.WriteLine(text, "SSDP Publisher");
}
private void WriteTrace(string text, SsdpDevice device)
{
var rootDevice = device as SsdpRootDevice;
if (rootDevice != null)
+ {
WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
+ }
else
+ {
WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
+ }
}
private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
{
- if (this.IsDisposed) return;
+ if (this.IsDisposed)
+ {
+ return;
+ }
if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase))
{
- //According to SSDP/UPnP spec, ignore message if missing these headers.
+ // According to SSDP/UPnP spec, ignore message if missing these headers.
// Edit: But some devices do it anyway
- //if (!e.Message.Headers.Contains("MX"))
+ // if (!e.Message.Headers.Contains("MX"))
// WriteTrace("Ignoring search request - missing MX header.");
- //else if (!e.Message.Headers.Contains("MAN"))
+ // else if (!e.Message.Headers.Contains("MAN"))
// WriteTrace("Ignoring search request - missing MAN header.");
- //else
+ // else
ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None);
}
}
private class SearchRequest
{
- public IpEndPointInfo EndPoint { get; set; }
+ public IPEndPoint EndPoint { get; set; }
+
public DateTime Received { get; set; }
+
public string SearchTarget { get; set; }
public string Key
diff --git a/RSSDP/SsdpEmbeddedDevice.cs b/RSSDP/SsdpEmbeddedDevice.cs
index 6f05518a9..f1a598111 100644
--- a/RSSDP/SsdpEmbeddedDevice.cs
+++ b/RSSDP/SsdpEmbeddedDevice.cs
@@ -1,7 +1,3 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
namespace Rssdp
{
/// <summary>
@@ -9,14 +5,8 @@ namespace Rssdp
/// </summary>
public class SsdpEmbeddedDevice : SsdpDevice
{
-
- #region Fields
private SsdpRootDevice _RootDevice;
- #endregion
-
- #region Constructors
-
/// <summary>
/// Default constructor.
/// </summary>
@@ -24,10 +14,6 @@ namespace Rssdp
{
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Returns the <see cref="SsdpRootDevice"/> that is this device's first ancestor. If this device is itself an <see cref="SsdpRootDevice"/>, then returns a reference to itself.
/// </summary>
@@ -37,6 +23,7 @@ namespace Rssdp
{
return _RootDevice;
}
+
internal set
{
_RootDevice = value;
@@ -49,7 +36,5 @@ namespace Rssdp
}
}
}
-
- #endregion
}
}
diff --git a/RSSDP/SsdpRootDevice.cs b/RSSDP/SsdpRootDevice.cs
index a2b0f60f5..5ecb1f86f 100644
--- a/RSSDP/SsdpRootDevice.cs
+++ b/RSSDP/SsdpRootDevice.cs
@@ -1,8 +1,5 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Xml;
-using Rssdp.Infrastructure;
+using System.Net;
namespace Rssdp
{
@@ -15,14 +12,8 @@ namespace Rssdp
/// </remarks>
public class SsdpRootDevice : SsdpDevice
{
- #region Fields
-
private Uri _UrlBase;
- #endregion
-
- #region Constructors
-
/// <summary>
/// Default constructor.
/// </summary>
@@ -30,15 +21,11 @@ namespace Rssdp
{
}
- #endregion
-
- #region Public Properties
-
/// <summary>
/// Specifies how long clients can cache this device's details for. Optional but defaults to <see cref="TimeSpan.Zero"/> which means no-caching. Recommended value is half an hour.
/// </summary>
/// <remarks>
- /// <para>Specifiy <see cref="TimeSpan.Zero"/> to indicate no caching allowed.</para>
+ /// <para>Specify <see cref="TimeSpan.Zero"/> to indicate no caching allowed.</para>
/// <para>Also used to specify how often to rebroadcast alive notifications.</para>
/// <para>The UPnP/SSDP specifications indicate this should not be less than 1800 seconds (half an hour), but this is not enforced by this library.</para>
/// </remarks>
@@ -52,9 +39,18 @@ namespace Rssdp
/// </summary>
public Uri Location { get; set; }
+ /// <summary>
+ /// Gets or sets the Address used to check if the received message from same interface with this device/tree. Required.
+ /// </summary>
+ public IPAddress Address { get; set; }
/// <summary>
- /// The base URL to use for all relative url's provided in other propertise (and those of child devices). Optional.
+ /// Gets or sets the prefix length used to check if the received message from same interface with this device/tree. Required.
+ /// </summary>
+ public byte PrefixLength { get; set; }
+
+ /// <summary>
+ /// The base URL to use for all relative url's provided in other properties (and those of child devices). Optional.
/// </summary>
/// <remarks>
/// <para>Defines the base URL. Used to construct fully-qualified URLs. All relative URLs that appear elsewhere in the description are combined with this base URL. If URLBase is empty or not given, the base URL is the URL from which the device description was retrieved (which is the preferred implementation; use of URLBase is no longer recommended). Specified by UPnP vendor. Single URL.</para>
@@ -71,7 +67,5 @@ namespace Rssdp
_UrlBase = value;
}
}
-
- #endregion
}
}
diff --git a/SharedVersion.cs b/SharedVersion.cs
index 41eda393a..5e2f151a2 100644
--- a/SharedVersion.cs
+++ b/SharedVersion.cs
@@ -1,4 +1,4 @@
using System.Reflection;
-[assembly: AssemblyVersion("10.2.1")]
-[assembly: AssemblyFileVersion("10.2.1")]
+[assembly: AssemblyVersion("10.8.0")]
+[assembly: AssemblyFileVersion("10.8.0")]
diff --git a/SocketHttpListener/ByteOrder.cs b/SocketHttpListener/ByteOrder.cs
deleted file mode 100644
index c04150c74..000000000
--- a/SocketHttpListener/ByteOrder.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the values that indicate whether the byte order is a Little-endian or Big-endian.
- /// </summary>
- public enum ByteOrder : byte
- {
- /// <summary>
- /// Indicates a Little-endian.
- /// </summary>
- Little,
- /// <summary>
- /// Indicates a Big-endian.
- /// </summary>
- Big
- }
-}
diff --git a/SocketHttpListener/CloseEventArgs.cs b/SocketHttpListener/CloseEventArgs.cs
deleted file mode 100644
index c6460fd23..000000000
--- a/SocketHttpListener/CloseEventArgs.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-using System;
-using System.Text;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the event data associated with a <see cref="WebSocket.OnClose"/> event.
- /// </summary>
- /// <remarks>
- /// A <see cref="WebSocket.OnClose"/> event occurs when the WebSocket connection has been closed.
- /// If you would like to get the reason for the close, you should access the <see cref="Code"/> or
- /// <see cref="Reason"/> property.
- /// </remarks>
- public class CloseEventArgs : EventArgs
- {
- #region Private Fields
-
- private bool _clean;
- private ushort _code;
- private string _reason;
-
- #endregion
-
- #region Internal Constructors
-
- internal CloseEventArgs(PayloadData payload)
- {
- var data = payload.ApplicationData;
- var len = data.Length;
- _code = len > 1
- ? data.SubArray(0, 2).ToUInt16(ByteOrder.Big)
- : (ushort)CloseStatusCode.NoStatusCode;
-
- _reason = len > 2
- ? GetUtf8String(data.SubArray(2, len - 2))
- : string.Empty;
- }
-
- private static string GetUtf8String(byte[] bytes)
- {
- return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- }
-
- #endregion
-
- #region Public Properties
-
- /// <summary>
- /// Gets the status code for the close.
- /// </summary>
- /// <value>
- /// A <see cref="ushort"/> that represents the status code for the close if any.
- /// </value>
- public ushort Code => _code;
-
- /// <summary>
- /// Gets the reason for the close.
- /// </summary>
- /// <value>
- /// A <see cref="string"/> that represents the reason for the close if any.
- /// </value>
- public string Reason => _reason;
-
- /// <summary>
- /// Gets a value indicating whether the WebSocket connection has been closed cleanly.
- /// </summary>
- /// <value>
- /// <c>true</c> if the WebSocket connection has been closed cleanly; otherwise, <c>false</c>.
- /// </value>
- public bool WasClean
- {
- get => _clean;
-
- internal set => _clean = value;
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/CloseStatusCode.cs b/SocketHttpListener/CloseStatusCode.cs
deleted file mode 100644
index 428595bb0..000000000
--- a/SocketHttpListener/CloseStatusCode.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the values of the status code for the WebSocket connection close.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The values of the status code are defined in
- /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">Section 7.4</see>
- /// of RFC 6455.
- /// </para>
- /// <para>
- /// "Reserved value" must not be set as a status code in a close control frame
- /// by an endpoint. It's designated for use in applications expecting a status
- /// code to indicate that the connection was closed due to the system grounds.
- /// </para>
- /// </remarks>
- public enum CloseStatusCode : ushort
- {
- /// <summary>
- /// Equivalent to close status 1000.
- /// Indicates a normal close.
- /// </summary>
- Normal = 1000,
- /// <summary>
- /// Equivalent to close status 1001.
- /// Indicates that an endpoint is going away.
- /// </summary>
- Away = 1001,
- /// <summary>
- /// Equivalent to close status 1002.
- /// Indicates that an endpoint is terminating the connection due to a protocol error.
- /// </summary>
- ProtocolError = 1002,
- /// <summary>
- /// Equivalent to close status 1003.
- /// Indicates that an endpoint is terminating the connection because it has received
- /// an unacceptable type message.
- /// </summary>
- IncorrectData = 1003,
- /// <summary>
- /// Equivalent to close status 1004.
- /// Still undefined. Reserved value.
- /// </summary>
- Undefined = 1004,
- /// <summary>
- /// Equivalent to close status 1005.
- /// Indicates that no status code was actually present. Reserved value.
- /// </summary>
- NoStatusCode = 1005,
- /// <summary>
- /// Equivalent to close status 1006.
- /// Indicates that the connection was closed abnormally. Reserved value.
- /// </summary>
- Abnormal = 1006,
- /// <summary>
- /// Equivalent to close status 1007.
- /// Indicates that an endpoint is terminating the connection because it has received
- /// a message that contains a data that isn't consistent with the type of the message.
- /// </summary>
- InconsistentData = 1007,
- /// <summary>
- /// Equivalent to close status 1008.
- /// Indicates that an endpoint is terminating the connection because it has received
- /// a message that violates its policy.
- /// </summary>
- PolicyViolation = 1008,
- /// <summary>
- /// Equivalent to close status 1009.
- /// Indicates that an endpoint is terminating the connection because it has received
- /// a message that is too big to process.
- /// </summary>
- TooBig = 1009,
- /// <summary>
- /// Equivalent to close status 1010.
- /// Indicates that the client is terminating the connection because it has expected
- /// the server to negotiate one or more extension, but the server didn't return them
- /// in the handshake response.
- /// </summary>
- IgnoreExtension = 1010,
- /// <summary>
- /// Equivalent to close status 1011.
- /// Indicates that the server is terminating the connection because it has encountered
- /// an unexpected condition that prevented it from fulfilling the request.
- /// </summary>
- ServerError = 1011,
- /// <summary>
- /// Equivalent to close status 1015.
- /// Indicates that the connection was closed due to a failure to perform a TLS handshake.
- /// Reserved value.
- /// </summary>
- TlsHandshakeFailure = 1015
- }
-}
diff --git a/SocketHttpListener/CompressionMethod.cs b/SocketHttpListener/CompressionMethod.cs
deleted file mode 100644
index d6bcd63d8..000000000
--- a/SocketHttpListener/CompressionMethod.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the values of the compression method used to compress the message on the WebSocket
- /// connection.
- /// </summary>
- /// <remarks>
- /// The values of the compression method are defined in
- /// <see href="http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-09">Compression
- /// Extensions for WebSocket</see>.
- /// </remarks>
- public enum CompressionMethod : byte
- {
- /// <summary>
- /// Indicates non compression.
- /// </summary>
- None,
- /// <summary>
- /// Indicates using DEFLATE.
- /// </summary>
- Deflate
- }
-}
diff --git a/SocketHttpListener/ErrorEventArgs.cs b/SocketHttpListener/ErrorEventArgs.cs
deleted file mode 100644
index 9502d2a15..000000000
--- a/SocketHttpListener/ErrorEventArgs.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-using System;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the event data associated with a <see cref="WebSocket.OnError"/> event.
- /// </summary>
- /// <remarks>
- /// A <see cref="WebSocket.OnError"/> event occurs when the <see cref="WebSocket"/> gets an error.
- /// If you would like to get the error message, you should access the <see cref="Message"/>
- /// property.
- /// </remarks>
- public class ErrorEventArgs : EventArgs
- {
- #region Private Fields
-
- private string _message;
-
- #endregion
-
- #region Internal Constructors
-
- internal ErrorEventArgs(string message)
- {
- _message = message;
- }
-
- #endregion
-
- #region Public Properties
-
- /// <summary>
- /// Gets the error message.
- /// </summary>
- /// <value>
- /// A <see cref="string"/> that represents the error message.
- /// </value>
- public string Message => _message;
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/Ext.cs b/SocketHttpListener/Ext.cs
deleted file mode 100644
index 2b3c67071..000000000
--- a/SocketHttpListener/Ext.cs
+++ /dev/null
@@ -1,947 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.IO.Compression;
-using System.Net;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Services;
-using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
-using WebSocketState = System.Net.WebSockets.WebSocketState;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// Provides a set of static methods for the websocket-sharp.
- /// </summary>
- public static class Ext
- {
- #region Private Const Fields
-
- private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
-
- #endregion
-
- #region Private Methods
-
- private static MemoryStream compress(this Stream stream)
- {
- var output = new MemoryStream();
- if (stream.Length == 0)
- return output;
-
- stream.Position = 0;
- using (var ds = new DeflateStream(output, CompressionMode.Compress, true))
- {
- stream.CopyTo(ds);
- //ds.Close(); // "BFINAL" set to 1.
- output.Position = 0;
-
- return output;
- }
- }
-
- private static byte[] decompress(this byte[] value)
- {
- if (value.Length == 0)
- return value;
-
- using (var input = new MemoryStream(value))
- {
- return input.decompressToArray();
- }
- }
-
- private static MemoryStream decompress(this Stream stream)
- {
- var output = new MemoryStream();
- if (stream.Length == 0)
- return output;
-
- stream.Position = 0;
- using (var ds = new DeflateStream(stream, CompressionMode.Decompress, true))
- {
- ds.CopyTo(output, true);
- return output;
- }
- }
-
- private static byte[] decompressToArray(this Stream stream)
- {
- using (var decomp = stream.decompress())
- {
- return decomp.ToArray();
- }
- }
-
- private static async Task<byte[]> ReadBytesAsync(this Stream stream, byte[] buffer, int offset, int length)
- {
- var len = await stream.ReadAsync(buffer, offset, length).ConfigureAwait(false);
- if (len < 1)
- return buffer.SubArray(0, offset);
-
- var tmp = 0;
- while (len < length)
- {
- tmp = await stream.ReadAsync(buffer, offset + len, length - len).ConfigureAwait(false);
- if (tmp < 1)
- {
- break;
- }
-
- len += tmp;
- }
-
- return len < length
- ? buffer.SubArray(0, offset + len)
- : buffer;
- }
-
- private static async Task<bool> ReadBytesAsync(this Stream stream, byte[] buffer, int offset, int length, Stream dest)
- {
- var bytes = await stream.ReadBytesAsync(buffer, offset, length).ConfigureAwait(false);
- var len = bytes.Length;
- dest.Write(bytes, 0, len);
-
- return len == offset + length;
- }
-
- #endregion
-
- #region Internal Methods
-
- internal static async Task<byte[]> AppendAsync(this ushort code, string reason)
- {
- using (var buffer = new MemoryStream())
- {
- var tmp = code.ToByteArrayInternally(ByteOrder.Big);
- await buffer.WriteAsync(tmp, 0, 2).ConfigureAwait(false);
- if (reason != null && reason.Length > 0)
- {
- tmp = Encoding.UTF8.GetBytes(reason);
- await buffer.WriteAsync(tmp, 0, tmp.Length).ConfigureAwait(false);
- }
-
- return buffer.ToArray();
- }
- }
-
- internal static string CheckIfClosable(this WebSocketState state)
- {
- return state == WebSocketState.CloseSent
- ? "While closing the WebSocket connection."
- : state == WebSocketState.Closed
- ? "The WebSocket connection has already been closed."
- : null;
- }
-
- internal static string CheckIfOpen(this WebSocketState state)
- {
- return state == WebSocketState.Connecting
- ? "A WebSocket connection isn't established."
- : state == WebSocketState.CloseSent
- ? "While closing the WebSocket connection."
- : state == WebSocketState.Closed
- ? "The WebSocket connection has already been closed."
- : null;
- }
-
- internal static string CheckIfValidControlData(this byte[] data, string paramName)
- {
- return data.Length > 125
- ? string.Format("'{0}' length must be less.", paramName)
- : null;
- }
-
- internal static Stream Compress(this Stream stream, CompressionMethod method)
- {
- return method == CompressionMethod.Deflate
- ? stream.compress()
- : stream;
- }
-
- internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition)
- {
- foreach (T elm in source)
- if (condition(elm))
- return true;
-
- return false;
- }
-
- internal static void CopyTo(this Stream src, Stream dest, bool setDefaultPosition)
- {
- var readLen = 0;
- var bufferLen = 256;
- var buffer = new byte[bufferLen];
- while ((readLen = src.Read(buffer, 0, bufferLen)) > 0)
- {
- dest.Write(buffer, 0, readLen);
- }
-
- if (setDefaultPosition)
- dest.Position = 0;
- }
-
- internal static byte[] Decompress(this byte[] value, CompressionMethod method)
- {
- return method == CompressionMethod.Deflate
- ? value.decompress()
- : value;
- }
-
- internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method)
- {
- return method == CompressionMethod.Deflate
- ? stream.decompressToArray()
- : stream.ToByteArray();
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
- /// and invokes the specified Action&lt;int&gt; delegate at the same time.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
- /// otherwise, <c>false</c>.
- /// </returns>
- /// <param name="value">
- /// An <see cref="int"/> to compare.
- /// </param>
- /// <param name="c">
- /// A <see cref="char"/> to compare.
- /// </param>
- /// <param name="action">
- /// An Action&lt;int&gt; delegate that references the method(s) called at
- /// the same time as comparing. An <see cref="int"/> parameter to pass to
- /// the method(s) is <paramref name="value"/>.
- /// </param>
- /// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="value"/> isn't between 0 and 255.
- /// </exception>
- internal static bool EqualsWith(this int value, char c, Action<int> action)
- {
- if (value < 0 || value > 255)
- throw new ArgumentOutOfRangeException(nameof(value));
-
- action(value);
- return value == c - 0;
- }
-
- internal static string GetMessage(this CloseStatusCode code)
- {
- return code == CloseStatusCode.ProtocolError
- ? "A WebSocket protocol error has occurred."
- : code == CloseStatusCode.IncorrectData
- ? "An incorrect data has been received."
- : code == CloseStatusCode.Abnormal
- ? "An exception has occurred."
- : code == CloseStatusCode.InconsistentData
- ? "An inconsistent data has been received."
- : code == CloseStatusCode.PolicyViolation
- ? "A policy violation has occurred."
- : code == CloseStatusCode.TooBig
- ? "A too big data has been received."
- : code == CloseStatusCode.IgnoreExtension
- ? "WebSocket client did not receive expected extension(s)."
- : code == CloseStatusCode.ServerError
- ? "WebSocket server got an internal error."
- : code == CloseStatusCode.TlsHandshakeFailure
- ? "An error has occurred while handshaking."
- : string.Empty;
- }
-
- internal static string GetNameInternal(this string nameAndValue, string separator)
- {
- var i = nameAndValue.IndexOf(separator);
- return i > 0
- ? nameAndValue.Substring(0, i).Trim()
- : null;
- }
-
- internal static string GetValueInternal(this string nameAndValue, string separator)
- {
- var i = nameAndValue.IndexOf(separator);
- return i >= 0 && i < nameAndValue.Length - 1
- ? nameAndValue.Substring(i + 1).Trim()
- : null;
- }
-
- internal static bool IsCompressionExtension(this string value, CompressionMethod method)
- {
- return value.StartsWith(method.ToExtensionString());
- }
-
- internal static bool IsPortNumber(this int value)
- {
- return value > 0 && value < 65536;
- }
-
- internal static bool IsReserved(this ushort code)
- {
- return code == (ushort)CloseStatusCode.Undefined ||
- code == (ushort)CloseStatusCode.NoStatusCode ||
- code == (ushort)CloseStatusCode.Abnormal ||
- code == (ushort)CloseStatusCode.TlsHandshakeFailure;
- }
-
- internal static bool IsReserved(this CloseStatusCode code)
- {
- return code == CloseStatusCode.Undefined ||
- code == CloseStatusCode.NoStatusCode ||
- code == CloseStatusCode.Abnormal ||
- code == CloseStatusCode.TlsHandshakeFailure;
- }
-
- internal static bool IsText(this string value)
- {
- var len = value.Length;
- for (var i = 0; i < len; i++)
- {
- char c = value[i];
- if (c < 0x20 && !"\r\n\t".Contains(c))
- return false;
-
- if (c == 0x7f)
- return false;
-
- if (c == '\n' && ++i < len)
- {
- c = value[i];
- if (!" \t".Contains(c))
- return false;
- }
- }
-
- return true;
- }
-
- internal static bool IsToken(this string value)
- {
- foreach (char c in value)
- if (c < 0x20 || c >= 0x7f || _tspecials.Contains(c))
- return false;
-
- return true;
- }
-
- internal static string Quote(this string value)
- {
- return value.IsToken()
- ? value
- : string.Format("\"{0}\"", value.Replace("\"", "\\\""));
- }
-
- internal static Task<byte[]> ReadBytesAsync(this Stream stream, int length)
- => stream.ReadBytesAsync(new byte[length], 0, length);
-
- internal static async Task<byte[]> ReadBytesAsync(this Stream stream, long length, int bufferLength)
- {
- using (var result = new MemoryStream())
- {
- var count = length / bufferLength;
- var rem = (int)(length % bufferLength);
-
- var buffer = new byte[bufferLength];
- var end = false;
- for (long i = 0; i < count; i++)
- {
- if (!await stream.ReadBytesAsync(buffer, 0, bufferLength, result).ConfigureAwait(false))
- {
- end = true;
- break;
- }
- }
-
- if (!end && rem > 0)
- {
- await stream.ReadBytesAsync(new byte[rem], 0, rem, result).ConfigureAwait(false);
- }
-
- return result.ToArray();
- }
- }
-
- internal static string RemovePrefix(this string value, params string[] prefixes)
- {
- var i = 0;
- foreach (var prefix in prefixes)
- {
- if (value.StartsWith(prefix))
- {
- i = prefix.Length;
- break;
- }
- }
-
- return i > 0
- ? value.Substring(i)
- : value;
- }
-
- internal static T[] Reverse<T>(this T[] array)
- {
- var len = array.Length;
- T[] reverse = new T[len];
-
- var end = len - 1;
- for (var i = 0; i <= end; i++)
- reverse[i] = array[end - i];
-
- return reverse;
- }
-
- internal static IEnumerable<string> SplitHeaderValue(
- this string value, params char[] separator)
- {
- var len = value.Length;
- var separators = new string(separator);
-
- var buffer = new StringBuilder(32);
- var quoted = false;
- var escaped = false;
-
- char c;
- for (var i = 0; i < len; i++)
- {
- c = value[i];
- if (c == '"')
- {
- if (escaped)
- escaped = !escaped;
- else
- quoted = !quoted;
- }
- else if (c == '\\')
- {
- if (i < len - 1 && value[i + 1] == '"')
- escaped = true;
- }
- else if (separators.Contains(c))
- {
- if (!quoted)
- {
- yield return buffer.ToString();
- buffer.Length = 0;
-
- continue;
- }
- }
- else
- {
- }
-
- buffer.Append(c);
- }
-
- if (buffer.Length > 0)
- yield return buffer.ToString();
- }
-
- internal static byte[] ToByteArray(this Stream stream)
- {
- using (var output = new MemoryStream())
- {
- stream.Position = 0;
- stream.CopyTo(output);
-
- return output.ToArray();
- }
- }
-
- internal static byte[] ToByteArrayInternally(this ushort value, ByteOrder order)
- {
- var bytes = BitConverter.GetBytes(value);
- if (!order.IsHostOrder())
- Array.Reverse(bytes);
-
- return bytes;
- }
-
- internal static byte[] ToByteArrayInternally(this ulong value, ByteOrder order)
- {
- var bytes = BitConverter.GetBytes(value);
- if (!order.IsHostOrder())
- Array.Reverse(bytes);
-
- return bytes;
- }
-
- internal static string ToExtensionString(
- this CompressionMethod method, params string[] parameters)
- {
- if (method == CompressionMethod.None)
- return string.Empty;
-
- var m = string.Format("permessage-{0}", method.ToString().ToLowerInvariant());
- if (parameters == null || parameters.Length == 0)
- return m;
-
- return string.Format("{0}; {1}", m, parameters.ToString("; "));
- }
-
- internal static ushort ToUInt16(this byte[] src, ByteOrder srcOrder)
- {
- src.ToHostOrder(srcOrder);
- return BitConverter.ToUInt16(src, 0);
- }
-
- internal static ulong ToUInt64(this byte[] src, ByteOrder srcOrder)
- {
- src.ToHostOrder(srcOrder);
- return BitConverter.ToUInt64(src, 0);
- }
-
- internal static string TrimEndSlash(this string value)
- {
- value = value.TrimEnd('/');
- return value.Length > 0
- ? value
- : "/";
- }
-
- internal static string Unquote(this string value)
- {
- var start = value.IndexOf('\"');
- var end = value.LastIndexOf('\"');
- if (start < end)
- value = value.Substring(start + 1, end - start - 1).Replace("\\\"", "\"");
-
- return value.Trim();
- }
-
- internal static void WriteBytes(this Stream stream, byte[] value)
- {
- using (var src = new MemoryStream(value))
- {
- src.CopyTo(stream);
- }
- }
-
- #endregion
-
- #region Public Methods
-
- /// <summary>
- /// Determines whether the specified <see cref="string"/> contains any of characters
- /// in the specified array of <see cref="char"/>.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
- /// otherwise, <c>false</c>.
- /// </returns>
- /// <param name="value">
- /// A <see cref="string"/> to test.
- /// </param>
- /// <param name="chars">
- /// An array of <see cref="char"/> that contains characters to find.
- /// </param>
- public static bool Contains(this string value, params char[] chars)
- {
- return chars == null || chars.Length == 0
- ? true
- : value == null || value.Length == 0
- ? false
- : value.IndexOfAny(chars) != -1;
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
- /// with the specified <paramref name="name"/>.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="collection"/> contains the entry
- /// with <paramref name="name"/>; otherwise, <c>false</c>.
- /// </returns>
- /// <param name="collection">
- /// A <see cref="QueryParamCollection"/> to test.
- /// </param>
- /// <param name="name">
- /// A <see cref="string"/> that represents the key of the entry to find.
- /// </param>
- public static bool Contains(this QueryParamCollection collection, string name)
- {
- return collection == null || collection.Count == 0
- ? false
- : collection[name] != null;
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
- /// with the specified both <paramref name="name"/> and <paramref name="value"/>.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="collection"/> contains the entry
- /// with both <paramref name="name"/> and <paramref name="value"/>;
- /// otherwise, <c>false</c>.
- /// </returns>
- /// <param name="collection">
- /// A <see cref="QueryParamCollection"/> to test.
- /// </param>
- /// <param name="name">
- /// A <see cref="string"/> that represents the key of the entry to find.
- /// </param>
- /// <param name="value">
- /// A <see cref="string"/> that represents the value of the entry to find.
- /// </param>
- public static bool Contains(this QueryParamCollection collection, string name, string value)
- {
- if (collection == null || collection.Count == 0)
- return false;
-
- var values = collection[name];
- if (values == null)
- return false;
-
- foreach (var v in values.Split(','))
- if (v.Trim().Equals(value, StringComparison.OrdinalIgnoreCase))
- return true;
-
- return false;
- }
-
- /// <summary>
- /// Emits the specified <c>EventHandler&lt;TEventArgs&gt;</c> delegate
- /// if it isn't <see langword="null"/>.
- /// </summary>
- /// <param name="eventHandler">
- /// An <c>EventHandler&lt;TEventArgs&gt;</c> to emit.
- /// </param>
- /// <param name="sender">
- /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
- /// </param>
- /// <param name="e">
- /// A <c>TEventArgs</c> that represents the event data.
- /// </param>
- /// <typeparam name="TEventArgs">
- /// The type of the event data generated by the event.
- /// </typeparam>
- public static void Emit<TEventArgs>(
- this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e)
- where TEventArgs : EventArgs
- {
- if (eventHandler != null)
- eventHandler(sender, e);
- }
-
- /// <summary>
- /// Gets the description of the specified HTTP status <paramref name="code"/>.
- /// </summary>
- /// <returns>
- /// A <see cref="string"/> that represents the description of the HTTP status code.
- /// </returns>
- /// <param name="code">
- /// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status codes.
- /// </param>
- public static string GetDescription(this HttpStatusCode code)
- {
- return ((int)code).GetStatusDescription();
- }
-
- /// <summary>
- /// Gets the description of the specified HTTP status <paramref name="code"/>.
- /// </summary>
- /// <returns>
- /// A <see cref="string"/> that represents the description of the HTTP status code.
- /// </returns>
- /// <param name="code">
- /// An <see cref="int"/> that represents the HTTP status code.
- /// </param>
- public static string GetStatusDescription(this int code)
- {
- switch (code)
- {
- case 100: return "Continue";
- case 101: return "Switching Protocols";
- case 102: return "Processing";
- case 200: return "OK";
- case 201: return "Created";
- case 202: return "Accepted";
- case 203: return "Non-Authoritative Information";
- case 204: return "No Content";
- case 205: return "Reset Content";
- case 206: return "Partial Content";
- case 207: return "Multi-Status";
- case 300: return "Multiple Choices";
- case 301: return "Moved Permanently";
- case 302: return "Found";
- case 303: return "See Other";
- case 304: return "Not Modified";
- case 305: return "Use Proxy";
- case 307: return "Temporary Redirect";
- case 400: return "Bad Request";
- case 401: return "Unauthorized";
- case 402: return "Payment Required";
- case 403: return "Forbidden";
- case 404: return "Not Found";
- case 405: return "Method Not Allowed";
- case 406: return "Not Acceptable";
- case 407: return "Proxy Authentication Required";
- case 408: return "Request Timeout";
- case 409: return "Conflict";
- case 410: return "Gone";
- case 411: return "Length Required";
- case 412: return "Precondition Failed";
- case 413: return "Request Entity Too Large";
- case 414: return "Request-Uri Too Long";
- case 415: return "Unsupported Media Type";
- case 416: return "Requested Range Not Satisfiable";
- case 417: return "Expectation Failed";
- case 422: return "Unprocessable Entity";
- case 423: return "Locked";
- case 424: return "Failed Dependency";
- case 500: return "Internal Server Error";
- case 501: return "Not Implemented";
- case 502: return "Bad Gateway";
- case 503: return "Service Unavailable";
- case 504: return "Gateway Timeout";
- case 505: return "Http Version Not Supported";
- case 507: return "Insufficient Storage";
- }
-
- return string.Empty;
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="ByteOrder"/> is host
- /// (this computer architecture) byte order.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="order"/> is host byte order;
- /// otherwise, <c>false</c>.
- /// </returns>
- /// <param name="order">
- /// One of the <see cref="ByteOrder"/> enum values, to test.
- /// </param>
- public static bool IsHostOrder(this ByteOrder order)
- {
- // true : !(true ^ true) or !(false ^ false)
- // false: !(true ^ false) or !(false ^ true)
- return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="string"/> is a predefined scheme.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="value"/> is a predefined scheme; otherwise, <c>false</c>.
- /// </returns>
- /// <param name="value">
- /// A <see cref="string"/> to test.
- /// </param>
- public static bool IsPredefinedScheme(this string value)
- {
- if (value == null || value.Length < 2)
- return false;
-
- var c = value[0];
- if (c == 'h')
- return value == "http" || value == "https";
-
- if (c == 'w')
- return value == "ws" || value == "wss";
-
- if (c == 'f')
- return value == "file" || value == "ftp";
-
- if (c == 'n')
- {
- c = value[1];
- return c == 'e'
- ? value == "news" || value == "net.pipe" || value == "net.tcp"
- : value == "nntp";
- }
-
- return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
- }
-
- /// <summary>
- /// Determines whether the specified <see cref="string"/> is a URI string.
- /// </summary>
- /// <returns>
- /// <c>true</c> if <paramref name="value"/> may be a URI string; otherwise, <c>false</c>.
- /// </returns>
- /// <param name="value">
- /// A <see cref="string"/> to test.
- /// </param>
- public static bool MaybeUri(this string value)
- {
- if (value == null || value.Length == 0)
- return false;
-
- var i = value.IndexOf(':');
- if (i == -1)
- return false;
-
- if (i >= 10)
- return false;
-
- return value.Substring(0, i).IsPredefinedScheme();
- }
-
- /// <summary>
- /// Retrieves a sub-array from the specified <paramref name="array"/>.
- /// A sub-array starts at the specified element position.
- /// </summary>
- /// <returns>
- /// An array of T that receives a sub-array, or an empty array of T if any problems
- /// with the parameters.
- /// </returns>
- /// <param name="array">
- /// An array of T that contains the data to retrieve a sub-array.
- /// </param>
- /// <param name="startIndex">
- /// An <see cref="int"/> that contains the zero-based starting position of a sub-array
- /// in <paramref name="array"/>.
- /// </param>
- /// <param name="length">
- /// An <see cref="int"/> that contains the number of elements to retrieve a sub-array.
- /// </param>
- /// <typeparam name="T">
- /// The type of elements in the <paramref name="array"/>.
- /// </typeparam>
- public static T[] SubArray<T>(this T[] array, int startIndex, int length)
- {
- if (array == null || array.Length == 0)
- return new T[0];
-
- if (startIndex < 0 || length <= 0)
- return new T[0];
-
- if (startIndex + length > array.Length)
- return new T[0];
-
- if (startIndex == 0 && array.Length == length)
- return array;
-
- T[] subArray = new T[length];
- Array.Copy(array, startIndex, subArray, 0, length);
-
- return subArray;
- }
-
- /// <summary>
- /// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
- /// </summary>
- /// <returns>
- /// An array of <see cref="byte"/> converted from <paramref name="src"/>.
- /// </returns>
- /// <param name="src">
- /// An array of <see cref="byte"/> to convert.
- /// </param>
- /// <param name="srcOrder">
- /// One of the <see cref="ByteOrder"/> enum values, indicates the byte order of
- /// <paramref name="src"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="src"/> is <see langword="null"/>.
- /// </exception>
- public static void ToHostOrder(this byte[] src, ByteOrder srcOrder)
- {
- if (src == null)
- {
- throw new ArgumentNullException(nameof(src));
- }
-
- if (src.Length > 1 && !srcOrder.IsHostOrder())
- {
- Array.Reverse(src);
- }
- }
-
- /// <summary>
- /// Converts the specified <paramref name="array"/> to a <see cref="string"/> that
- /// concatenates the each element of <paramref name="array"/> across the specified
- /// <paramref name="separator"/>.
- /// </summary>
- /// <returns>
- /// A <see cref="string"/> converted from <paramref name="array"/>,
- /// or <see cref="String.Empty"/> if <paramref name="array"/> is empty.
- /// </returns>
- /// <param name="array">
- /// An array of T to convert.
- /// </param>
- /// <param name="separator">
- /// A <see cref="string"/> that represents the separator string.
- /// </param>
- /// <typeparam name="T">
- /// The type of elements in <paramref name="array"/>.
- /// </typeparam>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="array"/> is <see langword="null"/>.
- /// </exception>
- public static string ToString<T>(this T[] array, string separator)
- {
- if (array == null)
- throw new ArgumentNullException(nameof(array));
-
- var len = array.Length;
- if (len == 0)
- return string.Empty;
-
- if (separator == null)
- separator = string.Empty;
-
- var buff = new StringBuilder(64);
- (len - 1).Times(i => buff.AppendFormat("{0}{1}", array[i].ToString(), separator));
-
- buff.Append(array[len - 1].ToString());
- return buff.ToString();
- }
-
- /// <summary>
- /// Executes the specified <c>Action&lt;int&gt;</c> delegate <paramref name="n"/> times.
- /// </summary>
- /// <param name="n">
- /// An <see cref="int"/> is the number of times to execute.
- /// </param>
- /// <param name="action">
- /// An <c>Action&lt;int&gt;</c> delegate that references the method(s) to execute.
- /// An <see cref="int"/> parameter to pass to the method(s) is the zero-based count of
- /// iteration.
- /// </param>
- public static void Times(this int n, Action<int> action)
- {
- if (n > 0 && action != null)
- for (int i = 0; i < n; i++)
- action(i);
- }
-
- /// <summary>
- /// Converts the specified <see cref="string"/> to a <see cref="Uri"/>.
- /// </summary>
- /// <returns>
- /// A <see cref="Uri"/> converted from <paramref name="uriString"/>, or <see langword="null"/>
- /// if <paramref name="uriString"/> isn't successfully converted.
- /// </returns>
- /// <param name="uriString">
- /// A <see cref="string"/> to convert.
- /// </param>
- public static Uri ToUri(this string uriString)
- {
- return Uri.TryCreate(
- uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out var res)
- ? res
- : null;
- }
-
- /// <summary>
- /// URL-decodes the specified <see cref="string"/>.
- /// </summary>
- /// <returns>
- /// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
- /// if it's <see langword="null"/> or empty.
- /// </returns>
- /// <param name="value">
- /// A <see cref="string"/> to decode.
- /// </param>
- public static string UrlDecode(this string value)
- {
- return value == null || value.Length == 0
- ? value
- : WebUtility.UrlDecode(value);
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/Fin.cs b/SocketHttpListener/Fin.cs
deleted file mode 100644
index c8ffbf2b2..000000000
--- a/SocketHttpListener/Fin.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace SocketHttpListener
-{
- internal enum Fin : byte
- {
- More = 0x0,
- Final = 0x1
- }
-}
diff --git a/SocketHttpListener/HttpBase.cs b/SocketHttpListener/HttpBase.cs
deleted file mode 100644
index c386b9374..000000000
--- a/SocketHttpListener/HttpBase.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-using System;
-using System.Text;
-using MediaBrowser.Model.Services;
-
-namespace SocketHttpListener
-{
- internal abstract class HttpBase
- {
- #region Private Fields
-
- private QueryParamCollection _headers;
- private Version _version;
-
- #endregion
-
- #region Protected Fields
-
- protected const string CrLf = "\r\n";
-
- #endregion
-
- #region Protected Constructors
-
- protected HttpBase(Version version, QueryParamCollection headers)
- {
- _version = version;
- _headers = headers;
- }
-
- #endregion
-
- #region Public Properties
-
- public QueryParamCollection Headers => _headers;
-
- public Version ProtocolVersion => _version;
-
- #endregion
-
- #region Private Methods
-
- private static Encoding getEncoding(string contentType)
- {
- if (contentType == null || contentType.Length == 0)
- return Encoding.UTF8;
-
- var i = contentType.IndexOf("charset=", StringComparison.Ordinal);
- if (i == -1)
- return Encoding.UTF8;
-
- var charset = contentType.Substring(i + 8);
- i = charset.IndexOf(';');
- if (i != -1)
- charset = charset.Substring(0, i).TrimEnd();
-
- return Encoding.GetEncoding(charset.Trim('"'));
- }
-
- #endregion
-
- #region Public Methods
-
- public byte[] ToByteArray()
- {
- return Encoding.UTF8.GetBytes(ToString());
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/HttpResponse.cs b/SocketHttpListener/HttpResponse.cs
deleted file mode 100644
index d5d9b4a1c..000000000
--- a/SocketHttpListener/HttpResponse.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-using System;
-using System.Linq;
-using System.Net;
-using System.Text;
-using MediaBrowser.Model.Services;
-using SocketHttpListener.Net;
-using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
-using HttpVersion = SocketHttpListener.Net.HttpVersion;
-
-namespace SocketHttpListener
-{
- internal class HttpResponse : HttpBase
- {
- #region Private Fields
-
- private string _code;
- private string _reason;
-
- #endregion
-
- #region Private Constructors
-
- private HttpResponse(string code, string reason, Version version, QueryParamCollection headers)
- : base(version, headers)
- {
- _code = code;
- _reason = reason;
- }
-
- #endregion
-
- #region Internal Constructors
-
- internal HttpResponse(HttpStatusCode code)
- : this(code, code.GetDescription())
- {
- }
-
- internal HttpResponse(HttpStatusCode code, string reason)
- : this(((int)code).ToString(), reason, HttpVersion.Version11, new QueryParamCollection())
- {
- Headers["Server"] = "websocket-sharp/1.0";
- }
-
- #endregion
-
- #region Public Properties
-
- public CookieCollection Cookies => GetCookies(Headers, true);
-
- private static CookieCollection GetCookies(QueryParamCollection headers, bool response)
- {
- var name = response ? "Set-Cookie" : "Cookie";
- return headers == null || !headers.Contains(name)
- ? new CookieCollection()
- : CookieHelper.Parse(headers[name], response);
- }
-
- public bool IsProxyAuthenticationRequired => _code == "407";
-
- public bool IsUnauthorized => _code == "401";
-
- public bool IsWebSocketResponse
- {
- get
- {
- var headers = Headers;
- return ProtocolVersion > HttpVersion.Version10 &&
- _code == "101" &&
- headers.Contains("Upgrade", "websocket") &&
- headers.Contains("Connection", "Upgrade");
- }
- }
-
- public string Reason => _reason;
-
- public string StatusCode => _code;
-
- #endregion
-
- #region Internal Methods
-
- internal static HttpResponse CreateCloseResponse(HttpStatusCode code)
- {
- var res = new HttpResponse(code);
- res.Headers["Connection"] = "close";
-
- return res;
- }
-
- #endregion
-
- #region Public Methods
-
- public void SetCookies(CookieCollection cookies)
- {
- if (cookies == null || cookies.Count == 0)
- return;
-
- var headers = Headers;
- var sorted = cookies.OfType<Cookie>().OrderBy(i => i.Name).ToList();
-
- foreach (var cookie in sorted)
- headers.Add("Set-Cookie", cookie.ToString());
- }
-
- public override string ToString()
- {
- var output = new StringBuilder(64);
- output.AppendFormat("HTTP/{0} {1} {2}{3}", ProtocolVersion, _code, _reason, CrLf);
-
- var headers = Headers;
- foreach (var key in headers.Keys)
- output.AppendFormat("{0}: {1}{2}", key, headers[key], CrLf);
-
- output.Append(CrLf);
-
- return output.ToString();
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/Mask.cs b/SocketHttpListener/Mask.cs
deleted file mode 100644
index c56f5b08c..000000000
--- a/SocketHttpListener/Mask.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace SocketHttpListener
-{
- internal enum Mask : byte
- {
- Unmask = 0x0,
- Mask = 0x1
- }
-}
diff --git a/SocketHttpListener/MessageEventArgs.cs b/SocketHttpListener/MessageEventArgs.cs
deleted file mode 100644
index 8e2151cb7..000000000
--- a/SocketHttpListener/MessageEventArgs.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-using System;
-using System.Text;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the event data associated with a <see cref="WebSocket.OnMessage"/> event.
- /// </summary>
- /// <remarks>
- /// A <see cref="WebSocket.OnMessage"/> event occurs when the <see cref="WebSocket"/> receives
- /// a text or binary data frame.
- /// If you want to get the received data, you access the <see cref="Data"/> or
- /// <see cref="RawData"/> property.
- /// </remarks>
- public class MessageEventArgs : EventArgs
- {
- #region Private Fields
-
- private string _data;
- private Opcode _opcode;
- private byte[] _rawData;
-
- #endregion
-
- #region Internal Constructors
-
- internal MessageEventArgs(Opcode opcode, byte[] data)
- {
- _opcode = opcode;
- _rawData = data;
- _data = convertToString(opcode, data);
- }
-
- internal MessageEventArgs(Opcode opcode, PayloadData payload)
- {
- _opcode = opcode;
- _rawData = payload.ApplicationData;
- _data = convertToString(opcode, _rawData);
- }
-
- #endregion
-
- #region Public Properties
-
- /// <summary>
- /// Gets the received data as a <see cref="string"/>.
- /// </summary>
- /// <value>
- /// A <see cref="string"/> that contains the received data.
- /// </value>
- public string Data => _data;
-
- /// <summary>
- /// Gets the received data as an array of <see cref="byte"/>.
- /// </summary>
- /// <value>
- /// An array of <see cref="byte"/> that contains the received data.
- /// </value>
- public byte[] RawData => _rawData;
-
- /// <summary>
- /// Gets the type of the received data.
- /// </summary>
- /// <value>
- /// One of the <see cref="Opcode"/> values, indicates the type of the received data.
- /// </value>
- public Opcode Type => _opcode;
-
- #endregion
-
- #region Private Methods
-
- private static string convertToString(Opcode opcode, byte[] data)
- {
- return data.Length == 0
- ? string.Empty
- : opcode == Opcode.Text
- ? Encoding.UTF8.GetString(data, 0, data.Length)
- : opcode.ToString();
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/Net/AuthenticationSchemeSelector.cs b/SocketHttpListener/Net/AuthenticationSchemeSelector.cs
deleted file mode 100644
index 77e6d0b8a..000000000
--- a/SocketHttpListener/Net/AuthenticationSchemeSelector.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-using System.Net;
-
-namespace SocketHttpListener.Net
-{
- public delegate AuthenticationSchemes AuthenticationSchemeSelector(HttpListenerRequest httpRequest);
-}
diff --git a/SocketHttpListener/Net/AuthenticationTypes.cs b/SocketHttpListener/Net/AuthenticationTypes.cs
deleted file mode 100644
index a3dbe9dff..000000000
--- a/SocketHttpListener/Net/AuthenticationTypes.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal class AuthenticationTypes
- {
- internal const string NTLM = "NTLM";
- internal const string Negotiate = "Negotiate";
- internal const string Basic = "Basic";
- }
-}
diff --git a/SocketHttpListener/Net/BoundaryType.cs b/SocketHttpListener/Net/BoundaryType.cs
deleted file mode 100644
index da0b22910..000000000
--- a/SocketHttpListener/Net/BoundaryType.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal enum BoundaryType
- {
- ContentLength = 0, // Content-Length: XXX
- Chunked = 1, // Transfer-Encoding: chunked
- Multipart = 3,
- None = 4,
- Invalid = 5,
- }
-}
diff --git a/SocketHttpListener/Net/ChunkStream.cs b/SocketHttpListener/Net/ChunkStream.cs
deleted file mode 100644
index 3836947d4..000000000
--- a/SocketHttpListener/Net/ChunkStream.cs
+++ /dev/null
@@ -1,385 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Text;
-
-namespace SocketHttpListener.Net
-{
- // Licensed to the .NET Foundation under one or more agreements.
- // See the LICENSE file in the project root for more information.
- //
- // System.Net.ResponseStream
- //
- // Author:
- // Gonzalo Paniagua Javier (gonzalo@novell.com)
- //
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
-
- internal sealed class ChunkStream
- {
- private enum State
- {
- None,
- PartialSize,
- Body,
- BodyFinished,
- Trailer
- }
-
- private class Chunk
- {
- public byte[] Bytes;
- public int Offset;
-
- public Chunk(byte[] chunk)
- {
- Bytes = chunk;
- }
-
- public int Read(byte[] buffer, int offset, int size)
- {
- int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
- Buffer.BlockCopy(Bytes, Offset, buffer, offset, nread);
- Offset += nread;
- return nread;
- }
- }
-
- internal WebHeaderCollection _headers;
- private int _chunkSize;
- private int _chunkRead;
- private int _totalWritten;
- private State _state;
- private StringBuilder _saved;
- private bool _sawCR;
- private bool _gotit;
- private int _trailerState;
- private List<Chunk> _chunks;
-
- public ChunkStream(WebHeaderCollection headers)
- {
- _headers = headers;
- _saved = new StringBuilder();
- _chunks = new List<Chunk>();
- _chunkSize = -1;
- _totalWritten = 0;
- }
-
- public void ResetBuffer()
- {
- _chunkSize = -1;
- _chunkRead = 0;
- _totalWritten = 0;
- _chunks.Clear();
- }
-
- public int Read(byte[] buffer, int offset, int size)
- {
- return ReadFromChunks(buffer, offset, size);
- }
-
- private int ReadFromChunks(byte[] buffer, int offset, int size)
- {
- int count = _chunks.Count;
- int nread = 0;
-
- var chunksForRemoving = new List<Chunk>(count);
- for (int i = 0; i < count; i++)
- {
- var chunk = _chunks[i];
-
- if (chunk.Offset == chunk.Bytes.Length)
- {
- chunksForRemoving.Add(chunk);
- continue;
- }
-
- nread += chunk.Read(buffer, offset + nread, size - nread);
- if (nread == size)
- break;
- }
-
- foreach (var chunk in chunksForRemoving)
- _chunks.Remove(chunk);
-
- return nread;
- }
-
- public void Write(byte[] buffer, int offset, int size)
- {
- // Note, the logic here only works when offset is 0 here.
- // Otherwise, it would treat "size" as the end offset instead of an actual byte count from offset.
-
- if (offset < size)
- InternalWrite(buffer, ref offset, size);
- }
-
- private void InternalWrite(byte[] buffer, ref int offset, int size)
- {
- if (_state == State.None || _state == State.PartialSize)
- {
- _state = GetChunkSize(buffer, ref offset, size);
- if (_state == State.PartialSize)
- return;
-
- _saved.Length = 0;
- _sawCR = false;
- _gotit = false;
- }
-
- if (_state == State.Body && offset < size)
- {
- _state = ReadBody(buffer, ref offset, size);
- if (_state == State.Body)
- return;
- }
-
- if (_state == State.BodyFinished && offset < size)
- {
- _state = ReadCRLF(buffer, ref offset, size);
- if (_state == State.BodyFinished)
- return;
-
- _sawCR = false;
- }
-
- if (_state == State.Trailer && offset < size)
- {
- _state = ReadTrailer(buffer, ref offset, size);
- if (_state == State.Trailer)
- return;
-
- _saved.Length = 0;
- _sawCR = false;
- _gotit = false;
- }
-
- if (offset < size)
- InternalWrite(buffer, ref offset, size);
- }
-
- public bool WantMore => (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None);
-
- public bool DataAvailable
- {
- get
- {
- int count = _chunks.Count;
- for (int i = 0; i < count; i++)
- {
- var ch = _chunks[i];
- if (ch == null || ch.Bytes == null)
- continue;
- if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
- return (_state != State.Body);
- }
- return false;
- }
- }
-
- public int TotalDataSize => _totalWritten;
-
- public int ChunkLeft => _chunkSize - _chunkRead;
-
- private State ReadBody(byte[] buffer, ref int offset, int size)
- {
- if (_chunkSize == 0)
- return State.BodyFinished;
-
- int diff = size - offset;
- if (diff + _chunkRead > _chunkSize)
- diff = _chunkSize - _chunkRead;
-
- byte[] chunk = new byte[diff];
- Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
- _chunks.Add(new Chunk(chunk));
- offset += diff;
- _chunkRead += diff;
- _totalWritten += diff;
-
- return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body;
- }
-
- private State GetChunkSize(byte[] buffer, ref int offset, int size)
- {
- _chunkRead = 0;
- _chunkSize = 0;
- char c = '\0';
- while (offset < size)
- {
- c = (char)buffer[offset++];
- if (c == '\r')
- {
- if (_sawCR)
- ThrowProtocolViolation("2 CR found");
-
- _sawCR = true;
- continue;
- }
-
- if (_sawCR && c == '\n')
- break;
-
- if (c == ' ')
- _gotit = true;
-
- if (!_gotit)
- _saved.Append(c);
-
- if (_saved.Length > 20)
- ThrowProtocolViolation("chunk size too long.");
- }
-
- if (!_sawCR || c != '\n')
- {
- if (offset < size)
- ThrowProtocolViolation("Missing \\n");
-
- try
- {
- if (_saved.Length > 0)
- {
- _chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
- }
- }
- catch (Exception)
- {
- ThrowProtocolViolation("Cannot parse chunk size.");
- }
-
- return State.PartialSize;
- }
-
- _chunkRead = 0;
- try
- {
- _chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
- }
- catch (Exception)
- {
- ThrowProtocolViolation("Cannot parse chunk size.");
- }
-
- if (_chunkSize == 0)
- {
- _trailerState = 2;
- return State.Trailer;
- }
-
- return State.Body;
- }
-
- private static string RemoveChunkExtension(string input)
- {
- int idx = input.IndexOf(';');
- if (idx == -1)
- return input;
- return input.Substring(0, idx);
- }
-
- private State ReadCRLF(byte[] buffer, ref int offset, int size)
- {
- if (!_sawCR)
- {
- if ((char)buffer[offset++] != '\r')
- ThrowProtocolViolation("Expecting \\r");
-
- _sawCR = true;
- if (offset == size)
- return State.BodyFinished;
- }
-
- if (_sawCR && (char)buffer[offset++] != '\n')
- ThrowProtocolViolation("Expecting \\n");
-
- return State.None;
- }
-
- private State ReadTrailer(byte[] buffer, ref int offset, int size)
- {
- char c = '\0';
-
- // short path
- if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0)
- {
- offset++;
- if (offset < size && (char)buffer[offset] == '\n')
- {
- offset++;
- return State.None;
- }
- offset--;
- }
-
- int st = _trailerState;
- string stString = "\r\n\r";
- while (offset < size && st < 4)
- {
- c = (char)buffer[offset++];
- if ((st == 0 || st == 2) && c == '\r')
- {
- st++;
- continue;
- }
-
- if ((st == 1 || st == 3) && c == '\n')
- {
- st++;
- continue;
- }
-
- if (st > 0)
- {
- _saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st));
- st = 0;
- if (_saved.Length > 4196)
- ThrowProtocolViolation("Error reading trailer (too long).");
- }
- }
-
- if (st < 4)
- {
- _trailerState = st;
- if (offset < size)
- ThrowProtocolViolation("Error reading trailer.");
-
- return State.Trailer;
- }
-
- var reader = new StringReader(_saved.ToString());
- string line;
- while ((line = reader.ReadLine()) != null && line != "")
- _headers.Add(line);
-
- return State.None;
- }
-
- private static void ThrowProtocolViolation(string message)
- {
- var we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
- throw we;
- }
- }
-}
diff --git a/SocketHttpListener/Net/ChunkedInputStream.cs b/SocketHttpListener/Net/ChunkedInputStream.cs
deleted file mode 100644
index 7aa8529e3..000000000
--- a/SocketHttpListener/Net/ChunkedInputStream.cs
+++ /dev/null
@@ -1,178 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-
-namespace SocketHttpListener.Net
-{
- // Licensed to the .NET Foundation under one or more agreements.
- // See the LICENSE file in the project root for more information.
- //
- // System.Net.ResponseStream
- //
- // Author:
- // Gonzalo Paniagua Javier (gonzalo@novell.com)
- //
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
-
- internal sealed class ChunkedInputStream : HttpRequestStream
- {
- private ChunkStream _decoder;
- private readonly HttpListenerContext _context;
- private bool _no_more_data;
-
- private class ReadBufferState
- {
- public byte[] Buffer;
- public int Offset;
- public int Count;
- public int InitialCount;
- public HttpStreamAsyncResult Ares;
- public ReadBufferState(byte[] buffer, int offset, int count, HttpStreamAsyncResult ares)
- {
- Buffer = buffer;
- Offset = offset;
- Count = count;
- InitialCount = count;
- Ares = ares;
- }
- }
-
- public ChunkedInputStream(HttpListenerContext context, Stream stream, byte[] buffer, int offset, int length)
- : base(stream, buffer, offset, length)
- {
- _context = context;
- var coll = (WebHeaderCollection)context.Request.Headers;
- _decoder = new ChunkStream(coll);
- }
-
- public ChunkStream Decoder
- {
- get => _decoder;
- set => _decoder = value;
- }
-
- protected override int ReadCore(byte[] buffer, int offset, int count)
- {
- IAsyncResult ares = BeginReadCore(buffer, offset, count, null, null);
- return EndRead(ares);
- }
-
- protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state)
- {
- var ares = new HttpStreamAsyncResult(this);
- ares._callback = cback;
- ares._state = state;
- if (_no_more_data || size == 0 || _closed)
- {
- ares.Complete();
- return ares;
- }
- int nread = _decoder.Read(buffer, offset, size);
- offset += nread;
- size -= nread;
- if (size == 0)
- {
- // got all we wanted, no need to bother the decoder yet
- ares._count = nread;
- ares.Complete();
- return ares;
- }
- if (!_decoder.WantMore)
- {
- _no_more_data = nread == 0;
- ares._count = nread;
- ares.Complete();
- return ares;
- }
- ares._buffer = new byte[8192];
- ares._offset = 0;
- ares._count = 8192;
- var rb = new ReadBufferState(buffer, offset, size, ares);
- rb.InitialCount += nread;
- base.BeginReadCore(ares._buffer, ares._offset, ares._count, OnRead, rb);
- return ares;
- }
-
- private void OnRead(IAsyncResult base_ares)
- {
- ReadBufferState rb = (ReadBufferState)base_ares.AsyncState;
- var ares = rb.Ares;
- try
- {
- int nread = base.EndRead(base_ares);
- if (nread == 0)
- {
- _no_more_data = true;
- ares._count = rb.InitialCount - rb.Count;
- ares.Complete();
- return;
- }
-
- _decoder.Write(ares._buffer, ares._offset, nread);
- nread = _decoder.Read(rb.Buffer, rb.Offset, rb.Count);
- rb.Offset += nread;
- rb.Count -= nread;
- if (rb.Count == 0 || !_decoder.WantMore)
- {
- _no_more_data = !_decoder.WantMore && nread == 0;
- ares._count = rb.InitialCount - rb.Count;
- ares.Complete();
- return;
- }
- ares._offset = 0;
- ares._count = Math.Min(8192, _decoder.ChunkLeft + 6);
- base.BeginReadCore(ares._buffer, ares._offset, ares._count, OnRead, rb);
- }
- catch (Exception e)
- {
- _context.Connection.SendError(e.Message, 400);
- ares.Complete(e);
- }
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- throw new ArgumentNullException(nameof(asyncResult));
-
- var ares = asyncResult as HttpStreamAsyncResult;
- if (ares == null || !ReferenceEquals(this, ares._parent))
- {
- throw new ArgumentException("Invalid async result");
- }
- if (ares._endCalled)
- {
- throw new InvalidOperationException("Invalid end call");
- }
- ares._endCalled = true;
-
- if (!asyncResult.IsCompleted)
- asyncResult.AsyncWaitHandle.WaitOne();
-
- if (ares._error != null)
- throw new HttpListenerException((int)HttpStatusCode.BadRequest, "Operation aborted");
-
- return ares._count;
- }
- }
-}
diff --git a/SocketHttpListener/Net/CookieHelper.cs b/SocketHttpListener/Net/CookieHelper.cs
deleted file mode 100644
index 3ad76ff23..000000000
--- a/SocketHttpListener/Net/CookieHelper.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Net;
-using System.Text;
-
-namespace SocketHttpListener.Net
-{
- public static class CookieHelper
- {
- internal static CookieCollection Parse(string value, bool response)
- {
- return response
- ? parseResponse(value)
- : null;
- }
-
- private static string[] splitCookieHeaderValue(string value)
- {
- return new List<string>(value.SplitHeaderValue(',', ';')).ToArray();
- }
-
- private static CookieCollection parseResponse(string value)
- {
- var cookies = new CookieCollection();
-
- Cookie cookie = null;
- var pairs = splitCookieHeaderValue(value);
- for (int i = 0; i < pairs.Length; i++)
- {
- var pair = pairs[i].Trim();
- if (pair.Length == 0)
- continue;
-
- if (pair.StartsWith("version", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Version = int.Parse(pair.GetValueInternal("=").Trim('"'));
- }
- else if (pair.StartsWith("expires", StringComparison.OrdinalIgnoreCase))
- {
- var buffer = new StringBuilder(pair.GetValueInternal("="), 32);
- if (i < pairs.Length - 1)
- buffer.AppendFormat(", {0}", pairs[++i].Trim());
-
- if (!DateTime.TryParseExact(
- buffer.ToString(),
- new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
- new CultureInfo("en-US"),
- DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
- out var expires))
- expires = DateTime.Now;
-
- if (cookie != null && cookie.Expires == DateTime.MinValue)
- cookie.Expires = expires.ToLocalTime();
- }
- else if (pair.StartsWith("max-age", StringComparison.OrdinalIgnoreCase))
- {
- var max = int.Parse(pair.GetValueInternal("=").Trim('"'));
- var expires = DateTime.Now.AddSeconds((double)max);
- if (cookie != null)
- cookie.Expires = expires;
- }
- else if (pair.StartsWith("path", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Path = pair.GetValueInternal("=");
- }
- else if (pair.StartsWith("domain", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Domain = pair.GetValueInternal("=");
- }
- else if (pair.StartsWith("port", StringComparison.OrdinalIgnoreCase))
- {
- var port = pair.Equals("port", StringComparison.OrdinalIgnoreCase)
- ? "\"\""
- : pair.GetValueInternal("=");
-
- if (cookie != null)
- cookie.Port = port;
- }
- else if (pair.StartsWith("comment", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Comment = pair.GetValueInternal("=").UrlDecode();
- }
- else if (pair.StartsWith("commenturl", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.CommentUri = pair.GetValueInternal("=").Trim('"').ToUri();
- }
- else if (pair.StartsWith("discard", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Discard = true;
- }
- else if (pair.StartsWith("secure", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.Secure = true;
- }
- else if (pair.StartsWith("httponly", StringComparison.OrdinalIgnoreCase))
- {
- if (cookie != null)
- cookie.HttpOnly = true;
- }
- else
- {
- if (cookie != null)
- cookies.Add(cookie);
-
- string name;
- string val = string.Empty;
-
- var pos = pair.IndexOf('=');
- if (pos == -1)
- {
- name = pair;
- }
- else if (pos == pair.Length - 1)
- {
- name = pair.Substring(0, pos).TrimEnd(' ');
- }
- else
- {
- name = pair.Substring(0, pos).TrimEnd(' ');
- val = pair.Substring(pos + 1).TrimStart(' ');
- }
-
- cookie = new Cookie(name, val);
- }
- }
-
- if (cookie != null)
- cookies.Add(cookie);
-
- return cookies;
- }
- }
-}
diff --git a/SocketHttpListener/Net/EntitySendFormat.cs b/SocketHttpListener/Net/EntitySendFormat.cs
deleted file mode 100644
index 3ed981084..000000000
--- a/SocketHttpListener/Net/EntitySendFormat.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal enum EntitySendFormat
- {
- ContentLength = 0, // Content-Length: XXX
- Chunked = 1, // Transfer-Encoding: chunked
- }
-}
diff --git a/SocketHttpListener/Net/HttpConnection.cs b/SocketHttpListener/Net/HttpConnection.cs
deleted file mode 100644
index e89f4ed9b..000000000
--- a/SocketHttpListener/Net/HttpConnection.cs
+++ /dev/null
@@ -1,528 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Security;
-using System.Net.Sockets;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-namespace SocketHttpListener.Net
-{
- sealed class HttpConnection
- {
- private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
- const int BufferSize = 8192;
- Socket _socket;
- Stream _stream;
- HttpEndPointListener _epl;
- MemoryStream _memoryStream;
- byte[] _buffer;
- HttpListenerContext _context;
- StringBuilder _currentLine;
- ListenerPrefix _prefix;
- HttpRequestStream _requestStream;
- HttpResponseStream _responseStream;
- bool _chunked;
- int _reuses;
- bool _contextBound;
- bool secure;
- IPEndPoint local_ep;
- HttpListener _lastListener;
- X509Certificate cert;
- SslStream ssl_stream;
-
- private readonly ILogger _logger;
- private readonly ICryptoProvider _cryptoProvider;
- private readonly IStreamHelper _streamHelper;
- private readonly IFileSystem _fileSystem;
- private readonly IEnvironmentInfo _environment;
-
- public HttpConnection(ILogger logger, Socket socket, HttpEndPointListener epl, bool secure,
- X509Certificate cert, ICryptoProvider cryptoProvider, IStreamHelper streamHelper, IFileSystem fileSystem,
- IEnvironmentInfo environment)
- {
- _logger = logger;
- this._socket = socket;
- this._epl = epl;
- this.secure = secure;
- this.cert = cert;
- _cryptoProvider = cryptoProvider;
- _streamHelper = streamHelper;
- _fileSystem = fileSystem;
- _environment = environment;
-
- if (secure == false)
- {
- _stream = new SocketStream(_socket, false);
- }
- else
- {
- ssl_stream = new SslStream(new SocketStream(_socket, false), false, (t, c, ch, e) =>
- {
- if (c == null)
- {
- return true;
- }
-
- //var c2 = c as X509Certificate2;
- //if (c2 == null)
- //{
- // c2 = new X509Certificate2(c.GetRawCertData());
- //}
-
- //_clientCert = c2;
- //_clientCertErrors = new int[] { (int)e };
- return true;
- });
-
- _stream = ssl_stream;
- }
- }
-
- public Stream Stream => _stream;
-
- public async Task Init()
- {
- if (ssl_stream != null)
- {
- var enableAsync = true;
- if (enableAsync)
- {
- await ssl_stream.AuthenticateAsServerAsync(cert, false, (SslProtocols)ServicePointManager.SecurityProtocol, false).ConfigureAwait(false);
- }
- else
- {
- ssl_stream.AuthenticateAsServer(cert, false, (SslProtocols)ServicePointManager.SecurityProtocol, false);
- }
- }
-
- InitInternal();
- }
-
- private void InitInternal()
- {
- _contextBound = false;
- _requestStream = null;
- _responseStream = null;
- _prefix = null;
- _chunked = false;
- _memoryStream = new MemoryStream();
- _position = 0;
- _inputState = InputState.RequestLine;
- _lineState = LineState.None;
- _context = new HttpListenerContext(this);
- }
-
- public bool IsClosed => (_socket == null);
-
- public int Reuses => _reuses;
-
- public IPEndPoint LocalEndPoint
- {
- get
- {
- if (local_ep != null)
- return local_ep;
-
- local_ep = (IPEndPoint)_socket.LocalEndPoint;
- return local_ep;
- }
- }
-
- public IPEndPoint RemoteEndPoint => _socket.RemoteEndPoint as IPEndPoint;
-
- public bool IsSecure => secure;
-
- public ListenerPrefix Prefix
- {
- get => _prefix;
- set => _prefix = value;
- }
-
- private void OnTimeout(object unused)
- {
- //_logger.LogInformation("HttpConnection timer fired");
- CloseSocket();
- Unbind();
- }
-
- public void BeginReadRequest()
- {
- if (_buffer == null)
- _buffer = new byte[BufferSize];
- try
- {
- _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
- }
- catch
- {
- CloseSocket();
- Unbind();
- }
- }
-
- public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
- {
- if (_requestStream == null)
- {
- byte[] buffer = _memoryStream.GetBuffer();
- int length = (int)_memoryStream.Length;
- _memoryStream = null;
- if (chunked)
- {
- _chunked = true;
- //_context.Response.SendChunked = true;
- _requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
- }
- else
- {
- _requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
- }
- }
- return _requestStream;
- }
-
- public HttpResponseStream GetResponseStream(bool isExpect100Continue = false)
- {
- // TODO: can we get this _stream before reading the input?
- if (_responseStream == null)
- {
- var supportsDirectSocketAccess = !_context.Response.SendChunked && !isExpect100Continue && !secure;
-
- _responseStream = new HttpResponseStream(_stream, _context.Response, false, _streamHelper, _socket, supportsDirectSocketAccess, _environment, _fileSystem, _logger);
- }
- return _responseStream;
- }
-
- private static void OnRead(IAsyncResult ares)
- {
- var cnc = (HttpConnection)ares.AsyncState;
- cnc.OnReadInternal(ares);
- }
-
- private void OnReadInternal(IAsyncResult ares)
- {
- int nread = -1;
- try
- {
- nread = _stream.EndRead(ares);
- _memoryStream.Write(_buffer, 0, nread);
- if (_memoryStream.Length > 32768)
- {
- SendError("Bad Request", 400);
- Close(true);
- return;
- }
- }
- catch
- {
- if (_memoryStream != null && _memoryStream.Length > 0)
- SendError();
- if (_socket != null)
- {
- CloseSocket();
- Unbind();
- }
- return;
- }
-
- if (nread == 0)
- {
- CloseSocket();
- Unbind();
- return;
- }
-
- if (ProcessInput(_memoryStream))
- {
- if (!_context.HaveError)
- _context.Request.FinishInitialization();
-
- if (_context.HaveError)
- {
- SendError();
- Close(true);
- return;
- }
-
- if (!_epl.BindContext(_context))
- {
- const int NotFoundErrorCode = 404;
- SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
- Close(true);
- return;
- }
- HttpListener listener = _epl.Listener;
- if (_lastListener != listener)
- {
- RemoveConnection();
- listener.AddConnection(this);
- _lastListener = listener;
- }
-
- _contextBound = true;
- listener.RegisterContext(_context);
- return;
- }
- _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
- }
-
- private void RemoveConnection()
- {
- if (_lastListener == null)
- _epl.RemoveConnection(this);
- else
- _lastListener.RemoveConnection(this);
- }
-
- private enum InputState
- {
- RequestLine,
- Headers
- }
-
- private enum LineState
- {
- None,
- CR,
- LF
- }
-
- InputState _inputState = InputState.RequestLine;
- LineState _lineState = LineState.None;
- int _position;
-
- // true -> done processing
- // false -> need more input
- private bool ProcessInput(MemoryStream ms)
- {
- byte[] buffer = ms.GetBuffer();
- int len = (int)ms.Length;
- int used = 0;
- string line;
-
- while (true)
- {
- if (_context.HaveError)
- return true;
-
- if (_position >= len)
- break;
-
- try
- {
- line = ReadLine(buffer, _position, len - _position, ref used);
- _position += used;
- }
- catch
- {
- _context.ErrorMessage = "Bad request";
- _context.ErrorStatus = 400;
- return true;
- }
-
- if (line == null)
- break;
-
- if (line == "")
- {
- if (_inputState == InputState.RequestLine)
- continue;
- _currentLine = null;
- ms = null;
- return true;
- }
-
- if (_inputState == InputState.RequestLine)
- {
- _context.Request.SetRequestLine(line);
- _inputState = InputState.Headers;
- }
- else
- {
- try
- {
- _context.Request.AddHeader(line);
- }
- catch (Exception e)
- {
- _context.ErrorMessage = e.Message;
- _context.ErrorStatus = 400;
- return true;
- }
- }
- }
-
- if (used == len)
- {
- ms.SetLength(0);
- _position = 0;
- }
- return false;
- }
-
- private string ReadLine(byte[] buffer, int offset, int len, ref int used)
- {
- if (_currentLine == null)
- _currentLine = new StringBuilder(128);
- int last = offset + len;
- used = 0;
- for (int i = offset; i < last && _lineState != LineState.LF; i++)
- {
- used++;
- byte b = buffer[i];
- if (b == 13)
- {
- _lineState = LineState.CR;
- }
- else if (b == 10)
- {
- _lineState = LineState.LF;
- }
- else
- {
- _currentLine.Append((char)b);
- }
- }
-
- string result = null;
- if (_lineState == LineState.LF)
- {
- _lineState = LineState.None;
- result = _currentLine.ToString();
- _currentLine.Length = 0;
- }
-
- return result;
- }
-
- public void SendError(string msg, int status)
- {
- try
- {
- HttpListenerResponse response = _context.Response;
- response.StatusCode = status;
- response.ContentType = "text/html";
- string description = HttpStatusDescription.Get(status);
- string str;
- if (msg != null)
- str = string.Format("<h1>{0} ({1})</h1>", description, msg);
- else
- str = string.Format("<h1>{0}</h1>", description);
-
- byte[] error = Encoding.UTF8.GetBytes(str);
- response.Close(error, false);
- }
- catch
- {
- // response was already closed
- }
- }
-
- public void SendError()
- {
- SendError(_context.ErrorMessage, _context.ErrorStatus);
- }
-
- private void Unbind()
- {
- if (_contextBound)
- {
- _epl.UnbindContext(_context);
- _contextBound = false;
- }
- }
-
- public void Close()
- {
- Close(false);
- }
-
- private void CloseSocket()
- {
- if (_socket == null)
- return;
-
- try
- {
- _socket.Close();
- }
- catch { }
- finally
- {
- _socket = null;
- }
-
- RemoveConnection();
- }
-
- internal void Close(bool force)
- {
- if (_socket != null)
- {
- Stream st = GetResponseStream();
- if (st != null)
- st.Close();
-
- _responseStream = null;
- }
-
- if (_socket != null)
- {
- force |= !_context.Request.KeepAlive;
- if (!force)
- force = (string.Equals(_context.Response.Headers["connection"], "close", StringComparison.OrdinalIgnoreCase));
-
- if (!force && _context.Request.FlushInput())
- {
- if (_chunked && _context.Response.ForceCloseChunked == false)
- {
- // Don't close. Keep working.
- _reuses++;
- Unbind();
- InitInternal();
- BeginReadRequest();
- return;
- }
-
- _reuses++;
- Unbind();
- InitInternal();
- BeginReadRequest();
- return;
- }
-
- Socket s = _socket;
- _socket = null;
- try
- {
- if (s != null)
- s.Shutdown(SocketShutdown.Both);
- }
- catch
- {
- }
- finally
- {
- if (s != null)
- {
- try
- {
- s.Close();
- }
- catch { }
- }
- }
- Unbind();
- RemoveConnection();
- return;
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpEndPointListener.cs b/SocketHttpListener/Net/HttpEndPointListener.cs
deleted file mode 100644
index 35d1af648..000000000
--- a/SocketHttpListener/Net/HttpEndPointListener.cs
+++ /dev/null
@@ -1,526 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using System.Net.Sockets;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace SocketHttpListener.Net
-{
- internal sealed class HttpEndPointListener
- {
- private HttpListener _listener;
- private IPEndPoint _endpoint;
- private Socket _socket;
- private Dictionary<ListenerPrefix, HttpListener> _prefixes;
- private List<ListenerPrefix> _unhandledPrefixes; // host = '*'
- private List<ListenerPrefix> _allPrefixes; // host = '+'
- private X509Certificate _cert;
- private bool _secure;
- private Dictionary<HttpConnection, HttpConnection> _unregisteredConnections;
-
- private readonly ILogger _logger;
- private bool _closed;
- private bool _enableDualMode;
- private readonly ICryptoProvider _cryptoProvider;
- private readonly ISocketFactory _socketFactory;
- private readonly IStreamHelper _streamHelper;
- private readonly IFileSystem _fileSystem;
- private readonly IEnvironmentInfo _environment;
-
- public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure, X509Certificate cert,
- ILogger logger, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, IStreamHelper streamHelper,
- IFileSystem fileSystem, IEnvironmentInfo environment)
- {
- this._listener = listener;
- _logger = logger;
- _cryptoProvider = cryptoProvider;
- _socketFactory = socketFactory;
- _streamHelper = streamHelper;
- _fileSystem = fileSystem;
- _environment = environment;
-
- this._secure = secure;
- this._cert = cert;
-
- _enableDualMode = addr.Equals(IPAddress.IPv6Any);
- _endpoint = new IPEndPoint(addr, port);
-
- _prefixes = new Dictionary<ListenerPrefix, HttpListener>();
- _unregisteredConnections = new Dictionary<HttpConnection, HttpConnection>();
-
- CreateSocket();
- }
-
- internal HttpListener Listener => _listener;
-
- private void CreateSocket()
- {
- try
- {
- _socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
- }
- catch (SocketCreateException ex)
- {
- if (_enableDualMode && _endpoint.Address.Equals(IPAddress.IPv6Any) &&
- (string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
- // mono 4.8.1 and lower on bsd is throwing this
- string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase) ||
- // mono 5.2 on bsd is throwing this
- string.Equals(ex.ErrorCode, "OperationNotSupported", StringComparison.OrdinalIgnoreCase)))
- {
- _endpoint = new IPEndPoint(IPAddress.Any, _endpoint.Port);
- _enableDualMode = false;
- _socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
- }
- else
- {
- throw;
- }
- }
-
- try
- {
- _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- }
- catch (SocketException)
- {
- // This is not supported on all operating systems (qnap)
- }
-
- _socket.Bind(_endpoint);
-
- // This is the number TcpListener uses.
- _socket.Listen(2147483647);
-
- Accept();
-
- _closed = false;
- }
-
- private void Accept()
- {
- var acceptEventArg = new SocketAsyncEventArgs();
- acceptEventArg.UserToken = this;
- acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAccept);
-
- Accept(acceptEventArg);
- }
-
- private static void TryCloseAndDispose(Socket socket)
- {
- try
- {
- using (socket)
- {
- socket.Close();
- }
- }
- catch
- {
-
- }
- }
-
- private static void TryClose(Socket socket)
- {
- try
- {
- socket.Close();
- }
- catch
- {
-
- }
- }
-
- private void Accept(SocketAsyncEventArgs acceptEventArg)
- {
- // acceptSocket must be cleared since the context object is being reused
- acceptEventArg.AcceptSocket = null;
-
- try
- {
- bool willRaiseEvent = _socket.AcceptAsync(acceptEventArg);
-
- if (!willRaiseEvent)
- {
- ProcessAccept(acceptEventArg);
- }
- }
- catch (ObjectDisposedException)
- {
- // TODO Investigate or properly fix.
- }
- catch (Exception ex)
- {
- var epl = (HttpEndPointListener)acceptEventArg.UserToken;
-
- epl._logger.LogError(ex, "Error in socket.AcceptAsync");
- }
- }
-
- // This method is the callback method associated with Socket.AcceptAsync
- // operations and is invoked when an accept operation is complete
- //
- private static void OnAccept(object sender, SocketAsyncEventArgs e)
- {
- ProcessAccept(e);
- }
-
- private static async void ProcessAccept(SocketAsyncEventArgs args)
- {
- var epl = (HttpEndPointListener)args.UserToken;
-
- if (epl._closed)
- {
- return;
- }
-
- // http://msdn.microsoft.com/en-us/library/system.net.sockets.acceptSocket.acceptasync%28v=vs.110%29.aspx
- // Under certain conditions ConnectionReset can occur
- // Need to attept to re-accept
- var socketError = args.SocketError;
- var accepted = args.AcceptSocket;
-
- epl.Accept(args);
-
- if (socketError == SocketError.ConnectionReset)
- {
- epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept.");
- return;
- }
-
- if (accepted == null)
- {
- return;
- }
-
- if (epl._secure && epl._cert == null)
- {
- TryClose(accepted);
- return;
- }
-
- try
- {
- var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString();
- var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString();
- //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
-
- var conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._fileSystem, epl._environment);
-
- await conn.Init().ConfigureAwait(false);
-
- //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
- lock (epl._unregisteredConnections)
- {
- epl._unregisteredConnections[conn] = conn;
- }
- conn.BeginReadRequest();
- }
- catch (Exception ex)
- {
- epl._logger.LogError(ex, "Error in ProcessAccept");
-
- TryClose(accepted);
- epl.Accept();
- return;
- }
- }
-
- private Socket CreateSocket(AddressFamily addressFamily, bool dualMode)
- {
- try
- {
- var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
-
- if (dualMode)
- {
- socket.DualMode = true;
- }
-
- return socket;
- }
- catch (SocketException ex)
- {
- throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
- }
- catch (ArgumentException ex)
- {
- if (dualMode)
- {
- // Mono for BSD incorrectly throws ArgumentException instead of SocketException
- throw new SocketCreateException("AddressFamilyNotSupported", ex);
- }
- else
- {
- throw;
- }
- }
- }
-
- internal void RemoveConnection(HttpConnection conn)
- {
- lock (_unregisteredConnections)
- {
- _unregisteredConnections.Remove(conn);
- }
- }
-
- public bool BindContext(HttpListenerContext context)
- {
- var req = context.Request;
- HttpListener listener = SearchListener(req.Url, out var prefix);
- if (listener == null)
- return false;
-
- context.Connection.Prefix = prefix;
- return true;
- }
-
- public void UnbindContext(HttpListenerContext context)
- {
- if (context == null || context.Request == null)
- return;
-
- _listener.UnregisterContext(context);
- }
-
- private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
- {
- prefix = null;
- if (uri == null)
- return null;
-
- string host = uri.Host;
- int port = uri.Port;
- string path = WebUtility.UrlDecode(uri.AbsolutePath);
- string pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
-
- HttpListener bestMatch = null;
- int bestLength = -1;
-
- if (host != null && host != "")
- {
- Dictionary<ListenerPrefix, HttpListener> localPrefixes = _prefixes;
- foreach (var p in localPrefixes.Keys)
- {
- string ppath = p.Path;
- if (ppath.Length < bestLength)
- continue;
-
- if (p.Host != host || p.Port != port)
- continue;
-
- if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
- {
- bestLength = ppath.Length;
- bestMatch = localPrefixes[p];
- prefix = p;
- }
- }
- if (bestLength != -1)
- return bestMatch;
- }
-
- List<ListenerPrefix> list = _unhandledPrefixes;
- bestMatch = MatchFromList(host, path, list, out prefix);
-
- if (path != pathSlash && bestMatch == null)
- bestMatch = MatchFromList(host, pathSlash, list, out prefix);
-
- if (bestMatch != null)
- return bestMatch;
-
- list = _allPrefixes;
- bestMatch = MatchFromList(host, path, list, out prefix);
-
- if (path != pathSlash && bestMatch == null)
- bestMatch = MatchFromList(host, pathSlash, list, out prefix);
-
- if (bestMatch != null)
- return bestMatch;
-
- return null;
- }
-
- private HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
- {
- prefix = null;
- if (list == null)
- return null;
-
- HttpListener bestMatch = null;
- int bestLength = -1;
-
- foreach (ListenerPrefix p in list)
- {
- string ppath = p.Path;
- if (ppath.Length < bestLength)
- continue;
-
- if (path.StartsWith(ppath))
- {
- bestLength = ppath.Length;
- bestMatch = p._listener;
- prefix = p;
- }
- }
-
- return bestMatch;
- }
-
- private void AddSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
- {
- if (list == null)
- return;
-
- foreach (ListenerPrefix p in list)
- {
- if (p.Path == prefix.Path)
- throw new Exception("net_listener_already");
- }
- list.Add(prefix);
- }
-
- private bool RemoveSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
- {
- if (list == null)
- return false;
-
- int c = list.Count;
- for (int i = 0; i < c; i++)
- {
- ListenerPrefix p = list[i];
- if (p.Path == prefix.Path)
- {
- list.RemoveAt(i);
- return true;
- }
- }
- return false;
- }
-
- private void CheckIfRemove()
- {
- if (_prefixes.Count > 0)
- return;
-
- List<ListenerPrefix> list = _unhandledPrefixes;
- if (list != null && list.Count > 0)
- return;
-
- list = _allPrefixes;
- if (list != null && list.Count > 0)
- return;
-
- HttpEndPointManager.RemoveEndPoint(this, _endpoint);
- }
-
- public void Close()
- {
- _closed = true;
- _socket.Close();
- lock (_unregisteredConnections)
- {
- // Clone the list because RemoveConnection can be called from Close
- var connections = new List<HttpConnection>(_unregisteredConnections.Keys);
-
- foreach (HttpConnection c in connections)
- c.Close(true);
- _unregisteredConnections.Clear();
- }
- }
-
- public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
- {
- List<ListenerPrefix> current;
- List<ListenerPrefix> future;
- if (prefix.Host == "*")
- {
- do
- {
- current = _unhandledPrefixes;
- future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
- prefix._listener = listener;
- AddSpecial(future, prefix);
- } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
- return;
- }
-
- if (prefix.Host == "+")
- {
- do
- {
- current = _allPrefixes;
- future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
- prefix._listener = listener;
- AddSpecial(future, prefix);
- } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
- return;
- }
-
- Dictionary<ListenerPrefix, HttpListener> prefs, p2;
- do
- {
- prefs = _prefixes;
- if (prefs.ContainsKey(prefix))
- {
- throw new Exception("net_listener_already");
- }
- p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
- p2[prefix] = listener;
- } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
- }
-
- public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
- {
- List<ListenerPrefix> current;
- List<ListenerPrefix> future;
- if (prefix.Host == "*")
- {
- do
- {
- current = _unhandledPrefixes;
- future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
- if (!RemoveSpecial(future, prefix))
- break; // Prefix not found
- } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
-
- CheckIfRemove();
- return;
- }
-
- if (prefix.Host == "+")
- {
- do
- {
- current = _allPrefixes;
- future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
- if (!RemoveSpecial(future, prefix))
- break; // Prefix not found
- } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
- CheckIfRemove();
- return;
- }
-
- Dictionary<ListenerPrefix, HttpListener> prefs, p2;
- do
- {
- prefs = _prefixes;
- if (!prefs.ContainsKey(prefix))
- break;
-
- p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
- p2.Remove(prefix);
- } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
- CheckIfRemove();
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpEndPointManager.cs b/SocketHttpListener/Net/HttpEndPointManager.cs
deleted file mode 100644
index 27b4244a6..000000000
--- a/SocketHttpListener/Net/HttpEndPointManager.cs
+++ /dev/null
@@ -1,192 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Net;
-using System.Net.Sockets;
-using Microsoft.Extensions.Logging;
-
-namespace SocketHttpListener.Net
-{
- internal sealed class HttpEndPointManager
- {
- private static Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>> s_ipEndPoints = new Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>>();
-
- private HttpEndPointManager()
- {
- }
-
- public static void AddListener(ILogger logger, HttpListener listener)
- {
- var added = new List<string>();
- try
- {
- lock ((s_ipEndPoints as ICollection).SyncRoot)
- {
- foreach (string prefix in listener.Prefixes)
- {
- AddPrefixInternal(logger, prefix, listener);
- added.Add(prefix);
- }
- }
- }
- catch
- {
- foreach (string prefix in added)
- {
- RemovePrefix(logger, prefix, listener);
- }
- throw;
- }
- }
-
- public static void AddPrefix(ILogger logger, string prefix, HttpListener listener)
- {
- lock ((s_ipEndPoints as ICollection).SyncRoot)
- {
- AddPrefixInternal(logger, prefix, listener);
- }
- }
-
- private static void AddPrefixInternal(ILogger logger, string p, HttpListener listener)
- {
- int start = p.IndexOf(':') + 3;
- int colon = p.IndexOf(':', start);
- if (colon != -1)
- {
- // root can't be -1 here, since we've already checked for ending '/' in ListenerPrefix.
- int root = p.IndexOf('/', colon, p.Length - colon);
- string portString = p.Substring(colon + 1, root - colon - 1);
-
- if (!int.TryParse(portString, out var port) || port <= 0 || port >= 65536)
- {
- throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_port");
- }
- }
-
- var lp = new ListenerPrefix(p);
- if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown)
- throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_listener_host");
-
- if (lp.Path.IndexOf('%') != -1)
- throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
-
- if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
- throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
-
- // listens on all the interfaces if host name cannot be parsed by IPAddress.
- HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
- epl.AddPrefix(lp, listener);
- }
-
- private static IPAddress GetIpAnyAddress(HttpListener listener)
- {
- return listener.EnableDualMode ? IPAddress.IPv6Any : IPAddress.Any;
- }
-
- private static HttpEndPointListener GetEPListener(ILogger logger, string host, int port, HttpListener listener, bool secure)
- {
- IPAddress addr;
- if (host == "*" || host == "+")
- {
- addr = GetIpAnyAddress(listener);
- }
- else
- {
- const int NotSupportedErrorCode = 50;
- try
- {
- addr = Dns.GetHostAddresses(host)[0];
- }
- catch
- {
- // Throw same error code as windows, request is not supported.
- throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
- }
-
- if (IPAddress.Any.Equals(addr))
- {
- // Don't support listening to 0.0.0.0, match windows behavior.
- throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
- }
- }
-
- Dictionary<int, HttpEndPointListener> p = null;
- if (s_ipEndPoints.ContainsKey(addr))
- {
- p = s_ipEndPoints[addr];
- }
- else
- {
- p = new Dictionary<int, HttpEndPointListener>();
- s_ipEndPoints[addr] = p;
- }
-
- HttpEndPointListener epl = null;
- if (p.ContainsKey(port))
- {
- epl = p[port];
- }
- else
- {
- try
- {
- epl = new HttpEndPointListener(listener, addr, port, secure, listener.Certificate, logger, listener.CryptoProvider, listener.SocketFactory, listener.StreamHelper, listener.FileSystem, listener.EnvironmentInfo);
- }
- catch (SocketException ex)
- {
- throw new HttpListenerException(ex.ErrorCode, ex.Message);
- }
- p[port] = epl;
- }
-
- return epl;
- }
-
- public static void RemoveEndPoint(HttpEndPointListener epl, IPEndPoint ep)
- {
- lock ((s_ipEndPoints as ICollection).SyncRoot)
- {
- Dictionary<int, HttpEndPointListener> p = null;
- p = s_ipEndPoints[ep.Address];
- p.Remove(ep.Port);
- if (p.Count == 0)
- {
- s_ipEndPoints.Remove(ep.Address);
- }
- epl.Close();
- }
- }
-
- public static void RemoveListener(ILogger logger, HttpListener listener)
- {
- lock ((s_ipEndPoints as ICollection).SyncRoot)
- {
- foreach (string prefix in listener.Prefixes)
- {
- RemovePrefixInternal(logger, prefix, listener);
- }
- }
- }
-
- public static void RemovePrefix(ILogger logger, string prefix, HttpListener listener)
- {
- lock ((s_ipEndPoints as ICollection).SyncRoot)
- {
- RemovePrefixInternal(logger, prefix, listener);
- }
- }
-
- private static void RemovePrefixInternal(ILogger logger, string prefix, HttpListener listener)
- {
- var lp = new ListenerPrefix(prefix);
- if (lp.Path.IndexOf('%') != -1)
- return;
-
- if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
- return;
-
- HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
- epl.RemovePrefix(lp, listener);
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpKnownHeaderNames.cs b/SocketHttpListener/Net/HttpKnownHeaderNames.cs
deleted file mode 100644
index dc6f2ce41..000000000
--- a/SocketHttpListener/Net/HttpKnownHeaderNames.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal static partial class HttpKnownHeaderNames
- {
- // When adding a new constant, add it to HttpKnownHeaderNames.TryGetHeaderName.cs as well.
-
- public const string Accept = "Accept";
- public const string AcceptCharset = "Accept-Charset";
- public const string AcceptEncoding = "Accept-Encoding";
- public const string AcceptLanguage = "Accept-Language";
- public const string AcceptPatch = "Accept-Patch";
- public const string AcceptRanges = "Accept-Ranges";
- public const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
- public const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
- public const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
- public const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
- public const string AccessControlExposeHeaders = "Access-Control-Expose-Headers";
- public const string AccessControlMaxAge = "Access-Control-Max-Age";
- public const string Age = "Age";
- public const string Allow = "Allow";
- public const string AltSvc = "Alt-Svc";
- public const string Authorization = "Authorization";
- public const string CacheControl = "Cache-Control";
- public const string Connection = "Connection";
- public const string ContentDisposition = "Content-Disposition";
- public const string ContentEncoding = "Content-Encoding";
- public const string ContentLanguage = "Content-Language";
- public const string ContentLength = "Content-Length";
- public const string ContentLocation = "Content-Location";
- public const string ContentMD5 = "Content-MD5";
- public const string ContentRange = "Content-Range";
- public const string ContentSecurityPolicy = "Content-Security-Policy";
- public const string ContentType = "Content-Type";
- public const string Cookie = "Cookie";
- public const string Cookie2 = "Cookie2";
- public const string Date = "Date";
- public const string ETag = "ETag";
- public const string Expect = "Expect";
- public const string Expires = "Expires";
- public const string From = "From";
- public const string Host = "Host";
- public const string IfMatch = "If-Match";
- public const string IfModifiedSince = "If-Modified-Since";
- public const string IfNoneMatch = "If-None-Match";
- public const string IfRange = "If-Range";
- public const string IfUnmodifiedSince = "If-Unmodified-Since";
- public const string KeepAlive = "Keep-Alive";
- public const string LastModified = "Last-Modified";
- public const string Link = "Link";
- public const string Location = "Location";
- public const string MaxForwards = "Max-Forwards";
- public const string Origin = "Origin";
- public const string P3P = "P3P";
- public const string Pragma = "Pragma";
- public const string ProxyAuthenticate = "Proxy-Authenticate";
- public const string ProxyAuthorization = "Proxy-Authorization";
- public const string ProxyConnection = "Proxy-Connection";
- public const string PublicKeyPins = "Public-Key-Pins";
- public const string Range = "Range";
- public const string Referer = "Referer"; // NB: The spelling-mistake "Referer" for "Referrer" must be matched.
- public const string RetryAfter = "Retry-After";
- public const string SecWebSocketAccept = "Sec-WebSocket-Accept";
- public const string SecWebSocketExtensions = "Sec-WebSocket-Extensions";
- public const string SecWebSocketKey = "Sec-WebSocket-Key";
- public const string SecWebSocketProtocol = "Sec-WebSocket-Protocol";
- public const string SecWebSocketVersion = "Sec-WebSocket-Version";
- public const string Server = "Server";
- public const string SetCookie = "Set-Cookie";
- public const string SetCookie2 = "Set-Cookie2";
- public const string StrictTransportSecurity = "Strict-Transport-Security";
- public const string TE = "TE";
- public const string TSV = "TSV";
- public const string Trailer = "Trailer";
- public const string TransferEncoding = "Transfer-Encoding";
- public const string Upgrade = "Upgrade";
- public const string UpgradeInsecureRequests = "Upgrade-Insecure-Requests";
- public const string UserAgent = "User-Agent";
- public const string Vary = "Vary";
- public const string Via = "Via";
- public const string WWWAuthenticate = "WWW-Authenticate";
- public const string Warning = "Warning";
- public const string XAspNetVersion = "X-AspNet-Version";
- public const string XContentDuration = "X-Content-Duration";
- public const string XContentTypeOptions = "X-Content-Type-Options";
- public const string XFrameOptions = "X-Frame-Options";
- public const string XMSEdgeRef = "X-MSEdge-Ref";
- public const string XPoweredBy = "X-Powered-By";
- public const string XRequestID = "X-Request-ID";
- public const string XUACompatible = "X-UA-Compatible";
- }
-}
diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs
deleted file mode 100644
index f17036a21..000000000
--- a/SocketHttpListener/Net/HttpListener.cs
+++ /dev/null
@@ -1,284 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Net;
-using System.Security.Cryptography.X509Certificates;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace SocketHttpListener.Net
-{
- public sealed class HttpListener : IDisposable
- {
- internal ICryptoProvider CryptoProvider { get; private set; }
- internal ISocketFactory SocketFactory { get; private set; }
- internal IFileSystem FileSystem { get; private set; }
- internal IStreamHelper StreamHelper { get; private set; }
- internal IEnvironmentInfo EnvironmentInfo { get; private set; }
-
- public bool EnableDualMode { get; set; }
-
- private AuthenticationSchemes auth_schemes;
- private HttpListenerPrefixCollection prefixes;
- private AuthenticationSchemeSelector auth_selector;
- private string realm;
- private bool unsafe_ntlm_auth;
- private bool listening;
- private bool disposed;
-
- private Dictionary<HttpListenerContext, HttpListenerContext> registry;
- private Dictionary<HttpConnection, HttpConnection> connections;
- private ILogger _logger;
- private X509Certificate _certificate;
-
- public Action<HttpListenerContext> OnContext { get; set; }
-
- public HttpListener(
- ILogger logger,
- ICryptoProvider cryptoProvider,
- ISocketFactory socketFactory,
- IStreamHelper streamHelper,
- IFileSystem fileSystem,
- IEnvironmentInfo environmentInfo)
- {
- _logger = logger;
- CryptoProvider = cryptoProvider;
- SocketFactory = socketFactory;
- StreamHelper = streamHelper;
- FileSystem = fileSystem;
- EnvironmentInfo = environmentInfo;
-
- prefixes = new HttpListenerPrefixCollection(logger, this);
- registry = new Dictionary<HttpListenerContext, HttpListenerContext>();
- connections = new Dictionary<HttpConnection, HttpConnection>();
- auth_schemes = AuthenticationSchemes.Anonymous;
- }
-
- public HttpListener(
- ILogger logger,
- X509Certificate certificate,
- ICryptoProvider cryptoProvider,
- ISocketFactory socketFactory,
- IStreamHelper streamHelper,
- IFileSystem fileSystem,
- IEnvironmentInfo environmentInfo)
- : this(logger, cryptoProvider, socketFactory, streamHelper, fileSystem, environmentInfo)
- {
- _certificate = certificate;
- }
-
- public void LoadCert(X509Certificate cert)
- {
- _certificate = cert;
- }
-
- // TODO: Digest, NTLM and Negotiate require ControlPrincipal
- public AuthenticationSchemes AuthenticationSchemes
- {
- get => auth_schemes;
- set
- {
- CheckDisposed();
- auth_schemes = value;
- }
- }
-
- public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate
- {
- get => auth_selector;
- set
- {
- CheckDisposed();
- auth_selector = value;
- }
- }
-
- public bool IsListening => listening;
-
- public static bool IsSupported => true;
-
- public HttpListenerPrefixCollection Prefixes
- {
- get
- {
- CheckDisposed();
- return prefixes;
- }
- }
-
- // TODO: use this
- public string Realm
- {
- get => realm;
- set
- {
- CheckDisposed();
- realm = value;
- }
- }
-
- public bool UnsafeConnectionNtlmAuthentication
- {
- get => unsafe_ntlm_auth;
- set
- {
- CheckDisposed();
- unsafe_ntlm_auth = value;
- }
- }
-
- //internal IMonoSslStream CreateSslStream(Stream innerStream, bool ownsStream, MSI.MonoRemoteCertificateValidationCallback callback)
- //{
- // lock (registry)
- // {
- // if (tlsProvider == null)
- // tlsProvider = MonoTlsProviderFactory.GetProviderInternal();
- // if (tlsSettings == null)
- // tlsSettings = MSI.MonoTlsSettings.CopyDefaultSettings();
- // if (tlsSettings.RemoteCertificateValidationCallback == null)
- // tlsSettings.RemoteCertificateValidationCallback = callback;
- // return tlsProvider.CreateSslStream(innerStream, ownsStream, tlsSettings);
- // }
- //}
-
- internal X509Certificate Certificate => _certificate;
-
- public void Abort()
- {
- if (disposed)
- return;
-
- if (!listening)
- {
- return;
- }
-
- Close(true);
- }
-
- public void Close()
- {
- if (disposed)
- return;
-
- if (!listening)
- {
- disposed = true;
- return;
- }
-
- Close(true);
- disposed = true;
- }
-
- void Close(bool force)
- {
- CheckDisposed();
- HttpEndPointManager.RemoveListener(_logger, this);
- Cleanup(force);
- }
-
- void Cleanup(bool close_existing)
- {
- lock (registry)
- {
- if (close_existing)
- {
- // Need to copy this since closing will call UnregisterContext
- ICollection keys = registry.Keys;
- var all = new HttpListenerContext[keys.Count];
- keys.CopyTo(all, 0);
- registry.Clear();
- for (int i = all.Length - 1; i >= 0; i--)
- all[i].Connection.Close(true);
- }
-
- lock (connections)
- {
- ICollection keys = connections.Keys;
- var conns = new HttpConnection[keys.Count];
- keys.CopyTo(conns, 0);
- connections.Clear();
- for (int i = conns.Length - 1; i >= 0; i--)
- conns[i].Close(true);
- }
- }
- }
-
- internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context)
- {
- if (AuthenticationSchemeSelectorDelegate != null)
- return AuthenticationSchemeSelectorDelegate(context.Request);
- else
- return auth_schemes;
- }
-
- public void Start()
- {
- CheckDisposed();
- if (listening)
- return;
-
- HttpEndPointManager.AddListener(_logger, this);
- listening = true;
- }
-
- public void Stop()
- {
- CheckDisposed();
- listening = false;
- Close(false);
- }
-
- void IDisposable.Dispose()
- {
- if (disposed)
- return;
-
- Close(true); //TODO: Should we force here or not?
- disposed = true;
- }
-
- internal void CheckDisposed()
- {
- if (disposed)
- throw new ObjectDisposedException(GetType().Name);
- }
-
- internal void RegisterContext(HttpListenerContext context)
- {
- if (OnContext != null && IsListening)
- {
- OnContext(context);
- }
-
- lock (registry)
- registry[context] = context;
- }
-
- internal void UnregisterContext(HttpListenerContext context)
- {
- lock (registry)
- registry.Remove(context);
- }
-
- internal void AddConnection(HttpConnection cnc)
- {
- lock (connections)
- {
- connections[cnc] = cnc;
- }
- }
-
- internal void RemoveConnection(HttpConnection cnc)
- {
- lock (connections)
- {
- connections.Remove(cnc);
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerBasicIdentity.cs b/SocketHttpListener/Net/HttpListenerBasicIdentity.cs
deleted file mode 100644
index 5f6ec44b9..000000000
--- a/SocketHttpListener/Net/HttpListenerBasicIdentity.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System.Security.Principal;
-
-namespace SocketHttpListener.Net
-{
- public class HttpListenerBasicIdentity : GenericIdentity
- {
- string password;
-
- public HttpListenerBasicIdentity(string username, string password)
- : base(username, "Basic")
- {
- this.password = password;
- }
-
- public virtual string Password => password;
- }
-
- public class GenericIdentity : IIdentity
- {
- private string m_name;
- private string m_type;
-
- public GenericIdentity(string name)
- {
- if (name == null)
- throw new System.ArgumentNullException(nameof(name));
-
- m_name = name;
- m_type = "";
- }
-
- public GenericIdentity(string name, string type)
- {
- if (name == null)
- throw new System.ArgumentNullException(nameof(name));
- if (type == null)
- throw new System.ArgumentNullException(nameof(type));
-
- m_name = name;
- m_type = type;
- }
-
- public virtual string Name => m_name;
-
- public virtual string AuthenticationType => m_type;
-
- public virtual bool IsAuthenticated => !m_name.Equals("");
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerContext.Managed.cs b/SocketHttpListener/Net/HttpListenerContext.Managed.cs
deleted file mode 100644
index 79742bf37..000000000
--- a/SocketHttpListener/Net/HttpListenerContext.Managed.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Security.Principal;
-using System.Text;
-using System.Threading.Tasks;
-using SocketHttpListener.Net.WebSockets;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerContext
- {
- private HttpConnection _connection;
-
- internal HttpListenerContext(HttpConnection connection)
- {
- _connection = connection;
- _response = new HttpListenerResponse(this);
- Request = new HttpListenerRequest(this);
- ErrorStatus = 400;
- }
-
- internal int ErrorStatus { get; set; }
-
- internal string ErrorMessage { get; set; }
-
- internal bool HaveError => ErrorMessage != null;
-
- internal HttpConnection Connection => _connection;
-
- internal void ParseAuthentication(System.Net.AuthenticationSchemes expectedSchemes)
- {
- if (expectedSchemes == System.Net.AuthenticationSchemes.Anonymous)
- return;
-
- string header = Request.Headers["Authorization"];
- if (string.IsNullOrEmpty(header))
- return;
-
- if (IsBasicHeader(header))
- {
- _user = ParseBasicAuthentication(header.Substring(AuthenticationTypes.Basic.Length + 1));
- }
- }
-
- internal IPrincipal ParseBasicAuthentication(string authData) =>
- TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string username, out string password) ?
- new GenericPrincipal(new HttpListenerBasicIdentity(username, password), Array.Empty<string>()) :
- null;
-
- internal static bool IsBasicHeader(string header) =>
- header.Length >= 6 &&
- header[5] == ' ' &&
- string.Compare(header, 0, AuthenticationTypes.Basic, 0, 5, StringComparison.OrdinalIgnoreCase) == 0;
-
- internal static bool TryParseBasicAuth(string headerValue, out HttpStatusCode errorCode, out string username, out string password)
- {
- errorCode = HttpStatusCode.OK;
- username = password = null;
- try
- {
- if (string.IsNullOrWhiteSpace(headerValue))
- {
- return false;
- }
-
- string authString = Encoding.UTF8.GetString(Convert.FromBase64String(headerValue));
- int colonPos = authString.IndexOf(':');
- if (colonPos < 0)
- {
- // username must be at least 1 char
- errorCode = HttpStatusCode.BadRequest;
- return false;
- }
-
- username = authString.Substring(0, colonPos);
- password = authString.Substring(colonPos + 1);
- return true;
- }
- catch
- {
- errorCode = HttpStatusCode.InternalServerError;
- return false;
- }
- }
-
- public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
- {
- return HttpWebSocket.AcceptWebSocketAsyncCore(this, subProtocol, receiveBufferSize, keepAliveInterval);
- }
-
- [EditorBrowsable(EditorBrowsableState.Never)]
- public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer)
- {
- WebSocketValidate.ValidateArraySegment(internalBuffer, nameof(internalBuffer));
- HttpWebSocket.ValidateOptions(subProtocol, receiveBufferSize, HttpWebSocket.MinSendBufferSize, keepAliveInterval);
- return HttpWebSocket.AcceptWebSocketAsyncCore(this, subProtocol, receiveBufferSize, keepAliveInterval, internalBuffer);
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerContext.cs b/SocketHttpListener/Net/HttpListenerContext.cs
deleted file mode 100644
index d84e2d1aa..000000000
--- a/SocketHttpListener/Net/HttpListenerContext.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using System;
-using System.Net;
-using System.Security.Principal;
-using System.Threading.Tasks;
-using SocketHttpListener.Net.WebSockets;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerContext
- {
- private HttpListenerResponse _response;
- private IPrincipal _user;
-
- public HttpListenerRequest Request { get; }
-
- public IPrincipal User => _user;
-
- // This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate.
- internal AuthenticationSchemes AuthenticationSchemes { get; set; }
-
- public HttpListenerResponse Response => _response;
-
- public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol)
- {
- return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, WebSocket.DefaultKeepAliveInterval);
- }
-
- public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string subProtocol, TimeSpan keepAliveInterval)
- {
- return AcceptWebSocketAsync(subProtocol, HttpWebSocket.DefaultReceiveBufferSize, keepAliveInterval);
- }
- }
-
- public class GenericPrincipal : IPrincipal
- {
- private IIdentity m_identity;
- private string[] m_roles;
-
- public GenericPrincipal(IIdentity identity, string[] roles)
- {
- if (identity == null)
- throw new ArgumentNullException(nameof(identity));
-
- m_identity = identity;
- if (roles != null)
- {
- m_roles = new string[roles.Length];
- for (int i = 0; i < roles.Length; ++i)
- {
- m_roles[i] = roles[i];
- }
- }
- else
- {
- m_roles = null;
- }
- }
-
- public virtual IIdentity Identity => m_identity;
-
- public virtual bool IsInRole(string role)
- {
- if (role == null || m_roles == null)
- return false;
-
- for (int i = 0; i < m_roles.Length; ++i)
- {
- if (m_roles[i] != null && string.Compare(m_roles[i], role, StringComparison.OrdinalIgnoreCase) == 0)
- return true;
- }
- return false;
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs
deleted file mode 100644
index 400a1adb6..000000000
--- a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using Microsoft.Extensions.Logging;
-
-namespace SocketHttpListener.Net
-{
- public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable
- {
- private List<string> _prefixes = new List<string>();
- private HttpListener _listener;
-
- private ILogger _logger;
-
- internal HttpListenerPrefixCollection(ILogger logger, HttpListener listener)
- {
- _logger = logger;
- _listener = listener;
- }
-
- public int Count => _prefixes.Count;
-
- public bool IsReadOnly => false;
-
- public bool IsSynchronized => false;
-
- public void Add(string uriPrefix)
- {
- _listener.CheckDisposed();
- //ListenerPrefix.CheckUri(uriPrefix);
- if (_prefixes.Contains(uriPrefix))
- {
- return;
- }
-
- _prefixes.Add(uriPrefix);
- if (_listener.IsListening)
- {
- HttpEndPointManager.AddPrefix(_logger, uriPrefix, _listener);
- }
- }
-
- public void AddRange(IEnumerable<string> uriPrefixes)
- {
- _listener.CheckDisposed();
-
- foreach (var uriPrefix in uriPrefixes)
- {
- if (_prefixes.Contains(uriPrefix))
- {
- continue;
- }
-
- _prefixes.Add(uriPrefix);
- if (_listener.IsListening)
- {
- HttpEndPointManager.AddPrefix(_logger, uriPrefix, _listener);
- }
- }
- }
-
- public void Clear()
- {
- _listener.CheckDisposed();
- _prefixes.Clear();
- if (_listener.IsListening)
- {
- HttpEndPointManager.RemoveListener(_logger, _listener);
- }
- }
-
- public bool Contains(string uriPrefix)
- {
- _listener.CheckDisposed();
- return _prefixes.Contains(uriPrefix);
- }
-
- public void CopyTo(string[] array, int offset)
- {
- _listener.CheckDisposed();
- _prefixes.CopyTo(array, offset);
- }
-
- public void CopyTo(Array array, int offset)
- {
- _listener.CheckDisposed();
- ((ICollection)_prefixes).CopyTo(array, offset);
- }
-
- public IEnumerator<string> GetEnumerator()
- {
- return _prefixes.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return _prefixes.GetEnumerator();
- }
-
- public bool Remove(string uriPrefix)
- {
- _listener.CheckDisposed();
- if (uriPrefix == null)
- {
- throw new ArgumentNullException(nameof(uriPrefix));
- }
-
- bool result = _prefixes.Remove(uriPrefix);
- if (result && _listener.IsListening)
- {
- HttpEndPointManager.RemovePrefix(_logger, uriPrefix, _listener);
- }
-
- return result;
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerRequest.Managed.cs b/SocketHttpListener/Net/HttpListenerRequest.Managed.cs
deleted file mode 100644
index 3f9e32f08..000000000
--- a/SocketHttpListener/Net/HttpListenerRequest.Managed.cs
+++ /dev/null
@@ -1,325 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-using MediaBrowser.Model.Services;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerRequest
- {
- private long _contentLength;
- private bool _clSet;
- private WebHeaderCollection _headers;
- private string _method;
- private Stream _inputStream;
- private HttpListenerContext _context;
- private bool _isChunked;
-
- private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
-
- internal HttpListenerRequest(HttpListenerContext context)
- {
- _context = context;
- _headers = new WebHeaderCollection();
- _version = HttpVersion.Version10;
- }
-
- private static readonly char[] s_separators = new char[] { ' ' };
-
- internal void SetRequestLine(string req)
- {
- string[] parts = req.Split(s_separators, 3);
- if (parts.Length != 3)
- {
- _context.ErrorMessage = "Invalid request line (parts).";
- return;
- }
-
- _method = parts[0];
- foreach (char c in _method)
- {
- int ic = (int)c;
-
- if ((ic >= 'A' && ic <= 'Z') ||
- (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
- c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
- c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
- c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
- continue;
-
- _context.ErrorMessage = "(Invalid verb)";
- return;
- }
-
- _rawUrl = parts[1];
- if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
- {
- _context.ErrorMessage = "Invalid request line (version).";
- return;
- }
-
- try
- {
- _version = new Version(parts[2].Substring(5));
- }
- catch
- {
- _context.ErrorMessage = "Invalid request line (version).";
- return;
- }
-
- if (_version.Major < 1)
- {
- _context.ErrorMessage = "Invalid request line (version).";
- return;
- }
- if (_version.Major > 1)
- {
- _context.ErrorStatus = (int)HttpStatusCode.HttpVersionNotSupported;
- _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.HttpVersionNotSupported);
- return;
- }
- }
-
- private static bool MaybeUri(string s)
- {
- int p = s.IndexOf(':');
- if (p == -1)
- return false;
-
- if (p >= 10)
- return false;
-
- return IsPredefinedScheme(s.Substring(0, p));
- }
-
- private static bool IsPredefinedScheme(string scheme)
- {
- if (scheme == null || scheme.Length < 3)
- return false;
-
- char c = scheme[0];
- if (c == 'h')
- return (scheme == UriScheme.Http || scheme == UriScheme.Https);
- if (c == 'f')
- return (scheme == UriScheme.File || scheme == UriScheme.Ftp);
-
- if (c == 'n')
- {
- c = scheme[1];
- if (c == 'e')
- return (scheme == UriScheme.News || scheme == UriScheme.NetPipe || scheme == UriScheme.NetTcp);
- if (scheme == UriScheme.Nntp)
- return true;
- return false;
- }
- if ((c == 'g' && scheme == UriScheme.Gopher) || (c == 'm' && scheme == UriScheme.Mailto))
- return true;
-
- return false;
- }
-
- internal void FinishInitialization()
- {
- string host = UserHostName;
- if (_version > HttpVersion.Version10 && (host == null || host.Length == 0))
- {
- _context.ErrorMessage = "Invalid host name";
- return;
- }
-
- string path;
- Uri raw_uri = null;
- if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri))
- path = raw_uri.PathAndQuery;
- else
- path = _rawUrl;
-
- if ((host == null || host.Length == 0))
- host = UserHostAddress;
-
- if (raw_uri != null)
- host = raw_uri.Host;
-
- int colon = host.IndexOf(']') == -1 ? host.IndexOf(':') : host.LastIndexOf(':');
- if (colon >= 0)
- host = host.Substring(0, colon);
-
- string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint.Port);
-
- if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _requestUri))
- {
- _context.ErrorMessage = System.Net.WebUtility.HtmlEncode("Invalid url: " + base_uri + path);
- return;
- }
-
- _requestUri = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _requestUri.Scheme,
- _requestUri.Authority, _requestUri.LocalPath, _requestUri.Query);
-
- if (_version >= HttpVersion.Version11)
- {
- string t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding];
- _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
- // 'identity' is not valid!
- if (t_encoding != null && !_isChunked)
- {
- _context.Connection.SendError(null, 501);
- return;
- }
- }
-
- if (!_isChunked && !_clSet)
- {
- if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase))
- {
- _context.Connection.SendError(null, 411);
- return;
- }
- }
-
- if (string.Compare(Headers[HttpKnownHeaderNames.Expect], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
- {
- HttpResponseStream output = _context.Connection.GetResponseStream();
- output.InternalWrite(s_100continue, 0, s_100continue.Length);
- }
- }
-
- internal static string Unquote(string str)
- {
- int start = str.IndexOf('\"');
- int end = str.LastIndexOf('\"');
- if (start >= 0 && end >= 0)
- str = str.Substring(start + 1, end - 1);
- return str.Trim();
- }
-
- internal void AddHeader(string header)
- {
- int colon = header.IndexOf(':');
- if (colon == -1 || colon == 0)
- {
- _context.ErrorMessage = HttpStatusDescription.Get(400);
- _context.ErrorStatus = 400;
- return;
- }
-
- string name = header.Substring(0, colon).Trim();
- string val = header.Substring(colon + 1).Trim();
- if (name.Equals("content-length", StringComparison.OrdinalIgnoreCase))
- {
- // To match Windows behavior:
- // Content lengths >= 0 and <= long.MaxValue are accepted as is.
- // Content lengths > long.MaxValue and <= ulong.MaxValue are treated as 0.
- // Content lengths < 0 cause the requests to fail.
- // Other input is a failure, too.
- long parsedContentLength =
- ulong.TryParse(val, out ulong parsedUlongContentLength) ? (parsedUlongContentLength <= long.MaxValue ? (long)parsedUlongContentLength : 0) :
- long.Parse(val);
- if (parsedContentLength < 0 || (_clSet && parsedContentLength != _contentLength))
- {
- _context.ErrorMessage = "Invalid Content-Length.";
- }
- else
- {
- _contentLength = parsedContentLength;
- _clSet = true;
- }
- }
- else if (name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase))
- {
- if (Headers[HttpKnownHeaderNames.TransferEncoding] != null)
- {
- _context.ErrorStatus = (int)HttpStatusCode.NotImplemented;
- _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.NotImplemented);
- }
- }
-
- if (_context.ErrorMessage == null)
- {
- _headers.Set(name, val);
- }
- }
-
- // returns true is the stream could be reused.
- internal bool FlushInput()
- {
- if (!HasEntityBody)
- return true;
-
- int length = 2048;
- if (_contentLength > 0)
- length = (int)Math.Min(_contentLength, (long)length);
-
- byte[] bytes = new byte[length];
- while (true)
- {
- try
- {
- IAsyncResult ares = InputStream.BeginRead(bytes, 0, length, null, null);
- if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(1000))
- return false;
- if (InputStream.EndRead(ares) <= 0)
- return true;
- }
- catch (ObjectDisposedException)
- {
- _inputStream = null;
- return true;
- }
- catch
- {
- return false;
- }
- }
- }
-
- public long ContentLength64
- {
- get
- {
- if (_isChunked)
- _contentLength = -1;
-
- return _contentLength;
- }
- }
-
- public bool HasEntityBody => (_contentLength > 0 || _isChunked);
-
- public QueryParamCollection Headers => _headers;
-
- public string HttpMethod => _method;
-
- public Stream InputStream
- {
- get
- {
- if (_inputStream == null)
- {
- if (_isChunked || _contentLength > 0)
- _inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength);
- else
- _inputStream = Stream.Null;
- }
-
- return _inputStream;
- }
- }
-
- public bool IsAuthenticated => false;
-
- public bool IsSecureConnection => _context.Connection.IsSecure;
-
- public System.Net.IPEndPoint LocalEndPoint => _context.Connection.LocalEndPoint;
-
- public System.Net.IPEndPoint RemoteEndPoint => _context.Connection.RemoteEndPoint;
-
- public Guid RequestTraceIdentifier { get; } = Guid.NewGuid();
-
- public string ServiceName => null;
-
- private Uri RequestUri => _requestUri;
- private bool SupportsWebSockets => true;
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerRequest.cs b/SocketHttpListener/Net/HttpListenerRequest.cs
deleted file mode 100644
index 667d58ea7..000000000
--- a/SocketHttpListener/Net/HttpListenerRequest.cs
+++ /dev/null
@@ -1,537 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Net;
-using System.Text;
-using MediaBrowser.Model.Services;
-using SocketHttpListener.Net.WebSockets;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerRequest
- {
- private CookieCollection _cookies;
- private bool? _keepAlive;
- private string _rawUrl;
- private Uri _requestUri;
- private Version _version;
-
- public string[] AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]);
-
- public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]);
-
- private static CookieCollection ParseCookies(Uri uri, string setCookieHeader)
- {
- var cookies = new CookieCollection();
- return cookies;
- }
-
- public CookieCollection Cookies
- {
- get
- {
- if (_cookies == null)
- {
- string cookieString = Headers[HttpKnownHeaderNames.Cookie];
- if (!string.IsNullOrEmpty(cookieString))
- {
- _cookies = ParseCookies(RequestUri, cookieString);
- }
- if (_cookies == null)
- {
- _cookies = new CookieCollection();
- }
- }
- return _cookies;
- }
- }
-
- public Encoding ContentEncoding
- {
- get
- {
- if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
- {
- string postDataCharset = Headers["x-up-devcap-post-charset"];
- if (postDataCharset != null && postDataCharset.Length > 0)
- {
- try
- {
- return Encoding.GetEncoding(postDataCharset);
- }
- catch (ArgumentException)
- {
- }
- }
- }
- if (HasEntityBody)
- {
- if (ContentType != null)
- {
- string charSet = Helpers.GetCharSetValueFromHeader(ContentType);
- if (charSet != null)
- {
- try
- {
- return Encoding.GetEncoding(charSet);
- }
- catch (ArgumentException)
- {
- }
- }
- }
- }
- return Encoding.UTF8;
- }
- }
-
- public string ContentType => Headers[HttpKnownHeaderNames.ContentType];
-
- public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
-
- public bool IsWebSocketRequest
- {
- get
- {
- if (!SupportsWebSockets)
- {
- return false;
- }
-
- bool foundConnectionUpgradeHeader = false;
- if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade]))
- {
- return false;
- }
-
- foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection))
- {
- if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
- {
- foundConnectionUpgradeHeader = true;
- break;
- }
- }
-
- if (!foundConnectionUpgradeHeader)
- {
- return false;
- }
-
- foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade))
- {
- if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
- }
- }
-
- public bool KeepAlive
- {
- get
- {
- if (!_keepAlive.HasValue)
- {
- string header = Headers[HttpKnownHeaderNames.ProxyConnection];
- if (string.IsNullOrEmpty(header))
- {
- header = Headers[HttpKnownHeaderNames.Connection];
- }
- if (string.IsNullOrEmpty(header))
- {
- if (ProtocolVersion >= HttpVersion.Version11)
- {
- _keepAlive = true;
- }
- else
- {
- header = Headers[HttpKnownHeaderNames.KeepAlive];
- _keepAlive = !string.IsNullOrEmpty(header);
- }
- }
- else
- {
- header = header.ToLowerInvariant();
- _keepAlive =
- header.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0 ||
- header.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0;
- }
- }
-
- return _keepAlive.Value;
- }
- }
-
- public QueryParamCollection QueryString
- {
- get
- {
- var queryString = new QueryParamCollection();
- Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
- return queryString;
- }
- }
-
- public string RawUrl => _rawUrl;
-
- private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http;
-
- public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent];
-
- public string UserHostAddress => LocalEndPoint.ToString();
-
- public string UserHostName => Headers[HttpKnownHeaderNames.Host];
-
- public Uri UrlReferrer
- {
- get
- {
- string referrer = Headers[HttpKnownHeaderNames.Referer];
- if (referrer == null)
- {
- return null;
- }
-
- bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out var urlReferrer);
- return success ? urlReferrer : null;
- }
- }
-
- public Uri Url => RequestUri;
-
- public Version ProtocolVersion => _version;
-
- private static class Helpers
- {
- //
- // Get attribute off header value
- //
- internal static string GetCharSetValueFromHeader(string headerValue)
- {
- const string AttrName = "charset";
-
- if (headerValue == null)
- return null;
-
- int l = headerValue.Length;
- int k = AttrName.Length;
-
- // find properly separated attribute name
- int i = 1; // start searching from 1
-
- while (i < l)
- {
- i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, AttrName, i, CompareOptions.IgnoreCase);
- if (i < 0)
- break;
- if (i + k >= l)
- break;
-
- char chPrev = headerValue[i - 1];
- char chNext = headerValue[i + k];
- if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext)))
- break;
-
- i += k;
- }
-
- if (i < 0 || i >= l)
- return null;
-
- // skip to '=' and the following whitespace
- i += k;
- while (i < l && char.IsWhiteSpace(headerValue[i]))
- i++;
- if (i >= l || headerValue[i] != '=')
- return null;
- i++;
- while (i < l && char.IsWhiteSpace(headerValue[i]))
- i++;
- if (i >= l)
- return null;
-
- // parse the value
- string attrValue = null;
-
- int j;
-
- if (i < l && headerValue[i] == '"')
- {
- if (i == l - 1)
- return null;
- j = headerValue.IndexOf('"', i + 1);
- if (j < 0 || j == i + 1)
- return null;
-
- attrValue = headerValue.Substring(i + 1, j - i - 1).Trim();
- }
- else
- {
- for (j = i; j < l; j++)
- {
- if (headerValue[j] == ';')
- break;
- }
-
- if (j == i)
- return null;
-
- attrValue = headerValue.Substring(i, j - i).Trim();
- }
-
- return attrValue;
- }
-
- internal static string[] ParseMultivalueHeader(string s)
- {
- if (s == null)
- return null;
-
- int l = s.Length;
-
- // collect comma-separated values into list
-
- var values = new List<string>();
- int i = 0;
-
- while (i < l)
- {
- // find next ,
- int ci = s.IndexOf(',', i);
- if (ci < 0)
- ci = l;
-
- // append corresponding server value
- values.Add(s.Substring(i, ci - i));
-
- // move to next
- i = ci + 1;
-
- // skip leading space
- if (i < l && s[i] == ' ')
- i++;
- }
-
- // return list as array of strings
-
- int n = values.Count;
- string[] strings;
-
- // if n is 0 that means s was empty string
-
- if (n == 0)
- {
- strings = new string[1];
- strings[0] = string.Empty;
- }
- else
- {
- strings = new string[n];
- values.CopyTo(0, strings, 0, n);
- }
- return strings;
- }
-
-
- private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
- {
- int count = s.Length;
- var helper = new UrlDecoder(count, e);
-
- // go through the string's chars collapsing %XX and %uXXXX and
- // appending each char as char, with exception of %XX constructs
- // that are appended as bytes
-
- for (int pos = 0; pos < count; pos++)
- {
- char ch = s[pos];
-
- if (ch == '+')
- {
- ch = ' ';
- }
- else if (ch == '%' && pos < count - 2)
- {
- if (s[pos + 1] == 'u' && pos < count - 5)
- {
- int h1 = HexToInt(s[pos + 2]);
- int h2 = HexToInt(s[pos + 3]);
- int h3 = HexToInt(s[pos + 4]);
- int h4 = HexToInt(s[pos + 5]);
-
- if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
- { // valid 4 hex chars
- ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
- pos += 5;
-
- // only add as char
- helper.AddChar(ch);
- continue;
- }
- }
- else
- {
- int h1 = HexToInt(s[pos + 1]);
- int h2 = HexToInt(s[pos + 2]);
-
- if (h1 >= 0 && h2 >= 0)
- { // valid 2 hex chars
- byte b = (byte)((h1 << 4) | h2);
- pos += 2;
-
- // don't add as char
- helper.AddByte(b);
- continue;
- }
- }
- }
-
- if ((ch & 0xFF80) == 0)
- helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
- else
- helper.AddChar(ch);
- }
-
- return helper.GetString();
- }
-
- private static int HexToInt(char h)
- {
- return (h >= '0' && h <= '9') ? h - '0' :
- (h >= 'a' && h <= 'f') ? h - 'a' + 10 :
- (h >= 'A' && h <= 'F') ? h - 'A' + 10 :
- -1;
- }
-
- private class UrlDecoder
- {
- private int _bufferSize;
-
- // Accumulate characters in a special array
- private int _numChars;
- private char[] _charBuffer;
-
- // Accumulate bytes for decoding into characters in a special array
- private int _numBytes;
- private byte[] _byteBuffer;
-
- // Encoding to convert chars to bytes
- private Encoding _encoding;
-
- private void FlushBytes()
- {
- if (_numBytes > 0)
- {
- _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
- _numBytes = 0;
- }
- }
-
- internal UrlDecoder(int bufferSize, Encoding encoding)
- {
- _bufferSize = bufferSize;
- _encoding = encoding;
-
- _charBuffer = new char[bufferSize];
- // byte buffer created on demand
- }
-
- internal void AddChar(char ch)
- {
- if (_numBytes > 0)
- FlushBytes();
-
- _charBuffer[_numChars++] = ch;
- }
-
- internal void AddByte(byte b)
- {
- {
- if (_byteBuffer == null)
- _byteBuffer = new byte[_bufferSize];
-
- _byteBuffer[_numBytes++] = b;
- }
- }
-
- internal string GetString()
- {
- if (_numBytes > 0)
- FlushBytes();
-
- if (_numChars > 0)
- return new string(_charBuffer, 0, _numChars);
- else
- return string.Empty;
- }
- }
-
-
- internal static void FillFromString(QueryParamCollection nvc, string s, bool urlencoded, Encoding encoding)
- {
- int l = (s != null) ? s.Length : 0;
- int i = (s.Length > 0 && s[0] == '?') ? 1 : 0;
-
- while (i < l)
- {
- // find next & while noting first = on the way (and if there are more)
-
- int si = i;
- int ti = -1;
-
- while (i < l)
- {
- char ch = s[i];
-
- if (ch == '=')
- {
- if (ti < 0)
- ti = i;
- }
- else if (ch == '&')
- {
- break;
- }
-
- i++;
- }
-
- // extract the name / value pair
-
- string name = null;
- string value = null;
-
- if (ti >= 0)
- {
- name = s.Substring(si, ti - si);
- value = s.Substring(ti + 1, i - ti - 1);
- }
- else
- {
- value = s.Substring(si, i - si);
- }
-
- // add name / value pair to the collection
-
- if (urlencoded)
- nvc.Add(
- name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
- UrlDecodeStringFromStringInternal(value, encoding));
- else
- nvc.Add(name, value);
-
- // trailing '&'
-
- if (i == l - 1 && s[i] == '&')
- nvc.Add(null, "");
-
- i++;
- }
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerRequestUriBuilder.cs b/SocketHttpListener/Net/HttpListenerRequestUriBuilder.cs
deleted file mode 100644
index 7b4b619e6..000000000
--- a/SocketHttpListener/Net/HttpListenerRequestUriBuilder.cs
+++ /dev/null
@@ -1,443 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Globalization;
-using System.Text;
-
-namespace SocketHttpListener.Net
-{
- // We don't use the cooked URL because http.sys unescapes all percent-encoded values. However,
- // we also can't just use the raw Uri, since http.sys supports not only Utf-8, but also ANSI/DBCS and
- // Unicode code points. System.Uri only supports Utf-8.
- // The purpose of this class is to convert all ANSI, DBCS, and Unicode code points into percent encoded
- // Utf-8 characters.
- internal sealed class HttpListenerRequestUriBuilder
- {
- private static readonly Encoding s_utf8Encoding = new UTF8Encoding(false, true);
- private static readonly Encoding s_ansiEncoding = Encoding.GetEncoding(0, new EncoderExceptionFallback(), new DecoderExceptionFallback());
-
- private readonly string _rawUri;
- private readonly string _cookedUriScheme;
- private readonly string _cookedUriHost;
- private readonly string _cookedUriPath;
- private readonly string _cookedUriQuery;
-
- // This field is used to build the final request Uri string from the Uri parts passed to the ctor.
- private StringBuilder _requestUriString;
-
- // The raw path is parsed by looping through all characters from left to right. 'rawOctets'
- // is used to store consecutive percent encoded octets as actual byte values: e.g. for path /pa%C3%84th%2F/
- // rawOctets will be set to { 0xC3, 0x84 } when we reach character 't' and it will be { 0x2F } when
- // we reach the final '/'. I.e. after a sequence of percent encoded octets ends, we use rawOctets as
- // input to the encoding and percent encode the resulting string into UTF-8 octets.
- //
- // When parsing ANSI (Latin 1) encoded path '/pa%C4th/', %C4 will be added to rawOctets and when
- // we reach 't', the content of rawOctets { 0xC4 } will be fed into the ANSI encoding. The resulting
- // string 'Ä' will be percent encoded into UTF-8 octets and appended to requestUriString. The final
- // path will be '/pa%C3%84th/', where '%C3%84' is the UTF-8 percent encoded character 'Ä'.
- private List<byte> _rawOctets;
- private string _rawPath;
-
- // Holds the final request Uri.
- private Uri _requestUri;
-
- private HttpListenerRequestUriBuilder(string rawUri, string cookedUriScheme, string cookedUriHost,
- string cookedUriPath, string cookedUriQuery)
- {
- _rawUri = rawUri;
- _cookedUriScheme = cookedUriScheme;
- _cookedUriHost = cookedUriHost;
- _cookedUriPath = AddSlashToAsteriskOnlyPath(cookedUriPath);
- _cookedUriQuery = cookedUriQuery ?? string.Empty;
- }
-
- public static Uri GetRequestUri(string rawUri, string cookedUriScheme, string cookedUriHost,
- string cookedUriPath, string cookedUriQuery)
- {
- var builder = new HttpListenerRequestUriBuilder(rawUri,
- cookedUriScheme, cookedUriHost, cookedUriPath, cookedUriQuery);
-
- return builder.Build();
- }
-
- private Uri Build()
- {
- BuildRequestUriUsingRawPath();
-
- if (_requestUri == null)
- {
- BuildRequestUriUsingCookedPath();
- }
-
- return _requestUri;
- }
-
- private void BuildRequestUriUsingCookedPath()
- {
- bool isValid = Uri.TryCreate(_cookedUriScheme + Uri.SchemeDelimiter + _cookedUriHost + _cookedUriPath +
- _cookedUriQuery, UriKind.Absolute, out _requestUri);
-
- // Creating a Uri from the cooked Uri should really always work: If not, we log at least.
- if (!isValid)
- {
- //if (NetEventSource.IsEnabled)
- // NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_create_uri, _cookedUriScheme, _cookedUriHost, _cookedUriPath, _cookedUriQuery));
- }
- }
-
- private void BuildRequestUriUsingRawPath()
- {
- bool isValid = false;
-
- // Initialize 'rawPath' only if really needed; i.e. if we build the request Uri from the raw Uri.
- _rawPath = GetPath(_rawUri);
-
- // Try to check the raw path using first the primary encoding (according to http.sys settings);
- // if it fails try the secondary encoding.
- ParsingResult result = BuildRequestUriUsingRawPath(GetEncoding(EncodingType.Primary));
- if (result == ParsingResult.EncodingError)
- {
- Encoding secondaryEncoding = GetEncoding(EncodingType.Secondary);
- result = BuildRequestUriUsingRawPath(secondaryEncoding);
- }
- isValid = (result == ParsingResult.Success) ? true : false;
-
- // Log that we weren't able to create a Uri from the raw string.
- if (!isValid)
- {
- //if (NetEventSource.IsEnabled)
- // NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_create_uri, _cookedUriScheme, _cookedUriHost, _rawPath, _cookedUriQuery));
- }
- }
-
- private static Encoding GetEncoding(EncodingType type)
- {
- Debug.Assert((type == EncodingType.Primary) || (type == EncodingType.Secondary),
- "Unknown 'EncodingType' value: " + type.ToString());
-
- if (type == EncodingType.Secondary)
- {
- return s_ansiEncoding;
- }
- else
- {
- return s_utf8Encoding;
- }
- }
-
- private ParsingResult BuildRequestUriUsingRawPath(Encoding encoding)
- {
- Debug.Assert(encoding != null, "'encoding' must be assigned.");
- Debug.Assert(!string.IsNullOrEmpty(_rawPath), "'rawPath' must have at least one character.");
-
- _rawOctets = new List<byte>();
- _requestUriString = new StringBuilder();
- _requestUriString.Append(_cookedUriScheme);
- _requestUriString.Append(Uri.SchemeDelimiter);
- _requestUriString.Append(_cookedUriHost);
-
- ParsingResult result = ParseRawPath(encoding);
- if (result == ParsingResult.Success)
- {
- _requestUriString.Append(_cookedUriQuery);
-
- Debug.Assert(_rawOctets.Count == 0,
- "Still raw octets left. They must be added to the result path.");
-
- if (!Uri.TryCreate(_requestUriString.ToString(), UriKind.Absolute, out _requestUri))
- {
- // If we can't create a Uri from the string, this is an invalid string and it doesn't make
- // sense to try another encoding.
- result = ParsingResult.InvalidString;
- }
- }
-
- if (result != ParsingResult.Success)
- {
- //if (NetEventSource.IsEnabled)
- // NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_raw_path, _rawPath, encoding.EncodingName));
- }
-
- return result;
- }
-
- private ParsingResult ParseRawPath(Encoding encoding)
- {
- Debug.Assert(encoding != null, "'encoding' must be assigned.");
-
- int index = 0;
- char current = '\0';
- while (index < _rawPath.Length)
- {
- current = _rawPath[index];
- if (current == '%')
- {
- // Assert is enough, since http.sys accepted the request string already. This should never happen.
- Debug.Assert(index + 2 < _rawPath.Length, "Expected >=2 characters after '%' (e.g. %2F)");
-
- index++;
- current = _rawPath[index];
- if (current == 'u' || current == 'U')
- {
- // We found "%u" which means, we have a Unicode code point of the form "%uXXXX".
- Debug.Assert(index + 4 < _rawPath.Length, "Expected >=4 characters after '%u' (e.g. %u0062)");
-
- // Decode the content of rawOctets into percent encoded UTF-8 characters and append them
- // to requestUriString.
- if (!EmptyDecodeAndAppendRawOctetsList(encoding))
- {
- return ParsingResult.EncodingError;
- }
- if (!AppendUnicodeCodePointValuePercentEncoded(_rawPath.Substring(index + 1, 4)))
- {
- return ParsingResult.InvalidString;
- }
- index += 5;
- }
- else
- {
- // We found '%', but not followed by 'u', i.e. we have a percent encoded octed: %XX
- if (!AddPercentEncodedOctetToRawOctetsList(encoding, _rawPath.Substring(index, 2)))
- {
- return ParsingResult.InvalidString;
- }
- index += 2;
- }
- }
- else
- {
- // We found a non-'%' character: decode the content of rawOctets into percent encoded
- // UTF-8 characters and append it to the result.
- if (!EmptyDecodeAndAppendRawOctetsList(encoding))
- {
- return ParsingResult.EncodingError;
- }
- // Append the current character to the result.
- _requestUriString.Append(current);
- index++;
- }
- }
-
- // if the raw path ends with a sequence of percent encoded octets, make sure those get added to the
- // result (requestUriString).
- if (!EmptyDecodeAndAppendRawOctetsList(encoding))
- {
- return ParsingResult.EncodingError;
- }
-
- return ParsingResult.Success;
- }
-
- private bool AppendUnicodeCodePointValuePercentEncoded(string codePoint)
- {
- // http.sys only supports %uXXXX (4 hex-digits), even though unicode code points could have up to
- // 6 hex digits. Therefore we parse always 4 characters after %u and convert them to an int.
- if (!int.TryParse(codePoint, NumberStyles.HexNumber, null, out var codePointValue))
- {
- //if (NetEventSource.IsEnabled)
- // NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_percent_value, codePoint));
- return false;
- }
-
- string unicodeString = null;
- try
- {
- unicodeString = char.ConvertFromUtf32(codePointValue);
- AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(unicodeString));
-
- return true;
- }
- catch (ArgumentOutOfRangeException)
- {
- //if (NetEventSource.IsEnabled)
- // NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_percent_value, codePoint));
- }
- catch (EncoderFallbackException)
- {
- // If utf8Encoding.GetBytes() fails
- //if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_to_utf8, unicodeString, e.Message));
- }
-
- return false;
- }
-
- private bool AddPercentEncodedOctetToRawOctetsList(Encoding encoding, string escapedCharacter)
- {
- if (!byte.TryParse(escapedCharacter, NumberStyles.HexNumber, null, out byte encodedValue))
- {
- //if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_percent_value, escapedCharacter));
- return false;
- }
-
- _rawOctets.Add(encodedValue);
-
- return true;
- }
-
- private bool EmptyDecodeAndAppendRawOctetsList(Encoding encoding)
- {
- if (_rawOctets.Count == 0)
- {
- return true;
- }
-
- string decodedString = null;
- try
- {
- // If the encoding can get a string out of the byte array, this is a valid string in the
- // 'encoding' encoding.
- decodedString = encoding.GetString(_rawOctets.ToArray());
-
- if (encoding == s_utf8Encoding)
- {
- AppendOctetsPercentEncoded(_requestUriString, _rawOctets.ToArray());
- }
- else
- {
- AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(decodedString));
- }
-
- _rawOctets.Clear();
-
- return true;
- }
- catch (DecoderFallbackException)
- {
- //if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_bytes, GetOctetsAsString(_rawOctets), e.Message));
- }
- catch (EncoderFallbackException)
- {
- // If utf8Encoding.GetBytes() fails
- //if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_cant_convert_to_utf8, decodedString, e.Message));
- }
-
- return false;
- }
-
- private static void AppendOctetsPercentEncoded(StringBuilder target, IEnumerable<byte> octets)
- {
- foreach (byte octet in octets)
- {
- target.Append('%');
- target.Append(octet.ToString("X2", CultureInfo.InvariantCulture));
- }
- }
-
- private static string GetOctetsAsString(IEnumerable<byte> octets)
- {
- var octetString = new StringBuilder();
-
- bool first = true;
- foreach (byte octet in octets)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- octetString.Append(' ');
- }
- octetString.Append(octet.ToString("X2", CultureInfo.InvariantCulture));
- }
-
- return octetString.ToString();
- }
-
- private static string GetPath(string uriString)
- {
- Debug.Assert(uriString != null, "uriString must not be null");
- Debug.Assert(uriString.Length > 0, "uriString must not be empty");
-
- int pathStartIndex = 0;
-
- // Perf. improvement: nearly all strings are relative Uris. So just look if the
- // string starts with '/'. If so, we have a relative Uri and the path starts at position 0.
- // (http.sys already trimmed leading whitespaces)
- if (uriString[0] != '/')
- {
- // We can't check against cookedUriScheme, since http.sys allows for request http://myserver/ to
- // use a request line 'GET https://myserver/' (note http vs. https). Therefore check if the
- // Uri starts with either http:// or https://.
- int authorityStartIndex = 0;
- if (uriString.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
- {
- authorityStartIndex = 7;
- }
- else if (uriString.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
- {
- authorityStartIndex = 8;
- }
-
- if (authorityStartIndex > 0)
- {
- // we have an absolute Uri. Find out where the authority ends and the path begins.
- // Note that Uris like "http://server?query=value/1/2" are invalid according to RFC2616
- // and http.sys behavior: If the Uri contains a query, there must be at least one '/'
- // between the authority and the '?' character: It's safe to just look for the first
- // '/' after the authority to determine the beginning of the path.
- pathStartIndex = uriString.IndexOf('/', authorityStartIndex);
- if (pathStartIndex == -1)
- {
- // e.g. for request lines like: 'GET http://myserver' (no final '/')
- pathStartIndex = uriString.Length;
- }
- }
- else
- {
- // RFC2616: Request-URI = "*" | absoluteURI | abs_path | authority
- // 'authority' can only be used with CONNECT which is never received by HttpListener.
- // I.e. if we don't have an absolute path (must start with '/') and we don't have
- // an absolute Uri (must start with http:// or https://), then 'uriString' must be '*'.
- Debug.Assert((uriString.Length == 1) && (uriString[0] == '*'), "Unknown request Uri string format",
- "Request Uri string is not an absolute Uri, absolute path, or '*': {0}", uriString);
-
- // Should we ever get here, be consistent with 2.0/3.5 behavior: just add an initial
- // slash to the string and treat it as a path:
- uriString = "/" + uriString;
- }
- }
-
- // Find end of path: The path is terminated by
- // - the first '?' character
- // - the first '#' character: This is never the case here, since http.sys won't accept
- // Uris containing fragments. Also, RFC2616 doesn't allow fragments in request Uris.
- // - end of Uri string
- int queryIndex = uriString.IndexOf('?');
- if (queryIndex == -1)
- {
- queryIndex = uriString.Length;
- }
-
- // will always return a != null string.
- return AddSlashToAsteriskOnlyPath(uriString.Substring(pathStartIndex, queryIndex - pathStartIndex));
- }
-
- private static string AddSlashToAsteriskOnlyPath(string path)
- {
- Debug.Assert(path != null, "'path' must not be null");
-
- // If a request like "OPTIONS * HTTP/1.1" is sent to the listener, then the request Uri
- // should be "http[s]://server[:port]/*" to be compatible with pre-4.0 behavior.
- if ((path.Length == 1) && (path[0] == '*'))
- {
- return "/*";
- }
-
- return path;
- }
-
- private enum ParsingResult
- {
- Success,
- InvalidString,
- EncodingError
- }
-
- private enum EncodingType
- {
- Primary,
- Secondary
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerResponse.Managed.cs b/SocketHttpListener/Net/HttpListenerResponse.Managed.cs
deleted file mode 100644
index f595fce7c..000000000
--- a/SocketHttpListener/Net/HttpListenerResponse.Managed.cs
+++ /dev/null
@@ -1,333 +0,0 @@
-using System;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerResponse : IDisposable
- {
- private long _contentLength;
- private Version _version = HttpVersion.Version11;
- private int _statusCode = 200;
- internal object _headersLock = new object();
- private bool _forceCloseChunked;
-
- internal HttpListenerResponse(HttpListenerContext context)
- {
- _httpContext = context;
- }
-
- internal bool ForceCloseChunked => _forceCloseChunked;
-
- private void EnsureResponseStream()
- {
- if (_responseStream == null)
- {
- _responseStream = _httpContext.Connection.GetResponseStream();
- }
- }
-
- public Version ProtocolVersion
- {
- get => _version;
- set
- {
- CheckDisposed();
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
- if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
- {
- throw new ArgumentException("Wrong version");
- }
-
- _version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor
- }
- }
-
- public int StatusCode
- {
- get => _statusCode;
- set
- {
- CheckDisposed();
-
- if (value < 100 || value > 999)
- throw new ProtocolViolationException("Invalid status");
-
- _statusCode = value;
- }
- }
-
- private void Dispose()
- {
- Close(true);
- }
-
- public void Close()
- {
- if (Disposed)
- return;
-
- Close(false);
- }
-
- public void Abort()
- {
- if (Disposed)
- return;
-
- Close(true);
- }
-
- private void Close(bool force)
- {
- Disposed = true;
- _httpContext.Connection.Close(force);
- }
-
- public void Close(byte[] responseEntity, bool willBlock)
- {
- CheckDisposed();
-
- if (responseEntity == null)
- {
- throw new ArgumentNullException(nameof(responseEntity));
- }
-
- if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
- {
- ContentLength64 = responseEntity.Length;
- }
-
- if (willBlock)
- {
- try
- {
- OutputStream.Write(responseEntity, 0, responseEntity.Length);
- }
- finally
- {
- Close(false);
- }
- }
- else
- {
- OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
- {
- var thisRef = (HttpListenerResponse)iar.AsyncState;
- try
- {
- try
- {
- thisRef.OutputStream.EndWrite(iar);
- }
- finally
- {
- thisRef.Close(false);
- }
- }
- catch (Exception)
- {
- // In case response was disposed during this time
- }
- }, this);
- }
- }
-
- public void CopyFrom(HttpListenerResponse templateResponse)
- {
- _webHeaders.Clear();
- //_webHeaders.Add(templateResponse._webHeaders);
- _contentLength = templateResponse._contentLength;
- _statusCode = templateResponse._statusCode;
- _statusDescription = templateResponse._statusDescription;
- _keepAlive = templateResponse._keepAlive;
- _version = templateResponse._version;
- }
-
- internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
- {
- if (!isWebSocketHandshake)
- {
- if (_webHeaders["Server"] == null)
- {
- _webHeaders.Set("Server", "Microsoft-NetCore/2.0");
- }
-
- if (_webHeaders["Date"] == null)
- {
- _webHeaders.Set("Date", DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
- }
-
- if (_boundaryType == BoundaryType.None)
- {
- if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
- {
- _keepAlive = false;
- }
- else
- {
- _boundaryType = BoundaryType.Chunked;
- }
-
- if (CanSendResponseBody(_httpContext.Response.StatusCode))
- {
- _contentLength = -1;
- }
- else
- {
- _boundaryType = BoundaryType.ContentLength;
- _contentLength = 0;
- }
- }
-
- if (_boundaryType != BoundaryType.Chunked)
- {
- if (_boundaryType != BoundaryType.ContentLength && closing)
- {
- _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
- }
-
- if (_boundaryType == BoundaryType.ContentLength)
- {
- _webHeaders.Set("Content-Length", _contentLength.ToString("D", CultureInfo.InvariantCulture));
- }
- }
-
- /* Apache forces closing the connection for these status codes:
- * HttpStatusCode.BadRequest 400
- * HttpStatusCode.RequestTimeout 408
- * HttpStatusCode.LengthRequired 411
- * HttpStatusCode.RequestEntityTooLarge 413
- * HttpStatusCode.RequestUriTooLong 414
- * HttpStatusCode.InternalServerError 500
- * HttpStatusCode.ServiceUnavailable 503
- */
- bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
- || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
- || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
- || _statusCode == (int)HttpStatusCode.ServiceUnavailable);
-
- if (!conn_close)
- {
- conn_close = !_httpContext.Request.KeepAlive;
- }
-
- // They sent both KeepAlive: true and Connection: close
- if (!_keepAlive || conn_close)
- {
- _webHeaders.Set("Connection", "Close");
- conn_close = true;
- }
-
- if (SendChunked)
- {
- _webHeaders.Set("Transfer-Encoding", "Chunked");
- }
-
- int reuses = _httpContext.Connection.Reuses;
- if (reuses >= 100)
- {
- _forceCloseChunked = true;
- if (!conn_close)
- {
- _webHeaders.Set("Connection", "Close");
- conn_close = true;
- }
- }
-
- if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
- {
- if (_keepAlive)
- {
- Headers["Keep-Alive"] = "true";
- }
-
- if (!conn_close)
- {
- _webHeaders.Set("Connection", "Keep-Alive");
- }
- }
-
- ComputeCookies();
- }
-
- var encoding = Encoding.UTF8;
- var writer = new StreamWriter(ms, encoding, 256);
- writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
- writer.Flush();
- byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
- ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
- writer.Write("\r\n");
-
- writer.Write(FormatHeaders(_webHeaders));
- writer.Flush();
- int preamble = encoding.GetPreamble().Length;
- EnsureResponseStream();
-
- /* Assumes that the ms was at position 0 */
- ms.Position = preamble;
- SentHeaders = !isWebSocketHandshake;
- }
-
- private static bool HeaderCanHaveEmptyValue(string name) =>
- !string.Equals(name, "Location", StringComparison.OrdinalIgnoreCase);
-
- private static string FormatHeaders(WebHeaderCollection headers)
- {
- var sb = new StringBuilder();
-
- for (int i = 0; i < headers.Count; i++)
- {
- string key = headers.GetKey(i);
- string[] values = headers.GetValues(i);
-
- int startingLength = sb.Length;
-
- sb.Append(key).Append(": ");
- bool anyValues = false;
- for (int j = 0; j < values.Length; j++)
- {
- string value = values[j];
- if (!string.IsNullOrWhiteSpace(value))
- {
- if (anyValues)
- {
- sb.Append(", ");
- }
- sb.Append(value);
- anyValues = true;
- }
- }
-
- if (anyValues || HeaderCanHaveEmptyValue(key))
- {
- // Complete the header
- sb.Append("\r\n");
- }
- else
- {
- // Empty header; remove it.
- sb.Length = startingLength;
- }
- }
-
- return sb.Append("\r\n").ToString();
- }
-
- private bool Disposed { get; set; }
- internal bool SentHeaders { get; set; }
-
- public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
- {
- return ((HttpResponseStream)OutputStream).TransmitFile(path, offset, count, fileShareMode, cancellationToken);
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpListenerResponse.cs b/SocketHttpListener/Net/HttpListenerResponse.cs
deleted file mode 100644
index 66ef88564..000000000
--- a/SocketHttpListener/Net/HttpListenerResponse.cs
+++ /dev/null
@@ -1,294 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-using System.Text;
-
-namespace SocketHttpListener.Net
-{
- public sealed partial class HttpListenerResponse : IDisposable
- {
- private BoundaryType _boundaryType = BoundaryType.None;
- private CookieCollection _cookies;
- private HttpListenerContext _httpContext;
- private bool _keepAlive = true;
- private HttpResponseStream _responseStream;
- private string _statusDescription;
- private WebHeaderCollection _webHeaders = new WebHeaderCollection();
-
- public WebHeaderCollection Headers => _webHeaders;
-
- public Encoding ContentEncoding { get; set; }
-
- public string ContentType
- {
- get => Headers["Content-Type"];
- set
- {
- CheckDisposed();
- if (string.IsNullOrEmpty(value))
- {
- Headers.Remove("Content-Type");
- }
- else
- {
- Headers.Set("Content-Type", value);
- }
- }
- }
-
- private HttpListenerContext HttpListenerContext => _httpContext;
-
- private HttpListenerRequest HttpListenerRequest => HttpListenerContext.Request;
-
- internal EntitySendFormat EntitySendFormat
- {
- get => (EntitySendFormat)_boundaryType;
- set
- {
- CheckDisposed();
- CheckSentHeaders();
- if (value == EntitySendFormat.Chunked && HttpListenerRequest.ProtocolVersion.Minor == 0)
- {
- throw new ProtocolViolationException("net_nochunkuploadonhttp10");
- }
- _boundaryType = (BoundaryType)value;
- if (value != EntitySendFormat.ContentLength)
- {
- _contentLength = -1;
- }
- }
- }
-
- public bool SendChunked
- {
- get => EntitySendFormat == EntitySendFormat.Chunked;
- set => EntitySendFormat = value ? EntitySendFormat.Chunked : EntitySendFormat.ContentLength;
- }
-
- // We MUST NOT send message-body when we send responses with these Status codes
- private static readonly int[] s_noResponseBody = { 100, 101, 204, 205, 304 };
-
- private static bool CanSendResponseBody(int responseCode)
- {
- for (int i = 0; i < s_noResponseBody.Length; i++)
- {
- if (responseCode == s_noResponseBody[i])
- {
- return false;
- }
- }
- return true;
- }
-
- public long ContentLength64
- {
- get => _contentLength;
- set
- {
- CheckDisposed();
- CheckSentHeaders();
- if (value >= 0)
- {
- _contentLength = value;
- _boundaryType = BoundaryType.ContentLength;
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(value));
- }
- }
- }
-
- public CookieCollection Cookies
- {
- get => _cookies ?? (_cookies = new CookieCollection());
- set => _cookies = value;
- }
-
- public bool KeepAlive
- {
- get => _keepAlive;
- set
- {
- CheckDisposed();
- _keepAlive = value;
- }
- }
-
- public Stream OutputStream
- {
- get
- {
- CheckDisposed();
- EnsureResponseStream();
- return _responseStream;
- }
- }
-
- public string RedirectLocation
- {
- get => Headers["Location"];
- set
- {
- // note that this doesn't set the status code to a redirect one
- CheckDisposed();
- if (string.IsNullOrEmpty(value))
- {
- Headers.Remove("Location");
- }
- else
- {
- Headers.Set("Location", value);
- }
- }
- }
-
- public string StatusDescription
- {
- get
- {
- if (_statusDescription == null)
- {
- // if the user hasn't set this, generated on the fly, if possible.
- // We know this one is safe, no need to verify it as in the setter.
- _statusDescription = HttpStatusDescription.Get(StatusCode);
- }
- if (_statusDescription == null)
- {
- _statusDescription = string.Empty;
- }
- return _statusDescription;
- }
- set
- {
- CheckDisposed();
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- // Need to verify the status description doesn't contain any control characters except HT. We mask off the high
- // byte since that's how it's encoded.
- for (int i = 0; i < value.Length; i++)
- {
- char c = (char)(0x000000ff & (uint)value[i]);
- if ((c <= 31 && c != (byte)'\t') || c == 127)
- {
- throw new ArgumentException("net_WebHeaderInvalidControlChars");
- }
- }
-
- _statusDescription = value;
- }
- }
-
- public void AddHeader(string name, string value)
- {
- Headers.Set(name, value);
- }
-
- public void AppendHeader(string name, string value)
- {
- Headers.Add(name, value);
- }
-
- public void AppendCookie(Cookie cookie)
- {
- if (cookie == null)
- {
- throw new ArgumentNullException(nameof(cookie));
- }
- Cookies.Add(cookie);
- }
-
- private void ComputeCookies()
- {
- if (_cookies != null)
- {
- // now go through the collection, and concatenate all the cookies in per-variant strings
- //string setCookie2 = null, setCookie = null;
- //for (int index = 0; index < _cookies.Count; index++)
- //{
- // Cookie cookie = _cookies[index];
- // string cookieString = cookie.ToServerString();
- // if (cookieString == null || cookieString.Length == 0)
- // {
- // continue;
- // }
-
- // if (cookie.IsRfc2965Variant())
- // {
- // setCookie2 = setCookie2 == null ? cookieString : setCookie2 + ", " + cookieString;
- // }
- // else
- // {
- // setCookie = setCookie == null ? cookieString : setCookie + ", " + cookieString;
- // }
- //}
-
- //if (!string.IsNullOrEmpty(setCookie))
- //{
- // Headers.Set(HttpKnownHeaderNames.SetCookie, setCookie);
- // if (string.IsNullOrEmpty(setCookie2))
- // {
- // Headers.Remove(HttpKnownHeaderNames.SetCookie2);
- // }
- //}
-
- //if (!string.IsNullOrEmpty(setCookie2))
- //{
- // Headers.Set(HttpKnownHeaderNames.SetCookie2, setCookie2);
- // if (string.IsNullOrEmpty(setCookie))
- // {
- // Headers.Remove(HttpKnownHeaderNames.SetCookie);
- // }
- //}
- }
- }
-
- public void Redirect(string url)
- {
- Headers["Location"] = url;
- StatusCode = (int)HttpStatusCode.Redirect;
- StatusDescription = "Found";
- }
-
- public void SetCookie(Cookie cookie)
- {
- if (cookie == null)
- {
- throw new ArgumentNullException(nameof(cookie));
- }
-
- //Cookie newCookie = cookie.Clone();
- //int added = Cookies.InternalAdd(newCookie, true);
-
- //if (added != 1)
- //{
- // // The Cookie already existed and couldn't be replaced.
- // throw new ArgumentException("Cookie exists");
- //}
- }
-
- void IDisposable.Dispose()
- {
- Dispose();
- }
-
- private void CheckDisposed()
- {
- if (Disposed)
- {
- throw new ObjectDisposedException(GetType().FullName);
- }
- }
-
- private void CheckSentHeaders()
- {
- if (SentHeaders)
- {
- throw new InvalidOperationException();
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpRequestStream.Managed.cs b/SocketHttpListener/Net/HttpRequestStream.Managed.cs
deleted file mode 100644
index 42fc4d97c..000000000
--- a/SocketHttpListener/Net/HttpRequestStream.Managed.cs
+++ /dev/null
@@ -1,210 +0,0 @@
-using System;
-using System.IO;
-
-namespace SocketHttpListener.Net
-{
- // Licensed to the .NET Foundation under one or more agreements.
- // See the LICENSE file in the project root for more information.
- //
- // System.Net.ResponseStream
- //
- // Author:
- // Gonzalo Paniagua Javier (gonzalo@novell.com)
- //
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
-
- internal partial class HttpRequestStream : Stream
- {
- private byte[] _buffer;
- private int _offset;
- private int _length;
- private long _remainingBody;
- protected bool _closed;
- private Stream _stream;
-
- internal HttpRequestStream(Stream stream, byte[] buffer, int offset, int length)
- : this(stream, buffer, offset, length, -1)
- {
- }
-
- internal HttpRequestStream(Stream stream, byte[] buffer, int offset, int length, long contentlength)
- {
- _stream = stream;
- _buffer = buffer;
- _offset = offset;
- _length = length;
- _remainingBody = contentlength;
- }
-
- // Returns 0 if we can keep reading from the base stream,
- // > 0 if we read something from the buffer.
- // -1 if we had a content length set and we finished reading that many bytes.
- private int FillFromBuffer(byte[] buffer, int offset, int count)
- {
- if (_remainingBody == 0)
- return -1;
-
- if (_length == 0)
- return 0;
-
- int size = Math.Min(_length, count);
- if (_remainingBody > 0)
- size = (int)Math.Min(size, _remainingBody);
-
- if (_offset > _buffer.Length - size)
- {
- size = Math.Min(size, _buffer.Length - _offset);
- }
- if (size == 0)
- return 0;
-
- Buffer.BlockCopy(_buffer, _offset, buffer, offset, size);
- _offset += size;
- _length -= size;
- if (_remainingBody > 0)
- _remainingBody -= size;
- return size;
- }
-
- protected virtual int ReadCore(byte[] buffer, int offset, int size)
- {
- // Call FillFromBuffer to check for buffer boundaries even when remaining_body is 0
- int nread = FillFromBuffer(buffer, offset, size);
- if (nread == -1)
- { // No more bytes available (Content-Length)
- return 0;
- }
- else if (nread > 0)
- {
- return nread;
- }
-
- if (_remainingBody > 0)
- {
- size = (int)Math.Min(_remainingBody, (long)size);
- }
-
- nread = _stream.Read(buffer, offset, size);
-
- if (_remainingBody > 0)
- {
- if (nread == 0)
- {
- throw new Exception("Bad request");
- }
-
- //Debug.Assert(nread <= _remainingBody);
- _remainingBody -= nread;
- }
-
- return nread;
- }
-
- protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state)
- {
- if (size == 0 || _closed)
- {
- var ares = new HttpStreamAsyncResult(this);
- ares._callback = cback;
- ares._state = state;
- ares.Complete();
- return ares;
- }
-
- int nread = FillFromBuffer(buffer, offset, size);
- if (nread > 0 || nread == -1)
- {
- var ares = new HttpStreamAsyncResult(this);
- ares._buffer = buffer;
- ares._offset = offset;
- ares._count = size;
- ares._callback = cback;
- ares._state = state;
- ares._synchRead = Math.Max(0, nread);
- ares.Complete();
- return ares;
- }
-
- // Avoid reading past the end of the request to allow
- // for HTTP pipelining
- if (_remainingBody >= 0 && size > _remainingBody)
- {
- size = (int)Math.Min(_remainingBody, (long)size);
- }
-
- return _stream.BeginRead(buffer, offset, size, cback, state);
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- throw new ArgumentNullException(nameof(asyncResult));
-
- var r = asyncResult as HttpStreamAsyncResult;
- if (r != null)
- {
- if (!ReferenceEquals(this, r._parent))
- {
- throw new ArgumentException("Invalid async result");
- }
- if (r._endCalled)
- {
- throw new InvalidOperationException("invalid end call");
- }
- r._endCalled = true;
-
- if (!asyncResult.IsCompleted)
- {
- asyncResult.AsyncWaitHandle.WaitOne();
- }
-
- return r._synchRead;
- }
-
- if (_closed)
- return 0;
-
- int nread = 0;
- try
- {
- nread = _stream.EndRead(asyncResult);
- }
- catch (IOException e) when (e.InnerException is ArgumentException || e.InnerException is InvalidOperationException)
- {
- throw e.InnerException;
- }
-
- if (_remainingBody > 0)
- {
- if (nread == 0)
- {
- throw new Exception("Bad request");
- }
-
- _remainingBody -= nread;
- }
-
- return nread;
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpRequestStream.cs b/SocketHttpListener/Net/HttpRequestStream.cs
deleted file mode 100644
index 1c554df20..000000000
--- a/SocketHttpListener/Net/HttpRequestStream.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace SocketHttpListener.Net
-{
- // Licensed to the .NET Foundation under one or more agreements.
- // See the LICENSE file in the project root for more information.
- //
- // System.Net.ResponseStream
- //
- // Author:
- // Gonzalo Paniagua Javier (gonzalo@novell.com)
- //
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
-
- internal partial class HttpRequestStream : Stream
- {
- public override bool CanSeek => false;
- public override bool CanWrite => false;
- public override bool CanRead => true;
-
- public override int Read(byte[] buffer, int offset, int size)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
- if (offset < 0 || offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(offset));
- }
- if (size < 0 || size > buffer.Length - offset)
- {
- throw new ArgumentOutOfRangeException(nameof(size));
- }
- if (size == 0 || _closed)
- {
- return 0;
- }
-
- return ReadCore(buffer, offset, size);
- }
-
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
- if (offset < 0 || offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(offset));
- }
- if (size < 0 || size > buffer.Length - offset)
- {
- throw new ArgumentOutOfRangeException(nameof(size));
- }
-
- return BeginReadCore(buffer, offset, size, callback, state);
- }
-
- public override void Flush() { }
- public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
-
- public override long Length => throw new NotImplementedException();
-
- public override long Position
- {
- get => throw new NotImplementedException();
-
- set => throw new NotImplementedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new NotImplementedException();
- }
-
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return base.BeginWrite(buffer, offset, count, callback, state);
- }
-
- public override void EndWrite(IAsyncResult asyncResult)
- {
- base.EndWrite(asyncResult);
- }
-
- internal bool Closed => _closed;
-
- protected override void Dispose(bool disposing)
- {
- _closed = true;
- base.Dispose(disposing);
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpResponseStream.Managed.cs b/SocketHttpListener/Net/HttpResponseStream.Managed.cs
deleted file mode 100644
index 5d02a9c95..000000000
--- a/SocketHttpListener/Net/HttpResponseStream.Managed.cs
+++ /dev/null
@@ -1,329 +0,0 @@
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-
-namespace SocketHttpListener.Net
-{
- // Licensed to the .NET Foundation under one or more agreements.
- // See the LICENSE file in the project root for more information.
- //
- // System.Net.ResponseStream
- //
- // Author:
- // Gonzalo Paniagua Javier (gonzalo@novell.com)
- //
- // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
-
- internal partial class HttpResponseStream : Stream
- {
- private HttpListenerResponse _response;
- private bool _ignore_errors;
- private bool _trailer_sent;
- private Stream _stream;
- private readonly IStreamHelper _streamHelper;
- private readonly Socket _socket;
- private readonly bool _supportsDirectSocketAccess;
- private readonly IEnvironmentInfo _environment;
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
-
- internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors, IStreamHelper streamHelper, Socket socket, bool supportsDirectSocketAccess, IEnvironmentInfo environment, IFileSystem fileSystem, ILogger logger)
- {
- _response = response;
- _ignore_errors = ignore_errors;
- _streamHelper = streamHelper;
- _socket = socket;
- _supportsDirectSocketAccess = supportsDirectSocketAccess;
- _environment = environment;
- _fileSystem = fileSystem;
- _logger = logger;
- _stream = stream;
- }
-
- private void DisposeCore()
- {
- byte[] bytes = null;
- MemoryStream ms = GetHeaders(true);
- bool chunked = _response.SendChunked;
- if (_stream.CanWrite)
- {
- try
- {
- if (ms != null)
- {
- long start = ms.Position;
- if (chunked && !_trailer_sent)
- {
- bytes = GetChunkSizeBytes(0, true);
- ms.Position = ms.Length;
- ms.Write(bytes, 0, bytes.Length);
- }
- InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
- _trailer_sent = true;
- }
- else if (chunked && !_trailer_sent)
- {
- bytes = GetChunkSizeBytes(0, true);
- InternalWrite(bytes, 0, bytes.Length);
- _trailer_sent = true;
- }
- }
- catch (HttpListenerException)
- {
- // Ignore error due to connection reset by peer
- }
- }
- _response.Close();
- }
-
- internal async Task WriteWebSocketHandshakeHeadersAsync()
- {
- if (_closed)
- throw new ObjectDisposedException(GetType().ToString());
-
- if (_stream.CanWrite)
- {
- MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true);
- bool chunked = _response.SendChunked;
-
- long start = ms.Position;
- if (chunked)
- {
- byte[] bytes = GetChunkSizeBytes(0, true);
- ms.Position = ms.Length;
- ms.Write(bytes, 0, bytes.Length);
- }
-
- await InternalWriteAsync(ms.GetBuffer(), (int)start, (int)(ms.Length - start)).ConfigureAwait(false);
- await _stream.FlushAsync().ConfigureAwait(false);
- }
- }
-
- private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false)
- {
- //// SendHeaders works on shared headers
- //lock (_response.headers_lock)
- //{
- // if (_response.HeadersSent)
- // return null;
- // var ms = CreateNew();
- // _response.SendHeaders(closing, ms);
- // return ms;
- //}
-
- // SendHeaders works on shared headers
- lock (_response._headersLock)
- {
- if (_response.SentHeaders)
- {
- return null;
- }
-
- MemoryStream ms = new MemoryStream();
- _response.SendHeaders(closing, ms, isWebSocketHandshake);
- return ms;
- }
- }
-
- private static byte[] s_crlf = new byte[] { 13, 10 };
- private static byte[] GetChunkSizeBytes(int size, bool final)
- {
- string str = string.Format("{0:x}\r\n{1}", size, final ? "\r\n" : "");
- return Encoding.ASCII.GetBytes(str);
- }
-
- internal void InternalWrite(byte[] buffer, int offset, int count)
- {
- if (_ignore_errors)
- {
- try
- {
- _stream.Write(buffer, offset, count);
- }
- catch { }
- }
- else
- {
- _stream.Write(buffer, offset, count);
- }
- }
-
- internal Task InternalWriteAsync(byte[] buffer, int offset, int count) =>
- _ignore_errors ? InternalWriteIgnoreErrorsAsync(buffer, offset, count) : _stream.WriteAsync(buffer, offset, count);
-
- private async Task InternalWriteIgnoreErrorsAsync(byte[] buffer, int offset, int count)
- {
- try { await _stream.WriteAsync(buffer, offset, count).ConfigureAwait(false); }
- catch { }
- }
-
- private void WriteCore(byte[] buffer, int offset, int size)
- {
- if (size == 0)
- return;
-
- byte[] bytes = null;
- MemoryStream ms = GetHeaders(false);
- bool chunked = _response.SendChunked;
- if (ms != null)
- {
- long start = ms.Position; // After the possible preamble for the encoding
- ms.Position = ms.Length;
- if (chunked)
- {
- bytes = GetChunkSizeBytes(size, false);
- ms.Write(bytes, 0, bytes.Length);
- }
-
- int new_count = Math.Min(size, 16384 - (int)ms.Position + (int)start);
- ms.Write(buffer, offset, new_count);
- size -= new_count;
- offset += new_count;
- InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
- ms.SetLength(0);
- ms.Capacity = 0; // 'dispose' the buffer in ms.
- }
- else if (chunked)
- {
- bytes = GetChunkSizeBytes(size, false);
- InternalWrite(bytes, 0, bytes.Length);
- }
-
- if (size > 0)
- InternalWrite(buffer, offset, size);
- if (chunked)
- InternalWrite(s_crlf, 0, 2);
- }
-
- private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state)
- {
- if (_closed)
- {
- var ares = new HttpStreamAsyncResult(this);
- ares._callback = cback;
- ares._state = state;
- ares.Complete();
- return ares;
- }
-
- byte[] bytes = null;
- MemoryStream ms = GetHeaders(false);
- bool chunked = _response.SendChunked;
- if (ms != null)
- {
- long start = ms.Position;
- ms.Position = ms.Length;
- if (chunked)
- {
- bytes = GetChunkSizeBytes(size, false);
- ms.Write(bytes, 0, bytes.Length);
- }
- ms.Write(buffer, offset, size);
- buffer = ms.GetBuffer();
- offset = (int)start;
- size = (int)(ms.Position - start);
- }
- else if (chunked)
- {
- bytes = GetChunkSizeBytes(size, false);
- InternalWrite(bytes, 0, bytes.Length);
- }
-
- return _stream.BeginWrite(buffer, offset, size, cback, state);
- }
-
- private void EndWriteCore(IAsyncResult asyncResult)
- {
- if (_closed)
- return;
-
- if (_ignore_errors)
- {
- try
- {
- _stream.EndWrite(asyncResult);
- if (_response.SendChunked)
- _stream.Write(s_crlf, 0, 2);
- }
- catch { }
- }
- else
- {
- _stream.EndWrite(asyncResult);
- if (_response.SendChunked)
- _stream.Write(s_crlf, 0, 2);
- }
- }
-
- public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
- {
- return TransmitFileManaged(path, offset, count, fileShareMode, cancellationToken);
- }
-
- const int StreamCopyToBufferSize = 81920;
- private async Task TransmitFileManaged(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
- {
- var allowAsync = _environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows;
-
- //if (count <= 0)
- //{
- // allowAsync = true;
- //}
-
- var fileOpenOptions = FileOpenOptions.SequentialScan;
-
- if (allowAsync)
- {
- fileOpenOptions |= FileOpenOptions.Asynchronous;
- }
-
- // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
-
- using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions))
- {
- if (offset > 0)
- {
- fs.Position = offset;
- }
-
- var targetStream = this;
-
- if (count > 0)
- {
- await _streamHelper.CopyToAsync(fs, targetStream, count, cancellationToken).ConfigureAwait(false);
- }
- else
- {
- await fs.CopyToAsync(targetStream, StreamCopyToBufferSize, cancellationToken).ConfigureAwait(false);
- }
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpResponseStream.cs b/SocketHttpListener/Net/HttpResponseStream.cs
deleted file mode 100644
index 085c2ad0c..000000000
--- a/SocketHttpListener/Net/HttpResponseStream.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace SocketHttpListener.Net
-{
- internal sealed partial class HttpResponseStream : Stream
- {
- private bool _closed;
- internal bool Closed => _closed;
-
- public override bool CanRead => false;
- public override bool CanSeek => false;
- public override bool CanWrite => true;
-
- public override void Flush() { }
- public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
-
- public override long Length => throw new NotImplementedException();
-
- public override long Position
- {
- get => throw new NotImplementedException();
-
- set => throw new NotImplementedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- throw new NotImplementedException();
- }
-
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return base.BeginRead(buffer, offset, count, callback, state);
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- return base.EndRead(asyncResult);
- }
-
- public override void Write(byte[] buffer, int offset, int size)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
- if (offset < 0 || offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(offset));
- }
- if (size < 0 || size > buffer.Length - offset)
- {
- throw new ArgumentOutOfRangeException(nameof(size));
- }
- if (_closed)
- {
- return;
- }
-
- WriteCore(buffer, offset, size);
- }
-
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
- if (offset < 0 || offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(offset));
- }
- if (size < 0 || size > buffer.Length - offset)
- {
- throw new ArgumentOutOfRangeException(nameof(size));
- }
-
- return BeginWriteCore(buffer, offset, size, callback, state);
- }
-
- public override void EndWrite(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- {
- throw new ArgumentNullException(nameof(asyncResult));
- }
-
- EndWriteCore(asyncResult);
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- {
- if (_closed)
- {
- return;
- }
- _closed = true;
- DisposeCore();
- }
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpStatusCode.cs b/SocketHttpListener/Net/HttpStatusCode.cs
deleted file mode 100644
index d4bb61b8a..000000000
--- a/SocketHttpListener/Net/HttpStatusCode.cs
+++ /dev/null
@@ -1,321 +0,0 @@
-namespace SocketHttpListener.Net
-{
- /// <summary>
- /// Contains the values of the HTTP status codes.
- /// </summary>
- /// <remarks>
- /// The HttpStatusCode enumeration contains the values of the HTTP status codes defined in
- /// <see href="http://tools.ietf.org/html/rfc2616#section-10">RFC 2616</see> for HTTP 1.1.
- /// </remarks>
- public enum HttpStatusCode
- {
- /// <summary>
- /// Equivalent to status code 100.
- /// Indicates that the client should continue with its request.
- /// </summary>
- Continue = 100,
- /// <summary>
- /// Equivalent to status code 101.
- /// Indicates that the server is switching the HTTP version or protocol on the connection.
- /// </summary>
- SwitchingProtocols = 101,
- /// <summary>
- /// Equivalent to status code 200.
- /// Indicates that the client's request has succeeded.
- /// </summary>
- OK = 200,
- /// <summary>
- /// Equivalent to status code 201.
- /// Indicates that the client's request has been fulfilled and resulted in a new resource being
- /// created.
- /// </summary>
- Created = 201,
- /// <summary>
- /// Equivalent to status code 202.
- /// Indicates that the client's request has been accepted for processing, but the processing
- /// hasn't been completed.
- /// </summary>
- Accepted = 202,
- /// <summary>
- /// Equivalent to status code 203.
- /// Indicates that the returned metainformation is from a local or a third-party copy instead of
- /// the origin server.
- /// </summary>
- NonAuthoritativeInformation = 203,
- /// <summary>
- /// Equivalent to status code 204.
- /// Indicates that the server has fulfilled the client's request but doesn't need to return
- /// an entity-body.
- /// </summary>
- NoContent = 204,
- /// <summary>
- /// Equivalent to status code 205.
- /// Indicates that the server has fulfilled the client's request, and the user agent should
- /// reset the document view which caused the request to be sent.
- /// </summary>
- ResetContent = 205,
- /// <summary>
- /// Equivalent to status code 206.
- /// Indicates that the server has fulfilled the partial GET request for the resource.
- /// </summary>
- PartialContent = 206,
- /// <summary>
- /// <para>
- /// Equivalent to status code 300.
- /// Indicates that the requested resource corresponds to any of multiple representations.
- /// </para>
- /// <para>
- /// MultipleChoices is a synonym for Ambiguous.
- /// </para>
- /// </summary>
- MultipleChoices = 300,
- /// <summary>
- /// <para>
- /// Equivalent to status code 300.
- /// Indicates that the requested resource corresponds to any of multiple representations.
- /// </para>
- /// <para>
- /// Ambiguous is a synonym for MultipleChoices.
- /// </para>
- /// </summary>
- Ambiguous = 300,
- /// <summary>
- /// <para>
- /// Equivalent to status code 301.
- /// Indicates that the requested resource has been assigned a new permanent URI and
- /// any future references to this resource should use one of the returned URIs.
- /// </para>
- /// <para>
- /// MovedPermanently is a synonym for Moved.
- /// </para>
- /// </summary>
- MovedPermanently = 301,
- /// <summary>
- /// <para>
- /// Equivalent to status code 301.
- /// Indicates that the requested resource has been assigned a new permanent URI and
- /// any future references to this resource should use one of the returned URIs.
- /// </para>
- /// <para>
- /// Moved is a synonym for MovedPermanently.
- /// </para>
- /// </summary>
- Moved = 301,
- /// <summary>
- /// <para>
- /// Equivalent to status code 302.
- /// Indicates that the requested resource is located temporarily under a different URI.
- /// </para>
- /// <para>
- /// Found is a synonym for Redirect.
- /// </para>
- /// </summary>
- Found = 302,
- /// <summary>
- /// <para>
- /// Equivalent to status code 302.
- /// Indicates that the requested resource is located temporarily under a different URI.
- /// </para>
- /// <para>
- /// Redirect is a synonym for Found.
- /// </para>
- /// </summary>
- Redirect = 302,
- /// <summary>
- /// <para>
- /// Equivalent to status code 303.
- /// Indicates that the response to the request can be found under a different URI and
- /// should be retrieved using a GET method on that resource.
- /// </para>
- /// <para>
- /// SeeOther is a synonym for RedirectMethod.
- /// </para>
- /// </summary>
- SeeOther = 303,
- /// <summary>
- /// <para>
- /// Equivalent to status code 303.
- /// Indicates that the response to the request can be found under a different URI and
- /// should be retrieved using a GET method on that resource.
- /// </para>
- /// <para>
- /// RedirectMethod is a synonym for SeeOther.
- /// </para>
- /// </summary>
- RedirectMethod = 303,
- /// <summary>
- /// Equivalent to status code 304.
- /// Indicates that the client has performed a conditional GET request and access is allowed,
- /// but the document hasn't been modified.
- /// </summary>
- NotModified = 304,
- /// <summary>
- /// Equivalent to status code 305.
- /// Indicates that the requested resource must be accessed through the proxy given by
- /// the Location field.
- /// </summary>
- UseProxy = 305,
- /// <summary>
- /// Equivalent to status code 306.
- /// This status code was used in a previous version of the specification, is no longer used,
- /// and is reserved for future use.
- /// </summary>
- Unused = 306,
- /// <summary>
- /// <para>
- /// Equivalent to status code 307.
- /// Indicates that the requested resource is located temporarily under a different URI.
- /// </para>
- /// <para>
- /// TemporaryRedirect is a synonym for RedirectKeepVerb.
- /// </para>
- /// </summary>
- TemporaryRedirect = 307,
- /// <summary>
- /// <para>
- /// Equivalent to status code 307.
- /// Indicates that the requested resource is located temporarily under a different URI.
- /// </para>
- /// <para>
- /// RedirectKeepVerb is a synonym for TemporaryRedirect.
- /// </para>
- /// </summary>
- RedirectKeepVerb = 307,
- /// <summary>
- /// Equivalent to status code 400.
- /// Indicates that the client's request couldn't be understood by the server due to
- /// malformed syntax.
- /// </summary>
- BadRequest = 400,
- /// <summary>
- /// Equivalent to status code 401.
- /// Indicates that the client's request requires user authentication.
- /// </summary>
- Unauthorized = 401,
- /// <summary>
- /// Equivalent to status code 402.
- /// This status code is reserved for future use.
- /// </summary>
- PaymentRequired = 402,
- /// <summary>
- /// Equivalent to status code 403.
- /// Indicates that the server understood the client's request but is refusing to fulfill it.
- /// </summary>
- Forbidden = 403,
- /// <summary>
- /// Equivalent to status code 404.
- /// Indicates that the server hasn't found anything matching the request URI.
- /// </summary>
- NotFound = 404,
- /// <summary>
- /// Equivalent to status code 405.
- /// Indicates that the method specified in the request line isn't allowed for the resource
- /// identified by the request URI.
- /// </summary>
- MethodNotAllowed = 405,
- /// <summary>
- /// Equivalent to status code 406.
- /// Indicates that the server doesn't have the appropriate resource to respond to the Accept
- /// headers in the client's request.
- /// </summary>
- NotAcceptable = 406,
- /// <summary>
- /// Equivalent to status code 407.
- /// Indicates that the client must first authenticate itself with the proxy.
- /// </summary>
- ProxyAuthenticationRequired = 407,
- /// <summary>
- /// Equivalent to status code 408.
- /// Indicates that the client didn't produce a request within the time that the server was
- /// prepared to wait.
- /// </summary>
- RequestTimeout = 408,
- /// <summary>
- /// Equivalent to status code 409.
- /// Indicates that the client's request couldn't be completed due to a conflict on the server.
- /// </summary>
- Conflict = 409,
- /// <summary>
- /// Equivalent to status code 410.
- /// Indicates that the requested resource is no longer available at the server and
- /// no forwarding address is known.
- /// </summary>
- Gone = 410,
- /// <summary>
- /// Equivalent to status code 411.
- /// Indicates that the server refuses to accept the client's request without a defined
- /// Content-Length.
- /// </summary>
- LengthRequired = 411,
- /// <summary>
- /// Equivalent to status code 412.
- /// Indicates that the precondition given in one or more of the request headers evaluated to
- /// false when it was tested on the server.
- /// </summary>
- PreconditionFailed = 412,
- /// <summary>
- /// Equivalent to status code 413.
- /// Indicates that the entity of the client's request is larger than the server is willing or
- /// able to process.
- /// </summary>
- RequestEntityTooLarge = 413,
- /// <summary>
- /// Equivalent to status code 414.
- /// Indicates that the request URI is longer than the server is willing to interpret.
- /// </summary>
- RequestUriTooLong = 414,
- /// <summary>
- /// Equivalent to status code 415.
- /// Indicates that the entity of the client's request is in a format not supported by
- /// the requested resource for the requested method.
- /// </summary>
- UnsupportedMediaType = 415,
- /// <summary>
- /// Equivalent to status code 416.
- /// Indicates that none of the range specifier values in a Range request header overlap
- /// the current extent of the selected resource.
- /// </summary>
- RequestedRangeNotSatisfiable = 416,
- /// <summary>
- /// Equivalent to status code 417.
- /// Indicates that the expectation given in an Expect request header couldn't be met by
- /// the server.
- /// </summary>
- ExpectationFailed = 417,
- /// <summary>
- /// Equivalent to status code 500.
- /// Indicates that the server encountered an unexpected condition which prevented it from
- /// fulfilling the client's request.
- /// </summary>
- InternalServerError = 500,
- /// <summary>
- /// Equivalent to status code 501.
- /// Indicates that the server doesn't support the functionality required to fulfill the client's
- /// request.
- /// </summary>
- NotImplemented = 501,
- /// <summary>
- /// Equivalent to status code 502.
- /// Indicates that a gateway or proxy server received an invalid response from the upstream
- /// server.
- /// </summary>
- BadGateway = 502,
- /// <summary>
- /// Equivalent to status code 503.
- /// Indicates that the server is currently unable to handle the client's request due to
- /// a temporary overloading or maintenance of the server.
- /// </summary>
- ServiceUnavailable = 503,
- /// <summary>
- /// Equivalent to status code 504.
- /// Indicates that a gateway or proxy server didn't receive a timely response from the upstream
- /// server or some other auxiliary server.
- /// </summary>
- GatewayTimeout = 504,
- /// <summary>
- /// Equivalent to status code 505.
- /// Indicates that the server doesn't support the HTTP version used in the client's request.
- /// </summary>
- HttpVersionNotSupported = 505,
- }
-}
diff --git a/SocketHttpListener/Net/HttpStatusDescription.cs b/SocketHttpListener/Net/HttpStatusDescription.cs
deleted file mode 100644
index a4e42560b..000000000
--- a/SocketHttpListener/Net/HttpStatusDescription.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal static class HttpStatusDescription
- {
- internal static string Get(HttpStatusCode code)
- {
- return Get((int)code);
- }
-
- internal static string Get(int code)
- {
- switch (code)
- {
- case 100: return "Continue";
- case 101: return "Switching Protocols";
- case 102: return "Processing";
-
- case 200: return "OK";
- case 201: return "Created";
- case 202: return "Accepted";
- case 203: return "Non-Authoritative Information";
- case 204: return "No Content";
- case 205: return "Reset Content";
- case 206: return "Partial Content";
- case 207: return "Multi-Status";
-
- case 300: return "Multiple Choices";
- case 301: return "Moved Permanently";
- case 302: return "Found";
- case 303: return "See Other";
- case 304: return "Not Modified";
- case 305: return "Use Proxy";
- case 307: return "Temporary Redirect";
-
- case 400: return "Bad Request";
- case 401: return "Unauthorized";
- case 402: return "Payment Required";
- case 403: return "Forbidden";
- case 404: return "Not Found";
- case 405: return "Method Not Allowed";
- case 406: return "Not Acceptable";
- case 407: return "Proxy Authentication Required";
- case 408: return "Request Timeout";
- case 409: return "Conflict";
- case 410: return "Gone";
- case 411: return "Length Required";
- case 412: return "Precondition Failed";
- case 413: return "Request Entity Too Large";
- case 414: return "Request-Uri Too Long";
- case 415: return "Unsupported Media Type";
- case 416: return "Requested Range Not Satisfiable";
- case 417: return "Expectation Failed";
- case 422: return "Unprocessable Entity";
- case 423: return "Locked";
- case 424: return "Failed Dependency";
- case 426: return "Upgrade Required"; // RFC 2817
-
- case 500: return "Internal Server Error";
- case 501: return "Not Implemented";
- case 502: return "Bad Gateway";
- case 503: return "Service Unavailable";
- case 504: return "Gateway Timeout";
- case 505: return "Http Version Not Supported";
- case 507: return "Insufficient Storage";
- }
- return null;
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpStreamAsyncResult.cs b/SocketHttpListener/Net/HttpStreamAsyncResult.cs
deleted file mode 100644
index 46944c624..000000000
--- a/SocketHttpListener/Net/HttpStreamAsyncResult.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace SocketHttpListener.Net
-{
- internal class HttpStreamAsyncResult : IAsyncResult
- {
- private object _locker = new object();
- private ManualResetEvent _handle;
- private bool _completed;
-
- internal readonly object _parent;
- internal byte[] _buffer;
- internal int _offset;
- internal int _count;
- internal AsyncCallback _callback;
- internal object _state;
- internal int _synchRead;
- internal Exception _error;
- internal bool _endCalled;
-
- internal HttpStreamAsyncResult(object parent)
- {
- _parent = parent;
- }
-
- public void Complete(Exception e)
- {
- _error = e;
- Complete();
- }
-
- public void Complete()
- {
- lock (_locker)
- {
- if (_completed)
- return;
-
- _completed = true;
- if (_handle != null)
- _handle.Set();
-
- if (_callback != null)
- Task.Run(() => _callback(this));
- }
- }
-
- public object AsyncState => _state;
-
- public WaitHandle AsyncWaitHandle
- {
- get
- {
- lock (_locker)
- {
- if (_handle == null)
- _handle = new ManualResetEvent(_completed);
- }
-
- return _handle;
- }
- }
-
- public bool CompletedSynchronously => false;
-
- public bool IsCompleted
- {
- get
- {
- lock (_locker)
- {
- return _completed;
- }
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/HttpVersion.cs b/SocketHttpListener/Net/HttpVersion.cs
deleted file mode 100644
index c0839b46d..000000000
--- a/SocketHttpListener/Net/HttpVersion.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System;
-
-namespace SocketHttpListener.Net
-{
- // <remarks>
- // </remarks>
- public class HttpVersion
- {
-
- public static readonly Version Version10 = new Version(1, 0);
- public static readonly Version Version11 = new Version(1, 1);
-
- // pretty useless..
- public HttpVersion() { }
- }
-}
diff --git a/SocketHttpListener/Net/ListenerPrefix.cs b/SocketHttpListener/Net/ListenerPrefix.cs
deleted file mode 100644
index edfcb8904..000000000
--- a/SocketHttpListener/Net/ListenerPrefix.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-using System;
-using System.Net;
-
-namespace SocketHttpListener.Net
-{
- internal sealed class ListenerPrefix
- {
- private string _original;
- private string _host;
- private ushort _port;
- private string _path;
- private bool _secure;
- private IPAddress[] _addresses;
- internal HttpListener _listener;
-
- public ListenerPrefix(string prefix)
- {
- _original = prefix;
- Parse(prefix);
- }
-
- public override string ToString()
- {
- return _original;
- }
-
- public IPAddress[] Addresses
- {
- get => _addresses;
- set => _addresses = value;
- }
- public bool Secure => _secure;
-
- public string Host => _host;
-
- public int Port => _port;
-
- public string Path => _path;
-
- // Equals and GetHashCode are required to detect duplicates in HttpListenerPrefixCollection.
- public override bool Equals(object o)
- {
- var other = o as ListenerPrefix;
- if (other == null)
- return false;
-
- return (_original == other._original);
- }
-
- public override int GetHashCode()
- {
- return _original.GetHashCode();
- }
-
- private void Parse(string uri)
- {
- ushort default_port = 80;
- if (uri.StartsWith("https://"))
- {
- default_port = 443;
- _secure = true;
- }
-
- int length = uri.Length;
- int start_host = uri.IndexOf(':') + 3;
- if (start_host >= length)
- throw new ArgumentException("net_listener_host");
-
- int colon = uri.IndexOf(':', start_host, length - start_host);
- int root;
- if (colon > 0)
- {
- _host = uri.Substring(start_host, colon - start_host);
- root = uri.IndexOf('/', colon, length - colon);
- _port = (ushort)int.Parse(uri.Substring(colon + 1, root - colon - 1));
- _path = uri.Substring(root);
- }
- else
- {
- root = uri.IndexOf('/', start_host, length - start_host);
- _host = uri.Substring(start_host, root - start_host);
- _port = default_port;
- _path = uri.Substring(root);
- }
- if (_path.Length != 1)
- _path = _path.Substring(0, _path.Length - 1);
- }
- }
-}
diff --git a/SocketHttpListener/Net/UriScheme.cs b/SocketHttpListener/Net/UriScheme.cs
deleted file mode 100644
index 33d1f09db..000000000
--- a/SocketHttpListener/Net/UriScheme.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace SocketHttpListener.Net
-{
- internal static class UriScheme
- {
- public const string File = "file";
- public const string Ftp = "ftp";
- public const string Gopher = "gopher";
- public const string Http = "http";
- public const string Https = "https";
- public const string News = "news";
- public const string NetPipe = "net.pipe";
- public const string NetTcp = "net.tcp";
- public const string Nntp = "nntp";
- public const string Mailto = "mailto";
- public const string Ws = "ws";
- public const string Wss = "wss";
-
- public const string SchemeDelimiter = "://";
- }
-}
diff --git a/SocketHttpListener/Net/WebHeaderCollection.cs b/SocketHttpListener/Net/WebHeaderCollection.cs
deleted file mode 100644
index 34fca808b..000000000
--- a/SocketHttpListener/Net/WebHeaderCollection.cs
+++ /dev/null
@@ -1,360 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Text;
-using MediaBrowser.Model.Services;
-
-namespace SocketHttpListener.Net
-{
- [ComVisible(true)]
- public class WebHeaderCollection : QueryParamCollection
- {
- [Flags]
- internal enum HeaderInfo
- {
- Request = 1,
- Response = 1 << 1,
- MultiValue = 1 << 10
- }
-
- static readonly bool[] allowed_chars = {
- false, false, false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, true, false, true, true, true, true, false, false, false, true,
- true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false,
- false, false, false, false, false, false, true, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
- false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
- false, true, false
- };
-
- static readonly Dictionary<string, HeaderInfo> headers;
-
- static WebHeaderCollection()
- {
- headers = new Dictionary<string, HeaderInfo>(StringComparer.OrdinalIgnoreCase) {
- { "Allow", HeaderInfo.MultiValue },
- { "Accept", HeaderInfo.Request | HeaderInfo.MultiValue },
- { "Accept-Charset", HeaderInfo.MultiValue },
- { "Accept-Encoding", HeaderInfo.MultiValue },
- { "Accept-Language", HeaderInfo.MultiValue },
- { "Accept-Ranges", HeaderInfo.MultiValue },
- { "Age", HeaderInfo.Response },
- { "Authorization", HeaderInfo.MultiValue },
- { "Cache-Control", HeaderInfo.MultiValue },
- { "Cookie", HeaderInfo.MultiValue },
- { "Connection", HeaderInfo.Request | HeaderInfo.MultiValue },
- { "Content-Encoding", HeaderInfo.MultiValue },
- { "Content-Length", HeaderInfo.Request | HeaderInfo.Response },
- { "Content-Type", HeaderInfo.Request },
- { "Content-Language", HeaderInfo.MultiValue },
- { "Date", HeaderInfo.Request },
- { "Expect", HeaderInfo.Request | HeaderInfo.MultiValue},
- { "Host", HeaderInfo.Request },
- { "If-Match", HeaderInfo.MultiValue },
- { "If-Modified-Since", HeaderInfo.Request },
- { "If-None-Match", HeaderInfo.MultiValue },
- { "Keep-Alive", HeaderInfo.Response },
- { "Pragma", HeaderInfo.MultiValue },
- { "Proxy-Authenticate", HeaderInfo.MultiValue },
- { "Proxy-Authorization", HeaderInfo.MultiValue },
- { "Proxy-Connection", HeaderInfo.Request | HeaderInfo.MultiValue },
- { "Range", HeaderInfo.Request | HeaderInfo.MultiValue },
- { "Referer", HeaderInfo.Request },
- { "Set-Cookie", HeaderInfo.MultiValue },
- { "Set-Cookie2", HeaderInfo.MultiValue },
- { "Server", HeaderInfo.Response },
- { "TE", HeaderInfo.MultiValue },
- { "Trailer", HeaderInfo.MultiValue },
- { "Transfer-Encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue },
- { "Translate", HeaderInfo.Request | HeaderInfo.Response },
- { "Upgrade", HeaderInfo.MultiValue },
- { "User-Agent", HeaderInfo.Request },
- { "Vary", HeaderInfo.MultiValue },
- { "Via", HeaderInfo.MultiValue },
- { "Warning", HeaderInfo.MultiValue },
- { "WWW-Authenticate", HeaderInfo.Response | HeaderInfo. MultiValue },
- { "SecWebSocketAccept", HeaderInfo.Response },
- { "SecWebSocketExtensions", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue },
- { "SecWebSocketKey", HeaderInfo.Request },
- { "Sec-WebSocket-Protocol", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue },
- { "SecWebSocketVersion", HeaderInfo.Response | HeaderInfo. MultiValue }
- };
- }
-
- // Methods
-
- public void Add(string header)
- {
- if (header == null)
- throw new ArgumentNullException(nameof(header));
- int pos = header.IndexOf(':');
- if (pos == -1)
- throw new ArgumentException("no colon found", nameof(header));
-
- this.Add(header.Substring(0, pos), header.Substring(pos + 1));
- }
-
- public override void Add(string name, string value)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- this.AddWithoutValidate(name, value);
- }
-
- protected void AddWithoutValidate(string headerName, string headerValue)
- {
- if (!IsHeaderName(headerName))
- throw new ArgumentException("invalid header name: " + headerName, nameof(headerName));
- if (headerValue == null)
- headerValue = string.Empty;
- else
- headerValue = headerValue.Trim();
- if (!IsHeaderValue(headerValue))
- throw new ArgumentException("invalid header value: " + headerValue, nameof(headerValue));
-
- AddValue(headerName, headerValue);
- }
-
- internal void AddValue(string headerName, string headerValue)
- {
- base.Add(headerName, headerValue);
- }
-
- internal List<string> GetValues_internal(string header, bool split)
- {
- if (header == null)
- throw new ArgumentNullException(nameof(header));
-
- var values = base.GetValues(header);
- if (values == null || values.Count == 0)
- return null;
-
- if (split && IsMultiValue(header))
- {
- List<string> separated = null;
- foreach (var value in values)
- {
- if (value.IndexOf(',') < 0)
- {
- if (separated != null)
- separated.Add(value);
-
- continue;
- }
-
- if (separated == null)
- {
- separated = new List<string>(values.Count + 1);
- foreach (var v in values)
- {
- if (v == value)
- break;
-
- separated.Add(v);
- }
- }
-
- var slices = value.Split(',');
- var slices_length = slices.Length;
- if (value[value.Length - 1] == ',')
- --slices_length;
-
- for (int i = 0; i < slices_length; ++i)
- {
- separated.Add(slices[i].Trim());
- }
- }
-
- if (separated != null)
- return separated;
- }
-
- return values;
- }
-
- public override List<string> GetValues(string header)
- {
- return GetValues_internal(header, true);
- }
-
- public override string[] GetValues(int index)
- {
- string[] values = base.GetValues(index);
-
- if (values == null || values.Length == 0)
- {
- return null;
- }
-
- return values;
- }
-
- public static bool IsRestricted(string headerName)
- {
- return IsRestricted(headerName, false);
- }
-
- public static bool IsRestricted(string headerName, bool response)
- {
- if (headerName == null)
- throw new ArgumentNullException(nameof(headerName));
-
- if (headerName.Length == 0)
- throw new ArgumentException("empty string", nameof(headerName));
-
- if (!IsHeaderName(headerName))
- throw new ArgumentException("Invalid character in header");
-
- if (!headers.TryGetValue(headerName, out HeaderInfo info))
- return false;
-
- var flag = response ? HeaderInfo.Response : HeaderInfo.Request;
- return (info & flag) != 0;
- }
-
- public override void Set(string name, string value)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (!IsHeaderName(name))
- throw new ArgumentException("invalid header name");
- if (value == null)
- value = string.Empty;
- else
- value = value.Trim();
- if (!IsHeaderValue(value))
- throw new ArgumentException("invalid header value");
-
- base.Set(name, value);
- }
-
- internal string ToStringMultiValue()
- {
- var sb = new StringBuilder();
-
- int count = base.Count;
- for (int i = 0; i < count; i++)
- {
- string key = GetKey(i);
- if (IsMultiValue(key))
- {
- foreach (string v in GetValues(i))
- {
- sb.Append(key)
- .Append(": ")
- .Append(v)
- .Append("\r\n");
- }
- }
- else
- {
- sb.Append(key)
- .Append(": ")
- .Append(Get(i))
- .Append("\r\n");
- }
- }
- return sb.Append("\r\n").ToString();
- }
-
- public override string ToString()
- {
- var sb = new StringBuilder();
-
- int count = base.Count;
- for (int i = 0; i < count; i++)
- sb.Append(GetKey(i))
- .Append(": ")
- .Append(Get(i))
- .Append("\r\n");
-
- return sb.Append("\r\n").ToString();
- }
-
-
- // Internal Methods
-
- // With this we don't check for invalid characters in header. See bug #55994.
- internal void SetInternal(string header)
- {
- int pos = header.IndexOf(':');
- if (pos == -1)
- throw new ArgumentException("no colon found", nameof(header));
-
- SetInternal(header.Substring(0, pos), header.Substring(pos + 1));
- }
-
- internal void SetInternal(string name, string value)
- {
- if (value == null)
- value = string.Empty;
- else
- value = value.Trim();
- if (!IsHeaderValue(value))
- throw new ArgumentException("invalid header value");
-
- if (IsMultiValue(name))
- {
- base.Add(name, value);
- }
- else
- {
- base.Remove(name);
- base.Set(name, value);
- }
- }
-
- internal static bool IsMultiValue(string headerName)
- {
- if (headerName == null)
- return false;
-
- return headers.TryGetValue(headerName, out HeaderInfo info) && (info & HeaderInfo.MultiValue) != 0;
- }
-
- internal static bool IsHeaderValue(string value)
- {
- // TEXT any 8 bit value except CTL's (0-31 and 127)
- // but including \r\n space and \t
- // after a newline at least one space or \t must follow
- // certain header fields allow comments ()
-
- int len = value.Length;
- for (int i = 0; i < len; i++)
- {
- char c = value[i];
- if (c == 127)
- return false;
- if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
- return false;
- if (c == '\n' && ++i < len)
- {
- c = value[i];
- if (c != ' ' && c != '\t')
- return false;
- }
- }
-
- return true;
- }
-
- internal static bool IsHeaderName(string name)
- {
- if (name == null || name.Length == 0)
- return false;
-
- int len = name.Length;
- for (int i = 0; i < len; i++)
- {
- char c = name[i];
- if (c > 126 || !allowed_chars[c])
- return false;
- }
-
- return true;
- }
- }
-}
diff --git a/SocketHttpListener/Net/WebHeaderEncoding.cs b/SocketHttpListener/Net/WebHeaderEncoding.cs
deleted file mode 100644
index 96e0cc85d..000000000
--- a/SocketHttpListener/Net/WebHeaderEncoding.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-using System.Text;
-
-namespace SocketHttpListener.Net
-{
- // we use this static class as a helper class to encode/decode HTTP headers.
- // what we need is a 1-1 correspondence between a char in the range U+0000-U+00FF
- // and a byte in the range 0x00-0xFF (which is the range that can hit the network).
- // The Latin-1 encoding (ISO-88591-1) (GetEncoding(28591)) works for byte[] to string, but is a little slow.
- // It doesn't work for string -> byte[] because of best-fit-mapping problems.
- internal static class WebHeaderEncoding
- {
- // We don't want '?' replacement characters, just fail.
- private static readonly Encoding s_utf8Decoder = Encoding.GetEncoding("utf-8", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
-
- internal static unsafe string GetString(byte[] bytes, int byteIndex, int byteCount)
- {
- fixed (byte* pBytes = bytes)
- return GetString(pBytes + byteIndex, byteCount);
- }
-
- internal static unsafe string GetString(byte* pBytes, int byteCount)
- {
- if (byteCount < 1)
- return "";
-
- string s = new string('\0', byteCount);
-
- fixed (char* pStr = s)
- {
- char* pString = pStr;
- while (byteCount >= 8)
- {
- pString[0] = (char)pBytes[0];
- pString[1] = (char)pBytes[1];
- pString[2] = (char)pBytes[2];
- pString[3] = (char)pBytes[3];
- pString[4] = (char)pBytes[4];
- pString[5] = (char)pBytes[5];
- pString[6] = (char)pBytes[6];
- pString[7] = (char)pBytes[7];
- pString += 8;
- pBytes += 8;
- byteCount -= 8;
- }
- for (int i = 0; i < byteCount; i++)
- {
- pString[i] = (char)pBytes[i];
- }
- }
-
- return s;
- }
-
- internal static int GetByteCount(string myString)
- {
- return myString.Length;
- }
- internal static unsafe void GetBytes(string myString, int charIndex, int charCount, byte[] bytes, int byteIndex)
- {
- if (myString.Length == 0)
- {
- return;
- }
- fixed (byte* bufferPointer = bytes)
- {
- byte* newBufferPointer = bufferPointer + byteIndex;
- int finalIndex = charIndex + charCount;
- while (charIndex < finalIndex)
- {
- *newBufferPointer++ = (byte)myString[charIndex++];
- }
- }
- }
- internal static byte[] GetBytes(string myString)
- {
- byte[] bytes = new byte[myString.Length];
- if (myString.Length != 0)
- {
- GetBytes(myString, 0, myString.Length, bytes, 0);
- }
- return bytes;
- }
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/HttpListenerWebSocketContext.cs b/SocketHttpListener/Net/WebSockets/HttpListenerWebSocketContext.cs
deleted file mode 100644
index 5ed49ec47..000000000
--- a/SocketHttpListener/Net/WebSockets/HttpListenerWebSocketContext.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using System.Security.Principal;
-using MediaBrowser.Model.Services;
-
-namespace SocketHttpListener.Net.WebSockets
-{
- public class HttpListenerWebSocketContext : WebSocketContext
- {
- private readonly Uri _requestUri;
- private readonly QueryParamCollection _headers;
- private readonly CookieCollection _cookieCollection;
- private readonly IPrincipal _user;
- private readonly bool _isAuthenticated;
- private readonly bool _isLocal;
- private readonly bool _isSecureConnection;
-
- private readonly string _origin;
- private readonly IEnumerable<string> _secWebSocketProtocols;
- private readonly string _secWebSocketVersion;
- private readonly string _secWebSocketKey;
-
- private readonly WebSocket _webSocket;
-
- internal HttpListenerWebSocketContext(
- Uri requestUri,
- QueryParamCollection headers,
- CookieCollection cookieCollection,
- IPrincipal user,
- bool isAuthenticated,
- bool isLocal,
- bool isSecureConnection,
- string origin,
- IEnumerable<string> secWebSocketProtocols,
- string secWebSocketVersion,
- string secWebSocketKey,
- WebSocket webSocket)
- {
- _cookieCollection = new CookieCollection();
- _cookieCollection.Add(cookieCollection);
-
- //_headers = new NameValueCollection(headers);
- _headers = headers;
- _user = CopyPrincipal(user);
-
- _requestUri = requestUri;
- _isAuthenticated = isAuthenticated;
- _isLocal = isLocal;
- _isSecureConnection = isSecureConnection;
- _origin = origin;
- _secWebSocketProtocols = secWebSocketProtocols;
- _secWebSocketVersion = secWebSocketVersion;
- _secWebSocketKey = secWebSocketKey;
- _webSocket = webSocket;
- }
-
- public override Uri RequestUri => _requestUri;
-
- public override QueryParamCollection Headers => _headers;
-
- public override string Origin => _origin;
-
- public override IEnumerable<string> SecWebSocketProtocols => _secWebSocketProtocols;
-
- public override string SecWebSocketVersion => _secWebSocketVersion;
-
- public override string SecWebSocketKey => _secWebSocketKey;
-
- public override CookieCollection CookieCollection => _cookieCollection;
-
- public override IPrincipal User => _user;
-
- public override bool IsAuthenticated => _isAuthenticated;
-
- public override bool IsLocal => _isLocal;
-
- public override bool IsSecureConnection => _isSecureConnection;
-
- public override WebSocket WebSocket => _webSocket;
-
- private static IPrincipal CopyPrincipal(IPrincipal user)
- {
- if (user != null)
- {
- throw new NotImplementedException();
- }
-
- return null;
- }
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/HttpWebSocket.Managed.cs b/SocketHttpListener/Net/WebSockets/HttpWebSocket.Managed.cs
deleted file mode 100644
index 1cfd2dc90..000000000
--- a/SocketHttpListener/Net/WebSockets/HttpWebSocket.Managed.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-using System;
-using System.Threading.Tasks;
-
-namespace SocketHttpListener.Net.WebSockets
-{
- internal static partial class HttpWebSocket
- {
- private const string SupportedVersion = "13";
-
- internal static async Task<HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
- string subProtocol,
- int receiveBufferSize,
- TimeSpan keepAliveInterval,
- ArraySegment<byte>? internalBuffer = null)
- {
- ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval);
-
- // get property will create a new response if one doesn't exist.
- HttpListenerResponse response = context.Response;
- HttpListenerRequest request = context.Request;
- ValidateWebSocketHeaders(context);
-
- string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
-
- // Optional for non-browser client
- string origin = request.Headers[HttpKnownHeaderNames.Origin];
-
- string[] secWebSocketProtocols = null;
- bool shouldSendSecWebSocketProtocolHeader =
- ProcessWebSocketProtocolHeader(
- request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
- subProtocol,
- out var outgoingSecWebSocketProtocolString);
-
- if (shouldSendSecWebSocketProtocolHeader)
- {
- secWebSocketProtocols = new string[] { outgoingSecWebSocketProtocolString };
- response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString);
- }
-
- // negotiate the websocket key return value
- string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
- string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey);
-
- response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
- response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
- response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);
-
- response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
- response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols);
-
- var responseStream = response.OutputStream as HttpResponseStream;
-
- // Send websocket handshake headers
- await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false);
-
- //WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer: true, subProtocol, keepAliveInterval);
- var webSocket = new WebSocket(subProtocol);
-
- var webSocketContext = new HttpListenerWebSocketContext(
- request.Url,
- request.Headers,
- request.Cookies,
- context.User,
- request.IsAuthenticated,
- request.IsLocal,
- request.IsSecureConnection,
- origin,
- secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty<string>(),
- secWebSocketVersion,
- secWebSocketKey,
- webSocket);
-
- webSocket.SetContext(webSocketContext, context.Connection.Close, context.Connection.Stream);
-
- return webSocketContext;
- }
-
- private const bool WebSocketsSupported = true;
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/HttpWebSocket.cs b/SocketHttpListener/Net/WebSockets/HttpWebSocket.cs
deleted file mode 100644
index b346cc98e..000000000
--- a/SocketHttpListener/Net/WebSockets/HttpWebSocket.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Security.Cryptography;
-using System.Text;
-using System.Threading;
-
-namespace SocketHttpListener.Net.WebSockets
-{
- internal static partial class HttpWebSocket
- {
- internal const string SecWebSocketKeyGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
- internal const string WebSocketUpgradeToken = "websocket";
- internal const int DefaultReceiveBufferSize = 16 * 1024;
- internal const int DefaultClientSendBufferSize = 16 * 1024;
-
- [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 used only for hashing purposes, not for crypto.")]
- internal static string GetSecWebSocketAcceptString(string secWebSocketKey)
- {
- string retVal;
-
- // SHA1 used only for hashing purposes, not for crypto. Check here for FIPS compat.
- using (var sha1 = SHA1.Create())
- {
- string acceptString = string.Concat(secWebSocketKey, HttpWebSocket.SecWebSocketKeyGuid);
- byte[] toHash = Encoding.UTF8.GetBytes(acceptString);
- retVal = Convert.ToBase64String(sha1.ComputeHash(toHash));
- }
-
- return retVal;
- }
-
- // return value here signifies if a Sec-WebSocket-Protocol header should be returned by the server.
- internal static bool ProcessWebSocketProtocolHeader(string clientSecWebSocketProtocol,
- string subProtocol,
- out string acceptProtocol)
- {
- acceptProtocol = string.Empty;
- if (string.IsNullOrEmpty(clientSecWebSocketProtocol))
- {
- // client hasn't specified any Sec-WebSocket-Protocol header
- if (subProtocol != null)
- {
- // If the server specified _anything_ this isn't valid.
- throw new WebSocketException("UnsupportedProtocol");
- }
- // Treat empty and null from the server as the same thing here, server should not send headers.
- return false;
- }
-
- // here, we know the client specified something and it's non-empty.
-
- if (subProtocol == null)
- {
- // client specified some protocols, server specified 'null'. So server should send headers.
- return true;
- }
-
- // here, we know that the client has specified something, it's not empty
- // and the server has specified exactly one protocol
-
- string[] requestProtocols = clientSecWebSocketProtocol.Split(new char[] { ',' },
- StringSplitOptions.RemoveEmptyEntries);
- acceptProtocol = subProtocol;
-
- // client specified protocols, serverOptions has exactly 1 non-empty entry. Check that
- // this exists in the list the client specified.
- for (int i = 0; i < requestProtocols.Length; i++)
- {
- string currentRequestProtocol = requestProtocols[i].Trim();
- if (string.Equals(acceptProtocol, currentRequestProtocol, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- throw new WebSocketException("net_WebSockets_AcceptUnsupportedProtocol");
- }
-
- internal static void ValidateOptions(string subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval)
- {
- if (subProtocol != null)
- {
- WebSocketValidate.ValidateSubprotocol(subProtocol);
- }
-
- if (receiveBufferSize < MinReceiveBufferSize)
- {
- throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), "The receiveBufferSize was too small.");
- }
-
- if (sendBufferSize < MinSendBufferSize)
- {
- throw new ArgumentOutOfRangeException(nameof(sendBufferSize), "The sendBufferSize was too small.");
- }
-
- if (receiveBufferSize > MaxBufferSize)
- {
- throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), "The receiveBufferSize was too large.");
- }
-
- if (sendBufferSize > MaxBufferSize)
- {
- throw new ArgumentOutOfRangeException(nameof(sendBufferSize), "The sendBufferSize was too large.");
- }
-
- if (keepAliveInterval < Timeout.InfiniteTimeSpan) // -1 millisecond
- {
- throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), "The keepAliveInterval was too small.");
- }
- }
-
- internal const int MinSendBufferSize = 16;
- internal const int MinReceiveBufferSize = 256;
- internal const int MaxBufferSize = 64 * 1024;
-
- private static void ValidateWebSocketHeaders(HttpListenerContext context)
- {
- if (!WebSocketsSupported)
- {
- throw new PlatformNotSupportedException("net_WebSockets_UnsupportedPlatform");
- }
-
- if (!context.Request.IsWebSocketRequest)
- {
- throw new WebSocketException("net_WebSockets_AcceptNotAWebSocket");
- }
-
- string secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
- if (string.IsNullOrEmpty(secWebSocketVersion))
- {
- throw new WebSocketException("net_WebSockets_AcceptHeaderNotFound");
- }
-
- if (!string.Equals(secWebSocketVersion, SupportedVersion, StringComparison.OrdinalIgnoreCase))
- {
- throw new WebSocketException("net_WebSockets_AcceptUnsupportedWebSocketVersion");
- }
-
- string secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
- bool isSecWebSocketKeyInvalid = string.IsNullOrWhiteSpace(secWebSocketKey);
- if (!isSecWebSocketKeyInvalid)
- {
- try
- {
- // key must be 16 bytes then base64-encoded
- isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey).Length != 16;
- }
- catch
- {
- isSecWebSocketKeyInvalid = true;
- }
- }
- if (isSecWebSocketKeyInvalid)
- {
- throw new WebSocketException("net_WebSockets_AcceptHeaderNotFound");
- }
- }
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/WebSocketCloseStatus.cs b/SocketHttpListener/Net/WebSockets/WebSocketCloseStatus.cs
deleted file mode 100644
index 5ac89cf48..000000000
--- a/SocketHttpListener/Net/WebSockets/WebSocketCloseStatus.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-namespace SocketHttpListener.Net.WebSockets
-{
- public enum WebSocketCloseStatus
- {
- NormalClosure = 1000,
- EndpointUnavailable = 1001,
- ProtocolError = 1002,
- InvalidMessageType = 1003,
- Empty = 1005,
- // AbnormalClosure = 1006, // 1006 is reserved and should never be used by user
- InvalidPayloadData = 1007,
- PolicyViolation = 1008,
- MessageTooBig = 1009,
- MandatoryExtension = 1010,
- InternalServerError = 1011
- // TLSHandshakeFailed = 1015, // 1015 is reserved and should never be used by user
-
- // 0 - 999 Status codes in the range 0-999 are not used.
- // 1000 - 1999 Status codes in the range 1000-1999 are reserved for definition by this protocol.
- // 2000 - 2999 Status codes in the range 2000-2999 are reserved for use by extensions.
- // 3000 - 3999 Status codes in the range 3000-3999 MAY be used by libraries and frameworks. The
- // interpretation of these codes is undefined by this protocol. End applications MUST
- // NOT use status codes in this range.
- // 4000 - 4999 Status codes in the range 4000-4999 MAY be used by application code. The interpretation
- // of these codes is undefined by this protocol.
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/WebSocketContext.cs b/SocketHttpListener/Net/WebSockets/WebSocketContext.cs
deleted file mode 100644
index 10ad86439..000000000
--- a/SocketHttpListener/Net/WebSockets/WebSocketContext.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using System.Security.Principal;
-using MediaBrowser.Model.Services;
-
-namespace SocketHttpListener.Net.WebSockets
-{
- public abstract class WebSocketContext
- {
- public abstract Uri RequestUri { get; }
- public abstract QueryParamCollection Headers { get; }
- public abstract string Origin { get; }
- public abstract IEnumerable<string> SecWebSocketProtocols { get; }
- public abstract string SecWebSocketVersion { get; }
- public abstract string SecWebSocketKey { get; }
- public abstract CookieCollection CookieCollection { get; }
- public abstract IPrincipal User { get; }
- public abstract bool IsAuthenticated { get; }
- public abstract bool IsLocal { get; }
- public abstract bool IsSecureConnection { get; }
- public abstract WebSocket WebSocket { get; }
- }
-}
diff --git a/SocketHttpListener/Net/WebSockets/WebSocketValidate.cs b/SocketHttpListener/Net/WebSockets/WebSocketValidate.cs
deleted file mode 100644
index 0469e3b6c..000000000
--- a/SocketHttpListener/Net/WebSockets/WebSocketValidate.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-using System;
-using System.Globalization;
-using System.Text;
-using WebSocketState = System.Net.WebSockets.WebSocketState;
-
-namespace SocketHttpListener.Net.WebSockets
-{
- internal static partial class WebSocketValidate
- {
- internal const int MaxControlFramePayloadLength = 123;
- private const int CloseStatusCodeAbort = 1006;
- private const int CloseStatusCodeFailedTLSHandshake = 1015;
- private const int InvalidCloseStatusCodesFrom = 0;
- private const int InvalidCloseStatusCodesTo = 999;
- private const string Separators = "()<>@,;:\\\"/[]?={} ";
-
- internal static void ThrowIfInvalidState(WebSocketState currentState, bool isDisposed, WebSocketState[] validStates)
- {
- string validStatesText = string.Empty;
-
- if (validStates != null && validStates.Length > 0)
- {
- foreach (WebSocketState validState in validStates)
- {
- if (currentState == validState)
- {
- // Ordering is important to maintain .NET 4.5 WebSocket implementation exception behavior.
- if (isDisposed)
- {
- throw new ObjectDisposedException(nameof(WebSocket));
- }
-
- return;
- }
- }
-
- validStatesText = string.Join(", ", validStates);
- }
-
- throw new WebSocketException("net_WebSockets_InvalidState");
- }
-
- internal static void ValidateSubprotocol(string subProtocol)
- {
- if (string.IsNullOrWhiteSpace(subProtocol))
- {
- throw new ArgumentException("net_WebSockets_InvalidEmptySubProtocol");
- }
-
- string invalidChar = null;
- int i = 0;
- while (i < subProtocol.Length)
- {
- char ch = subProtocol[i];
- if (ch < 0x21 || ch > 0x7e)
- {
- invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch);
- break;
- }
-
- if (!char.IsLetterOrDigit(ch) &&
- Separators.IndexOf(ch) >= 0)
- {
- invalidChar = ch.ToString();
- break;
- }
-
- i++;
- }
-
- if (invalidChar != null)
- {
- throw new ArgumentException("net_WebSockets_InvalidCharInProtocolString");
- }
- }
-
- internal static void ValidateCloseStatus(WebSocketCloseStatus closeStatus, string statusDescription)
- {
- if (closeStatus == WebSocketCloseStatus.Empty && !string.IsNullOrEmpty(statusDescription))
- {
- throw new ArgumentException("net_WebSockets_ReasonNotNull");
- }
-
- int closeStatusCode = (int)closeStatus;
-
- if ((closeStatusCode >= InvalidCloseStatusCodesFrom &&
- closeStatusCode <= InvalidCloseStatusCodesTo) ||
- closeStatusCode == CloseStatusCodeAbort ||
- closeStatusCode == CloseStatusCodeFailedTLSHandshake)
- {
- // CloseStatus 1006 means Aborted - this will never appear on the wire and is reflected by calling WebSocket.Abort
- throw new ArgumentException("net_WebSockets_InvalidCloseStatusCode");
- }
-
- int length = 0;
- if (!string.IsNullOrEmpty(statusDescription))
- {
- length = Encoding.UTF8.GetByteCount(statusDescription);
- }
-
- if (length > MaxControlFramePayloadLength)
- {
- throw new ArgumentException("net_WebSockets_InvalidCloseStatusDescription");
- }
- }
-
- internal static void ValidateArraySegment(ArraySegment<byte> arraySegment, string parameterName)
- {
- if (arraySegment.Array == null)
- {
- throw new ArgumentNullException(parameterName + "." + nameof(arraySegment.Array));
- }
- if (arraySegment.Offset < 0 || arraySegment.Offset > arraySegment.Array.Length)
- {
- throw new ArgumentOutOfRangeException(parameterName + "." + nameof(arraySegment.Offset));
- }
- if (arraySegment.Count < 0 || arraySegment.Count > (arraySegment.Array.Length - arraySegment.Offset))
- {
- throw new ArgumentOutOfRangeException(parameterName + "." + nameof(arraySegment.Count));
- }
- }
-
- internal static void ValidateBuffer(byte[] buffer, int offset, int count)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
-
- if (offset < 0 || offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(offset));
- }
-
- if (count < 0 || count > (buffer.Length - offset))
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
- }
- }
-}
diff --git a/SocketHttpListener/Opcode.cs b/SocketHttpListener/Opcode.cs
deleted file mode 100644
index 69cf3f372..000000000
--- a/SocketHttpListener/Opcode.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-namespace SocketHttpListener
-{
- /// <summary>
- /// Contains the values of the opcode that indicates the type of a WebSocket frame.
- /// </summary>
- /// <remarks>
- /// The values of the opcode are defined in
- /// <see href="http://tools.ietf.org/html/rfc6455#section-5.2">Section 5.2</see> of RFC 6455.
- /// </remarks>
- public enum Opcode : byte
- {
- /// <summary>
- /// Equivalent to numeric value 0.
- /// Indicates a continuation frame.
- /// </summary>
- Cont = 0x0,
- /// <summary>
- /// Equivalent to numeric value 1.
- /// Indicates a text frame.
- /// </summary>
- Text = 0x1,
- /// <summary>
- /// Equivalent to numeric value 2.
- /// Indicates a binary frame.
- /// </summary>
- Binary = 0x2,
- /// <summary>
- /// Equivalent to numeric value 8.
- /// Indicates a connection close frame.
- /// </summary>
- Close = 0x8,
- /// <summary>
- /// Equivalent to numeric value 9.
- /// Indicates a ping frame.
- /// </summary>
- Ping = 0x9,
- /// <summary>
- /// Equivalent to numeric value 10.
- /// Indicates a pong frame.
- /// </summary>
- Pong = 0xa
- }
-}
diff --git a/SocketHttpListener/PayloadData.cs b/SocketHttpListener/PayloadData.cs
deleted file mode 100644
index 6d15a6bcb..000000000
--- a/SocketHttpListener/PayloadData.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Text;
-
-namespace SocketHttpListener
-{
- internal class PayloadData : IEnumerable<byte>
- {
- #region Private Fields
-
- private byte[] _applicationData;
- private byte[] _extensionData;
- private bool _masked;
-
- #endregion
-
- #region Public Const Fields
-
- public const ulong MaxLength = long.MaxValue;
-
- #endregion
-
- #region Public Constructors
-
- public PayloadData()
- : this(new byte[0], new byte[0], false)
- {
- }
-
- public PayloadData(byte[] applicationData)
- : this(new byte[0], applicationData, false)
- {
- }
-
- public PayloadData(string applicationData)
- : this(new byte[0], Encoding.UTF8.GetBytes(applicationData), false)
- {
- }
-
- public PayloadData(byte[] applicationData, bool masked)
- : this(new byte[0], applicationData, masked)
- {
- }
-
- public PayloadData(byte[] extensionData, byte[] applicationData, bool masked)
- {
- _extensionData = extensionData;
- _applicationData = applicationData;
- _masked = masked;
- }
-
- #endregion
-
- #region Internal Properties
-
- internal bool ContainsReservedCloseStatusCode =>
- _applicationData.Length > 1 &&
- _applicationData.SubArray(0, 2).ToUInt16(ByteOrder.Big).IsReserved();
-
- #endregion
-
- #region Public Properties
-
- public byte[] ApplicationData => _applicationData;
-
- public byte[] ExtensionData => _extensionData;
-
- public bool IsMasked => _masked;
-
- public ulong Length => (ulong)(_extensionData.Length + _applicationData.Length);
-
- #endregion
-
- #region Private Methods
-
- private static void mask(byte[] src, byte[] key)
- {
- for (long i = 0; i < src.Length; i++)
- src[i] = (byte)(src[i] ^ key[i % 4]);
- }
-
- #endregion
-
- #region Public Methods
-
- public IEnumerator<byte> GetEnumerator()
- {
- foreach (byte b in _extensionData)
- yield return b;
-
- foreach (byte b in _applicationData)
- yield return b;
- }
-
- public void Mask(byte[] maskingKey)
- {
- if (_extensionData.Length > 0)
- mask(_extensionData, maskingKey);
-
- if (_applicationData.Length > 0)
- mask(_applicationData, maskingKey);
-
- _masked = !_masked;
- }
-
- public byte[] ToByteArray()
- {
- return _extensionData.Length > 0
- ? new List<byte>(this).ToArray()
- : _applicationData;
- }
-
- public override string ToString()
- {
- return BitConverter.ToString(ToByteArray());
- }
-
- #endregion
-
- #region Explicitly Implemented Interface Members
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/Properties/AssemblyInfo.cs b/SocketHttpListener/Properties/AssemblyInfo.cs
deleted file mode 100644
index a69bd176f..000000000
--- a/SocketHttpListener/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("SocketHttpListener")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/SocketHttpListener/Rsv.cs b/SocketHttpListener/Rsv.cs
deleted file mode 100644
index 87283791e..000000000
--- a/SocketHttpListener/Rsv.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace SocketHttpListener
-{
- internal enum Rsv : byte
- {
- Off = 0x0,
- On = 0x1
- }
-}
diff --git a/SocketHttpListener/SocketHttpListener.csproj b/SocketHttpListener/SocketHttpListener.csproj
deleted file mode 100644
index e700540a9..000000000
--- a/SocketHttpListener/SocketHttpListener.csproj
+++ /dev/null
@@ -1,18 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
-</Project>
diff --git a/SocketHttpListener/SocketStream.cs b/SocketHttpListener/SocketStream.cs
deleted file mode 100644
index f51fde97e..000000000
--- a/SocketHttpListener/SocketStream.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using System;
-using System.IO;
-using System.Net.Sockets;
-
-namespace SocketHttpListener
-{
- public class SocketStream : Stream
- {
- private readonly Socket _socket;
-
- public SocketStream(Socket socket, bool ownsSocket)
- {
- _socket = socket;
- }
-
- public override void Flush()
- {
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => false;
-
- public override bool CanWrite => true;
-
- public override long Length => throw new NotImplementedException();
-
- public override long Position
- {
- get => throw new NotImplementedException();
- set => throw new NotImplementedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- _socket.Send(buffer, offset, count, SocketFlags.None);
- }
-
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
- }
-
- public override void EndWrite(IAsyncResult asyncResult)
- {
- _socket.EndSend(asyncResult);
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- return _socket.Receive(buffer, offset, count, SocketFlags.None);
- }
-
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
- {
- return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- return _socket.EndReceive(asyncResult);
- }
- }
-}
diff --git a/SocketHttpListener/WebSocket.cs b/SocketHttpListener/WebSocket.cs
deleted file mode 100644
index 0dcb6a64b..000000000
--- a/SocketHttpListener/WebSocket.cs
+++ /dev/null
@@ -1,778 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using SocketHttpListener.Net.WebSockets;
-using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
-using WebSocketState = System.Net.WebSockets.WebSocketState;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// Implements the WebSocket interface.
- /// </summary>
- /// <remarks>
- /// The WebSocket class provides a set of methods and properties for two-way communication using
- /// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
- /// </remarks>
- public class WebSocket : IDisposable
- {
- #region Private Fields
-
- private Action _closeContext;
- private CompressionMethod _compression;
- private WebSocketContext _context;
- private CookieCollection _cookies;
- private AutoResetEvent _exitReceiving;
- private object _forConn;
- private readonly SemaphoreSlim _forEvent = new SemaphoreSlim(1, 1);
- private object _forMessageEventQueue;
- private readonly SemaphoreSlim _forSend = new SemaphoreSlim(1, 1);
- private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
- private Queue<MessageEventArgs> _messageEventQueue;
- private string _protocol;
- private volatile WebSocketState _readyState;
- private AutoResetEvent _receivePong;
- private bool _secure;
- private Stream _stream;
- private const string _version = "13";
-
- #endregion
-
- #region Internal Fields
-
- internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
-
- #endregion
-
- #region Internal Constructors
-
- // As server
- internal WebSocket(string protocol)
- {
- _protocol = protocol;
- }
-
- public void SetContext(HttpListenerWebSocketContext context, Action closeContextFn, Stream stream)
- {
- _context = context;
-
- _closeContext = closeContextFn;
- _secure = context.IsSecureConnection;
- _stream = stream;
-
- init();
- }
-
- // In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable default.
- public static TimeSpan DefaultKeepAliveInterval => TimeSpan.FromSeconds(30);
-
- #endregion
-
- /// <summary>
- /// Gets the state of the WebSocket connection.
- /// </summary>
- /// <value>
- /// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
- /// connection. The default value is <see cref="WebSocketState.Connecting"/>.
- /// </value>
- public WebSocketState ReadyState => _readyState;
-
- #region Public Events
-
- /// <summary>
- /// Occurs when the WebSocket connection has been closed.
- /// </summary>
- public event EventHandler<CloseEventArgs> OnClose;
-
- /// <summary>
- /// Occurs when the <see cref="WebSocket"/> gets an error.
- /// </summary>
- public event EventHandler<ErrorEventArgs> OnError;
-
- /// <summary>
- /// Occurs when the <see cref="WebSocket"/> receives a message.
- /// </summary>
- public event EventHandler<MessageEventArgs> OnMessage;
-
- /// <summary>
- /// Occurs when the WebSocket connection has been established.
- /// </summary>
- public event EventHandler OnOpen;
-
- #endregion
-
- #region Private Methods
-
- private async Task CloseAsync(CloseStatusCode code, string reason, bool wait)
- {
- await CloseAsync(new PayloadData(
- await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)),
- !code.IsReserved(),
- wait).ConfigureAwait(false);
- }
-
- private async Task CloseAsync(PayloadData payload, bool send, bool wait)
- {
- lock (_forConn)
- {
- if (_readyState == WebSocketState.CloseSent || _readyState == WebSocketState.Closed)
- {
- return;
- }
-
- _readyState = WebSocketState.CloseSent;
- }
-
- var e = new CloseEventArgs(payload)
- {
- WasClean = await CloseHandshakeAsync(
- send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
- wait ? 1000 : 0).ConfigureAwait(false)
- };
-
- _readyState = WebSocketState.Closed;
- try
- {
- OnClose.Emit(this, e);
- }
- catch (Exception ex)
- {
- error("An exception has occurred while OnClose.", ex);
- }
- }
-
- private async Task<bool> CloseHandshakeAsync(byte[] frameAsBytes, int millisecondsTimeout)
- {
- var sent = frameAsBytes != null && await WriteBytesAsync(frameAsBytes).ConfigureAwait(false);
- var received =
- millisecondsTimeout == 0 ||
- (sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout));
-
- closeServerResources();
-
- if (_receivePong != null)
- {
- _receivePong.Dispose();
- _receivePong = null;
- }
-
- if (_exitReceiving != null)
- {
- _exitReceiving.Dispose();
- _exitReceiving = null;
- }
-
- var result = sent && received;
-
- return result;
- }
-
- // As server
- private void closeServerResources()
- {
- if (_closeContext == null)
- return;
-
- try
- {
- _closeContext();
- }
- catch (SocketException)
- {
- // it could be unable to send the handshake response
- }
-
- _closeContext = null;
- _stream = null;
- _context = null;
- }
-
- private async Task<bool> ConcatenateFragmentsIntoAsync(Stream dest)
- {
- while (true)
- {
- var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false);
- if (frame.IsFinal)
- {
- /* FINAL */
-
- // CONT
- if (frame.IsContinuation)
- {
- dest.WriteBytes(frame.PayloadData.ApplicationData);
- break;
- }
-
- // PING
- if (frame.IsPing)
- {
- processPingFrame(frame);
- continue;
- }
-
- // PONG
- if (frame.IsPong)
- {
- processPongFrame(frame);
- continue;
- }
-
- // CLOSE
- if (frame.IsClose)
- return await ProcessCloseFrameAsync(frame).ConfigureAwait(false);
- }
- else
- {
- /* MORE */
-
- // CONT
- if (frame.IsContinuation)
- {
- dest.WriteBytes(frame.PayloadData.ApplicationData);
- continue;
- }
- }
-
- // ?
- return await ProcessUnsupportedFrameAsync(
- frame,
- CloseStatusCode.IncorrectData,
- "An incorrect data has been received while receiving fragmented data.").ConfigureAwait(false);
- }
-
- return true;
- }
-
- // As server
- private HttpResponse createHandshakeCloseResponse(HttpStatusCode code)
- {
- var res = HttpResponse.CreateCloseResponse(code);
- res.Headers["Sec-WebSocket-Version"] = _version;
-
- return res;
- }
-
- private MessageEventArgs dequeueFromMessageEventQueue()
- {
- lock (_forMessageEventQueue)
- return _messageEventQueue.Count > 0
- ? _messageEventQueue.Dequeue()
- : null;
- }
-
- private void enqueueToMessageEventQueue(MessageEventArgs e)
- {
- lock (_forMessageEventQueue)
- _messageEventQueue.Enqueue(e);
- }
-
- private void error(string message, Exception exception)
- {
- try
- {
- if (exception != null)
- {
- message += ". Exception.Message: " + exception.Message;
- }
- OnError.Emit(this, new ErrorEventArgs(message));
- }
- catch (Exception)
- {
- }
- }
-
- private void error(string message)
- {
- try
- {
- OnError.Emit(this, new ErrorEventArgs(message));
- }
- catch (Exception)
- {
- }
- }
-
- private void init()
- {
- _compression = CompressionMethod.None;
- _cookies = new CookieCollection();
- _forConn = new object();
- _messageEventQueue = new Queue<MessageEventArgs>();
- _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
- _readyState = WebSocketState.Connecting;
- }
-
- private async Task OpenAsync()
- {
- try
- {
- startReceiving();
-
- }
- catch (Exception ex)
- {
- await ProcessExceptionAsync(ex, "An exception has occurred while opening.").ConfigureAwait(false);
- }
-
- await _forEvent.WaitAsync().ConfigureAwait(false);
- try
- {
- OnOpen?.Invoke(this, EventArgs.Empty);
- }
- catch (Exception ex)
- {
- await ProcessExceptionAsync(ex, "An exception has occurred while OnOpen.").ConfigureAwait(false);
- }
- finally
- {
- _forEvent.Release();
- }
- }
-
- private async Task<bool> ProcessCloseFrameAsync(WebSocketFrame frame)
- {
- var payload = frame.PayloadData;
- await CloseAsync(payload, !payload.ContainsReservedCloseStatusCode, false).ConfigureAwait(false);
-
- return false;
- }
-
- private bool processDataFrame(WebSocketFrame frame)
- {
- var e = frame.IsCompressed
- ? new MessageEventArgs(
- frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression))
- : new MessageEventArgs(frame.Opcode, frame.PayloadData);
-
- enqueueToMessageEventQueue(e);
- return true;
- }
-
- private async Task ProcessExceptionAsync(Exception exception, string message)
- {
- var code = CloseStatusCode.Abnormal;
- var reason = message;
- if (exception is WebSocketException)
- {
- var wsex = (WebSocketException)exception;
- code = wsex.Code;
- reason = wsex.Message;
- }
-
- error(message ?? code.GetMessage(), exception);
- if (_readyState == WebSocketState.Connecting)
- {
- await CloseAsync(HttpStatusCode.BadRequest).ConfigureAwait(false);
- }
- else
- {
- await CloseAsync(code, reason ?? code.GetMessage(), false).ConfigureAwait(false);
- }
- }
-
- private Task<bool> ProcessFragmentedFrameAsync(WebSocketFrame frame)
- {
- return frame.IsContinuation // Not first fragment
- ? Task.FromResult(true)
- : ProcessFragmentsAsync(frame);
- }
-
- private async Task<bool> ProcessFragmentsAsync(WebSocketFrame first)
- {
- using (var buff = new MemoryStream())
- {
- buff.WriteBytes(first.PayloadData.ApplicationData);
- if (!await ConcatenateFragmentsIntoAsync(buff).ConfigureAwait(false))
- {
- return false;
- }
-
- byte[] data;
- if (_compression != CompressionMethod.None)
- {
- data = buff.DecompressToArray(_compression);
- }
- else
- {
- data = buff.ToArray();
- }
-
- enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
- return true;
- }
- }
-
- private bool processPingFrame(WebSocketFrame frame)
- {
- return true;
- }
-
- private bool processPongFrame(WebSocketFrame frame)
- {
- _receivePong.Set();
-
- return true;
- }
-
- private async Task<bool> ProcessUnsupportedFrameAsync(WebSocketFrame frame, CloseStatusCode code, string reason)
- {
- await ProcessExceptionAsync(new WebSocketException(code, reason), null).ConfigureAwait(false);
-
- return false;
- }
-
- private Task<bool> ProcessWebSocketFrameAsync(WebSocketFrame frame)
- {
- // TODO: @bond change to if/else chain
- return frame.IsCompressed && _compression == CompressionMethod.None
- ? ProcessUnsupportedFrameAsync(
- frame,
- CloseStatusCode.IncorrectData,
- "A compressed data has been received without available decompression method.")
- : frame.IsFragmented
- ? ProcessFragmentedFrameAsync(frame)
- : frame.IsData
- ? Task.FromResult(processDataFrame(frame))
- : frame.IsPing
- ? Task.FromResult(processPingFrame(frame))
- : frame.IsPong
- ? Task.FromResult(processPongFrame(frame))
- : frame.IsClose
- ? ProcessCloseFrameAsync(frame)
- : ProcessUnsupportedFrameAsync(frame, CloseStatusCode.PolicyViolation, null);
- }
-
- private async Task<bool> SendAsync(Opcode opcode, Stream stream)
- {
- await _forSend.WaitAsync().ConfigureAwait(false);
- try
- {
- var src = stream;
- var compressed = false;
- var sent = false;
- try
- {
- if (_compression != CompressionMethod.None)
- {
- stream = stream.Compress(_compression);
- compressed = true;
- }
-
- sent = await SendAsync(opcode, Mask.Unmask, stream, compressed).ConfigureAwait(false);
- if (!sent)
- error("Sending a data has been interrupted.");
- }
- catch (Exception ex)
- {
- error("An exception has occurred while sending a data.", ex);
- }
- finally
- {
- if (compressed)
- stream.Dispose();
-
- src.Dispose();
- }
-
- return sent;
- }
- finally
- {
- _forSend.Release();
- }
- }
-
- private async Task<bool> SendAsync(Opcode opcode, Mask mask, Stream stream, bool compressed)
- {
- var len = stream.Length;
-
- /* Not fragmented */
-
- if (len == 0)
- return await SendAsync(Fin.Final, opcode, mask, new byte[0], compressed).ConfigureAwait(false);
-
- var quo = len / FragmentLength;
- var rem = (int)(len % FragmentLength);
-
- byte[] buff = null;
- if (quo == 0)
- {
- buff = new byte[rem];
- return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
- await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
- }
-
- buff = new byte[FragmentLength];
- if (quo == 1 && rem == 0)
- return await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) == FragmentLength &&
- await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
-
- /* Send fragmented */
-
- // Begin
- if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
- !await SendAsync(Fin.More, opcode, mask, buff, compressed).ConfigureAwait(false))
- return false;
-
- var n = rem == 0 ? quo - 2 : quo - 1;
- for (long i = 0; i < n; i++)
- if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
- !await SendAsync(Fin.More, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false))
- return false;
-
- // End
- if (rem == 0)
- rem = FragmentLength;
- else
- buff = new byte[rem];
-
- return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
- await SendAsync(Fin.Final, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false);
- }
-
- private Task<bool> SendAsync(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
- {
- lock (_forConn)
- {
- if (_readyState != WebSocketState.Open)
- {
- return Task.FromResult(false);
- }
-
- return WriteBytesAsync(
- WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
- }
- }
-
- // As server
- private Task<bool> SendHttpResponseAsync(HttpResponse response)
- => WriteBytesAsync(response.ToByteArray());
-
- private void startReceiving()
- {
- if (_messageEventQueue.Count > 0)
- {
- _messageEventQueue.Clear();
- }
-
- _exitReceiving = new AutoResetEvent(false);
- _receivePong = new AutoResetEvent(false);
-
- Action receive = null;
- receive = async () => await WebSocketFrame.ReadAsync(
- _stream,
- true,
- async frame =>
- {
- if (await ProcessWebSocketFrameAsync(frame).ConfigureAwait(false) && _readyState != WebSocketState.Closed)
- {
- receive();
-
- if (!frame.IsData)
- {
- return;
- }
-
- await _forEvent.WaitAsync().ConfigureAwait(false);
-
- try
- {
- var e = dequeueFromMessageEventQueue();
- if (e != null && _readyState == WebSocketState.Open)
- {
- OnMessage.Emit(this, e);
- }
- }
- catch (Exception ex)
- {
- await ProcessExceptionAsync(ex, "An exception has occurred while OnMessage.").ConfigureAwait(false);
- }
- finally
- {
- _forEvent.Release();
- }
-
- }
- else if (_exitReceiving != null)
- {
- _exitReceiving.Set();
- }
- },
- async ex => await ProcessExceptionAsync(ex, "An exception has occurred while receiving a message.")).ConfigureAwait(false);
-
- receive();
- }
-
- private async Task<bool> WriteBytesAsync(byte[] data)
- {
- try
- {
- await _stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- #endregion
-
- #region Internal Methods
-
- // As server
- internal async Task CloseAsync(HttpResponse response)
- {
- _readyState = WebSocketState.CloseSent;
- await SendHttpResponseAsync(response).ConfigureAwait(false);
-
- closeServerResources();
-
- _readyState = WebSocketState.Closed;
- }
-
- // As server
- internal Task CloseAsync(HttpStatusCode code)
- => CloseAsync(createHandshakeCloseResponse(code));
-
- // As server
- public async Task ConnectAsServer()
- {
- try
- {
- _readyState = WebSocketState.Open;
- await OpenAsync().ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- await ProcessExceptionAsync(ex, "An exception has occurred while connecting.").ConfigureAwait(false);
- }
- }
-
- #endregion
-
- #region Public Methods
-
- /// <summary>
- /// Closes the WebSocket connection, and releases all associated resources.
- /// </summary>
- public Task CloseAsync()
- {
- var msg = _readyState.CheckIfClosable();
- if (msg != null)
- {
- error(msg);
-
- return Task.CompletedTask;
- }
-
- var send = _readyState == WebSocketState.Open;
- return CloseAsync(new PayloadData(), send, send);
- }
-
- /// <summary>
- /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
- /// and <see cref="string"/>, and releases all associated resources.
- /// </summary>
- /// <remarks>
- /// This method emits a <see cref="OnError"/> event if the size
- /// of <paramref name="reason"/> is greater than 123 bytes.
- /// </remarks>
- /// <param name="code">
- /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
- /// indicating the reason for the close.
- /// </param>
- /// <param name="reason">
- /// A <see cref="string"/> that represents the reason for the close.
- /// </param>
- public async Task CloseAsync(CloseStatusCode code, string reason)
- {
- byte[] data = null;
- var msg = _readyState.CheckIfClosable() ??
- (data = await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)).CheckIfValidControlData("reason");
-
- if (msg != null)
- {
- error(msg);
-
- return;
- }
-
- var send = _readyState == WebSocketState.Open && !code.IsReserved();
- await CloseAsync(new PayloadData(data), send, send).ConfigureAwait(false);
- }
-
- /// <summary>
- /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
- /// </summary>
- /// <remarks>
- /// This method doesn't wait for the send to be complete.
- /// </remarks>
- /// <param name="data">
- /// An array of <see cref="byte"/> that represents the binary data to send.
- /// </param>
- public Task SendAsync(byte[] data)
- {
- if (data == null)
- {
- throw new ArgumentNullException(nameof(data));
- }
-
- var msg = _readyState.CheckIfOpen();
- if (msg != null)
- {
- throw new Exception(msg);
- }
-
- return SendAsync(Opcode.Binary, new MemoryStream(data));
- }
-
- /// <summary>
- /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
- /// </summary>
- /// <remarks>
- /// This method doesn't wait for the send to be complete.
- /// </remarks>
- /// <param name="data">
- /// A <see cref="string"/> that represents the text data to send.
- /// </param>
- public Task SendAsync(string data)
- {
- if (data == null)
- {
- throw new ArgumentNullException(nameof(data));
- }
-
- var msg = _readyState.CheckIfOpen();
- if (msg != null)
- {
- throw new Exception(msg);
- }
-
- return SendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
- }
-
- #endregion
-
- #region Explicit Interface Implementation
-
- /// <summary>
- /// Closes the WebSocket connection, and releases all associated resources.
- /// </summary>
- /// <remarks>
- /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
- /// </remarks>
- void IDisposable.Dispose()
- {
- CloseAsync(CloseStatusCode.Away, null).GetAwaiter().GetResult();
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/WebSocketException.cs b/SocketHttpListener/WebSocketException.cs
deleted file mode 100644
index e86c46d0f..000000000
--- a/SocketHttpListener/WebSocketException.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using System;
-
-namespace SocketHttpListener
-{
- /// <summary>
- /// The exception that is thrown when a <see cref="WebSocket"/> gets a fatal error.
- /// </summary>
- public class WebSocketException : Exception
- {
- #region Internal Constructors
-
- internal WebSocketException()
- : this(CloseStatusCode.Abnormal, null, null)
- {
- }
-
- internal WebSocketException(string message)
- : this(CloseStatusCode.Abnormal, message, null)
- {
- }
-
- internal WebSocketException(CloseStatusCode code)
- : this(code, null, null)
- {
- }
-
- internal WebSocketException(string message, Exception innerException)
- : this(CloseStatusCode.Abnormal, message, innerException)
- {
- }
-
- internal WebSocketException(CloseStatusCode code, string message)
- : this(code, message, null)
- {
- }
-
- internal WebSocketException(CloseStatusCode code, string message, Exception innerException)
- : base(message ?? code.GetMessage(), innerException)
- {
- Code = code;
- }
-
- #endregion
-
- #region Public Properties
-
- /// <summary>
- /// Gets the status code indicating the cause for the exception.
- /// </summary>
- /// <value>
- /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating
- /// the cause for the exception.
- /// </value>
- public CloseStatusCode Code
- {
- get; private set;
- }
-
- #endregion
- }
-}
diff --git a/SocketHttpListener/WebSocketFrame.cs b/SocketHttpListener/WebSocketFrame.cs
deleted file mode 100644
index 8ec64026b..000000000
--- a/SocketHttpListener/WebSocketFrame.cs
+++ /dev/null
@@ -1,432 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-
-namespace SocketHttpListener
-{
- internal class WebSocketFrame : IEnumerable<byte>
- {
- #region Private Fields
-
- private byte[] _extPayloadLength;
- private Fin _fin;
- private Mask _mask;
- private byte[] _maskingKey;
- private Opcode _opcode;
- private PayloadData _payloadData;
- private byte _payloadLength;
- private Rsv _rsv1;
- private Rsv _rsv2;
- private Rsv _rsv3;
-
- #endregion
-
- #region Internal Fields
-
- internal static readonly byte[] EmptyUnmaskPingData;
-
- #endregion
-
- #region Static Constructor
-
- static WebSocketFrame()
- {
- EmptyUnmaskPingData = CreatePingFrame(Mask.Unmask).ToByteArray();
- }
-
- #endregion
-
- #region Private Constructors
-
- private WebSocketFrame()
- {
- }
-
- #endregion
-
- #region Internal Constructors
-
- internal WebSocketFrame(Opcode opcode, PayloadData payload)
- : this(Fin.Final, opcode, Mask.Mask, payload, false)
- {
- }
-
- internal WebSocketFrame(Opcode opcode, Mask mask, PayloadData payload)
- : this(Fin.Final, opcode, mask, payload, false)
- {
- }
-
- internal WebSocketFrame(Fin fin, Opcode opcode, Mask mask, PayloadData payload)
- : this(fin, opcode, mask, payload, false)
- {
- }
-
- internal WebSocketFrame(
- Fin fin, Opcode opcode, Mask mask, PayloadData payload, bool compressed)
- {
- _fin = fin;
- _rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
- _rsv2 = Rsv.Off;
- _rsv3 = Rsv.Off;
- _opcode = opcode;
- _mask = mask;
-
- var len = payload.Length;
- if (len < 126)
- {
- _payloadLength = (byte)len;
- _extPayloadLength = new byte[0];
- }
- else if (len < 0x010000)
- {
- _payloadLength = (byte)126;
- _extPayloadLength = ((ushort)len).ToByteArrayInternally(ByteOrder.Big);
- }
- else
- {
- _payloadLength = (byte)127;
- _extPayloadLength = len.ToByteArrayInternally(ByteOrder.Big);
- }
-
- if (mask == Mask.Mask)
- {
- _maskingKey = createMaskingKey();
- payload.Mask(_maskingKey);
- }
- else
- {
- _maskingKey = new byte[0];
- }
-
- _payloadData = payload;
- }
-
- #endregion
-
- #region Public Properties
-
- public byte[] ExtendedPayloadLength => _extPayloadLength;
-
- public Fin Fin => _fin;
-
- public bool IsBinary => _opcode == Opcode.Binary;
-
- public bool IsClose => _opcode == Opcode.Close;
-
- public bool IsCompressed => _rsv1 == Rsv.On;
-
- public bool IsContinuation => _opcode == Opcode.Cont;
-
- public bool IsControl => _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
-
- public bool IsData => _opcode == Opcode.Binary || _opcode == Opcode.Text;
-
- public bool IsFinal => _fin == Fin.Final;
-
- public bool IsFragmented => _fin == Fin.More || _opcode == Opcode.Cont;
-
- public bool IsMasked => _mask == Mask.Mask;
-
- public bool IsPerMessageCompressed => (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
-
- public bool IsPing => _opcode == Opcode.Ping;
-
- public bool IsPong => _opcode == Opcode.Pong;
-
- public bool IsText => _opcode == Opcode.Text;
-
- public ulong Length => 2 + (ulong)(_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
-
- public Mask Mask => _mask;
-
- public byte[] MaskingKey => _maskingKey;
-
- public Opcode Opcode => _opcode;
-
- public PayloadData PayloadData => _payloadData;
-
- public byte PayloadLength => _payloadLength;
-
- public Rsv Rsv1 => _rsv1;
-
- public Rsv Rsv2 => _rsv2;
-
- public Rsv Rsv3 => _rsv3;
-
- #endregion
-
- #region Private Methods
-
- private byte[] createMaskingKey()
- {
- var key = new byte[4];
- var rand = new Random();
- rand.NextBytes(key);
-
- return key;
- }
-
- private static bool isControl(Opcode opcode)
- {
- return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong;
- }
-
- private static bool isData(Opcode opcode)
- {
- return opcode == Opcode.Text || opcode == Opcode.Binary;
- }
-
- private static async Task<WebSocketFrame> ReadAsync(byte[] header, Stream stream, bool unmask)
- {
- /* Header */
-
- // FIN
- var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
- // RSV1
- var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
- // RSV2
- var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
- // RSV3
- var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
- // Opcode
- var opcode = (Opcode)(header[0] & 0x0f);
- // MASK
- var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
- // Payload Length
- var payloadLen = (byte)(header[1] & 0x7f);
-
- // Check if correct frame.
- var incorrect = isControl(opcode) && fin == Fin.More
- ? "A control frame is fragmented."
- : !isData(opcode) && rsv1 == Rsv.On
- ? "A non data frame is compressed."
- : null;
-
- if (incorrect != null)
- throw new WebSocketException(CloseStatusCode.IncorrectData, incorrect);
-
- // Check if consistent frame.
- if (isControl(opcode) && payloadLen > 125)
- throw new WebSocketException(
- CloseStatusCode.InconsistentData,
- "The length of payload data of a control frame is greater than 125 bytes.");
-
- var frame = new WebSocketFrame();
- frame._fin = fin;
- frame._rsv1 = rsv1;
- frame._rsv2 = rsv2;
- frame._rsv3 = rsv3;
- frame._opcode = opcode;
- frame._mask = mask;
- frame._payloadLength = payloadLen;
-
- /* Extended Payload Length */
-
- var size = payloadLen < 126
- ? 0
- : payloadLen == 126
- ? 2
- : 8;
-
- var extPayloadLen = size > 0 ? await stream.ReadBytesAsync(size).ConfigureAwait(false) : Array.Empty<byte>();
- if (size > 0 && extPayloadLen.Length != size)
- throw new WebSocketException(
- "The 'Extended Payload Length' of a frame cannot be read from the data source.");
-
- frame._extPayloadLength = extPayloadLen;
-
- /* Masking Key */
-
- var masked = mask == Mask.Mask;
- var maskingKey = masked ? await stream.ReadBytesAsync(4).ConfigureAwait(false) : Array.Empty<byte>();
- if (masked && maskingKey.Length != 4)
- throw new WebSocketException(
- "The 'Masking Key' of a frame cannot be read from the data source.");
-
- frame._maskingKey = maskingKey;
-
- /* Payload Data */
-
- ulong len = payloadLen < 126
- ? payloadLen
- : payloadLen == 126
- ? extPayloadLen.ToUInt16(ByteOrder.Big)
- : extPayloadLen.ToUInt64(ByteOrder.Big);
-
- byte[] data = null;
- if (len > 0)
- {
- // Check if allowable payload data length.
- if (payloadLen > 126 && len > PayloadData.MaxLength)
- throw new WebSocketException(
- CloseStatusCode.TooBig,
- "The length of 'Payload Data' of a frame is greater than the allowable length.");
-
- data = payloadLen > 126
- ? await stream.ReadBytesAsync((long)len, 1024).ConfigureAwait(false)
- : await stream.ReadBytesAsync((int)len).ConfigureAwait(false);
-
- //if (data.LongLength != (long)len)
- // throw new WebSocketException(
- // "The 'Payload Data' of a frame cannot be read from the data source.");
- }
- else
- {
- data = Array.Empty<byte>();
- }
-
- var payload = new PayloadData(data, masked);
- if (masked && unmask)
- {
- payload.Mask(maskingKey);
- frame._mask = Mask.Unmask;
- frame._maskingKey = Array.Empty<byte>();
- }
-
- frame._payloadData = payload;
- return frame;
- }
-
- #endregion
-
- #region Internal Methods
-
- internal static WebSocketFrame CreateCloseFrame(Mask mask, byte[] data)
- {
- return new WebSocketFrame(Opcode.Close, mask, new PayloadData(data));
- }
-
- internal static WebSocketFrame CreateCloseFrame(Mask mask, PayloadData payload)
- {
- return new WebSocketFrame(Opcode.Close, mask, payload);
- }
-
- internal static async Task<WebSocketFrame> CreateCloseFrameAsync(Mask mask, CloseStatusCode code, string reason)
- {
- return new WebSocketFrame(
- Opcode.Close, mask, new PayloadData(await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)));
- }
-
- internal static WebSocketFrame CreatePingFrame(Mask mask)
- {
- return new WebSocketFrame(Opcode.Ping, mask, new PayloadData());
- }
-
- internal static WebSocketFrame CreatePingFrame(Mask mask, byte[] data)
- {
- return new WebSocketFrame(Opcode.Ping, mask, new PayloadData(data));
- }
-
- internal static WebSocketFrame CreatePongFrame(Mask mask, PayloadData payload)
- {
- return new WebSocketFrame(Opcode.Pong, mask, payload);
- }
-
- internal static WebSocketFrame CreateWebSocketFrame(
- Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
- {
- return new WebSocketFrame(fin, opcode, mask, new PayloadData(data), compressed);
- }
-
- internal static Task<WebSocketFrame> ReadAsync(Stream stream)
- => ReadAsync(stream, true);
-
- internal static async Task<WebSocketFrame> ReadAsync(Stream stream, bool unmask)
- {
- var header = await stream.ReadBytesAsync(2).ConfigureAwait(false);
- if (header.Length != 2)
- {
- throw new WebSocketException(
- "The header part of a frame cannot be read from the data source.");
- }
-
- return await ReadAsync(header, stream, unmask).ConfigureAwait(false);
- }
-
- internal static async Task ReadAsync(
- Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
- {
- try
- {
- var header = await stream.ReadBytesAsync(2).ConfigureAwait(false);
- if (header.Length != 2)
- {
- throw new WebSocketException(
- "The header part of a frame cannot be read from the data source.");
- }
-
- var frame = await ReadAsync(header, stream, unmask).ConfigureAwait(false);
- completed?.Invoke(frame);
- }
- catch (Exception ex)
- {
- error.Invoke(ex);
- }
- }
-
- #endregion
-
- #region Public Methods
-
- public IEnumerator<byte> GetEnumerator()
- {
- foreach (var b in ToByteArray())
- yield return b;
- }
-
- public void Print(bool dumped)
- {
- //Console.WriteLine(dumped ? dump(this) : print(this));
- }
-
- public byte[] ToByteArray()
- {
- using (var buff = new MemoryStream())
- {
- var header = (int)_fin;
- header = (header << 1) + (int)_rsv1;
- header = (header << 1) + (int)_rsv2;
- header = (header << 1) + (int)_rsv3;
- header = (header << 4) + (int)_opcode;
- header = (header << 1) + (int)_mask;
- header = (header << 7) + (int)_payloadLength;
- buff.Write(((ushort)header).ToByteArrayInternally(ByteOrder.Big), 0, 2);
-
- if (_payloadLength > 125)
- buff.Write(_extPayloadLength, 0, _extPayloadLength.Length);
-
- if (_mask == Mask.Mask)
- buff.Write(_maskingKey, 0, _maskingKey.Length);
-
- if (_payloadLength > 0)
- {
- var payload = _payloadData.ToByteArray();
- if (_payloadLength < 127)
- buff.Write(payload, 0, payload.Length);
- else
- buff.WriteBytes(payload);
- }
-
- return buff.ToArray();
- }
- }
-
- public override string ToString()
- {
- return BitConverter.ToString(ToByteArray());
- }
-
- #endregion
-
- #region Explicitly Implemented Interface Members
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
-
- #endregion
- }
-}
diff --git a/build b/build
index 3b4167dae..c07a74de4 100755..120000
--- a/build
+++ b/build
@@ -1,229 +1 @@
-#!/usr/bin/env bash
-
-# build - build Jellyfin binaries or packages
-
-set -o errexit
-set -o pipefail
-
-# The list of possible package actions (except 'clean')
-declare -a actions=( 'build' 'package' 'sign' 'publish' )
-
-# The list of possible platforms, based on directories under 'deployment/'
-declare -a platforms=( $(
- find deployment/ -maxdepth 1 -mindepth 1 -type d -exec basename {} \; | sort
-) )
-
-# The list of standard dependencies required by all build scripts; individual
-# action scripts may specify their own dependencies
-declare -a dependencies=( 'tar' 'zip' )
-
-usage() {
- echo -e "build - build Jellyfin binaries or packages"
- echo -e ""
- echo -e "Usage:"
- echo -e " $ build --list-platforms"
- echo -e " $ build --list-actions <platform>"
- echo -e " $ build [-k/--keep-artifacts] [-b/--web-branch <web_branch>] <platform> <action>"
- echo -e ""
- echo -e "The 'keep-artifacts' option preserves build artifacts, e.g. Docker images for system package builds."
- echo -e "The web_branch defaults to the same branch name as the current main branch."
- echo -e "To build all platforms, use 'all'."
- echo -e "To perform all build actions, use 'all'."
- echo -e "Build output files are collected at '../jellyfin-build/<platform>'."
-}
-
-# Show usage on stderr with exit 1 on argless
-if [[ -z $1 ]]; then
- usage >&2
- exit 1
-fi
-# Show usage if -h or --help are specified in the args
-if [[ $@ =~ '-h' || $@ =~ '--help' ]]; then
- usage
- exit 0
-fi
-
-# List all available platforms then exit
-if [[ $1 == '--list-platforms' ]]; then
- echo -e "Available platforms:"
- for platform in ${platforms[@]}; do
- echo -e " ${platform}"
- done
- exit 0
-fi
-
-# List all available actions for a given platform then exit
-if [[ $1 == '--list-actions' ]]; then
- platform="$2"
- if [[ ! " ${platforms[@]} " =~ " ${platform} " ]]; then
- echo "ERROR: Platform ${platform} does not exist."
- exit 1
- fi
- echo -e "Available actions for platform ${platform}:"
- for action in ${actions[@]}; do
- if [[ -f deployment/${platform}/${action}.sh ]]; then
- echo -e " ${action}"
- fi
- done
- exit 0
-fi
-
-# Parse keep-artifacts option
-if [[ $1 == '-k' || $1 == '--keep-artifacts' ]]; then
- keep_artifacts="y"
- shift 1
-else
- keep_artifacts="n"
-fi
-
-# Parse branch option
-if [[ $1 == '-b' || $1 == '--web-branch' ]]; then
- web_branch="$2"
- shift 2
-else
- web_branch="$( git branch 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/' )"
-fi
-
-# Parse platform option
-if [[ -n $1 ]]; then
- cli_platform="$1"
- shift
-else
- echo "ERROR: A platform must be specified. Use 'all' to specify all platforms."
- exit 1
-fi
-if [[ ${cli_platform} == 'all' ]]; then
- declare -a platform=( ${platforms[@]} )
-else
- if [[ ! " ${platforms[@]} " =~ " ${cli_platform} " ]]; then
- echo "ERROR: Platform ${cli_platform} is invalid. Use the '--list-platforms' option to list available platforms."
- exit 1
- else
- declare -a platform=( "${cli_platform}" )
- fi
-fi
-
-# Parse action option
-if [[ -n $1 ]]; then
- cli_action="$1"
- shift
-else
- echo "ERROR: An action must be specified. Use 'all' to specify all actions."
- exit 1
-fi
-if [[ ${cli_action} == 'all' ]]; then
- declare -a action=( ${actions[@]} )
-else
- if [[ ! " ${actions[@]} " =~ " ${cli_action} " ]]; then
- echo "ERROR: Action ${cli_action} is invalid. Use the '--list-actions <platform>' option to list available actions."
- exit 1
- else
- declare -a action=( "${cli_action}" )
- fi
-fi
-
-# Verify required utilities are installed
-missing_deps=()
-for utility in ${dependencies[@]}; do
- if ! which ${utility} &>/dev/null; then
- missing_deps+=( ${utility} )
- fi
-done
-
-# Error if we're missing anything
-if [[ ${#missing_deps[@]} -gt 0 ]]; then
- echo -e "ERROR: This script requires the following missing utilities:"
- for utility in ${missing_deps[@]}; do
- echo -e " ${utility}"
- done
- exit 1
-fi
-
-# Parse platform-specific dependencies
-for target_platform in ${platform[@]}; do
- # Read platform-specific dependencies
- if [[ -f deployment/${target_platform}/dependencies.txt ]]; then
- platform_dependencies="$( grep -v '^#' deployment/${target_platform}/dependencies.txt )"
-
- # Verify required utilities are installed
- missing_deps=()
- for utility in ${platform_dependencies[@]}; do
- if ! which ${utility} &>/dev/null; then
- missing_deps+=( ${utility} )
- fi
- done
-
- # Error if we're missing anything
- if [[ ${#missing_deps[@]} -gt 0 ]]; then
- echo -e "ERROR: The ${target_platform} platform requires the following utilities:"
- for utility in ${missing_deps[@]}; do
- echo -e " ${utility}"
- done
- exit 1
- fi
- fi
-done
-
-# Initialize submodules
-git submodule update --init --recursive
-
-# configure branch
-pushd MediaBrowser.WebDashboard/jellyfin-web
-
-if ! git diff-index --quiet HEAD --; then
- popd
- echo
- echo "ERROR: Your 'jellyfin-web' submodule working directory is not clean!"
- echo "This script will overwrite your unstaged and unpushed changes."
- echo "Please do development on 'jellyfin-web' outside of the submodule."
- exit 1
-fi
-
-git fetch --all
-# If this is an official branch name, fetch it from origin
-official_branches_regex="^master$|^dev$|^release-.*$|^hotfix-.*$"
-if [[ ${web_branch} =~ ${official_branches_regex} ]]; then
- git checkout origin/${web_branch} || {
- echo "ERROR: 'jellyfin-web' branch 'origin/${web_branch}' is invalid."
- exit 1
- }
-# Otherwise, just check out the local branch (for testing, etc.)
-else
- git checkout ${web_branch} || {
- echo "ERROR: 'jellyfin-web' branch '${web_branch}' is invalid."
- exit 1
- }
-fi
-popd
-
-# Execute each platform and action in order, if said action is enabled
-pushd deployment/
-for target_platform in ${platform[@]}; do
- echo -e "> Processing platform ${target_platform}"
- date_start=$( date +%s )
- pushd ${target_platform}
- cleanup() {
- echo -e ">> Processing action clean"
- if [[ -f clean.sh && -x clean.sh ]]; then
- ./clean.sh ${keep_artifacts}
- fi
- }
- trap cleanup EXIT INT
- for target_action in ${action[@]}; do
- echo -e ">> Processing action ${target_action}"
- if [[ -f ${target_action}.sh && -x ${target_action}.sh ]]; then
- ./${target_action}.sh
- fi
- done
- if [[ -d pkg-dist/ ]]; then
- echo -e ">> Collecting build artifacts"
- target_dir="../../../jellyfin-build/${target_platform}"
- mkdir -p ${target_dir}
- mv pkg-dist/* ${target_dir}/
- fi
- cleanup
- date_end=$( date +%s )
- echo -e "> Completed platform ${target_platform} in $( expr ${date_end} - ${date_start} ) seconds."
- popd
-done
-popd
+build.sh \ No newline at end of file
diff --git a/build.sh b/build.sh
new file mode 100755
index 000000000..1db02af98
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,114 @@
+#!/usr/bin/env bash
+
+# build.sh - Build Jellyfin binary packages
+# Part of the Jellyfin Project
+
+set -o errexit
+set -o pipefail
+
+usage() {
+ echo -e "build.sh - Build Jellyfin binary packages"
+ echo -e "Usage:"
+ echo -e " $0 -t/--type <BUILD_TYPE> -p/--platform <PLATFORM> [-k/--keep-artifacts] [-l/--list-platforms]"
+ echo -e "Notes:"
+ echo -e " * BUILD_TYPE can be one of: [native, docker] and must be specified"
+ echo -e " * native: Build using the build script in the host OS"
+ echo -e " * docker: Build using the build script in a standardized Docker container"
+ echo -e " * PLATFORM can be any platform shown by -l/--list-platforms and must be specified"
+ echo -e " * If -k/--keep-artifacts is specified, transient artifacts (e.g. Docker containers) will be"
+ echo -e " retained after the build is finished; the source directory will still be cleaned"
+ echo -e " * If -l/--list-platforms is specified, all other arguments are ignored; the script will print"
+ echo -e " the list of supported platforms and exit"
+}
+
+list_platforms() {
+ declare -a platforms
+ platforms=(
+ $( find deployment -maxdepth 1 -mindepth 1 -name "build.*" | awk -F'.' '{ $1=""; printf $2; if ($3 != ""){ printf "." $3; }; if ($4 != ""){ printf "." $4; }; print ""; }' | sort )
+ )
+ echo -e "Valid platforms:"
+ echo
+ for platform in ${platforms[@]}; do
+ echo -e "* ${platform} : $( grep '^#=' deployment/build.${platform} | sed 's/^#= //' )"
+ done
+}
+
+do_build_native() {
+ if [[ ! -f $( which dpkg ) || $( dpkg --print-architecture | head -1 ) != "${PLATFORM##*.}" ]]; then
+ echo "Cross-building is not supported for native builds, use 'docker' builds on amd64 for cross-building."
+ exit 1
+ fi
+ export IS_DOCKER=NO
+ deployment/build.${PLATFORM}
+}
+
+do_build_docker() {
+ if [[ -f $( which dpkg ) && $( dpkg --print-architecture | head -1 ) != "amd64" ]]; then
+ echo "Docker-based builds only support amd64-based cross-building; use a 'native' build instead."
+ exit 1
+ fi
+ if [[ ! -f deployment/Dockerfile.${PLATFORM} ]]; then
+ echo "Missing Dockerfile for platform ${PLATFORM}"
+ exit 1
+ fi
+ if [[ ${KEEP_ARTIFACTS} == YES ]]; then
+ docker_args=""
+ else
+ docker_args="--rm"
+ fi
+
+ docker build . -t "jellyfin-builder.${PLATFORM}" -f deployment/Dockerfile.${PLATFORM}
+ mkdir -p ${ARTIFACT_DIR}
+ docker run $docker_args -v "${SOURCE_DIR}:/jellyfin" -v "${ARTIFACT_DIR}:/dist" "jellyfin-builder.${PLATFORM}"
+}
+
+while [[ $# -gt 0 ]]; do
+ key="$1"
+ case $key in
+ -t|--type)
+ BUILD_TYPE="$2"
+ shift # past argument
+ shift # past value
+ ;;
+ -p|--platform)
+ PLATFORM="$2"
+ shift # past argument
+ shift # past value
+ ;;
+ -k|--keep-artifacts)
+ KEEP_ARTIFACTS=YES
+ shift # past argument
+ ;;
+ -l|--list-platforms)
+ list_platforms
+ exit 0
+ ;;
+ -h|--help)
+ usage
+ exit 0
+ ;;
+ *) # unknown option
+ echo "Unknown option $1"
+ usage
+ exit 1
+ ;;
+ esac
+done
+
+if [[ -z ${BUILD_TYPE} || -z ${PLATFORM} ]]; then
+ usage
+ exit 1
+fi
+
+export SOURCE_DIR="$( pwd )"
+export ARTIFACT_DIR="${SOURCE_DIR}/../bin/${PLATFORM}"
+
+# Determine build type
+case ${BUILD_TYPE} in
+ native)
+ do_build_native
+ ;;
+ docker)
+ do_build_docker
+ ;;
+esac
diff --git a/build.yaml b/build.yaml
new file mode 100644
index 000000000..18434ee00
--- /dev/null
+++ b/build.yaml
@@ -0,0 +1,17 @@
+---
+# We just wrap `build` so this is really it
+name: "jellyfin"
+version: "10.8.0"
+packages:
+ - debian.amd64
+ - debian.arm64
+ - debian.armhf
+ - ubuntu.amd64
+ - ubuntu.arm64
+ - ubuntu.armhf
+ - fedora.amd64
+ - centos.amd64
+ - linux.amd64
+ - windows.amd64
+ - macos
+ - portable
diff --git a/bump_version b/bump_version
index a63fbf735..f615606e2 100755
--- a/bump_version
+++ b/bump_version
@@ -4,16 +4,13 @@
set -o errexit
set -o pipefail
+set -o xtrace
usage() {
echo -e "bump_version - increase the shared version and generate changelogs"
echo -e ""
echo -e "Usage:"
- echo -e " $ bump_version [-b/--web-branch <web_branch>] <new_version>"
- echo -e ""
- echo -e "The web_branch defaults to the same branch name as the current main branch."
- echo -e "This helps facilitate releases where both branches would be called release-X.Y.Z"
- echo -e "and would already be created before running this script."
+ echo -e " $ bump_version <new_version>"
}
if [[ -z $1 ]]; then
@@ -22,46 +19,16 @@ if [[ -z $1 ]]; then
fi
shared_version_file="./SharedVersion.cs"
-
-# Parse branch option
-if [[ $1 == '-b' || $1 == '--web-branch' ]]; then
- web_branch="$2"
- shift 2
-else
- web_branch="$( git branch 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/' )"
-fi
-
-# Initialize submodules
-git submodule update --init --recursive
-
-# configure branch
-pushd MediaBrowser.WebDashboard/jellyfin-web
-
-if ! git diff-index --quiet HEAD --; then
- popd
- echo
- echo "ERROR: Your 'jellyfin-web' submodule working directory is not clean!"
- echo "This script will overwrite your unstaged and unpushed changes."
- echo "Please do development on 'jellyfin-web' outside of the submodule."
- exit 1
-fi
-
-git fetch --all
-# If this is an official branch name, fetch it from origin
-official_branches_regex="^master$|^dev$|^release-.*$|^hotfix-.*$"
-if [[ ${web_branch} =~ ${official_branches_regex} ]]; then
- git checkout origin/${web_branch} || {
- echo "ERROR: 'jellyfin-web' branch 'origin/${web_branch}' is invalid."
- exit 1
- }
-# Otherwise, just check out the local branch (for testing, etc.)
-else
- git checkout ${web_branch} || {
- echo "ERROR: 'jellyfin-web' branch '${web_branch}' is invalid."
- exit 1
- }
-fi
-popd
+build_file="./build.yaml"
+# csproj files for nuget packages
+jellyfin_subprojects=(
+ MediaBrowser.Common/MediaBrowser.Common.csproj
+ Jellyfin.Data/Jellyfin.Data.csproj
+ MediaBrowser.Controller/MediaBrowser.Controller.csproj
+ MediaBrowser.Model/MediaBrowser.Model.csproj
+ Emby.Naming/Emby.Naming.csproj
+ src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
+)
new_version="$1"
@@ -70,107 +37,64 @@ old_version="$(
grep "AssemblyVersion" ${shared_version_file} \
| sed -E 's/\[assembly: ?AssemblyVersion\("([0-9\.]+)"\)\]/\1/'
)"
+echo $old_version
# Set the shared version to the specified new_version
old_version_sed="$( sed 's/\./\\./g' <<<"${old_version}" )" # Escape the '.' chars
-sed -i "s/${old_version_sed}/${new_version}/g" ${shared_version_file}
-
-declare -a pr_merges_since_last_master
-declare changelog_string_github
-declare changelog_string_deb
-declare changelog_string_yum
-
-# Build up a changelog from merge commits
-for repo in ./ MediaBrowser.WebDashboard/jellyfin-web/; do
- last_master_merge_commit=""
- pr_merges_since_last_master=()
- git_show_details=""
- pull_request_id=""
- pull_request_description=""
- changelog_strings_repo_github=""
- changelog_strings_repo_deb=""
- changelog_strings_repo_yum=""
-
- case $repo in
- *jellyfin-web*)
- repo_name="jellyfin-web"
- ;;
- *)
- repo_name="jellyfin"
- ;;
- esac
-
- pushd ${repo}
-
- # Find the last release commit, so we know what's happened since
- last_master_branch="release-${old_version}"
- last_master_merge_commit="$(
- git log --merges --pretty=oneline \
- | grep -F "${last_master_branch}" \
- | awk '{ print $1 }' \
- || true # Don't die here with errexit
+new_version_sed="$( cut -f1 -d'-' <<<"${new_version}" )"
+sed -i "s/${old_version_sed}/${new_version_sed}/g" ${shared_version_file}
+
+old_version="$(
+ grep "version:" ${build_file} \
+ | sed -E 's/version: "([0-9\.]+[-a-z0-9]*)"/\1/'
+)"
+echo $old_version
+
+# Set the build.yaml version to the specified new_version
+old_version_sed="$( sed 's/\./\\./g' <<<"${old_version}" )" # Escape the '.' chars
+sed -i "s/${old_version_sed}/${new_version}/g" ${build_file}
+
+# update nuget package version
+for subproject in ${jellyfin_subprojects[@]}; do
+ echo ${subproject}
+ # Parse the version from the *.csproj file
+ old_version="$(
+ grep "VersionPrefix" ${subproject} \
+ | awk '{$1=$1};1' \
+ | sed -E 's/<VersionPrefix>([0-9\.]+[-a-z0-9]*)<\/VersionPrefix>/\1/'
)"
- if [[ -z ${last_master_merge_commit} ]]; then
- # This repo has no last proper commit, so just skip it
- popd
- continue
- fi
- # Get all the PR merge commits since the last master merge commit in `jellyfin`
- pr_merges_since_last_master+=( $(
- git log --merges --pretty=oneline ${last_master_merge_commit}..HEAD \
- | grep -F "Merge pull request" \
- | awk '{ print $1 }'
- ) )
-
- for commit_hash in ${pr_merges_since_last_master[@]}; do
- git_show_details="$( git show ${commit_hash} )"
- pull_request_id="$(
- awk '
- /Merge pull request/{ print $4 }
- { next }
- ' <<<"${git_show_details}"
- )"
- pull_request_description="$(
- awk '
- /^[a-zA-Z]/{ next }
- /^ Merge/{ next }
- /^$/{ next }
- { print $0 }
- ' <<<"${git_show_details}"
- )"
- pull_request_description="$( sed ':a;N;$!ba;s/\n//g; s/ \+//g' <<<"${pull_request_description}" )"
- changelog_strings_repo_github="${changelog_strings_repo_github}\n* ${pull_request_id}: ${pull_request_description}"
- changelog_strings_repo_deb="${changelog_strings_repo_deb}\n * $( sed 's/#/PR/' <<<"${pull_request_id}" ) ${pull_request_description}"
- changelog_strings_repo_yum="${changelog_strings_repo_yum}\n- $( sed 's/#/PR/' <<<"${pull_request_id}" ) ${pull_request_description}"
- done
-
- changelog_string_github="${changelog_string_github}\n#### ${repo_name}:\n$( echo -e "${changelog_strings_repo_github}" | sort -nk2 )\n"
- changelog_string_deb="${changelog_string_deb}\n * ${repo_name}:$( echo -e "${changelog_strings_repo_deb}" | sort -nk2 )"
- changelog_string_yum="${changelog_string_yum}\n- ${repo_name}:$( echo -e "${changelog_strings_repo_yum}" | sort -nk2 )"
-
- popd
+ echo old nuget version: $old_version
+
+ # Set the nuget version to the specified new_version
+ sed -i "s|${old_version}|${new_version}|g" ${subproject}
done
+if [[ ${new_version} == *"-"* ]]; then
+ new_version_deb="$( sed 's/-/~/g' <<<"${new_version}" )"
+else
+ new_version_deb="${new_version}-1"
+fi
+
+# Update the metapackage equivs file
+debian_equivs_file="debian/metapackage/jellyfin"
+sed -i "s/${old_version_sed}/${new_version}/g" ${debian_equivs_file}
+
# Write out a temporary Debian changelog with our new stuff appended and some templated formatting
-debian_changelog_file="deployment/debian-package-x64/pkg-src/changelog"
+debian_changelog_file="debian/changelog"
debian_changelog_temp="$( mktemp )"
# Create new temp file with our changelog
-echo -e "### DEBIAN PACKAGE CHANGELOG: Verify this file looks correct or edit accordingly, then delete this line, write, and exit.
-jellyfin (${new_version}-1) unstable; urgency=medium
-${changelog_string_deb}
+echo -e "jellyfin-server (${new_version_deb}) unstable; urgency=medium
+
+ * New upstream version ${new_version}; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v${new_version}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
" >> ${debian_changelog_temp}
cat ${debian_changelog_file} >> ${debian_changelog_temp}
-# Edit the file to verify
-$EDITOR ${debian_changelog_temp}
# Move into place
mv ${debian_changelog_temp} ${debian_changelog_file}
-# Clean up
-rm -f ${debian_changelog_temp}
# Write out a temporary Yum changelog with our new stuff prepended and some templated formatting
-fedora_spec_file="deployment/fedora-package-x64/pkg-src/jellyfin.spec"
+fedora_spec_file="fedora/jellyfin.spec"
fedora_changelog_temp="$( mktemp )"
fedora_spec_temp_dir="$( mktemp -d )"
fedora_spec_temp="${fedora_spec_temp_dir}/jellyfin.spec.tmp"
@@ -180,29 +104,22 @@ pushd ${fedora_spec_temp_dir}
# Split out the stuff before and after changelog
csplit jellyfin.spec "/^%changelog/" # produces xx00 xx01
# Update the version in xx00
-sed -i "s/${old_version_sed}/${new_version}/g" xx00
+sed -i "s/${old_version_sed}/${new_version_sed}/g" xx00
# Remove the header from xx01
sed -i '/^%changelog/d' xx01
# Create new temp file with our changelog
-echo -e "### YUM SPEC CHANGELOG: Verify this file looks correct or edit accordingly, then delete this line, write, and exit.
-%changelog
-* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>${changelog_string_yum}" >> ${fedora_changelog_temp}
+echo -e "%changelog
+* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version ${new_version}; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v${new_version}" >> ${fedora_changelog_temp}
cat xx01 >> ${fedora_changelog_temp}
-# Edit the file to verify
-$EDITOR ${fedora_changelog_temp}
# Reassembble
cat xx00 ${fedora_changelog_temp} > ${fedora_spec_temp}
popd
# Move into place
mv ${fedora_spec_temp} ${fedora_spec_file}
# Clean up
-rm -rf ${fedora_changelog_temp} ${fedora_spec_temp_dir}
+rm -rf ${fedora_spec_temp_dir}
# Stage the changed files for commit
-git add ${shared_version_file} ${debian_changelog_file} ${fedora_spec_file}
+git add ${shared_version_file} ${build_file} ${debian_equivs_file} ${debian_changelog_file} ${fedora_spec_file}
git status
-
-# Write out the GitHub-formatted changelog for the merge request/release pages
-echo ""
-echo "=== The GitHub-formatted changelog follows ==="
-echo -e "${changelog_string_github}"
diff --git a/debian/bin/restart.sh b/debian/bin/restart.sh
new file mode 100755
index 000000000..4847b918b
--- /dev/null
+++ b/debian/bin/restart.sh
@@ -0,0 +1,56 @@
+#!/bin/bash
+
+# restart.sh - Jellyfin server restart script
+# Part of the Jellyfin project (https://github.com/jellyfin)
+#
+# This script restarts the Jellyfin daemon on Linux when using
+# the Restart button on the admin dashboard. It supports the
+# systemctl, service, and traditional /etc/init.d (sysv) restart
+# methods, chosen automatically by which one is found first (in
+# that order).
+#
+# This script is used by the Debian/Ubuntu/Fedora/CentOS packages.
+
+# This is the Right Way(tm) to check if we are booted with
+# systemd, according to sd_booted(3)
+if [ -d /run/systemd/system ]; then
+ cmd=systemctl
+else
+ # Everything else is really hard to figure out, so we just use
+ # service(8) if it's available - that works with most init
+ # systems/distributions I know of, including FreeBSD
+ if type service >/dev/null 2>&1; then
+ cmd=service
+ else
+ # If even service(8) isn't available, we just try /etc/init.d
+ # and hope for the best
+ if [ -d /etc/init.d ]; then
+ cmd=sysv
+ else
+ echo "Unable to detect a way to restart Jellyfin; bailing out" 1>&2
+ echo "Please report this bug to https://github.com/jellyfin/jellyfin/issues" 1>&2
+ exit 1
+ fi
+ fi
+fi
+
+if type sudo >/dev/null 2>&1; then
+ sudo_command=sudo
+else
+ sudo_command=
+fi
+
+echo "Detected service control platform '$cmd'; using it to restart Jellyfin..."
+case $cmd in
+ 'systemctl')
+ # Without systemd-run here, `jellyfin.service`'s shutdown terminates this process too
+ $sudo_command systemd-run systemctl restart jellyfin
+ ;;
+ 'service')
+ echo "sleep 0.5; $sudo_command service jellyfin start" | at now
+ ;;
+ 'sysv')
+ echo "sleep 0.5; /usr/bin/sudo /etc/init.d/jellyfin start" | at now
+ ;;
+esac
+exit 0
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 000000000..430594cac
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,83 @@
+jellyfin-server (10.8.0-1) unstable; urgency=medium
+
+ * Forthcoming stable release
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 04 Dec 2020 21:55:12 -0500
+
+jellyfin-server (10.7.0-1) unstable; urgency=medium
+
+ * Forthcoming stable release
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Mon, 27 Jul 2020 19:09:45 -0400
+
+jellyfin-server (10.6.0-2) unstable; urgency=medium
+
+ * Fix upgrade bug
+
+ -- Joshua Boniface <joshua@boniface.me> Sun, 19 Jul 22:47:27 -0400
+
+jellyfin-server (10.6.0-1) unstable; urgency=medium
+
+ * Forthcoming stable release
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Mon, 23 Mar 2020 14:46:05 -0400
+
+jellyfin (10.5.0-1) unstable; urgency=medium
+
+ * New upstream version 10.5.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.5.0
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 11 Oct 2019 20:12:38 -0400
+
+jellyfin (10.4.0-1) unstable; urgency=medium
+
+ * New upstream version 10.4.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.4.0
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Sat, 31 Aug 2019 21:38:56 -0400
+
+jellyfin (10.3.7-1) unstable; urgency=medium
+
+ * New upstream version 10.3.7; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.7
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Wed, 24 Jul 2019 10:48:28 -0400
+
+jellyfin (10.3.6-1) unstable; urgency=medium
+
+ * New upstream version 10.3.6; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.6
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Sat, 06 Jul 2019 13:34:19 -0400
+
+jellyfin (10.3.5-1) unstable; urgency=medium
+
+ * New upstream version 10.3.5; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.5
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Sun, 09 Jun 2019 21:47:35 -0400
+
+jellyfin (10.3.4-1) unstable; urgency=medium
+
+ * New upstream version 10.3.4; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.4
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Thu, 06 Jun 2019 22:45:31 -0400
+
+jellyfin (10.3.3-1) unstable; urgency=medium
+
+ * New upstream version 10.3.3; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.3
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 17 May 2019 23:12:08 -0400
+
+jellyfin (10.3.2-1) unstable; urgency=medium
+
+ * New upstream version 10.3.2; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.2
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Tue, 30 Apr 2019 20:18:44 -0400
+
+jellyfin (10.3.1-1) unstable; urgency=medium
+
+ * New upstream version 10.3.1; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.1
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Sat, 20 Apr 2019 14:24:07 -0400
+
+jellyfin (10.3.0-1) unstable; urgency=medium
+
+ * New upstream version 10.3.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.0
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 19 Apr 2019 14:24:29 -0400
diff --git a/deployment/debian-package-x64/pkg-src/compat b/debian/compat
index 45a4fb75d..45a4fb75d 100644
--- a/deployment/debian-package-x64/pkg-src/compat
+++ b/debian/compat
diff --git a/debian/conf/jellyfin b/debian/conf/jellyfin
new file mode 100644
index 000000000..ab8d5d1d4
--- /dev/null
+++ b/debian/conf/jellyfin
@@ -0,0 +1,51 @@
+# Jellyfin default configuration options
+# This is a POSIX shell fragment
+
+# Use this file to override the default configurations; add additional
+# options with JELLYFIN_ADD_OPTS.
+
+# Under systemd, use
+# /etc/systemd/system/jellyfin.service.d/jellyfin.service.conf
+# to override the user or this config file's location.
+
+#
+# General options
+#
+
+# Program directories
+JELLYFIN_DATA_DIR="/var/lib/jellyfin"
+JELLYFIN_CONFIG_DIR="/etc/jellyfin"
+JELLYFIN_LOG_DIR="/var/log/jellyfin"
+JELLYFIN_CACHE_DIR="/var/cache/jellyfin"
+
+# web client path, installed by the jellyfin-web package
+JELLYFIN_WEB_OPT="--webdir=/usr/share/jellyfin/web"
+
+# Restart script for in-app server control
+JELLYFIN_RESTART_OPT="--restartpath=/usr/lib/jellyfin/restart.sh"
+
+# ffmpeg binary paths, overriding the system values
+JELLYFIN_FFMPEG_OPT="--ffmpeg=/usr/lib/jellyfin-ffmpeg/ffmpeg"
+
+# [OPTIONAL] run Jellyfin as a headless service
+#JELLYFIN_SERVICE_OPT="--service"
+
+# [OPTIONAL] run Jellyfin without the web app
+#JELLYFIN_NOWEBAPP_OPT="--nowebclient"
+
+# Space to add additional command line options to jellyfin (for help see ~$ jellyfin --help)
+JELLYFIN_ADDITIONAL_OPTS=""
+
+# [OPTIONAL] run Jellyfin with ASP.NET Server Garbage Collection (uses more RAM and less CPU than Workstation GC)
+# 0 = Workstation
+# 1 = Server
+#COMPlus_gcServer=1
+
+#
+# SysV init/Upstart options
+#
+
+# Application username
+JELLYFIN_USER="jellyfin"
+# Full application command
+JELLYFIN_ARGS="$JELLYFIN_WEB_OPT $JELLYFIN_RESTART_OPT $JELLYFIN_FFMPEG_OPT $JELLYFIN_SERVICE_OPT $JELLYFIN_NOWEBAPP_OPT $JELLFIN_ADDITIONAL_OPTS"
diff --git a/deployment/debian-package-x64/pkg-src/conf/jellyfin-sudoers b/debian/conf/jellyfin-sudoers
index b481ba4ad..f84e7454f 100644
--- a/deployment/debian-package-x64/pkg-src/conf/jellyfin-sudoers
+++ b/debian/conf/jellyfin-sudoers
@@ -2,9 +2,9 @@
Cmnd_Alias RESTARTSERVER_SYSV = /sbin/service jellyfin restart, /usr/sbin/service jellyfin restart
Cmnd_Alias STARTSERVER_SYSV = /sbin/service jellyfin start, /usr/sbin/service jellyfin start
Cmnd_Alias STOPSERVER_SYSV = /sbin/service jellyfin stop, /usr/sbin/service jellyfin stop
-Cmnd_Alias RESTARTSERVER_SYSTEMD = /usr/bin/systemctl restart jellyfin, /bin/systemctl restart jellyfin
-Cmnd_Alias STARTSERVER_SYSTEMD = /usr/bin/systemctl start jellyfin, /bin/systemctl start jellyfin
-Cmnd_Alias STOPSERVER_SYSTEMD = /usr/bin/systemctl stop jellyfin, /bin/systemctl stop jellyfin
+Cmnd_Alias RESTARTSERVER_SYSTEMD = /usr/bin/systemd-run systemctl restart jellyfin
+Cmnd_Alias STARTSERVER_SYSTEMD = /usr/bin/systemd-run systemctl start jellyfin
+Cmnd_Alias STOPSERVER_SYSTEMD = /usr/bin/systemd-run systemctl stop jellyfin
Cmnd_Alias RESTARTSERVER_INITD = /etc/init.d/jellyfin restart
Cmnd_Alias STARTSERVER_INITD = /etc/init.d/jellyfin start
Cmnd_Alias STOPSERVER_INITD = /etc/init.d/jellyfin stop
diff --git a/deployment/debian-package-x64/pkg-src/conf/jellyfin.service.conf b/debian/conf/jellyfin.service.conf
index 1b69dd74e..1b69dd74e 100644
--- a/deployment/debian-package-x64/pkg-src/conf/jellyfin.service.conf
+++ b/debian/conf/jellyfin.service.conf
diff --git a/deployment/debian-package-x64/pkg-src/conf/logging.json b/debian/conf/logging.json
index f32b2089e..f32b2089e 100644
--- a/deployment/debian-package-x64/pkg-src/conf/logging.json
+++ b/debian/conf/logging.json
diff --git a/debian/control b/debian/control
new file mode 100644
index 000000000..da9aa94d4
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,28 @@
+Source: jellyfin-server
+Section: misc
+Priority: optional
+Maintainer: Jellyfin Team <team@jellyfin.org>
+Build-Depends: debhelper (>= 9),
+ dotnet-sdk-6.0,
+ libc6-dev,
+ libcurl4-openssl-dev,
+ libfontconfig1-dev,
+ libfreetype6-dev,
+ libssl-dev
+Standards-Version: 3.9.4
+Homepage: https://jellyfin.org/
+Vcs-Git: https://github.org/jellyfin/jellyfin.git
+Vcs-Browser: https://github.org/jellyfin/jellyfin
+
+Package: jellyfin-server
+Replaces: jellyfin (<<10.6.0)
+Breaks: jellyfin (<<10.6.0)
+Architecture: any
+Depends: at,
+ libsqlite3-0,
+ libfontconfig1,
+ libfreetype6,
+ libssl1.1
+Recommends: jellyfin-web, sudo
+Description: Jellyfin is the Free Software Media System.
+ This package provides the Jellyfin server backend and API.
diff --git a/deployment/debian-package-x64/pkg-src/copyright b/debian/copyright
index 0d7a2a600..0d7a2a600 100644
--- a/deployment/debian-package-x64/pkg-src/copyright
+++ b/debian/copyright
diff --git a/deployment/debian-package-x64/pkg-src/gbp.conf b/debian/gbp.conf
index 60b3d2872..60b3d2872 100644
--- a/deployment/debian-package-x64/pkg-src/gbp.conf
+++ b/debian/gbp.conf
diff --git a/deployment/debian-package-x64/pkg-src/install b/debian/install
index 994322d14..994322d14 100644
--- a/deployment/debian-package-x64/pkg-src/install
+++ b/debian/install
diff --git a/debian/jellyfin.init b/debian/jellyfin.init
new file mode 100644
index 000000000..7f5642bac
--- /dev/null
+++ b/debian/jellyfin.init
@@ -0,0 +1,61 @@
+### BEGIN INIT INFO
+# Provides: Jellyfin Media Server
+# Required-Start: $local_fs $network
+# Required-Stop: $local_fs
+# Default-Start: 2 3 4 5
+# Default-Stop: 0 1 6
+# Short-Description: Jellyfin Media Server
+# Description: Runs Jellyfin Server
+### END INIT INFO
+
+set -e
+
+# Carry out specific functions when asked to by the system
+
+if test -f /etc/default/jellyfin; then
+ . /etc/default/jellyfin
+fi
+
+. /lib/lsb/init-functions
+
+PIDFILE="/run/jellyfin.pid"
+
+case "$1" in
+ start)
+ log_daemon_msg "Starting Jellyfin Media Server" "jellyfin" || true
+
+ if start-stop-daemon --start --quiet --oknodo --background --pidfile $PIDFILE --make-pidfile --user $JELLYFIN_USER --chuid $JELLYFIN_USER --exec /usr/bin/jellyfin -- $JELLYFIN_ARGS; then
+ log_end_msg 0 || true
+ else
+ log_end_msg 1 || true
+ fi
+ ;;
+
+ stop)
+ log_daemon_msg "Stopping Jellyfin Media Server" "jellyfin" || true
+ if start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE --remove-pidfile; then
+ log_end_msg 0 || true
+ else
+ log_end_msg 1 || true
+ fi
+ ;;
+
+ restart)
+ log_daemon_msg "Restarting Jellyfin Media Server" "jellyfin" || true
+ start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $PIDFILE --remove-pidfile
+ if start-stop-daemon --start --quiet --oknodo --background --pidfile $PIDFILE --make-pidfile --user $JELLYFIN_USER --chuid $JELLYFIN_USER --exec /usr/bin/jellyfin -- $JELLYFIN_ARGS; then
+ log_end_msg 0 || true
+ else
+ log_end_msg 1 || true
+ fi
+ ;;
+
+ status)
+ status_of_proc -p $PIDFILE /usr/bin/jellyfin jellyfin && exit 0 || exit $?
+ ;;
+
+ *)
+ echo "Usage: $0 {start|stop|restart|status}"
+ exit 1
+ ;;
+esac
diff --git a/debian/jellyfin.service b/debian/jellyfin.service
new file mode 100644
index 000000000..b79cd47c7
--- /dev/null
+++ b/debian/jellyfin.service
@@ -0,0 +1,14 @@
+[Unit]
+Description = Jellyfin Media Server
+After = network-online.target
+
+[Service]
+Type = simple
+EnvironmentFile = /etc/default/jellyfin
+User = jellyfin
+ExecStart = /usr/bin/jellyfin ${JELLYFIN_WEB_OPT} ${JELLYFIN_RESTART_OPT} ${JELLYFIN_FFMPEG_OPT} ${JELLYFIN_SERVICE_OPT} ${JELLYFIN_NOWEBAPP_OPT} ${JELLYFIN_ADDITIONAL_OPTS}
+Restart = on-failure
+TimeoutSec = 15
+
+[Install]
+WantedBy = multi-user.target
diff --git a/deployment/debian-package-x64/pkg-src/jellyfin.upstart b/debian/jellyfin.upstart
index ef5bc9bca..ef5bc9bca 100644
--- a/deployment/debian-package-x64/pkg-src/jellyfin.upstart
+++ b/debian/jellyfin.upstart
diff --git a/debian/metapackage/jellyfin b/debian/metapackage/jellyfin
new file mode 100644
index 000000000..a9a0ae5b0
--- /dev/null
+++ b/debian/metapackage/jellyfin
@@ -0,0 +1,13 @@
+Source: jellyfin
+Section: misc
+Priority: optional
+Homepage: https://jellyfin.org
+Standards-Version: 3.9.2
+
+Package: jellyfin
+Version: 10.8.0
+Maintainer: Jellyfin Packaging Team <packaging@jellyfin.org>
+Depends: jellyfin-server, jellyfin-web
+Description: Provides the Jellyfin Free Software Media System
+ Provides the full Jellyfin experience, including both the server and web interface.
+
diff --git a/deployment/debian-package-x64/pkg-src/po/POTFILES.in b/debian/po/POTFILES.in
index cef83a340..cef83a340 100644
--- a/deployment/debian-package-x64/pkg-src/po/POTFILES.in
+++ b/debian/po/POTFILES.in
diff --git a/deployment/debian-package-x64/pkg-src/po/templates.pot b/debian/po/templates.pot
index 2cdcae417..2cdcae417 100644
--- a/deployment/debian-package-x64/pkg-src/po/templates.pot
+++ b/debian/po/templates.pot
diff --git a/deployment/debian-package-x64/pkg-src/postinst b/debian/postinst
index 860222e05..2f9c4cffb 100644
--- a/deployment/debian-package-x64/pkg-src/postinst
+++ b/debian/postinst
@@ -9,6 +9,8 @@ if [[ -f $DEFAULT_FILE ]]; then
. $DEFAULT_FILE
fi
+JELLYFIN_USER=${JELLYFIN_USER:-jellyfin}
+
# Data directories for program data (cache, db), configs, and logs
PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME}
CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME}
@@ -18,12 +20,12 @@ CACHEDATA=${JELLYFIN_CACHE_DIRECTORY-/var/cache/$NAME}
case "$1" in
configure)
# create jellyfin group if it does not exist
- if [[ -z "$(getent group jellyfin)" ]]; then
- addgroup --quiet --system jellyfin > /dev/null 2>&1
+ if [[ -z "$(getent group ${JELLYFIN_USER})" ]]; then
+ addgroup --quiet --system ${JELLYFIN_USER} > /dev/null 2>&1
fi
# create jellyfin user if it does not exist
- if [[ -z "$(getent passwd jellyfin)" ]]; then
- adduser --system --ingroup jellyfin --shell /bin/false jellyfin --no-create-home --home ${PROGRAMDATA} \
+ if [[ -z "$(getent passwd ${JELLYFIN_USER})" ]]; then
+ adduser --system --ingroup ${JELLYFIN_USER} --shell /bin/false ${JELLYFIN_USER} --no-create-home --home ${PROGRAMDATA} \
--gecos "Jellyfin default user" > /dev/null 2>&1
fi
# ensure $PROGRAMDATA exists
@@ -43,7 +45,7 @@ case "$1" in
mkdir $CACHEDATA
fi
# Ensure permissions are correct on all config directories
- chown -R jellyfin $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA
+ chown -R ${JELLYFIN_USER} $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA
chgrp adm $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA
chmod 0750 $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA
diff --git a/deployment/debian-package-x64/pkg-src/postrm b/debian/postrm
index 1d00a984e..3d56a5f1e 100644
--- a/deployment/debian-package-x64/pkg-src/postrm
+++ b/debian/postrm
@@ -25,7 +25,7 @@ case "$1" in
purge)
echo PURGE | debconf-communicate $NAME > /dev/null 2>&1 || true
- if [[ -x "/etc/init.d/jellyfin" ]] || [[ -e "/etc/init/jellyfin.connf" ]]; then
+ if [[ -x "/etc/init.d/jellyfin" ]] || [[ -e "/etc/init/jellyfin.conf" ]]; then
update-rc.d jellyfin remove >/dev/null 2>&1 || true
fi
@@ -54,7 +54,7 @@ case "$1" in
rm -rf $PROGRAMDATA
fi
# Remove binary symlink
- [[ -f /usr/bin/jellyfin ]] && rm /usr/bin/jellyfin
+ rm -f /usr/bin/jellyfin
# Remove sudoers config
[[ -f /etc/sudoers.d/jellyfin-sudoers ]] && rm /etc/sudoers.d/jellyfin-sudoers
# Remove anything at the default locations; catches situations where the user moved the defaults
diff --git a/deployment/debian-package-x64/pkg-src/preinst b/debian/preinst
index 2713fb9b8..2713fb9b8 100644
--- a/deployment/debian-package-x64/pkg-src/preinst
+++ b/debian/preinst
diff --git a/deployment/debian-package-x64/pkg-src/prerm b/debian/prerm
index e965cb7d7..e965cb7d7 100644
--- a/deployment/debian-package-x64/pkg-src/prerm
+++ b/debian/prerm
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 000000000..64e2b48ea
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,51 @@
+#! /usr/bin/make -f
+CONFIG := Release
+TERM := xterm
+SHELL := /bin/bash
+
+HOST_ARCH := $(shell arch)
+BUILD_ARCH := ${DEB_HOST_MULTIARCH}
+ifeq ($(HOST_ARCH),x86_64)
+ # Building AMD64
+ DOTNETRUNTIME := debian-x64
+ ifeq ($(BUILD_ARCH),arm-linux-gnueabihf)
+ # Cross-building ARM on AMD64
+ DOTNETRUNTIME := debian-arm
+ endif
+ ifeq ($(BUILD_ARCH),aarch64-linux-gnu)
+ # Cross-building ARM on AMD64
+ DOTNETRUNTIME := debian-arm64
+ endif
+endif
+ifeq ($(HOST_ARCH),armv7l)
+ # Building ARM
+ DOTNETRUNTIME := debian-arm
+endif
+ifeq ($(HOST_ARCH),arm64)
+ # Building ARM
+ DOTNETRUNTIME := debian-arm64
+endif
+
+export DH_VERBOSE=1
+export DOTNET_CLI_TELEMETRY_OPTOUT=1
+
+%:
+ dh $@
+
+# disable "make check"
+override_dh_auto_test:
+
+# disable stripping debugging symbols
+override_dh_clistrip:
+
+override_dh_auto_build:
+ dotnet publish -maxcpucount:1 --configuration $(CONFIG) --output='$(CURDIR)/usr/lib/jellyfin/bin' --self-contained --runtime $(DOTNETRUNTIME) \
+ "-p:DebugSymbols=false;DebugType=none" Jellyfin.Server
+
+override_dh_auto_clean:
+ dotnet clean -maxcpucount:1 --configuration $(CONFIG) Jellyfin.Server || true
+ rm -rf '$(CURDIR)/usr'
+
+# Force the service name to jellyfin even if we're building jellyfin-nightly
+override_dh_installinit:
+ dh_installinit --name=jellyfin
diff --git a/deployment/debian-package-x64/pkg-src/source.lintian-overrides b/debian/source.lintian-overrides
index aeb332f13..aeb332f13 100644
--- a/deployment/debian-package-x64/pkg-src/source.lintian-overrides
+++ b/debian/source.lintian-overrides
diff --git a/deployment/debian-package-x64/pkg-src/source/format b/debian/source/format
index d3827e75a..d3827e75a 100644
--- a/deployment/debian-package-x64/pkg-src/source/format
+++ b/debian/source/format
diff --git a/deployment/debian-package-x64/pkg-src/source/options b/debian/source/options
index 17b5373d5..17b5373d5 100644
--- a/deployment/debian-package-x64/pkg-src/source/options
+++ b/debian/source/options
diff --git a/deployment/Dockerfile.centos.amd64 b/deployment/Dockerfile.centos.amd64
new file mode 100644
index 000000000..78f051e4f
--- /dev/null
+++ b/deployment/Dockerfile.centos.amd64
@@ -0,0 +1,32 @@
+FROM centos:7
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV IS_DOCKER=YES
+
+# Prepare CentOS environment
+RUN yum update -yq \
+ && yum install -yq epel-release \
+ && yum install -yq @buildsys-build rpmdevtools yum-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel git wget
+
+# Install DotNET SDK
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+ && mkdir -p dotnet-sdk \
+ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
+ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
+
+# Create symlinks and directories
+RUN ln -sf ${SOURCE_DIR}/deployment/build.centos.amd64 /build.sh \
+ && mkdir -p ${SOURCE_DIR}/SPECS \
+ && ln -s ${SOURCE_DIR}/fedora/jellyfin.spec ${SOURCE_DIR}/SPECS/jellyfin.spec \
+ && mkdir -p ${SOURCE_DIR}/SOURCES \
+ && ln -s ${SOURCE_DIR}/fedora ${SOURCE_DIR}/SOURCES
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64
new file mode 100644
index 000000000..daba0eb7d
--- /dev/null
+++ b/deployment/Dockerfile.debian.amd64
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts build-essential mmv \
+ libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev libssl-dev \
+ libssl1.1 liblttng-ust0
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.debian.amd64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64
new file mode 100644
index 000000000..db4e7f817
--- /dev/null
+++ b/deployment/Dockerfile.debian.arm64
@@ -0,0 +1,39 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts build-essential mmv
+
+# Prepare the cross-toolchain
+RUN dpkg --add-architecture arm64 \
+ && apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends cross-gcc-dev \
+ && TARGET_LIST="arm64" cross-gcc-gensource 9 \
+ && cd cross-gcc-packages-amd64/cross-gcc-9-arm64 \
+ && apt-get install -yqq --no-install-recommends \
+ gcc-9-source libstdc++-9-dev-arm64-cross \
+ binutils-aarch64-linux-gnu bison flex libtool \
+ gdb sharutils netbase libmpc-dev libmpfr-dev libgmp-dev \
+ systemtap-sdt-dev autogen expect chrpath zlib1g-dev zip \
+ libc6-dev:arm64 linux-libc-dev:arm64 libgcc1:arm64 \
+ libcurl4-openssl-dev:arm64 libfontconfig1-dev:arm64 \
+ libfreetype6-dev:arm64 libssl-dev:arm64 liblttng-ust0:arm64 libstdc++-9-dev:arm64
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.debian.arm64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf
new file mode 100644
index 000000000..9b008e7fb
--- /dev/null
+++ b/deployment/Dockerfile.debian.armhf
@@ -0,0 +1,40 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts build-essential mmv
+
+# Prepare the cross-toolchain
+RUN dpkg --add-architecture armhf \
+ && apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends cross-gcc-dev \
+ && TARGET_LIST="armhf" cross-gcc-gensource 9 \
+ && cd cross-gcc-packages-amd64/cross-gcc-9-armhf \
+ && apt-get install -yqq --no-install-recommends\
+ gcc-9-source libstdc++-9-dev-armhf-cross \
+ binutils-aarch64-linux-gnu bison flex libtool gdb \
+ sharutils netbase libmpc-dev libmpfr-dev libgmp-dev \
+ systemtap-sdt-dev autogen expect chrpath zlib1g-dev \
+ zip binutils-arm-linux-gnueabihf libc6-dev:armhf \
+ linux-libc-dev:armhf libgcc1:armhf libcurl4-openssl-dev:armhf \
+ libfontconfig1-dev:armhf libfreetype6-dev:armhf libssl-dev:armhf \
+ liblttng-ust0:armhf libstdc++-9-dev:armhf
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.debian.armhf /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.docker.amd64 b/deployment/Dockerfile.docker.amd64
new file mode 100644
index 000000000..b2bd40713
--- /dev/null
+++ b/deployment/Dockerfile.docker.amd64
@@ -0,0 +1,13 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+
+ARG SOURCE_DIR=/src
+ARG ARTIFACT_DIR=/jellyfin
+
+WORKDIR ${SOURCE_DIR}
+COPY . .
+
+ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
+
+# because of changes in docker and systemd we need to not build in parallel at the moment
+# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
+RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-x64 "-p:DebugSymbols=false;DebugType=none"
diff --git a/deployment/Dockerfile.docker.arm64 b/deployment/Dockerfile.docker.arm64
new file mode 100644
index 000000000..fc60f1624
--- /dev/null
+++ b/deployment/Dockerfile.docker.arm64
@@ -0,0 +1,13 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+
+ARG SOURCE_DIR=/src
+ARG ARTIFACT_DIR=/jellyfin
+
+WORKDIR ${SOURCE_DIR}
+COPY . .
+
+ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
+
+# because of changes in docker and systemd we need to not build in parallel at the moment
+# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
+RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-arm64 "-p:DebugSymbols=false;DebugType=none"
diff --git a/deployment/Dockerfile.docker.armhf b/deployment/Dockerfile.docker.armhf
new file mode 100644
index 000000000..f5cc47d83
--- /dev/null
+++ b/deployment/Dockerfile.docker.armhf
@@ -0,0 +1,13 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+
+ARG SOURCE_DIR=/src
+ARG ARTIFACT_DIR=/jellyfin
+
+WORKDIR ${SOURCE_DIR}
+COPY . .
+
+ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
+
+# because of changes in docker and systemd we need to not build in parallel at the moment
+# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
+RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-arm "-p:DebugSymbols=false;DebugType=none"
diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64
new file mode 100644
index 000000000..14eeb6eed
--- /dev/null
+++ b/deployment/Dockerfile.fedora.amd64
@@ -0,0 +1,32 @@
+FROM fedora:33
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV IS_DOCKER=YES
+
+# Prepare Fedora environment
+RUN dnf update -yq \
+ && dnf install -yq @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel systemd wget
+
+# Install DotNET SDK
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+ && mkdir -p dotnet-sdk \
+ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
+ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
+
+
+# Create symlinks and directories
+RUN ln -sf ${SOURCE_DIR}/deployment/build.fedora.amd64 /build.sh \
+ && mkdir -p ${SOURCE_DIR}/SPECS \
+ && ln -s ${SOURCE_DIR}/fedora/jellyfin.spec ${SOURCE_DIR}/SPECS/jellyfin.spec \
+ && mkdir -p ${SOURCE_DIR}/SOURCES \
+ && ln -s ${SOURCE_DIR}/fedora ${SOURCE_DIR}/SOURCES
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64
new file mode 100644
index 000000000..2c7e41cac
--- /dev/null
+++ b/deployment/Dockerfile.linux.amd64
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts unzip \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.amd64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl
new file mode 100644
index 000000000..e903cf1d3
--- /dev/null
+++ b/deployment/Dockerfile.linux.amd64-musl
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts unzip \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.amd64-musl /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64
new file mode 100644
index 000000000..0dd3c5e4e
--- /dev/null
+++ b/deployment/Dockerfile.linux.arm64
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=arm64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts unzip \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.arm64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf
new file mode 100644
index 000000000..16a8218e1
--- /dev/null
+++ b/deployment/Dockerfile.linux.armhf
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=armhf
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts unzip \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.armhf /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos
new file mode 100644
index 000000000..699ab2d40
--- /dev/null
+++ b/deployment/Dockerfile.macos
@@ -0,0 +1,26 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.macos /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable
new file mode 100644
index 000000000..b567d7bce
--- /dev/null
+++ b/deployment/Dockerfile.portable
@@ -0,0 +1,25 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.portable /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64
new file mode 100644
index 000000000..8733be89c
--- /dev/null
+++ b/deployment/Dockerfile.ubuntu.amd64
@@ -0,0 +1,32 @@
+FROM ubuntu:bionic
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg wget ca-certificates devscripts \
+ mmv build-essential libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0
+
+# Install dotnet repository
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+ && mkdir -p dotnet-sdk \
+ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
+ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.ubuntu.amd64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64
new file mode 100644
index 000000000..6ae0d53cc
--- /dev/null
+++ b/deployment/Dockerfile.ubuntu.arm64
@@ -0,0 +1,55 @@
+FROM ubuntu:bionic
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg wget ca-certificates devscripts \
+ mmv build-essential lsb-release
+
+# Install dotnet repository
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+ && mkdir -p dotnet-sdk \
+ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
+ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
+
+# Prepare the cross-toolchain
+RUN rm /etc/apt/sources.list \
+ && export CODENAME="$( lsb_release -c -s )" \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME} main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-updates main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-backports main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-security main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=arm64] http://ports.ubuntu.com/ ${CODENAME} main restricted universe multiverse" >>/etc/apt/sources.list.d/arm64.list \
+ && echo "deb [arch=arm64] http://ports.ubuntu.com/ ${CODENAME}-updates main restricted universe multiverse" >>/etc/apt/sources.list.d/arm64.list \
+ && echo "deb [arch=arm64] http://ports.ubuntu.com/ ${CODENAME}-backports main restricted universe multiverse" >>/etc/apt/sources.list.d/arm64.list \
+ && echo "deb [arch=arm64] http://ports.ubuntu.com/ ${CODENAME}-security main restricted universe multiverse" >>/etc/apt/sources.list.d/arm64.list \
+ && dpkg --add-architecture arm64 \
+ && apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends cross-gcc-dev \
+ && TARGET_LIST="arm64" cross-gcc-gensource 6 \
+ && cd cross-gcc-packages-amd64/cross-gcc-6-arm64 \
+ && ln -fs /usr/share/zoneinfo/America/Toronto /etc/localtime \
+ && apt-get install -yqq --no-install-recommends \
+ gcc-6-source libstdc++6-arm64-cross binutils-aarch64-linux-gnu \
+ bison flex libtool gdb sharutils netbase libcloog-isl-dev libmpc-dev \
+ libmpfr-dev libgmp-dev systemtap-sdt-dev autogen expect chrpath zlib1g-dev \
+ zip libc6-dev:arm64 linux-libc-dev:arm64 libgcc1:arm64 libcurl4-openssl-dev:arm64 \
+ libfontconfig1-dev:arm64 libfreetype6-dev:arm64 liblttng-ust0:arm64 libstdc++6:arm64 libssl-dev:arm64
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.ubuntu.arm64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf
new file mode 100644
index 000000000..154388148
--- /dev/null
+++ b/deployment/Dockerfile.ubuntu.armhf
@@ -0,0 +1,55 @@
+FROM ubuntu:bionic
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV ARCH=amd64
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg wget ca-certificates devscripts \
+ mmv build-essential lsb-release
+
+# Install dotnet repository
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+ && mkdir -p dotnet-sdk \
+ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
+ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
+
+# Prepare the cross-toolchain
+RUN rm /etc/apt/sources.list \
+ && export CODENAME="$( lsb_release -c -s )" \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME} main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-updates main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-backports main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ ${CODENAME}-security main restricted universe multiverse" >>/etc/apt/sources.list.d/amd64.list \
+ && echo "deb [arch=armhf] http://ports.ubuntu.com/ ${CODENAME} main restricted universe multiverse" >>/etc/apt/sources.list.d/armhf.list \
+ && echo "deb [arch=armhf] http://ports.ubuntu.com/ ${CODENAME}-updates main restricted universe multiverse" >>/etc/apt/sources.list.d/armhf.list \
+ && echo "deb [arch=armhf] http://ports.ubuntu.com/ ${CODENAME}-backports main restricted universe multiverse" >>/etc/apt/sources.list.d/armhf.list \
+ && echo "deb [arch=armhf] http://ports.ubuntu.com/ ${CODENAME}-security main restricted universe multiverse" >>/etc/apt/sources.list.d/armhf.list \
+ && dpkg --add-architecture armhf \
+ && apt-get update -yqq \
+ && apt-get install -yqq cross-gcc-dev \
+ && TARGET_LIST="armhf" cross-gcc-gensource 6 \
+ && cd cross-gcc-packages-amd64/cross-gcc-6-armhf \
+ && ln -fs /usr/share/zoneinfo/America/Toronto /etc/localtime \
+ && apt-get install -yqq --no-install-recommends \
+ gcc-6-source libstdc++6-armhf-cross binutils-arm-linux-gnueabihf \
+ bison flex libtool gdb sharutils netbase libcloog-isl-dev libmpc-dev \
+ libmpfr-dev libgmp-dev systemtap-sdt-dev autogen expect chrpath zlib1g-dev \
+ zip libc6-dev:armhf linux-libc-dev:armhf libgcc1:armhf libcurl4-openssl-dev:armhf \
+ libfontconfig1-dev:armhf libfreetype6-dev:armhf liblttng-ust0:armhf libstdc++6:armhf libssl-dev:armhf
+
+# Link to build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.debian.armhf /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64
new file mode 100644
index 000000000..b9543a7c9
--- /dev/null
+++ b/deployment/Dockerfile.windows.amd64
@@ -0,0 +1,25 @@
+FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim
+# Docker build arguments
+ARG SOURCE_DIR=/jellyfin
+ARG ARTIFACT_DIR=/dist
+# Docker run environment
+ENV SOURCE_DIR=/jellyfin
+ENV ARTIFACT_DIR=/dist
+ENV DEB_BUILD_OPTIONS=noddebs
+ENV IS_DOCKER=YES
+
+# Prepare Debian build environment
+RUN apt-get update -yqq \
+ && apt-get install -yqq --no-install-recommends \
+ apt-transport-https debhelper gnupg devscripts unzip \
+ mmv libcurl4-openssl-dev libfontconfig1-dev \
+ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0 zip
+
+# Link to docker-build script
+RUN ln -sf ${SOURCE_DIR}/deployment/build.windows.amd64 /build.sh
+
+VOLUME ${SOURCE_DIR}/
+
+VOLUME ${ARTIFACT_DIR}/
+
+ENTRYPOINT ["/build.sh"]
diff --git a/deployment/README.md b/deployment/README.md
deleted file mode 100644
index a00cd3e6c..000000000
--- a/deployment/README.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Jellyfin Packaging
-
-This directory contains the packaging configuration of Jellyfin for multiple platforms. The specification is below; all package platforms must follow the specification to be compatable with the central `build` script.
-
-## Package List
-
-### Operating System Packages
-
-* `debian-package-x64`: Package for Debian and Ubuntu amd64 systems.
-* `fedora-package-x64`: Package for Fedora, CentOS, and Red Hat Enterprise Linux amd64 systems.
-
-### Portable Builds (archives)
-
-* `debian-x64`: Portable binary archive for Debian amd64 systems.
-* `ubuntu-x64`: Portable binary archive for Ubuntu amd64 systems.
-* `linux-x64`: Portable binary archive for generic Linux amd64 systems.
-* `osx-x64`: Portable binary archive for MacOS amd64 systems.
-* `win-x64`: Portable binary archive for Windows amd64 systems.
-* `win-x86`: Portable binary archive for Windows i386 systems.
-
-### Other Builds
-
-These builds are not necessarily run from the `build` script, but are present for other platforms.
-
-* `framework`: Compiled `.dll` for use with .NET Core runtime on any system.
-* `docker`: Docker manifests for auto-publishing.
-* `unraid`: unRaid Docker template; not built by `build` but imported into unRaid directly.
-* `win-generic`: Portable binary for generic Windows systems.
-
-## Package Specification
-
-### Dependencies
-
-* If a platform requires additional build dependencies, the required binary names, i.e. to validate `which <binary>`, should be specified in a `dependencies.txt` file inside the platform directory.
-
-* Each dependency should be present on its own line.
-
-### Action Scripts
-
-* Actions are defined in BASH scripts with the name `<action>.sh` within the platform directory.
-
-* The list of valid actions are:
-
- 1. `build`: Builds a set of binaries.
- 2. `package`: Assembles the compiled binaries into a package.
- 3. `sign`: Performs signing actions on a package.
- 4. `publish`: Performs a publishing action for a package.
- 5. `clean`: Cleans up any artifacts from the previous actions.
-
-* All package actions are optional, however at least one should generate output files, and any that do should contain a `clean` action.
-
-* Actions are executed in the order specified above, and later actions may depend on former actions.
-
-* Actions except for `clean` should `set -o errexit` to terminate on failed actions.
-
-* The `clean` action should always `exit 0` even if no work is done or it fails.
-
-* The `clean` action can be passed a variable as argument 1, named `keep_artifacts`, containing either the value `y` or `n`. It is indended to handle situations when the user runs `build --keep-artifacts` and should be handled intelligently. Usually, this is used to preserve Docker images while still removing temporary directories.
-
-### Output Files
-
-* Upon completion of the defined actions, at least one output file must be created in the `<platform>/pkg-dist` directory.
-
-* Output files will be moved to the directory `jellyfin-build/<platform>` one directory above the repository root upon completion.
-
-### Common Functions
-
-* A number of common functions are defined in `deployment/common.build.sh` for use by platform scripts.
-
-* Each action script should import the common functions to define a number of standard variables.
-
-* The common variables are:
-
- * `ROOT`: The Jellyfin repostiory root, usually `../..`.
- * `CONFIG`: The .NET config, usually `Release`.
- * `DOTNETRUNTIME`: The .NET `--runtime` value, platform-dependent.
- * `OUTPUT_DIR`: The intermediate output dir, usually `./dist/jellyfin_${VERSION}`.
- * `BUILD_CONTEXT`: The Docker build context, usually `../..`.
- * `DOCKERFILE`: The Dockerfile, usually `Dockerfile` in the platform directory.
- * `IMAGE_TAG`: A tag for the built Docker image.
- * `PKG_DIR`: The final binary output directory for collection, invariably `pkg-dist`.
- * `ARCHIVE_CMD`: The compression/archive command for release archives, usually `tar -xvzf` or `zip`.
-
-#### `get_version`
-
-Reads the version information from `SharedVersion.cs`.
-
-**Arguments:** `ROOT`
-
-#### `build_jellyfin`
-
-Build a standard self-contained binary in the current OS context.
-
-**Arguments:** `ROOT` `CONFIG` `DOTNETRUNTIME` `OUTPUT_DIR`
-
-#### `build_jellyfin_docker`
-
-Build a standard self-contained binary in a Docker image.
-
-**Arguments:** `BUILD_CONTEXT` `DOCKERFILE` `IMAGE_TAG`
-
-#### `clean_jellyfin`
-
-Clean up a build for housekeeping.
-
-**Arguments:** `ROOT` `CONFIG` `OUTPUT_DIR` `PKG_DIR`
-
-#### `package_portable`
-
-Produce a compressed archive.
-
-**Arguments:** `ROOT` `OUTPUT_DIR` `PKG_DIR` `ARCHIVE_CMD`
-
diff --git a/deployment/build.centos.amd64 b/deployment/build.centos.amd64
new file mode 100755
index 000000000..bfdc6e591
--- /dev/null
+++ b/deployment/build.centos.amd64
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+#= CentOS/RHEL 7+ amd64 .rpm
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove BuildRequires for dotnet-sdk-6.0, since it's installed manually
+ pushd fedora
+
+ cp -a jellyfin.spec /tmp/spec.orig
+ sed -i 's/BuildRequires: dotnet/# BuildRequires: dotnet/' jellyfin.spec
+
+ popd
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd fedora
+
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ sed -i "s/Version:.*/Version: ${BUILD_ID}/" jellyfin.spec
+ sed -i "/%changelog/q" jellyfin.spec
+
+ cat <<EOF >>jellyfin.spec
+* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
+- Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+EOF
+ popd
+fi
+
+# Build RPM
+make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
+rpmbuild --rebuild -bb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm
+
+# Move the artifacts out
+mv /root/rpmbuild/RPMS/x86_64/jellyfin-*.rpm /root/rpmbuild/SRPMS/jellyfin-*.src.rpm ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+rm -f fedora/jellyfin*.tar.gz
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ pushd fedora
+
+ cp -a /tmp/spec.orig jellyfin.spec
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+
+ popd
+fi
+
+popd
diff --git a/deployment/build.debian.amd64 b/deployment/build.debian.amd64
new file mode 100755
index 000000000..b2bbf9c29
--- /dev/null
+++ b/deployment/build.debian.amd64
@@ -0,0 +1,43 @@
+#!/bin/bash
+
+#= Debian 10+ amd64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+dpkg-buildpackage -us -uc --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.debian.arm64 b/deployment/build.debian.arm64
new file mode 100755
index 000000000..02f84471e
--- /dev/null
+++ b/deployment/build.debian.arm64
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#= Debian 10+ arm64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
+dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.debian.armhf b/deployment/build.debian.armhf
new file mode 100755
index 000000000..92779cb59
--- /dev/null
+++ b/deployment/build.debian.armhf
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#= Debian 10+ arm64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
+dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.fedora.amd64 b/deployment/build.fedora.amd64
new file mode 100755
index 000000000..23c5ed86a
--- /dev/null
+++ b/deployment/build.fedora.amd64
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+#= Fedora 29+ amd64 .rpm
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove BuildRequires for dotnet-sdk-6.0, since it's installed manually
+ pushd fedora
+
+ cp -a jellyfin.spec /tmp/spec.orig
+ sed -i 's/BuildRequires: dotnet/# BuildRequires: dotnet/' jellyfin.spec
+
+ popd
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd fedora
+
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ sed -i "s/Version:.*/Version: ${BUILD_ID}/" jellyfin.spec
+ sed -i "/%changelog/q" jellyfin.spec
+
+ cat <<EOF >>jellyfin.spec
+* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
+- Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+EOF
+ popd
+fi
+
+# Build RPM
+make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
+rpmbuild -rb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm
+
+# Move the artifacts out
+mv /root/rpmbuild/RPMS/x86_64/jellyfin-*.rpm /root/rpmbuild/SRPMS/jellyfin-*.src.rpm ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+rm -f fedora/jellyfin*.tar.gz
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ pushd fedora
+
+ cp -a /tmp/spec.orig jellyfin.spec
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+
+ popd
+fi
+
+popd
diff --git a/deployment/build.linux.amd64 b/deployment/build.linux.amd64
new file mode 100755
index 000000000..a1e7f661a
--- /dev/null
+++ b/deployment/build.linux.amd64
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= Generic Linux amd64 .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-x64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+tar -czf jellyfin-server_${version}_linux-amd64.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.linux.amd64-musl b/deployment/build.linux.amd64-musl
new file mode 100755
index 000000000..72444c05e
--- /dev/null
+++ b/deployment/build.linux.amd64-musl
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= Generic Linux amd64-musl .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-musl-x64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+tar -czf jellyfin-server_${version}_linux-amd64-musl.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.linux.arm64 b/deployment/build.linux.arm64
new file mode 100755
index 000000000..e362607a7
--- /dev/null
+++ b/deployment/build.linux.arm64
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= Generic Linux arm64 .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-arm64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+tar -czf jellyfin-server_${version}_linux-arm64.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.linux.armhf b/deployment/build.linux.armhf
new file mode 100755
index 000000000..c0d0607fc
--- /dev/null
+++ b/deployment/build.linux.armhf
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= Generic Linux armhf .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-arm --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+tar -czf jellyfin-server_${version}_linux-armhf.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.macos b/deployment/build.macos
new file mode 100755
index 000000000..6255c80cb
--- /dev/null
+++ b/deployment/build.macos
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= MacOS 10.13+ .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime osx-x64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+tar -czf jellyfin-server_${version}_macos-amd64.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.portable b/deployment/build.portable
new file mode 100755
index 000000000..a6c741881
--- /dev/null
+++ b/deployment/build.portable
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#= Portable .NET DLL .tar.gz
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+# Build archives
+dotnet publish Jellyfin.Server --configuration Release --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=false"
+tar -czf jellyfin-server_${version}_portable.tar.gz -C dist jellyfin-server_${version}
+rm -rf dist/jellyfin-server_${version}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.ubuntu.amd64 b/deployment/build.ubuntu.amd64
new file mode 100755
index 000000000..c36978c9e
--- /dev/null
+++ b/deployment/build.ubuntu.amd64
@@ -0,0 +1,43 @@
+#!/bin/bash
+
+#= Ubuntu 18.04+ amd64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+dpkg-buildpackage -us -uc --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.ubuntu.arm64 b/deployment/build.ubuntu.arm64
new file mode 100755
index 000000000..76d51e321
--- /dev/null
+++ b/deployment/build.ubuntu.arm64
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#= Ubuntu 18.04+ arm64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
+dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.ubuntu.armhf b/deployment/build.ubuntu.armhf
new file mode 100755
index 000000000..0ff5ab066
--- /dev/null
+++ b/deployment/build.ubuntu.armhf
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#= Ubuntu 18.04+ arm64 .deb
+
+set -o errexit
+set -o xtrace
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ # Remove build-dep for dotnet-sdk-6.0, since it's installed manually
+ cp -a debian/control /tmp/control.orig
+ sed -i '/dotnet-sdk-6.0,/d' debian/control
+fi
+
+# Modify changelog to unstable configuration if IS_UNSTABLE
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ pushd debian
+ PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
+
+ cat <<EOF >changelog
+jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
+
+ * Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
+
+ -- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
+EOF
+ popd
+fi
+
+# Build DEB
+export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
+dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean
+
+mkdir -p ${ARTIFACT_DIR}/
+mv ../jellyfin*.{deb,dsc,tar.gz,buildinfo,changes} ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ cp -a /tmp/control.orig debian/control
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/build.windows.amd64 b/deployment/build.windows.amd64
new file mode 100755
index 000000000..a9daa6a23
--- /dev/null
+++ b/deployment/build.windows.amd64
@@ -0,0 +1,52 @@
+#!/bin/bash
+
+#= Windows 7+ amd64 (x64) .zip
+
+set -o errexit
+set -o xtrace
+
+# Version variables
+NSSM_VERSION="nssm-2.24-101-g897c7ad"
+NSSM_URL="http://files.evilt.win/nssm/${NSSM_VERSION}.zip"
+FFMPEG_URL="https://repo.jellyfin.org/releases/server/windows/ffmpeg/jellyfin-ffmpeg.zip";
+
+# Move to source directory
+pushd ${SOURCE_DIR}
+
+# Get version
+if [[ ${IS_UNSTABLE} == 'yes' ]]; then
+ version="${BUILD_ID}"
+else
+ version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
+fi
+
+output_dir="dist/jellyfin-server_${version}"
+
+# Build binary
+dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime win-x64 --output ${output_dir}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true"
+
+# Prepare addins
+addin_build_dir="$( mktemp -d )"
+wget ${NSSM_URL} -O ${addin_build_dir}/nssm.zip
+wget ${FFMPEG_URL} -O ${addin_build_dir}/jellyfin-ffmpeg.zip
+unzip ${addin_build_dir}/nssm.zip -d ${addin_build_dir}
+cp ${addin_build_dir}/${NSSM_VERSION}/win64/nssm.exe ${output_dir}/nssm.exe
+unzip ${addin_build_dir}/jellyfin-ffmpeg.zip -d ${addin_build_dir}/jellyfin-ffmpeg
+cp ${addin_build_dir}/jellyfin-ffmpeg/* ${output_dir}
+rm -rf ${addin_build_dir}
+
+# Create zip package
+pushd dist
+zip -qr jellyfin-server_${version}.portable.zip jellyfin-server_${version}
+popd
+rm -rf ${output_dir}
+
+# Move the artifacts out
+mkdir -p ${ARTIFACT_DIR}/
+mv dist/jellyfin[-_]*.zip ${ARTIFACT_DIR}/
+
+if [[ ${IS_DOCKER} == YES ]]; then
+ chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR}
+fi
+
+popd
diff --git a/deployment/centos-package-x64/Dockerfile b/deployment/centos-package-x64/Dockerfile
deleted file mode 100644
index 38853f173..000000000
--- a/deployment/centos-package-x64/Dockerfile
+++ /dev/null
@@ -1,27 +0,0 @@
-FROM centos:7
-# Docker build arguments
-ARG SOURCE_DIR=/jellyfin
-ARG PLATFORM_DIR=/jellyfin/deployment/centos-package-x64
-ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=2.2
-# Docker run environment
-ENV SOURCE_DIR=/jellyfin
-ENV ARTIFACT_DIR=/dist
-
-# Prepare CentOS build environment
-RUN yum update -y \
- && yum install -y @buildsys-build rpmdevtools yum-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel \
- && rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm \
- && rpmdev-setuptree \
- && yum install -y dotnet-sdk-${SDK_VERSION} \
- && ln -sf ${PLATFORM_DIR}/docker-build.sh /docker-build.sh \
- && mkdir -p ${SOURCE_DIR}/SPECS \
- && ln -s ${PLATFORM_DIR}/pkg-src/jellyfin.spec ${SOURCE_DIR}/SPECS/jellyfin.spec \
- && mkdir -p ${SOURCE_DIR}/SOURCES \
- && ln -s ${PLATFORM_DIR}/pkg-src ${SOURCE_DIR}/SOURCES
-
-VOLUME ${ARTIFACT_DIR}/
-
-COPY . ${SOURCE_DIR}/
-
-ENTRYPOINT ["/docker-build.sh"]
diff --git a/deployment/centos-package-x64/clean.sh b/deployment/centos-package-x64/clean.sh
deleted file mode 100755
index 7278372e1..000000000
--- a/deployment/centos-package-x64/clean.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-keep_artifacts="${1}"
-
-WORKDIR="$( pwd )"
-VERSION="$( grep -A1 '^Version:' ${WORKDIR}/pkg-src/jellyfin.spec | awk '{ print $NF }' )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-package_source_dir="${WORKDIR}/pkg-src"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-centos-build"
-
-rm -f "${package_source_dir}/jellyfin-${VERSION}.tar.gz" &>/dev/null \
- || sudo rm -f "${package_source_dir}/jellyfin-${VERSION}.tar.gz" &>/dev/null
-
-rm -rf "${package_temporary_dir}" &>/dev/null \
- || sudo rm -rf "${package_temporary_dir}" &>/dev/null
-
-rm -rf "${output_dir}" &>/dev/null \
- || sudo rm -rf "${output_dir}" &>/dev/null
-
-if [[ ${keep_artifacts} == 'n' ]]; then
- docker_sudo=""
- if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo=sudo
- fi
- ${docker_sudo} docker image rm ${image_name} --force
-fi
diff --git a/deployment/centos-package-x64/dependencies.txt b/deployment/centos-package-x64/dependencies.txt
deleted file mode 100644
index bdb967096..000000000
--- a/deployment/centos-package-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-docker
diff --git a/deployment/centos-package-x64/docker-build.sh b/deployment/centos-package-x64/docker-build.sh
deleted file mode 100755
index 3acf1ec0d..000000000
--- a/deployment/centos-package-x64/docker-build.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-# Builds the RPM inside the Docker container
-
-set -o errexit
-set -o xtrace
-
-# Move to source directory
-pushd ${SOURCE_DIR}
-
-ls -al SOURCES/pkg-src/
-
-# Build RPM
-spectool -g -R SPECS/jellyfin.spec
-rpmbuild -bs SPECS/jellyfin.spec --define "_sourcedir ${SOURCE_DIR}/SOURCES/pkg-src/"
-rpmbuild -bb SPECS/jellyfin.spec --define "_sourcedir ${SOURCE_DIR}/SOURCES/pkg-src/"
-
-# Move the artifacts out
-mkdir -p ${ARTIFACT_DIR}/rpm
-mv /root/rpmbuild/RPMS/x86_64/jellyfin-*.rpm /root/rpmbuild/SRPMS/jellyfin-*.src.rpm ${ARTIFACT_DIR}/rpm/
diff --git a/deployment/centos-package-x64/package.sh b/deployment/centos-package-x64/package.sh
deleted file mode 100755
index 27d686e46..000000000
--- a/deployment/centos-package-x64/package.sh
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-WORKDIR="$( pwd )"
-VERSION="$( grep '^Version:' ${WORKDIR}/pkg-src/jellyfin.spec | awk '{ print $NF }' )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-pkg_src_dir="${WORKDIR}/pkg-src"
-current_user="$( whoami )"
-image_name="jellyfin-centos-build"
-
-# Determine if sudo should be used for Docker
-if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo="sudo"
-else
- docker_sudo=""
-fi
-
-# Create RPM source archive
-GNU_TAR=1
-mkdir -p "${package_temporary_dir}"
-echo "Bundling all sources for RPM build."
-tar \
---transform "s,^\.,jellyfin-${VERSION}," \
---exclude='.git*' \
---exclude='**/.git' \
---exclude='**/.hg' \
---exclude='**/.vs' \
---exclude='**/.vscode' \
---exclude='deployment' \
---exclude='**/bin' \
---exclude='**/obj' \
---exclude='**/.nuget' \
---exclude='*.deb' \
---exclude='*.rpm' \
--czf "${pkg_src_dir}/jellyfin-${VERSION}.tar.gz" \
--C "../.." ./ || GNU_TAR=0
-
-if [ $GNU_TAR -eq 0 ]; then
- echo "The installed tar binary did not support --transform. Using workaround."
- mkdir -p "${package_temporary_dir}/jellyfin"
- # Not GNU tar
- tar \
- --exclude='.git*' \
- --exclude='**/.git' \
- --exclude='**/.hg' \
- --exclude='**/.vs' \
- --exclude='**/.vscode' \
- --exclude='deployment' \
- --exclude='**/bin' \
- --exclude='**/obj' \
- --exclude='**/.nuget' \
- --exclude='*.deb' \
- --exclude='*.rpm' \
- -zcf \
- "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz" \
- -C "../.." ./
- echo "Extracting filtered package."
- tar -xzf "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz" -C "${package_temporary_dir}/jellyfin-${VERSION}"
- echo "Removing filtered package."
- rm -f "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz"
- echo "Repackaging package into final tarball."
- tar -czf "${pkg_src_dir}/jellyfin-${VERSION}.tar.gz" -C "${package_temporary_dir}" "jellyfin-${VERSION}"
-fi
-
-# Set up the build environment Docker image
-${docker_sudo} docker build ../.. -t "${image_name}" -f ./Dockerfile
-# Build the RPMs and copy out to ${package_temporary_dir}
-${docker_sudo} docker run --rm -v "${package_temporary_dir}:/dist" "${image_name}"
-# Correct ownership on the RPMs (as current user, then as root if that fails)
-chown -R "${current_user}" "${package_temporary_dir}" \
- || sudo chown -R "${current_user}" "${package_temporary_dir}"
-# Move the RPMs to the output directory
-mkdir -p "${output_dir}"
-mv "${package_temporary_dir}"/rpm/* "${output_dir}"
diff --git a/deployment/centos-package-x64/pkg-src b/deployment/centos-package-x64/pkg-src
deleted file mode 120000
index dfd6497cf..000000000
--- a/deployment/centos-package-x64/pkg-src
+++ /dev/null
@@ -1 +0,0 @@
-../fedora-package-x64/pkg-src \ No newline at end of file
diff --git a/deployment/common.build.sh b/deployment/common.build.sh
deleted file mode 100755
index c191ec2a1..000000000
--- a/deployment/common.build.sh
+++ /dev/null
@@ -1,111 +0,0 @@
-#!/usr/bin/env bash
-
-set -o errexit
-set -o nounset
-
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-CYAN='\033[0;36m'
-NC='\033[0m' # No Color
-
-DEFAULT_BUILD_CONTEXT="../.."
-DEFAULT_ROOT="."
-DEFAULT_DOTNETRUNTIME="framework"
-DEFAULT_CONFIG="Release"
-DEFAULT_OUTPUT_DIR="dist/jellyfin-git"
-DEFAULT_PKG_DIR="pkg-dist"
-DEFAULT_DOCKERFILE="Dockerfile"
-DEFAULT_IMAGE_TAG="jellyfin:"`git rev-parse --abbrev-ref HEAD`
-DEFAULT_ARCHIVE_CMD="tar -xvzf"
-
-# Parse the version from the AssemblyVersion
-get_version()
-(
- local ROOT=${1-$DEFAULT_ROOT}
- grep "AssemblyVersion" ${ROOT}/SharedVersion.cs \
- | sed -E 's/\[assembly: ?AssemblyVersion\("([0-9\.]+)"\)\]/\1/'
-)
-
-# Run a build
-build_jellyfin()
-(
- ROOT=${1-$DEFAULT_ROOT}
- CONFIG=${2-$DEFAULT_CONFIG}
- DOTNETRUNTIME=${3-$DEFAULT_DOTNETRUNTIME}
- OUTPUT_DIR=${4-$DEFAULT_OUTPUT_DIR}
-
- echo -e "${CYAN}Building jellyfin in '${ROOT}' for ${DOTNETRUNTIME} with configuration ${CONFIG} and output directory '${OUTPUT_DIR}'.${NC}"
- if [[ $DOTNETRUNTIME == 'framework' ]]; then
- dotnet publish "${ROOT}" --configuration "${CONFIG}" --output="${OUTPUT_DIR}"
- else
- dotnet publish "${ROOT}" --configuration "${CONFIG}" --output="${OUTPUT_DIR}" --self-contained --runtime ${DOTNETRUNTIME}
- fi
- EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Build jellyfin in '${ROOT}' for ${DOTNETRUNTIME} with configuration ${CONFIG} and output directory '${OUTPUT_DIR}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Build jellyfin in '${ROOT}' for ${DOTNETRUNTIME} with configuration ${CONFIG} and output directory '${OUTPUT_DIR}' FAILED.${NC}"
- fi
-)
-
-# Run a docker
-build_jellyfin_docker()
-(
- BUILD_CONTEXT=${1-$DEFAULT_BUILD_CONTEXT}
- DOCKERFILE=${2-$DEFAULT_DOCKERFILE}
- IMAGE_TAG=${3-$DEFAULT_IMAGE_TAG}
-
- echo -e "${CYAN}Building jellyfin docker image in '${BUILD_CONTEXT}' with Dockerfile '${DOCKERFILE}' and tag '${IMAGE_TAG}'.${NC}"
- docker build -t ${IMAGE_TAG} -f ${DOCKERFILE} ${BUILD_CONTEXT}
- EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Building jellyfin docker image in '${BUILD_CONTEXT}' with Dockerfile '${DOCKERFILE}' and tag '${IMAGE_TAG}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Building jellyfin docker image in '${BUILD_CONTEXT}' with Dockerfile '${DOCKERFILE}' and tag '${IMAGE_TAG}' FAILED.${NC}"
- fi
-)
-
-# Clean a build
-clean_jellyfin()
-(
- local ROOT=${1-$DEFAULT_ROOT}
- local CONFIG=${2-$DEFAULT_CONFIG}
- local OUTPUT_DIR=${3-$DEFAULT_OUTPUT_DIR}
- local PKG_DIR=${4-$DEFAULT_PKG_DIR}
- echo -e "${CYAN}Cleaning jellyfin in '${ROOT}'' with configuration ${CONFIG} and output directory '${OUTPUT_DIR}'.${NC}"
- echo -e "${CYAN}Deleting '${OUTPUT_DIR}'${NC}"
- rm -rf "$OUTPUT_DIR"
- echo -e "${CYAN}Deleting '${PKG_DIR}'${NC}"
- rm -rf "$PKG_DIR"
- dotnet clean "${ROOT}" -maxcpucount:1 --configuration ${CONFIG}
- local EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Clean jellyfin in '${ROOT}' with configuration ${CONFIG} and output directory '${OUTPUT_DIR}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Clean jellyfin in '${ROOT}' with configuration ${CONFIG} and output directory '${OUTPUT_DIR}' failed.${NC}"
- fi
-)
-
-# Packages the output folder into an archive.
-package_portable()
-(
- local ROOT=${1-$DEFAULT_ROOT}
- local OUTPUT_DIR=${2-$DEFAULT_OUTPUT_DIR}
- local PKG_DIR=${3-$DEFAULT_PKG_DIR}
- local ARCHIVE_CMD=${4-$DEFAULT_ARCHIVE_CMD}
- # Package portable build result
- if [ -d ${OUTPUT_DIR} ]; then
- echo -e "${CYAN}Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}'.${NC}"
- mkdir -p ${PKG_DIR}
- tar -zcvf "${PKG_DIR}/`basename "${OUTPUT_DIR}"`.portable.tar.gz" -C "`dirname "${OUTPUT_DIR}"`" "`basename "${OUTPUT_DIR}"`"
- local EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' FAILED.${NC}"
- fi
- else
- echo -e "${RED}[FAIL] Build artifacts do not exist for ${OUTPUT_DIR}. Run build.sh first.${NC}"
- fi
-)
-
diff --git a/deployment/debian-package-x64/Dockerfile b/deployment/debian-package-x64/Dockerfile
deleted file mode 100644
index 9819cc20d..000000000
--- a/deployment/debian-package-x64/Dockerfile
+++ /dev/null
@@ -1,21 +0,0 @@
-FROM microsoft/dotnet:2.2-sdk-stretch
-# Docker build arguments
-ARG SOURCE_DIR=/jellyfin
-ARG PLATFORM_DIR=/jellyfin/deployment/debian-package-x64
-ARG ARTIFACT_DIR=/dist
-# Docker run environment
-ENV SOURCE_DIR=/jellyfin
-ENV ARTIFACT_DIR=/dist
-ENV DEB_BUILD_OPTIONS=noddebs
-
-# Prepare Debian build environment
-RUN apt-get update \
- && apt-get install -y apt-transport-https debhelper gnupg wget devscripts mmv libc6-dev libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev \
- && ln -sf ${PLATFORM_DIR}/docker-build.sh /docker-build.sh \
- && mkdir -p ${SOURCE_DIR} && ln -sf ${PLATFORM_DIR}/pkg-src ${SOURCE_DIR}/debian
-
-VOLUME ${ARTIFACT_DIR}/
-
-COPY . ${SOURCE_DIR}/
-
-ENTRYPOINT ["/docker-build.sh"]
diff --git a/deployment/debian-package-x64/clean.sh b/deployment/debian-package-x64/clean.sh
deleted file mode 100755
index b2960fcb3..000000000
--- a/deployment/debian-package-x64/clean.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-keep_artifacts="${1}"
-
-WORKDIR="$( pwd )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-debian-build"
-
-rm -rf "${package_temporary_dir}" &>/dev/null \
- || sudo rm -rf "${package_temporary_dir}" &>/dev/null
-
-rm -rf "${output_dir}" &>/dev/null \
- || sudo rm -rf "${output_dir}" &>/dev/null
-
-if [[ ${keep_artifacts} == 'n' ]]; then
- docker_sudo=""
- if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo=sudo
- fi
- ${docker_sudo} docker image rm ${image_name} --force
-fi
diff --git a/deployment/debian-package-x64/dependencies.txt b/deployment/debian-package-x64/dependencies.txt
deleted file mode 100644
index bdb967096..000000000
--- a/deployment/debian-package-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-docker
diff --git a/deployment/debian-package-x64/docker-build.sh b/deployment/debian-package-x64/docker-build.sh
deleted file mode 100755
index 0590be097..000000000
--- a/deployment/debian-package-x64/docker-build.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/bash
-
-# Builds the DEB inside the Docker container
-
-set -o errexit
-set -o xtrace
-
-# Move to source directory
-pushd ${SOURCE_DIR}
-
-# Remove build-dep for dotnet-sdk-2.2, since it's not a package in this image
-sed -i '/dotnet-sdk-2.2,/d' debian/control
-
-# Build DEB
-dpkg-buildpackage -us -uc
-
-# Move the artifacts out
-mkdir -p ${ARTIFACT_DIR}/deb
-mv /jellyfin_* ${ARTIFACT_DIR}/deb/
diff --git a/deployment/debian-package-x64/package.sh b/deployment/debian-package-x64/package.sh
deleted file mode 100755
index d7c3f5809..000000000
--- a/deployment/debian-package-x64/package.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-WORKDIR="$( pwd )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-debian-build"
-
-# Determine if sudo should be used for Docker
-if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo="sudo"
-else
- docker_sudo=""
-fi
-
-# Set up the build environment Docker image
-${docker_sudo} docker build ../.. -t "${image_name}" -f ./Dockerfile
-# Build the DEBs and copy out to ${package_temporary_dir}
-${docker_sudo} docker run --rm -v "${package_temporary_dir}:/dist" "${image_name}"
-# Correct ownership on the DEBs (as current user, then as root if that fails)
-chown -R "${current_user}" "${package_temporary_dir}" &>/dev/null \
- || sudo chown -R "${current_user}" "${package_temporary_dir}" &>/dev/null
-# Move the DEBs to the output directory
-mkdir -p "${output_dir}"
-mv "${package_temporary_dir}"/deb/* "${output_dir}"
diff --git a/deployment/debian-package-x64/pkg-src/bin/restart.sh b/deployment/debian-package-x64/pkg-src/bin/restart.sh
deleted file mode 100644
index 738f86727..000000000
--- a/deployment/debian-package-x64/pkg-src/bin/restart.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-NAME=jellyfin
-
-restart_cmds=(
- "systemctl restart ${NAME}"
- "service ${NAME} restart"
- "/etc/init.d/${NAME} restart"
- "s6-svc -t /var/run/s6/services/${NAME}"
-)
-
-for restart_cmd in "${restart_cmds[@]}"; do
- cmd=$(echo "$restart_cmd" | awk '{print $1}')
- cmd_loc=$(command -v ${cmd})
- if [[ -n "$cmd_loc" ]]; then
- restart_cmd=$(echo "$restart_cmd" | sed -e "s%${cmd}%${cmd_loc}%")
- echo "sleep 2; sudo $restart_cmd > /dev/null 2>&1" | at now > /dev/null 2>&1
- exit 0
- fi
-done
diff --git a/deployment/debian-package-x64/pkg-src/changelog b/deployment/debian-package-x64/pkg-src/changelog
deleted file mode 100644
index 7b7efff27..000000000
--- a/deployment/debian-package-x64/pkg-src/changelog
+++ /dev/null
@@ -1,276 +0,0 @@
-jellyfin (10.2.1-1) unstable; urgency=medium
-
- * jellyfin:
- * PR920 Fix cachedir missing from Docker container
- * PR924 Use the movie name instead of folder name
- * PR933 Semi-revert to prefer old movie grouping behaviour
- * PR948 Revert movie matching (supercedes PR933, PR924, PR739)
- * PR960 Use jellyfin/ffmpeg image
- * jellyfin-web:
- * PR136 Re-add OpenSubtitles configuration page
- * PR137 Replace HeaderEmbyServer with HeaderJellyfinServer on plugincatalog
- * PR138 Remove left-over JS for Customize Home Screen
- * PR141 Exit fullscreen automatically after video playback ends
-
- -- Jellyfin Packaging Team <packaging@jellyfin.org> Wed, 20 Feb 2019 11:36:16 -0500
-
-jellyfin (10.2.0-2) unstable; urgency=medium
-
- * jellyfin:
- * PR452 Use EF Core for Activity database
- * PR535 Clean up streambuilder
- * PR655 Support trying local branches in submodule
- * PR656 Do some logging in MediaInfoService
- * PR657 Remove conditions that are always true/false
- * PR661 Fix NullRef from progress report
- * PR663 Use TagLibSharp Nuget package
- * PR664 Revert "Fix segment_time_delta for ffmpeg 4.1"
- * PR666 Add cross-platform build for arm64
- * PR668 Return Audio objects from MusicAlbum.Tracks
- * PR671 Set EnableRaisingEvents correctly
- * PR672 Remove unconditional caching, modified since header and use ETags
- * PR677 Fix arm32 Docker
- * PR681 Fix Windows build script errors + pin ffmpeg to 4.0
- * PR686 Disable some StyleCop warnings
- * PR687 Fix some analyzer warnings
- * PR689 Fix RPM package build for fedora
- * PR702 Fix debug build on windows
- * PR706 Make another docker layer reusable
- * PR709 Fix always null expressions
- * PR710 Fix a spelling mistake
- * PR711 Remove remnants of system events
- * PR713 Fix empty statement in DidlBuilder.cs
- * PR716 Remove more compile time warnings
- * PR721 Change image dimentions from double to int
- * PR723 Minor improvements to db code
- * PR724 Move Skia back into it's own project
- * PR726 Clean up IFileSystem wrappers around stdlib.
- * PR727 Change default aspect ratio to 2/3 from 0
- * PR728 Use ffmpeg from jrottenberg/ffmpeg
- * PR732 Reworked LocalizationManager to load data async
- * PR733 Remove unused function
- * PR734 Fix more analyzer warnings
- * PR736 Start startup tasks async
- * PR737 Add AssemblyInfo for Jellyfin.Drawing.Skia
- * PR739 Change multi version logic for movies
- * PR740 Remove code for pre-installed plugins & properly check if file exists
- * PR756 Make cache dir configurable
- * PR757 Fix default aspect ratio
- * PR758 Add password field to initial setup
- * PR764 Remove dead code, made some functions properly async
- * PR769 Fix conditions where the ! was swallowed in #726
- * PR774 reimplement support for plugin repository
- * PR782 Remove commented file MediaBrowser.LocalMetadata.Savers.PersonXmlSaver
- * PR783 Update builds to use #749 and #756
- * PR788 Fix more warnings
- * PR794 Remove MoreLINQ
- * PR797 Fix all warnings
- * PR798 Cleanup around the api endpoints
- * PR800 Add CentOS and update rpm spec for the cachedir option
- * PR802 Fix build error
- * PR804 Handle new option parser properly
- * PR805 Add weblate translation status to README
- * PR807 Fix restart script in OS packages
- * PR810 Fix loading of rating files
- * PR812 Fix up the explicit docs links in the README
- * PR819 Some small changes in Device.cs and DidlBuilder.cs
- * PR822 Complete rename ImageSize -> ImageDimensions
- * PR824 Improved Docker pkgbuild
- * PR831 Move some arrays to generics
- * PR833 Add await to GetCountries in LocalizationService
- * PR834 Add donation badge and reorganize badges
- * PR838 Quick style fix
- * PR840 Fix more warnings
- * PR841 Fix OC badge to all and add forum badge
- * PR842 Use VAAPI-enabled ffmpeg
- * PR852 Use SQLitePCL.pretty.netstandard on NuGet
- * PR853 Fix poor handling of cache directories
- * PR864: Add support for ZIP plugin archives
- * PR868: Fix audio streaming via BaseProgressiveStreamingService
- * PR869: Remove DLL support and require all packages/plugins to be zip archives
- * PR872: Fix potential NullReferenceException
- * PR890: Drop ETag and use Last-Modified header
- * PR892: Add jellyfin-ffmpeg and versioning to package deps
- * PR899: DLNA: Fix race condition leading to missing device names
- * PR901: Properly dispose HttpWebResponse when the request failed to avoid 'too many open files'
- * PR909: Fix docker arm builds
- * PR910: Enhance Dockerfiles
- * PR911: Checkout submodules in Docker Hub hook
- * jellyfin-web:
- * PR51 remove more code for sync and camera roll
- * PR56 Use English for fallback translations and clean up language files
- * PR58 Css slider fixes
- * PR62 remove BOM markers
- * PR65 Fix profile image not being shown on profile page
- * PR73 Dev sync
- * PR74 Add download menu option to media items
- * PR75 User profile fixes
- * PR76 Fix syntax error caused by deminification
- * PR79 Remove unused Connect related from the frontend
- * PR80 Remove games
- * PR92 Added frontend support for a password field on setup
- * PR94 Update british strings
- * PR95 add display language option back
- * PR112 Removed seasonal theme support
- * PR116 Consolidate all strings into a single file per language
- * PR117 Fix volume slider behavior
- * PR118 Enable and fix PiP for Safari
- * PR119 Make the toggle track visible on all themes
- * PR121 Fix syntax error in site.js
- * PR127 Change sharedcomponents module to core
- * PR135 Make sure fallback culture is always available
-
- -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 15 Feb 2019 20:51:25 -0500
-
-jellyfin (10.1.0-1) unstable; urgency=medium
-
- * jellyfin:
- * PR335 Build scripts and build system consolidation.
- * PR424 add jellyfin-web as submodule
- * PR455 Cleanup some small things
- * PR458 Clean up several minor issues and add TODOs
- * PR506 Removing tabs and trailing whitespace
- * PR508 Update internal versioning and user agents.
- * PR516 Remove useless properties from IEnvironmentInfo
- * PR520 Fix potential bug where aspect ratio would be incorrectly calculated
- * PR534 Add linux-arm and linux-arm64 native NuGet dependency.
- * PR540 Update Emby API keys to our own
- * PR541 Change ItemId to Guid in ProviderManager
- * PR556 Fix "Password Reset by PIN" page
- * PR562 Fix error with uppercase photo extension and fix typo in a log line
- * PR563 Update dev from master
- * PR566 Avoid printing stacktrace when bind to port 1900 fails
- * PR567 Shutdown gracefully when recieving a termination signal
- * PR571 Add more NuGet metadata properties
- * PR575 Reformat all C# server code to conform with code standards
- * PR576 Add code analysers for debug builds
- * PR580 Fix Docker build
- * PR582 Replace custom image parser with Skia
- * PR587 Add nuget info to Emby.Naming
- * PR589 Ensure config and log folders exist
- * PR596 Fix indentation for xml files
- * PR598 Remove MediaBrowser.Text for license violations and hackiness
- * PR606 Slim down docker image
- * PR613 Update MediaEncoding
- * PR616 Add Swagger documentation
- * PR619 Really slim down Docker container
- * PR621 Minor improvements to library scan code
- * PR622 Add unified build script and bump_version script
- * PR623 Replaced injections of ILogger with ILoggerFactory
- * PR625 Update taglib-sharp
- * PR626 Fix extra type name in parameter, add out keyword
- * PR627 Use string for ApplicationVersion
- * PR628 Update Product Name (User-Agent)
- * PR629 Fix subtitle converter misinterpreting 0 valued endTimeTicks
- * PR631 Cleanup ImageProcessor and SkiaEncoder
- * PR634 Replace our TVDB key with @drakus72's which is V1
- * PR636 Allow subtitle extraction and conversion in direct streaming
- * PR637 Remove unused font
- * PR638 Removed XmlTv testfiles and nuget install
- * PR646: Fix infinite loop bug on subtitle.m3u8 request
- * PR655: Support trying local branches in submodule
- * PR661: Fix NullRef from progress report
- * PR666: Add cross-platform build for arm64
- * jellyfin-web:
- * PR1: Change webcomponents to non-minified version
- * PR4: Fix user profile regression
- * PR6: Make icon into proper ico and large PNG
- * PR7: Fix firefox failing to set password for users with no password set
- * PR8: Remove premiere stuff and fix crashes caused by earlier removals
- * PR12: Fix return from PIN reset to index.html
- * PR13: Send android clients to select server before login
- * PR14: Reimplement page to add server
- * PR16: Fix spinning circle at the end of config wizard
- * PR17: Fix directorybrower not resetting scroll
- * PR19: Set union merge for CONTRIBUTORS.md
- * PR20: Show album thumbnail and artist image in page itemdetail
- * PR26: Make the card titles clickable
- * PR27: Stop pagination and adding a library from being able to trigger multiple times
- * PR28: Add transparent nav bar to BlueRadiance theme CSS
- * PR29: Clean up imageuploader
- * PR30: Remove iap and simplify registrationservices
- * PR36: Open videos in fullscreen on android devices
- * PR37: Remove broken features from web interface
- * PR38: Fix inconsistent UI coloring around settings drawer
- * PR39: Remove back button from dashboard and metadata manager
- * PR42: Fix Home backdrop not loading
- * PR43: Filter videos by audio stream language
- * PR44: Remove filter from library collection type options
- * PR45: Fix data-backbutton logic
- * PR46: Minor changes to navbar elements
- * PR48: Remove Sync code
- * PR52: Fix progress color
- * PR53: Fix user tabs color
- * PR54: Add back button to server dashboard
-
- -- Jellyfin Packaging Team <packaging@jellyfin.org> Sun, 20 Jan 2019 23:19:46 -0500
-
-jellyfin (10.0.2-1) unstable; urgency=medium
-
- * Hotfix release
- * jellyfin/jellyfin-web#23: Update Chromecast app ID [via direct commit]
- * #540: Update Emby API keys to our own
- * #541: Change ItemId to Guid in ProviderManager
- * #566: Avoid printing stacktrace when bind to port 1900 fails
-
- -- Joshua Boniface <joshua@boniface.me> Sat, 19 Jan 2019 01:19:59 -0500
-
-jellyfin (10.0.1-1) unstable; urgency=medium
-
- * Hotfix release, corrects several small bugs from 10.0.0
- * #512: Fix CONTRIBUTORS.md formatting
- * #501: Fix regression in integer divisions in latest movies category
- * #498: Change contributing link in settings to readthedocs.io
- * #493: Remove unused values.txt resource
- * #491: Fix userprofile.js crash
- * #519: Fix the DecodeJfif function to get proper image sizes
- * #486: Add NuGet package info to plugin projects
-
- -- Joshua Boniface <joshua@boniface.me> Tue, 08 Jan 2019 20:06:01 -0500
-
-jellyfin (10.0.0-1) unstable; urgency=medium
-
- * The first Jellyfin release under our new versioning scheme
- * Numerous bugfixes and code readability improvements
- * Updated logging configuration, including flag for it and configdir
- * Updated theming including logo
- * Dozens of other improvements as documented in GitHub pull request #419
-
- -- Joshua Boniface <joshua@boniface.me> Sat, 05 Jan 2019 15:39:25 -0500
-
-jellyfin (3.5.2-5) unstable; urgency=medium
-
- * Fully GPL'd release - remove tainted code from MediaBrowser.Common
- * Several code cleanups and tweaks
-
- -- Joshua Boniface <joshua@boniface.me> Fri, 28 Dec 2018 10:26:30 -0500
-
-jellyfin (3.5.2-4) unstable; urgency=medium
-
- * Correct manifest.json bug and vdpau
-
- -- Joshua Boniface <joshua@boniface.me> Thu, 20 Dec 2018 18:31:43 -0500
-
-jellyfin (3.5.2-3) unstable; urgency=medium
-
- * Correct several bugs in 3.5.2-2 packaging
-
- -- Joshua Boniface <joshua@boniface.me> Sat, 15 Dec 2018 18:17:32 -0500
-
-jellyfin (3.5.2-2) unstable; urgency=medium
-
- * Major code updates related to rebranding and cleanup
-
- -- Joshua Boniface <joshua@boniface.me> Fri, 14 Dec 2018 00:07:46 -0500
-
-jellyfin (3.5.2-1) unstable; urgency=medium
-
- * Add ffmpeg dependency and cleanup work
-
- -- Joshua Boniface <joshua@boniface.me> Tue, 11 Dec 2018 20:55:32 -0500
-
-jellyfin (3.5.2) unstable; urgency=medium
-
- * Rename from emby-server on version 3.5.2
-
- -- Joshua Boniface <joshua@boniface.me> Sun, 9 Dec 2018 15:20:58 -0400
diff --git a/deployment/debian-package-x64/pkg-src/conf/jellyfin b/deployment/debian-package-x64/pkg-src/conf/jellyfin
deleted file mode 100644
index b052b2ec6..000000000
--- a/deployment/debian-package-x64/pkg-src/conf/jellyfin
+++ /dev/null
@@ -1,41 +0,0 @@
-# Jellyfin default configuration options
-# This is a POSIX shell fragment
-
-# Use this file to override the default configurations; add additional
-# options with JELLYFIN_ADD_OPTS.
-
-# Under systemd, use
-# /etc/systemd/system/jellyfin.service.d/jellyfin.service.conf
-# to override the user or this config file's location.
-
-#
-# General options
-#
-
-# Program directories
-JELLYFIN_DATA_DIRECTORY="/var/lib/jellyfin"
-JELLYFIN_CONFIG_DIRECTORY="/etc/jellyfin"
-JELLYFIN_LOG_DIRECTORY="/var/log/jellyfin"
-JELLYFIN_CACHE_DIRECTORY="/var/cache/jellyfin"
-
-# Restart script for in-app server control
-JELLYFIN_RESTART_OPT="--restartpath=/usr/lib/jellyfin/restart.sh"
-
-# [OPTIONAL] ffmpeg binary paths, overriding the UI-configured values
-#JELLYFIN_FFMPEG_OPT="--ffmpeg=/usr/bin/ffmpeg"
-#JELLYFIN_FFPROBE_OPT="--ffprobe=/usr/bin/ffprobe"
-
-# [OPTIONAL] run Jellyfin as a headless service
-#JELLYFIN_SERVICE_OPT="--service"
-
-# [OPTIONAL] run Jellyfin without the web app
-#JELLYFIN_NOWEBAPP_OPT="--noautorunwebapp"
-
-#
-# SysV init/Upstart options
-#
-
-# Application username
-JELLYFIN_USER="jellyfin"
-# Full application command
-JELLYFIN_ARGS="--datadir=$JELLYFIN_DATA_DIRECTORY --configdir=$JELLYFIN_CONFIG_DIRECTORY --logdir=$JELLYFIN_LOG_DIRECTORY --cachedir=$JELLYFIN_CACHE_DIRECTORY $JELLYFIN_RESTART_OPT $JELLYFIN_FFMPEG_OPT $JELLYFIN_FFPROBE_OPT $JELLYFIN_SERVICE_OPT $JELLFIN_NOWEBAPP_OPT"
diff --git a/deployment/debian-package-x64/pkg-src/control b/deployment/debian-package-x64/pkg-src/control
deleted file mode 100644
index 88d10438b..000000000
--- a/deployment/debian-package-x64/pkg-src/control
+++ /dev/null
@@ -1,28 +0,0 @@
-Source: jellyfin
-Section: misc
-Priority: optional
-Maintainer: Jellyfin Team <team@jellyfin.org>
-Build-Depends: debhelper (>= 9),
- dotnet-sdk-2.2,
- libc6-dev,
- libcurl4-openssl-dev,
- libfontconfig1-dev,
- libfreetype6-dev
-Standards-Version: 3.9.4
-Homepage: https://jellyfin.media/
-Vcs-Git: https://github.org/jellyfin/jellyfin.git
-Vcs-Browser: https://github.org/jellyfin/jellyfin
-
-Package: jellyfin
-Replaces: mediabrowser, emby, emby-server-beta, jellyfin-dev, emby-server
-Breaks: mediabrowser, emby, emby-server-beta, jellyfin-dev, emby-server
-Conflicts: mediabrowser, emby, emby-server-beta, jellyfin-dev, emby-server
-Architecture: any
-Depends: at,
- libsqlite3-0,
- ffmpeg (<7:4.1) | jellyfin-ffmpeg,
- libfontconfig1,
- libfreetype6,
- libssl1.0.0 | libssl1.0.2
-Description: Jellyfin is a home media server.
- It is built on top of other popular open source technologies such as Service Stack, jQuery, jQuery mobile, and Mono. It features a REST-based api with built-in documentation to facilitate client development. We also have client libraries for our api to enable rapid development.
diff --git a/deployment/debian-package-x64/pkg-src/jellyfin.init b/deployment/debian-package-x64/pkg-src/jellyfin.init
deleted file mode 100644
index d103fb0f1..000000000
--- a/deployment/debian-package-x64/pkg-src/jellyfin.init
+++ /dev/null
@@ -1,49 +0,0 @@
-### BEGIN INIT INFO
-# Provides: Jellyfin Media Server
-# Required-Start: $local_fs $network
-# Required-Stop: $local_fs
-# Default-Start: 2 3 4 5
-# Default-Stop: 0 1 6
-# Short-Description: Jellyfin Media Server
-# Description: Runs Jellyfin Server
-### END INIT INFO
-
-# Carry out specific functions when asked to by the system
-
-pidfile="/var/run/jellyfin.pid"
-pid=`cat $pidfile`
-
-case "$1" in
- start)
- if [ "$pid" == "" ]; then
- echo "Starting Jellyfin..."
- . /etc/default/jellyfin
- nohup su -u $JELLYFIN_USER -c /usr/bin/jellyfin $JELLYFIN_ARGS
- echo ?? > $pidfile
- else
- echo "Jellyfin already running"
- fi
- ;;
- stop)
- if [ "$pid" != "" ]; then
- echo "Stopping Jellyfin..."
- kill $pid
- sleep 2
- rm -f $pidfile
- else
- echo "Jellyfin not running"
- fi
- ;;
- status)
- if [ "$pid" != "" ]; then
- echo "Jellyfin running as $pid"
- ps -f $pid
- else
- echo "Jellyfin is not running"
- fi
- ;;
- *)
- echo "Usage: $0 {start|stop}"
- exit 1
- ;;
-esac
diff --git a/deployment/debian-package-x64/pkg-src/jellyfin.service b/deployment/debian-package-x64/pkg-src/jellyfin.service
deleted file mode 100644
index 9c6c6667f..000000000
--- a/deployment/debian-package-x64/pkg-src/jellyfin.service
+++ /dev/null
@@ -1,14 +0,0 @@
-[Unit]
-Description = Jellyfin Media Server
-After = network.target
-
-[Service]
-Type = simple
-EnvironmentFile = /etc/default/jellyfin
-User = jellyfin
-ExecStart = /usr/bin/jellyfin --datadir=${JELLYFIN_DATA_DIRECTORY} --configdir=${JELLYFIN_CONFIG_DIRECTORY} --logdir=${JELLYFIN_LOG_DIRECTORY} --cachedir=${JELLYFIN_CACHE_DIRECTORY} ${JELLYFIN_RESTART_OPT} ${JELLYFIN_FFMPEG_OPT} ${JELLYFIN_FFPROBE_OPT} ${JELLYFIN_SERVICE_OPT} ${JELLYFIN_NOWEBAPP_OPT}
-Restart = on-failure
-TimeoutSec = 15
-
-[Install]
-WantedBy = multi-user.target
diff --git a/deployment/debian-package-x64/pkg-src/rules b/deployment/debian-package-x64/pkg-src/rules
deleted file mode 100644
index ce98cb8f8..000000000
--- a/deployment/debian-package-x64/pkg-src/rules
+++ /dev/null
@@ -1,23 +0,0 @@
-#! /usr/bin/make -f
-CONFIG := Release
-TERM := xterm
-SHELL := /bin/bash
-DOTNETRUNTIME := debian-x64
-export DH_VERBOSE=1
-export DOTNET_CLI_TELEMETRY_OPTOUT=1
-
-%:
- dh $@
-
-# disable "make check"
-override_dh_auto_test:
-
-# disable stripping debugging symbols
-override_dh_clistrip:
-
-override_dh_auto_build:
- dotnet publish --configuration $(CONFIG) --output='$(CURDIR)/usr/lib/jellyfin/bin' --self-contained --runtime $(DOTNETRUNTIME) Jellyfin.Server
-
-override_dh_auto_clean:
- dotnet clean -maxcpucount:1 --configuration $(CONFIG) Jellyfin.Server || true
- rm -rf '$(CURDIR)/usr'
diff --git a/deployment/docker/build.sh b/deployment/docker/build.sh
deleted file mode 100755
index 444208c85..000000000
--- a/deployment/docker/build.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-build_jellyfin_docker ../.. ../../Dockerfile jellyfin:amd64-${VERSION}
-
-build_jellyfin_docker ../.. ../../Dockerfile.arm jellyfin:arm-${VERSION}
-
-#build_jellyfin_docker ../.. ../../Dockerfile.arm64v8 jellyfin:arm64v8-${VERSION}
-#build_jellyfin_docker ../.. ../../Dockerfile.arm32v7 jellyfin:arm32v7-${VERSION}
diff --git a/deployment/docker/dependencies.txt b/deployment/docker/dependencies.txt
deleted file mode 100644
index bdb967096..000000000
--- a/deployment/docker/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-docker
diff --git a/deployment/docker/package.sh b/deployment/docker/package.sh
deleted file mode 100755
index d74426e2f..000000000
--- a/deployment/docker/package.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-docker manifest create jellyfin:${VERSION} jellyfin:amd64-${VERSION} jellyfin:arm32v7-${VERSION} jellyfin:arm64v8-${VERSION}
-docker manifest annotate jellyfin:amd64-${VERSION} --os linux --arch amd64
-#docker manifest annotate jellyfin:arm32v7-${VERSION} --os linux --arch arm --variant armv7
-#docker manifest annotate jellyfin:arm64v8-${VERSION} --os linux --arch arm64 --variant armv8
-
-#TODO publish.sh - docker manifest push jellyfin:${VERSION}
diff --git a/deployment/fedora-package-x64/Dockerfile b/deployment/fedora-package-x64/Dockerfile
deleted file mode 100644
index 8bb1d527d..000000000
--- a/deployment/fedora-package-x64/Dockerfile
+++ /dev/null
@@ -1,27 +0,0 @@
-FROM fedora:29
-# Docker build arguments
-ARG SOURCE_DIR=/jellyfin
-ARG PLATFORM_DIR=/jellyfin/deployment/fedora-package-x64
-ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=2.2
-# Docker run environment
-ENV SOURCE_DIR=/jellyfin
-ENV ARTIFACT_DIR=/dist
-
-# Prepare Fedora build environment
-RUN dnf update -y \
- && dnf install -y @buildsys-build rpmdevtools dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel \
- && dnf copr enable -y @dotnet-sig/dotnet \
- && rpmdev-setuptree \
- && dnf install -y dotnet-sdk-${SDK_VERSION} \
- && ln -sf ${PLATFORM_DIR}/docker-build.sh /docker-build.sh \
- && mkdir -p ${SOURCE_DIR}/SPECS \
- && ln -s ${PLATFORM_DIR}/pkg-src/jellyfin.spec ${SOURCE_DIR}/SPECS/jellyfin.spec \
- && mkdir -p ${SOURCE_DIR}/SOURCES \
- && ln -s ${PLATFORM_DIR}/pkg-src ${SOURCE_DIR}/SOURCES
-
-VOLUME ${ARTIFACT_DIR}/
-
-COPY . ${SOURCE_DIR}/
-
-ENTRYPOINT ["/docker-build.sh"]
diff --git a/deployment/fedora-package-x64/clean.sh b/deployment/fedora-package-x64/clean.sh
deleted file mode 100755
index 408167e49..000000000
--- a/deployment/fedora-package-x64/clean.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-keep_artifacts="${1}"
-
-WORKDIR="$( pwd )"
-VERSION="$( grep -A1 '^Version:' ${WORKDIR}/pkg-src/jellyfin.spec | awk '{ print $NF }' )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-package_source_dir="${WORKDIR}/pkg-src"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-fedora-build"
-
-rm -f "${package_source_dir}/jellyfin-${VERSION}.tar.gz" &>/dev/null \
- || sudo rm -f "${package_source_dir}/jellyfin-${VERSION}.tar.gz" &>/dev/null
-
-rm -rf "${package_temporary_dir}" &>/dev/null \
- || sudo rm -rf "${package_temporary_dir}" &>/dev/null
-
-rm -rf "${output_dir}" &>/dev/null \
- || sudo rm -rf "${output_dir}" &>/dev/null
-
-if [[ ${keep_artifacts} == 'n' ]]; then
- docker_sudo=""
- if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo=sudo
- fi
- ${docker_sudo} docker image rm ${image_name} --force
-fi
diff --git a/deployment/fedora-package-x64/create_tarball.sh b/deployment/fedora-package-x64/create_tarball.sh
deleted file mode 100755
index e8301c989..000000000
--- a/deployment/fedora-package-x64/create_tarball.sh
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env bash
-
-# shellcheck disable=SC1091
-source ../common.build.sh
-
-WORKDIR="$( pwd )"
-VERSION="$( sed -ne '/^Version:/s/.* *//p' "${WORKDIR}"/pkg-src/jellyfin.spec )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-pkg_src_dir="${WORKDIR}/pkg-src"
-
-GNU_TAR=1
-echo "Bundling all sources for RPM build."
-tar \
---transform "s,^\.,jellyfin-${VERSION}," \
---exclude='.git*' \
---exclude='**/.git' \
---exclude='**/.hg' \
---exclude='**/.vs' \
---exclude='**/.vscode' \
---exclude='deployment' \
---exclude='**/bin' \
---exclude='**/obj' \
---exclude='**/.nuget' \
---exclude='*.deb' \
---exclude='*.rpm' \
--czf "$pkg_src_dir/jellyfin-${VERSION}.tar.gz" \
--C "../.." ./ || GNU_TAR=0
-
-if [ $GNU_TAR -eq 0 ]; then
- echo "The installed tar binary did not support --transform. Using workaround."
- mkdir -p "${package_temporary_dir}/jellyfin"{,-"${VERSION}"}
- # Not GNU tar
- tar \
- --exclude='.git*' \
- --exclude='**/.git' \
- --exclude='**/.hg' \
- --exclude='**/.vs' \
- --exclude='**/.vscode' \
- --exclude='deployment' \
- --exclude='**/bin' \
- --exclude='**/obj' \
- --exclude='**/.nuget' \
- --exclude='*.deb' \
- --exclude='*.rpm' \
- -zcf \
- "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz" \
- -C "../.." ./
- echo "Extracting filtered package."
- tar -xzf "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz" -C "${package_temporary_dir}/jellyfin-${VERSION}"
- echo "Removing filtered package."
- rm -f "${package_temporary_dir}/jellyfin/jellyfin-${VERSION}.tar.gz"
- echo "Repackaging package into final tarball."
- tar -czf "${pkg_src_dir}/jellyfin-${VERSION}.tar.gz" -C "${package_temporary_dir}" "jellyfin-${VERSION}"
-fi
diff --git a/deployment/fedora-package-x64/dependencies.txt b/deployment/fedora-package-x64/dependencies.txt
deleted file mode 100644
index bdb967096..000000000
--- a/deployment/fedora-package-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-docker
diff --git a/deployment/fedora-package-x64/docker-build.sh b/deployment/fedora-package-x64/docker-build.sh
deleted file mode 100755
index 3acf1ec0d..000000000
--- a/deployment/fedora-package-x64/docker-build.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-# Builds the RPM inside the Docker container
-
-set -o errexit
-set -o xtrace
-
-# Move to source directory
-pushd ${SOURCE_DIR}
-
-ls -al SOURCES/pkg-src/
-
-# Build RPM
-spectool -g -R SPECS/jellyfin.spec
-rpmbuild -bs SPECS/jellyfin.spec --define "_sourcedir ${SOURCE_DIR}/SOURCES/pkg-src/"
-rpmbuild -bb SPECS/jellyfin.spec --define "_sourcedir ${SOURCE_DIR}/SOURCES/pkg-src/"
-
-# Move the artifacts out
-mkdir -p ${ARTIFACT_DIR}/rpm
-mv /root/rpmbuild/RPMS/x86_64/jellyfin-*.rpm /root/rpmbuild/SRPMS/jellyfin-*.src.rpm ${ARTIFACT_DIR}/rpm/
diff --git a/deployment/fedora-package-x64/package.sh b/deployment/fedora-package-x64/package.sh
deleted file mode 100755
index eed29aef3..000000000
--- a/deployment/fedora-package-x64/package.sh
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-WORKDIR="$( pwd )"
-VERSION="$( grep '^Version:' ${WORKDIR}/pkg-src/jellyfin.spec | awk '{ print $NF }' )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-pkg_src_dir="${WORKDIR}/pkg-src"
-current_user="$( whoami )"
-image_name="jellyfin-fedora-build"
-
-# Determine if sudo should be used for Docker
-if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo="sudo"
-else
- docker_sudo=""
-fi
-
-./create_tarball.sh
-
-# Set up the build environment Docker image
-${docker_sudo} docker build ../.. -t "${image_name}" -f ./Dockerfile
-# Build the RPMs and copy out to ${package_temporary_dir}
-${docker_sudo} docker run --rm -v "${package_temporary_dir}:/dist" "${image_name}"
-# Correct ownership on the RPMs (as current user, then as root if that fails)
-chown -R "${current_user}" "${package_temporary_dir}" \
- || sudo chown -R "${current_user}" "${package_temporary_dir}"
-# Move the RPMs to the output directory
-mkdir -p "${output_dir}"
-mv "${package_temporary_dir}"/rpm/* "${output_dir}"
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin.service b/deployment/fedora-package-x64/pkg-src/jellyfin.service
deleted file mode 100644
index d58df9d94..000000000
--- a/deployment/fedora-package-x64/pkg-src/jellyfin.service
+++ /dev/null
@@ -1,15 +0,0 @@
-[Unit]
-After=network.target
-Description=Jellyfin is a free software media system that puts you in control of managing and streaming your media.
-
-[Service]
-EnvironmentFile=/etc/sysconfig/jellyfin
-WorkingDirectory=/var/lib/jellyfin
-ExecStart=/usr/bin/jellyfin --datadir=${JELLYFIN_DATA_DIRECTORY} --configdir=${JELLYFIN_CONFIG_DIRECTORY} --logdir=${JELLYFIN_LOG_DIRECTORY} --cachedir=${JELLYFIN_CACHE_DIRECTORY} ${JELLYFIN_RESTART_OPT} ${JELLYFIN_FFMPEG_OPT} ${JELLYFIN_FFPROBE_OPT} ${JELLYFIN_SERVICE_OPT} ${JELLYFIN_NOWEBAPP_OPT}
-TimeoutSec=15
-Restart=on-failure
-User=jellyfin
-Group=jellyfin
-
-[Install]
-WantedBy=multi-user.target
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin.spec b/deployment/fedora-package-x64/pkg-src/jellyfin.spec
deleted file mode 100644
index 146486428..000000000
--- a/deployment/fedora-package-x64/pkg-src/jellyfin.spec
+++ /dev/null
@@ -1,339 +0,0 @@
-%global debug_package %{nil}
-# Set the dotnet runtime
-%if 0%{?fedora}
-%global dotnet_runtime fedora-x64
-%else
-%global dotnet_runtime centos-x64
-%endif
-
-Name: jellyfin
-Version: 10.2.1
-Release: 1%{?dist}
-Summary: The Free Software Media Browser
-License: GPLv2
-URL: https://jellyfin.media
-Source0: %{name}-%{version}.tar.gz
-Source1: jellyfin.service
-Source2: jellyfin.env
-Source3: jellyfin.sudoers
-Source4: restart.sh
-Source5: jellyfin.override.conf
-Source6: jellyfin-firewalld.xml
-
-%{?systemd_requires}
-BuildRequires: systemd
-Requires(pre): shadow-utils
-BuildRequires: libcurl-devel, fontconfig-devel, freetype-devel, openssl-devel, glibc-devel, libicu-devel
-Requires: libcurl, fontconfig, freetype, openssl, glibc libicu
-# Requirements not packaged in main repos
-# COPR @dotnet-sig/dotnet
-BuildRequires: dotnet-sdk-2.2
-# RPMfusion free
-Requires: ffmpeg
-
-# Fedora has openssl1.1 which is incompatible with dotnet
-%{?fedora:Requires: compat-openssl10}
-
-# Disable Automatic Dependency Processing
-AutoReqProv: no
-
-%description
-Jellyfin is a free software media system that puts you in control of managing and streaming your media.
-
-
-%prep
-%autosetup -n %{name}-%{version}
-
-%build
-
-%install
-export DOTNET_CLI_TELEMETRY_OPTOUT=1
-export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
-dotnet publish --configuration Release --output='%{buildroot}%{_libdir}/jellyfin' --self-contained --runtime %{dotnet_runtime} Jellyfin.Server
-%{__install} -D -m 0644 LICENSE %{buildroot}%{_datadir}/licenses/%{name}/LICENSE
-%{__install} -D -m 0644 %{SOURCE5} %{buildroot}%{_sysconfdir}/systemd/system/%{name}.service.d/override.conf
-%{__install} -D -m 0644 Jellyfin.Server/Resources/Configuration/logging.json %{buildroot}%{_sysconfdir}/%{name}/logging.json
-%{__mkdir} -p %{buildroot}%{_bindir}
-tee %{buildroot}%{_bindir}/jellyfin << EOF
-#!/bin/sh
-exec %{_libdir}/%{name}/%{name} \${@}
-EOF
-%{__mkdir} -p %{buildroot}%{_sharedstatedir}/jellyfin
-%{__mkdir} -p %{buildroot}%{_sysconfdir}/%{name}
-%{__mkdir} -p %{buildroot}%{_var}/log/jellyfin
-%{__mkdir} -p %{buildroot}%{_var}/cache/jellyfin
-
-%{__install} -D -m 0644 %{SOURCE1} %{buildroot}%{_unitdir}/%{name}.service
-%{__install} -D -m 0644 %{SOURCE2} %{buildroot}%{_sysconfdir}/sysconfig/%{name}
-%{__install} -D -m 0600 %{SOURCE3} %{buildroot}%{_sysconfdir}/sudoers.d/%{name}-sudoers
-%{__install} -D -m 0755 %{SOURCE4} %{buildroot}%{_libexecdir}/%{name}/restart.sh
-%{__install} -D -m 0644 %{SOURCE6} %{buildroot}%{_prefix}/lib/firewalld/service/%{name}.xml
-
-%files
-%{_libdir}/%{name}/jellyfin-web/*
-%attr(755,root,root) %{_bindir}/%{name}
-%{_libdir}/%{name}/*.json
-%{_libdir}/%{name}/*.pdb
-%{_libdir}/%{name}/*.dll
-%{_libdir}/%{name}/*.so
-%{_libdir}/%{name}/*.a
-%{_libdir}/%{name}/createdump
-# Needs 755 else only root can run it since binary build by dotnet is 722
-%attr(755,root,root) %{_libdir}/%{name}/jellyfin
-%{_libdir}/%{name}/sosdocsunix.txt
-%{_unitdir}/%{name}.service
-%{_libexecdir}/%{name}/restart.sh
-%{_prefix}/lib/firewalld/service/%{name}.xml
-%attr(755,jellyfin,jellyfin) %dir %{_sysconfdir}/%{name}
-%config %{_sysconfdir}/sysconfig/%{name}
-%config(noreplace) %attr(600,root,root) %{_sysconfdir}/sudoers.d/%{name}-sudoers
-%config(noreplace) %{_sysconfdir}/systemd/system/%{name}.service.d/override.conf
-%config(noreplace) %attr(644,jellyfin,jellyfin) %{_sysconfdir}/%{name}/logging.json
-%attr(750,jellyfin,jellyfin) %dir %{_sharedstatedir}/jellyfin
-%attr(-,jellyfin,jellyfin) %dir %{_var}/log/jellyfin
-%attr(750,jellyfin,jellyfin) %dir %{_var}/cache/jellyfin
-%if 0%{?fedora}
-%license LICENSE
-%else
-%{_datadir}/licenses/%{name}/LICENSE
-%endif
-
-%pre
-getent group jellyfin >/dev/null || groupadd -r jellyfin
-getent passwd jellyfin >/dev/null || \
- useradd -r -g jellyfin -d %{_sharedstatedir}/jellyfin -s /sbin/nologin \
- -c "Jellyfin default user" jellyfin
-exit 0
-
-%post
-# Move existing configuration cache and logs to their new locations and symlink them.
-if [ $1 -gt 1 ] ; then
- service_state=$(systemctl is-active jellyfin.service)
- if [ "${service_state}" = "active" ]; then
- systemctl stop jellyfin.service
- fi
- if [ ! -L %{_sharedstatedir}/%{name}/config ]; then
- mv %{_sharedstatedir}/%{name}/config/* %{_sysconfdir}/%{name}/
- rmdir %{_sharedstatedir}/%{name}/config
- ln -sf %{_sysconfdir}/%{name} %{_sharedstatedir}/%{name}/config
- fi
- if [ ! -L %{_sharedstatedir}/%{name}/logs ]; then
- mv %{_sharedstatedir}/%{name}/logs/* %{_var}/log/jellyfin
- rmdir %{_sharedstatedir}/%{name}/logs
- ln -sf %{_var}/log/jellyfin %{_sharedstatedir}/%{name}/logs
- fi
- if [ ! -L %{_sharedstatedir}/%{name}/cache ]; then
- mv %{_sharedstatedir}/%{name}/cache/* %{_var}/cache/jellyfin
- rmdir %{_sharedstatedir}/%{name}/cache
- ln -sf %{_var}/cache/jellyfin %{_sharedstatedir}/%{name}/cache
- fi
- if [ "${service_state}" = "active" ]; then
- systemctl start jellyfin.service
- fi
-fi
-%systemd_post jellyfin.service
-
-%preun
-%systemd_preun jellyfin.service
-
-%postun
-%systemd_postun_with_restart jellyfin.service
-
-%changelog
-* Wed Feb 20 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
-- jellyfin:
-- PR920 Fix cachedir missing from Docker container
-- PR924 Use the movie name instead of folder name
-- PR933 Semi-revert to prefer old movie grouping behaviour
-- PR948 Revert movie matching (supercedes PR933, PR924, PR739)
-- PR960 Use jellyfin/ffmpeg image
-- jellyfin-web:
-- PR136 Re-add OpenSubtitles configuration page
-- PR137 Replace HeaderEmbyServer with HeaderJellyfinServer on plugincatalog
-- PR138 Remove left-over JS for Customize Home Screen
-- PR141 Exit fullscreen automatically after video playback ends
-* Fri Feb 15 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
-- jellyfin:
-- PR452 Use EF Core for Activity database
-- PR535 Clean up streambuilder
-- PR655 Support trying local branches in submodule
-- PR656 Do some logging in MediaInfoService
-- PR657 Remove conditions that are always true/false
-- PR661 Fix NullRef from progress report
-- PR663 Use TagLibSharp Nuget package
-- PR664 Revert "Fix segment_time_delta for ffmpeg 4.1"
-- PR666 Add cross-platform build for arm64
-- PR668 Return Audio objects from MusicAlbum.Tracks
-- PR671 Set EnableRaisingEvents correctly
-- PR672 Remove unconditional caching, modified since header and use ETags
-- PR677 Fix arm32 Docker
-- PR681 Fix Windows build script errors + pin ffmpeg to 4.0
-- PR686 Disable some StyleCop warnings
-- PR687 Fix some analyzer warnings
-- PR689 Fix RPM package build for fedora
-- PR702 Fix debug build on windows
-- PR706 Make another docker layer reusable
-- PR709 Fix always null expressions
-- PR710 Fix a spelling mistake
-- PR711 Remove remnants of system events
-- PR713 Fix empty statement in DidlBuilder.cs
-- PR716 Remove more compile time warnings
-- PR721 Change image dimentions from double to int
-- PR723 Minor improvements to db code
-- PR724 Move Skia back into it's own project
-- PR726 Clean up IFileSystem wrappers around stdlib.
-- PR727 Change default aspect ratio to 2/3 from 0
-- PR728 Use ffmpeg from jrottenberg/ffmpeg
-- PR732 Reworked LocalizationManager to load data async
-- PR733 Remove unused function
-- PR734 Fix more analyzer warnings
-- PR736 Start startup tasks async
-- PR737 Add AssemblyInfo for Jellyfin.Drawing.Skia
-- PR739 Change multi version logic for movies
-- PR740 Remove code for pre-installed plugins & properly check if file exists
-- PR756 Make cache dir configurable
-- PR757 Fix default aspect ratio
-- PR758 Add password field to initial setup
-- PR764 Remove dead code, made some functions properly async
-- PR769 Fix conditions where the ! was swallowed in #726
-- PR774 reimplement support for plugin repository
-- PR782 Remove commented file MediaBrowser.LocalMetadata.Savers.PersonXmlSaver
-- PR783 Update builds to use #749 and #756
-- PR788 Fix more warnings
-- PR794 Remove MoreLINQ
-- PR797 Fix all warnings
-- PR798 Cleanup around the api endpoints
-- PR800 Add CentOS and update rpm spec for the cachedir option
-- PR802 Fix build error
-- PR804 Handle new option parser properly
-- PR805 Add weblate translation status to README
-- PR807 Fix restart script in OS packages
-- PR810 Fix loading of rating files
-- PR812 Fix up the explicit docs links in the README
-- PR819 Some small changes in Device.cs and DidlBuilder.cs
-- PR822 Complete rename ImageSize -> ImageDimensions
-- PR824 Improved Docker pkgbuild
-- PR831 Move some arrays to generics
-- PR833 Add await to GetCountries in LocalizationService
-- PR834 Add donation badge and reorganize badges
-- PR838 Quick style fix
-- PR840 Fix more warnings
-- PR841 Fix OC badge to all and add forum badge
-- PR842 Use VAAPI-enabled ffmpeg
-- PR852 Use SQLitePCL.pretty.netstandard on NuGet
-- PR853 Fix poor handling of cache directories
-- PR864 Add support for ZIP plugin archives
-- PR868 Fix audio streaming via BaseProgressiveStreamingService
-- PR869 Remove DLL support and require all packages/plugins to be zip archives
-- PR872 Fix potential NullReferenceException
-- PR899: DLNA: Fix race condition leading to missing device names
-- PR890 Drop ETag and use Last-Modified header
-- PR892: Add jellyfin-ffmpeg and versioning to package deps
-- PR901: Properly dispose HttpWebResponse when the request failed to avoid 'too many open files'
-- PR909: Fix docker arm builds
-- PR910: Enhance Dockerfiles
-- PR911: Checkout submodules in Docker Hub hook
-- jellyfin-web:
-- PR51 remove more code for sync and camera roll
-- PR56 Use English for fallback translations and clean up language files
-- PR58 Css slider fixes
-- PR62 remove BOM markers
-- PR65 Fix profile image not being shown on profile page
-- PR73 Dev sync
-- PR74 Add download menu option to media items
-- PR75 User profile fixes
-- PR76 Fix syntax error caused by deminification
-- PR79 Remove unused Connect related from the frontend
-- PR80 Remove games
-- PR92 Added frontend support for a password field on setup
-- PR94 Update british strings
-- PR95 add display language option back
-- PR112 Removed seasonal theme support
-- PR116 Consolidate all strings into a single file per language
-- PR117 Fix volume slider behavior
-- PR118 Enable and fix PiP for Safari
-- PR119 Make the toggle track visible on all themes
-- PR121 Fix syntax error in site.js
-- PR127 Change sharedcomponents module to core
-- PR135 Make sure fallback culture is always available
-* Sun Jan 20 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
-- jellyfin:
-- PR335 Build scripts and build system consolidation.
-- PR424 add jellyfin-web as submodule
-- PR455 Cleanup some small things
-- PR458 Clean up several minor issues and add TODOs
-- PR506 Removing tabs and trailing whitespace
-- PR508 Update internal versioning and user agents.
-- PR516 Remove useless properties from IEnvironmentInfo
-- PR520 Fix potential bug where aspect ratio would be incorrectly calculated
-- PR534 Add linux-arm and linux-arm64 native NuGet dependency.
-- PR540 Update Emby API keys to our own
-- PR541 Change ItemId to Guid in ProviderManager
-- PR556 Fix "Password Reset by PIN" page
-- PR562 Fix error with uppercase photo extension and fix typo in a log line
-- PR563 Update dev from master
-- PR566 Avoid printing stacktrace when bind to port 1900 fails
-- PR567 Shutdown gracefully when recieving a termination signal
-- PR571 Add more NuGet metadata properties
-- PR575 Reformat all C# server code to conform with code standards
-- PR576 Add code analysers for debug builds
-- PR580 Fix Docker build
-- PR582 Replace custom image parser with Skia
-- PR587 Add nuget info to Emby.Naming
-- PR589 Ensure config and log folders exist
-- PR596 Fix indentation for xml files
-- PR598 Remove MediaBrowser.Text for license violations and hackiness
-- PR606 Slim down docker image
-- PR613 Update MediaEncoding
-- PR616 Add Swagger documentation
-- PR619 Really slim down Docker container
-- PR621 Minor improvements to library scan code
-- PR622 Add unified build script and bump_version script
-- PR623 Replaced injections of ILogger with ILoggerFactory
-- PR625 Update taglib-sharp
-- PR626 Fix extra type name in parameter, add out keyword
-- PR627 Use string for ApplicationVersion
-- PR628 Update Product Name (User-Agent)
-- PR629 Fix subtitle converter misinterpreting 0 valued endTimeTicks
-- PR631 Cleanup ImageProcessor and SkiaEncoder
-- PR634 Replace our TVDB key with @drakus72's which is V1
-- PR636 Allow subtitle extraction and conversion in direct streaming
-- PR637 Remove unused font
-- PR638 Removed XmlTv testfiles and nuget install
-- PR646: Fix infinite loop bug on subtitle.m3u8 request
-- PR655: Support trying local branches in submodule
-- PR661: Fix NullRef from progress report
-- PR666: Add cross-platform build for arm64
-- jellyfin-web:
-- PR1: Change webcomponents to non-minified version
-- PR4: Fix user profile regression
-- PR6: Make icon into proper ico and large PNG
-- PR7: Fix firefox failing to set password for users with no password set
-- PR8: Remove premiere stuff and fix crashes caused by earlier removals
-- PR12: Fix return from PIN reset to index.html
-- PR13: Send android clients to select server before login
-- PR14: Reimplement page to add server
-- PR16: Fix spinning circle at the end of config wizard
-- PR17: Fix directorybrower not resetting scroll
-- PR19: Set union merge for CONTRIBUTORS.md
-- PR20: Show album thumbnail and artist image in page itemdetail
-- PR26: Make the card titles clickable
-- PR27: Stop pagination and adding a library from being able to trigger multiple times
-- PR28: Add transparent nav bar to BlueRadiance theme CSS
-- PR29: Clean up imageuploader
-- PR30: Remove iap and simplify registrationservices
-- PR36: Open videos in fullscreen on android devices
-- PR37: Remove broken features from web interface
-- PR38: Fix inconsistent UI coloring around settings drawer
-- PR39: Remove back button from dashboard and metadata manager
-- PR42: Fix Home backdrop not loading
-- PR43: Filter videos by audio stream language
-- PR44: Remove filter from library collection type options
-- PR45: Fix data-backbutton logic
-- PR46: Minor changes to navbar elements
-- PR48: Remove Sync code
-- PR52: Fix progress color
-- PR53: Fix user tabs color
-- PR54: Add back button to server dashboard
-* Fri Jan 11 2019 Thomas Büttner <thomas@vergesslicher.tech> - 10.0.2-1
-- TODO Changelog for 10.0.2
diff --git a/deployment/fedora-package-x64/pkg-src/restart.sh b/deployment/fedora-package-x64/pkg-src/restart.sh
deleted file mode 100644
index e84dca587..000000000
--- a/deployment/fedora-package-x64/pkg-src/restart.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/sh
-
-NAME=jellyfin
-restart_cmd="/usr/bin/systemctl restart ${NAME}"
-echo "sleep 2; sudo $restart_cmd > /dev/null 2>&1" | at now > /dev/null 2>&1
-exit 0 \ No newline at end of file
diff --git a/deployment/linux-x64/build.sh b/deployment/linux-x64/build.sh
deleted file mode 100755
index 1f0fb62d3..000000000
--- a/deployment/linux-x64/build.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-build_jellyfin ../../Jellyfin.Server Release linux-x64 `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/linux-x64/clean.sh b/deployment/linux-x64/clean.sh
deleted file mode 100755
index 3df2d7796..000000000
--- a/deployment/linux-x64/clean.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-clean_jellyfin ../.. Release `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/linux-x64/dependencies.txt b/deployment/linux-x64/dependencies.txt
deleted file mode 100644
index 3d25d1bdf..000000000
--- a/deployment/linux-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-dotnet
diff --git a/deployment/linux-x64/package.sh b/deployment/linux-x64/package.sh
deleted file mode 100755
index 13b943ea8..000000000
--- a/deployment/linux-x64/package.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-package_portable ../.. `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/macos/build.sh b/deployment/macos/build.sh
deleted file mode 100755
index d6bfb9f5e..000000000
--- a/deployment/macos/build.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-build_jellyfin ../../Jellyfin.Server Release osx-x64 `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/macos/clean.sh b/deployment/macos/clean.sh
deleted file mode 100755
index 3df2d7796..000000000
--- a/deployment/macos/clean.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-clean_jellyfin ../.. Release `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/macos/dependencies.txt b/deployment/macos/dependencies.txt
deleted file mode 100644
index 3d25d1bdf..000000000
--- a/deployment/macos/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-dotnet
diff --git a/deployment/macos/package.sh b/deployment/macos/package.sh
deleted file mode 100755
index 13b943ea8..000000000
--- a/deployment/macos/package.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-package_portable ../.. `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/portable/build.sh b/deployment/portable/build.sh
deleted file mode 100755
index 4f2e6363e..000000000
--- a/deployment/portable/build.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-#Magic word framework will create a non self contained build
-build_jellyfin ../../Jellyfin.Server Release framework `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/portable/clean.sh b/deployment/portable/clean.sh
deleted file mode 100755
index 3df2d7796..000000000
--- a/deployment/portable/clean.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-clean_jellyfin ../.. Release `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/portable/package.sh b/deployment/portable/package.sh
deleted file mode 100755
index 13b943ea8..000000000
--- a/deployment/portable/package.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-package_portable ../.. `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/ubuntu-package-x64/Dockerfile b/deployment/ubuntu-package-x64/Dockerfile
deleted file mode 100644
index 485b6c42c..000000000
--- a/deployment/ubuntu-package-x64/Dockerfile
+++ /dev/null
@@ -1,21 +0,0 @@
-FROM microsoft/dotnet:2.2-sdk-bionic
-# Docker build arguments
-ARG SOURCE_DIR=/jellyfin
-ARG PLATFORM_DIR=/jellyfin/deployment/ubuntu-package-x64
-ARG ARTIFACT_DIR=/dist
-# Docker run environment
-ENV SOURCE_DIR=/jellyfin
-ENV ARTIFACT_DIR=/dist
-ENV DEB_BUILD_OPTIONS=noddebs
-
-# Prepare Ubuntu build environment
-RUN apt-get update \
- && apt-get install -y apt-transport-https debhelper gnupg wget devscripts mmv libc6-dev libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev \
- && ln -sf ${PLATFORM_DIR}/docker-build.sh /docker-build.sh \
- && mkdir -p ${SOURCE_DIR} && ln -sf ${PLATFORM_DIR}/pkg-src ${SOURCE_DIR}/debian
-
-VOLUME ${ARTIFACT_DIR}/
-
-COPY . ${SOURCE_DIR}/
-
-ENTRYPOINT ["/docker-build.sh"]
diff --git a/deployment/ubuntu-package-x64/clean.sh b/deployment/ubuntu-package-x64/clean.sh
deleted file mode 100755
index c92c7fdec..000000000
--- a/deployment/ubuntu-package-x64/clean.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-keep_artifacts="${1}"
-
-WORKDIR="$( pwd )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-ubuntu-build"
-
-rm -rf "${package_temporary_dir}" &>/dev/null \
- || sudo rm -rf "${package_temporary_dir}" &>/dev/null
-
-rm -rf "${output_dir}" &>/dev/null \
- || sudo rm -rf "${output_dir}" &>/dev/null
-
-if [[ ${keep_artifacts} == 'n' ]]; then
- docker_sudo=""
- if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo=sudo
- fi
- ${docker_sudo} docker image rm ${image_name} --force
-fi
diff --git a/deployment/ubuntu-package-x64/dependencies.txt b/deployment/ubuntu-package-x64/dependencies.txt
deleted file mode 100644
index bdb967096..000000000
--- a/deployment/ubuntu-package-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-docker
diff --git a/deployment/ubuntu-package-x64/docker-build.sh b/deployment/ubuntu-package-x64/docker-build.sh
deleted file mode 100755
index 0590be097..000000000
--- a/deployment/ubuntu-package-x64/docker-build.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/bash
-
-# Builds the DEB inside the Docker container
-
-set -o errexit
-set -o xtrace
-
-# Move to source directory
-pushd ${SOURCE_DIR}
-
-# Remove build-dep for dotnet-sdk-2.2, since it's not a package in this image
-sed -i '/dotnet-sdk-2.2,/d' debian/control
-
-# Build DEB
-dpkg-buildpackage -us -uc
-
-# Move the artifacts out
-mkdir -p ${ARTIFACT_DIR}/deb
-mv /jellyfin_* ${ARTIFACT_DIR}/deb/
diff --git a/deployment/ubuntu-package-x64/package.sh b/deployment/ubuntu-package-x64/package.sh
deleted file mode 100755
index 6d4625a19..000000000
--- a/deployment/ubuntu-package-x64/package.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-WORKDIR="$( pwd )"
-
-package_temporary_dir="${WORKDIR}/pkg-dist-tmp"
-output_dir="${WORKDIR}/pkg-dist"
-current_user="$( whoami )"
-image_name="jellyfin-ubuntu-build"
-
-# Determine if sudo should be used for Docker
-if [[ ! -z $(id -Gn | grep -q 'docker') ]] \
- && [[ ! ${EUID:-1000} -eq 0 ]] \
- && [[ ! ${USER} == "root" ]] \
- && [[ ! -z $( echo "${OSTYPE}" | grep -q "darwin" ) ]]; then
- docker_sudo="sudo"
-else
- docker_sudo=""
-fi
-
-# Set up the build environment Docker image
-${docker_sudo} docker build ../.. -t "${image_name}" -f ./Dockerfile
-# Build the DEBs and copy out to ${package_temporary_dir}
-${docker_sudo} docker run --rm -v "${package_temporary_dir}:/dist" "${image_name}"
-# Correct ownership on the DEBs (as current user, then as root if that fails)
-chown -R "${current_user}" "${package_temporary_dir}" &>/dev/null \
- || sudo chown -R "${current_user}" "${package_temporary_dir}" &>/dev/null
-# Move the DEBs to the output directory
-mkdir -p "${output_dir}"
-mv "${package_temporary_dir}"/deb/* "${output_dir}"
diff --git a/deployment/ubuntu-package-x64/pkg-src b/deployment/ubuntu-package-x64/pkg-src
deleted file mode 120000
index 4c695fea1..000000000
--- a/deployment/ubuntu-package-x64/pkg-src
+++ /dev/null
@@ -1 +0,0 @@
-../debian-package-x64/pkg-src \ No newline at end of file
diff --git a/deployment/unraid/docker-templates/README.md b/deployment/unraid/docker-templates/README.md
index 2c268e8b3..8e401e009 100644
--- a/deployment/unraid/docker-templates/README.md
+++ b/deployment/unraid/docker-templates/README.md
@@ -8,7 +8,7 @@ Click on the Docker tab
Add the following line under "Template Repositories"
-https://github.com/jellyfin/jellyfin/blob/master/deployment/unraid/docker-templates
+https://github.com/jellyfin/jellyfin/tree/master/deployment/unraid/docker-templates
Click save than click on Add Container and select jellyfin.
diff --git a/deployment/unraid/docker-templates/jellyfin.xml b/deployment/unraid/docker-templates/jellyfin.xml
index 1d97a9f00..57b4cc5ae 100644
--- a/deployment/unraid/docker-templates/jellyfin.xml
+++ b/deployment/unraid/docker-templates/jellyfin.xml
@@ -3,14 +3,15 @@
<TemplateURL>https://raw.githubusercontent.com/jellyfin/jellyfin/deployment/unraid/docker-templates/jellyfin.xml</TemplateURL>
<Beta>False</Beta>
<Category>MediaApp:Video MediaApp:Music MediaApp:Photos MediaServer:Video MediaServer:Music MediaServer:Photos</Category>
- <Name>JellyFin</Name>
+ <Name>Jellyfin</Name>
<Description>
- JellyFin is The Free Software Media Browser Converted By Community Applications Always verify this template (and values) against the dockerhub support page for the container!![br][br]
+ Jellyfin is The Free Software Media Browser Converted By Community Applications Always verify this template (and values) against the dockerhub support page for the container!![br][br]
You can add as many mount points as needed for recordings, movies ,etc. [br][br]
[b][span style='color: #E80000;']Directions:[/span][/b][br]
- [b]/config[/b] : this is where Jellyfin will store it's databases and configuration.[br][br]
+ [b]/config[/b] : This is where Jellyfin will store it's databases and configuration.[br][br]
[b]Port[/b] : This is the default port for Jellyfin. (Will add ssl port later)[br][br]
- [b]Media[/b] : This is the mounting point of your media. When you access it in Jellyfin it will be /media or whatever you chose for a mount point
+ [b]Media[/b] : This is the mounting point of your media. When you access it in Jellyfin it will be /media or whatever you chose for a mount point[br][br]
+ [b]Cache[/b] : This is where Jellyfin will store and manage cached files like images to serve to clients. This is not where all images are stored.[br][br]
[b]Tip:[/b] You can add more volume mappings if you wish Jellyfin has access to it.
</Description>
<Overview>
@@ -35,7 +36,7 @@
</Networking>
<Data>
<Volume>
- <HostDir>/mnt/cache/appdata/config</HostDir>
+ <HostDir>/mnt/user/appdata/Jellyfin</HostDir>
<ContainerDir>/config</ContainerDir>
<Mode>rw</Mode>
</Volume>
@@ -44,8 +45,13 @@
<ContainerDir>/media</ContainerDir>
<Mode>rw</Mode>
</Volume>
+ <Volume>
+ <HostDir>/mnt/user/appdata/Jellyfin/cache/</HostDir>
+ <ContainerDir>/cache</ContainerDir>
+ <Mode>rw</Mode>
+ </Volume>
</Data>
<WebUI>http://[IP]:[PORT:8096]/</WebUI>
- <Icon>https://raw.githubusercontent.com/binhex/docker-templates/master/binhex/images/emby-icon.png</Icon>
+ <Icon>https://raw.githubusercontent.com/binhex/docker-templates/master/binhex/images/jellyfin-icon.png</Icon>
<ExtraParams></ExtraParams>
</Containers>
diff --git a/deployment/win-x64/build.sh b/deployment/win-x64/build.sh
deleted file mode 100755
index 0b3046203..000000000
--- a/deployment/win-x64/build.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-build_jellyfin ../../Jellyfin.Server Release win-x64 `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/win-x64/clean.sh b/deployment/win-x64/clean.sh
deleted file mode 100755
index 3df2d7796..000000000
--- a/deployment/win-x64/clean.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-clean_jellyfin ../.. Release `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/win-x64/dependencies.txt b/deployment/win-x64/dependencies.txt
deleted file mode 100644
index 3d25d1bdf..000000000
--- a/deployment/win-x64/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-dotnet
diff --git a/deployment/win-x64/package.sh b/deployment/win-x64/package.sh
deleted file mode 100755
index d21e3b532..000000000
--- a/deployment/win-x64/package.sh
+++ /dev/null
@@ -1,47 +0,0 @@
-#!/usr/bin/env bash
-set -x
-package_win64() (
- local NSSM_VERSION="nssm-2.24-101-g897c7ad"
- local NSSM_URL="https://nssm.cc/ci/${NSSM_VERSION}.zip"
- local FFMPEG_VERSION="ffmpeg-4.0.2-win64-static"
- local FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win64/static/${FFMPEG_VERSION}.zip"
- local ROOT=${1-$DEFAULT_ROOT}
- local OUTPUT_DIR=${2-$DEFAULT_OUTPUT_DIR}
- local PKG_DIR=${3-$DEFAULT_PKG_DIR}
- local ARCHIVE_CMD="zip -r"
- # Package portable build result
- if [ -d ${OUTPUT_DIR} ]; then
- echo -e "${CYAN}Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}'.${NC}"
- local TEMP_DIR="$(mktemp -d)"
- wget ${NSSM_URL} -O ${TEMP_DIR}/nssm.zip
- wget ${FFMPEG_URL} -O ${TEMP_DIR}/ffmpeg.zip
- unzip ${TEMP_DIR}/nssm.zip -d $TEMP_DIR
- cp ${TEMP_DIR}/${NSSM_VERSION}/win64/nssm.exe ${OUTPUT_DIR}/nssm.exe
- unzip ${TEMP_DIR}/ffmpeg.zip -d $TEMP_DIR
- cp ${TEMP_DIR}/${FFMPEG_VERSION}/bin/ffmpeg.exe ${OUTPUT_DIR}/ffmpeg.exe
- cp ${TEMP_DIR}/${FFMPEG_VERSION}/bin/ffprobe.exe ${OUTPUT_DIR}/ffprobe.exe
- rm -r ${TEMP_DIR}
- cp ${ROOT}/deployment/win-generic/install-jellyfin.ps1 ${OUTPUT_DIR}/install-jellyfin.ps1
- cp ${ROOT}/deployment/win-generic/install.bat ${OUTPUT_DIR}/install.bat
- mkdir -p ${PKG_DIR}
- pushd ${OUTPUT_DIR}
- ${ARCHIVE_CMD} ${ROOT}/${PKG_DIR}/`basename "${OUTPUT_DIR}"`.zip .
- popd
- local EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' FAILED.${NC}"
- fi
- else
- echo -e "${RED}[FAIL] Build artifacts do not exist for ${OUTPUT_DIR}. Run build.sh first.${NC}"
- fi
-)
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-package_win64 ../.. `pwd`/dist/jellyfin_${VERSION}
-
-#TODO setup and maybe change above code to produce the Windows native zip format.
diff --git a/deployment/win-x86/build.sh b/deployment/win-x86/build.sh
deleted file mode 100755
index 610db356a..000000000
--- a/deployment/win-x86/build.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-build_jellyfin ../../Jellyfin.Server Release win-x86 `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/win-x86/clean.sh b/deployment/win-x86/clean.sh
deleted file mode 100755
index 3df2d7796..000000000
--- a/deployment/win-x86/clean.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-clean_jellyfin ../.. Release `pwd`/dist/jellyfin_${VERSION}
diff --git a/deployment/win-x86/dependencies.txt b/deployment/win-x86/dependencies.txt
deleted file mode 100644
index 3d25d1bdf..000000000
--- a/deployment/win-x86/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-dotnet
diff --git a/deployment/win-x86/package.sh b/deployment/win-x86/package.sh
deleted file mode 100755
index 3cc4eb623..000000000
--- a/deployment/win-x86/package.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/env bash
-package_win32() (
- local NSSM_VERSION="nssm-2.24-101-g897c7ad"
- local NSSM_URL="https://nssm.cc/ci/${NSSM_VERSION}.zip"
- local FFMPEG_VERSION="ffmpeg-4.0.2-win32-static"
- local FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win32/static/${FFMPEG_VERSION}.zip"
- local ROOT=${1-$DEFAULT_ROOT}
- local OUTPUT_DIR=${2-$DEFAULT_OUTPUT_DIR}
- local PKG_DIR=${3-$DEFAULT_PKG_DIR}
- local ARCHIVE_CMD="zip -r"
- # Package portable build result
- if [ -d ${OUTPUT_DIR} ]; then
- echo -e "${CYAN}Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}'.${NC}"
- local TEMP_DIR="$(mktemp -d)"
- wget ${NSSM_URL} -O ${TEMP_DIR}/nssm.zip
- wget ${FFMPEG_URL} -O ${TEMP_DIR}/ffmpeg.zip
- unzip ${TEMP_DIR}/nssm.zip -d $TEMP_DIR
- cp ${TEMP_DIR}/${NSSM_VERSION}/win32/nssm.exe ${OUTPUT_DIR}/nssm.exe
- unzip ${TEMP_DIR}/ffmpeg.zip -d $TEMP_DIR
- cp ${TEMP_DIR}/${FFMPEG_VERSION}/bin/ffmpeg.exe ${OUTPUT_DIR}/ffmpeg.exe
- cp ${TEMP_DIR}/${FFMPEG_VERSION}/bin/ffprobe.exe ${OUTPUT_DIR}/ffprobe.exe
- rm -r ${TEMP_DIR}
- cp ${ROOT}/deployment/win-generic/install-jellyfin.ps1 ${OUTPUT_DIR}/install-jellyfin.ps1
- cp ${ROOT}/deployment/win-generic/install.bat ${OUTPUT_DIR}/install.bat
- mkdir -p ${PKG_DIR}
- pushd ${OUTPUT_DIR}
- ${ARCHIVE_CMD} ${ROOT}/${PKG_DIR}/`basename "${OUTPUT_DIR}"`.zip .
- popd
- local EXIT_CODE=$?
- if [ $EXIT_CODE -eq 0 ]; then
- echo -e "${GREEN}[DONE] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' complete.${NC}"
- else
- echo -e "${RED}[FAIL] Packaging build in '${OUTPUT_DIR}' for `basename "${OUTPUT_DIR}"` to '${PKG_DIR}' with root '${ROOT}' FAILED.${NC}"
- fi
- else
- echo -e "${RED}[FAIL] Build artifacts do not exist for ${OUTPUT_DIR}. Run build.sh first.${NC}"
- fi
-)
-source ../common.build.sh
-
-VERSION=`get_version ../..`
-
-package_win32 ../.. `pwd`/dist/jellyfin_${VERSION}
-
-#TODO setup and maybe change above code to produce the Windows native zip format.
diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1
deleted file mode 100644
index 2c83f264c..000000000
--- a/deployment/windows/build-jellyfin.ps1
+++ /dev/null
@@ -1,110 +0,0 @@
-[CmdletBinding()]
-param(
- [switch]$InstallFFMPEG,
- [switch]$InstallNSSM,
- [switch]$GenerateZip,
- [string]$InstallLocation = "$Env:AppData/Jellyfin-Server/",
- [ValidateSet('Debug','Release')][string]$BuildType = 'Release',
- [ValidateSet('Quiet','Minimal', 'Normal')][string]$DotNetVerbosity = 'Minimal',
- [ValidateSet('win','win7', 'win8','win81','win10')][string]$WindowsVersion = 'win',
- [ValidateSet('x64','x86', 'arm', 'arm64')][string]$Architecture = 'x64'
-)
-
-#PowershellCore and *nix check to make determine which temp dir to use.
-if(($PSVersionTable.PSEdition -eq 'Core') -and (-not $IsWindows)){
- $TempDir = mktemp -d
-}else{
- $TempDir = $env:Temp
-}
-
-function Build-JellyFin {
- if(($Architecture -eq 'arm64') -and ($WindowsVersion -ne 'win10')){
- Write-Error "arm64 only supported with Windows10 Version"
- exit
- }
- if(($Architecture -eq 'arm') -and ($WindowsVersion -notin @('win10','win81','win8'))){
- Write-Error "arm only supported with Windows 8 or higher"
- exit
- }
- dotnet publish -c $BuildType -r "$windowsversion-$Architecture" MediaBrowser.sln -o $InstallLocation -v $DotNetVerbosity
-}
-
-function Install-FFMPEG {
- param(
- [string]$InstallLocation,
- [string]$Architecture
- )
- Write-Verbose "Checking Architecture"
- if($Architecture -notin @('x86','x64')){
- Write-Warning "No builds available for your selected architecture of $Architecture"
- Write-Warning "FFMPEG will not be installed"
- }elseif($Architecture -eq 'x64'){
- Write-Verbose "Downloading 64 bit FFMPEG"
- Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-4.0.2-win64-static.zip -UseBasicParsing -OutFile "$tempdir/fmmpeg.zip" | Write-Verbose
- }else{
- Write-Verbose "Downloading 32 bit FFMPEG"
- Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-4.0.2-win32-static.zip -UseBasicParsing -OutFile "$tempdir/fmmpeg.zip" | Write-Verbose
- }
-
- Expand-Archive "$tempdir/fmmpeg.zip" -DestinationPath "$tempdir/ffmpeg/" | Write-Verbose
- if($Architecture -eq 'x64'){
- Write-Verbose "Copying Binaries to Jellyfin location"
- Get-ChildItem "$tempdir/ffmpeg/ffmpeg-4.0.2-win64-static/bin" | ForEach-Object {
- Copy-Item $_.FullName -Destination $installLocation | Write-Verbose
- }
- }else{
- Write-Verbose "Copying Binaries to Jellyfin location"
- Get-ChildItem "$tempdir/ffmpeg/ffmpeg-4.0.2-win32-static/bin" | ForEach-Object {
- Copy-Item $_.FullName -Destination $installLocation | Write-Verbose
- }
- }
- Remove-Item "$tempdir/ffmpeg/" -Recurse -Force -ErrorAction Continue | Write-Verbose
- Remove-Item "$tempdir/fmmpeg.zip" -Force -ErrorAction Continue | Write-Verbose
-}
-
-function Install-NSSM {
- param(
- [string]$InstallLocation,
- [string]$Architecture
- )
- Write-Verbose "Checking Architecture"
- if($Architecture -notin @('x86','x64')){
- Write-Warning "No builds available for your selected architecture of $Architecture"
- Write-Warning "NSSM will not be installed"
- }else{
- Write-Verbose "Downloading NSSM"
- Invoke-WebRequest -Uri https://nssm.cc/ci/nssm-2.24-101-g897c7ad.zip -UseBasicParsing -OutFile "$tempdir/nssm.zip" | Write-Verbose
- }
-
- Expand-Archive "$tempdir/nssm.zip" -DestinationPath "$tempdir/nssm/" | Write-Verbose
- if($Architecture -eq 'x64'){
- Write-Verbose "Copying Binaries to Jellyfin location"
- Get-ChildItem "$tempdir/nssm/nssm-2.24-101-g897c7ad/win64" | ForEach-Object {
- Copy-Item $_.FullName -Destination $installLocation | Write-Verbose
- }
- }else{
- Write-Verbose "Copying Binaries to Jellyfin location"
- Get-ChildItem "$tempdir/nssm/nssm-2.24-101-g897c7ad/win32" | ForEach-Object {
- Copy-Item $_.FullName -Destination $installLocation | Write-Verbose
- }
- }
- Remove-Item "$tempdir/nssm/" -Recurse -Force -ErrorAction Continue | Write-Verbose
- Remove-Item "$tempdir/nssm.zip" -Force -ErrorAction Continue | Write-Verbose
-}
-
-Write-Verbose "Starting Build Process: Selected Environment is $WindowsVersion-$Architecture"
-Build-JellyFin
-if($InstallFFMPEG.IsPresent -or ($InstallFFMPEG -eq $true)){
- Write-Verbose "Starting FFMPEG Install"
- Install-FFMPEG $InstallLocation $Architecture
-}
-if($InstallNSSM.IsPresent -or ($InstallNSSM -eq $true)){
- Write-Verbose "Starting NSSM Install"
- Install-NSSM $InstallLocation $Architecture
-}
-Copy-Item .\deployment\windows\install-jellyfin.ps1 $InstallLocation\install-jellyfin.ps1
-Copy-Item .\deployment\windows\install.bat $InstallLocation\install.bat
-if($GenerateZip.IsPresent -or ($GenerateZip -eq $true)){
- Compress-Archive -Path $InstallLocation -DestinationPath "$InstallLocation/jellyfin.zip" -Force
-}
-Write-Verbose "Finished"
diff --git a/deployment/windows/dependencies.txt b/deployment/windows/dependencies.txt
deleted file mode 100644
index 3d25d1bdf..000000000
--- a/deployment/windows/dependencies.txt
+++ /dev/null
@@ -1 +0,0 @@
-dotnet
diff --git a/deployment/windows/install-jellyfin.ps1 b/deployment/windows/install-jellyfin.ps1
deleted file mode 100644
index b6e00e056..000000000
--- a/deployment/windows/install-jellyfin.ps1
+++ /dev/null
@@ -1,460 +0,0 @@
-[CmdletBinding()]
-
-param(
- [Switch]$Quiet,
- [Switch]$InstallAsService,
- [pscredential]$ServiceUser,
- [switch]$CreateDesktopShorcut,
- [switch]$LaunchJellyfin,
- [switch]$MigrateEmbyLibrary,
- [string]$InstallLocation,
- [string]$EmbyLibraryLocation,
- [string]$JellyfinLibraryLocation
-)
-<# This form was created using POSHGUI.com a free online gui designer for PowerShell
-.NAME
- Install-Jellyfin
-#>
-
-#This doesn't need to be used by default anymore, but I am keeping it in as a function for future use.
-function Elevate-Window {
- # Get the ID and security principal of the current user account
- $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
- $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
-
- # Get the security principal for the Administrator role
- $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
-
- # Check to see if we are currently running "as Administrator"
- if ($myWindowsPrincipal.IsInRole($adminRole))
- {
- # We are running "as Administrator" - so change the title and background color to indicate this
- $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
- $Host.UI.RawUI.BackgroundColor = "DarkBlue"
- clear-host
- }
- else
- {
- # We are not running "as Administrator" - so relaunch as administrator
-
- # Create a new process object that starts PowerShell
- $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
-
- # Specify the current script path and name as a parameter
- $newProcess.Arguments = $myInvocation.MyCommand.Definition;
-
- # Indicate that the process should be elevated
- $newProcess.Verb = "runas";
-
- # Start the new process
- [System.Diagnostics.Process]::Start($newProcess);
-
- # Exit from the current, unelevated, process
- exit
- }
-}
-
-#FIXME The install methods should be a function that takes all the params, the quiet flag should be a paramset
-
-if($Quiet.IsPresent -or $Quiet -eq $true){
- if([string]::IsNullOrEmpty($JellyfinLibraryLocation)){
- $Script:JellyfinDataDir = "$env:AppData\jellyfin\"
- }else{
- $Script:JellyfinDataDir = $JellyfinLibraryLocation
- }
- if([string]::IsNullOrEmpty($InstallLocation)){
- $Script:DefaultJellyfinInstallDirectory = "$env:Appdata\jellyfin\"
- }else{
- $Script:DefaultJellyfinInstallDirectory = $InstallLocation
- }
-
- if([string]::IsNullOrEmpty($EmbyLibraryLocation)){
- $Script:defaultEmbyDataDir = "$env:Appdata\Emby-Server\data\"
- }else{
- $Script:defaultEmbyDataDir = $EmbyLibraryLocation
- }
-
- if($InstallAsService.IsPresent -or $InstallAsService -eq $true){
- $Script:InstallAsService = $true
- }else{$Script:InstallAsService = $false}
- if($null -eq $ServiceUser){
- $Script:InstallServiceAsUser = $false
- }else{
- $Script:InstallServiceAsUser = $true
- $Script:UserCredentials = $ServiceUser
- $Script:JellyfinDataDir = "C:\Users\$($Script:UserCredentials.UserName)\Appdata\Roaming\jellyfin\"}
- if($CreateDesktopShorcut.IsPresent -or $CreateDesktopShorcut -eq $true) {$Script:CreateShortcut = $true}else{$Script:CreateShortcut = $false}
- if($MigrateEmbyLibrary.IsPresent -or $MigrateEmbyLibrary -eq $true){$Script:MigrateLibrary = $true}else{$Script:MigrateLibrary = $false}
- if($LaunchJellyfin.IsPresent -or $LaunchJellyfin -eq $true){$Script:StartJellyfin = $true}else{$Script:StartJellyfin = $false}
-
- if(-not (Test-Path $Script:DefaultJellyfinInstallDirectory)){
- mkdir $Script:DefaultJellyfinInstallDirectory
- }
- Copy-Item -Path $PSScriptRoot/* -DestinationPath "$Script:DefaultJellyfinInstallDirectory/" -Force -Recurse
- if($Script:InstallAsService){
- if($Script:InstallServiceAsUser){
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" install Jellyfin `"$Script:DefaultJellyfinInstallDirectory\jellyfin.exe`" --datadir `"$Script:JellyfinDataDir`"
- Start-Sleep -Milliseconds 500
- &sc.exe config Jellyfin obj=".\$($Script:UserCredentials.UserName)" password="$($Script:UserCredentials.GetNetworkCredential().Password)"
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" set Jellyfin Start SERVICE_DELAYED_AUTO_START
- }else{
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" install Jellyfin `"$Script:DefaultJellyfinInstallDirectory\jellyfin.exe`" --datadir `"$Script:JellyfinDataDir`"
- Start-Sleep -Milliseconds 500
- #&"$Script:DefaultJellyfinInstallDirectory\nssm.exe" set Jellyfin ObjectName $Script:UserCredentials.UserName $Script:UserCredentials.GetNetworkCredential().Password
- #Set-Service -Name Jellyfin -Credential $Script:UserCredentials
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" set Jellyfin Start SERVICE_DELAYED_AUTO_START
- }
- }
- if($Script:MigrateLibrary){
- Copy-Item -Path $Script:defaultEmbyDataDir/config -Destination $Script:JellyfinDataDir -force -Recurse
- Copy-Item -Path $Script:defaultEmbyDataDir/cache -Destination $Script:JellyfinDataDir -force -Recurse
- Copy-Item -Path $Script:defaultEmbyDataDir/data -Destination $Script:JellyfinDataDir -force -Recurse
- Copy-Item -Path $Script:defaultEmbyDataDir/metadata -Destination $Script:JellyfinDataDir -force -Recurse
- Copy-Item -Path $Script:defaultEmbyDataDir/root -Destination $Script:JellyfinDataDir -force -Recurse
- }
- if($Script:CreateShortcut){
- $WshShell = New-Object -comObject WScript.Shell
- $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Jellyfin.lnk")
- $Shortcut.TargetPath = "$Script:DefaultJellyfinInstallDirectory\jellyfin.exe"
- $Shortcut.Save()
- }
- if($Script:StartJellyfin){
- if($Script:InstallAsService){
- Get-Service Jellyfin | Start-Service
- }else{
- Start-Process -FilePath $Script:DefaultJellyfinInstallDirectory\jellyfin.exe -PassThru
- }
- }
-}else{
-
-}
-Add-Type -AssemblyName System.Windows.Forms
-[System.Windows.Forms.Application]::EnableVisualStyles()
-
-$Script:JellyFinDataDir = "$env:AppData\jellyfin\"
-$Script:DefaultJellyfinInstallDirectory = "$env:Appdata\jellyfin\"
-$Script:defaultEmbyDataDir = "$env:Appdata\Emby-Server\"
-$Script:InstallAsService = $False
-$Script:InstallServiceAsUser = $false
-$Script:CreateShortcut = $false
-$Script:MigrateLibrary = $false
-$Script:StartJellyfin = $false
-
-function InstallJellyfin {
- Write-Host "Install as service: $Script:InstallAsService"
- Write-Host "Install as serviceuser: $Script:InstallServiceAsUser"
- Write-Host "Create Shortcut: $Script:CreateShortcut"
- Write-Host "MigrateLibrary: $Script:MigrateLibrary"
- $GUIElementsCollection | ForEach-Object {
- $_.Enabled = $false
- }
- Write-Host "Making Jellyfin directory"
- $ProgressBar.Minimum = 1
- $ProgressBar.Maximum = 100
- $ProgressBar.Value = 1
- if($Script:DefaultJellyfinInstallDirectory -ne $InstallLocationBox.Text){
- Write-Host "Custom Install Location Chosen: $($InstallLocationBox.Text)"
- $Script:DefaultJellyfinInstallDirectory = $InstallLocationBox.Text
- }
- if($Script:JellyfinDataDir -ne $CustomLibraryBox.Text){
- Write-Host "Custom Library Location Chosen: $($CustomLibraryBox.Text)"
- $Script:JellyfinDataDir = $CustomLibraryBox.Text
- }
- if(-not (Test-Path $Script:DefaultJellyfinInstallDirectory)){
- mkdir $Script:DefaultJellyfinInstallDirectory
- }
- Write-Host "Copying Jellyfin Data"
- $progressbar.Value = 10
- Copy-Item -Path $PSScriptRoot/* -Destination $Script:DefaultJellyfinInstallDirectory/ -Force -Recurse
- Write-Host "Finished Copying"
- $ProgressBar.Value = 50
- if($Script:InstallAsService){
- if($Script:InstallServiceAsUser){
- Write-Host "Installing Service as user $($Script:UserCredentials.UserName)"
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" install Jellyfin `"$Script:DefaultJellyfinInstallDirectory\jellyfin.exe`" --datadir `"$Script:JellyfinDataDir`"
- Start-Sleep -Milliseconds 2000
- &sc.exe config Jellyfin obj=".\$($Script:UserCredentials.UserName)" password="$($Script:UserCredentials.GetNetworkCredential().Password)"
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" set Jellyfin Start SERVICE_DELAYED_AUTO_START
- }else{
- Write-Host "Installing Service as LocalSystem"
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" install Jellyfin `"$Script:DefaultJellyfinInstallDirectory\jellyfin.exe`" --datadir `"$Script:JellyfinDataDir`"
- Start-Sleep -Milliseconds 2000
- &"$Script:DefaultJellyfinInstallDirectory\nssm.exe" set Jellyfin Start SERVICE_DELAYED_AUTO_START
- }
- }
- $progressbar.Value = 60
- if($Script:MigrateLibrary){
- if($Script:defaultEmbyDataDir -ne $LibraryLocationBox.Text){
- Write-Host "Custom location defined for emby library: $($LibraryLocationBox.Text)"
- $Script:defaultEmbyDataDir = $LibraryLocationBox.Text
- }
- Write-Host "Copying emby library from $Script:defaultEmbyDataDir to $Script:JellyFinDataDir"
- Write-Host "This could take a while depending on the size of your library. Please be patient"
- Write-Host "Copying config"
- Copy-Item -Path $Script:defaultEmbyDataDir/config -Destination $Script:JellyfinDataDir -force -Recurse
- Write-Host "Copying cache"
- Copy-Item -Path $Script:defaultEmbyDataDir/cache -Destination $Script:JellyfinDataDir -force -Recurse
- Write-Host "Copying data"
- Copy-Item -Path $Script:defaultEmbyDataDir/data -Destination $Script:JellyfinDataDir -force -Recurse
- Write-Host "Copying metadata"
- Copy-Item -Path $Script:defaultEmbyDataDir/metadata -Destination $Script:JellyfinDataDir -force -Recurse
- Write-Host "Copying root dir"
- Copy-Item -Path $Script:defaultEmbyDataDir/root -Destination $Script:JellyfinDataDir -force -Recurse
- }
- $progressbar.Value = 80
- if($Script:CreateShortcut){
- Write-Host "Creating Shortcut"
- $WshShell = New-Object -comObject WScript.Shell
- $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Jellyfin.lnk")
- $Shortcut.TargetPath = "$Script:DefaultJellyfinInstallDirectory\jellyfin.exe"
- $Shortcut.Save()
- }
- $ProgressBar.Value = 90
- if($Script:StartJellyfin){
- if($Script:InstallAsService){
- Write-Host "Starting Jellyfin Service"
- Get-Service Jellyfin | Start-Service
- }else{
- Write-Host "Starting Jellyfin"
- Start-Process -FilePath $Script:DefaultJellyfinInstallDirectory\jellyfin.exe -PassThru
- }
- }
- $progressbar.Value = 100
- Write-Host Finished
- $wshell = New-Object -ComObject Wscript.Shell
- $wshell.Popup("Operation Completed",0,"Done",0x1)
- $InstallForm.Close()
-}
-function ServiceBoxCheckChanged {
- if($InstallAsServiceCheck.Checked){
- $Script:InstallAsService = $true
- $ServiceUserLabel.Visible = $true
- $ServiceUserLabel.Enabled = $true
- $ServiceUserBox.Visible = $true
- $ServiceUserBox.Enabled = $true
- }else{
- $Script:InstallAsService = $false
- $ServiceUserLabel.Visible = $false
- $ServiceUserLabel.Enabled = $false
- $ServiceUserBox.Visible = $false
- $ServiceUserBox.Enabled = $false
- }
-}
-function UserSelect {
- if($ServiceUserBox.Text -eq 'Local System')
- {
- $Script:InstallServiceAsUser = $false
- $Script:UserCredentials = $null
- $ServiceUserBox.Items.RemoveAt(1)
- $ServiceUserBox.Items.Add("Custom User")
- }elseif($ServiceUserBox.Text -eq 'Custom User'){
- $Script:InstallServiceAsUser = $true
- $Script:UserCredentials = Get-Credential -Message "Please enter the credentials of the user you with to run Jellyfin Service as" -UserName $env:USERNAME
- $ServiceUserBox.Items[1] = "$($Script:UserCredentials.UserName)"
- }
-}
-function CreateShortcutBoxCheckChanged {
- if($CreateShortcutCheck.Checked){
- $Script:CreateShortcut = $true
- }else{
- $Script:CreateShortcut = $False
- }
-}
-function StartJellyFinBoxCheckChanged {
- if($StartProgramCheck.Checked){
- $Script:StartJellyfin = $true
- }else{
- $Script:StartJellyfin = $false
- }
-}
-
-function CustomLibraryCheckChanged {
- if($CustomLibraryCheck.Checked){
- $Script:UseCustomLibrary = $true
- $CustomLibraryBox.Enabled = $true
- }else{
- $Script:UseCustomLibrary = $false
- $CustomLibraryBox.Enabled = $false
- }
-}
-
-function MigrateLibraryCheckboxChanged {
-
- if($MigrateLibraryCheck.Checked){
- $Script:MigrateLibrary = $true
- $LibraryMigrationLabel.Visible = $true
- $LibraryMigrationLabel.Enabled = $true
- $LibraryLocationBox.Visible = $true
- $LibraryLocationBox.Enabled = $true
- }else{
- $Script:MigrateLibrary = $false
- $LibraryMigrationLabel.Visible = $false
- $LibraryMigrationLabel.Enabled = $false
- $LibraryLocationBox.Visible = $false
- $LibraryLocationBox.Enabled = $false
- }
-
-}
-
-
-#region begin GUI{
-
-$InstallForm = New-Object system.Windows.Forms.Form
-$InstallForm.ClientSize = '320,240'
-$InstallForm.text = "Terrible Jellyfin Installer"
-$InstallForm.TopMost = $false
-
-$GUIElementsCollection = @()
-
-$InstallButton = New-Object system.Windows.Forms.Button
-$InstallButton.text = "Install"
-$InstallButton.width = 60
-$InstallButton.height = 30
-$InstallButton.location = New-Object System.Drawing.Point(5,5)
-$InstallButton.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $InstallButton
-
-$ProgressBar = New-Object system.Windows.Forms.ProgressBar
-$ProgressBar.width = 245
-$ProgressBar.height = 30
-$ProgressBar.location = New-Object System.Drawing.Point(70,5)
-
-$InstallLocationLabel = New-Object system.Windows.Forms.Label
-$InstallLocationLabel.text = "Install Location"
-$InstallLocationLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
-$InstallLocationLabel.AutoSize = $true
-$InstallLocationLabel.width = 100
-$InstallLocationLabel.height = 20
-$InstallLocationLabel.location = New-Object System.Drawing.Point(5,50)
-$InstallLocationLabel.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $InstallLocationLabel
-
-$InstallLocationBox = New-Object system.Windows.Forms.TextBox
-$InstallLocationBox.multiline = $false
-$InstallLocationBox.width = 205
-$InstallLocationBox.height = 20
-$InstallLocationBox.location = New-Object System.Drawing.Point(110,50)
-$InstallLocationBox.Text = $Script:DefaultJellyfinInstallDirectory
-$InstallLocationBox.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $InstallLocationBox
-
-$CustomLibraryCheck = New-Object system.Windows.Forms.CheckBox
-$CustomLibraryCheck.text = "Custom Library Location:"
-$CustomLibraryCheck.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
-$CustomLibraryCheck.AutoSize = $false
-$CustomLibraryCheck.width = 180
-$CustomLibraryCheck.height = 20
-$CustomLibraryCheck.location = New-Object System.Drawing.Point(5,75)
-$CustomLibraryCheck.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $CustomLibraryCheck
-
-$CustomLibraryBox = New-Object system.Windows.Forms.TextBox
-$CustomLibraryBox.multiline = $false
-$CustomLibraryBox.width = 130
-$CustomLibraryBox.height = 20
-$CustomLibraryBox.location = New-Object System.Drawing.Point(185,75)
-$CustomLibraryBox.Text = $Script:JellyFinDataDir
-$CustomLibraryBox.Font = 'Microsoft Sans Serif,10'
-$CustomLibraryBox.Enabled = $false
-$GUIElementsCollection += $CustomLibraryBox
-
-$InstallAsServiceCheck = New-Object system.Windows.Forms.CheckBox
-$InstallAsServiceCheck.text = "Install as Service"
-$InstallAsServiceCheck.AutoSize = $false
-$InstallAsServiceCheck.width = 140
-$InstallAsServiceCheck.height = 20
-$InstallAsServiceCheck.location = New-Object System.Drawing.Point(5,125)
-$InstallAsServiceCheck.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $InstallAsServiceCheck
-
-$ServiceUserLabel = New-Object system.Windows.Forms.Label
-$ServiceUserLabel.text = "Run Service As:"
-$ServiceUserLabel.AutoSize = $true
-$ServiceUserLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
-$ServiceUserLabel.width = 100
-$ServiceUserLabel.height = 20
-$ServiceUserLabel.location = New-Object System.Drawing.Point(15,145)
-$ServiceUserLabel.Font = 'Microsoft Sans Serif,10'
-$ServiceUserLabel.Visible = $false
-$ServiceUserLabel.Enabled = $false
-$GUIElementsCollection += $ServiceUserLabel
-
-$ServiceUserBox = New-Object system.Windows.Forms.ComboBox
-$ServiceUserBox.text = "Run Service As"
-$ServiceUserBox.width = 195
-$ServiceUserBox.height = 20
-@('Local System','Custom User') | ForEach-Object {[void] $ServiceUserBox.Items.Add($_)}
-$ServiceUserBox.location = New-Object System.Drawing.Point(120,145)
-$ServiceUserBox.Font = 'Microsoft Sans Serif,10'
-$ServiceUserBox.Visible = $false
-$ServiceUserBox.Enabled = $false
-$ServiceUserBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
-$GUIElementsCollection += $ServiceUserBox
-
-$MigrateLibraryCheck = New-Object system.Windows.Forms.CheckBox
-$MigrateLibraryCheck.text = "Import Emby Library"
-$MigrateLibraryCheck.AutoSize = $false
-$MigrateLibraryCheck.width = 160
-$MigrateLibraryCheck.height = 20
-$MigrateLibraryCheck.location = New-Object System.Drawing.Point(5,170)
-$MigrateLibraryCheck.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $MigrateLibraryCheck
-
-$LibraryMigrationLabel = New-Object system.Windows.Forms.Label
-$LibraryMigrationLabel.text = "Emby Library Path"
-$LibraryMigrationLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
-$LibraryMigrationLabel.AutoSize = $false
-$LibraryMigrationLabel.width = 120
-$LibraryMigrationLabel.height = 20
-$LibraryMigrationLabel.location = New-Object System.Drawing.Point(15,190)
-$LibraryMigrationLabel.Font = 'Microsoft Sans Serif,10'
-$LibraryMigrationLabel.Visible = $false
-$LibraryMigrationLabel.Enabled = $false
-$GUIElementsCollection += $LibraryMigrationLabel
-
-$LibraryLocationBox = New-Object system.Windows.Forms.TextBox
-$LibraryLocationBox.multiline = $false
-$LibraryLocationBox.width = 175
-$LibraryLocationBox.height = 20
-$LibraryLocationBox.location = New-Object System.Drawing.Point(140,190)
-$LibraryLocationBox.Text = $Script:defaultEmbyDataDir
-$LibraryLocationBox.Font = 'Microsoft Sans Serif,10'
-$LibraryLocationBox.Visible = $false
-$LibraryLocationBox.Enabled = $false
-$GUIElementsCollection += $LibraryLocationBox
-
-$CreateShortcutCheck = New-Object system.Windows.Forms.CheckBox
-$CreateShortcutCheck.text = "Desktop Shortcut"
-$CreateShortcutCheck.AutoSize = $false
-$CreateShortcutCheck.width = 150
-$CreateShortcutCheck.height = 20
-$CreateShortcutCheck.location = New-Object System.Drawing.Point(5,215)
-$CreateShortcutCheck.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $CreateShortcutCheck
-
-$StartProgramCheck = New-Object system.Windows.Forms.CheckBox
-$StartProgramCheck.text = "Start Jellyfin"
-$StartProgramCheck.AutoSize = $false
-$StartProgramCheck.width = 160
-$StartProgramCheck.height = 20
-$StartProgramCheck.location = New-Object System.Drawing.Point(160,215)
-$StartProgramCheck.Font = 'Microsoft Sans Serif,10'
-$GUIElementsCollection += $StartProgramCheck
-
-$InstallForm.controls.AddRange($GUIElementsCollection)
-$InstallForm.Controls.Add($ProgressBar)
-
-#region gui events {
-$InstallButton.Add_Click({ InstallJellyfin })
-$CustomLibraryCheck.Add_CheckedChanged({CustomLibraryCheckChanged})
-$InstallAsServiceCheck.Add_CheckedChanged({ServiceBoxCheckChanged})
-$ServiceUserBox.Add_SelectedValueChanged({ UserSelect })
-$MigrateLibraryCheck.Add_CheckedChanged({MigrateLibraryCheckboxChanged})
-$CreateShortcutCheck.Add_CheckedChanged({CreateShortcutBoxCheckChanged})
-$StartProgramCheck.Add_CheckedChanged({StartJellyFinBoxCheckChanged})
-#endregion events }
-
-#endregion GUI }
-
-
-[void]$InstallForm.ShowDialog()
diff --git a/deployment/windows/install.bat b/deployment/windows/install.bat
deleted file mode 100644
index e21479a79..000000000
--- a/deployment/windows/install.bat
+++ /dev/null
@@ -1 +0,0 @@
-powershell.exe -executionpolicy Bypass -file install-jellyfin.ps1
diff --git a/deployment/fedora-package-x64/pkg-src/.gitignore b/fedora/.gitignore
index 6019b98c2..6019b98c2 100644
--- a/deployment/fedora-package-x64/pkg-src/.gitignore
+++ b/fedora/.gitignore
diff --git a/fedora/Makefile b/fedora/Makefile
new file mode 100644
index 000000000..97904ddd3
--- /dev/null
+++ b/fedora/Makefile
@@ -0,0 +1,26 @@
+VERSION := $(shell sed -ne '/^Version:/s/.* *//p' fedora/jellyfin.spec)
+
+srpm:
+ cd fedora/; \
+ SOURCE_DIR=.. \
+ WORKDIR="$${PWD}"; \
+ tar \
+ --transform "s,^\.,jellyfin-server-$(VERSION)," \
+ --exclude='.git*' \
+ --exclude='**/.git' \
+ --exclude='**/.hg' \
+ --exclude='**/.vs' \
+ --exclude='**/.vscode' \
+ --exclude='deployment' \
+ --exclude='**/bin' \
+ --exclude='**/obj' \
+ --exclude='**/.nuget' \
+ --exclude='*.deb' \
+ --exclude='*.rpm' \
+ --exclude='jellyfin-server-$(VERSION).tar.gz' \
+ -czf "jellyfin-server-$(VERSION).tar.gz" \
+ -C $${SOURCE_DIR} ./
+ cd fedora/; \
+ rpmbuild -bs jellyfin.spec \
+ --define "_sourcedir $$PWD/" \
+ --define "_srcrpmdir $(outdir)"
diff --git a/deployment/fedora-package-x64/pkg-src/README.md b/fedora/README.md
index 7ed6f7efc..7ed6f7efc 100644
--- a/deployment/fedora-package-x64/pkg-src/README.md
+++ b/fedora/README.md
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin-firewalld.xml b/fedora/jellyfin-firewalld.xml
index 538c5d65f..538c5d65f 100644
--- a/deployment/fedora-package-x64/pkg-src/jellyfin-firewalld.xml
+++ b/fedora/jellyfin-firewalld.xml
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin.env b/fedora/jellyfin.env
index abfa670e4..56b7a3558 100644
--- a/deployment/fedora-package-x64/pkg-src/jellyfin.env
+++ b/fedora/jellyfin.env
@@ -15,17 +15,19 @@
#
# Program directories
-JELLYFIN_DATA_DIRECTORY="/var/lib/jellyfin"
-JELLYFIN_CONFIG_DIRECTORY="/etc/jellyfin"
-JELLYFIN_LOG_DIRECTORY="/var/log/jellyfin"
-JELLYFIN_CACHE_DIRECTORY="/var/cache/jellyfin"
+JELLYFIN_DATA_DIR="/var/lib/jellyfin"
+JELLYFIN_CONFIG_DIR="/etc/jellyfin"
+JELLYFIN_LOG_DIR="/var/log/jellyfin"
+JELLYFIN_CACHE_DIR="/var/cache/jellyfin"
+
+# web client path, installed by the jellyfin-web package
+JELLYFIN_WEB_OPT="--webdir=/usr/share/jellyfin-web"
# In-App service control
JELLYFIN_RESTART_OPT="--restartpath=/usr/libexec/jellyfin/restart.sh"
# [OPTIONAL] ffmpeg binary paths, overriding the UI-configured values
#JELLYFIN_FFMPEG_OPT="--ffmpeg=/usr/bin/ffmpeg"
-#JELLYFIN_FFPROBE_OPT="--ffprobe=/usr/bin/ffprobe"
# [OPTIONAL] run Jellyfin as a headless service
#JELLYFIN_SERVICE_OPT="--service"
@@ -33,3 +35,7 @@ JELLYFIN_RESTART_OPT="--restartpath=/usr/libexec/jellyfin/restart.sh"
# [OPTIONAL] run Jellyfin without the web app
#JELLYFIN_NOWEBAPP_OPT="--noautorunwebapp"
+# [OPTIONAL] run Jellyfin with ASP.NET Server Garbage Collection (uses more RAM and less CPU than Workstation GC)
+# 0 = Workstation
+# 1 = Server
+#COMPlus_gcServer=1
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin.override.conf b/fedora/jellyfin.override.conf
index 8652450bb..8652450bb 100644
--- a/deployment/fedora-package-x64/pkg-src/jellyfin.override.conf
+++ b/fedora/jellyfin.override.conf
diff --git a/fedora/jellyfin.service b/fedora/jellyfin.service
new file mode 100644
index 000000000..f706b0ad3
--- /dev/null
+++ b/fedora/jellyfin.service
@@ -0,0 +1,15 @@
+[Unit]
+After=network-online.target
+Description=Jellyfin is a free software media system that puts you in control of managing and streaming your media.
+
+[Service]
+EnvironmentFile=/etc/sysconfig/jellyfin
+WorkingDirectory=/var/lib/jellyfin
+ExecStart=/usr/bin/jellyfin ${JELLYFIN_WEB_OPT} ${JELLYFIN_RESTART_OPT} ${JELLYFIN_FFMPEG_OPT} ${JELLYFIN_SERVICE_OPT} ${JELLYFIN_NOWEBAPP_OPT}
+TimeoutSec=15
+Restart=on-failure
+User=jellyfin
+Group=jellyfin
+
+[Install]
+WantedBy=multi-user.target
diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec
new file mode 100644
index 000000000..47dee7c13
--- /dev/null
+++ b/fedora/jellyfin.spec
@@ -0,0 +1,165 @@
+%global debug_package %{nil}
+# Set the dotnet runtime
+%if 0%{?fedora}
+%global dotnet_runtime fedora-x64
+%else
+%global dotnet_runtime centos-x64
+%endif
+
+Name: jellyfin
+Version: 10.8.0
+Release: 1%{?dist}
+Summary: The Free Software Media System
+License: GPLv3
+URL: https://jellyfin.org
+# Jellyfin Server tarball created by `make -f .copr/Makefile srpm`, real URL ends with `v%{version}.tar.gz`
+Source0: jellyfin-server-%{version}.tar.gz
+Source11: jellyfin.service
+Source12: jellyfin.env
+Source13: jellyfin.sudoers
+Source14: restart.sh
+Source15: jellyfin.override.conf
+Source16: jellyfin-firewalld.xml
+
+%{?systemd_requires}
+BuildRequires: systemd
+BuildRequires: libcurl-devel, fontconfig-devel, freetype-devel, openssl-devel, glibc-devel, libicu-devel
+# Requirements not packaged in main repos
+# COPR @dotnet-sig/dotnet or
+# https://packages.microsoft.com/rhel/7/prod/
+BuildRequires: dotnet-runtime-6.0, dotnet-sdk-6.0
+Requires: %{name}-server = %{version}-%{release}, %{name}-web = %{version}-%{release}
+# Disable Automatic Dependency Processing
+AutoReqProv: no
+
+%description
+Jellyfin is a free software media system that puts you in control of managing and streaming your media.
+
+%package server
+# RPMfusion free
+Summary: The Free Software Media System Server backend
+Requires(pre): shadow-utils
+Requires: ffmpeg
+Requires: libcurl, fontconfig, freetype, openssl, glibc, libicu, at, sudo
+
+%description server
+The Jellyfin media server backend.
+
+%prep
+%autosetup -n jellyfin-server-%{version} -b 0
+
+%build
+
+%install
+export DOTNET_CLI_TELEMETRY_OPTOUT=1
+export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
+dotnet publish --configuration Release --output='%{buildroot}%{_libdir}/jellyfin' --self-contained --runtime %{dotnet_runtime} \
+ "-p:DebugSymbols=false;DebugType=none" Jellyfin.Server
+%{__install} -D -m 0644 LICENSE %{buildroot}%{_datadir}/licenses/jellyfin/LICENSE
+%{__install} -D -m 0644 %{SOURCE15} %{buildroot}%{_sysconfdir}/systemd/system/jellyfin.service.d/override.conf
+%{__install} -D -m 0644 Jellyfin.Server/Resources/Configuration/logging.json %{buildroot}%{_sysconfdir}/jellyfin/logging.json
+%{__mkdir} -p %{buildroot}%{_bindir}
+tee %{buildroot}%{_bindir}/jellyfin << EOF
+#!/bin/sh
+exec %{_libdir}/jellyfin/jellyfin \${@}
+EOF
+%{__mkdir} -p %{buildroot}%{_sharedstatedir}/jellyfin
+%{__mkdir} -p %{buildroot}%{_sysconfdir}/jellyfin
+%{__mkdir} -p %{buildroot}%{_var}/log/jellyfin
+%{__mkdir} -p %{buildroot}%{_var}/cache/jellyfin
+
+%{__install} -D -m 0644 %{SOURCE11} %{buildroot}%{_unitdir}/jellyfin.service
+%{__install} -D -m 0644 %{SOURCE12} %{buildroot}%{_sysconfdir}/sysconfig/jellyfin
+%{__install} -D -m 0600 %{SOURCE13} %{buildroot}%{_sysconfdir}/sudoers.d/jellyfin-sudoers
+%{__install} -D -m 0755 %{SOURCE14} %{buildroot}%{_libexecdir}/jellyfin/restart.sh
+%{__install} -D -m 0644 %{SOURCE16} %{buildroot}%{_prefix}/lib/firewalld/services/jellyfin.xml
+
+%files
+# empty as this is just a meta-package
+
+%files server
+%attr(755,root,root) %{_bindir}/jellyfin
+%{_libdir}/jellyfin/*
+# Needs 755 else only root can run it since binary build by dotnet is 722
+%attr(755,root,root) %{_libdir}/jellyfin/jellyfin
+%{_unitdir}/jellyfin.service
+%{_libexecdir}/jellyfin/restart.sh
+%{_prefix}/lib/firewalld/services/jellyfin.xml
+%attr(755,jellyfin,jellyfin) %dir %{_sysconfdir}/jellyfin
+%config %{_sysconfdir}/sysconfig/jellyfin
+%config(noreplace) %attr(600,root,root) %{_sysconfdir}/sudoers.d/jellyfin-sudoers
+%config(noreplace) %{_sysconfdir}/systemd/system/jellyfin.service.d/override.conf
+%config(noreplace) %attr(644,jellyfin,jellyfin) %{_sysconfdir}/jellyfin/logging.json
+%attr(750,jellyfin,jellyfin) %dir %{_sharedstatedir}/jellyfin
+%attr(-,jellyfin,jellyfin) %dir %{_var}/log/jellyfin
+%attr(750,jellyfin,jellyfin) %dir %{_var}/cache/jellyfin
+%{_datadir}/licenses/jellyfin/LICENSE
+
+%pre server
+getent group jellyfin >/dev/null || groupadd -r jellyfin
+getent passwd jellyfin >/dev/null || \
+ useradd -r -g jellyfin -d %{_sharedstatedir}/jellyfin -s /sbin/nologin \
+ -c "Jellyfin default user" jellyfin
+exit 0
+
+%post server
+# Move existing configuration cache and logs to their new locations and symlink them.
+if [ $1 -gt 1 ] ; then
+ service_state=$(systemctl is-active jellyfin.service)
+ if [ "${service_state}" = "active" ]; then
+ systemctl stop jellyfin.service
+ fi
+ if [ ! -L %{_sharedstatedir}/jellyfin/config ]; then
+ mv %{_sharedstatedir}/jellyfin/config/* %{_sysconfdir}/jellyfin/
+ rmdir %{_sharedstatedir}/jellyfin/config
+ ln -sf %{_sysconfdir}/jellyfin %{_sharedstatedir}/jellyfin/config
+ fi
+ if [ ! -L %{_sharedstatedir}/jellyfin/logs ]; then
+ mv %{_sharedstatedir}/jellyfin/logs/* %{_var}/log/jellyfin
+ rmdir %{_sharedstatedir}/jellyfin/logs
+ ln -sf %{_var}/log/jellyfin %{_sharedstatedir}/jellyfin/logs
+ fi
+ if [ ! -L %{_sharedstatedir}/jellyfin/cache ]; then
+ mv %{_sharedstatedir}/jellyfin/cache/* %{_var}/cache/jellyfin
+ rmdir %{_sharedstatedir}/jellyfin/cache
+ ln -sf %{_var}/cache/jellyfin %{_sharedstatedir}/jellyfin/cache
+ fi
+ if [ "${service_state}" = "active" ]; then
+ systemctl start jellyfin.service
+ fi
+fi
+%systemd_post jellyfin.service
+
+%preun server
+%systemd_preun jellyfin.service
+
+%postun server
+%systemd_postun_with_restart jellyfin.service
+
+%changelog
+* Fri Dec 04 2020 Jellyfin Packaging Team <packaging@jellyfin.org>
+- Forthcoming stable release
+* Mon Jul 27 2020 Jellyfin Packaging Team <packaging@jellyfin.org>
+- Forthcoming stable release
+* Mon Mar 23 2020 Jellyfin Packaging Team <packaging@jellyfin.org>
+- Forthcoming stable release
+* Fri Oct 11 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.5.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.5.0
+* Sat Aug 31 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.4.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.4.0
+* Wed Jul 24 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.7; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.7
+* Sat Jul 06 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.6; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.6
+* Sun Jun 09 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.5; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.5
+* Thu Jun 06 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.4; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.4
+* Fri May 17 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.3; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.3
+* Tue Apr 30 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.2; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.2
+* Sat Apr 20 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.1; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.1
+* Fri Apr 19 2019 Jellyfin Packaging Team <packaging@jellyfin.org>
+- New upstream version 10.3.0; release changelog at https://github.com/jellyfin/jellyfin/releases/tag/v10.3.0
diff --git a/deployment/fedora-package-x64/pkg-src/jellyfin.sudoers b/fedora/jellyfin.sudoers
index dd245af4b..57a9e7b67 100644
--- a/deployment/fedora-package-x64/pkg-src/jellyfin.sudoers
+++ b/fedora/jellyfin.sudoers
@@ -1,8 +1,7 @@
# Allow jellyfin group to start, stop and restart itself
-Cmnd_Alias RESTARTSERVER_SYSTEMD = /usr/bin/systemctl restart jellyfin, /bin/systemctl restart jellyfin
-Cmnd_Alias STARTSERVER_SYSTEMD = /usr/bin/systemctl start jellyfin, /bin/systemctl start jellyfin
-Cmnd_Alias STOPSERVER_SYSTEMD = /usr/bin/systemctl stop jellyfin, /bin/systemctl stop jellyfin
-
+Cmnd_Alias RESTARTSERVER_SYSTEMD = /usr/bin/systemd-run systemctl restart jellyfin
+Cmnd_Alias STARTSERVER_SYSTEMD = /usr/bin/systemd-run systemctl start jellyfin
+Cmnd_Alias STOPSERVER_SYSTEMD = /usr/bin/systemd-run systemctl stop jellyfin
jellyfin ALL=(ALL) NOPASSWD: RESTARTSERVER_SYSTEMD
jellyfin ALL=(ALL) NOPASSWD: STARTSERVER_SYSTEMD
diff --git a/fedora/restart.sh b/fedora/restart.sh
new file mode 100755
index 000000000..4847b918b
--- /dev/null
+++ b/fedora/restart.sh
@@ -0,0 +1,56 @@
+#!/bin/bash
+
+# restart.sh - Jellyfin server restart script
+# Part of the Jellyfin project (https://github.com/jellyfin)
+#
+# This script restarts the Jellyfin daemon on Linux when using
+# the Restart button on the admin dashboard. It supports the
+# systemctl, service, and traditional /etc/init.d (sysv) restart
+# methods, chosen automatically by which one is found first (in
+# that order).
+#
+# This script is used by the Debian/Ubuntu/Fedora/CentOS packages.
+
+# This is the Right Way(tm) to check if we are booted with
+# systemd, according to sd_booted(3)
+if [ -d /run/systemd/system ]; then
+ cmd=systemctl
+else
+ # Everything else is really hard to figure out, so we just use
+ # service(8) if it's available - that works with most init
+ # systems/distributions I know of, including FreeBSD
+ if type service >/dev/null 2>&1; then
+ cmd=service
+ else
+ # If even service(8) isn't available, we just try /etc/init.d
+ # and hope for the best
+ if [ -d /etc/init.d ]; then
+ cmd=sysv
+ else
+ echo "Unable to detect a way to restart Jellyfin; bailing out" 1>&2
+ echo "Please report this bug to https://github.com/jellyfin/jellyfin/issues" 1>&2
+ exit 1
+ fi
+ fi
+fi
+
+if type sudo >/dev/null 2>&1; then
+ sudo_command=sudo
+else
+ sudo_command=
+fi
+
+echo "Detected service control platform '$cmd'; using it to restart Jellyfin..."
+case $cmd in
+ 'systemctl')
+ # Without systemd-run here, `jellyfin.service`'s shutdown terminates this process too
+ $sudo_command systemd-run systemctl restart jellyfin
+ ;;
+ 'service')
+ echo "sleep 0.5; $sudo_command service jellyfin start" | at now
+ ;;
+ 'sysv')
+ echo "sleep 0.5; /usr/bin/sudo /etc/init.d/jellyfin start" | at now
+ ;;
+esac
+exit 0
diff --git a/fuzz/.gitignore b/fuzz/.gitignore
new file mode 100644
index 000000000..652de0a45
--- /dev/null
+++ b/fuzz/.gitignore
@@ -0,0 +1 @@
+Findings
diff --git a/fuzz/Emby.Server.Implementations.Fuzz/Emby.Server.Implementations.Fuzz.csproj b/fuzz/Emby.Server.Implementations.Fuzz/Emby.Server.Implementations.Fuzz.csproj
new file mode 100644
index 000000000..6abdb7734
--- /dev/null
+++ b/fuzz/Emby.Server.Implementations.Fuzz/Emby.Server.Implementations.Fuzz.csproj
@@ -0,0 +1,25 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net5.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Reference Include="Emby.Server.Implementations">
+ <HintPath>Emby.Server.Implementations.dll</HintPath>
+ </Reference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Controller/MediaBrowser.Controller.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="SharpFuzz" Version="1.6.2" />
+ </ItemGroup>
+
+</Project>
diff --git a/fuzz/Emby.Server.Implementations.Fuzz/Program.cs b/fuzz/Emby.Server.Implementations.Fuzz/Program.cs
new file mode 100644
index 000000000..03b296494
--- /dev/null
+++ b/fuzz/Emby.Server.Implementations.Fuzz/Program.cs
@@ -0,0 +1,62 @@
+using System;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.Data;
+using Emby.Server.Implementations.Library;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Entities;
+using Moq;
+using SharpFuzz;
+
+namespace Emby.Server.Implementations.Fuzz
+{
+ public static class Program
+ {
+ public static void Main(string[] args)
+ {
+ switch (args[0])
+ {
+ case "PathExtensions.TryReplaceSubPath": Run(PathExtensions_TryReplaceSubPath); return;
+ case "SqliteItemRepository.ItemImageInfoFromValueString": Run(SqliteItemRepository_ItemImageInfoFromValueString); return;
+ default: throw new ArgumentException($"Unknown fuzzing function: {args[0]}");
+ }
+ }
+
+ private static void Run(Action<string> action) => Fuzzer.OutOfProcess.Run(action);
+
+ private static void PathExtensions_TryReplaceSubPath(string data)
+ {
+ // Stupid, but it worked
+ var parts = data.Split(':');
+ if (parts.Length != 3)
+ {
+ return;
+ }
+
+ _ = PathExtensions.TryReplaceSubPath(parts[0], parts[1], parts[2], out _);
+ }
+
+ private static void SqliteItemRepository_ItemImageInfoFromValueString(string data)
+ {
+ var sqliteItemRepository = MockSqliteItemRepository();
+ sqliteItemRepository.ItemImageInfoFromValueString(data);
+ }
+
+ private static SqliteItemRepository MockSqliteItemRepository()
+ {
+ const string VirtualMetaDataPath = "%MetadataPath%";
+ const string MetaDataPath = "/meta/data/path";
+
+ var appHost = new Mock<IServerApplicationHost>();
+ appHost.Setup(x => x.ExpandVirtualPath(It.IsAny<string>()))
+ .Returns((string x) => x.Replace(VirtualMetaDataPath, MetaDataPath, StringComparison.Ordinal));
+ appHost.Setup(x => x.ReverseVirtualPath(It.IsAny<string>()))
+ .Returns((string x) => x.Replace(MetaDataPath, VirtualMetaDataPath, StringComparison.Ordinal));
+
+ IFixture fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
+ fixture.Inject(appHost);
+ return fixture.Create<SqliteItemRepository>();
+ }
+ }
+}
diff --git a/fuzz/Emby.Server.Implementations.Fuzz/Testcases/PathExtensions.TryReplaceSubPath/test1.txt b/fuzz/Emby.Server.Implementations.Fuzz/Testcases/PathExtensions.TryReplaceSubPath/test1.txt
new file mode 100644
index 000000000..aacf973d6
--- /dev/null
+++ b/fuzz/Emby.Server.Implementations.Fuzz/Testcases/PathExtensions.TryReplaceSubPath/test1.txt
@@ -0,0 +1 @@
+/fuzz/Emby.Server.Implementations.Fuzz/Testcases/PathExtensions.TryReplaceSubPath/test1.txt/:/home/bond/dev/jellyfin/:/srv/jellyfin/
diff --git a/fuzz/Emby.Server.Implementations.Fuzz/Testcases/SqliteItemRepository.ItemImageInfoFromValueString/test1.txt b/fuzz/Emby.Server.Implementations.Fuzz/Testcases/SqliteItemRepository.ItemImageInfoFromValueString/test1.txt
new file mode 100644
index 000000000..1b0115882
--- /dev/null
+++ b/fuzz/Emby.Server.Implementations.Fuzz/Testcases/SqliteItemRepository.ItemImageInfoFromValueString/test1.txt
@@ -0,0 +1 @@
+/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN
diff --git a/fuzz/Emby.Server.Implementations.Fuzz/fuzz.sh b/fuzz/Emby.Server.Implementations.Fuzz/fuzz.sh
new file mode 100755
index 000000000..244f73402
--- /dev/null
+++ b/fuzz/Emby.Server.Implementations.Fuzz/fuzz.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+set -e
+
+dotnet build -c Release ../../Emby.Server.Implementations/Emby.Server.Implementations.csproj --output bin
+sharpfuzz bin/Emby.Server.Implementations.dll
+cp bin/Emby.Server.Implementations.dll .
+
+dotnet build
+mkdir -p Findings
+AFL_SKIP_BIN_CHECK=1 afl-fuzz -i "Testcases/$1" -o "Findings/$1" -t 5000 -m 10240 dotnet bin/Debug/net5.0/Emby.Server.Implementations.Fuzz.dll "$1"
diff --git a/fuzz/Jellyfin.Server.Fuzz/Jellyfin.Server.Fuzz.csproj b/fuzz/Jellyfin.Server.Fuzz/Jellyfin.Server.Fuzz.csproj
new file mode 100644
index 000000000..6fcfbae0e
--- /dev/null
+++ b/fuzz/Jellyfin.Server.Fuzz/Jellyfin.Server.Fuzz.csproj
@@ -0,0 +1,22 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net5.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Reference Include="Jellyfin.Server">
+ <HintPath>jellyfin.dll</HintPath>
+ </Reference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="SharpFuzz" Version="1.6.2" />
+ </ItemGroup>
+
+</Project>
diff --git a/fuzz/Jellyfin.Server.Fuzz/Program.cs b/fuzz/Jellyfin.Server.Fuzz/Program.cs
new file mode 100644
index 000000000..e47286c13
--- /dev/null
+++ b/fuzz/Jellyfin.Server.Fuzz/Program.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using Jellyfin.Server.Middleware;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
+using Microsoft.Extensions.Primitives;
+using SharpFuzz;
+
+namespace Emby.Server.Implementations.Fuzz
+{
+ public static class Program
+ {
+ public static void Main(string[] args)
+ {
+ switch (args[0])
+ {
+ case "UrlDecodeQueryFeature": Run(UrlDecodeQueryFeature); return;
+ default: throw new ArgumentException($"Unknown fuzzing function: {args[0]}");
+ }
+ }
+
+ private static void Run(Action<string> action) => Fuzzer.OutOfProcess.Run(action);
+
+ private static void UrlDecodeQueryFeature(string data)
+ {
+ var dict = new Dictionary<string, StringValues>
+ {
+ { data, StringValues.Empty }
+ };
+ _ = new UrlDecodeQueryFeature(new QueryFeature(new QueryCollection(dict)));
+ }
+ }
+}
diff --git a/fuzz/Jellyfin.Server.Fuzz/Testcases/UrlDecodeQueryFeature/test1.txt b/fuzz/Jellyfin.Server.Fuzz/Testcases/UrlDecodeQueryFeature/test1.txt
new file mode 100644
index 000000000..73f356b93
--- /dev/null
+++ b/fuzz/Jellyfin.Server.Fuzz/Testcases/UrlDecodeQueryFeature/test1.txt
@@ -0,0 +1 @@
+a%3D1%26b%3D2%26c%3D3
diff --git a/fuzz/Jellyfin.Server.Fuzz/fuzz.sh b/fuzz/Jellyfin.Server.Fuzz/fuzz.sh
new file mode 100755
index 000000000..ad81e2c35
--- /dev/null
+++ b/fuzz/Jellyfin.Server.Fuzz/fuzz.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+set -e
+
+dotnet build -c Release ../../Jellyfin.Server/Jellyfin.Server.csproj --output bin
+sharpfuzz bin/jellyfin.dll
+cp bin/jellyfin.dll .
+
+dotnet build
+mkdir -p Findings
+AFL_SKIP_BIN_CHECK=1 afl-fuzz -i "Testcases/$1" -o "Findings/$1" -t 5000 -m 10240 dotnet bin/Debug/net5.0/Jellyfin.Server.Fuzz.dll "$1"
diff --git a/hooks/pre_build b/hooks/pre_build
deleted file mode 100644
index 2fd6136c5..000000000
--- a/hooks/pre_build
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/bash
-git submodule update --init --recursive
-
-# Register qemu-*-static for all supported processors except the
-# current one, but also remove all registered binfmt_misc before
-docker run --rm --privileged multiarch/qemu-user-static:register --reset
diff --git a/jellyfin.ruleset b/jellyfin.ruleset
index 4381349ca..dfb991170 100644
--- a/jellyfin.ruleset
+++ b/jellyfin.ruleset
@@ -1,21 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for Jellyfin.Server" Description="Code analysis rules for Jellyfin.Server.csproj" ToolsVersion="14.0">
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
+ <!-- disable warning SA1009: Closing parenthesis should be followed by a space. -->
+ <Rule Id="SA1009" Action="None" />
+ <!-- disable warning SA1011: Closing square bracket should be followed by a space. -->
+ <Rule Id="SA1011" Action="None" />
<!-- disable warning SA1101: Prefix local calls with 'this.' -->
<Rule Id="SA1101" Action="None" />
+ <!-- disable warning SA1108: Block statements should not contain embedded comments -->
+ <Rule Id="SA1108" Action="None" />
+ <!-- disable warning SA1118: Parameter must not span multiple lines. -->
+ <Rule Id="SA1118" Action="None" />
+ <!-- disable warning SA1128:: Put constructor initializers on their own line -->
+ <Rule Id="SA1128" Action="None" />
<!-- disable warning SA1130: Use lambda syntax -->
<Rule Id="SA1130" Action="None" />
<!-- disable warning SA1200: 'using' directive must appear within a namespace declaration -->
<Rule Id="SA1200" Action="None" />
+ <!-- disable warning SA1202: 'public' members must come before 'private' members -->
+ <Rule Id="SA1202" Action="None" />
+ <!-- disable warning SA1204: Static members must appear before non-static members -->
+ <Rule Id="SA1204" Action="None" />
<!-- disable warning SA1309: Fields must not begin with an underscore -->
<Rule Id="SA1309" Action="None" />
+ <!-- disable warning SA1413: Use trailing comma in multi-line initializers -->
+ <Rule Id="SA1413" Action="None" />
<!-- disable warning SA1512: Single-line comments must not be followed by blank line -->
<Rule Id="SA1512" Action="None" />
+ <!-- disable warning SA1515: Single-line comment should be preceded by blank line -->
+ <Rule Id="SA1515" Action="None" />
+ <!-- disable warning SA1600: Elements should be documented -->
+ <Rule Id="SA1600" Action="None" />
+ <!-- disable warning SA1602: Enumeration items should be documented -->
+ <Rule Id="SA1602" Action="None" />
<!-- disable warning SA1633: The file header is missing or not located at the top of the file -->
<Rule Id="SA1633" Action="None" />
</Rules>
- <Rules AnalyzerId="Microsoft.CodeAnalysis.FxCopAnalyzers" RuleNamespace="Microsoft.Design">
+
+ <Rules AnalyzerId="Microsoft.CodeAnalysis.NetAnalyzers" RuleNamespace="Microsoft.Design">
+ <!-- error on CA1305: Specify IFormatProvider -->
+ <Rule Id="CA1305" Action="Error" />
+ <!-- error on CA1725: Parameter names should match base declaration -->
+ <Rule Id="CA1725" Action="Error" />
+ <!-- error on CA2016: Forward the CancellationToken parameter to methods that take one
+ or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token -->
+ <Rule Id="CA2016" Action="Error" />
+
+ <!-- disable warning CA1014: Mark assemblies with CLSCompliantAttribute -->
+ <Rule Id="CA1014" Action="Info" />
+ <!-- disable warning CA1024: Use properties where appropriate -->
+ <Rule Id="CA1024" Action="Info" />
+ <!-- disable warning CA1031: Do not catch general exception types -->
+ <Rule Id="CA1031" Action="Info" />
+ <!-- disable warning CA1032: Implement standard exception constructors -->
+ <Rule Id="CA1032" Action="Info" />
+ <!-- disable warning CA1040: Avoid empty interfaces -->
+ <Rule Id="CA1040" Action="Info" />
+ <!-- disable warning CA1062: Validate arguments of public methods -->
+ <Rule Id="CA1062" Action="Info" />
+ <!-- TODO: enable when false positives are fixed -->
+ <!-- disable warning CA1508: Avoid dead conditional code -->
+ <Rule Id="CA1508" Action="Info" />
+ <!-- disable warning CA1716: Identifiers should not match keywords -->
+ <Rule Id="CA1716" Action="Info" />
+ <!-- disable warning CA1720: Identifiers should not contain type names -->
+ <Rule Id="CA1720" Action="Info" />
+ <!-- disable warning CA1724: Type names should not match namespaces -->
+ <Rule Id="CA1724" Action="Info" />
+ <!-- disable warning CA1805: Do not initialize unnecessarily -->
+ <Rule Id="CA1805" Action="Info" />
+ <!-- disable warning CA1812: internal class that is apparently never instantiated.
+ If so, remove the code from the assembly.
+ If this class is intended to contain only static members, make it static -->
+ <Rule Id="CA1812" Action="Info" />
+ <!-- disable warning CA1822: Member does not access instance data and can be marked as static -->
+ <Rule Id="CA1822" Action="Info" />
+ <!-- disable warning CA2000: Dispose objects before losing scope -->
+ <Rule Id="CA2000" Action="Info" />
+ <!-- disable warning CA5394: Do not use insecure randomness -->
+ <Rule Id="CA5394" Action="Info" />
+
<!-- disable warning CA1054: Change the type of parameter url from string to System.Uri -->
<Rule Id="CA1054" Action="None" />
+ <!-- disable warning CA1055: URI return values should not be strings -->
+ <Rule Id="CA1055" Action="None" />
+ <!-- disable warning CA1056: URI properties should not be strings -->
+ <Rule Id="CA1056" Action="None" />
+ <!-- disable warning CA1303: Do not pass literals as localized parameters -->
+ <Rule Id="CA1303" Action="None" />
+ <!-- disable warning CA1308: Normalize strings to uppercase -->
+ <Rule Id="CA1308" Action="None" />
+ <!-- disable warning CA2101: Specify marshaling for P/Invoke string arguments -->
+ <Rule Id="CA2101" Action="None" />
+ <!-- disable warning CA2234: Pass System.Uri objects instead of strings -->
+ <Rule Id="CA2234" Action="None" />
</Rules>
</RuleSet>
diff --git a/new-file-header.txt b/new-file-header.txt
deleted file mode 100644
index 4247a8e24..000000000
--- a/new-file-header.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-### This header should be used to start new files.
-### It provides an explicit per-file license reference that should be present on all new files.
-### To use this header, delete these lines and the following empty line, modify <filename> to
-### the proper full path, and then add new code following the header and a single empty line.
-
-// <filename>
-// Part of the Jellyfin project (https://jellyfin.media)
-//
-// All copyright belongs to the Jellyfin contributors; a full list can
-// be found in the file CONTRIBUTORS.md
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, version 2.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/nuget.config b/nuget.config
new file mode 100644
index 000000000..326331f32
--- /dev/null
+++ b/nuget.config
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+ <packageSources>
+ <add key="NuGet official package source" value="https://api.nuget.org/v3/index.json" />
+ </packageSources>
+</configuration>
diff --git a/src/Jellyfin.Extensions/AlphanumericComparator.cs b/src/Jellyfin.Extensions/AlphanumericComparator.cs
new file mode 100644
index 000000000..e3c81eba8
--- /dev/null
+++ b/src/Jellyfin.Extensions/AlphanumericComparator.cs
@@ -0,0 +1,144 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Alphanumeric <see cref="IComparer{T}" />.
+ /// </summary>
+ public class AlphanumericComparator : IComparer<string?>
+ {
+ /// <summary>
+ /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
+ /// </summary>
+ /// <param name="s1">The first object to compare.</param>
+ /// <param name="s2">The second object to compare.</param>
+ /// <returns>A signed integer that indicates the relative values of <c>x</c> and <c>y</c>.</returns>
+ public static int CompareValues(string? s1, string? s2)
+ {
+ if (s1 == null && s2 == null)
+ {
+ return 0;
+ }
+ else if (s1 == null)
+ {
+ return -1;
+ }
+ else if (s2 == null)
+ {
+ return 1;
+ }
+
+ int len1 = s1.Length;
+ int len2 = s2.Length;
+
+ // Early return for empty strings
+ if (len1 == 0 && len2 == 0)
+ {
+ return 0;
+ }
+ else if (len1 == 0)
+ {
+ return -1;
+ }
+ else if (len2 == 0)
+ {
+ return 1;
+ }
+
+ int pos1 = 0;
+ int pos2 = 0;
+
+ do
+ {
+ int start1 = pos1;
+ int start2 = pos2;
+
+ bool isNum1 = char.IsDigit(s1[pos1++]);
+ bool isNum2 = char.IsDigit(s2[pos2++]);
+
+ while (pos1 < len1 && char.IsDigit(s1[pos1]) == isNum1)
+ {
+ pos1++;
+ }
+
+ while (pos2 < len2 && char.IsDigit(s2[pos2]) == isNum2)
+ {
+ pos2++;
+ }
+
+ var span1 = s1.AsSpan(start1, pos1 - start1);
+ var span2 = s2.AsSpan(start2, pos2 - start2);
+
+ if (isNum1 && isNum2)
+ {
+ // Trim leading zeros so we can compare the length
+ // of the strings to find the largest number
+ span1 = span1.TrimStart('0');
+ span2 = span2.TrimStart('0');
+ var span1Len = span1.Length;
+ var span2Len = span2.Length;
+ if (span1Len < span2Len)
+ {
+ return -1;
+ }
+ else if (span1Len > span2Len)
+ {
+ return 1;
+ }
+ else if (span1Len >= 20) // Number is probably too big for a ulong
+ {
+ // Trim all the first digits that are the same
+ int i = 0;
+ while (i < span1Len && span1[i] == span2[i])
+ {
+ i++;
+ }
+
+ // If there are no more digits it's the same number
+ if (i == span1Len)
+ {
+ continue;
+ }
+
+ // Only need to compare the most significant digit
+ span1 = span1.Slice(i, 1);
+ span2 = span2.Slice(i, 1);
+ }
+
+ if (!ulong.TryParse(span1, out var num1)
+ || !ulong.TryParse(span2, out var num2))
+ {
+ return 0;
+ }
+ else if (num1 < num2)
+ {
+ return -1;
+ }
+ else if (num1 > num2)
+ {
+ return 1;
+ }
+ }
+ else
+ {
+ int result = span1.CompareTo(span2, StringComparison.InvariantCulture);
+ if (result != 0)
+ {
+ return result;
+ }
+ }
+#pragma warning disable SA1500 // TODO remove with StyleCop.Analyzers v1.2.0 https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/3196
+ } while (pos1 < len1 && pos2 < len2);
+#pragma warning restore SA1500
+
+ return len1 - len2;
+ }
+
+ /// <inheritdoc />
+ public int Compare(string? x, string? y)
+ {
+ return CompareValues(x, y);
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/CopyToExtensions.cs b/src/Jellyfin.Extensions/CopyToExtensions.cs
new file mode 100644
index 000000000..72d37b5b6
--- /dev/null
+++ b/src/Jellyfin.Extensions/CopyToExtensions.cs
@@ -0,0 +1,26 @@
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Provides <c>CopyTo</c> extensions methods for <see cref="IReadOnlyList{T}" />.
+ /// </summary>
+ public static class CopyToExtensions
+ {
+ /// <summary>
+ /// Copies all the elements of the current collection to the specified list
+ /// starting at the specified destination array index. The index is specified as a 32-bit integer.
+ /// </summary>
+ /// <param name="source">The current collection that is the source of the elements.</param>
+ /// <param name="destination">The list that is the destination of the elements copied from the current collection.</param>
+ /// <param name="index">A 32-bit integer that represents the index in <c>destination</c> at which copying begins.</param>
+ /// <typeparam name="T">The type of the array.</typeparam>
+ public static void CopyTo<T>(this IReadOnlyList<T> source, IList<T> destination, int index = 0)
+ {
+ for (int i = 0; i < source.Count; i++)
+ {
+ destination[index + i] = source[i];
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/DictionaryExtensions.cs b/src/Jellyfin.Extensions/DictionaryExtensions.cs
new file mode 100644
index 000000000..5bb828d01
--- /dev/null
+++ b/src/Jellyfin.Extensions/DictionaryExtensions.cs
@@ -0,0 +1,64 @@
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Static extensions for the <see cref="IReadOnlyDictionary{TKey,TValue}"/> interface.
+ /// </summary>
+ public static class DictionaryExtensions
+ {
+ /// <summary>
+ /// Gets a string from a string dictionary, checking all keys sequentially,
+ /// stopping at the first key that returns a result that's neither null nor blank.
+ /// </summary>
+ /// <param name="dictionary">The dictionary.</param>
+ /// <param name="key1">The first checked key.</param>
+ /// <returns>System.String.</returns>
+ public static string? GetFirstNotNullNorWhiteSpaceValue(this IReadOnlyDictionary<string, string> dictionary, string key1)
+ {
+ return dictionary.GetFirstNotNullNorWhiteSpaceValue(key1, string.Empty, string.Empty);
+ }
+
+ /// <summary>
+ /// Gets a string from a string dictionary, checking all keys sequentially,
+ /// stopping at the first key that returns a result that's neither null nor blank.
+ /// </summary>
+ /// <param name="dictionary">The dictionary.</param>
+ /// <param name="key1">The first checked key.</param>
+ /// <param name="key2">The second checked key.</param>
+ /// <returns>System.String.</returns>
+ public static string? GetFirstNotNullNorWhiteSpaceValue(this IReadOnlyDictionary<string, string> dictionary, string key1, string key2)
+ {
+ return dictionary.GetFirstNotNullNorWhiteSpaceValue(key1, key2, string.Empty);
+ }
+
+ /// <summary>
+ /// Gets a string from a string dictionary, checking all keys sequentially,
+ /// stopping at the first key that returns a result that's neither null nor blank.
+ /// </summary>
+ /// <param name="dictionary">The dictionary.</param>
+ /// <param name="key1">The first checked key.</param>
+ /// <param name="key2">The second checked key.</param>
+ /// <param name="key3">The third checked key.</param>
+ /// <returns>System.String.</returns>
+ public static string? GetFirstNotNullNorWhiteSpaceValue(this IReadOnlyDictionary<string, string> dictionary, string key1, string key2, string key3)
+ {
+ if (dictionary.TryGetValue(key1, out var val) && !string.IsNullOrWhiteSpace(val))
+ {
+ return val;
+ }
+
+ if (!string.IsNullOrEmpty(key2) && dictionary.TryGetValue(key2, out val) && !string.IsNullOrWhiteSpace(val))
+ {
+ return val;
+ }
+
+ if (!string.IsNullOrEmpty(key3) && dictionary.TryGetValue(key3, out val) && !string.IsNullOrWhiteSpace(val))
+ {
+ return val;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/EnumerableExtensions.cs b/src/Jellyfin.Extensions/EnumerableExtensions.cs
new file mode 100644
index 000000000..b5fe93357
--- /dev/null
+++ b/src/Jellyfin.Extensions/EnumerableExtensions.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Static extensions for the <see cref="IEnumerable{T}"/> interface.
+ /// </summary>
+ public static class EnumerableExtensions
+ {
+ /// <summary>
+ /// Determines whether the value is contained in the source collection.
+ /// </summary>
+ /// <param name="source">An instance of the <see cref="IEnumerable{String}"/> interface.</param>
+ /// <param name="value">The value to look for in the collection.</param>
+ /// <param name="stringComparison">The string comparison.</param>
+ /// <returns>A value indicating whether the value is contained in the collection.</returns>
+ /// <exception cref="ArgumentNullException">The source is null.</exception>
+ public static bool Contains(this IEnumerable<string> source, ReadOnlySpan<char> value, StringComparison stringComparison)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (source is IList<string> list)
+ {
+ int len = list.Count;
+ for (int i = 0; i < len; i++)
+ {
+ if (value.Equals(list[i], stringComparison))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ foreach (string element in source)
+ {
+ if (value.Equals(element, stringComparison))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Jellyfin.Extensions.csproj b/src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
new file mode 100644
index 000000000..3d9538d1b
--- /dev/null
+++ b/src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
@@ -0,0 +1,37 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <PublishRepositoryUrl>true</PublishRepositoryUrl>
+ <EmbedUntrackedSources>true</EmbedUntrackedSources>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <Authors>Jellyfin Contributors</Authors>
+ <PackageId>Jellyfin.Extensions</PackageId>
+ <VersionPrefix>10.8.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>
+ <Compile Include="../../SharedVersion.cs" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup>
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+</Project>
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonBoolNumberConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonBoolNumberConverter.cs
new file mode 100644
index 000000000..c2543cf7c
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonBoolNumberConverter.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a number to a boolean.
+ /// This is needed for HDHomerun.
+ /// </summary>
+ public class JsonBoolNumberConverter : JsonConverter<bool>
+ {
+ /// <inheritdoc />
+ public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.Number)
+ {
+ return Convert.ToBoolean(reader.GetInt32());
+ }
+
+ return reader.GetBoolean();
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
+ {
+ writer.WriteBooleanValue(value);
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverter.cs
new file mode 100644
index 000000000..0d0cc2d06
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverter.cs
@@ -0,0 +1,19 @@
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Convert comma delimited string to array of type.
+ /// </summary>
+ /// <typeparam name="T">Type to convert to.</typeparam>
+ public sealed class JsonCommaDelimitedArrayConverter<T> : JsonDelimitedArrayConverter<T>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonCommaDelimitedArrayConverter{T}"/> class.
+ /// </summary>
+ public JsonCommaDelimitedArrayConverter() : base()
+ {
+ }
+
+ /// <inheritdoc />
+ protected override char Delimiter => ',';
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs b/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs
new file mode 100644
index 000000000..cc9311a24
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Json comma delimited array converter factory.
+ /// </summary>
+ /// <remarks>
+ /// This must be applied as an attribute, adding to the JsonConverter list causes stack overflow.
+ /// </remarks>
+ public class JsonCommaDelimitedArrayConverterFactory : JsonConverterFactory
+ {
+ /// <inheritdoc />
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return true;
+ }
+
+ /// <inheritdoc />
+ public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0];
+ return (JsonConverter?)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType));
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonDateTimeConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonDateTimeConverter.cs
new file mode 100644
index 000000000..8ae080b15
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonDateTimeConverter.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Legacy DateTime converter.
+ /// Milliseconds aren't output if zero by default.
+ /// </summary>
+ public class JsonDateTimeConverter : JsonConverter<DateTime>
+ {
+ /// <inheritdoc />
+ public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ return reader.GetDateTime();
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
+ {
+ if (value.Millisecond == 0)
+ {
+ // Remaining ticks value will be 0, manually format.
+ writer.WriteStringValue(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffZ", CultureInfo.InvariantCulture));
+ }
+ else
+ {
+ writer.WriteStringValue(value);
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonDelimitedArrayConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonDelimitedArrayConverter.cs
new file mode 100644
index 000000000..51b955145
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonDelimitedArrayConverter.cs
@@ -0,0 +1,81 @@
+using System;
+using System.ComponentModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Convert delimited string to array of type.
+ /// </summary>
+ /// <typeparam name="T">Type to convert to.</typeparam>
+ public abstract class JsonDelimitedArrayConverter<T> : JsonConverter<T[]?>
+ {
+ private readonly TypeConverter _typeConverter;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonDelimitedArrayConverter{T}"/> class.
+ /// </summary>
+ protected JsonDelimitedArrayConverter()
+ {
+ _typeConverter = TypeDescriptor.GetConverter(typeof(T));
+ }
+
+ /// <summary>
+ /// Gets the array delimiter.
+ /// </summary>
+ protected virtual char Delimiter { get; }
+
+ /// <inheritdoc />
+ public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ // GetString can't return null here because we already handled it above
+ var stringEntries = reader.GetString()?.Split(Delimiter, StringSplitOptions.RemoveEmptyEntries);
+ if (stringEntries == null || stringEntries.Length == 0)
+ {
+ return Array.Empty<T>();
+ }
+
+ var parsedValues = new object[stringEntries.Length];
+ var convertedCount = 0;
+ for (var i = 0; i < stringEntries.Length; i++)
+ {
+ try
+ {
+ parsedValues[i] = _typeConverter.ConvertFromInvariantString(stringEntries[i].Trim()) ?? throw new FormatException();
+ convertedCount++;
+ }
+ catch (FormatException)
+ {
+ // TODO log when upgraded to .Net6
+ // https://github.com/dotnet/runtime/issues/42975
+ // _logger.LogDebug(e, "Error converting value.");
+ }
+ }
+
+ var typedValues = new T[convertedCount];
+ var typedValueIndex = 0;
+ for (var i = 0; i < stringEntries.Length; i++)
+ {
+ if (parsedValues[i] != null)
+ {
+ typedValues.SetValue(parsedValues[i], typedValueIndex);
+ typedValueIndex++;
+ }
+ }
+
+ return typedValues;
+ }
+
+ return JsonSerializer.Deserialize<T[]>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, T[]? value, JsonSerializerOptions options)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs
new file mode 100644
index 000000000..be94dd519
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a GUID object or value to/from JSON.
+ /// </summary>
+ public class JsonGuidConverter : JsonConverter<Guid>
+ {
+ /// <inheritdoc />
+ public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ var guidStr = reader.GetString();
+ return guidStr == null ? Guid.Empty : new Guid(guidStr);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value.ToString("N", CultureInfo.InvariantCulture));
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonLowerCaseConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonLowerCaseConverter.cs
new file mode 100644
index 000000000..cd582ced6
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonLowerCaseConverter.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts an object to a lowercase string.
+ /// </summary>
+ /// <typeparam name="T">The object type.</typeparam>
+ public class JsonLowerCaseConverter<T> : JsonConverter<T>
+ {
+ /// <inheritdoc />
+ public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ return JsonSerializer.Deserialize<T>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value?.ToString()?.ToLowerInvariant());
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonNullableGuidConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonNullableGuidConverter.cs
new file mode 100644
index 000000000..6192d1598
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonNullableGuidConverter.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a GUID object or value to/from JSON.
+ /// </summary>
+ public class JsonNullableGuidConverter : JsonConverter<Guid?>
+ {
+ /// <inheritdoc />
+ public override Guid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ var guidStr = reader.GetString();
+ return guidStr == null ? null : new Guid(guidStr);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options)
+ {
+ if (value == null || value == Guid.Empty)
+ {
+ writer.WriteNullValue();
+ }
+ else
+ {
+ writer.WriteStringValue(value.Value.ToString("N", CultureInfo.InvariantCulture));
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
new file mode 100644
index 000000000..6de238b39
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
@@ -0,0 +1,45 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a nullable struct or value to/from JSON.
+ /// Required - some clients send an empty string.
+ /// </summary>
+ /// <typeparam name="TStruct">The struct type.</typeparam>
+ public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
+ where TStruct : struct
+ {
+ /// <inheritdoc />
+ public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.Null)
+ {
+ return null;
+ }
+
+ // Token is empty string.
+ if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
+ {
+ return null;
+ }
+
+ return JsonSerializer.Deserialize<TStruct>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
+ {
+ if (value.HasValue)
+ {
+ JsonSerializer.Serialize(writer, value.Value, options);
+ }
+ else
+ {
+ writer.WriteNullValue();
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverterFactory.cs b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverterFactory.cs
new file mode 100644
index 000000000..e7749589a
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverterFactory.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Json nullable struct converter factory.
+ /// </summary>
+ public class JsonNullableStructConverterFactory : JsonConverterFactory
+ {
+ /// <inheritdoc />
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return typeToConvert.IsGenericType
+ && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>)
+ && typeToConvert.GenericTypeArguments[0].IsValueType;
+ }
+
+ /// <inheritdoc />
+ public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var structType = typeToConvert.GenericTypeArguments[0];
+ return (JsonConverter?)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType));
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverter.cs
new file mode 100644
index 000000000..6e59fe464
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverter.cs
@@ -0,0 +1,19 @@
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Convert Pipe delimited string to array of type.
+ /// </summary>
+ /// <typeparam name="T">Type to convert to.</typeparam>
+ public sealed class JsonPipeDelimitedArrayConverter<T> : JsonDelimitedArrayConverter<T>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonPipeDelimitedArrayConverter{T}"/> class.
+ /// </summary>
+ public JsonPipeDelimitedArrayConverter() : base()
+ {
+ }
+
+ /// <inheritdoc />
+ protected override char Delimiter => '|';
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs b/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs
new file mode 100644
index 000000000..579674f18
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Json Pipe delimited array converter factory.
+ /// </summary>
+ /// <remarks>
+ /// This must be applied as an attribute, adding to the JsonConverter list causes stack overflow.
+ /// </remarks>
+ public class JsonPipeDelimitedArrayConverterFactory : JsonConverterFactory
+ {
+ /// <inheritdoc />
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return true;
+ }
+
+ /// <inheritdoc />
+ public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0];
+ return (JsonConverter?)Activator.CreateInstance(typeof(JsonPipeDelimitedArrayConverter<>).MakeGenericType(structType));
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonStringConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonStringConverter.cs
new file mode 100644
index 000000000..1a7a8c4f5
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonStringConverter.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Buffers;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converter to allow the serializer to read strings.
+ /// </summary>
+ public class JsonStringConverter : JsonConverter<string?>
+ {
+ /// <inheritdoc />
+ public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ return reader.TokenType switch
+ {
+ JsonTokenType.Null => null,
+ JsonTokenType.String => reader.GetString(),
+ _ => GetRawValue(reader)
+ };
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value);
+ }
+
+ private static string GetRawValue(Utf8JsonReader reader)
+ {
+ var utf8Bytes = reader.HasValueSequence
+ ? reader.ValueSequence.ToArray()
+ : reader.ValueSpan;
+ return Encoding.UTF8.GetString(utf8Bytes);
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonVersionConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonVersionConverter.cs
new file mode 100644
index 000000000..51ffec1cb
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonVersionConverter.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters
+{
+ /// <summary>
+ /// Converts a Version object or value to/from JSON.
+ /// </summary>
+ /// <remarks>
+ /// Required to send <see cref="Version"/> as a string instead of an object.
+ /// </remarks>
+ public class JsonVersionConverter : JsonConverter<Version>
+ {
+ /// <inheritdoc />
+ public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ => new Version(reader.GetString()!); // Will throw ArgumentNullException on null
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options)
+ => writer.WriteStringValue(value.ToString());
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/JsonDefaults.cs b/src/Jellyfin.Extensions/Json/JsonDefaults.cs
new file mode 100644
index 000000000..f4ec91123
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/JsonDefaults.cs
@@ -0,0 +1,90 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+
+namespace Jellyfin.Extensions.Json
+{
+ /// <summary>
+ /// Helper class for having compatible JSON throughout the codebase.
+ /// </summary>
+ public static class JsonDefaults
+ {
+ /// <summary>
+ /// Pascal case json profile media type.
+ /// </summary>
+ public const string PascalCaseMediaType = "application/json; profile=\"PascalCase\"";
+
+ /// <summary>
+ /// Camel case json profile media type.
+ /// </summary>
+ public const string CamelCaseMediaType = "application/json; profile=\"CamelCase\"";
+
+ /// <summary>
+ /// When changing these options, update
+ /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+ /// -> AddJellyfinApi
+ /// -> AddJsonOptions.
+ /// </summary>
+ private static readonly JsonSerializerOptions _jsonSerializerOptions = new ()
+ {
+ ReadCommentHandling = JsonCommentHandling.Disallow,
+ WriteIndented = false,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ NumberHandling = JsonNumberHandling.AllowReadingFromString,
+ Converters =
+ {
+ new JsonGuidConverter(),
+ new JsonNullableGuidConverter(),
+ new JsonVersionConverter(),
+ new JsonStringEnumConverter(),
+ new JsonNullableStructConverterFactory(),
+ new JsonBoolNumberConverter(),
+ new JsonDateTimeConverter(),
+ new JsonStringConverter()
+ }
+ };
+
+ private static readonly JsonSerializerOptions _pascalCaseJsonSerializerOptions = new (_jsonSerializerOptions)
+ {
+ PropertyNamingPolicy = null
+ };
+
+ private static readonly JsonSerializerOptions _camelCaseJsonSerializerOptions = new (_jsonSerializerOptions)
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+ };
+
+ /// <summary>
+ /// Gets the default <see cref="JsonSerializerOptions" /> options.
+ /// </summary>
+ /// <remarks>
+ /// The return value must not be modified.
+ /// If the defaults must be modified the author must use the copy constructor.
+ /// </remarks>
+ /// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
+ public static JsonSerializerOptions Options
+ => _jsonSerializerOptions;
+
+ /// <summary>
+ /// Gets camelCase json options.
+ /// </summary>
+ /// <remarks>
+ /// The return value must not be modified.
+ /// If the defaults must be modified the author must use the copy constructor.
+ /// </remarks>
+ /// <returns>The camelCase <see cref="JsonSerializerOptions" /> options.</returns>
+ public static JsonSerializerOptions CamelCaseOptions
+ => _camelCaseJsonSerializerOptions;
+
+ /// <summary>
+ /// Gets PascalCase json options.
+ /// </summary>
+ /// <remarks>
+ /// The return value must not be modified.
+ /// If the defaults must be modified the author must use the copy constructor.
+ /// </remarks>
+ /// <returns>The PascalCase <see cref="JsonSerializerOptions" /> options.</returns>
+ public static JsonSerializerOptions PascalCaseOptions
+ => _pascalCaseJsonSerializerOptions;
+ }
+}
diff --git a/src/Jellyfin.Extensions/ReadOnlyListExtension.cs b/src/Jellyfin.Extensions/ReadOnlyListExtension.cs
new file mode 100644
index 000000000..7785cfb49
--- /dev/null
+++ b/src/Jellyfin.Extensions/ReadOnlyListExtension.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Static extensions for the <see cref="IReadOnlyList{T}"/> interface.
+ /// </summary>
+ public static class ReadOnlyListExtension
+ {
+ /// <summary>
+ /// Finds the index of the desired item.
+ /// </summary>
+ /// <param name="source">The source list.</param>
+ /// <param name="value">The value to fine.</param>
+ /// <typeparam name="T">The type of item to find.</typeparam>
+ /// <returns>Index if found, else -1.</returns>
+ public static int IndexOf<T>(this IReadOnlyList<T> source, T value)
+ {
+ if (source is IList<T> list)
+ {
+ return list.IndexOf(value);
+ }
+
+ for (int i = 0; i < source.Count; i++)
+ {
+ if (Equals(value, source[i]))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /// <summary>
+ /// Finds the index of the predicate.
+ /// </summary>
+ /// <param name="source">The source list.</param>
+ /// <param name="match">The value to find.</param>
+ /// <typeparam name="T">The type of item to find.</typeparam>
+ /// <returns>Index if found, else -1.</returns>
+ public static int FindIndex<T>(this IReadOnlyList<T> source, Predicate<T> match)
+ {
+ if (source is List<T> list)
+ {
+ return list.FindIndex(match);
+ }
+
+ for (int i = 0; i < source.Count; i++)
+ {
+ if (match(source[i]))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/ShuffleExtensions.cs b/src/Jellyfin.Extensions/ShuffleExtensions.cs
new file mode 100644
index 000000000..33c492053
--- /dev/null
+++ b/src/Jellyfin.Extensions/ShuffleExtensions.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Provides <c>Shuffle</c> extensions methods for <see cref="IList{T}" />.
+ /// </summary>
+ public static class ShuffleExtensions
+ {
+ /// <summary>
+ /// Shuffles the items in a list.
+ /// </summary>
+ /// <param name="list">The list that should get shuffled.</param>
+ /// <typeparam name="T">The type.</typeparam>
+ public static void Shuffle<T>(this IList<T> list)
+ {
+ list.Shuffle(Random.Shared);
+ }
+
+ /// <summary>
+ /// Shuffles the items in a list.
+ /// </summary>
+ /// <param name="list">The list that should get shuffled.</param>
+ /// <param name="rng">The random number generator to use.</param>
+ /// <typeparam name="T">The type.</typeparam>
+ public static void Shuffle<T>(this IList<T> list, Random rng)
+ {
+ int n = list.Count;
+ while (n > 1)
+ {
+ int k = rng.Next(n--);
+ T value = list[k];
+ list[k] = list[n];
+ list[n] = value;
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/SplitStringExtensions.cs b/src/Jellyfin.Extensions/SplitStringExtensions.cs
new file mode 100644
index 000000000..5fa5c0123
--- /dev/null
+++ b/src/Jellyfin.Extensions/SplitStringExtensions.cs
@@ -0,0 +1,115 @@
+/*
+MIT License
+
+Copyright (c) 2019 Gérald Barré
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+ */
+
+// TODO: remove when analyzer is fixed: https://github.com/dotnet/roslyn-analyzers/issues/5158
+#pragma warning disable CA1034 // Nested types should not be visible
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Extension class for splitting lines without unnecessary allocations.
+ /// </summary>
+ public static class SplitStringExtensions
+ {
+ /// <summary>
+ /// Creates a new string split enumerator.
+ /// </summary>
+ /// <param name="str">The string to split.</param>
+ /// <param name="separator">The separator to split on.</param>
+ /// <returns>The enumerator struct.</returns>
+ [Pure]
+ public static Enumerator SpanSplit(this string str, char separator) => new (str.AsSpan(), separator);
+
+ /// <summary>
+ /// Creates a new span split enumerator.
+ /// </summary>
+ /// <param name="str">The span to split.</param>
+ /// <param name="separator">The separator to split on.</param>
+ /// <returns>The enumerator struct.</returns>
+ [Pure]
+ public static Enumerator Split(this ReadOnlySpan<char> str, char separator) => new (str, separator);
+
+ /// <summary>
+ /// Provides an enumerator for the substrings seperated by the separator.
+ /// </summary>
+ [StructLayout(LayoutKind.Auto)]
+ public ref struct Enumerator
+ {
+ private readonly char _separator;
+ private ReadOnlySpan<char> _str;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Enumerator"/> struct.
+ /// </summary>
+ /// <param name="str">The span to split.</param>
+ /// <param name="separator">The separator to split on.</param>
+ public Enumerator(ReadOnlySpan<char> str, char separator)
+ {
+ _str = str;
+ _separator = separator;
+ Current = default;
+ }
+
+ /// <summary>
+ /// Gets a reference to the item at the current position of the enumerator.
+ /// </summary>
+ public ReadOnlySpan<char> Current { get; private set; }
+
+ /// <summary>
+ /// Returns <c>this</c>.
+ /// </summary>
+ /// <returns><c>this</c>.</returns>
+ public readonly Enumerator GetEnumerator() => this;
+
+ /// <summary>
+ /// Advances the enumerator to the next item.
+ /// </summary>
+ /// <returns><c>true</c> if there is a next element; otherwise <c>false</c>.</returns>
+ public bool MoveNext()
+ {
+ if (_str.Length == 0)
+ {
+ return false;
+ }
+
+ var span = _str;
+ var index = span.IndexOf(_separator);
+ if (index == -1)
+ {
+ _str = ReadOnlySpan<char>.Empty;
+ Current = span;
+ return true;
+ }
+
+ Current = span.Slice(0, index);
+ _str = span[(index + 1)..];
+ return true;
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/StreamExtensions.cs b/src/Jellyfin.Extensions/StreamExtensions.cs
new file mode 100644
index 000000000..9751d9d42
--- /dev/null
+++ b/src/Jellyfin.Extensions/StreamExtensions.cs
@@ -0,0 +1,63 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Class BaseExtensions.
+ /// </summary>
+ public static class StreamExtensions
+ {
+ /// <summary>
+ /// Reads all lines in the <see cref="Stream" />.
+ /// </summary>
+ /// <param name="stream">The <see cref="Stream" /> to read from.</param>
+ /// <returns>All lines in the stream.</returns>
+ public static string[] ReadAllLines(this Stream stream)
+ => ReadAllLines(stream, Encoding.UTF8);
+
+ /// <summary>
+ /// Reads all lines in the <see cref="Stream" />.
+ /// </summary>
+ /// <param name="stream">The <see cref="Stream" /> to read from.</param>
+ /// <param name="encoding">The character encoding to use.</param>
+ /// <returns>All lines in the stream.</returns>
+ public static string[] ReadAllLines(this Stream stream, Encoding encoding)
+ {
+ using (StreamReader reader = new StreamReader(stream, encoding))
+ {
+ return ReadAllLines(reader).ToArray();
+ }
+ }
+
+ /// <summary>
+ /// Reads all lines in the <see cref="TextReader" />.
+ /// </summary>
+ /// <param name="reader">The <see cref="TextReader" /> to read from.</param>
+ /// <returns>All lines in the stream.</returns>
+ public static IEnumerable<string> ReadAllLines(this TextReader reader)
+ {
+ string? line;
+ while ((line = reader.ReadLine()) != null)
+ {
+ yield return line;
+ }
+ }
+
+ /// <summary>
+ /// Reads all lines in the <see cref="TextReader" />.
+ /// </summary>
+ /// <param name="reader">The <see cref="TextReader" /> to read from.</param>
+ /// <returns>All lines in the stream.</returns>
+ public static async IAsyncEnumerable<string> ReadAllLinesAsync(this TextReader reader)
+ {
+ string? line;
+ while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
+ {
+ yield return line;
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/StringBuilderExtensions.cs b/src/Jellyfin.Extensions/StringBuilderExtensions.cs
new file mode 100644
index 000000000..02ff7cc1f
--- /dev/null
+++ b/src/Jellyfin.Extensions/StringBuilderExtensions.cs
@@ -0,0 +1,35 @@
+using System.Collections.Generic;
+using System.Text;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Extension methods for the <see cref="StringBuilder"/> class.
+ /// </summary>
+ public static class StringBuilderExtensions
+ {
+ /// <summary>
+ /// Concatenates and appends the members of a collection in single quotes using the specified delimiter.
+ /// </summary>
+ /// <param name="builder">The string builder.</param>
+ /// <param name="delimiter">The character delimiter.</param>
+ /// <param name="values">The collection of strings to concatenate.</param>
+ /// <returns>The updated string builder.</returns>
+ public static StringBuilder AppendJoinInSingleQuotes(this StringBuilder builder, char delimiter, IReadOnlyList<string> values)
+ {
+ var len = values.Count;
+ for (var i = 0; i < len; i++)
+ {
+ builder.Append('\'')
+ .Append(values[i])
+ .Append('\'')
+ .Append(delimiter);
+ }
+
+ // remove last ,
+ builder.Length--;
+
+ return builder;
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/StringExtensions.cs b/src/Jellyfin.Extensions/StringExtensions.cs
new file mode 100644
index 000000000..3a7707253
--- /dev/null
+++ b/src/Jellyfin.Extensions/StringExtensions.cs
@@ -0,0 +1,65 @@
+using System;
+
+namespace Jellyfin.Extensions
+{
+ /// <summary>
+ /// Provides extensions methods for <see cref="string" />.
+ /// </summary>
+ public static class StringExtensions
+ {
+ /// <summary>
+ /// Counts the number of occurrences of [needle] in the string.
+ /// </summary>
+ /// <param name="value">The haystack to search in.</param>
+ /// <param name="needle">The character to search for.</param>
+ /// <returns>The number of occurrences of the [needle] character.</returns>
+ public static int Count(this ReadOnlySpan<char> value, char needle)
+ {
+ var count = 0;
+ var length = value.Length;
+ for (var i = 0; i < length; i++)
+ {
+ if (value[i] == needle)
+ {
+ count++;
+ }
+ }
+
+ return count;
+ }
+
+ /// <summary>
+ /// Returns the part on the left of the <c>needle</c>.
+ /// </summary>
+ /// <param name="haystack">The string to seek.</param>
+ /// <param name="needle">The needle to find.</param>
+ /// <returns>The part left of the <paramref name="needle" />.</returns>
+ public static ReadOnlySpan<char> LeftPart(this ReadOnlySpan<char> haystack, char needle)
+ {
+ var pos = haystack.IndexOf(needle);
+ return pos == -1 ? haystack : haystack[..pos];
+ }
+
+ /// <summary>
+ /// Returns the part on the right of the <c>needle</c>.
+ /// </summary>
+ /// <param name="haystack">The string to seek.</param>
+ /// <param name="needle">The needle to find.</param>
+ /// <returns>The part right of the <paramref name="needle" />.</returns>
+ public static ReadOnlySpan<char> RightPart(this ReadOnlySpan<char> haystack, char needle)
+ {
+ var pos = haystack.LastIndexOf(needle);
+ if (pos == -1)
+ {
+ return haystack;
+ }
+
+ if (pos == haystack.Length - 1)
+ {
+ return ReadOnlySpan<char>.Empty;
+ }
+
+ return haystack[(pos + 1)..];
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs
new file mode 100644
index 000000000..cd03958b6
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs
@@ -0,0 +1,154 @@
+using System;
+using System.Linq;
+using System.Security.Claims;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Net;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth
+{
+ public class CustomAuthenticationHandlerTests
+ {
+ private readonly IFixture _fixture;
+
+ private readonly Mock<IAuthService> _jellyfinAuthServiceMock;
+
+ private readonly CustomAuthenticationHandler _sut;
+ private readonly AuthenticationScheme _scheme;
+
+ public CustomAuthenticationHandlerTests()
+ {
+ var fixtureCustomizations = new AutoMoqCustomization
+ {
+ ConfigureMembers = true
+ };
+
+ _fixture = new Fixture().Customize(fixtureCustomizations);
+ AllowFixtureCircularDependencies();
+
+ _jellyfinAuthServiceMock = _fixture.Freeze<Mock<IAuthService>>();
+ var optionsMonitorMock = _fixture.Freeze<Mock<IOptionsMonitor<AuthenticationSchemeOptions>>>();
+ var serviceProviderMock = _fixture.Freeze<Mock<IServiceProvider>>();
+ var authenticationServiceMock = _fixture.Freeze<Mock<IAuthenticationService>>();
+ _fixture.Register<ILoggerFactory>(() => new NullLoggerFactory());
+
+ serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService)))
+ .Returns(authenticationServiceMock.Object);
+
+ optionsMonitorMock.Setup(o => o.Get(It.IsAny<string>()))
+ .Returns(new AuthenticationSchemeOptions
+ {
+ ForwardAuthenticate = null
+ });
+
+ HttpContext context = new DefaultHttpContext
+ {
+ RequestServices = serviceProviderMock.Object
+ };
+
+ _scheme = new AuthenticationScheme(
+ _fixture.Create<string>(),
+ null,
+ typeof(CustomAuthenticationHandler));
+
+ _sut = _fixture.Create<CustomAuthenticationHandler>();
+ _sut.InitializeAsync(_scheme, context).Wait();
+ }
+
+ [Fact]
+ public async Task HandleAuthenticateAsyncShouldProvideNoResultOnAuthenticationException()
+ {
+ var errorMessage = _fixture.Create<string>();
+
+ _jellyfinAuthServiceMock.Setup(
+ a => a.Authenticate(
+ It.IsAny<HttpRequest>()))
+ .Throws(new AuthenticationException(errorMessage));
+
+ var authenticateResult = await _sut.AuthenticateAsync();
+
+ Assert.False(authenticateResult.Succeeded);
+ Assert.True(authenticateResult.None);
+ }
+
+ [Fact]
+ public async Task HandleAuthenticateAsyncShouldSucceedWithUser()
+ {
+ SetupUser();
+ var authenticateResult = await _sut.AuthenticateAsync();
+
+ Assert.True(authenticateResult.Succeeded);
+ Assert.Null(authenticateResult.Failure);
+ }
+
+ [Fact]
+ public async Task HandleAuthenticateAsyncShouldAssignNameClaim()
+ {
+ var authorizationInfo = SetupUser();
+ var authenticateResult = await _sut.AuthenticateAsync();
+
+ Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username));
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin)
+ {
+ var authorizationInfo = SetupUser(isAdmin);
+ var authenticateResult = await _sut.AuthenticateAsync();
+
+ var expectedRole = authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User;
+ Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Role, expectedRole));
+ }
+
+ [Fact]
+ public async Task HandleAuthenticateAsyncShouldAssignTicketCorrectScheme()
+ {
+ SetupUser();
+ var authenticatedResult = await _sut.AuthenticateAsync();
+
+ Assert.Equal(_scheme.Name, authenticatedResult.Ticket?.AuthenticationScheme);
+ }
+
+ private AuthorizationInfo SetupUser(bool isAdmin = false)
+ {
+ var authorizationInfo = _fixture.Create<AuthorizationInfo>();
+ authorizationInfo.User = _fixture.Create<User>();
+ authorizationInfo.User.AddDefaultPermissions();
+ authorizationInfo.User.AddDefaultPreferences();
+ authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin);
+ authorizationInfo.IsApiKey = false;
+
+ _jellyfinAuthServiceMock.Setup(
+ a => a.Authenticate(
+ It.IsAny<HttpRequest>()))
+ .Returns(Task.FromResult(authorizationInfo));
+
+ return authorizationInfo;
+ }
+
+ private void AllowFixtureCircularDependencies()
+ {
+ // A circular dependency exists in the User entity around parent folders,
+ // this allows Autofixture to generate a User regardless, rather than throw
+ // an error.
+ _fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
+ .ForEach(b => _fixture.Behaviors.Remove(b));
+ _fixture.Behaviors.Add(new OmitOnRecursionBehavior());
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandlerTests.cs
new file mode 100644
index 000000000..23c51999f
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandlerTests.cs
@@ -0,0 +1,110 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
+using Jellyfin.Api.Constants;
+using Jellyfin.Server.Implementations.Security;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth.DefaultAuthorizationPolicy
+{
+ public class DefaultAuthorizationHandlerTests
+ {
+ private readonly Mock<IConfigurationManager> _configurationManagerMock;
+ private readonly List<IAuthorizationRequirement> _requirements;
+ private readonly DefaultAuthorizationHandler _sut;
+ private readonly Mock<IUserManager> _userManagerMock;
+ private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
+
+ public DefaultAuthorizationHandlerTests()
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization());
+ _configurationManagerMock = fixture.Freeze<Mock<IConfigurationManager>>();
+ _requirements = new List<IAuthorizationRequirement> { new DefaultAuthorizationRequirement() };
+ _userManagerMock = fixture.Freeze<Mock<IUserManager>>();
+ _httpContextAccessor = fixture.Freeze<Mock<IHttpContextAccessor>>();
+
+ _sut = fixture.Create<DefaultAuthorizationHandler>();
+ }
+
+ [Theory]
+ [InlineData(UserRoles.Administrator)]
+ [InlineData(UserRoles.Guest)]
+ [InlineData(UserRoles.User)]
+ public async Task ShouldSucceedOnUser(string userRole)
+ {
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, true);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ userRole);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+
+ await _sut.HandleAsync(context);
+ Assert.True(context.HasSucceeded);
+ }
+
+ [Theory]
+ [MemberData(nameof(GetParts_ValidAuthHeader_Success_Data))]
+ public void GetParts_ValidAuthHeader_Success(string input, Dictionary<string, string> parts)
+ {
+ var dict = AuthorizationContext.GetParts(input);
+ foreach (var (key, value) in parts)
+ {
+ Assert.Equal(dict[key], value);
+ }
+ }
+
+ private static TheoryData<string, Dictionary<string, string>> GetParts_ValidAuthHeader_Success_Data()
+ {
+ var data = new TheoryData<string, Dictionary<string, string>>();
+
+ data.Add(
+ "x=\"123,123\",y=\"123\"",
+ new Dictionary<string, string>
+ {
+ { "x", "123,123" },
+ { "y", "123" }
+ });
+
+ data.Add(
+ "x=\"123,123\", y=\"123\",z=\"'hi'\"",
+ new Dictionary<string, string>
+ {
+ { "x", "123,123" },
+ { "y", "123" },
+ { "z", "'hi'" }
+ });
+
+ data.Add(
+ "x=\"ab\"",
+ new Dictionary<string, string>
+ {
+ { "x", "ab" }
+ });
+
+ data.Add(
+ "param=Hörbücher",
+ new Dictionary<string, string>
+ {
+ { "param", "Hörbücher" }
+ });
+
+ data.Add(
+ "param=%22%Hörbücher",
+ new Dictionary<string, string>
+ {
+ { "param", "\"%Hörbücher" }
+ });
+
+ return data;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs
new file mode 100644
index 000000000..ee42216e4
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs
@@ -0,0 +1,71 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth.FirstTimeSetupOrElevatedPolicy
+{
+ public class FirstTimeSetupOrElevatedHandlerTests
+ {
+ private readonly Mock<IConfigurationManager> _configurationManagerMock;
+ private readonly List<IAuthorizationRequirement> _requirements;
+ private readonly FirstTimeSetupOrElevatedHandler _sut;
+ private readonly Mock<IUserManager> _userManagerMock;
+ private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
+
+ public FirstTimeSetupOrElevatedHandlerTests()
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization());
+ _configurationManagerMock = fixture.Freeze<Mock<IConfigurationManager>>();
+ _requirements = new List<IAuthorizationRequirement> { new FirstTimeSetupOrElevatedRequirement() };
+ _userManagerMock = fixture.Freeze<Mock<IUserManager>>();
+ _httpContextAccessor = fixture.Freeze<Mock<IHttpContextAccessor>>();
+
+ _sut = fixture.Create<FirstTimeSetupOrElevatedHandler>();
+ }
+
+ [Theory]
+ [InlineData(UserRoles.Administrator)]
+ [InlineData(UserRoles.Guest)]
+ [InlineData(UserRoles.User)]
+ public async Task ShouldSucceedIfStartupWizardIncomplete(string userRole)
+ {
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, false);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ userRole);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+
+ await _sut.HandleAsync(context);
+ Assert.True(context.HasSucceeded);
+ }
+
+ [Theory]
+ [InlineData(UserRoles.Administrator, true)]
+ [InlineData(UserRoles.Guest, false)]
+ [InlineData(UserRoles.User, false)]
+ public async Task ShouldRequireAdministratorIfStartupWizardComplete(string userRole, bool shouldSucceed)
+ {
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, true);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ userRole);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+
+ await _sut.HandleAsync(context);
+ Assert.Equal(shouldSucceed, context.HasSucceeded);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/IgnoreSchedulePolicy/IgnoreScheduleHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/IgnoreSchedulePolicy/IgnoreScheduleHandlerTests.cs
new file mode 100644
index 000000000..7150c90bb
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/IgnoreSchedulePolicy/IgnoreScheduleHandlerTests.cs
@@ -0,0 +1,62 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth.IgnoreSchedulePolicy
+{
+ public class IgnoreScheduleHandlerTests
+ {
+ private readonly Mock<IConfigurationManager> _configurationManagerMock;
+ private readonly List<IAuthorizationRequirement> _requirements;
+ private readonly IgnoreParentalControlHandler _sut;
+ private readonly Mock<IUserManager> _userManagerMock;
+ private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
+
+ /// <summary>
+ /// Globally disallow access.
+ /// </summary>
+ private readonly AccessSchedule[] _accessSchedules = { new AccessSchedule(DynamicDayOfWeek.Everyday, 0, 0, Guid.Empty) };
+
+ public IgnoreScheduleHandlerTests()
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization());
+ _configurationManagerMock = fixture.Freeze<Mock<IConfigurationManager>>();
+ _requirements = new List<IAuthorizationRequirement> { new IgnoreParentalControlRequirement() };
+ _userManagerMock = fixture.Freeze<Mock<IUserManager>>();
+ _httpContextAccessor = fixture.Freeze<Mock<IHttpContextAccessor>>();
+
+ _sut = fixture.Create<IgnoreParentalControlHandler>();
+ }
+
+ [Theory]
+ [InlineData(UserRoles.Administrator, true)]
+ [InlineData(UserRoles.User, true)]
+ [InlineData(UserRoles.Guest, true)]
+ public async Task ShouldAllowScheduleCorrectly(string role, bool shouldSucceed)
+ {
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, true);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ role,
+ _accessSchedules);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+
+ await _sut.HandleAsync(context);
+ Assert.Equal(shouldSucceed, context.HasSucceeded);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs
new file mode 100644
index 000000000..5b3d784ff
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs
@@ -0,0 +1,59 @@
+using System.Collections.Generic;
+using System.Net;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth.LocalAccessPolicy;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth.LocalAccessPolicy
+{
+ public class LocalAccessHandlerTests
+ {
+ private readonly Mock<IConfigurationManager> _configurationManagerMock;
+ private readonly List<IAuthorizationRequirement> _requirements;
+ private readonly LocalAccessHandler _sut;
+ private readonly Mock<IUserManager> _userManagerMock;
+ private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
+ private readonly Mock<INetworkManager> _networkManagerMock;
+
+ public LocalAccessHandlerTests()
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization());
+ _configurationManagerMock = fixture.Freeze<Mock<IConfigurationManager>>();
+ _requirements = new List<IAuthorizationRequirement> { new LocalAccessRequirement() };
+ _userManagerMock = fixture.Freeze<Mock<IUserManager>>();
+ _httpContextAccessor = fixture.Freeze<Mock<IHttpContextAccessor>>();
+ _networkManagerMock = fixture.Freeze<Mock<INetworkManager>>();
+
+ _sut = fixture.Create<LocalAccessHandler>();
+ }
+
+ [Theory]
+ [InlineData(true, true)]
+ [InlineData(false, false)]
+ public async Task LocalAccessOnly(bool isInLocalNetwork, bool shouldSucceed)
+ {
+ _networkManagerMock
+ .Setup(n => n.IsInLocalNetwork(It.IsAny<IPAddress>()))
+ .Returns(isInLocalNetwork);
+
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, true);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ UserRoles.User);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+ await _sut.HandleAsync(context);
+ Assert.Equal(shouldSucceed, context.HasSucceeded);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs
new file mode 100644
index 000000000..ffe88fcde
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs
@@ -0,0 +1,53 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Jellyfin.Api.Auth.RequiresElevationPolicy;
+using Jellyfin.Api.Constants;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Auth.RequiresElevationPolicy
+{
+ public class RequiresElevationHandlerTests
+ {
+ private readonly Mock<IConfigurationManager> _configurationManagerMock;
+ private readonly List<IAuthorizationRequirement> _requirements;
+ private readonly RequiresElevationHandler _sut;
+ private readonly Mock<IUserManager> _userManagerMock;
+ private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
+
+ public RequiresElevationHandlerTests()
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization());
+ _configurationManagerMock = fixture.Freeze<Mock<IConfigurationManager>>();
+ _requirements = new List<IAuthorizationRequirement> { new RequiresElevationRequirement() };
+ _userManagerMock = fixture.Freeze<Mock<IUserManager>>();
+ _httpContextAccessor = fixture.Freeze<Mock<IHttpContextAccessor>>();
+
+ _sut = fixture.Create<RequiresElevationHandler>();
+ }
+
+ [Theory]
+ [InlineData(UserRoles.Administrator, true)]
+ [InlineData(UserRoles.User, false)]
+ [InlineData(UserRoles.Guest, false)]
+ public async Task ShouldHandleRolesCorrectly(string role, bool shouldSucceed)
+ {
+ TestHelpers.SetupConfigurationManager(_configurationManagerMock, true);
+ var claims = TestHelpers.SetupUser(
+ _userManagerMock,
+ _httpContextAccessor,
+ role);
+
+ var context = new AuthorizationHandlerContext(_requirements, claims, null);
+
+ await _sut.HandleAsync(context);
+ Assert.Equal(shouldSucceed, context.HasSucceeded);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs
new file mode 100644
index 000000000..1f06e8fde
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs
@@ -0,0 +1,45 @@
+using System;
+using Jellyfin.Api.Controllers;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Controllers
+{
+ public class DynamicHlsControllerTests
+ {
+ [Theory]
+ [MemberData(nameof(GetSegmentLengths_Success_TestData))]
+ public void GetSegmentLengths_Success(long runtimeTicks, int segmentlength, double[] expected)
+ {
+ var res = DynamicHlsController.GetSegmentLengthsInternal(runtimeTicks, segmentlength);
+ Assert.Equal(expected.Length, res.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ Assert.Equal(expected[i], res[i]);
+ }
+ }
+
+ public static TheoryData<long, int, double[]> GetSegmentLengths_Success_TestData()
+ {
+ var data = new TheoryData<long, int, double[]>();
+ data.Add(0, 6, Array.Empty<double>());
+ data.Add(
+ TimeSpan.FromSeconds(3).Ticks,
+ 6,
+ new double[] { 3 });
+ data.Add(
+ TimeSpan.FromSeconds(6).Ticks,
+ 6,
+ new double[] { 6 });
+ data.Add(
+ TimeSpan.FromSeconds(3.3333333).Ticks,
+ 6,
+ new double[] { 3.3333333 });
+ data.Add(
+ TimeSpan.FromSeconds(9.3333333).Ticks,
+ 6,
+ new double[] { 6, 3.3333333 });
+
+ return data;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs
new file mode 100644
index 000000000..4ba7e1d2f
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Collections.Generic;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Data.Enums;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Helpers
+{
+ public static class RequestHelpersTests
+ {
+ [Theory]
+ [MemberData(nameof(GetOrderBy_Success_TestData))]
+ public static void GetOrderBy_Success(IReadOnlyList<string> sortBy, IReadOnlyList<SortOrder> requestedSortOrder, (string, SortOrder)[] expected)
+ {
+ Assert.Equal(expected, RequestHelpers.GetOrderBy(sortBy, requestedSortOrder));
+ }
+
+ public static TheoryData<IReadOnlyList<string>, IReadOnlyList<SortOrder>, (string, SortOrder)[]> GetOrderBy_Success_TestData()
+ {
+ var data = new TheoryData<IReadOnlyList<string>, IReadOnlyList<SortOrder>, (string, SortOrder)[]>();
+
+ data.Add(
+ Array.Empty<string>(),
+ Array.Empty<SortOrder>(),
+ Array.Empty<(string, SortOrder)>());
+
+ data.Add(
+ new string[]
+ {
+ "IsFavoriteOrLiked",
+ "Random"
+ },
+ Array.Empty<SortOrder>(),
+ new (string, SortOrder)[]
+ {
+ ("IsFavoriteOrLiked", SortOrder.Ascending),
+ ("Random", SortOrder.Ascending),
+ });
+
+ data.Add(
+ new string[]
+ {
+ "SortName",
+ "ProductionYear"
+ },
+ new SortOrder[]
+ {
+ SortOrder.Descending
+ },
+ new (string, SortOrder)[]
+ {
+ ("SortName", SortOrder.Descending),
+ ("ProductionYear", SortOrder.Descending),
+ });
+
+ return data;
+ }
+
+ [Fact]
+ public static void GetItemTypeStrings_Empty_Empty()
+ {
+ Assert.Empty(RequestHelpers.GetItemTypeStrings(Array.Empty<BaseItemKind>()));
+ }
+
+ [Fact]
+ public static void GetItemTypeStrings_Valid_Success()
+ {
+ BaseItemKind[] input =
+ {
+ BaseItemKind.AggregateFolder,
+ BaseItemKind.Audio,
+ BaseItemKind.BasePluginFolder,
+ BaseItemKind.CollectionFolder
+ };
+
+ string[] expected =
+ {
+ "AggregateFolder",
+ "Audio",
+ "BasePluginFolder",
+ "CollectionFolder"
+ };
+
+ var res = RequestHelpers.GetItemTypeStrings(input);
+
+ Assert.Equal(expected, res);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj
new file mode 100644
index 000000000..57ec86316
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj
@@ -0,0 +1,39 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../Jellyfin.Api/Jellyfin.Api.csproj" />
+ <ProjectReference Include="../../Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs
new file mode 100644
index 000000000..3ae6ae5bd
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs
@@ -0,0 +1,226 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Api.ModelBinders;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Primitives;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.ModelBinders
+{
+ public sealed class CommaDelimitedArrayModelBinderTests
+ {
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedStringArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<string> queryParamValues = new[] { "lol", "xd" };
+ var queryParamString = "lol,xd";
+ var queryParamType = typeof(string[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<string>?)bindingContextMock.Object?.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedIntArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<int> queryParamValues = new[] { 42, 0 };
+ var queryParamString = "42,0";
+ var queryParamType = typeof(int[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<int>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How,Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQueryWithDoubleCommas()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How,,Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString1 = "How";
+ var queryParamString2 = "Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsEmptyEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = Array.Empty<TestType>();
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(value: null) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_EnumArrayQuery_BindValidOnly()
+ {
+ var queryParamName = "test";
+ var queryParamString = "🔥,😢";
+ var queryParamType = typeof(IReadOnlyList<TestType>);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Empty((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_EnumArrayQuery_BindValidOnly_2()
+ {
+ var queryParamName = "test";
+ var queryParamString1 = "How";
+ var queryParamString2 = "😱";
+ var queryParamType = typeof(IReadOnlyList<TestType>);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Single((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs
new file mode 100644
index 000000000..938d19a15
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs
@@ -0,0 +1,226 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Api.ModelBinders;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Primitives;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.ModelBinders
+{
+ public sealed class PipeDelimitedArrayModelBinderTests
+ {
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedStringArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<string> queryParamValues = new[] { "lol", "xd" };
+ var queryParamString = "lol|xd";
+ var queryParamType = typeof(string[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<string>?)bindingContextMock.Object?.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidDelimitedIntArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<int> queryParamValues = new[] { 42, 0 };
+ var queryParamString = "42|0";
+ var queryParamType = typeof(int[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<int>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How|Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedEnumArrayQueryWithDoublePipes()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How||Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString1 = "How";
+ var queryParamString2 = "Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsEmptyEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList<TestType> queryParamValues = Array.Empty<TestType>();
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(value: null) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_EnumArrayQuery_BindValidOnly()
+ {
+ var queryParamName = "test";
+ var queryParamString = "🔥|😢";
+ var queryParamType = typeof(IReadOnlyList<TestType>);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Empty((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_EnumArrayQuery_BindValidOnly_2()
+ {
+ var queryParamName = "test";
+ var queryParamString1 = "How";
+ var queryParamString2 = "😱";
+ var queryParamType = typeof(IReadOnlyList<TestType>);
+
+ var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary<string, StringValues>
+ {
+ { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock<ModelBindingContext>();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Single((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs b/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs
new file mode 100644
index 000000000..92c534eae
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs
@@ -0,0 +1,11 @@
+namespace Jellyfin.Api.Tests.ModelBinders
+{
+ public enum TestType
+ {
+ How,
+ Much,
+ Is,
+ The,
+ Fish
+ }
+}
diff --git a/tests/Jellyfin.Api.Tests/TestHelpers.cs b/tests/Jellyfin.Api.Tests/TestHelpers.cs
new file mode 100644
index 000000000..f9bca4146
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/TestHelpers.cs
@@ -0,0 +1,84 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Net;
+using System.Security.Claims;
+using Jellyfin.Api.Constants;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Server.Implementations.Users;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Configuration;
+using Microsoft.AspNetCore.Http;
+using Moq;
+using AccessSchedule = Jellyfin.Data.Entities.AccessSchedule;
+
+namespace Jellyfin.Api.Tests
+{
+ public static class TestHelpers
+ {
+ public static ClaimsPrincipal SetupUser(
+ Mock<IUserManager> userManagerMock,
+ Mock<IHttpContextAccessor> httpContextAccessorMock,
+ string role,
+ IEnumerable<AccessSchedule>? accessSchedules = null)
+ {
+ var user = new User(
+ "jellyfin",
+ typeof(DefaultAuthenticationProvider).FullName!,
+ typeof(DefaultPasswordResetProvider).FullName!);
+
+ user.AddDefaultPermissions();
+ user.AddDefaultPreferences();
+
+ // Set administrator flag.
+ user.SetPermission(PermissionKind.IsAdministrator, role.Equals(UserRoles.Administrator, StringComparison.OrdinalIgnoreCase));
+
+ // Add access schedules if set.
+ if (accessSchedules != null)
+ {
+ foreach (var accessSchedule in accessSchedules)
+ {
+ user.AccessSchedules.Add(accessSchedule);
+ }
+ }
+
+ var claims = new[]
+ {
+ new Claim(ClaimTypes.Role, role),
+ new Claim(ClaimTypes.Name, "jellyfin"),
+ new Claim(InternalClaimTypes.UserId, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)),
+ new Claim(InternalClaimTypes.DeviceId, Guid.Empty.ToString("N", CultureInfo.InvariantCulture)),
+ new Claim(InternalClaimTypes.Device, "test"),
+ new Claim(InternalClaimTypes.Client, "test"),
+ new Claim(InternalClaimTypes.Version, "test"),
+ new Claim(InternalClaimTypes.Token, "test"),
+ };
+
+ var identity = new ClaimsIdentity(claims);
+
+ userManagerMock
+ .Setup(u => u.GetUserById(It.IsAny<Guid>()))
+ .Returns(user);
+
+ httpContextAccessorMock
+ .Setup(h => h.HttpContext!.Connection.RemoteIpAddress)
+ .Returns(new IPAddress(0));
+
+ return new ClaimsPrincipal(identity);
+ }
+
+ public static void SetupConfigurationManager(in Mock<IConfigurationManager> configurationManagerMock, bool startupWizardCompleted)
+ {
+ var commonConfiguration = new BaseApplicationConfiguration
+ {
+ IsStartupWizardCompleted = startupWizardCompleted
+ };
+
+ configurationManagerMock
+ .Setup(c => c.CommonConfiguration)
+ .Returns(commonConfiguration);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Common.Tests/Crc32Tests.cs b/tests/Jellyfin.Common.Tests/Crc32Tests.cs
new file mode 100644
index 000000000..e95a2867f
--- /dev/null
+++ b/tests/Jellyfin.Common.Tests/Crc32Tests.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Text;
+using MediaBrowser.Common;
+using Xunit;
+
+namespace Jellyfin.Common.Tests
+{
+ public static class Crc32Tests
+ {
+ [Fact]
+ public static void Compute_Empty_Zero()
+ {
+ Assert.Equal<uint>(0, Crc32.Compute(Array.Empty<byte>()));
+ }
+
+ [Theory]
+ [InlineData(0x414fa339, "The quick brown fox jumps over the lazy dog")]
+ public static void Compute_Valid_Success(uint expected, string data)
+ {
+ Assert.Equal(expected, Crc32.Compute(Encoding.UTF8.GetBytes(data)));
+ }
+
+ [Theory]
+ [InlineData(0x414fa339, "54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F67")]
+ [InlineData(0x190a55ad, "0000000000000000000000000000000000000000000000000000000000000000")]
+ [InlineData(0xff6cab0b, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")]
+ [InlineData(0x91267e8a, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")]
+ public static void Compute_ValidHex_Success(uint expected, string data)
+ {
+ Assert.Equal(expected, Crc32.Compute(Convert.FromHexString(data)));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs
new file mode 100644
index 000000000..bfece97b6
--- /dev/null
+++ b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs
@@ -0,0 +1,169 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Cryptography;
+using Xunit;
+
+namespace Jellyfin.Common.Tests.Cryptography
+{
+ public static class PasswordHashTests
+ {
+ [Fact]
+ public static void Ctor_Null_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => new PasswordHash(null!, Array.Empty<byte>()));
+ }
+
+ [Fact]
+ public static void Ctor_Empty_ThrowsArgumentException()
+ {
+ Assert.Throws<ArgumentException>(() => new PasswordHash(string.Empty, Array.Empty<byte>()));
+ }
+
+ public static TheoryData<string, PasswordHash> Parse_Valid_TestData()
+ {
+ var data = new TheoryData<string, PasswordHash>();
+ // Id
+ data.Add(
+ "$PBKDF2",
+ new PasswordHash("PBKDF2", Array.Empty<byte>()));
+
+ // Id + parameter
+ data.Add(
+ "$PBKDF2$iterations=1000",
+ new PasswordHash(
+ "PBKDF2",
+ Array.Empty<byte>(),
+ Array.Empty<byte>(),
+ new Dictionary<string, string>()
+ {
+ { "iterations", "1000" },
+ }));
+
+ // Id + parameters
+ data.Add(
+ "$PBKDF2$iterations=1000,m=120",
+ new PasswordHash(
+ "PBKDF2",
+ Array.Empty<byte>(),
+ Array.Empty<byte>(),
+ new Dictionary<string, string>()
+ {
+ { "iterations", "1000" },
+ { "m", "120" }
+ }));
+
+ // Id + hash
+ data.Add(
+ "$PBKDF2$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D",
+ new PasswordHash(
+ "PBKDF2",
+ Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"),
+ Array.Empty<byte>(),
+ new Dictionary<string, string>()));
+
+ // Id + salt + hash
+ data.Add(
+ "$PBKDF2$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D",
+ new PasswordHash(
+ "PBKDF2",
+ Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"),
+ Convert.FromHexString("69F420"),
+ new Dictionary<string, string>()));
+
+ // Id + parameter + hash
+ data.Add(
+ "$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D",
+ new PasswordHash(
+ "PBKDF2",
+ Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"),
+ Array.Empty<byte>(),
+ new Dictionary<string, string>()
+ {
+ { "iterations", "1000" }
+ }));
+ // Id + parameters + hash
+ data.Add(
+ "$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D",
+ new PasswordHash(
+ "PBKDF2",
+ Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"),
+ Array.Empty<byte>(),
+ new Dictionary<string, string>()
+ {
+ { "iterations", "1000" },
+ { "m", "120" }
+ }));
+ // Id + parameters + salt + hash
+ data.Add(
+ "$PBKDF2$iterations=1000,m=120$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D",
+ new PasswordHash(
+ "PBKDF2",
+ Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"),
+ Convert.FromHexString("69F420"),
+ new Dictionary<string, string>()
+ {
+ { "iterations", "1000" },
+ { "m", "120" }
+ }));
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(Parse_Valid_TestData))]
+ public static void Parse_Valid_Success(string passwordHashString, PasswordHash expected)
+ {
+ var passwordHash = PasswordHash.Parse(passwordHashString);
+ Assert.Equal(expected.Id, passwordHash.Id);
+ Assert.Equal(expected.Parameters, passwordHash.Parameters);
+ Assert.Equal(expected.Salt.ToArray(), passwordHash.Salt.ToArray());
+ Assert.Equal(expected.Hash.ToArray(), passwordHash.Hash.ToArray());
+ Assert.Equal(expected.ToString(), passwordHash.ToString());
+ }
+
+ [Theory]
+ [InlineData("$PBKDF2")]
+ [InlineData("$PBKDF2$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")]
+ [InlineData("$PBKDF2$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")]
+ [InlineData("$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")]
+ [InlineData("$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")]
+ [InlineData("$PBKDF2$iterations=1000,m=120$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")]
+ [InlineData("$PBKDF2$iterations=1000,m=120")]
+ public static void ToString_Roundtrip_Success(string passwordHash)
+ {
+ Assert.Equal(passwordHash, PasswordHash.Parse(passwordHash).ToString());
+ }
+
+ [Fact]
+ public static void Parse_Null_ThrowsArgumentException()
+ {
+ Assert.Throws<ArgumentException>(() => PasswordHash.Parse(null));
+ }
+
+ [Fact]
+ public static void Parse_Empty_ThrowsArgumentException()
+ {
+ Assert.Throws<ArgumentException>(() => PasswordHash.Parse(string.Empty));
+ }
+
+ [Theory]
+ [InlineData("$")] // No id
+ [InlineData("$$")] // Empty segments
+ [InlineData("PBKDF2$")] // Doesn't start with $
+ [InlineData("$PBKDF2$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty segment
+ [InlineData("$PBKDF2$iterations=1000$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty salt segment
+ [InlineData("$PBKDF2$iterations=1000$69F420$")] // Empty hash segment
+ [InlineData("$PBKDF2$=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter
+ [InlineData("$PBKDF2$=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter
+ [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter
+ [InlineData("$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$")] // Ends on $
+ [InlineData("$PBKDF2$iterations=1000$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$")] // Extra segment
+ [InlineData("$PBKDF2$iterations=1000$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$anotherone")] // Extra segment
+ [InlineData("$PBKDF2$iterations=1000$invalidstalt$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid salt
+ [InlineData("$PBKDF2$iterations=1000$69F420$invalid hash")] // Invalid hash
+ [InlineData("$PBKDF2$69F420$")] // Empty hash
+ public static void Parse_InvalidFormat_ThrowsFormatException(string passwordHash)
+ {
+ Assert.Throws<FormatException>(() => PasswordHash.Parse(passwordHash));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj
new file mode 100644
index 000000000..ce607b2ec
--- /dev/null
+++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj
@@ -0,0 +1,34 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{DF194677-DFD3-42AF-9F75-D44D5A416478}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="FsCheck.Xunit" Version="2.16.3" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ <ProjectReference Include="../../MediaBrowser.Providers/MediaBrowser.Providers.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs
new file mode 100644
index 000000000..ef9d31cc1
--- /dev/null
+++ b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs
@@ -0,0 +1,85 @@
+using System;
+using MediaBrowser.Common.Providers;
+using Xunit;
+
+namespace Jellyfin.Common.Tests.Providers
+{
+ public class ProviderIdParserTests
+ {
+ [Theory]
+ [InlineData("tt1234567", "tt1234567")]
+ [InlineData("tt12345678", "tt12345678")]
+ [InlineData("https://www.imdb.com/title/tt1234567", "tt1234567")]
+ [InlineData("https://www.imdb.com/title/tt12345678", "tt12345678")]
+ [InlineData(@"multiline\nhttps://www.imdb.com/title/tt1234567", "tt1234567")]
+ [InlineData(@"multiline\nhttps://www.imdb.com/title/tt12345678", "tt12345678")]
+ [InlineData("tt1234567tt7654321", "tt1234567")]
+ [InlineData("tt12345678tt7654321", "tt12345678")]
+ [InlineData("tt123456789", "tt12345678")]
+ public void FindImdbId_Valid_Success(string text, string expected)
+ {
+ Assert.True(ProviderIdParsers.TryFindImdbId(text, out ReadOnlySpan<char> parsedId));
+ Assert.Equal(expected, parsedId.ToString());
+ }
+
+ [Theory]
+ [InlineData("tt123456")]
+ [InlineData("https://www.imdb.com/title/tt123456")]
+ [InlineData("Jellyfin")]
+ public void FindImdbId_Invalid_Success(string text)
+ {
+ Assert.False(ProviderIdParsers.TryFindImdbId(text, out _));
+ }
+
+ [Theory]
+ [InlineData("https://www.themoviedb.org/movie/30287-fallo", "30287")]
+ [InlineData("themoviedb.org/movie/30287", "30287")]
+ public void FindTmdbMovieId_Valid_Success(string text, string expected)
+ {
+ Assert.True(ProviderIdParsers.TryFindTmdbMovieId(text, out ReadOnlySpan<char> parsedId));
+ Assert.Equal(expected, parsedId.ToString());
+ }
+
+ [Theory]
+ [InlineData("https://www.themoviedb.org/movie/fallo-30287")]
+ [InlineData("https://www.themoviedb.org/tv/1668-friends")]
+ public void FindTmdbMovieId_Invalid_Success(string text)
+ {
+ Assert.False(ProviderIdParsers.TryFindTmdbMovieId(text, out _));
+ }
+
+ [Theory]
+ [InlineData("https://www.themoviedb.org/tv/1668-friends", "1668")]
+ [InlineData("themoviedb.org/tv/1668", "1668")]
+ public void FindTmdbSeriesId_Valid_Success(string text, string expected)
+ {
+ Assert.True(ProviderIdParsers.TryFindTmdbSeriesId(text, out ReadOnlySpan<char> parsedId));
+ Assert.Equal(expected, parsedId.ToString());
+ }
+
+ [Theory]
+ [InlineData("https://www.themoviedb.org/tv/friends-1668")]
+ [InlineData("https://www.themoviedb.org/movie/30287-fallo")]
+ public void FindTmdbSeriesId_Invalid_Success(string text)
+ {
+ Assert.False(ProviderIdParsers.TryFindTmdbSeriesId(text, out _));
+ }
+
+ [Theory]
+ [InlineData("https://www.thetvdb.com/?tab=series&id=121361", "121361")]
+ [InlineData("thetvdb.com/?tab=series&id=121361", "121361")]
+ public void FindTvdbId_Valid_Success(string text, string expected)
+ {
+ Assert.True(ProviderIdParsers.TryFindTvdbId(text, out ReadOnlySpan<char> parsedId));
+ Assert.Equal(expected, parsedId.ToString());
+ }
+
+ [Theory]
+ [InlineData("thetvdb.com/?tab=series&id=Jellyfin121361")]
+ [InlineData("https://www.themoviedb.org/tv/1668-friends")]
+ public void FindTvdbId_Invalid_Success(string text)
+ {
+ Assert.False(ProviderIdParsers.TryFindTvdbId(text, out _));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs b/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs
new file mode 100644
index 000000000..feffb50e8
--- /dev/null
+++ b/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs
@@ -0,0 +1,200 @@
+using System.Linq;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.IO;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Controller.Tests
+{
+ public class DirectoryServiceTests
+ {
+ private const string LowerCasePath = "/music/someartist";
+ private const string UpperCasePath = "/music/SOMEARTIST";
+
+ private static readonly FileSystemMetadata[] _lowerCaseFileSystemMetadata =
+ {
+ new ()
+ {
+ FullName = LowerCasePath + "/Artwork",
+ IsDirectory = true
+ },
+ new ()
+ {
+ FullName = LowerCasePath + "/Some Other Folder",
+ IsDirectory = true
+ },
+ new ()
+ {
+ FullName = LowerCasePath + "/Song 2.mp3",
+ IsDirectory = false
+ },
+ new ()
+ {
+ FullName = LowerCasePath + "/Song 3.mp3",
+ IsDirectory = false
+ }
+ };
+
+ private static readonly FileSystemMetadata[] _upperCaseFileSystemMetadata =
+ {
+ new ()
+ {
+ FullName = UpperCasePath + "/Lyrics",
+ IsDirectory = true
+ },
+ new ()
+ {
+ FullName = UpperCasePath + "/Song 1.mp3",
+ IsDirectory = false
+ }
+ };
+
+ [Fact]
+ public void GetFileSystemEntries_GivenPathsWithDifferentCasing_CachesAll()
+ {
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is<string>(x => x == UpperCasePath), false)).Returns(_upperCaseFileSystemMetadata);
+ fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is<string>(x => x == LowerCasePath), false)).Returns(_lowerCaseFileSystemMetadata);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var upperCaseResult = directoryService.GetFileSystemEntries(UpperCasePath);
+ var lowerCaseResult = directoryService.GetFileSystemEntries(LowerCasePath);
+
+ Assert.Equal(_upperCaseFileSystemMetadata, upperCaseResult);
+ Assert.Equal(_lowerCaseFileSystemMetadata, lowerCaseResult);
+ }
+
+ [Fact]
+ public void GetFiles_GivenPathsWithDifferentCasing_ReturnsCorrectFiles()
+ {
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is<string>(x => x == UpperCasePath), false)).Returns(_upperCaseFileSystemMetadata);
+ fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is<string>(x => x == LowerCasePath), false)).Returns(_lowerCaseFileSystemMetadata);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var upperCaseResult = directoryService.GetFiles(UpperCasePath);
+ var lowerCaseResult = directoryService.GetFiles(LowerCasePath);
+
+ Assert.Equal(_upperCaseFileSystemMetadata.Where(f => !f.IsDirectory), upperCaseResult);
+ Assert.Equal(_lowerCaseFileSystemMetadata.Where(f => !f.IsDirectory), lowerCaseResult);
+ }
+
+ [Fact]
+ public void GetFile_GivenFilePathsWithDifferentCasing_ReturnsCorrectFile()
+ {
+ const string lowerCasePath = "/music/someartist/song 1.mp3";
+ var lowerCaseFileSystemMetadata = new FileSystemMetadata
+ {
+ FullName = lowerCasePath,
+ Exists = true
+ };
+ const string upperCasePath = "/music/SOMEARTIST/SONG 1.mp3";
+ var upperCaseFileSystemMetadata = new FileSystemMetadata
+ {
+ FullName = upperCasePath,
+ Exists = false
+ };
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFileInfo(It.Is<string>(x => x == upperCasePath))).Returns(upperCaseFileSystemMetadata);
+ fileSystemMock.Setup(f => f.GetFileInfo(It.Is<string>(x => x == lowerCasePath))).Returns(lowerCaseFileSystemMetadata);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var lowerCaseResult = directoryService.GetFile(lowerCasePath);
+ var upperCaseResult = directoryService.GetFile(upperCasePath);
+
+ Assert.Equal(lowerCaseFileSystemMetadata, lowerCaseResult);
+ Assert.Null(upperCaseResult);
+ }
+
+ [Fact]
+ public void GetFile_GivenCachedPath_ReturnsCachedFile()
+ {
+ const string path = "/music/someartist/song 1.mp3";
+ var cachedFileSystemMetadata = new FileSystemMetadata
+ {
+ FullName = path,
+ Exists = true
+ };
+ var newFileSystemMetadata = new FileSystemMetadata
+ {
+ FullName = "/music/SOMEARTIST/song 1.mp3",
+ Exists = true
+ };
+
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFileInfo(It.Is<string>(x => x == path))).Returns(cachedFileSystemMetadata);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var result = directoryService.GetFile(path);
+ fileSystemMock.Setup(f => f.GetFileInfo(It.Is<string>(x => x == path))).Returns(newFileSystemMetadata);
+ var secondResult = directoryService.GetFile(path);
+
+ Assert.Equal(cachedFileSystemMetadata, result);
+ Assert.Equal(cachedFileSystemMetadata, secondResult);
+ }
+
+ [Fact]
+ public void GetFilePaths_GivenCachedFilePathWithoutClear_ReturnsOnlyCachedPaths()
+ {
+ const string path = "/music/someartist";
+
+ var cachedPaths = new[]
+ {
+ "/music/someartist/song 1.mp3",
+ "/music/someartist/song 2.mp3",
+ "/music/someartist/song 3.mp3",
+ "/music/someartist/song 4.mp3",
+ };
+ var newPaths = new[]
+ {
+ "/music/someartist/song 5.mp3",
+ "/music/someartist/song 6.mp3",
+ "/music/someartist/song 7.mp3",
+ "/music/someartist/song 8.mp3",
+ };
+
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFilePaths(It.Is<string>(x => x == path), false)).Returns(cachedPaths);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var result = directoryService.GetFilePaths(path);
+ fileSystemMock.Setup(f => f.GetFilePaths(It.Is<string>(x => x == path), false)).Returns(newPaths);
+ var secondResult = directoryService.GetFilePaths(path);
+
+ Assert.Equal(cachedPaths, result);
+ Assert.Equal(cachedPaths, secondResult);
+ }
+
+ [Fact]
+ public void GetFilePaths_GivenCachedFilePathWithClear_ReturnsNewPaths()
+ {
+ const string path = "/music/someartist";
+
+ var cachedPaths = new[]
+ {
+ "/music/someartist/song 1.mp3",
+ "/music/someartist/song 2.mp3",
+ "/music/someartist/song 3.mp3",
+ "/music/someartist/song 4.mp3",
+ };
+ var newPaths = new[]
+ {
+ "/music/someartist/song 5.mp3",
+ "/music/someartist/song 6.mp3",
+ "/music/someartist/song 7.mp3",
+ "/music/someartist/song 8.mp3",
+ };
+
+ var fileSystemMock = new Mock<IFileSystem>();
+ fileSystemMock.Setup(f => f.GetFilePaths(It.Is<string>(x => x == path), false)).Returns(cachedPaths);
+ var directoryService = new DirectoryService(fileSystemMock.Object);
+
+ var result = directoryService.GetFilePaths(path);
+ fileSystemMock.Setup(f => f.GetFilePaths(It.Is<string>(x => x == path), false)).Returns(newPaths);
+ var secondResult = directoryService.GetFilePaths(path, true);
+
+ Assert.Equal(cachedPaths, result);
+ Assert.Equal(newPaths, secondResult);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj
new file mode 100644
index 000000000..0ffc19833
--- /dev/null
+++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj
@@ -0,0 +1,33 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{462584F7-5023-4019-9EAC-B98CA458C0A0}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Controller/MediaBrowser.Controller.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs
new file mode 100644
index 000000000..668bd8f87
--- /dev/null
+++ b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs
@@ -0,0 +1,131 @@
+using Emby.Dlna;
+using Emby.Dlna.PlayTo;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller;
+using MediaBrowser.Model.Dlna;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Dlna.Tests
+{
+ public class DlnaManagerTests
+ {
+ private DlnaManager GetManager()
+ {
+ var xmlSerializer = new Mock<IXmlSerializer>();
+ var fileSystem = new Mock<IFileSystem>();
+ var appPaths = new Mock<IApplicationPaths>();
+ var loggerFactory = new Mock<ILoggerFactory>();
+ var appHost = new Mock<IServerApplicationHost>();
+
+ return new DlnaManager(xmlSerializer.Object, fileSystem.Object, appPaths.Object, loggerFactory.Object, appHost.Object);
+ }
+
+ [Fact]
+ public void IsMatch_GivenMatchingName_ReturnsTrue()
+ {
+ var device = new DeviceInfo()
+ {
+ Name = "My Device",
+ Manufacturer = "LG Electronics",
+ ManufacturerUrl = "http://www.lge.com",
+ ModelDescription = "LG WebOSTV DMRplus",
+ ModelName = "LG TV",
+ ModelNumber = "1.0",
+ };
+
+ var profile = new DeviceProfile()
+ {
+ Name = "Test Profile",
+ FriendlyName = "My Device",
+ Manufacturer = "LG Electronics",
+ ManufacturerUrl = "http://www.lge.com",
+ ModelDescription = "LG WebOSTV DMRplus",
+ ModelName = "LG TV",
+ ModelNumber = "1.0",
+ Identification = new ()
+ {
+ FriendlyName = "My Device",
+ Manufacturer = "LG Electronics",
+ ManufacturerUrl = "http://www.lge.com",
+ ModelDescription = "LG WebOSTV DMRplus",
+ ModelName = "LG TV",
+ ModelNumber = "1.0",
+ }
+ };
+
+ var profile2 = new DeviceProfile()
+ {
+ Name = "Test Profile",
+ FriendlyName = "My Device",
+ Identification = new DeviceIdentification()
+ {
+ FriendlyName = "My Device",
+ }
+ };
+
+ var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile2.Identification);
+ var deviceMatch2 = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification);
+
+ Assert.True(deviceMatch);
+ Assert.True(deviceMatch2);
+ }
+
+ [Fact]
+ public void IsMatch_GivenNamesAndManufacturersDoNotMatch_ReturnsFalse()
+ {
+ var device = new DeviceInfo()
+ {
+ Name = "My Device",
+ Manufacturer = "JVC"
+ };
+
+ var profile = new DeviceProfile()
+ {
+ Name = "Test Profile",
+ FriendlyName = "My Device",
+ Manufacturer = "LG Electronics",
+ ManufacturerUrl = "http://www.lge.com",
+ ModelDescription = "LG WebOSTV DMRplus",
+ ModelName = "LG TV",
+ ModelNumber = "1.0",
+ Identification = new ()
+ {
+ FriendlyName = "My Device",
+ Manufacturer = "LG Electronics",
+ ManufacturerUrl = "http://www.lge.com",
+ ModelDescription = "LG WebOSTV DMRplus",
+ ModelName = "LG TV",
+ ModelNumber = "1.0",
+ }
+ };
+
+ var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification);
+
+ Assert.False(deviceMatch);
+ }
+
+ [Fact]
+ public void IsMatch_GivenNamesAndRegExMatch_ReturnsTrue()
+ {
+ var device = new DeviceInfo()
+ {
+ Name = "My Device"
+ };
+
+ var profile = new DeviceProfile()
+ {
+ Name = "Test Profile",
+ FriendlyName = "My .*",
+ Identification = new ()
+ };
+
+ var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification);
+
+ Assert.True(deviceMatch);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs b/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs
new file mode 100644
index 000000000..7655e3f7c
--- /dev/null
+++ b/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs
@@ -0,0 +1,17 @@
+using Emby.Dlna.PlayTo;
+using Xunit;
+
+namespace Jellyfin.Dlna.Tests
+{
+ public static class GetUuidTests
+ {
+ [Theory]
+ [InlineData("uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::urn:schemas-upnp-org:device:WANDevice:1", "fc4ec57e-b051-11db-88f8-0060085db3f6")]
+ [InlineData("uuid:IGD{8c80f73f-4ba0-45fa-835d-042505d052be}000000000000", "8c80f73f-4ba0-45fa-835d-042505d052be")]
+ [InlineData("uuid:IGD{8c80f73f-4ba0-45fa-835d-042505d052be}000000000000::urn:schemas-upnp-org:device:InternetGatewayDevice:1", "8c80f73f-4ba0-45fa-835d-042505d052be")]
+ [InlineData("uuid:00000000-0000-0000-0000-000000000000::upnp:rootdevice", "00000000-0000-0000-0000-000000000000")]
+ [InlineData("uuid:fc4ec57e-b051-11db-88f8-0060085db3f6", "fc4ec57e-b051-11db-88f8-0060085db3f6")]
+ public static void GetUuid_Valid_Success(string usn, string uuid)
+ => Assert.Equal(uuid, PlayToManager.GetUuid(usn));
+ }
+}
diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj
new file mode 100644
index 000000000..098166001
--- /dev/null
+++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj
@@ -0,0 +1,28 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../Emby.Dlna/Emby.Dlna.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Extensions.Tests/AlphanumericComparatorTests.cs b/tests/Jellyfin.Extensions.Tests/AlphanumericComparatorTests.cs
new file mode 100644
index 000000000..7730841a1
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/AlphanumericComparatorTests.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Linq;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests
+{
+ public class AlphanumericComparatorTests
+ {
+ // InlineData is pre-sorted
+ [Theory]
+ [InlineData(null, "", "1", "9", "10", "a", "z")]
+ [InlineData("50F", "100F", "SR9", "SR100")]
+ [InlineData("image-1.jpg", "image-02.jpg", "image-4.jpg", "image-9.jpg", "image-10.jpg", "image-11.jpg", "image-22.jpg")]
+ [InlineData("Hard drive 2GB", "Hard drive 20GB")]
+ [InlineData("b", "e", "è", "ě", "f", "g", "k")]
+ [InlineData("123456789", "123456789a", "abc", "abcd")]
+ [InlineData("12345678912345678912345678913234567891", "123456789123456789123456789132345678912")]
+ [InlineData("12345678912345678912345678913234567891", "12345678912345678912345678913234567891")]
+ [InlineData("12345678912345678912345678913234567891", "12345678912345678912345678913234567892")]
+ [InlineData("12345678912345678912345678913234567891a", "12345678912345678912345678913234567891a")]
+ [InlineData("12345678912345678912345678913234567891a", "12345678912345678912345678913234567891b")]
+ public void AlphanumericComparatorTest(params string?[] strings)
+ {
+ var copy = strings.Reverse().ToArray();
+ Array.Sort(copy, new AlphanumericComparator());
+ Assert.True(strings.SequenceEqual(copy));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/CopyToExtensionsTests.cs b/tests/Jellyfin.Extensions.Tests/CopyToExtensionsTests.cs
new file mode 100644
index 000000000..d46beedd9
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/CopyToExtensionsTests.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Collections.Generic;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests
+{
+ public static class CopyToExtensionsTests
+ {
+ public static TheoryData<IReadOnlyList<int>, IList<int>, int, IList<int>> CopyTo_Valid_Correct_TestData()
+ {
+ var data = new TheoryData<IReadOnlyList<int>, IList<int>, int, IList<int>>();
+
+ data.Add(
+ new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, 0, new[] { 0, 1, 2, 3, 4, 5 });
+
+ data.Add(
+ new[] { 0, 1, 2 }, new[] { 5, 4, 3, 2, 1, 0 }, 2, new[] { 5, 4, 0, 1, 2, 0 } );
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(CopyTo_Valid_Correct_TestData))]
+ public static void CopyTo_Valid_Correct<T>(IReadOnlyList<T> source, IList<T> destination, int index, IList<T> expected)
+ {
+ source.CopyTo(destination, index);
+ Assert.Equal(expected, destination);
+ }
+
+ public static TheoryData<IReadOnlyList<int>, IList<int>, int> CopyTo_Invalid_ThrowsArgumentOutOfRangeException_TestData()
+ {
+ var data = new TheoryData<IReadOnlyList<int>, IList<int>, int>();
+
+ data.Add(
+ new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, -1 );
+
+ data.Add(
+ new[] { 0, 1, 2 }, new[] { 5, 4, 3, 2, 1, 0 }, 6 );
+
+ data.Add(
+ new[] { 0, 1, 2 }, Array.Empty<int>(), 0 );
+
+ data.Add(
+ new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0 }, 0 );
+
+ data.Add(
+ new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, 1 );
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(CopyTo_Invalid_ThrowsArgumentOutOfRangeException_TestData))]
+ public static void CopyTo_Invalid_ThrowsArgumentOutOfRangeException<T>(IReadOnlyList<T> source, IList<T> destination, int index)
+ {
+ Assert.Throws<ArgumentOutOfRangeException>(() => source.CopyTo(destination, index));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj b/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj
new file mode 100644
index 000000000..ee3af7559
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj
@@ -0,0 +1,35 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="coverlet.collector" Version="3.1.0">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="FsCheck.Xunit" Version="2.16.3" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Model/MediaBrowser.Model.csproj" />
+ <ProjectReference Include="../../src/Jellyfin.Extensions/Jellyfin.Extensions.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonBoolNumberTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonBoolNumberTests.cs
new file mode 100644
index 000000000..125229ff9
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonBoolNumberTests.cs
@@ -0,0 +1,44 @@
+using System.Text.Json;
+using FsCheck;
+using FsCheck.Xunit;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonBoolNumberTests
+ {
+ private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions()
+ {
+ Converters =
+ {
+ new JsonBoolNumberConverter()
+ }
+ };
+
+ [Theory]
+ [InlineData("1", true)]
+ [InlineData("0", false)]
+ [InlineData("2", true)]
+ [InlineData("true", true)]
+ [InlineData("false", false)]
+ public void Deserialize_Number_Valid_Success(string input, bool? output)
+ {
+ var value = JsonSerializer.Deserialize<bool>(input, _jsonOptions);
+ Assert.Equal(value, output);
+ }
+
+ [Theory]
+ [InlineData(true, "true")]
+ [InlineData(false, "false")]
+ public void Serialize_Bool_Success(bool input, string output)
+ {
+ var value = JsonSerializer.Serialize(input, _jsonOptions);
+ Assert.Equal(value, output);
+ }
+
+ [Property]
+ public Property Deserialize_NonZeroInt_True(NonZeroInt input)
+ => JsonSerializer.Deserialize<bool>(input.ToString(), _jsonOptions).ToProperty();
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedArrayTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedArrayTests.cs
new file mode 100644
index 000000000..f2ca2ff08
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedArrayTests.cs
@@ -0,0 +1,142 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Tests.Json.Models;
+using MediaBrowser.Model.Session;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public static class JsonCommaDelimitedArrayTests
+ {
+ [Fact]
+ public static void Deserialize_String_Null_Success()
+ {
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<string>>(@"{ ""Value"": null }", options);
+ Assert.Null(value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_Empty_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<string>
+ {
+ Value = Array.Empty<string>()
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<string>>(@"{ ""Value"": """" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_String_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<string>>(@"{ ""Value"": ""a,b,c"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_String_Space_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<string>>(@"{ ""Value"": ""a, b, c"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_EmptyEntry_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp,,MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Invalid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp,TotallyNotAVallidCommand,MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Space_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_String_Array_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<string>>(@"{ ""Value"": [""a"",""b"",""c""] }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Array_Valid_Success()
+ {
+ var desiredValue = new GenericBodyArrayModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyArrayModel<GeneralCommandType>>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedIReadOnlyListTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedIReadOnlyListTests.cs
new file mode 100644
index 000000000..92886dcd2
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonCommaDelimitedIReadOnlyListTests.cs
@@ -0,0 +1,92 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Tests.Json.Models;
+using MediaBrowser.Model.Session;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public static class JsonCommaDelimitedIReadOnlyListTests
+ {
+ [Fact]
+ public static void Deserialize_String_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<string>>(@"{ ""Value"": ""a,b,c"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_String_Space_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<string>>(@"{ ""Value"": ""a, b, c"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Space_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<GeneralCommandType>>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_String_Array_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<string>
+ {
+ Value = new[] { "a", "b", "c" }
+ };
+
+ var options = new JsonSerializerOptions();
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<string>>(@"{ ""Value"": [""a"",""b"",""c""] }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+
+ [Fact]
+ public static void Deserialize_GenericCommandType_Array_Valid_Success()
+ {
+ var desiredValue = new GenericBodyIReadOnlyListModel<GeneralCommandType>
+ {
+ Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown }
+ };
+
+ var options = new JsonSerializerOptions();
+ options.Converters.Add(new JsonStringEnumConverter());
+ var value = JsonSerializer.Deserialize<GenericBodyIReadOnlyListModel<GeneralCommandType>>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options);
+ Assert.Equal(desiredValue.Value, value?.Value);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonGuidConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonGuidConverterTests.cs
new file mode 100644
index 000000000..8465d465a
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonGuidConverterTests.cs
@@ -0,0 +1,68 @@
+using System;
+using System.Text.Json;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonGuidConverterTests
+ {
+ private readonly JsonSerializerOptions _options;
+
+ public JsonGuidConverterTests()
+ {
+ _options = new JsonSerializerOptions();
+ _options.Converters.Add(new JsonGuidConverter());
+ }
+
+ [Fact]
+ public void Deserialize_Valid_Success()
+ {
+ Guid value = JsonSerializer.Deserialize<Guid>(@"""a852a27afe324084ae66db579ee3ee18""", _options);
+ Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value);
+ }
+
+ [Fact]
+ public void Deserialize_ValidDashed_Success()
+ {
+ Guid value = JsonSerializer.Deserialize<Guid>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", _options);
+ Assert.Equal(new Guid("e9b2dcaa-529c-426e-9433-5e9981f27f2e"), value);
+ }
+
+ [Fact]
+ public void Roundtrip_Valid_Success()
+ {
+ Guid guid = new Guid("a852a27afe324084ae66db579ee3ee18");
+ string value = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal(guid, JsonSerializer.Deserialize<Guid>(value, _options));
+ }
+
+ [Fact]
+ public void Deserialize_Null_EmptyGuid()
+ {
+ Assert.Equal(Guid.Empty, JsonSerializer.Deserialize<Guid>("null", _options));
+ }
+
+ [Fact]
+ public void Serialize_EmptyGuid_EmptyGuid()
+ {
+ Assert.Equal($"\"{Guid.Empty:N}\"", JsonSerializer.Serialize(Guid.Empty, _options));
+ }
+
+ [Fact]
+ public void Serialize_Valid_NoDash_Success()
+ {
+ var guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
+ var str = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal($"\"{guid:N}\"", str);
+ }
+
+ [Fact]
+ public void Serialize_Nullable_Success()
+ {
+ Guid? guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
+ var str = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal($"\"{guid:N}\"", str);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonLowerCaseConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonLowerCaseConverterTests.cs
new file mode 100644
index 000000000..af9227de2
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonLowerCaseConverterTests.cs
@@ -0,0 +1,71 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+using MediaBrowser.Model.Entities;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonLowerCaseConverterTests
+ {
+ private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions()
+ {
+ Converters =
+ {
+ new JsonStringEnumConverter()
+ }
+ };
+
+ [Theory]
+ [InlineData(null, "{\"CollectionType\":null}")]
+ [InlineData(CollectionTypeOptions.Movies, "{\"CollectionType\":\"movies\"}")]
+ [InlineData(CollectionTypeOptions.MusicVideos, "{\"CollectionType\":\"musicvideos\"}")]
+ public void Serialize_CollectionTypeOptions_Correct(CollectionTypeOptions? collectionType, string expected)
+ {
+ Assert.Equal(expected, JsonSerializer.Serialize(new TestContainer(collectionType), _jsonOptions));
+ }
+
+ [Theory]
+ [InlineData("{\"CollectionType\":null}", null)]
+ [InlineData("{\"CollectionType\":\"movies\"}", CollectionTypeOptions.Movies)]
+ [InlineData("{\"CollectionType\":\"musicvideos\"}", CollectionTypeOptions.MusicVideos)]
+ public void Deserialize_CollectionTypeOptions_Correct(string json, CollectionTypeOptions? result)
+ {
+ var res = JsonSerializer.Deserialize<TestContainer>(json, _jsonOptions);
+ Assert.NotNull(res);
+ Assert.Equal(result, res!.CollectionType);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData(CollectionTypeOptions.Movies)]
+ [InlineData(CollectionTypeOptions.MusicVideos)]
+ public void RoundTrip_CollectionTypeOptions_Correct(CollectionTypeOptions? value)
+ {
+ var res = JsonSerializer.Deserialize<TestContainer>(JsonSerializer.Serialize(new TestContainer(value), _jsonOptions), _jsonOptions);
+ Assert.NotNull(res);
+ Assert.Equal(value, res!.CollectionType);
+ }
+
+ [Theory]
+ [InlineData("{\"CollectionType\":null}")]
+ [InlineData("{\"CollectionType\":\"movies\"}")]
+ [InlineData("{\"CollectionType\":\"musicvideos\"}")]
+ public void RoundTrip_String_Correct(string json)
+ {
+ var res = JsonSerializer.Serialize(JsonSerializer.Deserialize<TestContainer>(json, _jsonOptions), _jsonOptions);
+ Assert.Equal(json, res);
+ }
+
+ private class TestContainer
+ {
+ public TestContainer(CollectionTypeOptions? collectionType)
+ {
+ CollectionType = collectionType;
+ }
+
+ [JsonConverter(typeof(JsonLowerCaseConverter<CollectionTypeOptions?>))]
+ public CollectionTypeOptions? CollectionType { get; set; }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonNullableGuidConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonNullableGuidConverterTests.cs
new file mode 100644
index 000000000..b0dbc09e4
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonNullableGuidConverterTests.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Text.Json;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonNullableGuidConverterTests
+ {
+ private readonly JsonSerializerOptions _options;
+
+ public JsonNullableGuidConverterTests()
+ {
+ _options = new JsonSerializerOptions();
+ _options.Converters.Add(new JsonNullableGuidConverter());
+ }
+
+ [Fact]
+ public void Deserialize_Valid_Success()
+ {
+ Guid? value = JsonSerializer.Deserialize<Guid?>(@"""a852a27afe324084ae66db579ee3ee18""", _options);
+ Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value);
+ }
+
+ [Fact]
+ public void Deserialize_ValidDashed_Success()
+ {
+ Guid? value = JsonSerializer.Deserialize<Guid?>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", _options);
+ Assert.Equal(new Guid("e9b2dcaa-529c-426e-9433-5e9981f27f2e"), value);
+ }
+
+ [Fact]
+ public void Roundtrip_Valid_Success()
+ {
+ Guid guid = new Guid("a852a27afe324084ae66db579ee3ee18");
+ string value = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal(guid, JsonSerializer.Deserialize<Guid?>(value, _options));
+ }
+
+ [Fact]
+ public void Deserialize_Null_Null()
+ {
+ Assert.Null(JsonSerializer.Deserialize<Guid?>("null", _options));
+ }
+
+ [Fact]
+ public void Deserialize_EmptyGuid_EmptyGuid()
+ {
+ Assert.Equal(Guid.Empty, JsonSerializer.Deserialize<Guid?>(@"""00000000-0000-0000-0000-000000000000""", _options));
+ }
+
+ [Fact]
+ public void Serialize_EmptyGuid_Null()
+ {
+ Assert.Equal("null", JsonSerializer.Serialize((Guid?)Guid.Empty, _options));
+ }
+
+ [Fact]
+ public void Serialize_Null_Null()
+ {
+ Assert.Equal("null", JsonSerializer.Serialize((Guid?)null, _options));
+ }
+
+ [Fact]
+ public void Serialize_Valid_NoDash_Success()
+ {
+ var guid = (Guid?)new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
+ var str = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal($"\"{guid:N}\"", str);
+ }
+
+ [Fact]
+ public void Serialize_Nullable_Success()
+ {
+ Guid? guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA");
+ var str = JsonSerializer.Serialize(guid, _options);
+ Assert.Equal($"\"{guid:N}\"", str);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonStringConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonStringConverterTests.cs
new file mode 100644
index 000000000..655e07074
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonStringConverterTests.cs
@@ -0,0 +1,38 @@
+using System.Text.Json;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonStringConverterTests
+ {
+ private readonly JsonSerializerOptions _jsonSerializerOptions = new ()
+ {
+ Converters =
+ {
+ new JsonStringConverter()
+ }
+ };
+
+ [Theory]
+ [InlineData("\"test\"", "test")]
+ [InlineData("123", "123")]
+ [InlineData("123.45", "123.45")]
+ [InlineData("true", "true")]
+ [InlineData("false", "false")]
+ public void Deserialize_String_Valid_Success(string input, string output)
+ {
+ var deserialized = JsonSerializer.Deserialize<string>(input, _jsonSerializerOptions);
+ Assert.Equal(deserialized, output);
+ }
+
+ [Fact]
+ public void Deserialize_Int32asInt32_Valid_Success()
+ {
+ const string? input = "123";
+ const int output = 123;
+ var deserialized = JsonSerializer.Deserialize<int>(input, _jsonSerializerOptions);
+ Assert.Equal(deserialized, output);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonVersionConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonVersionConverterTests.cs
new file mode 100644
index 000000000..5fbac7eab
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonVersionConverterTests.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Text.Json;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters
+{
+ public class JsonVersionConverterTests
+ {
+ private readonly JsonSerializerOptions _options;
+
+ public JsonVersionConverterTests()
+ {
+ _options = new JsonSerializerOptions();
+ _options.Converters.Add(new JsonVersionConverter());
+ }
+
+ [Fact]
+ public void Deserialize_Version_Success()
+ {
+ var input = "\"1.025.222\"";
+ var output = new Version(1, 25, 222);
+ var deserializedInput = JsonSerializer.Deserialize<Version>(input, _options);
+ Assert.Equal(output, deserializedInput);
+ }
+
+ [Fact]
+ public void Serialize_Version_Success()
+ {
+ var input = new Version(1, 09, 59);
+ var output = "\"1.9.59\"";
+ var serializedInput = JsonSerializer.Serialize(input, _options);
+ Assert.Equal(output, serializedInput);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyArrayModel.cs b/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyArrayModel.cs
new file mode 100644
index 000000000..ef135278f
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyArrayModel.cs
@@ -0,0 +1,20 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+
+namespace Jellyfin.Extensions.Tests.Json.Models
+{
+ /// <summary>
+ /// The generic body model.
+ /// </summary>
+ /// <typeparam name="T">The value type.</typeparam>
+ public class GenericBodyArrayModel<T>
+ {
+ /// <summary>
+ /// Gets or sets the value.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA1819:Properties should not return arrays", MessageId = "Value", Justification = "Imported from ServiceStack")]
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public T[] Value { get; set; } = default!;
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyIReadOnlyListModel.cs b/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyIReadOnlyListModel.cs
new file mode 100644
index 000000000..8e7b5a35b
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Models/GenericBodyIReadOnlyListModel.cs
@@ -0,0 +1,19 @@
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json.Converters;
+
+namespace Jellyfin.Extensions.Tests.Json.Models
+{
+ /// <summary>
+ /// The generic body <c>IReadOnlyList</c> model.
+ /// </summary>
+ /// <typeparam name="T">The value type.</typeparam>
+ public class GenericBodyIReadOnlyListModel<T>
+ {
+ /// <summary>
+ /// Gets or sets the value.
+ /// </summary>
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList<T> Value { get; set; } = default!;
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/ShuffleExtensionsTests.cs b/tests/Jellyfin.Extensions.Tests/ShuffleExtensionsTests.cs
new file mode 100644
index 000000000..a73cfb078
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/ShuffleExtensionsTests.cs
@@ -0,0 +1,19 @@
+using System;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests
+{
+ public static class ShuffleExtensionsTests
+ {
+ [Fact]
+ public static void Shuffle_Valid_Correct()
+ {
+ byte[] original = new byte[1 << 6];
+ Random.Shared.NextBytes(original);
+ byte[] shuffled = (byte[])original.Clone();
+ shuffled.Shuffle();
+
+ Assert.NotEqual(original, shuffled);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/StringExtensionsTests.cs b/tests/Jellyfin.Extensions.Tests/StringExtensionsTests.cs
new file mode 100644
index 000000000..7186cc023
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/StringExtensionsTests.cs
@@ -0,0 +1,41 @@
+using System;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests
+{
+ public class StringExtensionsTests
+ {
+ [Theory]
+ [InlineData("", '_', 0)]
+ [InlineData("___", '_', 3)]
+ [InlineData("test\x00", '\x00', 1)]
+ [InlineData("Imdb=tt0119567|Tmdb=330|TmdbCollection=328", '|', 2)]
+ public void ReadOnlySpan_Count_Success(string str, char needle, int count)
+ {
+ Assert.Equal(count, str.AsSpan().Count(needle));
+ }
+
+ [Theory]
+ [InlineData("", 'q', "")]
+ [InlineData("Banana split", ' ', "Banana")]
+ [InlineData("Banana split", 'q', "Banana split")]
+ [InlineData("Banana split 2", ' ', "Banana")]
+ public void LeftPart_ValidArgsCharNeedle_Correct(string str, char needle, string expectedResult)
+ {
+ var result = str.AsSpan().LeftPart(needle).ToString();
+ Assert.Equal(expectedResult, result);
+ }
+
+ [Theory]
+ [InlineData("", 'q', "")]
+ [InlineData("Banana split", ' ', "split")]
+ [InlineData("Banana split", 'q', "Banana split")]
+ [InlineData("Banana split.", '.', "")]
+ [InlineData("Banana split 2", ' ', "2")]
+ public void RightPart_ValidArgsCharNeedle_Correct(string str, char needle, string expectedResult)
+ {
+ var result = str.AsSpan().RightPart(needle).ToString();
+ Assert.Equal(expectedResult, result);
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTests.cs b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTests.cs
new file mode 100644
index 000000000..c0c363d3d
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTests.cs
@@ -0,0 +1,52 @@
+using System;
+using MediaBrowser.MediaEncoding.Encoder;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Tests
+{
+ public class EncoderValidatorTests
+ {
+ private readonly EncoderValidator _encoderValidator = new EncoderValidator(new NullLogger<EncoderValidatorTests>(), "ffmpeg");
+
+ [Theory]
+ [ClassData(typeof(GetFFmpegVersionTestData))]
+ public void GetFFmpegVersionTest(string versionOutput, Version? version)
+ {
+ Assert.Equal(version, _encoderValidator.GetFFmpegVersionInternal(versionOutput));
+ }
+
+ [Theory]
+ [InlineData(EncoderValidatorTestsData.FFmpegV44Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV432Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV431Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV43Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV421Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV42Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV414Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegV404Output, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegGitUnknownOutput2, true)]
+ [InlineData(EncoderValidatorTestsData.FFmpegGitUnknownOutput, false)]
+ public void ValidateVersionInternalTest(string versionOutput, bool valid)
+ {
+ Assert.Equal(valid, _encoderValidator.ValidateVersionInternal(versionOutput));
+ }
+
+ private class GetFFmpegVersionTestData : TheoryData<string, Version?>
+ {
+ public GetFFmpegVersionTestData()
+ {
+ Add(EncoderValidatorTestsData.FFmpegV44Output, new Version(4, 4));
+ Add(EncoderValidatorTestsData.FFmpegV432Output, new Version(4, 3, 2));
+ Add(EncoderValidatorTestsData.FFmpegV431Output, new Version(4, 3, 1));
+ Add(EncoderValidatorTestsData.FFmpegV43Output, new Version(4, 3));
+ Add(EncoderValidatorTestsData.FFmpegV421Output, new Version(4, 2, 1));
+ Add(EncoderValidatorTestsData.FFmpegV42Output, new Version(4, 2));
+ Add(EncoderValidatorTestsData.FFmpegV414Output, new Version(4, 1, 4));
+ Add(EncoderValidatorTestsData.FFmpegV404Output, new Version(4, 0, 4));
+ Add(EncoderValidatorTestsData.FFmpegGitUnknownOutput2, new Version(4, 0));
+ Add(EncoderValidatorTestsData.FFmpegGitUnknownOutput, null);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs
new file mode 100644
index 000000000..02bf046ed
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs
@@ -0,0 +1,126 @@
+namespace Jellyfin.MediaEncoding.Tests
+{
+ internal static class EncoderValidatorTestsData
+ {
+ public const string FFmpegV44Output = @"ffmpeg version 4.4-Jellyfin Copyright (c) 2000-2021 the FFmpeg developers
+built with gcc 10.3.0 (Rev5, Built by MSYS2 project)
+configuration: --disable-static --enable-shared --extra-version=Jellyfin --disable-ffplay --disable-debug --enable-gpl --enable-version3 --enable-bzlib --enable-iconv --enable-lzma --enable-zlib --enable-sdl2 --enable-fontconfig --enable-gmp --enable-libass --enable-libzimg --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libvpx --enable-libx264 --enable-libx265 --enable-libdav1d --enable-opencl --enable-dxva2 --enable-d3d11va --enable-amf --enable-libmfx --enable-cuda --enable-cuda-llvm --enable-cuvid --enable-nvenc --enable-nvdec --enable-ffnvcodec --enable-gnutls
+libavutil 56. 70.100 / 56. 70.100
+libavcodec 58.134.100 / 58.134.100
+libavformat 58. 76.100 / 58. 76.100
+libavdevice 58. 13.100 / 58. 13.100
+libavfilter 7.110.100 / 7.110.100
+libswscale 5. 9.100 / 5. 9.100
+libswresample 3. 9.100 / 3. 9.100
+libpostproc 55. 9.100 / 55. 9.100";
+
+ public const string FFmpegV432Output = @"ffmpeg version n4.3.2-Jellyfin Copyright (c) 2000-2021 the FFmpeg developers
+built with gcc 10.2.0 (Rev9, Built by MSYS2 project)
+configuration: --disable-static --enable-shared --cc='ccache gcc' --cxx='ccache g++' --extra-version=Jellyfin --disable-ffplay --disable-debug --enable-lto --enable-gpl --enable-version3 --enable-bzlib --enable-iconv --enable-lzma --enable-zlib --enable-sdl2 --enable-fontconfig --enable-gmp --enable-libass --enable-libzimg --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libvpx --enable-libx264 --enable-libx265 --enable-libdav1d --enable-opencl --enable-dxva2 --enable-d3d11va --enable-amf --enable-libmfx --enable-cuda --enable-cuda-llvm --enable-cuvid --enable-nvenc --enable-nvdec --enable-ffnvcodec --enable-gnutls
+libavutil 56. 51.100 / 56. 51.100
+libavcodec 58. 91.100 / 58. 91.100
+libavformat 58. 45.100 / 58. 45.100
+libavdevice 58. 10.100 / 58. 10.100
+libavfilter 7. 85.100 / 7. 85.100
+libswscale 5. 7.100 / 5. 7.100
+libswresample 3. 7.100 / 3. 7.100
+libpostproc 55. 7.100 / 55. 7.100";
+
+ public const string FFmpegV431Output = @"ffmpeg version n4.3.1 Copyright (c) 2000-2020 the FFmpeg developers
+built with gcc 10.1.0 (GCC)
+configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-avisynth --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmfx --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librav1e --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-nvdec --enable-nvenc --enable-omx --enable-shared --enable-version3
+libavutil 56. 51.100 / 56. 51.100
+libavcodec 58. 91.100 / 58. 91.100
+libavformat 58. 45.100 / 58. 45.100
+libavdevice 58. 10.100 / 58. 10.100
+libavfilter 7. 85.100 / 7. 85.100
+libswscale 5. 7.100 / 5. 7.100
+libswresample 3. 7.100 / 3. 7.100
+libpostproc 55. 7.100 / 55. 7.100";
+
+ public const string FFmpegV43Output = @"ffmpeg version 4.3 Copyright (c) 2000-2020 the FFmpeg developers
+built with gcc 7 (Ubuntu 7.5.0-3ubuntu1~18.04)
+configuration: --prefix=/usr/lib/jellyfin-ffmpeg --target-os=linux --disable-doc --disable-ffplay --disable-shared --disable-libxcb --disable-vdpau --disable-sdl2 --disable-xlib --enable-gpl --enable-version3 --enable-static --enable-libfontconfig --enable-fontconfig --enable-gmp --enable-gnutls --enable-libass --enable-libbluray --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libx264 --enable-libx265 --enable-libzvbi --arch=amd64 --enable-amf --enable-nvenc --enable-nvdec --enable-vaapi --enable-opencl
+libavutil 56. 51.100 / 56. 51.100
+libavcodec 58. 91.100 / 58. 91.100
+libavformat 58. 45.100 / 58. 45.100
+libavdevice 58. 10.100 / 58. 10.100
+libavfilter 7. 85.100 / 7. 85.100
+libswscale 5. 7.100 / 5. 7.100
+libswresample 3. 7.100 / 3. 7.100
+libpostproc 55. 7.100 / 55. 7.100";
+
+ public const string FFmpegV421Output = @"ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers
+built with gcc 9.1.1 (GCC) 20190807
+configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
+libavutil 56. 31.100 / 56. 31.100
+libavcodec 58. 54.100 / 58. 54.100
+libavformat 58. 29.100 / 58. 29.100
+libavdevice 58. 8.100 / 58. 8.100
+libavfilter 7. 57.100 / 7. 57.100
+libswscale 5. 5.100 / 5. 5.100
+libswresample 3. 5.100 / 3. 5.100
+libpostproc 55. 5.100 / 55. 5.100";
+
+ public const string FFmpegV42Output = @"ffmpeg version n4.2 Copyright (c) 2000-2019 the FFmpeg developers
+built with gcc 9.1.0 (GCC)
+configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-nvdec --enable-nvenc --enable-omx --enable-shared --enable-version3
+libavutil 56. 31.100 / 56. 31.100
+libavcodec 58. 54.100 / 58. 54.100
+libavformat 58. 29.100 / 58. 29.100
+libavdevice 58. 8.100 / 58. 8.100
+libavfilter 7. 57.100 / 7. 57.100
+libswscale 5. 5.100 / 5. 5.100
+libswresample 3. 5.100 / 3. 5.100
+libpostproc 55. 5.100 / 55. 5.100";
+
+ public const string FFmpegV414Output = @"ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers
+built with gcc 8 (Raspbian 8.3.0-6+rpi1)
+configuration: --prefix=/usr --extra-version='1~deb10u1' --toolchain=hardened --libdir=/usr/lib/arm-linux-gnueabihf --incdir=/usr/include/arm-linux-gnueabihf --arch=arm --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
+libavutil 56. 22.100 / 56. 22.100
+libavcodec 58. 35.100 / 58. 35.100
+libavformat 58. 20.100 / 58. 20.100
+libavdevice 58. 5.100 / 58. 5.100
+libavfilter 7. 40.101 / 7. 40.101
+libavresample 4. 0. 0 / 4. 0. 0
+libswscale 5. 3.100 / 5. 3.100
+libswresample 3. 3.100 / 3. 3.100
+libpostproc 55. 3.100 / 55. 3.100";
+
+ public const string FFmpegV404Output = @"ffmpeg version 4.0.4 Copyright (c) 2000-2019 the FFmpeg developers
+built with gcc 8 (Debian 8.3.0-6)
+configuration: --toolchain=hardened --prefix=/usr --target-os=linux --enable-cross-compile --extra-cflags=--static --enable-gpl --enable-static --disable-doc --disable-ffplay --disable-shared --disable-libxcb --disable-sdl2 --disable-xlib --enable-libfontconfig --enable-fontconfig --enable-gmp --enable-gnutls --enable-libass --enable-libbluray --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libx264 --enable-libx265 --enable-libzvbi --enable-omx --enable-omx-rpi --enable-version3 --enable-vaapi --enable-vdpau --arch=amd64 --enable-nvenc --enable-nvdec
+libavutil 56. 14.100 / 56. 14.100
+libavcodec 58. 18.100 / 58. 18.100
+libavformat 58. 12.100 / 58. 12.100
+libavdevice 58. 3.100 / 58. 3.100
+libavfilter 7. 16.100 / 7. 16.100
+libswscale 5. 1.100 / 5. 1.100
+libswresample 3. 1.100 / 3. 1.100
+libpostproc 55. 1.100 / 55. 1.100";
+
+ public const string FFmpegGitUnknownOutput2 = @"ffmpeg version N-94303-g7cb4f8c962 Copyright (c) 2000-2019 the FFmpeg developers
+built with gcc 9.1.1 (GCC) 20190716
+configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
+libavutil 56. 30.100 / 56. 30.100
+libavcodec 58. 53.101 / 58. 53.101
+libavformat 58. 28.102 / 58. 28.102
+libavdevice 58. 7.100 / 58. 7.100
+libavfilter 7. 56.101 / 7. 56.101
+libswscale 5. 4.101 / 5. 4.101
+libswresample 3. 4.100 / 3. 4.100
+libpostproc 55. 4.100 / 55. 4.100";
+
+ public const string FFmpegGitUnknownOutput = @"ffmpeg version N-45325-gb173e0353-static https://johnvansickle.com/ffmpeg/ Copyright (c) 2000-2018 the FFmpeg developers
+built with gcc 6.3.0 (Debian 6.3.0-18+deb9u1) 20170516
+configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc-6 --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gray --enable-libfribidi --enable-libass --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg
+libavutil 56. 9.100 / 56. 9.100
+libavcodec 58. 14.100 / 58. 14.100
+libavformat 58. 10.100 / 58. 10.100
+libavdevice 58. 2.100 / 58. 2.100
+libavfilter 7. 13.100 / 7. 13.100
+libswscale 5. 0.102 / 5. 0.102
+libswresample 3. 0.101 / 3. 0.101
+libpostproc 55. 0.100 / 55. 0.100";
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs
new file mode 100644
index 000000000..97dbb3be0
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs
@@ -0,0 +1,25 @@
+using System.IO;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.MediaEncoding.Probing;
+using MediaBrowser.Model.IO;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Tests
+{
+ public class FFprobeParserTests
+ {
+ [Theory]
+ [InlineData("ffprobe1.json")]
+ public async Task Test(string fileName)
+ {
+ var path = Path.Join("Test Data", fileName);
+ await using (var stream = AsyncFile.OpenRead(path))
+ {
+ var res = await JsonSerializer.DeserializeAsync<InternalMediaInfoResult>(stream, JsonDefaults.Options).ConfigureAwait(false);
+ Assert.NotNull(res);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj
new file mode 100644
index 000000000..dc4a42c19
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj
@@ -0,0 +1,42 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{28464062-0939-4AA7-9F7B-24DDDA61A7C0}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <None Include="Test Data\**\*.*">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
new file mode 100644
index 000000000..4504924cb
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
@@ -0,0 +1,196 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Text.Json;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.MediaEncoding.Probing;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Tests.Probing
+{
+ public class ProbeResultNormalizerTests
+ {
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private readonly ProbeResultNormalizer _probeResultNormalizer = new ProbeResultNormalizer(new NullLogger<EncoderValidatorTests>(), null);
+
+ [Fact]
+ public void GetMediaInfo_MetaData_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/video_metadata.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_metadata.mkv", MediaProtocol.File);
+
+ Assert.Single(res.MediaStreams);
+
+ Assert.NotNull(res.VideoStream);
+ Assert.Equal("4:3", res.VideoStream.AspectRatio);
+ Assert.Equal(25f, res.VideoStream.AverageFrameRate);
+ Assert.Equal(8, res.VideoStream.BitDepth);
+ Assert.Equal(69432, res.VideoStream.BitRate);
+ Assert.Equal("h264", res.VideoStream.Codec);
+ Assert.Equal("1/50", res.VideoStream.CodecTimeBase);
+ Assert.Equal(240, res.VideoStream.Height);
+ Assert.Equal(320, res.VideoStream.Width);
+ Assert.Equal(0, res.VideoStream.Index);
+ Assert.False(res.VideoStream.IsAnamorphic);
+ Assert.True(res.VideoStream.IsAVC);
+ Assert.True(res.VideoStream.IsDefault);
+ Assert.False(res.VideoStream.IsExternal);
+ Assert.False(res.VideoStream.IsForced);
+ Assert.False(res.VideoStream.IsInterlaced);
+ Assert.False(res.VideoStream.IsTextSubtitleStream);
+ Assert.Equal(13d, res.VideoStream.Level);
+ Assert.Equal("4", res.VideoStream.NalLengthSize);
+ Assert.Equal("yuv444p", res.VideoStream.PixelFormat);
+ Assert.Equal("High 4:4:4 Predictive", res.VideoStream.Profile);
+ Assert.Equal(25f, res.VideoStream.RealFrameRate);
+ Assert.Equal(1, res.VideoStream.RefFrames);
+ Assert.Equal("1/1000", res.VideoStream.TimeBase);
+ Assert.Equal(MediaStreamType.Video, res.VideoStream.Type);
+
+ Assert.Empty(res.Chapters);
+ Assert.Equal("Just color bars", res.Overview);
+ }
+
+ [Fact]
+ public void GetMediaInfo_Mp4MetaData_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/video_mp4_metadata.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+
+ // subtitle handling requires a localization object, set a mock to return the input string
+ var mockLocalization = new Mock<ILocalizationManager>();
+ mockLocalization.Setup(x => x.GetLocalizedString(It.IsAny<string>())).Returns<string>(x => x);
+ ProbeResultNormalizer localizedProbeResultNormalizer = new ProbeResultNormalizer(new NullLogger<EncoderValidatorTests>(), mockLocalization.Object);
+
+ MediaInfo res = localizedProbeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_mp4_metadata.mkv", MediaProtocol.File);
+
+ // [Video, Audio (Main), Audio (Commentary), Subtitle (Main, Spanish), Subtitle (Main, English), Subtitle (Commentary)
+ Assert.Equal(6, 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(358, res.VideoStream.Height);
+ Assert.Equal(720, res.VideoStream.Width);
+ Assert.Equal("2.40:1", res.VideoStream.AspectRatio);
+ Assert.Equal("yuv420p", res.VideoStream.PixelFormat);
+ Assert.Equal(31d, res.VideoStream.Level);
+ Assert.Equal(1, res.VideoStream.RefFrames);
+ Assert.True(res.VideoStream.IsAVC);
+ Assert.Equal(120f, res.VideoStream.RealFrameRate);
+ Assert.Equal("1/90000", res.VideoStream.TimeBase);
+ Assert.Equal(1147365, res.VideoStream.BitRate);
+ Assert.Equal(8, res.VideoStream.BitDepth);
+ Assert.True(res.VideoStream.IsDefault);
+ Assert.Equal("und", res.VideoStream.Language);
+
+ Assert.Equal(MediaStreamType.Audio, res.MediaStreams[1].Type);
+ Assert.Equal("aac", res.MediaStreams[1].Codec);
+ Assert.Equal(7, res.MediaStreams[1].Channels);
+ Assert.True(res.MediaStreams[1].IsDefault);
+ Assert.Equal("eng", res.MediaStreams[1].Language);
+ Assert.Equal("Surround 6.1", res.MediaStreams[1].Title);
+
+ Assert.Equal(MediaStreamType.Audio, res.MediaStreams[2].Type);
+ Assert.Equal("aac", res.MediaStreams[2].Codec);
+ Assert.Equal(2, res.MediaStreams[2].Channels);
+ Assert.False(res.MediaStreams[2].IsDefault);
+ Assert.Equal("eng", res.MediaStreams[2].Language);
+ Assert.Equal("Commentary", res.MediaStreams[2].Title);
+
+ Assert.Equal("spa", res.MediaStreams[3].Language);
+ Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[3].Type);
+ Assert.Equal("DVDSUB", res.MediaStreams[3].Codec);
+ Assert.Null(res.MediaStreams[3].Title);
+
+ Assert.Equal("eng", res.MediaStreams[4].Language);
+ Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[4].Type);
+ Assert.Equal("mov_text", res.MediaStreams[4].Codec);
+ Assert.Null(res.MediaStreams[4].Title);
+
+ Assert.Equal("eng", res.MediaStreams[5].Language);
+ Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[5].Type);
+ Assert.Equal("mov_text", res.MediaStreams[5].Codec);
+ Assert.Equal("Commentary", res.MediaStreams[5].Title);
+ }
+
+ [Fact]
+ public void GetMediaInfo_MusicVideo_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/music_video_metadata.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/music_video.mkv", MediaProtocol.File);
+
+ Assert.Equal("The Title", res.Name);
+ Assert.Equal("Title, The", res.ForcedSortName);
+ Assert.Single(res.Artists);
+ Assert.Equal("The Artist", res.Artists[0]);
+ Assert.Equal("Album", res.Album);
+ Assert.Equal(2021, res.ProductionYear);
+ Assert.True(res.PremiereDate.HasValue);
+ Assert.Equal(DateTime.Parse("2021-01-01T00:00Z", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AdjustToUniversal), res.PremiereDate);
+ }
+
+ [Fact]
+ public void GetMediaInfo_GivenOriginalDateContainsOnlyYear_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/music_year_only_metadata.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, null, true, "Test Data/Probing/music.flac", MediaProtocol.File);
+
+ Assert.Equal("Baker Street", res.Name);
+ Assert.Single(res.Artists);
+ Assert.Equal("Gerry Rafferty", res.Artists[0]);
+ Assert.Equal("City to City", res.Album);
+ Assert.Equal(1978, res.ProductionYear);
+ Assert.True(res.PremiereDate.HasValue);
+ Assert.Equal(DateTime.Parse("1978-01-01T00:00Z", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AdjustToUniversal), res.PremiereDate);
+ Assert.Contains("Electronic", res.Genres);
+ Assert.Contains("Ambient", res.Genres);
+ Assert.Contains("Pop", res.Genres);
+ Assert.Contains("Jazz", res.Genres);
+ }
+
+ [Fact]
+ public void GetMediaInfo_Music_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/music_metadata.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, null, true, "Test Data/Probing/music.flac", MediaProtocol.File);
+
+ Assert.Equal("UP NO MORE", res.Name);
+ Assert.Single(res.Artists);
+ Assert.Equal("TWICE", res.Artists[0]);
+ Assert.Equal("Eyes wide open", res.Album);
+ Assert.Equal(2020, res.ProductionYear);
+ Assert.True(res.PremiereDate.HasValue);
+ Assert.Equal(DateTime.Parse("2020-10-26T00:00Z", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AdjustToUniversal), res.PremiereDate);
+ Assert.Equal(22, res.People.Length);
+ Assert.Equal("Krysta Youngs", res.People[0].Name);
+ Assert.Equal(PersonType.Composer, res.People[0].Type);
+ Assert.Equal("Julia Ross", res.People[1].Name);
+ Assert.Equal(PersonType.Composer, res.People[1].Type);
+ Assert.Equal("Yiwoomin", res.People[2].Name);
+ Assert.Equal(PersonType.Composer, res.People[2].Type);
+ Assert.Equal("Ji-hyo Park", res.People[3].Name);
+ Assert.Equal(PersonType.Lyricist, res.People[3].Type);
+ Assert.Equal("Yiwoomin", res.People[4].Name);
+ Assert.Equal(PersonType.Actor, res.People[4].Type);
+ Assert.Equal("Electric Piano", res.People[4].Role);
+ Assert.Equal(4, res.Genres.Length);
+ Assert.Contains("Electronic", res.Genres);
+ Assert.Contains("Trance", res.Genres);
+ Assert.Contains("Dance", res.Genres);
+ Assert.Contains("Jazz", res.Genres);
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs
new file mode 100644
index 000000000..3775555de
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Threading;
+using MediaBrowser.MediaEncoding.Subtitles;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Subtitles.Tests
+{
+ public class AssParserTests
+ {
+ [Fact]
+ public void Parse_Valid_Success()
+ {
+ using (var stream = File.OpenRead("Test Data/example.ass"))
+ {
+ var parsed = new AssParser(new NullLogger<AssParser>()).Parse(stream, CancellationToken.None);
+ Assert.Single(parsed.TrackEvents);
+ var trackEvent = parsed.TrackEvents[0];
+
+ Assert.Equal("1", trackEvent.Id);
+ Assert.Equal(TimeSpan.Parse("00:00:01.18", CultureInfo.InvariantCulture).Ticks, trackEvent.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:00:06.85", CultureInfo.InvariantCulture).Ticks, trackEvent.EndPositionTicks);
+ Assert.Equal("{\\pos(400,570)}Like an Angel with pity on nobody" + Environment.NewLine + "The second line in subtitle", trackEvent.Text);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs
new file mode 100644
index 000000000..c07c9ea7d
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Threading;
+using MediaBrowser.MediaEncoding.Subtitles;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Subtitles.Tests
+{
+ public class SrtParserTests
+ {
+ [Fact]
+ public void Parse_Valid_Success()
+ {
+ using (var stream = File.OpenRead("Test Data/example.srt"))
+ {
+ var parsed = new SrtParser(new NullLogger<SrtParser>()).Parse(stream, CancellationToken.None);
+ Assert.Equal(2, parsed.TrackEvents.Count);
+
+ var trackEvent1 = parsed.TrackEvents[0];
+ Assert.Equal("1", trackEvent1.Id);
+ Assert.Equal(TimeSpan.Parse("00:02:17.440", CultureInfo.InvariantCulture).Ticks, trackEvent1.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:02:20.375", CultureInfo.InvariantCulture).Ticks, trackEvent1.EndPositionTicks);
+ Assert.Equal("Senator, we're making" + Environment.NewLine + "our final approach into Coruscant.", trackEvent1.Text);
+
+ var trackEvent2 = parsed.TrackEvents[1];
+ Assert.Equal("2", trackEvent2.Id);
+ Assert.Equal(TimeSpan.Parse("00:02:20.476", CultureInfo.InvariantCulture).Ticks, trackEvent2.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:02:22.501", CultureInfo.InvariantCulture).Ticks, trackEvent2.EndPositionTicks);
+ Assert.Equal("Very good, Lieutenant.", trackEvent2.Text);
+ }
+ }
+
+ [Fact]
+ public void Parse_EmptyNewlineBetweenText_Success()
+ {
+ using (var stream = File.OpenRead("Test Data/example2.srt"))
+ {
+ var parsed = new SrtParser(new NullLogger<SrtParser>()).Parse(stream, CancellationToken.None);
+ Assert.Equal(2, parsed.TrackEvents.Count);
+
+ var trackEvent1 = parsed.TrackEvents[0];
+ Assert.Equal("311", trackEvent1.Id);
+ Assert.Equal(TimeSpan.Parse("00:16:46.465", CultureInfo.InvariantCulture).Ticks, trackEvent1.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:16:49.009", CultureInfo.InvariantCulture).Ticks, trackEvent1.EndPositionTicks);
+ Assert.Equal("Una vez que la gente se entere" + Environment.NewLine + Environment.NewLine + "de que ustedes están aquí,", trackEvent1.Text);
+
+ var trackEvent2 = parsed.TrackEvents[1];
+ Assert.Equal("312", trackEvent2.Id);
+ Assert.Equal(TimeSpan.Parse("00:16:49.092", CultureInfo.InvariantCulture).Ticks, trackEvent2.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:16:51.470", CultureInfo.InvariantCulture).Ticks, trackEvent2.EndPositionTicks);
+ Assert.Equal("este lugar se convertirá" + Environment.NewLine + Environment.NewLine + "en un maldito zoológico.", trackEvent2.Text);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs
new file mode 100644
index 000000000..56649db8f
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Threading;
+using MediaBrowser.MediaEncoding.Subtitles;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Subtitles.Tests
+{
+ public class SsaParserTests
+ {
+ private readonly SsaParser _parser = new SsaParser(new NullLogger<AssParser>());
+
+ [Theory]
+ [MemberData(nameof(Parse_MultipleDialogues_TestData))]
+ public void Parse_MultipleDialogues_Success(string ssa, IReadOnlyList<SubtitleTrackEvent> expectedSubtitleTrackEvents)
+ {
+ using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa)))
+ {
+ SubtitleTrackInfo subtitleTrackInfo = _parser.Parse(stream, CancellationToken.None);
+
+ Assert.Equal(expectedSubtitleTrackEvents.Count, subtitleTrackInfo.TrackEvents.Count);
+
+ for (int i = 0; i < expectedSubtitleTrackEvents.Count; ++i)
+ {
+ SubtitleTrackEvent expected = expectedSubtitleTrackEvents[i];
+ SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[i];
+
+ Assert.Equal(expected.Id, actual.Id);
+ Assert.Equal(expected.Text, actual.Text);
+ Assert.Equal(expected.StartPositionTicks, actual.StartPositionTicks);
+ Assert.Equal(expected.EndPositionTicks, actual.EndPositionTicks);
+ }
+ }
+ }
+
+ public static TheoryData<string, IReadOnlyList<SubtitleTrackEvent>> Parse_MultipleDialogues_TestData()
+ {
+ var data = new TheoryData<string, IReadOnlyList<SubtitleTrackEvent>>();
+
+ data.Add(
+ @"[Events]
+ Format: Layer, Start, End, Text
+ Dialogue: ,0:00:01.18,0:00:01.85,dialogue1
+ Dialogue: ,0:00:02.18,0:00:02.85,dialogue2
+ Dialogue: ,0:00:03.18,0:00:03.85,dialogue3
+ ",
+ new List<SubtitleTrackEvent>
+ {
+ new SubtitleTrackEvent("1", "dialogue1")
+ {
+ StartPositionTicks = 11800000,
+ EndPositionTicks = 18500000
+ },
+ new SubtitleTrackEvent("2", "dialogue2")
+ {
+ StartPositionTicks = 21800000,
+ EndPositionTicks = 28500000
+ },
+ new SubtitleTrackEvent("3", "dialogue3")
+ {
+ StartPositionTicks = 31800000,
+ EndPositionTicks = 38500000
+ }
+ });
+
+ return data;
+ }
+
+ [Fact]
+ public void Parse_Valid_Success()
+ {
+ using (var stream = File.OpenRead("Test Data/example.ssa"))
+ {
+ var parsed = _parser.Parse(stream, CancellationToken.None);
+ Assert.Single(parsed.TrackEvents);
+ var trackEvent = parsed.TrackEvents[0];
+
+ Assert.Equal("1", trackEvent.Id);
+ Assert.Equal(TimeSpan.Parse("00:00:01.18", CultureInfo.InvariantCulture).Ticks, trackEvent.StartPositionTicks);
+ Assert.Equal(TimeSpan.Parse("00:00:06.85", CultureInfo.InvariantCulture).Ticks, trackEvent.EndPositionTicks);
+ Assert.Equal("{\\pos(400,570)}Like an angel with pity on nobody", trackEvent.Text);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleEncoderTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleEncoderTests.cs
new file mode 100644
index 000000000..639c364df
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleEncoderTests.cs
@@ -0,0 +1,83 @@
+using System.Threading;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using MediaBrowser.MediaEncoding.Subtitles;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.MediaInfo;
+using Xunit;
+
+namespace Jellyfin.MediaEncoding.Subtitles.Tests
+{
+ public class SubtitleEncoderTests
+ {
+ internal static TheoryData<MediaSourceInfo, MediaStream, SubtitleEncoder.SubtitleInfo> GetReadableFile_Valid_TestData()
+ {
+ var data = new TheoryData<MediaSourceInfo, MediaStream, SubtitleEncoder.SubtitleInfo>();
+
+ data.Add(
+ new MediaSourceInfo()
+ {
+ Protocol = MediaProtocol.File
+ },
+ new MediaStream()
+ {
+ Path = "/media/sub.ass",
+ IsExternal = true
+ },
+ new SubtitleEncoder.SubtitleInfo("/media/sub.ass", MediaProtocol.File, "ass", true));
+
+ data.Add(
+ new MediaSourceInfo()
+ {
+ Protocol = MediaProtocol.File
+ },
+ new MediaStream()
+ {
+ Path = "/media/sub.ssa",
+ IsExternal = true
+ },
+ new SubtitleEncoder.SubtitleInfo("/media/sub.ssa", MediaProtocol.File, "ssa", true));
+
+ data.Add(
+ new MediaSourceInfo()
+ {
+ Protocol = MediaProtocol.File
+ },
+ new MediaStream()
+ {
+ Path = "/media/sub.srt",
+ IsExternal = true
+ },
+ new SubtitleEncoder.SubtitleInfo("/media/sub.srt", MediaProtocol.File, "srt", true));
+
+ data.Add(
+ new MediaSourceInfo()
+ {
+ Protocol = MediaProtocol.Http
+ },
+ new MediaStream()
+ {
+ Path = "/media/sub.ass",
+ IsExternal = true
+ },
+ new SubtitleEncoder.SubtitleInfo("/media/sub.ass", MediaProtocol.File, "ass", true));
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(GetReadableFile_Valid_TestData))]
+ internal async Task GetReadableFile_Valid_Success(MediaSourceInfo mediaSource, MediaStream subtitleStream, SubtitleEncoder.SubtitleInfo subtitleInfo)
+ {
+ var fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
+ var subtitleEncoder = fixture.Create<SubtitleEncoder>();
+ var result = await subtitleEncoder.GetReadableFile(mediaSource, subtitleStream, CancellationToken.None).ConfigureAwait(false);
+ Assert.Equal(subtitleInfo.Path, result.Path);
+ Assert.Equal(subtitleInfo.Protocol, result.Protocol);
+ Assert.Equal(subtitleInfo.Format, result.Format);
+ Assert.Equal(subtitleInfo.IsExternal, result.IsExternal);
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_metadata.json
new file mode 100644
index 000000000..6530629fe
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_metadata.json
@@ -0,0 +1,144 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "flac",
+ "codec_long_name": "FLAC (Free Lossless Audio Codec)",
+ "codec_type": "audio",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "sample_fmt": "s16",
+ "sample_rate": "44100",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "bits_per_sample": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/44100",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 9447984,
+ "duration": "214.240000",
+ "bits_per_raw_sample": "16",
+ "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
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "mjpeg",
+ "codec_long_name": "Motion JPEG",
+ "profile": "Baseline",
+ "codec_type": "video",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 500,
+ "height": 500,
+ "coded_width": 500,
+ "coded_height": 500,
+ "closed_captions": 0,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "1:1",
+ "pix_fmt": "yuvj420p",
+ "level": -99,
+ "color_range": "pc",
+ "color_space": "bt470bg",
+ "chroma_location": "center",
+ "refs": 1,
+ "r_frame_rate": "90000/1",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 19281600,
+ "duration": "214.240000",
+ "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": 1,
+ "timed_thumbnails": 0
+ },
+ "tags": {
+ "comment": "Cover (front)"
+ }
+ }
+ ],
+ "format": {
+ "filename": "03 UP NO MORE.flac",
+ "nb_streams": 2,
+ "nb_programs": 0,
+ "format_name": "flac",
+ "format_long_name": "raw FLAC",
+ "start_time": "0.000000",
+ "duration": "214.240000",
+ "size": "28714641",
+ "bit_rate": "1072242",
+ "probe_score": 100,
+ "tags": {
+ "MUSICBRAINZ_RELEASEGROUPID": "aa05ff10-8589-4c9c-a0d4-6b024f4e4556",
+ "ORIGINALDATE": "2020-10-26",
+ "ORIGINALYEAR": "2020",
+ "RELEASETYPE": "album",
+ "MUSICBRAINZ_ALBUMID": "222e6610-75c9-400e-8dc3-bb61f9fc5ca7",
+ "SCRIPT": "Latn",
+ "ALBUM": "Eyes wide open",
+ "RELEASECOUNTRY": "JP",
+ "BARCODE": "190295105280",
+ "LABEL": "JYP Entertainment",
+ "RELEASESTATUS": "official",
+ "DATE": "2020-10-26",
+ "MUSICBRAINZ_ALBUMARTISTID": "8da127cc-c432-418f-b356-ef36210d82ac",
+ "album_artist": "TWICE",
+ "ALBUMARTISTSORT": "TWICE",
+ "TOTALDISCS": "1",
+ "TOTALTRACKS": "13",
+ "MEDIA": "Digital Media",
+ "disc": "1",
+ "MUSICBRAINZ_TRACKID": "7d1a1044-b564-480d-9df3-22f9656fdb97",
+ "TITLE": "UP NO MORE",
+ "ISRC": "US5TA2000136",
+ "PERFORMER": "Yiwoomin (electric piano);Yiwoomin (synthesizer);Yiwoomin (bass);Yiwoomin (guitar);TWICE;Tzu-yu Chou (vocals);Momo Hirai (vocals);Na-yeon Im (vocals);Da-hyun Kim (vocals);Sana Minatozaki (vocals);Mina Myoui (vocals);Ji-hyo Park (vocals);Chae-young Son (vocals);Jeong-yeon Yoo (vocals);Perrie (background vocals)",
+ "MIXER": "Bong Won Shin",
+ "ARRANGER": "Krysta Youngs;Julia Ross;Yiwoomin",
+ "MUSICBRAINZ_WORKID": "02b37083-0337-4721-9f17-bf31971043e8",
+ "LANGUAGE": "kor;eng",
+ "WORK": "Up No More",
+ "COMPOSER": "Krysta Youngs;Julia Ross;Yiwoomin",
+ "COMPOSERSORT": "Krysta Youngs;Ross, Julia;Yiwoomin",
+ "LYRICIST": "Ji-hyo Park",
+ "MUSICBRAINZ_ARTISTID": "8da127cc-c432-418f-b356-ef36210d82ac",
+ "ARTIST": "TWICE",
+ "ARTISTSORT": "TWICE",
+ "ARTISTS": "TWICE",
+ "MUSICBRAINZ_RELEASETRACKID": "ad49b840-da9e-4e7c-924b-29fdee187052",
+ "track": "3",
+ "GENRE": "Electronic;Trance;Dance;Jazz",
+ "WEBSITE": "http://twice.jype.com/;http://www.twicejapan.com/",
+ "ACOUSTID_ID": "aae2e972-108c-4d0c-8e31-9d078283e3dc",
+ "MOOD": "Not acoustic;Not aggressive;Electronic;Happy;Party;Not relaxed;Not sad",
+ "TRACKTOTAL": "13",
+ "DISCTOTAL": "1"
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json
new file mode 100644
index 000000000..97d6600a4
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json
@@ -0,0 +1,111 @@
+{
+ "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_time_base": "1001/48000",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 1920,
+ "height": 1080,
+ "coded_width": 1920,
+ "coded_height": 1088,
+ "closed_captions": 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": "24000/1001",
+ "avg_frame_rate": "24000/1001",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "bits_per_raw_sample": "8",
+ "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
+ },
+ "tags": {
+ "language": "eng"
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_long_name": "AAC (Advanced Audio Coding)",
+ "profile": "LC",
+ "codec_type": "audio",
+ "codec_time_base": "1/48000",
+ "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,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "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
+ },
+ "tags": {
+ "language": "eng"
+ }
+ }
+ ],
+ "chapters": [
+ ],
+ "format": {
+ "filename": "music_video.mkv",
+ "nb_streams": 2,
+ "nb_programs": 0,
+ "format_name": "matroska,webm",
+ "format_long_name": "Matroska / WebM",
+ "start_time": "0.000000",
+ "duration": "180.000000",
+ "size": "500000000",
+ "bit_rate": "22222222",
+ "probe_score": 100,
+ "tags": {
+ "TITLE-eng": "The Title",
+ "TITLESORT": "Title, The",
+ "ARTIST": "The Artist",
+ "ARTISTSORT": "Artist, The",
+ "ALBUM": "Album",
+ "DATE_RELEASED": "2021-01-01"
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_year_only_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_year_only_metadata.json
new file mode 100644
index 000000000..ddf890c45
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_year_only_metadata.json
@@ -0,0 +1,147 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "flac",
+ "codec_long_name": "FLAC (Free Lossless Audio Codec)",
+ "codec_type": "audio",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "sample_fmt": "s16",
+ "sample_rate": "44100",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "bits_per_sample": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/44100",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 16394616,
+ "duration": "371.760000",
+ "bits_per_raw_sample": "16",
+ "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
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "mjpeg",
+ "codec_long_name": "Motion JPEG",
+ "profile": "Baseline",
+ "codec_type": "video",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 500,
+ "height": 498,
+ "coded_width": 500,
+ "coded_height": 498,
+ "closed_captions": 0,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "250:249",
+ "pix_fmt": "yuvj420p",
+ "level": -99,
+ "color_range": "pc",
+ "color_space": "bt470bg",
+ "chroma_location": "center",
+ "refs": 1,
+ "r_frame_rate": "90000/1",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 33458400,
+ "duration": "371.760000",
+ "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": 1,
+ "timed_thumbnails": 0
+ },
+ "tags": {
+ "comment": "Cover (front)"
+ }
+ }
+ ],
+ "format": {
+ "filename": "02 Baker Street.flac",
+ "nb_streams": 2,
+ "nb_programs": 0,
+ "format_name": "flac",
+ "format_long_name": "raw FLAC",
+ "start_time": "0.000000",
+ "duration": "371.760000",
+ "size": "37072649",
+ "bit_rate": "797775",
+ "probe_score": 100,
+ "tags": {
+ "MUSICBRAINZ_RELEASEGROUPID": "238c3fb4-5792-342b-b217-02f66298b424",
+ "ORIGINALDATE": "1978",
+ "ORIGINALYEAR": "1978",
+ "RELEASETYPE": "album",
+ "MUSICBRAINZ_ALBUMID": "30156786-e511-3106-ac95-66f0e880b24b",
+ "ASIN": "B000007O5H",
+ "MUSICBRAINZ_ALBUMARTISTID": "563201cb-721c-4cfb-acca-c1ba69e3d1fb",
+ "album_artist": "Gerry Rafferty",
+ "ALBUMARTISTSORT": "Rafferty, Gerry",
+ "LABEL": "Liberty EMI Records UK",
+ "CATALOGNUMBER": "CDP 7 46049 2",
+ "DATE": "1989-07-26",
+ "RELEASECOUNTRY": "GB",
+ "BARCODE": "077774604925",
+ "ALBUM": "City to City",
+ "SCRIPT": "Latn",
+ "RELEASESTATUS": "official",
+ "TOTALDISCS": "1",
+ "disc": "1",
+ "MEDIA": "CD",
+ "TOTALTRACKS": "10",
+ "MUSICBRAINZ_TRACKID": "9235e22e-afbd-48f7-b329-21dae6da2810",
+ "ISRC": "GBAYE1100924;GBAYE7800619",
+ "PERFORMER": "Hugh Burns (electric guitar);Nigel Jenkins (electric guitar);Tommy Eyre (keyboard and Moog);Glen LeFleur (percussion);Raphael Ravenscroft (saxophone);Henry Spinetti (drums (drum set));Gary Taylor (bass);Gerry Rafferty (lead vocals)",
+ "ARRANGER": "Graham Preskett",
+ "MIXER": "Declan O’Doherty",
+ "PRODUCER": "Hugh Murphy;Gerry Rafferty",
+ "MUSICBRAINZ_WORKID": "a9eb3c45-784c-3c32-860c-4b406f03961b",
+ "LANGUAGE": "eng",
+ "WORK": "Baker Street",
+ "COMPOSER": "Gerry Rafferty",
+ "COMPOSERSORT": "Rafferty, Gerry",
+ "LYRICIST": "Gerry Rafferty",
+ "TITLE": "Baker Street",
+ "MUSICBRAINZ_ARTISTID": "563201cb-721c-4cfb-acca-c1ba69e3d1fb",
+ "ARTIST": "Gerry Rafferty",
+ "ARTISTSORT": "Rafferty, Gerry",
+ "ARTISTS": "Gerry Rafferty",
+ "MUSICBRAINZ_RELEASETRACKID": "407cf7f7-440d-3e76-8b89-8686198868ea",
+ "track": "2",
+ "GENRE": "Electronic;Ambient;Pop;Jazz",
+ "WEBSITE": "http://www.gerryrafferty.com/",
+ "ACOUSTID_ID": "68f8d979-a659-4aa0-a216-eb3721a951eb",
+ "MOOD": "Acoustic;Not aggressive;Not electronic;Not happy;Party;Relaxed;Not sad",
+ "TRACKTOTAL": "10",
+ "DISCTOTAL": "1"
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json
new file mode 100644
index 000000000..720fc5c8f
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json
@@ -0,0 +1,74 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
+ "profile": "High 4:4:4 Predictive",
+ "codec_type": "video",
+ "codec_time_base": "1/50",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 320,
+ "height": 240,
+ "coded_width": 320,
+ "coded_height": 240,
+ "closed_captions": 0,
+ "has_b_frames": 2,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "4:3",
+ "pix_fmt": "yuv444p",
+ "level": 13,
+ "chroma_location": "left",
+ "field_order": "progressive",
+ "refs": 1,
+ "is_avc": "true",
+ "nal_length_size": "4",
+ "r_frame_rate": "25/1",
+ "avg_frame_rate": "25/1",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "bits_per_raw_sample": "8",
+ "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
+ },
+ "tags": {
+ "ENCODER": "Lavc57.107.100 libx264",
+ "DURATION": "00:00:01.000000000"
+ }
+ }
+ ],
+ "chapters": [
+
+ ],
+ "format": {
+ "filename": "some_metadata.mkv",
+ "nb_streams": 1,
+ "nb_programs": 0,
+ "format_name": "matroska,webm",
+ "format_long_name": "Matroska / WebM",
+ "start_time": "0.000000",
+ "duration": "1.000000",
+ "size": "8679",
+ "bit_rate": "69432",
+ "probe_score": 100,
+ "tags": {
+ "DESCRIPTION": "Just color bars",
+ "ARCHIVAL": "yes",
+ "PRESERVE_THIS": "okay",
+ "ENCODER": "Lavf57.83.100"
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_mp4_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_mp4_metadata.json
new file mode 100644
index 000000000..77e3def76
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_mp4_metadata.json
@@ -0,0 +1,260 @@
+{
+ "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": "avc1",
+ "codec_tag": "0x31637661",
+ "width": 720,
+ "height": 358,
+ "coded_width": 720,
+ "coded_height": 358,
+ "closed_captions": 0,
+ "has_b_frames": 2,
+ "sample_aspect_ratio": "32:27",
+ "display_aspect_ratio": "1280:537",
+ "pix_fmt": "yuv420p",
+ "level": 31,
+ "color_range": "tv",
+ "color_space": "smpte170m",
+ "color_transfer": "bt709",
+ "color_primaries": "smpte170m",
+ "chroma_location": "left",
+ "refs": 1,
+ "is_avc": "true",
+ "nal_length_size": "4",
+ "r_frame_rate": "120/1",
+ "avg_frame_rate": "1704753000/71073479",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 1421469580,
+ "duration": "15794.106444",
+ "bit_rate": "1147365",
+ "bits_per_raw_sample": "8",
+ "nb_frames": "378834",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "und",
+ "handler_name": "VideoHandler",
+ "vendor_id": "[0][0][0][0]"
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_long_name": "AAC (Advanced Audio Coding)",
+ "profile": "LC",
+ "codec_type": "audio",
+ "codec_tag_string": "mp4a",
+ "codec_tag": "0x6134706d",
+ "sample_fmt": "fltp",
+ "sample_rate": "48000",
+ "channels": 7,
+ "bits_per_sample": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/48000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 758115312,
+ "duration": "15794.069000",
+ "bit_rate": "224197",
+ "nb_frames": "740348",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "eng",
+ "handler_name": "Surround 6.1",
+ "vendor_id": "[0][0][0][0]"
+ }
+ },
+ {
+ "index": 2,
+ "codec_name": "aac",
+ "codec_long_name": "AAC (Advanced Audio Coding)",
+ "profile": "LC",
+ "codec_type": "audio",
+ "codec_tag_string": "mp4a",
+ "codec_tag": "0x6134706d",
+ "sample_fmt": "fltp",
+ "sample_rate": "48000",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "bits_per_sample": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/48000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 758114304,
+ "duration": "15794.048000",
+ "bit_rate": "160519",
+ "nb_frames": "740347",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "eng",
+ "handler_name": "Commentary",
+ "vendor_id": "[0][0][0][0]"
+ }
+ },
+ {
+ "index": 3,
+ "codec_name": "dvd_subtitle",
+ "codec_long_name": "DVD subtitles",
+ "codec_type": "subtitle",
+ "codec_tag_string": "mp4s",
+ "codec_tag": "0x7334706d",
+ "width": 720,
+ "height": 480,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 1300301588,
+ "duration": "14447.795422",
+ "bit_rate": "2653",
+ "nb_frames": "3545",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "spa",
+ "handler_name": "SubtitleHandler"
+ }
+ },
+ {
+ "index": 4,
+ "codec_name": "mov_text",
+ "codec_long_name": "MOV text",
+ "codec_type": "subtitle",
+ "codec_tag_string": "tx3g",
+ "codec_tag": "0x67337874",
+ "width": 853,
+ "height": 51,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 1401339330,
+ "duration": "15570.437000",
+ "bit_rate": "88",
+ "nb_frames": "5079",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "eng",
+ "handler_name": "SubtitleHandler"
+ }
+ },
+ {
+ "index": 5,
+ "codec_name": "mov_text",
+ "codec_long_name": "MOV text",
+ "codec_type": "subtitle",
+ "codec_tag_string": "tx3g",
+ "codec_tag": "0x67337874",
+ "width": 853,
+ "height": 51,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "duration_ts": 1370580300,
+ "duration": "15228.670000",
+ "bit_rate": "18",
+ "nb_frames": "1563",
+ "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
+ },
+ "tags": {
+ "creation_time": "2021-09-13T22:42:42.000000Z",
+ "language": "eng",
+ "handler_name": "Commentary"
+ }
+ }
+ ]
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass
new file mode 100644
index 000000000..d5ac31d70
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass
@@ -0,0 +1,22 @@
+[Script Info]
+; Script generated by Aegisub
+; http://www.aegisub.org
+Title: Neon Genesis Evangelion - Episode 26 (neutral Spanish)
+Original Script: RoRo
+Script Updated By: version 2.8.01
+ScriptType: v4.00+
+Collisions: Normal
+PlayResY: 600
+PlayDepth: 0
+Timer: 100,0000
+Video Aspect Ratio: 0
+Video Zoom: 6
+Video Position: 0
+
+[V4+ Styles]
+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
+Style: DefaultVCD, Arial,28,&H00B4FCFC,&H00B4FCFC,&H00000008,&H80000008,-1,0,0,0,100,100,0.00,0.00,1,1.00,2.00,2,30,30,30,0
+
+[Events]
+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
+Dialogue: 0,0:00:01.18,0:00:06.85,DefaultVCD, NTP,0000,0000,0000,,{\pos(400,570)}Like an Angel with pity on nobody\NThe second line in subtitle
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt
new file mode 100644
index 000000000..78d74014e
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt
@@ -0,0 +1,8 @@
+1
+00:02:17,440 --> 00:02:20,375
+Senator, we're making
+our final approach into Coruscant.
+
+2
+00:02:20,476 --> 00:02:22,501
+Very good, Lieutenant.
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ssa b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ssa
new file mode 100644
index 000000000..dcbb972eb
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ssa
@@ -0,0 +1,20 @@
+[Script Info]
+; This is a Sub Station Alpha v4 script.
+; For Sub Station Alpha info and downloads,
+; go to http://www.eswat.demon.co.uk/
+Title: Neon Genesis Evangelion - Episode 26 (neutral Spanish)
+Original Script: RoRo
+Script Updated By: version 2.8.01
+ScriptType: v4.00
+Collisions: Normal
+PlayResY: 600
+PlayDepth: 0
+Timer: 100,0000
+
+[V4 Styles]
+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
+Style: DefaultVCD, Arial,28,11861244,11861244,11861244,-2147483640,-1,0,1,1,2,2,30,30,30,0,0
+
+[Events]
+Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
+Dialogue: Marked=0,0:00:01.18,0:00:06.85,DefaultVCD, NTP,0000,0000,0000,,{\pos(400,570)}Like an angel with pity on nobody
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example2.srt b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example2.srt
new file mode 100644
index 000000000..b14aa8ea3
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example2.srt
@@ -0,0 +1,11 @@
+311
+00:16:46,465 --> 00:16:49,009
+Una vez que la gente se entere
+
+de que ustedes están aquí,
+
+312
+00:16:49,092 --> 00:16:51,470
+este lugar se convertirá
+
+en un maldito zoológico.
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json
new file mode 100644
index 000000000..cdad5df50
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json
@@ -0,0 +1,105 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
+ "profile": "Main",
+ "codec_type": "video",
+ "codec_time_base": "1/50",
+ "codec_tag_string": "[27][0][0][0]",
+ "codec_tag": "0x001b",
+ "width": 1920,
+ "height": 1080,
+ "coded_width": 1920,
+ "coded_height": 1080,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "0:1",
+ "display_aspect_ratio": "0:1",
+ "pix_fmt": "yuvj420p",
+ "level": 42,
+ "color_range": "pc",
+ "color_space": "bt709",
+ "color_transfer": "bt709",
+ "color_primaries": "bt709",
+ "chroma_location": "left",
+ "field_order": "progressive",
+ "refs": 1,
+ "is_avc": "false",
+ "nal_length_size": "0",
+ "id": "0x1",
+ "r_frame_rate": "25/1",
+ "avg_frame_rate": "25/1",
+ "time_base": "1/90000",
+ "start_pts": 8570867078,
+ "start_time": "95231.856422",
+ "duration_ts": 31694552,
+ "duration": "352.161689",
+ "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
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_long_name": "AAC (Advanced Audio Coding)",
+ "profile": "LC",
+ "codec_type": "audio",
+ "codec_time_base": "1/44100",
+ "codec_tag_string": "[15][0][0][0]",
+ "codec_tag": "0x000f",
+ "sample_fmt": "fltp",
+ "sample_rate": "44100",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "bits_per_sample": 0,
+ "id": "0x2",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/90000",
+ "start_pts": 8570867697,
+ "start_time": "95231.863300",
+ "duration_ts": 31695687,
+ "duration": "352.174300",
+ "bit_rate": "98191",
+ "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
+ }
+ }
+ ],
+ "format": {
+ "filename": "TS Test record.ts",
+ "nb_streams": 2,
+ "nb_programs": 1,
+ "format_name": "mpegts",
+ "format_long_name": "MPEG-TS (MPEG-2 Transport Stream)",
+ "start_time": "95231.856422",
+ "duration": "352.181178",
+ "size": "179003772",
+ "bit_rate": "4066174",
+ "probe_score": 50
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs b/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs
new file mode 100644
index 000000000..cca056c28
--- /dev/null
+++ b/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs
@@ -0,0 +1,19 @@
+using MediaBrowser.Model.Dlna;
+using Xunit;
+
+namespace Jellyfin.Model.Tests.Dlna
+{
+ public class ContainerProfileTests
+ {
+ private readonly ContainerProfile _emptyContainerProfile = new ContainerProfile();
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("mp4")]
+ public void ContainsContainer_EmptyContainerProfile_True(string? containers)
+ {
+ Assert.True(_emptyContainerProfile.ContainsContainer(containers));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Entities/MediaStreamTests.cs b/tests/Jellyfin.Model.Tests/Entities/MediaStreamTests.cs
new file mode 100644
index 000000000..0c97a90b4
--- /dev/null
+++ b/tests/Jellyfin.Model.Tests/Entities/MediaStreamTests.cs
@@ -0,0 +1,150 @@
+using MediaBrowser.Model.Entities;
+using Xunit;
+
+namespace Jellyfin.Model.Tests.Entities
+{
+ public class MediaStreamTests
+ {
+ public static TheoryData<MediaStream, string> Get_DisplayTitle_TestData()
+ {
+ var data = new TheoryData<MediaStream, string>();
+
+ data.Add(
+ new MediaStream
+ {
+ Type = MediaStreamType.Subtitle,
+ Title = "English",
+ Language = string.Empty,
+ IsForced = false,
+ IsDefault = false,
+ Codec = "ASS"
+ },
+ "English - Und - ASS");
+
+ data.Add(
+ new MediaStream
+ {
+ Type = MediaStreamType.Subtitle,
+ Title = "English",
+ Language = string.Empty,
+ IsForced = false,
+ IsDefault = false,
+ Codec = string.Empty
+ },
+ "English - Und");
+
+ data.Add(
+ new MediaStream
+ {
+ Type = MediaStreamType.Subtitle,
+ Title = "English",
+ Language = "EN",
+ IsForced = false,
+ IsDefault = false,
+ Codec = string.Empty
+ },
+ "English");
+
+ data.Add(
+ new MediaStream
+ {
+ Type = MediaStreamType.Subtitle,
+ Title = "English",
+ Language = "EN",
+ IsForced = true,
+ IsDefault = true,
+ Codec = "SRT"
+ },
+ "English - Default - Forced - SRT");
+
+ data.Add(
+ new MediaStream
+ {
+ Type = MediaStreamType.Subtitle,
+ Title = null,
+ Language = null,
+ IsForced = false,
+ IsDefault = false,
+ Codec = null
+ },
+ "Und");
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(Get_DisplayTitle_TestData))]
+ public void Get_DisplayTitle_should_return_valid_title(MediaStream mediaStream, string expected)
+ {
+ Assert.Equal(expected, mediaStream.DisplayTitle);
+ }
+
+ [Theory]
+ [InlineData(null, null, false, null)]
+ [InlineData(null, 0, false, null)]
+ [InlineData(0, null, false, null)]
+ [InlineData(640, 480, false, "480p")]
+ [InlineData(640, 480, true, "480i")]
+ [InlineData(720, 576, false, "576p")]
+ [InlineData(720, 576, true, "576i")]
+ [InlineData(960, 540, false, "540p")]
+ [InlineData(960, 540, true, "540i")]
+ [InlineData(1280, 720, false, "720p")]
+ [InlineData(1280, 720, true, "720i")]
+ [InlineData(1920, 1080, false, "1080p")]
+ [InlineData(1920, 1080, true, "1080i")]
+ [InlineData(4096, 3072, false, "4K")]
+ [InlineData(8192, 6144, false, "8K")]
+ [InlineData(512, 384, false, "480p")]
+ [InlineData(576, 336, false, "480p")]
+ [InlineData(624, 352, false, "480p")]
+ [InlineData(640, 352, false, "480p")]
+ [InlineData(704, 396, false, "480p")]
+ [InlineData(720, 404, false, "480p")]
+ [InlineData(720, 480, false, "480p")]
+ [InlineData(768, 576, false, "576p")]
+ [InlineData(960, 720, false, "720p")]
+ [InlineData(1280, 528, false, "720p")]
+ [InlineData(1280, 532, false, "720p")]
+ [InlineData(1280, 534, false, "720p")]
+ [InlineData(1280, 536, false, "720p")]
+ [InlineData(1280, 544, false, "720p")]
+ [InlineData(1280, 690, false, "720p")]
+ [InlineData(1280, 694, false, "720p")]
+ [InlineData(1280, 696, false, "720p")]
+ [InlineData(1280, 716, false, "720p")]
+ [InlineData(1280, 718, false, "720p")]
+ [InlineData(1912, 792, false, "1080p")]
+ [InlineData(1916, 1076, false, "1080p")]
+ [InlineData(1918, 1080, false, "1080p")]
+ [InlineData(1920, 796, false, "1080p")]
+ [InlineData(1920, 800, false, "1080p")]
+ [InlineData(1920, 802, false, "1080p")]
+ [InlineData(1920, 804, false, "1080p")]
+ [InlineData(1920, 808, false, "1080p")]
+ [InlineData(1920, 816, false, "1080p")]
+ [InlineData(1920, 856, false, "1080p")]
+ [InlineData(1920, 960, false, "1080p")]
+ [InlineData(1920, 1024, false, "1080p")]
+ [InlineData(1920, 1040, false, "1080p")]
+ [InlineData(1920, 1072, false, "1080p")]
+ [InlineData(1440, 1072, false, "1080p")]
+ [InlineData(1440, 1080, false, "1080p")]
+ [InlineData(3840, 1600, false, "4K")]
+ [InlineData(3840, 1606, false, "4K")]
+ [InlineData(3840, 1608, false, "4K")]
+ [InlineData(3840, 2160, false, "4K")]
+ [InlineData(7680, 4320, false, "8K")]
+ public void GetResolutionText_Valid(int? width, int? height, bool interlaced, string expected)
+ {
+ var mediaStream = new MediaStream()
+ {
+ Width = width,
+ Height = height,
+ IsInterlaced = interlaced
+ };
+
+ Assert.Equal(expected, mediaStream.GetResolutionText());
+ }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs
new file mode 100644
index 000000000..a1ace8476
--- /dev/null
+++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs
@@ -0,0 +1,196 @@
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Entities;
+using Xunit;
+
+namespace Jellyfin.Model.Tests.Entities
+{
+ public class ProviderIdsExtensionsTests
+ {
+ private const string ExampleImdbId = "tt0113375";
+
+ [Fact]
+ public void HasProviderId_NullInstance_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => ProviderIdsExtensions.HasProviderId(null!, MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void HasProviderId_NullProvider_False()
+ {
+ var nullProvider = new ProviderIdsExtensionsTestsObject
+ {
+ ProviderIds = null!
+ };
+
+ Assert.False(nullProvider.HasProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void HasProviderId_NullName_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => ProviderIdsExtensionsTestsObject.Empty.HasProviderId(null!));
+ }
+
+ [Fact]
+ public void HasProviderId_NotFoundName_False()
+ {
+ Assert.False(ProviderIdsExtensionsTestsObject.Empty.HasProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void HasProviderId_FoundName_True()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId;
+
+ Assert.True(provider.HasProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void HasProviderId_FoundNameEmptyValue_False()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = string.Empty;
+
+ Assert.False(provider.HasProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void GetProviderId_NullInstance_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => ProviderIdsExtensions.GetProviderId(null!, MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void GetProviderId_NullName_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => ProviderIdsExtensionsTestsObject.Empty.GetProviderId(null!));
+ }
+
+ [Fact]
+ public void GetProviderId_NotFoundName_Null()
+ {
+ Assert.Null(ProviderIdsExtensionsTestsObject.Empty.GetProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void GetProviderId_NullProvider_Null()
+ {
+ var nullProvider = new ProviderIdsExtensionsTestsObject
+ {
+ ProviderIds = null!
+ };
+
+ Assert.Null(nullProvider.GetProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void TryGetProviderId_NotFoundName_False()
+ {
+ Assert.False(ProviderIdsExtensionsTestsObject.Empty.TryGetProviderId(MetadataProvider.Imdb, out _));
+ }
+
+ [Fact]
+ public void TryGetProviderId_NullProvider_False()
+ {
+ var nullProvider = new ProviderIdsExtensionsTestsObject
+ {
+ ProviderIds = null!
+ };
+
+ Assert.False(nullProvider.TryGetProviderId(MetadataProvider.Imdb, out _));
+ }
+
+ [Fact]
+ public void GetProviderId_FoundName_Id()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId;
+
+ Assert.Equal(ExampleImdbId, provider.GetProviderId(MetadataProvider.Imdb));
+ }
+
+ [Fact]
+ public void TryGetProviderId_FoundName_True()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId;
+
+ Assert.True(provider.TryGetProviderId(MetadataProvider.Imdb, out var id));
+ Assert.Equal(ExampleImdbId, id);
+ }
+
+ [Fact]
+ public void TryGetProviderId_FoundNameEmptyValue_False()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = string.Empty;
+
+ Assert.False(provider.TryGetProviderId(MetadataProvider.Imdb, out var id));
+ Assert.Null(id);
+ }
+
+ [Fact]
+ public void SetProviderId_NullInstance_ThrowsArgumentNullException()
+ {
+ Assert.Throws<ArgumentNullException>(() => ProviderIdsExtensions.SetProviderId(null!, MetadataProvider.Imdb, ExampleImdbId));
+ }
+
+ [Fact]
+ public void SetProviderId_Null_Remove()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.SetProviderId(MetadataProvider.Imdb, null!);
+ Assert.Empty(provider.ProviderIds);
+ }
+
+ [Fact]
+ public void SetProviderId_EmptyName_Remove()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId;
+ provider.SetProviderId(MetadataProvider.Imdb, string.Empty);
+ Assert.Empty(provider.ProviderIds);
+ }
+
+ [Fact]
+ public void SetProviderId_NonEmptyId_Success()
+ {
+ var provider = new ProviderIdsExtensionsTestsObject();
+ provider.SetProviderId(MetadataProvider.Imdb, ExampleImdbId);
+ Assert.Single(provider.ProviderIds);
+ }
+
+ [Fact]
+ public void SetProviderId_NullProvider_Success()
+ {
+ var nullProvider = new ProviderIdsExtensionsTestsObject
+ {
+ ProviderIds = null!
+ };
+
+ nullProvider.SetProviderId(MetadataProvider.Imdb, ExampleImdbId);
+ Assert.Single(nullProvider.ProviderIds);
+ }
+
+ [Fact]
+ public void SetProviderId_NullProviderAndEmptyName_Success()
+ {
+ var nullProvider = new ProviderIdsExtensionsTestsObject
+ {
+ ProviderIds = null!
+ };
+
+ nullProvider.SetProviderId(MetadataProvider.Imdb, string.Empty);
+ Assert.Null(nullProvider.ProviderIds);
+ }
+
+ private class ProviderIdsExtensionsTestsObject : IHasProviderIds
+ {
+ public static readonly ProviderIdsExtensionsTestsObject Empty = new ProviderIdsExtensionsTestsObject();
+
+ public Dictionary<string, string> ProviderIds { get; set; } = new Dictionary<string, string>();
+ }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs b/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs
new file mode 100644
index 000000000..0a4e060df
--- /dev/null
+++ b/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs
@@ -0,0 +1,32 @@
+using System;
+using FsCheck;
+using FsCheck.Xunit;
+using MediaBrowser.Model.Extensions;
+using Xunit;
+
+namespace Jellyfin.Model.Tests.Extensions
+{
+ public class StringHelperTests
+ {
+ [Theory]
+ [InlineData("", "")]
+ [InlineData("banana", "Banana")]
+ [InlineData("Banana", "Banana")]
+ [InlineData("ä", "Ä")]
+ [InlineData("\027", "\027")]
+ public void StringHelper_ValidArgs_Success(string input, string expectedResult)
+ {
+ Assert.Equal(expectedResult, StringHelper.FirstToUpper(input));
+ }
+
+ [Property]
+ public Property FirstToUpper_RandomArg_Correct(NonEmptyString input)
+ {
+ var result = StringHelper.FirstToUpper(input.Item);
+
+ // We check IsLower instead of IsUpper because both return false for non-letters
+ return (!char.IsLower(result[0])).Label("First char is uppercase")
+ .And(input.Item.Length == 1 || result[1..].Equals(input.Item[1..], StringComparison.Ordinal)).Label("Remaining chars are unmodified");
+ }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj
new file mode 100644
index 000000000..7e8397d9f
--- /dev/null
+++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj
@@ -0,0 +1,28 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="FsCheck.Xunit" Version="2.16.3" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Model/MediaBrowser.Model.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs
new file mode 100644
index 000000000..cf21f964e
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs
@@ -0,0 +1,30 @@
+using Emby.Naming.AudioBook;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.AudioBook
+{
+ public class AudioBookFileInfoTests
+ {
+ [Fact]
+ public void CompareTo_Same_Success()
+ {
+ var info = new AudioBookFileInfo(string.Empty, string.Empty);
+ Assert.Equal(0, info.CompareTo(info));
+ }
+
+ [Fact]
+ public void CompareTo_Null_Success()
+ {
+ var info = new AudioBookFileInfo(string.Empty, string.Empty);
+ Assert.Equal(1, info.CompareTo(null));
+ }
+
+ [Fact]
+ public void CompareTo_Empty_Success()
+ {
+ var info1 = new AudioBookFileInfo(string.Empty, string.Empty);
+ var info2 = new AudioBookFileInfo(string.Empty, string.Empty);
+ Assert.Equal(0, info1.CompareTo(info2));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs
new file mode 100644
index 000000000..d9e77dd2e
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs
@@ -0,0 +1,272 @@
+using System;
+using System.Linq;
+using Emby.Naming.AudioBook;
+using Emby.Naming.Common;
+using MediaBrowser.Model.IO;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.AudioBook
+{
+ public class AudioBookListResolverTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestStackAndExtras()
+ {
+ // No stacking here because there is no part/disc/etc
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows/Part 1.mp3",
+ "Harry Potter and the Deathly Hallows/Part 2.mp3",
+ "Harry Potter and the Deathly Hallows/Extra.mp3",
+
+ "Batman/Chapter 1.mp3",
+ "Batman/Chapter 2.mp3",
+ "Batman/Chapter 3.mp3",
+
+ "Badman/audiobook.mp3",
+ "Badman/extra.mp3",
+
+ "Superman (2020)/Part 1.mp3",
+ "Superman (2020)/extra.mp3",
+
+ "Ready Player One (2020)/audiobook.mp3",
+ "Ready Player One (2020)/extra.mp3",
+
+ ".mp3"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ })).ToList();
+
+ Assert.Equal(5, result.Count);
+
+ Assert.Equal(2, result[0].Files.Count);
+ Assert.Single(result[0].Extras);
+ Assert.Equal("Harry Potter and the Deathly Hallows", result[0].Name);
+
+ Assert.Equal(3, result[1].Files.Count);
+ Assert.Empty(result[1].Extras);
+ Assert.Equal("Batman", result[1].Name);
+
+ Assert.Single(result[2].Files);
+ Assert.Single(result[2].Extras);
+ Assert.Equal("Badman", result[2].Name);
+
+ Assert.Single(result[3].Files);
+ Assert.Single(result[3].Extras);
+ Assert.Equal("Superman", result[3].Name);
+
+ Assert.Single(result[4].Files);
+ Assert.Single(result[4].Extras);
+ Assert.Equal("Ready Player One", result[4].Name);
+ }
+
+ [Fact]
+ public void TestAlternativeVersions()
+ {
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows/Chapter 1.ogg",
+ "Harry Potter and the Deathly Hallows/Chapter 1.mp3",
+
+ "Deadpool.mp3",
+ "Deadpool [HQ].mp3",
+
+ "Superman/audiobook.mp3",
+ "Superman/Superman.mp3",
+ "Superman/Superman [HQ].mp3",
+ "Superman/extra.mp3",
+
+ "Batman/ Chapter 1 .mp3",
+ "Batman/Chapter 1[loss-less].mp3"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ })).ToList();
+
+ Assert.Equal(5, result.Count);
+ // HP - Same name so we don't care which file is alternative
+ Assert.Single(result[0].AlternateVersions);
+ // DP
+ Assert.Empty(result[1].AlternateVersions);
+ // DP HQ (directory missing so we do not group deadpools together)
+ Assert.Empty(result[2].AlternateVersions);
+ // Superman
+ // Priority:
+ // 1. Name
+ // 2. audiobook
+ // 3. Names with modifiers
+ Assert.Equal(2, result[3].AlternateVersions.Count);
+ var paths = result[3].AlternateVersions.Select(x => x.Path).ToList();
+ Assert.Contains("Superman/audiobook.mp3", paths);
+ Assert.Contains("Superman/Superman [HQ].mp3", paths);
+ // Batman
+ Assert.Single(result[4].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestNameYearExtraction()
+ {
+ var data = new[]
+ {
+ new NameYearPath
+ {
+ Name = "Harry Potter and the Deathly Hallows",
+ Path = "Harry Potter and the Deathly Hallows (2007)/Chapter 1.ogg",
+ Year = 2007
+ },
+ new NameYearPath
+ {
+ Name = "Batman",
+ Path = "Batman (2020).ogg",
+ Year = 2020
+ },
+ new NameYearPath
+ {
+ Name = "Batman",
+ Path = "Batman( 2021 ).mp3",
+ Year = 2021
+ },
+ new NameYearPath
+ {
+ Name = "Batman(*2021*)",
+ Path = "Batman(*2021*).mp3",
+ Year = null
+ },
+ new NameYearPath
+ {
+ Name = "Batman",
+ Path = "Batman.mp3",
+ Year = null
+ },
+ new NameYearPath
+ {
+ Name = "+ Batman .",
+ Path = " + Batman . .mp3",
+ Year = null
+ },
+ new NameYearPath
+ {
+ Name = " ",
+ Path = " .mp3",
+ Year = null
+ }
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(data.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i.Path
+ })).ToList();
+
+ Assert.Equal(data.Length, result.Count);
+
+ for (int i = 0; i < data.Length; i++)
+ {
+ Assert.Equal(data[i].Name, result[i].Name);
+ Assert.Equal(data[i].Year, result[i].Year);
+ }
+ }
+
+ [Fact]
+ public void TestWithMetadata()
+ {
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows/Chapter 1.ogg",
+ "Harry Potter and the Deathly Hallows/Harry Potter and the Deathly Hallows.nfo"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }));
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestWithExtra()
+ {
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows/Chapter 1.mp3",
+ "Harry Potter and the Deathly Hallows/Harry Potter and the Deathly Hallows trailer.mp3"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ })).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestWithoutFolder()
+ {
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows trailer.mp3"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ })).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestEmpty()
+ {
+ var files = Array.Empty<string>();
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ })).ToList();
+
+ Assert.Empty(result);
+ }
+
+ private AudioBookListResolver GetResolver()
+ {
+ return new AudioBookListResolver(_namingOptions);
+ }
+
+ internal struct NameYearPath
+ {
+ public string Name;
+ public string Path;
+ public int? Year;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs
new file mode 100644
index 000000000..c72a3315e
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs
@@ -0,0 +1,65 @@
+using Emby.Naming.AudioBook;
+using Emby.Naming.Common;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.AudioBook
+{
+ public class AudioBookResolverTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ public static TheoryData<AudioBookFileInfo> Resolve_ValidFileNameTestData()
+ {
+ var data = new TheoryData<AudioBookFileInfo>();
+
+ data.Add(
+ new AudioBookFileInfo(
+ @"/server/AudioBooks/Larry Potter/Larry Potter.mp3",
+ "mp3"));
+
+ data.Add(
+ new AudioBookFileInfo(
+ @"/server/AudioBooks/Berry Potter/Chapter 1 .ogg",
+ "ogg",
+ chapterNumber: 1));
+
+ data.Add(
+ new AudioBookFileInfo(
+ @"/server/AudioBooks/Nerry Potter/Part 3 - Chapter 2.mp3",
+ "mp3",
+ chapterNumber: 2,
+ partNumber: 3));
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(Resolve_ValidFileNameTestData))]
+ public void Resolve_ValidFileName_Success(AudioBookFileInfo expectedResult)
+ {
+ var result = new AudioBookResolver(_namingOptions).Resolve(expectedResult.Path);
+
+ Assert.NotNull(result);
+ Assert.Equal(result!.Path, expectedResult.Path);
+ Assert.Equal(result!.Container, expectedResult.Container);
+ Assert.Equal(result!.ChapterNumber, expectedResult.ChapterNumber);
+ Assert.Equal(result!.PartNumber, expectedResult.PartNumber);
+ }
+
+ [Fact]
+ public void Resolve_InvalidExtension()
+ {
+ var result = new AudioBookResolver(_namingOptions).Resolve(@"/server/AudioBooks/Larry Potter/Larry Potter.mp9");
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void Resolve_EmptyFileName()
+ {
+ var result = new AudioBookResolver(_namingOptions).Resolve(string.Empty);
+
+ Assert.Null(result);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs b/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs
new file mode 100644
index 000000000..3892d00f6
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs
@@ -0,0 +1,36 @@
+using Emby.Naming.Common;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Common
+{
+ public class NamingOptionsTest
+ {
+ [Fact]
+ public void TestNamingOptionsCompile()
+ {
+ var options = new NamingOptions();
+
+ Assert.NotEmpty(options.VideoFileStackingRegexes);
+ Assert.NotEmpty(options.CleanDateTimeRegexes);
+ Assert.NotEmpty(options.CleanStringRegexes);
+ Assert.NotEmpty(options.EpisodeWithoutSeasonRegexes);
+ Assert.NotEmpty(options.EpisodeMultiPartRegexes);
+ }
+
+ [Fact]
+ public void TestNamingOptionsEpisodeExpressions()
+ {
+ var exp = new EpisodeExpression(string.Empty);
+
+ Assert.False(exp.IsOptimistic);
+ exp.IsOptimistic = true;
+ Assert.True(exp.IsOptimistic);
+
+ Assert.Equal(string.Empty, exp.Expression);
+ Assert.NotNull(exp.Regex);
+ exp.Expression = "test";
+ Assert.Equal("test", exp.Expression);
+ Assert.NotNull(exp.Regex);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj
new file mode 100644
index 000000000..4096873a3
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj
@@ -0,0 +1,32 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{3998657B-1CCC-49DD-A19F-275DC8495F57}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\Emby.Naming\Emby.Naming.csproj" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs
new file mode 100644
index 000000000..c9a295a4c
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs
@@ -0,0 +1,50 @@
+using Emby.Naming.Audio;
+using Emby.Naming.Common;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Music
+{
+ public class MultiDiscAlbumTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData("", false)]
+ [InlineData("C:/", false)]
+ [InlineData("/home/", false)]
+ [InlineData(@"blah blah", false)]
+ [InlineData(@"D:/music/weezer/03 Pinkerton", false)]
+ [InlineData(@"D:/music/michael jackson/Bad (2012 Remaster)", false)]
+ [InlineData(@"cd1", true)]
+ [InlineData(@"disc18", true)]
+ [InlineData(@"disk10", true)]
+ [InlineData(@"vol7", true)]
+ [InlineData(@"volume1", true)]
+ [InlineData(@"cd 1", true)]
+ [InlineData(@"disc 1", true)]
+ [InlineData(@"disk 1", true)]
+ [InlineData(@"disk", false)]
+ [InlineData(@"disk ·", false)]
+ [InlineData(@"disk a", false)]
+ [InlineData(@"disk volume", false)]
+ [InlineData(@"disc disc", false)]
+ [InlineData(@"disk disc 6", false)]
+ [InlineData(@"cd - 1", true)]
+ [InlineData(@"disc- 1", true)]
+ [InlineData(@"disk - 1", true)]
+ [InlineData(@"Disc 01 (Hugo Wolf · 24 Lieder)", true)]
+ [InlineData(@"Disc 04 (Encores and Folk Songs)", true)]
+ [InlineData(@"Disc04 (Encores and Folk Songs)", true)]
+ [InlineData(@"Disc 04(Encores and Folk Songs)", true)]
+ [InlineData(@"Disc04(Encores and Folk Songs)", true)]
+ [InlineData(@"D:/Video/MBTestLibrary/VideoTest/music/.38 special/anth/Disc 2", true)]
+ [InlineData(@"[1985] Opportunities (Let's make lots of money) (1985)", false)]
+ [InlineData(@"Blah 04(Encores and Folk Songs)", false)]
+ public void AlbumParser_MultidiscPath_Identifies(string path, bool result)
+ {
+ var parser = new AlbumParser(_namingOptions);
+
+ Assert.Equal(result, parser.IsMultiPart(path));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs
new file mode 100644
index 000000000..2446660f3
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs
@@ -0,0 +1,41 @@
+using Emby.Naming.Common;
+using Emby.Naming.Subtitles;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Subtitles
+{
+ public class SubtitleParserTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData("The Skin I Live In (2011).srt", null, false, false)]
+ [InlineData("The Skin I Live In (2011).eng.srt", "eng", false, false)]
+ [InlineData("The Skin I Live In (2011).eng.default.srt", "eng", true, false)]
+ [InlineData("The Skin I Live In (2011).eng.forced.srt", "eng", false, true)]
+ [InlineData("The Skin I Live In (2011).eng.foreign.srt", "eng", false, true)]
+ [InlineData("The Skin I Live In (2011).eng.default.foreign.srt", "eng", true, true)]
+ [InlineData("The Skin I Live In (2011).default.foreign.eng.srt", "eng", true, true)]
+ public void SubtitleParser_ValidFileName_Parses(string input, string language, bool isDefault, bool isForced)
+ {
+ var parser = new SubtitleParser(_namingOptions);
+
+ var result = parser.ParseFile(input);
+
+ Assert.Equal(language, result?.Language, true);
+ Assert.Equal(isDefault, result?.IsDefault);
+ Assert.Equal(isForced, result?.IsForced);
+ Assert.Equal(input, result?.Path);
+ }
+
+ [Theory]
+ [InlineData("The Skin I Live In (2011).mp4")]
+ [InlineData("")]
+ public void SubtitleParser_InvalidFileName_ReturnsNull(string input)
+ {
+ var parser = new SubtitleParser(_namingOptions);
+
+ Assert.Null(parser.ParseFile(input));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs
new file mode 100644
index 000000000..356ba216d
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs
@@ -0,0 +1,27 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class AbsoluteEpisodeNumberTests
+ {
+ [Theory]
+ [InlineData("The Simpsons/12.avi", 12)]
+ [InlineData("The Simpsons/The Simpsons 12.avi", 12)]
+ [InlineData("The Simpsons/The Simpsons 82.avi", 82)]
+ [InlineData("The Simpsons/The Simpsons 112.avi", 112)]
+ [InlineData("The Simpsons/Foo_ep_02.avi", 2)]
+ [InlineData("The Simpsons/The Simpsons 889.avi", 889)]
+ [InlineData("The Simpsons/The Simpsons 101.avi", 101)]
+ public void GetEpisodeNumberFromFileTest(string path, int episodeNumber)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodeResolver(options)
+ .Resolve(path, false, null, null, true);
+
+ Assert.Equal(episodeNumber, result?.EpisodeNumber);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs
new file mode 100644
index 000000000..2937914b9
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs
@@ -0,0 +1,32 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class DailyEpisodeTests
+ {
+ [Theory]
+ [InlineData(@"/server/anything_1996.11.14.mp4", "anything", 1996, 11, 14)]
+ [InlineData(@"/server/anything_1996-11-14.mp4", "anything", 1996, 11, 14)]
+ [InlineData(@"/server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv", "james.corden", 2017, 04, 20)]
+ [InlineData(@"/server/ABC News 2018_03_24_19_00_00.mkv", "ABC News", 2018, 03, 24)]
+ // TODO: [InlineData(@"/server/anything_14.11.1996.mp4", "anything", 1996, 11, 14)]
+ // TODO: [InlineData(@"/server/A Daily Show - (2015-01-15) - Episode Name - [720p].mkv", "A Daily Show", 2015, 01, 15)]
+ // TODO: [InlineData(@"/server/Last Man Standing_KTLADT_2018_05_25_01_28_00.wtv", "Last Man Standing", 2018, 05, 25)]
+ public void Test(string path, string seriesName, int? year, int? month, int? day)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodeResolver(options)
+ .Resolve(path, false);
+
+ Assert.Null(result?.SeasonNumber);
+ Assert.Null(result?.EpisodeNumber);
+ Assert.Equal(year, result?.Year);
+ Assert.Equal(month, result?.Month);
+ Assert.Equal(day, result?.Day);
+ Assert.Equal(seriesName, result?.SeriesName, true);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs
new file mode 100644
index 000000000..2873f6161
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs
@@ -0,0 +1,88 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class EpisodeNumberTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData("Watchmen (2019)/Watchmen 1x03 [WEBDL-720p][EAC3 5.1][h264][-TBS] - She Was Killed by Space Junk.mkv", 3)]
+ [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 22)]
+ [InlineData("Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", 1)]
+ [InlineData("After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", 6)]
+ [InlineData("Season 02/S02E03 blah.avi", 3)]
+ [InlineData("Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 02/02x03 - x04 - x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 1/01x02 blah.avi", 2)]
+ [InlineData("Season 1/S01x02 blah.avi", 2)]
+ [InlineData("Season 1/S01E02 blah.avi", 2)]
+ [InlineData("Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", 3)]
+ [InlineData("Season 1/S01xE02 blah.avi", 2)]
+ [InlineData("Season 1/seriesname S01E02 blah.avi", 2)]
+ [InlineData("Season 2/Episode - 16.avi", 16)]
+ [InlineData("Season 2/Episode 16.avi", 16)]
+ [InlineData("Season 2/Episode 16 - Some Title.avi", 16)]
+ [InlineData("Season 2/16 Some Title.avi", 16)]
+ [InlineData("Season 2/16 - 12 Some Title.avi", 16)]
+ [InlineData("Season 2/7 - 12 Angry Men.avi", 7)]
+ [InlineData("Season 1/seriesname 01x02 blah.avi", 2)]
+ [InlineData("Season 25/The Simpsons.S25E09.Steal this episode.mp4", 9)]
+ [InlineData("Season 1/seriesname S01x02 blah.avi", 2)]
+ [InlineData("Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 1/seriesname S01xE02 blah.avi", 2)]
+ [InlineData("Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2/02x03-04-15 - Ep Name.mp4", 3)]
+ [InlineData("Season 02/02x03-E15 - Ep Name.mp4", 3)]
+ [InlineData("Season 02/Elementary - 02x03-E15 - Ep Name.mp4", 3)]
+ [InlineData("Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", 23)]
+ [InlineData("Season 2009/S2009E23-E24-E26 - The Woman.mp4", 23)]
+ [InlineData("Season 2009/2009x02 blah.avi", 2)]
+ [InlineData("Season 2009/S2009x02 blah.avi", 2)]
+ [InlineData("Season 2009/S2009E02 blah.avi", 2)]
+ [InlineData("Season 2009/seriesname 2009x02 blah.avi", 2)]
+ [InlineData("Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/2009x03x04x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/S2009xE02 blah.avi", 2)]
+ [InlineData("Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4", 23)]
+ [InlineData("Season 2009/seriesname S2009xE02 blah.avi", 2)]
+ [InlineData("Season 2009/2009x03-E15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/seriesname S2009E02 blah.avi", 2)]
+ [InlineData("Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/2009x03 - x04 - x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/seriesname S2009x02 blah.avi", 2)]
+ [InlineData("Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/2009x03-04-15 - Ep Name.mp4", 3)]
+ [InlineData("Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4", 3)]
+ [InlineData("Season 1/02 - blah-02 a.avi", 2)]
+ [InlineData("Season 1/02 - blah.avi", 2)]
+ [InlineData("Season 2/02 - blah 14 blah.avi", 2)]
+ [InlineData("Season 2/02.avi", 2)]
+ [InlineData("Season 2/2. Infestation.avi", 2)]
+ [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)]
+ [InlineData("Running Man/Running Man S2017E368.mkv", 368)]
+ [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] // triple digit episode number
+ [InlineData("Log Horizon 2/[HorribleSubs] Log Horizon 2 - 03 [720p].mkv", 3)] // digit in series name
+ [InlineData("Season 1/seriesname 05.mkv", 5)] // no hyphen between series name and episode number
+ [InlineData("[BBT-RMX] Ranma ½ - 154 [50AC421A].mkv", 154)] // hyphens in the pre-name info, triple digit episode number
+ [InlineData("Season 2/Episode 21 - 94 Meetings.mp4", 21)] // Title starts with a number
+ // [InlineData("Case Closed (1996-2007)/Case Closed - 317.mkv", 317)] // triple digit episode number
+ // TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)]
+ // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)]
+ // TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)]
+ // TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)]
+ // TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)]
+ public void GetEpisodeNumberFromFileTest(string path, int? expected)
+ {
+ var result = new EpisodePathParser(_namingOptions)
+ .Parse(path, false);
+
+ Assert.Equal(expected, result.EpisodeNumber);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs
new file mode 100644
index 000000000..8bd1a43d6
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs
@@ -0,0 +1,35 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class EpisodeNumberWithoutSeasonTests
+ {
+ [Theory]
+ [InlineData(8, @"The Simpsons/The Simpsons.S25E08.Steal this episode.mp4")]
+ [InlineData(2, @"The Simpsons/The Simpsons - 02 - Ep Name.avi")]
+ [InlineData(2, @"The Simpsons/02.avi")]
+ [InlineData(2, @"The Simpsons/02 - Ep Name.avi")]
+ [InlineData(2, @"The Simpsons/02-Ep Name.avi")]
+ [InlineData(2, @"The Simpsons/02.EpName.avi")]
+ [InlineData(2, @"The Simpsons/The Simpsons - 02.avi")]
+ [InlineData(2, @"The Simpsons/The Simpsons - 02 Ep Name.avi")]
+ [InlineData(7, @"GJ Club (2013)/GJ Club - 07.mkv")]
+ [InlineData(17, @"Case Closed (1996-2007)/Case Closed - 317.mkv")]
+ // TODO: [InlineData(2, @"The Simpsons/The Simpsons 5 - 02 - Ep Name.avi")]
+ // TODO: [InlineData(2, @"The Simpsons/The Simpsons 5 - 02 Ep Name.avi")]
+ // TODO: [InlineData(7, @"Seinfeld/Seinfeld 0807 The Checks.avi")]
+ // This is not supported anymore after removing the episode number 365+ hack from EpisodePathParser
+ // TODO: [InlineData(13, @"Case Closed (1996-2007)/Case Closed - 13.mkv")]
+ public void GetEpisodeNumberFromFileTest(int episodeNumber, string path)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodeResolver(options)
+ .Resolve(path, false);
+
+ Assert.Equal(episodeNumber, result?.EpisodeNumber);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs
new file mode 100644
index 000000000..12fc19bc4
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs
@@ -0,0 +1,104 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class EpisodePathParserTest
+ {
+ [Theory]
+ [InlineData("/media/Foo/Foo-S01E01", true, "Foo", 1, 1)]
+ [InlineData("/media/Foo - S04E011", true, "Foo", 4, 11)]
+ [InlineData("/media/Foo/Foo s01x01", true, "Foo", 1, 1)]
+ [InlineData("/media/Foo (2019)/Season 4/Foo (2019).S04E03", true, "Foo (2019)", 4, 3)]
+ [InlineData("D:\\media\\Foo\\Foo-S01E01", true, "Foo", 1, 1)]
+ [InlineData("D:\\media\\Foo - S04E011", true, "Foo", 4, 11)]
+ [InlineData("D:\\media\\Foo\\Foo s01x01", true, "Foo", 1, 1)]
+ [InlineData("D:\\media\\Foo (2019)\\Season 4\\Foo (2019).S04E03", true, "Foo (2019)", 4, 3)]
+ [InlineData("/Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", false, "Elementary", 2, 3)]
+ [InlineData("/Season 1/seriesname S01E02 blah.avi", false, "seriesname", 1, 2)]
+ [InlineData("/Running Man/Running Man S2017E368.mkv", false, "Running Man", 2017, 368)]
+ [InlineData("/Season 1/seriesname 01x02 blah.avi", false, "seriesname", 1, 2)]
+ [InlineData("/Season 25/The Simpsons.S25E09.Steal this episode.mp4", false, "The Simpsons", 25, 9)]
+ [InlineData("/Season 1/seriesname S01x02 blah.avi", false, "seriesname", 1, 2)]
+ [InlineData("/Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", false, "Elementary", 2, 3)]
+ [InlineData("/Season 1/seriesname S01xE02 blah.avi", false, "seriesname", 1, 2)]
+ [InlineData("/Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", false, "Elementary", 2, 3)]
+ [InlineData("/Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", false, "Elementary", 2, 3)]
+ [InlineData("/Season 02/Elementary - 02x03-E15 - Ep Name.mp4", false, "Elementary", 2, 3)]
+ [InlineData("/Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", false, "Elementary", 1, 23)]
+ [InlineData("/The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", false, "The Wonder Years", 4, 7)]
+ // TODO: [InlineData("/Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", "Castle Rock", 2, 1)]
+ // TODO: [InlineData("/After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", "After Life", 1, 6)]
+ // TODO: [InlineData("/Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", "Uchuu Senkan Yamoto 2199", 4, 3)]
+ // TODO: [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", "The Daily Show", 25, 22)]
+ // TODO: [InlineData("Watchmen (2019)/Watchmen 1x03 [WEBDL-720p][EAC3 5.1][h264][-TBS] - She Was Killed by Space Junk.mkv", "Watchmen (2019)", 1, 3)]
+ // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", "The Legend of Condor Heroes 2017", 1, 7)]
+ public void ParseEpisodesCorrectly(string path, bool isDirectory, string name, int season, int episode)
+ {
+ NamingOptions o = new NamingOptions();
+ EpisodePathParser p = new EpisodePathParser(o);
+ var res = p.Parse(path, isDirectory);
+
+ Assert.True(res.Success);
+ Assert.Equal(name, res.SeriesName);
+ Assert.Equal(season, res.SeasonNumber);
+ Assert.Equal(episode, res.EpisodeNumber);
+ }
+
+ [Theory]
+ [InlineData("/test/01-03.avi", true, true)]
+ public void EpisodePathParserTest_DifferentExpressionsParameters(string path, bool? isNamed, bool? isOptimistic)
+ {
+ NamingOptions o = new NamingOptions();
+ EpisodePathParser p = new EpisodePathParser(o);
+ var res = p.Parse(path, false, isNamed, isOptimistic);
+
+ Assert.True(res.Success);
+ }
+
+ [Fact]
+ public void EpisodePathParserTest_FalsePositivePixelRate()
+ {
+ NamingOptions o = new NamingOptions();
+ EpisodePathParser p = new EpisodePathParser(o);
+ var res = p.Parse("Series Special (1920x1080).mkv", false);
+
+ Assert.False(res.Success);
+ }
+
+ [Fact]
+ public void EpisodeResolverTest_WrongExtension()
+ {
+ var res = new EpisodeResolver(new NamingOptions()).Resolve("test.mp3", false);
+ Assert.Null(res);
+ }
+
+ [Fact]
+ public void EpisodeResolverTest_WrongExtensionStub()
+ {
+ var res = new EpisodeResolver(new NamingOptions()).Resolve("dvd.disc", false);
+ Assert.NotNull(res);
+ Assert.True(res!.IsStub);
+ }
+
+ /*
+ * EpisodePathParser.cs:130 is currently unreachable, but the piece of code is useful and could be reached with addition of new EpisodeExpressions.
+ * In order to preserve it but achieve 100% code coverage the test case below with made up expressions and filename is used.
+ */
+ [Fact]
+ public void EpisodePathParserTest_EmptyDateParsers()
+ {
+ NamingOptions o = new NamingOptions()
+ {
+ EpisodeExpressions = new[] { new EpisodeExpression("(([0-9]{4})-([0-9]{2})-([0-9]{2}) [0-9]{2}:[0-9]{2}:[0-9]{2})", true) }
+ };
+ o.Compile();
+
+ EpisodePathParser p = new EpisodePathParser(o);
+ var res = p.Parse("ABC_2019_10_21 11:00:00", false);
+
+ Assert.True(res.Success);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs
new file mode 100644
index 000000000..d0418a49e
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs
@@ -0,0 +1,27 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class EpisodeWithoutSeasonTests
+ {
+ // TODO: [Theory]
+ // TODO: [InlineData(@"/server/anything_ep02.mp4", "anything", null, 2)]
+ // TODO: [InlineData(@"/server/anything_ep_02.mp4", "anything", null, 2)]
+ // TODO: [InlineData(@"/server/anything_part.II.mp4", "anything", null, null)]
+ // TODO: [InlineData(@"/server/anything_pt.II.mp4", "anything", null, null)]
+ // TODO: [InlineData(@"/server/anything_pt_II.mp4", "anything", null, null)]
+ public void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodeResolver(options)
+ .Resolve(path, false);
+
+ Assert.Equal(seasonNumber, result?.SeasonNumber);
+ Assert.Equal(episodeNumber, result?.EpisodeNumber);
+ Assert.Equal(seriesName, result?.SeriesName, ignoreCase: true);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs
new file mode 100644
index 000000000..58ea0bec5
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs
@@ -0,0 +1,80 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class MultiEpisodeTests
+ {
+ [Theory]
+ [InlineData(@"Season 1/4x01 – 20 Hours in America (1).mkv", null)]
+ [InlineData(@"Season 1/01x02 blah.avi", null)]
+ [InlineData(@"Season 1/S01x02 blah.avi", null)]
+ [InlineData(@"Season 1/S01E02 blah.avi", null)]
+ [InlineData(@"Season 1/S01xE02 blah.avi", null)]
+ [InlineData(@"Season 1/seriesname 01x02 blah.avi", null)]
+ [InlineData(@"Season 1/seriesname S01x02 blah.avi", null)]
+ [InlineData(@"Season 1/seriesname S01E02 blah.avi", null)]
+ [InlineData(@"Season 1/seriesname S01xE02 blah.avi", null)]
+ [InlineData(@"Season 2/02x03 - 04 Ep Name.mp4", null)]
+ [InlineData(@"Season 2/My show name 02x03 - 04 Ep Name.mp4", null)]
+ [InlineData(@"Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2/02x03-04-15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/02x03-E15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/Elementary - 02x03-E15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/02x03 - x04 - x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/02x03x04x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", 26)]
+ [InlineData(@"Season 1/S01E23-E24-E26 - The Woman.mp4", 26)]
+ // Four Digits seasons
+ [InlineData(@"Season 2009/2009x02 blah.avi", null)]
+ [InlineData(@"Season 2009/S2009x02 blah.avi", null)]
+ [InlineData(@"Season 2009/S2009E02 blah.avi", null)]
+ [InlineData(@"Season 2009/S2009xE02 blah.avi", null)]
+ [InlineData(@"Season 2009/seriesname 2009x02 blah.avi", null)]
+ [InlineData(@"Season 2009/seriesname S2009x02 blah.avi", null)]
+ [InlineData(@"Season 2009/seriesname S2009E02 blah.avi", null)]
+ [InlineData(@"Season 2009/seriesname S2009xE02 blah.avi", null)]
+ [InlineData(@"Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/2009x03-04-15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/2009x03-E15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/2009x03 - x04 - x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/2009x03x04x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4", 15)]
+ [InlineData(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4", 26)]
+ [InlineData(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4", 26)]
+ // Without season number
+ [InlineData(@"Season 1/02 - blah.avi", null)]
+ [InlineData(@"Season 2/02 - blah 14 blah.avi", null)]
+ [InlineData(@"Season 1/02 - blah-02 a.avi", null)]
+ [InlineData(@"Season 2/02.avi", null)]
+ [InlineData(@"Season 1/02-03 - blah.avi", 3)]
+ [InlineData(@"Season 2/02-04 - blah 14 blah.avi", 4)]
+ [InlineData(@"Season 1/02-05 - blah-02 a.avi", 5)]
+ [InlineData(@"Season 2/02-04.avi", 4)]
+ [InlineData(@"Season 2 /[HorribleSubs] Hunter X Hunter - 136[720p].mkv", null)]
+ // With format specification that must not be detected as ending episode number
+ [InlineData(@"Season 1/series-s09e14-1080p.mkv", null)]
+ [InlineData(@"Season 1/series-s09e14-720p.mkv", null)]
+ [InlineData(@"Season 1/series-s09e14-720i.mkv", null)]
+ [InlineData(@"Season 1/MOONLIGHTING_s01e01-e04.mkv", 4)]
+ [InlineData(@"Season 1/MOONLIGHTING_s01e01-e04", 4)]
+ public void TestGetEndingEpisodeNumberFromFile(string filename, int? endingEpisodeNumber)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodePathParser(options)
+ .Parse(filename, false);
+
+ Assert.Equal(result.EndingEpisodeNumber, endingEpisodeNumber);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs
new file mode 100644
index 000000000..b7b5b54ec
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs
@@ -0,0 +1,35 @@
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class SeasonFolderTests
+ {
+ [Theory]
+ [InlineData(@"/Drive/Season 1", 1, true)]
+ [InlineData(@"/Drive/Season 2", 2, true)]
+ [InlineData(@"/Drive/Season 02", 2, true)]
+ [InlineData(@"/Drive/Seinfeld/S02", 2, true)]
+ [InlineData(@"/Drive/Seinfeld/2", 2, true)]
+ [InlineData(@"/Drive/Season 2009", 2009, true)]
+ [InlineData(@"/Drive/Season1", 1, true)]
+ [InlineData(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH", 4, true)]
+ [InlineData(@"/Drive/Season 7 (2016)", 7, false)]
+ [InlineData(@"/Drive/Staffel 7 (2016)", 7, false)]
+ [InlineData(@"/Drive/Stagione 7 (2016)", 7, false)]
+ [InlineData(@"/Drive/Season (8)", null, false)]
+ [InlineData(@"/Drive/3.Staffel", 3, false)]
+ [InlineData(@"/Drive/s06e05", null, false)]
+ [InlineData(@"/Drive/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv", null, false)]
+ [InlineData(@"/Drive/extras", 0, true)]
+ [InlineData(@"/Drive/specials", 0, true)]
+ public void GetSeasonNumberFromPathTest(string path, int? seasonNumber, bool isSeasonDirectory)
+ {
+ var result = SeasonPathParser.Parse(path, true, true);
+
+ Assert.Equal(result.SeasonNumber != null, result.Success);
+ Assert.Equal(result.SeasonNumber, seasonNumber);
+ Assert.Equal(isSeasonDirectory, result.IsSeasonFolder);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs
new file mode 100644
index 000000000..4837e3a3b
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs
@@ -0,0 +1,65 @@
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class SeasonNumberTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 25)]
+ [InlineData("/Show/Season 02/S02E03 blah.avi", 2)]
+ [InlineData("Season 1/seriesname S01x02 blah.avi", 1)]
+ [InlineData("Season 1/S01x02 blah.avi", 1)]
+ [InlineData("Season 1/seriesname S01xE02 blah.avi", 1)]
+ [InlineData("Season 1/01x02 blah.avi", 1)]
+ [InlineData("Season 1/S01E02 blah.avi", 1)]
+ [InlineData("Season 1/S01xE02 blah.avi", 1)]
+ [InlineData("Season 1/seriesname 01x02 blah.avi", 1)]
+ [InlineData("Season 1/seriesname S01E02 blah.avi", 1)]
+ [InlineData("Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 2/02x03-04-15 - Ep Name.mp4", 2)]
+ [InlineData("Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/02x03-E15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/Elementary - 02x03-E15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/02x03 - x04 - x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", 2)]
+ [InlineData("Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", 1)]
+ [InlineData("Season 1/S01E23-E24-E26 - The Woman.mp4", 1)]
+ [InlineData("Season 25/The Simpsons.S25E09.Steal this episode.mp4", 25)]
+ [InlineData("The Simpsons/The Simpsons.S25E09.Steal this episode.mp4", 25)]
+ [InlineData("2016/Season s2016e1.mp4", 2016)]
+ [InlineData("2016/Season 2016x1.mp4", 2016)]
+ [InlineData("Season 2009/2009x02 blah.avi", 2009)]
+ [InlineData("Season 2009/S2009x02 blah.avi", 2009)]
+ [InlineData("Season 2009/S2009E02 blah.avi", 2009)]
+ [InlineData("Season 2009/S2009xE02 blah.avi", 2009)]
+ [InlineData("Season 2009/seriesname 2009x02 blah.avi", 2009)]
+ [InlineData("Season 2009/seriesname S2009x02 blah.avi", 2009)]
+ [InlineData("Season 2009/seriesname S2009E02 blah.avi", 2009)]
+ [InlineData("Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/2009x03-04-15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/2009x03x04x15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4", 2009)]
+ [InlineData("Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4", 2009)]
+ [InlineData("Season 2009/S2009E23-E24-E26 - The Woman.mp4", 2009)]
+ [InlineData("Series/1-12 - The Woman.mp4", 1)]
+ [InlineData(@"Running Man/Running Man S2017E368.mkv", 2017)]
+ [InlineData(@"Case Closed (1996-2007)/Case Closed - 317.mkv", 3)]
+ // TODO: [InlineData(@"Seinfeld/Seinfeld 0807 The Checks.avi", 8)]
+ public void GetSeasonNumberFromEpisodeFileTest(string path, int? expected)
+ {
+ var result = new EpisodeResolver(_namingOptions)
+ .Resolve(path, false);
+
+ Assert.Equal(expected, result?.SeasonNumber);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs
new file mode 100644
index 000000000..6d49ac832
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs
@@ -0,0 +1,61 @@
+using System.IO;
+using Emby.Naming.Common;
+using Emby.Naming.TV;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.TV
+{
+ public class SimpleEpisodeTests
+ {
+ [Theory]
+ [InlineData("/server/anything_s01e02.mp4", "anything", 1, 2)]
+ [InlineData("/server/anything_s1e2.mp4", "anything", 1, 2)]
+ [InlineData("/server/anything_s01.e02.mp4", "anything", 1, 2)]
+ [InlineData("/server/anything_102.mp4", "anything", 1, 2)]
+ [InlineData("/server/anything_1x02.mp4", "anything", 1, 2)]
+ [InlineData("/server/The Walking Dead 4x01.mp4", "The Walking Dead", 4, 1)]
+ [InlineData("/server/the_simpsons-s02e01_18536.mp4", "the_simpsons", 2, 1)]
+ [InlineData("/server/Temp/S01E02 foo.mp4", "", 1, 2)]
+ [InlineData("Series/4x12 - The Woman.mp4", "", 4, 12)]
+ [InlineData("Series/LA X, Pt. 1_s06e32.mp4", "LA X, Pt. 1", 6, 32)]
+ [InlineData("[Baz-Bar]Foo - [1080p][Multiple Subtitle]/[Baz-Bar] Foo - 05 [1080p][Multiple Subtitle].mkv", "Foo", null, 5)]
+ [InlineData(@"/Foo/The.Series.Name.S01E04.WEBRip.x264-Baz[Bar]/the.series.name.s01e04.webrip.x264-Baz[Bar].mkv", "The.Series.Name", 1, 4)]
+ [InlineData(@"Love.Death.and.Robots.S01.1080p.NF.WEB-DL.DDP5.1.x264-NTG/Love.Death.and.Robots.S01E01.Sonnies.Edge.1080p.NF.WEB-DL.DDP5.1.x264-NTG.mkv", "Love.Death.and.Robots", 1, 1)]
+ [InlineData("[YuiSubs] Tensura Nikki - Tensei Shitara Slime Datta Ken/[YuiSubs] Tensura Nikki - Tensei Shitara Slime Datta Ken - 12 (NVENC H.265 1080p).mkv", "Tensura Nikki - Tensei Shitara Slime Datta Ken", null, 12)]
+ [InlineData("[Baz-Bar]Foo - 01 - 12[1080p][Multiple Subtitle]/[Baz-Bar] Foo - 05 [1080p][Multiple Subtitle].mkv", "Foo", null, 5)]
+ // TODO: [InlineData("E:\\Anime\\Yahari Ore no Seishun Love Comedy wa Machigatteiru\\Yahari Ore no Seishun Love Comedy wa Machigatteiru. Zoku\\Oregairu Zoku 11 - Hayama Hayato Always Renconds to Everyone's Expectations..mkv", "Yahari Ore no Seishun Love Comedy wa Machigatteiru", null, 11)]
+ // TODO: [InlineData(@"/Library/Series/The Grand Tour (2016)/Season 1/S01E01 The Holy Trinity.mkv", "The Grand Tour", 1, 1)]
+ public void TestSimple(string path, string seriesName, int? seasonNumber, int? episodeNumber)
+ {
+ Test(path, seriesName, seasonNumber, episodeNumber, null);
+ }
+
+ [Theory]
+ [InlineData("Series/4-12 - The Woman.mp4", "", 4, 12, 12)]
+ public void TestWithPossibleEpisodeEnd(string path, string seriesName, int? seasonNumber, int? episodeNumber, int? episodeEndNumber)
+ {
+ Test(path, seriesName, seasonNumber, episodeNumber, episodeEndNumber);
+ }
+
+ private void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber, int? episodeEndNumber)
+ {
+ var options = new NamingOptions();
+
+ var result = new EpisodeResolver(options)
+ .Resolve(path, false);
+
+ Assert.NotNull(result);
+ Assert.Equal(seasonNumber, result?.SeasonNumber);
+ Assert.Equal(episodeNumber, result?.EpisodeNumber);
+ Assert.Equal(seriesName, result?.SeriesName, true);
+ Assert.Equal(path, result?.Path);
+ Assert.Equal(Path.GetExtension(path).Substring(1), result?.Container);
+ Assert.Null(result?.Format3D);
+ Assert.False(result?.Is3D);
+ Assert.False(result?.IsStub);
+ Assert.Null(result?.StubType);
+ Assert.Equal(episodeEndNumber, result?.EndingEpisodeNumber);
+ Assert.False(result?.IsByDate);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs
new file mode 100644
index 000000000..b1141df47
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs
@@ -0,0 +1,67 @@
+using System.IO;
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public sealed class CleanDateTimeTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013)]
+ [InlineData(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013)]
+ [InlineData(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013)]
+ [InlineData(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013)]
+ [InlineData(@"300 (2006).mkv", "300", 2006)]
+ [InlineData(@"d:/movies/300 (2006).mkv", "300", 2006)]
+ [InlineData(@"300 2 (2006).mkv", "300 2", 2006)]
+ [InlineData(@"300 - 2 (2006).mkv", "300 - 2", 2006)]
+ [InlineData(@"300 2001 (2006).mkv", "300 2001", 2006)]
+ [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013)]
+ [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013)]
+ [InlineData(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006)]
+ [InlineData(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016)]
+ [InlineData(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013)]
+ [InlineData(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013)]
+ [InlineData(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013)]
+ [InlineData(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013)]
+ [InlineData(@"300 (2006)", "300", 2006)]
+ [InlineData(@"d:/movies/300 (2006)", "300", 2006)]
+ [InlineData(@"300 2 (2006)", "300 2", 2006)]
+ [InlineData(@"300 - 2 (2006)", "300 - 2", 2006)]
+ [InlineData(@"300 2001 (2006)", "300 2001", 2006)]
+ [InlineData(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006)]
+ [InlineData(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006)]
+ [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv", null)]
+ [InlineData(@"American Psycho.mkv", "American Psycho.mkv", null)]
+ [InlineData(@"[rec].mkv", "[rec].mkv", null)]
+ [InlineData(@"St. Vincent (2014)", "St. Vincent", 2014)]
+ [InlineData("Super movie(2009).mp4", "Super movie", 2009)]
+ [InlineData("Drug War 2013.mp4", "Drug War", 2013)]
+ [InlineData("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997)]
+ [InlineData("First Man 2018 1080p.mkv", "First Man", 2018)]
+ [InlineData("First Man (2018) 1080p.mkv", "First Man", 2018)]
+ [InlineData("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016)]
+ // FIXME: [InlineData("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018)]
+ [InlineData(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014)] // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again
+ [InlineData("3 days to kill (2005).mkv", "3 days to kill", 2005)]
+ [InlineData(@"Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", "Rain Man", 1988)]
+ [InlineData("My Movie 2013.12.09", "My Movie 2013.12.09", null)]
+ [InlineData("My Movie 2013-12-09", "My Movie 2013-12-09", null)]
+ [InlineData("My Movie 20131209", "My Movie 20131209", null)]
+ [InlineData("My Movie 2013-12-09 2013", "My Movie 2013-12-09", 2013)]
+ [InlineData(null, null, null)]
+ [InlineData("", "", null)]
+ public void CleanDateTimeTest(string input, string expectedName, int? expectedYear)
+ {
+ input = Path.GetFileName(input);
+
+ var result = VideoResolver.CleanDateTime(input, _namingOptions);
+
+ Assert.Equal(expectedName, result.Name, true);
+ Assert.Equal(expectedYear, result.Year);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs
new file mode 100644
index 000000000..1574bce58
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs
@@ -0,0 +1,52 @@
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public sealed class CleanStringTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Theory]
+ [InlineData("Super movie 480p.mp4", "Super movie")]
+ [InlineData("Super movie 480p 2001.mp4", "Super movie")]
+ [InlineData("Super movie [480p].mp4", "Super movie")]
+ [InlineData("480 Super movie [tmdbid=12345].mp4", "480 Super movie")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")]
+ [InlineData("[HorribleSubs] Made in Abyss - 13 [720p].mkv", "Made in Abyss")]
+ [InlineData("[Tsundere] Kore wa Zombie Desu ka of the Dead [BDRip h264 1920x1080 FLAC]", "Kore wa Zombie Desu ka of the Dead")]
+ [InlineData("[Erai-raws] Jujutsu Kaisen - 03 [720p][Multiple Subtitle].mkv", "Jujutsu Kaisen")]
+ [InlineData("[OCN] 애타는 로맨스 720p-NEXT", "애타는 로맨스")]
+ [InlineData("[tvN] 혼술남녀.E01-E16.720p-NEXT", "혼술남녀")]
+ [InlineData("[tvN] 연애말고 결혼 E01~E16 END HDTV.H264.720p-WITH", "연애말고 결혼")]
+ // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")]
+ public void CleanStringTest_NeedsCleaning_Success(string input, string expectedName)
+ {
+ Assert.True(VideoResolver.TryCleanString(input, _namingOptions, out var newName));
+ Assert.Equal(expectedName, newName);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("Super movie(2009).mp4")]
+ [InlineData("[rec].mkv")]
+ [InlineData("American.Psycho.mkv")]
+ [InlineData("American Psycho.mkv")]
+ [InlineData("Run lola run (lola rennt) (2009).mp4")]
+ public void CleanStringTest_DoesntNeedCleaning_False(string? input)
+ {
+ Assert.False(VideoResolver.TryCleanString(input, _namingOptions, out var newName));
+ Assert.True(string.IsNullOrEmpty(newName));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs
new file mode 100644
index 000000000..d13e89cee
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs
@@ -0,0 +1,106 @@
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using MediaBrowser.Model.Entities;
+using Xunit;
+using MediaType = Emby.Naming.Common.MediaType;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class ExtraTests
+ {
+ private readonly NamingOptions _videoOptions = new NamingOptions();
+
+ // Requirements
+ // movie-deleted = ExtraType deletedscene
+
+ // All of the above rules should be configurable through the options objects (ideally, even the ExtraTypes)
+
+ [Fact]
+ public void TestKodiExtras()
+ {
+ Test("trailer.mp4", ExtraType.Trailer);
+ Test("300-trailer.mp4", ExtraType.Trailer);
+
+ Test("theme.mp3", ExtraType.ThemeSong);
+ }
+
+ [Fact]
+ public void TestExpandedExtras()
+ {
+ Test("trailer.mp4", ExtraType.Trailer);
+ Test("trailer.mp3", null);
+ Test("300-trailer.mp4", ExtraType.Trailer);
+ Test("stuff trailerthings.mkv", null);
+
+ Test("theme.mp3", ExtraType.ThemeSong);
+ Test("theme.mkv", null);
+
+ Test("300-scene.mp4", ExtraType.Scene);
+ Test("300-scene2.mp4", ExtraType.Scene);
+ Test("300-clip.mp4", ExtraType.Clip);
+
+ Test("300-deleted.mp4", ExtraType.DeletedScene);
+ Test("300-deletedscene.mp4", ExtraType.DeletedScene);
+ Test("300-interview.mp4", ExtraType.Interview);
+ Test("300-behindthescenes.mp4", ExtraType.BehindTheScenes);
+ }
+
+ [Theory]
+ [InlineData(ExtraType.BehindTheScenes, "behind the scenes")]
+ [InlineData(ExtraType.DeletedScene, "deleted scenes")]
+ [InlineData(ExtraType.Interview, "interviews")]
+ [InlineData(ExtraType.Scene, "scenes")]
+ [InlineData(ExtraType.Sample, "samples")]
+ [InlineData(ExtraType.Clip, "shorts")]
+ [InlineData(ExtraType.Clip, "featurettes")]
+ [InlineData(ExtraType.Unknown, "extras")]
+ public void TestDirectories(ExtraType type, string dirName)
+ {
+ Test(dirName + "/300.mp4", type);
+ Test("300/" + dirName + "/something.mkv", type);
+ Test("/data/something/Movies/300/" + dirName + "/whoknows.mp4", type);
+ }
+
+ [Theory]
+ [InlineData("gibberish")]
+ [InlineData("not a scene")]
+ [InlineData("The Big Short")]
+ public void TestNonExtraDirectories(string dirName)
+ {
+ Test(dirName + "/300.mp4", null);
+ Test("300/" + dirName + "/something.mkv", null);
+ Test("/data/something/Movies/300/" + dirName + "/whoknows.mp4", null);
+ Test("/data/something/Movies/" + dirName + "/" + dirName + ".mp4", null);
+ }
+
+ [Fact]
+ public void TestSample()
+ {
+ Test("300-sample.mp4", ExtraType.Sample);
+ }
+
+ private void Test(string input, ExtraType? expectedType)
+ {
+ var parser = GetExtraTypeParser(_videoOptions);
+
+ var extraType = parser.GetExtraInfo(input).ExtraType;
+
+ Assert.Equal(expectedType, extraType);
+ }
+
+ [Fact]
+ public void TestExtraInfo_InvalidRuleType()
+ {
+ var rule = new ExtraRule(ExtraType.Unknown, ExtraRuleType.Regex, @"([eE]x(tra)?\.\w+)", MediaType.Video);
+ var options = new NamingOptions { VideoExtraRules = new[] { rule } };
+ var res = GetExtraTypeParser(options).GetExtraInfo("extra.mp4");
+
+ Assert.Equal(rule, res.Rule);
+ }
+
+ private ExtraResolver GetExtraTypeParser(NamingOptions videoOptions)
+ {
+ return new ExtraResolver(videoOptions);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs b/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs
new file mode 100644
index 000000000..1762b91b9
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs
@@ -0,0 +1,74 @@
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class Format3DTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestKodiFormat3D()
+ {
+ Test("Super movie.3d.mp4", false, null);
+ Test("Super movie.3d.hsbs.mp4", true, "hsbs");
+ Test("Super movie.3d.sbs.mp4", true, "sbs");
+ Test("Super movie.3d.htab.mp4", true, "htab");
+ Test("Super movie.3d.tab.mp4", true, "tab");
+ Test("Super movie 3d hsbs.mp4", true, "hsbs");
+ }
+
+ [Fact]
+ public void Test3DName()
+ {
+ var result = VideoResolver.ResolveFile(@"C:/Users/media/Desktop/Video Test/Movies/Oblivion/Oblivion.3d.hsbs.mkv", _namingOptions);
+
+ Assert.Equal("hsbs", result?.Format3D);
+ Assert.Equal("Oblivion", result?.Name);
+ }
+
+ [Fact]
+ public void TestExpandedFormat3D()
+ {
+ // These were introduced for Media Browser 3
+ // Kodi conventions are preferred but these still need to be supported
+
+ Test("Super movie.3d.mp4", false, null);
+ Test("Super movie.3d.hsbs.mp4", true, "hsbs");
+ Test("Super movie.3d.sbs.mp4", true, "sbs");
+ Test("Super movie.3d.htab.mp4", true, "htab");
+ Test("Super movie.3d.tab.mp4", true, "tab");
+
+ Test("Super movie.hsbs.mp4", true, "hsbs");
+ Test("Super movie.sbs.mp4", true, "sbs");
+ Test("Super movie.htab.mp4", true, "htab");
+ Test("Super movie.tab.mp4", true, "tab");
+ Test("Super movie.sbs3d.mp4", true, "sbs3d");
+ Test("Super movie.3d.mvc.mp4", true, "mvc");
+
+ Test("Super movie [3d].mp4", false, null);
+ Test("Super movie [hsbs].mp4", true, "hsbs");
+ Test("Super movie [fsbs].mp4", true, "fsbs");
+ Test("Super movie [ftab].mp4", true, "ftab");
+ Test("Super movie [htab].mp4", true, "htab");
+ Test("Super movie [sbs3d].mp4", true, "sbs3d");
+ }
+
+ private void Test(string input, bool is3D, string? format3D)
+ {
+ var result = Format3DParser.Parse(input, _namingOptions);
+
+ Assert.Equal(is3D, result.Is3D);
+
+ if (format3D == null)
+ {
+ Assert.Null(result?.Format3D);
+ }
+ else
+ {
+ Assert.Equal(format3D, result.Format3D, true);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs
new file mode 100644
index 000000000..d02f8ae92
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs
@@ -0,0 +1,448 @@
+using System.Collections.Generic;
+using System.Linq;
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using MediaBrowser.Model.IO;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class MultiVersionTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestMultiEdition1()
+ {
+ var files = new[]
+ {
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - 1080p.mkv",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past-trailer.mp4",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - [hsbs].mkv",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [hsbs].mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Single(result[0].Extras);
+ }
+
+ [Fact]
+ public void TestMultiEdition2()
+ {
+ var files = new[]
+ {
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - apple.mkv",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past-trailer.mp4",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - banana.mkv",
+ @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [banana].mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Single(result[0].Extras);
+ Assert.Equal(2, result[0].AlternateVersions.Count);
+ }
+
+ [Fact]
+ public void TestMultiEdition3()
+ {
+ var files = new[]
+ {
+ @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1925 version.mkv",
+ @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1929 version.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Single(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestLetterFolders()
+ {
+ var files = new[]
+ {
+ @"/movies/M/Movie 1.mkv",
+ @"/movies/M/Movie 2.mkv",
+ @"/movies/M/Movie 3.mkv",
+ @"/movies/M/Movie 4.mkv",
+ @"/movies/M/Movie 5.mkv",
+ @"/movies/M/Movie 6.mkv",
+ @"/movies/M/Movie 7.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(7, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersionLimit()
+ {
+ var files = new[]
+ {
+ @"/movies/Movie/Movie.mkv",
+ @"/movies/Movie/Movie-2.mkv",
+ @"/movies/Movie/Movie-3.mkv",
+ @"/movies/Movie/Movie-4.mkv",
+ @"/movies/Movie/Movie-5.mkv",
+ @"/movies/Movie/Movie-6.mkv",
+ @"/movies/Movie/Movie-7.mkv",
+ @"/movies/Movie/Movie-8.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Equal(7, result[0].AlternateVersions.Count);
+ }
+
+ [Fact]
+ public void TestMultiVersionLimit2()
+ {
+ var files = new[]
+ {
+ @"/movies/Mo/Movie 1.mkv",
+ @"/movies/Mo/Movie 2.mkv",
+ @"/movies/Mo/Movie 3.mkv",
+ @"/movies/Mo/Movie 4.mkv",
+ @"/movies/Mo/Movie 5.mkv",
+ @"/movies/Mo/Movie 6.mkv",
+ @"/movies/Mo/Movie 7.mkv",
+ @"/movies/Mo/Movie 8.mkv",
+ @"/movies/Mo/Movie 9.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(9, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion3()
+ {
+ var files = new[]
+ {
+ @"/movies/Movie/Movie 1.mkv",
+ @"/movies/Movie/Movie 2.mkv",
+ @"/movies/Movie/Movie 3.mkv",
+ @"/movies/Movie/Movie 4.mkv",
+ @"/movies/Movie/Movie 5.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(5, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion4()
+ {
+ // Test for false positive
+
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man.mkv",
+ @"/movies/Iron Man/Iron Man (2008).mkv",
+ @"/movies/Iron Man/Iron Man (2009).mkv",
+ @"/movies/Iron Man/Iron Man (2010).mkv",
+ @"/movies/Iron Man/Iron Man (2011).mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(5, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion5()
+ {
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man.mkv",
+ @"/movies/Iron Man/Iron Man-720p.mkv",
+ @"/movies/Iron Man/Iron Man-test.mkv",
+ @"/movies/Iron Man/Iron Man-bluray.mkv",
+ @"/movies/Iron Man/Iron Man-3d.mkv",
+ @"/movies/Iron Man/Iron Man-3d-hsbs.mkv",
+ @"/movies/Iron Man/Iron Man-3d.hsbs.mkv",
+ @"/movies/Iron Man/Iron Man[test].mkv",
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Equal(7, result[0].AlternateVersions.Count);
+ Assert.False(result[0].AlternateVersions[2].Is3D);
+ Assert.True(result[0].AlternateVersions[3].Is3D);
+ Assert.True(result[0].AlternateVersions[4].Is3D);
+ }
+
+ [Fact]
+ public void TestMultiVersion6()
+ {
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man.mkv",
+ @"/movies/Iron Man/Iron Man - 720p.mkv",
+ @"/movies/Iron Man/Iron Man - test.mkv",
+ @"/movies/Iron Man/Iron Man - bluray.mkv",
+ @"/movies/Iron Man/Iron Man - 3d.mkv",
+ @"/movies/Iron Man/Iron Man - 3d-hsbs.mkv",
+ @"/movies/Iron Man/Iron Man - 3d.hsbs.mkv",
+ @"/movies/Iron Man/Iron Man [test].mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Equal(7, result[0].AlternateVersions.Count);
+ Assert.False(result[0].AlternateVersions[3].Is3D);
+ Assert.True(result[0].AlternateVersions[4].Is3D);
+ Assert.True(result[0].AlternateVersions[5].Is3D);
+ }
+
+ [Fact]
+ public void TestMultiVersion7()
+ {
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man - B (2006).mkv",
+ @"/movies/Iron Man/Iron Man - C (2007).mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(2, result.Count);
+ }
+
+ [Fact]
+ public void TestMultiVersion8()
+ {
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man.mkv",
+ @"/movies/Iron Man/Iron Man_720p.mkv",
+ @"/movies/Iron Man/Iron Man_test.mkv",
+ @"/movies/Iron Man/Iron Man_bluray.mkv",
+ @"/movies/Iron Man/Iron Man_3d.mkv",
+ @"/movies/Iron Man/Iron Man_3d-hsbs.mkv",
+ @"/movies/Iron Man/Iron Man_3d.hsbs.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(7, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion9()
+ {
+ // Test for false positive
+
+ var files = new[]
+ {
+ @"/movies/Iron Man/Iron Man (2007).mkv",
+ @"/movies/Iron Man/Iron Man (2008).mkv",
+ @"/movies/Iron Man/Iron Man (2009).mkv",
+ @"/movies/Iron Man/Iron Man (2010).mkv",
+ @"/movies/Iron Man/Iron Man (2011).mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(5, result.Count);
+ Assert.Empty(result[0].Extras);
+ Assert.Empty(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion10()
+ {
+ var files = new[]
+ {
+ @"/movies/Blade Runner (1982)/Blade Runner (1982) [Final Cut] [1080p HEVC AAC].mkv",
+ @"/movies/Blade Runner (1982)/Blade Runner (1982) [EE by ADM] [480p HEVC AAC,AAC,AAC].mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Single(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void TestMultiVersion11()
+ {
+ var files = new[]
+ {
+ @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [1080p] Blu-ray.x264.DTS.mkv",
+ @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [2160p] Blu-ray.x265.AAC.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Single(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void Resolve_GivenFolderNameWithBracketsAndHyphens_GroupsBasedOnFolderName()
+ {
+ var files = new[]
+ {
+ @"/movies/John Wick - Kapitel 3 (2019) [imdbid=tt6146586]/John Wick - Kapitel 3 (2019) [imdbid=tt6146586] - Version 1.mkv",
+ @"/movies/John Wick - Kapitel 3 (2019) [imdbid=tt6146586]/John Wick - Kapitel 3 (2019) [imdbid=tt6146586] - Version 2.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ Assert.Empty(result[0].Extras);
+ Assert.Single(result[0].AlternateVersions);
+ }
+
+ [Fact]
+ public void Resolve_GivenUnclosedBrackets_DoesNotGroup()
+ {
+ var files = new[]
+ {
+ @"/movies/John Wick - Chapter 3 (2019)/John Wick - Chapter 3 (2019) [Version 1].mkv",
+ @"/movies/John Wick - Chapter 3 (2019)/John Wick - Chapter 3 (2019) [Version 2.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(2, result.Count);
+ }
+
+ [Fact]
+ public void TestEmptyList()
+ {
+ var result = VideoListResolver.Resolve(new List<FileSystemMetadata>(), _namingOptions).ToList();
+
+ Assert.Empty(result);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs
new file mode 100644
index 000000000..8794d3ebe
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs
@@ -0,0 +1,454 @@
+using System.Linq;
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using MediaBrowser.Model.IO;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class StackTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestSimpleStack()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006) part1.mkv",
+ "Bad Boys (2006) part2.mkv",
+ "Bad Boys (2006) part3.mkv",
+ "Bad Boys (2006) part4.mkv",
+ "Bad Boys (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "Bad Boys (2006)", 4);
+ }
+
+ [Fact]
+ public void TestFalsePositives()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006).mkv",
+ "Bad Boys (2007).mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestFalsePositives2()
+ {
+ var files = new[]
+ {
+ "Bad Boys 2006.mkv",
+ "Bad Boys 2007.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestFalsePositives3()
+ {
+ var files = new[]
+ {
+ "300 (2006).mkv",
+ "300 (2007).mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestFalsePositives4()
+ {
+ var files = new[]
+ {
+ "300 2006.mkv",
+ "300 2007.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestFalsePositives5()
+ {
+ var files = new[]
+ {
+ "Star Trek 1 - The motion picture.mkv",
+ "Star Trek 2- The wrath of khan.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestFalsePositives6()
+ {
+ var files = new[]
+ {
+ "Red Riding in the Year of Our Lord 1983 (2009).mkv",
+ "Red Riding in the Year of Our Lord 1980 (2009).mkv",
+ "Red Riding in the Year of Our Lord 1974 (2009).mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestStackName()
+ {
+ var files = new[]
+ {
+ "d:/movies/300 2006 part1.mkv",
+ "d:/movies/300 2006 part2.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "300 2006", 2);
+ }
+
+ [Fact]
+ public void TestDirtyNames()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006).part1.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
+ "Bad Boys (2006).part2.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
+ "Bad Boys (2006).part3.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
+ "Bad Boys (2006).part4.stv.unrated.multi.1080p.bluray.x264-rough.mkv",
+ "Bad Boys (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "Bad Boys (2006).stv.unrated.multi.1080p.bluray.x264-rough", 4);
+ }
+
+ [Fact]
+ public void TestNumberedFiles()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006).mkv",
+ "Bad Boys (2006) 1.mkv",
+ "Bad Boys (2006) 2.mkv",
+ "Bad Boys (2006) 3.mkv",
+ "Bad Boys (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestSimpleStackWithNumericName()
+ {
+ var files = new[]
+ {
+ "300 (2006) part1.mkv",
+ "300 (2006) part2.mkv",
+ "300 (2006) part3.mkv",
+ "300 (2006) part4.mkv",
+ "300 (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "300 (2006)", 4);
+ }
+
+ [Fact]
+ public void TestMixedExpressionsNotAllowed()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006) part1.mkv",
+ "Bad Boys (2006) part2.mkv",
+ "Bad Boys (2006) part3.mkv",
+ "Bad Boys (2006) parta.mkv",
+ "Bad Boys (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "Bad Boys (2006)", 3);
+ }
+
+ [Fact]
+ public void TestDualStacks()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006) part1.mkv",
+ "Bad Boys (2006) part2.mkv",
+ "Bad Boys (2006) part3.mkv",
+ "Bad Boys (2006) part4.mkv",
+ "Bad Boys (2006)-trailer.mkv",
+ "300 (2006) part1.mkv",
+ "300 (2006) part2.mkv",
+ "300 (2006) part3.mkv",
+ "300 (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Equal(2, result.Count);
+ TestStackInfo(result[1], "Bad Boys (2006)", 4);
+ TestStackInfo(result[0], "300 (2006)", 3);
+ }
+
+ [Fact]
+ public void TestDirectories()
+ {
+ var files = new[]
+ {
+ "blah blah - cd 1",
+ "blah blah - cd 2"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveDirectories(files).ToList();
+
+ Assert.Single(result);
+ TestStackInfo(result[0], "blah blah", 2);
+ }
+
+ [Fact]
+ public void TestFalsePositive()
+ {
+ var files = new[]
+ {
+ "300a.mkv",
+ "300b.mkv",
+ "300c.mkv",
+ "300-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+
+ TestStackInfo(result[0], "300", 3);
+ }
+
+ [Fact]
+ public void TestFailSequence()
+ {
+ var files = new[]
+ {
+ "300 part1.mkv",
+ "300 part2.mkv",
+ "Avatar",
+ "Avengers part1.mkv",
+ "Avengers part2.mkv",
+ "Avengers part3.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Equal(2, result.Count);
+
+ TestStackInfo(result[0], "300", 2);
+ TestStackInfo(result[1], "Avengers", 3);
+ }
+
+ [Fact]
+ public void TestMixedExpressions()
+ {
+ var files = new[]
+ {
+ "Bad Boys (2006) part1.mkv",
+ "Bad Boys (2006) part2.mkv",
+ "Bad Boys (2006) part3.mkv",
+ "Bad Boys (2006) part4.mkv",
+ "Bad Boys (2006)-trailer.mkv",
+ "300 (2006) parta.mkv",
+ "300 (2006) partb.mkv",
+ "300 (2006) partc.mkv",
+ "300 (2006) partd.mkv",
+ "300 (2006)-trailer.mkv",
+ "300a.mkv",
+ "300b.mkv",
+ "300c.mkv",
+ "300-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Equal(3, result.Count);
+
+ TestStackInfo(result[0], "300 (2006)", 4);
+ TestStackInfo(result[1], "300", 3);
+ TestStackInfo(result[2], "Bad Boys (2006)", 4);
+ }
+
+ [Fact]
+ public void TestAlphaLimitOfFour()
+ {
+ var files = new[]
+ {
+ "300 (2006) parta.mkv",
+ "300 (2006) partb.mkv",
+ "300 (2006) partc.mkv",
+ "300 (2006) partd.mkv",
+ "300 (2006) parte.mkv",
+ "300 (2006) partf.mkv",
+ "300 (2006) partg.mkv",
+ "300 (2006)-trailer.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+
+ TestStackInfo(result[0], "300 (2006)", 4);
+ }
+
+ [Fact]
+ public void TestMixed()
+ {
+ var files = new[]
+ {
+ new FileSystemMetadata { FullName = "Bad Boys (2006) part1.mkv", IsDirectory = false },
+ new FileSystemMetadata { FullName = "Bad Boys (2006) part2.mkv", IsDirectory = false },
+ new FileSystemMetadata { FullName = "300 (2006) part2", IsDirectory = true },
+ new FileSystemMetadata { FullName = "300 (2006) part3", IsDirectory = true },
+ new FileSystemMetadata { FullName = "300 (2006) part1", IsDirectory = true }
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.Resolve(files).ToList();
+
+ Assert.Equal(2, result.Count);
+ TestStackInfo(result[0], "300 (2006)", 3);
+ TestStackInfo(result[1], "Bad Boys (2006)", 2);
+ }
+
+ [Fact]
+ public void TestNamesWithoutParts()
+ {
+ // No stacking here because there is no part/disc/etc
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows.mkv",
+ "Harry Potter and the Deathly Hallows 1.mkv",
+ "Harry Potter and the Deathly Hallows 2.mkv",
+ "Harry Potter and the Deathly Hallows 3.mkv",
+ "Harry Potter and the Deathly Hallows 4.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Empty(result);
+ }
+
+ [Fact]
+ public void TestNumbersAppearingBeforePartNumber()
+ {
+ // No stacking here because there is no part/disc/etc
+ var files = new[]
+ {
+ "Neverland (2011)[720p][PG][Voted 6.5][Family-Fantasy]part1.mkv",
+ "Neverland (2011)[720p][PG][Voted 6.5][Family-Fantasy]part2.mkv"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveFiles(files).ToList();
+
+ Assert.Single(result);
+ Assert.Equal(2, result[0].Files.Count);
+ }
+
+ [Fact]
+ public void TestMultiDiscs()
+ {
+ // No stacking here because there is no part/disc/etc
+ var files = new[]
+ {
+ @"M:/Movies (DVD)/Movies (Musical)/The Sound of Music/The Sound of Music (1965) (Disc 01)",
+ @"M:/Movies (DVD)/Movies (Musical)/The Sound of Music/The Sound of Music (1965) (Disc 02)"
+ };
+
+ var resolver = GetResolver();
+
+ var result = resolver.ResolveDirectories(files).ToList();
+
+ Assert.Single(result);
+ Assert.Equal(2, result[0].Files.Count);
+ }
+
+ private void TestStackInfo(FileStack stack, string name, int fileCount)
+ {
+ Assert.Equal(fileCount, stack.Files.Count);
+ Assert.Equal(name, stack.Name);
+ }
+
+ private StackResolver GetResolver()
+ {
+ return new StackResolver(_namingOptions);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/StubTests.cs b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs
new file mode 100644
index 000000000..1d50df7a6
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs
@@ -0,0 +1,53 @@
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class StubTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestStubs()
+ {
+ Test("video.mkv", false, null);
+ Test("video.disc", true, null);
+ Test("video.dvd.disc", true, "dvd");
+ Test("video.hddvd.disc", true, "hddvd");
+ Test("video.bluray.disc", true, "bluray");
+ Test("video.brrip.disc", true, "bluray");
+ Test("video.bd25.disc", true, "bluray");
+ Test("video.bd50.disc", true, "bluray");
+ Test("video.vhs.disc", true, "vhs");
+ Test("video.hdtv.disc", true, "tv");
+ Test("video.pdtv.disc", true, "tv");
+ Test("video.dsr.disc", true, "tv");
+ Test(string.Empty, false, "tv");
+ }
+
+ [Fact]
+ public void TestStubName()
+ {
+ var result = VideoResolver.ResolveFile(@"C:/Users/media/Desktop/Video Test/Movies/Oblivion/Oblivion.dvd.disc", _namingOptions);
+
+ Assert.Equal("Oblivion", result?.Name);
+ }
+
+ private void Test(string path, bool isStub, string? stubType)
+ {
+ var isStubResult = StubResolver.TryResolveFile(path, _namingOptions, out var stubTypeResult);
+
+ Assert.Equal(isStub, isStubResult);
+
+ if (isStub)
+ {
+ Assert.Equal(stubType, stubTypeResult);
+ }
+ else
+ {
+ Assert.Null(stubTypeResult);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs
new file mode 100644
index 000000000..9e0776c3c
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs
@@ -0,0 +1,462 @@
+using System;
+using System.Linq;
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using MediaBrowser.Model.IO;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class VideoListResolverTests
+ {
+ private readonly NamingOptions _namingOptions = new NamingOptions();
+
+ [Fact]
+ public void TestStackAndExtras()
+ {
+ // No stacking here because there is no part/disc/etc
+ var files = new[]
+ {
+ "Harry Potter and the Deathly Hallows-trailer.mkv",
+ "Harry Potter and the Deathly Hallows.trailer.mkv",
+ "Harry Potter and the Deathly Hallows part1.mkv",
+ "Harry Potter and the Deathly Hallows part2.mkv",
+ "Harry Potter and the Deathly Hallows part3.mkv",
+ "Harry Potter and the Deathly Hallows part4.mkv",
+ "Batman-deleted.mkv",
+ "Batman-sample.mkv",
+ "Batman-trailer.mkv",
+ "Batman part1.mkv",
+ "Batman part2.mkv",
+ "Batman part3.mkv",
+ "Avengers.mkv",
+ "Avengers-trailer.mkv",
+
+ // Despite having a keyword in the name that will return an ExtraType, there's no original video to match it to
+ // So this is just a standalone video
+ "trailer.mkv",
+
+ // Same as above
+ "WillyWonka-trailer.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(5, result.Count);
+ var batman = result.FirstOrDefault(x => string.Equals(x.Name, "Batman", StringComparison.Ordinal));
+ Assert.NotNull(batman);
+ Assert.Equal(3, batman!.Files.Count);
+ Assert.Equal(3, batman!.Extras.Count);
+
+ var harry = result.FirstOrDefault(x => string.Equals(x.Name, "Harry Potter and the Deathly Hallows", StringComparison.Ordinal));
+ Assert.NotNull(harry);
+ Assert.Equal(4, harry!.Files.Count);
+ Assert.Equal(2, harry!.Extras.Count);
+ }
+
+ [Fact]
+ public void TestWithMetadata()
+ {
+ var files = new[]
+ {
+ "300.mkv",
+ "300.nfo"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestWithExtra()
+ {
+ var files = new[]
+ {
+ "300.mkv",
+ "300 trailer.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestVariationWithFolderName()
+ {
+ var files = new[]
+ {
+ "X-Men Days of Future Past - 1080p.mkv",
+ "X-Men Days of Future Past-trailer.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestTrailer2()
+ {
+ var files = new[]
+ {
+ "X-Men Days of Future Past - 1080p.mkv",
+ "X-Men Days of Future Past-trailer.mp4",
+ "X-Men Days of Future Past-trailer2.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestDifferentNames()
+ {
+ var files = new[]
+ {
+ "Looper (2012)-trailer.mkv",
+ "Looper.2012.bluray.720p.x264.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestSeparateFiles()
+ {
+ // These should be considered separate, unrelated videos
+ var files = new[]
+ {
+ "My video 1.mkv",
+ "My video 2.mkv",
+ "My video 3.mkv",
+ "My video 4.mkv",
+ "My video 5.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(5, result.Count);
+ }
+
+ [Fact]
+ public void TestMultiDisc()
+ {
+ var files = new[]
+ {
+ @"M:/Movies (DVD)/Movies (Musical)/Sound of Music (1965)/Sound of Music Disc 1",
+ @"M:/Movies (DVD)/Movies (Musical)/Sound of Music (1965)/Sound of Music Disc 2"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = true,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestPoundSign()
+ {
+ // These should be considered separate, unrelated videos
+ var files = new[]
+ {
+ @"My movie #1.mp4",
+ @"My movie #2.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = true,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(2, result.Count);
+ }
+
+ [Fact]
+ public void TestStackedWithTrailer()
+ {
+ var files = new[]
+ {
+ @"No (2012) part1.mp4",
+ @"No (2012) part2.mp4",
+ @"No (2012) part1-trailer.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestStackedWithTrailer2()
+ {
+ var files = new[]
+ {
+ @"No (2012) part1.mp4",
+ @"No (2012) part2.mp4",
+ @"No (2012)-trailer.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestExtrasByFolderName()
+ {
+ var files = new[]
+ {
+ @"/Movies/Top Gun (1984)/movie.mp4",
+ @"/Movies/Top Gun (1984)/Top Gun (1984)-trailer.mp4",
+ @"/Movies/Top Gun (1984)/Top Gun (1984)-trailer2.mp4",
+ @"trailer.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestDoubleTags()
+ {
+ var files = new[]
+ {
+ @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Counterfeit Racks (2011) Disc 1 cd1.avi",
+ @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Counterfeit Racks (2011) Disc 1 cd2.avi",
+ @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Disc 2 cd1.avi",
+ @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Disc 2 cd2.avi"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(2, result.Count);
+ }
+
+ [Fact]
+ public void TestArgumentOutOfRangeException()
+ {
+ var files = new[]
+ {
+ @"/nas-markrobbo78/Videos/INDEX HTPC/Movies/Watched/3 - ACTION/Argo (2012)/movie.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestColony()
+ {
+ var files = new[]
+ {
+ @"The Colony.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestFourSisters()
+ {
+ var files = new[]
+ {
+ @"Four Sisters and a Wedding - A.avi",
+ @"Four Sisters and a Wedding - B.avi"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestFourRooms()
+ {
+ var files = new[]
+ {
+ @"Four Rooms - A.avi",
+ @"Four Rooms - A.mp4"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(2, result.Count);
+ }
+
+ [Fact]
+ public void TestMovieTrailer()
+ {
+ var files = new[]
+ {
+ @"/Server/Despicable Me/Despicable Me (2010).mkv",
+ @"/Server/Despicable Me/movie-trailer.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestTrailerFalsePositives()
+ {
+ var files = new[]
+ {
+ @"/Server/Despicable Me/Skyscraper (2018) - Big Game Spot.mkv",
+ @"/Server/Despicable Me/Skyscraper (2018) - Trailer.mkv",
+ @"/Server/Despicable Me/Baywatch (2017) - Big Game Spot.mkv",
+ @"/Server/Despicable Me/Baywatch (2017) - Trailer.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Equal(4, result.Count);
+ }
+
+ [Fact]
+ public void TestSubfolders()
+ {
+ var files = new[]
+ {
+ @"/Movies/Despicable Me/Despicable Me.mkv",
+ @"/Movies/Despicable Me/trailers/trailer.mkv"
+ };
+
+ var result = VideoListResolver.Resolve(
+ files.Select(i => new FileSystemMetadata
+ {
+ IsDirectory = false,
+ FullName = i
+ }).ToList(),
+ _namingOptions).ToList();
+
+ Assert.Single(result);
+ }
+
+ [Fact]
+ public void TestDirectoryStack()
+ {
+ var stack = new FileStack();
+ Assert.False(stack.ContainsFile("XX", true));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs
new file mode 100644
index 000000000..33a99e107
--- /dev/null
+++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs
@@ -0,0 +1,194 @@
+using System.Linq;
+using Emby.Naming.Common;
+using Emby.Naming.Video;
+using MediaBrowser.Model.Entities;
+using Xunit;
+
+namespace Jellyfin.Naming.Tests.Video
+{
+ public class VideoResolverTests
+ {
+ private static NamingOptions _namingOptions = new NamingOptions();
+
+ public static TheoryData<VideoFileInfo> ResolveFile_ValidFileNameTestData()
+ {
+ var data = new TheoryData<VideoFileInfo>();
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/7 Psychos.mkv/7 Psychos.mkv",
+ container: "mkv",
+ name: "7 Psychos"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/3 days to kill (2005)/3 days to kill (2005).mkv",
+ container: "mkv",
+ name: "3 days to kill",
+ year: 2005));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/American Psycho/American.Psycho.mkv",
+ container: "mkv",
+ name: "American.Psycho"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/brave (2007)/brave (2006).3d.sbs.mkv",
+ container: "mkv",
+ name: "brave",
+ year: 2006,
+ is3D: true,
+ format3D: "sbs"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006).3d1.sbas.mkv",
+ container: "mkv",
+ name: "300",
+ year: 2006));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006).3d.sbs.mkv",
+ container: "mkv",
+ name: "300",
+ year: 2006,
+ is3D: true,
+ format3D: "sbs"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/brave (2007)/brave (2006)-trailer.bluray.disc",
+ container: "disc",
+ name: "brave",
+ year: 2006,
+ isStub: true,
+ stubType: "bluray"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006)-trailer.bluray.disc",
+ container: "disc",
+ name: "300",
+ year: 2006,
+ isStub: true,
+ stubType: "bluray"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/Brave (2007)/Brave (2006).bluray.disc",
+ container: "disc",
+ name: "Brave",
+ year: 2006,
+ isStub: true,
+ stubType: "bluray"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006).bluray.disc",
+ container: "disc",
+ name: "300",
+ year: 2006,
+ isStub: true,
+ stubType: "bluray"));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006)-trailer.mkv",
+ container: "mkv",
+ name: "300",
+ year: 2006,
+ extraType: ExtraType.Trailer));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/Brave (2007)/Brave (2006)-trailer.mkv",
+ container: "mkv",
+ name: "Brave",
+ year: 2006,
+ extraType: ExtraType.Trailer));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/300 (2007)/300 (2006).mkv",
+ container: "mkv",
+ name: "300",
+ year: 2006));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/Bad Boys (1995)/Bad Boys (1995).mkv",
+ container: "mkv",
+ name: "Bad Boys",
+ year: 1995));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/Brave (2007)/Brave (2006).mkv",
+ container: "mkv",
+ name: "Brave",
+ year: 2006));
+
+ data.Add(
+ new VideoFileInfo(
+ path: @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - JEFF/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - JEFF.mp4",
+ container: "mp4",
+ name: "Rain Man",
+ year: 1988));
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(ResolveFile_ValidFileNameTestData))]
+ public void ResolveFile_ValidFileName_Success(VideoFileInfo expectedResult)
+ {
+ var result = VideoResolver.ResolveFile(expectedResult.Path, _namingOptions);
+
+ Assert.NotNull(result);
+ Assert.Equal(result!.Path, expectedResult.Path);
+ Assert.Equal(result.Container, expectedResult.Container);
+ Assert.Equal(result.Name, expectedResult.Name);
+ Assert.Equal(result.Year, expectedResult.Year);
+ Assert.Equal(result.ExtraType, expectedResult.ExtraType);
+ Assert.Equal(result.Format3D, expectedResult.Format3D);
+ Assert.Equal(result.Is3D, expectedResult.Is3D);
+ Assert.Equal(result.IsStub, expectedResult.IsStub);
+ Assert.Equal(result.StubType, expectedResult.StubType);
+ Assert.Equal(result.IsDirectory, expectedResult.IsDirectory);
+ Assert.Equal(result.FileNameWithoutExtension.ToString(), expectedResult.FileNameWithoutExtension.ToString());
+ Assert.Equal(result.ToString(), expectedResult.ToString());
+ }
+
+ [Fact]
+ public void ResolveFile_EmptyPath()
+ {
+ var result = VideoResolver.ResolveFile(string.Empty, _namingOptions);
+
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public void ResolveDirectoryTest()
+ {
+ var paths = new[]
+ {
+ @"/Server/Iron Man",
+ @"Batman",
+ string.Empty
+ };
+
+ var results = paths.Select(path => VideoResolver.ResolveDirectory(path, _namingOptions)).ToList();
+
+ Assert.Equal(3, results.Count);
+ Assert.NotNull(results[0]);
+ Assert.NotNull(results[1]);
+ Assert.Null(results[2]);
+ foreach (var result in results)
+ {
+ Assert.Null(result?.Container);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Networking.Tests/IPHostTests.cs b/tests/Jellyfin.Networking.Tests/IPHostTests.cs
new file mode 100644
index 000000000..ec3a1300c
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/IPHostTests.cs
@@ -0,0 +1,53 @@
+using FsCheck;
+using FsCheck.Xunit;
+using MediaBrowser.Common.Net;
+using Xunit;
+
+namespace Jellyfin.Networking.Tests
+{
+ public static class IPHostTests
+ {
+ /// <summary>
+ /// Checks IP address formats.
+ /// </summary>
+ /// <param name="address">IP Address.</param>
+ [Theory]
+ [InlineData("127.0.0.1")]
+ [InlineData("127.0.0.1:123")]
+ [InlineData("localhost")]
+ [InlineData("localhost:1345")]
+ [InlineData("www.google.co.uk")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]:124")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16:123")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]")]
+ [InlineData("192.168.1.2/255.255.255.0")]
+ [InlineData("192.168.1.2/24")]
+ public static void TryParse_ValidHostStrings_True(string address)
+ => Assert.True(IPHost.TryParse(address, out _));
+
+ [Property]
+ public static Property TryParse_IPv4Address_True(IPv4Address address)
+ => IPHost.TryParse(address.Item.ToString(), out _).ToProperty();
+
+ [Property]
+ public static Property TryParse_IPv6Address_True(IPv6Address address)
+ => IPHost.TryParse(address.Item.ToString(), out _).ToProperty();
+
+ /// <summary>
+ /// All should be invalid address strings.
+ /// </summary>
+ /// <param name="address">Invalid address strings.</param>
+ [Theory]
+ [InlineData("256.128.0.0.0.1")]
+ [InlineData("127.0.0.1#")]
+ [InlineData("localhost!")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")]
+ public static void TryParse_InvalidAddressString_False(string address)
+ => Assert.False(IPHost.TryParse(address, out _));
+ }
+}
diff --git a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs b/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs
new file mode 100644
index 000000000..aa2dbc57a
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs
@@ -0,0 +1,49 @@
+using FsCheck;
+using FsCheck.Xunit;
+using MediaBrowser.Common.Net;
+using Xunit;
+
+namespace Jellyfin.Networking.Tests
+{
+ public static class IPNetAddressTests
+ {
+ /// <summary>
+ /// Checks IP address formats.
+ /// </summary>
+ /// <param name="address">IP Address.</param>
+ [Theory]
+ [InlineData("127.0.0.1")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16:123")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]")]
+ [InlineData("192.168.1.2/255.255.255.0")]
+ [InlineData("192.168.1.2/24")]
+ public static void TryParse_ValidIPStrings_True(string address)
+ => Assert.True(IPNetAddress.TryParse(address, out _));
+
+ [Property]
+ public static Property TryParse_IPv4Address_True(IPv4Address address)
+ => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty();
+
+ [Property]
+ public static Property TryParse_IPv6Address_True(IPv6Address address)
+ => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty();
+
+ /// <summary>
+ /// All should be invalid address strings.
+ /// </summary>
+ /// <param name="address">Invalid address strings.</param>
+ [Theory]
+ [InlineData("256.128.0.0.0.1")]
+ [InlineData("127.0.0.1#")]
+ [InlineData("localhost!")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")]
+ public static void TryParse_InvalidAddressString_False(string address)
+ => Assert.False(IPNetAddress.TryParse(address, out _));
+ }
+}
diff --git a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj
new file mode 100644
index 000000000..78556ee67
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj
@@ -0,0 +1,39 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="FsCheck.Xunit" Version="2.16.3" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../Emby.Server.Implementations/Emby.Server.Implementations.csproj" />
+ <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ </ItemGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+ <DefineConstants>DEBUG</DefineConstants>
+ </PropertyGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs
new file mode 100644
index 000000000..1cad625b7
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs
@@ -0,0 +1,63 @@
+using System.Net;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.Networking.Tests
+{
+ public class NetworkManagerTests
+ {
+ /// <summary>
+ /// Checks that the given IP address is in the specified network(s).
+ /// </summary>
+ /// <param name="network">Network address(es).</param>
+ /// <param name="value">The IP to check.</param>
+ [Theory]
+ [InlineData("192.168.2.1/24", "192.168.2.123")]
+ [InlineData("192.168.2.1/24, !192.168.2.122/32", "192.168.2.123")]
+ [InlineData("fd23:184f:2029:0::/56", "fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0::/56, !fd23:184f:2029:0:3139:7386:67d7:d518/128", "fd23:184f:2029:0:3139:7386:67d7:d517")]
+ public void InNetwork_True_Success(string network, string value)
+ {
+ var ip = IPAddress.Parse(value);
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ LocalNetworkSubnets = network.Split(',')
+ };
+
+ using var networkManager = new NetworkManager(NetworkParseTests.GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Assert.True(networkManager.IsInLocalNetwork(ip));
+ }
+
+ /// <summary>
+ /// Checks that thge given IP address is not in the network provided.
+ /// </summary>
+ /// <param name="network">Network address(es).</param>
+ /// <param name="value">The IP to check.</param>
+ [Theory]
+ [InlineData("192.168.10.0/24", "192.168.11.1")]
+ [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")]
+ [InlineData("192.168.10.0/24", "fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0::/56", "fd24:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0::/56, !fd23:184f:2029:0:3139:7386:67d7:d500/120", "fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0::/56", "192.168.10.60")]
+ public void InNetwork_False_Success(string network, string value)
+ {
+ var ip = IPAddress.Parse(value);
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ LocalNetworkSubnets = network.Split(',')
+ };
+
+ using var nm = new NetworkManager(NetworkParseTests.GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Assert.False(nm.IsInLocalNetwork(ip));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
new file mode 100644
index 000000000..a24eee693
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
@@ -0,0 +1,480 @@
+using System;
+using System.Collections.ObjectModel;
+using System.Net;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Networking.Tests
+{
+ public class NetworkParseTests
+ {
+ internal static IConfigurationManager GetMockConfig(NetworkConfiguration conf)
+ {
+ var configManager = new Mock<IConfigurationManager>
+ {
+ CallBase = true
+ };
+ configManager.Setup(x => x.GetConfiguration(It.IsAny<string>())).Returns(conf);
+ return configManager.Object;
+ }
+
+ /// <summary>
+ /// Checks the ability to ignore virtual interfaces.
+ /// </summary>
+ /// <param name="interfaces">Mock network setup, in the format (IP address, interface index, interface name) | .... </param>
+ /// <param name="lan">LAN addresses.</param>
+ /// <param name="value">Bind addresses that are excluded.</param>
+ [Theory]
+ // All valid
+ [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")]
+ // eth16 only
+ [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")]
+ // All interfaces excluded. (including loopbacks)
+ [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[127.0.0.1/8,::1/128]")]
+ // vEthernet1 and vEthernet212 should be excluded.
+ [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24,127.0.0.1/8,::1/128]")]
+ // Overlapping interface,
+ [InlineData("192.168.1.110/24,-20,br0|192.168.1.10/24,-16,br0|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.110/24,192.168.1.10/24]")]
+ public void IgnoreVirtualInterfaces(string interfaces, string lan, string value)
+ {
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan))
+ };
+
+ NetworkManager.MockNetworkSettings = interfaces;
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ Assert.Equal(nm.GetInternalBindAddresses().AsString(), value);
+ }
+
+ /// <summary>
+ /// Test collection parsing.
+ /// </summary>
+ /// <param name="settings">Collection to parse.</param>
+ /// <param name="result1">Included addresses from the collection.</param>
+ /// <param name="result2">Included IP4 addresses from the collection.</param>
+ /// <param name="result3">Excluded addresses from the collection.</param>
+ /// <param name="result4">Excluded IP4 addresses from the collection.</param>
+ /// <param name="result5">Network addresses of the collection.</param>
+ [Theory]
+ [InlineData(
+ "127.0.0.1#",
+ "[]",
+ "[]",
+ "[]",
+ "[]",
+ "[]")]
+ [InlineData(
+ "!127.0.0.1",
+ "[]",
+ "[]",
+ "[127.0.0.1/32]",
+ "[127.0.0.1/32]",
+ "[]")]
+ [InlineData(
+ "",
+ "[]",
+ "[]",
+ "[]",
+ "[]",
+ "[]")]
+ [InlineData(
+ "192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, !10.10.10.10",
+ "[192.158.1.2/16,[127.0.0.1/32,::1/128],fd23:184f:2029:0:3139:7386:67d7:d517/128]",
+ "[192.158.1.2/16,127.0.0.1/32]",
+ "[10.10.10.10/32]",
+ "[10.10.10.10/32]",
+ "[192.158.0.0/16,127.0.0.1/32,::1/128,fd23:184f:2029:0:3139:7386:67d7:d517/128]")]
+ [InlineData(
+ "192.158.1.2/255.255.0.0,192.169.1.2/8",
+ "[192.158.1.2/16,192.169.1.2/8]",
+ "[192.158.1.2/16,192.169.1.2/8]",
+ "[]",
+ "[]",
+ "[192.158.0.0/16,192.0.0.0/8]")]
+ public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5)
+ {
+ if (settings == null)
+ {
+ throw new ArgumentNullException(nameof(settings));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ // Test included.
+ Collection<IPObject> nc = nm.CreateIPCollection(settings.Split(','), false);
+ Assert.Equal(nc.AsString(), result1);
+
+ // Test excluded.
+ nc = nm.CreateIPCollection(settings.Split(','), true);
+ Assert.Equal(nc.AsString(), result3);
+
+ conf.EnableIPV6 = false;
+ nm.UpdateSettings(conf);
+
+ // Test IP4 included.
+ nc = nm.CreateIPCollection(settings.Split(','), false);
+ Assert.Equal(nc.AsString(), result2);
+
+ // Test IP4 excluded.
+ nc = nm.CreateIPCollection(settings.Split(','), true);
+ Assert.Equal(nc.AsString(), result4);
+
+ conf.EnableIPV6 = true;
+ nm.UpdateSettings(conf);
+
+ // Test network addresses of collection.
+ nc = nm.CreateIPCollection(settings.Split(','), false);
+ nc = nc.AsNetworks();
+ Assert.Equal(nc.AsString(), result5);
+ }
+
+ /// <summary>
+ /// Union two collections.
+ /// </summary>
+ /// <param name="settings">Source.</param>
+ /// <param name="compare">Destination.</param>
+ /// <param name="result">Result.</param>
+ [Theory]
+ [InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")]
+ [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")]
+ public void UnionCheck(string settings, string compare, string result)
+ {
+ if (settings == null)
+ {
+ throw new ArgumentNullException(nameof(settings));
+ }
+
+ if (compare == null)
+ {
+ throw new ArgumentNullException(nameof(compare));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Collection<IPObject> nc1 = nm.CreateIPCollection(settings.Split(','), false);
+ Collection<IPObject> nc2 = nm.CreateIPCollection(compare.Split(','), false);
+
+ Assert.Equal(nc1.ThatAreContainedInNetworks(nc2).AsString(), result);
+ }
+
+ [Theory]
+ [InlineData("192.168.5.85/24", "192.168.5.1")]
+ [InlineData("192.168.5.85/24", "192.168.5.254")]
+ [InlineData("10.128.240.50/30", "10.128.240.48")]
+ [InlineData("10.128.240.50/30", "10.128.240.49")]
+ [InlineData("10.128.240.50/30", "10.128.240.50")]
+ [InlineData("10.128.240.50/30", "10.128.240.51")]
+ [InlineData("127.0.0.1/8", "127.0.0.1")]
+ public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("192.168.5.85/24", "192.168.4.254")]
+ [InlineData("192.168.5.85/24", "191.168.5.254")]
+ [InlineData("10.128.240.50/30", "10.128.240.47")]
+ [InlineData("10.128.240.50/30", "10.128.240.52")]
+ [InlineData("10.128.240.50/30", "10.128.239.50")]
+ [InlineData("10.128.240.50/30", "10.127.240.51")]
+ public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")]
+ [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
+ public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")]
+ [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")]
+ public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")]
+ [InlineData("10.0.0.0/8", "10.10.10.1/32")]
+ [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")]
+
+ [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")]
+ [InlineData("10.10.0.0/16", "10.10.10.1/32")]
+ [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")]
+
+ [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")]
+ [InlineData("10.10.10.0/24", "10.10.10.1/32")]
+ [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")]
+
+ public void TestSubnetContains(string network, string ip)
+ {
+ Assert.True(IPNetAddress.TryParse(network, out var networkObj));
+ Assert.True(IPNetAddress.TryParse(ip, out var ipObj));
+ Assert.True(networkObj.Contains(ipObj));
+ }
+
+ [Theory]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")]
+
+ public void TestCollectionEquality(string source, string dest, string result)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (dest == null)
+ {
+ throw new ArgumentNullException(nameof(dest));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ // Test included, IP6.
+ Collection<IPObject> ncSource = nm.CreateIPCollection(source.Split(','));
+ Collection<IPObject> ncDest = nm.CreateIPCollection(dest.Split(','));
+ Collection<IPObject> ncResult = ncSource.ThatAreContainedInNetworks(ncDest);
+ Collection<IPObject> resultCollection = nm.CreateIPCollection(result.Split(','));
+ Assert.True(ncResult.Compare(resultCollection));
+ }
+
+ [Theory]
+ [InlineData("10.1.1.1/32", "10.1.1.1")]
+ [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")]
+
+ public void TestEquals(string source, string dest)
+ {
+ Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest)));
+ Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source)));
+ }
+
+ [Theory]
+
+ // Testing bind interfaces.
+ // On my system eth16 is internal, eth11 external (Windows defines the indexes).
+ //
+ // This test is to replicate how DNLA requests work throughout the system.
+
+ // User on internal network, we're bound internal and external - so result is internal.
+ [InlineData("192.168.1.1", "eth16,eth11", false, "eth16")]
+ // User on external network, we're bound internal and external - so result is external.
+ [InlineData("8.8.8.8", "eth16,eth11", false, "eth11")]
+ // User on internal network, we're bound internal only - so result is internal.
+ [InlineData("10.10.10.10", "eth16", false, "eth16")]
+ // User on internal network, no binding specified - so result is the 1st internal.
+ [InlineData("192.168.1.1", "", false, "eth16")]
+ // User on external network, internal binding only - so result is the 1st internal.
+ [InlineData("jellyfin.org", "eth16", false, "eth16")]
+ // User on external network, no binding - so result is the 1st external.
+ [InlineData("jellyfin.org", "", false, "eth11")]
+ // Dns failure - should skip the test.
+ // https://en.wikipedia.org/wiki/.test
+ [InlineData("invalid.domain.test", "", false, "eth11")]
+ // User assumed to be internal, no binding - so result is the 1st internal.
+ [InlineData("", "", false, "eth16")]
+ public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (bindAddresses == null)
+ {
+ throw new ArgumentNullException(nameof(bindAddresses));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ LocalNetworkAddresses = bindAddresses.Split(','),
+ EnableIPV6 = ipv6enabled,
+ EnableIPV4 = true
+ };
+
+ NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11";
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ _ = nm.TryParseInterface(result, out Collection<IPObject>? resultObj);
+
+ // Check to see if dns resolution is working. If not, skip test.
+ _ = IPHost.TryParse(source, out var host);
+
+ if (resultObj != null && host?.HasAddress == true)
+ {
+ result = ((IPNetAddress)resultObj[0]).ToString(true);
+ var intf = nm.GetBindInterface(source, out _);
+
+ Assert.Equal(intf, result);
+ }
+ }
+
+ [Theory]
+
+ // Testing bind interfaces. These are set for my system so won't work elsewhere.
+ // On my system eth16 is internal, eth11 external (Windows defines the indexes).
+ //
+ // This test is to replicate how subnet bound ServerPublisherUri work throughout the system.
+
+ // User on internal network, we're bound internal and external - so result is internal override.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "eth16,eth11", false, "192.168.1.0/24=internal.jellyfin", "internal.jellyfin")]
+
+ // User on external network, we're bound internal and external - so result is override.
+ [InlineData("8.8.8.8", "192.168.1.0/24", "eth16,eth11", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")]
+
+ // User on internal network, we're bound internal only, but the address isn't in the LAN - so return the override.
+ [InlineData("10.10.10.10", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://internalButNotDefinedAsLan.com", "http://internalButNotDefinedAsLan.com")]
+
+ // User on internal network, no binding specified - so result is the 1st internal.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")]
+
+ // User on external network, internal binding only - so assumption is a proxy forward, return external override.
+ [InlineData("jellyfin.org", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")]
+
+ // User on external network, no binding - so result is the 1st external which is overriden.
+ [InlineData("jellyfin.org", "192.168.1.0/24", "", false, "0.0.0.0 = http://helloworld.com", "http://helloworld.com")]
+
+ // User assumed to be internal, no binding - so result is the 1st internal.
+ [InlineData("", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")]
+
+ // User is internal, no binding - so result is the 1st internal, which is then overridden.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "eth16=http://helloworld.com", "http://helloworld.com")]
+ public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result)
+ {
+ if (lan == null)
+ {
+ throw new ArgumentNullException(nameof(lan));
+ }
+
+ if (bindAddresses == null)
+ {
+ throw new ArgumentNullException(nameof(bindAddresses));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ LocalNetworkSubnets = lan.Split(','),
+ LocalNetworkAddresses = bindAddresses.Split(','),
+ EnableIPV6 = ipv6enabled,
+ EnableIPV4 = true,
+ PublishedServerUriBySubnet = new string[] { publishedServers }
+ };
+
+ NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11";
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ if (nm.TryParseInterface(result, out Collection<IPObject>? resultObj) && resultObj != null)
+ {
+ // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks).
+ result = ((IPNetAddress)resultObj[0]).ToString(true);
+ }
+
+ var intf = nm.GetBindInterface(source, out int? _);
+
+ Assert.Equal(intf, result);
+ }
+
+ [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)]
+
+ public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied)
+ {
+ // 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
+ };
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied);
+ }
+
+ [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)]
+ public void HasRemoteAccess_GivenBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied)
+ {
+ // 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 = true
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj
new file mode 100644
index 000000000..bb88ec6a1
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj
@@ -0,0 +1,34 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="coverlet.collector" Version="3.1.0">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.Providers/MediaBrowser.Providers.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs
new file mode 100644
index 000000000..b194e3885
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs
@@ -0,0 +1,216 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Providers.MediaInfo;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.MediaInfo
+{
+ public class EmbeddedImageProviderTests
+ {
+ private static TheoryData<BaseItem> GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty_TestData()
+ {
+ return new ()
+ {
+ new AudioBook(),
+ new BoxSet(),
+ new Series(),
+ new Season(),
+ };
+ }
+
+ [Theory]
+ [MemberData(nameof(GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty_TestData))]
+ public void GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty(BaseItem item)
+ {
+ var embeddedImageProvider = GetEmbeddedImageProvider(null);
+ Assert.Empty(embeddedImageProvider.GetSupportedImages(item));
+ }
+
+ private static TheoryData<BaseItem, IEnumerable<ImageType>> GetSupportedImages_SupportedBaseItems_ReturnsPopulated_TestData()
+ {
+ return new TheoryData<BaseItem, IEnumerable<ImageType>>
+ {
+ { new Episode(), new List<ImageType> { ImageType.Primary } },
+ { new Movie(), new List<ImageType> { ImageType.Logo, ImageType.Backdrop, ImageType.Primary } },
+ };
+ }
+
+ [Theory]
+ [MemberData(nameof(GetSupportedImages_SupportedBaseItems_ReturnsPopulated_TestData))]
+ public void GetSupportedImages_SupportedBaseItems_ReturnsPopulated(BaseItem item, IEnumerable<ImageType> expected)
+ {
+ var embeddedImageProvider = GetEmbeddedImageProvider(null);
+ var actual = embeddedImageProvider.GetSupportedImages(item);
+ Assert.Equal(expected.OrderBy(i => i.ToString()), actual.OrderBy(i => i.ToString()));
+ }
+
+ [Fact]
+ public async void GetImage_InputWithNoStreams_ReturnsNoImage()
+ {
+ var embeddedImageProvider = GetEmbeddedImageProvider(null);
+
+ var input = GetMovie(new List<MediaAttachment>(), new List<MediaStream>());
+
+ var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_InputWithUnlabeledAttachments_ReturnsNoImage()
+ {
+ var embeddedImageProvider = GetEmbeddedImageProvider(null);
+
+ // add an attachment without a filename - has a list to look through but finds nothing
+ var input = GetMovie(
+ new List<MediaAttachment> { new () },
+ new List<MediaStream>());
+
+ var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_InputWithLabeledAttachments_ReturnsCorrectSelection()
+ {
+ // first tests file extension detection, second uses mimetype, third defaults to jpg
+ MediaAttachment sampleAttachment1 = new () { FileName = "clearlogo.png", Index = 1 };
+ MediaAttachment sampleAttachment2 = new () { FileName = "backdrop", MimeType = "image/bmp", Index = 2 };
+ MediaAttachment sampleAttachment3 = new () { FileName = "poster", Index = 3 };
+ string targetPath1 = "path1.png";
+ string targetPath2 = "path2.bmp";
+ string targetPath3 = "path2.jpg";
+
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 1, ".png", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath1));
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 2, ".bmp", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath2));
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 3, ".jpg", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath3));
+ var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(
+ new List<MediaAttachment> { sampleAttachment1, sampleAttachment2, sampleAttachment3 },
+ new List<MediaStream>());
+
+ var actualLogo = await embeddedImageProvider.GetImage(input, ImageType.Logo, CancellationToken.None);
+ Assert.NotNull(actualLogo);
+ Assert.True(actualLogo.HasImage);
+ Assert.Equal(targetPath1, actualLogo.Path);
+ Assert.Equal(ImageFormat.Png, actualLogo.Format);
+
+ var actualBackdrop = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None);
+ Assert.NotNull(actualBackdrop);
+ Assert.True(actualBackdrop.HasImage);
+ Assert.Equal(targetPath2, actualBackdrop.Path);
+ Assert.Equal(ImageFormat.Bmp, actualBackdrop.Format);
+
+ var actualPrimary = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actualPrimary);
+ Assert.True(actualPrimary.HasImage);
+ Assert.Equal(targetPath3, actualPrimary.Path);
+ Assert.Equal(ImageFormat.Jpg, actualPrimary.Format);
+ }
+
+ [Fact]
+ public async void GetImage_InputWithUnlabeledEmbeddedImages_BackdropReturnsNoImage()
+ {
+ var embeddedImageProvider = GetEmbeddedImageProvider(null);
+
+ var input = GetMovie(
+ new List<MediaAttachment>(),
+ new List<MediaStream> { new () { Type = MediaStreamType.EmbeddedImage } });
+
+ var actual = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_InputWithUnlabeledEmbeddedImages_PrimaryReturnsImage()
+ {
+ MediaStream sampleStream = new () { Type = MediaStreamType.EmbeddedImage, Index = 1 };
+ string targetPath = "path";
+
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream, 1, ".jpg", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath));
+ var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(
+ new List<MediaAttachment>(),
+ new List<MediaStream> { sampleStream });
+
+ var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.True(actual.HasImage);
+ Assert.Equal(targetPath, actual.Path);
+ Assert.Equal(ImageFormat.Jpg, actual.Format);
+ }
+
+ [Fact]
+ public async void GetImage_InputWithLabeledEmbeddedImages_ReturnsCorrectSelection()
+ {
+ // primary is second stream to ensure it's not defaulting, backdrop is first
+ MediaStream sampleStream1 = new () { Type = MediaStreamType.EmbeddedImage, Index = 1, Comment = "backdrop" };
+ MediaStream sampleStream2 = new () { Type = MediaStreamType.EmbeddedImage, Index = 2, Comment = "cover" };
+ string targetPath1 = "path1.jpg";
+ string targetPath2 = "path2.jpg";
+
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream1, 1, ".jpg", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath1));
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream2, 2, ".jpg", CancellationToken.None))
+ .Returns(Task.FromResult(targetPath2));
+ var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(
+ new List<MediaAttachment>(),
+ new List<MediaStream> { sampleStream1, sampleStream2 });
+
+ var actualPrimary = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actualPrimary);
+ Assert.True(actualPrimary.HasImage);
+ Assert.Equal(targetPath2, actualPrimary.Path);
+ Assert.Equal(ImageFormat.Jpg, actualPrimary.Format);
+
+ var actualBackdrop = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None);
+ Assert.NotNull(actualBackdrop);
+ Assert.True(actualBackdrop.HasImage);
+ Assert.Equal(targetPath1, actualBackdrop.Path);
+ Assert.Equal(ImageFormat.Jpg, actualBackdrop.Format);
+ }
+
+ private static EmbeddedImageProvider GetEmbeddedImageProvider(IMediaEncoder? mediaEncoder)
+ {
+ return new EmbeddedImageProvider(mediaEncoder);
+ }
+
+ private static Movie GetMovie(List<MediaAttachment> mediaAttachments, List<MediaStream> mediaStreams)
+ {
+ // Mocking IMediaSourceManager GetMediaAttachments and GetMediaStreams instead of mocking Movie works, but
+ // has concurrency problems between this and VideoImageProviderTests due to BaseItem.MediaSourceManager
+ // being static
+ var movie = new Mock<Movie>();
+
+ movie.Setup(item => item.GetMediaSources(It.IsAny<bool>()))
+ .Returns(new List<MediaSourceInfo> { new () { MediaAttachments = mediaAttachments } } );
+ movie.Setup(item => item.GetMediaStreams())
+ .Returns(mediaStreams);
+
+ return movie.Object;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs
new file mode 100644
index 000000000..c289a7112
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs
@@ -0,0 +1,98 @@
+#pragma warning disable CA1002 // Do not expose generic lists
+
+using System.Collections.Generic;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Providers.MediaInfo;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.MediaInfo
+{
+ public class SubtitleResolverTests
+ {
+ public static TheoryData<List<MediaStream>, string, int, string[], MediaStream[]> AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles_TestData()
+ {
+ var data = new TheoryData<List<MediaStream>, string, int, string[], MediaStream[]>();
+
+ var index = 0;
+ data.Add(
+ new List<MediaStream>(),
+ "/video/My.Video.mkv",
+ index,
+ new[]
+ {
+ "/video/My.Video.mp3",
+ "/video/My.Video.png",
+ "/video/My.Video.srt",
+ "/video/My.Video.txt",
+ "/video/My.Video.vtt",
+ "/video/My.Video.ass",
+ "/video/My.Video.sub",
+ "/video/My.Video.ssa",
+ "/video/My.Video.smi",
+ "/video/My.Video.sami",
+ "/video/My.Video.en.srt",
+ "/video/My.Video.default.en.srt",
+ "/video/My.Video.default.forced.en.srt",
+ "/video/My.Video.en.default.forced.srt",
+ "/video/My.Video.With.Additional.Garbage.en.srt",
+ "/video/My.Video With Additional Garbage.srt"
+ },
+ new[]
+ {
+ CreateMediaStream("/video/My.Video.srt", "srt", null, index++),
+ CreateMediaStream("/video/My.Video.vtt", "vtt", null, index++),
+ CreateMediaStream("/video/My.Video.ass", "ass", null, index++),
+ CreateMediaStream("/video/My.Video.sub", "sub", null, index++),
+ CreateMediaStream("/video/My.Video.ssa", "ssa", null, index++),
+ CreateMediaStream("/video/My.Video.smi", "smi", null, index++),
+ CreateMediaStream("/video/My.Video.sami", "sami", null, index++),
+ CreateMediaStream("/video/My.Video.en.srt", "srt", "en", index++),
+ CreateMediaStream("/video/My.Video.default.en.srt", "srt", "en", index++, isDefault: true),
+ CreateMediaStream("/video/My.Video.default.forced.en.srt", "srt", "en", index++, isForced: true, isDefault: true),
+ CreateMediaStream("/video/My.Video.en.default.forced.srt", "srt", "en", index++, isForced: true, isDefault: true),
+ CreateMediaStream("/video/My.Video.With.Additional.Garbage.en.srt", "srt", "en", index),
+ });
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles_TestData))]
+ public void AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles(List<MediaStream> streams, string videoPath, int startIndex, string[] files, MediaStream[] expectedResult)
+ {
+ new SubtitleResolver(Mock.Of<ILocalizationManager>()).AddExternalSubtitleStreams(streams, videoPath, startIndex, files);
+
+ Assert.Equal(expectedResult.Length, streams.Count);
+ for (var i = 0; i < expectedResult.Length; i++)
+ {
+ var expected = expectedResult[i];
+ var actual = streams[i];
+
+ Assert.Equal(expected.Index, actual.Index);
+ Assert.Equal(expected.Type, actual.Type);
+ Assert.Equal(expected.IsExternal, actual.IsExternal);
+ Assert.Equal(expected.Path, actual.Path);
+ Assert.Equal(expected.IsDefault, actual.IsDefault);
+ Assert.Equal(expected.IsForced, actual.IsForced);
+ Assert.Equal(expected.Language, actual.Language);
+ }
+ }
+
+ private static MediaStream CreateMediaStream(string path, string codec, string? language, int index, bool isForced = false, bool isDefault = false)
+ {
+ return new ()
+ {
+ Index = index,
+ Codec = codec,
+ Type = MediaStreamType.Subtitle,
+ IsExternal = true,
+ Path = path,
+ IsDefault = isDefault,
+ IsForced = isForced,
+ Language = language
+ };
+ }
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs
new file mode 100644
index 000000000..0f51a2b8f
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs
@@ -0,0 +1,176 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Providers.MediaInfo;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.MediaInfo
+{
+ public class VideoImageProviderTests
+ {
+ [Fact]
+ public async void GetImage_InputIsPlaceholder_ReturnsNoImage()
+ {
+ var videoImageProvider = GetVideoImageProvider(null);
+
+ var input = new Movie
+ {
+ IsPlaceHolder = true
+ };
+
+ var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_NoDefaultVideoStream_ReturnsNoImage()
+ {
+ var videoImageProvider = GetVideoImageProvider(null);
+
+ var input = new Movie
+ {
+ DefaultVideoStreamIndex = null
+ };
+
+ var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_DefaultSetButNoVideoStream_ReturnsNoImage()
+ {
+ var videoImageProvider = GetVideoImageProvider(null);
+
+ // set a default index but don't put anything there (invalid input, but provider shouldn't break)
+ var input = GetMovie(0, null, new List<MediaStream>());
+
+ var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.False(actual.HasImage);
+ }
+
+ [Fact]
+ public async void GetImage_DefaultSetMultipleVideoStreams_ReturnsDefaultStreamImage()
+ {
+ MediaStream firstStream = new () { Type = MediaStreamType.Video, Index = 0 };
+ MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 1 };
+ string targetPath = "path.jpg";
+
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), firstStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None))
+ .Returns(Task.FromResult("wrong stream called!"));
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), targetStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None))
+ .Returns(Task.FromResult(targetPath));
+ var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(1, targetStream, new List<MediaStream> { firstStream, targetStream } );
+
+ var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.True(actual.HasImage);
+ Assert.Equal(targetPath, actual.Path);
+ Assert.Equal(ImageFormat.Jpg, actual.Format);
+ }
+
+ [Fact]
+ public async void GetImage_InvalidDefaultSingleVideoStream_ReturnsFirstVideoStreamImage()
+ {
+ MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 };
+ string targetPath = "path.jpg";
+
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), targetStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None))
+ .Returns(Task.FromResult(targetPath));
+ var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object);
+
+ // provide query results for default (empty) and all streams (populated)
+ var input = GetMovie(5, null, new List<MediaStream> { targetStream });
+
+ var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+ Assert.NotNull(actual);
+ Assert.True(actual.HasImage);
+ Assert.Equal(targetPath, actual.Path);
+ Assert.Equal(ImageFormat.Jpg, actual.Format);
+ }
+
+ [Fact]
+ public async void GetImage_NoTimeSpanSet_CallsEncoderWithDefaultTime()
+ {
+ MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 };
+
+ // use a callback to catch the actual value
+ // provides more information on failure than verifying a specific input was called on the mock
+ TimeSpan? actualTimeSpan = null;
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None))
+ .Callback<string, string, MediaSourceInfo, MediaStream, Video3DFormat?, TimeSpan?, CancellationToken>((_, _, _, _, _, timeSpan, _) => actualTimeSpan = timeSpan)
+ .Returns(Task.FromResult("path"));
+ var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(0, targetStream, new List<MediaStream> { targetStream });
+
+ // not testing return, just verifying what gets requested for time span
+ await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+
+ Assert.Equal(TimeSpan.FromSeconds(10), actualTimeSpan);
+ }
+
+ [Fact]
+ public async void GetImage_TimeSpanSet_CallsEncoderWithCalculatedTime()
+ {
+ MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 };
+
+ TimeSpan? actualTimeSpan = null;
+ var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict);
+ mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None))
+ .Callback<string, string, MediaSourceInfo, MediaStream, Video3DFormat?, TimeSpan?, CancellationToken>((_, _, _, _, _, timeSpan, _) => actualTimeSpan = timeSpan)
+ .Returns(Task.FromResult("path"));
+ var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object);
+
+ var input = GetMovie(0, targetStream, new List<MediaStream> { targetStream });
+ input.RunTimeTicks = 5000;
+
+ // not testing return, just verifying what gets requested for time span
+ await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None);
+
+ Assert.Equal(TimeSpan.FromTicks(500), actualTimeSpan);
+ }
+
+ private static VideoImageProvider GetVideoImageProvider(IMediaEncoder? mediaEncoder)
+ {
+ // strict to ensure this isn't accidentally used where a prepared mock is intended
+ mediaEncoder ??= new Mock<IMediaEncoder>(MockBehavior.Strict).Object;
+ return new VideoImageProvider(mediaEncoder, new NullLogger<VideoImageProvider>());
+ }
+
+ private static Movie GetMovie(int defaultVideoStreamIndex, MediaStream? defaultStream, List<MediaStream> mediaStreams)
+ {
+ // Mocking IMediaSourceManager GetMediaStreams instead of mocking Movie works, but has concurrency problems
+ // between this and EmbeddedImageProviderTests due to BaseItem.MediaSourceManager being static
+ var movie = new Mock<Movie>
+ {
+ Object =
+ {
+ DefaultVideoStreamIndex = defaultVideoStreamIndex
+ }
+ };
+
+ movie.Setup(item => item.GetDefaultVideoStream())
+ .Returns(defaultStream!);
+ movie.Setup(item => item.GetMediaStreams())
+ .Returns(mediaStreams);
+
+ return movie.Object;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/Omdb/JsonOmdbConverterTests.cs b/tests/Jellyfin.Providers.Tests/Omdb/JsonOmdbConverterTests.cs
new file mode 100644
index 000000000..25900bc09
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/Omdb/JsonOmdbConverterTests.cs
@@ -0,0 +1,86 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using MediaBrowser.Providers.Plugins.Omdb;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.Omdb
+{
+ public class JsonOmdbConverterTests
+ {
+ private readonly JsonSerializerOptions _options;
+
+ public JsonOmdbConverterTests()
+ {
+ _options = new JsonSerializerOptions();
+ _options.Converters.Add(new JsonOmdbNotAvailableStringConverter());
+ _options.Converters.Add(new JsonOmdbNotAvailableInt32Converter());
+ _options.NumberHandling = JsonNumberHandling.AllowReadingFromString;
+ }
+
+ [Fact]
+ public void Deserialize_Omdb_Response_Not_Available_Success()
+ {
+ const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}";
+ var seasonRootObject = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, _options);
+ Assert.NotNull(seasonRootObject);
+ Assert.Null(seasonRootObject?.Awards);
+ Assert.Null(seasonRootObject?.Episode);
+ Assert.Null(seasonRootObject?.Metascore);
+ }
+
+ [Theory]
+ [InlineData("\"N/A\"")]
+ [InlineData("null")]
+ public void Deserialization_To_Nullable_Int_Shoud_Be_Null(string input)
+ {
+ var result = JsonSerializer.Deserialize<int?>(input, _options);
+ Assert.Null(result);
+ }
+
+ [Theory]
+ [InlineData("\"8\"", 8)]
+ [InlineData("8", 8)]
+ public void Deserialize_NullableInt_Success(string input, int? expected)
+ {
+ var result = JsonSerializer.Deserialize<int?>(input, _options);
+ Assert.Equal(result, expected);
+ }
+
+ [Theory]
+ [InlineData("\"N/A\"")]
+ [InlineData("null")]
+ public void Deserialization_To_Nullable_String_Shoud_Be_Null(string input)
+ {
+ var result = JsonSerializer.Deserialize<string?>(input, _options);
+ Assert.Null(result);
+ }
+
+ [Theory]
+ [InlineData("\"Jellyfin\"", "Jellyfin")]
+ public void Deserialize_Normal_String_Success(string input, string expected)
+ {
+ var result = JsonSerializer.Deserialize<string?>(input, _options);
+ Assert.Equal(expected, result);
+ }
+
+ [Fact]
+ public void Roundtrip_Valid_Success()
+ {
+ const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}";
+ var trip1 = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, _options);
+ Assert.NotNull(trip1);
+ Assert.NotNull(trip1?.Title);
+ Assert.Null(trip1?.Awards);
+ Assert.Null(trip1?.Episode);
+ Assert.Null(trip1?.Metascore);
+
+ var serializedTrip1 = JsonSerializer.Serialize(trip1!, _options);
+ var trip2 = JsonSerializer.Deserialize<OmdbProvider.RootObject>(serializedTrip1, _options);
+ Assert.NotNull(trip2);
+ Assert.NotNull(trip2?.Title);
+ Assert.Null(trip2?.Awards);
+ Assert.Null(trip2?.Episode);
+ Assert.Null(trip2?.Metascore);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs
new file mode 100644
index 000000000..f6a7c676f
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs
@@ -0,0 +1,27 @@
+using MediaBrowser.Providers.Plugins.Tmdb;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.Tmdb
+{
+ public static class TmdbUtilsTests
+ {
+ [Theory]
+ [InlineData("de", "de")]
+ [InlineData("En", "En")]
+ [InlineData("de-de", "de-DE")]
+ [InlineData("en-US", "en-US")]
+ [InlineData("de-CH", "de")]
+ public static void NormalizeLanguage_Valid_Success(string input, string expected)
+ {
+ Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input));
+ }
+
+ [Theory]
+ [InlineData(null, null)]
+ [InlineData("", "")]
+ public static void NormalizeLanguage_Invalid_Equal(string? input, string? expected)
+ {
+ Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input!));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs
new file mode 100644
index 000000000..6337dea41
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs
@@ -0,0 +1,290 @@
+using System;
+using System.Collections.Generic;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.Data;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Entities;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Data
+{
+ public class SqliteItemRepositoryTests
+ {
+ public const string VirtualMetaDataPath = "%MetadataPath%";
+ public const string MetaDataPath = "/meta/data/path";
+
+ private readonly IFixture _fixture;
+ private readonly SqliteItemRepository _sqliteItemRepository;
+
+ public SqliteItemRepositoryTests()
+ {
+ var appHost = new Mock<IServerApplicationHost>();
+ appHost.Setup(x => x.ExpandVirtualPath(It.IsAny<string>()))
+ .Returns((string x) => x.Replace(VirtualMetaDataPath, MetaDataPath, StringComparison.Ordinal));
+ appHost.Setup(x => x.ReverseVirtualPath(It.IsAny<string>()))
+ .Returns((string x) => x.Replace(MetaDataPath, VirtualMetaDataPath, StringComparison.Ordinal));
+
+ _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
+ _fixture.Inject(appHost);
+ _sqliteItemRepository = _fixture.Create<SqliteItemRepository>();
+ }
+
+ public static TheoryData<string, ItemImageInfo> ItemImageInfoFromValueString_Valid_TestData()
+ {
+ var data = new TheoryData<string, ItemImageInfo>();
+
+ data.Add(
+ "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN",
+ new ItemImageInfo
+ {
+ Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg",
+ Type = ImageType.Primary,
+ DateModified = new DateTime(637452096478512963, DateTimeKind.Utc),
+ Width = 1920,
+ Height = 1080,
+ BlurHash = "WjQbtJtSO8nhNZ%L_Io#R*oaS6o}-;adXAoIn7j[%hW9s:WGw[nN"
+ });
+
+ data.Add(
+ "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary*0*0",
+ new ItemImageInfo
+ {
+ Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg",
+ Type = ImageType.Primary,
+ });
+
+ data.Add(
+ "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary",
+ new ItemImageInfo
+ {
+ Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg",
+ Type = ImageType.Primary,
+ });
+
+ data.Add(
+ "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary*600",
+ new ItemImageInfo
+ {
+ Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg",
+ Type = ImageType.Primary,
+ });
+
+ data.Add(
+ "%MetadataPath%/library/68/68578562b96c80a7ebd530848801f645/poster.jpg*637264380567586027*Primary*600*336",
+ new ItemImageInfo
+ {
+ Path = "/meta/data/path/library/68/68578562b96c80a7ebd530848801f645/poster.jpg",
+ Type = ImageType.Primary,
+ DateModified = new DateTime(637264380567586027, DateTimeKind.Utc),
+ Width = 600,
+ Height = 336
+ });
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(ItemImageInfoFromValueString_Valid_TestData))]
+ public void ItemImageInfoFromValueString_Valid_Success(string value, ItemImageInfo expected)
+ {
+ var result = _sqliteItemRepository.ItemImageInfoFromValueString(value);
+ Assert.Equal(expected.Path, result.Path);
+ Assert.Equal(expected.Type, result.Type);
+ Assert.Equal(expected.DateModified, result.DateModified);
+ Assert.Equal(expected.Width, result.Width);
+ Assert.Equal(expected.Height, result.Height);
+ Assert.Equal(expected.BlurHash, result.BlurHash);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("*")]
+ [InlineData("https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0")]
+ [InlineData("/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*6374520964785129080*WjQbtJtSO8nhNZ%L_Io#R/oaS<o}-;adXAoIn7j[%hW9s:WGw[nN")] // Invalid modified date
+ [InlineData("/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*-637452096478512963*WjQbtJtSO8nhNZ%L_Io#R/oaS<o}-;adXAoIn7j[%hW9s:WGw[nN")] // Negative modified date
+ [InlineData("/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Invalid*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN")] // Invalid type
+ public void ItemImageInfoFromValueString_Invalid_Null(string value)
+ {
+ Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value));
+ }
+
+ public static TheoryData<string, ItemImageInfo[]> DeserializeImages_Valid_TestData()
+ {
+ var data = new TheoryData<string, ItemImageInfo[]>();
+ data.Add(
+ "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN",
+ new ItemImageInfo[]
+ {
+ new ItemImageInfo()
+ {
+ Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg",
+ Type = ImageType.Primary,
+ DateModified = new DateTime(637452096478512963, DateTimeKind.Utc),
+ Width = 1920,
+ Height = 1080,
+ BlurHash = "WjQbtJtSO8nhNZ%L_Io#R*oaS6o}-;adXAoIn7j[%hW9s:WGw[nN"
+ }
+ });
+
+ data.Add(
+ "%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/poster.jpg*637261226720645297*Primary*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/logo.png*637261226720805297*Logo*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/landscape.jpg*637261226721285297*Thumb*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/backdrop.jpg*637261226721685297*Backdrop*0*0",
+ new ItemImageInfo[]
+ {
+ new ItemImageInfo()
+ {
+ Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/poster.jpg",
+ Type = ImageType.Primary,
+ DateModified = new DateTime(637261226720645297, DateTimeKind.Utc),
+ },
+ new ItemImageInfo()
+ {
+ Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/logo.png",
+ Type = ImageType.Logo,
+ DateModified = new DateTime(637261226720805297, DateTimeKind.Utc),
+ },
+ new ItemImageInfo()
+ {
+ Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/landscape.jpg",
+ Type = ImageType.Thumb,
+ DateModified = new DateTime(637261226721285297, DateTimeKind.Utc),
+ },
+ new ItemImageInfo()
+ {
+ Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/backdrop.jpg",
+ Type = ImageType.Backdrop,
+ DateModified = new DateTime(637261226721685297, DateTimeKind.Utc),
+ }
+ });
+
+ return data;
+ }
+
+ public static TheoryData<string, ItemImageInfo[]> DeserializeImages_ValidAndInvalid_TestData()
+ {
+ var data = new TheoryData<string, ItemImageInfo[]>();
+ data.Add(
+ string.Empty,
+ Array.Empty<ItemImageInfo>());
+
+ data.Add(
+ "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN|test|1234||ss",
+ new ItemImageInfo[]
+ {
+ new ()
+ {
+ Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg",
+ Type = ImageType.Primary,
+ DateModified = new DateTime(637452096478512963, DateTimeKind.Utc),
+ Width = 1920,
+ Height = 1080,
+ BlurHash = "WjQbtJtSO8nhNZ%L_Io#R*oaS6o}-;adXAoIn7j[%hW9s:WGw[nN"
+ }
+ });
+
+ data.Add(
+ "|",
+ Array.Empty<ItemImageInfo>());
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(DeserializeImages_Valid_TestData))]
+ public void DeserializeImages_Valid_Success(string value, ItemImageInfo[] expected)
+ {
+ var result = _sqliteItemRepository.DeserializeImages(value);
+ Assert.Equal(expected.Length, result.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ Assert.Equal(expected[i].Path, result[i].Path);
+ Assert.Equal(expected[i].Type, result[i].Type);
+ Assert.Equal(expected[i].DateModified, result[i].DateModified);
+ Assert.Equal(expected[i].Width, result[i].Width);
+ Assert.Equal(expected[i].Height, result[i].Height);
+ Assert.Equal(expected[i].BlurHash, result[i].BlurHash);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(DeserializeImages_ValidAndInvalid_TestData))]
+ public void DeserializeImages_ValidAndInvalid_Success(string value, ItemImageInfo[] expected)
+ {
+ var result = _sqliteItemRepository.DeserializeImages(value);
+ Assert.Equal(expected.Length, result.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ Assert.Equal(expected[i].Path, result[i].Path);
+ Assert.Equal(expected[i].Type, result[i].Type);
+ Assert.Equal(expected[i].DateModified, result[i].DateModified);
+ Assert.Equal(expected[i].Width, result[i].Width);
+ Assert.Equal(expected[i].Height, result[i].Height);
+ Assert.Equal(expected[i].BlurHash, result[i].BlurHash);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(DeserializeImages_Valid_TestData))]
+ public void SerializeImages_Valid_Success(string expected, ItemImageInfo[] value)
+ {
+ Assert.Equal(expected, _sqliteItemRepository.SerializeImages(value));
+ }
+
+ public static TheoryData<string, Dictionary<string, string>> DeserializeProviderIds_Valid_TestData()
+ {
+ var data = new TheoryData<string, Dictionary<string, string>>();
+
+ data.Add(
+ "Imdb=tt0119567",
+ new Dictionary<string, string>()
+ {
+ { "Imdb", "tt0119567" },
+ });
+
+ data.Add(
+ "Imdb=tt0119567|Tmdb=330|TmdbCollection=328",
+ new Dictionary<string, string>()
+ {
+ { "Imdb", "tt0119567" },
+ { "Tmdb", "330" },
+ { "TmdbCollection", "328" },
+ });
+
+ data.Add(
+ "MusicBrainzAlbum=9d363e43-f24f-4b39-bc5a-7ef305c677c7|MusicBrainzReleaseGroup=63eba062-847c-3b73-8b0f-6baf27bba6fa|AudioDbArtist=111352|AudioDbAlbum=2116560|MusicBrainzAlbumArtist=20244d07-534f-4eff-b4d4-930878889970",
+ new Dictionary<string, string>()
+ {
+ { "MusicBrainzAlbum", "9d363e43-f24f-4b39-bc5a-7ef305c677c7" },
+ { "MusicBrainzReleaseGroup", "63eba062-847c-3b73-8b0f-6baf27bba6fa" },
+ { "AudioDbArtist", "111352" },
+ { "AudioDbAlbum", "2116560" },
+ { "MusicBrainzAlbumArtist", "20244d07-534f-4eff-b4d4-930878889970" },
+ });
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(DeserializeProviderIds_Valid_TestData))]
+ public void DeserializeProviderIds_Valid_Success(string value, Dictionary<string, string> expected)
+ {
+ var result = new ProviderIdsExtensionsTestsObject();
+ SqliteItemRepository.DeserializeProviderIds(value, result);
+ Assert.Equal(expected, result.ProviderIds);
+ }
+
+ [Theory]
+ [MemberData(nameof(DeserializeProviderIds_Valid_TestData))]
+ public void SerializeProviderIds_Valid_Success(string expected, Dictionary<string, string> values)
+ {
+ Assert.Equal(expected, SqliteItemRepository.SerializeProviderIds(values));
+ }
+
+ private class ProviderIdsExtensionsTestsObject : IHasProviderIds
+ {
+ public Dictionary<string, string> ProviderIds { get; set; } = new Dictionary<string, string>();
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs b/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs
new file mode 100644
index 000000000..1ce2096ea
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Buffers;
+using System.IO;
+using System.Text.Json;
+using Emby.Server.Implementations.HttpServer;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.HttpServer
+{
+ public class WebSocketConnectionTests
+ {
+ [Fact]
+ public void DeserializeWebSocketMessage_SingleSegment_Success()
+ {
+ var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
+ var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json");
+ con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed);
+ Assert.Equal(109, bytesConsumed);
+ }
+
+ [Fact]
+ public void DeserializeWebSocketMessage_MultipleSegments_Success()
+ {
+ const int SplitPos = 64;
+ var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
+ var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json");
+ var seg1 = new BufferSegment(new Memory<byte>(bytes, 0, SplitPos));
+ var seg2 = seg1.Append(new Memory<byte>(bytes, SplitPos, bytes.Length - SplitPos));
+ con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(seg1, 0, seg2, seg2.Memory.Length - 1), out var bytesConsumed);
+ Assert.Equal(109, bytesConsumed);
+ }
+
+ [Fact]
+ public void DeserializeWebSocketMessage_ValidPartial_Success()
+ {
+ var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
+ var bytes = File.ReadAllBytes("Test Data/HttpServer/ValidPartial.json");
+ con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed);
+ Assert.Equal(109, bytesConsumed);
+ }
+
+ [Fact]
+ public void DeserializeWebSocketMessage_Partial_ThrowJsonException()
+ {
+ var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
+ var bytes = File.ReadAllBytes("Test Data/HttpServer/Partial.json");
+ Assert.Throws<JsonException>(() => con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed));
+ }
+
+ internal class BufferSegment : ReadOnlySequenceSegment<byte>
+ {
+ public BufferSegment(Memory<byte> memory)
+ {
+ Memory = memory;
+ }
+
+ public BufferSegment Append(Memory<byte> memory)
+ {
+ var segment = new BufferSegment(memory)
+ {
+ RunningIndex = RunningIndex + Memory.Length
+ };
+ Next = segment;
+ return segment;
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs
new file mode 100644
index 000000000..d991f5574
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs
@@ -0,0 +1,76 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Runtime.InteropServices;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.IO;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.IO
+{
+ 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>();
+ }
+
+ [Theory]
+ [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")]
+ public void MakeAbsolutePathCorrectlyHandlesRelativeFilePaths(
+ string folderPath,
+ string filePath,
+ string expectedAbsolutePath)
+ {
+ var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath);
+
+ if (OperatingSystem.IsWindows())
+ {
+ var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\');
+ Assert.Equal(expectedWindowsPath, generatedPath.Split(':')[1]);
+ }
+ else
+ {
+ 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/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj
new file mode 100644
index 000000000..028ebdf55
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj
@@ -0,0 +1,45 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ <RootNamespace>Jellyfin.Server.Implementations.Tests</RootNamespace>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <None Include="Test Data\**\*.*">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
+ <ProjectReference Include="..\..\Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj" />
+ <ProjectReference Include="..\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs
new file mode 100644
index 000000000..c393742eb
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs
@@ -0,0 +1,72 @@
+using System;
+using Emby.Server.Implementations.Library.Resolvers.TV;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Library
+{
+ public class EpisodeResolverTest
+ {
+ [Fact]
+ public void Resolve_GivenVideoInExtrasFolder_DoesNotResolveToEpisode()
+ {
+ var season = new Season { Name = "Season 1" };
+ var parent = new Folder { Name = "extras" };
+ var libraryManagerMock = new Mock<ILibraryManager>();
+ libraryManagerMock.Setup(x => x.GetItemById(It.IsAny<Guid>())).Returns(season);
+
+ var episodeResolver = new EpisodeResolver(libraryManagerMock.Object);
+ var itemResolveArgs = new ItemResolveArgs(
+ Mock.Of<IServerApplicationPaths>(),
+ Mock.Of<IDirectoryService>())
+ {
+ Parent = parent,
+ CollectionType = CollectionType.TvShows,
+ FileInfo = new FileSystemMetadata()
+ {
+ FullName = "All My Children/Season 01/Extras/All My Children S01E01 - Behind The Scenes.mkv"
+ }
+ };
+
+ Assert.Null(episodeResolver.Resolve(itemResolveArgs));
+ }
+
+ [Fact]
+ public void Resolve_GivenVideoInExtrasSeriesFolder_ResolvesToEpisode()
+ {
+ var series = new Series { Name = "Extras" };
+
+ // Have to create a mock because of moq proxies not being castable to a concrete implementation
+ // https://github.com/jellyfin/jellyfin/blob/ab0cff8556403e123642dc9717ba778329554634/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs#L48
+ var episodeResolver = new EpisodeResolverMock(Mock.Of<ILibraryManager>());
+ var itemResolveArgs = new ItemResolveArgs(
+ Mock.Of<IServerApplicationPaths>(),
+ Mock.Of<IDirectoryService>())
+ {
+ Parent = series,
+ CollectionType = CollectionType.TvShows,
+ FileInfo = new FileSystemMetadata()
+ {
+ FullName = "Extras/Extras S01E01.mkv"
+ }
+ };
+ Assert.NotNull(episodeResolver.Resolve(itemResolveArgs));
+ }
+
+ private class EpisodeResolverMock : EpisodeResolver
+ {
+ public EpisodeResolverMock(ILibraryManager libraryManager) : base(libraryManager)
+ {
+ }
+
+ protected override TVideoType ResolveVideo<TVideoType>(ItemResolveArgs args, bool parseName) => new ();
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/IgnorePatternsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/IgnorePatternsTests.cs
new file mode 100644
index 000000000..09eb22328
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Library/IgnorePatternsTests.cs
@@ -0,0 +1,39 @@
+using Emby.Server.Implementations.Library;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Library
+{
+ public class IgnorePatternsTests
+ {
+ [Theory]
+ [InlineData("/media/small.jpg", true)]
+ [InlineData("/media/albumart.jpg", true)]
+ [InlineData("/media/movie.sample.mp4", true)]
+ [InlineData("/media/movie/sample.mp4", true)]
+ [InlineData("/media/movie/sample/movie.mp4", true)]
+ [InlineData("/foo/sample/bar/baz.mkv", false)]
+ [InlineData("/media/movies/the sample/the sample.mkv", false)]
+ [InlineData("/media/movies/sampler.mkv", false)]
+ [InlineData("/media/movies/#Recycle/test.txt", true)]
+ [InlineData("/media/movies/#recycle/", true)]
+ [InlineData("/media/movies/#recycle", true)]
+ [InlineData("thumbs.db", true)]
+ [InlineData(@"C:\media\movies\movie.avi", false)]
+ [InlineData("/media/.hiddendir/file.mp4", false)]
+ [InlineData("/media/dir/.hiddenfile.mp4", true)]
+ [InlineData("/media/dir/._macjunk.mp4", true)]
+ [InlineData("/volume1/video/Series/@eaDir", true)]
+ [InlineData("/volume1/video/Series/@eaDir/file.txt", true)]
+ [InlineData("/directory/@Recycle", true)]
+ [InlineData("/directory/@Recycle/file.mp3", true)]
+ [InlineData("/media/movies/.@__thumb", true)]
+ [InlineData("/media/movies/.@__thumb/foo-bar-thumbnail.png", true)]
+ [InlineData("/media/music/Foo B.A.R./epic.flac", false)]
+ [InlineData("/media/music/Foo B.A.R", false)]
+ [InlineData("/media/music/Foo B.A.R.", false)]
+ public void PathIgnored(string path, bool expected)
+ {
+ Assert.Equal(expected, IgnorePatterns.ShouldIgnore(path));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs
new file mode 100644
index 000000000..c5cc056f5
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs
@@ -0,0 +1,59 @@
+using System;
+using Emby.Server.Implementations.Library;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Library
+{
+ public class PathExtensionsTests
+ {
+ [Theory]
+ [InlineData("Superman: Red Son [imdbid=tt10985510]", "imdbid", "tt10985510")]
+ [InlineData("Superman: Red Son - tt10985510", "imdbid", "tt10985510")]
+ [InlineData("Superman: Red Son", "imdbid", null)]
+ [InlineData("Superman: Red Son", "something", null)]
+ public void GetAttributeValue_ValidArgs_Correct(string input, string attribute, string? expectedResult)
+ {
+ Assert.Equal(expectedResult, PathExtensions.GetAttributeValue(input, attribute));
+ }
+
+ [Theory]
+ [InlineData("", "")]
+ [InlineData("Superman: Red Son [imdbid=tt10985510]", "")]
+ [InlineData("", "imdbid")]
+ public void GetAttributeValue_EmptyString_ThrowsArgumentException(string input, string attribute)
+ {
+ Assert.Throws<ArgumentException>(() => PathExtensions.GetAttributeValue(input, attribute));
+ }
+
+ [Theory]
+ [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff", "/home/jeff", "/home/jeff/myfile.mkv")]
+ [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff/", "/home/jeff", "/home/jeff/myfile.mkv")]
+ [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/jeff's band", "/home/not jeff", "/home/not jeff/consistently inconsistent.mp3")]
+ [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff", "/home/jeff/myfile.mkv")]
+ [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff/", "/home/jeff/myfile.mkv")]
+ [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/home/jeff/", "/home/jeff/myfile.mkv")]
+ [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/", "/myfile.mkv")]
+ [InlineData("/o", "/o", "/s", "/s")] // regression test for #5977
+ public void TryReplaceSubPath_ValidArgs_Correct(string path, string subPath, string newSubPath, string? expectedResult)
+ {
+ Assert.True(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result));
+ Assert.Equal(expectedResult, result);
+ }
+
+ [Theory]
+ [InlineData(null, null, null)]
+ [InlineData(null, "/my/path", "/another/path")]
+ [InlineData("/my/path", null, "/another/path")]
+ [InlineData("/my/path", "/another/path", null)]
+ [InlineData("", "", "")]
+ [InlineData("/my/path", "", "")]
+ [InlineData("", "/another/path", "")]
+ [InlineData("", "", "/new/subpath")]
+ [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/not jeff's band", "/home/not jeff")]
+ public void TryReplaceSubPath_InvalidInput_ReturnsFalseAndNull(string? path, string? subPath, string? newSubPath)
+ {
+ Assert.False(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result));
+ Assert.Null(result);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs
new file mode 100644
index 000000000..c859d11c6
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs
@@ -0,0 +1,156 @@
+using System;
+using System.IO;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun;
+using MediaBrowser.Model.LiveTv;
+using Moq;
+using Moq.Protected;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.LiveTv
+{
+ public class HdHomerunHostTests
+ {
+ private readonly Fixture _fixture;
+ private readonly HdHomerunHost _hdHomerunHost;
+
+ public HdHomerunHostTests()
+ {
+ var messageHandler = new Mock<HttpMessageHandler>();
+ messageHandler.Protected()
+ .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
+ .Returns<HttpRequestMessage, CancellationToken>(
+ (m, _) =>
+ {
+ return Task.FromResult(new HttpResponseMessage()
+ {
+ Content = new StreamContent(File.OpenRead(Path.Combine("Test Data/LiveTv", m.RequestUri!.Host, m.RequestUri.Segments[^1])))
+ });
+ });
+
+ var http = new Mock<IHttpClientFactory>();
+ http.Setup(x => x.CreateClient(It.IsAny<string>()))
+ .Returns(new HttpClient(messageHandler.Object));
+ _fixture = new Fixture();
+ _fixture.Customize(new AutoMoqCustomization
+ {
+ ConfigureMembers = true
+ }).Inject(http);
+ _hdHomerunHost = _fixture.Create<HdHomerunHost>();
+ }
+
+ [Fact]
+ public async Task GetModelInfo_Valid_Success()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = "192.168.1.182"
+ };
+
+ var modelInfo = await _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None).ConfigureAwait(false);
+ Assert.Equal("HDHomeRun PRIME", modelInfo.FriendlyName);
+ Assert.Equal("HDHR3-CC", modelInfo.ModelNumber);
+ Assert.Equal("hdhomerun3_cablecard", modelInfo.FirmwareName);
+ Assert.Equal("20160630atest2", modelInfo.FirmwareVersion);
+ Assert.Equal("FFFFFFFF", modelInfo.DeviceID);
+ Assert.Equal("FFFFFFFF", modelInfo.DeviceAuth);
+ Assert.Equal(3, modelInfo.TunerCount);
+ Assert.Equal("http://192.168.1.182:80", modelInfo.BaseURL);
+ Assert.Equal("http://192.168.1.182:80/lineup.json", modelInfo.LineupURL);
+ }
+
+ [Fact]
+ public async Task GetModelInfo_Legacy_Success()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = "10.10.10.100"
+ };
+
+ var modelInfo = await _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None).ConfigureAwait(false);
+ Assert.Equal("HDHomeRun DUAL", modelInfo.FriendlyName);
+ Assert.Equal("HDHR3-US", modelInfo.ModelNumber);
+ Assert.Equal("hdhomerun3_atsc", modelInfo.FirmwareName);
+ Assert.Equal("20200225", modelInfo.FirmwareVersion);
+ Assert.Equal("10xxxxx5", modelInfo.DeviceID);
+ Assert.Null(modelInfo.DeviceAuth);
+ Assert.Equal(2, modelInfo.TunerCount);
+ Assert.Equal("http://10.10.10.100:80", modelInfo.BaseURL);
+ Assert.Null(modelInfo.LineupURL);
+ }
+
+ [Fact]
+ public async Task GetModelInfo_EmptyUrl_ArgumentException()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = string.Empty
+ };
+
+ await Assert.ThrowsAsync<ArgumentException>(() => _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None));
+ }
+
+ [Fact]
+ public async Task GetLineup_Valid_Success()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = "192.168.1.182"
+ };
+
+ var channels = await _hdHomerunHost.GetLineup(host, CancellationToken.None).ConfigureAwait(false);
+ Assert.Equal(6, channels.Count);
+ Assert.Equal("4.1", channels[0].GuideNumber);
+ Assert.Equal("WCMH-DT", channels[0].GuideName);
+ Assert.True(channels[0].HD);
+ Assert.True(channels[0].Favorite);
+ Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL);
+ }
+
+ [Fact]
+ public async Task GetLineup_Legacy_Success()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = "10.10.10.100"
+ };
+
+ // Placeholder json is invalid, just need to make sure we can reach it
+ await Assert.ThrowsAsync<JsonException>(() => _hdHomerunHost.GetLineup(host, CancellationToken.None));
+ }
+
+ [Fact]
+ public async Task GetLineup_ImportFavoritesOnly_Success()
+ {
+ var host = new TunerHostInfo()
+ {
+ Url = "192.168.1.182",
+ ImportFavoritesOnly = true
+ };
+
+ var channels = await _hdHomerunHost.GetLineup(host, CancellationToken.None).ConfigureAwait(false);
+ Assert.Single(channels);
+ Assert.Equal("4.1", channels[0].GuideNumber);
+ Assert.Equal("WCMH-DT", channels[0].GuideName);
+ Assert.True(channels[0].HD);
+ Assert.True(channels[0].Favorite);
+ Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL);
+ }
+
+ [Fact]
+ public async Task TryGetTunerHostInfo_Valid_Success()
+ {
+ var host = await _hdHomerunHost.TryGetTunerHostInfo("192.168.1.182", CancellationToken.None).ConfigureAwait(false);
+ Assert.Equal(_hdHomerunHost.Type, host.Type);
+ Assert.Equal("192.168.1.182", host.Url);
+ Assert.Equal("HDHomeRun PRIME", host.FriendlyName);
+ Assert.Equal("FFFFFFFF", host.DeviceId);
+ Assert.Equal(3, host.TunerCount);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs
new file mode 100644
index 000000000..fd499d9cf
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs
@@ -0,0 +1,326 @@
+using System;
+using System.Text;
+using Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.LiveTv
+{
+ public class HdHomerunManagerTests
+ {
+ [Fact]
+ public void WriteNullTerminatedString_Empty_Success()
+ {
+ ReadOnlySpan<byte> expected = stackalloc byte[]
+ {
+ 1, 0
+ };
+
+ Span<byte> buffer = stackalloc byte[128];
+ int len = HdHomerunManager.WriteNullTerminatedString(buffer, string.Empty);
+
+ Assert.Equal(
+ Convert.ToHexString(expected),
+ Convert.ToHexString(buffer.Slice(0, len)));
+ }
+
+ [Fact]
+ public void WriteNullTerminatedString_Valid_Success()
+ {
+ ReadOnlySpan<byte> expected = stackalloc byte[]
+ {
+ 10, (byte)'T', (byte)'h', (byte)'e', (byte)' ', (byte)'q', (byte)'u', (byte)'i', (byte)'c', (byte)'k', 0
+ };
+
+ Span<byte> buffer = stackalloc byte[128];
+ int len = HdHomerunManager.WriteNullTerminatedString(buffer, "The quick");
+
+ Assert.Equal(
+ Convert.ToHexString(expected),
+ Convert.ToHexString(buffer.Slice(0, len)));
+ }
+
+ [Fact]
+ public void WriteGetMessage_Valid_Success()
+ {
+ ReadOnlySpan<byte> expected = stackalloc byte[]
+ {
+ 0, 4,
+ 0, 12,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 0xc0, 0xc9, 0x87, 0x33
+ };
+
+ Span<byte> buffer = stackalloc byte[128];
+ int len = HdHomerunManager.WriteGetMessage(buffer, 0, "N");
+
+ Assert.Equal(
+ Convert.ToHexString(expected),
+ Convert.ToHexString(buffer.Slice(0, len)));
+ }
+
+ [Fact]
+ public void WriteSetMessage_NoLockKey_Success()
+ {
+ ReadOnlySpan<byte> expected = stackalloc byte[]
+ {
+ 0, 4,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xa9, 0x49, 0xd0, 0x68
+ };
+
+ Span<byte> buffer = stackalloc byte[128];
+ int len = HdHomerunManager.WriteSetMessage(buffer, 0, "N", "value", null);
+
+ Assert.Equal(
+ Convert.ToHexString(expected),
+ Convert.ToHexString(buffer.Slice(0, len)));
+ }
+
+ [Fact]
+ public void WriteSetMessage_LockKey_Success()
+ {
+ ReadOnlySpan<byte> expected = stackalloc byte[]
+ {
+ 0, 4,
+ 0, 26,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 21,
+ 4, 0x00, 0x01, 0x38, 0xd5,
+ 0x8e, 0xb6, 0x06, 0x82
+ };
+
+ Span<byte> buffer = stackalloc byte[128];
+ int len = HdHomerunManager.WriteSetMessage(buffer, 0, "N", "value", 80085);
+
+ Assert.Equal(
+ Convert.ToHexString(expected),
+ Convert.ToHexString(buffer.Slice(0, len)));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_Valid_Success()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x7d, 0xa3, 0xa3, 0xf3
+ };
+
+ Assert.True(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out var value));
+ Assert.Equal("value", Encoding.UTF8.GetString(value));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_InvalidCrc_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x7d, 0xa3, 0xa3, 0xf4
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_InvalidPacketType_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 4,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xa9, 0x49, 0xd0, 0x68
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_InvalidPacket_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 0x7d, 0xa3, 0xa3
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_TooSmallMessageLength_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 19,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x25, 0x25, 0x44, 0x9a
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_TooLargeMessageLength_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 21,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xe3, 0x20, 0x79, 0x6c
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_TooLargeNameLength_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 20, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xe1, 0x8e, 0x9c, 0x74
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_InvalidGetSetNameTag_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 4,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xee, 0x05, 0xe7, 0x12
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_InvalidGetSetValueTag_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 3,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x64, 0xaa, 0x66, 0xf9
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void TryGetReturnValueOfGetSet_TooLargeValueLength_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 7, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0xc9, 0xa8, 0xd4, 0x55
+ };
+
+ Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _));
+ }
+
+ [Fact]
+ public void VerifyReturnValueOfGetSet_Valid_True()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x7d, 0xa3, 0xa3, 0xf3
+ };
+
+ Assert.True(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "value"));
+ }
+
+ [Fact]
+ public void VerifyReturnValueOfGetSet_WrongValue_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 5,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x7d, 0xa3, 0xa3, 0xf3
+ };
+
+ Assert.False(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "none"));
+ }
+
+ [Fact]
+ public void VerifyReturnValueOfGetSet_InvalidPacket_False()
+ {
+ ReadOnlySpan<byte> packet = new byte[]
+ {
+ 0, 4,
+ 0, 20,
+ 3,
+ 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0,
+ 4,
+ 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0,
+ 0x7d, 0xa3, 0xa3, 0xf3
+ };
+
+ Assert.False(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "value"));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs
new file mode 100644
index 000000000..976afe195
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs
@@ -0,0 +1,98 @@
+using System;
+using Emby.Server.Implementations.LiveTv.EmbyTV;
+using MediaBrowser.Controller.LiveTv;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.LiveTv
+{
+ public static class RecordingHelperTests
+ {
+ public static TheoryData<string, TimerInfo> GetRecordingName_Success_TestData()
+ {
+ var data = new TheoryData<string, TimerInfo>();
+
+ data.Add(
+ "The Incredibles 2020_04_20_21_06_00",
+ new TimerInfo
+ {
+ Name = "The Incredibles",
+ StartDate = new DateTime(2020, 4, 20, 21, 6, 0, DateTimeKind.Local),
+ IsMovie = true
+ });
+
+ data.Add(
+ "The Incredibles (2004)",
+ new TimerInfo
+ {
+ Name = "The Incredibles",
+ IsMovie = true,
+ ProductionYear = 2004
+ });
+ data.Add(
+ "The Big Bang Theory 2020_04_20_21_06_00",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ StartDate = new DateTime(2020, 4, 20, 21, 6, 0, DateTimeKind.Local),
+ IsProgramSeries = true,
+ });
+ data.Add(
+ "The Big Bang Theory S12E10",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ IsProgramSeries = true,
+ SeasonNumber = 12,
+ EpisodeNumber = 10
+ });
+ data.Add(
+ "The Big Bang Theory S12E10 The VCR Illumination",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ IsProgramSeries = true,
+ SeasonNumber = 12,
+ EpisodeNumber = 10,
+ EpisodeTitle = "The VCR Illumination"
+ });
+ data.Add(
+ "The Big Bang Theory 2018-12-06",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ IsProgramSeries = true,
+ OriginalAirDate = new DateTime(2018, 12, 6)
+ });
+
+ data.Add(
+ "The Big Bang Theory 2018-12-06 - The VCR Illumination",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ IsProgramSeries = true,
+ OriginalAirDate = new DateTime(2018, 12, 6),
+ EpisodeTitle = "The VCR Illumination"
+ });
+
+ data.Add(
+ "The Big Bang Theory 2018_12_06_21_06_00 - The VCR Illumination",
+ new TimerInfo
+ {
+ Name = "The Big Bang Theory",
+ StartDate = new DateTime(2018, 12, 6, 21, 6, 0, DateTimeKind.Local),
+ IsProgramSeries = true,
+ OriginalAirDate = new DateTime(2018, 12, 6),
+ EpisodeTitle = "The VCR Illumination"
+ });
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(GetRecordingName_Success_TestData))]
+ public static void GetRecordingName_Success(string expected, TimerInfo timerInfo)
+ {
+ Assert.Equal(expected, RecordingHelper.GetRecordingName(timerInfo));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/SchedulesDirect/SchedulesDirectDeserializeTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/SchedulesDirect/SchedulesDirectDeserializeTests.cs
new file mode 100644
index 000000000..3b3e38bd1
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/SchedulesDirect/SchedulesDirectDeserializeTests.cs
@@ -0,0 +1,240 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.Json;
+using Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos;
+using Jellyfin.Extensions.Json;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.LiveTv.SchedulesDirect
+{
+ public class SchedulesDirectDeserializeTests
+ {
+ private readonly JsonSerializerOptions _jsonOptions;
+
+ public SchedulesDirectDeserializeTests()
+ {
+ _jsonOptions = JsonDefaults.Options;
+ }
+
+ /// <summary>
+ /// /token reponse.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Token_Response_Live_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/token_live_response.json");
+ var tokenDto = JsonSerializer.Deserialize<TokenDto>(bytes, _jsonOptions);
+
+ Assert.NotNull(tokenDto);
+ Assert.Equal(0, tokenDto!.Code);
+ Assert.Equal("OK", tokenDto.Message);
+ Assert.Equal("AWS-SD-web.1", tokenDto.ServerId);
+ Assert.Equal(new DateTime(2016, 08, 23, 13, 55, 25, DateTimeKind.Utc), tokenDto.TokenTimestamp);
+ Assert.Equal("f3fca79989cafe7dead71beefedc812b", tokenDto.Token);
+ }
+
+ /// <summary>
+ /// /token response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Token_Response_Offline_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/token_offline_response.json");
+ var tokenDto = JsonSerializer.Deserialize<TokenDto>(bytes, _jsonOptions);
+
+ Assert.NotNull(tokenDto);
+ Assert.Equal(3_000, tokenDto!.Code);
+ Assert.Equal("Server offline for maintenance.", tokenDto.Message);
+ Assert.Equal("20141201.web.1", tokenDto.ServerId);
+ Assert.Equal(new DateTime(2015, 04, 23, 00, 03, 32, DateTimeKind.Utc), tokenDto.TokenTimestamp);
+ Assert.Equal("CAFEDEADBEEFCAFEDEADBEEFCAFEDEADBEEFCAFE", tokenDto.Token);
+ Assert.Equal("SERVICE_OFFLINE", tokenDto.Response);
+ }
+
+ /// <summary>
+ /// /schedules request.
+ /// </summary>
+ [Fact]
+ public void Serialize_Schedule_Request_Success()
+ {
+ var expectedString = File.ReadAllText("Test Data/SchedulesDirect/schedules_request.json").Trim();
+
+ var requestObject = new RequestScheduleForChannelDto[]
+ {
+ new RequestScheduleForChannelDto
+ {
+ StationId = "20454",
+ Date = new[]
+ {
+ "2015-03-13",
+ "2015-03-17"
+ }
+ },
+ new RequestScheduleForChannelDto
+ {
+ StationId = "10021",
+ Date = new[]
+ {
+ "2015-03-12",
+ "2015-03-13"
+ }
+ }
+ };
+
+ var requestString = JsonSerializer.Serialize(requestObject, _jsonOptions);
+ Assert.Equal(expectedString, requestString);
+ }
+
+ /// <summary>
+ /// /schedules response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Schedule_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/schedules_response.json");
+ var days = JsonSerializer.Deserialize<IReadOnlyList<DayDto>>(bytes, _jsonOptions);
+
+ Assert.NotNull(days);
+ Assert.Equal(1, days!.Count);
+
+ var dayDto = days[0];
+ Assert.Equal("20454", dayDto.StationId);
+ Assert.Equal(2, dayDto.Programs.Count);
+
+ Assert.Equal("SH005371070000", dayDto.Programs[0].ProgramId);
+ Assert.Equal(new DateTime(2015, 03, 03, 00, 00, 00, DateTimeKind.Utc), dayDto.Programs[0].AirDateTime);
+ Assert.Equal(1_800, dayDto.Programs[0].Duration);
+ Assert.Equal("Sy8HEMBPcuiAx3FBukUhKQ", dayDto.Programs[0].Md5);
+ Assert.True(dayDto.Programs[0].New);
+ Assert.Equal(2, dayDto.Programs[0].AudioProperties.Count);
+ Assert.Equal("stereo", dayDto.Programs[0].AudioProperties[0]);
+ Assert.Equal("cc", dayDto.Programs[0].AudioProperties[1]);
+ Assert.Equal(1, dayDto.Programs[0].VideoProperties.Count);
+ Assert.Equal("hdtv", dayDto.Programs[0].VideoProperties[0]);
+ }
+
+ /// <summary>
+ /// /programs response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Program_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/programs_response.json");
+ var programDtos = JsonSerializer.Deserialize<IReadOnlyList<ProgramDetailsDto>>(bytes, _jsonOptions);
+
+ Assert.NotNull(programDtos);
+ Assert.Equal(2, programDtos!.Count);
+ Assert.Equal("EP000000060003", programDtos[0].ProgramId);
+ Assert.Equal(1, programDtos[0].Titles.Count);
+ Assert.Equal("'Allo 'Allo!", programDtos[0].Titles[0].Title120);
+ Assert.Equal("Series", programDtos[0].EventDetails?.SubType);
+ Assert.Equal("en", programDtos[0].Descriptions?.Description1000[0].DescriptionLanguage);
+ Assert.Equal("A disguised British Intelligence officer is sent to help the airmen.", programDtos[0].Descriptions?.Description1000[0].Description);
+ Assert.Equal(new DateTime(1985, 11, 04), programDtos[0].OriginalAirDate);
+ Assert.Equal(1, programDtos[0].Genres.Count);
+ Assert.Equal("Sitcom", programDtos[0].Genres[0]);
+ Assert.Equal("The Poloceman Cometh", programDtos[0].EpisodeTitle150);
+ Assert.Equal(2, programDtos[0].Metadata[0].Gracenote?.Season);
+ Assert.Equal(3, programDtos[0].Metadata[0].Gracenote?.Episode);
+ Assert.Equal(13, programDtos[0].Cast.Count);
+ Assert.Equal("383774", programDtos[0].Cast[0].PersonId);
+ Assert.Equal("392649", programDtos[0].Cast[0].NameId);
+ Assert.Equal("Gorden Kaye", programDtos[0].Cast[0].Name);
+ Assert.Equal("Actor", programDtos[0].Cast[0].Role);
+ Assert.Equal("01", programDtos[0].Cast[0].BillingOrder);
+ Assert.Equal(3, programDtos[0].Crew.Count);
+ Assert.Equal("354407", programDtos[0].Crew[0].PersonId);
+ Assert.Equal("363281", programDtos[0].Crew[0].NameId);
+ Assert.Equal("David Croft", programDtos[0].Crew[0].Name);
+ Assert.Equal("Director", programDtos[0].Crew[0].Role);
+ Assert.Equal("01", programDtos[0].Crew[0].BillingOrder);
+ }
+
+ /// <summary>
+ /// /metadata/programs response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Metadata_Programs_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/metadata_programs_response.json");
+ var showImagesDtos = JsonSerializer.Deserialize<IReadOnlyList<ShowImagesDto>>(bytes, _jsonOptions);
+
+ Assert.NotNull(showImagesDtos);
+ Assert.Equal(1, showImagesDtos!.Count);
+ Assert.Equal("SH00712240", showImagesDtos[0].ProgramId);
+ Assert.Equal(4, showImagesDtos[0].Data.Count);
+ Assert.Equal("135", showImagesDtos[0].Data[0].Width);
+ Assert.Equal("180", showImagesDtos[0].Data[0].Height);
+ Assert.Equal("assets/p282288_b_v2_aa.jpg", showImagesDtos[0].Data[0].Uri);
+ Assert.Equal("Sm", showImagesDtos[0].Data[0].Size);
+ Assert.Equal("3x4", showImagesDtos[0].Data[0].Aspect);
+ Assert.Equal("Banner-L3", showImagesDtos[0].Data[0].Category);
+ Assert.Equal("yes", showImagesDtos[0].Data[0].Text);
+ Assert.Equal("true", showImagesDtos[0].Data[0].Primary);
+ Assert.Equal("Series", showImagesDtos[0].Data[0].Tier);
+ }
+
+ /// <summary>
+ /// /headends response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Headends_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/headends_response.json");
+ var headendsDtos = JsonSerializer.Deserialize<IReadOnlyList<HeadendsDto>>(bytes, _jsonOptions);
+
+ Assert.NotNull(headendsDtos);
+ Assert.Equal(8, headendsDtos!.Count);
+ Assert.Equal("CA00053", headendsDtos[0].Headend);
+ Assert.Equal("Cable", headendsDtos[0].Transport);
+ Assert.Equal("Beverly Hills", headendsDtos[0].Location);
+ Assert.Equal(2, headendsDtos[0].Lineups.Count);
+ Assert.Equal("Time Warner Cable - Cable", headendsDtos[0].Lineups[0].Name);
+ Assert.Equal("USA-CA00053-DEFAULT", headendsDtos[0].Lineups[0].Lineup);
+ Assert.Equal("/20141201/lineups/USA-CA00053-DEFAULT", headendsDtos[0].Lineups[0].Uri);
+ }
+
+ /// <summary>
+ /// /lineups response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Lineups_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/lineups_response.json");
+ var lineupsDto = JsonSerializer.Deserialize<LineupsDto>(bytes, _jsonOptions);
+
+ Assert.NotNull(lineupsDto);
+ Assert.Equal(0, lineupsDto!.Code);
+ Assert.Equal("20141201.web.1", lineupsDto.ServerId);
+ Assert.Equal(new DateTime(2015, 04, 17, 14, 22, 17, DateTimeKind.Utc), lineupsDto.LineupTimestamp);
+ Assert.Equal(5, lineupsDto.Lineups.Count);
+ Assert.Equal("GBR-0001317-DEFAULT", lineupsDto.Lineups[0].Lineup);
+ Assert.Equal("Freeview - Carlton - LWT (Southeast)", lineupsDto.Lineups[0].Name);
+ Assert.Equal("DVB-T", lineupsDto.Lineups[0].Transport);
+ Assert.Equal("London", lineupsDto.Lineups[0].Location);
+ Assert.Equal("/20141201/lineups/GBR-0001317-DEFAULT", lineupsDto.Lineups[0].Uri);
+
+ Assert.Equal("DELETED LINEUP", lineupsDto.Lineups[4].Name);
+ Assert.True(lineupsDto.Lineups[4].IsDeleted);
+ }
+
+ /// <summary>
+ /// /lineup/:id response.
+ /// </summary>
+ [Fact]
+ public void Deserialize_Lineup_Response_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/SchedulesDirect/lineup_response.json");
+ var channelDto = JsonSerializer.Deserialize<ChannelDto>(bytes, _jsonOptions);
+
+ Assert.NotNull(channelDto);
+ Assert.Equal(2, channelDto!.Map.Count);
+ Assert.Equal("24326", channelDto.Map[0].StationId);
+ Assert.Equal("001", channelDto.Map[0].Channel);
+ Assert.Equal("BBC ONE South", channelDto.Map[0].ProvderCallsign);
+ Assert.Equal("1", channelDto.Map[0].LogicalChannelNumber);
+ Assert.Equal("providerCallsign", channelDto.Map[0].MatchType);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs
new file mode 100644
index 000000000..143020d43
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs
@@ -0,0 +1,179 @@
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using Emby.Server.Implementations.Localization;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Configuration;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Localization
+{
+ public class LocalizationManagerTests
+ {
+ [Fact]
+ public void GetCountries_All_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration
+ {
+ UICulture = "de-DE"
+ });
+ var countries = localizationManager.GetCountries().ToList();
+
+ Assert.Equal(139, countries.Count);
+
+ var germany = countries.FirstOrDefault(x => x.Name.Equals("DE", StringComparison.Ordinal));
+ Assert.NotNull(germany);
+ Assert.Equal("Germany", germany!.DisplayName);
+ Assert.Equal("DEU", germany.ThreeLetterISORegionName);
+ Assert.Equal("DE", germany.TwoLetterISORegionName);
+ }
+
+ [Fact]
+ public async Task GetCultures_All_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration
+ {
+ UICulture = "de-DE"
+ });
+ await localizationManager.LoadAll();
+ var cultures = localizationManager.GetCultures().ToList();
+
+ Assert.Equal(189, cultures.Count);
+
+ var germany = cultures.FirstOrDefault(x => x.TwoLetterISOLanguageName.Equals("de", StringComparison.Ordinal));
+ Assert.NotNull(germany);
+ Assert.Equal("ger", germany!.ThreeLetterISOLanguageName);
+ Assert.Equal("German", germany.DisplayName);
+ Assert.Equal("German", germany.Name);
+ Assert.Contains("deu", germany.ThreeLetterISOLanguageNames);
+ Assert.Contains("ger", germany.ThreeLetterISOLanguageNames);
+ }
+
+ [Theory]
+ [InlineData("de")]
+ [InlineData("ger")]
+ [InlineData("german")]
+ public async Task FindLanguageInfo_Valid_Success(string identifier)
+ {
+ var localizationManager = Setup(new ServerConfiguration
+ {
+ UICulture = "de-DE"
+ });
+ await localizationManager.LoadAll();
+
+ var germany = localizationManager.FindLanguageInfo(identifier);
+ Assert.NotNull(germany);
+
+ Assert.Equal("ger", germany!.ThreeLetterISOLanguageName);
+ Assert.Equal("German", germany.DisplayName);
+ Assert.Equal("German", germany.Name);
+ Assert.Contains("deu", germany.ThreeLetterISOLanguageNames);
+ Assert.Contains("ger", germany.ThreeLetterISOLanguageNames);
+ }
+
+ [Fact]
+ public async Task GetParentalRatings_Default_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration
+ {
+ UICulture = "de-DE"
+ });
+ await localizationManager.LoadAll();
+ var ratings = localizationManager.GetParentalRatings().ToList();
+
+ Assert.Equal(23, ratings.Count);
+
+ var tvma = ratings.FirstOrDefault(x => x.Name.Equals("TV-MA", StringComparison.Ordinal));
+ Assert.NotNull(tvma);
+ Assert.Equal(9, tvma!.Value);
+ }
+
+ [Fact]
+ public async Task GetParentalRatings_ConfiguredCountryCode_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration()
+ {
+ MetadataCountryCode = "DE"
+ });
+ await localizationManager.LoadAll();
+ var ratings = localizationManager.GetParentalRatings().ToList();
+
+ Assert.Equal(10, ratings.Count);
+
+ var fsk = ratings.FirstOrDefault(x => x.Name.Equals("FSK-12", StringComparison.Ordinal));
+ Assert.NotNull(fsk);
+ Assert.Equal(7, fsk!.Value);
+ }
+
+ [Theory]
+ [InlineData("CA-R", "CA", 10)]
+ [InlineData("FSK-16", "DE", 8)]
+ [InlineData("FSK-18", "DE", 9)]
+ [InlineData("FSK-18", "US", 9)]
+ [InlineData("TV-MA", "US", 9)]
+ [InlineData("XXX", "asdf", 100)]
+ [InlineData("Germany: FSK-18", "DE", 9)]
+ public async Task GetRatingLevel_GivenValidString_Success(string value, string countryCode, int expectedLevel)
+ {
+ var localizationManager = Setup(new ServerConfiguration()
+ {
+ MetadataCountryCode = countryCode
+ });
+ await localizationManager.LoadAll();
+ var level = localizationManager.GetRatingLevel(value);
+ Assert.NotNull(level);
+ Assert.Equal(expectedLevel, level!);
+ }
+
+ [Fact]
+ public async Task GetRatingLevel_GivenUnratedString_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration()
+ {
+ UICulture = "de-DE"
+ });
+ await localizationManager.LoadAll();
+ Assert.Null(localizationManager.GetRatingLevel("n/a"));
+ }
+
+ [Theory]
+ [InlineData("Default", "Default")]
+ [InlineData("HeaderLiveTV", "Live TV")]
+ public void GetLocalizedString_Valid_Success(string key, string expected)
+ {
+ var localizationManager = Setup(new ServerConfiguration()
+ {
+ UICulture = "en-US"
+ });
+
+ var translated = localizationManager.GetLocalizedString(key);
+ Assert.NotNull(translated);
+ Assert.Equal(expected, translated);
+ }
+
+ [Fact]
+ public void GetLocalizedString_Invalid_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration()
+ {
+ UICulture = "en-US"
+ });
+
+ var key = "SuperInvalidTranslationKeyThatWillNeverBeAdded";
+
+ var translated = localizationManager.GetLocalizedString(key);
+ Assert.NotNull(translated);
+ Assert.Equal(key, translated);
+ }
+
+ private LocalizationManager Setup(ServerConfiguration config)
+ {
+ var mockConfiguration = new Mock<IServerConfigurationManager>();
+ mockConfiguration.SetupGet(x => x.Configuration).Returns(config);
+
+ return new LocalizationManager(mockConfiguration.Object, new NullLogger<LocalizationManager>());
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
new file mode 100644
index 000000000..bc6a44741
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
@@ -0,0 +1,45 @@
+using System;
+using System.IO;
+using Emby.Server.Implementations.Plugins;
+using MediaBrowser.Common.Plugins;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Plugins
+{
+ public class PluginManagerTests
+ {
+ private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
+
+ [Fact]
+ public void SaveManifest_RoundTrip_Success()
+ {
+ var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, null!, new Version(1, 0));
+ var manifest = new PluginManifest()
+ {
+ Version = "1.0"
+ };
+
+ var tempPath = Path.Combine(_testPathRoot, "manifest-" + Path.GetRandomFileName());
+ Directory.CreateDirectory(tempPath);
+
+ Assert.True(pluginManager.SaveManifest(manifest, tempPath));
+
+ var res = pluginManager.LoadManifest(tempPath);
+
+ Assert.Equal(manifest.Category, res.Manifest.Category);
+ Assert.Equal(manifest.Changelog, res.Manifest.Changelog);
+ Assert.Equal(manifest.Description, res.Manifest.Description);
+ Assert.Equal(manifest.Id, res.Manifest.Id);
+ Assert.Equal(manifest.Name, res.Manifest.Name);
+ Assert.Equal(manifest.Overview, res.Manifest.Overview);
+ Assert.Equal(manifest.Owner, res.Manifest.Owner);
+ Assert.Equal(manifest.TargetAbi, res.Manifest.TargetAbi);
+ Assert.Equal(manifest.Timestamp, res.Manifest.Timestamp);
+ Assert.Equal(manifest.Version, res.Manifest.Version);
+ Assert.Equal(manifest.Status, res.Manifest.Status);
+ Assert.Equal(manifest.AutoUpdate, res.Manifest.AutoUpdate);
+ Assert.Equal(manifest.ImagePath, res.Manifest.ImagePath);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/QuickConnect/QuickConnectManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/QuickConnect/QuickConnectManagerTests.cs
new file mode 100644
index 000000000..28d832ef8
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/QuickConnect/QuickConnectManagerTests.cs
@@ -0,0 +1,124 @@
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.QuickConnect;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Model.Configuration;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.QuickConnect
+{
+ public class QuickConnectManagerTests
+ {
+ private static readonly AuthorizationInfo _quickConnectAuthInfo = new AuthorizationInfo
+ {
+ Device = "Device",
+ DeviceId = "DeviceId",
+ Client = "Client",
+ Version = "1.0.0"
+ };
+
+ private readonly Fixture _fixture;
+ private readonly ServerConfiguration _config;
+ private readonly QuickConnectManager _quickConnectManager;
+
+ public QuickConnectManagerTests()
+ {
+ _config = new ServerConfiguration();
+ var configManager = new Mock<IServerConfigurationManager>();
+ configManager.Setup(x => x.Configuration).Returns(_config);
+
+ _fixture = new Fixture();
+ _fixture.Customize(new AutoMoqCustomization
+ {
+ ConfigureMembers = true
+ }).Inject(configManager.Object);
+
+ // User object contains circular references.
+ _fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
+ .ForEach(b => _fixture.Behaviors.Remove(b));
+ _fixture.Behaviors.Add(new OmitOnRecursionBehavior());
+
+ _quickConnectManager = _fixture.Create<QuickConnectManager>();
+ }
+
+ [Fact]
+ public void IsEnabled_QuickConnectUnavailable_False()
+ => Assert.False(_quickConnectManager.IsEnabled);
+
+ [Theory]
+ [InlineData("", "DeviceId", "Client", "1.0.0")]
+ [InlineData("Device", "", "Client", "1.0.0")]
+ [InlineData("Device", "DeviceId", "", "1.0.0")]
+ [InlineData("Device", "DeviceId", "Client", "")]
+ public void TryConnect_InvalidAuthorizationInfo_ThrowsArgumentException(string device, string deviceId, string client, string version)
+ => Assert.Throws<ArgumentException>(() => _quickConnectManager.TryConnect(
+ new AuthorizationInfo
+ {
+ Device = device,
+ DeviceId = deviceId,
+ Client = client,
+ Version = version
+ }));
+
+ [Fact]
+ public void TryConnect_QuickConnectUnavailable_ThrowsAuthenticationException()
+ => Assert.Throws<AuthenticationException>(() => _quickConnectManager.TryConnect(_quickConnectAuthInfo));
+
+ [Fact]
+ public void CheckRequestStatus_QuickConnectUnavailable_ThrowsAuthenticationException()
+ => Assert.Throws<AuthenticationException>(() => _quickConnectManager.CheckRequestStatus(string.Empty));
+
+ [Fact]
+ public void AuthorizeRequest_QuickConnectUnavailable_ThrowsAuthenticationException()
+ => Assert.ThrowsAsync<AuthenticationException>(() => _quickConnectManager.AuthorizeRequest(Guid.Empty, string.Empty));
+
+ [Fact]
+ public void GetAuthorizedRequest_QuickConnectUnavailable_ThrowsAuthenticationException()
+ => Assert.Throws<AuthenticationException>(() => _quickConnectManager.GetAuthorizedRequest(string.Empty));
+
+ [Fact]
+ public void IsEnabled_QuickConnectAvailable_True()
+ {
+ _config.QuickConnectAvailable = true;
+ Assert.True(_quickConnectManager.IsEnabled);
+ }
+
+ [Fact]
+ public void CheckRequestStatus_QuickConnectAvailable_Success()
+ {
+ _config.QuickConnectAvailable = true;
+ var res1 = _quickConnectManager.TryConnect(_quickConnectAuthInfo);
+ var res2 = _quickConnectManager.CheckRequestStatus(res1.Secret);
+ Assert.Equal(res1, res2);
+ }
+
+ [Fact]
+ public void CheckRequestStatus_UnknownSecret_ThrowsResourceNotFoundException()
+ {
+ _config.QuickConnectAvailable = true;
+ Assert.Throws<ResourceNotFoundException>(() => _quickConnectManager.CheckRequestStatus("Unknown secret"));
+ }
+
+ [Fact]
+ public void GetAuthorizedRequest_UnknownSecret_ThrowsResourceNotFoundException()
+ {
+ _config.QuickConnectAvailable = true;
+ Assert.Throws<ResourceNotFoundException>(() => _quickConnectManager.GetAuthorizedRequest("Unknown secret"));
+ }
+
+ [Fact]
+ public async Task AuthorizeRequest_QuickConnectAvailable_Success()
+ {
+ _config.QuickConnectAvailable = true;
+ var res = _quickConnectManager.TryConnect(_quickConnectAuthInfo);
+ Assert.True(await _quickConnectManager.AuthorizeRequest(Guid.Empty, res.Code));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Sorting/AiredEpisodeOrderComparerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Sorting/AiredEpisodeOrderComparerTests.cs
new file mode 100644
index 000000000..59d82678e
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Sorting/AiredEpisodeOrderComparerTests.cs
@@ -0,0 +1,164 @@
+using System;
+using Emby.Server.Implementations.Sorting;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Sorting
+{
+ public class AiredEpisodeOrderComparerTests
+ {
+ [Theory]
+ [ClassData(typeof(EpisodeBadData))]
+ public void Compare_GivenNull_ThrowsArgumentNullException(BaseItem? x, BaseItem? y)
+ {
+ var cmp = new AiredEpisodeOrderComparer();
+ Assert.Throws<ArgumentNullException>(() => cmp.Compare(x, y));
+ }
+
+ [Theory]
+ [ClassData(typeof(EpisodeTestData))]
+ public void AiredEpisodeOrderCompareTest(BaseItem x, BaseItem y, int expected)
+ {
+ var cmp = new AiredEpisodeOrderComparer();
+
+ Assert.Equal(expected, cmp.Compare(x, y));
+ Assert.Equal(-expected, cmp.Compare(y, x));
+ }
+
+ private class EpisodeBadData : TheoryData<BaseItem?, BaseItem?>
+ {
+ public EpisodeBadData()
+ {
+ Add(null, new Episode());
+ Add(new Episode(), null);
+ }
+ }
+
+ private class EpisodeTestData : TheoryData<BaseItem, BaseItem, int>
+ {
+ public EpisodeTestData()
+ {
+ Add(
+ new Movie(),
+ new Movie(),
+ 0);
+
+ Add(
+ new Movie(),
+ new Episode(),
+ 1);
+
+ // Good cases
+ Add(
+ new Episode(),
+ new Episode(),
+ 0);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ 0);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 2 },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 2, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ 1);
+
+ // Good Specials
+ Add(
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ 0);
+
+ Add(
+ new Episode { ParentIndexNumber = 0, IndexNumber = 2 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ 1);
+
+ // Specials to Episodes
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 2 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 2 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 2 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 2 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsAfterSeasonNumber = 1 },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 3, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsAfterSeasonNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 3, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsAfterSeasonNumber = 1, AirsBeforeEpisodeNumber = 2 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsBeforeSeasonNumber = 1 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 2 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsBeforeSeasonNumber = 1, AirsBeforeEpisodeNumber = 2 },
+ 1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsBeforeSeasonNumber = 1, AirsBeforeEpisodeNumber = 2 },
+ 0);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 3 },
+ new Episode { ParentIndexNumber = 0, IndexNumber = 1, AirsBeforeSeasonNumber = 1, AirsBeforeEpisodeNumber = 2 },
+ 1);
+
+ // Premiere Date
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 12, 0, 0, 0) },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 12, 0, 0, 0) },
+ 0);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 11, 0, 0, 0) },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 12, 0, 0, 0) },
+ -1);
+
+ Add(
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 12, 0, 0, 0) },
+ new Episode { ParentIndexNumber = 1, IndexNumber = 1, PremiereDate = new DateTime(2021, 09, 11, 0, 0, 0) },
+ 1);
+ }
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json
new file mode 100644
index 000000000..0472a3cd0
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json
@@ -0,0 +1 @@
+{"MessageType":"ForceKeepAlive","MessageId":"00000000-0000-0000-0000-000000000000","ServerId":null,"Data":60}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json
new file mode 100644
index 000000000..72f810725
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json
@@ -0,0 +1 @@
+{"MessageType":"KeepAlive","MessageId":"d29ef449-6965-4000
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json
new file mode 100644
index 000000000..62d9099c8
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json
@@ -0,0 +1 @@
+{"MessageType":"ForceKeepAlive","MessageId":"00000000-0000-0000-0000-000000000000","ServerId":null,"Data":60}{"MessageType":"KeepAlive","MessageId":"d29ef449-6965-4000
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json
new file mode 100644
index 000000000..a4ad4ed44
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json
@@ -0,0 +1 @@
+{"FriendlyName":"HDHomeRun DUAL","ModelNumber":"HDHR3-US","Legacy":1,"FirmwareName":"hdhomerun3_atsc","FirmwareVersion":"20200225","DeviceID":"10xxxxx5","TunerCount":2,"BaseURL":"http://10.10.10.100:80"}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json
@@ -0,0 +1 @@
+{}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json
new file mode 100644
index 000000000..851f17bb2
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json
@@ -0,0 +1 @@
+{"FriendlyName":"HDHomeRun PRIME","ModelNumber":"HDHR3-CC","FirmwareName":"hdhomerun3_cablecard","FirmwareVersion":"20160630atest2","DeviceID":"FFFFFFFF","DeviceAuth":"FFFFFFFF","TunerCount":3,"ConditionalAccess":1,"BaseURL":"http://192.168.1.182:80","LineupURL":"http://192.168.1.182:80/lineup.json"}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json
new file mode 100644
index 000000000..4cb5ebc8e
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json
@@ -0,0 +1 @@
+[ { "GuideNumber": "4.1", "GuideName": "WCMH-DT", "HD": 1, "Favorite": 1, "URL": "http://192.168.1.111:5004/auto/v4.1" }, { "GuideNumber": "4.2", "GuideName": "MeTV", "URL": "http://192.168.1.111:5004/auto/v4.2" }, { "GuideNumber": "4.3", "GuideName": "ION TV", "URL": "http://192.168.1.111:5004/auto/v4.3" }, { "GuideNumber": "6.1", "GuideName": "WSYX DT", "HD": 1, "URL": "http://192.168.1.111:5004/auto/v6.1" }, { "GuideNumber": "6.2", "GuideName": "MYTV", "URL": "http://192.168.1.111:5004/auto/v6.2" }, { "GuideNumber": "6.3", "GuideName": "ANTENNA", "URL": "http://192.168.1.111:5004/auto/v6.3" } ]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/headends_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/headends_response.json
new file mode 100644
index 000000000..015afeecc
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/headends_response.json
@@ -0,0 +1 @@
+[{"headend":"CA00053","transport":"Cable","location":"Beverly Hills","lineups":[{"name":"Time Warner Cable - Cable","lineup":"USA-CA00053-DEFAULT","uri":"/20141201/lineups/USA-CA00053-DEFAULT"},{"name":"Time Warner Cable - Digital","lineup":"USA-CA00053-X","uri":"/20141201/lineups/USA-CA00053-X"}]},{"headend":"CA61222","transport":"Cable","location":"Beverly Hills","lineups":[{"name":"Mulholland Estates - Cable","lineup":"USA-CA61222-DEFAULT","uri":"/20141201/lineups/USA-CA61222-DEFAULT"}]},{"headend":"CA66511","transport":"Cable","location":"Los Angeles","lineups":[{"name":"AT&T U-verse TV - Digital","lineup":"USA-CA66511-X","uri":"/20141201/lineups/USA-CA66511-X"}]},{"headend":"CA67309","transport":"Cable","location":"Westchester","lineups":[{"name":"Time Warner Cable Sherman Oaks - Cable","lineup":"USA-CA67309-DEFAULT","uri":"/20141201/lineups/USA-CA67309-DEFAULT"},{"name":"Time Warner Cable Sherman Oaks - Digital","lineup":"USA-CA67309-X","uri":"/20141201/lineups/USA-CA67309-X"}]},{"headend":"CA67310","transport":"Cable","location":"Eagle Rock","lineups":[{"name":"Time Warner Cable City of Los Angeles - Cable","lineup":"USA-CA67310-DEFAULT","uri":"/20141201/lineups/USA-CA67310-DEFAULT"},{"name":"Time Warner Cable City of Los Angeles - Digital","lineup":"USA-CA67310-X","uri":"/20141201/lineups/USA-CA67310-X"}]},{"headend":"DISH803","transport":"Satellite","location":"Los Angeles","lineups":[{"name":"DISH Los Angeles - Satellite","lineup":"USA-DISH803-DEFAULT","uri":"/20141201/lineups/USA-DISH803-DEFAULT"}]},{"headend":"DITV803","transport":"Satellite","location":"Los Angeles","lineups":[{"name":"DIRECTV Los Angeles - Satellite","lineup":"USA-DITV803-DEFAULT","uri":"/20141201/lineups/USA-DITV803-DEFAULT"}]},{"headend":"90210","transport":"Antenna","location":"90210","lineups":[{"name":"Antenna","lineup":"USA-OTA-90210","uri":"/20141201/lineups/USA-OTA-90210"}]}]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineup_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineup_response.json
new file mode 100644
index 000000000..072089470
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineup_response.json
@@ -0,0 +1 @@
+{"map":[{"stationID":"24326","channel":"001","providerCallsign":"BBC ONE South","logicalChannelNumber":"1","matchType":"providerCallsign"},{"stationID":"17154","channel":"002","providerCallsign":"BBC TWO","logicalChannelNumber":"2","matchType":"providerCallsign"}]}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineups_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineups_response.json
new file mode 100644
index 000000000..032a84e59
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/lineups_response.json
@@ -0,0 +1 @@
+{"code":0,"serverID":"20141201.web.1","datetime":"2015-04-17T14:22:17Z","lineups":[{"lineup":"GBR-0001317-DEFAULT","name":"Freeview - Carlton - LWT (Southeast)","transport":"DVB-T","location":"London","uri":"/20141201/lineups/GBR-0001317-DEFAULT"},{"lineup":"USA-IL57303-X","name":"Comcast Waukegan/Lake Forest Area - Digital","transport":"Cable","location":"Lake Forest","uri":"/20141201/lineups/USA-IL57303-X"},{"lineup":"USA-NY67791-X","name":"Verizon Fios Queens - Digital","transport":"Cable","location":"Fresh Meadows","uri":"/20141201/lineups/USA-NY67791-X"},{"lineup":"USA-OTA-60030","name":"Local Over the Air Broadcast","transport":"Antenna","location":"60030","uri":"/20141201/lineups/USA-OTA-60030"},{"lineup":"USA-WI61859-DEFAULT","name":"DELETED LINEUP","isDeleted":true}]}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/metadata_programs_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/metadata_programs_response.json
new file mode 100644
index 000000000..78166f09a
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/metadata_programs_response.json
@@ -0,0 +1 @@
+[{"programID":"SH00712240","data":[{"width":"135","height":"180","uri":"assets/p282288_b_v2_aa.jpg","size":"Sm","aspect":"3x4","category":"Banner-L3","text":"yes","primary":"true","tier":"Series"},{"width":"720","height":"540","uri":"assets/p282288_b_h6_aa.jpg","size":"Lg","aspect":"4x3","category":"Banner-L3","text":"yes","primary":"true","tier":"Series"},{"width":"960","height":"1440","uri":"assets/p282288_b_v8_aa.jpg","size":"Ms","aspect":"2x3","category":"Banner-L3","text":"yes","primary":"true","tier":"Series"},{"width":"180","height":"135","uri":"assets/p282288_b_h5_aa.jpg","size":"Sm","aspect":"4x3","category":"Banner-L3","text":"yes","primary":"true","tier":"Series"}]}]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/programs_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/programs_response.json
new file mode 100644
index 000000000..fe2a94436
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/programs_response.json
@@ -0,0 +1 @@
+[{"programID":"EP000000060003","titles":[{"title120":"'Allo 'Allo!"}],"eventDetails":{"subType":"Series"},"descriptions":{"description1000":[{"descriptionLanguage":"en","description":"A disguised British Intelligence officer is sent to help the airmen."}]},"originalAirDate":"1985-11-04","genres":["Sitcom"],"episodeTitle150":"The Poloceman Cometh","metadata":[{"Gracenote":{"season":2,"episode":3}}],"cast":[{"personId":"383774","nameId":"392649","name":"Gorden Kaye","role":"Actor","billingOrder":"01"},{"personId":"246840","nameId":"250387","name":"Carmen Silvera","role":"Actor","billingOrder":"02"},{"personId":"376955","nameId":"385830","name":"Rose Hill","role":"Actor","billingOrder":"03"},{"personId":"259773","nameId":"263340","name":"Vicki Michelle","role":"Actor","billingOrder":"04"},{"personId":"353113","nameId":"361987","name":"Kirsten Cooke","role":"Actor","billingOrder":"05"},{"personId":"77787","nameId":"77787","name":"Richard Marner","role":"Actor","billingOrder":"06"},{"personId":"230921","nameId":"234193","name":"Guy Siner","role":"Actor","billingOrder":"07"},{"personId":"374934","nameId":"383809","name":"Kim Hartman","role":"Actor","billingOrder":"08"},{"personId":"369151","nameId":"378026","name":"Richard Gibson","role":"Actor","billingOrder":"09"},{"personId":"343690","nameId":"352564","name":"Arthur Bostrom","role":"Actor","billingOrder":"10"},{"personId":"352557","nameId":"361431","name":"John D. Collins","role":"Actor","billingOrder":"11"},{"personId":"605275","nameId":"627734","name":"Nicholas Frankau","role":"Actor","billingOrder":"12"},{"personId":"373394","nameId":"382269","name":"Jack Haig","role":"Actor","billingOrder":"13"}],"crew":[{"personId":"354407","nameId":"363281","name":"David Croft","role":"Director","billingOrder":"01"},{"personId":"354407","nameId":"363281","name":"David Croft","role":"Writer","billingOrder":"02"},{"personId":"105145","nameId":"105145","name":"Jeremy Lloyd","role":"Writer","billingOrder":"03"}],"showType":"Series","hasImageArtwork":true,"md5":"Jo5NKxoo44xRvBCAq8QT2A"},{"programID":"EP000000510142","titles":[{"title120":"A Different World"}],"eventDetails":{"subType":"Series"},"descriptions":{"description1000":[{"descriptionLanguage":"en","description":"Whitley and Dwayne tell new students about their honeymoon in Los Angeles."}]},"originalAirDate":"1992-09-24","genres":["Sitcom"],"episodeTitle150":"Honeymoon in L.A.","metadata":[{"Gracenote":{"season":6,"episode":1}}],"cast":[{"personId":"700","nameId":"700","name":"Jasmine Guy","role":"Actor","billingOrder":"01"},{"personId":"729","nameId":"729","name":"Kadeem Hardison","role":"Actor","billingOrder":"02"},{"personId":"120","nameId":"120","name":"Darryl M. Bell","role":"Actor","billingOrder":"03"},{"personId":"1729","nameId":"1729","name":"Cree Summer","role":"Actor","billingOrder":"04"},{"personId":"217","nameId":"217","name":"Charnele Brown","role":"Actor","billingOrder":"05"},{"personId":"1811","nameId":"1811","name":"Glynn Turman","role":"Actor","billingOrder":"06"},{"personId":"1232","nameId":"1232","name":"Lou Myers","role":"Actor","billingOrder":"07"},{"personId":"1363","nameId":"1363","name":"Jada Pinkett","role":"Guest Star","billingOrder":"08"},{"personId":"222967","nameId":"225536","name":"Ajai Sanders","role":"Guest Star","billingOrder":"09"},{"personId":"181744","nameId":"183292","name":"Karen Malina White","role":"Guest Star","billingOrder":"10"},{"personId":"305017","nameId":"318897","name":"Patrick Y. Malone","role":"Guest Star","billingOrder":"11"},{"personId":"9841","nameId":"9841","name":"Bumper Robinson","role":"Guest Star","billingOrder":"12"},{"personId":"426422","nameId":"435297","name":"Sister Souljah","role":"Guest Star","billingOrder":"13"},{"personId":"25","nameId":"25","name":"Debbie Allen","role":"Guest Star","billingOrder":"14"},{"personId":"668","nameId":"668","name":"Gilbert Gottfried","role":"Guest Star","billingOrder":"15"}],"showType":"Series","hasImageArtwork":true,"md5":"P5kz0QmCeYxIA+yL0H4DWw"}]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_request.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_request.json
new file mode 100644
index 000000000..5ef1bfb1c
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_request.json
@@ -0,0 +1 @@
+[{"stationID":"20454","date":["2015-03-13","2015-03-17"]},{"stationID":"10021","date":["2015-03-12","2015-03-13"]}]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_response.json
new file mode 100644
index 000000000..4a97e5517
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/schedules_response.json
@@ -0,0 +1 @@
+[{"stationID":"20454","programs":[{"programID":"SH005371070000","airDateTime":"2015-03-03T00:00:00Z","duration":1800,"md5":"Sy8HEMBPcuiAx3FBukUhKQ","new":true,"audioProperties":["stereo","cc"],"videoProperties":["hdtv"]},{"programID":"EP000014577244","airDateTime":"2015-03-03T00:30:00Z","duration":1800,"md5":"25DNXVXO192JI7Y9vSW9lQ","new":true,"audioProperties":["stereo","cc"],"videoProperties":["hdtv"]}]}]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_live_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_live_response.json
new file mode 100644
index 000000000..e5fb64a6f
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_live_response.json
@@ -0,0 +1 @@
+{"code":0,"message":"OK","serverID":"AWS-SD-web.1","datetime":"2016-08-23T13:55:25Z","token":"f3fca79989cafe7dead71beefedc812b"}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_offline_response.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_offline_response.json
new file mode 100644
index 000000000..b66a4ed0c
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/SchedulesDirect/token_offline_response.json
@@ -0,0 +1 @@
+{"response":"SERVICE_OFFLINE","code":3000,"serverID":"20141201.web.1","message":"Server offline for maintenance.","datetime":"2015-04-23T00:03:32Z","token":"CAFEDEADBEEFCAFEDEADBEEFCAFEDEADBEEFCAFE"}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/empty.zip b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/empty.zip
new file mode 100644
index 000000000..15628e26b
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/empty.zip
Binary files differ
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
new file mode 100644
index 000000000..b766e668e
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
@@ -0,0 +1,684 @@
+[
+ {
+ "guid": "a4df60c5-6ab4-412a-8f79-2cab93fb2bc5",
+ "name": "Anime",
+ "description": "Manage your anime in Jellyfin. This plugin supports several different metadata providers and options for organizing your collection.\n",
+ "overview": "Manage your anime from Jellyfin",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "10.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_10.0.0.0.zip",
+ "checksum": "93e969adeba1050423fc8817ed3c36f8",
+ "timestamp": "2020-08-17T01:41:13Z"
+ },
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_9.0.0.0.zip",
+ "checksum": "9b1cebff835813e15f414f44b40c41c8",
+ "timestamp": "2020-07-20T01:30:16Z"
+ }
+ ]
+ },
+ {
+ "guid": "70b7b43b-471b-4159-b4be-56750c795499",
+ "name": "Auto Organize",
+ "description": "Automatically organize your media",
+ "overview": "Automatically organize your media",
+ "owner": "jellyfin",
+ "category": "General",
+ "versions": [
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/auto-organize/auto-organize_9.0.0.0.zip",
+ "checksum": "ff29ac3cbe05d208b6af94cd6d9dea39",
+ "timestamp": "2020-12-05T22:31:12Z"
+ },
+ {
+ "version": "8.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/auto-organize/auto-organize_8.0.0.0.zip",
+ "checksum": "460bbb45e556464a8476b18e41c097f5",
+ "timestamp": "2020-07-20T01:30:25Z"
+ }
+ ]
+ },
+ {
+ "guid": "9c4e63f1-031b-4f25-988b-4f7d78a8b53e",
+ "name": "Bookshelf",
+ "description": "Supports several different metadata providers and options for organizing your collection.\n",
+ "overview": "Manage your books",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "5.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/bookshelf/bookshelf_5.0.0.0.zip",
+ "checksum": "2063fb8ab317b8d77b200fde41eb5e1e",
+ "timestamp": "2020-12-05T22:03:13Z"
+ },
+ {
+ "version": "4.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/bookshelf/bookshelf_4.0.0.0.zip",
+ "checksum": "fc9f76c0815d766491e5b0f30ede55ed",
+ "timestamp": "2020-07-20T01:30:33Z"
+ }
+ ]
+ },
+ {
+ "guid": "cfa0f7f4-4155-4d71-849b-d6598dc4c5bb",
+ "name": "Email",
+ "description": "Send SMTP email notifications",
+ "overview": "Send SMTP email notifications",
+ "owner": "jellyfin",
+ "category": "Notifications",
+ "versions": [
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/email/email_9.0.0.0.zip",
+ "checksum": "cfe7afc00f3fbd6d6ab8244d7ff968ce",
+ "timestamp": "2020-12-05T22:20:32Z"
+ },
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/email/email_7.0.0.0.zip",
+ "checksum": "680ca511d8ad84923cb04f024fd8eb19",
+ "timestamp": "2020-07-20T01:30:40Z"
+ }
+ ]
+ },
+ {
+ "guid": "170a157f-ac6c-437a-abdd-ca9c25cebd39",
+ "name": "Fanart",
+ "description": "Scrape poster images for movies, shows, and artists in your library.",
+ "overview": "Scrape poster images from Fanart",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/fanart/fanart_6.0.0.0.zip",
+ "checksum": "ee4360bfcc8722d5a3a54cfe7eef640f",
+ "timestamp": "2020-12-05T22:25:43Z"
+ },
+ {
+ "version": "5.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/fanart/fanart_5.0.0.0.zip",
+ "checksum": "f842f7d65d23f377761c907d40b89647",
+ "timestamp": "2020-07-20T01:30:48Z"
+ }
+ ]
+ },
+ {
+ "guid": "e29621a5-fa9e-4330-982e-ef6e54c0cad2",
+ "name": "Gotify Notification",
+ "description": "You must have a Gotify server to use this plugin!\n",
+ "overview": "Sends notifications to your Gotify server",
+ "owner": "crobibero",
+ "category": "Notifications",
+ "versions": [
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/gotify-notification/gotify-notification_7.0.0.0.zip",
+ "checksum": "7c5ff9e8792c8cdee7e8a2aaeb6cc093",
+ "timestamp": "2020-07-20T01:30:56Z"
+ }
+ ]
+ },
+ {
+ "guid": "a59b5c4b-05a8-488f-bfa8-7a63fffc7639",
+ "name": "IPTV",
+ "description": "Enable IPTV support in Jellyfin",
+ "overview": "Enable IPTV support in Jellyfin",
+ "owner": "jellyfin",
+ "category": "Channel",
+ "versions": [
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/iptv/iptv_6.0.0.0.zip",
+ "checksum": "9cf103bf67a4eda7c3a42d9b235f6447",
+ "timestamp": "2020-07-20T01:31:05Z"
+ }
+ ]
+ },
+ {
+ "guid": "4682DD4C-A675-4F1B-8E7C-79ADF137A8F8",
+ "name": "ISO Mounter",
+ "description": "Mount your ISO files for Jellyfin.\n",
+ "overview": "Mount your ISO files for Jellyfin",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "1.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/iso-mounter/iso-mounter_1.0.0.0.zip",
+ "checksum": "847e5bc7ac34c1bf4dc5b28173170fae",
+ "timestamp": "2020-07-20T01:31:13Z"
+ }
+ ]
+ },
+ {
+ "guid": "771e19d6-5385-4caf-b35c-28a0e865cf63",
+ "name": "Kodi Sync Queue",
+ "description": "This plugin will track all media changes while Kodi clients are offline to decrease sync times.",
+ "overview": "Sync all media changes with Kodi clients",
+ "owner": "jellyfin",
+ "category": "General",
+ "versions": [
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/kodi-sync-queue/kodi-sync-queue_6.0.0.0.zip",
+ "checksum": "787c856c0d2ad2224cdd8b3094cf0329",
+ "timestamp": "2020-12-05T22:10:37Z"
+ },
+ {
+ "version": "5.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/kodi-sync-queue/kodi-sync-queue_5.0.0.0.zip",
+ "checksum": "08285397aecd93ea64a4f15d38b1bd7b",
+ "timestamp": "2020-07-20T01:31:22Z"
+ }
+ ]
+ },
+ {
+ "guid": "958aad66-3784-4d2a-b89a-a7b6fab6e25c",
+ "name": "LDAP Authentication",
+ "description": "Authenticate your Jellyfin users against an LDAP database, and optionally create users who do not yet exist automatically.\nAllows the administrator to customize most aspects of the LDAP authentication process, including customizable search attributes, username attribute, and a search filter for administrative users (set on user creation). The user, via the \"Manual Login\" process, can enter any valid attribute value, which will be mapped back to the specified username attribute automatically as well.\n",
+ "overview": "Authenticate users against an LDAP database",
+ "owner": "jellyfin",
+ "category": "Authentication",
+ "versions": [
+ {
+ "version": "10.0.0.0",
+ "changelog": "Update for 10.7 support\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_10.0.0.0.zip",
+ "checksum": "62e7e1cd3ffae0944c14750a3c90df4f",
+ "timestamp": "2020-12-05T19:48:10Z"
+ },
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_9.0.0.0.zip",
+ "checksum": "7f2f83587a65a43ebf168e4058421463",
+ "timestamp": "2020-07-22T15:42:57Z"
+ },
+ {
+ "version": "8.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_8.0.0.0.zip",
+ "checksum": "8af8cee62717d63577f8b1e710839415",
+ "timestamp": "2020-07-20T01:31:30Z"
+ }
+ ]
+ },
+ {
+ "guid": "9574ac10-bf23-49bc-949f-924f23cfa48f",
+ "name": "NextPVR",
+ "description": "Provides access to live TV, program guide, and recordings from NextPVR.\n",
+ "overview": "Live TV plugin for NextPVR",
+ "owner": "jellyfin",
+ "category": "LiveTV",
+ "versions": [
+ {
+ "version": "5.0.0.0",
+ "changelog": "Updated to use NextPVR API v5, no longer compatable with API v4.\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/nextpvr/nextpvr_5.0.0.0.zip",
+ "checksum": "d70f694d14bf9462ba2b2ebe110068d3",
+ "timestamp": "2020-12-05T22:24:03Z"
+ },
+ {
+ "version": "4.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/nextpvr/nextpvr_4.0.0.0.zip",
+ "checksum": "b15949d895ac5a8c89496581db350478",
+ "timestamp": "2020-07-20T01:31:38Z"
+ }
+ ]
+ },
+ {
+ "guid": "4b9ed42f-5185-48b5-9803-6ff2989014c4",
+ "name": "Open Subtitles",
+ "description": "Download subtitles from the internet to use with your media files.",
+ "overview": "Download subtitles for your media",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "10.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/open-subtitles/open-subtitles_10.0.0.0.zip",
+ "checksum": "ed99d03ec463bf15fca1256a113f57b4",
+ "timestamp": "2020-12-05T21:56:19Z"
+ },
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/open-subtitles/open-subtitles_9.0.0.0.zip",
+ "checksum": "16789b26497cea0509daf6b18c579340",
+ "timestamp": "2020-07-20T01:32:00Z"
+ }
+ ]
+ },
+ {
+ "guid": "5c534381-91a3-43cb-907a-35aa02eb9d2c",
+ "name": "Playback Reporting",
+ "description": "Collect and show user play statistics",
+ "overview": "Collect and show user play statistics",
+ "owner": "jellyfin",
+ "category": "General",
+ "versions": [
+ {
+ "version": "9.0.0.0",
+ "changelog": "Add authentication to plugin endpoints\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_9.0.0.0.zip",
+ "checksum": "ca323b3dcb2cb86cc2e72a7a0f1eee22",
+ "timestamp": "2020-12-05T22:15:48Z"
+ },
+ {
+ "version": "8.0.0.0",
+ "changelog": "Add authentication to plugin endpoints\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_8.0.0.0.zip",
+ "checksum": "58644c505586542ef0b8b65e2f704bd1",
+ "timestamp": "2020-11-18T03:01:51Z"
+ },
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_7.0.0.0.zip",
+ "checksum": "6a361ef33bca97f9155856d02ff47380",
+ "timestamp": "2020-07-20T01:32:09Z"
+ }
+ ]
+ },
+ {
+ "guid": "de228f12-e43e-4bd9-9fc0-2830819c3b92",
+ "name": "Pushbullet",
+ "description": "Get notifications via Pushbullet.\n",
+ "overview": "Pushbullet notification plugin",
+ "owner": "jellyfin",
+ "category": "Notifications",
+ "versions": [
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushbullet/pushbullet_6.0.0.0.zip",
+ "checksum": "248cf3d56644f1d909e75aaddbdfb3a6",
+ "timestamp": "2020-12-06T02:47:53Z"
+ },
+ {
+ "version": "5.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushbullet/pushbullet_5.0.0.0.zip",
+ "checksum": "dabbdd86328b2922a69dfa0c9e1c8343",
+ "timestamp": "2020-07-20T01:32:17Z"
+ }
+ ]
+ },
+ {
+ "guid": "F240D6BE-5743-441B-87F1-A70ECAC42642",
+ "name": "Pushover",
+ "description": "Send messages to a wide range of devices through Pushover.",
+ "overview": "Send notifications via Pushover",
+ "owner": "crobibero",
+ "category": "Notifications",
+ "versions": [
+ {
+ "version": "4.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushover/pushover_4.0.0.0.zip",
+ "checksum": "56a0da16c7e48cc184987737b7e155dd",
+ "timestamp": "2020-07-20T01:32:25Z"
+ }
+ ]
+ },
+ {
+ "guid": "d4312cd9-5c90-4f38-82e8-51da566790e8",
+ "name": "Reports",
+ "description": "Generate reports of your media library",
+ "overview": "Generate reports of your media library",
+ "owner": "jellyfin",
+ "category": "General",
+ "versions": [
+ {
+ "version": "11.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_11.0.0.0.zip",
+ "checksum": "d71bc6a4c008e58ee70ad44c83bfd310",
+ "timestamp": "2020-12-05T22:00:46Z"
+ },
+ {
+ "version": "10.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_10.0.0.0.zip",
+ "checksum": "3917e75839337475b42daf2ba0b5bd7b",
+ "timestamp": "2020-10-19T19:30:41Z"
+ },
+ {
+ "version": "9.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_9.0.0.0.zip",
+ "checksum": "5b5ad8d885616a21e8d1e8eecf5ea979",
+ "timestamp": "2020-10-16T23:52:37Z"
+ }
+ ]
+ },
+ {
+ "guid": "1fc322a1-af2e-49a5-b2eb-a89b4240f700",
+ "name": "ServerWMC",
+ "description": "Provides access to Live TV, Program Guide and Recordings from your Windows MediaCenter Server running ServerWMC. Requires ServerWMC to be installed and running on your Windows MediaCenter machine.\n",
+ "overview": "Jellyfin Live TV plugin for Windows MediaCenter with ServerWMC",
+ "owner": "jellyfin",
+ "category": "LiveTV",
+ "versions": [
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/serverwmc/serverwmc_6.0.0.0.zip",
+ "checksum": "3120af0cea2c1cb8b7cf578d9b4b862c",
+ "timestamp": "2020-12-05T22:28:15Z"
+ },
+ {
+ "version": "5.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/serverwmc/serverwmc_5.0.0.0.zip",
+ "checksum": "dc44b039aa1b66eaf40a44fbf02d37e2",
+ "timestamp": "2020-07-20T01:32:42Z"
+ }
+ ]
+ },
+ {
+ "guid": "94fb77c3-55ad-4c50-bf4e-4e5497467b79",
+ "name": "Slack Notifications",
+ "description": "Get notifications via Slack.\n",
+ "overview": "Get notifications via Slack",
+ "owner": "jellyfin",
+ "category": "Notifications",
+ "versions": [
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/slack-notifications/slack-notifications_7.0.0.0.zip",
+ "checksum": "1d5330a77ce7b2a9ac8e5d58088a012c",
+ "timestamp": "2020-12-05T22:40:02Z"
+ },
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/slack-notifications/slack-notifications_6.0.0.0.zip",
+ "checksum": "ede4cbe064542d1ecccc5823921bee4b",
+ "timestamp": "2020-07-20T01:32:50Z"
+ }
+ ]
+ },
+ {
+ "guid": "bc4aad2e-d3d0-4725-a5e2-fd07949e5b42",
+ "name": "TMDb Box Sets",
+ "description": "Automatically create movie box sets based on TMDb collections",
+ "overview": "Automatically create movie box sets based on TMDb collections",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tmdb-box-sets/tmdb-box-sets_7.0.0.0.zip",
+ "checksum": "1551792e6af4d36f2cead01153c73cf0",
+ "timestamp": "2020-12-05T22:07:21Z"
+ },
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tmdb-box-sets/tmdb-box-sets_6.0.0.0.zip",
+ "checksum": "b92b68a922c5fcbb8f4d47b8601b01b6",
+ "timestamp": "2020-07-20T01:32:58Z"
+ }
+ ]
+ },
+ {
+ "guid": "4fe3201e-d6ae-4f2e-8917-e12bda571281",
+ "name": "Trakt",
+ "description": "Record your watched media with Trakt.\n",
+ "overview": "Record your watched media with Trakt",
+ "owner": "jellyfin",
+ "category": "General",
+ "versions": [
+ {
+ "version": "11.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/trakt/trakt_11.0.0.0.zip",
+ "checksum": "2257ccde1e39114644a27e0966a0bf2d",
+ "timestamp": "2020-12-05T19:56:12Z"
+ },
+ {
+ "version": "10.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/trakt/trakt_10.0.0.0.zip",
+ "checksum": "ab67e6b59ea2e7860a6a3ff7b8452759",
+ "timestamp": "2020-07-20T01:33:06Z"
+ }
+ ]
+ },
+ {
+ "guid": "3fd018e5-5e78-4e58-b280-a0c068febee0",
+ "name": "TVHeadend",
+ "description": "Manage TVHeadend from Jellyfin",
+ "overview": "Manage TVHeadend from Jellyfin",
+ "owner": "jellyfin",
+ "category": "LiveTV",
+ "versions": [
+ {
+ "version": "7.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tvheadend/tvheadend_7.0.0.0.zip",
+ "checksum": "1abbfce737b6962f4b1b2255dc63e932",
+ "timestamp": "2021-01-05T16:20:33Z"
+ },
+ {
+ "version": "6.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tvheadend/tvheadend_6.0.0.0.zip",
+ "checksum": "143c34fd70d7173b8912cc03ce4b517d",
+ "timestamp": "2020-07-20T01:33:15Z"
+ }
+ ]
+ },
+ {
+ "guid": "022a3003-993f-45f1-8565-87d12af2e12a",
+ "name": "InfuseSync",
+ "description": "This plugin will track all media changes while any Infuse clients are offline to decrease sync times when logging back in to your server.",
+ "overview": "Blazing fast indexing for Infuse",
+ "owner": "Firecore LLC",
+ "category": "General",
+ "versions": [
+ {
+ "version": "1.2.4.0",
+ "changelog": "New Playlist support.\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.4/InfuseSync-jellyfin-1.2.4.zip",
+ "checksum": "7adde11b8c8404fd2923f59d98fb1a30",
+ "timestamp": "2020-10-12T08:00:00Z"
+ },
+ {
+ "version": "1.2.1.3",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.3/InfuseSync-jellyfin-1.2.3.zip",
+ "checksum": "d8e2c5fe736a302097bb3bac3d04b1c4",
+ "timestamp": "2020-09-18T12:19:00Z"
+ },
+ {
+ "version": "1.2.1.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.1/InfuseSync-jellyfin-1.2.1.zip",
+ "checksum": "1a853e926cc422f5d79d398d9ae18ee8",
+ "timestamp": "2020-08-21T10:48:00Z"
+ },
+ {
+ "version": "1.2.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.0/InfuseSync-jellyfin-1.2.0.zip",
+ "checksum": "2d3c7859852695a7f05adc6d3fcbc783",
+ "timestamp": "2020-07-20T11:51:00Z"
+ }
+ ]
+ },
+ {
+ "guid": "8119f3c6-cfc2-4d9c-a0ba-028f1d93e526",
+ "name": "Cover Art Archive",
+ "description": "This plugin provides images from the Cover Art Archive https://musicbrainz.org/doc/Cover_Art_Archive and depends on the MusicBrainz metadata provider to know what images belong where\n",
+ "overview": "MusicBrainz Cover Art Archive",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "2.0.0.0",
+ "changelog": "changelog\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/cover-art-archive/cover-art-archive_2.0.0.0.zip",
+ "checksum": "bea8fa4a37b3e7ed74e22266e7597a68",
+ "timestamp": "2020-12-06T02:51:03Z"
+ },
+ {
+ "version": "1.0.0.3",
+ "changelog": "changelog\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/cover-art-archive/cover-art-archive_1.0.0.3.zip",
+ "checksum": "c502a5c54b168810614c1c40709b9598",
+ "timestamp": "2020-08-06T21:21:22Z"
+ }
+ ]
+ },
+ {
+ "guid": "A4A488D0-17A3-4919-8D82-7F3DE4F6B209",
+ "name": "TV Maze",
+ "description": "Get TV metadata from TV Maze\n",
+ "overview": "Get TV metadata from TV Maze",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "5.0.0.0",
+ "changelog": "Get additional image types\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_5.0.0.0.zip",
+ "checksum": "509a85e40b1d1ac36eef45673deaf606",
+ "timestamp": "2020-12-06T02:51:56Z"
+ },
+ {
+ "version": "4.0.0.0",
+ "changelog": "Get additional image types\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_4.0.0.0.zip",
+ "checksum": "58ee9ab3f129151bdfff033ad889ad87",
+ "timestamp": "2020-11-24T14:44:37Z"
+ },
+ {
+ "version": "3.0.0.0",
+ "changelog": "Remove unused dependencies \n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_3.0.0.0.zip",
+ "checksum": "f3b2c70b3e136fb15c917e4420f4fdec",
+ "timestamp": "2020-11-09T14:32:56Z"
+ },
+ {
+ "version": "2.0.0.0",
+ "changelog": "Remove unused dependencies \n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_2.0.0.0.zip",
+ "checksum": "c7662ae8ae52ce8a4e8d685d55f36e80",
+ "timestamp": "2020-11-09T02:33:11Z"
+ },
+ {
+ "version": "1.0.0.0",
+ "changelog": "Initial release.\n",
+ "targetAbi": "10.6.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_1.0.0.0.zip",
+ "checksum": "c90eee48c12f2c07880b4b28e507fd14",
+ "timestamp": "2020-11-08T19:05:32Z"
+ }
+ ]
+ },
+ {
+ "guid": "a677c0da-fac5-4cde-941a-7134223f14c8",
+ "name": "TheTVDB",
+ "description": "Get TV metadata from TheTvdb\n",
+ "overview": "Get TV metadata from TheTvdb",
+ "owner": "jellyfin",
+ "category": "Metadata",
+ "versions": [
+ {
+ "version": "2.0.0.0",
+ "changelog": "Remove from Jellyfin core.\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/thetvdb/thetvdb_2.0.0.0.zip",
+ "checksum": "e46cee334476a1b475e5c553171c4cb6",
+ "timestamp": "2020-12-16T20:03:28Z"
+ },
+ {
+ "version": "1.0.0.0",
+ "changelog": "Remove from Jellyfin core.\n",
+ "targetAbi": "10.7.0.0",
+ "sourceUrl": "https://repo.jellyfin.org/releases/plugin/thetvdb/thetvdb_1.0.0.0.zip",
+ "checksum": "5a3dca5c0db4824d83bfd4e7e2b7bf11",
+ "timestamp": "2020-12-06T02:56:40Z"
+ }
+ ]
+ }
+] \ No newline at end of file
diff --git a/tests/Jellyfin.Server.Implementations.Tests/TypedBaseItem/BaseItemKindTests.cs b/tests/Jellyfin.Server.Implementations.Tests/TypedBaseItem/BaseItemKindTests.cs
new file mode 100644
index 000000000..31f33c682
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/TypedBaseItem/BaseItemKindTests.cs
@@ -0,0 +1,63 @@
+using System;
+using System.Linq;
+using Jellyfin.Data.Enums;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.TypedBaseItem
+{
+ public class BaseItemKindTests
+ {
+ public static TheoryData<Type> BaseItemKind_TestData()
+ {
+ var data = new TheoryData<Type>();
+
+ var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
+ foreach (var assembly in loadedAssemblies)
+ {
+ if (IsProjectAssemblyName(assembly.FullName))
+ {
+ var baseItemTypes = assembly.GetTypes()
+ .Where(targetType => targetType.IsClass
+ && !targetType.IsAbstract
+ && targetType.IsSubclassOf(typeof(MediaBrowser.Controller.Entities.BaseItem)));
+ foreach (var baseItemType in baseItemTypes)
+ {
+ data.Add(baseItemType);
+ }
+ }
+ }
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(BaseItemKind_TestData))]
+ public void EnumParse_GivenValidBaseItemType_ReturnsEnumValue(Type baseItemDescendantType)
+ {
+ var enumValue = Enum.Parse<BaseItemKind>(baseItemDescendantType.Name);
+ Assert.True(Enum.IsDefined(typeof(BaseItemKind), enumValue));
+ }
+
+ [Theory]
+ [MemberData(nameof(BaseItemKind_TestData))]
+ public void GetBaseItemKind_WhenCalledAfterDefaultCtor_DoesNotThrow(Type baseItemDescendantType)
+ {
+ var defaultConstructor = baseItemDescendantType.GetConstructor(Type.EmptyTypes);
+ var instance = (MediaBrowser.Controller.Entities.BaseItem)defaultConstructor!.Invoke(null);
+ var exception = Record.Exception(() => instance.GetBaseItemKind());
+ Assert.Null(exception);
+ }
+
+ private static bool IsProjectAssemblyName(string? name)
+ {
+ if (name == null)
+ {
+ return false;
+ }
+
+ return name.StartsWith("Jellyfin", StringComparison.OrdinalIgnoreCase)
+ || name.StartsWith("Emby", StringComparison.OrdinalIgnoreCase)
+ || name.StartsWith("MediaBrowser", StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
new file mode 100644
index 000000000..09c4bd100
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
@@ -0,0 +1,113 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using AutoFixture;
+using AutoFixture.AutoMoq;
+using Emby.Server.Implementations.Archiving;
+using Emby.Server.Implementations.Updates;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Updates;
+using Moq;
+using Moq.Protected;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Updates
+{
+ public class InstallationManagerTests
+ {
+ private readonly Fixture _fixture;
+ private readonly InstallationManager _installationManager;
+
+ public InstallationManagerTests()
+ {
+ var messageHandler = new Mock<HttpMessageHandler>();
+ messageHandler.Protected()
+ .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
+ .Returns<HttpRequestMessage, CancellationToken>(
+ (m, _) =>
+ {
+ return Task.FromResult(new HttpResponseMessage()
+ {
+ Content = new StreamContent(File.OpenRead("Test Data/Updates/" + m.RequestUri?.Segments[^1]))
+ });
+ });
+
+ var http = new Mock<IHttpClientFactory>();
+ http.Setup(x => x.CreateClient(It.IsAny<string>()))
+ .Returns(new HttpClient(messageHandler.Object));
+ _fixture = new Fixture();
+ _fixture.Customize(new AutoMoqCustomization
+ {
+ ConfigureMembers = true
+ });
+ _fixture.Inject(http);
+ _fixture.Inject<IZipClient>(new ZipClient());
+ _installationManager = _fixture.Create<InstallationManager>();
+ }
+
+ [Fact]
+ public async Task GetPackages_Valid_Success()
+ {
+ PackageInfo[] packages = await _installationManager.GetPackages(
+ "Jellyfin Stable",
+ "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ false);
+
+ Assert.Equal(25, packages.Length);
+ }
+
+ [Fact]
+ public async Task FilterPackages_NameOnly_Success()
+ {
+ PackageInfo[] packages = await _installationManager.GetPackages(
+ "Jellyfin Stable",
+ "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ false);
+
+ packages = _installationManager.FilterPackages(packages, "Anime").ToArray();
+ Assert.Single(packages);
+ }
+
+ [Fact]
+ public async Task FilterPackages_GuidOnly_Success()
+ {
+ PackageInfo[] packages = await _installationManager.GetPackages(
+ "Jellyfin Stable",
+ "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ false);
+
+ packages = _installationManager.FilterPackages(packages, id: new Guid("a4df60c5-6ab4-412a-8f79-2cab93fb2bc5")).ToArray();
+ Assert.Single(packages);
+ }
+
+ [Fact]
+ public async Task InstallPackage_InvalidChecksum_ThrowsInvalidDataException()
+ {
+ var packageInfo = new InstallationInfo()
+ {
+ Name = "Test",
+ SourceUrl = "https://repo.jellyfin.org/releases/plugin/empty/empty.zip",
+ Checksum = "InvalidChecksum"
+ };
+
+ await Assert.ThrowsAsync<InvalidDataException>(() => _installationManager.InstallPackage(packageInfo, CancellationToken.None)).ConfigureAwait(false);
+ }
+
+ [Fact]
+ public async Task InstallPackage_Valid_Success()
+ {
+ var packageInfo = new InstallationInfo()
+ {
+ Name = "Test",
+ SourceUrl = "https://repo.jellyfin.org/releases/plugin/empty/empty.zip",
+ Checksum = "11b5b2f1a9ebc4f66d6ef19018543361"
+ };
+
+ var ex = await Record.ExceptionAsync(() => _installationManager.InstallPackage(packageInfo, CancellationToken.None)).ConfigureAwait(false);
+ Assert.Null(ex);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Users/UserManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Users/UserManagerTests.cs
new file mode 100644
index 000000000..867dda29d
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Users/UserManagerTests.cs
@@ -0,0 +1,28 @@
+using System;
+using Jellyfin.Server.Implementations.Users;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Users
+{
+ public class UserManagerTests
+ {
+ [Theory]
+ [InlineData("this_is_valid")]
+ [InlineData("this is also valid")]
+ [InlineData("0@_-' .")]
+ public void ThrowIfInvalidUsername_WhenValidUsername_DoesNotThrowArgumentException(string username)
+ {
+ var ex = Record.Exception(() => UserManager.ThrowIfInvalidUsername(username));
+ Assert.Null(ex);
+ }
+
+ [Theory]
+ [InlineData(" ")]
+ [InlineData("")]
+ [InlineData("special characters like & $ ? are not allowed")]
+ public void ThrowIfInvalidUsername_WhenInvalidUsername_ThrowsArgumentException(string username)
+ {
+ Assert.Throws<ArgumentException>(() => UserManager.ThrowIfInvalidUsername(username));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs
new file mode 100644
index 000000000..4ea05397d
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StartupDtos;
+using Jellyfin.Api.Models.UserDtos;
+using Jellyfin.Extensions.Json;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public static class AuthHelper
+ {
+ public const string AuthHeaderName = "X-Emby-Authorization";
+ public const string DummyAuthHeader = "MediaBrowser Client=\"Jellyfin.Server Integration Tests\", DeviceId=\"69420\", Device=\"Apple II\", Version=\"10.8.0\"";
+
+ public static async Task<string> CompleteStartupAsync(HttpClient client)
+ {
+ var jsonOptions = JsonDefaults.Options;
+ var userResponse = await client.GetByteArrayAsync("/Startup/User").ConfigureAwait(false);
+ var user = JsonSerializer.Deserialize<StartupUserDto>(userResponse, jsonOptions);
+
+ using var completeResponse = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty<byte>())).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, completeResponse.StatusCode);
+
+ using var content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(
+ new AuthenticateUserByName()
+ {
+ Username = user!.Name,
+ Pw = user.Password,
+ },
+ jsonOptions));
+ content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ content.Headers.Add("X-Emby-Authorization", DummyAuthHeader);
+
+ using var authResponse = await client.PostAsync("/Users/AuthenticateByName", content).ConfigureAwait(false);
+ var auth = await JsonSerializer.DeserializeAsync<AuthenticationResultDto>(
+ await authResponse.Content.ReadAsStreamAsync().ConfigureAwait(false),
+ jsonOptions).ConfigureAwait(false);
+
+ return auth!.AccessToken;
+ }
+
+ public static void AddAuthHeader(this HttpHeaders headers, string accessToken)
+ {
+ headers.Add(AuthHeaderName, DummyAuthHeader + $", Token={accessToken}");
+ }
+
+ private class AuthenticationResultDto
+ {
+ public string AccessToken { get; set; } = string.Empty;
+
+ public string ServerId { get; set; } = string.Empty;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs
new file mode 100644
index 000000000..be89fbc9a
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs
@@ -0,0 +1,30 @@
+using System.Net;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ public sealed class ActivityLogControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private static string? _accessToken;
+
+ public ActivityLogControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task ActivityLog_GetEntries_Ok()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.GetAsync("System/ActivityLog/Entries").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/BaseJellyfinTestController.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/BaseJellyfinTestController.cs
new file mode 100644
index 000000000..9db8689a7
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/BaseJellyfinTestController.cs
@@ -0,0 +1,14 @@
+using Jellyfin.Api;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ /// <summary>
+ /// Base controller for testing infrastructure.
+ /// Automatically ignored in generated openapi spec.
+ /// </summary>
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public class BaseJellyfinTestController : BaseJellyfinApiController
+ {
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs
new file mode 100644
index 000000000..87136dfc8
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs
@@ -0,0 +1,54 @@
+using System.Net;
+using System.Net.Mime;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using MediaBrowser.Model.Branding;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public sealed class BrandingControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+
+ public BrandingControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task GetConfiguration_ReturnsCorrectResponse()
+ {
+ // Arrange
+ var client = _factory.CreateClient();
+
+ // Act
+ var response = await client.GetAsync("/Branding/Configuration");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet);
+ var responseBody = await response.Content.ReadAsStreamAsync();
+ _ = await JsonSerializer.DeserializeAsync<BrandingOptions>(responseBody);
+ }
+
+ [Theory]
+ [InlineData("/Branding/Css")]
+ [InlineData("/Branding/Css.css")]
+ public async Task GetCss_ReturnsCorrectResponse(string url)
+ {
+ // Arrange
+ var client = _factory.CreateClient();
+
+ // Act
+ var response = await client.GetAsync(url);
+
+ // Assert
+ Assert.True(response.IsSuccessStatusCode);
+ Assert.Equal("text/css", response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs
new file mode 100644
index 000000000..827365363
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs
@@ -0,0 +1,86 @@
+using System.IO;
+using System.Net;
+using System.Net.Mime;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models;
+using Jellyfin.Extensions.Json;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ public sealed class DashboardControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options;
+
+ public DashboardControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task GetDashboardConfigurationPage_NonExistingPage_NotFound()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("web/ConfigurationPage?name=ThisPageDoesntExists").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task GetDashboardConfigurationPage_ExistingPage_CorrectPage()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("/web/ConfigurationPage?name=TestPlugin").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Text.Html, response.Content.Headers.ContentType?.MediaType);
+ StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Server.Integration.Tests.TestPage.html")!);
+ Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd());
+ }
+
+ [Fact]
+ public async Task GetDashboardConfigurationPage_BrokenPage_NotFound()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("/web/ConfigurationPage?name=BrokenPage").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task GetConfigurationPages_NoParams_AllConfigurationPages()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("/web/ConfigurationPages").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ var res = await response.Content.ReadAsStreamAsync();
+ _ = await JsonSerializer.DeserializeAsync<ConfigurationPageInfo[]>(res, _jsonOpions);
+ // TODO: check content
+ }
+
+ [Fact]
+ public async Task GetConfigurationPages_True_MainMenuConfigurationPages()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("/web/ConfigurationPages?enableInMainMenu=true").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet);
+
+ var res = await response.Content.ReadAsStreamAsync();
+ var data = await JsonSerializer.DeserializeAsync<ConfigurationPageInfo[]>(res, _jsonOpions);
+ Assert.Empty(data);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/DlnaControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DlnaControllerTests.cs
new file mode 100644
index 000000000..4421ced72
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DlnaControllerTests.cs
@@ -0,0 +1,141 @@
+using System;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Model.Dlna;
+using Xunit;
+using Xunit.Priority;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)]
+ public sealed class DlnaControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private const string NonExistentProfile = "1322f35b8f2c434dad3cc07c9b97dbd1";
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private static string? _accessToken;
+ private static string? _newDeviceProfileId;
+
+ public DlnaControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ [Priority(0)]
+ public async Task GetProfile_DoesNotExist_NotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var getResponse = await client.GetAsync("/Dlna/Profiles/" + NonExistentProfile).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NotFound, getResponse.StatusCode);
+ }
+
+ [Fact]
+ [Priority(0)]
+ public async Task DeleteProfile_DoesNotExist_NotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var getResponse = await client.DeleteAsync("/Dlna/Profiles/" + NonExistentProfile).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NotFound, getResponse.StatusCode);
+ }
+
+ [Fact]
+ [Priority(0)]
+ public async Task UpdateProfile_DoesNotExist_NotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var deviceProfile = new DeviceProfile()
+ {
+ Name = "ThisProfileDoesNotExist"
+ };
+
+ using var content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(deviceProfile, _jsonOptions));
+ content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ using var getResponse = await client.PostAsync("/Dlna/Profiles/" + NonExistentProfile, content).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NotFound, getResponse.StatusCode);
+ }
+
+ [Fact]
+ [Priority(1)]
+ public async Task CreateProfile_Valid_NoContent()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var deviceProfile = new DeviceProfile()
+ {
+ Name = "ThisProfileIsNew"
+ };
+
+ using var content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(deviceProfile, _jsonOptions));
+ content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ using var getResponse = await client.PostAsync("/Dlna/Profiles", content).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, getResponse.StatusCode);
+ }
+
+ [Fact]
+ [Priority(2)]
+ public async Task GetProfileInfos_Valid_ContainsThisProfileIsNew()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var response = await client.GetAsync("/Dlna/ProfileInfos").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet);
+
+ var profiles = await JsonSerializer.DeserializeAsync<DeviceProfileInfo[]>(
+ await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
+ _jsonOptions).ConfigureAwait(false);
+
+ var newProfile = profiles?.FirstOrDefault(x => string.Equals(x.Name, "ThisProfileIsNew", StringComparison.Ordinal));
+ Assert.NotNull(newProfile);
+ _newDeviceProfileId = newProfile!.Id;
+ }
+
+ [Fact]
+ [Priority(3)]
+ public async Task UpdateProfile_Valid_NoContent()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var updatedProfile = new DeviceProfile()
+ {
+ Name = "ThisProfileIsUpdated",
+ Id = _newDeviceProfileId
+ };
+
+ using var content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(updatedProfile, _jsonOptions));
+ content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ using var getResponse = await client.PostAsync("/Dlna/Profiles", content).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, getResponse.StatusCode);
+ }
+
+ [Fact]
+ [Priority(4)]
+ public async Task DeleteProfile_Valid_NoContent()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var getResponse = await client.DeleteAsync("/Dlna/Profiles/" + _newDeviceProfileId).ConfigureAwait(false);
+ Console.WriteLine(await getResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
+ Assert.Equal(HttpStatusCode.NoContent, getResponse.StatusCode);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs
new file mode 100644
index 000000000..1a720c2f6
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs
@@ -0,0 +1,53 @@
+using System.Collections.Generic;
+using System.Linq;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ /// <summary>
+ /// Controller for testing the encoded url.
+ /// </summary>
+ public class EncoderController : BaseJellyfinTestController
+ {
+ /// <summary>
+ /// Tests the url decoding.
+ /// </summary>
+ /// <param name="params">Parameters to echo back in the response.</param>
+ /// <returns>An <see cref="OkResult"/>.</returns>
+ /// <response code="200">Information retrieved.</response>
+ [HttpGet("UrlDecode")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ContentResult TestUrlDecoding([FromQuery] Dictionary<string, string>? @params = null)
+ {
+ return new ContentResult()
+ {
+ Content = (@params != null && @params.Count > 0)
+ ? string.Join("&", @params.Select(x => x.Key + "=" + x.Value))
+ : string.Empty,
+ ContentType = "text/plain; charset=utf-8",
+ StatusCode = 200
+ };
+ }
+
+ /// <summary>
+ /// Tests the url decoding.
+ /// </summary>
+ /// <param name="params">Parameters to echo back in the response.</param>
+ /// <returns>An <see cref="OkResult"/>.</returns>
+ /// <response code="200">Information retrieved.</response>
+ [HttpGet("UrlArrayDecode")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ContentResult TestUrlArrayDecoding([FromQuery] Dictionary<string, string[]>? @params = null)
+ {
+ return new ContentResult()
+ {
+ Content = (@params != null && @params.Count > 0)
+ ? string.Join("&", @params.Select(x => x.Key + "=" + string.Join(',', x.Value)))
+ : string.Empty,
+ ContentType = "text/plain; charset=utf-8",
+ StatusCode = 200
+ };
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaInfoControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaInfoControllerTests.cs
new file mode 100644
index 000000000..34d26680a
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaInfoControllerTests.cs
@@ -0,0 +1,61 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Mime;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ public sealed class MediaInfoControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private static string? _accessToken;
+
+ public MediaInfoControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task BitrateTest_Default_Ok()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.GetAsync("Playback/BitrateTest").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Octet, response.Content.Headers.ContentType?.MediaType);
+ Assert.NotNull(response.Content.Headers.ContentLength);
+ }
+
+ [Theory]
+ [InlineData(102400)]
+ public async Task BitrateTest_WithValidParam_Ok(int size)
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.GetAsync("Playback/BitrateTest?size=" + size.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Octet, response.Content.Headers.ContentType?.MediaType);
+ Assert.NotNull(response.Content.Headers.ContentLength);
+ Assert.InRange(response.Content.Headers.ContentLength!.Value, size, long.MaxValue);
+ }
+
+ [Theory]
+ [InlineData(0)] // Zero
+ [InlineData(-102400)] // Negative value
+ [InlineData(1000000000)] // Too large
+ public async Task BitrateTest_InvalidValue_BadRequest(int size)
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.GetAsync("Playback/BitrateTest?size=" + size.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaStructureControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaStructureControllerTests.cs
new file mode 100644
index 000000000..19d8381ea
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/MediaStructureControllerTests.cs
@@ -0,0 +1,122 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.LibraryStructureDto;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Model.Configuration;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ public sealed class MediaStructureControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private static string? _accessToken;
+
+ public MediaStructureControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task RenameVirtualFolder_WhiteSpaceName_ReturnsBadRequest()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var postContent = new ByteArrayContent(Array.Empty<byte>());
+ var response = await client.PostAsync("Library/VirtualFolders/Name?name=+&newName=test", postContent).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task RenameVirtualFolder_WhiteSpaceNewName_ReturnsBadRequest()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var postContent = new ByteArrayContent(Array.Empty<byte>());
+ var response = await client.PostAsync("Library/VirtualFolders/Name?name=test&newName=+", postContent).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task RenameVirtualFolder_NameDoesntExist_ReturnsNotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var postContent = new ByteArrayContent(Array.Empty<byte>());
+ var response = await client.PostAsync("Library/VirtualFolders/Name?name=doesnt+exist&newName=test", postContent).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task AddMediaPath_PathDoesntExist_ReturnsNotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var data = new MediaPathDto()
+ {
+ Name = "Test",
+ Path = "/this/path/doesnt/exist"
+ };
+
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(data, _jsonOptions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ var response = await client.PostAsync("Library/VirtualFolders/Paths", postContent).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task UpdateMediaPath_WhiteSpaceName_ReturnsBadRequest()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var data = new UpdateMediaPathRequestDto()
+ {
+ Name = " ",
+ PathInfo = new MediaPathInfo("test")
+ };
+
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(data, _jsonOptions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ var response = await client.PostAsync("Library/VirtualFolders/Paths/Update", postContent).ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task RemoveMediaPath_WhiteSpaceName_ReturnsBadRequest()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.DeleteAsync("Library/VirtualFolders/Paths?name=+").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task RemoveMediaPath_PathDoesntExist_ReturnsNotFound()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ var response = await client.DeleteAsync("Library/VirtualFolders/Paths?name=none&path=%2Fthis%2Fpath%2Fdoesnt%2Fexist").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs
new file mode 100644
index 000000000..9c0fc72f6
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs
@@ -0,0 +1,119 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.StartupDtos;
+using Jellyfin.Extensions.Json;
+using Xunit;
+using Xunit.Priority;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)]
+ public sealed class StartupControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+
+ public StartupControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ [Priority(-2)]
+ public async Task Configuration_EditConfig_Success()
+ {
+ var client = _factory.CreateClient();
+
+ var config = new StartupConfigurationDto()
+ {
+ UICulture = "NewCulture",
+ MetadataCountryCode = "be",
+ PreferredMetadataLanguage = "nl"
+ };
+
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(config, _jsonOptions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ using var postResponse = await client.PostAsync("/Startup/Configuration", postContent).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, postResponse.StatusCode);
+
+ using var getResponse = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, getResponse.Content.Headers.ContentType?.MediaType);
+
+ using var responseStream = await getResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ var newConfig = await JsonSerializer.DeserializeAsync<StartupConfigurationDto>(responseStream, _jsonOptions).ConfigureAwait(false);
+ Assert.Equal(config.UICulture, newConfig!.UICulture);
+ Assert.Equal(config.MetadataCountryCode, newConfig.MetadataCountryCode);
+ Assert.Equal(config.PreferredMetadataLanguage, newConfig.PreferredMetadataLanguage);
+ }
+
+ [Fact]
+ [Priority(-2)]
+ public async Task User_DefaultUser_NameWithoutPassword()
+ {
+ var client = _factory.CreateClient();
+
+ using var response = await client.GetAsync("/Startup/User").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+
+ using var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ var user = await JsonSerializer.DeserializeAsync<StartupUserDto>(contentStream, _jsonOptions).ConfigureAwait(false);
+ Assert.NotEmpty(user!.Name);
+ Assert.Null(user.Password);
+ }
+
+ [Fact]
+ [Priority(-1)]
+ public async Task User_EditUser_Success()
+ {
+ var client = _factory.CreateClient();
+
+ var user = new StartupUserDto()
+ {
+ Name = "NewName",
+ Password = "NewPassword"
+ };
+
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ var postResponse = await client.PostAsync("/Startup/User", postContent).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, postResponse.StatusCode);
+
+ var getResponse = await client.GetAsync("/Startup/User").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, getResponse.Content.Headers.ContentType?.MediaType);
+
+ var contentStream = await getResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ var newUser = await JsonSerializer.DeserializeAsync<StartupUserDto>(contentStream, _jsonOptions).ConfigureAwait(false);
+ Assert.Equal(user.Name, newUser!.Name);
+ Assert.NotEmpty(newUser.Password);
+ Assert.NotEqual(user.Password, newUser.Password);
+ }
+
+ [Fact]
+ [Priority(0)]
+ public async Task CompleteWizard_Success()
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty<byte>())).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
+ }
+
+ [Fact]
+ [Priority(1)]
+ public async Task GetFirstUser_CompleteWizard_Unauthorized()
+ {
+ var client = _factory.CreateClient();
+
+ using var response = await client.GetAsync("/Startup/User").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs
new file mode 100644
index 000000000..8866ab53c
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs
@@ -0,0 +1,170 @@
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mime;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.UserDtos;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Model.Dto;
+using Xunit;
+using Xunit.Priority;
+
+namespace Jellyfin.Server.Integration.Tests.Controllers
+{
+ [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)]
+ public sealed class UserControllerTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private const string TestUsername = "testUser01";
+
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options;
+ private static string? _accessToken;
+ private static Guid _testUserId = Guid.Empty;
+
+ public UserControllerTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ private Task<HttpResponseMessage> CreateUserByName(HttpClient httpClient, CreateUserByName request)
+ {
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(request, _jsonOpions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ return httpClient.PostAsync("Users/New", postContent);
+ }
+
+ private Task<HttpResponseMessage> UpdateUserPassword(HttpClient httpClient, Guid userId, UpdateUserPassword request)
+ {
+ using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(request, _jsonOpions));
+ postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
+ return httpClient.PostAsync("Users/" + userId.ToString("N", CultureInfo.InvariantCulture) + "/Password", postContent);
+ }
+
+ [Fact]
+ [Priority(-1)]
+ public async Task GetPublicUsers_Valid_Success()
+ {
+ var client = _factory.CreateClient();
+
+ using var response = await client.GetAsync("Users/Public").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var users = await JsonSerializer.DeserializeAsync<UserDto[]>(
+ await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false);
+ // User are hidden by default
+ Assert.Empty(users);
+ }
+
+ [Fact]
+ [Priority(-1)]
+ public async Task GetUsers_Valid_Success()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false));
+
+ using var response = await client.GetAsync("Users").ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var users = await JsonSerializer.DeserializeAsync<UserDto[]>(
+ await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false);
+ Assert.Single(users);
+ Assert.False(users![0].HasConfiguredPassword);
+ }
+
+ [Fact]
+ [Priority(0)]
+ public async Task New_Valid_Success()
+ {
+ var client = _factory.CreateClient();
+
+ // access token can't be null here as the previous test populated it
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken!);
+
+ var createRequest = new CreateUserByName()
+ {
+ Name = TestUsername
+ };
+
+ using var response = await CreateUserByName(client, createRequest).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var user = await JsonSerializer.DeserializeAsync<UserDto>(
+ await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false);
+ Assert.Equal(TestUsername, user!.Name);
+ Assert.False(user.HasPassword);
+ Assert.False(user.HasConfiguredPassword);
+
+ _testUserId = user.Id;
+
+ Console.WriteLine(user.Id.ToString("N", CultureInfo.InvariantCulture));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("‼️")]
+ [Priority(0)]
+ public async Task New_Invalid_Fail(string? username)
+ {
+ var client = _factory.CreateClient();
+
+ // access token can't be null here as the previous test populated it
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken!);
+
+ var createRequest = new CreateUserByName()
+ {
+ Name = username
+ };
+
+ using var response = await CreateUserByName(client, createRequest).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ [Priority(1)]
+ public async Task UpdateUserPassword_Valid_Success()
+ {
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken!);
+
+ var createRequest = new UpdateUserPassword()
+ {
+ NewPw = "4randomPa$$word"
+ };
+
+ using var response = await UpdateUserPassword(client, _testUserId, createRequest).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
+
+ var users = await JsonSerializer.DeserializeAsync<UserDto[]>(
+ await client.GetStreamAsync("Users").ConfigureAwait(false), _jsonOpions).ConfigureAwait(false);
+ var user = users!.First(x => x.Id == _testUserId);
+ Assert.True(user.HasPassword);
+ Assert.True(user.HasConfiguredPassword);
+ }
+
+ [Fact]
+ [Priority(2)]
+ public async Task UpdateUserPassword_Empty_RemoveSetPassword()
+ {
+ var client = _factory.CreateClient();
+
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken!);
+
+ var createRequest = new UpdateUserPassword()
+ {
+ CurrentPw = "4randomPa$$word",
+ };
+
+ using var response = await UpdateUserPassword(client, _testUserId, createRequest).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
+
+ var users = await JsonSerializer.DeserializeAsync<UserDto[]>(
+ await client.GetStreamAsync("Users").ConfigureAwait(false), _jsonOpions).ConfigureAwait(false);
+ var user = users!.First(x => x.Id == _testUserId);
+ Assert.False(user.HasPassword);
+ Assert.False(user.HasConfiguredPassword);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs
new file mode 100644
index 000000000..2361e4aa4
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs
@@ -0,0 +1,49 @@
+using System.Net;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ /// <summary>
+ /// Defines the test for encoded querystrings in the url.
+ /// </summary>
+ public class EncodedQueryStringTest : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+
+ public EncodedQueryStringTest(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Theory]
+ [InlineData("a=1&b=2&c=3", "a=1&b=2&c=3")] // won't be processed as there is more than 1.
+ [InlineData("a=1", "a=1")] // won't be processed as it has a value
+ [InlineData("a%3D1%26b%3D2%26c%3D3", "a=1&b=2&c=3")] // will be processed.
+ [InlineData("a=b&a=c", "a=b")]
+ [InlineData("a%3D1", "a=1")]
+ [InlineData("a%3Db%26a%3Dc", "a=b")]
+ public async Task Ensure_Decoding_Of_Urls_Is_Working(string sourceUrl, string unencodedUrl)
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("Encoder/UrlDecode?" + sourceUrl).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string reply = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ Assert.Equal(unencodedUrl, reply);
+ }
+
+ [Theory]
+ [InlineData("a=b&a=c", "a=b,c")]
+ [InlineData("a%3Db%26a%3Dc", "a=b,c")]
+ public async Task Ensure_Array_Decoding_Of_Urls_Is_Working(string sourceUrl, string unencodedUrl)
+ {
+ var client = _factory.CreateClient();
+
+ var response = await client.GetAsync("Encoder/UrlArrayDecode?" + sourceUrl).ConfigureAwait(false);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string reply = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ Assert.Equal(unencodedUrl, reply);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj
new file mode 100644
index 000000000..889220d86
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj
@@ -0,0 +1,44 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="Xunit.Priority" Version="1.1.6" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <!-- Don't run tests in parallel -->
+ <None Update="xunit.runner.json">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../Jellyfin.Server/Jellyfin.Server.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="TestPage.html" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs
new file mode 100644
index 000000000..976e19d46
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Concurrent;
+using System.IO;
+using System.Threading;
+using Emby.Server.Implementations;
+using Emby.Server.Implementations.IO;
+using MediaBrowser.Common;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Serilog.Extensions.Logging;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ /// <summary>
+ /// Factory for bootstrapping the Jellyfin application in memory for functional end to end tests.
+ /// </summary>
+ public class JellyfinApplicationFactory : WebApplicationFactory<Startup>
+ {
+ private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
+ private readonly ConcurrentBag<IDisposable> _disposableComponents = new ConcurrentBag<IDisposable>();
+
+ /// <summary>
+ /// Initializes static members of the <see cref="JellyfinApplicationFactory"/> class.
+ /// </summary>
+ static JellyfinApplicationFactory()
+ {
+ // Perform static initialization that only needs to happen once per test-run
+ Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
+ Program.PerformStaticInitialization();
+ }
+
+ /// <inheritdoc/>
+ protected override IWebHostBuilder CreateWebHostBuilder()
+ {
+ return new WebHostBuilder();
+ }
+
+ /// <inheritdoc/>
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ // Specify the startup command line options
+ var commandLineOpts = new StartupOptions();
+
+ // Use a temporary directory for the application paths
+ var webHostPathRoot = Path.Combine(_testPathRoot, "test-host-" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
+ Directory.CreateDirectory(Path.Combine(webHostPathRoot, "logs"));
+ Directory.CreateDirectory(Path.Combine(webHostPathRoot, "config"));
+ Directory.CreateDirectory(Path.Combine(webHostPathRoot, "cache"));
+ Directory.CreateDirectory(Path.Combine(webHostPathRoot, "jellyfin-web"));
+ var appPaths = new ServerApplicationPaths(
+ webHostPathRoot,
+ Path.Combine(webHostPathRoot, "logs"),
+ Path.Combine(webHostPathRoot, "config"),
+ Path.Combine(webHostPathRoot, "cache"),
+ Path.Combine(webHostPathRoot, "jellyfin-web"));
+
+ // Create the logging config file
+ // TODO: We shouldn't need to do this since we are only logging to console
+ Program.InitLoggingConfigFile(appPaths).GetAwaiter().GetResult();
+
+ // Create a copy of the application configuration to use for startup
+ var startupConfig = Program.CreateAppConfiguration(commandLineOpts, appPaths);
+
+ ILoggerFactory loggerFactory = new SerilogLoggerFactory();
+ var serviceCollection = new ServiceCollection();
+ _disposableComponents.Add(loggerFactory);
+
+ // Create the app host and initialize it
+ var appHost = new TestAppHost(
+ appPaths,
+ loggerFactory,
+ commandLineOpts,
+ new ConfigurationBuilder().Build(),
+ new ManagedFileSystem(loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
+ serviceCollection);
+ _disposableComponents.Add(appHost);
+ appHost.Init();
+
+ // Configure the web host builder
+ Program.ConfigureWebHostBuilder(builder, appHost, serviceCollection, commandLineOpts, startupConfig, appPaths);
+ }
+
+ /// <inheritdoc/>
+ protected override TestServer CreateServer(IWebHostBuilder builder)
+ {
+ // Create the test server using the base implementation
+ var testServer = base.CreateServer(builder);
+
+ // Finish initializing the app host
+ var appHost = (TestAppHost)testServer.Services.GetRequiredService<IApplicationHost>();
+ appHost.ServiceProvider = testServer.Services;
+ appHost.InitializeServices().GetAwaiter().GetResult();
+ appHost.RunStartupTasksAsync(CancellationToken.None).GetAwaiter().GetResult();
+
+ return testServer;
+ }
+
+ /// <inheritdoc/>
+ protected override void Dispose(bool disposing)
+ {
+ foreach (var disposable in _disposableComponents)
+ {
+ disposable.Dispose();
+ }
+
+ _disposableComponents.Clear();
+
+ base.Dispose(disposing);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/Middleware/RobotsRedirectionMiddlewareTests.cs b/tests/Jellyfin.Server.Integration.Tests/Middleware/RobotsRedirectionMiddlewareTests.cs
new file mode 100644
index 000000000..8c49a2e2b
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/Middleware/RobotsRedirectionMiddlewareTests.cs
@@ -0,0 +1,32 @@
+using System.Net;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests.Middleware
+{
+ public sealed class RobotsRedirectionMiddlewareTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+
+ public RobotsRedirectionMiddlewareTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task RobotsDotTxtRedirects()
+ {
+ var client = _factory.CreateClient(
+ new WebApplicationFactoryClientOptions()
+ {
+ AllowAutoRedirect = false
+ });
+
+ var response = await client.GetAsync("robots.txt").ConfigureAwait(false);
+
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("web/robots.txt", response.Headers.Location?.ToString());
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs
new file mode 100644
index 000000000..0ade345a1
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs
@@ -0,0 +1,40 @@
+using System.IO;
+using System.Reflection;
+using System.Threading.Tasks;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public sealed class OpenApiSpecTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+ private readonly ITestOutputHelper _outputHelper;
+
+ public OpenApiSpecTests(JellyfinApplicationFactory factory, ITestOutputHelper outputHelper)
+ {
+ _factory = factory;
+ _outputHelper = outputHelper;
+ }
+
+ [Fact]
+ public async Task GetSpec_ReturnsCorrectResponse()
+ {
+ // Arrange
+ var client = _factory.CreateClient();
+
+ // Act
+ var response = await client.GetAsync("/api-docs/openapi.json");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString());
+
+ // Write out for publishing
+ var responseBody = await response.Content.ReadAsStringAsync();
+ string outputPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".", "openapi.json"));
+ _outputHelper.WriteLine("Writing OpenAPI Spec JSON to '{0}'.", outputPath);
+ File.WriteAllText(outputPath, responseBody);
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs
new file mode 100644
index 000000000..0a463cfa3
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs
@@ -0,0 +1,54 @@
+using System.Collections.Generic;
+using System.Reflection;
+using Emby.Server.Implementations;
+using MediaBrowser.Controller;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ /// <summary>
+ /// Implementation of the abstract <see cref="ApplicationHost" /> class.
+ /// </summary>
+ public class TestAppHost : CoreAppHost
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestAppHost" /> class.
+ /// </summary>
+ /// <param name="applicationPaths">The <see cref="ServerApplicationPaths" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="loggerFactory">The <see cref="ILoggerFactory" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="options">The <see cref="StartupOptions" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="startup">The <see cref="IConfiguration" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="fileSystem">The <see cref="IFileSystem" /> to be used by the <see cref="CoreAppHost" />.</param>
+ /// <param name="collection">The <see cref="IServiceCollection"/> to be used by the <see cref="CoreAppHost"/>.</param>
+ public TestAppHost(
+ IServerApplicationPaths applicationPaths,
+ ILoggerFactory loggerFactory,
+ IStartupOptions options,
+ IConfiguration startup,
+ IFileSystem fileSystem,
+ IServiceCollection collection)
+ : base(
+ applicationPaths,
+ loggerFactory,
+ options,
+ startup,
+ fileSystem,
+ collection)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override IEnumerable<Assembly> GetAssembliesWithPartsInternal()
+ {
+ foreach (var a in base.GetAssembliesWithPartsInternal())
+ {
+ yield return a;
+ }
+
+ yield return typeof(TestPlugin).Assembly;
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/TestPage.html b/tests/Jellyfin.Server.Integration.Tests/TestPage.html
new file mode 100644
index 000000000..8037af8a6
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/TestPage.html
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>TestPlugin</title>
+</head>
+<body>
+ <h1>This is a Test Page.</h1>
+</body>
+</html>
diff --git a/tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs b/tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs
new file mode 100644
index 000000000..1d67ac487
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs
@@ -0,0 +1,43 @@
+#pragma warning disable CS1591
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public class TestPlugin : BasePlugin<BasePluginConfiguration>, IHasWebPages
+ {
+ public TestPlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ public static TestPlugin? Instance { get; private set; }
+
+ public override Guid Id => new Guid("2d350a13-0bf7-4b61-859c-d5e601b5facf");
+
+ public override string Name => nameof(TestPlugin);
+
+ public override string Description => "Server test Plugin.";
+
+ public IEnumerable<PluginPageInfo> GetPages()
+ {
+ yield return new PluginPageInfo
+ {
+ Name = Name,
+ EmbeddedResourcePath = GetType().Namespace + ".TestPage.html"
+ };
+
+ yield return new PluginPageInfo
+ {
+ Name = "BrokenPage",
+ EmbeddedResourcePath = GetType().Namespace + ".foobar"
+ };
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs b/tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs
new file mode 100644
index 000000000..ac10c4784
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs
@@ -0,0 +1,27 @@
+#pragma warning disable CS1591
+
+using System;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Serialization;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public class TestPluginWithoutPages : BasePlugin<BasePluginConfiguration>
+ {
+ public TestPluginWithoutPages(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
+ : base(applicationPaths, xmlSerializer)
+ {
+ Instance = this;
+ }
+
+ public static TestPluginWithoutPages? Instance { get; private set; }
+
+ public override Guid Id => new Guid("ae95cbe6-bd3d-4d73-8596-490db334611e");
+
+ public override string Name => nameof(TestPluginWithoutPages);
+
+ public override string Description => "Server test Plugin without web pages.";
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs b/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs
new file mode 100644
index 000000000..ffdc04eba
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Jellyfin.Server.Integration.Tests
+{
+ public sealed class WebSocketTests : IClassFixture<JellyfinApplicationFactory>
+ {
+ private readonly JellyfinApplicationFactory _factory;
+
+ public WebSocketTests(JellyfinApplicationFactory factory)
+ {
+ _factory = factory;
+ }
+
+ [Fact]
+ public async Task WebSocket_Unauthenticated_ThrowsInvalidOperationException()
+ {
+ var server = _factory.Server;
+ var client = server.CreateWebSocketClient();
+
+ await Assert.ThrowsAsync<InvalidOperationException>(
+ () => client.ConnectAsync(
+ new UriBuilder(server.BaseAddress)
+ {
+ Scheme = "ws",
+ Path = "websocket"
+ }.Uri, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json b/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json
new file mode 100644
index 000000000..809e880c7
--- /dev/null
+++ b/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json
@@ -0,0 +1,4 @@
+{
+ "parallelizeAssembly": false,
+ "parallelizeTestCollections": false
+}
diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj
new file mode 100644
index 000000000..3daa45e56
--- /dev/null
+++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj
@@ -0,0 +1,33 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="AutoFixture" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
+ <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../Jellyfin.Server/Jellyfin.Server.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
new file mode 100644
index 000000000..a1bdfa31b
--- /dev/null
+++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Linq;
+using System.Net;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
+using Jellyfin.Server.Extensions;
+using MediaBrowser.Common.Configuration;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.HttpOverrides;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Server.Tests
+{
+ public class ParseNetworkTests
+ {
+ public static TheoryData<bool, bool, string[], IPAddress[], IPNetwork[]> TestNetworks_TestData()
+ {
+ var data = new TheoryData<bool, bool, string[], IPAddress[], IPNetwork[]>();
+ data.Add(
+ true,
+ true,
+ new string[] { "192.168.t", "127.0.0.1", "1234.1232.12.1234" },
+ new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
+ Array.Empty<IPNetwork>());
+
+ data.Add(
+ true,
+ false,
+ new string[] { "192.168.x", "127.0.0.1", "1234.1232.12.1234" },
+ new IPAddress[] { IPAddress.Loopback },
+ Array.Empty<IPNetwork>());
+
+ data.Add(
+ true,
+ true,
+ new string[] { "::1" },
+ Array.Empty<IPAddress>(),
+ new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
+
+ data.Add(
+ false,
+ false,
+ new string[] { "localhost" },
+ Array.Empty<IPAddress>(),
+ Array.Empty<IPNetwork>());
+
+ data.Add(
+ true,
+ false,
+ new string[] { "localhost" },
+ new IPAddress[] { IPAddress.Loopback },
+ Array.Empty<IPNetwork>());
+
+ data.Add(
+ false,
+ true,
+ new string[] { "localhost" },
+ Array.Empty<IPAddress>(),
+ new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
+
+ data.Add(
+ true,
+ true,
+ new string[] { "localhost" },
+ new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
+ new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(TestNetworks_TestData))]
+ public void TestNetworks(bool ip4, bool ip6, string[] hostList, IPAddress[] knownProxies, IPNetwork[] knownNetworks)
+ {
+ using var nm = CreateNetworkManager();
+
+ var settings = new NetworkConfiguration
+ {
+ EnableIPV4 = ip4,
+ EnableIPV6 = ip6
+ };
+
+ ForwardedHeadersOptions options = new ForwardedHeadersOptions();
+
+ // Need this here as ::1 and 127.0.0.1 are in them by default.
+ options.KnownProxies.Clear();
+ options.KnownNetworks.Clear();
+
+ ApiServiceCollectionExtensions.AddProxyAddresses(settings, hostList, options);
+
+ Assert.Equal(knownProxies.Length, options.KnownProxies.Count);
+ foreach (var item in knownProxies)
+ {
+ Assert.True(options.KnownProxies.Contains(item));
+ }
+
+ Assert.Equal(knownNetworks.Length, options.KnownNetworks.Count);
+ foreach (var item in knownNetworks)
+ {
+ Assert.NotNull(options.KnownNetworks.FirstOrDefault(x => x.Prefix.Equals(item.Prefix) && x.PrefixLength == item.PrefixLength));
+ }
+ }
+
+ private static IConfigurationManager GetMockConfig(NetworkConfiguration conf)
+ {
+ var configManager = new Mock<IConfigurationManager>
+ {
+ CallBase = true
+ };
+ configManager.Setup(x => x.GetConfiguration(It.IsAny<string>())).Returns(conf);
+ return configManager.Object;
+ }
+
+ private static NetworkManager CreateNetworkManager()
+ {
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ };
+
+ return new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Tests/UrlDecodeQueryFeatureTests.cs b/tests/Jellyfin.Server.Tests/UrlDecodeQueryFeatureTests.cs
new file mode 100644
index 000000000..d15c9d6f5
--- /dev/null
+++ b/tests/Jellyfin.Server.Tests/UrlDecodeQueryFeatureTests.cs
@@ -0,0 +1,28 @@
+using System.Collections.Generic;
+using System.Linq;
+using Jellyfin.Server.Middleware;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
+using Microsoft.Extensions.Primitives;
+using Xunit;
+
+namespace Jellyfin.Server.Tests
+{
+ public static class UrlDecodeQueryFeatureTests
+ {
+ [Theory]
+ [InlineData("e0a72cb2a2c7", "e0a72cb2a2c7")] // isn't encoded
+ public static void EmptyValueTest(string query, string key)
+ {
+ var dict = new Dictionary<string, StringValues>
+ {
+ { query, StringValues.Empty }
+ };
+ var test = new UrlDecodeQueryFeature(new QueryFeature(new QueryCollection(dict)));
+ Assert.Single(test.Query);
+ var (k, v) = test.Query.First();
+ Assert.Equal(key, k);
+ Assert.Empty(v);
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj
new file mode 100644
index 000000000..edf9e0fef
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj
@@ -0,0 +1,35 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net6.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <None Include="Test Data\**\*.*">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
+ <PackageReference Include="Moq" Version="4.16.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+ <PackageReference Include="coverlet.collector" Version="3.1.0" />
+ </ItemGroup>
+
+ <!-- Code Analyzers -->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="../../MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj" />
+ <ProjectReference Include="../../MediaBrowser.Providers/MediaBrowser.Providers.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Location/MovieNfoLocationTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Location/MovieNfoLocationTests.cs
new file mode 100644
index 000000000..8019e0ab3
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Location/MovieNfoLocationTests.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Linq;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.XbmcMetadata.Savers;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Location
+{
+ public class MovieNfoLocationTests
+ {
+ [Fact]
+ public static void Movie_MixedFolder_Success()
+ {
+ var movie = new Movie() { Path = "/media/movies/Avengers Endgame.mp4", IsInMixedFolder = true };
+
+ var paths = MovieNfoSaver.GetMovieSavePaths(new ItemInfo(movie)).ToArray();
+ Assert.Single(paths);
+ Assert.Contains("/media/movies/Avengers Endgame.nfo", paths);
+ }
+
+ [Fact]
+ public static void Movie_SeparateFolder_Success()
+ {
+ var movie = new Movie() { Path = "/media/movies/Avengers Endgame/Avengers Endgame.mp4" };
+ var path1 = "/media/movies/Avengers Endgame/Avengers Endgame.nfo";
+ var path2 = "/media/movies/Avengers Endgame/movie.nfo";
+
+ // uses ContainingFolderPath which uses Operating system specific paths
+ if (OperatingSystem.IsWindows())
+ {
+ movie.Path = movie.Path.Replace('/', '\\');
+ path1 = path1.Replace('/', '\\');
+ path2 = path2.Replace('/', '\\');
+ }
+
+ var paths = MovieNfoSaver.GetMovieSavePaths(new ItemInfo(movie)).ToArray();
+ Assert.Equal(2, paths.Length);
+ Assert.Contains(path1, paths);
+ Assert.Contains(path2, paths);
+ }
+
+ [Fact]
+ public void Movie_DVD_Success()
+ {
+ var movie = new Movie() { Path = "/media/movies/Avengers Endgame", VideoType = VideoType.Dvd };
+ var path1 = "/media/movies/Avengers Endgame/Avengers Endgame.nfo";
+ var path2 = "/media/movies/Avengers Endgame/VIDEO_TS/VIDEO_TS.nfo";
+
+ // uses ContainingFolderPath which uses Operating system specific paths
+ if (OperatingSystem.IsWindows())
+ {
+ movie.Path = movie.Path.Replace('/', '\\');
+ path1 = path1.Replace('/', '\\');
+ path2 = path2.Replace('/', '\\');
+ }
+
+ var paths = MovieNfoSaver.GetMovieSavePaths(new ItemInfo(movie)).ToArray();
+ Assert.Equal(2, paths.Length);
+ Assert.Contains(path1, paths);
+ Assert.Contains(path2, paths);
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs
new file mode 100644
index 000000000..3e726f23d
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs
@@ -0,0 +1,144 @@
+using System;
+using System.Linq;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Movies;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class EpisodeNfoProviderTests
+ {
+ private readonly EpisodeNfoParser _parser;
+
+ public EpisodeNfoProviderTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+
+ var imdbExternalId = new ImdbExternalId();
+ var externalIdInfo = new ExternalIdInfo(imdbExternalId.ProviderName, imdbExternalId.Key, imdbExternalId.Type, imdbExternalId.UrlFormatString);
+
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(new[] { externalIdInfo });
+
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new EpisodeNfoParser(
+ new NullLogger<EpisodeNfoParser>(),
+ config.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<Episode>()
+ {
+ Item = new Episode()
+ };
+
+ _parser.Fetch(result, "Test Data/The Bone Orchard.nfo", CancellationToken.None);
+
+ var item = result.Item;
+ Assert.Equal("The Bone Orchard", item.Name);
+ Assert.Equal("American Gods", item.SeriesName);
+ Assert.Equal(1, item.IndexNumber);
+ Assert.Equal(1, item.ParentIndexNumber);
+ Assert.Equal("When Shadow Moon is released from prison early after the death of his wife, he meets Mr. Wednesday and is recruited as his bodyguard. Shadow discovers that this may be more than he bargained for.", item.Overview);
+ Assert.Equal(0, item.RunTimeTicks);
+ Assert.Equal("16", item.OfficialRating);
+ Assert.Contains("Drama", item.Genres);
+ Assert.Contains("Mystery", item.Genres);
+ Assert.Contains("Sci-Fi & Fantasy", item.Genres);
+ Assert.Equal(new DateTime(2017, 4, 30), item.PremiereDate);
+ Assert.Equal(2017, item.ProductionYear);
+ Assert.Single(item.Studios);
+ Assert.Contains("Starz", item.Studios);
+ Assert.Equal(1, item.IndexNumberEnd);
+ Assert.Equal(2, item.AirsAfterSeasonNumber);
+ Assert.Equal(3, item.AirsBeforeSeasonNumber);
+ Assert.Equal(1, item.AirsBeforeEpisodeNumber);
+ Assert.Equal("tt5017734", item.ProviderIds[MetadataProvider.Imdb.ToString()]);
+ Assert.Equal("1276153", item.ProviderIds[MetadataProvider.Tmdb.ToString()]);
+
+ // Credits
+ var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray();
+ Assert.Equal(2, writers.Length);
+ Assert.Contains("Bryan Fuller", writers.Select(x => x.Name));
+ Assert.Contains("Michael Green", writers.Select(x => x.Name));
+
+ // Direcotrs
+ var directors = result.People.Where(x => x.Type == PersonType.Director).ToArray();
+ Assert.Single(directors);
+ Assert.Contains("David Slade", directors.Select(x => x.Name));
+
+ // Actors
+ var actors = result.People.Where(x => x.Type == PersonType.Actor).ToArray();
+ Assert.Equal(11, actors.Length);
+ // Only test one actor
+ var shadow = actors.FirstOrDefault(x => x.Role.Equals("Shadow Moon", StringComparison.Ordinal));
+ Assert.NotNull(shadow);
+ Assert.Equal("Ricky Whittle", shadow!.Name);
+ Assert.Equal(0, shadow!.SortOrder);
+ Assert.Equal("http://image.tmdb.org/t/p/original/cjeDbVfBp6Qvb3C74Dfy7BKDTQN.jpg", shadow!.ImageUrl);
+
+ Assert.Equal(new DateTime(2017, 10, 7, 14, 25, 47), item.DateCreated);
+ }
+
+ [Fact]
+ public void Fetch_Valid_MultiEpisode_Success()
+ {
+ var result = new MetadataResult<Episode>()
+ {
+ Item = new Episode()
+ };
+
+ _parser.Fetch(result, "Test Data/Rising.nfo", CancellationToken.None);
+
+ var item = result.Item;
+ Assert.Equal("Rising (1)", item.Name);
+ Assert.Equal(1, item.IndexNumber);
+ Assert.Equal(2, item.IndexNumberEnd);
+ Assert.Equal(1, item.ParentIndexNumber);
+ Assert.Equal("A new Stargate team embarks on a dangerous mission to a distant galaxy, where they discover a mythical lost city -- and a deadly new enemy.", item.Overview);
+ Assert.Equal(new DateTime(2004, 7, 16), item.PremiereDate);
+ Assert.Equal(2004, item.ProductionYear);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Episode>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/The Bone Orchard.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Episode>()
+ {
+ Item = new Episode()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs
new file mode 100644
index 000000000..7ea45d14d
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs
@@ -0,0 +1,257 @@
+using System;
+using System.Linq;
+using System.Threading;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Plugins.Tmdb.Movies;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class MovieNfoParserTests
+ {
+ private readonly MovieNfoParser _parser;
+ private readonly IUserDataManager _userDataManager;
+ private readonly User _testUser;
+ private readonly FileSystemMetadata _localImageFileMetadata;
+
+ public MovieNfoParserTests()
+ {
+ _testUser = new User("Test User", "Auth provider", "Reset provider");
+
+ var providerManager = new Mock<IProviderManager>();
+
+ var tmdbExternalId = new TmdbMovieExternalId();
+ var externalIdInfo = new ExternalIdInfo(tmdbExternalId.ProviderName, tmdbExternalId.Key, tmdbExternalId.Type, tmdbExternalId.UrlFormatString);
+
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(new[] { externalIdInfo });
+
+ var nfoConfig = new XbmcMetadataOptions()
+ {
+ UserId = "F38E6443-090B-4F7A-BD12-9CFF5020F7BC"
+ };
+ var configManager = new Mock<IConfigurationManager>();
+ configManager.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(nfoConfig);
+
+ var user = new Mock<IUserManager>();
+ user.Setup(x => x.GetUserById(It.IsAny<Guid>()))
+ .Returns(_testUser);
+
+ var userData = new Mock<IUserDataManager>();
+ userData.Setup(x => x.GetUserData(_testUser, It.IsAny<BaseItem>()))
+ .Returns(new UserItemData());
+
+ var directoryService = new Mock<IDirectoryService>();
+ _localImageFileMetadata = new FileSystemMetadata()
+ {
+ Exists = true,
+ FullName = OperatingSystem.IsWindows() ?
+ "C:\\media\\movies\\Justice League (2017).jpg"
+ : "/media/movies/Justice League (2017).jpg"
+ };
+ directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName))
+ .Returns(_localImageFileMetadata);
+
+ _userDataManager = userData.Object;
+ _parser = new MovieNfoParser(
+ new NullLogger<MovieNfoParser>(),
+ configManager.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new Movie()
+ };
+
+ _parser.Fetch(result, "Test Data/Justice League.nfo", CancellationToken.None);
+ var item = (Movie)result.Item;
+
+ Assert.Equal("Justice League", item.OriginalTitle);
+ Assert.Equal("Justice for all.", item.Tagline);
+ Assert.Equal("tt0974015", item.ProviderIds[MetadataProvider.Imdb.ToString()]);
+ Assert.Equal("141052", item.ProviderIds[MetadataProvider.Tmdb.ToString()]);
+
+ Assert.Equal(4, item.Genres.Length);
+ Assert.Contains("Action", item.Genres);
+ Assert.Contains("Adventure", item.Genres);
+ Assert.Contains("Fantasy", item.Genres);
+ Assert.Contains("Sci-Fi", item.Genres);
+
+ Assert.Equal(new DateTime(2017, 11, 15), item.PremiereDate);
+ Assert.Equal(new DateTime(2017, 11, 16), item.EndDate);
+ Assert.Single(item.Studios);
+ Assert.Contains("DC Comics", item.Studios);
+
+ Assert.Equal("1.777778", item.AspectRatio);
+ Assert.Equal(Video3DFormat.HalfSideBySide, item.Video3DFormat);
+ Assert.Equal(1920, item.Width);
+ Assert.Equal(1080, item.Height);
+ Assert.Equal(new TimeSpan(0, 0, 6268).Ticks, item.RunTimeTicks);
+ Assert.True(item.HasSubtitles);
+ Assert.Equal(7.6f, item.CriticRating);
+ Assert.Equal("8.7", item.CustomRating);
+ Assert.Equal("en", item.PreferredMetadataLanguage);
+ Assert.Equal("us", item.PreferredMetadataCountryCode);
+ Assert.Single(item.RemoteTrailers);
+ Assert.Equal("https://www.youtube.com/watch?v=dQw4w9WgXcQ", item.RemoteTrailers[0].Url);
+
+ Assert.Equal(20, result.People.Count);
+
+ var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray();
+ Assert.Equal(3, writers.Length);
+ var writerNames = writers.Select(x => x.Name);
+ Assert.Contains("Jerry Siegel", writerNames);
+ Assert.Contains("Joe Shuster", writerNames);
+ Assert.Contains("Test", writerNames);
+
+ var directors = result.People.Where(x => x.Type == PersonType.Director).ToArray();
+ Assert.Single(directors);
+ Assert.Equal("Zack Snyder", directors[0].Name);
+
+ var actors = result.People.Where(x => x.Type == PersonType.Actor).ToArray();
+ Assert.Equal(15, actors.Length);
+
+ // Only test one actor
+ var aquaman = actors.FirstOrDefault(x => x.Role.Equals("Aquaman", StringComparison.Ordinal));
+ Assert.NotNull(aquaman);
+ Assert.Equal("Jason Momoa", aquaman!.Name);
+ Assert.Equal(5, aquaman!.SortOrder);
+ Assert.Equal("https://m.media-amazon.com/images/M/MV5BMTI5MTU5NjM1MV5BMl5BanBnXkFtZTcwODc4MDk0Mw@@._V1_SX1024_SY1024_.jpg", aquaman!.ImageUrl);
+
+ var lyricist = result.People.FirstOrDefault(x => x.Type == PersonType.Lyricist);
+ Assert.NotNull(lyricist);
+ Assert.Equal("Test Lyricist", lyricist!.Name);
+
+ Assert.Equal(new DateTime(2019, 8, 6, 9, 1, 18), item.DateCreated);
+
+ // userData
+ var userData = _userDataManager.GetUserData(_testUser, item);
+ Assert.Equal(2, userData.PlayCount);
+ Assert.True(userData.Played);
+ Assert.Equal(new DateTime(2021, 02, 11, 07, 47, 23), userData.LastPlayedDate);
+
+ // Movie set
+ Assert.Equal("702342", item.ProviderIds[MetadataProvider.TmdbCollection.ToString()]);
+ Assert.Equal("Justice League Collection", item.CollectionName);
+
+ // Images
+ Assert.Equal(7, result.RemoteImages.Count);
+
+ var posters = result.RemoteImages.Where(x => x.type == ImageType.Primary).ToList();
+ Assert.Single(posters);
+ Assert.Equal("http://image.tmdb.org/t/p/original/9rtrRGeRnL0JKtu9IMBWsmlmmZz.jpg", posters[0].url);
+
+ var logos = result.RemoteImages.Where(x => x.type == ImageType.Logo).ToList();
+ Assert.Single(logos);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png", logos[0].url);
+
+ var banners = result.RemoteImages.Where(x => x.type == ImageType.Banner).ToList();
+ Assert.Single(banners);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-586017e95adbd.jpg", banners[0].url);
+
+ var thumbs = result.RemoteImages.Where(x => x.type == ImageType.Thumb).ToList();
+ Assert.Single(thumbs);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585fb155c3743.jpg", thumbs[0].url);
+
+ var art = result.RemoteImages.Where(x => x.type == ImageType.Art).ToList();
+ Assert.Single(art);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/hdmovieclearart/justice-league-5865c23193041.png", art[0].url);
+
+ var discArt = result.RemoteImages.Where(x => x.type == ImageType.Disc).ToList();
+ Assert.Single(discArt);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png", discArt[0].url);
+
+ var backdrop = result.RemoteImages.Where(x => x.type == ImageType.Backdrop).ToList();
+ Assert.Single(backdrop);
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg", backdrop[0].url);
+
+ // Local Image - contains only one item depending on operating system
+ Assert.Single(result.Images);
+ Assert.Equal(_localImageFileMetadata.Name, result.Images[0].FileInfo.Name);
+ }
+
+ [Theory]
+ [InlineData("Test Data/Tmdb.nfo", "Tmdb", "30287")]
+ [InlineData("Test Data/Imdb.nfo", "Imdb", "tt0944947")]
+ public void Parse_UrlFile_Success(string path, string provider, string id)
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new Movie()
+ };
+
+ _parser.Fetch(result, path, CancellationToken.None);
+ var item = (Movie)result.Item;
+
+ Assert.Equal(id, item.ProviderIds[provider]);
+ }
+
+ [Fact]
+ public void Parse_GivenFileWithFanartTag_Success()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new Movie()
+ };
+
+ _parser.Fetch(result, "Test Data/Fanart.nfo", CancellationToken.None);
+
+ Assert.Single(result.RemoteImages.Where(x => x.type == ImageType.Backdrop));
+ Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg", result.RemoteImages.First(x => x.type == ImageType.Backdrop).url);
+ }
+
+ [Fact]
+ public void Parse_RadarrUrlFile_Success()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new Movie()
+ };
+
+ _parser.Fetch(result, "Test Data/Radarr.nfo", CancellationToken.None);
+ var item = (Movie)result.Item;
+
+ Assert.Equal("583689", item.ProviderIds[MetadataProvider.Tmdb.ToString()]);
+ Assert.Equal("tt4154796", item.ProviderIds[MetadataProvider.Imdb.ToString()]);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Video>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/Justice League.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new Movie()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs
new file mode 100644
index 000000000..eea8cb50a
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs
@@ -0,0 +1,86 @@
+using System;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Music;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class MusicAlbumNfoProviderTests
+ {
+ private readonly BaseNfoParser<MusicAlbum> _parser;
+
+ public MusicAlbumNfoProviderTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+
+ var musicBrainzArtist = new MusicBrainzArtistExternalId();
+ var externalIdInfo = new ExternalIdInfo(musicBrainzArtist.ProviderName, musicBrainzArtist.Key, musicBrainzArtist.Type, "MusicBrainzServer");
+
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(new[] { externalIdInfo });
+
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new BaseNfoParser<MusicAlbum>(
+ new NullLogger<BaseNfoParser<MusicAlbum>>(),
+ config.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<MusicAlbum>()
+ {
+ Item = new MusicAlbum()
+ };
+
+ _parser.Fetch(result, "Test Data/The Best of 1980-1990.nfo", CancellationToken.None);
+ var item = result.Item;
+
+ Assert.Equal("The Best of 1980-1990", item.Name);
+ Assert.Equal(1989, item.ProductionYear);
+ Assert.Contains("Pop", item.Genres);
+ Assert.Single(item.Genres);
+ Assert.Contains("Rock/Pop", item.Tags);
+ Assert.Equal("The Best of 1980-1990 is the first greatest hits compilation by Irish rock band U2, released in November 1998. It mostly contains the group's hit singles from the eighties but also mixes in some live staples as well as one new recording, Sweetest Thing. In April 1999, a companion video (featuring music videos and live footage) was released. The album was followed by another compilation, The Best of 1990-2000, in 2002.\nA limited edition version containing a special B-sides disc was released on the same date as the single-disc version. At the time of release, the official word was that the 2-disc album would be available the first week the album went on sale, then pulled from the stores. While this threat never materialized, it did result in the 2-disc version being in very high demand. Both versions charted in the Billboard 200.\nThe boy on the cover is Peter Rowan, brother of Bono's friend Guggi (real name Derek Rowan) of the Virgin Prunes. He also appears on the covers of the early EP Three, two of the band's first three albums (Boy and War), and Early Demos.", item.Overview);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<MusicAlbum>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/The Best of 1980-1990.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<MusicAlbum>()
+ {
+ Item = new MusicAlbum()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs
new file mode 100644
index 000000000..8ca3dd96e
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs
@@ -0,0 +1,86 @@
+using System;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.Providers.Music;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class MusicArtistNfoParserTests
+ {
+ private readonly BaseNfoParser<MusicArtist> _parser;
+
+ public MusicArtistNfoParserTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+
+ var musicBrainzArtist = new MusicBrainzArtistExternalId();
+ var externalIdInfo = new ExternalIdInfo(musicBrainzArtist.ProviderName, musicBrainzArtist.Key, musicBrainzArtist.Type, "MusicBrainzServer");
+
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(new[] { externalIdInfo });
+
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new BaseNfoParser<MusicArtist>(
+ new NullLogger<BaseNfoParser<MusicArtist>>(),
+ config.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<MusicArtist>()
+ {
+ Item = new MusicArtist()
+ };
+
+ _parser.Fetch(result, "Test Data/U2.nfo", CancellationToken.None);
+ var item = result.Item;
+
+ Assert.Equal("U2", item.Name);
+ Assert.Equal("U2", item.SortName);
+ Assert.Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432", item.ProviderIds[MetadataProvider.MusicBrainzArtist.ToString()]);
+
+ Assert.Single(item.Genres);
+ Assert.Equal("Rock", item.Genres[0]);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<MusicArtist>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/U2.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<MusicArtist>()
+ {
+ Item = new MusicArtist()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs
new file mode 100644
index 000000000..bf887cab1
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Linq;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class MusicVideoNfoParserTests
+ {
+ private readonly MovieNfoParser _parser;
+
+ public MusicVideoNfoParserTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(Enumerable.Empty<ExternalIdInfo>());
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new MovieNfoParser(
+ new NullLogger<BaseNfoParser<MusicVideo>>(),
+ config.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Succes()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new MusicVideo()
+ };
+
+ _parser.Fetch(result, "Test Data/Dancing Queen.nfo", CancellationToken.None);
+ var item = (MusicVideo)result.Item;
+
+ Assert.Equal("Dancing Queen", item.Name);
+ Assert.Single(item.Artists);
+ Assert.Contains("ABBA", item.Artists);
+ Assert.Equal("Arrival", item.Album);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Video>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/Dancing Queen.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Video>()
+ {
+ Item = new MusicVideo()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs
new file mode 100644
index 000000000..31110dbd7
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Linq;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class SeasonNfoProviderTests
+ {
+ private readonly SeasonNfoParser _parser;
+
+ public SeasonNfoProviderTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(Enumerable.Empty<ExternalIdInfo>());
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new SeasonNfoParser(
+ new NullLogger<SeasonNfoParser>(),
+ config.Object,
+ providerManager.Object,
+ user.Object,
+ userData.Object,
+ directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<Season>()
+ {
+ Item = new Season()
+ };
+
+ _parser.Fetch(result, "Test Data/Season 01.nfo", CancellationToken.None);
+ var item = result.Item;
+
+ Assert.Equal("Season 1", item.Name);
+ Assert.Equal(1, item.IndexNumber);
+ Assert.False(item.IsLocked);
+ Assert.Equal(2019, item.ProductionYear);
+ Assert.Equal(new DateTime(2019, 11, 08), item.PremiereDate);
+ Assert.Equal(new DateTime(2020, 06, 14, 17, 26, 51), item.DateCreated);
+
+ Assert.Equal(10, result.People.Count);
+
+ Assert.True(result.People.All(x => x.Type == PersonType.Actor));
+
+ // Only test one actor
+ var nini = result.People.FirstOrDefault(x => x.Role.Equals("Nini", StringComparison.Ordinal));
+ Assert.NotNull(nini);
+ Assert.Equal("Olivia Rodrigo", nini!.Name);
+ Assert.Equal(0, nini!.SortOrder);
+ Assert.Equal("/config/metadata/People/O/Olivia Rodrigo/poster.jpg", nini!.ImageUrl);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Season>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/Season 01.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Season>()
+ {
+ Item = new Season()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs
new file mode 100644
index 000000000..bdedae205
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Linq;
+using System.Threading;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Providers;
+using MediaBrowser.XbmcMetadata.Parsers;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.XbmcMetadata.Tests.Parsers
+{
+ public class SeriesNfoParserTests
+ {
+ private readonly SeriesNfoParser _parser;
+
+ public SeriesNfoParserTests()
+ {
+ var providerManager = new Mock<IProviderManager>();
+ providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>()))
+ .Returns(Enumerable.Empty<ExternalIdInfo>());
+ var config = new Mock<IConfigurationManager>();
+ config.Setup(x => x.GetConfiguration(It.IsAny<string>()))
+ .Returns(new XbmcMetadataOptions());
+ var user = new Mock<IUserManager>();
+ var userData = new Mock<IUserDataManager>();
+ var directoryService = new Mock<IDirectoryService>();
+
+ _parser = new SeriesNfoParser(new NullLogger<SeriesNfoParser>(), config.Object, providerManager.Object, user.Object, userData.Object, directoryService.Object);
+ }
+
+ [Fact]
+ public void Fetch_Valid_Success()
+ {
+ var result = new MetadataResult<Series>()
+ {
+ Item = new Series()
+ };
+
+ _parser.Fetch(result, "Test Data/American Gods.nfo", CancellationToken.None);
+ var item = result.Item;
+
+ Assert.Equal("American Gods", item.OriginalTitle);
+ Assert.Equal(string.Empty, item.Tagline);
+ Assert.Equal(0, item.RunTimeTicks);
+ Assert.Equal("46639", item.ProviderIds[MetadataProvider.Tmdb.ToString()]);
+ Assert.Equal("253573", item.ProviderIds[MetadataProvider.Tvdb.ToString()]);
+ Assert.Equal("tt11111", item.ProviderIds[MetadataProvider.Imdb.ToString()]);
+
+ Assert.Equal(3, item.Genres.Length);
+ Assert.Contains("Drama", item.Genres);
+ Assert.Contains("Mystery", item.Genres);
+ Assert.Contains("Sci-Fi & Fantasy", item.Genres);
+
+ Assert.Equal(new DateTime(2017, 4, 30), item.PremiereDate);
+ Assert.Single(item.Studios);
+ Assert.Contains("Starz", item.Studios);
+ Assert.Equal("9 PM", item.AirTime);
+ Assert.Single(item.AirDays);
+ Assert.Contains(DayOfWeek.Friday, item.AirDays);
+ Assert.Equal(SeriesStatus.Ended, item.Status);
+
+ Assert.Equal(6, result.People.Count);
+
+ Assert.True(result.People.All(x => x.Type == PersonType.Actor));
+
+ // Only test one actor
+ var sweeney = result.People.FirstOrDefault(x => x.Role.Equals("Mad Sweeney", StringComparison.Ordinal));
+ Assert.NotNull(sweeney);
+ Assert.Equal("Pablo Schreiber", sweeney!.Name);
+ Assert.Equal(3, sweeney!.SortOrder);
+ Assert.Equal("http://image.tmdb.org/t/p/original/uo8YljeePz3pbj7gvWXdB4gOOW4.jpg", sweeney!.ImageUrl);
+
+ Assert.Equal(new DateTime(2017, 10, 7, 14, 25, 47), item.DateCreated);
+ }
+
+ [Theory]
+ [InlineData("Test Data/Tvdb.nfo", "Tvdb", "121361")]
+ public void Parse_UrlFile_Success(string path, string provider, string id)
+ {
+ var result = new MetadataResult<Series>()
+ {
+ Item = new Series()
+ };
+
+ _parser.Fetch(result, path, CancellationToken.None);
+ var item = (Series)result.Item;
+
+ Assert.Equal(id, item.ProviderIds[provider]);
+ }
+
+ [Fact]
+ public void Fetch_WithNullItem_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Series>();
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, "Test Data/American Gods.nfo", CancellationToken.None));
+ }
+
+ [Fact]
+ public void Fetch_NullResult_ThrowsArgumentException()
+ {
+ var result = new MetadataResult<Series>()
+ {
+ Item = new Series()
+ };
+
+ Assert.Throws<ArgumentException>(() => _parser.Fetch(result, string.Empty, CancellationToken.None));
+ }
+ }
+}
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/American Gods.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/American Gods.nfo
new file mode 100644
index 000000000..5bf7e08eb
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/American Gods.nfo
@@ -0,0 +1,187 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<tvshow>
+ <title>American Gods</title>
+ <originaltitle>American Gods</originaltitle>
+ <showtitle>American Gods</showtitle>
+ <sorttitle>American Gods</sorttitle>
+ <ratings>
+ <rating name="themoviedb" max="10" default="true">
+ <value>6.800000</value>
+ <votes>581</votes>
+ </rating>
+ <rating name="imdb" max="10" default="true">
+ <value>5.500000</value>
+ <votes>86352</votes>
+ </rating>
+ <rating name="metacritic" max="10">
+ <value>6.0</value>
+ <votes>22</votes>
+ </rating>
+ <rating name="tomatometerallcritics" max="10">
+ <value>7.6</value>
+ <votes>71</votes>
+ </rating>
+ <rating name="tomatometerallaudience" max="10">
+ <value>6.2</value>
+ <votes>119873</votes>
+ </rating>
+ </ratings>
+ <userrating>0</userrating>
+ <top250>0</top250>
+ <season>2</season>
+ <episode>16</episode>
+ <displayseason>-1</displayseason>
+ <displayepisode>-1</displayepisode>
+ <outline></outline>
+ <plot>An ex-con becomes the traveling partner of a conman who turns out to be one of the older gods trying to recruit troops to battle the upstart deities. Based on Neil Gaiman&apos;s fantasy novel.</plot>
+ <tagline></tagline>
+ <runtime>0</runtime>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/tv/253573/tvposter/american-gods-58b18cd8d667a.jpg">https://assets.fanart.tv/fanart/tv/253573/tvposter/american-gods-58b18cd8d667a.jpg</thumb>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/tv/253573/tvposter/american-gods-5c896dbee9d21.jpg">https://assets.fanart.tv/fanart/tv/253573/tvposter/american-gods-5c896dbee9d21.jpg</thumb>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/tv/253573/tvposter/american-gods-57dda913a44e0.jpg">https://assets.fanart.tv/fanart/tv/253573/tvposter/american-gods-57dda913a44e0.jpg</thumb>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/tv/253573/tvposter/american-gods-590c159dcbf3a.jpg">https://assets.fanart.tv/fanart/tv/253573/tvposter/american-gods-590c159dcbf3a.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/tv/253573/tvbanner/american-gods-5cbbdaa84298d.jpg">https://assets.fanart.tv/fanart/tv/253573/tvbanner/american-gods-5cbbdaa84298d.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/tv/253573/tvbanner/american-gods-5932b1ffb3522.jpg">https://assets.fanart.tv/fanart/tv/253573/tvbanner/american-gods-5932b1ffb3522.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/tv/253573/tvbanner/american-gods-5932b1ffb43e4.jpg">https://assets.fanart.tv/fanart/tv/253573/tvbanner/american-gods-5932b1ffb43e4.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/tv/253573/tvthumb/american-gods-58db45dc886f5.jpg">https://assets.fanart.tv/fanart/tv/253573/tvthumb/american-gods-58db45dc886f5.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/tv/253573/tvthumb/american-gods-5932aee79947a.jpg">https://assets.fanart.tv/fanart/tv/253573/tvthumb/american-gods-5932aee79947a.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/tv/253573/tvthumb/american-gods-5932aee799e5a.jpg">https://assets.fanart.tv/fanart/tv/253573/tvthumb/american-gods-5932aee799e5a.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/tv/253573/tvthumb/american-gods-5932aee79a2f2.jpg">https://assets.fanart.tv/fanart/tv/253573/tvthumb/american-gods-5932aee79a2f2.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/tv/253573/tvthumb/american-gods-5932aee79a7c9.jpg">https://assets.fanart.tv/fanart/tv/253573/tvthumb/american-gods-5932aee79a7c9.jpg</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/tv/253573/hdtvlogo/american-gods-58b04bdcecefd.png">https://assets.fanart.tv/fanart/tv/253573/hdtvlogo/american-gods-58b04bdcecefd.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/tv/253573/hdtvlogo/american-gods-58b04d78a7ffc.png">https://assets.fanart.tv/fanart/tv/253573/hdtvlogo/american-gods-58b04d78a7ffc.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/tv/253573/hdtvlogo/american-gods-59e6660cb7dbc.png">https://assets.fanart.tv/fanart/tv/253573/hdtvlogo/american-gods-59e6660cb7dbc.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/tv/253573/hdtvlogo/american-gods-59e6660cc0716.png">https://assets.fanart.tv/fanart/tv/253573/hdtvlogo/american-gods-59e6660cc0716.png</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/tv/253573/hdclearart/american-gods-59177740ba6cd.png">https://assets.fanart.tv/fanart/tv/253573/hdclearart/american-gods-59177740ba6cd.png</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/tv/253573/hdclearart/american-gods-5913b6b2ce91d.png">https://assets.fanart.tv/fanart/tv/253573/hdclearart/american-gods-5913b6b2ce91d.png</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/tv/253573/hdclearart/american-gods-5913b6b2cfa64.png">https://assets.fanart.tv/fanart/tv/253573/hdclearart/american-gods-5913b6b2cfa64.png</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/tv/253573/hdclearart/american-gods-5913b6b2cf502.png">https://assets.fanart.tv/fanart/tv/253573/hdclearart/american-gods-5913b6b2cf502.png</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/tv/253573/hdclearart/american-gods-5a4805be0619f.png">https://assets.fanart.tv/fanart/tv/253573/hdclearart/american-gods-5a4805be0619f.png</thumb>
+ <thumb aspect="characterart" preview="https://assets.fanart.tv/preview/tv/253573/characterart/american-gods-5a4805af07a04.png">https://assets.fanart.tv/fanart/tv/253573/characterart/american-gods-5a4805af07a04.png</thumb>
+ <thumb aspect="characterart" preview="https://assets.fanart.tv/preview/tv/253573/characterart/american-gods-59e6b1c71b65a.png">https://assets.fanart.tv/fanart/tv/253573/characterart/american-gods-59e6b1c71b65a.png</thumb>
+ <thumb aspect="poster" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5d1274a8c31cb.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5d1274a8c31cb.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-59fea294b565f.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-59fea294b565f.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5cacdf37068db.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5cacdf37068db.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5cacdf7783e04.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5cacdf7783e04.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5d1274a8c31cb.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5d1274a8c31cb.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-59fea294b565f.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-59fea294b565f.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5cacdf37068db.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5cacdf37068db.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonposter/american-gods-5cacdf7783e04.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonposter/american-gods-5cacdf7783e04.jpg</thumb>
+ <thumb aspect="banner" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonbanner/american-gods-5cc6b35699d26.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonbanner/american-gods-5cc6b35699d26.jpg</thumb>
+ <thumb aspect="banner" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonbanner/american-gods-5cc6b36965b54.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonbanner/american-gods-5cc6b36965b54.jpg</thumb>
+ <thumb aspect="banner" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonbanner/american-gods-5cc6b35699d26.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonbanner/american-gods-5cc6b35699d26.jpg</thumb>
+ <thumb aspect="banner" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonbanner/american-gods-5cc6b36965b54.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonbanner/american-gods-5cc6b36965b54.jpg</thumb>
+ <thumb aspect="landscape" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonthumb/american-gods-5cc6b380d6c56.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonthumb/american-gods-5cc6b380d6c56.jpg</thumb>
+ <thumb aspect="landscape" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonthumb/american-gods-59e6b5a03e7aa.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonthumb/american-gods-59e6b5a03e7aa.jpg</thumb>
+ <thumb aspect="landscape" type="season" season="2" preview="https://assets.fanart.tv/preview/tv/253573/seasonthumb/american-gods-5cc6b380d6c56.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonthumb/american-gods-5cc6b380d6c56.jpg</thumb>
+ <thumb aspect="landscape" type="season" season="1" preview="https://assets.fanart.tv/preview/tv/253573/seasonthumb/american-gods-59e6b5a03e7aa.jpg">https://assets.fanart.tv/fanart/tv/253573/seasonthumb/american-gods-59e6b5a03e7aa.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/m6qf6lq3yARgbZwspvDLbUFtASh.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/gevw5nZRYz2kWj1PqW9pz4sgeeZ.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/btwTe5cQbGWGOErBiRqnjNP9cJl.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/loJ4sfr4zp995qMoeCHiIIGaOg8.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/dHo8Lw7ruIaQTdTTDZPCMyZxwy5.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/zfAXP4bG2G17VuLNU9cqRcVU0xj.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/oxYUbNpG2st2zXWzYRvewehmvuj.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/mwoQ6zynu2DBxKCBYi30qoM236N.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/8XEoXAMzgcf7m1KiUDZ9N1UGh4o.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/rWsayJB1grML2LdPjjKDC3g0Brr.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/8qRsj8uJ4zPARQmQ9FvejTY1lnV.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/acjnZP0GrwWDxCxV6QejKizbzOy.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/hN1sI57QILGfdrEOqpUfo0NtHjW.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/hz2jNy3DfseYzRSybGRlUtz4pTi.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/hLDgNDdrkB0oWiuClpxN4E3XadJ.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/4FiqawHsVz1mYCRudPtXKbfmP4M.jpg</thumb>
+ <thumb aspect="poster">http://image.tmdb.org/t/p/original/sKR8Q36YBtyRc19y4yGYuD1xBgA.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/4l8Vnbb7e5QA6bAItMqQIHXLRgc.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/ni0thXw5Zi5dQKBY6Oj0vcfIS2n.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/v17HfCzWKQKOBrww9RxZmN5R9tF.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/2ffvlgYsxbXGiWkc3V6Q8tgpiBo.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1">http://image.tmdb.org/t/p/original/rASj7OUjWDhfhAeO2MaFOA3lJpQ.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1">http://image.tmdb.org/t/p/original/67exRijfvN5RRmBCqFtk1bhJ7Uh.jpg</thumb>
+ <thumb aspect="poster" type="season" season="1">http://image.tmdb.org/t/p/original/59iE3xxP7H8rAiXW6TDR2HSoUUm.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/4l8Vnbb7e5QA6bAItMqQIHXLRgc.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/ni0thXw5Zi5dQKBY6Oj0vcfIS2n.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/v17HfCzWKQKOBrww9RxZmN5R9tF.jpg</thumb>
+ <thumb aspect="poster" type="season" season="2">http://image.tmdb.org/t/p/original/2ffvlgYsxbXGiWkc3V6Q8tgpiBo.jpg</thumb>
+ <thumb aspect="banner">https://thetvdb.com/banners/graphical/253573-g3.jpg</thumb>
+ <thumb aspect="banner">https://thetvdb.com/banners/graphical/253573-g4.jpg</thumb>
+ <thumb aspect="banner">https://thetvdb.com/banners/graphical/253573-g2.jpg</thumb>
+ <thumb aspect="banner">https://thetvdb.com/banners/graphical/253573-g.jpg</thumb>
+ <thumb aspect="banner">https://thetvdb.com/banners/graphical/253573-g5.jpg</thumb>
+ <fanart>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5c8965c58e778.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5c8965c58e778.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-59e6a8a495c2a.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-59e6a8a495c2a.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-59e6b13827ba2.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-59e6b13827ba2.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e07ad.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e07ad.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e2913.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e2913.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e0000.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e0000.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e0d3a.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e0d3a.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e1395.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e1395.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e1952.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e1952.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/tv/253573/showbackground/american-gods-5932b089e23ca.jpg">https://assets.fanart.tv/fanart/tv/253573/showbackground/american-gods-5932b089e23ca.jpg</thumb>
+ </fanart>
+ <mpaa>Australia:MA</mpaa>
+ <playcount>0</playcount>
+ <lastplayed></lastplayed>
+ <episodeguide>
+ <url cache="tmdb-46639-en.json">http://api.themoviedb.org/3/tv/46639?api_key=6a5be4999abf74eba1f9a8311294c267&amp;language=en</url>
+ </episodeguide>
+ <id IMDB="tt11111" TMDB="46639">253573</id>
+ <uniqueid type="tmdb" default="true">46639</uniqueid>
+ <uniqueid type="tvdb">253573</uniqueid>
+ <genre>Drama</genre>
+ <genre>Mystery</genre>
+ <genre>Sci-Fi &amp; Fantasy</genre>
+ <premiered>2017-04-30</premiered>
+ <year>2017</year>
+ <status>ended</status>
+ <airs_time>9 PM</airs_time>
+ <airs_dayofweek>Friday</airs_dayofweek>
+ <code></code>
+ <aired></aired>
+ <studio>Starz</studio>
+ <trailer></trailer>
+ <actor>
+ <name>Ricky Whittle</name>
+ <role>Shadow Moon</role>
+ <order>0</order>
+ <thumb>http://image.tmdb.org/t/p/original/cjeDbVfBp6Qvb3C74Dfy7BKDTQN.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ian McShane</name>
+ <role>Mr. Wednesday</role>
+ <order>1</order>
+ <thumb>http://image.tmdb.org/t/p/original/pY9ud4BJwHekNiO4MMItPbgkdAy.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Emily Browning</name>
+ <role>Laura Moon</role>
+ <order>2</order>
+ <thumb>http://image.tmdb.org/t/p/original/fa1Kyj02wxwcdS6EHb2i27TNXvU.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Pablo Schreiber</name>
+ <role>Mad Sweeney</role>
+ <order>3</order>
+ <thumb>http://image.tmdb.org/t/p/original/uo8YljeePz3pbj7gvWXdB4gOOW4.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Bruce Langley</name>
+ <role>Technical Boy</role>
+ <order>4</order>
+ <thumb>http://image.tmdb.org/t/p/original/f4EOWUmznLqboq8Ce7jnlkHVK3Y.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Yetide Badaki</name>
+ <role>Bilquis</role>
+ <order>5</order>
+ <thumb>http://image.tmdb.org/t/p/original/qfzkREHuI1JvMxBteIAjKX8qMEr.jpg</thumb>
+ </actor>
+ <namedseason number="1">Season 1</namedseason>
+ <namedseason number="2">Season 2</namedseason>
+ <resume>
+ <position>0.000000</position>
+ <total>0.000000</total>
+ </resume>
+ <dateadded>2017-10-07 14:25:47</dateadded>
+</tvshow>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Dancing Queen.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Dancing Queen.nfo
new file mode 100644
index 000000000..29f19e1a0
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Dancing Queen.nfo
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+<musicvideo>
+ <title>Dancing Queen</title>
+ <userrating>0</userrating>
+ <top250>0</top250>
+ <track>3</track>
+ <album>Arrival</album>
+ <outline></outline>
+ <plot>Dancing Queen est un des tubes emblématiques de l&apos;ère disco produits par le groupe suédois ABBA en 1976. Ce tube connaît un regain de popularité en 1994 lors de la sortie de Priscilla, folle du désert, et fait « presque » partie de la distribution du film Muriel.&#x0A;Le groupe a également enregistré une version espagnole de ce titre, La reina del baile, pour le marché d&apos;Amérique latine. On peut retrouver ces versions en espagnol des succès de ABBA sur l&apos;abum Oro. Le 18 juin 1976, ABBA a interprété cette chanson lors d&apos;un spectacle télévisé organisé en l&apos;honneur du roi Charles XVI Gustave de Suède, qui venait de se marier. Le titre sera repris en 2011 par Glee dans la saison 2, épisode 20.</plot>
+ <tagline></tagline>
+ <runtime>2</runtime>
+ <thumb preview="https://www.theaudiodb.com/images/media/album/thumb/arrival-4ee244732bbde.jpg/preview">https://www.theaudiodb.com/images/media/album/thumb/arrival-4ee244732bbde.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/d87e52c5-bb8d-4da8-b941-9f4928627dc8/albumcover/arrival-548ab7a698b49.jpg">https://assets.fanart.tv/fanart/music/d87e52c5-bb8d-4da8-b941-9f4928627dc8/albumcover/arrival-548ab7a698b49.jpg</thumb>
+ <mpaa></mpaa>
+ <playcount>0</playcount>
+ <lastplayed></lastplayed>
+ <id></id>
+ <genre>Pop</genre>
+ <director>John Smith</director>
+ <premiered>1976-01-01</premiered>
+ <year>1976</year>
+ <status></status>
+ <code></code>
+ <aired></aired>
+ <studio>Studio 54</studio>
+ <trailer></trailer>
+ <fileinfo>
+ <streamdetails>
+ <video>
+ <codec>hevc</codec>
+ <aspect>1.792230</aspect>
+ <width>716</width>
+ <height>568</height>
+ <durationinseconds>143</durationinseconds>
+ <stereomode></stereomode>
+ </video>
+ <audio>
+ <codec>ac3</codec>
+ <language>eng</language>
+ <channels>2</channels>
+ </audio>
+ </streamdetails>
+ </fileinfo>
+ <artist>ABBA</artist>
+ <resume>
+ <position>0.000000</position>
+ <total>0.000000</total>
+ </resume>
+ <dateadded>2018-09-10 09:46:06</dateadded>
+</musicvideo>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Fanart.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Fanart.nfo
new file mode 100644
index 000000000..0b129bd8c
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Fanart.nfo
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<movie>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-57b476a831d74.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57b476a831d74.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-57947e28cf10b.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57947e28cf10b.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5863d5c0cf0c9.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5863d5c0cf0c9.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5a801747e5545.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5a801747e5545.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5cd75683df92b.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5cd75683df92b.png</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-586017e95adbd.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-586017e95adbd.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-5934d45bc6592.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5934d45bc6592.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-5aa9289a379fa.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5aa9289a379fa.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-585fb155c3743.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585fb155c3743.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-585edbda91d82.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585edbda91d82.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-5b86588882c12.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5b86588882c12.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-5bbb9babe600c.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5bbb9babe600c.jpg</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/movies/141052/hdmovieclearart/justice-league-5865c23193041.png">https://assets.fanart.tv/fanart/movies/141052/hdmovieclearart/justice-league-5865c23193041.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a3af26360617.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-58690967b9765.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-58690967b9765.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a953ca4db6a6.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a953ca4db6a6.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a0b913c233be.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a0b913c233be.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-59dc595362ef1.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-59dc595362ef1.png</thumb>
+ <fanart>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-58fa1f1932897.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-58fa1f1932897.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a14f5fd8dd16.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a14f5fd8dd16.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a119394ea362.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a119394ea362.jpg</thumb>
+ </fanart>
+ <thumb aspect="fanart">This-should-not-be-saved-as-a-fanart-image.jpg</thumb>
+</movie>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Imdb.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Imdb.nfo
new file mode 100644
index 000000000..e30a1c660
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Imdb.nfo
@@ -0,0 +1 @@
+https://www.imdb.com/title/tt0944947/
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo
new file mode 100644
index 000000000..4e8c79dca
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo
@@ -0,0 +1,248 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<movie>
+ <title>Justice League</title>
+ <originaltitle>Justice League</originaltitle>
+ <ratings>
+ <rating name="imdb" max="10" default="true">
+ <value>6.400000</value>
+ <votes>335583</votes>
+ </rating>
+ <rating name="metacritic" max="10">
+ <value>4.500000</value>
+ <votes>52</votes>
+ </rating>
+ <rating name="themoviedb" max="10">
+ <value>6.200000</value>
+ <votes>7788</votes>
+ </rating>
+ <rating name="tomatometerallcritics" max="10">
+ <value>7.6</value>
+ <votes>71</votes>
+ </rating>
+ <rating name="tomatometerallaudience" max="10">
+ <value>6.2</value>
+ <votes>119873</votes>
+ </rating>
+ </ratings>
+ <criticrating>7.6</criticrating>
+ <language>en</language>
+ <countrycode>us</countrycode>
+ <customrating>8.7</customrating>
+ <aspectratio>1.777778</aspectratio>
+ <userrating>0</userrating>
+ <top250>0</top250>
+ <outline>Fueled by his restored faith in humanity and inspired by Superman&apos;s selfless act, Bruce Wayne enlists the help of his new-found ally, Diana Prince, to face an even greater enemy.</outline>
+ <plot>Fueled by his restored faith in humanity and inspired by Superman&apos;s selfless act, Bruce Wayne enlists the help of his newfound ally, Diana Prince, to face an even greater enemy. Together, Batman and Wonder Woman work quickly to find and recruit a team of meta-humans to stand against this newly awakened threat. But despite the formation of this unprecedented league of heroes-Batman, Wonder Woman, Aquaman, Cyborg and The Flash-it may already be too late to save the planet from an assault of catastrophic proportions.</plot>
+ <tagline>Justice for all.</tagline>
+ <runtime>120</runtime>
+ <playcount>2</playcount>
+ <watched>true</watched>
+ <lastplayed>2021-02-11 07:47:23</lastplayed>
+ <tmdbId>141052</tmdbId>
+ <thumb aspect="set.poster" preview="https://assets.fanart.tv/preview/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg">https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg</thumb>
+ <thumb aspect="set.poster" preview="https://assets.fanart.tv/preview/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg">https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg</thumb>
+ <thumb aspect="set.clearlogo" preview="https://assets.fanart.tv/preview/movies/468551/hdmovielogo/justice-league-collection-5ba855ed4239a.png">https://assets.fanart.tv/fanart/movies/468551/hdmovielogo/justice-league-collection-5ba855ed4239a.png</thumb>
+ <thumb aspect="set.clearart" preview="https://assets.fanart.tv/preview/movies/468551/hdmovieclearart/justice-league-collection-5c24eae8d4d71.png">https://assets.fanart.tv/fanart/movies/468551/hdmovieclearart/justice-league-collection-5c24eae8d4d71.png</thumb>
+ <thumb aspect="set.landscape" preview="https://assets.fanart.tv/preview/movies/468551/moviethumb/justice-league-collection-5c24ebc7d0d2b.jpg">https://assets.fanart.tv/fanart/movies/468551/moviethumb/justice-league-collection-5c24ebc7d0d2b.jpg</thumb>
+ <thumb aspect="set.poster" preview="http://image.tmdb.org/t/p/w500/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg">http://image.tmdb.org/t/p/original/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg</thumb>
+ <thumb aspect="set.poster" preview="http://image.tmdb.org/t/p/w500/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg">http://image.tmdb.org/t/p/original/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg</thumb>
+ <thumb aspect="set.poster" preview="http://image.tmdb.org/t/p/w500/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg">http://image.tmdb.org/t/p/original/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg</thumb>
+ <thumb aspect="set.poster" preview="http://image.tmdb.org/t/p/w500/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg">http://image.tmdb.org/t/p/original/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg</thumb>
+ <thumb aspect="set.poster" preview="http://image.tmdb.org/t/p/w500/7iO1C4c5igXsB6AyxnqsCPv6fiq.jpg">http://image.tmdb.org/t/p/original/7iO1C4c5igXsB6AyxnqsCPv6fiq.jpg</thumb>
+ <thumb aspect="set.fanart" preview="http://image.tmdb.org/t/p/w500/vyxOJuk6cxrRcGzuMRbDTpwji1w.jpg">http://image.tmdb.org/t/p/original/vyxOJuk6cxrRcGzuMRbDTpwji1w.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/9rtrRGeRnL0JKtu9IMBWsmlmmZz.jpg">http://image.tmdb.org/t/p/original/9rtrRGeRnL0JKtu9IMBWsmlmmZz.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/eRoXqOzciHkSPs1Z8pGnJMZo0Zb.jpg">http://image.tmdb.org/t/p/original/eRoXqOzciHkSPs1Z8pGnJMZo0Zb.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/aQkEdqaXVxYObMLeoBSAUcgkxLs.jpg">http://image.tmdb.org/t/p/original/aQkEdqaXVxYObMLeoBSAUcgkxLs.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/4lo1fTexk2eNIeQx3Tp74kN7ASE.jpg">http://image.tmdb.org/t/p/original/4lo1fTexk2eNIeQx3Tp74kN7ASE.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/fF94rvT1kJpVzIE2aSYgYj9B3pc.jpg">http://image.tmdb.org/t/p/original/fF94rvT1kJpVzIE2aSYgYj9B3pc.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/uwegp70cWe16EtwsSjbL6ShPenG.jpg">http://image.tmdb.org/t/p/original/uwegp70cWe16EtwsSjbL6ShPenG.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/exLtrlI7JjKcfQVTccI7XdQRFMz.jpg">http://image.tmdb.org/t/p/original/exLtrlI7JjKcfQVTccI7XdQRFMz.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/paLcue01KpfQftorfjKqqD4qvlL.jpg">http://image.tmdb.org/t/p/original/paLcue01KpfQftorfjKqqD4qvlL.jpg</thumb>
+ <thumb aspect="poster" preview="http://image.tmdb.org/t/p/w500/yVDIfiKIsCbdFcgLXW34bAsnQvy.jpg">http://image.tmdb.org/t/p/original/yVDIfiKIsCbdFcgLXW34bAsnQvy.jpg</thumb>
+ <thumb aspect="poster">C:\media\movies\Justice League (2017).jpg</thumb>
+ <thumb aspect="poster">/media/movies/Justice League (2017).jpg</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-57b476a831d74.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57b476a831d74.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-57947e28cf10b.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57947e28cf10b.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5863d5c0cf0c9.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5863d5c0cf0c9.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5a801747e5545.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5a801747e5545.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/movies/141052/hdmovielogo/justice-league-5cd75683df92b.png">https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5cd75683df92b.png</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-586017e95adbd.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-586017e95adbd.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-5934d45bc6592.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5934d45bc6592.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/movies/141052/moviebanner/justice-league-5aa9289a379fa.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5aa9289a379fa.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-585fb155c3743.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585fb155c3743.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-585edbda91d82.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585edbda91d82.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-5b86588882c12.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5b86588882c12.jpg</thumb>
+ <thumb aspect="landscape" preview="https://assets.fanart.tv/preview/movies/141052/moviethumb/justice-league-5bbb9babe600c.jpg">https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5bbb9babe600c.jpg</thumb>
+ <thumb aspect="clearart" preview="https://assets.fanart.tv/preview/movies/141052/hdmovieclearart/justice-league-5865c23193041.png">https://assets.fanart.tv/fanart/movies/141052/hdmovieclearart/justice-league-5865c23193041.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a3af26360617.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-58690967b9765.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-58690967b9765.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a953ca4db6a6.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a953ca4db6a6.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a0b913c233be.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a0b913c233be.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png</thumb>
+ <thumb aspect="discart" preview="https://assets.fanart.tv/preview/movies/141052/moviedisc/justice-league-59dc595362ef1.png">https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-59dc595362ef1.png</thumb>
+ <thumb aspect="fanart">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg</thumb>
+ <fanart>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-58fa1f1932897.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-58fa1f1932897.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a14f5fd8dd16.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a14f5fd8dd16.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/movies/141052/moviebackground/justice-league-5a119394ea362.jpg">https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a119394ea362.jpg</thumb>
+ </fanart>
+ <mpaa>Australia:M</mpaa>
+ <id>tt0974015</id>
+ <uniqueid type="imdb">tt0974015</uniqueid>
+ <uniqueid type="tmdb">141052</uniqueid>
+ <genre>Action</genre>
+ <genre>Adventure</genre>
+ <genre>Fantasy</genre>
+ <genre>Sci-Fi</genre>
+ <country>USA</country>
+ <country>Canada</country>
+ <country>UK</country>
+ <set tmdbcolid="702342">
+ <name>Justice League Collection</name>
+ <overview>Based on the DC Comics superhero team</overview>
+ </set>
+ <credits>Jerry Siegel</credits>
+ <credits>Joe Shuster</credits>
+ <director>Zack Snyder,</director>
+ <writer>Test</writer>
+ <premiered>2017-11-15</premiered>
+ <enddate>2017-11-16</enddate>
+ <year>2017</year>
+ <status></status>
+ <code></code>
+ <aired></aired>
+ <studio>DC Comics</studio>
+ <trailer>plugin://plugin.video.youtube/?action=play_video&amp;videoid=dQw4w9WgXcQ</trailer>
+ <fileinfo>
+ <streamdetails>
+ <video>
+ <codec>h264</codec>
+ <aspect>1.777778</aspect>
+ <width>1920</width>
+ <height>1080</height>
+ <durationinseconds>6268</durationinseconds>
+ <stereomode></stereomode>
+ <format3d>HSBS</format3d>
+ </video>
+ <audio>
+ <codec>truehd</codec>
+ <language>eng</language>
+ <channels>8</channels>
+ </audio>
+ <audio>
+ <codec>ac3</codec>
+ <language></language>
+ <channels>6</channels>
+ </audio>
+ <subtitle>
+ <language>eng</language>
+ </subtitle>
+ </streamdetails>
+ </fileinfo>
+ <actor>
+ <name>Ben Affleck</name>
+ <role>Batman</role>
+ <order>0</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTI4MzIxMTk0Nl5BMl5BanBnXkFtZTcwOTU5NjA0Mg@@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Henry Cavill</name>
+ <role>Superman</role>
+ <order>1</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTUxNTExMzUzOF5BMl5BanBnXkFtZTgwOTI1MjA3OTE@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Amy Adams</name>
+ <role>Lois Lane</role>
+ <order>2</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTg2NTk2MTgxMV5BMl5BanBnXkFtZTgwNjcxMjAzMTI@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Gal Gadot</name>
+ <role>Wonder Woman</role>
+ <order>3</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMjUzZTJmZDItODRjYS00ZGRhLTg2NWQtOGE0YjJhNWVlMjNjXkEyXkFqcGdeQXVyMTg4NDI0NDM@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ezra Miller</name>
+ <role>The Flash</role>
+ <order>4</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMjEwMjQ3ODgxOV5BMl5BanBnXkFtZTgwNzc4NjE4NTE@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Jason Momoa</name>
+ <role>Aquaman</role>
+ <order>5</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTI5MTU5NjM1MV5BMl5BanBnXkFtZTcwODc4MDk0Mw@@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ray Fisher</name>
+ <role>Cyborg</role>
+ <order>6</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BYzdhMzkyYTgtMjQzMC00ODhmLWExZmItNTU4MDVlMzY2NzgwXkEyXkFqcGdeQXVyNzA5NjQ5MDk@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Jeremy Irons</name>
+ <role>Alfred</role>
+ <order>7</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTY5Mzg2NDY5OV5BMl5BanBnXkFtZTcwMDQwNzA0Mg@@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Diane Lane</name>
+ <role>Martha Kent</role>
+ <order>8</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMzM5ODM1ZWMtZjcyYy00MzgzLWJmMGQtZWY5OGQyNTRiODIxXkEyXkFqcGdeQXVyOTE0NjgwMjY@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Connie Nielsen</name>
+ <role>Queen Hippolyta</role>
+ <order>9</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BYzZiYTQ4YTAtMzRkMi00ZDZlLWFkZWItNGI2ZTIyODRiYTc4XkEyXkFqcGdeQXVyMjUzMjc2MjE@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>J.K. Simmons</name>
+ <role>Commissioner Gordon</role>
+ <order>10</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMzg2NTI5NzQ1MV5BMl5BanBnXkFtZTgwNjI1NDEwMDI@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ciarán Hinds</name>
+ <role>Steppenwolf</role>
+ <order>11</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTIyNjM0MzU0NF5BMl5BanBnXkFtZTcwOTIxMzg1MQ@@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Amber Heard</name>
+ <role>Mera</role>
+ <order>12</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMjA4NDkyODA3M15BMl5BanBnXkFtZTgwMzUzMjYzNzM@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Joe Morton</name>
+ <role>Silas Stone</role>
+ <order>13</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BMTQ1MjYwMTQ2MF5BMl5BanBnXkFtZTgwNzI4MTA0NDE@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Lisa Loven Kongsli</name>
+ <role>Menalippe</role>
+ <order>14</order>
+ <thumb>https://m.media-amazon.com/images/M/MV5BOTFjOTFhNTgtZjk3Ny00MTNjLWE3MWUtMWI3ZWM5NDljZjQwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_SX1024_SY1024_.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Test Lyricist</name>
+ <type>Lyricist</type>
+ <order>15</order>
+ </actor>
+ <resume>
+ <position>0.000000</position>
+ <total>0.000000</total>
+ </resume>
+ <showlink>Justice League</showlink>
+ <dateadded>2019-08-06 09:01:18</dateadded>
+</movie>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Radarr.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Radarr.nfo
new file mode 100644
index 000000000..43da4881c
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Radarr.nfo
@@ -0,0 +1,2 @@
+https://www.themoviedb.org/movie/583689
+https://www.imdb.com/title/tt4154796
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo
new file mode 100644
index 000000000..56250c09a
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo
@@ -0,0 +1,20 @@
+<episodedetails>
+ <title>Rising (1)</title>
+ <season>1</season>
+ <episode>1</episode>
+ <aired>2004-07-16</aired>
+ <plot>A new Stargate team embarks on a dangerous mission to a distant galaxy, where they discover a mythical lost city -- and a deadly new enemy.</plot>
+ <thumb>https://artworks.thetvdb.com/banners/episodes/70851/25333.jpg</thumb>
+ <watched>false</watched>
+ <rating>8.0</rating>
+</episodedetails>
+<episodedetails>
+ <title>Rising (2)</title>
+ <season>1</season>
+ <episode>2</episode>
+ <aired>2004-07-16</aired>
+ <plot>Sheppard tries to convince Weir to mount a rescue mission to free Colonel Sumner, Teyla, and the others captured by the Wraith.</plot>
+ <thumb>https://artworks.thetvdb.com/banners/episodes/70851/25334.jpg</thumb>
+ <watched>false</watched>
+ <rating>7.9</rating>
+</episodedetails>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo
new file mode 100644
index 000000000..91f0392f4
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+<season>
+ <plot />
+ <outline />
+ <lockdata>false</lockdata>
+ <dateadded>2020-06-14 17:26:51</dateadded>
+ <title>Season 1</title>
+ <year>2019</year>
+ <tvdbid>359728</tvdbid>
+ <premiered>2019-11-08</premiered>
+ <releasedate>2019-11-08</releasedate>
+ <art>
+ <poster>/media/Serien/High School Musical The Musical The Series (2019)/Season 1/Season 1.jpeg</poster>
+ </art>
+ <actor>
+ <name>Olivia Rodrigo</name>
+ <role>Nini</role>
+ <type>Actor</type>
+ <sortorder>0</sortorder>
+ <thumb>/config/metadata/People/O/Olivia Rodrigo/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Kate Reinders</name>
+ <role>Miss Jenn</role>
+ <type>Actor</type>
+ <sortorder>1</sortorder>
+ <thumb>/config/metadata/People/K/Kate Reinders/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Sofia Wylie</name>
+ <role>Gina</role>
+ <type>Actor</type>
+ <sortorder>2</sortorder>
+ <thumb>/config/metadata/People/S/Sofia Wylie/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Matt Cornett</name>
+ <role>E.J.</role>
+ <type>Actor</type>
+ <sortorder>3</sortorder>
+ <thumb>/config/metadata/People/M/Matt Cornett/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Dara Reneé</name>
+ <role>Kourtney</role>
+ <type>Actor</type>
+ <sortorder>4</sortorder>
+ <thumb>/config/metadata/People/D/Dara Reneé/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Julia Lester</name>
+ <role>Ashlyn</role>
+ <type>Actor</type>
+ <sortorder>5</sortorder>
+ <thumb>/config/metadata/People/J/Julia Lester/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Joshua Bassett</name>
+ <role>Ricky</role>
+ <type>Actor</type>
+ <sortorder>6</sortorder>
+ <thumb>/config/metadata/People/J/Joshua Bassett/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Frankie A. Rodriguez</name>
+ <role>Carlos</role>
+ <type>Actor</type>
+ <sortorder>7</sortorder>
+ <thumb>/config/metadata/People/F/Frankie A. Rodriguez/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Larry Saperstein</name>
+ <role>Big Red</role>
+ <type>Actor</type>
+ <sortorder>8</sortorder>
+ <thumb>/config/metadata/People/L/Larry Saperstein/poster.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Mark St. Cyr</name>
+ <role>Mr. Mazzara</role>
+ <type>Actor</type>
+ <sortorder>9</sortorder>
+ <thumb>/config/metadata/People/M/Mark St. Cyr/poster.jpg</thumb>
+ </actor>
+ <seasonnumber>1</seasonnumber>
+</season>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo
new file mode 100644
index 000000000..4ab8400d3
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<album>
+ <title>The Best of 1980-1990</title>
+ <musicbrainzalbumid>59b5a40b-e2fd-3f18-a218-e8c9aae12ab5</musicbrainzalbumid>
+ <musicbrainzreleasegroupid>6c301dbd-6ccb-3403-a6c4-6a22240a0297</musicbrainzreleasegroupid>
+ <scrapedmbid>false</scrapedmbid>
+ <artistdesc>U2</artistdesc>
+ <genre>Pop</genre>
+ <style>Rock/Pop</style>
+ <mood>Political</mood>
+ <compilation>false</compilation>
+ <review>The Best of 1980-1990 is the first greatest hits compilation by Irish rock band U2, released in November 1998. It mostly contains the group&apos;s hit singles from the eighties but also mixes in some live staples as well as one new recording, Sweetest Thing. In April 1999, a companion video (featuring music videos and live footage) was released. The album was followed by another compilation, The Best of 1990-2000, in 2002.&#x0A;A limited edition version containing a special B-sides disc was released on the same date as the single-disc version. At the time of release, the official word was that the 2-disc album would be available the first week the album went on sale, then pulled from the stores. While this threat never materialized, it did result in the 2-disc version being in very high demand. Both versions charted in the Billboard 200.&#x0A;The boy on the cover is Peter Rowan, brother of Bono&apos;s friend Guggi (real name Derek Rowan) of the Virgin Prunes. He also appears on the covers of the early EP Three, two of the band&apos;s first three albums (Boy and War), and Early Demos.</review>
+ <type>album / compilation</type>
+ <releasedate></releasedate>
+ <label>Island</label>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-4e43a22cab023.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-4e43a22cab023.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-5bc4301068645.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-5bc4301068645.jpg</thumb>
+ <thumb preview="https://www.theaudiodb.com/images/media/album/thumb/the-best-of-1980-1990-4e43a22cab023.jpg/preview">https://www.theaudiodb.com/images/media/album/thumb/the-best-of-1980-1990-4e43a22cab023.jpg</thumb>
+ <path>C:\KODI\Test- Music\U2\Best Of 1980-1990, The\</path>
+ <rating max="10">-1.000000</rating>
+ <userrating max="10">-1</userrating>
+ <votes>-1</votes>
+ <year>1989</year>
+ <albumArtistCredits>
+ <artist>U2</artist>
+ <musicBrainzArtistID>a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432</musicBrainzArtistID>
+ </albumArtistCredits>
+ <releasetype>album</releasetype>
+</album>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo
new file mode 100644
index 000000000..cd275e4cf
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<episodedetails>
+ <title>The Bone Orchard</title>
+ <showtitle>American Gods</showtitle>
+ <ratings>
+ <rating name="tmdb" max="10" default="true">
+ <value>7.532000</value>
+ <votes>31</votes>
+ </rating>
+ </ratings>
+ <userrating>0</userrating>
+ <top250>0</top250>
+ <season>1</season>
+ <episode>1</episode>
+ <displayseason>-1</displayseason>
+ <displayepisode>-1</displayepisode>
+ <episodenumberend>1</episodenumberend>
+ <airsbefore_episode>1</airsbefore_episode>
+ <airsafter_season>2</airsafter_season>
+ <airsbefore_season>3</airsbefore_season>
+ <outline></outline>
+ <plot>When Shadow Moon is released from prison early after the death of his wife, he meets Mr. Wednesday and is recruited as his bodyguard. Shadow discovers that this may be more than he bargained for.</plot>
+ <tagline></tagline>
+ <runtime>0</runtime>
+ <thumb>http://image.tmdb.org/t/p/original/uvry4weK00pFLn7fxQ9M4m3Da2A.jpg</thumb>
+ <mpaa>16</mpaa>
+ <playcount>0</playcount>
+ <lastplayed></lastplayed>
+ <id>1276153</id>
+ <uniqueid type="tmdb" default="true">1276153</uniqueid>
+ <imdbId>tt5017734</imdbId>
+ <genre>Drama</genre>
+ <genre>Mystery</genre>
+ <genre>Sci-Fi &amp; Fantasy</genre>
+ <credits>Bryan Fuller</credits>
+ <credits>Michael Green</credits>
+ <director>David Slade</director>
+ <premiered>2017-04-30</premiered>
+ <year>2017</year>
+ <status></status>
+ <code></code>
+ <aired>2017-04-30</aired>
+ <studio>Starz</studio>
+ <trailer></trailer>
+ <actor>
+ <name>Jonathan Tucker</name>
+ <role>&apos;Low Key&apos; Lyesmith</role>
+ <order>10</order>
+ <thumb>http://image.tmdb.org/t/p/original/jvJpYDbwmUTACw7Yn7PKOP6CdlJ.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Demore Barnes</name>
+ <role>Mr. Ibis</role>
+ <order>11</order>
+ <thumb>http://image.tmdb.org/t/p/original/4rEVzSIFPgiN14xYQnjKcKQ7tYE.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Betty Gilpin</name>
+ <role>Audrey</role>
+ <order>12</order>
+ <thumb>http://image.tmdb.org/t/p/original/xFeqyem5i4Kf0nFjBZ4Oi9NM26k.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Beth Grant</name>
+ <role>Jack</role>
+ <order>13</order>
+ <thumb>http://image.tmdb.org/t/p/original/zAT9GvzJE0ytL3C36L461cgKI9p.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Joel Murray</name>
+ <role>Paunch</role>
+ <order>14</order>
+ <thumb>http://image.tmdb.org/t/p/original/t5syYfCgxbTC7XPrNeXhhhQULUf.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ricky Whittle</name>
+ <role>Shadow Moon</role>
+ <order>0</order>
+ <thumb>http://image.tmdb.org/t/p/original/cjeDbVfBp6Qvb3C74Dfy7BKDTQN.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Ian McShane</name>
+ <role>Mr. Wednesday</role>
+ <order>1</order>
+ <thumb>http://image.tmdb.org/t/p/original/pY9ud4BJwHekNiO4MMItPbgkdAy.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Emily Browning</name>
+ <role>Laura Moon</role>
+ <order>2</order>
+ <thumb>http://image.tmdb.org/t/p/original/fa1Kyj02wxwcdS6EHb2i27TNXvU.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Pablo Schreiber</name>
+ <role>Mad Sweeney</role>
+ <order>3</order>
+ <thumb>http://image.tmdb.org/t/p/original/uo8YljeePz3pbj7gvWXdB4gOOW4.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Bruce Langley</name>
+ <role>Technical Boy</role>
+ <order>4</order>
+ <thumb>http://image.tmdb.org/t/p/original/f4EOWUmznLqboq8Ce7jnlkHVK3Y.jpg</thumb>
+ </actor>
+ <actor>
+ <name>Yetide Badaki</name>
+ <role>Bilquis</role>
+ <order>5</order>
+ <thumb>http://image.tmdb.org/t/p/original/qfzkREHuI1JvMxBteIAjKX8qMEr.jpg</thumb>
+ </actor>
+ <resume>
+ <position>0.000000</position>
+ <total>0.000000</total>
+ </resume>
+ <dateadded>2017-10-07 14:25:47</dateadded>
+</episodedetails>
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tmdb.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tmdb.nfo
new file mode 100644
index 000000000..15af71852
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tmdb.nfo
@@ -0,0 +1 @@
+https://www.themoviedb.org/movie/30287-fallo
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tvdb.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tvdb.nfo
new file mode 100644
index 000000000..9de69f8e1
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Tvdb.nfo
@@ -0,0 +1 @@
+https://www.thetvdb.com/?tab=series&id=121361
diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/U2.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/U2.nfo
new file mode 100644
index 000000000..8c46fdeb8
--- /dev/null
+++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/U2.nfo
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
+<artist>
+ <name>U2</name>
+ <musicBrainzArtistID>a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432</musicBrainzArtistID>
+ <sortname>U2</sortname>
+ <type></type>
+ <gender></gender>
+ <disambiguation>Irish rock band</disambiguation>
+ <genre>Rock</genre>
+ <style>Rock/Pop</style>
+ <mood>Political</mood>
+ <born></born>
+ <formed>Dublin, Ireland (1976)</formed>
+ <biography>U2 are an Irish rock band from Dublin. Formed in 1976, the group consists of Bono (vocals and rhythm guitar), the Edge (lead guitar, keyboards, and vocals), Adam Clayton (bass guitar), and Larry Mullen, Jr. (drums and percussion). U2&apos;s early sound was rooted in post-punk but eventually grew to incorporate influences from many genres of popular music. Throughout the group&apos;s musical pursuits, they have maintained a sound built on melodic instrumentals. Their lyrics, often embellished with spiritual imagery, focus on personal themes and sociopolitical concerns.&#x0A;The band formed at Mount Temple Comprehensive School in 1976 when the members were teenagers with limited musical proficiency. Within four years, they signed with Island Records and released their debut album Boy. By the mid-1980s, U2 had become a top international act. They were more successful as a touring act than they were at selling records until their 1987 album The Joshua Tree which, according to Rolling Stone, elevated the band&apos;s stature &quot;from heroes to superstars&quot;. Reacting to musical stagnation and criticism of their earnest image and musical direction in the late 1980s, U2 reinvented themselves with their 1991 album, Achtung Baby, and the accompanying Zoo TV Tour; they integrated dance, industrial, and alternative rock influences into their sound, and embraced a more ironic and self-deprecating image. They embraced similar experimentation for the remainder of the 1990s with varying levels of success. U2 regained critical and commercial favour in the 2000s with the records All That You Can&apos;t Leave Behind (2000) and How to Dismantle an Atomic Bomb (2004), which established a more conventional, mainstream sound for the group. Their U2 360° Tour of 2009–2011 is the highest-attended and highest-grossing concert tour in history.&#x0A;U2 have released 13 studio albums and are one of the world&apos;s best-selling music artists of all time, having sold more than 170 million records worldwide. They have won 22 Grammy Awards, more than any other band; and, in 2005, were inducted into the Rock and Roll Hall of Fame in their first year of eligibility. Rolling Stone ranked U2 at number 22 in its list of the &quot;100 Greatest Artists of All Time&quot;, and labelled them the &quot;Biggest Band in the World&quot;. Throughout their career, as a band and as individuals, they have campaigned for human rights and philanthropic causes, including Amnesty International, the ONE/DATA campaigns, Product Red, War Child and the Edge&apos;s Music Rising.</biography>
+ <died></died>
+ <disbanded></disbanded>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistthumb/u2-50104c356fd2b.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistthumb/u2-50104c356fd2b.jpg</thumb>
+ <thumb aspect="poster" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistthumb/u2-4fdf7ab5bfa99.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistthumb/u2-4fdf7ab5bfa99.jpg</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b320283c98.png">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b320283c98.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b3268cc581.png">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b3268cc581.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-55b02a97170c7.png">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-55b02a97170c7.png</thumb>
+ <thumb aspect="clearlogo" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b39954caf1.png">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/hdmusiclogo/u2-538b39954caf1.png</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-59e65cba172de.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-59e65cba172de.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-54063da8ca135.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-54063da8ca135.jpg</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-503f9e062c802.JPG">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-503f9e062c802.JPG</thumb>
+ <thumb aspect="banner" preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-591ce819c91a5.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/musicbanner/u2-591ce819c91a5.jpg</thumb>
+ <thumb preview="https://www.theaudiodb.com/images/media/artist/thumb/qvuxvs1347997318.jpg/preview">https://www.theaudiodb.com/images/media/artist/thumb/qvuxvs1347997318.jpg</thumb>
+ <thumb aspect="clearlogo" preview="https://www.theaudiodb.com/images/media/artist/logo/qywsvv1347997327.png/preview">https://www.theaudiodb.com/images/media/artist/logo/qywsvv1347997327.png</thumb>
+ <thumb aspect="clearart" preview="https://www.theaudiodb.com/images/media/artist/clearart/vwpyxv1511531849.png/preview">https://www.theaudiodb.com/images/media/artist/clearart/vwpyxv1511531849.png</thumb>
+ <thumb aspect="landscape" preview="https://www.theaudiodb.com/images/media/artist/widethumb/wxsxwq1524669620.jpg/preview">https://www.theaudiodb.com/images/media/artist/widethumb/wxsxwq1524669620.jpg</thumb>
+ <thumb aspect="banner" preview="https://www.theaudiodb.com/images/media/artist/banner/rpqwpu1488384726.jpg/preview">https://www.theaudiodb.com/images/media/artist/banner/rpqwpu1488384726.jpg</thumb>
+ <path>E:\z-Music Artists\U2</path>
+ <fanart>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377b181.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377b181.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-5058bffb80200.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-5058bffb80200.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377b5a0.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377b5a0.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4df96804ad0f3.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4df96804ad0f3.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-5487022bd1524.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-5487022bd1524.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-50104bf699b84.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-50104bf699b84.jpg</thumb>
+ <thumb preview="https://assets.fanart.tv/preview/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377acdb.jpg">https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/artistbackground/u2-4f805e377acdb.jpg</thumb>
+ </fanart>
+ <album>
+ <title>Pop</title>
+ <year>1997</year>
+ </album>
+ <album>
+ <title>How to Dismantle an Atomic Bomb</title>
+ <year>2004</year>
+ </album>
+ <album>
+ <title>Boy</title>
+ <year>1980</year>
+ </album>
+ <album>
+ <title>Pop</title>
+ <year>1997</year>
+ </album>
+ <album>
+ <title>The Joshua Tree</title>
+ <year>1987</year>
+ </album>
+ <album>
+ <title>Achtung Baby</title>
+ <year>1991</year>
+ </album>
+ <album>
+ <title>Zooropa</title>
+ <year>1993</year>
+ </album>
+</artist>
diff --git a/tests/coverletArgs.runsettings b/tests/coverletArgs.runsettings
new file mode 100644
index 000000000..3113957e0
--- /dev/null
+++ b/tests/coverletArgs.runsettings
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<RunSettings>
+ <DataCollectionRunSettings>
+ <DataCollectors>
+ <DataCollector friendlyName="XPlat code coverage">
+ <Configuration>
+ <Format>cobertura</Format>
+ <Exclude>[coverlet.*.tests?]*,[*]Coverlet.Core*,[*]Moq*</Exclude> <!-- [Assembly-Filter]Type-Filter -->
+ <ExcludeByAttribute>Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute</ExcludeByAttribute>
+ <SingleHit>false</SingleHit>
+ <UseSourceLink>true</UseSourceLink>
+ <IncludeTestAssembly>false</IncludeTestAssembly>
+ </Configuration>
+ </DataCollector>
+ </DataCollectors>
+ </DataCollectionRunSettings>
+</RunSettings> \ No newline at end of file
diff --git a/tests/jellyfin-tests.ruleset b/tests/jellyfin-tests.ruleset
new file mode 100644
index 000000000..e2abaf5bb
--- /dev/null
+++ b/tests/jellyfin-tests.ruleset
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RuleSet Name="Rules for Jellyfin.Api.Tests" Description="Code analysis rules for Jellyfin.Api.Tests.csproj" ToolsVersion="14.0">
+
+ <!-- Include the solution default RuleSet. The rules in this file will override the defaults. -->
+ <Include Path="../jellyfin.ruleset" Action="Default" />
+
+ <!-- StyleCop Analyzer Rules -->
+ <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
+ <!-- SA0001: XML comment analysis is disabled due to project configuration -->
+ <Rule Id="SA0001" Action="None" />
+ </Rules>
+
+ <!-- FxCop Analyzer Rules -->
+ <Rules AnalyzerId="Microsoft.CodeAnalysis.FxCopAnalyzers" RuleNamespace="Microsoft.Design">
+ <!-- CA1707: Identifiers should not contain underscores -->
+ <Rule Id="CA1707" Action="None" />
+ <!-- CA2007: Consider calling ConfigureAwait on the awaited task -->
+ <Rule Id="CA2007" Action="None" />
+ <!-- CA2234: Pass system uri objects instead of strings -->
+ <Rule Id="CA2234" Action="Info" />
+ </Rules>
+</RuleSet>